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_PATIENCE;
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 char *input_str;
636 int wait_for_ui;
637 } tog_io;
638 static int using_mock_io;
640 #define TOG_KEY_SCRDUMP SHRT_MIN
642 /*
643 * We implement two types of views: parent views and child views.
645 * The 'Tab' key switches focus between a parent view and its child view.
646 * Child views are shown side-by-side to their parent view, provided
647 * there is enough screen estate.
649 * When a new view is opened from within a parent view, this new view
650 * becomes a child view of the parent view, replacing any existing child.
652 * When a new view is opened from within a child view, this new view
653 * becomes a parent view which will obscure the views below until the
654 * user quits the new parent view by typing 'q'.
656 * This list of views contains parent views only.
657 * Child views are only pointed to by their parent view.
658 */
659 TAILQ_HEAD(tog_view_list_head, tog_view);
661 struct tog_view {
662 TAILQ_ENTRY(tog_view) entry;
663 WINDOW *window;
664 PANEL *panel;
665 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
666 int resized_y, resized_x; /* begin_y/x based on user resizing */
667 int maxx, x; /* max column and current start column */
668 int lines, cols; /* copies of LINES and COLS */
669 int nscrolled, offset; /* lines scrolled and hsplit line offset */
670 int gline, hiline; /* navigate to and highlight this nG line */
671 int ch, count; /* current keymap and count prefix */
672 int resized; /* set when in a resize event */
673 int focussed; /* Only set on one parent or child view at a time. */
674 int dying;
675 struct tog_view *parent;
676 struct tog_view *child;
678 /*
679 * This flag is initially set on parent views when a new child view
680 * is created. It gets toggled when the 'Tab' key switches focus
681 * between parent and child.
682 * The flag indicates whether focus should be passed on to our child
683 * view if this parent view gets picked for focus after another parent
684 * view was closed. This prevents child views from losing focus in such
685 * situations.
686 */
687 int focus_child;
689 enum tog_view_mode mode;
690 /* type-specific state */
691 enum tog_view_type type;
692 union {
693 struct tog_diff_view_state diff;
694 struct tog_log_view_state log;
695 struct tog_blame_view_state blame;
696 struct tog_tree_view_state tree;
697 struct tog_ref_view_state ref;
698 struct tog_help_view_state help;
699 } state;
701 const struct got_error *(*show)(struct tog_view *);
702 const struct got_error *(*input)(struct tog_view **,
703 struct tog_view *, int);
704 const struct got_error *(*reset)(struct tog_view *);
705 const struct got_error *(*resize)(struct tog_view *, int);
706 const struct got_error *(*close)(struct tog_view *);
708 const struct got_error *(*search_start)(struct tog_view *);
709 const struct got_error *(*search_next)(struct tog_view *);
710 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
711 int **, int **, int **, int **);
712 int search_started;
713 int searching;
714 #define TOG_SEARCH_FORWARD 1
715 #define TOG_SEARCH_BACKWARD 2
716 int search_next_done;
717 #define TOG_SEARCH_HAVE_MORE 1
718 #define TOG_SEARCH_NO_MORE 2
719 #define TOG_SEARCH_HAVE_NONE 3
720 regex_t regex;
721 regmatch_t regmatch;
722 const char *action;
723 };
725 static const struct got_error *open_diff_view(struct tog_view *,
726 struct got_object_id *, struct got_object_id *,
727 const char *, const char *, int, int, int, struct tog_view *,
728 struct got_repository *);
729 static const struct got_error *show_diff_view(struct tog_view *);
730 static const struct got_error *input_diff_view(struct tog_view **,
731 struct tog_view *, int);
732 static const struct got_error *reset_diff_view(struct tog_view *);
733 static const struct got_error* close_diff_view(struct tog_view *);
734 static const struct got_error *search_start_diff_view(struct tog_view *);
735 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
736 size_t *, int **, int **, int **, int **);
737 static const struct got_error *search_next_view_match(struct tog_view *);
739 static const struct got_error *open_log_view(struct tog_view *,
740 struct got_object_id *, struct got_repository *,
741 const char *, const char *, int, struct got_worktree *);
742 static const struct got_error * show_log_view(struct tog_view *);
743 static const struct got_error *input_log_view(struct tog_view **,
744 struct tog_view *, int);
745 static const struct got_error *resize_log_view(struct tog_view *, int);
746 static const struct got_error *close_log_view(struct tog_view *);
747 static const struct got_error *search_start_log_view(struct tog_view *);
748 static const struct got_error *search_next_log_view(struct tog_view *);
750 static const struct got_error *open_blame_view(struct tog_view *, char *,
751 struct got_object_id *, struct got_repository *);
752 static const struct got_error *show_blame_view(struct tog_view *);
753 static const struct got_error *input_blame_view(struct tog_view **,
754 struct tog_view *, int);
755 static const struct got_error *reset_blame_view(struct tog_view *);
756 static const struct got_error *close_blame_view(struct tog_view *);
757 static const struct got_error *search_start_blame_view(struct tog_view *);
758 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
759 size_t *, int **, int **, int **, int **);
761 static const struct got_error *open_tree_view(struct tog_view *,
762 struct got_object_id *, const char *, struct got_repository *);
763 static const struct got_error *show_tree_view(struct tog_view *);
764 static const struct got_error *input_tree_view(struct tog_view **,
765 struct tog_view *, int);
766 static const struct got_error *close_tree_view(struct tog_view *);
767 static const struct got_error *search_start_tree_view(struct tog_view *);
768 static const struct got_error *search_next_tree_view(struct tog_view *);
770 static const struct got_error *open_ref_view(struct tog_view *,
771 struct got_repository *);
772 static const struct got_error *show_ref_view(struct tog_view *);
773 static const struct got_error *input_ref_view(struct tog_view **,
774 struct tog_view *, int);
775 static const struct got_error *close_ref_view(struct tog_view *);
776 static const struct got_error *search_start_ref_view(struct tog_view *);
777 static const struct got_error *search_next_ref_view(struct tog_view *);
779 static const struct got_error *open_help_view(struct tog_view *,
780 struct tog_view *);
781 static const struct got_error *show_help_view(struct tog_view *);
782 static const struct got_error *input_help_view(struct tog_view **,
783 struct tog_view *, int);
784 static const struct got_error *reset_help_view(struct tog_view *);
785 static const struct got_error* close_help_view(struct tog_view *);
786 static const struct got_error *search_start_help_view(struct tog_view *);
787 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
788 size_t *, int **, int **, int **, int **);
790 static volatile sig_atomic_t tog_sigwinch_received;
791 static volatile sig_atomic_t tog_sigpipe_received;
792 static volatile sig_atomic_t tog_sigcont_received;
793 static volatile sig_atomic_t tog_sigint_received;
794 static volatile sig_atomic_t tog_sigterm_received;
796 static void
797 tog_sigwinch(int signo)
799 tog_sigwinch_received = 1;
802 static void
803 tog_sigpipe(int signo)
805 tog_sigpipe_received = 1;
808 static void
809 tog_sigcont(int signo)
811 tog_sigcont_received = 1;
814 static void
815 tog_sigint(int signo)
817 tog_sigint_received = 1;
820 static void
821 tog_sigterm(int signo)
823 tog_sigterm_received = 1;
826 static int
827 tog_fatal_signal_received(void)
829 return (tog_sigpipe_received ||
830 tog_sigint_received || tog_sigterm_received);
833 static const struct got_error *
834 view_close(struct tog_view *view)
836 const struct got_error *err = NULL, *child_err = NULL;
838 if (view->child) {
839 child_err = view_close(view->child);
840 view->child = NULL;
842 if (view->close)
843 err = view->close(view);
844 if (view->panel)
845 del_panel(view->panel);
846 if (view->window)
847 delwin(view->window);
848 free(view);
849 return err ? err : child_err;
852 static struct tog_view *
853 view_open(int nlines, int ncols, int begin_y, int begin_x,
854 enum tog_view_type type)
856 struct tog_view *view = calloc(1, sizeof(*view));
858 if (view == NULL)
859 return NULL;
861 view->type = type;
862 view->lines = LINES;
863 view->cols = COLS;
864 view->nlines = nlines ? nlines : LINES - begin_y;
865 view->ncols = ncols ? ncols : COLS - begin_x;
866 view->begin_y = begin_y;
867 view->begin_x = begin_x;
868 view->window = newwin(nlines, ncols, begin_y, begin_x);
869 if (view->window == NULL) {
870 view_close(view);
871 return NULL;
873 view->panel = new_panel(view->window);
874 if (view->panel == NULL ||
875 set_panel_userptr(view->panel, view) != OK) {
876 view_close(view);
877 return NULL;
880 keypad(view->window, TRUE);
881 return view;
884 static int
885 view_split_begin_x(int begin_x)
887 if (begin_x > 0 || COLS < 120)
888 return 0;
889 return (COLS - MAX(COLS / 2, 80));
892 /* XXX Stub till we decide what to do. */
893 static int
894 view_split_begin_y(int lines)
896 return lines * HSPLIT_SCALE;
899 static const struct got_error *view_resize(struct tog_view *);
901 static const struct got_error *
902 view_splitscreen(struct tog_view *view)
904 const struct got_error *err = NULL;
906 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
907 if (view->resized_y && view->resized_y < view->lines)
908 view->begin_y = view->resized_y;
909 else
910 view->begin_y = view_split_begin_y(view->nlines);
911 view->begin_x = 0;
912 } else if (!view->resized) {
913 if (view->resized_x && view->resized_x < view->cols - 1 &&
914 view->cols > 119)
915 view->begin_x = view->resized_x;
916 else
917 view->begin_x = view_split_begin_x(0);
918 view->begin_y = 0;
920 view->nlines = LINES - view->begin_y;
921 view->ncols = COLS - view->begin_x;
922 view->lines = LINES;
923 view->cols = COLS;
924 err = view_resize(view);
925 if (err)
926 return err;
928 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
929 view->parent->nlines = view->begin_y;
931 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
932 return got_error_from_errno("mvwin");
934 return NULL;
937 static const struct got_error *
938 view_fullscreen(struct tog_view *view)
940 const struct got_error *err = NULL;
942 view->begin_x = 0;
943 view->begin_y = view->resized ? view->begin_y : 0;
944 view->nlines = view->resized ? view->nlines : LINES;
945 view->ncols = COLS;
946 view->lines = LINES;
947 view->cols = COLS;
948 err = view_resize(view);
949 if (err)
950 return err;
952 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
953 return got_error_from_errno("mvwin");
955 return NULL;
958 static int
959 view_is_parent_view(struct tog_view *view)
961 return view->parent == NULL;
964 static int
965 view_is_splitscreen(struct tog_view *view)
967 return view->begin_x > 0 || view->begin_y > 0;
970 static int
971 view_is_fullscreen(struct tog_view *view)
973 return view->nlines == LINES && view->ncols == COLS;
976 static int
977 view_is_hsplit_top(struct tog_view *view)
979 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
980 view_is_splitscreen(view->child);
983 static void
984 view_border(struct tog_view *view)
986 PANEL *panel;
987 const struct tog_view *view_above;
989 if (view->parent)
990 return view_border(view->parent);
992 panel = panel_above(view->panel);
993 if (panel == NULL)
994 return;
996 view_above = panel_userptr(panel);
997 if (view->mode == TOG_VIEW_SPLIT_HRZN)
998 mvwhline(view->window, view_above->begin_y - 1,
999 view->begin_x, ACS_HLINE, view->ncols);
1000 else
1001 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
1002 ACS_VLINE, view->nlines);
1005 static const struct got_error *view_init_hsplit(struct tog_view *, int);
1006 static const struct got_error *request_log_commits(struct tog_view *);
1007 static const struct got_error *offset_selection_down(struct tog_view *);
1008 static void offset_selection_up(struct tog_view *);
1009 static void view_get_split(struct tog_view *, int *, int *);
1011 static const struct got_error *
1012 view_resize(struct tog_view *view)
1014 const struct got_error *err = NULL;
1015 int dif, nlines, ncols;
1017 dif = LINES - view->lines; /* line difference */
1019 if (view->lines > LINES)
1020 nlines = view->nlines - (view->lines - LINES);
1021 else
1022 nlines = view->nlines + (LINES - view->lines);
1023 if (view->cols > COLS)
1024 ncols = view->ncols - (view->cols - COLS);
1025 else
1026 ncols = view->ncols + (COLS - view->cols);
1028 if (view->child) {
1029 int hs = view->child->begin_y;
1031 if (!view_is_fullscreen(view))
1032 view->child->begin_x = view_split_begin_x(view->begin_x);
1033 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1034 view->child->begin_x == 0) {
1035 ncols = COLS;
1037 view_fullscreen(view->child);
1038 if (view->child->focussed)
1039 show_panel(view->child->panel);
1040 else
1041 show_panel(view->panel);
1042 } else {
1043 ncols = view->child->begin_x;
1045 view_splitscreen(view->child);
1046 show_panel(view->child->panel);
1049 * XXX This is ugly and needs to be moved into the above
1050 * logic but "works" for now and my attempts at moving it
1051 * break either 'tab' or 'F' key maps in horizontal splits.
1053 if (hs) {
1054 err = view_splitscreen(view->child);
1055 if (err)
1056 return err;
1057 if (dif < 0) { /* top split decreased */
1058 err = offset_selection_down(view);
1059 if (err)
1060 return err;
1062 view_border(view);
1063 update_panels();
1064 doupdate();
1065 show_panel(view->child->panel);
1066 nlines = view->nlines;
1068 } else if (view->parent == NULL)
1069 ncols = COLS;
1071 if (view->resize && dif > 0) {
1072 err = view->resize(view, dif);
1073 if (err)
1074 return err;
1077 if (wresize(view->window, nlines, ncols) == ERR)
1078 return got_error_from_errno("wresize");
1079 if (replace_panel(view->panel, view->window) == ERR)
1080 return got_error_from_errno("replace_panel");
1081 wclear(view->window);
1083 view->nlines = nlines;
1084 view->ncols = ncols;
1085 view->lines = LINES;
1086 view->cols = COLS;
1088 return NULL;
1091 static const struct got_error *
1092 resize_log_view(struct tog_view *view, int increase)
1094 struct tog_log_view_state *s = &view->state.log;
1095 const struct got_error *err = NULL;
1096 int n = 0;
1098 if (s->selected_entry)
1099 n = s->selected_entry->idx + view->lines - s->selected;
1102 * Request commits to account for the increased
1103 * height so we have enough to populate the view.
1105 if (s->commits->ncommits < n) {
1106 view->nscrolled = n - s->commits->ncommits + increase + 1;
1107 err = request_log_commits(view);
1110 return err;
1113 static void
1114 view_adjust_offset(struct tog_view *view, int n)
1116 if (n == 0)
1117 return;
1119 if (view->parent && view->parent->offset) {
1120 if (view->parent->offset + n >= 0)
1121 view->parent->offset += n;
1122 else
1123 view->parent->offset = 0;
1124 } else if (view->offset) {
1125 if (view->offset - n >= 0)
1126 view->offset -= n;
1127 else
1128 view->offset = 0;
1132 static const struct got_error *
1133 view_resize_split(struct tog_view *view, int resize)
1135 const struct got_error *err = NULL;
1136 struct tog_view *v = NULL;
1138 if (view->parent)
1139 v = view->parent;
1140 else
1141 v = view;
1143 if (!v->child || !view_is_splitscreen(v->child))
1144 return NULL;
1146 v->resized = v->child->resized = resize; /* lock for resize event */
1148 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1149 if (v->child->resized_y)
1150 v->child->begin_y = v->child->resized_y;
1151 if (view->parent)
1152 v->child->begin_y -= resize;
1153 else
1154 v->child->begin_y += resize;
1155 if (v->child->begin_y < 3) {
1156 view->count = 0;
1157 v->child->begin_y = 3;
1158 } else if (v->child->begin_y > LINES - 1) {
1159 view->count = 0;
1160 v->child->begin_y = LINES - 1;
1162 v->ncols = COLS;
1163 v->child->ncols = COLS;
1164 view_adjust_offset(view, resize);
1165 err = view_init_hsplit(v, v->child->begin_y);
1166 if (err)
1167 return err;
1168 v->child->resized_y = v->child->begin_y;
1169 } else {
1170 if (v->child->resized_x)
1171 v->child->begin_x = v->child->resized_x;
1172 if (view->parent)
1173 v->child->begin_x -= resize;
1174 else
1175 v->child->begin_x += resize;
1176 if (v->child->begin_x < 11) {
1177 view->count = 0;
1178 v->child->begin_x = 11;
1179 } else if (v->child->begin_x > COLS - 1) {
1180 view->count = 0;
1181 v->child->begin_x = COLS - 1;
1183 v->child->resized_x = v->child->begin_x;
1186 v->child->mode = v->mode;
1187 v->child->nlines = v->lines - v->child->begin_y;
1188 v->child->ncols = v->cols - v->child->begin_x;
1189 v->focus_child = 1;
1191 err = view_fullscreen(v);
1192 if (err)
1193 return err;
1194 err = view_splitscreen(v->child);
1195 if (err)
1196 return err;
1198 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1199 err = offset_selection_down(v->child);
1200 if (err)
1201 return err;
1204 if (v->resize)
1205 err = v->resize(v, 0);
1206 else if (v->child->resize)
1207 err = v->child->resize(v->child, 0);
1209 v->resized = v->child->resized = 0;
1211 return err;
1214 static void
1215 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1217 struct tog_view *v = src->child ? src->child : src;
1219 dst->resized_x = v->resized_x;
1220 dst->resized_y = v->resized_y;
1223 static const struct got_error *
1224 view_close_child(struct tog_view *view)
1226 const struct got_error *err = NULL;
1228 if (view->child == NULL)
1229 return NULL;
1231 err = view_close(view->child);
1232 view->child = NULL;
1233 return err;
1236 static const struct got_error *
1237 view_set_child(struct tog_view *view, struct tog_view *child)
1239 const struct got_error *err = NULL;
1241 view->child = child;
1242 child->parent = view;
1244 err = view_resize(view);
1245 if (err)
1246 return err;
1248 if (view->child->resized_x || view->child->resized_y)
1249 err = view_resize_split(view, 0);
1251 return err;
1254 static const struct got_error *view_dispatch_request(struct tog_view **,
1255 struct tog_view *, enum tog_view_type, int, int);
1257 static const struct got_error *
1258 view_request_new(struct tog_view **requested, struct tog_view *view,
1259 enum tog_view_type request)
1261 struct tog_view *new_view = NULL;
1262 const struct got_error *err;
1263 int y = 0, x = 0;
1265 *requested = NULL;
1267 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1268 view_get_split(view, &y, &x);
1270 err = view_dispatch_request(&new_view, view, request, y, x);
1271 if (err)
1272 return err;
1274 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1275 request != TOG_VIEW_HELP) {
1276 err = view_init_hsplit(view, y);
1277 if (err)
1278 return err;
1281 view->focussed = 0;
1282 new_view->focussed = 1;
1283 new_view->mode = view->mode;
1284 new_view->nlines = request == TOG_VIEW_HELP ?
1285 view->lines : view->lines - y;
1287 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1288 view_transfer_size(new_view, view);
1289 err = view_close_child(view);
1290 if (err)
1291 return err;
1292 err = view_set_child(view, new_view);
1293 if (err)
1294 return err;
1295 view->focus_child = 1;
1296 } else
1297 *requested = new_view;
1299 return NULL;
1302 static void
1303 tog_resizeterm(void)
1305 int cols, lines;
1306 struct winsize size;
1308 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1309 cols = 80; /* Default */
1310 lines = 24;
1311 } else {
1312 cols = size.ws_col;
1313 lines = size.ws_row;
1315 resize_term(lines, cols);
1318 static const struct got_error *
1319 view_search_start(struct tog_view *view, int fast_refresh)
1321 const struct got_error *err = NULL;
1322 struct tog_view *v = view;
1323 char pattern[1024];
1324 int ret;
1326 if (view->search_started) {
1327 regfree(&view->regex);
1328 view->searching = 0;
1329 memset(&view->regmatch, 0, sizeof(view->regmatch));
1331 view->search_started = 0;
1333 if (view->nlines < 1)
1334 return NULL;
1336 if (view_is_hsplit_top(view))
1337 v = view->child;
1338 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1339 v = view->parent;
1341 if (tog_io.input_str != NULL) {
1342 if (strlcpy(pattern, tog_io.input_str, sizeof(pattern)) >=
1343 sizeof(pattern))
1344 return got_error(GOT_ERR_NO_SPACE);
1345 } else {
1346 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1347 wclrtoeol(v->window);
1348 nodelay(v->window, FALSE); /* block for search term input */
1349 nocbreak();
1350 echo();
1351 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1352 wrefresh(v->window);
1353 cbreak();
1354 noecho();
1355 nodelay(v->window, TRUE);
1356 if (!fast_refresh && !using_mock_io)
1357 halfdelay(10);
1358 if (ret == ERR)
1359 return NULL;
1362 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1363 err = view->search_start(view);
1364 if (err) {
1365 regfree(&view->regex);
1366 return err;
1368 view->search_started = 1;
1369 view->searching = TOG_SEARCH_FORWARD;
1370 view->search_next_done = 0;
1371 view->search_next(view);
1374 return NULL;
1377 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1378 static const struct got_error *
1379 switch_split(struct tog_view *view)
1381 const struct got_error *err = NULL;
1382 struct tog_view *v = NULL;
1384 if (view->parent)
1385 v = view->parent;
1386 else
1387 v = view;
1389 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1390 v->mode = TOG_VIEW_SPLIT_VERT;
1391 else
1392 v->mode = TOG_VIEW_SPLIT_HRZN;
1394 if (!v->child)
1395 return NULL;
1396 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1397 v->mode = TOG_VIEW_SPLIT_NONE;
1399 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1400 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1401 v->child->begin_y = v->child->resized_y;
1402 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1403 v->child->begin_x = v->child->resized_x;
1406 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1407 v->ncols = COLS;
1408 v->child->ncols = COLS;
1409 v->child->nscrolled = LINES - v->child->nlines;
1411 err = view_init_hsplit(v, v->child->begin_y);
1412 if (err)
1413 return err;
1415 v->child->mode = v->mode;
1416 v->child->nlines = v->lines - v->child->begin_y;
1417 v->focus_child = 1;
1419 err = view_fullscreen(v);
1420 if (err)
1421 return err;
1422 err = view_splitscreen(v->child);
1423 if (err)
1424 return err;
1426 if (v->mode == TOG_VIEW_SPLIT_NONE)
1427 v->mode = TOG_VIEW_SPLIT_VERT;
1428 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1429 err = offset_selection_down(v);
1430 if (err)
1431 return err;
1432 err = offset_selection_down(v->child);
1433 if (err)
1434 return err;
1435 } else {
1436 offset_selection_up(v);
1437 offset_selection_up(v->child);
1439 if (v->resize)
1440 err = v->resize(v, 0);
1441 else if (v->child->resize)
1442 err = v->child->resize(v->child, 0);
1444 return err;
1448 * Strip trailing whitespace from str starting at byte *n;
1449 * if *n < 0, use strlen(str). Return new str length in *n.
1451 static void
1452 strip_trailing_ws(char *str, int *n)
1454 size_t x = *n;
1456 if (str == NULL || *str == '\0')
1457 return;
1459 if (x < 0)
1460 x = strlen(str);
1462 while (x-- > 0 && isspace((unsigned char)str[x]))
1463 str[x] = '\0';
1465 *n = x + 1;
1469 * Extract visible substring of line y from the curses screen
1470 * and strip trailing whitespace. If vline is set, overwrite
1471 * line[vline] with '|' because the ACS_VLINE character is
1472 * written out as 'x'. Write the line to file f.
1474 static const struct got_error *
1475 view_write_line(FILE *f, int y, int vline)
1477 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1478 int r, w;
1480 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1481 if (r == ERR)
1482 return got_error_fmt(GOT_ERR_RANGE,
1483 "failed to extract line %d", y);
1486 * In some views, lines are padded with blanks to COLS width.
1487 * Strip them so we can diff without the -b flag when testing.
1489 strip_trailing_ws(line, &r);
1491 if (vline > 0)
1492 line[vline] = '|';
1494 w = fprintf(f, "%s\n", line);
1495 if (w != r + 1) /* \n */
1496 return got_ferror(f, GOT_ERR_IO);
1498 return NULL;
1502 * Capture the visible curses screen by writing each line to the
1503 * file at the path set via the TOG_SCR_DUMP environment variable.
1505 static const struct got_error *
1506 screendump(struct tog_view *view)
1508 const struct got_error *err;
1509 int i;
1511 err = got_opentemp_truncate(tog_io.sdump);
1512 if (err)
1513 return err;
1515 if ((view->child && view->child->begin_x) ||
1516 (view->parent && view->begin_x)) {
1517 int ncols = view->child ? view->ncols : view->parent->ncols;
1519 /* vertical splitscreen */
1520 for (i = 0; i < view->nlines; ++i) {
1521 err = view_write_line(tog_io.sdump, i, ncols - 1);
1522 if (err)
1523 goto done;
1525 } else {
1526 int hline = 0;
1528 /* fullscreen or horizontal splitscreen */
1529 if ((view->child && view->child->begin_y) ||
1530 (view->parent && view->begin_y)) /* hsplit */
1531 hline = view->child ?
1532 view->child->begin_y : view->begin_y;
1534 for (i = 0; i < view->lines; i++) {
1535 if (hline && i == hline - 1) {
1536 int c;
1538 /* ACS_HLINE writes out as 'q', overwrite it */
1539 for (c = 0; c < view->cols; ++c)
1540 fputc('-', tog_io.sdump);
1541 fputc('\n', tog_io.sdump);
1542 continue;
1545 err = view_write_line(tog_io.sdump, i, 0);
1546 if (err)
1547 goto done;
1551 done:
1552 return err;
1556 * Compute view->count from numeric input. Assign total to view->count and
1557 * return first non-numeric key entered.
1559 static int
1560 get_compound_key(struct tog_view *view, int c)
1562 struct tog_view *v = view;
1563 int x, n = 0;
1565 if (view_is_hsplit_top(view))
1566 v = view->child;
1567 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1568 v = view->parent;
1570 view->count = 0;
1571 cbreak(); /* block for input */
1572 nodelay(view->window, FALSE);
1573 wmove(v->window, v->nlines - 1, 0);
1574 wclrtoeol(v->window);
1575 waddch(v->window, ':');
1577 do {
1578 x = getcurx(v->window);
1579 if (x != ERR && x < view->ncols) {
1580 waddch(v->window, c);
1581 wrefresh(v->window);
1585 * Don't overflow. Max valid request should be the greatest
1586 * between the longest and total lines; cap at 10 million.
1588 if (n >= 9999999)
1589 n = 9999999;
1590 else
1591 n = n * 10 + (c - '0');
1592 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1594 if (c == 'G' || c == 'g') { /* nG key map */
1595 view->gline = view->hiline = n;
1596 n = 0;
1597 c = 0;
1600 /* Massage excessive or inapplicable values at the input handler. */
1601 view->count = n;
1603 return c;
1606 static void
1607 action_report(struct tog_view *view)
1609 struct tog_view *v = view;
1611 if (view_is_hsplit_top(view))
1612 v = view->child;
1613 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1614 v = view->parent;
1616 wmove(v->window, v->nlines - 1, 0);
1617 wclrtoeol(v->window);
1618 wprintw(v->window, ":%s", view->action);
1619 wrefresh(v->window);
1622 * Clear action status report. Only clear in blame view
1623 * once annotating is complete, otherwise it's too fast.
1625 if (view->type == TOG_VIEW_BLAME) {
1626 if (view->state.blame.blame_complete)
1627 view->action = NULL;
1628 } else
1629 view->action = NULL;
1633 * Read the next line from the test script and assign
1634 * key instruction to *ch. If at EOF, set the *done flag.
1636 static const struct got_error *
1637 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1639 const struct got_error *err = NULL;
1640 char *line = NULL;
1641 size_t linesz = 0;
1642 ssize_t n;
1645 if (view->count && --view->count) {
1646 *ch = view->ch;
1647 return NULL;
1648 } else
1649 *ch = -1;
1651 if ((n = getline(&line, &linesz, script)) == -1) {
1652 if (feof(script)) {
1653 *done = 1;
1654 goto done;
1655 } else {
1656 err = got_ferror(script, GOT_ERR_IO);
1657 goto done;
1661 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1662 tog_io.wait_for_ui = 1;
1663 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1664 *ch = KEY_ENTER;
1665 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1666 *ch = KEY_RIGHT;
1667 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1668 *ch = KEY_LEFT;
1669 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1670 *ch = KEY_DOWN;
1671 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1672 *ch = KEY_UP;
1673 else if (strncasecmp(line, "TAB", 3) == 0)
1674 *ch = '\t';
1675 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1676 *ch = TOG_KEY_SCRDUMP;
1677 else if (isdigit((unsigned char)*line)) {
1678 char *t = line;
1680 while (isdigit((unsigned char)*t))
1681 ++t;
1682 view->ch = *ch = *t;
1683 *t = '\0';
1684 /* ignore error, view->count is 0 if instruction is invalid */
1685 view->count = strtonum(line, 0, INT_MAX, NULL);
1686 } else {
1687 *ch = *line;
1688 if (n > 2 && (*ch == '/' || *ch == '&')) {
1689 /* skip leading keymap and trim trailing newline */
1690 tog_io.input_str = strndup(line + 1, n - 2);
1691 if (tog_io.input_str == NULL) {
1692 err = got_error_from_errno("strndup");
1693 goto done;
1698 done:
1699 free(line);
1700 return err;
1703 static const struct got_error *
1704 view_input(struct tog_view **new, int *done, struct tog_view *view,
1705 struct tog_view_list_head *views, int fast_refresh)
1707 const struct got_error *err = NULL;
1708 struct tog_view *v;
1709 int ch, errcode;
1711 *new = NULL;
1713 if (view->action)
1714 action_report(view);
1716 /* Clear "no matches" indicator. */
1717 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1718 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1719 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1720 view->count = 0;
1723 if (view->searching && !view->search_next_done) {
1724 errcode = pthread_mutex_unlock(&tog_mutex);
1725 if (errcode)
1726 return got_error_set_errno(errcode,
1727 "pthread_mutex_unlock");
1728 sched_yield();
1729 errcode = pthread_mutex_lock(&tog_mutex);
1730 if (errcode)
1731 return got_error_set_errno(errcode,
1732 "pthread_mutex_lock");
1733 view->search_next(view);
1734 return NULL;
1737 /* Allow threads to make progress while we are waiting for input. */
1738 errcode = pthread_mutex_unlock(&tog_mutex);
1739 if (errcode)
1740 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1742 if (using_mock_io) {
1743 err = tog_read_script_key(tog_io.f, view, &ch, done);
1744 if (err) {
1745 errcode = pthread_mutex_lock(&tog_mutex);
1746 return err;
1748 } else if (view->count && --view->count) {
1749 cbreak();
1750 nodelay(view->window, TRUE);
1751 ch = wgetch(view->window);
1752 /* let C-g or backspace abort unfinished count */
1753 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1754 view->count = 0;
1755 else
1756 ch = view->ch;
1757 } else {
1758 ch = wgetch(view->window);
1759 if (ch >= '1' && ch <= '9')
1760 view->ch = ch = get_compound_key(view, ch);
1762 if (view->hiline && ch != ERR && ch != 0)
1763 view->hiline = 0; /* key pressed, clear line highlight */
1764 nodelay(view->window, TRUE);
1765 errcode = pthread_mutex_lock(&tog_mutex);
1766 if (errcode)
1767 return got_error_set_errno(errcode, "pthread_mutex_lock");
1769 if (tog_sigwinch_received || tog_sigcont_received) {
1770 tog_resizeterm();
1771 tog_sigwinch_received = 0;
1772 tog_sigcont_received = 0;
1773 TAILQ_FOREACH(v, views, entry) {
1774 err = view_resize(v);
1775 if (err)
1776 return err;
1777 err = v->input(new, v, KEY_RESIZE);
1778 if (err)
1779 return err;
1780 if (v->child) {
1781 err = view_resize(v->child);
1782 if (err)
1783 return err;
1784 err = v->child->input(new, v->child,
1785 KEY_RESIZE);
1786 if (err)
1787 return err;
1788 if (v->child->resized_x || v->child->resized_y) {
1789 err = view_resize_split(v, 0);
1790 if (err)
1791 return err;
1797 switch (ch) {
1798 case '?':
1799 case 'H':
1800 case KEY_F(1):
1801 if (view->type == TOG_VIEW_HELP)
1802 err = view->reset(view);
1803 else
1804 err = view_request_new(new, view, TOG_VIEW_HELP);
1805 break;
1806 case '\t':
1807 view->count = 0;
1808 if (view->child) {
1809 view->focussed = 0;
1810 view->child->focussed = 1;
1811 view->focus_child = 1;
1812 } else if (view->parent) {
1813 view->focussed = 0;
1814 view->parent->focussed = 1;
1815 view->parent->focus_child = 0;
1816 if (!view_is_splitscreen(view)) {
1817 if (view->parent->resize) {
1818 err = view->parent->resize(view->parent,
1819 0);
1820 if (err)
1821 return err;
1823 offset_selection_up(view->parent);
1824 err = view_fullscreen(view->parent);
1825 if (err)
1826 return err;
1829 break;
1830 case 'q':
1831 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1832 if (view->parent->resize) {
1833 /* might need more commits to fill fullscreen */
1834 err = view->parent->resize(view->parent, 0);
1835 if (err)
1836 break;
1838 offset_selection_up(view->parent);
1840 err = view->input(new, view, ch);
1841 view->dying = 1;
1842 break;
1843 case 'Q':
1844 *done = 1;
1845 break;
1846 case 'F':
1847 view->count = 0;
1848 if (view_is_parent_view(view)) {
1849 if (view->child == NULL)
1850 break;
1851 if (view_is_splitscreen(view->child)) {
1852 view->focussed = 0;
1853 view->child->focussed = 1;
1854 err = view_fullscreen(view->child);
1855 } else {
1856 err = view_splitscreen(view->child);
1857 if (!err)
1858 err = view_resize_split(view, 0);
1860 if (err)
1861 break;
1862 err = view->child->input(new, view->child,
1863 KEY_RESIZE);
1864 } else {
1865 if (view_is_splitscreen(view)) {
1866 view->parent->focussed = 0;
1867 view->focussed = 1;
1868 err = view_fullscreen(view);
1869 } else {
1870 err = view_splitscreen(view);
1871 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1872 err = view_resize(view->parent);
1873 if (!err)
1874 err = view_resize_split(view, 0);
1876 if (err)
1877 break;
1878 err = view->input(new, view, KEY_RESIZE);
1880 if (err)
1881 break;
1882 if (view->resize) {
1883 err = view->resize(view, 0);
1884 if (err)
1885 break;
1887 if (view->parent) {
1888 if (view->parent->resize) {
1889 err = view->parent->resize(view->parent, 0);
1890 if (err != NULL)
1891 break;
1893 err = offset_selection_down(view->parent);
1894 if (err != NULL)
1895 break;
1897 err = offset_selection_down(view);
1898 break;
1899 case 'S':
1900 view->count = 0;
1901 err = switch_split(view);
1902 break;
1903 case '-':
1904 err = view_resize_split(view, -1);
1905 break;
1906 case '+':
1907 err = view_resize_split(view, 1);
1908 break;
1909 case KEY_RESIZE:
1910 break;
1911 case '/':
1912 view->count = 0;
1913 if (view->search_start)
1914 view_search_start(view, fast_refresh);
1915 else
1916 err = view->input(new, view, ch);
1917 break;
1918 case 'N':
1919 case 'n':
1920 if (view->search_started && view->search_next) {
1921 view->searching = (ch == 'n' ?
1922 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1923 view->search_next_done = 0;
1924 view->search_next(view);
1925 } else
1926 err = view->input(new, view, ch);
1927 break;
1928 case 'A':
1929 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1930 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1931 view->action = "Patience diff algorithm";
1932 } else {
1933 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1934 view->action = "Myers diff algorithm";
1936 TAILQ_FOREACH(v, views, entry) {
1937 if (v->reset) {
1938 err = v->reset(v);
1939 if (err)
1940 return err;
1942 if (v->child && v->child->reset) {
1943 err = v->child->reset(v->child);
1944 if (err)
1945 return err;
1948 break;
1949 case TOG_KEY_SCRDUMP:
1950 err = screendump(view);
1951 break;
1952 default:
1953 err = view->input(new, view, ch);
1954 break;
1957 return err;
1960 static int
1961 view_needs_focus_indication(struct tog_view *view)
1963 if (view_is_parent_view(view)) {
1964 if (view->child == NULL || view->child->focussed)
1965 return 0;
1966 if (!view_is_splitscreen(view->child))
1967 return 0;
1968 } else if (!view_is_splitscreen(view))
1969 return 0;
1971 return view->focussed;
1974 static const struct got_error *
1975 tog_io_close(void)
1977 const struct got_error *err = NULL;
1979 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1980 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1981 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1982 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1983 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1984 err = got_ferror(tog_io.f, GOT_ERR_IO);
1985 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1986 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1987 if (tog_io.input_str != NULL)
1988 free(tog_io.input_str);
1990 return err;
1993 static const struct got_error *
1994 view_loop(struct tog_view *view)
1996 const struct got_error *err = NULL;
1997 struct tog_view_list_head views;
1998 struct tog_view *new_view;
1999 char *mode;
2000 int fast_refresh = 10;
2001 int done = 0, errcode;
2003 mode = getenv("TOG_VIEW_SPLIT_MODE");
2004 if (!mode || !(*mode == 'h' || *mode == 'H'))
2005 view->mode = TOG_VIEW_SPLIT_VERT;
2006 else
2007 view->mode = TOG_VIEW_SPLIT_HRZN;
2009 errcode = pthread_mutex_lock(&tog_mutex);
2010 if (errcode)
2011 return got_error_set_errno(errcode, "pthread_mutex_lock");
2013 TAILQ_INIT(&views);
2014 TAILQ_INSERT_HEAD(&views, view, entry);
2016 view->focussed = 1;
2017 err = view->show(view);
2018 if (err)
2019 return err;
2020 update_panels();
2021 doupdate();
2022 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
2023 !tog_fatal_signal_received()) {
2024 /* Refresh fast during initialization, then become slower. */
2025 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
2026 halfdelay(10); /* switch to once per second */
2028 err = view_input(&new_view, &done, view, &views, fast_refresh);
2029 if (err)
2030 break;
2032 if (view->dying && view == TAILQ_FIRST(&views) &&
2033 TAILQ_NEXT(view, entry) == NULL)
2034 done = 1;
2035 if (done) {
2036 struct tog_view *v;
2039 * When we quit, scroll the screen up a single line
2040 * so we don't lose any information.
2042 TAILQ_FOREACH(v, &views, entry) {
2043 wmove(v->window, 0, 0);
2044 wdeleteln(v->window);
2045 wnoutrefresh(v->window);
2046 if (v->child && !view_is_fullscreen(v)) {
2047 wmove(v->child->window, 0, 0);
2048 wdeleteln(v->child->window);
2049 wnoutrefresh(v->child->window);
2052 doupdate();
2055 if (view->dying) {
2056 struct tog_view *v, *prev = NULL;
2058 if (view_is_parent_view(view))
2059 prev = TAILQ_PREV(view, tog_view_list_head,
2060 entry);
2061 else if (view->parent)
2062 prev = view->parent;
2064 if (view->parent) {
2065 view->parent->child = NULL;
2066 view->parent->focus_child = 0;
2067 /* Restore fullscreen line height. */
2068 view->parent->nlines = view->parent->lines;
2069 err = view_resize(view->parent);
2070 if (err)
2071 break;
2072 /* Make resized splits persist. */
2073 view_transfer_size(view->parent, view);
2074 } else
2075 TAILQ_REMOVE(&views, view, entry);
2077 err = view_close(view);
2078 if (err)
2079 goto done;
2081 view = NULL;
2082 TAILQ_FOREACH(v, &views, entry) {
2083 if (v->focussed)
2084 break;
2086 if (view == NULL && new_view == NULL) {
2087 /* No view has focus. Try to pick one. */
2088 if (prev)
2089 view = prev;
2090 else if (!TAILQ_EMPTY(&views)) {
2091 view = TAILQ_LAST(&views,
2092 tog_view_list_head);
2094 if (view) {
2095 if (view->focus_child) {
2096 view->child->focussed = 1;
2097 view = view->child;
2098 } else
2099 view->focussed = 1;
2103 if (new_view) {
2104 struct tog_view *v, *t;
2105 /* Only allow one parent view per type. */
2106 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2107 if (v->type != new_view->type)
2108 continue;
2109 TAILQ_REMOVE(&views, v, entry);
2110 err = view_close(v);
2111 if (err)
2112 goto done;
2113 break;
2115 TAILQ_INSERT_TAIL(&views, new_view, entry);
2116 view = new_view;
2118 if (view && !done) {
2119 if (view_is_parent_view(view)) {
2120 if (view->child && view->child->focussed)
2121 view = view->child;
2122 } else {
2123 if (view->parent && view->parent->focussed)
2124 view = view->parent;
2126 show_panel(view->panel);
2127 if (view->child && view_is_splitscreen(view->child))
2128 show_panel(view->child->panel);
2129 if (view->parent && view_is_splitscreen(view)) {
2130 err = view->parent->show(view->parent);
2131 if (err)
2132 goto done;
2134 err = view->show(view);
2135 if (err)
2136 goto done;
2137 if (view->child) {
2138 err = view->child->show(view->child);
2139 if (err)
2140 goto done;
2142 update_panels();
2143 doupdate();
2146 done:
2147 while (!TAILQ_EMPTY(&views)) {
2148 const struct got_error *close_err;
2149 view = TAILQ_FIRST(&views);
2150 TAILQ_REMOVE(&views, view, entry);
2151 close_err = view_close(view);
2152 if (close_err && err == NULL)
2153 err = close_err;
2156 errcode = pthread_mutex_unlock(&tog_mutex);
2157 if (errcode && err == NULL)
2158 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2160 return err;
2163 __dead static void
2164 usage_log(void)
2166 endwin();
2167 fprintf(stderr,
2168 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2169 getprogname());
2170 exit(1);
2173 /* Create newly allocated wide-character string equivalent to a byte string. */
2174 static const struct got_error *
2175 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2177 char *vis = NULL;
2178 const struct got_error *err = NULL;
2180 *ws = NULL;
2181 *wlen = mbstowcs(NULL, s, 0);
2182 if (*wlen == (size_t)-1) {
2183 int vislen;
2184 if (errno != EILSEQ)
2185 return got_error_from_errno("mbstowcs");
2187 /* byte string invalid in current encoding; try to "fix" it */
2188 err = got_mbsavis(&vis, &vislen, s);
2189 if (err)
2190 return err;
2191 *wlen = mbstowcs(NULL, vis, 0);
2192 if (*wlen == (size_t)-1) {
2193 err = got_error_from_errno("mbstowcs"); /* give up */
2194 goto done;
2198 *ws = calloc(*wlen + 1, sizeof(**ws));
2199 if (*ws == NULL) {
2200 err = got_error_from_errno("calloc");
2201 goto done;
2204 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2205 err = got_error_from_errno("mbstowcs");
2206 done:
2207 free(vis);
2208 if (err) {
2209 free(*ws);
2210 *ws = NULL;
2211 *wlen = 0;
2213 return err;
2216 static const struct got_error *
2217 expand_tab(char **ptr, const char *src)
2219 char *dst;
2220 size_t len, n, idx = 0, sz = 0;
2222 *ptr = NULL;
2223 n = len = strlen(src);
2224 dst = malloc(n + 1);
2225 if (dst == NULL)
2226 return got_error_from_errno("malloc");
2228 while (idx < len && src[idx]) {
2229 const char c = src[idx];
2231 if (c == '\t') {
2232 size_t nb = TABSIZE - sz % TABSIZE;
2233 char *p;
2235 p = realloc(dst, n + nb);
2236 if (p == NULL) {
2237 free(dst);
2238 return got_error_from_errno("realloc");
2241 dst = p;
2242 n += nb;
2243 memset(dst + sz, ' ', nb);
2244 sz += nb;
2245 } else
2246 dst[sz++] = src[idx];
2247 ++idx;
2250 dst[sz] = '\0';
2251 *ptr = dst;
2252 return NULL;
2256 * Advance at most n columns from wline starting at offset off.
2257 * Return the index to the first character after the span operation.
2258 * Return the combined column width of all spanned wide characters in
2259 * *rcol.
2261 static int
2262 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2264 int width, i, cols = 0;
2266 if (n == 0) {
2267 *rcol = cols;
2268 return off;
2271 for (i = off; wline[i] != L'\0'; ++i) {
2272 if (wline[i] == L'\t')
2273 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2274 else
2275 width = wcwidth(wline[i]);
2277 if (width == -1) {
2278 width = 1;
2279 wline[i] = L'.';
2282 if (cols + width > n)
2283 break;
2284 cols += width;
2287 *rcol = cols;
2288 return i;
2292 * Format a line for display, ensuring that it won't overflow a width limit.
2293 * With scrolling, the width returned refers to the scrolled version of the
2294 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2296 static const struct got_error *
2297 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2298 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2300 const struct got_error *err = NULL;
2301 int cols;
2302 wchar_t *wline = NULL;
2303 char *exstr = NULL;
2304 size_t wlen;
2305 int i, scrollx;
2307 *wlinep = NULL;
2308 *widthp = 0;
2310 if (expand) {
2311 err = expand_tab(&exstr, line);
2312 if (err)
2313 return err;
2316 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2317 free(exstr);
2318 if (err)
2319 return err;
2321 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2323 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2324 wline[wlen - 1] = L'\0';
2325 wlen--;
2327 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2328 wline[wlen - 1] = L'\0';
2329 wlen--;
2332 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2333 wline[i] = L'\0';
2335 if (widthp)
2336 *widthp = cols;
2337 if (scrollxp)
2338 *scrollxp = scrollx;
2339 if (err)
2340 free(wline);
2341 else
2342 *wlinep = wline;
2343 return err;
2346 static const struct got_error*
2347 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2348 struct got_object_id *id, struct got_repository *repo)
2350 static const struct got_error *err = NULL;
2351 struct got_reflist_entry *re;
2352 char *s;
2353 const char *name;
2355 *refs_str = NULL;
2357 if (refs == NULL)
2358 return NULL;
2360 TAILQ_FOREACH(re, refs, entry) {
2361 struct got_tag_object *tag = NULL;
2362 struct got_object_id *ref_id;
2363 int cmp;
2365 name = got_ref_get_name(re->ref);
2366 if (strcmp(name, GOT_REF_HEAD) == 0)
2367 continue;
2368 if (strncmp(name, "refs/", 5) == 0)
2369 name += 5;
2370 if (strncmp(name, "got/", 4) == 0)
2371 continue;
2372 if (strncmp(name, "heads/", 6) == 0)
2373 name += 6;
2374 if (strncmp(name, "remotes/", 8) == 0) {
2375 name += 8;
2376 s = strstr(name, "/" GOT_REF_HEAD);
2377 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
2378 continue;
2380 err = got_ref_resolve(&ref_id, repo, re->ref);
2381 if (err)
2382 break;
2383 if (strncmp(name, "tags/", 5) == 0) {
2384 err = got_object_open_as_tag(&tag, repo, ref_id);
2385 if (err) {
2386 if (err->code != GOT_ERR_OBJ_TYPE) {
2387 free(ref_id);
2388 break;
2390 /* Ref points at something other than a tag. */
2391 err = NULL;
2392 tag = NULL;
2395 cmp = got_object_id_cmp(tag ?
2396 got_object_tag_get_object_id(tag) : ref_id, id);
2397 free(ref_id);
2398 if (tag)
2399 got_object_tag_close(tag);
2400 if (cmp != 0)
2401 continue;
2402 s = *refs_str;
2403 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2404 s ? ", " : "", name) == -1) {
2405 err = got_error_from_errno("asprintf");
2406 free(s);
2407 *refs_str = NULL;
2408 break;
2410 free(s);
2413 return err;
2416 static const struct got_error *
2417 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2418 int col_tab_align)
2420 char *smallerthan;
2422 smallerthan = strchr(author, '<');
2423 if (smallerthan && smallerthan[1] != '\0')
2424 author = smallerthan + 1;
2425 author[strcspn(author, "@>")] = '\0';
2426 return format_line(wauthor, author_width, NULL, author, 0, limit,
2427 col_tab_align, 0);
2430 static const struct got_error *
2431 draw_commit(struct tog_view *view, struct commit_queue_entry *entry,
2432 const size_t date_display_cols, int author_display_cols)
2434 struct tog_log_view_state *s = &view->state.log;
2435 const struct got_error *err = NULL;
2436 struct got_commit_object *commit = entry->commit;
2437 struct got_object_id *id = entry->id;
2438 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2439 char *refs_str = NULL;
2440 char *logmsg0 = NULL, *logmsg = NULL;
2441 char *author = NULL;
2442 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2443 int author_width, refstr_width, logmsg_width;
2444 char *newline, *line = NULL;
2445 int col, limit, scrollx, logmsg_x;
2446 const int avail = view->ncols, marker_column = author_display_cols + 1;
2447 struct tm tm;
2448 time_t committer_time;
2449 struct tog_color *tc;
2450 struct got_reflist_head *refs;
2452 if (tog_base_commit.id != NULL && tog_base_commit.idx == -1 &&
2453 got_object_id_cmp(id, tog_base_commit.id) == 0)
2454 tog_base_commit.idx = entry->idx;
2455 if (tog_io.wait_for_ui && s->thread_args.need_commit_marker) {
2456 int rc;
2458 rc = pthread_cond_wait(&s->thread_args.log_loaded, &tog_mutex);
2459 if (rc)
2460 return got_error_set_errno(rc, "pthread_cond_wait");
2463 committer_time = got_object_commit_get_committer_time(commit);
2464 if (gmtime_r(&committer_time, &tm) == NULL)
2465 return got_error_from_errno("gmtime_r");
2466 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2467 return got_error(GOT_ERR_NO_SPACE);
2469 if (avail <= date_display_cols)
2470 limit = MIN(sizeof(datebuf) - 1, avail);
2471 else
2472 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2473 tc = get_color(&s->colors, TOG_COLOR_DATE);
2474 if (tc)
2475 wattr_on(view->window,
2476 COLOR_PAIR(tc->colorpair), NULL);
2477 waddnstr(view->window, datebuf, limit);
2478 if (tc)
2479 wattr_off(view->window,
2480 COLOR_PAIR(tc->colorpair), NULL);
2481 col = limit;
2482 if (col > avail)
2483 goto done;
2485 if (avail >= 120) {
2486 char *id_str;
2487 err = got_object_id_str(&id_str, id);
2488 if (err)
2489 goto done;
2490 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2491 if (tc)
2492 wattr_on(view->window,
2493 COLOR_PAIR(tc->colorpair), NULL);
2494 wprintw(view->window, "%.8s ", id_str);
2495 if (tc)
2496 wattr_off(view->window,
2497 COLOR_PAIR(tc->colorpair), NULL);
2498 free(id_str);
2499 col += 9;
2500 if (col > avail)
2501 goto done;
2504 if (s->use_committer)
2505 author = strdup(got_object_commit_get_committer(commit));
2506 else
2507 author = strdup(got_object_commit_get_author(commit));
2508 if (author == NULL) {
2509 err = got_error_from_errno("strdup");
2510 goto done;
2512 err = format_author(&wauthor, &author_width, author, avail - col, col);
2513 if (err)
2514 goto done;
2515 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2516 if (tc)
2517 wattr_on(view->window,
2518 COLOR_PAIR(tc->colorpair), NULL);
2519 waddwstr(view->window, wauthor);
2520 col += author_width;
2521 while (col < avail && author_width < author_display_cols + 2) {
2522 if (tog_base_commit.marker != GOT_WORKTREE_STATE_UNKNOWN &&
2523 author_width == marker_column &&
2524 entry->idx == tog_base_commit.idx && !s->limit_view) {
2525 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2526 if (tc)
2527 wattr_on(view->window,
2528 COLOR_PAIR(tc->colorpair), NULL);
2529 waddch(view->window, tog_base_commit.marker);
2530 if (tc)
2531 wattr_off(view->window,
2532 COLOR_PAIR(tc->colorpair), NULL);
2533 } else
2534 waddch(view->window, ' ');
2535 col++;
2536 author_width++;
2538 if (tc)
2539 wattr_off(view->window,
2540 COLOR_PAIR(tc->colorpair), NULL);
2541 if (col > avail)
2542 goto done;
2544 err = got_object_commit_get_logmsg(&logmsg0, commit);
2545 if (err)
2546 goto done;
2547 logmsg = logmsg0;
2548 while (*logmsg == '\n')
2549 logmsg++;
2550 newline = strchr(logmsg, '\n');
2551 if (newline)
2552 *newline = '\0';
2554 limit = avail - col;
2555 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2556 limit--; /* for the border */
2558 /* Prepend reference labels to log message if possible .*/
2559 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2560 err = build_refs_str(&refs_str, refs, id, s->repo);
2561 if (err)
2562 goto done;
2563 if (refs_str) {
2564 char *rs;
2566 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2567 err = got_error_from_errno("asprintf");
2568 goto done;
2570 err = format_line(&wrefstr, &refstr_width,
2571 &scrollx, rs, view->x, limit, col, 1);
2572 free(rs);
2573 if (err)
2574 goto done;
2575 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2576 if (tc)
2577 wattr_on(view->window,
2578 COLOR_PAIR(tc->colorpair), NULL);
2579 waddwstr(view->window, &wrefstr[scrollx]);
2580 if (tc)
2581 wattr_off(view->window,
2582 COLOR_PAIR(tc->colorpair), NULL);
2583 col += MAX(refstr_width, 0);
2584 if (col > avail)
2585 goto done;
2587 if (col < avail) {
2588 waddch(view->window, ' ');
2589 col++;
2592 if (refstr_width > 0)
2593 logmsg_x = 0;
2594 else {
2595 int unscrolled_refstr_width;
2596 size_t len = wcslen(wrefstr);
2599 * No need to check for -1 return value here since
2600 * unprintables have been replaced by span_wline().
2602 unscrolled_refstr_width = wcswidth(wrefstr, len);
2603 unscrolled_refstr_width += 1; /* trailing space */
2604 logmsg_x = view->x - unscrolled_refstr_width;
2607 limit = avail - col;
2608 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2609 limit--; /* for the border */
2610 } else
2611 logmsg_x = view->x;
2613 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2614 limit, col, 1);
2615 if (err)
2616 goto done;
2617 waddwstr(view->window, &wlogmsg[scrollx]);
2618 col += MAX(logmsg_width, 0);
2619 while (col < avail) {
2620 waddch(view->window, ' ');
2621 col++;
2623 done:
2624 free(logmsg0);
2625 free(wlogmsg);
2626 free(wrefstr);
2627 free(refs_str);
2628 free(author);
2629 free(wauthor);
2630 free(line);
2631 return err;
2634 static struct commit_queue_entry *
2635 alloc_commit_queue_entry(struct got_commit_object *commit,
2636 struct got_object_id *id)
2638 struct commit_queue_entry *entry;
2639 struct got_object_id *dup;
2641 entry = calloc(1, sizeof(*entry));
2642 if (entry == NULL)
2643 return NULL;
2645 dup = got_object_id_dup(id);
2646 if (dup == NULL) {
2647 free(entry);
2648 return NULL;
2651 entry->id = dup;
2652 entry->commit = commit;
2653 return entry;
2656 static void
2657 pop_commit(struct commit_queue *commits)
2659 struct commit_queue_entry *entry;
2661 entry = TAILQ_FIRST(&commits->head);
2662 TAILQ_REMOVE(&commits->head, entry, entry);
2663 got_object_commit_close(entry->commit);
2664 commits->ncommits--;
2665 free(entry->id);
2666 free(entry);
2669 static void
2670 free_commits(struct commit_queue *commits)
2672 while (!TAILQ_EMPTY(&commits->head))
2673 pop_commit(commits);
2676 static const struct got_error *
2677 match_commit(int *have_match, struct got_object_id *id,
2678 struct got_commit_object *commit, regex_t *regex)
2680 const struct got_error *err = NULL;
2681 regmatch_t regmatch;
2682 char *id_str = NULL, *logmsg = NULL;
2684 *have_match = 0;
2686 err = got_object_id_str(&id_str, id);
2687 if (err)
2688 return err;
2690 err = got_object_commit_get_logmsg(&logmsg, commit);
2691 if (err)
2692 goto done;
2694 if (regexec(regex, got_object_commit_get_author(commit), 1,
2695 &regmatch, 0) == 0 ||
2696 regexec(regex, got_object_commit_get_committer(commit), 1,
2697 &regmatch, 0) == 0 ||
2698 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2699 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2700 *have_match = 1;
2701 done:
2702 free(id_str);
2703 free(logmsg);
2704 return err;
2707 static const struct got_error *
2708 queue_commits(struct tog_log_thread_args *a)
2710 const struct got_error *err = NULL;
2713 * We keep all commits open throughout the lifetime of the log
2714 * view in order to avoid having to re-fetch commits from disk
2715 * while updating the display.
2717 do {
2718 struct got_object_id id;
2719 struct got_commit_object *commit;
2720 struct commit_queue_entry *entry;
2721 int limit_match = 0;
2722 int errcode;
2724 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2725 NULL, NULL);
2726 if (err)
2727 break;
2729 err = got_object_open_as_commit(&commit, a->repo, &id);
2730 if (err)
2731 break;
2732 entry = alloc_commit_queue_entry(commit, &id);
2733 if (entry == NULL) {
2734 err = got_error_from_errno("alloc_commit_queue_entry");
2735 break;
2738 errcode = pthread_mutex_lock(&tog_mutex);
2739 if (errcode) {
2740 err = got_error_set_errno(errcode,
2741 "pthread_mutex_lock");
2742 break;
2745 entry->idx = a->real_commits->ncommits;
2746 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2747 a->real_commits->ncommits++;
2749 if (*a->limiting) {
2750 err = match_commit(&limit_match, &id, commit,
2751 a->limit_regex);
2752 if (err)
2753 break;
2755 if (limit_match) {
2756 struct commit_queue_entry *matched;
2758 matched = alloc_commit_queue_entry(
2759 entry->commit, entry->id);
2760 if (matched == NULL) {
2761 err = got_error_from_errno(
2762 "alloc_commit_queue_entry");
2763 break;
2765 matched->commit = entry->commit;
2766 got_object_commit_retain(entry->commit);
2768 matched->idx = a->limit_commits->ncommits;
2769 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2770 matched, entry);
2771 a->limit_commits->ncommits++;
2775 * This is how we signal log_thread() that we
2776 * have found a match, and that it should be
2777 * counted as a new entry for the view.
2779 a->limit_match = limit_match;
2782 if (*a->searching == TOG_SEARCH_FORWARD &&
2783 !*a->search_next_done) {
2784 int have_match;
2785 err = match_commit(&have_match, &id, commit, a->regex);
2786 if (err)
2787 break;
2789 if (*a->limiting) {
2790 if (limit_match && have_match)
2791 *a->search_next_done =
2792 TOG_SEARCH_HAVE_MORE;
2793 } else if (have_match)
2794 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2797 errcode = pthread_mutex_unlock(&tog_mutex);
2798 if (errcode && err == NULL)
2799 err = got_error_set_errno(errcode,
2800 "pthread_mutex_unlock");
2801 if (err)
2802 break;
2803 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2805 return err;
2808 static void
2809 select_commit(struct tog_log_view_state *s)
2811 struct commit_queue_entry *entry;
2812 int ncommits = 0;
2814 entry = s->first_displayed_entry;
2815 while (entry) {
2816 if (ncommits == s->selected) {
2817 s->selected_entry = entry;
2818 break;
2820 entry = TAILQ_NEXT(entry, entry);
2821 ncommits++;
2825 static const struct got_error *
2826 draw_commits(struct tog_view *view)
2828 const struct got_error *err = NULL;
2829 struct tog_log_view_state *s = &view->state.log;
2830 struct commit_queue_entry *entry = s->selected_entry;
2831 int limit = view->nlines;
2832 int width;
2833 int ncommits, author_cols = 4, refstr_cols;
2834 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2835 char *refs_str = NULL;
2836 wchar_t *wline;
2837 struct tog_color *tc;
2838 static const size_t date_display_cols = 12;
2839 struct got_reflist_head *refs;
2841 if (view_is_hsplit_top(view))
2842 --limit; /* account for border */
2844 if (s->selected_entry &&
2845 !(view->searching && view->search_next_done == 0)) {
2846 err = got_object_id_str(&id_str, s->selected_entry->id);
2847 if (err)
2848 return err;
2849 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2850 s->selected_entry->id);
2851 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2852 s->repo);
2853 if (err)
2854 goto done;
2857 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2858 halfdelay(10); /* disable fast refresh */
2860 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2861 if (asprintf(&ncommits_str, " [%d/%d] %s",
2862 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2863 (view->searching && !view->search_next_done) ?
2864 "searching..." : "loading...") == -1) {
2865 err = got_error_from_errno("asprintf");
2866 goto done;
2868 } else {
2869 const char *search_str = NULL;
2870 const char *limit_str = NULL;
2872 if (view->searching) {
2873 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2874 search_str = "no more matches";
2875 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2876 search_str = "no matches found";
2877 else if (!view->search_next_done)
2878 search_str = "searching...";
2881 if (s->limit_view && s->commits->ncommits == 0)
2882 limit_str = "no matches found";
2884 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2885 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2886 search_str ? search_str : (refs_str ? refs_str : ""),
2887 limit_str ? limit_str : "") == -1) {
2888 err = got_error_from_errno("asprintf");
2889 goto done;
2893 free(refs_str);
2894 refs_str = NULL;
2896 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2897 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2898 "........................................",
2899 s->in_repo_path, ncommits_str) == -1) {
2900 err = got_error_from_errno("asprintf");
2901 header = NULL;
2902 goto done;
2904 } else if (asprintf(&header, "commit %s%s",
2905 id_str ? id_str : "........................................",
2906 ncommits_str) == -1) {
2907 err = got_error_from_errno("asprintf");
2908 header = NULL;
2909 goto done;
2911 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2912 if (err)
2913 goto done;
2915 werase(view->window);
2917 if (view_needs_focus_indication(view))
2918 wstandout(view->window);
2919 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2920 if (tc)
2921 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2922 waddwstr(view->window, wline);
2923 while (width < view->ncols) {
2924 waddch(view->window, ' ');
2925 width++;
2927 if (tc)
2928 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2929 if (view_needs_focus_indication(view))
2930 wstandend(view->window);
2931 free(wline);
2932 if (limit <= 1)
2933 goto done;
2935 /* Grow author column size if necessary, and set view->maxx. */
2936 entry = s->first_displayed_entry;
2937 ncommits = 0;
2938 view->maxx = 0;
2939 while (entry) {
2940 struct got_commit_object *c = entry->commit;
2941 char *author, *eol, *msg, *msg0;
2942 wchar_t *wauthor, *wmsg;
2943 int width;
2944 if (ncommits >= limit - 1)
2945 break;
2946 if (s->use_committer)
2947 author = strdup(got_object_commit_get_committer(c));
2948 else
2949 author = strdup(got_object_commit_get_author(c));
2950 if (author == NULL) {
2951 err = got_error_from_errno("strdup");
2952 goto done;
2954 err = format_author(&wauthor, &width, author, COLS,
2955 date_display_cols);
2956 if (author_cols < width)
2957 author_cols = width;
2958 free(wauthor);
2959 free(author);
2960 if (err)
2961 goto done;
2962 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2963 entry->id);
2964 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2965 if (err)
2966 goto done;
2967 if (refs_str) {
2968 wchar_t *ws;
2969 err = format_line(&ws, &width, NULL, refs_str,
2970 0, INT_MAX, date_display_cols + author_cols, 0);
2971 free(ws);
2972 free(refs_str);
2973 refs_str = NULL;
2974 if (err)
2975 goto done;
2976 refstr_cols = width + 3; /* account for [ ] + space */
2977 } else
2978 refstr_cols = 0;
2979 err = got_object_commit_get_logmsg(&msg0, c);
2980 if (err)
2981 goto done;
2982 msg = msg0;
2983 while (*msg == '\n')
2984 ++msg;
2985 if ((eol = strchr(msg, '\n')))
2986 *eol = '\0';
2987 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2988 date_display_cols + author_cols + refstr_cols, 0);
2989 if (err)
2990 goto done;
2991 view->maxx = MAX(view->maxx, width + refstr_cols);
2992 free(msg0);
2993 free(wmsg);
2994 ncommits++;
2995 entry = TAILQ_NEXT(entry, entry);
2998 entry = s->first_displayed_entry;
2999 s->last_displayed_entry = s->first_displayed_entry;
3000 ncommits = 0;
3001 while (entry) {
3002 if (ncommits >= limit - 1)
3003 break;
3004 if (ncommits == s->selected)
3005 wstandout(view->window);
3006 err = draw_commit(view, entry, date_display_cols, author_cols);
3007 if (ncommits == s->selected)
3008 wstandend(view->window);
3009 if (err)
3010 goto done;
3011 ncommits++;
3012 s->last_displayed_entry = entry;
3013 entry = TAILQ_NEXT(entry, entry);
3016 view_border(view);
3017 done:
3018 free(id_str);
3019 free(refs_str);
3020 free(ncommits_str);
3021 free(header);
3022 return err;
3025 static void
3026 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
3028 struct commit_queue_entry *entry;
3029 int nscrolled = 0;
3031 entry = TAILQ_FIRST(&s->commits->head);
3032 if (s->first_displayed_entry == entry)
3033 return;
3035 entry = s->first_displayed_entry;
3036 while (entry && nscrolled < maxscroll) {
3037 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3038 if (entry) {
3039 s->first_displayed_entry = entry;
3040 nscrolled++;
3045 static const struct got_error *
3046 trigger_log_thread(struct tog_view *view, int wait)
3048 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3049 int errcode;
3051 if (!using_mock_io)
3052 halfdelay(1); /* fast refresh while loading commits */
3054 while (!ta->log_complete && !tog_thread_error &&
3055 (ta->commits_needed > 0 || ta->load_all)) {
3056 /* Wake the log thread. */
3057 errcode = pthread_cond_signal(&ta->need_commits);
3058 if (errcode)
3059 return got_error_set_errno(errcode,
3060 "pthread_cond_signal");
3063 * The mutex will be released while the view loop waits
3064 * in wgetch(), at which time the log thread will run.
3066 if (!wait)
3067 break;
3069 /* Display progress update in log view. */
3070 show_log_view(view);
3071 update_panels();
3072 doupdate();
3074 /* Wait right here while next commit is being loaded. */
3075 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3076 if (errcode)
3077 return got_error_set_errno(errcode,
3078 "pthread_cond_wait");
3080 /* Display progress update in log view. */
3081 show_log_view(view);
3082 update_panels();
3083 doupdate();
3086 return NULL;
3089 static const struct got_error *
3090 request_log_commits(struct tog_view *view)
3092 struct tog_log_view_state *state = &view->state.log;
3093 const struct got_error *err = NULL;
3095 if (state->thread_args.log_complete)
3096 return NULL;
3098 state->thread_args.commits_needed += view->nscrolled;
3099 err = trigger_log_thread(view, 1);
3100 view->nscrolled = 0;
3102 return err;
3105 static const struct got_error *
3106 log_scroll_down(struct tog_view *view, int maxscroll)
3108 struct tog_log_view_state *s = &view->state.log;
3109 const struct got_error *err = NULL;
3110 struct commit_queue_entry *pentry;
3111 int nscrolled = 0, ncommits_needed;
3113 if (s->last_displayed_entry == NULL)
3114 return NULL;
3116 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3117 if (s->commits->ncommits < ncommits_needed &&
3118 !s->thread_args.log_complete) {
3120 * Ask the log thread for required amount of commits.
3122 s->thread_args.commits_needed +=
3123 ncommits_needed - s->commits->ncommits;
3124 err = trigger_log_thread(view, 1);
3125 if (err)
3126 return err;
3129 do {
3130 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3131 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3132 break;
3134 s->last_displayed_entry = pentry ?
3135 pentry : s->last_displayed_entry;
3137 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3138 if (pentry == NULL)
3139 break;
3140 s->first_displayed_entry = pentry;
3141 } while (++nscrolled < maxscroll);
3143 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3144 view->nscrolled += nscrolled;
3145 else
3146 view->nscrolled = 0;
3148 return err;
3151 static const struct got_error *
3152 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3153 struct got_commit_object *commit, struct got_object_id *commit_id,
3154 struct tog_view *log_view, struct got_repository *repo)
3156 const struct got_error *err;
3157 struct got_object_qid *parent_id;
3158 struct tog_view *diff_view;
3160 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3161 if (diff_view == NULL)
3162 return got_error_from_errno("view_open");
3164 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3165 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3166 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3167 if (err == NULL)
3168 *new_view = diff_view;
3169 return err;
3172 static const struct got_error *
3173 tree_view_visit_subtree(struct tog_tree_view_state *s,
3174 struct got_tree_object *subtree)
3176 struct tog_parent_tree *parent;
3178 parent = calloc(1, sizeof(*parent));
3179 if (parent == NULL)
3180 return got_error_from_errno("calloc");
3182 parent->tree = s->tree;
3183 parent->first_displayed_entry = s->first_displayed_entry;
3184 parent->selected_entry = s->selected_entry;
3185 parent->selected = s->selected;
3186 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3187 s->tree = subtree;
3188 s->selected = 0;
3189 s->first_displayed_entry = NULL;
3190 return NULL;
3193 static const struct got_error *
3194 tree_view_walk_path(struct tog_tree_view_state *s,
3195 struct got_commit_object *commit, const char *path)
3197 const struct got_error *err = NULL;
3198 struct got_tree_object *tree = NULL;
3199 const char *p;
3200 char *slash, *subpath = NULL;
3202 /* Walk the path and open corresponding tree objects. */
3203 p = path;
3204 while (*p) {
3205 struct got_tree_entry *te;
3206 struct got_object_id *tree_id;
3207 char *te_name;
3209 while (p[0] == '/')
3210 p++;
3212 /* Ensure the correct subtree entry is selected. */
3213 slash = strchr(p, '/');
3214 if (slash == NULL)
3215 te_name = strdup(p);
3216 else
3217 te_name = strndup(p, slash - p);
3218 if (te_name == NULL) {
3219 err = got_error_from_errno("strndup");
3220 break;
3222 te = got_object_tree_find_entry(s->tree, te_name);
3223 if (te == NULL) {
3224 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3225 free(te_name);
3226 break;
3228 free(te_name);
3229 s->first_displayed_entry = s->selected_entry = te;
3231 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3232 break; /* jump to this file's entry */
3234 slash = strchr(p, '/');
3235 if (slash)
3236 subpath = strndup(path, slash - path);
3237 else
3238 subpath = strdup(path);
3239 if (subpath == NULL) {
3240 err = got_error_from_errno("strdup");
3241 break;
3244 err = got_object_id_by_path(&tree_id, s->repo, commit,
3245 subpath);
3246 if (err)
3247 break;
3249 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3250 free(tree_id);
3251 if (err)
3252 break;
3254 err = tree_view_visit_subtree(s, tree);
3255 if (err) {
3256 got_object_tree_close(tree);
3257 break;
3259 if (slash == NULL)
3260 break;
3261 free(subpath);
3262 subpath = NULL;
3263 p = slash;
3266 free(subpath);
3267 return err;
3270 static const struct got_error *
3271 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3272 struct commit_queue_entry *entry, const char *path,
3273 const char *head_ref_name, struct got_repository *repo)
3275 const struct got_error *err = NULL;
3276 struct tog_tree_view_state *s;
3277 struct tog_view *tree_view;
3279 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3280 if (tree_view == NULL)
3281 return got_error_from_errno("view_open");
3283 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3284 if (err)
3285 return err;
3286 s = &tree_view->state.tree;
3288 *new_view = tree_view;
3290 if (got_path_is_root_dir(path))
3291 return NULL;
3293 return tree_view_walk_path(s, entry->commit, path);
3296 static const struct got_error *
3297 block_signals_used_by_main_thread(void)
3299 sigset_t sigset;
3300 int errcode;
3302 if (sigemptyset(&sigset) == -1)
3303 return got_error_from_errno("sigemptyset");
3305 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3306 if (sigaddset(&sigset, SIGWINCH) == -1)
3307 return got_error_from_errno("sigaddset");
3308 if (sigaddset(&sigset, SIGCONT) == -1)
3309 return got_error_from_errno("sigaddset");
3310 if (sigaddset(&sigset, SIGINT) == -1)
3311 return got_error_from_errno("sigaddset");
3312 if (sigaddset(&sigset, SIGTERM) == -1)
3313 return got_error_from_errno("sigaddset");
3315 /* ncurses handles SIGTSTP */
3316 if (sigaddset(&sigset, SIGTSTP) == -1)
3317 return got_error_from_errno("sigaddset");
3319 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3320 if (errcode)
3321 return got_error_set_errno(errcode, "pthread_sigmask");
3323 return NULL;
3326 static void *
3327 log_thread(void *arg)
3329 const struct got_error *err = NULL;
3330 int errcode = 0;
3331 struct tog_log_thread_args *a = arg;
3332 int done = 0;
3335 * Sync startup with main thread such that we begin our
3336 * work once view_input() has released the mutex.
3338 errcode = pthread_mutex_lock(&tog_mutex);
3339 if (errcode) {
3340 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3341 return (void *)err;
3344 err = block_signals_used_by_main_thread();
3345 if (err) {
3346 pthread_mutex_unlock(&tog_mutex);
3347 goto done;
3350 while (!done && !err && !tog_fatal_signal_received()) {
3351 errcode = pthread_mutex_unlock(&tog_mutex);
3352 if (errcode) {
3353 err = got_error_set_errno(errcode,
3354 "pthread_mutex_unlock");
3355 goto done;
3357 err = queue_commits(a);
3358 if (err) {
3359 if (err->code != GOT_ERR_ITER_COMPLETED)
3360 goto done;
3361 err = NULL;
3362 done = 1;
3363 a->commits_needed = 0;
3364 } else if (a->commits_needed > 0 && !a->load_all) {
3365 if (*a->limiting) {
3366 if (a->limit_match)
3367 a->commits_needed--;
3368 } else
3369 a->commits_needed--;
3372 errcode = pthread_mutex_lock(&tog_mutex);
3373 if (errcode) {
3374 err = got_error_set_errno(errcode,
3375 "pthread_mutex_lock");
3376 goto done;
3377 } else if (*a->quit)
3378 done = 1;
3379 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3380 *a->first_displayed_entry =
3381 TAILQ_FIRST(&a->limit_commits->head);
3382 *a->selected_entry = *a->first_displayed_entry;
3383 } else if (*a->first_displayed_entry == NULL) {
3384 *a->first_displayed_entry =
3385 TAILQ_FIRST(&a->real_commits->head);
3386 *a->selected_entry = *a->first_displayed_entry;
3389 errcode = pthread_cond_signal(&a->commit_loaded);
3390 if (errcode) {
3391 err = got_error_set_errno(errcode,
3392 "pthread_cond_signal");
3393 pthread_mutex_unlock(&tog_mutex);
3394 goto done;
3397 if (a->commits_needed == 0 &&
3398 a->need_commit_marker && a->worktree) {
3399 errcode = pthread_mutex_unlock(&tog_mutex);
3400 if (errcode) {
3401 err = got_error_set_errno(errcode,
3402 "pthread_mutex_unlock");
3403 goto done;
3405 err = got_worktree_get_state(&tog_base_commit.marker,
3406 a->repo, a->worktree, NULL, NULL);
3407 if (err)
3408 goto done;
3409 errcode = pthread_mutex_lock(&tog_mutex);
3410 if (errcode) {
3411 err = got_error_set_errno(errcode,
3412 "pthread_mutex_lock");
3413 goto done;
3415 a->need_commit_marker = 0;
3417 * The main thread did not close this
3418 * work tree yet. Close it now.
3420 got_worktree_close(a->worktree);
3421 a->worktree = NULL;
3423 if (*a->quit)
3424 done = 1;
3427 if (done)
3428 a->commits_needed = 0;
3429 else {
3430 if (a->commits_needed == 0 && !a->load_all) {
3431 if (tog_io.wait_for_ui) {
3432 errcode = pthread_cond_signal(
3433 &a->log_loaded);
3434 if (errcode && err == NULL)
3435 err = got_error_set_errno(
3436 errcode,
3437 "pthread_cond_signal");
3440 errcode = pthread_cond_wait(&a->need_commits,
3441 &tog_mutex);
3442 if (errcode) {
3443 err = got_error_set_errno(errcode,
3444 "pthread_cond_wait");
3445 pthread_mutex_unlock(&tog_mutex);
3446 goto done;
3448 if (*a->quit)
3449 done = 1;
3453 a->log_complete = 1;
3454 if (tog_io.wait_for_ui) {
3455 errcode = pthread_cond_signal(&a->log_loaded);
3456 if (errcode && err == NULL)
3457 err = got_error_set_errno(errcode,
3458 "pthread_cond_signal");
3461 errcode = pthread_mutex_unlock(&tog_mutex);
3462 if (errcode)
3463 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3464 done:
3465 if (err) {
3466 tog_thread_error = 1;
3467 pthread_cond_signal(&a->commit_loaded);
3468 if (a->worktree) {
3469 got_worktree_close(a->worktree);
3470 a->worktree = NULL;
3473 return (void *)err;
3476 static const struct got_error *
3477 stop_log_thread(struct tog_log_view_state *s)
3479 const struct got_error *err = NULL, *thread_err = NULL;
3480 int errcode;
3482 if (s->thread) {
3483 s->quit = 1;
3484 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3485 if (errcode)
3486 return got_error_set_errno(errcode,
3487 "pthread_cond_signal");
3488 errcode = pthread_mutex_unlock(&tog_mutex);
3489 if (errcode)
3490 return got_error_set_errno(errcode,
3491 "pthread_mutex_unlock");
3492 errcode = pthread_join(s->thread, (void **)&thread_err);
3493 if (errcode)
3494 return got_error_set_errno(errcode, "pthread_join");
3495 errcode = pthread_mutex_lock(&tog_mutex);
3496 if (errcode)
3497 return got_error_set_errno(errcode,
3498 "pthread_mutex_lock");
3499 s->thread = 0; //NULL;
3502 if (s->thread_args.repo) {
3503 err = got_repo_close(s->thread_args.repo);
3504 s->thread_args.repo = NULL;
3507 if (s->thread_args.pack_fds) {
3508 const struct got_error *pack_err =
3509 got_repo_pack_fds_close(s->thread_args.pack_fds);
3510 if (err == NULL)
3511 err = pack_err;
3512 s->thread_args.pack_fds = NULL;
3515 if (s->thread_args.graph) {
3516 got_commit_graph_close(s->thread_args.graph);
3517 s->thread_args.graph = NULL;
3520 return err ? err : thread_err;
3523 static const struct got_error *
3524 close_log_view(struct tog_view *view)
3526 const struct got_error *err = NULL;
3527 struct tog_log_view_state *s = &view->state.log;
3528 int errcode;
3530 err = stop_log_thread(s);
3532 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3533 if (errcode && err == NULL)
3534 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3536 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3537 if (errcode && err == NULL)
3538 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3540 free_commits(&s->limit_commits);
3541 free_commits(&s->real_commits);
3542 free_colors(&s->colors);
3543 free(s->in_repo_path);
3544 s->in_repo_path = NULL;
3545 free(s->start_id);
3546 s->start_id = NULL;
3547 free(s->head_ref_name);
3548 s->head_ref_name = NULL;
3549 return err;
3553 * We use two queues to implement the limit feature: first consists of
3554 * commits matching the current limit_regex; second is the real queue
3555 * of all known commits (real_commits). When the user starts limiting,
3556 * we swap queues such that all movement and displaying functionality
3557 * works with very slight change.
3559 static const struct got_error *
3560 limit_log_view(struct tog_view *view)
3562 struct tog_log_view_state *s = &view->state.log;
3563 struct commit_queue_entry *entry;
3564 struct tog_view *v = view;
3565 const struct got_error *err = NULL;
3566 char pattern[1024];
3567 int ret;
3569 if (view_is_hsplit_top(view))
3570 v = view->child;
3571 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3572 v = view->parent;
3574 if (tog_io.input_str != NULL) {
3575 if (strlcpy(pattern, tog_io.input_str, sizeof(pattern)) >=
3576 sizeof(pattern))
3577 return got_error(GOT_ERR_NO_SPACE);
3578 } else {
3579 wmove(v->window, v->nlines - 1, 0);
3580 wclrtoeol(v->window);
3581 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3582 nodelay(v->window, FALSE);
3583 nocbreak();
3584 echo();
3585 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3586 cbreak();
3587 noecho();
3588 nodelay(v->window, TRUE);
3589 if (ret == ERR)
3590 return NULL;
3593 if (*pattern == '\0') {
3595 * Safety measure for the situation where the user
3596 * resets limit without previously limiting anything.
3598 if (!s->limit_view)
3599 return NULL;
3602 * User could have pressed Ctrl+L, which refreshed the
3603 * commit queues, it means we can't save previously
3604 * (before limit took place) displayed entries,
3605 * because they would point to already free'ed memory,
3606 * so we are forced to always select first entry of
3607 * the queue.
3609 s->commits = &s->real_commits;
3610 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3611 s->selected_entry = s->first_displayed_entry;
3612 s->selected = 0;
3613 s->limit_view = 0;
3615 return NULL;
3618 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3619 return NULL;
3621 s->limit_view = 1;
3623 /* Clear the screen while loading limit view */
3624 s->first_displayed_entry = NULL;
3625 s->last_displayed_entry = NULL;
3626 s->selected_entry = NULL;
3627 s->commits = &s->limit_commits;
3629 /* Prepare limit queue for new search */
3630 free_commits(&s->limit_commits);
3631 s->limit_commits.ncommits = 0;
3633 /* First process commits, which are in queue already */
3634 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3635 int have_match = 0;
3637 err = match_commit(&have_match, entry->id,
3638 entry->commit, &s->limit_regex);
3639 if (err)
3640 return err;
3642 if (have_match) {
3643 struct commit_queue_entry *matched;
3645 matched = alloc_commit_queue_entry(entry->commit,
3646 entry->id);
3647 if (matched == NULL) {
3648 err = got_error_from_errno(
3649 "alloc_commit_queue_entry");
3650 break;
3652 matched->commit = entry->commit;
3653 got_object_commit_retain(entry->commit);
3655 matched->idx = s->limit_commits.ncommits;
3656 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3657 matched, entry);
3658 s->limit_commits.ncommits++;
3662 /* Second process all the commits, until we fill the screen */
3663 if (s->limit_commits.ncommits < view->nlines - 1 &&
3664 !s->thread_args.log_complete) {
3665 s->thread_args.commits_needed +=
3666 view->nlines - s->limit_commits.ncommits - 1;
3667 err = trigger_log_thread(view, 1);
3668 if (err)
3669 return err;
3672 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3673 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3674 s->selected = 0;
3676 return NULL;
3679 static const struct got_error *
3680 search_start_log_view(struct tog_view *view)
3682 struct tog_log_view_state *s = &view->state.log;
3684 s->matched_entry = NULL;
3685 s->search_entry = NULL;
3686 return NULL;
3689 static const struct got_error *
3690 search_next_log_view(struct tog_view *view)
3692 const struct got_error *err = NULL;
3693 struct tog_log_view_state *s = &view->state.log;
3694 struct commit_queue_entry *entry;
3696 /* Display progress update in log view. */
3697 show_log_view(view);
3698 update_panels();
3699 doupdate();
3701 if (s->search_entry) {
3702 if (!using_mock_io) {
3703 int errcode, ch;
3705 errcode = pthread_mutex_unlock(&tog_mutex);
3706 if (errcode)
3707 return got_error_set_errno(errcode,
3708 "pthread_mutex_unlock");
3709 ch = wgetch(view->window);
3710 errcode = pthread_mutex_lock(&tog_mutex);
3711 if (errcode)
3712 return got_error_set_errno(errcode,
3713 "pthread_mutex_lock");
3714 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3715 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3716 return NULL;
3719 if (view->searching == TOG_SEARCH_FORWARD)
3720 entry = TAILQ_NEXT(s->search_entry, entry);
3721 else
3722 entry = TAILQ_PREV(s->search_entry,
3723 commit_queue_head, entry);
3724 } else if (s->matched_entry) {
3726 * If the user has moved the cursor after we hit a match,
3727 * the position from where we should continue searching
3728 * might have changed.
3730 if (view->searching == TOG_SEARCH_FORWARD)
3731 entry = TAILQ_NEXT(s->selected_entry, entry);
3732 else
3733 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3734 entry);
3735 } else {
3736 entry = s->selected_entry;
3739 while (1) {
3740 int have_match = 0;
3742 if (entry == NULL) {
3743 if (s->thread_args.log_complete ||
3744 view->searching == TOG_SEARCH_BACKWARD) {
3745 view->search_next_done =
3746 (s->matched_entry == NULL ?
3747 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3748 s->search_entry = NULL;
3749 return NULL;
3752 * Poke the log thread for more commits and return,
3753 * allowing the main loop to make progress. Search
3754 * will resume at s->search_entry once we come back.
3756 s->search_entry = s->selected_entry;
3757 s->thread_args.commits_needed++;
3758 return trigger_log_thread(view, 0);
3761 err = match_commit(&have_match, entry->id, entry->commit,
3762 &view->regex);
3763 if (err)
3764 break;
3765 if (have_match) {
3766 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3767 s->matched_entry = entry;
3768 break;
3771 s->search_entry = entry;
3772 if (view->searching == TOG_SEARCH_FORWARD)
3773 entry = TAILQ_NEXT(entry, entry);
3774 else
3775 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3778 if (s->matched_entry) {
3779 int cur = s->selected_entry->idx;
3780 while (cur < s->matched_entry->idx) {
3781 err = input_log_view(NULL, view, KEY_DOWN);
3782 if (err)
3783 return err;
3784 cur++;
3786 while (cur > s->matched_entry->idx) {
3787 err = input_log_view(NULL, view, KEY_UP);
3788 if (err)
3789 return err;
3790 cur--;
3794 s->search_entry = NULL;
3796 return NULL;
3799 static const struct got_error *
3800 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3801 struct got_repository *repo, const char *head_ref_name,
3802 const char *in_repo_path, int log_branches,
3803 struct got_worktree *worktree)
3805 const struct got_error *err = NULL;
3806 struct tog_log_view_state *s = &view->state.log;
3807 struct got_repository *thread_repo = NULL;
3808 struct got_commit_graph *thread_graph = NULL;
3809 int errcode;
3811 if (in_repo_path != s->in_repo_path) {
3812 free(s->in_repo_path);
3813 s->in_repo_path = strdup(in_repo_path);
3814 if (s->in_repo_path == NULL) {
3815 err = got_error_from_errno("strdup");
3816 goto done;
3820 /* The commit queue only contains commits being displayed. */
3821 TAILQ_INIT(&s->real_commits.head);
3822 s->real_commits.ncommits = 0;
3823 s->commits = &s->real_commits;
3825 TAILQ_INIT(&s->limit_commits.head);
3826 s->limit_view = 0;
3827 s->limit_commits.ncommits = 0;
3829 s->repo = repo;
3830 if (head_ref_name) {
3831 s->head_ref_name = strdup(head_ref_name);
3832 if (s->head_ref_name == NULL) {
3833 err = got_error_from_errno("strdup");
3834 goto done;
3837 s->start_id = got_object_id_dup(start_id);
3838 if (s->start_id == NULL) {
3839 err = got_error_from_errno("got_object_id_dup");
3840 goto done;
3842 s->log_branches = log_branches;
3843 s->use_committer = 1;
3845 STAILQ_INIT(&s->colors);
3846 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3847 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3848 get_color_value("TOG_COLOR_COMMIT"));
3849 if (err)
3850 goto done;
3851 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3852 get_color_value("TOG_COLOR_AUTHOR"));
3853 if (err)
3854 goto done;
3855 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3856 get_color_value("TOG_COLOR_DATE"));
3857 if (err)
3858 goto done;
3861 view->show = show_log_view;
3862 view->input = input_log_view;
3863 view->resize = resize_log_view;
3864 view->close = close_log_view;
3865 view->search_start = search_start_log_view;
3866 view->search_next = search_next_log_view;
3868 if (s->thread_args.pack_fds == NULL) {
3869 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3870 if (err)
3871 goto done;
3873 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3874 s->thread_args.pack_fds);
3875 if (err)
3876 goto done;
3877 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3878 !s->log_branches);
3879 if (err)
3880 goto done;
3881 err = got_commit_graph_bfsort(thread_graph, s->start_id,
3882 s->repo, NULL, NULL);
3883 if (err)
3884 goto done;
3886 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3887 if (errcode) {
3888 err = got_error_set_errno(errcode, "pthread_cond_init");
3889 goto done;
3891 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3892 if (errcode) {
3893 err = got_error_set_errno(errcode, "pthread_cond_init");
3894 goto done;
3897 if (using_mock_io) {
3898 int rc;
3900 rc = pthread_cond_init(&s->thread_args.log_loaded, NULL);
3901 if (rc)
3902 return got_error_set_errno(rc, "pthread_cond_init");
3905 s->thread_args.commits_needed = view->nlines;
3906 s->thread_args.graph = thread_graph;
3907 s->thread_args.real_commits = &s->real_commits;
3908 s->thread_args.limit_commits = &s->limit_commits;
3909 s->thread_args.in_repo_path = s->in_repo_path;
3910 s->thread_args.start_id = s->start_id;
3911 s->thread_args.repo = thread_repo;
3912 s->thread_args.log_complete = 0;
3913 s->thread_args.quit = &s->quit;
3914 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3915 s->thread_args.selected_entry = &s->selected_entry;
3916 s->thread_args.searching = &view->searching;
3917 s->thread_args.search_next_done = &view->search_next_done;
3918 s->thread_args.regex = &view->regex;
3919 s->thread_args.limiting = &s->limit_view;
3920 s->thread_args.limit_regex = &s->limit_regex;
3921 s->thread_args.limit_commits = &s->limit_commits;
3922 s->thread_args.worktree = worktree;
3923 if (worktree)
3924 s->thread_args.need_commit_marker = 1;
3925 done:
3926 if (err) {
3927 if (view->close == NULL)
3928 close_log_view(view);
3929 view_close(view);
3931 return err;
3934 static const struct got_error *
3935 show_log_view(struct tog_view *view)
3937 const struct got_error *err;
3938 struct tog_log_view_state *s = &view->state.log;
3940 if (s->thread == 0) { //NULL) {
3941 int errcode = pthread_create(&s->thread, NULL, log_thread,
3942 &s->thread_args);
3943 if (errcode)
3944 return got_error_set_errno(errcode, "pthread_create");
3945 if (s->thread_args.commits_needed > 0) {
3946 err = trigger_log_thread(view, 1);
3947 if (err)
3948 return err;
3952 return draw_commits(view);
3955 static void
3956 log_move_cursor_up(struct tog_view *view, int page, int home)
3958 struct tog_log_view_state *s = &view->state.log;
3960 if (s->first_displayed_entry == NULL)
3961 return;
3962 if (s->selected_entry->idx == 0)
3963 view->count = 0;
3965 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3966 || home)
3967 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3969 if (!page && !home && s->selected > 0)
3970 --s->selected;
3971 else
3972 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3974 select_commit(s);
3975 return;
3978 static const struct got_error *
3979 log_move_cursor_down(struct tog_view *view, int page)
3981 struct tog_log_view_state *s = &view->state.log;
3982 const struct got_error *err = NULL;
3983 int eos = view->nlines - 2;
3985 if (s->first_displayed_entry == NULL)
3986 return NULL;
3988 if (s->thread_args.log_complete &&
3989 s->selected_entry->idx >= s->commits->ncommits - 1)
3990 return NULL;
3992 if (view_is_hsplit_top(view))
3993 --eos; /* border consumes the last line */
3995 if (!page) {
3996 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3997 ++s->selected;
3998 else
3999 err = log_scroll_down(view, 1);
4000 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
4001 struct commit_queue_entry *entry;
4002 int n;
4004 s->selected = 0;
4005 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
4006 s->last_displayed_entry = entry;
4007 for (n = 0; n <= eos; n++) {
4008 if (entry == NULL)
4009 break;
4010 s->first_displayed_entry = entry;
4011 entry = TAILQ_PREV(entry, commit_queue_head, entry);
4013 if (n > 0)
4014 s->selected = n - 1;
4015 } else {
4016 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
4017 s->thread_args.log_complete)
4018 s->selected += MIN(page,
4019 s->commits->ncommits - s->selected_entry->idx - 1);
4020 else
4021 err = log_scroll_down(view, page);
4023 if (err)
4024 return err;
4027 * We might necessarily overshoot in horizontal
4028 * splits; if so, select the last displayed commit.
4030 if (s->first_displayed_entry && s->last_displayed_entry) {
4031 s->selected = MIN(s->selected,
4032 s->last_displayed_entry->idx -
4033 s->first_displayed_entry->idx);
4036 select_commit(s);
4038 if (s->thread_args.log_complete &&
4039 s->selected_entry->idx == s->commits->ncommits - 1)
4040 view->count = 0;
4042 return NULL;
4045 static void
4046 view_get_split(struct tog_view *view, int *y, int *x)
4048 *x = 0;
4049 *y = 0;
4051 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
4052 if (view->child && view->child->resized_y)
4053 *y = view->child->resized_y;
4054 else if (view->resized_y)
4055 *y = view->resized_y;
4056 else
4057 *y = view_split_begin_y(view->lines);
4058 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
4059 if (view->child && view->child->resized_x)
4060 *x = view->child->resized_x;
4061 else if (view->resized_x)
4062 *x = view->resized_x;
4063 else
4064 *x = view_split_begin_x(view->begin_x);
4068 /* Split view horizontally at y and offset view->state->selected line. */
4069 static const struct got_error *
4070 view_init_hsplit(struct tog_view *view, int y)
4072 const struct got_error *err = NULL;
4074 view->nlines = y;
4075 view->ncols = COLS;
4076 err = view_resize(view);
4077 if (err)
4078 return err;
4080 err = offset_selection_down(view);
4082 return err;
4085 static const struct got_error *
4086 log_goto_line(struct tog_view *view, int nlines)
4088 const struct got_error *err = NULL;
4089 struct tog_log_view_state *s = &view->state.log;
4090 int g, idx = s->selected_entry->idx;
4092 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
4093 return NULL;
4095 g = view->gline;
4096 view->gline = 0;
4098 if (g >= s->first_displayed_entry->idx + 1 &&
4099 g <= s->last_displayed_entry->idx + 1 &&
4100 g - s->first_displayed_entry->idx - 1 < nlines) {
4101 s->selected = g - s->first_displayed_entry->idx - 1;
4102 select_commit(s);
4103 return NULL;
4106 if (idx + 1 < g) {
4107 err = log_move_cursor_down(view, g - idx - 1);
4108 if (!err && g > s->selected_entry->idx + 1)
4109 err = log_move_cursor_down(view,
4110 g - s->first_displayed_entry->idx - 1);
4111 if (err)
4112 return err;
4113 } else if (idx + 1 > g)
4114 log_move_cursor_up(view, idx - g + 1, 0);
4116 if (g < nlines && s->first_displayed_entry->idx == 0)
4117 s->selected = g - 1;
4119 select_commit(s);
4120 return NULL;
4124 static void
4125 horizontal_scroll_input(struct tog_view *view, int ch)
4128 switch (ch) {
4129 case KEY_LEFT:
4130 case 'h':
4131 view->x -= MIN(view->x, 2);
4132 if (view->x <= 0)
4133 view->count = 0;
4134 break;
4135 case KEY_RIGHT:
4136 case 'l':
4137 if (view->x + view->ncols / 2 < view->maxx)
4138 view->x += 2;
4139 else
4140 view->count = 0;
4141 break;
4142 case '0':
4143 view->x = 0;
4144 break;
4145 case '$':
4146 view->x = MAX(view->maxx - view->ncols / 2, 0);
4147 view->count = 0;
4148 break;
4149 default:
4150 break;
4154 static const struct got_error *
4155 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4157 const struct got_error *err = NULL;
4158 struct tog_log_view_state *s = &view->state.log;
4159 int eos, nscroll;
4161 if (s->thread_args.load_all) {
4162 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4163 s->thread_args.load_all = 0;
4164 else if (s->thread_args.log_complete) {
4165 err = log_move_cursor_down(view, s->commits->ncommits);
4166 s->thread_args.load_all = 0;
4168 if (err)
4169 return err;
4172 eos = nscroll = view->nlines - 1;
4173 if (view_is_hsplit_top(view))
4174 --eos; /* border */
4176 if (view->gline)
4177 return log_goto_line(view, eos);
4179 switch (ch) {
4180 case '&':
4181 err = limit_log_view(view);
4182 break;
4183 case 'q':
4184 s->quit = 1;
4185 break;
4186 case '0':
4187 case '$':
4188 case KEY_RIGHT:
4189 case 'l':
4190 case KEY_LEFT:
4191 case 'h':
4192 horizontal_scroll_input(view, ch);
4193 break;
4194 case 'k':
4195 case KEY_UP:
4196 case '<':
4197 case ',':
4198 case CTRL('p'):
4199 log_move_cursor_up(view, 0, 0);
4200 break;
4201 case 'g':
4202 case '=':
4203 case KEY_HOME:
4204 log_move_cursor_up(view, 0, 1);
4205 view->count = 0;
4206 break;
4207 case CTRL('u'):
4208 case 'u':
4209 nscroll /= 2;
4210 /* FALL THROUGH */
4211 case KEY_PPAGE:
4212 case CTRL('b'):
4213 case 'b':
4214 log_move_cursor_up(view, nscroll, 0);
4215 break;
4216 case 'j':
4217 case KEY_DOWN:
4218 case '>':
4219 case '.':
4220 case CTRL('n'):
4221 err = log_move_cursor_down(view, 0);
4222 break;
4223 case '@':
4224 s->use_committer = !s->use_committer;
4225 view->action = s->use_committer ?
4226 "show committer" : "show commit author";
4227 break;
4228 case 'G':
4229 case '*':
4230 case KEY_END: {
4231 /* We don't know yet how many commits, so we're forced to
4232 * traverse them all. */
4233 view->count = 0;
4234 s->thread_args.load_all = 1;
4235 if (!s->thread_args.log_complete)
4236 return trigger_log_thread(view, 0);
4237 err = log_move_cursor_down(view, s->commits->ncommits);
4238 s->thread_args.load_all = 0;
4239 break;
4241 case CTRL('d'):
4242 case 'd':
4243 nscroll /= 2;
4244 /* FALL THROUGH */
4245 case KEY_NPAGE:
4246 case CTRL('f'):
4247 case 'f':
4248 case ' ':
4249 err = log_move_cursor_down(view, nscroll);
4250 break;
4251 case KEY_RESIZE:
4252 if (s->selected > view->nlines - 2)
4253 s->selected = view->nlines - 2;
4254 if (s->selected > s->commits->ncommits - 1)
4255 s->selected = s->commits->ncommits - 1;
4256 select_commit(s);
4257 if (s->commits->ncommits < view->nlines - 1 &&
4258 !s->thread_args.log_complete) {
4259 s->thread_args.commits_needed += (view->nlines - 1) -
4260 s->commits->ncommits;
4261 err = trigger_log_thread(view, 1);
4263 break;
4264 case KEY_ENTER:
4265 case '\r':
4266 view->count = 0;
4267 if (s->selected_entry == NULL)
4268 break;
4269 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4270 break;
4271 case 'T':
4272 view->count = 0;
4273 if (s->selected_entry == NULL)
4274 break;
4275 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4276 break;
4277 case KEY_BACKSPACE:
4278 case CTRL('l'):
4279 case 'B':
4280 view->count = 0;
4281 if (ch == KEY_BACKSPACE &&
4282 got_path_is_root_dir(s->in_repo_path))
4283 break;
4284 err = stop_log_thread(s);
4285 if (err)
4286 return err;
4287 if (ch == KEY_BACKSPACE) {
4288 char *parent_path;
4289 err = got_path_dirname(&parent_path, s->in_repo_path);
4290 if (err)
4291 return err;
4292 free(s->in_repo_path);
4293 s->in_repo_path = parent_path;
4294 s->thread_args.in_repo_path = s->in_repo_path;
4295 } else if (ch == CTRL('l')) {
4296 struct got_object_id *start_id;
4297 err = got_repo_match_object_id(&start_id, NULL,
4298 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4299 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4300 if (err) {
4301 if (s->head_ref_name == NULL ||
4302 err->code != GOT_ERR_NOT_REF)
4303 return err;
4304 /* Try to cope with deleted references. */
4305 free(s->head_ref_name);
4306 s->head_ref_name = NULL;
4307 err = got_repo_match_object_id(&start_id,
4308 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4309 &tog_refs, s->repo);
4310 if (err)
4311 return err;
4313 free(s->start_id);
4314 s->start_id = start_id;
4315 s->thread_args.start_id = s->start_id;
4316 } else /* 'B' */
4317 s->log_branches = !s->log_branches;
4319 if (s->thread_args.pack_fds == NULL) {
4320 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4321 if (err)
4322 return err;
4324 err = got_repo_open(&s->thread_args.repo,
4325 got_repo_get_path(s->repo), NULL,
4326 s->thread_args.pack_fds);
4327 if (err)
4328 return err;
4329 tog_free_refs();
4330 err = tog_load_refs(s->repo, 0);
4331 if (err)
4332 return err;
4333 err = got_commit_graph_open(&s->thread_args.graph,
4334 s->in_repo_path, !s->log_branches);
4335 if (err)
4336 return err;
4337 err = got_commit_graph_bfsort(s->thread_args.graph,
4338 s->start_id, s->repo, NULL, NULL);
4339 if (err)
4340 return err;
4341 free_commits(&s->real_commits);
4342 free_commits(&s->limit_commits);
4343 s->first_displayed_entry = NULL;
4344 s->last_displayed_entry = NULL;
4345 s->selected_entry = NULL;
4346 s->selected = 0;
4347 s->thread_args.log_complete = 0;
4348 s->quit = 0;
4349 s->thread_args.commits_needed = view->lines;
4350 s->matched_entry = NULL;
4351 s->search_entry = NULL;
4352 view->offset = 0;
4353 break;
4354 case 'R':
4355 view->count = 0;
4356 err = view_request_new(new_view, view, TOG_VIEW_REF);
4357 break;
4358 default:
4359 view->count = 0;
4360 break;
4363 return err;
4366 static const struct got_error *
4367 apply_unveil(const char *repo_path, const char *worktree_path)
4369 const struct got_error *error;
4371 #ifdef PROFILE
4372 if (unveil("gmon.out", "rwc") != 0)
4373 return got_error_from_errno2("unveil", "gmon.out");
4374 #endif
4375 if (repo_path && unveil(repo_path, "r") != 0)
4376 return got_error_from_errno2("unveil", repo_path);
4378 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4379 return got_error_from_errno2("unveil", worktree_path);
4381 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4382 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4384 error = got_privsep_unveil_exec_helpers();
4385 if (error != NULL)
4386 return error;
4388 if (unveil(NULL, NULL) != 0)
4389 return got_error_from_errno("unveil");
4391 return NULL;
4394 static const struct got_error *
4395 init_mock_term(const char *test_script_path)
4397 const struct got_error *err = NULL;
4398 const char *screen_dump_path;
4399 int in;
4401 if (test_script_path == NULL || *test_script_path == '\0')
4402 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4404 tog_io.f = fopen(test_script_path, "re");
4405 if (tog_io.f == NULL) {
4406 err = got_error_from_errno_fmt("fopen: %s",
4407 test_script_path);
4408 goto done;
4411 /* test mode, we don't want any output */
4412 tog_io.cout = fopen("/dev/null", "w+");
4413 if (tog_io.cout == NULL) {
4414 err = got_error_from_errno2("fopen", "/dev/null");
4415 goto done;
4418 in = dup(fileno(tog_io.cout));
4419 if (in == -1) {
4420 err = got_error_from_errno("dup");
4421 goto done;
4423 tog_io.cin = fdopen(in, "r");
4424 if (tog_io.cin == NULL) {
4425 err = got_error_from_errno("fdopen");
4426 close(in);
4427 goto done;
4430 screen_dump_path = getenv("TOG_SCR_DUMP");
4431 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4432 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4433 tog_io.sdump = fopen(screen_dump_path, "we");
4434 if (tog_io.sdump == NULL) {
4435 err = got_error_from_errno2("fopen", screen_dump_path);
4436 goto done;
4439 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4440 err = got_error_from_errno("fseeko");
4441 goto done;
4444 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4445 err = got_error_msg(GOT_ERR_IO,
4446 "newterm: failed to initialise curses");
4448 using_mock_io = 1;
4450 done:
4451 if (err)
4452 tog_io_close();
4453 return err;
4456 static void
4457 init_curses(void)
4459 if (using_mock_io) /* In test mode we use a fake terminal */
4460 return;
4462 initscr();
4464 cbreak();
4465 halfdelay(1); /* Fast refresh while initial view is loading. */
4466 noecho();
4467 nonl();
4468 intrflush(stdscr, FALSE);
4469 keypad(stdscr, TRUE);
4470 curs_set(0);
4471 if (getenv("TOG_COLORS") != NULL) {
4472 start_color();
4473 use_default_colors();
4476 return;
4479 static const struct got_error *
4480 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4482 tog_base_commit.id = got_object_id_dup(
4483 got_worktree_get_base_commit_id(worktree));
4484 if (tog_base_commit.id == NULL)
4485 return got_error_from_errno( "got_object_id_dup");
4487 return NULL;
4490 static const struct got_error *
4491 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4492 struct got_repository *repo, struct got_worktree *worktree)
4494 const struct got_error *err = NULL;
4496 if (argc == 0) {
4497 *in_repo_path = strdup("/");
4498 if (*in_repo_path == NULL)
4499 return got_error_from_errno("strdup");
4500 return NULL;
4503 if (worktree) {
4504 const char *prefix = got_worktree_get_path_prefix(worktree);
4505 char *p;
4507 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4508 if (err)
4509 return err;
4510 if (asprintf(in_repo_path, "%s%s%s", prefix,
4511 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4512 p) == -1) {
4513 err = got_error_from_errno("asprintf");
4514 *in_repo_path = NULL;
4516 free(p);
4517 } else
4518 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4520 return err;
4523 static const struct got_error *
4524 cmd_log(int argc, char *argv[])
4526 const struct got_error *error;
4527 struct got_repository *repo = NULL;
4528 struct got_worktree *worktree = NULL;
4529 struct got_object_id *start_id = NULL;
4530 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4531 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4532 struct got_reference *ref = NULL;
4533 const char *head_ref_name = NULL;
4534 int ch, log_branches = 0;
4535 struct tog_view *view;
4536 int *pack_fds = NULL;
4538 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4539 switch (ch) {
4540 case 'b':
4541 log_branches = 1;
4542 break;
4543 case 'c':
4544 start_commit = optarg;
4545 break;
4546 case 'r':
4547 repo_path = realpath(optarg, NULL);
4548 if (repo_path == NULL)
4549 return got_error_from_errno2("realpath",
4550 optarg);
4551 break;
4552 default:
4553 usage_log();
4554 /* NOTREACHED */
4558 argc -= optind;
4559 argv += optind;
4561 if (argc > 1)
4562 usage_log();
4564 error = got_repo_pack_fds_open(&pack_fds);
4565 if (error != NULL)
4566 goto done;
4568 if (repo_path == NULL) {
4569 cwd = getcwd(NULL, 0);
4570 if (cwd == NULL) {
4571 error = got_error_from_errno("getcwd");
4572 goto done;
4574 error = got_worktree_open(&worktree, cwd, NULL);
4575 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4576 goto done;
4577 if (worktree)
4578 repo_path =
4579 strdup(got_worktree_get_repo_path(worktree));
4580 else
4581 repo_path = strdup(cwd);
4582 if (repo_path == NULL) {
4583 error = got_error_from_errno("strdup");
4584 goto done;
4588 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4589 if (error != NULL)
4590 goto done;
4592 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4593 repo, worktree);
4594 if (error)
4595 goto done;
4597 init_curses();
4599 error = apply_unveil(got_repo_get_path(repo),
4600 worktree ? got_worktree_get_root_path(worktree) : NULL);
4601 if (error)
4602 goto done;
4604 /* already loaded by tog_log_with_path()? */
4605 if (TAILQ_EMPTY(&tog_refs)) {
4606 error = tog_load_refs(repo, 0);
4607 if (error)
4608 goto done;
4611 if (start_commit == NULL) {
4612 error = got_repo_match_object_id(&start_id, &label,
4613 worktree ? got_worktree_get_head_ref_name(worktree) :
4614 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4615 if (error)
4616 goto done;
4617 head_ref_name = label;
4618 } else {
4619 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4620 repo, worktree);
4621 if (error != NULL)
4622 goto done;
4623 if (keyword_idstr != NULL)
4624 start_commit = keyword_idstr;
4626 error = got_ref_open(&ref, repo, start_commit, 0);
4627 if (error == NULL)
4628 head_ref_name = got_ref_get_name(ref);
4629 else if (error->code != GOT_ERR_NOT_REF)
4630 goto done;
4631 error = got_repo_match_object_id(&start_id, NULL,
4632 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4633 if (error)
4634 goto done;
4637 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4638 if (view == NULL) {
4639 error = got_error_from_errno("view_open");
4640 goto done;
4643 if (worktree) {
4644 error = set_tog_base_commit(repo, worktree);
4645 if (error != NULL)
4646 goto done;
4649 error = open_log_view(view, start_id, repo, head_ref_name,
4650 in_repo_path, log_branches, worktree);
4651 if (error)
4652 goto done;
4654 if (worktree) {
4655 /* The work tree will be closed by the log thread. */
4656 worktree = NULL;
4659 error = view_loop(view);
4661 done:
4662 free(tog_base_commit.id);
4663 free(keyword_idstr);
4664 free(in_repo_path);
4665 free(repo_path);
4666 free(cwd);
4667 free(start_id);
4668 free(label);
4669 if (ref)
4670 got_ref_close(ref);
4671 if (repo) {
4672 const struct got_error *close_err = got_repo_close(repo);
4673 if (error == NULL)
4674 error = close_err;
4676 if (worktree)
4677 got_worktree_close(worktree);
4678 if (pack_fds) {
4679 const struct got_error *pack_err =
4680 got_repo_pack_fds_close(pack_fds);
4681 if (error == NULL)
4682 error = pack_err;
4684 tog_free_refs();
4685 return error;
4688 __dead static void
4689 usage_diff(void)
4691 endwin();
4692 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4693 "object1 object2\n", getprogname());
4694 exit(1);
4697 static int
4698 match_line(const char *line, regex_t *regex, size_t nmatch,
4699 regmatch_t *regmatch)
4701 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4704 static struct tog_color *
4705 match_color(struct tog_colors *colors, const char *line)
4707 struct tog_color *tc = NULL;
4709 STAILQ_FOREACH(tc, colors, entry) {
4710 if (match_line(line, &tc->regex, 0, NULL))
4711 return tc;
4714 return NULL;
4717 static const struct got_error *
4718 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4719 WINDOW *window, int skipcol, regmatch_t *regmatch)
4721 const struct got_error *err = NULL;
4722 char *exstr = NULL;
4723 wchar_t *wline = NULL;
4724 int rme, rms, n, width, scrollx;
4725 int width0 = 0, width1 = 0, width2 = 0;
4726 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4728 *wtotal = 0;
4730 rms = regmatch->rm_so;
4731 rme = regmatch->rm_eo;
4733 err = expand_tab(&exstr, line);
4734 if (err)
4735 return err;
4737 /* Split the line into 3 segments, according to match offsets. */
4738 seg0 = strndup(exstr, rms);
4739 if (seg0 == NULL) {
4740 err = got_error_from_errno("strndup");
4741 goto done;
4743 seg1 = strndup(exstr + rms, rme - rms);
4744 if (seg1 == NULL) {
4745 err = got_error_from_errno("strndup");
4746 goto done;
4748 seg2 = strdup(exstr + rme);
4749 if (seg2 == NULL) {
4750 err = got_error_from_errno("strndup");
4751 goto done;
4754 /* draw up to matched token if we haven't scrolled past it */
4755 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4756 col_tab_align, 1);
4757 if (err)
4758 goto done;
4759 n = MAX(width0 - skipcol, 0);
4760 if (n) {
4761 free(wline);
4762 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4763 wlimit, col_tab_align, 1);
4764 if (err)
4765 goto done;
4766 waddwstr(window, &wline[scrollx]);
4767 wlimit -= width;
4768 *wtotal += width;
4771 if (wlimit > 0) {
4772 int i = 0, w = 0;
4773 size_t wlen;
4775 free(wline);
4776 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4777 col_tab_align, 1);
4778 if (err)
4779 goto done;
4780 wlen = wcslen(wline);
4781 while (i < wlen) {
4782 width = wcwidth(wline[i]);
4783 if (width == -1) {
4784 /* should not happen, tabs are expanded */
4785 err = got_error(GOT_ERR_RANGE);
4786 goto done;
4788 if (width0 + w + width > skipcol)
4789 break;
4790 w += width;
4791 i++;
4793 /* draw (visible part of) matched token (if scrolled into it) */
4794 if (width1 - w > 0) {
4795 wattron(window, A_STANDOUT);
4796 waddwstr(window, &wline[i]);
4797 wattroff(window, A_STANDOUT);
4798 wlimit -= (width1 - w);
4799 *wtotal += (width1 - w);
4803 if (wlimit > 0) { /* draw rest of line */
4804 free(wline);
4805 if (skipcol > width0 + width1) {
4806 err = format_line(&wline, &width2, &scrollx, seg2,
4807 skipcol - (width0 + width1), wlimit,
4808 col_tab_align, 1);
4809 if (err)
4810 goto done;
4811 waddwstr(window, &wline[scrollx]);
4812 } else {
4813 err = format_line(&wline, &width2, NULL, seg2, 0,
4814 wlimit, col_tab_align, 1);
4815 if (err)
4816 goto done;
4817 waddwstr(window, wline);
4819 *wtotal += width2;
4821 done:
4822 free(wline);
4823 free(exstr);
4824 free(seg0);
4825 free(seg1);
4826 free(seg2);
4827 return err;
4830 static int
4831 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4833 FILE *f = NULL;
4834 int *eof, *first, *selected;
4836 if (view->type == TOG_VIEW_DIFF) {
4837 struct tog_diff_view_state *s = &view->state.diff;
4839 first = &s->first_displayed_line;
4840 selected = first;
4841 eof = &s->eof;
4842 f = s->f;
4843 } else if (view->type == TOG_VIEW_HELP) {
4844 struct tog_help_view_state *s = &view->state.help;
4846 first = &s->first_displayed_line;
4847 selected = first;
4848 eof = &s->eof;
4849 f = s->f;
4850 } else if (view->type == TOG_VIEW_BLAME) {
4851 struct tog_blame_view_state *s = &view->state.blame;
4853 first = &s->first_displayed_line;
4854 selected = &s->selected_line;
4855 eof = &s->eof;
4856 f = s->blame.f;
4857 } else
4858 return 0;
4860 /* Center gline in the middle of the page like vi(1). */
4861 if (*lineno < view->gline - (view->nlines - 3) / 2)
4862 return 0;
4863 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4864 rewind(f);
4865 *eof = 0;
4866 *first = 1;
4867 *lineno = 0;
4868 *nprinted = 0;
4869 return 0;
4872 *selected = view->gline <= (view->nlines - 3) / 2 ?
4873 view->gline : (view->nlines - 3) / 2 + 1;
4874 view->gline = 0;
4876 return 1;
4879 static const struct got_error *
4880 draw_file(struct tog_view *view, const char *header)
4882 struct tog_diff_view_state *s = &view->state.diff;
4883 regmatch_t *regmatch = &view->regmatch;
4884 const struct got_error *err;
4885 int nprinted = 0;
4886 char *line;
4887 size_t linesize = 0;
4888 ssize_t linelen;
4889 wchar_t *wline;
4890 int width;
4891 int max_lines = view->nlines;
4892 int nlines = s->nlines;
4893 off_t line_offset;
4895 s->lineno = s->first_displayed_line - 1;
4896 line_offset = s->lines[s->first_displayed_line - 1].offset;
4897 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4898 return got_error_from_errno("fseek");
4900 werase(view->window);
4902 if (view->gline > s->nlines - 1)
4903 view->gline = s->nlines - 1;
4905 if (header) {
4906 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4907 1 : view->gline - (view->nlines - 3) / 2 :
4908 s->lineno + s->selected_line;
4910 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4911 return got_error_from_errno("asprintf");
4912 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4913 0, 0);
4914 free(line);
4915 if (err)
4916 return err;
4918 if (view_needs_focus_indication(view))
4919 wstandout(view->window);
4920 waddwstr(view->window, wline);
4921 free(wline);
4922 wline = NULL;
4923 while (width++ < view->ncols)
4924 waddch(view->window, ' ');
4925 if (view_needs_focus_indication(view))
4926 wstandend(view->window);
4928 if (max_lines <= 1)
4929 return NULL;
4930 max_lines--;
4933 s->eof = 0;
4934 view->maxx = 0;
4935 line = NULL;
4936 while (max_lines > 0 && nprinted < max_lines) {
4937 enum got_diff_line_type linetype;
4938 attr_t attr = 0;
4940 linelen = getline(&line, &linesize, s->f);
4941 if (linelen == -1) {
4942 if (feof(s->f)) {
4943 s->eof = 1;
4944 break;
4946 free(line);
4947 return got_ferror(s->f, GOT_ERR_IO);
4950 if (++s->lineno < s->first_displayed_line)
4951 continue;
4952 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4953 continue;
4954 if (s->lineno == view->hiline)
4955 attr = A_STANDOUT;
4957 /* Set view->maxx based on full line length. */
4958 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4959 view->x ? 1 : 0);
4960 if (err) {
4961 free(line);
4962 return err;
4964 view->maxx = MAX(view->maxx, width);
4965 free(wline);
4966 wline = NULL;
4968 linetype = s->lines[s->lineno].type;
4969 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4970 linetype < GOT_DIFF_LINE_CONTEXT)
4971 attr |= COLOR_PAIR(linetype);
4972 if (attr)
4973 wattron(view->window, attr);
4974 if (s->first_displayed_line + nprinted == s->matched_line &&
4975 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4976 err = add_matched_line(&width, line, view->ncols, 0,
4977 view->window, view->x, regmatch);
4978 if (err) {
4979 free(line);
4980 return err;
4982 } else {
4983 int skip;
4984 err = format_line(&wline, &width, &skip, line,
4985 view->x, view->ncols, 0, view->x ? 1 : 0);
4986 if (err) {
4987 free(line);
4988 return err;
4990 waddwstr(view->window, &wline[skip]);
4991 free(wline);
4992 wline = NULL;
4994 if (s->lineno == view->hiline) {
4995 /* highlight full gline length */
4996 while (width++ < view->ncols)
4997 waddch(view->window, ' ');
4998 } else {
4999 if (width <= view->ncols - 1)
5000 waddch(view->window, '\n');
5002 if (attr)
5003 wattroff(view->window, attr);
5004 if (++nprinted == 1)
5005 s->first_displayed_line = s->lineno;
5007 free(line);
5008 if (nprinted >= 1)
5009 s->last_displayed_line = s->first_displayed_line +
5010 (nprinted - 1);
5011 else
5012 s->last_displayed_line = s->first_displayed_line;
5014 view_border(view);
5016 if (s->eof) {
5017 while (nprinted < view->nlines) {
5018 waddch(view->window, '\n');
5019 nprinted++;
5022 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
5023 view->ncols, 0, 0);
5024 if (err) {
5025 return err;
5028 wstandout(view->window);
5029 waddwstr(view->window, wline);
5030 free(wline);
5031 wline = NULL;
5032 wstandend(view->window);
5035 return NULL;
5038 static char *
5039 get_datestr(time_t *time, char *datebuf)
5041 struct tm mytm, *tm;
5042 char *p, *s;
5044 tm = gmtime_r(time, &mytm);
5045 if (tm == NULL)
5046 return NULL;
5047 s = asctime_r(tm, datebuf);
5048 if (s == NULL)
5049 return NULL;
5050 p = strchr(s, '\n');
5051 if (p)
5052 *p = '\0';
5053 return s;
5056 static const struct got_error *
5057 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
5058 off_t off, uint8_t type)
5060 struct got_diff_line *p;
5062 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
5063 if (p == NULL)
5064 return got_error_from_errno("reallocarray");
5065 *lines = p;
5066 (*lines)[*nlines].offset = off;
5067 (*lines)[*nlines].type = type;
5068 (*nlines)++;
5070 return NULL;
5073 static const struct got_error *
5074 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
5075 struct got_diff_line *s_lines, size_t s_nlines)
5077 struct got_diff_line *p;
5078 char buf[BUFSIZ];
5079 size_t i, r;
5081 if (fseeko(src, 0L, SEEK_SET) == -1)
5082 return got_error_from_errno("fseeko");
5084 for (;;) {
5085 r = fread(buf, 1, sizeof(buf), src);
5086 if (r == 0) {
5087 if (ferror(src))
5088 return got_error_from_errno("fread");
5089 if (feof(src))
5090 break;
5092 if (fwrite(buf, 1, r, dst) != r)
5093 return got_ferror(dst, GOT_ERR_IO);
5096 if (s_nlines == 0 && *d_nlines == 0)
5097 return NULL;
5100 * If commit info was in dst, increment line offsets
5101 * of the appended diff content, but skip s_lines[0]
5102 * because offset zero is already in *d_lines.
5104 if (*d_nlines > 0) {
5105 for (i = 1; i < s_nlines; ++i)
5106 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5108 if (s_nlines > 0) {
5109 --s_nlines;
5110 ++s_lines;
5114 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5115 if (p == NULL) {
5116 /* d_lines is freed in close_diff_view() */
5117 return got_error_from_errno("reallocarray");
5120 *d_lines = p;
5122 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5123 *d_nlines += s_nlines;
5125 return NULL;
5128 static const struct got_error *
5129 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5130 struct got_object_id *commit_id, struct got_reflist_head *refs,
5131 struct got_repository *repo, int ignore_ws, int force_text_diff,
5132 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5134 const struct got_error *err = NULL;
5135 char datebuf[26], *datestr;
5136 struct got_commit_object *commit;
5137 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5138 time_t committer_time;
5139 const char *author, *committer;
5140 char *refs_str = NULL;
5141 struct got_pathlist_entry *pe;
5142 off_t outoff = 0;
5143 int n;
5145 err = build_refs_str(&refs_str, refs, commit_id, repo);
5146 if (err)
5147 return err;
5149 err = got_object_open_as_commit(&commit, repo, commit_id);
5150 if (err)
5151 return err;
5153 err = got_object_id_str(&id_str, commit_id);
5154 if (err) {
5155 err = got_error_from_errno("got_object_id_str");
5156 goto done;
5159 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5160 if (err)
5161 goto done;
5163 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5164 refs_str ? refs_str : "", refs_str ? ")" : "");
5165 if (n < 0) {
5166 err = got_error_from_errno("fprintf");
5167 goto done;
5169 outoff += n;
5170 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5171 if (err)
5172 goto done;
5174 n = fprintf(outfile, "from: %s\n",
5175 got_object_commit_get_author(commit));
5176 if (n < 0) {
5177 err = got_error_from_errno("fprintf");
5178 goto done;
5180 outoff += n;
5181 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5182 if (err)
5183 goto done;
5185 author = got_object_commit_get_author(commit);
5186 committer = got_object_commit_get_committer(commit);
5187 if (strcmp(author, committer) != 0) {
5188 n = fprintf(outfile, "via: %s\n", committer);
5189 if (n < 0) {
5190 err = got_error_from_errno("fprintf");
5191 goto done;
5193 outoff += n;
5194 err = add_line_metadata(lines, nlines, outoff,
5195 GOT_DIFF_LINE_AUTHOR);
5196 if (err)
5197 goto done;
5199 committer_time = got_object_commit_get_committer_time(commit);
5200 datestr = get_datestr(&committer_time, datebuf);
5201 if (datestr) {
5202 n = fprintf(outfile, "date: %s UTC\n", datestr);
5203 if (n < 0) {
5204 err = got_error_from_errno("fprintf");
5205 goto done;
5207 outoff += n;
5208 err = add_line_metadata(lines, nlines, outoff,
5209 GOT_DIFF_LINE_DATE);
5210 if (err)
5211 goto done;
5213 if (got_object_commit_get_nparents(commit) > 1) {
5214 const struct got_object_id_queue *parent_ids;
5215 struct got_object_qid *qid;
5216 int pn = 1;
5217 parent_ids = got_object_commit_get_parent_ids(commit);
5218 STAILQ_FOREACH(qid, parent_ids, entry) {
5219 err = got_object_id_str(&id_str, &qid->id);
5220 if (err)
5221 goto done;
5222 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5223 if (n < 0) {
5224 err = got_error_from_errno("fprintf");
5225 goto done;
5227 outoff += n;
5228 err = add_line_metadata(lines, nlines, outoff,
5229 GOT_DIFF_LINE_META);
5230 if (err)
5231 goto done;
5232 free(id_str);
5233 id_str = NULL;
5237 err = got_object_commit_get_logmsg(&logmsg, commit);
5238 if (err)
5239 goto done;
5240 s = logmsg;
5241 while ((line = strsep(&s, "\n")) != NULL) {
5242 n = fprintf(outfile, "%s\n", line);
5243 if (n < 0) {
5244 err = got_error_from_errno("fprintf");
5245 goto done;
5247 outoff += n;
5248 err = add_line_metadata(lines, nlines, outoff,
5249 GOT_DIFF_LINE_LOGMSG);
5250 if (err)
5251 goto done;
5254 TAILQ_FOREACH(pe, dsa->paths, entry) {
5255 struct got_diff_changed_path *cp = pe->data;
5256 int pad = dsa->max_path_len - pe->path_len + 1;
5258 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5259 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5260 dsa->rm_cols + 1, cp->rm);
5261 if (n < 0) {
5262 err = got_error_from_errno("fprintf");
5263 goto done;
5265 outoff += n;
5266 err = add_line_metadata(lines, nlines, outoff,
5267 GOT_DIFF_LINE_CHANGES);
5268 if (err)
5269 goto done;
5272 fputc('\n', outfile);
5273 outoff++;
5274 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5275 if (err)
5276 goto done;
5278 n = fprintf(outfile,
5279 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5280 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5281 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5282 if (n < 0) {
5283 err = got_error_from_errno("fprintf");
5284 goto done;
5286 outoff += n;
5287 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5288 if (err)
5289 goto done;
5291 fputc('\n', outfile);
5292 outoff++;
5293 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5294 done:
5295 free(id_str);
5296 free(logmsg);
5297 free(refs_str);
5298 got_object_commit_close(commit);
5299 if (err) {
5300 free(*lines);
5301 *lines = NULL;
5302 *nlines = 0;
5304 return err;
5307 static const struct got_error *
5308 create_diff(struct tog_diff_view_state *s)
5310 const struct got_error *err = NULL;
5311 FILE *tmp_diff_file = NULL;
5312 int obj_type;
5313 struct got_diff_line *lines = NULL;
5314 struct got_pathlist_head changed_paths;
5315 struct got_commit_object *commit2 = NULL;
5317 TAILQ_INIT(&changed_paths);
5319 free(s->lines);
5320 s->lines = malloc(sizeof(*s->lines));
5321 if (s->lines == NULL)
5322 return got_error_from_errno("malloc");
5323 s->nlines = 0;
5325 if (s->f && fclose(s->f) == EOF) {
5326 s->f = NULL;
5327 return got_error_from_errno("fclose");
5330 s->f = got_opentemp();
5331 if (s->f == NULL)
5332 return got_error_from_errno("got_opentemp");
5334 tmp_diff_file = got_opentemp();
5335 if (tmp_diff_file == NULL)
5336 return got_error_from_errno("got_opentemp");
5338 if (s->id1)
5339 err = got_object_get_type(&obj_type, s->repo, s->id1);
5340 else
5341 err = got_object_get_type(&obj_type, s->repo, s->id2);
5342 if (err)
5343 goto done;
5345 switch (obj_type) {
5346 case GOT_OBJ_TYPE_BLOB:
5347 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5348 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5349 s->label1, s->label2, tog_diff_algo, s->diff_context,
5350 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5351 s->f);
5352 break;
5353 case GOT_OBJ_TYPE_TREE:
5354 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5355 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5356 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5357 s->force_text_diff, NULL, s->repo, s->f);
5358 break;
5359 case GOT_OBJ_TYPE_COMMIT: {
5360 const struct got_object_id_queue *parent_ids;
5361 struct got_object_qid *pid;
5362 struct got_reflist_head *refs;
5363 size_t nlines = 0;
5364 struct got_diffstat_cb_arg dsa = {
5365 0, 0, 0, 0, 0, 0,
5366 &changed_paths,
5367 s->ignore_whitespace,
5368 s->force_text_diff,
5369 tog_diff_algo
5372 lines = malloc(sizeof(*lines));
5373 if (lines == NULL) {
5374 err = got_error_from_errno("malloc");
5375 goto done;
5378 /* build diff first in tmp file then append to commit info */
5379 err = got_diff_objects_as_commits(&lines, &nlines,
5380 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5381 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5382 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5383 if (err)
5384 break;
5386 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5387 /* Show commit info if we're diffing to a parent/root commit. */
5388 if (s->id1 == NULL) {
5389 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5390 refs, s->repo, s->ignore_whitespace,
5391 s->force_text_diff, &dsa, s->f);
5392 if (err)
5393 goto done;
5394 } else {
5395 err = got_object_open_as_commit(&commit2, s->repo,
5396 s->id2);
5397 if (err)
5398 goto done;
5400 parent_ids = got_object_commit_get_parent_ids(commit2);
5401 STAILQ_FOREACH(pid, parent_ids, entry) {
5402 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5403 err = write_commit_info(&s->lines,
5404 &s->nlines, s->id2, refs, s->repo,
5405 s->ignore_whitespace,
5406 s->force_text_diff, &dsa, s->f);
5407 if (err)
5408 goto done;
5409 break;
5414 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5415 lines, nlines);
5416 break;
5418 default:
5419 err = got_error(GOT_ERR_OBJ_TYPE);
5420 break;
5422 done:
5423 free(lines);
5424 if (commit2 != NULL)
5425 got_object_commit_close(commit2);
5426 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5427 if (s->f && fflush(s->f) != 0 && err == NULL)
5428 err = got_error_from_errno("fflush");
5429 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5430 err = got_error_from_errno("fclose");
5431 return err;
5434 static void
5435 diff_view_indicate_progress(struct tog_view *view)
5437 mvwaddstr(view->window, 0, 0, "diffing...");
5438 update_panels();
5439 doupdate();
5442 static const struct got_error *
5443 search_start_diff_view(struct tog_view *view)
5445 struct tog_diff_view_state *s = &view->state.diff;
5447 s->matched_line = 0;
5448 return NULL;
5451 static void
5452 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5453 size_t *nlines, int **first, int **last, int **match, int **selected)
5455 struct tog_diff_view_state *s = &view->state.diff;
5457 *f = s->f;
5458 *nlines = s->nlines;
5459 *line_offsets = NULL;
5460 *match = &s->matched_line;
5461 *first = &s->first_displayed_line;
5462 *last = &s->last_displayed_line;
5463 *selected = &s->selected_line;
5466 static const struct got_error *
5467 search_next_view_match(struct tog_view *view)
5469 const struct got_error *err = NULL;
5470 FILE *f;
5471 int lineno;
5472 char *line = NULL;
5473 size_t linesize = 0;
5474 ssize_t linelen;
5475 off_t *line_offsets;
5476 size_t nlines = 0;
5477 int *first, *last, *match, *selected;
5479 if (!view->search_setup)
5480 return got_error_msg(GOT_ERR_NOT_IMPL,
5481 "view search not supported");
5482 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5483 &match, &selected);
5485 if (!view->searching) {
5486 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5487 return NULL;
5490 if (*match) {
5491 if (view->searching == TOG_SEARCH_FORWARD)
5492 lineno = *first + 1;
5493 else
5494 lineno = *first - 1;
5495 } else
5496 lineno = *first - 1 + *selected;
5498 while (1) {
5499 off_t offset;
5501 if (lineno <= 0 || lineno > nlines) {
5502 if (*match == 0) {
5503 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5504 break;
5507 if (view->searching == TOG_SEARCH_FORWARD)
5508 lineno = 1;
5509 else
5510 lineno = nlines;
5513 offset = view->type == TOG_VIEW_DIFF ?
5514 view->state.diff.lines[lineno - 1].offset :
5515 line_offsets[lineno - 1];
5516 if (fseeko(f, offset, SEEK_SET) != 0) {
5517 free(line);
5518 return got_error_from_errno("fseeko");
5520 linelen = getline(&line, &linesize, f);
5521 if (linelen != -1) {
5522 char *exstr;
5523 err = expand_tab(&exstr, line);
5524 if (err)
5525 break;
5526 if (match_line(exstr, &view->regex, 1,
5527 &view->regmatch)) {
5528 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5529 *match = lineno;
5530 free(exstr);
5531 break;
5533 free(exstr);
5535 if (view->searching == TOG_SEARCH_FORWARD)
5536 lineno++;
5537 else
5538 lineno--;
5540 free(line);
5542 if (*match) {
5543 *first = *match;
5544 *selected = 1;
5547 return err;
5550 static const struct got_error *
5551 close_diff_view(struct tog_view *view)
5553 const struct got_error *err = NULL;
5554 struct tog_diff_view_state *s = &view->state.diff;
5556 free(s->id1);
5557 s->id1 = NULL;
5558 free(s->id2);
5559 s->id2 = NULL;
5560 if (s->f && fclose(s->f) == EOF)
5561 err = got_error_from_errno("fclose");
5562 s->f = NULL;
5563 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5564 err = got_error_from_errno("fclose");
5565 s->f1 = NULL;
5566 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5567 err = got_error_from_errno("fclose");
5568 s->f2 = NULL;
5569 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5570 err = got_error_from_errno("close");
5571 s->fd1 = -1;
5572 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5573 err = got_error_from_errno("close");
5574 s->fd2 = -1;
5575 free(s->lines);
5576 s->lines = NULL;
5577 s->nlines = 0;
5578 return err;
5581 static const struct got_error *
5582 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5583 struct got_object_id *id2, const char *label1, const char *label2,
5584 int diff_context, int ignore_whitespace, int force_text_diff,
5585 struct tog_view *parent_view, struct got_repository *repo)
5587 const struct got_error *err;
5588 struct tog_diff_view_state *s = &view->state.diff;
5590 memset(s, 0, sizeof(*s));
5591 s->fd1 = -1;
5592 s->fd2 = -1;
5594 if (id1 != NULL && id2 != NULL) {
5595 int type1, type2;
5597 err = got_object_get_type(&type1, repo, id1);
5598 if (err)
5599 goto done;
5600 err = got_object_get_type(&type2, repo, id2);
5601 if (err)
5602 goto done;
5604 if (type1 != type2) {
5605 err = got_error(GOT_ERR_OBJ_TYPE);
5606 goto done;
5609 s->first_displayed_line = 1;
5610 s->last_displayed_line = view->nlines;
5611 s->selected_line = 1;
5612 s->repo = repo;
5613 s->label1 = label1;
5614 s->label2 = label2;
5616 if (id1) {
5617 s->id1 = got_object_id_dup(id1);
5618 if (s->id1 == NULL) {
5619 err = got_error_from_errno("got_object_id_dup");
5620 goto done;
5622 } else
5623 s->id1 = NULL;
5625 s->id2 = got_object_id_dup(id2);
5626 if (s->id2 == NULL) {
5627 err = got_error_from_errno("got_object_id_dup");
5628 goto done;
5631 s->f1 = got_opentemp();
5632 if (s->f1 == NULL) {
5633 err = got_error_from_errno("got_opentemp");
5634 goto done;
5637 s->f2 = got_opentemp();
5638 if (s->f2 == NULL) {
5639 err = got_error_from_errno("got_opentemp");
5640 goto done;
5643 s->fd1 = got_opentempfd();
5644 if (s->fd1 == -1) {
5645 err = got_error_from_errno("got_opentempfd");
5646 goto done;
5649 s->fd2 = got_opentempfd();
5650 if (s->fd2 == -1) {
5651 err = got_error_from_errno("got_opentempfd");
5652 goto done;
5655 s->diff_context = diff_context;
5656 s->ignore_whitespace = ignore_whitespace;
5657 s->force_text_diff = force_text_diff;
5658 s->parent_view = parent_view;
5659 s->repo = repo;
5661 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5662 int rc;
5664 rc = init_pair(GOT_DIFF_LINE_MINUS,
5665 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5666 if (rc != ERR)
5667 rc = init_pair(GOT_DIFF_LINE_PLUS,
5668 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5669 if (rc != ERR)
5670 rc = init_pair(GOT_DIFF_LINE_HUNK,
5671 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5672 if (rc != ERR)
5673 rc = init_pair(GOT_DIFF_LINE_META,
5674 get_color_value("TOG_COLOR_DIFF_META"), -1);
5675 if (rc != ERR)
5676 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5677 get_color_value("TOG_COLOR_DIFF_META"), -1);
5678 if (rc != ERR)
5679 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5680 get_color_value("TOG_COLOR_DIFF_META"), -1);
5681 if (rc != ERR)
5682 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5683 get_color_value("TOG_COLOR_DIFF_META"), -1);
5684 if (rc != ERR)
5685 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5686 get_color_value("TOG_COLOR_AUTHOR"), -1);
5687 if (rc != ERR)
5688 rc = init_pair(GOT_DIFF_LINE_DATE,
5689 get_color_value("TOG_COLOR_DATE"), -1);
5690 if (rc == ERR) {
5691 err = got_error(GOT_ERR_RANGE);
5692 goto done;
5696 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5697 view_is_splitscreen(view))
5698 show_log_view(parent_view); /* draw border */
5699 diff_view_indicate_progress(view);
5701 err = create_diff(s);
5703 view->show = show_diff_view;
5704 view->input = input_diff_view;
5705 view->reset = reset_diff_view;
5706 view->close = close_diff_view;
5707 view->search_start = search_start_diff_view;
5708 view->search_setup = search_setup_diff_view;
5709 view->search_next = search_next_view_match;
5710 done:
5711 if (err) {
5712 if (view->close == NULL)
5713 close_diff_view(view);
5714 view_close(view);
5716 return err;
5719 static const struct got_error *
5720 show_diff_view(struct tog_view *view)
5722 const struct got_error *err;
5723 struct tog_diff_view_state *s = &view->state.diff;
5724 char *id_str1 = NULL, *id_str2, *header;
5725 const char *label1, *label2;
5727 if (s->id1) {
5728 err = got_object_id_str(&id_str1, s->id1);
5729 if (err)
5730 return err;
5731 label1 = s->label1 ? s->label1 : id_str1;
5732 } else
5733 label1 = "/dev/null";
5735 err = got_object_id_str(&id_str2, s->id2);
5736 if (err)
5737 return err;
5738 label2 = s->label2 ? s->label2 : id_str2;
5740 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5741 err = got_error_from_errno("asprintf");
5742 free(id_str1);
5743 free(id_str2);
5744 return err;
5746 free(id_str1);
5747 free(id_str2);
5749 err = draw_file(view, header);
5750 free(header);
5751 return err;
5754 static const struct got_error *
5755 set_selected_commit(struct tog_diff_view_state *s,
5756 struct commit_queue_entry *entry)
5758 const struct got_error *err;
5759 const struct got_object_id_queue *parent_ids;
5760 struct got_commit_object *selected_commit;
5761 struct got_object_qid *pid;
5763 free(s->id2);
5764 s->id2 = got_object_id_dup(entry->id);
5765 if (s->id2 == NULL)
5766 return got_error_from_errno("got_object_id_dup");
5768 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5769 if (err)
5770 return err;
5771 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5772 free(s->id1);
5773 pid = STAILQ_FIRST(parent_ids);
5774 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5775 got_object_commit_close(selected_commit);
5776 return NULL;
5779 static const struct got_error *
5780 reset_diff_view(struct tog_view *view)
5782 struct tog_diff_view_state *s = &view->state.diff;
5784 view->count = 0;
5785 wclear(view->window);
5786 s->first_displayed_line = 1;
5787 s->last_displayed_line = view->nlines;
5788 s->matched_line = 0;
5789 diff_view_indicate_progress(view);
5790 return create_diff(s);
5793 static void
5794 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5796 int start, i;
5798 i = start = s->first_displayed_line - 1;
5800 while (s->lines[i].type != type) {
5801 if (i == 0)
5802 i = s->nlines - 1;
5803 if (--i == start)
5804 return; /* do nothing, requested type not in file */
5807 s->selected_line = 1;
5808 s->first_displayed_line = i;
5811 static void
5812 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5814 int start, i;
5816 i = start = s->first_displayed_line + 1;
5818 while (s->lines[i].type != type) {
5819 if (i == s->nlines - 1)
5820 i = 0;
5821 if (++i == start)
5822 return; /* do nothing, requested type not in file */
5825 s->selected_line = 1;
5826 s->first_displayed_line = i;
5829 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5830 int, int, int);
5831 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5832 int, int);
5834 static const struct got_error *
5835 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5837 const struct got_error *err = NULL;
5838 struct tog_diff_view_state *s = &view->state.diff;
5839 struct tog_log_view_state *ls;
5840 struct commit_queue_entry *old_selected_entry;
5841 char *line = NULL;
5842 size_t linesize = 0;
5843 ssize_t linelen;
5844 int i, nscroll = view->nlines - 1, up = 0;
5846 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5848 switch (ch) {
5849 case '0':
5850 case '$':
5851 case KEY_RIGHT:
5852 case 'l':
5853 case KEY_LEFT:
5854 case 'h':
5855 horizontal_scroll_input(view, ch);
5856 break;
5857 case 'a':
5858 case 'w':
5859 if (ch == 'a') {
5860 s->force_text_diff = !s->force_text_diff;
5861 view->action = s->force_text_diff ?
5862 "force ASCII text enabled" :
5863 "force ASCII text disabled";
5865 else if (ch == 'w') {
5866 s->ignore_whitespace = !s->ignore_whitespace;
5867 view->action = s->ignore_whitespace ?
5868 "ignore whitespace enabled" :
5869 "ignore whitespace disabled";
5871 err = reset_diff_view(view);
5872 break;
5873 case 'g':
5874 case KEY_HOME:
5875 s->first_displayed_line = 1;
5876 view->count = 0;
5877 break;
5878 case 'G':
5879 case KEY_END:
5880 view->count = 0;
5881 if (s->eof)
5882 break;
5884 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5885 s->eof = 1;
5886 break;
5887 case 'k':
5888 case KEY_UP:
5889 case CTRL('p'):
5890 if (s->first_displayed_line > 1)
5891 s->first_displayed_line--;
5892 else
5893 view->count = 0;
5894 break;
5895 case CTRL('u'):
5896 case 'u':
5897 nscroll /= 2;
5898 /* FALL THROUGH */
5899 case KEY_PPAGE:
5900 case CTRL('b'):
5901 case 'b':
5902 if (s->first_displayed_line == 1) {
5903 view->count = 0;
5904 break;
5906 i = 0;
5907 while (i++ < nscroll && s->first_displayed_line > 1)
5908 s->first_displayed_line--;
5909 break;
5910 case 'j':
5911 case KEY_DOWN:
5912 case CTRL('n'):
5913 if (!s->eof)
5914 s->first_displayed_line++;
5915 else
5916 view->count = 0;
5917 break;
5918 case CTRL('d'):
5919 case 'd':
5920 nscroll /= 2;
5921 /* FALL THROUGH */
5922 case KEY_NPAGE:
5923 case CTRL('f'):
5924 case 'f':
5925 case ' ':
5926 if (s->eof) {
5927 view->count = 0;
5928 break;
5930 i = 0;
5931 while (!s->eof && i++ < nscroll) {
5932 linelen = getline(&line, &linesize, s->f);
5933 s->first_displayed_line++;
5934 if (linelen == -1) {
5935 if (feof(s->f)) {
5936 s->eof = 1;
5937 } else
5938 err = got_ferror(s->f, GOT_ERR_IO);
5939 break;
5942 free(line);
5943 break;
5944 case '(':
5945 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5946 break;
5947 case ')':
5948 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5949 break;
5950 case '{':
5951 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5952 break;
5953 case '}':
5954 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5955 break;
5956 case '[':
5957 if (s->diff_context > 0) {
5958 s->diff_context--;
5959 s->matched_line = 0;
5960 diff_view_indicate_progress(view);
5961 err = create_diff(s);
5962 if (s->first_displayed_line + view->nlines - 1 >
5963 s->nlines) {
5964 s->first_displayed_line = 1;
5965 s->last_displayed_line = view->nlines;
5967 } else
5968 view->count = 0;
5969 break;
5970 case ']':
5971 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5972 s->diff_context++;
5973 s->matched_line = 0;
5974 diff_view_indicate_progress(view);
5975 err = create_diff(s);
5976 } else
5977 view->count = 0;
5978 break;
5979 case '<':
5980 case ',':
5981 case 'K':
5982 up = 1;
5983 /* FALL THROUGH */
5984 case '>':
5985 case '.':
5986 case 'J':
5987 if (s->parent_view == NULL) {
5988 view->count = 0;
5989 break;
5991 s->parent_view->count = view->count;
5993 if (s->parent_view->type == TOG_VIEW_LOG) {
5994 ls = &s->parent_view->state.log;
5995 old_selected_entry = ls->selected_entry;
5997 err = input_log_view(NULL, s->parent_view,
5998 up ? KEY_UP : KEY_DOWN);
5999 if (err)
6000 break;
6001 view->count = s->parent_view->count;
6003 if (old_selected_entry == ls->selected_entry)
6004 break;
6006 err = set_selected_commit(s, ls->selected_entry);
6007 if (err)
6008 break;
6009 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
6010 struct tog_blame_view_state *bs;
6011 struct got_object_id *id, *prev_id;
6013 bs = &s->parent_view->state.blame;
6014 prev_id = get_annotation_for_line(bs->blame.lines,
6015 bs->blame.nlines, bs->last_diffed_line);
6017 err = input_blame_view(&view, s->parent_view,
6018 up ? KEY_UP : KEY_DOWN);
6019 if (err)
6020 break;
6021 view->count = s->parent_view->count;
6023 if (prev_id == NULL)
6024 break;
6025 id = get_selected_commit_id(bs->blame.lines,
6026 bs->blame.nlines, bs->first_displayed_line,
6027 bs->selected_line);
6028 if (id == NULL)
6029 break;
6031 if (!got_object_id_cmp(prev_id, id))
6032 break;
6034 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
6035 if (err)
6036 break;
6038 s->first_displayed_line = 1;
6039 s->last_displayed_line = view->nlines;
6040 s->matched_line = 0;
6041 view->x = 0;
6043 diff_view_indicate_progress(view);
6044 err = create_diff(s);
6045 break;
6046 default:
6047 view->count = 0;
6048 break;
6051 return err;
6054 static const struct got_error *
6055 cmd_diff(int argc, char *argv[])
6057 const struct got_error *error;
6058 struct got_repository *repo = NULL;
6059 struct got_worktree *worktree = NULL;
6060 struct got_object_id *id1 = NULL, *id2 = NULL;
6061 char *repo_path = NULL, *cwd = NULL;
6062 char *id_str1 = NULL, *id_str2 = NULL;
6063 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
6064 char *label1 = NULL, *label2 = NULL;
6065 int diff_context = 3, ignore_whitespace = 0;
6066 int ch, force_text_diff = 0;
6067 const char *errstr;
6068 struct tog_view *view;
6069 int *pack_fds = NULL;
6071 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
6072 switch (ch) {
6073 case 'a':
6074 force_text_diff = 1;
6075 break;
6076 case 'C':
6077 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
6078 &errstr);
6079 if (errstr != NULL)
6080 errx(1, "number of context lines is %s: %s",
6081 errstr, errstr);
6082 break;
6083 case 'r':
6084 repo_path = realpath(optarg, NULL);
6085 if (repo_path == NULL)
6086 return got_error_from_errno2("realpath",
6087 optarg);
6088 got_path_strip_trailing_slashes(repo_path);
6089 break;
6090 case 'w':
6091 ignore_whitespace = 1;
6092 break;
6093 default:
6094 usage_diff();
6095 /* NOTREACHED */
6099 argc -= optind;
6100 argv += optind;
6102 if (argc == 0) {
6103 usage_diff(); /* TODO show local worktree changes */
6104 } else if (argc == 2) {
6105 id_str1 = argv[0];
6106 id_str2 = argv[1];
6107 } else
6108 usage_diff();
6110 error = got_repo_pack_fds_open(&pack_fds);
6111 if (error)
6112 goto done;
6114 if (repo_path == NULL) {
6115 cwd = getcwd(NULL, 0);
6116 if (cwd == NULL)
6117 return got_error_from_errno("getcwd");
6118 error = got_worktree_open(&worktree, cwd, NULL);
6119 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6120 goto done;
6121 if (worktree)
6122 repo_path =
6123 strdup(got_worktree_get_repo_path(worktree));
6124 else
6125 repo_path = strdup(cwd);
6126 if (repo_path == NULL) {
6127 error = got_error_from_errno("strdup");
6128 goto done;
6132 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6133 if (error)
6134 goto done;
6136 init_curses();
6138 error = apply_unveil(got_repo_get_path(repo), NULL);
6139 if (error)
6140 goto done;
6142 error = tog_load_refs(repo, 0);
6143 if (error)
6144 goto done;
6146 if (id_str1 != NULL) {
6147 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6148 repo, worktree);
6149 if (error != NULL)
6150 goto done;
6151 if (keyword_idstr1 != NULL)
6152 id_str1 = keyword_idstr1;
6154 if (id_str2 != NULL) {
6155 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6156 repo, worktree);
6157 if (error != NULL)
6158 goto done;
6159 if (keyword_idstr2 != NULL)
6160 id_str2 = keyword_idstr2;
6163 error = got_repo_match_object_id(&id1, &label1, id_str1,
6164 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6165 if (error)
6166 goto done;
6168 error = got_repo_match_object_id(&id2, &label2, id_str2,
6169 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6170 if (error)
6171 goto done;
6173 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6174 if (view == NULL) {
6175 error = got_error_from_errno("view_open");
6176 goto done;
6178 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6179 ignore_whitespace, force_text_diff, NULL, repo);
6180 if (error)
6181 goto done;
6183 if (worktree) {
6184 error = set_tog_base_commit(repo, worktree);
6185 if (error != NULL)
6186 goto done;
6188 /* Release work tree lock. */
6189 got_worktree_close(worktree);
6190 worktree = NULL;
6193 error = view_loop(view);
6195 done:
6196 free(tog_base_commit.id);
6197 free(keyword_idstr1);
6198 free(keyword_idstr2);
6199 free(label1);
6200 free(label2);
6201 free(id1);
6202 free(id2);
6203 free(repo_path);
6204 free(cwd);
6205 if (repo) {
6206 const struct got_error *close_err = got_repo_close(repo);
6207 if (error == NULL)
6208 error = close_err;
6210 if (worktree)
6211 got_worktree_close(worktree);
6212 if (pack_fds) {
6213 const struct got_error *pack_err =
6214 got_repo_pack_fds_close(pack_fds);
6215 if (error == NULL)
6216 error = pack_err;
6218 tog_free_refs();
6219 return error;
6222 __dead static void
6223 usage_blame(void)
6225 endwin();
6226 fprintf(stderr,
6227 "usage: %s blame [-c commit] [-r repository-path] path\n",
6228 getprogname());
6229 exit(1);
6232 struct tog_blame_line {
6233 int annotated;
6234 struct got_object_id *id;
6237 static const struct got_error *
6238 draw_blame(struct tog_view *view)
6240 struct tog_blame_view_state *s = &view->state.blame;
6241 struct tog_blame *blame = &s->blame;
6242 regmatch_t *regmatch = &view->regmatch;
6243 const struct got_error *err;
6244 int lineno = 0, nprinted = 0;
6245 char *line = NULL;
6246 size_t linesize = 0;
6247 ssize_t linelen;
6248 wchar_t *wline;
6249 int width;
6250 struct tog_blame_line *blame_line;
6251 struct got_object_id *prev_id = NULL;
6252 char *id_str;
6253 struct tog_color *tc;
6255 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6256 if (err)
6257 return err;
6259 rewind(blame->f);
6260 werase(view->window);
6262 if (asprintf(&line, "commit %s", id_str) == -1) {
6263 err = got_error_from_errno("asprintf");
6264 free(id_str);
6265 return err;
6268 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6269 free(line);
6270 line = NULL;
6271 if (err)
6272 return err;
6273 if (view_needs_focus_indication(view))
6274 wstandout(view->window);
6275 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6276 if (tc)
6277 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6278 waddwstr(view->window, wline);
6279 while (width++ < view->ncols)
6280 waddch(view->window, ' ');
6281 if (tc)
6282 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6283 if (view_needs_focus_indication(view))
6284 wstandend(view->window);
6285 free(wline);
6286 wline = NULL;
6288 if (view->gline > blame->nlines)
6289 view->gline = blame->nlines;
6291 if (tog_io.wait_for_ui) {
6292 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6293 int rc;
6295 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6296 if (rc)
6297 return got_error_set_errno(rc, "pthread_cond_wait");
6298 tog_io.wait_for_ui = 0;
6301 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6302 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6303 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6304 free(id_str);
6305 return got_error_from_errno("asprintf");
6307 free(id_str);
6308 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6309 free(line);
6310 line = NULL;
6311 if (err)
6312 return err;
6313 waddwstr(view->window, wline);
6314 free(wline);
6315 wline = NULL;
6316 if (width < view->ncols - 1)
6317 waddch(view->window, '\n');
6319 s->eof = 0;
6320 view->maxx = 0;
6321 while (nprinted < view->nlines - 2) {
6322 linelen = getline(&line, &linesize, blame->f);
6323 if (linelen == -1) {
6324 if (feof(blame->f)) {
6325 s->eof = 1;
6326 break;
6328 free(line);
6329 return got_ferror(blame->f, GOT_ERR_IO);
6331 if (++lineno < s->first_displayed_line)
6332 continue;
6333 if (view->gline && !gotoline(view, &lineno, &nprinted))
6334 continue;
6336 /* Set view->maxx based on full line length. */
6337 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6338 if (err) {
6339 free(line);
6340 return err;
6342 free(wline);
6343 wline = NULL;
6344 view->maxx = MAX(view->maxx, width);
6346 if (nprinted == s->selected_line - 1)
6347 wstandout(view->window);
6349 if (blame->nlines > 0) {
6350 blame_line = &blame->lines[lineno - 1];
6351 if (blame_line->annotated && prev_id &&
6352 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6353 !(nprinted == s->selected_line - 1)) {
6354 waddstr(view->window, " ");
6355 } else if (blame_line->annotated) {
6356 char *id_str;
6357 err = got_object_id_str(&id_str,
6358 blame_line->id);
6359 if (err) {
6360 free(line);
6361 return err;
6363 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6364 if (tc)
6365 wattr_on(view->window,
6366 COLOR_PAIR(tc->colorpair), NULL);
6367 wprintw(view->window, "%.8s", id_str);
6368 if (tc)
6369 wattr_off(view->window,
6370 COLOR_PAIR(tc->colorpair), NULL);
6371 free(id_str);
6372 prev_id = blame_line->id;
6373 } else {
6374 waddstr(view->window, "........");
6375 prev_id = NULL;
6377 } else {
6378 waddstr(view->window, "........");
6379 prev_id = NULL;
6382 if (nprinted == s->selected_line - 1)
6383 wstandend(view->window);
6384 waddstr(view->window, " ");
6386 if (view->ncols <= 9) {
6387 width = 9;
6388 } else if (s->first_displayed_line + nprinted ==
6389 s->matched_line &&
6390 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6391 err = add_matched_line(&width, line, view->ncols - 9, 9,
6392 view->window, view->x, regmatch);
6393 if (err) {
6394 free(line);
6395 return err;
6397 width += 9;
6398 } else {
6399 int skip;
6400 err = format_line(&wline, &width, &skip, line,
6401 view->x, view->ncols - 9, 9, 1);
6402 if (err) {
6403 free(line);
6404 return err;
6406 waddwstr(view->window, &wline[skip]);
6407 width += 9;
6408 free(wline);
6409 wline = NULL;
6412 if (width <= view->ncols - 1)
6413 waddch(view->window, '\n');
6414 if (++nprinted == 1)
6415 s->first_displayed_line = lineno;
6417 free(line);
6418 s->last_displayed_line = lineno;
6420 view_border(view);
6422 return NULL;
6425 static const struct got_error *
6426 blame_cb(void *arg, int nlines, int lineno,
6427 struct got_commit_object *commit, struct got_object_id *id)
6429 const struct got_error *err = NULL;
6430 struct tog_blame_cb_args *a = arg;
6431 struct tog_blame_line *line;
6432 int errcode;
6434 if (nlines != a->nlines ||
6435 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6436 return got_error(GOT_ERR_RANGE);
6438 errcode = pthread_mutex_lock(&tog_mutex);
6439 if (errcode)
6440 return got_error_set_errno(errcode, "pthread_mutex_lock");
6442 if (*a->quit) { /* user has quit the blame view */
6443 err = got_error(GOT_ERR_ITER_COMPLETED);
6444 goto done;
6447 if (lineno == -1)
6448 goto done; /* no change in this commit */
6450 line = &a->lines[lineno - 1];
6451 if (line->annotated)
6452 goto done;
6454 line->id = got_object_id_dup(id);
6455 if (line->id == NULL) {
6456 err = got_error_from_errno("got_object_id_dup");
6457 goto done;
6459 line->annotated = 1;
6460 done:
6461 errcode = pthread_mutex_unlock(&tog_mutex);
6462 if (errcode)
6463 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6464 return err;
6467 static void *
6468 blame_thread(void *arg)
6470 const struct got_error *err, *close_err;
6471 struct tog_blame_thread_args *ta = arg;
6472 struct tog_blame_cb_args *a = ta->cb_args;
6473 int errcode, fd1 = -1, fd2 = -1;
6474 FILE *f1 = NULL, *f2 = NULL;
6476 fd1 = got_opentempfd();
6477 if (fd1 == -1)
6478 return (void *)got_error_from_errno("got_opentempfd");
6480 fd2 = got_opentempfd();
6481 if (fd2 == -1) {
6482 err = got_error_from_errno("got_opentempfd");
6483 goto done;
6486 f1 = got_opentemp();
6487 if (f1 == NULL) {
6488 err = (void *)got_error_from_errno("got_opentemp");
6489 goto done;
6491 f2 = got_opentemp();
6492 if (f2 == NULL) {
6493 err = (void *)got_error_from_errno("got_opentemp");
6494 goto done;
6497 err = block_signals_used_by_main_thread();
6498 if (err)
6499 goto done;
6501 err = got_blame(ta->path, a->commit_id, ta->repo,
6502 tog_diff_algo, blame_cb, ta->cb_args,
6503 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6504 if (err && err->code == GOT_ERR_CANCELLED)
6505 err = NULL;
6507 errcode = pthread_mutex_lock(&tog_mutex);
6508 if (errcode) {
6509 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6510 goto done;
6513 close_err = got_repo_close(ta->repo);
6514 if (err == NULL)
6515 err = close_err;
6516 ta->repo = NULL;
6517 *ta->complete = 1;
6519 if (tog_io.wait_for_ui) {
6520 errcode = pthread_cond_signal(&ta->blame_complete);
6521 if (errcode && err == NULL)
6522 err = got_error_set_errno(errcode,
6523 "pthread_cond_signal");
6526 errcode = pthread_mutex_unlock(&tog_mutex);
6527 if (errcode && err == NULL)
6528 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6530 done:
6531 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6532 err = got_error_from_errno("close");
6533 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6534 err = got_error_from_errno("close");
6535 if (f1 && fclose(f1) == EOF && err == NULL)
6536 err = got_error_from_errno("fclose");
6537 if (f2 && fclose(f2) == EOF && err == NULL)
6538 err = got_error_from_errno("fclose");
6540 return (void *)err;
6543 static struct got_object_id *
6544 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6545 int first_displayed_line, int selected_line)
6547 struct tog_blame_line *line;
6549 if (nlines <= 0)
6550 return NULL;
6552 line = &lines[first_displayed_line - 1 + selected_line - 1];
6553 if (!line->annotated)
6554 return NULL;
6556 return line->id;
6559 static struct got_object_id *
6560 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6561 int lineno)
6563 struct tog_blame_line *line;
6565 if (nlines <= 0 || lineno >= nlines)
6566 return NULL;
6568 line = &lines[lineno - 1];
6569 if (!line->annotated)
6570 return NULL;
6572 return line->id;
6575 static const struct got_error *
6576 stop_blame(struct tog_blame *blame)
6578 const struct got_error *err = NULL;
6579 int i;
6581 if (blame->thread) {
6582 int errcode;
6583 errcode = pthread_mutex_unlock(&tog_mutex);
6584 if (errcode)
6585 return got_error_set_errno(errcode,
6586 "pthread_mutex_unlock");
6587 errcode = pthread_join(blame->thread, (void **)&err);
6588 if (errcode)
6589 return got_error_set_errno(errcode, "pthread_join");
6590 errcode = pthread_mutex_lock(&tog_mutex);
6591 if (errcode)
6592 return got_error_set_errno(errcode,
6593 "pthread_mutex_lock");
6594 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6595 err = NULL;
6596 blame->thread = 0; //NULL;
6598 if (blame->thread_args.repo) {
6599 const struct got_error *close_err;
6600 close_err = got_repo_close(blame->thread_args.repo);
6601 if (err == NULL)
6602 err = close_err;
6603 blame->thread_args.repo = NULL;
6605 if (blame->f) {
6606 if (fclose(blame->f) == EOF && err == NULL)
6607 err = got_error_from_errno("fclose");
6608 blame->f = NULL;
6610 if (blame->lines) {
6611 for (i = 0; i < blame->nlines; i++)
6612 free(blame->lines[i].id);
6613 free(blame->lines);
6614 blame->lines = NULL;
6616 free(blame->cb_args.commit_id);
6617 blame->cb_args.commit_id = NULL;
6618 if (blame->pack_fds) {
6619 const struct got_error *pack_err =
6620 got_repo_pack_fds_close(blame->pack_fds);
6621 if (err == NULL)
6622 err = pack_err;
6623 blame->pack_fds = NULL;
6625 free(blame->line_offsets);
6626 blame->line_offsets = NULL;
6627 return err;
6630 static const struct got_error *
6631 cancel_blame_view(void *arg)
6633 const struct got_error *err = NULL;
6634 int *done = arg;
6635 int errcode;
6637 errcode = pthread_mutex_lock(&tog_mutex);
6638 if (errcode)
6639 return got_error_set_errno(errcode,
6640 "pthread_mutex_unlock");
6642 if (*done)
6643 err = got_error(GOT_ERR_CANCELLED);
6645 errcode = pthread_mutex_unlock(&tog_mutex);
6646 if (errcode)
6647 return got_error_set_errno(errcode,
6648 "pthread_mutex_lock");
6650 return err;
6653 static const struct got_error *
6654 run_blame(struct tog_view *view)
6656 struct tog_blame_view_state *s = &view->state.blame;
6657 struct tog_blame *blame = &s->blame;
6658 const struct got_error *err = NULL;
6659 struct got_commit_object *commit = NULL;
6660 struct got_blob_object *blob = NULL;
6661 struct got_repository *thread_repo = NULL;
6662 struct got_object_id *obj_id = NULL;
6663 int obj_type, fd = -1;
6664 int *pack_fds = NULL;
6666 err = got_object_open_as_commit(&commit, s->repo,
6667 &s->blamed_commit->id);
6668 if (err)
6669 return err;
6671 fd = got_opentempfd();
6672 if (fd == -1) {
6673 err = got_error_from_errno("got_opentempfd");
6674 goto done;
6677 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6678 if (err)
6679 goto done;
6681 err = got_object_get_type(&obj_type, s->repo, obj_id);
6682 if (err)
6683 goto done;
6685 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6686 err = got_error(GOT_ERR_OBJ_TYPE);
6687 goto done;
6690 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6691 if (err)
6692 goto done;
6693 blame->f = got_opentemp();
6694 if (blame->f == NULL) {
6695 err = got_error_from_errno("got_opentemp");
6696 goto done;
6698 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6699 &blame->line_offsets, blame->f, blob);
6700 if (err)
6701 goto done;
6702 if (blame->nlines == 0) {
6703 s->blame_complete = 1;
6704 goto done;
6707 /* Don't include \n at EOF in the blame line count. */
6708 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6709 blame->nlines--;
6711 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6712 if (blame->lines == NULL) {
6713 err = got_error_from_errno("calloc");
6714 goto done;
6717 err = got_repo_pack_fds_open(&pack_fds);
6718 if (err)
6719 goto done;
6720 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6721 pack_fds);
6722 if (err)
6723 goto done;
6725 blame->pack_fds = pack_fds;
6726 blame->cb_args.view = view;
6727 blame->cb_args.lines = blame->lines;
6728 blame->cb_args.nlines = blame->nlines;
6729 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6730 if (blame->cb_args.commit_id == NULL) {
6731 err = got_error_from_errno("got_object_id_dup");
6732 goto done;
6734 blame->cb_args.quit = &s->done;
6736 blame->thread_args.path = s->path;
6737 blame->thread_args.repo = thread_repo;
6738 blame->thread_args.cb_args = &blame->cb_args;
6739 blame->thread_args.complete = &s->blame_complete;
6740 blame->thread_args.cancel_cb = cancel_blame_view;
6741 blame->thread_args.cancel_arg = &s->done;
6742 s->blame_complete = 0;
6744 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6745 s->first_displayed_line = 1;
6746 s->last_displayed_line = view->nlines;
6747 s->selected_line = 1;
6749 s->matched_line = 0;
6751 done:
6752 if (commit)
6753 got_object_commit_close(commit);
6754 if (fd != -1 && close(fd) == -1 && err == NULL)
6755 err = got_error_from_errno("close");
6756 if (blob)
6757 got_object_blob_close(blob);
6758 free(obj_id);
6759 if (err)
6760 stop_blame(blame);
6761 return err;
6764 static const struct got_error *
6765 open_blame_view(struct tog_view *view, char *path,
6766 struct got_object_id *commit_id, struct got_repository *repo)
6768 const struct got_error *err = NULL;
6769 struct tog_blame_view_state *s = &view->state.blame;
6771 STAILQ_INIT(&s->blamed_commits);
6773 s->path = strdup(path);
6774 if (s->path == NULL)
6775 return got_error_from_errno("strdup");
6777 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6778 if (err) {
6779 free(s->path);
6780 return err;
6783 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6784 s->first_displayed_line = 1;
6785 s->last_displayed_line = view->nlines;
6786 s->selected_line = 1;
6787 s->blame_complete = 0;
6788 s->repo = repo;
6789 s->commit_id = commit_id;
6790 memset(&s->blame, 0, sizeof(s->blame));
6792 STAILQ_INIT(&s->colors);
6793 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6794 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6795 get_color_value("TOG_COLOR_COMMIT"));
6796 if (err)
6797 return err;
6800 view->show = show_blame_view;
6801 view->input = input_blame_view;
6802 view->reset = reset_blame_view;
6803 view->close = close_blame_view;
6804 view->search_start = search_start_blame_view;
6805 view->search_setup = search_setup_blame_view;
6806 view->search_next = search_next_view_match;
6808 if (using_mock_io) {
6809 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6810 int rc;
6812 rc = pthread_cond_init(&bta->blame_complete, NULL);
6813 if (rc)
6814 return got_error_set_errno(rc, "pthread_cond_init");
6817 return run_blame(view);
6820 static const struct got_error *
6821 close_blame_view(struct tog_view *view)
6823 const struct got_error *err = NULL;
6824 struct tog_blame_view_state *s = &view->state.blame;
6826 if (s->blame.thread)
6827 err = stop_blame(&s->blame);
6829 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6830 struct got_object_qid *blamed_commit;
6831 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6832 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6833 got_object_qid_free(blamed_commit);
6836 if (using_mock_io) {
6837 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6838 int rc;
6840 rc = pthread_cond_destroy(&bta->blame_complete);
6841 if (rc && err == NULL)
6842 err = got_error_set_errno(rc, "pthread_cond_destroy");
6845 free(s->path);
6846 free_colors(&s->colors);
6847 return err;
6850 static const struct got_error *
6851 search_start_blame_view(struct tog_view *view)
6853 struct tog_blame_view_state *s = &view->state.blame;
6855 s->matched_line = 0;
6856 return NULL;
6859 static void
6860 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6861 size_t *nlines, int **first, int **last, int **match, int **selected)
6863 struct tog_blame_view_state *s = &view->state.blame;
6865 *f = s->blame.f;
6866 *nlines = s->blame.nlines;
6867 *line_offsets = s->blame.line_offsets;
6868 *match = &s->matched_line;
6869 *first = &s->first_displayed_line;
6870 *last = &s->last_displayed_line;
6871 *selected = &s->selected_line;
6874 static const struct got_error *
6875 show_blame_view(struct tog_view *view)
6877 const struct got_error *err = NULL;
6878 struct tog_blame_view_state *s = &view->state.blame;
6879 int errcode;
6881 if (s->blame.thread == 0 && !s->blame_complete) {
6882 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6883 &s->blame.thread_args);
6884 if (errcode)
6885 return got_error_set_errno(errcode, "pthread_create");
6887 if (!using_mock_io)
6888 halfdelay(1); /* fast refresh while annotating */
6891 if (s->blame_complete && !using_mock_io)
6892 halfdelay(10); /* disable fast refresh */
6894 err = draw_blame(view);
6896 view_border(view);
6897 return err;
6900 static const struct got_error *
6901 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6902 struct got_repository *repo, struct got_object_id *id)
6904 struct tog_view *log_view;
6905 const struct got_error *err = NULL;
6907 *new_view = NULL;
6909 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6910 if (log_view == NULL)
6911 return got_error_from_errno("view_open");
6913 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
6914 if (err)
6915 view_close(log_view);
6916 else
6917 *new_view = log_view;
6919 return err;
6922 static const struct got_error *
6923 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6925 const struct got_error *err = NULL, *thread_err = NULL;
6926 struct tog_view *diff_view;
6927 struct tog_blame_view_state *s = &view->state.blame;
6928 int eos, nscroll, begin_y = 0, begin_x = 0;
6930 eos = nscroll = view->nlines - 2;
6931 if (view_is_hsplit_top(view))
6932 --eos; /* border */
6934 switch (ch) {
6935 case '0':
6936 case '$':
6937 case KEY_RIGHT:
6938 case 'l':
6939 case KEY_LEFT:
6940 case 'h':
6941 horizontal_scroll_input(view, ch);
6942 break;
6943 case 'q':
6944 s->done = 1;
6945 break;
6946 case 'g':
6947 case KEY_HOME:
6948 s->selected_line = 1;
6949 s->first_displayed_line = 1;
6950 view->count = 0;
6951 break;
6952 case 'G':
6953 case KEY_END:
6954 if (s->blame.nlines < eos) {
6955 s->selected_line = s->blame.nlines;
6956 s->first_displayed_line = 1;
6957 } else {
6958 s->selected_line = eos;
6959 s->first_displayed_line = s->blame.nlines - (eos - 1);
6961 view->count = 0;
6962 break;
6963 case 'k':
6964 case KEY_UP:
6965 case CTRL('p'):
6966 if (s->selected_line > 1)
6967 s->selected_line--;
6968 else if (s->selected_line == 1 &&
6969 s->first_displayed_line > 1)
6970 s->first_displayed_line--;
6971 else
6972 view->count = 0;
6973 break;
6974 case CTRL('u'):
6975 case 'u':
6976 nscroll /= 2;
6977 /* FALL THROUGH */
6978 case KEY_PPAGE:
6979 case CTRL('b'):
6980 case 'b':
6981 if (s->first_displayed_line == 1) {
6982 if (view->count > 1)
6983 nscroll += nscroll;
6984 s->selected_line = MAX(1, s->selected_line - nscroll);
6985 view->count = 0;
6986 break;
6988 if (s->first_displayed_line > nscroll)
6989 s->first_displayed_line -= nscroll;
6990 else
6991 s->first_displayed_line = 1;
6992 break;
6993 case 'j':
6994 case KEY_DOWN:
6995 case CTRL('n'):
6996 if (s->selected_line < eos && s->first_displayed_line +
6997 s->selected_line <= s->blame.nlines)
6998 s->selected_line++;
6999 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
7000 s->first_displayed_line++;
7001 else
7002 view->count = 0;
7003 break;
7004 case 'c':
7005 case 'p': {
7006 struct got_object_id *id = NULL;
7008 view->count = 0;
7009 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7010 s->first_displayed_line, s->selected_line);
7011 if (id == NULL)
7012 break;
7013 if (ch == 'p') {
7014 struct got_commit_object *commit, *pcommit;
7015 struct got_object_qid *pid;
7016 struct got_object_id *blob_id = NULL;
7017 int obj_type;
7018 err = got_object_open_as_commit(&commit,
7019 s->repo, id);
7020 if (err)
7021 break;
7022 pid = STAILQ_FIRST(
7023 got_object_commit_get_parent_ids(commit));
7024 if (pid == NULL) {
7025 got_object_commit_close(commit);
7026 break;
7028 /* Check if path history ends here. */
7029 err = got_object_open_as_commit(&pcommit,
7030 s->repo, &pid->id);
7031 if (err)
7032 break;
7033 err = got_object_id_by_path(&blob_id, s->repo,
7034 pcommit, s->path);
7035 got_object_commit_close(pcommit);
7036 if (err) {
7037 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7038 err = NULL;
7039 got_object_commit_close(commit);
7040 break;
7042 err = got_object_get_type(&obj_type, s->repo,
7043 blob_id);
7044 free(blob_id);
7045 /* Can't blame non-blob type objects. */
7046 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7047 got_object_commit_close(commit);
7048 break;
7050 err = got_object_qid_alloc(&s->blamed_commit,
7051 &pid->id);
7052 got_object_commit_close(commit);
7053 } else {
7054 if (got_object_id_cmp(id,
7055 &s->blamed_commit->id) == 0)
7056 break;
7057 err = got_object_qid_alloc(&s->blamed_commit,
7058 id);
7060 if (err)
7061 break;
7062 s->done = 1;
7063 thread_err = stop_blame(&s->blame);
7064 s->done = 0;
7065 if (thread_err)
7066 break;
7067 STAILQ_INSERT_HEAD(&s->blamed_commits,
7068 s->blamed_commit, entry);
7069 err = run_blame(view);
7070 if (err)
7071 break;
7072 break;
7074 case 'C': {
7075 struct got_object_qid *first;
7077 view->count = 0;
7078 first = STAILQ_FIRST(&s->blamed_commits);
7079 if (!got_object_id_cmp(&first->id, s->commit_id))
7080 break;
7081 s->done = 1;
7082 thread_err = stop_blame(&s->blame);
7083 s->done = 0;
7084 if (thread_err)
7085 break;
7086 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7087 got_object_qid_free(s->blamed_commit);
7088 s->blamed_commit =
7089 STAILQ_FIRST(&s->blamed_commits);
7090 err = run_blame(view);
7091 if (err)
7092 break;
7093 break;
7095 case 'L':
7096 view->count = 0;
7097 s->id_to_log = get_selected_commit_id(s->blame.lines,
7098 s->blame.nlines, s->first_displayed_line, s->selected_line);
7099 if (s->id_to_log)
7100 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7101 break;
7102 case KEY_ENTER:
7103 case '\r': {
7104 struct got_object_id *id = NULL;
7105 struct got_object_qid *pid;
7106 struct got_commit_object *commit = NULL;
7108 view->count = 0;
7109 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7110 s->first_displayed_line, s->selected_line);
7111 if (id == NULL)
7112 break;
7113 err = got_object_open_as_commit(&commit, s->repo, id);
7114 if (err)
7115 break;
7116 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7117 if (*new_view) {
7118 /* traversed from diff view, release diff resources */
7119 err = close_diff_view(*new_view);
7120 if (err)
7121 break;
7122 diff_view = *new_view;
7123 } else {
7124 if (view_is_parent_view(view))
7125 view_get_split(view, &begin_y, &begin_x);
7127 diff_view = view_open(0, 0, begin_y, begin_x,
7128 TOG_VIEW_DIFF);
7129 if (diff_view == NULL) {
7130 got_object_commit_close(commit);
7131 err = got_error_from_errno("view_open");
7132 break;
7135 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7136 id, NULL, NULL, 3, 0, 0, view, s->repo);
7137 got_object_commit_close(commit);
7138 if (err)
7139 break;
7140 s->last_diffed_line = s->first_displayed_line - 1 +
7141 s->selected_line;
7142 if (*new_view)
7143 break; /* still open from active diff view */
7144 if (view_is_parent_view(view) &&
7145 view->mode == TOG_VIEW_SPLIT_HRZN) {
7146 err = view_init_hsplit(view, begin_y);
7147 if (err)
7148 break;
7151 view->focussed = 0;
7152 diff_view->focussed = 1;
7153 diff_view->mode = view->mode;
7154 diff_view->nlines = view->lines - begin_y;
7155 if (view_is_parent_view(view)) {
7156 view_transfer_size(diff_view, view);
7157 err = view_close_child(view);
7158 if (err)
7159 break;
7160 err = view_set_child(view, diff_view);
7161 if (err)
7162 break;
7163 view->focus_child = 1;
7164 } else
7165 *new_view = diff_view;
7166 if (err)
7167 break;
7168 break;
7170 case CTRL('d'):
7171 case 'd':
7172 nscroll /= 2;
7173 /* FALL THROUGH */
7174 case KEY_NPAGE:
7175 case CTRL('f'):
7176 case 'f':
7177 case ' ':
7178 if (s->last_displayed_line >= s->blame.nlines &&
7179 s->selected_line >= MIN(s->blame.nlines,
7180 view->nlines - 2)) {
7181 view->count = 0;
7182 break;
7184 if (s->last_displayed_line >= s->blame.nlines &&
7185 s->selected_line < view->nlines - 2) {
7186 s->selected_line +=
7187 MIN(nscroll, s->last_displayed_line -
7188 s->first_displayed_line - s->selected_line + 1);
7190 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7191 s->first_displayed_line += nscroll;
7192 else
7193 s->first_displayed_line =
7194 s->blame.nlines - (view->nlines - 3);
7195 break;
7196 case KEY_RESIZE:
7197 if (s->selected_line > view->nlines - 2) {
7198 s->selected_line = MIN(s->blame.nlines,
7199 view->nlines - 2);
7201 break;
7202 default:
7203 view->count = 0;
7204 break;
7206 return thread_err ? thread_err : err;
7209 static const struct got_error *
7210 reset_blame_view(struct tog_view *view)
7212 const struct got_error *err;
7213 struct tog_blame_view_state *s = &view->state.blame;
7215 view->count = 0;
7216 s->done = 1;
7217 err = stop_blame(&s->blame);
7218 s->done = 0;
7219 if (err)
7220 return err;
7221 return run_blame(view);
7224 static const struct got_error *
7225 cmd_blame(int argc, char *argv[])
7227 const struct got_error *error;
7228 struct got_repository *repo = NULL;
7229 struct got_worktree *worktree = NULL;
7230 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7231 char *link_target = NULL;
7232 struct got_object_id *commit_id = NULL;
7233 struct got_commit_object *commit = NULL;
7234 char *keyword_idstr = NULL, *commit_id_str = NULL;
7235 int ch;
7236 struct tog_view *view = NULL;
7237 int *pack_fds = NULL;
7239 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7240 switch (ch) {
7241 case 'c':
7242 commit_id_str = optarg;
7243 break;
7244 case 'r':
7245 repo_path = realpath(optarg, NULL);
7246 if (repo_path == NULL)
7247 return got_error_from_errno2("realpath",
7248 optarg);
7249 break;
7250 default:
7251 usage_blame();
7252 /* NOTREACHED */
7256 argc -= optind;
7257 argv += optind;
7259 if (argc != 1)
7260 usage_blame();
7262 error = got_repo_pack_fds_open(&pack_fds);
7263 if (error != NULL)
7264 goto done;
7266 if (repo_path == NULL) {
7267 cwd = getcwd(NULL, 0);
7268 if (cwd == NULL)
7269 return got_error_from_errno("getcwd");
7270 error = got_worktree_open(&worktree, cwd, NULL);
7271 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7272 goto done;
7273 if (worktree)
7274 repo_path =
7275 strdup(got_worktree_get_repo_path(worktree));
7276 else
7277 repo_path = strdup(cwd);
7278 if (repo_path == NULL) {
7279 error = got_error_from_errno("strdup");
7280 goto done;
7284 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7285 if (error != NULL)
7286 goto done;
7288 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7289 worktree);
7290 if (error)
7291 goto done;
7293 init_curses();
7295 error = apply_unveil(got_repo_get_path(repo), NULL);
7296 if (error)
7297 goto done;
7299 error = tog_load_refs(repo, 0);
7300 if (error)
7301 goto done;
7303 if (commit_id_str == NULL) {
7304 struct got_reference *head_ref;
7305 error = got_ref_open(&head_ref, repo, worktree ?
7306 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7307 if (error != NULL)
7308 goto done;
7309 error = got_ref_resolve(&commit_id, repo, head_ref);
7310 got_ref_close(head_ref);
7311 } else {
7312 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7313 repo, worktree);
7314 if (error != NULL)
7315 goto done;
7316 if (keyword_idstr != NULL)
7317 commit_id_str = keyword_idstr;
7319 error = got_repo_match_object_id(&commit_id, NULL,
7320 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7322 if (error != NULL)
7323 goto done;
7325 error = got_object_open_as_commit(&commit, repo, commit_id);
7326 if (error)
7327 goto done;
7329 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7330 commit, repo);
7331 if (error)
7332 goto done;
7334 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7335 if (view == NULL) {
7336 error = got_error_from_errno("view_open");
7337 goto done;
7339 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7340 commit_id, repo);
7341 if (error != NULL) {
7342 if (view->close == NULL)
7343 close_blame_view(view);
7344 view_close(view);
7345 goto done;
7348 if (worktree) {
7349 error = set_tog_base_commit(repo, worktree);
7350 if (error != NULL)
7351 goto done;
7353 /* Release work tree lock. */
7354 got_worktree_close(worktree);
7355 worktree = NULL;
7358 error = view_loop(view);
7360 done:
7361 free(tog_base_commit.id);
7362 free(repo_path);
7363 free(in_repo_path);
7364 free(link_target);
7365 free(cwd);
7366 free(commit_id);
7367 free(keyword_idstr);
7368 if (commit)
7369 got_object_commit_close(commit);
7370 if (worktree)
7371 got_worktree_close(worktree);
7372 if (repo) {
7373 const struct got_error *close_err = got_repo_close(repo);
7374 if (error == NULL)
7375 error = close_err;
7377 if (pack_fds) {
7378 const struct got_error *pack_err =
7379 got_repo_pack_fds_close(pack_fds);
7380 if (error == NULL)
7381 error = pack_err;
7383 tog_free_refs();
7384 return error;
7387 static const struct got_error *
7388 draw_tree_entries(struct tog_view *view, const char *parent_path)
7390 struct tog_tree_view_state *s = &view->state.tree;
7391 const struct got_error *err = NULL;
7392 struct got_tree_entry *te;
7393 wchar_t *wline;
7394 char *index = NULL;
7395 struct tog_color *tc;
7396 int width, n, nentries, scrollx, i = 1;
7397 int limit = view->nlines;
7399 s->ndisplayed = 0;
7400 if (view_is_hsplit_top(view))
7401 --limit; /* border */
7403 werase(view->window);
7405 if (limit == 0)
7406 return NULL;
7408 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7409 0, 0);
7410 if (err)
7411 return err;
7412 if (view_needs_focus_indication(view))
7413 wstandout(view->window);
7414 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7415 if (tc)
7416 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7417 waddwstr(view->window, wline);
7418 free(wline);
7419 wline = NULL;
7420 while (width++ < view->ncols)
7421 waddch(view->window, ' ');
7422 if (tc)
7423 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7424 if (view_needs_focus_indication(view))
7425 wstandend(view->window);
7426 if (--limit <= 0)
7427 return NULL;
7429 i += s->selected;
7430 if (s->first_displayed_entry) {
7431 i += got_tree_entry_get_index(s->first_displayed_entry);
7432 if (s->tree != s->root)
7433 ++i; /* account for ".." entry */
7435 nentries = got_object_tree_get_nentries(s->tree);
7436 if (asprintf(&index, "[%d/%d] %s",
7437 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7438 return got_error_from_errno("asprintf");
7439 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7440 free(index);
7441 if (err)
7442 return err;
7443 waddwstr(view->window, wline);
7444 free(wline);
7445 wline = NULL;
7446 if (width < view->ncols - 1)
7447 waddch(view->window, '\n');
7448 if (--limit <= 0)
7449 return NULL;
7450 waddch(view->window, '\n');
7451 if (--limit <= 0)
7452 return NULL;
7454 if (s->first_displayed_entry == NULL) {
7455 te = got_object_tree_get_first_entry(s->tree);
7456 if (s->selected == 0) {
7457 if (view->focussed)
7458 wstandout(view->window);
7459 s->selected_entry = NULL;
7461 waddstr(view->window, " ..\n"); /* parent directory */
7462 if (s->selected == 0 && view->focussed)
7463 wstandend(view->window);
7464 s->ndisplayed++;
7465 if (--limit <= 0)
7466 return NULL;
7467 n = 1;
7468 } else {
7469 n = 0;
7470 te = s->first_displayed_entry;
7473 view->maxx = 0;
7474 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7475 char *line = NULL, *id_str = NULL, *link_target = NULL;
7476 const char *modestr = "";
7477 mode_t mode;
7479 te = got_object_tree_get_entry(s->tree, i);
7480 mode = got_tree_entry_get_mode(te);
7482 if (s->show_ids) {
7483 err = got_object_id_str(&id_str,
7484 got_tree_entry_get_id(te));
7485 if (err)
7486 return got_error_from_errno(
7487 "got_object_id_str");
7489 if (got_object_tree_entry_is_submodule(te))
7490 modestr = "$";
7491 else if (S_ISLNK(mode)) {
7492 int i;
7494 err = got_tree_entry_get_symlink_target(&link_target,
7495 te, s->repo);
7496 if (err) {
7497 free(id_str);
7498 return err;
7500 for (i = 0; link_target[i] != '\0'; i++) {
7501 if (!isprint((unsigned char)link_target[i]))
7502 link_target[i] = '?';
7504 modestr = "@";
7506 else if (S_ISDIR(mode))
7507 modestr = "/";
7508 else if (mode & S_IXUSR)
7509 modestr = "*";
7510 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7511 got_tree_entry_get_name(te), modestr,
7512 link_target ? " -> ": "",
7513 link_target ? link_target : "") == -1) {
7514 free(id_str);
7515 free(link_target);
7516 return got_error_from_errno("asprintf");
7518 free(id_str);
7519 free(link_target);
7521 /* use full line width to determine view->maxx */
7522 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7523 if (err) {
7524 free(line);
7525 break;
7527 view->maxx = MAX(view->maxx, width);
7528 free(wline);
7529 wline = NULL;
7531 err = format_line(&wline, &width, &scrollx, line, view->x,
7532 view->ncols, 0, 0);
7533 if (err) {
7534 free(line);
7535 break;
7537 if (n == s->selected) {
7538 if (view->focussed)
7539 wstandout(view->window);
7540 s->selected_entry = te;
7542 tc = match_color(&s->colors, line);
7543 if (tc)
7544 wattr_on(view->window,
7545 COLOR_PAIR(tc->colorpair), NULL);
7546 waddwstr(view->window, &wline[scrollx]);
7547 if (tc)
7548 wattr_off(view->window,
7549 COLOR_PAIR(tc->colorpair), NULL);
7550 if (width < view->ncols)
7551 waddch(view->window, '\n');
7552 if (n == s->selected && view->focussed)
7553 wstandend(view->window);
7554 free(line);
7555 free(wline);
7556 wline = NULL;
7557 n++;
7558 s->ndisplayed++;
7559 s->last_displayed_entry = te;
7560 if (--limit <= 0)
7561 break;
7564 return err;
7567 static void
7568 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7570 struct got_tree_entry *te;
7571 int isroot = s->tree == s->root;
7572 int i = 0;
7574 if (s->first_displayed_entry == NULL)
7575 return;
7577 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7578 while (i++ < maxscroll) {
7579 if (te == NULL) {
7580 if (!isroot)
7581 s->first_displayed_entry = NULL;
7582 break;
7584 s->first_displayed_entry = te;
7585 te = got_tree_entry_get_prev(s->tree, te);
7589 static const struct got_error *
7590 tree_scroll_down(struct tog_view *view, int maxscroll)
7592 struct tog_tree_view_state *s = &view->state.tree;
7593 struct got_tree_entry *next, *last;
7594 int n = 0;
7596 if (s->first_displayed_entry)
7597 next = got_tree_entry_get_next(s->tree,
7598 s->first_displayed_entry);
7599 else
7600 next = got_object_tree_get_first_entry(s->tree);
7602 last = s->last_displayed_entry;
7603 while (next && n++ < maxscroll) {
7604 if (last) {
7605 s->last_displayed_entry = last;
7606 last = got_tree_entry_get_next(s->tree, last);
7608 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7609 s->first_displayed_entry = next;
7610 next = got_tree_entry_get_next(s->tree, next);
7614 return NULL;
7617 static const struct got_error *
7618 tree_entry_path(char **path, struct tog_parent_trees *parents,
7619 struct got_tree_entry *te)
7621 const struct got_error *err = NULL;
7622 struct tog_parent_tree *pt;
7623 size_t len = 2; /* for leading slash and NUL */
7625 TAILQ_FOREACH(pt, parents, entry)
7626 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7627 + 1 /* slash */;
7628 if (te)
7629 len += strlen(got_tree_entry_get_name(te));
7631 *path = calloc(1, len);
7632 if (path == NULL)
7633 return got_error_from_errno("calloc");
7635 (*path)[0] = '/';
7636 pt = TAILQ_LAST(parents, tog_parent_trees);
7637 while (pt) {
7638 const char *name = got_tree_entry_get_name(pt->selected_entry);
7639 if (strlcat(*path, name, len) >= len) {
7640 err = got_error(GOT_ERR_NO_SPACE);
7641 goto done;
7643 if (strlcat(*path, "/", len) >= len) {
7644 err = got_error(GOT_ERR_NO_SPACE);
7645 goto done;
7647 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7649 if (te) {
7650 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7651 err = got_error(GOT_ERR_NO_SPACE);
7652 goto done;
7655 done:
7656 if (err) {
7657 free(*path);
7658 *path = NULL;
7660 return err;
7663 static const struct got_error *
7664 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7665 struct got_tree_entry *te, struct tog_parent_trees *parents,
7666 struct got_object_id *commit_id, struct got_repository *repo)
7668 const struct got_error *err = NULL;
7669 char *path;
7670 struct tog_view *blame_view;
7672 *new_view = NULL;
7674 err = tree_entry_path(&path, parents, te);
7675 if (err)
7676 return err;
7678 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7679 if (blame_view == NULL) {
7680 err = got_error_from_errno("view_open");
7681 goto done;
7684 err = open_blame_view(blame_view, path, commit_id, repo);
7685 if (err) {
7686 if (err->code == GOT_ERR_CANCELLED)
7687 err = NULL;
7688 view_close(blame_view);
7689 } else
7690 *new_view = blame_view;
7691 done:
7692 free(path);
7693 return err;
7696 static const struct got_error *
7697 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7698 struct tog_tree_view_state *s)
7700 struct tog_view *log_view;
7701 const struct got_error *err = NULL;
7702 char *path;
7704 *new_view = NULL;
7706 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7707 if (log_view == NULL)
7708 return got_error_from_errno("view_open");
7710 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7711 if (err)
7712 return err;
7714 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7715 path, 0, NULL);
7716 if (err)
7717 view_close(log_view);
7718 else
7719 *new_view = log_view;
7720 free(path);
7721 return err;
7724 static const struct got_error *
7725 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7726 const char *head_ref_name, struct got_repository *repo)
7728 const struct got_error *err = NULL;
7729 char *commit_id_str = NULL;
7730 struct tog_tree_view_state *s = &view->state.tree;
7731 struct got_commit_object *commit = NULL;
7733 TAILQ_INIT(&s->parents);
7734 STAILQ_INIT(&s->colors);
7736 s->commit_id = got_object_id_dup(commit_id);
7737 if (s->commit_id == NULL) {
7738 err = got_error_from_errno("got_object_id_dup");
7739 goto done;
7742 err = got_object_open_as_commit(&commit, repo, commit_id);
7743 if (err)
7744 goto done;
7747 * The root is opened here and will be closed when the view is closed.
7748 * Any visited subtrees and their path-wise parents are opened and
7749 * closed on demand.
7751 err = got_object_open_as_tree(&s->root, repo,
7752 got_object_commit_get_tree_id(commit));
7753 if (err)
7754 goto done;
7755 s->tree = s->root;
7757 err = got_object_id_str(&commit_id_str, commit_id);
7758 if (err != NULL)
7759 goto done;
7761 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7762 err = got_error_from_errno("asprintf");
7763 goto done;
7766 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7767 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7768 if (head_ref_name) {
7769 s->head_ref_name = strdup(head_ref_name);
7770 if (s->head_ref_name == NULL) {
7771 err = got_error_from_errno("strdup");
7772 goto done;
7775 s->repo = repo;
7777 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7778 err = add_color(&s->colors, "\\$$",
7779 TOG_COLOR_TREE_SUBMODULE,
7780 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7781 if (err)
7782 goto done;
7783 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7784 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7785 if (err)
7786 goto done;
7787 err = add_color(&s->colors, "/$",
7788 TOG_COLOR_TREE_DIRECTORY,
7789 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7790 if (err)
7791 goto done;
7793 err = add_color(&s->colors, "\\*$",
7794 TOG_COLOR_TREE_EXECUTABLE,
7795 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7796 if (err)
7797 goto done;
7799 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7800 get_color_value("TOG_COLOR_COMMIT"));
7801 if (err)
7802 goto done;
7805 view->show = show_tree_view;
7806 view->input = input_tree_view;
7807 view->close = close_tree_view;
7808 view->search_start = search_start_tree_view;
7809 view->search_next = search_next_tree_view;
7810 done:
7811 free(commit_id_str);
7812 if (commit)
7813 got_object_commit_close(commit);
7814 if (err) {
7815 if (view->close == NULL)
7816 close_tree_view(view);
7817 view_close(view);
7819 return err;
7822 static const struct got_error *
7823 close_tree_view(struct tog_view *view)
7825 struct tog_tree_view_state *s = &view->state.tree;
7827 free_colors(&s->colors);
7828 free(s->tree_label);
7829 s->tree_label = NULL;
7830 free(s->commit_id);
7831 s->commit_id = NULL;
7832 free(s->head_ref_name);
7833 s->head_ref_name = NULL;
7834 while (!TAILQ_EMPTY(&s->parents)) {
7835 struct tog_parent_tree *parent;
7836 parent = TAILQ_FIRST(&s->parents);
7837 TAILQ_REMOVE(&s->parents, parent, entry);
7838 if (parent->tree != s->root)
7839 got_object_tree_close(parent->tree);
7840 free(parent);
7843 if (s->tree != NULL && s->tree != s->root)
7844 got_object_tree_close(s->tree);
7845 if (s->root)
7846 got_object_tree_close(s->root);
7847 return NULL;
7850 static const struct got_error *
7851 search_start_tree_view(struct tog_view *view)
7853 struct tog_tree_view_state *s = &view->state.tree;
7855 s->matched_entry = NULL;
7856 return NULL;
7859 static int
7860 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7862 regmatch_t regmatch;
7864 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7865 0) == 0;
7868 static const struct got_error *
7869 search_next_tree_view(struct tog_view *view)
7871 struct tog_tree_view_state *s = &view->state.tree;
7872 struct got_tree_entry *te = NULL;
7874 if (!view->searching) {
7875 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7876 return NULL;
7879 if (s->matched_entry) {
7880 if (view->searching == TOG_SEARCH_FORWARD) {
7881 if (s->selected_entry)
7882 te = got_tree_entry_get_next(s->tree,
7883 s->selected_entry);
7884 else
7885 te = got_object_tree_get_first_entry(s->tree);
7886 } else {
7887 if (s->selected_entry == NULL)
7888 te = got_object_tree_get_last_entry(s->tree);
7889 else
7890 te = got_tree_entry_get_prev(s->tree,
7891 s->selected_entry);
7893 } else {
7894 if (s->selected_entry)
7895 te = s->selected_entry;
7896 else if (view->searching == TOG_SEARCH_FORWARD)
7897 te = got_object_tree_get_first_entry(s->tree);
7898 else
7899 te = got_object_tree_get_last_entry(s->tree);
7902 while (1) {
7903 if (te == NULL) {
7904 if (s->matched_entry == NULL) {
7905 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7906 return NULL;
7908 if (view->searching == TOG_SEARCH_FORWARD)
7909 te = got_object_tree_get_first_entry(s->tree);
7910 else
7911 te = got_object_tree_get_last_entry(s->tree);
7914 if (match_tree_entry(te, &view->regex)) {
7915 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7916 s->matched_entry = te;
7917 break;
7920 if (view->searching == TOG_SEARCH_FORWARD)
7921 te = got_tree_entry_get_next(s->tree, te);
7922 else
7923 te = got_tree_entry_get_prev(s->tree, te);
7926 if (s->matched_entry) {
7927 s->first_displayed_entry = s->matched_entry;
7928 s->selected = 0;
7931 return NULL;
7934 static const struct got_error *
7935 show_tree_view(struct tog_view *view)
7937 const struct got_error *err = NULL;
7938 struct tog_tree_view_state *s = &view->state.tree;
7939 char *parent_path;
7941 err = tree_entry_path(&parent_path, &s->parents, NULL);
7942 if (err)
7943 return err;
7945 err = draw_tree_entries(view, parent_path);
7946 free(parent_path);
7948 view_border(view);
7949 return err;
7952 static const struct got_error *
7953 tree_goto_line(struct tog_view *view, int nlines)
7955 const struct got_error *err = NULL;
7956 struct tog_tree_view_state *s = &view->state.tree;
7957 struct got_tree_entry **fte, **lte, **ste;
7958 int g, last, first = 1, i = 1;
7959 int root = s->tree == s->root;
7960 int off = root ? 1 : 2;
7962 g = view->gline;
7963 view->gline = 0;
7965 if (g == 0)
7966 g = 1;
7967 else if (g > got_object_tree_get_nentries(s->tree))
7968 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7970 fte = &s->first_displayed_entry;
7971 lte = &s->last_displayed_entry;
7972 ste = &s->selected_entry;
7974 if (*fte != NULL) {
7975 first = got_tree_entry_get_index(*fte);
7976 first += off; /* account for ".." */
7978 last = got_tree_entry_get_index(*lte);
7979 last += off;
7981 if (g >= first && g <= last && g - first < nlines) {
7982 s->selected = g - first;
7983 return NULL; /* gline is on the current page */
7986 if (*ste != NULL) {
7987 i = got_tree_entry_get_index(*ste);
7988 i += off;
7991 if (i < g) {
7992 err = tree_scroll_down(view, g - i);
7993 if (err)
7994 return err;
7995 if (got_tree_entry_get_index(*lte) >=
7996 got_object_tree_get_nentries(s->tree) - 1 &&
7997 first + s->selected < g &&
7998 s->selected < s->ndisplayed - 1) {
7999 first = got_tree_entry_get_index(*fte);
8000 first += off;
8001 s->selected = g - first;
8003 } else if (i > g)
8004 tree_scroll_up(s, i - g);
8006 if (g < nlines &&
8007 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
8008 s->selected = g - 1;
8010 return NULL;
8013 static const struct got_error *
8014 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
8016 const struct got_error *err = NULL;
8017 struct tog_tree_view_state *s = &view->state.tree;
8018 struct got_tree_entry *te;
8019 int n, nscroll = view->nlines - 3;
8021 if (view->gline)
8022 return tree_goto_line(view, nscroll);
8024 switch (ch) {
8025 case '0':
8026 case '$':
8027 case KEY_RIGHT:
8028 case 'l':
8029 case KEY_LEFT:
8030 case 'h':
8031 horizontal_scroll_input(view, ch);
8032 break;
8033 case 'i':
8034 s->show_ids = !s->show_ids;
8035 view->count = 0;
8036 break;
8037 case 'L':
8038 view->count = 0;
8039 if (!s->selected_entry)
8040 break;
8041 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8042 break;
8043 case 'R':
8044 view->count = 0;
8045 err = view_request_new(new_view, view, TOG_VIEW_REF);
8046 break;
8047 case 'g':
8048 case '=':
8049 case KEY_HOME:
8050 s->selected = 0;
8051 view->count = 0;
8052 if (s->tree == s->root)
8053 s->first_displayed_entry =
8054 got_object_tree_get_first_entry(s->tree);
8055 else
8056 s->first_displayed_entry = NULL;
8057 break;
8058 case 'G':
8059 case '*':
8060 case KEY_END: {
8061 int eos = view->nlines - 3;
8063 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8064 --eos; /* border */
8065 s->selected = 0;
8066 view->count = 0;
8067 te = got_object_tree_get_last_entry(s->tree);
8068 for (n = 0; n < eos; n++) {
8069 if (te == NULL) {
8070 if (s->tree != s->root) {
8071 s->first_displayed_entry = NULL;
8072 n++;
8074 break;
8076 s->first_displayed_entry = te;
8077 te = got_tree_entry_get_prev(s->tree, te);
8079 if (n > 0)
8080 s->selected = n - 1;
8081 break;
8083 case 'k':
8084 case KEY_UP:
8085 case CTRL('p'):
8086 if (s->selected > 0) {
8087 s->selected--;
8088 break;
8090 tree_scroll_up(s, 1);
8091 if (s->selected_entry == NULL ||
8092 (s->tree == s->root && s->selected_entry ==
8093 got_object_tree_get_first_entry(s->tree)))
8094 view->count = 0;
8095 break;
8096 case CTRL('u'):
8097 case 'u':
8098 nscroll /= 2;
8099 /* FALL THROUGH */
8100 case KEY_PPAGE:
8101 case CTRL('b'):
8102 case 'b':
8103 if (s->tree == s->root) {
8104 if (got_object_tree_get_first_entry(s->tree) ==
8105 s->first_displayed_entry)
8106 s->selected -= MIN(s->selected, nscroll);
8107 } else {
8108 if (s->first_displayed_entry == NULL)
8109 s->selected -= MIN(s->selected, nscroll);
8111 tree_scroll_up(s, MAX(0, nscroll));
8112 if (s->selected_entry == NULL ||
8113 (s->tree == s->root && s->selected_entry ==
8114 got_object_tree_get_first_entry(s->tree)))
8115 view->count = 0;
8116 break;
8117 case 'j':
8118 case KEY_DOWN:
8119 case CTRL('n'):
8120 if (s->selected < s->ndisplayed - 1) {
8121 s->selected++;
8122 break;
8124 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8125 == NULL) {
8126 /* can't scroll any further */
8127 view->count = 0;
8128 break;
8130 tree_scroll_down(view, 1);
8131 break;
8132 case CTRL('d'):
8133 case 'd':
8134 nscroll /= 2;
8135 /* FALL THROUGH */
8136 case KEY_NPAGE:
8137 case CTRL('f'):
8138 case 'f':
8139 case ' ':
8140 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8141 == NULL) {
8142 /* can't scroll any further; move cursor down */
8143 if (s->selected < s->ndisplayed - 1)
8144 s->selected += MIN(nscroll,
8145 s->ndisplayed - s->selected - 1);
8146 else
8147 view->count = 0;
8148 break;
8150 tree_scroll_down(view, nscroll);
8151 break;
8152 case KEY_ENTER:
8153 case '\r':
8154 case KEY_BACKSPACE:
8155 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8156 struct tog_parent_tree *parent;
8157 /* user selected '..' */
8158 if (s->tree == s->root) {
8159 view->count = 0;
8160 break;
8162 parent = TAILQ_FIRST(&s->parents);
8163 TAILQ_REMOVE(&s->parents, parent,
8164 entry);
8165 got_object_tree_close(s->tree);
8166 s->tree = parent->tree;
8167 s->first_displayed_entry =
8168 parent->first_displayed_entry;
8169 s->selected_entry =
8170 parent->selected_entry;
8171 s->selected = parent->selected;
8172 if (s->selected > view->nlines - 3) {
8173 err = offset_selection_down(view);
8174 if (err)
8175 break;
8177 free(parent);
8178 } else if (S_ISDIR(got_tree_entry_get_mode(
8179 s->selected_entry))) {
8180 struct got_tree_object *subtree;
8181 view->count = 0;
8182 err = got_object_open_as_tree(&subtree, s->repo,
8183 got_tree_entry_get_id(s->selected_entry));
8184 if (err)
8185 break;
8186 err = tree_view_visit_subtree(s, subtree);
8187 if (err) {
8188 got_object_tree_close(subtree);
8189 break;
8191 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8192 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8193 break;
8194 case KEY_RESIZE:
8195 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8196 s->selected = view->nlines - 4;
8197 view->count = 0;
8198 break;
8199 default:
8200 view->count = 0;
8201 break;
8204 return err;
8207 __dead static void
8208 usage_tree(void)
8210 endwin();
8211 fprintf(stderr,
8212 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8213 getprogname());
8214 exit(1);
8217 static const struct got_error *
8218 cmd_tree(int argc, char *argv[])
8220 const struct got_error *error;
8221 struct got_repository *repo = NULL;
8222 struct got_worktree *worktree = NULL;
8223 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8224 struct got_object_id *commit_id = NULL;
8225 struct got_commit_object *commit = NULL;
8226 const char *commit_id_arg = NULL;
8227 char *keyword_idstr = NULL, *label = NULL;
8228 struct got_reference *ref = NULL;
8229 const char *head_ref_name = NULL;
8230 int ch;
8231 struct tog_view *view;
8232 int *pack_fds = NULL;
8234 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8235 switch (ch) {
8236 case 'c':
8237 commit_id_arg = optarg;
8238 break;
8239 case 'r':
8240 repo_path = realpath(optarg, NULL);
8241 if (repo_path == NULL)
8242 return got_error_from_errno2("realpath",
8243 optarg);
8244 break;
8245 default:
8246 usage_tree();
8247 /* NOTREACHED */
8251 argc -= optind;
8252 argv += optind;
8254 if (argc > 1)
8255 usage_tree();
8257 error = got_repo_pack_fds_open(&pack_fds);
8258 if (error != NULL)
8259 goto done;
8261 if (repo_path == NULL) {
8262 cwd = getcwd(NULL, 0);
8263 if (cwd == NULL)
8264 return got_error_from_errno("getcwd");
8265 error = got_worktree_open(&worktree, cwd, NULL);
8266 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8267 goto done;
8268 if (worktree)
8269 repo_path =
8270 strdup(got_worktree_get_repo_path(worktree));
8271 else
8272 repo_path = strdup(cwd);
8273 if (repo_path == NULL) {
8274 error = got_error_from_errno("strdup");
8275 goto done;
8279 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8280 if (error != NULL)
8281 goto done;
8283 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8284 repo, worktree);
8285 if (error)
8286 goto done;
8288 init_curses();
8290 error = apply_unveil(got_repo_get_path(repo), NULL);
8291 if (error)
8292 goto done;
8294 error = tog_load_refs(repo, 0);
8295 if (error)
8296 goto done;
8298 if (commit_id_arg == NULL) {
8299 error = got_repo_match_object_id(&commit_id, &label,
8300 worktree ? got_worktree_get_head_ref_name(worktree) :
8301 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8302 if (error)
8303 goto done;
8304 head_ref_name = label;
8305 } else {
8306 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8307 repo, worktree);
8308 if (error != NULL)
8309 goto done;
8310 if (keyword_idstr != NULL)
8311 commit_id_arg = keyword_idstr;
8313 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8314 if (error == NULL)
8315 head_ref_name = got_ref_get_name(ref);
8316 else if (error->code != GOT_ERR_NOT_REF)
8317 goto done;
8318 error = got_repo_match_object_id(&commit_id, NULL,
8319 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8320 if (error)
8321 goto done;
8324 error = got_object_open_as_commit(&commit, repo, commit_id);
8325 if (error)
8326 goto done;
8328 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8329 if (view == NULL) {
8330 error = got_error_from_errno("view_open");
8331 goto done;
8333 error = open_tree_view(view, commit_id, head_ref_name, repo);
8334 if (error)
8335 goto done;
8336 if (!got_path_is_root_dir(in_repo_path)) {
8337 error = tree_view_walk_path(&view->state.tree, commit,
8338 in_repo_path);
8339 if (error)
8340 goto done;
8343 if (worktree) {
8344 error = set_tog_base_commit(repo, worktree);
8345 if (error != NULL)
8346 goto done;
8348 /* Release work tree lock. */
8349 got_worktree_close(worktree);
8350 worktree = NULL;
8353 error = view_loop(view);
8355 done:
8356 free(tog_base_commit.id);
8357 free(keyword_idstr);
8358 free(repo_path);
8359 free(cwd);
8360 free(commit_id);
8361 free(label);
8362 if (commit != NULL)
8363 got_object_commit_close(commit);
8364 if (ref)
8365 got_ref_close(ref);
8366 if (worktree != NULL)
8367 got_worktree_close(worktree);
8368 if (repo) {
8369 const struct got_error *close_err = got_repo_close(repo);
8370 if (error == NULL)
8371 error = close_err;
8373 if (pack_fds) {
8374 const struct got_error *pack_err =
8375 got_repo_pack_fds_close(pack_fds);
8376 if (error == NULL)
8377 error = pack_err;
8379 tog_free_refs();
8380 return error;
8383 static const struct got_error *
8384 ref_view_load_refs(struct tog_ref_view_state *s)
8386 struct got_reflist_entry *sre;
8387 struct tog_reflist_entry *re;
8389 s->nrefs = 0;
8390 TAILQ_FOREACH(sre, &tog_refs, entry) {
8391 if (strncmp(got_ref_get_name(sre->ref),
8392 "refs/got/", 9) == 0 &&
8393 strncmp(got_ref_get_name(sre->ref),
8394 "refs/got/backup/", 16) != 0)
8395 continue;
8397 re = malloc(sizeof(*re));
8398 if (re == NULL)
8399 return got_error_from_errno("malloc");
8401 re->ref = got_ref_dup(sre->ref);
8402 if (re->ref == NULL)
8403 return got_error_from_errno("got_ref_dup");
8404 re->idx = s->nrefs++;
8405 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8408 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8409 return NULL;
8412 static void
8413 ref_view_free_refs(struct tog_ref_view_state *s)
8415 struct tog_reflist_entry *re;
8417 while (!TAILQ_EMPTY(&s->refs)) {
8418 re = TAILQ_FIRST(&s->refs);
8419 TAILQ_REMOVE(&s->refs, re, entry);
8420 got_ref_close(re->ref);
8421 free(re);
8425 static const struct got_error *
8426 open_ref_view(struct tog_view *view, struct got_repository *repo)
8428 const struct got_error *err = NULL;
8429 struct tog_ref_view_state *s = &view->state.ref;
8431 s->selected_entry = 0;
8432 s->repo = repo;
8434 TAILQ_INIT(&s->refs);
8435 STAILQ_INIT(&s->colors);
8437 err = ref_view_load_refs(s);
8438 if (err)
8439 goto done;
8441 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8442 err = add_color(&s->colors, "^refs/heads/",
8443 TOG_COLOR_REFS_HEADS,
8444 get_color_value("TOG_COLOR_REFS_HEADS"));
8445 if (err)
8446 goto done;
8448 err = add_color(&s->colors, "^refs/tags/",
8449 TOG_COLOR_REFS_TAGS,
8450 get_color_value("TOG_COLOR_REFS_TAGS"));
8451 if (err)
8452 goto done;
8454 err = add_color(&s->colors, "^refs/remotes/",
8455 TOG_COLOR_REFS_REMOTES,
8456 get_color_value("TOG_COLOR_REFS_REMOTES"));
8457 if (err)
8458 goto done;
8460 err = add_color(&s->colors, "^refs/got/backup/",
8461 TOG_COLOR_REFS_BACKUP,
8462 get_color_value("TOG_COLOR_REFS_BACKUP"));
8463 if (err)
8464 goto done;
8467 view->show = show_ref_view;
8468 view->input = input_ref_view;
8469 view->close = close_ref_view;
8470 view->search_start = search_start_ref_view;
8471 view->search_next = search_next_ref_view;
8472 done:
8473 if (err) {
8474 if (view->close == NULL)
8475 close_ref_view(view);
8476 view_close(view);
8478 return err;
8481 static const struct got_error *
8482 close_ref_view(struct tog_view *view)
8484 struct tog_ref_view_state *s = &view->state.ref;
8486 ref_view_free_refs(s);
8487 free_colors(&s->colors);
8489 return NULL;
8492 static const struct got_error *
8493 resolve_reflist_entry(struct got_object_id **commit_id,
8494 struct tog_reflist_entry *re, struct got_repository *repo)
8496 const struct got_error *err = NULL;
8497 struct got_object_id *obj_id;
8498 struct got_tag_object *tag = NULL;
8499 int obj_type;
8501 *commit_id = NULL;
8503 err = got_ref_resolve(&obj_id, repo, re->ref);
8504 if (err)
8505 return err;
8507 err = got_object_get_type(&obj_type, repo, obj_id);
8508 if (err)
8509 goto done;
8511 switch (obj_type) {
8512 case GOT_OBJ_TYPE_COMMIT:
8513 *commit_id = obj_id;
8514 break;
8515 case GOT_OBJ_TYPE_TAG:
8516 err = got_object_open_as_tag(&tag, repo, obj_id);
8517 if (err)
8518 goto done;
8519 free(obj_id);
8520 err = got_object_get_type(&obj_type, repo,
8521 got_object_tag_get_object_id(tag));
8522 if (err)
8523 goto done;
8524 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8525 err = got_error(GOT_ERR_OBJ_TYPE);
8526 goto done;
8528 *commit_id = got_object_id_dup(
8529 got_object_tag_get_object_id(tag));
8530 if (*commit_id == NULL) {
8531 err = got_error_from_errno("got_object_id_dup");
8532 goto done;
8534 break;
8535 default:
8536 err = got_error(GOT_ERR_OBJ_TYPE);
8537 break;
8540 done:
8541 if (tag)
8542 got_object_tag_close(tag);
8543 if (err) {
8544 free(*commit_id);
8545 *commit_id = NULL;
8547 return err;
8550 static const struct got_error *
8551 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8552 struct tog_reflist_entry *re, struct got_repository *repo)
8554 struct tog_view *log_view;
8555 const struct got_error *err = NULL;
8556 struct got_object_id *commit_id = NULL;
8558 *new_view = NULL;
8560 err = resolve_reflist_entry(&commit_id, re, repo);
8561 if (err) {
8562 if (err->code != GOT_ERR_OBJ_TYPE)
8563 return err;
8564 else
8565 return NULL;
8568 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8569 if (log_view == NULL) {
8570 err = got_error_from_errno("view_open");
8571 goto done;
8574 err = open_log_view(log_view, commit_id, repo,
8575 got_ref_get_name(re->ref), "", 0, NULL);
8576 done:
8577 if (err)
8578 view_close(log_view);
8579 else
8580 *new_view = log_view;
8581 free(commit_id);
8582 return err;
8585 static void
8586 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8588 struct tog_reflist_entry *re;
8589 int i = 0;
8591 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8592 return;
8594 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8595 while (i++ < maxscroll) {
8596 if (re == NULL)
8597 break;
8598 s->first_displayed_entry = re;
8599 re = TAILQ_PREV(re, tog_reflist_head, entry);
8603 static const struct got_error *
8604 ref_scroll_down(struct tog_view *view, int maxscroll)
8606 struct tog_ref_view_state *s = &view->state.ref;
8607 struct tog_reflist_entry *next, *last;
8608 int n = 0;
8610 if (s->first_displayed_entry)
8611 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8612 else
8613 next = TAILQ_FIRST(&s->refs);
8615 last = s->last_displayed_entry;
8616 while (next && n++ < maxscroll) {
8617 if (last) {
8618 s->last_displayed_entry = last;
8619 last = TAILQ_NEXT(last, entry);
8621 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8622 s->first_displayed_entry = next;
8623 next = TAILQ_NEXT(next, entry);
8627 return NULL;
8630 static const struct got_error *
8631 search_start_ref_view(struct tog_view *view)
8633 struct tog_ref_view_state *s = &view->state.ref;
8635 s->matched_entry = NULL;
8636 return NULL;
8639 static int
8640 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8642 regmatch_t regmatch;
8644 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8645 0) == 0;
8648 static const struct got_error *
8649 search_next_ref_view(struct tog_view *view)
8651 struct tog_ref_view_state *s = &view->state.ref;
8652 struct tog_reflist_entry *re = NULL;
8654 if (!view->searching) {
8655 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8656 return NULL;
8659 if (s->matched_entry) {
8660 if (view->searching == TOG_SEARCH_FORWARD) {
8661 if (s->selected_entry)
8662 re = TAILQ_NEXT(s->selected_entry, entry);
8663 else
8664 re = TAILQ_PREV(s->selected_entry,
8665 tog_reflist_head, entry);
8666 } else {
8667 if (s->selected_entry == NULL)
8668 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8669 else
8670 re = TAILQ_PREV(s->selected_entry,
8671 tog_reflist_head, entry);
8673 } else {
8674 if (s->selected_entry)
8675 re = s->selected_entry;
8676 else if (view->searching == TOG_SEARCH_FORWARD)
8677 re = TAILQ_FIRST(&s->refs);
8678 else
8679 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8682 while (1) {
8683 if (re == NULL) {
8684 if (s->matched_entry == NULL) {
8685 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8686 return NULL;
8688 if (view->searching == TOG_SEARCH_FORWARD)
8689 re = TAILQ_FIRST(&s->refs);
8690 else
8691 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8694 if (match_reflist_entry(re, &view->regex)) {
8695 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8696 s->matched_entry = re;
8697 break;
8700 if (view->searching == TOG_SEARCH_FORWARD)
8701 re = TAILQ_NEXT(re, entry);
8702 else
8703 re = TAILQ_PREV(re, tog_reflist_head, entry);
8706 if (s->matched_entry) {
8707 s->first_displayed_entry = s->matched_entry;
8708 s->selected = 0;
8711 return NULL;
8714 static const struct got_error *
8715 show_ref_view(struct tog_view *view)
8717 const struct got_error *err = NULL;
8718 struct tog_ref_view_state *s = &view->state.ref;
8719 struct tog_reflist_entry *re;
8720 char *line = NULL;
8721 wchar_t *wline;
8722 struct tog_color *tc;
8723 int width, n, scrollx;
8724 int limit = view->nlines;
8726 werase(view->window);
8728 s->ndisplayed = 0;
8729 if (view_is_hsplit_top(view))
8730 --limit; /* border */
8732 if (limit == 0)
8733 return NULL;
8735 re = s->first_displayed_entry;
8737 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8738 s->nrefs) == -1)
8739 return got_error_from_errno("asprintf");
8741 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8742 if (err) {
8743 free(line);
8744 return err;
8746 if (view_needs_focus_indication(view))
8747 wstandout(view->window);
8748 waddwstr(view->window, wline);
8749 while (width++ < view->ncols)
8750 waddch(view->window, ' ');
8751 if (view_needs_focus_indication(view))
8752 wstandend(view->window);
8753 free(wline);
8754 wline = NULL;
8755 free(line);
8756 line = NULL;
8757 if (--limit <= 0)
8758 return NULL;
8760 n = 0;
8761 view->maxx = 0;
8762 while (re && limit > 0) {
8763 char *line = NULL;
8764 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8766 if (s->show_date) {
8767 struct got_commit_object *ci;
8768 struct got_tag_object *tag;
8769 struct got_object_id *id;
8770 struct tm tm;
8771 time_t t;
8773 err = got_ref_resolve(&id, s->repo, re->ref);
8774 if (err)
8775 return err;
8776 err = got_object_open_as_tag(&tag, s->repo, id);
8777 if (err) {
8778 if (err->code != GOT_ERR_OBJ_TYPE) {
8779 free(id);
8780 return err;
8782 err = got_object_open_as_commit(&ci, s->repo,
8783 id);
8784 if (err) {
8785 free(id);
8786 return err;
8788 t = got_object_commit_get_committer_time(ci);
8789 got_object_commit_close(ci);
8790 } else {
8791 t = got_object_tag_get_tagger_time(tag);
8792 got_object_tag_close(tag);
8794 free(id);
8795 if (gmtime_r(&t, &tm) == NULL)
8796 return got_error_from_errno("gmtime_r");
8797 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8798 return got_error(GOT_ERR_NO_SPACE);
8800 if (got_ref_is_symbolic(re->ref)) {
8801 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8802 ymd : "", got_ref_get_name(re->ref),
8803 got_ref_get_symref_target(re->ref)) == -1)
8804 return got_error_from_errno("asprintf");
8805 } else if (s->show_ids) {
8806 struct got_object_id *id;
8807 char *id_str;
8808 err = got_ref_resolve(&id, s->repo, re->ref);
8809 if (err)
8810 return err;
8811 err = got_object_id_str(&id_str, id);
8812 if (err) {
8813 free(id);
8814 return err;
8816 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8817 got_ref_get_name(re->ref), id_str) == -1) {
8818 err = got_error_from_errno("asprintf");
8819 free(id);
8820 free(id_str);
8821 return err;
8823 free(id);
8824 free(id_str);
8825 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8826 got_ref_get_name(re->ref)) == -1)
8827 return got_error_from_errno("asprintf");
8829 /* use full line width to determine view->maxx */
8830 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8831 if (err) {
8832 free(line);
8833 return err;
8835 view->maxx = MAX(view->maxx, width);
8836 free(wline);
8837 wline = NULL;
8839 err = format_line(&wline, &width, &scrollx, line, view->x,
8840 view->ncols, 0, 0);
8841 if (err) {
8842 free(line);
8843 return err;
8845 if (n == s->selected) {
8846 if (view->focussed)
8847 wstandout(view->window);
8848 s->selected_entry = re;
8850 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8851 if (tc)
8852 wattr_on(view->window,
8853 COLOR_PAIR(tc->colorpair), NULL);
8854 waddwstr(view->window, &wline[scrollx]);
8855 if (tc)
8856 wattr_off(view->window,
8857 COLOR_PAIR(tc->colorpair), NULL);
8858 if (width < view->ncols)
8859 waddch(view->window, '\n');
8860 if (n == s->selected && view->focussed)
8861 wstandend(view->window);
8862 free(line);
8863 free(wline);
8864 wline = NULL;
8865 n++;
8866 s->ndisplayed++;
8867 s->last_displayed_entry = re;
8869 limit--;
8870 re = TAILQ_NEXT(re, entry);
8873 view_border(view);
8874 return err;
8877 static const struct got_error *
8878 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8879 struct tog_reflist_entry *re, struct got_repository *repo)
8881 const struct got_error *err = NULL;
8882 struct got_object_id *commit_id = NULL;
8883 struct tog_view *tree_view;
8885 *new_view = NULL;
8887 err = resolve_reflist_entry(&commit_id, re, repo);
8888 if (err) {
8889 if (err->code != GOT_ERR_OBJ_TYPE)
8890 return err;
8891 else
8892 return NULL;
8896 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8897 if (tree_view == NULL) {
8898 err = got_error_from_errno("view_open");
8899 goto done;
8902 err = open_tree_view(tree_view, commit_id,
8903 got_ref_get_name(re->ref), repo);
8904 if (err)
8905 goto done;
8907 *new_view = tree_view;
8908 done:
8909 free(commit_id);
8910 return err;
8913 static const struct got_error *
8914 ref_goto_line(struct tog_view *view, int nlines)
8916 const struct got_error *err = NULL;
8917 struct tog_ref_view_state *s = &view->state.ref;
8918 int g, idx = s->selected_entry->idx;
8920 g = view->gline;
8921 view->gline = 0;
8923 if (g == 0)
8924 g = 1;
8925 else if (g > s->nrefs)
8926 g = s->nrefs;
8928 if (g >= s->first_displayed_entry->idx + 1 &&
8929 g <= s->last_displayed_entry->idx + 1 &&
8930 g - s->first_displayed_entry->idx - 1 < nlines) {
8931 s->selected = g - s->first_displayed_entry->idx - 1;
8932 return NULL;
8935 if (idx + 1 < g) {
8936 err = ref_scroll_down(view, g - idx - 1);
8937 if (err)
8938 return err;
8939 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8940 s->first_displayed_entry->idx + s->selected < g &&
8941 s->selected < s->ndisplayed - 1)
8942 s->selected = g - s->first_displayed_entry->idx - 1;
8943 } else if (idx + 1 > g)
8944 ref_scroll_up(s, idx - g + 1);
8946 if (g < nlines && s->first_displayed_entry->idx == 0)
8947 s->selected = g - 1;
8949 return NULL;
8953 static const struct got_error *
8954 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8956 const struct got_error *err = NULL;
8957 struct tog_ref_view_state *s = &view->state.ref;
8958 struct tog_reflist_entry *re;
8959 int n, nscroll = view->nlines - 1;
8961 if (view->gline)
8962 return ref_goto_line(view, nscroll);
8964 switch (ch) {
8965 case '0':
8966 case '$':
8967 case KEY_RIGHT:
8968 case 'l':
8969 case KEY_LEFT:
8970 case 'h':
8971 horizontal_scroll_input(view, ch);
8972 break;
8973 case 'i':
8974 s->show_ids = !s->show_ids;
8975 view->count = 0;
8976 break;
8977 case 'm':
8978 s->show_date = !s->show_date;
8979 view->count = 0;
8980 break;
8981 case 'o':
8982 s->sort_by_date = !s->sort_by_date;
8983 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8984 view->count = 0;
8985 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8986 got_ref_cmp_by_commit_timestamp_descending :
8987 tog_ref_cmp_by_name, s->repo);
8988 if (err)
8989 break;
8990 got_reflist_object_id_map_free(tog_refs_idmap);
8991 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8992 &tog_refs, s->repo);
8993 if (err)
8994 break;
8995 ref_view_free_refs(s);
8996 err = ref_view_load_refs(s);
8997 break;
8998 case KEY_ENTER:
8999 case '\r':
9000 view->count = 0;
9001 if (!s->selected_entry)
9002 break;
9003 err = view_request_new(new_view, view, TOG_VIEW_LOG);
9004 break;
9005 case 'T':
9006 view->count = 0;
9007 if (!s->selected_entry)
9008 break;
9009 err = view_request_new(new_view, view, TOG_VIEW_TREE);
9010 break;
9011 case 'g':
9012 case '=':
9013 case KEY_HOME:
9014 s->selected = 0;
9015 view->count = 0;
9016 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
9017 break;
9018 case 'G':
9019 case '*':
9020 case KEY_END: {
9021 int eos = view->nlines - 1;
9023 if (view->mode == TOG_VIEW_SPLIT_HRZN)
9024 --eos; /* border */
9025 s->selected = 0;
9026 view->count = 0;
9027 re = TAILQ_LAST(&s->refs, tog_reflist_head);
9028 for (n = 0; n < eos; n++) {
9029 if (re == NULL)
9030 break;
9031 s->first_displayed_entry = re;
9032 re = TAILQ_PREV(re, tog_reflist_head, entry);
9034 if (n > 0)
9035 s->selected = n - 1;
9036 break;
9038 case 'k':
9039 case KEY_UP:
9040 case CTRL('p'):
9041 if (s->selected > 0) {
9042 s->selected--;
9043 break;
9045 ref_scroll_up(s, 1);
9046 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9047 view->count = 0;
9048 break;
9049 case CTRL('u'):
9050 case 'u':
9051 nscroll /= 2;
9052 /* FALL THROUGH */
9053 case KEY_PPAGE:
9054 case CTRL('b'):
9055 case 'b':
9056 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
9057 s->selected -= MIN(nscroll, s->selected);
9058 ref_scroll_up(s, MAX(0, nscroll));
9059 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9060 view->count = 0;
9061 break;
9062 case 'j':
9063 case KEY_DOWN:
9064 case CTRL('n'):
9065 if (s->selected < s->ndisplayed - 1) {
9066 s->selected++;
9067 break;
9069 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9070 /* can't scroll any further */
9071 view->count = 0;
9072 break;
9074 ref_scroll_down(view, 1);
9075 break;
9076 case CTRL('d'):
9077 case 'd':
9078 nscroll /= 2;
9079 /* FALL THROUGH */
9080 case KEY_NPAGE:
9081 case CTRL('f'):
9082 case 'f':
9083 case ' ':
9084 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9085 /* can't scroll any further; move cursor down */
9086 if (s->selected < s->ndisplayed - 1)
9087 s->selected += MIN(nscroll,
9088 s->ndisplayed - s->selected - 1);
9089 if (view->count > 1 && s->selected < s->ndisplayed - 1)
9090 s->selected += s->ndisplayed - s->selected - 1;
9091 view->count = 0;
9092 break;
9094 ref_scroll_down(view, nscroll);
9095 break;
9096 case CTRL('l'):
9097 view->count = 0;
9098 tog_free_refs();
9099 err = tog_load_refs(s->repo, s->sort_by_date);
9100 if (err)
9101 break;
9102 ref_view_free_refs(s);
9103 err = ref_view_load_refs(s);
9104 break;
9105 case KEY_RESIZE:
9106 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
9107 s->selected = view->nlines - 2;
9108 break;
9109 default:
9110 view->count = 0;
9111 break;
9114 return err;
9117 __dead static void
9118 usage_ref(void)
9120 endwin();
9121 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
9122 getprogname());
9123 exit(1);
9126 static const struct got_error *
9127 cmd_ref(int argc, char *argv[])
9129 const struct got_error *error;
9130 struct got_repository *repo = NULL;
9131 struct got_worktree *worktree = NULL;
9132 char *cwd = NULL, *repo_path = NULL;
9133 int ch;
9134 struct tog_view *view;
9135 int *pack_fds = NULL;
9137 while ((ch = getopt(argc, argv, "r:")) != -1) {
9138 switch (ch) {
9139 case 'r':
9140 repo_path = realpath(optarg, NULL);
9141 if (repo_path == NULL)
9142 return got_error_from_errno2("realpath",
9143 optarg);
9144 break;
9145 default:
9146 usage_ref();
9147 /* NOTREACHED */
9151 argc -= optind;
9152 argv += optind;
9154 if (argc > 1)
9155 usage_ref();
9157 error = got_repo_pack_fds_open(&pack_fds);
9158 if (error != NULL)
9159 goto done;
9161 if (repo_path == NULL) {
9162 cwd = getcwd(NULL, 0);
9163 if (cwd == NULL)
9164 return got_error_from_errno("getcwd");
9165 error = got_worktree_open(&worktree, cwd, NULL);
9166 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9167 goto done;
9168 if (worktree)
9169 repo_path =
9170 strdup(got_worktree_get_repo_path(worktree));
9171 else
9172 repo_path = strdup(cwd);
9173 if (repo_path == NULL) {
9174 error = got_error_from_errno("strdup");
9175 goto done;
9179 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9180 if (error != NULL)
9181 goto done;
9183 init_curses();
9185 error = apply_unveil(got_repo_get_path(repo), NULL);
9186 if (error)
9187 goto done;
9189 error = tog_load_refs(repo, 0);
9190 if (error)
9191 goto done;
9193 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9194 if (view == NULL) {
9195 error = got_error_from_errno("view_open");
9196 goto done;
9199 error = open_ref_view(view, repo);
9200 if (error)
9201 goto done;
9203 if (worktree) {
9204 error = set_tog_base_commit(repo, worktree);
9205 if (error != NULL)
9206 goto done;
9208 /* Release work tree lock. */
9209 got_worktree_close(worktree);
9210 worktree = NULL;
9213 error = view_loop(view);
9215 done:
9216 free(tog_base_commit.id);
9217 free(repo_path);
9218 free(cwd);
9219 if (worktree != NULL)
9220 got_worktree_close(worktree);
9221 if (repo) {
9222 const struct got_error *close_err = got_repo_close(repo);
9223 if (close_err)
9224 error = close_err;
9226 if (pack_fds) {
9227 const struct got_error *pack_err =
9228 got_repo_pack_fds_close(pack_fds);
9229 if (error == NULL)
9230 error = pack_err;
9232 tog_free_refs();
9233 return error;
9236 static const struct got_error*
9237 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9238 const char *str)
9240 size_t len;
9242 if (win == NULL)
9243 win = stdscr;
9245 len = strlen(str);
9246 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9248 if (focus)
9249 wstandout(win);
9250 if (mvwprintw(win, y, x, "%s", str) == ERR)
9251 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9252 if (focus)
9253 wstandend(win);
9255 return NULL;
9258 static const struct got_error *
9259 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9261 off_t *p;
9263 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9264 if (p == NULL) {
9265 free(*line_offsets);
9266 *line_offsets = NULL;
9267 return got_error_from_errno("reallocarray");
9270 *line_offsets = p;
9271 (*line_offsets)[*nlines] = off;
9272 ++(*nlines);
9273 return NULL;
9276 static const struct got_error *
9277 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9279 *ret = 0;
9281 for (;n > 0; --n, ++km) {
9282 char *t0, *t, *k;
9283 size_t len = 1;
9285 if (km->keys == NULL)
9286 continue;
9288 t = t0 = strdup(km->keys);
9289 if (t0 == NULL)
9290 return got_error_from_errno("strdup");
9292 len += strlen(t);
9293 while ((k = strsep(&t, " ")) != NULL)
9294 len += strlen(k) > 1 ? 2 : 0;
9295 free(t0);
9296 *ret = MAX(*ret, len);
9299 return NULL;
9303 * Write keymap section headers, keys, and key info in km to f.
9304 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9305 * wrap control and symbolic keys in guillemets, else use <>.
9307 static const struct got_error *
9308 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9310 int n, len = width;
9312 if (km->keys) {
9313 static const char *u8_glyph[] = {
9314 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9315 "\xe2\x80\xba" /* U+203A (utf8 >) */
9317 char *t0, *t, *k;
9318 int cs, s, first = 1;
9320 cs = got_locale_is_utf8();
9322 t = t0 = strdup(km->keys);
9323 if (t0 == NULL)
9324 return got_error_from_errno("strdup");
9326 len = strlen(km->keys);
9327 while ((k = strsep(&t, " ")) != NULL) {
9328 s = strlen(k) > 1; /* control or symbolic key */
9329 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9330 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9331 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9332 if (n < 0) {
9333 free(t0);
9334 return got_error_from_errno("fprintf");
9336 first = 0;
9337 len += s ? 2 : 0;
9338 *off += n;
9340 free(t0);
9342 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9343 if (n < 0)
9344 return got_error_from_errno("fprintf");
9345 *off += n;
9347 return NULL;
9350 static const struct got_error *
9351 format_help(struct tog_help_view_state *s)
9353 const struct got_error *err = NULL;
9354 off_t off = 0;
9355 int i, max, n, show = s->all;
9356 static const struct tog_key_map km[] = {
9357 #define KEYMAP_(info, type) { NULL, (info), type }
9358 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9359 GENERATE_HELP
9360 #undef KEYMAP_
9361 #undef KEY_
9364 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9365 if (err)
9366 return err;
9368 n = nitems(km);
9369 err = max_key_str(&max, km, n);
9370 if (err)
9371 return err;
9373 for (i = 0; i < n; ++i) {
9374 if (km[i].keys == NULL) {
9375 show = s->all;
9376 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9377 km[i].type == s->type || s->all)
9378 show = 1;
9380 if (show) {
9381 err = format_help_line(&off, s->f, &km[i], max);
9382 if (err)
9383 return err;
9384 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9385 if (err)
9386 return err;
9389 fputc('\n', s->f);
9390 ++off;
9391 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9392 return err;
9395 static const struct got_error *
9396 create_help(struct tog_help_view_state *s)
9398 FILE *f;
9399 const struct got_error *err;
9401 free(s->line_offsets);
9402 s->line_offsets = NULL;
9403 s->nlines = 0;
9405 f = got_opentemp();
9406 if (f == NULL)
9407 return got_error_from_errno("got_opentemp");
9408 s->f = f;
9410 err = format_help(s);
9411 if (err)
9412 return err;
9414 if (s->f && fflush(s->f) != 0)
9415 return got_error_from_errno("fflush");
9417 return NULL;
9420 static const struct got_error *
9421 search_start_help_view(struct tog_view *view)
9423 view->state.help.matched_line = 0;
9424 return NULL;
9427 static void
9428 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9429 size_t *nlines, int **first, int **last, int **match, int **selected)
9431 struct tog_help_view_state *s = &view->state.help;
9433 *f = s->f;
9434 *nlines = s->nlines;
9435 *line_offsets = s->line_offsets;
9436 *match = &s->matched_line;
9437 *first = &s->first_displayed_line;
9438 *last = &s->last_displayed_line;
9439 *selected = &s->selected_line;
9442 static const struct got_error *
9443 show_help_view(struct tog_view *view)
9445 struct tog_help_view_state *s = &view->state.help;
9446 const struct got_error *err;
9447 regmatch_t *regmatch = &view->regmatch;
9448 wchar_t *wline;
9449 char *line;
9450 ssize_t linelen;
9451 size_t linesz = 0;
9452 int width, nprinted = 0, rc = 0;
9453 int eos = view->nlines;
9455 if (view_is_hsplit_top(view))
9456 --eos; /* account for border */
9458 s->lineno = 0;
9459 rewind(s->f);
9460 werase(view->window);
9462 if (view->gline > s->nlines - 1)
9463 view->gline = s->nlines - 1;
9465 err = win_draw_center(view->window, 0, 0, view->ncols,
9466 view_needs_focus_indication(view),
9467 "tog help (press q to return to tog)");
9468 if (err)
9469 return err;
9470 if (eos <= 1)
9471 return NULL;
9472 waddstr(view->window, "\n\n");
9473 eos -= 2;
9475 s->eof = 0;
9476 view->maxx = 0;
9477 line = NULL;
9478 while (eos > 0 && nprinted < eos) {
9479 attr_t attr = 0;
9481 linelen = getline(&line, &linesz, s->f);
9482 if (linelen == -1) {
9483 if (!feof(s->f)) {
9484 free(line);
9485 return got_ferror(s->f, GOT_ERR_IO);
9487 s->eof = 1;
9488 break;
9490 if (++s->lineno < s->first_displayed_line)
9491 continue;
9492 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9493 continue;
9494 if (s->lineno == view->hiline)
9495 attr = A_STANDOUT;
9497 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9498 view->x ? 1 : 0);
9499 if (err) {
9500 free(line);
9501 return err;
9503 view->maxx = MAX(view->maxx, width);
9504 free(wline);
9505 wline = NULL;
9507 if (attr)
9508 wattron(view->window, attr);
9509 if (s->first_displayed_line + nprinted == s->matched_line &&
9510 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9511 err = add_matched_line(&width, line, view->ncols - 1, 0,
9512 view->window, view->x, regmatch);
9513 if (err) {
9514 free(line);
9515 return err;
9517 } else {
9518 int skip;
9520 err = format_line(&wline, &width, &skip, line,
9521 view->x, view->ncols, 0, view->x ? 1 : 0);
9522 if (err) {
9523 free(line);
9524 return err;
9526 waddwstr(view->window, &wline[skip]);
9527 free(wline);
9528 wline = NULL;
9530 if (s->lineno == view->hiline) {
9531 while (width++ < view->ncols)
9532 waddch(view->window, ' ');
9533 } else {
9534 if (width < view->ncols)
9535 waddch(view->window, '\n');
9537 if (attr)
9538 wattroff(view->window, attr);
9539 if (++nprinted == 1)
9540 s->first_displayed_line = s->lineno;
9542 free(line);
9543 if (nprinted > 0)
9544 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9545 else
9546 s->last_displayed_line = s->first_displayed_line;
9548 view_border(view);
9550 if (s->eof) {
9551 rc = waddnstr(view->window,
9552 "See the tog(1) manual page for full documentation",
9553 view->ncols - 1);
9554 if (rc == ERR)
9555 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9556 } else {
9557 wmove(view->window, view->nlines - 1, 0);
9558 wclrtoeol(view->window);
9559 wstandout(view->window);
9560 rc = waddnstr(view->window, "scroll down for more...",
9561 view->ncols - 1);
9562 if (rc == ERR)
9563 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9564 if (getcurx(view->window) < view->ncols - 6) {
9565 rc = wprintw(view->window, "[%.0f%%]",
9566 100.00 * s->last_displayed_line / s->nlines);
9567 if (rc == ERR)
9568 return got_error_msg(GOT_ERR_IO, "wprintw");
9570 wstandend(view->window);
9573 return NULL;
9576 static const struct got_error *
9577 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9579 struct tog_help_view_state *s = &view->state.help;
9580 const struct got_error *err = NULL;
9581 char *line = NULL;
9582 ssize_t linelen;
9583 size_t linesz = 0;
9584 int eos, nscroll;
9586 eos = nscroll = view->nlines;
9587 if (view_is_hsplit_top(view))
9588 --eos; /* border */
9590 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9592 switch (ch) {
9593 case '0':
9594 case '$':
9595 case KEY_RIGHT:
9596 case 'l':
9597 case KEY_LEFT:
9598 case 'h':
9599 horizontal_scroll_input(view, ch);
9600 break;
9601 case 'g':
9602 case KEY_HOME:
9603 s->first_displayed_line = 1;
9604 view->count = 0;
9605 break;
9606 case 'G':
9607 case KEY_END:
9608 view->count = 0;
9609 if (s->eof)
9610 break;
9611 s->first_displayed_line = (s->nlines - eos) + 3;
9612 s->eof = 1;
9613 break;
9614 case 'k':
9615 case KEY_UP:
9616 if (s->first_displayed_line > 1)
9617 --s->first_displayed_line;
9618 else
9619 view->count = 0;
9620 break;
9621 case CTRL('u'):
9622 case 'u':
9623 nscroll /= 2;
9624 /* FALL THROUGH */
9625 case KEY_PPAGE:
9626 case CTRL('b'):
9627 case 'b':
9628 if (s->first_displayed_line == 1) {
9629 view->count = 0;
9630 break;
9632 while (--nscroll > 0 && s->first_displayed_line > 1)
9633 s->first_displayed_line--;
9634 break;
9635 case 'j':
9636 case KEY_DOWN:
9637 case CTRL('n'):
9638 if (!s->eof)
9639 ++s->first_displayed_line;
9640 else
9641 view->count = 0;
9642 break;
9643 case CTRL('d'):
9644 case 'd':
9645 nscroll /= 2;
9646 /* FALL THROUGH */
9647 case KEY_NPAGE:
9648 case CTRL('f'):
9649 case 'f':
9650 case ' ':
9651 if (s->eof) {
9652 view->count = 0;
9653 break;
9655 while (!s->eof && --nscroll > 0) {
9656 linelen = getline(&line, &linesz, s->f);
9657 s->first_displayed_line++;
9658 if (linelen == -1) {
9659 if (feof(s->f))
9660 s->eof = 1;
9661 else
9662 err = got_ferror(s->f, GOT_ERR_IO);
9663 break;
9666 free(line);
9667 break;
9668 default:
9669 view->count = 0;
9670 break;
9673 return err;
9676 static const struct got_error *
9677 close_help_view(struct tog_view *view)
9679 struct tog_help_view_state *s = &view->state.help;
9681 free(s->line_offsets);
9682 s->line_offsets = NULL;
9683 if (fclose(s->f) == EOF)
9684 return got_error_from_errno("fclose");
9686 return NULL;
9689 static const struct got_error *
9690 reset_help_view(struct tog_view *view)
9692 struct tog_help_view_state *s = &view->state.help;
9695 if (s->f && fclose(s->f) == EOF)
9696 return got_error_from_errno("fclose");
9698 wclear(view->window);
9699 view->count = 0;
9700 view->x = 0;
9701 s->all = !s->all;
9702 s->first_displayed_line = 1;
9703 s->last_displayed_line = view->nlines;
9704 s->matched_line = 0;
9706 return create_help(s);
9709 static const struct got_error *
9710 open_help_view(struct tog_view *view, struct tog_view *parent)
9712 const struct got_error *err = NULL;
9713 struct tog_help_view_state *s = &view->state.help;
9715 s->type = (enum tog_keymap_type)parent->type;
9716 s->first_displayed_line = 1;
9717 s->last_displayed_line = view->nlines;
9718 s->selected_line = 1;
9720 view->show = show_help_view;
9721 view->input = input_help_view;
9722 view->reset = reset_help_view;
9723 view->close = close_help_view;
9724 view->search_start = search_start_help_view;
9725 view->search_setup = search_setup_help_view;
9726 view->search_next = search_next_view_match;
9728 err = create_help(s);
9729 return err;
9732 static const struct got_error *
9733 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9734 enum tog_view_type request, int y, int x)
9736 const struct got_error *err = NULL;
9738 *new_view = NULL;
9740 switch (request) {
9741 case TOG_VIEW_DIFF:
9742 if (view->type == TOG_VIEW_LOG) {
9743 struct tog_log_view_state *s = &view->state.log;
9745 err = open_diff_view_for_commit(new_view, y, x,
9746 s->selected_entry->commit, s->selected_entry->id,
9747 view, s->repo);
9748 } else
9749 return got_error_msg(GOT_ERR_NOT_IMPL,
9750 "parent/child view pair not supported");
9751 break;
9752 case TOG_VIEW_BLAME:
9753 if (view->type == TOG_VIEW_TREE) {
9754 struct tog_tree_view_state *s = &view->state.tree;
9756 err = blame_tree_entry(new_view, y, x,
9757 s->selected_entry, &s->parents, s->commit_id,
9758 s->repo);
9759 } else
9760 return got_error_msg(GOT_ERR_NOT_IMPL,
9761 "parent/child view pair not supported");
9762 break;
9763 case TOG_VIEW_LOG:
9764 if (view->type == TOG_VIEW_BLAME)
9765 err = log_annotated_line(new_view, y, x,
9766 view->state.blame.repo, view->state.blame.id_to_log);
9767 else if (view->type == TOG_VIEW_TREE)
9768 err = log_selected_tree_entry(new_view, y, x,
9769 &view->state.tree);
9770 else if (view->type == TOG_VIEW_REF)
9771 err = log_ref_entry(new_view, y, x,
9772 view->state.ref.selected_entry,
9773 view->state.ref.repo);
9774 else
9775 return got_error_msg(GOT_ERR_NOT_IMPL,
9776 "parent/child view pair not supported");
9777 break;
9778 case TOG_VIEW_TREE:
9779 if (view->type == TOG_VIEW_LOG)
9780 err = browse_commit_tree(new_view, y, x,
9781 view->state.log.selected_entry,
9782 view->state.log.in_repo_path,
9783 view->state.log.head_ref_name,
9784 view->state.log.repo);
9785 else if (view->type == TOG_VIEW_REF)
9786 err = browse_ref_tree(new_view, y, x,
9787 view->state.ref.selected_entry,
9788 view->state.ref.repo);
9789 else
9790 return got_error_msg(GOT_ERR_NOT_IMPL,
9791 "parent/child view pair not supported");
9792 break;
9793 case TOG_VIEW_REF:
9794 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9795 if (*new_view == NULL)
9796 return got_error_from_errno("view_open");
9797 if (view->type == TOG_VIEW_LOG)
9798 err = open_ref_view(*new_view, view->state.log.repo);
9799 else if (view->type == TOG_VIEW_TREE)
9800 err = open_ref_view(*new_view, view->state.tree.repo);
9801 else
9802 err = got_error_msg(GOT_ERR_NOT_IMPL,
9803 "parent/child view pair not supported");
9804 if (err)
9805 view_close(*new_view);
9806 break;
9807 case TOG_VIEW_HELP:
9808 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9809 if (*new_view == NULL)
9810 return got_error_from_errno("view_open");
9811 err = open_help_view(*new_view, view);
9812 if (err)
9813 view_close(*new_view);
9814 break;
9815 default:
9816 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9819 return err;
9823 * If view was scrolled down to move the selected line into view when opening a
9824 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9826 static void
9827 offset_selection_up(struct tog_view *view)
9829 switch (view->type) {
9830 case TOG_VIEW_BLAME: {
9831 struct tog_blame_view_state *s = &view->state.blame;
9832 if (s->first_displayed_line == 1) {
9833 s->selected_line = MAX(s->selected_line - view->offset,
9834 1);
9835 break;
9837 if (s->first_displayed_line > view->offset)
9838 s->first_displayed_line -= view->offset;
9839 else
9840 s->first_displayed_line = 1;
9841 s->selected_line += view->offset;
9842 break;
9844 case TOG_VIEW_LOG:
9845 log_scroll_up(&view->state.log, view->offset);
9846 view->state.log.selected += view->offset;
9847 break;
9848 case TOG_VIEW_REF:
9849 ref_scroll_up(&view->state.ref, view->offset);
9850 view->state.ref.selected += view->offset;
9851 break;
9852 case TOG_VIEW_TREE:
9853 tree_scroll_up(&view->state.tree, view->offset);
9854 view->state.tree.selected += view->offset;
9855 break;
9856 default:
9857 break;
9860 view->offset = 0;
9864 * If the selected line is in the section of screen covered by the bottom split,
9865 * scroll down offset lines to move it into view and index its new position.
9867 static const struct got_error *
9868 offset_selection_down(struct tog_view *view)
9870 const struct got_error *err = NULL;
9871 const struct got_error *(*scrolld)(struct tog_view *, int);
9872 int *selected = NULL;
9873 int header, offset;
9875 switch (view->type) {
9876 case TOG_VIEW_BLAME: {
9877 struct tog_blame_view_state *s = &view->state.blame;
9878 header = 3;
9879 scrolld = NULL;
9880 if (s->selected_line > view->nlines - header) {
9881 offset = abs(view->nlines - s->selected_line - header);
9882 s->first_displayed_line += offset;
9883 s->selected_line -= offset;
9884 view->offset = offset;
9886 break;
9888 case TOG_VIEW_LOG: {
9889 struct tog_log_view_state *s = &view->state.log;
9890 scrolld = &log_scroll_down;
9891 header = view_is_parent_view(view) ? 3 : 2;
9892 selected = &s->selected;
9893 break;
9895 case TOG_VIEW_REF: {
9896 struct tog_ref_view_state *s = &view->state.ref;
9897 scrolld = &ref_scroll_down;
9898 header = 3;
9899 selected = &s->selected;
9900 break;
9902 case TOG_VIEW_TREE: {
9903 struct tog_tree_view_state *s = &view->state.tree;
9904 scrolld = &tree_scroll_down;
9905 header = 5;
9906 selected = &s->selected;
9907 break;
9909 default:
9910 selected = NULL;
9911 scrolld = NULL;
9912 header = 0;
9913 break;
9916 if (selected && *selected > view->nlines - header) {
9917 offset = abs(view->nlines - *selected - header);
9918 view->offset = offset;
9919 if (scrolld && offset) {
9920 err = scrolld(view, offset);
9921 *selected -= offset;
9925 return err;
9928 static void
9929 list_commands(FILE *fp)
9931 size_t i;
9933 fprintf(fp, "commands:");
9934 for (i = 0; i < nitems(tog_commands); i++) {
9935 const struct tog_cmd *cmd = &tog_commands[i];
9936 fprintf(fp, " %s", cmd->name);
9938 fputc('\n', fp);
9941 __dead static void
9942 usage(int hflag, int status)
9944 FILE *fp = (status == 0) ? stdout : stderr;
9946 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9947 getprogname());
9948 if (hflag) {
9949 fprintf(fp, "lazy usage: %s path\n", getprogname());
9950 list_commands(fp);
9952 exit(status);
9955 static char **
9956 make_argv(int argc, ...)
9958 va_list ap;
9959 char **argv;
9960 int i;
9962 va_start(ap, argc);
9964 argv = calloc(argc, sizeof(char *));
9965 if (argv == NULL)
9966 err(1, "calloc");
9967 for (i = 0; i < argc; i++) {
9968 argv[i] = strdup(va_arg(ap, char *));
9969 if (argv[i] == NULL)
9970 err(1, "strdup");
9973 va_end(ap);
9974 return argv;
9978 * Try to convert 'tog path' into a 'tog log path' command.
9979 * The user could simply have mistyped the command rather than knowingly
9980 * provided a path. So check whether argv[0] can in fact be resolved
9981 * to a path in the HEAD commit and print a special error if not.
9982 * This hack is for mpi@ <3
9984 static const struct got_error *
9985 tog_log_with_path(int argc, char *argv[])
9987 const struct got_error *error = NULL, *close_err;
9988 const struct tog_cmd *cmd = NULL;
9989 struct got_repository *repo = NULL;
9990 struct got_worktree *worktree = NULL;
9991 struct got_object_id *commit_id = NULL, *id = NULL;
9992 struct got_commit_object *commit = NULL;
9993 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9994 char *commit_id_str = NULL, **cmd_argv = NULL;
9995 int *pack_fds = NULL;
9997 cwd = getcwd(NULL, 0);
9998 if (cwd == NULL)
9999 return got_error_from_errno("getcwd");
10001 error = got_repo_pack_fds_open(&pack_fds);
10002 if (error != NULL)
10003 goto done;
10005 error = got_worktree_open(&worktree, cwd, NULL);
10006 if (error && error->code != GOT_ERR_NOT_WORKTREE)
10007 goto done;
10009 if (worktree)
10010 repo_path = strdup(got_worktree_get_repo_path(worktree));
10011 else
10012 repo_path = strdup(cwd);
10013 if (repo_path == NULL) {
10014 error = got_error_from_errno("strdup");
10015 goto done;
10018 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
10019 if (error != NULL)
10020 goto done;
10022 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
10023 repo, worktree);
10024 if (error)
10025 goto done;
10027 error = tog_load_refs(repo, 0);
10028 if (error)
10029 goto done;
10030 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
10031 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
10032 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
10033 if (error)
10034 goto done;
10036 if (worktree) {
10037 got_worktree_close(worktree);
10038 worktree = NULL;
10041 error = got_object_open_as_commit(&commit, repo, commit_id);
10042 if (error)
10043 goto done;
10045 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
10046 if (error) {
10047 if (error->code != GOT_ERR_NO_TREE_ENTRY)
10048 goto done;
10049 fprintf(stderr, "%s: '%s' is no known command or path\n",
10050 getprogname(), argv[0]);
10051 usage(1, 1);
10052 /* not reached */
10055 error = got_object_id_str(&commit_id_str, commit_id);
10056 if (error)
10057 goto done;
10059 cmd = &tog_commands[0]; /* log */
10060 argc = 4;
10061 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
10062 error = cmd->cmd_main(argc, cmd_argv);
10063 done:
10064 if (repo) {
10065 close_err = got_repo_close(repo);
10066 if (error == NULL)
10067 error = close_err;
10069 if (commit)
10070 got_object_commit_close(commit);
10071 if (worktree)
10072 got_worktree_close(worktree);
10073 if (pack_fds) {
10074 const struct got_error *pack_err =
10075 got_repo_pack_fds_close(pack_fds);
10076 if (error == NULL)
10077 error = pack_err;
10079 free(id);
10080 free(commit_id_str);
10081 free(commit_id);
10082 free(cwd);
10083 free(repo_path);
10084 free(in_repo_path);
10085 if (cmd_argv) {
10086 int i;
10087 for (i = 0; i < argc; i++)
10088 free(cmd_argv[i]);
10089 free(cmd_argv);
10091 tog_free_refs();
10092 return error;
10095 int
10096 main(int argc, char *argv[])
10098 const struct got_error *io_err, *error = NULL;
10099 const struct tog_cmd *cmd = NULL;
10100 int ch, hflag = 0, Vflag = 0;
10101 char **cmd_argv = NULL;
10102 static const struct option longopts[] = {
10103 { "version", no_argument, NULL, 'V' },
10104 { NULL, 0, NULL, 0}
10106 char *diff_algo_str = NULL;
10107 const char *test_script_path;
10109 setlocale(LC_CTYPE, "");
10112 * Override default signal handlers before starting ncurses.
10113 * This should prevent ncurses from installing its own
10114 * broken cleanup() signal handler.
10116 signal(SIGWINCH, tog_sigwinch);
10117 signal(SIGPIPE, tog_sigpipe);
10118 signal(SIGCONT, tog_sigcont);
10119 signal(SIGINT, tog_sigint);
10120 signal(SIGTERM, tog_sigterm);
10123 * Test mode init must happen before pledge() because "tty" will
10124 * not allow TTY-related ioctls to occur via regular files.
10126 test_script_path = getenv("TOG_TEST_SCRIPT");
10127 if (test_script_path != NULL) {
10128 error = init_mock_term(test_script_path);
10129 if (error) {
10130 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10131 return 1;
10133 } else if (!isatty(STDIN_FILENO))
10134 errx(1, "standard input is not a tty");
10136 #if !defined(PROFILE)
10137 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
10138 NULL) == -1)
10139 err(1, "pledge");
10140 #endif
10142 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
10143 switch (ch) {
10144 case 'h':
10145 hflag = 1;
10146 break;
10147 case 'V':
10148 Vflag = 1;
10149 break;
10150 default:
10151 usage(hflag, 1);
10152 /* NOTREACHED */
10156 argc -= optind;
10157 argv += optind;
10158 optind = 1;
10159 optreset = 1;
10161 if (Vflag) {
10162 got_version_print_str();
10163 return 0;
10166 if (argc == 0) {
10167 if (hflag)
10168 usage(hflag, 0);
10169 /* Build an argument vector which runs a default command. */
10170 cmd = &tog_commands[0];
10171 argc = 1;
10172 cmd_argv = make_argv(argc, cmd->name);
10173 } else {
10174 size_t i;
10176 /* Did the user specify a command? */
10177 for (i = 0; i < nitems(tog_commands); i++) {
10178 if (strncmp(tog_commands[i].name, argv[0],
10179 strlen(argv[0])) == 0) {
10180 cmd = &tog_commands[i];
10181 break;
10186 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10187 if (diff_algo_str) {
10188 if (strcasecmp(diff_algo_str, "patience") == 0)
10189 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10190 if (strcasecmp(diff_algo_str, "myers") == 0)
10191 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10194 tog_base_commit.idx = -1;
10195 tog_base_commit.marker = GOT_WORKTREE_STATE_UNKNOWN;
10197 if (cmd == NULL) {
10198 if (argc != 1)
10199 usage(0, 1);
10200 /* No command specified; try log with a path */
10201 error = tog_log_with_path(argc, argv);
10202 } else {
10203 if (hflag)
10204 cmd->cmd_usage();
10205 else
10206 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10209 if (using_mock_io) {
10210 io_err = tog_io_close();
10211 if (error == NULL)
10212 error = io_err;
10214 endwin();
10215 if (cmd_argv) {
10216 int i;
10217 for (i = 0; i < argc; i++)
10218 free(cmd_argv[i]);
10219 free(cmd_argv);
10222 if (error && error->code != GOT_ERR_CANCELLED &&
10223 error->code != GOT_ERR_EOF &&
10224 error->code != GOT_ERR_PRIVSEP_EXIT &&
10225 error->code != GOT_ERR_PRIVSEP_PIPE &&
10226 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10227 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10228 return 1;
10230 return 0;