Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #if defined(__FreeBSD__) || defined(__APPLE__)
24 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
25 #endif
26 #include <curses.h>
27 #include <panel.h>
28 #include <locale.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_compat.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"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 TOG_VIEW_HELP
112 };
114 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
115 enum tog_keymap_type {
116 TOG_KEYMAP_KEYS = -2,
117 TOG_KEYMAP_GLOBAL,
118 TOG_KEYMAP_DIFF,
119 TOG_KEYMAP_LOG,
120 TOG_KEYMAP_BLAME,
121 TOG_KEYMAP_TREE,
122 TOG_KEYMAP_REF,
123 TOG_KEYMAP_HELP
124 };
126 enum tog_view_mode {
127 TOG_VIEW_SPLIT_NONE,
128 TOG_VIEW_SPLIT_VERT,
129 TOG_VIEW_SPLIT_HRZN
130 };
132 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
134 #define TOG_EOF_STRING "(END)"
136 struct commit_queue_entry {
137 TAILQ_ENTRY(commit_queue_entry) entry;
138 struct got_object_id *id;
139 struct got_commit_object *commit;
140 int idx;
141 };
142 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
143 struct commit_queue {
144 int ncommits;
145 struct commit_queue_head head;
146 };
148 struct tog_color {
149 STAILQ_ENTRY(tog_color) entry;
150 regex_t regex;
151 short colorpair;
152 };
153 STAILQ_HEAD(tog_colors, tog_color);
155 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
156 static struct got_reflist_object_id_map *tog_refs_idmap;
157 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
159 static const struct got_error *
160 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
161 struct got_reference* re2)
163 const char *name1 = got_ref_get_name(re1);
164 const char *name2 = got_ref_get_name(re2);
165 int isbackup1, isbackup2;
167 /* Sort backup refs towards the bottom of the list. */
168 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
169 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
170 if (!isbackup1 && isbackup2) {
171 *cmp = -1;
172 return NULL;
173 } else if (isbackup1 && !isbackup2) {
174 *cmp = 1;
175 return NULL;
178 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
179 return NULL;
182 static const struct got_error *
183 tog_load_refs(struct got_repository *repo, int sort_by_date)
185 const struct got_error *err;
187 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
188 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
189 repo);
190 if (err)
191 return err;
193 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
194 repo);
197 static void
198 tog_free_refs(void)
200 if (tog_refs_idmap) {
201 got_reflist_object_id_map_free(tog_refs_idmap);
202 tog_refs_idmap = NULL;
204 got_ref_list_free(&tog_refs);
207 static const struct got_error *
208 add_color(struct tog_colors *colors, const char *pattern,
209 int idx, short color)
211 const struct got_error *err = NULL;
212 struct tog_color *tc;
213 int regerr = 0;
215 if (idx < 1 || idx > COLOR_PAIRS - 1)
216 return NULL;
218 init_pair(idx, color, -1);
220 tc = calloc(1, sizeof(*tc));
221 if (tc == NULL)
222 return got_error_from_errno("calloc");
223 regerr = regcomp(&tc->regex, pattern,
224 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
225 if (regerr) {
226 static char regerr_msg[512];
227 static char err_msg[512];
228 regerror(regerr, &tc->regex, regerr_msg,
229 sizeof(regerr_msg));
230 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
231 regerr_msg);
232 err = got_error_msg(GOT_ERR_REGEX, err_msg);
233 free(tc);
234 return err;
236 tc->colorpair = idx;
237 STAILQ_INSERT_HEAD(colors, tc, entry);
238 return NULL;
241 static void
242 free_colors(struct tog_colors *colors)
244 struct tog_color *tc;
246 while (!STAILQ_EMPTY(colors)) {
247 tc = STAILQ_FIRST(colors);
248 STAILQ_REMOVE_HEAD(colors, entry);
249 regfree(&tc->regex);
250 free(tc);
254 static struct tog_color *
255 get_color(struct tog_colors *colors, int colorpair)
257 struct tog_color *tc = NULL;
259 STAILQ_FOREACH(tc, colors, entry) {
260 if (tc->colorpair == colorpair)
261 return tc;
264 return NULL;
267 static int
268 default_color_value(const char *envvar)
270 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
271 return COLOR_MAGENTA;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
273 return COLOR_CYAN;
274 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
275 return COLOR_YELLOW;
276 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
277 return COLOR_GREEN;
278 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
279 return COLOR_MAGENTA;
280 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
283 return COLOR_CYAN;
284 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
285 return COLOR_GREEN;
286 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
287 return COLOR_GREEN;
288 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
289 return COLOR_CYAN;
290 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
291 return COLOR_YELLOW;
292 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
293 return COLOR_GREEN;
294 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
295 return COLOR_MAGENTA;
296 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
297 return COLOR_YELLOW;
298 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
299 return COLOR_CYAN;
301 return -1;
304 static int
305 get_color_value(const char *envvar)
307 const char *val = getenv(envvar);
309 if (val == NULL)
310 return default_color_value(envvar);
312 if (strcasecmp(val, "black") == 0)
313 return COLOR_BLACK;
314 if (strcasecmp(val, "red") == 0)
315 return COLOR_RED;
316 if (strcasecmp(val, "green") == 0)
317 return COLOR_GREEN;
318 if (strcasecmp(val, "yellow") == 0)
319 return COLOR_YELLOW;
320 if (strcasecmp(val, "blue") == 0)
321 return COLOR_BLUE;
322 if (strcasecmp(val, "magenta") == 0)
323 return COLOR_MAGENTA;
324 if (strcasecmp(val, "cyan") == 0)
325 return COLOR_CYAN;
326 if (strcasecmp(val, "white") == 0)
327 return COLOR_WHITE;
328 if (strcasecmp(val, "default") == 0)
329 return -1;
331 return default_color_value(envvar);
334 struct tog_diff_view_state {
335 struct got_object_id *id1, *id2;
336 const char *label1, *label2;
337 FILE *f, *f1, *f2;
338 int fd1, fd2;
339 int lineno;
340 int first_displayed_line;
341 int last_displayed_line;
342 int eof;
343 int diff_context;
344 int ignore_whitespace;
345 int force_text_diff;
346 struct got_repository *repo;
347 struct got_diff_line *lines;
348 size_t nlines;
349 int matched_line;
350 int selected_line;
352 /* passed from log or blame view; may be NULL */
353 struct tog_view *parent_view;
354 };
356 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
357 static volatile sig_atomic_t tog_thread_error;
359 struct tog_log_thread_args {
360 pthread_cond_t need_commits;
361 pthread_cond_t commit_loaded;
362 int commits_needed;
363 int load_all;
364 struct got_commit_graph *graph;
365 struct commit_queue *real_commits;
366 const char *in_repo_path;
367 struct got_object_id *start_id;
368 struct got_repository *repo;
369 int *pack_fds;
370 int log_complete;
371 sig_atomic_t *quit;
372 struct commit_queue_entry **first_displayed_entry;
373 struct commit_queue_entry **selected_entry;
374 int *searching;
375 int *search_next_done;
376 regex_t *regex;
377 int *limiting;
378 int limit_match;
379 regex_t *limit_regex;
380 struct commit_queue *limit_commits;
381 };
383 struct tog_log_view_state {
384 struct commit_queue *commits;
385 struct commit_queue_entry *first_displayed_entry;
386 struct commit_queue_entry *last_displayed_entry;
387 struct commit_queue_entry *selected_entry;
388 struct commit_queue real_commits;
389 int selected;
390 char *in_repo_path;
391 char *head_ref_name;
392 int log_branches;
393 struct got_repository *repo;
394 struct got_object_id *start_id;
395 sig_atomic_t quit;
396 pthread_t thread;
397 struct tog_log_thread_args thread_args;
398 struct commit_queue_entry *matched_entry;
399 struct commit_queue_entry *search_entry;
400 struct tog_colors colors;
401 int use_committer;
402 int limit_view;
403 regex_t limit_regex;
404 struct commit_queue limit_commits;
405 };
407 #define TOG_COLOR_DIFF_MINUS 1
408 #define TOG_COLOR_DIFF_PLUS 2
409 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
410 #define TOG_COLOR_DIFF_META 4
411 #define TOG_COLOR_TREE_SUBMODULE 5
412 #define TOG_COLOR_TREE_SYMLINK 6
413 #define TOG_COLOR_TREE_DIRECTORY 7
414 #define TOG_COLOR_TREE_EXECUTABLE 8
415 #define TOG_COLOR_COMMIT 9
416 #define TOG_COLOR_AUTHOR 10
417 #define TOG_COLOR_DATE 11
418 #define TOG_COLOR_REFS_HEADS 12
419 #define TOG_COLOR_REFS_TAGS 13
420 #define TOG_COLOR_REFS_REMOTES 14
421 #define TOG_COLOR_REFS_BACKUP 15
423 struct tog_blame_cb_args {
424 struct tog_blame_line *lines; /* one per line */
425 int nlines;
427 struct tog_view *view;
428 struct got_object_id *commit_id;
429 int *quit;
430 };
432 struct tog_blame_thread_args {
433 const char *path;
434 struct got_repository *repo;
435 struct tog_blame_cb_args *cb_args;
436 int *complete;
437 got_cancel_cb cancel_cb;
438 void *cancel_arg;
439 };
441 struct tog_blame {
442 FILE *f;
443 off_t filesize;
444 struct tog_blame_line *lines;
445 int nlines;
446 off_t *line_offsets;
447 pthread_t thread;
448 struct tog_blame_thread_args thread_args;
449 struct tog_blame_cb_args cb_args;
450 const char *path;
451 int *pack_fds;
452 };
454 struct tog_blame_view_state {
455 int first_displayed_line;
456 int last_displayed_line;
457 int selected_line;
458 int last_diffed_line;
459 int blame_complete;
460 int eof;
461 int done;
462 struct got_object_id_queue blamed_commits;
463 struct got_object_qid *blamed_commit;
464 char *path;
465 struct got_repository *repo;
466 struct got_object_id *commit_id;
467 struct got_object_id *id_to_log;
468 struct tog_blame blame;
469 int matched_line;
470 struct tog_colors colors;
471 };
473 struct tog_parent_tree {
474 TAILQ_ENTRY(tog_parent_tree) entry;
475 struct got_tree_object *tree;
476 struct got_tree_entry *first_displayed_entry;
477 struct got_tree_entry *selected_entry;
478 int selected;
479 };
481 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
483 struct tog_tree_view_state {
484 char *tree_label;
485 struct got_object_id *commit_id;/* commit which this tree belongs to */
486 struct got_tree_object *root; /* the commit's root tree entry */
487 struct got_tree_object *tree; /* currently displayed (sub-)tree */
488 struct got_tree_entry *first_displayed_entry;
489 struct got_tree_entry *last_displayed_entry;
490 struct got_tree_entry *selected_entry;
491 int ndisplayed, selected, show_ids;
492 struct tog_parent_trees parents; /* parent trees of current sub-tree */
493 char *head_ref_name;
494 struct got_repository *repo;
495 struct got_tree_entry *matched_entry;
496 struct tog_colors colors;
497 };
499 struct tog_reflist_entry {
500 TAILQ_ENTRY(tog_reflist_entry) entry;
501 struct got_reference *ref;
502 int idx;
503 };
505 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
507 struct tog_ref_view_state {
508 struct tog_reflist_head refs;
509 struct tog_reflist_entry *first_displayed_entry;
510 struct tog_reflist_entry *last_displayed_entry;
511 struct tog_reflist_entry *selected_entry;
512 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
513 struct got_repository *repo;
514 struct tog_reflist_entry *matched_entry;
515 struct tog_colors colors;
516 };
518 struct tog_help_view_state {
519 FILE *f;
520 off_t *line_offsets;
521 size_t nlines;
522 int lineno;
523 int first_displayed_line;
524 int last_displayed_line;
525 int eof;
526 int matched_line;
527 int selected_line;
528 int all;
529 enum tog_keymap_type type;
530 };
532 #define GENERATE_HELP \
533 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
534 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
535 KEY_("k C-p Up", "Move cursor or page up one line"), \
536 KEY_("j C-n Down", "Move cursor or page down one line"), \
537 KEY_("C-b b PgUp", "Scroll the view up one page"), \
538 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
539 KEY_("C-u u", "Scroll the view up one half page"), \
540 KEY_("C-d d", "Scroll the view down one half page"), \
541 KEY_("g", "Go to line N (default: first line)"), \
542 KEY_("Home =", "Go to the first line"), \
543 KEY_("G", "Go to line N (default: last line)"), \
544 KEY_("End *", "Go to the last line"), \
545 KEY_("l Right", "Scroll the view right"), \
546 KEY_("h Left", "Scroll the view left"), \
547 KEY_("$", "Scroll view to the rightmost position"), \
548 KEY_("0", "Scroll view to the leftmost position"), \
549 KEY_("-", "Decrease size of the focussed split"), \
550 KEY_("+", "Increase size of the focussed split"), \
551 KEY_("Tab", "Switch focus between views"), \
552 KEY_("F", "Toggle fullscreen mode"), \
553 KEY_("/", "Open prompt to enter search term"), \
554 KEY_("n", "Find next line/token matching the current search term"), \
555 KEY_("N", "Find previous line/token matching the current search term"),\
556 KEY_("q", "Quit the focussed view; Quit help screen"), \
557 KEY_("Q", "Quit tog"), \
559 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
560 KEY_("< ,", "Move cursor up one commit"), \
561 KEY_("> .", "Move cursor down one commit"), \
562 KEY_("Enter", "Open diff view of the selected commit"), \
563 KEY_("B", "Reload the log view and toggle display of merged commits"), \
564 KEY_("R", "Open ref view of all repository references"), \
565 KEY_("T", "Display tree view of the repository from the selected" \
566 " commit"), \
567 KEY_("@", "Toggle between displaying author and committer name"), \
568 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
569 KEY_("C-g Backspace", "Cancel current search or log operation"), \
570 KEY_("C-l", "Reload the log view with new commits in the repository"), \
572 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
573 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
574 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
575 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
576 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
577 " data"), \
578 KEY_("(", "Go to the previous file in the diff"), \
579 KEY_(")", "Go to the next file in the diff"), \
580 KEY_("{", "Go to the previous hunk in the diff"), \
581 KEY_("}", "Go to the next hunk in the diff"), \
582 KEY_("[", "Decrease the number of context lines"), \
583 KEY_("]", "Increase the number of context lines"), \
584 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
586 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
587 KEY_("Enter", "Display diff view of the selected line's commit"), \
588 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
589 KEY_("L", "Open log view for the currently selected annotated line"), \
590 KEY_("C", "Reload view with the previously blamed commit"), \
591 KEY_("c", "Reload view with the version of the file found in the" \
592 " selected line's commit"), \
593 KEY_("p", "Reload view with the version of the file found in the" \
594 " selected line's parent commit"), \
596 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
597 KEY_("Enter", "Enter selected directory or open blame view of the" \
598 " selected file"), \
599 KEY_("L", "Open log view for the selected entry"), \
600 KEY_("R", "Open ref view of all repository references"), \
601 KEY_("i", "Show object IDs for all tree entries"), \
602 KEY_("Backspace", "Return to the parent directory"), \
604 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
605 KEY_("Enter", "Display log view of the selected reference"), \
606 KEY_("T", "Display tree view of the selected reference"), \
607 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
608 KEY_("m", "Toggle display of last modified date for each reference"), \
609 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
610 KEY_("C-l", "Reload view with all repository references")
612 struct tog_key_map {
613 const char *keys;
614 const char *info;
615 enum tog_keymap_type type;
616 };
618 /*
619 * We implement two types of views: parent views and child views.
621 * The 'Tab' key switches focus between a parent view and its child view.
622 * Child views are shown side-by-side to their parent view, provided
623 * there is enough screen estate.
625 * When a new view is opened from within a parent view, this new view
626 * becomes a child view of the parent view, replacing any existing child.
628 * When a new view is opened from within a child view, this new view
629 * becomes a parent view which will obscure the views below until the
630 * user quits the new parent view by typing 'q'.
632 * This list of views contains parent views only.
633 * Child views are only pointed to by their parent view.
634 */
635 TAILQ_HEAD(tog_view_list_head, tog_view);
637 struct tog_view {
638 TAILQ_ENTRY(tog_view) entry;
639 WINDOW *window;
640 PANEL *panel;
641 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
642 int resized_y, resized_x; /* begin_y/x based on user resizing */
643 int maxx, x; /* max column and current start column */
644 int lines, cols; /* copies of LINES and COLS */
645 int nscrolled, offset; /* lines scrolled and hsplit line offset */
646 int gline, hiline; /* navigate to and highlight this nG line */
647 int ch, count; /* current keymap and count prefix */
648 int resized; /* set when in a resize event */
649 int focussed; /* Only set on one parent or child view at a time. */
650 int dying;
651 struct tog_view *parent;
652 struct tog_view *child;
654 /*
655 * This flag is initially set on parent views when a new child view
656 * is created. It gets toggled when the 'Tab' key switches focus
657 * between parent and child.
658 * The flag indicates whether focus should be passed on to our child
659 * view if this parent view gets picked for focus after another parent
660 * view was closed. This prevents child views from losing focus in such
661 * situations.
662 */
663 int focus_child;
665 enum tog_view_mode mode;
666 /* type-specific state */
667 enum tog_view_type type;
668 union {
669 struct tog_diff_view_state diff;
670 struct tog_log_view_state log;
671 struct tog_blame_view_state blame;
672 struct tog_tree_view_state tree;
673 struct tog_ref_view_state ref;
674 struct tog_help_view_state help;
675 } state;
677 const struct got_error *(*show)(struct tog_view *);
678 const struct got_error *(*input)(struct tog_view **,
679 struct tog_view *, int);
680 const struct got_error *(*reset)(struct tog_view *);
681 const struct got_error *(*resize)(struct tog_view *, int);
682 const struct got_error *(*close)(struct tog_view *);
684 const struct got_error *(*search_start)(struct tog_view *);
685 const struct got_error *(*search_next)(struct tog_view *);
686 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
687 int **, int **, int **, int **);
688 int search_started;
689 int searching;
690 #define TOG_SEARCH_FORWARD 1
691 #define TOG_SEARCH_BACKWARD 2
692 int search_next_done;
693 #define TOG_SEARCH_HAVE_MORE 1
694 #define TOG_SEARCH_NO_MORE 2
695 #define TOG_SEARCH_HAVE_NONE 3
696 regex_t regex;
697 regmatch_t regmatch;
698 const char *action;
699 };
701 static const struct got_error *open_diff_view(struct tog_view *,
702 struct got_object_id *, struct got_object_id *,
703 const char *, const char *, int, int, int, struct tog_view *,
704 struct got_repository *);
705 static const struct got_error *show_diff_view(struct tog_view *);
706 static const struct got_error *input_diff_view(struct tog_view **,
707 struct tog_view *, int);
708 static const struct got_error *reset_diff_view(struct tog_view *);
709 static const struct got_error* close_diff_view(struct tog_view *);
710 static const struct got_error *search_start_diff_view(struct tog_view *);
711 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
712 size_t *, int **, int **, int **, int **);
713 static const struct got_error *search_next_view_match(struct tog_view *);
715 static const struct got_error *open_log_view(struct tog_view *,
716 struct got_object_id *, struct got_repository *,
717 const char *, const char *, int);
718 static const struct got_error * show_log_view(struct tog_view *);
719 static const struct got_error *input_log_view(struct tog_view **,
720 struct tog_view *, int);
721 static const struct got_error *resize_log_view(struct tog_view *, int);
722 static const struct got_error *close_log_view(struct tog_view *);
723 static const struct got_error *search_start_log_view(struct tog_view *);
724 static const struct got_error *search_next_log_view(struct tog_view *);
726 static const struct got_error *open_blame_view(struct tog_view *, char *,
727 struct got_object_id *, struct got_repository *);
728 static const struct got_error *show_blame_view(struct tog_view *);
729 static const struct got_error *input_blame_view(struct tog_view **,
730 struct tog_view *, int);
731 static const struct got_error *reset_blame_view(struct tog_view *);
732 static const struct got_error *close_blame_view(struct tog_view *);
733 static const struct got_error *search_start_blame_view(struct tog_view *);
734 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
735 size_t *, int **, int **, int **, int **);
737 static const struct got_error *open_tree_view(struct tog_view *,
738 struct got_object_id *, const char *, struct got_repository *);
739 static const struct got_error *show_tree_view(struct tog_view *);
740 static const struct got_error *input_tree_view(struct tog_view **,
741 struct tog_view *, int);
742 static const struct got_error *close_tree_view(struct tog_view *);
743 static const struct got_error *search_start_tree_view(struct tog_view *);
744 static const struct got_error *search_next_tree_view(struct tog_view *);
746 static const struct got_error *open_ref_view(struct tog_view *,
747 struct got_repository *);
748 static const struct got_error *show_ref_view(struct tog_view *);
749 static const struct got_error *input_ref_view(struct tog_view **,
750 struct tog_view *, int);
751 static const struct got_error *close_ref_view(struct tog_view *);
752 static const struct got_error *search_start_ref_view(struct tog_view *);
753 static const struct got_error *search_next_ref_view(struct tog_view *);
755 static const struct got_error *open_help_view(struct tog_view *,
756 struct tog_view *);
757 static const struct got_error *show_help_view(struct tog_view *);
758 static const struct got_error *input_help_view(struct tog_view **,
759 struct tog_view *, int);
760 static const struct got_error *reset_help_view(struct tog_view *);
761 static const struct got_error* close_help_view(struct tog_view *);
762 static const struct got_error *search_start_help_view(struct tog_view *);
763 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
764 size_t *, int **, int **, int **, int **);
766 static volatile sig_atomic_t tog_sigwinch_received;
767 static volatile sig_atomic_t tog_sigpipe_received;
768 static volatile sig_atomic_t tog_sigcont_received;
769 static volatile sig_atomic_t tog_sigint_received;
770 static volatile sig_atomic_t tog_sigterm_received;
772 static void
773 tog_sigwinch(int signo)
775 tog_sigwinch_received = 1;
778 static void
779 tog_sigpipe(int signo)
781 tog_sigpipe_received = 1;
784 static void
785 tog_sigcont(int signo)
787 tog_sigcont_received = 1;
790 static void
791 tog_sigint(int signo)
793 tog_sigint_received = 1;
796 static void
797 tog_sigterm(int signo)
799 tog_sigterm_received = 1;
802 static int
803 tog_fatal_signal_received(void)
805 return (tog_sigpipe_received ||
806 tog_sigint_received || tog_sigterm_received);
809 static const struct got_error *
810 view_close(struct tog_view *view)
812 const struct got_error *err = NULL, *child_err = NULL;
814 if (view->child) {
815 child_err = view_close(view->child);
816 view->child = NULL;
818 if (view->close)
819 err = view->close(view);
820 if (view->panel)
821 del_panel(view->panel);
822 if (view->window)
823 delwin(view->window);
824 free(view);
825 return err ? err : child_err;
828 static struct tog_view *
829 view_open(int nlines, int ncols, int begin_y, int begin_x,
830 enum tog_view_type type)
832 struct tog_view *view = calloc(1, sizeof(*view));
834 if (view == NULL)
835 return NULL;
837 view->type = type;
838 view->lines = LINES;
839 view->cols = COLS;
840 view->nlines = nlines ? nlines : LINES - begin_y;
841 view->ncols = ncols ? ncols : COLS - begin_x;
842 view->begin_y = begin_y;
843 view->begin_x = begin_x;
844 view->window = newwin(nlines, ncols, begin_y, begin_x);
845 if (view->window == NULL) {
846 view_close(view);
847 return NULL;
849 view->panel = new_panel(view->window);
850 if (view->panel == NULL ||
851 set_panel_userptr(view->panel, view) != OK) {
852 view_close(view);
853 return NULL;
856 keypad(view->window, TRUE);
857 return view;
860 static int
861 view_split_begin_x(int begin_x)
863 if (begin_x > 0 || COLS < 120)
864 return 0;
865 return (COLS - MAX(COLS / 2, 80));
868 /* XXX Stub till we decide what to do. */
869 static int
870 view_split_begin_y(int lines)
872 return lines * HSPLIT_SCALE;
875 static const struct got_error *view_resize(struct tog_view *);
877 static const struct got_error *
878 view_splitscreen(struct tog_view *view)
880 const struct got_error *err = NULL;
882 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
883 if (view->resized_y && view->resized_y < view->lines)
884 view->begin_y = view->resized_y;
885 else
886 view->begin_y = view_split_begin_y(view->nlines);
887 view->begin_x = 0;
888 } else if (!view->resized) {
889 if (view->resized_x && view->resized_x < view->cols - 1 &&
890 view->cols > 119)
891 view->begin_x = view->resized_x;
892 else
893 view->begin_x = view_split_begin_x(0);
894 view->begin_y = 0;
896 view->nlines = LINES - view->begin_y;
897 view->ncols = COLS - view->begin_x;
898 view->lines = LINES;
899 view->cols = COLS;
900 err = view_resize(view);
901 if (err)
902 return err;
904 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
905 view->parent->nlines = view->begin_y;
907 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
908 return got_error_from_errno("mvwin");
910 return NULL;
913 static const struct got_error *
914 view_fullscreen(struct tog_view *view)
916 const struct got_error *err = NULL;
918 view->begin_x = 0;
919 view->begin_y = view->resized ? view->begin_y : 0;
920 view->nlines = view->resized ? view->nlines : LINES;
921 view->ncols = COLS;
922 view->lines = LINES;
923 view->cols = COLS;
924 err = view_resize(view);
925 if (err)
926 return err;
928 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
929 return got_error_from_errno("mvwin");
931 return NULL;
934 static int
935 view_is_parent_view(struct tog_view *view)
937 return view->parent == NULL;
940 static int
941 view_is_splitscreen(struct tog_view *view)
943 return view->begin_x > 0 || view->begin_y > 0;
946 static int
947 view_is_fullscreen(struct tog_view *view)
949 return view->nlines == LINES && view->ncols == COLS;
952 static int
953 view_is_hsplit_top(struct tog_view *view)
955 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
956 view_is_splitscreen(view->child);
959 static void
960 view_border(struct tog_view *view)
962 PANEL *panel;
963 const struct tog_view *view_above;
965 if (view->parent)
966 return view_border(view->parent);
968 panel = panel_above(view->panel);
969 if (panel == NULL)
970 return;
972 view_above = panel_userptr(panel);
973 if (view->mode == TOG_VIEW_SPLIT_HRZN)
974 mvwhline(view->window, view_above->begin_y - 1,
975 view->begin_x, got_locale_is_utf8() ?
976 ACS_HLINE : '-', view->ncols);
977 else
978 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
979 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
982 static const struct got_error *view_init_hsplit(struct tog_view *, int);
983 static const struct got_error *request_log_commits(struct tog_view *);
984 static const struct got_error *offset_selection_down(struct tog_view *);
985 static void offset_selection_up(struct tog_view *);
986 static void view_get_split(struct tog_view *, int *, int *);
988 static const struct got_error *
989 view_resize(struct tog_view *view)
991 const struct got_error *err = NULL;
992 int dif, nlines, ncols;
994 dif = LINES - view->lines; /* line difference */
996 if (view->lines > LINES)
997 nlines = view->nlines - (view->lines - LINES);
998 else
999 nlines = view->nlines + (LINES - view->lines);
1000 if (view->cols > COLS)
1001 ncols = view->ncols - (view->cols - COLS);
1002 else
1003 ncols = view->ncols + (COLS - view->cols);
1005 if (view->child) {
1006 int hs = view->child->begin_y;
1008 if (!view_is_fullscreen(view))
1009 view->child->begin_x = view_split_begin_x(view->begin_x);
1010 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1011 view->child->begin_x == 0) {
1012 ncols = COLS;
1014 view_fullscreen(view->child);
1015 if (view->child->focussed)
1016 show_panel(view->child->panel);
1017 else
1018 show_panel(view->panel);
1019 } else {
1020 ncols = view->child->begin_x;
1022 view_splitscreen(view->child);
1023 show_panel(view->child->panel);
1026 * XXX This is ugly and needs to be moved into the above
1027 * logic but "works" for now and my attempts at moving it
1028 * break either 'tab' or 'F' key maps in horizontal splits.
1030 if (hs) {
1031 err = view_splitscreen(view->child);
1032 if (err)
1033 return err;
1034 if (dif < 0) { /* top split decreased */
1035 err = offset_selection_down(view);
1036 if (err)
1037 return err;
1039 view_border(view);
1040 update_panels();
1041 doupdate();
1042 show_panel(view->child->panel);
1043 nlines = view->nlines;
1045 } else if (view->parent == NULL)
1046 ncols = COLS;
1048 if (view->resize && dif > 0) {
1049 err = view->resize(view, dif);
1050 if (err)
1051 return err;
1054 if (wresize(view->window, nlines, ncols) == ERR)
1055 return got_error_from_errno("wresize");
1056 if (replace_panel(view->panel, view->window) == ERR)
1057 return got_error_from_errno("replace_panel");
1058 wclear(view->window);
1060 view->nlines = nlines;
1061 view->ncols = ncols;
1062 view->lines = LINES;
1063 view->cols = COLS;
1065 return NULL;
1068 static const struct got_error *
1069 resize_log_view(struct tog_view *view, int increase)
1071 struct tog_log_view_state *s = &view->state.log;
1072 const struct got_error *err = NULL;
1073 int n = 0;
1075 if (s->selected_entry)
1076 n = s->selected_entry->idx + view->lines - s->selected;
1079 * Request commits to account for the increased
1080 * height so we have enough to populate the view.
1082 if (s->commits->ncommits < n) {
1083 view->nscrolled = n - s->commits->ncommits + increase + 1;
1084 err = request_log_commits(view);
1087 return err;
1090 static void
1091 view_adjust_offset(struct tog_view *view, int n)
1093 if (n == 0)
1094 return;
1096 if (view->parent && view->parent->offset) {
1097 if (view->parent->offset + n >= 0)
1098 view->parent->offset += n;
1099 else
1100 view->parent->offset = 0;
1101 } else if (view->offset) {
1102 if (view->offset - n >= 0)
1103 view->offset -= n;
1104 else
1105 view->offset = 0;
1109 static const struct got_error *
1110 view_resize_split(struct tog_view *view, int resize)
1112 const struct got_error *err = NULL;
1113 struct tog_view *v = NULL;
1115 if (view->parent)
1116 v = view->parent;
1117 else
1118 v = view;
1120 if (!v->child || !view_is_splitscreen(v->child))
1121 return NULL;
1123 v->resized = v->child->resized = resize; /* lock for resize event */
1125 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1126 if (v->child->resized_y)
1127 v->child->begin_y = v->child->resized_y;
1128 if (view->parent)
1129 v->child->begin_y -= resize;
1130 else
1131 v->child->begin_y += resize;
1132 if (v->child->begin_y < 3) {
1133 view->count = 0;
1134 v->child->begin_y = 3;
1135 } else if (v->child->begin_y > LINES - 1) {
1136 view->count = 0;
1137 v->child->begin_y = LINES - 1;
1139 v->ncols = COLS;
1140 v->child->ncols = COLS;
1141 view_adjust_offset(view, resize);
1142 err = view_init_hsplit(v, v->child->begin_y);
1143 if (err)
1144 return err;
1145 v->child->resized_y = v->child->begin_y;
1146 } else {
1147 if (v->child->resized_x)
1148 v->child->begin_x = v->child->resized_x;
1149 if (view->parent)
1150 v->child->begin_x -= resize;
1151 else
1152 v->child->begin_x += resize;
1153 if (v->child->begin_x < 11) {
1154 view->count = 0;
1155 v->child->begin_x = 11;
1156 } else if (v->child->begin_x > COLS - 1) {
1157 view->count = 0;
1158 v->child->begin_x = COLS - 1;
1160 v->child->resized_x = v->child->begin_x;
1163 v->child->mode = v->mode;
1164 v->child->nlines = v->lines - v->child->begin_y;
1165 v->child->ncols = v->cols - v->child->begin_x;
1166 v->focus_child = 1;
1168 err = view_fullscreen(v);
1169 if (err)
1170 return err;
1171 err = view_splitscreen(v->child);
1172 if (err)
1173 return err;
1175 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1176 err = offset_selection_down(v->child);
1177 if (err)
1178 return err;
1181 if (v->resize)
1182 err = v->resize(v, 0);
1183 else if (v->child->resize)
1184 err = v->child->resize(v->child, 0);
1186 v->resized = v->child->resized = 0;
1188 return err;
1191 static void
1192 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1194 struct tog_view *v = src->child ? src->child : src;
1196 dst->resized_x = v->resized_x;
1197 dst->resized_y = v->resized_y;
1200 static const struct got_error *
1201 view_close_child(struct tog_view *view)
1203 const struct got_error *err = NULL;
1205 if (view->child == NULL)
1206 return NULL;
1208 err = view_close(view->child);
1209 view->child = NULL;
1210 return err;
1213 static const struct got_error *
1214 view_set_child(struct tog_view *view, struct tog_view *child)
1216 const struct got_error *err = NULL;
1218 view->child = child;
1219 child->parent = view;
1221 err = view_resize(view);
1222 if (err)
1223 return err;
1225 if (view->child->resized_x || view->child->resized_y)
1226 err = view_resize_split(view, 0);
1228 return err;
1231 static const struct got_error *view_dispatch_request(struct tog_view **,
1232 struct tog_view *, enum tog_view_type, int, int);
1234 static const struct got_error *
1235 view_request_new(struct tog_view **requested, struct tog_view *view,
1236 enum tog_view_type request)
1238 struct tog_view *new_view = NULL;
1239 const struct got_error *err;
1240 int y = 0, x = 0;
1242 *requested = NULL;
1244 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1245 view_get_split(view, &y, &x);
1247 err = view_dispatch_request(&new_view, view, request, y, x);
1248 if (err)
1249 return err;
1251 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1252 request != TOG_VIEW_HELP) {
1253 err = view_init_hsplit(view, y);
1254 if (err)
1255 return err;
1258 view->focussed = 0;
1259 new_view->focussed = 1;
1260 new_view->mode = view->mode;
1261 new_view->nlines = request == TOG_VIEW_HELP ?
1262 view->lines : view->lines - y;
1264 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1265 view_transfer_size(new_view, view);
1266 err = view_close_child(view);
1267 if (err)
1268 return err;
1269 err = view_set_child(view, new_view);
1270 if (err)
1271 return err;
1272 view->focus_child = 1;
1273 } else
1274 *requested = new_view;
1276 return NULL;
1279 static void
1280 tog_resizeterm(void)
1282 int cols, lines;
1283 struct winsize size;
1285 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1286 cols = 80; /* Default */
1287 lines = 24;
1288 } else {
1289 cols = size.ws_col;
1290 lines = size.ws_row;
1292 resize_term(lines, cols);
1295 static const struct got_error *
1296 view_search_start(struct tog_view *view, int fast_refresh)
1298 const struct got_error *err = NULL;
1299 struct tog_view *v = view;
1300 char pattern[1024];
1301 int ret;
1303 if (view->search_started) {
1304 regfree(&view->regex);
1305 view->searching = 0;
1306 memset(&view->regmatch, 0, sizeof(view->regmatch));
1308 view->search_started = 0;
1310 if (view->nlines < 1)
1311 return NULL;
1313 if (view_is_hsplit_top(view))
1314 v = view->child;
1315 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1316 v = view->parent;
1318 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1319 wclrtoeol(v->window);
1321 nodelay(v->window, FALSE); /* block for search term input */
1322 nocbreak();
1323 echo();
1324 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1325 wrefresh(v->window);
1326 cbreak();
1327 noecho();
1328 nodelay(v->window, TRUE);
1329 if (!fast_refresh)
1330 halfdelay(10);
1331 if (ret == ERR)
1332 return NULL;
1334 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1335 err = view->search_start(view);
1336 if (err) {
1337 regfree(&view->regex);
1338 return err;
1340 view->search_started = 1;
1341 view->searching = TOG_SEARCH_FORWARD;
1342 view->search_next_done = 0;
1343 view->search_next(view);
1346 return NULL;
1349 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1350 static const struct got_error *
1351 switch_split(struct tog_view *view)
1353 const struct got_error *err = NULL;
1354 struct tog_view *v = NULL;
1356 if (view->parent)
1357 v = view->parent;
1358 else
1359 v = view;
1361 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1362 v->mode = TOG_VIEW_SPLIT_VERT;
1363 else
1364 v->mode = TOG_VIEW_SPLIT_HRZN;
1366 if (!v->child)
1367 return NULL;
1368 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1369 v->mode = TOG_VIEW_SPLIT_NONE;
1371 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1372 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1373 v->child->begin_y = v->child->resized_y;
1374 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1375 v->child->begin_x = v->child->resized_x;
1378 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1379 v->ncols = COLS;
1380 v->child->ncols = COLS;
1381 v->child->nscrolled = LINES - v->child->nlines;
1383 err = view_init_hsplit(v, v->child->begin_y);
1384 if (err)
1385 return err;
1387 v->child->mode = v->mode;
1388 v->child->nlines = v->lines - v->child->begin_y;
1389 v->focus_child = 1;
1391 err = view_fullscreen(v);
1392 if (err)
1393 return err;
1394 err = view_splitscreen(v->child);
1395 if (err)
1396 return err;
1398 if (v->mode == TOG_VIEW_SPLIT_NONE)
1399 v->mode = TOG_VIEW_SPLIT_VERT;
1400 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1401 err = offset_selection_down(v);
1402 if (err)
1403 return err;
1404 err = offset_selection_down(v->child);
1405 if (err)
1406 return err;
1407 } else {
1408 offset_selection_up(v);
1409 offset_selection_up(v->child);
1411 if (v->resize)
1412 err = v->resize(v, 0);
1413 else if (v->child->resize)
1414 err = v->child->resize(v->child, 0);
1416 return err;
1420 * Compute view->count from numeric input. Assign total to view->count and
1421 * return first non-numeric key entered.
1423 static int
1424 get_compound_key(struct tog_view *view, int c)
1426 struct tog_view *v = view;
1427 int x, n = 0;
1429 if (view_is_hsplit_top(view))
1430 v = view->child;
1431 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1432 v = view->parent;
1434 view->count = 0;
1435 cbreak(); /* block for input */
1436 nodelay(view->window, FALSE);
1437 wmove(v->window, v->nlines - 1, 0);
1438 wclrtoeol(v->window);
1439 waddch(v->window, ':');
1441 do {
1442 x = getcurx(v->window);
1443 if (x != ERR && x < view->ncols) {
1444 waddch(v->window, c);
1445 wrefresh(v->window);
1449 * Don't overflow. Max valid request should be the greatest
1450 * between the longest and total lines; cap at 10 million.
1452 if (n >= 9999999)
1453 n = 9999999;
1454 else
1455 n = n * 10 + (c - '0');
1456 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1458 if (c == 'G' || c == 'g') { /* nG key map */
1459 view->gline = view->hiline = n;
1460 n = 0;
1461 c = 0;
1464 /* Massage excessive or inapplicable values at the input handler. */
1465 view->count = n;
1467 return c;
1470 static void
1471 action_report(struct tog_view *view)
1473 struct tog_view *v = view;
1475 if (view_is_hsplit_top(view))
1476 v = view->child;
1477 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1478 v = view->parent;
1480 wmove(v->window, v->nlines - 1, 0);
1481 wclrtoeol(v->window);
1482 wprintw(v->window, ":%s", view->action);
1483 wrefresh(v->window);
1486 * Clear action status report. Only clear in blame view
1487 * once annotating is complete, otherwise it's too fast.
1489 if (view->type == TOG_VIEW_BLAME) {
1490 if (view->state.blame.blame_complete)
1491 view->action = NULL;
1492 } else
1493 view->action = NULL;
1496 static const struct got_error *
1497 view_input(struct tog_view **new, int *done, struct tog_view *view,
1498 struct tog_view_list_head *views, int fast_refresh)
1500 const struct got_error *err = NULL;
1501 struct tog_view *v;
1502 int ch, errcode;
1504 *new = NULL;
1506 if (view->action)
1507 action_report(view);
1509 /* Clear "no matches" indicator. */
1510 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1511 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1512 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1513 view->count = 0;
1516 if (view->searching && !view->search_next_done) {
1517 errcode = pthread_mutex_unlock(&tog_mutex);
1518 if (errcode)
1519 return got_error_set_errno(errcode,
1520 "pthread_mutex_unlock");
1521 sched_yield();
1522 errcode = pthread_mutex_lock(&tog_mutex);
1523 if (errcode)
1524 return got_error_set_errno(errcode,
1525 "pthread_mutex_lock");
1526 view->search_next(view);
1527 return NULL;
1530 /* Allow threads to make progress while we are waiting for input. */
1531 errcode = pthread_mutex_unlock(&tog_mutex);
1532 if (errcode)
1533 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1534 /* If we have an unfinished count, let C-g or backspace abort. */
1535 if (view->count && --view->count) {
1536 cbreak();
1537 nodelay(view->window, TRUE);
1538 ch = wgetch(view->window);
1539 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1540 view->count = 0;
1541 else
1542 ch = view->ch;
1543 } else {
1544 ch = wgetch(view->window);
1545 if (ch >= '1' && ch <= '9')
1546 view->ch = ch = get_compound_key(view, ch);
1548 if (view->hiline && ch != ERR && ch != 0)
1549 view->hiline = 0; /* key pressed, clear line highlight */
1550 nodelay(view->window, TRUE);
1551 errcode = pthread_mutex_lock(&tog_mutex);
1552 if (errcode)
1553 return got_error_set_errno(errcode, "pthread_mutex_lock");
1555 if (tog_sigwinch_received || tog_sigcont_received) {
1556 tog_resizeterm();
1557 tog_sigwinch_received = 0;
1558 tog_sigcont_received = 0;
1559 TAILQ_FOREACH(v, views, entry) {
1560 err = view_resize(v);
1561 if (err)
1562 return err;
1563 err = v->input(new, v, KEY_RESIZE);
1564 if (err)
1565 return err;
1566 if (v->child) {
1567 err = view_resize(v->child);
1568 if (err)
1569 return err;
1570 err = v->child->input(new, v->child,
1571 KEY_RESIZE);
1572 if (err)
1573 return err;
1574 if (v->child->resized_x || v->child->resized_y) {
1575 err = view_resize_split(v, 0);
1576 if (err)
1577 return err;
1583 switch (ch) {
1584 case '?':
1585 case 'H':
1586 case KEY_F(1):
1587 if (view->type == TOG_VIEW_HELP)
1588 err = view->reset(view);
1589 else
1590 err = view_request_new(new, view, TOG_VIEW_HELP);
1591 break;
1592 case '\t':
1593 view->count = 0;
1594 if (view->child) {
1595 view->focussed = 0;
1596 view->child->focussed = 1;
1597 view->focus_child = 1;
1598 } else if (view->parent) {
1599 view->focussed = 0;
1600 view->parent->focussed = 1;
1601 view->parent->focus_child = 0;
1602 if (!view_is_splitscreen(view)) {
1603 if (view->parent->resize) {
1604 err = view->parent->resize(view->parent,
1605 0);
1606 if (err)
1607 return err;
1609 offset_selection_up(view->parent);
1610 err = view_fullscreen(view->parent);
1611 if (err)
1612 return err;
1615 break;
1616 case 'q':
1617 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1618 if (view->parent->resize) {
1619 /* might need more commits to fill fullscreen */
1620 err = view->parent->resize(view->parent, 0);
1621 if (err)
1622 break;
1624 offset_selection_up(view->parent);
1626 err = view->input(new, view, ch);
1627 view->dying = 1;
1628 break;
1629 case 'Q':
1630 *done = 1;
1631 break;
1632 case 'F':
1633 view->count = 0;
1634 if (view_is_parent_view(view)) {
1635 if (view->child == NULL)
1636 break;
1637 if (view_is_splitscreen(view->child)) {
1638 view->focussed = 0;
1639 view->child->focussed = 1;
1640 err = view_fullscreen(view->child);
1641 } else {
1642 err = view_splitscreen(view->child);
1643 if (!err)
1644 err = view_resize_split(view, 0);
1646 if (err)
1647 break;
1648 err = view->child->input(new, view->child,
1649 KEY_RESIZE);
1650 } else {
1651 if (view_is_splitscreen(view)) {
1652 view->parent->focussed = 0;
1653 view->focussed = 1;
1654 err = view_fullscreen(view);
1655 } else {
1656 err = view_splitscreen(view);
1657 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1658 err = view_resize(view->parent);
1659 if (!err)
1660 err = view_resize_split(view, 0);
1662 if (err)
1663 break;
1664 err = view->input(new, view, KEY_RESIZE);
1666 if (err)
1667 break;
1668 if (view->resize) {
1669 err = view->resize(view, 0);
1670 if (err)
1671 break;
1673 if (view->parent)
1674 err = offset_selection_down(view->parent);
1675 if (!err)
1676 err = offset_selection_down(view);
1677 break;
1678 case 'S':
1679 view->count = 0;
1680 err = switch_split(view);
1681 break;
1682 case '-':
1683 err = view_resize_split(view, -1);
1684 break;
1685 case '+':
1686 err = view_resize_split(view, 1);
1687 break;
1688 case KEY_RESIZE:
1689 break;
1690 case '/':
1691 view->count = 0;
1692 if (view->search_start)
1693 view_search_start(view, fast_refresh);
1694 else
1695 err = view->input(new, view, ch);
1696 break;
1697 case 'N':
1698 case 'n':
1699 if (view->search_started && view->search_next) {
1700 view->searching = (ch == 'n' ?
1701 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1702 view->search_next_done = 0;
1703 view->search_next(view);
1704 } else
1705 err = view->input(new, view, ch);
1706 break;
1707 case 'A':
1708 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1709 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1710 view->action = "Patience diff algorithm";
1711 } else {
1712 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1713 view->action = "Myers diff algorithm";
1715 TAILQ_FOREACH(v, views, entry) {
1716 if (v->reset) {
1717 err = v->reset(v);
1718 if (err)
1719 return err;
1721 if (v->child && v->child->reset) {
1722 err = v->child->reset(v->child);
1723 if (err)
1724 return err;
1727 break;
1728 default:
1729 err = view->input(new, view, ch);
1730 break;
1733 return err;
1736 static int
1737 view_needs_focus_indication(struct tog_view *view)
1739 if (view_is_parent_view(view)) {
1740 if (view->child == NULL || view->child->focussed)
1741 return 0;
1742 if (!view_is_splitscreen(view->child))
1743 return 0;
1744 } else if (!view_is_splitscreen(view))
1745 return 0;
1747 return view->focussed;
1750 static const struct got_error *
1751 view_loop(struct tog_view *view)
1753 const struct got_error *err = NULL;
1754 struct tog_view_list_head views;
1755 struct tog_view *new_view;
1756 char *mode;
1757 int fast_refresh = 10;
1758 int done = 0, errcode;
1760 mode = getenv("TOG_VIEW_SPLIT_MODE");
1761 if (!mode || !(*mode == 'h' || *mode == 'H'))
1762 view->mode = TOG_VIEW_SPLIT_VERT;
1763 else
1764 view->mode = TOG_VIEW_SPLIT_HRZN;
1766 errcode = pthread_mutex_lock(&tog_mutex);
1767 if (errcode)
1768 return got_error_set_errno(errcode, "pthread_mutex_lock");
1770 TAILQ_INIT(&views);
1771 TAILQ_INSERT_HEAD(&views, view, entry);
1773 view->focussed = 1;
1774 err = view->show(view);
1775 if (err)
1776 return err;
1777 update_panels();
1778 doupdate();
1779 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1780 !tog_fatal_signal_received()) {
1781 /* Refresh fast during initialization, then become slower. */
1782 if (fast_refresh && --fast_refresh == 0)
1783 halfdelay(10); /* switch to once per second */
1785 err = view_input(&new_view, &done, view, &views, fast_refresh);
1786 if (err)
1787 break;
1789 if (view->dying && view == TAILQ_FIRST(&views) &&
1790 TAILQ_NEXT(view, entry) == NULL)
1791 done = 1;
1792 if (done) {
1793 struct tog_view *v;
1796 * When we quit, scroll the screen up a single line
1797 * so we don't lose any information.
1799 TAILQ_FOREACH(v, &views, entry) {
1800 wmove(v->window, 0, 0);
1801 wdeleteln(v->window);
1802 wnoutrefresh(v->window);
1803 if (v->child && !view_is_fullscreen(v)) {
1804 wmove(v->child->window, 0, 0);
1805 wdeleteln(v->child->window);
1806 wnoutrefresh(v->child->window);
1809 doupdate();
1812 if (view->dying) {
1813 struct tog_view *v, *prev = NULL;
1815 if (view_is_parent_view(view))
1816 prev = TAILQ_PREV(view, tog_view_list_head,
1817 entry);
1818 else if (view->parent)
1819 prev = view->parent;
1821 if (view->parent) {
1822 view->parent->child = NULL;
1823 view->parent->focus_child = 0;
1824 /* Restore fullscreen line height. */
1825 view->parent->nlines = view->parent->lines;
1826 err = view_resize(view->parent);
1827 if (err)
1828 break;
1829 /* Make resized splits persist. */
1830 view_transfer_size(view->parent, view);
1831 } else
1832 TAILQ_REMOVE(&views, view, entry);
1834 err = view_close(view);
1835 if (err)
1836 goto done;
1838 view = NULL;
1839 TAILQ_FOREACH(v, &views, entry) {
1840 if (v->focussed)
1841 break;
1843 if (view == NULL && new_view == NULL) {
1844 /* No view has focus. Try to pick one. */
1845 if (prev)
1846 view = prev;
1847 else if (!TAILQ_EMPTY(&views)) {
1848 view = TAILQ_LAST(&views,
1849 tog_view_list_head);
1851 if (view) {
1852 if (view->focus_child) {
1853 view->child->focussed = 1;
1854 view = view->child;
1855 } else
1856 view->focussed = 1;
1860 if (new_view) {
1861 struct tog_view *v, *t;
1862 /* Only allow one parent view per type. */
1863 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1864 if (v->type != new_view->type)
1865 continue;
1866 TAILQ_REMOVE(&views, v, entry);
1867 err = view_close(v);
1868 if (err)
1869 goto done;
1870 break;
1872 TAILQ_INSERT_TAIL(&views, new_view, entry);
1873 view = new_view;
1875 if (view && !done) {
1876 if (view_is_parent_view(view)) {
1877 if (view->child && view->child->focussed)
1878 view = view->child;
1879 } else {
1880 if (view->parent && view->parent->focussed)
1881 view = view->parent;
1883 show_panel(view->panel);
1884 if (view->child && view_is_splitscreen(view->child))
1885 show_panel(view->child->panel);
1886 if (view->parent && view_is_splitscreen(view)) {
1887 err = view->parent->show(view->parent);
1888 if (err)
1889 goto done;
1891 err = view->show(view);
1892 if (err)
1893 goto done;
1894 if (view->child) {
1895 err = view->child->show(view->child);
1896 if (err)
1897 goto done;
1899 update_panels();
1900 doupdate();
1903 done:
1904 while (!TAILQ_EMPTY(&views)) {
1905 const struct got_error *close_err;
1906 view = TAILQ_FIRST(&views);
1907 TAILQ_REMOVE(&views, view, entry);
1908 close_err = view_close(view);
1909 if (close_err && err == NULL)
1910 err = close_err;
1913 errcode = pthread_mutex_unlock(&tog_mutex);
1914 if (errcode && err == NULL)
1915 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1917 return err;
1920 __dead static void
1921 usage_log(void)
1923 endwin();
1924 fprintf(stderr,
1925 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1926 getprogname());
1927 exit(1);
1930 /* Create newly allocated wide-character string equivalent to a byte string. */
1931 static const struct got_error *
1932 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1934 char *vis = NULL;
1935 const struct got_error *err = NULL;
1937 *ws = NULL;
1938 *wlen = mbstowcs(NULL, s, 0);
1939 if (*wlen == (size_t)-1) {
1940 int vislen;
1941 if (errno != EILSEQ)
1942 return got_error_from_errno("mbstowcs");
1944 /* byte string invalid in current encoding; try to "fix" it */
1945 err = got_mbsavis(&vis, &vislen, s);
1946 if (err)
1947 return err;
1948 *wlen = mbstowcs(NULL, vis, 0);
1949 if (*wlen == (size_t)-1) {
1950 err = got_error_from_errno("mbstowcs"); /* give up */
1951 goto done;
1955 *ws = calloc(*wlen + 1, sizeof(**ws));
1956 if (*ws == NULL) {
1957 err = got_error_from_errno("calloc");
1958 goto done;
1961 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1962 err = got_error_from_errno("mbstowcs");
1963 done:
1964 free(vis);
1965 if (err) {
1966 free(*ws);
1967 *ws = NULL;
1968 *wlen = 0;
1970 return err;
1973 static const struct got_error *
1974 expand_tab(char **ptr, const char *src)
1976 char *dst;
1977 size_t len, n, idx = 0, sz = 0;
1979 *ptr = NULL;
1980 n = len = strlen(src);
1981 dst = malloc(n + 1);
1982 if (dst == NULL)
1983 return got_error_from_errno("malloc");
1985 while (idx < len && src[idx]) {
1986 const char c = src[idx];
1988 if (c == '\t') {
1989 size_t nb = TABSIZE - sz % TABSIZE;
1990 char *p;
1992 p = realloc(dst, n + nb);
1993 if (p == NULL) {
1994 free(dst);
1995 return got_error_from_errno("realloc");
1998 dst = p;
1999 n += nb;
2000 memset(dst + sz, ' ', nb);
2001 sz += nb;
2002 } else
2003 dst[sz++] = src[idx];
2004 ++idx;
2007 dst[sz] = '\0';
2008 *ptr = dst;
2009 return NULL;
2013 * Advance at most n columns from wline starting at offset off.
2014 * Return the index to the first character after the span operation.
2015 * Return the combined column width of all spanned wide character in
2016 * *rcol.
2018 static int
2019 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2021 int width, i, cols = 0;
2023 if (n == 0) {
2024 *rcol = cols;
2025 return off;
2028 for (i = off; wline[i] != L'\0'; ++i) {
2029 if (wline[i] == L'\t')
2030 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2031 else
2032 width = wcwidth(wline[i]);
2034 if (width == -1) {
2035 width = 1;
2036 wline[i] = L'.';
2039 if (cols + width > n)
2040 break;
2041 cols += width;
2044 *rcol = cols;
2045 return i;
2049 * Format a line for display, ensuring that it won't overflow a width limit.
2050 * With scrolling, the width returned refers to the scrolled version of the
2051 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2053 static const struct got_error *
2054 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2055 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2057 const struct got_error *err = NULL;
2058 int cols;
2059 wchar_t *wline = NULL;
2060 char *exstr = NULL;
2061 size_t wlen;
2062 int i, scrollx;
2064 *wlinep = NULL;
2065 *widthp = 0;
2067 if (expand) {
2068 err = expand_tab(&exstr, line);
2069 if (err)
2070 return err;
2073 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2074 free(exstr);
2075 if (err)
2076 return err;
2078 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2080 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2081 wline[wlen - 1] = L'\0';
2082 wlen--;
2084 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2085 wline[wlen - 1] = L'\0';
2086 wlen--;
2089 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2090 wline[i] = L'\0';
2092 if (widthp)
2093 *widthp = cols;
2094 if (scrollxp)
2095 *scrollxp = scrollx;
2096 if (err)
2097 free(wline);
2098 else
2099 *wlinep = wline;
2100 return err;
2103 static const struct got_error*
2104 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2105 struct got_object_id *id, struct got_repository *repo)
2107 static const struct got_error *err = NULL;
2108 struct got_reflist_entry *re;
2109 char *s;
2110 const char *name;
2112 *refs_str = NULL;
2114 TAILQ_FOREACH(re, refs, entry) {
2115 struct got_tag_object *tag = NULL;
2116 struct got_object_id *ref_id;
2117 int cmp;
2119 name = got_ref_get_name(re->ref);
2120 if (strcmp(name, GOT_REF_HEAD) == 0)
2121 continue;
2122 if (strncmp(name, "refs/", 5) == 0)
2123 name += 5;
2124 if (strncmp(name, "got/", 4) == 0 &&
2125 strncmp(name, "got/backup/", 11) != 0)
2126 continue;
2127 if (strncmp(name, "heads/", 6) == 0)
2128 name += 6;
2129 if (strncmp(name, "remotes/", 8) == 0) {
2130 name += 8;
2131 s = strstr(name, "/" GOT_REF_HEAD);
2132 if (s != NULL && s[strlen(s)] == '\0')
2133 continue;
2135 err = got_ref_resolve(&ref_id, repo, re->ref);
2136 if (err)
2137 break;
2138 if (strncmp(name, "tags/", 5) == 0) {
2139 err = got_object_open_as_tag(&tag, repo, ref_id);
2140 if (err) {
2141 if (err->code != GOT_ERR_OBJ_TYPE) {
2142 free(ref_id);
2143 break;
2145 /* Ref points at something other than a tag. */
2146 err = NULL;
2147 tag = NULL;
2150 cmp = got_object_id_cmp(tag ?
2151 got_object_tag_get_object_id(tag) : ref_id, id);
2152 free(ref_id);
2153 if (tag)
2154 got_object_tag_close(tag);
2155 if (cmp != 0)
2156 continue;
2157 s = *refs_str;
2158 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2159 s ? ", " : "", name) == -1) {
2160 err = got_error_from_errno("asprintf");
2161 free(s);
2162 *refs_str = NULL;
2163 break;
2165 free(s);
2168 return err;
2171 static const struct got_error *
2172 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2173 int col_tab_align)
2175 char *smallerthan;
2177 smallerthan = strchr(author, '<');
2178 if (smallerthan && smallerthan[1] != '\0')
2179 author = smallerthan + 1;
2180 author[strcspn(author, "@>")] = '\0';
2181 return format_line(wauthor, author_width, NULL, author, 0, limit,
2182 col_tab_align, 0);
2185 static const struct got_error *
2186 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2187 struct got_object_id *id, const size_t date_display_cols,
2188 int author_display_cols)
2190 struct tog_log_view_state *s = &view->state.log;
2191 const struct got_error *err = NULL;
2192 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2193 char *logmsg0 = NULL, *logmsg = NULL;
2194 char *author = NULL;
2195 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2196 int author_width, logmsg_width;
2197 char *newline, *line = NULL;
2198 int col, limit, scrollx;
2199 const int avail = view->ncols;
2200 struct tm tm;
2201 time_t committer_time;
2202 struct tog_color *tc;
2204 committer_time = got_object_commit_get_committer_time(commit);
2205 if (gmtime_r(&committer_time, &tm) == NULL)
2206 return got_error_from_errno("gmtime_r");
2207 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2208 return got_error(GOT_ERR_NO_SPACE);
2210 if (avail <= date_display_cols)
2211 limit = MIN(sizeof(datebuf) - 1, avail);
2212 else
2213 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2214 tc = get_color(&s->colors, TOG_COLOR_DATE);
2215 if (tc)
2216 wattr_on(view->window,
2217 COLOR_PAIR(tc->colorpair), NULL);
2218 waddnstr(view->window, datebuf, limit);
2219 if (tc)
2220 wattr_off(view->window,
2221 COLOR_PAIR(tc->colorpair), NULL);
2222 col = limit;
2223 if (col > avail)
2224 goto done;
2226 if (avail >= 120) {
2227 char *id_str;
2228 err = got_object_id_str(&id_str, id);
2229 if (err)
2230 goto done;
2231 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2232 if (tc)
2233 wattr_on(view->window,
2234 COLOR_PAIR(tc->colorpair), NULL);
2235 wprintw(view->window, "%.8s ", id_str);
2236 if (tc)
2237 wattr_off(view->window,
2238 COLOR_PAIR(tc->colorpair), NULL);
2239 free(id_str);
2240 col += 9;
2241 if (col > avail)
2242 goto done;
2245 if (s->use_committer)
2246 author = strdup(got_object_commit_get_committer(commit));
2247 else
2248 author = strdup(got_object_commit_get_author(commit));
2249 if (author == NULL) {
2250 err = got_error_from_errno("strdup");
2251 goto done;
2253 err = format_author(&wauthor, &author_width, author, avail - col, col);
2254 if (err)
2255 goto done;
2256 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2257 if (tc)
2258 wattr_on(view->window,
2259 COLOR_PAIR(tc->colorpair), NULL);
2260 waddwstr(view->window, wauthor);
2261 col += author_width;
2262 while (col < avail && author_width < author_display_cols + 2) {
2263 waddch(view->window, ' ');
2264 col++;
2265 author_width++;
2267 if (tc)
2268 wattr_off(view->window,
2269 COLOR_PAIR(tc->colorpair), NULL);
2270 if (col > avail)
2271 goto done;
2273 err = got_object_commit_get_logmsg(&logmsg0, commit);
2274 if (err)
2275 goto done;
2276 logmsg = logmsg0;
2277 while (*logmsg == '\n')
2278 logmsg++;
2279 newline = strchr(logmsg, '\n');
2280 if (newline)
2281 *newline = '\0';
2282 limit = avail - col;
2283 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2284 limit--; /* for the border */
2285 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2286 limit, col, 1);
2287 if (err)
2288 goto done;
2289 waddwstr(view->window, &wlogmsg[scrollx]);
2290 col += MAX(logmsg_width, 0);
2291 while (col < avail) {
2292 waddch(view->window, ' ');
2293 col++;
2295 done:
2296 free(logmsg0);
2297 free(wlogmsg);
2298 free(author);
2299 free(wauthor);
2300 free(line);
2301 return err;
2304 static struct commit_queue_entry *
2305 alloc_commit_queue_entry(struct got_commit_object *commit,
2306 struct got_object_id *id)
2308 struct commit_queue_entry *entry;
2309 struct got_object_id *dup;
2311 entry = calloc(1, sizeof(*entry));
2312 if (entry == NULL)
2313 return NULL;
2315 dup = got_object_id_dup(id);
2316 if (dup == NULL) {
2317 free(entry);
2318 return NULL;
2321 entry->id = dup;
2322 entry->commit = commit;
2323 return entry;
2326 static void
2327 pop_commit(struct commit_queue *commits)
2329 struct commit_queue_entry *entry;
2331 entry = TAILQ_FIRST(&commits->head);
2332 TAILQ_REMOVE(&commits->head, entry, entry);
2333 got_object_commit_close(entry->commit);
2334 commits->ncommits--;
2335 free(entry->id);
2336 free(entry);
2339 static void
2340 free_commits(struct commit_queue *commits)
2342 while (!TAILQ_EMPTY(&commits->head))
2343 pop_commit(commits);
2346 static const struct got_error *
2347 match_commit(int *have_match, struct got_object_id *id,
2348 struct got_commit_object *commit, regex_t *regex)
2350 const struct got_error *err = NULL;
2351 regmatch_t regmatch;
2352 char *id_str = NULL, *logmsg = NULL;
2354 *have_match = 0;
2356 err = got_object_id_str(&id_str, id);
2357 if (err)
2358 return err;
2360 err = got_object_commit_get_logmsg(&logmsg, commit);
2361 if (err)
2362 goto done;
2364 if (regexec(regex, got_object_commit_get_author(commit), 1,
2365 &regmatch, 0) == 0 ||
2366 regexec(regex, got_object_commit_get_committer(commit), 1,
2367 &regmatch, 0) == 0 ||
2368 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2369 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2370 *have_match = 1;
2371 done:
2372 free(id_str);
2373 free(logmsg);
2374 return err;
2377 static const struct got_error *
2378 queue_commits(struct tog_log_thread_args *a)
2380 const struct got_error *err = NULL;
2383 * We keep all commits open throughout the lifetime of the log
2384 * view in order to avoid having to re-fetch commits from disk
2385 * while updating the display.
2387 do {
2388 struct got_object_id id;
2389 struct got_commit_object *commit;
2390 struct commit_queue_entry *entry;
2391 int limit_match = 0;
2392 int errcode;
2394 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2395 NULL, NULL);
2396 if (err)
2397 break;
2399 err = got_object_open_as_commit(&commit, a->repo, &id);
2400 if (err)
2401 break;
2402 entry = alloc_commit_queue_entry(commit, &id);
2403 if (entry == NULL) {
2404 err = got_error_from_errno("alloc_commit_queue_entry");
2405 break;
2408 errcode = pthread_mutex_lock(&tog_mutex);
2409 if (errcode) {
2410 err = got_error_set_errno(errcode,
2411 "pthread_mutex_lock");
2412 break;
2415 entry->idx = a->real_commits->ncommits;
2416 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2417 a->real_commits->ncommits++;
2419 if (*a->limiting) {
2420 err = match_commit(&limit_match, &id, commit,
2421 a->limit_regex);
2422 if (err)
2423 break;
2425 if (limit_match) {
2426 struct commit_queue_entry *matched;
2428 matched = alloc_commit_queue_entry(
2429 entry->commit, entry->id);
2430 if (matched == NULL) {
2431 err = got_error_from_errno(
2432 "alloc_commit_queue_entry");
2433 break;
2435 matched->commit = entry->commit;
2436 got_object_commit_retain(entry->commit);
2438 matched->idx = a->limit_commits->ncommits;
2439 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2440 matched, entry);
2441 a->limit_commits->ncommits++;
2445 * This is how we signal log_thread() that we
2446 * have found a match, and that it should be
2447 * counted as a new entry for the view.
2449 a->limit_match = limit_match;
2452 if (*a->searching == TOG_SEARCH_FORWARD &&
2453 !*a->search_next_done) {
2454 int have_match;
2455 err = match_commit(&have_match, &id, commit, a->regex);
2456 if (err)
2457 break;
2459 if (*a->limiting) {
2460 if (limit_match && have_match)
2461 *a->search_next_done =
2462 TOG_SEARCH_HAVE_MORE;
2463 } else if (have_match)
2464 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2467 errcode = pthread_mutex_unlock(&tog_mutex);
2468 if (errcode && err == NULL)
2469 err = got_error_set_errno(errcode,
2470 "pthread_mutex_unlock");
2471 if (err)
2472 break;
2473 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2475 return err;
2478 static void
2479 select_commit(struct tog_log_view_state *s)
2481 struct commit_queue_entry *entry;
2482 int ncommits = 0;
2484 entry = s->first_displayed_entry;
2485 while (entry) {
2486 if (ncommits == s->selected) {
2487 s->selected_entry = entry;
2488 break;
2490 entry = TAILQ_NEXT(entry, entry);
2491 ncommits++;
2495 static const struct got_error *
2496 draw_commits(struct tog_view *view)
2498 const struct got_error *err = NULL;
2499 struct tog_log_view_state *s = &view->state.log;
2500 struct commit_queue_entry *entry = s->selected_entry;
2501 int limit = view->nlines;
2502 int width;
2503 int ncommits, author_cols = 4;
2504 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2505 char *refs_str = NULL;
2506 wchar_t *wline;
2507 struct tog_color *tc;
2508 static const size_t date_display_cols = 12;
2510 if (view_is_hsplit_top(view))
2511 --limit; /* account for border */
2513 if (s->selected_entry &&
2514 !(view->searching && view->search_next_done == 0)) {
2515 struct got_reflist_head *refs;
2516 err = got_object_id_str(&id_str, s->selected_entry->id);
2517 if (err)
2518 return err;
2519 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2520 s->selected_entry->id);
2521 if (refs) {
2522 err = build_refs_str(&refs_str, refs,
2523 s->selected_entry->id, s->repo);
2524 if (err)
2525 goto done;
2529 if (s->thread_args.commits_needed == 0)
2530 halfdelay(10); /* disable fast refresh */
2532 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2533 if (asprintf(&ncommits_str, " [%d/%d] %s",
2534 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2535 (view->searching && !view->search_next_done) ?
2536 "searching..." : "loading...") == -1) {
2537 err = got_error_from_errno("asprintf");
2538 goto done;
2540 } else {
2541 const char *search_str = NULL;
2542 const char *limit_str = NULL;
2544 if (view->searching) {
2545 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2546 search_str = "no more matches";
2547 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2548 search_str = "no matches found";
2549 else if (!view->search_next_done)
2550 search_str = "searching...";
2553 if (s->limit_view && s->commits->ncommits == 0)
2554 limit_str = "no matches found";
2556 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2557 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2558 search_str ? search_str : (refs_str ? refs_str : ""),
2559 limit_str ? limit_str : "") == -1) {
2560 err = got_error_from_errno("asprintf");
2561 goto done;
2565 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2566 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2567 "........................................",
2568 s->in_repo_path, ncommits_str) == -1) {
2569 err = got_error_from_errno("asprintf");
2570 header = NULL;
2571 goto done;
2573 } else if (asprintf(&header, "commit %s%s",
2574 id_str ? id_str : "........................................",
2575 ncommits_str) == -1) {
2576 err = got_error_from_errno("asprintf");
2577 header = NULL;
2578 goto done;
2580 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2581 if (err)
2582 goto done;
2584 werase(view->window);
2586 if (view_needs_focus_indication(view))
2587 wstandout(view->window);
2588 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2589 if (tc)
2590 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2591 waddwstr(view->window, wline);
2592 while (width < view->ncols) {
2593 waddch(view->window, ' ');
2594 width++;
2596 if (tc)
2597 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2598 if (view_needs_focus_indication(view))
2599 wstandend(view->window);
2600 free(wline);
2601 if (limit <= 1)
2602 goto done;
2604 /* Grow author column size if necessary, and set view->maxx. */
2605 entry = s->first_displayed_entry;
2606 ncommits = 0;
2607 view->maxx = 0;
2608 while (entry) {
2609 struct got_commit_object *c = entry->commit;
2610 char *author, *eol, *msg, *msg0;
2611 wchar_t *wauthor, *wmsg;
2612 int width;
2613 if (ncommits >= limit - 1)
2614 break;
2615 if (s->use_committer)
2616 author = strdup(got_object_commit_get_committer(c));
2617 else
2618 author = strdup(got_object_commit_get_author(c));
2619 if (author == NULL) {
2620 err = got_error_from_errno("strdup");
2621 goto done;
2623 err = format_author(&wauthor, &width, author, COLS,
2624 date_display_cols);
2625 if (author_cols < width)
2626 author_cols = width;
2627 free(wauthor);
2628 free(author);
2629 if (err)
2630 goto done;
2631 err = got_object_commit_get_logmsg(&msg0, c);
2632 if (err)
2633 goto done;
2634 msg = msg0;
2635 while (*msg == '\n')
2636 ++msg;
2637 if ((eol = strchr(msg, '\n')))
2638 *eol = '\0';
2639 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2640 date_display_cols + author_cols, 0);
2641 if (err)
2642 goto done;
2643 view->maxx = MAX(view->maxx, width);
2644 free(msg0);
2645 free(wmsg);
2646 ncommits++;
2647 entry = TAILQ_NEXT(entry, entry);
2650 entry = s->first_displayed_entry;
2651 s->last_displayed_entry = s->first_displayed_entry;
2652 ncommits = 0;
2653 while (entry) {
2654 if (ncommits >= limit - 1)
2655 break;
2656 if (ncommits == s->selected)
2657 wstandout(view->window);
2658 err = draw_commit(view, entry->commit, entry->id,
2659 date_display_cols, author_cols);
2660 if (ncommits == s->selected)
2661 wstandend(view->window);
2662 if (err)
2663 goto done;
2664 ncommits++;
2665 s->last_displayed_entry = entry;
2666 entry = TAILQ_NEXT(entry, entry);
2669 view_border(view);
2670 done:
2671 free(id_str);
2672 free(refs_str);
2673 free(ncommits_str);
2674 free(header);
2675 return err;
2678 static void
2679 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2681 struct commit_queue_entry *entry;
2682 int nscrolled = 0;
2684 entry = TAILQ_FIRST(&s->commits->head);
2685 if (s->first_displayed_entry == entry)
2686 return;
2688 entry = s->first_displayed_entry;
2689 while (entry && nscrolled < maxscroll) {
2690 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2691 if (entry) {
2692 s->first_displayed_entry = entry;
2693 nscrolled++;
2698 static const struct got_error *
2699 trigger_log_thread(struct tog_view *view, int wait)
2701 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2702 int errcode;
2704 halfdelay(1); /* fast refresh while loading commits */
2706 while (!ta->log_complete && !tog_thread_error &&
2707 (ta->commits_needed > 0 || ta->load_all)) {
2708 /* Wake the log thread. */
2709 errcode = pthread_cond_signal(&ta->need_commits);
2710 if (errcode)
2711 return got_error_set_errno(errcode,
2712 "pthread_cond_signal");
2715 * The mutex will be released while the view loop waits
2716 * in wgetch(), at which time the log thread will run.
2718 if (!wait)
2719 break;
2721 /* Display progress update in log view. */
2722 show_log_view(view);
2723 update_panels();
2724 doupdate();
2726 /* Wait right here while next commit is being loaded. */
2727 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2728 if (errcode)
2729 return got_error_set_errno(errcode,
2730 "pthread_cond_wait");
2732 /* Display progress update in log view. */
2733 show_log_view(view);
2734 update_panels();
2735 doupdate();
2738 return NULL;
2741 static const struct got_error *
2742 request_log_commits(struct tog_view *view)
2744 struct tog_log_view_state *state = &view->state.log;
2745 const struct got_error *err = NULL;
2747 if (state->thread_args.log_complete)
2748 return NULL;
2750 state->thread_args.commits_needed += view->nscrolled;
2751 err = trigger_log_thread(view, 1);
2752 view->nscrolled = 0;
2754 return err;
2757 static const struct got_error *
2758 log_scroll_down(struct tog_view *view, int maxscroll)
2760 struct tog_log_view_state *s = &view->state.log;
2761 const struct got_error *err = NULL;
2762 struct commit_queue_entry *pentry;
2763 int nscrolled = 0, ncommits_needed;
2765 if (s->last_displayed_entry == NULL)
2766 return NULL;
2768 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2769 if (s->commits->ncommits < ncommits_needed &&
2770 !s->thread_args.log_complete) {
2772 * Ask the log thread for required amount of commits.
2774 s->thread_args.commits_needed +=
2775 ncommits_needed - s->commits->ncommits;
2776 err = trigger_log_thread(view, 1);
2777 if (err)
2778 return err;
2781 do {
2782 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2783 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2784 break;
2786 s->last_displayed_entry = pentry ?
2787 pentry : s->last_displayed_entry;
2789 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2790 if (pentry == NULL)
2791 break;
2792 s->first_displayed_entry = pentry;
2793 } while (++nscrolled < maxscroll);
2795 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2796 view->nscrolled += nscrolled;
2797 else
2798 view->nscrolled = 0;
2800 return err;
2803 static const struct got_error *
2804 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2805 struct got_commit_object *commit, struct got_object_id *commit_id,
2806 struct tog_view *log_view, struct got_repository *repo)
2808 const struct got_error *err;
2809 struct got_object_qid *parent_id;
2810 struct tog_view *diff_view;
2812 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2813 if (diff_view == NULL)
2814 return got_error_from_errno("view_open");
2816 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2817 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2818 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2819 if (err == NULL)
2820 *new_view = diff_view;
2821 return err;
2824 static const struct got_error *
2825 tree_view_visit_subtree(struct tog_tree_view_state *s,
2826 struct got_tree_object *subtree)
2828 struct tog_parent_tree *parent;
2830 parent = calloc(1, sizeof(*parent));
2831 if (parent == NULL)
2832 return got_error_from_errno("calloc");
2834 parent->tree = s->tree;
2835 parent->first_displayed_entry = s->first_displayed_entry;
2836 parent->selected_entry = s->selected_entry;
2837 parent->selected = s->selected;
2838 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2839 s->tree = subtree;
2840 s->selected = 0;
2841 s->first_displayed_entry = NULL;
2842 return NULL;
2845 static const struct got_error *
2846 tree_view_walk_path(struct tog_tree_view_state *s,
2847 struct got_commit_object *commit, const char *path)
2849 const struct got_error *err = NULL;
2850 struct got_tree_object *tree = NULL;
2851 const char *p;
2852 char *slash, *subpath = NULL;
2854 /* Walk the path and open corresponding tree objects. */
2855 p = path;
2856 while (*p) {
2857 struct got_tree_entry *te;
2858 struct got_object_id *tree_id;
2859 char *te_name;
2861 while (p[0] == '/')
2862 p++;
2864 /* Ensure the correct subtree entry is selected. */
2865 slash = strchr(p, '/');
2866 if (slash == NULL)
2867 te_name = strdup(p);
2868 else
2869 te_name = strndup(p, slash - p);
2870 if (te_name == NULL) {
2871 err = got_error_from_errno("strndup");
2872 break;
2874 te = got_object_tree_find_entry(s->tree, te_name);
2875 if (te == NULL) {
2876 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2877 free(te_name);
2878 break;
2880 free(te_name);
2881 s->first_displayed_entry = s->selected_entry = te;
2883 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2884 break; /* jump to this file's entry */
2886 slash = strchr(p, '/');
2887 if (slash)
2888 subpath = strndup(path, slash - path);
2889 else
2890 subpath = strdup(path);
2891 if (subpath == NULL) {
2892 err = got_error_from_errno("strdup");
2893 break;
2896 err = got_object_id_by_path(&tree_id, s->repo, commit,
2897 subpath);
2898 if (err)
2899 break;
2901 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2902 free(tree_id);
2903 if (err)
2904 break;
2906 err = tree_view_visit_subtree(s, tree);
2907 if (err) {
2908 got_object_tree_close(tree);
2909 break;
2911 if (slash == NULL)
2912 break;
2913 free(subpath);
2914 subpath = NULL;
2915 p = slash;
2918 free(subpath);
2919 return err;
2922 static const struct got_error *
2923 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2924 struct commit_queue_entry *entry, const char *path,
2925 const char *head_ref_name, struct got_repository *repo)
2927 const struct got_error *err = NULL;
2928 struct tog_tree_view_state *s;
2929 struct tog_view *tree_view;
2931 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2932 if (tree_view == NULL)
2933 return got_error_from_errno("view_open");
2935 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2936 if (err)
2937 return err;
2938 s = &tree_view->state.tree;
2940 *new_view = tree_view;
2942 if (got_path_is_root_dir(path))
2943 return NULL;
2945 return tree_view_walk_path(s, entry->commit, path);
2948 static const struct got_error *
2949 block_signals_used_by_main_thread(void)
2951 sigset_t sigset;
2952 int errcode;
2954 if (sigemptyset(&sigset) == -1)
2955 return got_error_from_errno("sigemptyset");
2957 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2958 if (sigaddset(&sigset, SIGWINCH) == -1)
2959 return got_error_from_errno("sigaddset");
2960 if (sigaddset(&sigset, SIGCONT) == -1)
2961 return got_error_from_errno("sigaddset");
2962 if (sigaddset(&sigset, SIGINT) == -1)
2963 return got_error_from_errno("sigaddset");
2964 if (sigaddset(&sigset, SIGTERM) == -1)
2965 return got_error_from_errno("sigaddset");
2967 /* ncurses handles SIGTSTP */
2968 if (sigaddset(&sigset, SIGTSTP) == -1)
2969 return got_error_from_errno("sigaddset");
2971 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2972 if (errcode)
2973 return got_error_set_errno(errcode, "pthread_sigmask");
2975 return NULL;
2978 static void *
2979 log_thread(void *arg)
2981 const struct got_error *err = NULL;
2982 int errcode = 0;
2983 struct tog_log_thread_args *a = arg;
2984 int done = 0;
2987 * Sync startup with main thread such that we begin our
2988 * work once view_input() has released the mutex.
2990 errcode = pthread_mutex_lock(&tog_mutex);
2991 if (errcode) {
2992 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2993 return (void *)err;
2996 err = block_signals_used_by_main_thread();
2997 if (err) {
2998 pthread_mutex_unlock(&tog_mutex);
2999 goto done;
3002 while (!done && !err && !tog_fatal_signal_received()) {
3003 errcode = pthread_mutex_unlock(&tog_mutex);
3004 if (errcode) {
3005 err = got_error_set_errno(errcode,
3006 "pthread_mutex_unlock");
3007 goto done;
3009 err = queue_commits(a);
3010 if (err) {
3011 if (err->code != GOT_ERR_ITER_COMPLETED)
3012 goto done;
3013 err = NULL;
3014 done = 1;
3015 } else if (a->commits_needed > 0 && !a->load_all) {
3016 if (*a->limiting) {
3017 if (a->limit_match)
3018 a->commits_needed--;
3019 } else
3020 a->commits_needed--;
3023 errcode = pthread_mutex_lock(&tog_mutex);
3024 if (errcode) {
3025 err = got_error_set_errno(errcode,
3026 "pthread_mutex_lock");
3027 goto done;
3028 } else if (*a->quit)
3029 done = 1;
3030 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3031 *a->first_displayed_entry =
3032 TAILQ_FIRST(&a->limit_commits->head);
3033 *a->selected_entry = *a->first_displayed_entry;
3034 } else if (*a->first_displayed_entry == NULL) {
3035 *a->first_displayed_entry =
3036 TAILQ_FIRST(&a->real_commits->head);
3037 *a->selected_entry = *a->first_displayed_entry;
3040 errcode = pthread_cond_signal(&a->commit_loaded);
3041 if (errcode) {
3042 err = got_error_set_errno(errcode,
3043 "pthread_cond_signal");
3044 pthread_mutex_unlock(&tog_mutex);
3045 goto done;
3048 if (done)
3049 a->commits_needed = 0;
3050 else {
3051 if (a->commits_needed == 0 && !a->load_all) {
3052 errcode = pthread_cond_wait(&a->need_commits,
3053 &tog_mutex);
3054 if (errcode) {
3055 err = got_error_set_errno(errcode,
3056 "pthread_cond_wait");
3057 pthread_mutex_unlock(&tog_mutex);
3058 goto done;
3060 if (*a->quit)
3061 done = 1;
3065 a->log_complete = 1;
3066 errcode = pthread_mutex_unlock(&tog_mutex);
3067 if (errcode)
3068 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3069 done:
3070 if (err) {
3071 tog_thread_error = 1;
3072 pthread_cond_signal(&a->commit_loaded);
3074 return (void *)err;
3077 static const struct got_error *
3078 stop_log_thread(struct tog_log_view_state *s)
3080 const struct got_error *err = NULL, *thread_err = NULL;
3081 int errcode;
3083 if (s->thread) {
3084 s->quit = 1;
3085 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3086 if (errcode)
3087 return got_error_set_errno(errcode,
3088 "pthread_cond_signal");
3089 errcode = pthread_mutex_unlock(&tog_mutex);
3090 if (errcode)
3091 return got_error_set_errno(errcode,
3092 "pthread_mutex_unlock");
3093 errcode = pthread_join(s->thread, (void **)&thread_err);
3094 if (errcode)
3095 return got_error_set_errno(errcode, "pthread_join");
3096 errcode = pthread_mutex_lock(&tog_mutex);
3097 if (errcode)
3098 return got_error_set_errno(errcode,
3099 "pthread_mutex_lock");
3100 s->thread = 0; //NULL;
3103 if (s->thread_args.repo) {
3104 err = got_repo_close(s->thread_args.repo);
3105 s->thread_args.repo = NULL;
3108 if (s->thread_args.pack_fds) {
3109 const struct got_error *pack_err =
3110 got_repo_pack_fds_close(s->thread_args.pack_fds);
3111 if (err == NULL)
3112 err = pack_err;
3113 s->thread_args.pack_fds = NULL;
3116 if (s->thread_args.graph) {
3117 got_commit_graph_close(s->thread_args.graph);
3118 s->thread_args.graph = NULL;
3121 return err ? err : thread_err;
3124 static const struct got_error *
3125 close_log_view(struct tog_view *view)
3127 const struct got_error *err = NULL;
3128 struct tog_log_view_state *s = &view->state.log;
3129 int errcode;
3131 err = stop_log_thread(s);
3133 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3134 if (errcode && err == NULL)
3135 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3137 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3138 if (errcode && err == NULL)
3139 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3141 free_commits(&s->limit_commits);
3142 free_commits(&s->real_commits);
3143 free(s->in_repo_path);
3144 s->in_repo_path = NULL;
3145 free(s->start_id);
3146 s->start_id = NULL;
3147 free(s->head_ref_name);
3148 s->head_ref_name = NULL;
3149 return err;
3153 * We use two queues to implement the limit feature: first consists of
3154 * commits matching the current limit_regex; second is the real queue
3155 * of all known commits (real_commits). When the user starts limiting,
3156 * we swap queues such that all movement and displaying functionality
3157 * works with very slight change.
3159 static const struct got_error *
3160 limit_log_view(struct tog_view *view)
3162 struct tog_log_view_state *s = &view->state.log;
3163 struct commit_queue_entry *entry;
3164 struct tog_view *v = view;
3165 const struct got_error *err = NULL;
3166 char pattern[1024];
3167 int ret;
3169 if (view_is_hsplit_top(view))
3170 v = view->child;
3171 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3172 v = view->parent;
3174 /* Get the pattern */
3175 wmove(v->window, v->nlines - 1, 0);
3176 wclrtoeol(v->window);
3177 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3178 nodelay(v->window, FALSE);
3179 nocbreak();
3180 echo();
3181 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3182 cbreak();
3183 noecho();
3184 nodelay(v->window, TRUE);
3185 if (ret == ERR)
3186 return NULL;
3188 if (*pattern == '\0') {
3190 * Safety measure for the situation where the user
3191 * resets limit without previously limiting anything.
3193 if (!s->limit_view)
3194 return NULL;
3197 * User could have pressed Ctrl+L, which refreshed the
3198 * commit queues, it means we can't save previously
3199 * (before limit took place) displayed entries,
3200 * because they would point to already free'ed memory,
3201 * so we are forced to always select first entry of
3202 * the queue.
3204 s->commits = &s->real_commits;
3205 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3206 s->selected_entry = s->first_displayed_entry;
3207 s->selected = 0;
3208 s->limit_view = 0;
3210 return NULL;
3213 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3214 return NULL;
3216 s->limit_view = 1;
3218 /* Clear the screen while loading limit view */
3219 s->first_displayed_entry = NULL;
3220 s->last_displayed_entry = NULL;
3221 s->selected_entry = NULL;
3222 s->commits = &s->limit_commits;
3224 /* Prepare limit queue for new search */
3225 free_commits(&s->limit_commits);
3226 s->limit_commits.ncommits = 0;
3228 /* First process commits, which are in queue already */
3229 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3230 int have_match = 0;
3232 err = match_commit(&have_match, entry->id,
3233 entry->commit, &s->limit_regex);
3234 if (err)
3235 return err;
3237 if (have_match) {
3238 struct commit_queue_entry *matched;
3240 matched = alloc_commit_queue_entry(entry->commit,
3241 entry->id);
3242 if (matched == NULL) {
3243 err = got_error_from_errno(
3244 "alloc_commit_queue_entry");
3245 break;
3247 matched->commit = entry->commit;
3248 got_object_commit_retain(entry->commit);
3250 matched->idx = s->limit_commits.ncommits;
3251 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3252 matched, entry);
3253 s->limit_commits.ncommits++;
3257 /* Second process all the commits, until we fill the screen */
3258 if (s->limit_commits.ncommits < view->nlines - 1 &&
3259 !s->thread_args.log_complete) {
3260 s->thread_args.commits_needed +=
3261 view->nlines - s->limit_commits.ncommits - 1;
3262 err = trigger_log_thread(view, 1);
3263 if (err)
3264 return err;
3267 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3268 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3269 s->selected = 0;
3271 return NULL;
3274 static const struct got_error *
3275 search_start_log_view(struct tog_view *view)
3277 struct tog_log_view_state *s = &view->state.log;
3279 s->matched_entry = NULL;
3280 s->search_entry = NULL;
3281 return NULL;
3284 static const struct got_error *
3285 search_next_log_view(struct tog_view *view)
3287 const struct got_error *err = NULL;
3288 struct tog_log_view_state *s = &view->state.log;
3289 struct commit_queue_entry *entry;
3291 /* Display progress update in log view. */
3292 show_log_view(view);
3293 update_panels();
3294 doupdate();
3296 if (s->search_entry) {
3297 int errcode, ch;
3298 errcode = pthread_mutex_unlock(&tog_mutex);
3299 if (errcode)
3300 return got_error_set_errno(errcode,
3301 "pthread_mutex_unlock");
3302 ch = wgetch(view->window);
3303 errcode = pthread_mutex_lock(&tog_mutex);
3304 if (errcode)
3305 return got_error_set_errno(errcode,
3306 "pthread_mutex_lock");
3307 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3308 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3309 return NULL;
3311 if (view->searching == TOG_SEARCH_FORWARD)
3312 entry = TAILQ_NEXT(s->search_entry, entry);
3313 else
3314 entry = TAILQ_PREV(s->search_entry,
3315 commit_queue_head, entry);
3316 } else if (s->matched_entry) {
3318 * If the user has moved the cursor after we hit a match,
3319 * the position from where we should continue searching
3320 * might have changed.
3322 if (view->searching == TOG_SEARCH_FORWARD)
3323 entry = TAILQ_NEXT(s->selected_entry, entry);
3324 else
3325 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3326 entry);
3327 } else {
3328 entry = s->selected_entry;
3331 while (1) {
3332 int have_match = 0;
3334 if (entry == NULL) {
3335 if (s->thread_args.log_complete ||
3336 view->searching == TOG_SEARCH_BACKWARD) {
3337 view->search_next_done =
3338 (s->matched_entry == NULL ?
3339 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3340 s->search_entry = NULL;
3341 return NULL;
3344 * Poke the log thread for more commits and return,
3345 * allowing the main loop to make progress. Search
3346 * will resume at s->search_entry once we come back.
3348 s->thread_args.commits_needed++;
3349 return trigger_log_thread(view, 0);
3352 err = match_commit(&have_match, entry->id, entry->commit,
3353 &view->regex);
3354 if (err)
3355 break;
3356 if (have_match) {
3357 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3358 s->matched_entry = entry;
3359 break;
3362 s->search_entry = entry;
3363 if (view->searching == TOG_SEARCH_FORWARD)
3364 entry = TAILQ_NEXT(entry, entry);
3365 else
3366 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3369 if (s->matched_entry) {
3370 int cur = s->selected_entry->idx;
3371 while (cur < s->matched_entry->idx) {
3372 err = input_log_view(NULL, view, KEY_DOWN);
3373 if (err)
3374 return err;
3375 cur++;
3377 while (cur > s->matched_entry->idx) {
3378 err = input_log_view(NULL, view, KEY_UP);
3379 if (err)
3380 return err;
3381 cur--;
3385 s->search_entry = NULL;
3387 return NULL;
3390 static const struct got_error *
3391 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3392 struct got_repository *repo, const char *head_ref_name,
3393 const char *in_repo_path, int log_branches)
3395 const struct got_error *err = NULL;
3396 struct tog_log_view_state *s = &view->state.log;
3397 struct got_repository *thread_repo = NULL;
3398 struct got_commit_graph *thread_graph = NULL;
3399 int errcode;
3401 if (in_repo_path != s->in_repo_path) {
3402 free(s->in_repo_path);
3403 s->in_repo_path = strdup(in_repo_path);
3404 if (s->in_repo_path == NULL)
3405 return got_error_from_errno("strdup");
3408 /* The commit queue only contains commits being displayed. */
3409 TAILQ_INIT(&s->real_commits.head);
3410 s->real_commits.ncommits = 0;
3411 s->commits = &s->real_commits;
3413 TAILQ_INIT(&s->limit_commits.head);
3414 s->limit_view = 0;
3415 s->limit_commits.ncommits = 0;
3417 s->repo = repo;
3418 if (head_ref_name) {
3419 s->head_ref_name = strdup(head_ref_name);
3420 if (s->head_ref_name == NULL) {
3421 err = got_error_from_errno("strdup");
3422 goto done;
3425 s->start_id = got_object_id_dup(start_id);
3426 if (s->start_id == NULL) {
3427 err = got_error_from_errno("got_object_id_dup");
3428 goto done;
3430 s->log_branches = log_branches;
3431 s->use_committer = 1;
3433 STAILQ_INIT(&s->colors);
3434 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3435 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3436 get_color_value("TOG_COLOR_COMMIT"));
3437 if (err)
3438 goto done;
3439 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3440 get_color_value("TOG_COLOR_AUTHOR"));
3441 if (err) {
3442 free_colors(&s->colors);
3443 goto done;
3445 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3446 get_color_value("TOG_COLOR_DATE"));
3447 if (err) {
3448 free_colors(&s->colors);
3449 goto done;
3453 view->show = show_log_view;
3454 view->input = input_log_view;
3455 view->resize = resize_log_view;
3456 view->close = close_log_view;
3457 view->search_start = search_start_log_view;
3458 view->search_next = search_next_log_view;
3460 if (s->thread_args.pack_fds == NULL) {
3461 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3462 if (err)
3463 goto done;
3465 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3466 s->thread_args.pack_fds);
3467 if (err)
3468 goto done;
3469 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3470 !s->log_branches);
3471 if (err)
3472 goto done;
3473 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3474 s->repo, NULL, NULL);
3475 if (err)
3476 goto done;
3478 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3479 if (errcode) {
3480 err = got_error_set_errno(errcode, "pthread_cond_init");
3481 goto done;
3483 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3484 if (errcode) {
3485 err = got_error_set_errno(errcode, "pthread_cond_init");
3486 goto done;
3489 s->thread_args.commits_needed = view->nlines;
3490 s->thread_args.graph = thread_graph;
3491 s->thread_args.real_commits = &s->real_commits;
3492 s->thread_args.limit_commits = &s->limit_commits;
3493 s->thread_args.in_repo_path = s->in_repo_path;
3494 s->thread_args.start_id = s->start_id;
3495 s->thread_args.repo = thread_repo;
3496 s->thread_args.log_complete = 0;
3497 s->thread_args.quit = &s->quit;
3498 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3499 s->thread_args.selected_entry = &s->selected_entry;
3500 s->thread_args.searching = &view->searching;
3501 s->thread_args.search_next_done = &view->search_next_done;
3502 s->thread_args.regex = &view->regex;
3503 s->thread_args.limiting = &s->limit_view;
3504 s->thread_args.limit_regex = &s->limit_regex;
3505 s->thread_args.limit_commits = &s->limit_commits;
3506 done:
3507 if (err)
3508 close_log_view(view);
3509 return err;
3512 static const struct got_error *
3513 show_log_view(struct tog_view *view)
3515 const struct got_error *err;
3516 struct tog_log_view_state *s = &view->state.log;
3518 if (s->thread == 0) { //NULL) {
3519 int errcode = pthread_create(&s->thread, NULL, log_thread,
3520 &s->thread_args);
3521 if (errcode)
3522 return got_error_set_errno(errcode, "pthread_create");
3523 if (s->thread_args.commits_needed > 0) {
3524 err = trigger_log_thread(view, 1);
3525 if (err)
3526 return err;
3530 return draw_commits(view);
3533 static void
3534 log_move_cursor_up(struct tog_view *view, int page, int home)
3536 struct tog_log_view_state *s = &view->state.log;
3538 if (s->first_displayed_entry == NULL)
3539 return;
3540 if (s->selected_entry->idx == 0)
3541 view->count = 0;
3543 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3544 || home)
3545 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3547 if (!page && !home && s->selected > 0)
3548 --s->selected;
3549 else
3550 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3552 select_commit(s);
3553 return;
3556 static const struct got_error *
3557 log_move_cursor_down(struct tog_view *view, int page)
3559 struct tog_log_view_state *s = &view->state.log;
3560 const struct got_error *err = NULL;
3561 int eos = view->nlines - 2;
3563 if (s->first_displayed_entry == NULL)
3564 return NULL;
3566 if (s->thread_args.log_complete &&
3567 s->selected_entry->idx >= s->commits->ncommits - 1)
3568 return NULL;
3570 if (view_is_hsplit_top(view))
3571 --eos; /* border consumes the last line */
3573 if (!page) {
3574 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3575 ++s->selected;
3576 else
3577 err = log_scroll_down(view, 1);
3578 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3579 struct commit_queue_entry *entry;
3580 int n;
3582 s->selected = 0;
3583 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3584 s->last_displayed_entry = entry;
3585 for (n = 0; n <= eos; n++) {
3586 if (entry == NULL)
3587 break;
3588 s->first_displayed_entry = entry;
3589 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3591 if (n > 0)
3592 s->selected = n - 1;
3593 } else {
3594 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3595 s->thread_args.log_complete)
3596 s->selected += MIN(page,
3597 s->commits->ncommits - s->selected_entry->idx - 1);
3598 else
3599 err = log_scroll_down(view, page);
3601 if (err)
3602 return err;
3605 * We might necessarily overshoot in horizontal
3606 * splits; if so, select the last displayed commit.
3608 if (s->first_displayed_entry && s->last_displayed_entry) {
3609 s->selected = MIN(s->selected,
3610 s->last_displayed_entry->idx -
3611 s->first_displayed_entry->idx);
3614 select_commit(s);
3616 if (s->thread_args.log_complete &&
3617 s->selected_entry->idx == s->commits->ncommits - 1)
3618 view->count = 0;
3620 return NULL;
3623 static void
3624 view_get_split(struct tog_view *view, int *y, int *x)
3626 *x = 0;
3627 *y = 0;
3629 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3630 if (view->child && view->child->resized_y)
3631 *y = view->child->resized_y;
3632 else if (view->resized_y)
3633 *y = view->resized_y;
3634 else
3635 *y = view_split_begin_y(view->lines);
3636 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3637 if (view->child && view->child->resized_x)
3638 *x = view->child->resized_x;
3639 else if (view->resized_x)
3640 *x = view->resized_x;
3641 else
3642 *x = view_split_begin_x(view->begin_x);
3646 /* Split view horizontally at y and offset view->state->selected line. */
3647 static const struct got_error *
3648 view_init_hsplit(struct tog_view *view, int y)
3650 const struct got_error *err = NULL;
3652 view->nlines = y;
3653 view->ncols = COLS;
3654 err = view_resize(view);
3655 if (err)
3656 return err;
3658 err = offset_selection_down(view);
3660 return err;
3663 static const struct got_error *
3664 log_goto_line(struct tog_view *view, int nlines)
3666 const struct got_error *err = NULL;
3667 struct tog_log_view_state *s = &view->state.log;
3668 int g, idx = s->selected_entry->idx;
3670 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3671 return NULL;
3673 g = view->gline;
3674 view->gline = 0;
3676 if (g >= s->first_displayed_entry->idx + 1 &&
3677 g <= s->last_displayed_entry->idx + 1 &&
3678 g - s->first_displayed_entry->idx - 1 < nlines) {
3679 s->selected = g - s->first_displayed_entry->idx - 1;
3680 select_commit(s);
3681 return NULL;
3684 if (idx + 1 < g) {
3685 err = log_move_cursor_down(view, g - idx - 1);
3686 if (!err && g > s->selected_entry->idx + 1)
3687 err = log_move_cursor_down(view,
3688 g - s->first_displayed_entry->idx - 1);
3689 if (err)
3690 return err;
3691 } else if (idx + 1 > g)
3692 log_move_cursor_up(view, idx - g + 1, 0);
3694 if (g < nlines && s->first_displayed_entry->idx == 0)
3695 s->selected = g - 1;
3697 select_commit(s);
3698 return NULL;
3702 static void
3703 horizontal_scroll_input(struct tog_view *view, int ch)
3706 switch (ch) {
3707 case KEY_LEFT:
3708 case 'h':
3709 view->x -= MIN(view->x, 2);
3710 if (view->x <= 0)
3711 view->count = 0;
3712 break;
3713 case KEY_RIGHT:
3714 case 'l':
3715 if (view->x + view->ncols / 2 < view->maxx)
3716 view->x += 2;
3717 else
3718 view->count = 0;
3719 break;
3720 case '0':
3721 view->x = 0;
3722 break;
3723 case '$':
3724 view->x = MAX(view->maxx - view->ncols / 2, 0);
3725 view->count = 0;
3726 break;
3727 default:
3728 break;
3732 static const struct got_error *
3733 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3735 const struct got_error *err = NULL;
3736 struct tog_log_view_state *s = &view->state.log;
3737 int eos, nscroll;
3739 if (s->thread_args.load_all) {
3740 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3741 s->thread_args.load_all = 0;
3742 else if (s->thread_args.log_complete) {
3743 err = log_move_cursor_down(view, s->commits->ncommits);
3744 s->thread_args.load_all = 0;
3746 if (err)
3747 return err;
3750 eos = nscroll = view->nlines - 1;
3751 if (view_is_hsplit_top(view))
3752 --eos; /* border */
3754 if (view->gline)
3755 return log_goto_line(view, eos);
3757 switch (ch) {
3758 case '&':
3759 err = limit_log_view(view);
3760 break;
3761 case 'q':
3762 s->quit = 1;
3763 break;
3764 case '0':
3765 case '$':
3766 case KEY_RIGHT:
3767 case 'l':
3768 case KEY_LEFT:
3769 case 'h':
3770 horizontal_scroll_input(view, ch);
3771 break;
3772 case 'k':
3773 case KEY_UP:
3774 case '<':
3775 case ',':
3776 case CTRL('p'):
3777 log_move_cursor_up(view, 0, 0);
3778 break;
3779 case 'g':
3780 case '=':
3781 case KEY_HOME:
3782 log_move_cursor_up(view, 0, 1);
3783 view->count = 0;
3784 break;
3785 case CTRL('u'):
3786 case 'u':
3787 nscroll /= 2;
3788 /* FALL THROUGH */
3789 case KEY_PPAGE:
3790 case CTRL('b'):
3791 case 'b':
3792 log_move_cursor_up(view, nscroll, 0);
3793 break;
3794 case 'j':
3795 case KEY_DOWN:
3796 case '>':
3797 case '.':
3798 case CTRL('n'):
3799 err = log_move_cursor_down(view, 0);
3800 break;
3801 case '@':
3802 s->use_committer = !s->use_committer;
3803 view->action = s->use_committer ?
3804 "show committer" : "show commit author";
3805 break;
3806 case 'G':
3807 case '*':
3808 case KEY_END: {
3809 /* We don't know yet how many commits, so we're forced to
3810 * traverse them all. */
3811 view->count = 0;
3812 s->thread_args.load_all = 1;
3813 if (!s->thread_args.log_complete)
3814 return trigger_log_thread(view, 0);
3815 err = log_move_cursor_down(view, s->commits->ncommits);
3816 s->thread_args.load_all = 0;
3817 break;
3819 case CTRL('d'):
3820 case 'd':
3821 nscroll /= 2;
3822 /* FALL THROUGH */
3823 case KEY_NPAGE:
3824 case CTRL('f'):
3825 case 'f':
3826 case ' ':
3827 err = log_move_cursor_down(view, nscroll);
3828 break;
3829 case KEY_RESIZE:
3830 if (s->selected > view->nlines - 2)
3831 s->selected = view->nlines - 2;
3832 if (s->selected > s->commits->ncommits - 1)
3833 s->selected = s->commits->ncommits - 1;
3834 select_commit(s);
3835 if (s->commits->ncommits < view->nlines - 1 &&
3836 !s->thread_args.log_complete) {
3837 s->thread_args.commits_needed += (view->nlines - 1) -
3838 s->commits->ncommits;
3839 err = trigger_log_thread(view, 1);
3841 break;
3842 case KEY_ENTER:
3843 case '\r':
3844 view->count = 0;
3845 if (s->selected_entry == NULL)
3846 break;
3847 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3848 break;
3849 case 'T':
3850 view->count = 0;
3851 if (s->selected_entry == NULL)
3852 break;
3853 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3854 break;
3855 case KEY_BACKSPACE:
3856 case CTRL('l'):
3857 case 'B':
3858 view->count = 0;
3859 if (ch == KEY_BACKSPACE &&
3860 got_path_is_root_dir(s->in_repo_path))
3861 break;
3862 err = stop_log_thread(s);
3863 if (err)
3864 return err;
3865 if (ch == KEY_BACKSPACE) {
3866 char *parent_path;
3867 err = got_path_dirname(&parent_path, s->in_repo_path);
3868 if (err)
3869 return err;
3870 free(s->in_repo_path);
3871 s->in_repo_path = parent_path;
3872 s->thread_args.in_repo_path = s->in_repo_path;
3873 } else if (ch == CTRL('l')) {
3874 struct got_object_id *start_id;
3875 err = got_repo_match_object_id(&start_id, NULL,
3876 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3877 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3878 if (err) {
3879 if (s->head_ref_name == NULL ||
3880 err->code != GOT_ERR_NOT_REF)
3881 return err;
3882 /* Try to cope with deleted references. */
3883 free(s->head_ref_name);
3884 s->head_ref_name = NULL;
3885 err = got_repo_match_object_id(&start_id,
3886 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
3887 &tog_refs, s->repo);
3888 if (err)
3889 return err;
3891 free(s->start_id);
3892 s->start_id = start_id;
3893 s->thread_args.start_id = s->start_id;
3894 } else /* 'B' */
3895 s->log_branches = !s->log_branches;
3897 if (s->thread_args.pack_fds == NULL) {
3898 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3899 if (err)
3900 return err;
3902 err = got_repo_open(&s->thread_args.repo,
3903 got_repo_get_path(s->repo), NULL,
3904 s->thread_args.pack_fds);
3905 if (err)
3906 return err;
3907 tog_free_refs();
3908 err = tog_load_refs(s->repo, 0);
3909 if (err)
3910 return err;
3911 err = got_commit_graph_open(&s->thread_args.graph,
3912 s->in_repo_path, !s->log_branches);
3913 if (err)
3914 return err;
3915 err = got_commit_graph_iter_start(s->thread_args.graph,
3916 s->start_id, s->repo, NULL, NULL);
3917 if (err)
3918 return err;
3919 free_commits(&s->real_commits);
3920 free_commits(&s->limit_commits);
3921 s->first_displayed_entry = NULL;
3922 s->last_displayed_entry = NULL;
3923 s->selected_entry = NULL;
3924 s->selected = 0;
3925 s->thread_args.log_complete = 0;
3926 s->quit = 0;
3927 s->thread_args.commits_needed = view->lines;
3928 s->matched_entry = NULL;
3929 s->search_entry = NULL;
3930 view->offset = 0;
3931 break;
3932 case 'R':
3933 view->count = 0;
3934 err = view_request_new(new_view, view, TOG_VIEW_REF);
3935 break;
3936 default:
3937 view->count = 0;
3938 break;
3941 return err;
3944 static const struct got_error *
3945 apply_unveil(const char *repo_path, const char *worktree_path)
3947 const struct got_error *error;
3949 #ifdef PROFILE
3950 if (unveil("gmon.out", "rwc") != 0)
3951 return got_error_from_errno2("unveil", "gmon.out");
3952 #endif
3953 if (repo_path && unveil(repo_path, "r") != 0)
3954 return got_error_from_errno2("unveil", repo_path);
3956 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3957 return got_error_from_errno2("unveil", worktree_path);
3959 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3960 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3962 error = got_privsep_unveil_exec_helpers();
3963 if (error != NULL)
3964 return error;
3966 if (unveil(NULL, NULL) != 0)
3967 return got_error_from_errno("unveil");
3969 return NULL;
3972 static void
3973 init_curses(void)
3976 * Override default signal handlers before starting ncurses.
3977 * This should prevent ncurses from installing its own
3978 * broken cleanup() signal handler.
3980 signal(SIGWINCH, tog_sigwinch);
3981 signal(SIGPIPE, tog_sigpipe);
3982 signal(SIGCONT, tog_sigcont);
3983 signal(SIGINT, tog_sigint);
3984 signal(SIGTERM, tog_sigterm);
3986 initscr();
3987 cbreak();
3988 halfdelay(1); /* Do fast refresh while initial view is loading. */
3989 noecho();
3990 nonl();
3991 intrflush(stdscr, FALSE);
3992 keypad(stdscr, TRUE);
3993 curs_set(0);
3994 if (getenv("TOG_COLORS") != NULL) {
3995 start_color();
3996 use_default_colors();
4000 static const struct got_error *
4001 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4002 struct got_repository *repo, struct got_worktree *worktree)
4004 const struct got_error *err = NULL;
4006 if (argc == 0) {
4007 *in_repo_path = strdup("/");
4008 if (*in_repo_path == NULL)
4009 return got_error_from_errno("strdup");
4010 return NULL;
4013 if (worktree) {
4014 const char *prefix = got_worktree_get_path_prefix(worktree);
4015 char *p;
4017 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4018 if (err)
4019 return err;
4020 if (asprintf(in_repo_path, "%s%s%s", prefix,
4021 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4022 p) == -1) {
4023 err = got_error_from_errno("asprintf");
4024 *in_repo_path = NULL;
4026 free(p);
4027 } else
4028 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4030 return err;
4033 static const struct got_error *
4034 cmd_log(int argc, char *argv[])
4036 const struct got_error *error;
4037 struct got_repository *repo = NULL;
4038 struct got_worktree *worktree = NULL;
4039 struct got_object_id *start_id = NULL;
4040 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4041 char *start_commit = NULL, *label = NULL;
4042 struct got_reference *ref = NULL;
4043 const char *head_ref_name = NULL;
4044 int ch, log_branches = 0;
4045 struct tog_view *view;
4046 int *pack_fds = NULL;
4048 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4049 switch (ch) {
4050 case 'b':
4051 log_branches = 1;
4052 break;
4053 case 'c':
4054 start_commit = optarg;
4055 break;
4056 case 'r':
4057 repo_path = realpath(optarg, NULL);
4058 if (repo_path == NULL)
4059 return got_error_from_errno2("realpath",
4060 optarg);
4061 break;
4062 default:
4063 usage_log();
4064 /* NOTREACHED */
4068 argc -= optind;
4069 argv += optind;
4071 if (argc > 1)
4072 usage_log();
4074 error = got_repo_pack_fds_open(&pack_fds);
4075 if (error != NULL)
4076 goto done;
4078 if (repo_path == NULL) {
4079 cwd = getcwd(NULL, 0);
4080 if (cwd == NULL)
4081 return got_error_from_errno("getcwd");
4082 error = got_worktree_open(&worktree, cwd);
4083 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4084 goto done;
4085 if (worktree)
4086 repo_path =
4087 strdup(got_worktree_get_repo_path(worktree));
4088 else
4089 repo_path = strdup(cwd);
4090 if (repo_path == NULL) {
4091 error = got_error_from_errno("strdup");
4092 goto done;
4096 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4097 if (error != NULL)
4098 goto done;
4100 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4101 repo, worktree);
4102 if (error)
4103 goto done;
4105 init_curses();
4107 error = apply_unveil(got_repo_get_path(repo),
4108 worktree ? got_worktree_get_root_path(worktree) : NULL);
4109 if (error)
4110 goto done;
4112 /* already loaded by tog_log_with_path()? */
4113 if (TAILQ_EMPTY(&tog_refs)) {
4114 error = tog_load_refs(repo, 0);
4115 if (error)
4116 goto done;
4119 if (start_commit == NULL) {
4120 error = got_repo_match_object_id(&start_id, &label,
4121 worktree ? got_worktree_get_head_ref_name(worktree) :
4122 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4123 if (error)
4124 goto done;
4125 head_ref_name = label;
4126 } else {
4127 error = got_ref_open(&ref, repo, start_commit, 0);
4128 if (error == NULL)
4129 head_ref_name = got_ref_get_name(ref);
4130 else if (error->code != GOT_ERR_NOT_REF)
4131 goto done;
4132 error = got_repo_match_object_id(&start_id, NULL,
4133 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4134 if (error)
4135 goto done;
4138 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4139 if (view == NULL) {
4140 error = got_error_from_errno("view_open");
4141 goto done;
4143 error = open_log_view(view, start_id, repo, head_ref_name,
4144 in_repo_path, log_branches);
4145 if (error)
4146 goto done;
4147 if (worktree) {
4148 /* Release work tree lock. */
4149 got_worktree_close(worktree);
4150 worktree = NULL;
4152 error = view_loop(view);
4153 done:
4154 free(in_repo_path);
4155 free(repo_path);
4156 free(cwd);
4157 free(start_id);
4158 free(label);
4159 if (ref)
4160 got_ref_close(ref);
4161 if (repo) {
4162 const struct got_error *close_err = got_repo_close(repo);
4163 if (error == NULL)
4164 error = close_err;
4166 if (worktree)
4167 got_worktree_close(worktree);
4168 if (pack_fds) {
4169 const struct got_error *pack_err =
4170 got_repo_pack_fds_close(pack_fds);
4171 if (error == NULL)
4172 error = pack_err;
4174 tog_free_refs();
4175 return error;
4178 __dead static void
4179 usage_diff(void)
4181 endwin();
4182 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4183 "object1 object2\n", getprogname());
4184 exit(1);
4187 static int
4188 match_line(const char *line, regex_t *regex, size_t nmatch,
4189 regmatch_t *regmatch)
4191 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4194 static struct tog_color *
4195 match_color(struct tog_colors *colors, const char *line)
4197 struct tog_color *tc = NULL;
4199 STAILQ_FOREACH(tc, colors, entry) {
4200 if (match_line(line, &tc->regex, 0, NULL))
4201 return tc;
4204 return NULL;
4207 static const struct got_error *
4208 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4209 WINDOW *window, int skipcol, regmatch_t *regmatch)
4211 const struct got_error *err = NULL;
4212 char *exstr = NULL;
4213 wchar_t *wline = NULL;
4214 int rme, rms, n, width, scrollx;
4215 int width0 = 0, width1 = 0, width2 = 0;
4216 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4218 *wtotal = 0;
4220 rms = regmatch->rm_so;
4221 rme = regmatch->rm_eo;
4223 err = expand_tab(&exstr, line);
4224 if (err)
4225 return err;
4227 /* Split the line into 3 segments, according to match offsets. */
4228 seg0 = strndup(exstr, rms);
4229 if (seg0 == NULL) {
4230 err = got_error_from_errno("strndup");
4231 goto done;
4233 seg1 = strndup(exstr + rms, rme - rms);
4234 if (seg1 == NULL) {
4235 err = got_error_from_errno("strndup");
4236 goto done;
4238 seg2 = strdup(exstr + rme);
4239 if (seg2 == NULL) {
4240 err = got_error_from_errno("strndup");
4241 goto done;
4244 /* draw up to matched token if we haven't scrolled past it */
4245 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4246 col_tab_align, 1);
4247 if (err)
4248 goto done;
4249 n = MAX(width0 - skipcol, 0);
4250 if (n) {
4251 free(wline);
4252 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4253 wlimit, col_tab_align, 1);
4254 if (err)
4255 goto done;
4256 waddwstr(window, &wline[scrollx]);
4257 wlimit -= width;
4258 *wtotal += width;
4261 if (wlimit > 0) {
4262 int i = 0, w = 0;
4263 size_t wlen;
4265 free(wline);
4266 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4267 col_tab_align, 1);
4268 if (err)
4269 goto done;
4270 wlen = wcslen(wline);
4271 while (i < wlen) {
4272 width = wcwidth(wline[i]);
4273 if (width == -1) {
4274 /* should not happen, tabs are expanded */
4275 err = got_error(GOT_ERR_RANGE);
4276 goto done;
4278 if (width0 + w + width > skipcol)
4279 break;
4280 w += width;
4281 i++;
4283 /* draw (visible part of) matched token (if scrolled into it) */
4284 if (width1 - w > 0) {
4285 wattron(window, A_STANDOUT);
4286 waddwstr(window, &wline[i]);
4287 wattroff(window, A_STANDOUT);
4288 wlimit -= (width1 - w);
4289 *wtotal += (width1 - w);
4293 if (wlimit > 0) { /* draw rest of line */
4294 free(wline);
4295 if (skipcol > width0 + width1) {
4296 err = format_line(&wline, &width2, &scrollx, seg2,
4297 skipcol - (width0 + width1), wlimit,
4298 col_tab_align, 1);
4299 if (err)
4300 goto done;
4301 waddwstr(window, &wline[scrollx]);
4302 } else {
4303 err = format_line(&wline, &width2, NULL, seg2, 0,
4304 wlimit, col_tab_align, 1);
4305 if (err)
4306 goto done;
4307 waddwstr(window, wline);
4309 *wtotal += width2;
4311 done:
4312 free(wline);
4313 free(exstr);
4314 free(seg0);
4315 free(seg1);
4316 free(seg2);
4317 return err;
4320 static int
4321 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4323 FILE *f = NULL;
4324 int *eof, *first, *selected;
4326 if (view->type == TOG_VIEW_DIFF) {
4327 struct tog_diff_view_state *s = &view->state.diff;
4329 first = &s->first_displayed_line;
4330 selected = first;
4331 eof = &s->eof;
4332 f = s->f;
4333 } else if (view->type == TOG_VIEW_HELP) {
4334 struct tog_help_view_state *s = &view->state.help;
4336 first = &s->first_displayed_line;
4337 selected = first;
4338 eof = &s->eof;
4339 f = s->f;
4340 } else if (view->type == TOG_VIEW_BLAME) {
4341 struct tog_blame_view_state *s = &view->state.blame;
4343 first = &s->first_displayed_line;
4344 selected = &s->selected_line;
4345 eof = &s->eof;
4346 f = s->blame.f;
4347 } else
4348 return 0;
4350 /* Center gline in the middle of the page like vi(1). */
4351 if (*lineno < view->gline - (view->nlines - 3) / 2)
4352 return 0;
4353 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4354 rewind(f);
4355 *eof = 0;
4356 *first = 1;
4357 *lineno = 0;
4358 *nprinted = 0;
4359 return 0;
4362 *selected = view->gline <= (view->nlines - 3) / 2 ?
4363 view->gline : (view->nlines - 3) / 2 + 1;
4364 view->gline = 0;
4366 return 1;
4369 static const struct got_error *
4370 draw_file(struct tog_view *view, const char *header)
4372 struct tog_diff_view_state *s = &view->state.diff;
4373 regmatch_t *regmatch = &view->regmatch;
4374 const struct got_error *err;
4375 int nprinted = 0;
4376 char *line;
4377 size_t linesize = 0;
4378 ssize_t linelen;
4379 wchar_t *wline;
4380 int width;
4381 int max_lines = view->nlines;
4382 int nlines = s->nlines;
4383 off_t line_offset;
4385 s->lineno = s->first_displayed_line - 1;
4386 line_offset = s->lines[s->first_displayed_line - 1].offset;
4387 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4388 return got_error_from_errno("fseek");
4390 werase(view->window);
4392 if (view->gline > s->nlines - 1)
4393 view->gline = s->nlines - 1;
4395 if (header) {
4396 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4397 1 : view->gline - (view->nlines - 3) / 2 :
4398 s->lineno + s->selected_line;
4400 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4401 return got_error_from_errno("asprintf");
4402 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4403 0, 0);
4404 free(line);
4405 if (err)
4406 return err;
4408 if (view_needs_focus_indication(view))
4409 wstandout(view->window);
4410 waddwstr(view->window, wline);
4411 free(wline);
4412 wline = NULL;
4413 while (width++ < view->ncols)
4414 waddch(view->window, ' ');
4415 if (view_needs_focus_indication(view))
4416 wstandend(view->window);
4418 if (max_lines <= 1)
4419 return NULL;
4420 max_lines--;
4423 s->eof = 0;
4424 view->maxx = 0;
4425 line = NULL;
4426 while (max_lines > 0 && nprinted < max_lines) {
4427 enum got_diff_line_type linetype;
4428 attr_t attr = 0;
4430 linelen = getline(&line, &linesize, s->f);
4431 if (linelen == -1) {
4432 if (feof(s->f)) {
4433 s->eof = 1;
4434 break;
4436 free(line);
4437 return got_ferror(s->f, GOT_ERR_IO);
4440 if (++s->lineno < s->first_displayed_line)
4441 continue;
4442 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4443 continue;
4444 if (s->lineno == view->hiline)
4445 attr = A_STANDOUT;
4447 /* Set view->maxx based on full line length. */
4448 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4449 view->x ? 1 : 0);
4450 if (err) {
4451 free(line);
4452 return err;
4454 view->maxx = MAX(view->maxx, width);
4455 free(wline);
4456 wline = NULL;
4458 linetype = s->lines[s->lineno].type;
4459 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4460 linetype < GOT_DIFF_LINE_CONTEXT)
4461 attr |= COLOR_PAIR(linetype);
4462 if (attr)
4463 wattron(view->window, attr);
4464 if (s->first_displayed_line + nprinted == s->matched_line &&
4465 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4466 err = add_matched_line(&width, line, view->ncols, 0,
4467 view->window, view->x, regmatch);
4468 if (err) {
4469 free(line);
4470 return err;
4472 } else {
4473 int skip;
4474 err = format_line(&wline, &width, &skip, line,
4475 view->x, view->ncols, 0, view->x ? 1 : 0);
4476 if (err) {
4477 free(line);
4478 return err;
4480 waddwstr(view->window, &wline[skip]);
4481 free(wline);
4482 wline = NULL;
4484 if (s->lineno == view->hiline) {
4485 /* highlight full gline length */
4486 while (width++ < view->ncols)
4487 waddch(view->window, ' ');
4488 } else {
4489 if (width <= view->ncols - 1)
4490 waddch(view->window, '\n');
4492 if (attr)
4493 wattroff(view->window, attr);
4494 if (++nprinted == 1)
4495 s->first_displayed_line = s->lineno;
4497 free(line);
4498 if (nprinted >= 1)
4499 s->last_displayed_line = s->first_displayed_line +
4500 (nprinted - 1);
4501 else
4502 s->last_displayed_line = s->first_displayed_line;
4504 view_border(view);
4506 if (s->eof) {
4507 while (nprinted < view->nlines) {
4508 waddch(view->window, '\n');
4509 nprinted++;
4512 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4513 view->ncols, 0, 0);
4514 if (err) {
4515 return err;
4518 wstandout(view->window);
4519 waddwstr(view->window, wline);
4520 free(wline);
4521 wline = NULL;
4522 wstandend(view->window);
4525 return NULL;
4528 static char *
4529 get_datestr(time_t *time, char *datebuf)
4531 struct tm mytm, *tm;
4532 char *p, *s;
4534 tm = gmtime_r(time, &mytm);
4535 if (tm == NULL)
4536 return NULL;
4537 s = asctime_r(tm, datebuf);
4538 if (s == NULL)
4539 return NULL;
4540 p = strchr(s, '\n');
4541 if (p)
4542 *p = '\0';
4543 return s;
4546 static const struct got_error *
4547 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4548 off_t off, uint8_t type)
4550 struct got_diff_line *p;
4552 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4553 if (p == NULL)
4554 return got_error_from_errno("reallocarray");
4555 *lines = p;
4556 (*lines)[*nlines].offset = off;
4557 (*lines)[*nlines].type = type;
4558 (*nlines)++;
4560 return NULL;
4563 static const struct got_error *
4564 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4565 struct got_diff_line *s_lines, size_t s_nlines)
4567 struct got_diff_line *p;
4568 char buf[BUFSIZ];
4569 size_t i, r;
4571 if (fseeko(src, 0L, SEEK_SET) == -1)
4572 return got_error_from_errno("fseeko");
4574 for (;;) {
4575 r = fread(buf, 1, sizeof(buf), src);
4576 if (r == 0) {
4577 if (ferror(src))
4578 return got_error_from_errno("fread");
4579 if (feof(src))
4580 break;
4582 if (fwrite(buf, 1, r, dst) != r)
4583 return got_ferror(dst, GOT_ERR_IO);
4587 * The diff driver initialises the first line at offset zero when the
4588 * array isn't prepopulated, skip it; we already have it in *d_lines.
4590 for (i = 1; i < s_nlines; ++i)
4591 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4593 --s_nlines;
4595 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4596 if (p == NULL) {
4597 /* d_lines is freed in close_diff_view() */
4598 return got_error_from_errno("reallocarray");
4601 *d_lines = p;
4603 memcpy(*d_lines + *d_nlines, s_lines + 1, s_nlines * sizeof(*s_lines));
4604 *d_nlines += s_nlines;
4606 return NULL;
4609 static const struct got_error *
4610 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4611 struct got_object_id *commit_id, struct got_reflist_head *refs,
4612 struct got_repository *repo, int ignore_ws, int force_text_diff,
4613 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4615 const struct got_error *err = NULL;
4616 char datebuf[26], *datestr;
4617 struct got_commit_object *commit;
4618 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4619 time_t committer_time;
4620 const char *author, *committer;
4621 char *refs_str = NULL;
4622 struct got_pathlist_entry *pe;
4623 off_t outoff = 0;
4624 int n;
4626 if (refs) {
4627 err = build_refs_str(&refs_str, refs, commit_id, repo);
4628 if (err)
4629 return err;
4632 err = got_object_open_as_commit(&commit, repo, commit_id);
4633 if (err)
4634 return err;
4636 err = got_object_id_str(&id_str, commit_id);
4637 if (err) {
4638 err = got_error_from_errno("got_object_id_str");
4639 goto done;
4642 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4643 if (err)
4644 goto done;
4646 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4647 refs_str ? refs_str : "", refs_str ? ")" : "");
4648 if (n < 0) {
4649 err = got_error_from_errno("fprintf");
4650 goto done;
4652 outoff += n;
4653 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4654 if (err)
4655 goto done;
4657 n = fprintf(outfile, "from: %s\n",
4658 got_object_commit_get_author(commit));
4659 if (n < 0) {
4660 err = got_error_from_errno("fprintf");
4661 goto done;
4663 outoff += n;
4664 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4665 if (err)
4666 goto done;
4668 author = got_object_commit_get_author(commit);
4669 committer = got_object_commit_get_committer(commit);
4670 if (strcmp(author, committer) != 0) {
4671 n = fprintf(outfile, "via: %s\n", committer);
4672 if (n < 0) {
4673 err = got_error_from_errno("fprintf");
4674 goto done;
4676 outoff += n;
4677 err = add_line_metadata(lines, nlines, outoff,
4678 GOT_DIFF_LINE_AUTHOR);
4679 if (err)
4680 goto done;
4682 committer_time = got_object_commit_get_committer_time(commit);
4683 datestr = get_datestr(&committer_time, datebuf);
4684 if (datestr) {
4685 n = fprintf(outfile, "date: %s UTC\n", datestr);
4686 if (n < 0) {
4687 err = got_error_from_errno("fprintf");
4688 goto done;
4690 outoff += n;
4691 err = add_line_metadata(lines, nlines, outoff,
4692 GOT_DIFF_LINE_DATE);
4693 if (err)
4694 goto done;
4696 if (got_object_commit_get_nparents(commit) > 1) {
4697 const struct got_object_id_queue *parent_ids;
4698 struct got_object_qid *qid;
4699 int pn = 1;
4700 parent_ids = got_object_commit_get_parent_ids(commit);
4701 STAILQ_FOREACH(qid, parent_ids, entry) {
4702 err = got_object_id_str(&id_str, &qid->id);
4703 if (err)
4704 goto done;
4705 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4706 if (n < 0) {
4707 err = got_error_from_errno("fprintf");
4708 goto done;
4710 outoff += n;
4711 err = add_line_metadata(lines, nlines, outoff,
4712 GOT_DIFF_LINE_META);
4713 if (err)
4714 goto done;
4715 free(id_str);
4716 id_str = NULL;
4720 err = got_object_commit_get_logmsg(&logmsg, commit);
4721 if (err)
4722 goto done;
4723 s = logmsg;
4724 while ((line = strsep(&s, "\n")) != NULL) {
4725 n = fprintf(outfile, "%s\n", line);
4726 if (n < 0) {
4727 err = got_error_from_errno("fprintf");
4728 goto done;
4730 outoff += n;
4731 err = add_line_metadata(lines, nlines, outoff,
4732 GOT_DIFF_LINE_LOGMSG);
4733 if (err)
4734 goto done;
4737 TAILQ_FOREACH(pe, dsa->paths, entry) {
4738 struct got_diff_changed_path *cp = pe->data;
4739 int pad = dsa->max_path_len - pe->path_len + 1;
4741 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4742 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4743 dsa->rm_cols + 1, cp->rm);
4744 if (n < 0) {
4745 err = got_error_from_errno("fprintf");
4746 goto done;
4748 outoff += n;
4749 err = add_line_metadata(lines, nlines, outoff,
4750 GOT_DIFF_LINE_CHANGES);
4751 if (err)
4752 goto done;
4755 fputc('\n', outfile);
4756 outoff++;
4757 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4758 if (err)
4759 goto done;
4761 n = fprintf(outfile,
4762 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4763 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4764 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4765 if (n < 0) {
4766 err = got_error_from_errno("fprintf");
4767 goto done;
4769 outoff += n;
4770 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4771 if (err)
4772 goto done;
4774 fputc('\n', outfile);
4775 outoff++;
4776 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4777 done:
4778 free(id_str);
4779 free(logmsg);
4780 free(refs_str);
4781 got_object_commit_close(commit);
4782 if (err) {
4783 free(*lines);
4784 *lines = NULL;
4785 *nlines = 0;
4787 return err;
4790 static const struct got_error *
4791 create_diff(struct tog_diff_view_state *s)
4793 const struct got_error *err = NULL;
4794 FILE *f = NULL, *tmp_diff_file = NULL;
4795 int obj_type;
4796 struct got_diff_line *lines = NULL;
4797 struct got_pathlist_head changed_paths;
4799 TAILQ_INIT(&changed_paths);
4801 free(s->lines);
4802 s->lines = malloc(sizeof(*s->lines));
4803 if (s->lines == NULL)
4804 return got_error_from_errno("malloc");
4805 s->nlines = 0;
4807 f = got_opentemp();
4808 if (f == NULL) {
4809 err = got_error_from_errno("got_opentemp");
4810 goto done;
4812 tmp_diff_file = got_opentemp();
4813 if (tmp_diff_file == NULL) {
4814 err = got_error_from_errno("got_opentemp");
4815 goto done;
4817 if (s->f && fclose(s->f) == EOF) {
4818 err = got_error_from_errno("fclose");
4819 goto done;
4821 s->f = f;
4823 if (s->id1)
4824 err = got_object_get_type(&obj_type, s->repo, s->id1);
4825 else
4826 err = got_object_get_type(&obj_type, s->repo, s->id2);
4827 if (err)
4828 goto done;
4830 switch (obj_type) {
4831 case GOT_OBJ_TYPE_BLOB:
4832 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4833 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4834 s->label1, s->label2, tog_diff_algo, s->diff_context,
4835 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
4836 s->f);
4837 break;
4838 case GOT_OBJ_TYPE_TREE:
4839 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4840 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4841 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4842 s->force_text_diff, NULL, s->repo, s->f);
4843 break;
4844 case GOT_OBJ_TYPE_COMMIT: {
4845 const struct got_object_id_queue *parent_ids;
4846 struct got_object_qid *pid;
4847 struct got_commit_object *commit2;
4848 struct got_reflist_head *refs;
4849 size_t nlines = 0;
4850 struct got_diffstat_cb_arg dsa = {
4851 0, 0, 0, 0, 0, 0,
4852 &changed_paths,
4853 s->ignore_whitespace,
4854 s->force_text_diff,
4855 tog_diff_algo
4858 lines = malloc(sizeof(*lines));
4859 if (lines == NULL) {
4860 err = got_error_from_errno("malloc");
4861 goto done;
4864 /* build diff first in tmp file then append to commit info */
4865 err = got_diff_objects_as_commits(&lines, &nlines,
4866 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4867 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4868 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
4869 if (err)
4870 break;
4872 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4873 if (err)
4874 goto done;
4875 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4876 /* Show commit info if we're diffing to a parent/root commit. */
4877 if (s->id1 == NULL) {
4878 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4879 refs, s->repo, s->ignore_whitespace,
4880 s->force_text_diff, &dsa, s->f);
4881 if (err)
4882 goto done;
4883 } else {
4884 parent_ids = got_object_commit_get_parent_ids(commit2);
4885 STAILQ_FOREACH(pid, parent_ids, entry) {
4886 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4887 err = write_commit_info(&s->lines,
4888 &s->nlines, s->id2, refs, s->repo,
4889 s->ignore_whitespace,
4890 s->force_text_diff, &dsa, s->f);
4891 if (err)
4892 goto done;
4893 break;
4897 got_object_commit_close(commit2);
4899 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
4900 lines, nlines);
4901 break;
4903 default:
4904 err = got_error(GOT_ERR_OBJ_TYPE);
4905 break;
4907 done:
4908 free(lines);
4909 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4910 if (s->f && fflush(s->f) != 0 && err == NULL)
4911 err = got_error_from_errno("fflush");
4912 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
4913 err = got_error_from_errno("fclose");
4914 return err;
4917 static void
4918 diff_view_indicate_progress(struct tog_view *view)
4920 mvwaddstr(view->window, 0, 0, "diffing...");
4921 update_panels();
4922 doupdate();
4925 static const struct got_error *
4926 search_start_diff_view(struct tog_view *view)
4928 struct tog_diff_view_state *s = &view->state.diff;
4930 s->matched_line = 0;
4931 return NULL;
4934 static void
4935 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4936 size_t *nlines, int **first, int **last, int **match, int **selected)
4938 struct tog_diff_view_state *s = &view->state.diff;
4940 *f = s->f;
4941 *nlines = s->nlines;
4942 *line_offsets = NULL;
4943 *match = &s->matched_line;
4944 *first = &s->first_displayed_line;
4945 *last = &s->last_displayed_line;
4946 *selected = &s->selected_line;
4949 static const struct got_error *
4950 search_next_view_match(struct tog_view *view)
4952 const struct got_error *err = NULL;
4953 FILE *f;
4954 int lineno;
4955 char *line = NULL;
4956 size_t linesize = 0;
4957 ssize_t linelen;
4958 off_t *line_offsets;
4959 size_t nlines = 0;
4960 int *first, *last, *match, *selected;
4962 if (!view->search_setup)
4963 return got_error_msg(GOT_ERR_NOT_IMPL,
4964 "view search not supported");
4965 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4966 &match, &selected);
4968 if (!view->searching) {
4969 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4970 return NULL;
4973 if (*match) {
4974 if (view->searching == TOG_SEARCH_FORWARD)
4975 lineno = *match + 1;
4976 else
4977 lineno = *match - 1;
4978 } else
4979 lineno = *first - 1 + *selected;
4981 while (1) {
4982 off_t offset;
4984 if (lineno <= 0 || lineno > nlines) {
4985 if (*match == 0) {
4986 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4987 break;
4990 if (view->searching == TOG_SEARCH_FORWARD)
4991 lineno = 1;
4992 else
4993 lineno = nlines;
4996 offset = view->type == TOG_VIEW_DIFF ?
4997 view->state.diff.lines[lineno - 1].offset :
4998 line_offsets[lineno - 1];
4999 if (fseeko(f, offset, SEEK_SET) != 0) {
5000 free(line);
5001 return got_error_from_errno("fseeko");
5003 linelen = getline(&line, &linesize, f);
5004 if (linelen != -1) {
5005 char *exstr;
5006 err = expand_tab(&exstr, line);
5007 if (err)
5008 break;
5009 if (match_line(exstr, &view->regex, 1,
5010 &view->regmatch)) {
5011 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5012 *match = lineno;
5013 free(exstr);
5014 break;
5016 free(exstr);
5018 if (view->searching == TOG_SEARCH_FORWARD)
5019 lineno++;
5020 else
5021 lineno--;
5023 free(line);
5025 if (*match) {
5026 *first = *match;
5027 *selected = 1;
5030 return err;
5033 static const struct got_error *
5034 close_diff_view(struct tog_view *view)
5036 const struct got_error *err = NULL;
5037 struct tog_diff_view_state *s = &view->state.diff;
5039 free(s->id1);
5040 s->id1 = NULL;
5041 free(s->id2);
5042 s->id2 = NULL;
5043 if (s->f && fclose(s->f) == EOF)
5044 err = got_error_from_errno("fclose");
5045 s->f = NULL;
5046 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5047 err = got_error_from_errno("fclose");
5048 s->f1 = NULL;
5049 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5050 err = got_error_from_errno("fclose");
5051 s->f2 = NULL;
5052 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5053 err = got_error_from_errno("close");
5054 s->fd1 = -1;
5055 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5056 err = got_error_from_errno("close");
5057 s->fd2 = -1;
5058 free(s->lines);
5059 s->lines = NULL;
5060 s->nlines = 0;
5061 return err;
5064 static const struct got_error *
5065 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5066 struct got_object_id *id2, const char *label1, const char *label2,
5067 int diff_context, int ignore_whitespace, int force_text_diff,
5068 struct tog_view *parent_view, struct got_repository *repo)
5070 const struct got_error *err;
5071 struct tog_diff_view_state *s = &view->state.diff;
5073 memset(s, 0, sizeof(*s));
5074 s->fd1 = -1;
5075 s->fd2 = -1;
5077 if (id1 != NULL && id2 != NULL) {
5078 int type1, type2;
5079 err = got_object_get_type(&type1, repo, id1);
5080 if (err)
5081 return err;
5082 err = got_object_get_type(&type2, repo, id2);
5083 if (err)
5084 return err;
5086 if (type1 != type2)
5087 return got_error(GOT_ERR_OBJ_TYPE);
5089 s->first_displayed_line = 1;
5090 s->last_displayed_line = view->nlines;
5091 s->selected_line = 1;
5092 s->repo = repo;
5093 s->id1 = id1;
5094 s->id2 = id2;
5095 s->label1 = label1;
5096 s->label2 = label2;
5098 if (id1) {
5099 s->id1 = got_object_id_dup(id1);
5100 if (s->id1 == NULL)
5101 return got_error_from_errno("got_object_id_dup");
5102 } else
5103 s->id1 = NULL;
5105 s->id2 = got_object_id_dup(id2);
5106 if (s->id2 == NULL) {
5107 err = got_error_from_errno("got_object_id_dup");
5108 goto done;
5111 s->f1 = got_opentemp();
5112 if (s->f1 == NULL) {
5113 err = got_error_from_errno("got_opentemp");
5114 goto done;
5117 s->f2 = got_opentemp();
5118 if (s->f2 == NULL) {
5119 err = got_error_from_errno("got_opentemp");
5120 goto done;
5123 s->fd1 = got_opentempfd();
5124 if (s->fd1 == -1) {
5125 err = got_error_from_errno("got_opentempfd");
5126 goto done;
5129 s->fd2 = got_opentempfd();
5130 if (s->fd2 == -1) {
5131 err = got_error_from_errno("got_opentempfd");
5132 goto done;
5135 s->diff_context = diff_context;
5136 s->ignore_whitespace = ignore_whitespace;
5137 s->force_text_diff = force_text_diff;
5138 s->parent_view = parent_view;
5139 s->repo = repo;
5141 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5142 int rc;
5144 rc = init_pair(GOT_DIFF_LINE_MINUS,
5145 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5146 if (rc != ERR)
5147 rc = init_pair(GOT_DIFF_LINE_PLUS,
5148 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5149 if (rc != ERR)
5150 rc = init_pair(GOT_DIFF_LINE_HUNK,
5151 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5152 if (rc != ERR)
5153 rc = init_pair(GOT_DIFF_LINE_META,
5154 get_color_value("TOG_COLOR_DIFF_META"), -1);
5155 if (rc != ERR)
5156 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5157 get_color_value("TOG_COLOR_DIFF_META"), -1);
5158 if (rc != ERR)
5159 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5160 get_color_value("TOG_COLOR_DIFF_META"), -1);
5161 if (rc != ERR)
5162 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5163 get_color_value("TOG_COLOR_DIFF_META"), -1);
5164 if (rc != ERR)
5165 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5166 get_color_value("TOG_COLOR_AUTHOR"), -1);
5167 if (rc != ERR)
5168 rc = init_pair(GOT_DIFF_LINE_DATE,
5169 get_color_value("TOG_COLOR_DATE"), -1);
5170 if (rc == ERR) {
5171 err = got_error(GOT_ERR_RANGE);
5172 goto done;
5176 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5177 view_is_splitscreen(view))
5178 show_log_view(parent_view); /* draw border */
5179 diff_view_indicate_progress(view);
5181 err = create_diff(s);
5183 view->show = show_diff_view;
5184 view->input = input_diff_view;
5185 view->reset = reset_diff_view;
5186 view->close = close_diff_view;
5187 view->search_start = search_start_diff_view;
5188 view->search_setup = search_setup_diff_view;
5189 view->search_next = search_next_view_match;
5190 done:
5191 if (err)
5192 close_diff_view(view);
5193 return err;
5196 static const struct got_error *
5197 show_diff_view(struct tog_view *view)
5199 const struct got_error *err;
5200 struct tog_diff_view_state *s = &view->state.diff;
5201 char *id_str1 = NULL, *id_str2, *header;
5202 const char *label1, *label2;
5204 if (s->id1) {
5205 err = got_object_id_str(&id_str1, s->id1);
5206 if (err)
5207 return err;
5208 label1 = s->label1 ? s->label1 : id_str1;
5209 } else
5210 label1 = "/dev/null";
5212 err = got_object_id_str(&id_str2, s->id2);
5213 if (err)
5214 return err;
5215 label2 = s->label2 ? s->label2 : id_str2;
5217 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5218 err = got_error_from_errno("asprintf");
5219 free(id_str1);
5220 free(id_str2);
5221 return err;
5223 free(id_str1);
5224 free(id_str2);
5226 err = draw_file(view, header);
5227 free(header);
5228 return err;
5231 static const struct got_error *
5232 set_selected_commit(struct tog_diff_view_state *s,
5233 struct commit_queue_entry *entry)
5235 const struct got_error *err;
5236 const struct got_object_id_queue *parent_ids;
5237 struct got_commit_object *selected_commit;
5238 struct got_object_qid *pid;
5240 free(s->id2);
5241 s->id2 = got_object_id_dup(entry->id);
5242 if (s->id2 == NULL)
5243 return got_error_from_errno("got_object_id_dup");
5245 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5246 if (err)
5247 return err;
5248 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5249 free(s->id1);
5250 pid = STAILQ_FIRST(parent_ids);
5251 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5252 got_object_commit_close(selected_commit);
5253 return NULL;
5256 static const struct got_error *
5257 reset_diff_view(struct tog_view *view)
5259 struct tog_diff_view_state *s = &view->state.diff;
5261 view->count = 0;
5262 wclear(view->window);
5263 s->first_displayed_line = 1;
5264 s->last_displayed_line = view->nlines;
5265 s->matched_line = 0;
5266 diff_view_indicate_progress(view);
5267 return create_diff(s);
5270 static void
5271 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5273 int start, i;
5275 i = start = s->first_displayed_line - 1;
5277 while (s->lines[i].type != type) {
5278 if (i == 0)
5279 i = s->nlines - 1;
5280 if (--i == start)
5281 return; /* do nothing, requested type not in file */
5284 s->selected_line = 1;
5285 s->first_displayed_line = i;
5288 static void
5289 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5291 int start, i;
5293 i = start = s->first_displayed_line + 1;
5295 while (s->lines[i].type != type) {
5296 if (i == s->nlines - 1)
5297 i = 0;
5298 if (++i == start)
5299 return; /* do nothing, requested type not in file */
5302 s->selected_line = 1;
5303 s->first_displayed_line = i;
5306 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5307 int, int, int);
5308 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5309 int, int);
5311 static const struct got_error *
5312 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5314 const struct got_error *err = NULL;
5315 struct tog_diff_view_state *s = &view->state.diff;
5316 struct tog_log_view_state *ls;
5317 struct commit_queue_entry *old_selected_entry;
5318 char *line = NULL;
5319 size_t linesize = 0;
5320 ssize_t linelen;
5321 int i, nscroll = view->nlines - 1, up = 0;
5323 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5325 switch (ch) {
5326 case '0':
5327 case '$':
5328 case KEY_RIGHT:
5329 case 'l':
5330 case KEY_LEFT:
5331 case 'h':
5332 horizontal_scroll_input(view, ch);
5333 break;
5334 case 'a':
5335 case 'w':
5336 if (ch == 'a') {
5337 s->force_text_diff = !s->force_text_diff;
5338 view->action = s->force_text_diff ?
5339 "force ASCII text enabled" :
5340 "force ASCII text disabled";
5342 else if (ch == 'w') {
5343 s->ignore_whitespace = !s->ignore_whitespace;
5344 view->action = s->ignore_whitespace ?
5345 "ignore whitespace enabled" :
5346 "ignore whitespace disabled";
5348 err = reset_diff_view(view);
5349 break;
5350 case 'g':
5351 case KEY_HOME:
5352 s->first_displayed_line = 1;
5353 view->count = 0;
5354 break;
5355 case 'G':
5356 case KEY_END:
5357 view->count = 0;
5358 if (s->eof)
5359 break;
5361 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5362 s->eof = 1;
5363 break;
5364 case 'k':
5365 case KEY_UP:
5366 case CTRL('p'):
5367 if (s->first_displayed_line > 1)
5368 s->first_displayed_line--;
5369 else
5370 view->count = 0;
5371 break;
5372 case CTRL('u'):
5373 case 'u':
5374 nscroll /= 2;
5375 /* FALL THROUGH */
5376 case KEY_PPAGE:
5377 case CTRL('b'):
5378 case 'b':
5379 if (s->first_displayed_line == 1) {
5380 view->count = 0;
5381 break;
5383 i = 0;
5384 while (i++ < nscroll && s->first_displayed_line > 1)
5385 s->first_displayed_line--;
5386 break;
5387 case 'j':
5388 case KEY_DOWN:
5389 case CTRL('n'):
5390 if (!s->eof)
5391 s->first_displayed_line++;
5392 else
5393 view->count = 0;
5394 break;
5395 case CTRL('d'):
5396 case 'd':
5397 nscroll /= 2;
5398 /* FALL THROUGH */
5399 case KEY_NPAGE:
5400 case CTRL('f'):
5401 case 'f':
5402 case ' ':
5403 if (s->eof) {
5404 view->count = 0;
5405 break;
5407 i = 0;
5408 while (!s->eof && i++ < nscroll) {
5409 linelen = getline(&line, &linesize, s->f);
5410 s->first_displayed_line++;
5411 if (linelen == -1) {
5412 if (feof(s->f)) {
5413 s->eof = 1;
5414 } else
5415 err = got_ferror(s->f, GOT_ERR_IO);
5416 break;
5419 free(line);
5420 break;
5421 case '(':
5422 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5423 break;
5424 case ')':
5425 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5426 break;
5427 case '{':
5428 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5429 break;
5430 case '}':
5431 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5432 break;
5433 case '[':
5434 if (s->diff_context > 0) {
5435 s->diff_context--;
5436 s->matched_line = 0;
5437 diff_view_indicate_progress(view);
5438 err = create_diff(s);
5439 if (s->first_displayed_line + view->nlines - 1 >
5440 s->nlines) {
5441 s->first_displayed_line = 1;
5442 s->last_displayed_line = view->nlines;
5444 } else
5445 view->count = 0;
5446 break;
5447 case ']':
5448 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5449 s->diff_context++;
5450 s->matched_line = 0;
5451 diff_view_indicate_progress(view);
5452 err = create_diff(s);
5453 } else
5454 view->count = 0;
5455 break;
5456 case '<':
5457 case ',':
5458 case 'K':
5459 up = 1;
5460 /* FALL THROUGH */
5461 case '>':
5462 case '.':
5463 case 'J':
5464 if (s->parent_view == NULL) {
5465 view->count = 0;
5466 break;
5468 s->parent_view->count = view->count;
5470 if (s->parent_view->type == TOG_VIEW_LOG) {
5471 ls = &s->parent_view->state.log;
5472 old_selected_entry = ls->selected_entry;
5474 err = input_log_view(NULL, s->parent_view,
5475 up ? KEY_UP : KEY_DOWN);
5476 if (err)
5477 break;
5478 view->count = s->parent_view->count;
5480 if (old_selected_entry == ls->selected_entry)
5481 break;
5483 err = set_selected_commit(s, ls->selected_entry);
5484 if (err)
5485 break;
5486 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5487 struct tog_blame_view_state *bs;
5488 struct got_object_id *id, *prev_id;
5490 bs = &s->parent_view->state.blame;
5491 prev_id = get_annotation_for_line(bs->blame.lines,
5492 bs->blame.nlines, bs->last_diffed_line);
5494 err = input_blame_view(&view, s->parent_view,
5495 up ? KEY_UP : KEY_DOWN);
5496 if (err)
5497 break;
5498 view->count = s->parent_view->count;
5500 if (prev_id == NULL)
5501 break;
5502 id = get_selected_commit_id(bs->blame.lines,
5503 bs->blame.nlines, bs->first_displayed_line,
5504 bs->selected_line);
5505 if (id == NULL)
5506 break;
5508 if (!got_object_id_cmp(prev_id, id))
5509 break;
5511 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5512 if (err)
5513 break;
5515 s->first_displayed_line = 1;
5516 s->last_displayed_line = view->nlines;
5517 s->matched_line = 0;
5518 view->x = 0;
5520 diff_view_indicate_progress(view);
5521 err = create_diff(s);
5522 break;
5523 default:
5524 view->count = 0;
5525 break;
5528 return err;
5531 static const struct got_error *
5532 cmd_diff(int argc, char *argv[])
5534 const struct got_error *error = NULL;
5535 struct got_repository *repo = NULL;
5536 struct got_worktree *worktree = NULL;
5537 struct got_object_id *id1 = NULL, *id2 = NULL;
5538 char *repo_path = NULL, *cwd = NULL;
5539 char *id_str1 = NULL, *id_str2 = NULL;
5540 char *label1 = NULL, *label2 = NULL;
5541 int diff_context = 3, ignore_whitespace = 0;
5542 int ch, force_text_diff = 0;
5543 const char *errstr;
5544 struct tog_view *view;
5545 int *pack_fds = NULL;
5547 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5548 switch (ch) {
5549 case 'a':
5550 force_text_diff = 1;
5551 break;
5552 case 'C':
5553 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5554 &errstr);
5555 if (errstr != NULL)
5556 errx(1, "number of context lines is %s: %s",
5557 errstr, errstr);
5558 break;
5559 case 'r':
5560 repo_path = realpath(optarg, NULL);
5561 if (repo_path == NULL)
5562 return got_error_from_errno2("realpath",
5563 optarg);
5564 got_path_strip_trailing_slashes(repo_path);
5565 break;
5566 case 'w':
5567 ignore_whitespace = 1;
5568 break;
5569 default:
5570 usage_diff();
5571 /* NOTREACHED */
5575 argc -= optind;
5576 argv += optind;
5578 if (argc == 0) {
5579 usage_diff(); /* TODO show local worktree changes */
5580 } else if (argc == 2) {
5581 id_str1 = argv[0];
5582 id_str2 = argv[1];
5583 } else
5584 usage_diff();
5586 error = got_repo_pack_fds_open(&pack_fds);
5587 if (error)
5588 goto done;
5590 if (repo_path == NULL) {
5591 cwd = getcwd(NULL, 0);
5592 if (cwd == NULL)
5593 return got_error_from_errno("getcwd");
5594 error = got_worktree_open(&worktree, cwd);
5595 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5596 goto done;
5597 if (worktree)
5598 repo_path =
5599 strdup(got_worktree_get_repo_path(worktree));
5600 else
5601 repo_path = strdup(cwd);
5602 if (repo_path == NULL) {
5603 error = got_error_from_errno("strdup");
5604 goto done;
5608 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5609 if (error)
5610 goto done;
5612 init_curses();
5614 error = apply_unveil(got_repo_get_path(repo), NULL);
5615 if (error)
5616 goto done;
5618 error = tog_load_refs(repo, 0);
5619 if (error)
5620 goto done;
5622 error = got_repo_match_object_id(&id1, &label1, id_str1,
5623 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5624 if (error)
5625 goto done;
5627 error = got_repo_match_object_id(&id2, &label2, id_str2,
5628 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5629 if (error)
5630 goto done;
5632 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5633 if (view == NULL) {
5634 error = got_error_from_errno("view_open");
5635 goto done;
5637 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5638 ignore_whitespace, force_text_diff, NULL, repo);
5639 if (error)
5640 goto done;
5641 error = view_loop(view);
5642 done:
5643 free(label1);
5644 free(label2);
5645 free(repo_path);
5646 free(cwd);
5647 if (repo) {
5648 const struct got_error *close_err = got_repo_close(repo);
5649 if (error == NULL)
5650 error = close_err;
5652 if (worktree)
5653 got_worktree_close(worktree);
5654 if (pack_fds) {
5655 const struct got_error *pack_err =
5656 got_repo_pack_fds_close(pack_fds);
5657 if (error == NULL)
5658 error = pack_err;
5660 tog_free_refs();
5661 return error;
5664 __dead static void
5665 usage_blame(void)
5667 endwin();
5668 fprintf(stderr,
5669 "usage: %s blame [-c commit] [-r repository-path] path\n",
5670 getprogname());
5671 exit(1);
5674 struct tog_blame_line {
5675 int annotated;
5676 struct got_object_id *id;
5679 static const struct got_error *
5680 draw_blame(struct tog_view *view)
5682 struct tog_blame_view_state *s = &view->state.blame;
5683 struct tog_blame *blame = &s->blame;
5684 regmatch_t *regmatch = &view->regmatch;
5685 const struct got_error *err;
5686 int lineno = 0, nprinted = 0;
5687 char *line = NULL;
5688 size_t linesize = 0;
5689 ssize_t linelen;
5690 wchar_t *wline;
5691 int width;
5692 struct tog_blame_line *blame_line;
5693 struct got_object_id *prev_id = NULL;
5694 char *id_str;
5695 struct tog_color *tc;
5697 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5698 if (err)
5699 return err;
5701 rewind(blame->f);
5702 werase(view->window);
5704 if (asprintf(&line, "commit %s", id_str) == -1) {
5705 err = got_error_from_errno("asprintf");
5706 free(id_str);
5707 return err;
5710 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5711 free(line);
5712 line = NULL;
5713 if (err)
5714 return err;
5715 if (view_needs_focus_indication(view))
5716 wstandout(view->window);
5717 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5718 if (tc)
5719 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5720 waddwstr(view->window, wline);
5721 while (width++ < view->ncols)
5722 waddch(view->window, ' ');
5723 if (tc)
5724 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5725 if (view_needs_focus_indication(view))
5726 wstandend(view->window);
5727 free(wline);
5728 wline = NULL;
5730 if (view->gline > blame->nlines)
5731 view->gline = blame->nlines;
5733 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5734 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5735 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5736 free(id_str);
5737 return got_error_from_errno("asprintf");
5739 free(id_str);
5740 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5741 free(line);
5742 line = NULL;
5743 if (err)
5744 return err;
5745 waddwstr(view->window, wline);
5746 free(wline);
5747 wline = NULL;
5748 if (width < view->ncols - 1)
5749 waddch(view->window, '\n');
5751 s->eof = 0;
5752 view->maxx = 0;
5753 while (nprinted < view->nlines - 2) {
5754 linelen = getline(&line, &linesize, blame->f);
5755 if (linelen == -1) {
5756 if (feof(blame->f)) {
5757 s->eof = 1;
5758 break;
5760 free(line);
5761 return got_ferror(blame->f, GOT_ERR_IO);
5763 if (++lineno < s->first_displayed_line)
5764 continue;
5765 if (view->gline && !gotoline(view, &lineno, &nprinted))
5766 continue;
5768 /* Set view->maxx based on full line length. */
5769 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5770 if (err) {
5771 free(line);
5772 return err;
5774 free(wline);
5775 wline = NULL;
5776 view->maxx = MAX(view->maxx, width);
5778 if (nprinted == s->selected_line - 1)
5779 wstandout(view->window);
5781 if (blame->nlines > 0) {
5782 blame_line = &blame->lines[lineno - 1];
5783 if (blame_line->annotated && prev_id &&
5784 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5785 !(nprinted == s->selected_line - 1)) {
5786 waddstr(view->window, " ");
5787 } else if (blame_line->annotated) {
5788 char *id_str;
5789 err = got_object_id_str(&id_str,
5790 blame_line->id);
5791 if (err) {
5792 free(line);
5793 return err;
5795 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5796 if (tc)
5797 wattr_on(view->window,
5798 COLOR_PAIR(tc->colorpair), NULL);
5799 wprintw(view->window, "%.8s", id_str);
5800 if (tc)
5801 wattr_off(view->window,
5802 COLOR_PAIR(tc->colorpair), NULL);
5803 free(id_str);
5804 prev_id = blame_line->id;
5805 } else {
5806 waddstr(view->window, "........");
5807 prev_id = NULL;
5809 } else {
5810 waddstr(view->window, "........");
5811 prev_id = NULL;
5814 if (nprinted == s->selected_line - 1)
5815 wstandend(view->window);
5816 waddstr(view->window, " ");
5818 if (view->ncols <= 9) {
5819 width = 9;
5820 } else if (s->first_displayed_line + nprinted ==
5821 s->matched_line &&
5822 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5823 err = add_matched_line(&width, line, view->ncols - 9, 9,
5824 view->window, view->x, regmatch);
5825 if (err) {
5826 free(line);
5827 return err;
5829 width += 9;
5830 } else {
5831 int skip;
5832 err = format_line(&wline, &width, &skip, line,
5833 view->x, view->ncols - 9, 9, 1);
5834 if (err) {
5835 free(line);
5836 return err;
5838 waddwstr(view->window, &wline[skip]);
5839 width += 9;
5840 free(wline);
5841 wline = NULL;
5844 if (width <= view->ncols - 1)
5845 waddch(view->window, '\n');
5846 if (++nprinted == 1)
5847 s->first_displayed_line = lineno;
5849 free(line);
5850 s->last_displayed_line = lineno;
5852 view_border(view);
5854 return NULL;
5857 static const struct got_error *
5858 blame_cb(void *arg, int nlines, int lineno,
5859 struct got_commit_object *commit, struct got_object_id *id)
5861 const struct got_error *err = NULL;
5862 struct tog_blame_cb_args *a = arg;
5863 struct tog_blame_line *line;
5864 int errcode;
5866 if (nlines != a->nlines ||
5867 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5868 return got_error(GOT_ERR_RANGE);
5870 errcode = pthread_mutex_lock(&tog_mutex);
5871 if (errcode)
5872 return got_error_set_errno(errcode, "pthread_mutex_lock");
5874 if (*a->quit) { /* user has quit the blame view */
5875 err = got_error(GOT_ERR_ITER_COMPLETED);
5876 goto done;
5879 if (lineno == -1)
5880 goto done; /* no change in this commit */
5882 line = &a->lines[lineno - 1];
5883 if (line->annotated)
5884 goto done;
5886 line->id = got_object_id_dup(id);
5887 if (line->id == NULL) {
5888 err = got_error_from_errno("got_object_id_dup");
5889 goto done;
5891 line->annotated = 1;
5892 done:
5893 errcode = pthread_mutex_unlock(&tog_mutex);
5894 if (errcode)
5895 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5896 return err;
5899 static void *
5900 blame_thread(void *arg)
5902 const struct got_error *err, *close_err;
5903 struct tog_blame_thread_args *ta = arg;
5904 struct tog_blame_cb_args *a = ta->cb_args;
5905 int errcode, fd1 = -1, fd2 = -1;
5906 FILE *f1 = NULL, *f2 = NULL;
5908 fd1 = got_opentempfd();
5909 if (fd1 == -1)
5910 return (void *)got_error_from_errno("got_opentempfd");
5912 fd2 = got_opentempfd();
5913 if (fd2 == -1) {
5914 err = got_error_from_errno("got_opentempfd");
5915 goto done;
5918 f1 = got_opentemp();
5919 if (f1 == NULL) {
5920 err = (void *)got_error_from_errno("got_opentemp");
5921 goto done;
5923 f2 = got_opentemp();
5924 if (f2 == NULL) {
5925 err = (void *)got_error_from_errno("got_opentemp");
5926 goto done;
5929 err = block_signals_used_by_main_thread();
5930 if (err)
5931 goto done;
5933 err = got_blame(ta->path, a->commit_id, ta->repo,
5934 tog_diff_algo, blame_cb, ta->cb_args,
5935 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5936 if (err && err->code == GOT_ERR_CANCELLED)
5937 err = NULL;
5939 errcode = pthread_mutex_lock(&tog_mutex);
5940 if (errcode) {
5941 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5942 goto done;
5945 close_err = got_repo_close(ta->repo);
5946 if (err == NULL)
5947 err = close_err;
5948 ta->repo = NULL;
5949 *ta->complete = 1;
5951 errcode = pthread_mutex_unlock(&tog_mutex);
5952 if (errcode && err == NULL)
5953 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5955 done:
5956 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5957 err = got_error_from_errno("close");
5958 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5959 err = got_error_from_errno("close");
5960 if (f1 && fclose(f1) == EOF && err == NULL)
5961 err = got_error_from_errno("fclose");
5962 if (f2 && fclose(f2) == EOF && err == NULL)
5963 err = got_error_from_errno("fclose");
5965 return (void *)err;
5968 static struct got_object_id *
5969 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5970 int first_displayed_line, int selected_line)
5972 struct tog_blame_line *line;
5974 if (nlines <= 0)
5975 return NULL;
5977 line = &lines[first_displayed_line - 1 + selected_line - 1];
5978 if (!line->annotated)
5979 return NULL;
5981 return line->id;
5984 static struct got_object_id *
5985 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5986 int lineno)
5988 struct tog_blame_line *line;
5990 if (nlines <= 0 || lineno >= nlines)
5991 return NULL;
5993 line = &lines[lineno - 1];
5994 if (!line->annotated)
5995 return NULL;
5997 return line->id;
6000 static const struct got_error *
6001 stop_blame(struct tog_blame *blame)
6003 const struct got_error *err = NULL;
6004 int i;
6006 if (blame->thread) {
6007 int errcode;
6008 errcode = pthread_mutex_unlock(&tog_mutex);
6009 if (errcode)
6010 return got_error_set_errno(errcode,
6011 "pthread_mutex_unlock");
6012 errcode = pthread_join(blame->thread, (void **)&err);
6013 if (errcode)
6014 return got_error_set_errno(errcode, "pthread_join");
6015 errcode = pthread_mutex_lock(&tog_mutex);
6016 if (errcode)
6017 return got_error_set_errno(errcode,
6018 "pthread_mutex_lock");
6019 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6020 err = NULL;
6021 blame->thread = 0; //NULL;
6023 if (blame->thread_args.repo) {
6024 const struct got_error *close_err;
6025 close_err = got_repo_close(blame->thread_args.repo);
6026 if (err == NULL)
6027 err = close_err;
6028 blame->thread_args.repo = NULL;
6030 if (blame->f) {
6031 if (fclose(blame->f) == EOF && err == NULL)
6032 err = got_error_from_errno("fclose");
6033 blame->f = NULL;
6035 if (blame->lines) {
6036 for (i = 0; i < blame->nlines; i++)
6037 free(blame->lines[i].id);
6038 free(blame->lines);
6039 blame->lines = NULL;
6041 free(blame->cb_args.commit_id);
6042 blame->cb_args.commit_id = NULL;
6043 if (blame->pack_fds) {
6044 const struct got_error *pack_err =
6045 got_repo_pack_fds_close(blame->pack_fds);
6046 if (err == NULL)
6047 err = pack_err;
6048 blame->pack_fds = NULL;
6050 return err;
6053 static const struct got_error *
6054 cancel_blame_view(void *arg)
6056 const struct got_error *err = NULL;
6057 int *done = arg;
6058 int errcode;
6060 errcode = pthread_mutex_lock(&tog_mutex);
6061 if (errcode)
6062 return got_error_set_errno(errcode,
6063 "pthread_mutex_unlock");
6065 if (*done)
6066 err = got_error(GOT_ERR_CANCELLED);
6068 errcode = pthread_mutex_unlock(&tog_mutex);
6069 if (errcode)
6070 return got_error_set_errno(errcode,
6071 "pthread_mutex_lock");
6073 return err;
6076 static const struct got_error *
6077 run_blame(struct tog_view *view)
6079 struct tog_blame_view_state *s = &view->state.blame;
6080 struct tog_blame *blame = &s->blame;
6081 const struct got_error *err = NULL;
6082 struct got_commit_object *commit = NULL;
6083 struct got_blob_object *blob = NULL;
6084 struct got_repository *thread_repo = NULL;
6085 struct got_object_id *obj_id = NULL;
6086 int obj_type, fd = -1;
6087 int *pack_fds = NULL;
6089 err = got_object_open_as_commit(&commit, s->repo,
6090 &s->blamed_commit->id);
6091 if (err)
6092 return err;
6094 fd = got_opentempfd();
6095 if (fd == -1) {
6096 err = got_error_from_errno("got_opentempfd");
6097 goto done;
6100 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6101 if (err)
6102 goto done;
6104 err = got_object_get_type(&obj_type, s->repo, obj_id);
6105 if (err)
6106 goto done;
6108 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6109 err = got_error(GOT_ERR_OBJ_TYPE);
6110 goto done;
6113 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6114 if (err)
6115 goto done;
6116 blame->f = got_opentemp();
6117 if (blame->f == NULL) {
6118 err = got_error_from_errno("got_opentemp");
6119 goto done;
6121 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6122 &blame->line_offsets, blame->f, blob);
6123 if (err)
6124 goto done;
6125 if (blame->nlines == 0) {
6126 s->blame_complete = 1;
6127 goto done;
6130 /* Don't include \n at EOF in the blame line count. */
6131 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6132 blame->nlines--;
6134 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6135 if (blame->lines == NULL) {
6136 err = got_error_from_errno("calloc");
6137 goto done;
6140 err = got_repo_pack_fds_open(&pack_fds);
6141 if (err)
6142 goto done;
6143 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6144 pack_fds);
6145 if (err)
6146 goto done;
6148 blame->pack_fds = pack_fds;
6149 blame->cb_args.view = view;
6150 blame->cb_args.lines = blame->lines;
6151 blame->cb_args.nlines = blame->nlines;
6152 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6153 if (blame->cb_args.commit_id == NULL) {
6154 err = got_error_from_errno("got_object_id_dup");
6155 goto done;
6157 blame->cb_args.quit = &s->done;
6159 blame->thread_args.path = s->path;
6160 blame->thread_args.repo = thread_repo;
6161 blame->thread_args.cb_args = &blame->cb_args;
6162 blame->thread_args.complete = &s->blame_complete;
6163 blame->thread_args.cancel_cb = cancel_blame_view;
6164 blame->thread_args.cancel_arg = &s->done;
6165 s->blame_complete = 0;
6167 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6168 s->first_displayed_line = 1;
6169 s->last_displayed_line = view->nlines;
6170 s->selected_line = 1;
6172 s->matched_line = 0;
6174 done:
6175 if (commit)
6176 got_object_commit_close(commit);
6177 if (fd != -1 && close(fd) == -1 && err == NULL)
6178 err = got_error_from_errno("close");
6179 if (blob)
6180 got_object_blob_close(blob);
6181 free(obj_id);
6182 if (err)
6183 stop_blame(blame);
6184 return err;
6187 static const struct got_error *
6188 open_blame_view(struct tog_view *view, char *path,
6189 struct got_object_id *commit_id, struct got_repository *repo)
6191 const struct got_error *err = NULL;
6192 struct tog_blame_view_state *s = &view->state.blame;
6194 STAILQ_INIT(&s->blamed_commits);
6196 s->path = strdup(path);
6197 if (s->path == NULL)
6198 return got_error_from_errno("strdup");
6200 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6201 if (err) {
6202 free(s->path);
6203 return err;
6206 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6207 s->first_displayed_line = 1;
6208 s->last_displayed_line = view->nlines;
6209 s->selected_line = 1;
6210 s->blame_complete = 0;
6211 s->repo = repo;
6212 s->commit_id = commit_id;
6213 memset(&s->blame, 0, sizeof(s->blame));
6215 STAILQ_INIT(&s->colors);
6216 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6217 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6218 get_color_value("TOG_COLOR_COMMIT"));
6219 if (err)
6220 return err;
6223 view->show = show_blame_view;
6224 view->input = input_blame_view;
6225 view->reset = reset_blame_view;
6226 view->close = close_blame_view;
6227 view->search_start = search_start_blame_view;
6228 view->search_setup = search_setup_blame_view;
6229 view->search_next = search_next_view_match;
6231 return run_blame(view);
6234 static const struct got_error *
6235 close_blame_view(struct tog_view *view)
6237 const struct got_error *err = NULL;
6238 struct tog_blame_view_state *s = &view->state.blame;
6240 if (s->blame.thread)
6241 err = stop_blame(&s->blame);
6243 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6244 struct got_object_qid *blamed_commit;
6245 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6246 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6247 got_object_qid_free(blamed_commit);
6250 free(s->path);
6251 free_colors(&s->colors);
6252 return err;
6255 static const struct got_error *
6256 search_start_blame_view(struct tog_view *view)
6258 struct tog_blame_view_state *s = &view->state.blame;
6260 s->matched_line = 0;
6261 return NULL;
6264 static void
6265 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6266 size_t *nlines, int **first, int **last, int **match, int **selected)
6268 struct tog_blame_view_state *s = &view->state.blame;
6270 *f = s->blame.f;
6271 *nlines = s->blame.nlines;
6272 *line_offsets = s->blame.line_offsets;
6273 *match = &s->matched_line;
6274 *first = &s->first_displayed_line;
6275 *last = &s->last_displayed_line;
6276 *selected = &s->selected_line;
6279 static const struct got_error *
6280 show_blame_view(struct tog_view *view)
6282 const struct got_error *err = NULL;
6283 struct tog_blame_view_state *s = &view->state.blame;
6284 int errcode;
6286 if (s->blame.thread == 0 && !s->blame_complete) {
6287 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6288 &s->blame.thread_args);
6289 if (errcode)
6290 return got_error_set_errno(errcode, "pthread_create");
6292 halfdelay(1); /* fast refresh while annotating */
6295 if (s->blame_complete)
6296 halfdelay(10); /* disable fast refresh */
6298 err = draw_blame(view);
6300 view_border(view);
6301 return err;
6304 static const struct got_error *
6305 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6306 struct got_repository *repo, struct got_object_id *id)
6308 struct tog_view *log_view;
6309 const struct got_error *err = NULL;
6311 *new_view = NULL;
6313 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6314 if (log_view == NULL)
6315 return got_error_from_errno("view_open");
6317 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6318 if (err)
6319 view_close(log_view);
6320 else
6321 *new_view = log_view;
6323 return err;
6326 static const struct got_error *
6327 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6329 const struct got_error *err = NULL, *thread_err = NULL;
6330 struct tog_view *diff_view;
6331 struct tog_blame_view_state *s = &view->state.blame;
6332 int eos, nscroll, begin_y = 0, begin_x = 0;
6334 eos = nscroll = view->nlines - 2;
6335 if (view_is_hsplit_top(view))
6336 --eos; /* border */
6338 switch (ch) {
6339 case '0':
6340 case '$':
6341 case KEY_RIGHT:
6342 case 'l':
6343 case KEY_LEFT:
6344 case 'h':
6345 horizontal_scroll_input(view, ch);
6346 break;
6347 case 'q':
6348 s->done = 1;
6349 break;
6350 case 'g':
6351 case KEY_HOME:
6352 s->selected_line = 1;
6353 s->first_displayed_line = 1;
6354 view->count = 0;
6355 break;
6356 case 'G':
6357 case KEY_END:
6358 if (s->blame.nlines < eos) {
6359 s->selected_line = s->blame.nlines;
6360 s->first_displayed_line = 1;
6361 } else {
6362 s->selected_line = eos;
6363 s->first_displayed_line = s->blame.nlines - (eos - 1);
6365 view->count = 0;
6366 break;
6367 case 'k':
6368 case KEY_UP:
6369 case CTRL('p'):
6370 if (s->selected_line > 1)
6371 s->selected_line--;
6372 else if (s->selected_line == 1 &&
6373 s->first_displayed_line > 1)
6374 s->first_displayed_line--;
6375 else
6376 view->count = 0;
6377 break;
6378 case CTRL('u'):
6379 case 'u':
6380 nscroll /= 2;
6381 /* FALL THROUGH */
6382 case KEY_PPAGE:
6383 case CTRL('b'):
6384 case 'b':
6385 if (s->first_displayed_line == 1) {
6386 if (view->count > 1)
6387 nscroll += nscroll;
6388 s->selected_line = MAX(1, s->selected_line - nscroll);
6389 view->count = 0;
6390 break;
6392 if (s->first_displayed_line > nscroll)
6393 s->first_displayed_line -= nscroll;
6394 else
6395 s->first_displayed_line = 1;
6396 break;
6397 case 'j':
6398 case KEY_DOWN:
6399 case CTRL('n'):
6400 if (s->selected_line < eos && s->first_displayed_line +
6401 s->selected_line <= s->blame.nlines)
6402 s->selected_line++;
6403 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6404 s->first_displayed_line++;
6405 else
6406 view->count = 0;
6407 break;
6408 case 'c':
6409 case 'p': {
6410 struct got_object_id *id = NULL;
6412 view->count = 0;
6413 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6414 s->first_displayed_line, s->selected_line);
6415 if (id == NULL)
6416 break;
6417 if (ch == 'p') {
6418 struct got_commit_object *commit, *pcommit;
6419 struct got_object_qid *pid;
6420 struct got_object_id *blob_id = NULL;
6421 int obj_type;
6422 err = got_object_open_as_commit(&commit,
6423 s->repo, id);
6424 if (err)
6425 break;
6426 pid = STAILQ_FIRST(
6427 got_object_commit_get_parent_ids(commit));
6428 if (pid == NULL) {
6429 got_object_commit_close(commit);
6430 break;
6432 /* Check if path history ends here. */
6433 err = got_object_open_as_commit(&pcommit,
6434 s->repo, &pid->id);
6435 if (err)
6436 break;
6437 err = got_object_id_by_path(&blob_id, s->repo,
6438 pcommit, s->path);
6439 got_object_commit_close(pcommit);
6440 if (err) {
6441 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6442 err = NULL;
6443 got_object_commit_close(commit);
6444 break;
6446 err = got_object_get_type(&obj_type, s->repo,
6447 blob_id);
6448 free(blob_id);
6449 /* Can't blame non-blob type objects. */
6450 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6451 got_object_commit_close(commit);
6452 break;
6454 err = got_object_qid_alloc(&s->blamed_commit,
6455 &pid->id);
6456 got_object_commit_close(commit);
6457 } else {
6458 if (got_object_id_cmp(id,
6459 &s->blamed_commit->id) == 0)
6460 break;
6461 err = got_object_qid_alloc(&s->blamed_commit,
6462 id);
6464 if (err)
6465 break;
6466 s->done = 1;
6467 thread_err = stop_blame(&s->blame);
6468 s->done = 0;
6469 if (thread_err)
6470 break;
6471 STAILQ_INSERT_HEAD(&s->blamed_commits,
6472 s->blamed_commit, entry);
6473 err = run_blame(view);
6474 if (err)
6475 break;
6476 break;
6478 case 'C': {
6479 struct got_object_qid *first;
6481 view->count = 0;
6482 first = STAILQ_FIRST(&s->blamed_commits);
6483 if (!got_object_id_cmp(&first->id, s->commit_id))
6484 break;
6485 s->done = 1;
6486 thread_err = stop_blame(&s->blame);
6487 s->done = 0;
6488 if (thread_err)
6489 break;
6490 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6491 got_object_qid_free(s->blamed_commit);
6492 s->blamed_commit =
6493 STAILQ_FIRST(&s->blamed_commits);
6494 err = run_blame(view);
6495 if (err)
6496 break;
6497 break;
6499 case 'L':
6500 view->count = 0;
6501 s->id_to_log = get_selected_commit_id(s->blame.lines,
6502 s->blame.nlines, s->first_displayed_line, s->selected_line);
6503 if (s->id_to_log)
6504 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6505 break;
6506 case KEY_ENTER:
6507 case '\r': {
6508 struct got_object_id *id = NULL;
6509 struct got_object_qid *pid;
6510 struct got_commit_object *commit = NULL;
6512 view->count = 0;
6513 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6514 s->first_displayed_line, s->selected_line);
6515 if (id == NULL)
6516 break;
6517 err = got_object_open_as_commit(&commit, s->repo, id);
6518 if (err)
6519 break;
6520 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6521 if (*new_view) {
6522 /* traversed from diff view, release diff resources */
6523 err = close_diff_view(*new_view);
6524 if (err)
6525 break;
6526 diff_view = *new_view;
6527 } else {
6528 if (view_is_parent_view(view))
6529 view_get_split(view, &begin_y, &begin_x);
6531 diff_view = view_open(0, 0, begin_y, begin_x,
6532 TOG_VIEW_DIFF);
6533 if (diff_view == NULL) {
6534 got_object_commit_close(commit);
6535 err = got_error_from_errno("view_open");
6536 break;
6539 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6540 id, NULL, NULL, 3, 0, 0, view, s->repo);
6541 got_object_commit_close(commit);
6542 if (err) {
6543 view_close(diff_view);
6544 break;
6546 s->last_diffed_line = s->first_displayed_line - 1 +
6547 s->selected_line;
6548 if (*new_view)
6549 break; /* still open from active diff view */
6550 if (view_is_parent_view(view) &&
6551 view->mode == TOG_VIEW_SPLIT_HRZN) {
6552 err = view_init_hsplit(view, begin_y);
6553 if (err)
6554 break;
6557 view->focussed = 0;
6558 diff_view->focussed = 1;
6559 diff_view->mode = view->mode;
6560 diff_view->nlines = view->lines - begin_y;
6561 if (view_is_parent_view(view)) {
6562 view_transfer_size(diff_view, view);
6563 err = view_close_child(view);
6564 if (err)
6565 break;
6566 err = view_set_child(view, diff_view);
6567 if (err)
6568 break;
6569 view->focus_child = 1;
6570 } else
6571 *new_view = diff_view;
6572 if (err)
6573 break;
6574 break;
6576 case CTRL('d'):
6577 case 'd':
6578 nscroll /= 2;
6579 /* FALL THROUGH */
6580 case KEY_NPAGE:
6581 case CTRL('f'):
6582 case 'f':
6583 case ' ':
6584 if (s->last_displayed_line >= s->blame.nlines &&
6585 s->selected_line >= MIN(s->blame.nlines,
6586 view->nlines - 2)) {
6587 view->count = 0;
6588 break;
6590 if (s->last_displayed_line >= s->blame.nlines &&
6591 s->selected_line < view->nlines - 2) {
6592 s->selected_line +=
6593 MIN(nscroll, s->last_displayed_line -
6594 s->first_displayed_line - s->selected_line + 1);
6596 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6597 s->first_displayed_line += nscroll;
6598 else
6599 s->first_displayed_line =
6600 s->blame.nlines - (view->nlines - 3);
6601 break;
6602 case KEY_RESIZE:
6603 if (s->selected_line > view->nlines - 2) {
6604 s->selected_line = MIN(s->blame.nlines,
6605 view->nlines - 2);
6607 break;
6608 default:
6609 view->count = 0;
6610 break;
6612 return thread_err ? thread_err : err;
6615 static const struct got_error *
6616 reset_blame_view(struct tog_view *view)
6618 const struct got_error *err;
6619 struct tog_blame_view_state *s = &view->state.blame;
6621 view->count = 0;
6622 s->done = 1;
6623 err = stop_blame(&s->blame);
6624 s->done = 0;
6625 if (err)
6626 return err;
6627 return run_blame(view);
6630 static const struct got_error *
6631 cmd_blame(int argc, char *argv[])
6633 const struct got_error *error;
6634 struct got_repository *repo = NULL;
6635 struct got_worktree *worktree = NULL;
6636 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6637 char *link_target = NULL;
6638 struct got_object_id *commit_id = NULL;
6639 struct got_commit_object *commit = NULL;
6640 char *commit_id_str = NULL;
6641 int ch;
6642 struct tog_view *view;
6643 int *pack_fds = NULL;
6645 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6646 switch (ch) {
6647 case 'c':
6648 commit_id_str = optarg;
6649 break;
6650 case 'r':
6651 repo_path = realpath(optarg, NULL);
6652 if (repo_path == NULL)
6653 return got_error_from_errno2("realpath",
6654 optarg);
6655 break;
6656 default:
6657 usage_blame();
6658 /* NOTREACHED */
6662 argc -= optind;
6663 argv += optind;
6665 if (argc != 1)
6666 usage_blame();
6668 error = got_repo_pack_fds_open(&pack_fds);
6669 if (error != NULL)
6670 goto done;
6672 if (repo_path == NULL) {
6673 cwd = getcwd(NULL, 0);
6674 if (cwd == NULL)
6675 return got_error_from_errno("getcwd");
6676 error = got_worktree_open(&worktree, cwd);
6677 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6678 goto done;
6679 if (worktree)
6680 repo_path =
6681 strdup(got_worktree_get_repo_path(worktree));
6682 else
6683 repo_path = strdup(cwd);
6684 if (repo_path == NULL) {
6685 error = got_error_from_errno("strdup");
6686 goto done;
6690 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6691 if (error != NULL)
6692 goto done;
6694 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6695 worktree);
6696 if (error)
6697 goto done;
6699 init_curses();
6701 error = apply_unveil(got_repo_get_path(repo), NULL);
6702 if (error)
6703 goto done;
6705 error = tog_load_refs(repo, 0);
6706 if (error)
6707 goto done;
6709 if (commit_id_str == NULL) {
6710 struct got_reference *head_ref;
6711 error = got_ref_open(&head_ref, repo, worktree ?
6712 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6713 if (error != NULL)
6714 goto done;
6715 error = got_ref_resolve(&commit_id, repo, head_ref);
6716 got_ref_close(head_ref);
6717 } else {
6718 error = got_repo_match_object_id(&commit_id, NULL,
6719 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6721 if (error != NULL)
6722 goto done;
6724 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6725 if (view == NULL) {
6726 error = got_error_from_errno("view_open");
6727 goto done;
6730 error = got_object_open_as_commit(&commit, repo, commit_id);
6731 if (error)
6732 goto done;
6734 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6735 commit, repo);
6736 if (error)
6737 goto done;
6739 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6740 commit_id, repo);
6741 if (error)
6742 goto done;
6743 if (worktree) {
6744 /* Release work tree lock. */
6745 got_worktree_close(worktree);
6746 worktree = NULL;
6748 error = view_loop(view);
6749 done:
6750 free(repo_path);
6751 free(in_repo_path);
6752 free(link_target);
6753 free(cwd);
6754 free(commit_id);
6755 if (commit)
6756 got_object_commit_close(commit);
6757 if (worktree)
6758 got_worktree_close(worktree);
6759 if (repo) {
6760 const struct got_error *close_err = got_repo_close(repo);
6761 if (error == NULL)
6762 error = close_err;
6764 if (pack_fds) {
6765 const struct got_error *pack_err =
6766 got_repo_pack_fds_close(pack_fds);
6767 if (error == NULL)
6768 error = pack_err;
6770 tog_free_refs();
6771 return error;
6774 static const struct got_error *
6775 draw_tree_entries(struct tog_view *view, const char *parent_path)
6777 struct tog_tree_view_state *s = &view->state.tree;
6778 const struct got_error *err = NULL;
6779 struct got_tree_entry *te;
6780 wchar_t *wline;
6781 char *index = NULL;
6782 struct tog_color *tc;
6783 int width, n, nentries, scrollx, i = 1;
6784 int limit = view->nlines;
6786 s->ndisplayed = 0;
6787 if (view_is_hsplit_top(view))
6788 --limit; /* border */
6790 werase(view->window);
6792 if (limit == 0)
6793 return NULL;
6795 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6796 0, 0);
6797 if (err)
6798 return err;
6799 if (view_needs_focus_indication(view))
6800 wstandout(view->window);
6801 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6802 if (tc)
6803 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6804 waddwstr(view->window, wline);
6805 free(wline);
6806 wline = NULL;
6807 while (width++ < view->ncols)
6808 waddch(view->window, ' ');
6809 if (tc)
6810 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6811 if (view_needs_focus_indication(view))
6812 wstandend(view->window);
6813 if (--limit <= 0)
6814 return NULL;
6816 i += s->selected;
6817 if (s->first_displayed_entry) {
6818 i += got_tree_entry_get_index(s->first_displayed_entry);
6819 if (s->tree != s->root)
6820 ++i; /* account for ".." entry */
6822 nentries = got_object_tree_get_nentries(s->tree);
6823 if (asprintf(&index, "[%d/%d] %s",
6824 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6825 return got_error_from_errno("asprintf");
6826 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6827 free(index);
6828 if (err)
6829 return err;
6830 waddwstr(view->window, wline);
6831 free(wline);
6832 wline = NULL;
6833 if (width < view->ncols - 1)
6834 waddch(view->window, '\n');
6835 if (--limit <= 0)
6836 return NULL;
6837 waddch(view->window, '\n');
6838 if (--limit <= 0)
6839 return NULL;
6841 if (s->first_displayed_entry == NULL) {
6842 te = got_object_tree_get_first_entry(s->tree);
6843 if (s->selected == 0) {
6844 if (view->focussed)
6845 wstandout(view->window);
6846 s->selected_entry = NULL;
6848 waddstr(view->window, " ..\n"); /* parent directory */
6849 if (s->selected == 0 && view->focussed)
6850 wstandend(view->window);
6851 s->ndisplayed++;
6852 if (--limit <= 0)
6853 return NULL;
6854 n = 1;
6855 } else {
6856 n = 0;
6857 te = s->first_displayed_entry;
6860 view->maxx = 0;
6861 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6862 char *line = NULL, *id_str = NULL, *link_target = NULL;
6863 const char *modestr = "";
6864 mode_t mode;
6866 te = got_object_tree_get_entry(s->tree, i);
6867 mode = got_tree_entry_get_mode(te);
6869 if (s->show_ids) {
6870 err = got_object_id_str(&id_str,
6871 got_tree_entry_get_id(te));
6872 if (err)
6873 return got_error_from_errno(
6874 "got_object_id_str");
6876 if (got_object_tree_entry_is_submodule(te))
6877 modestr = "$";
6878 else if (S_ISLNK(mode)) {
6879 int i;
6881 err = got_tree_entry_get_symlink_target(&link_target,
6882 te, s->repo);
6883 if (err) {
6884 free(id_str);
6885 return err;
6887 for (i = 0; i < strlen(link_target); i++) {
6888 if (!isprint((unsigned char)link_target[i]))
6889 link_target[i] = '?';
6891 modestr = "@";
6893 else if (S_ISDIR(mode))
6894 modestr = "/";
6895 else if (mode & S_IXUSR)
6896 modestr = "*";
6897 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6898 got_tree_entry_get_name(te), modestr,
6899 link_target ? " -> ": "",
6900 link_target ? link_target : "") == -1) {
6901 free(id_str);
6902 free(link_target);
6903 return got_error_from_errno("asprintf");
6905 free(id_str);
6906 free(link_target);
6908 /* use full line width to determine view->maxx */
6909 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
6910 if (err) {
6911 free(line);
6912 break;
6914 view->maxx = MAX(view->maxx, width);
6915 free(wline);
6916 wline = NULL;
6918 err = format_line(&wline, &width, &scrollx, line, view->x,
6919 view->ncols, 0, 0);
6920 if (err) {
6921 free(line);
6922 break;
6924 if (n == s->selected) {
6925 if (view->focussed)
6926 wstandout(view->window);
6927 s->selected_entry = te;
6929 tc = match_color(&s->colors, line);
6930 if (tc)
6931 wattr_on(view->window,
6932 COLOR_PAIR(tc->colorpair), NULL);
6933 waddwstr(view->window, &wline[scrollx]);
6934 if (tc)
6935 wattr_off(view->window,
6936 COLOR_PAIR(tc->colorpair), NULL);
6937 if (width < view->ncols)
6938 waddch(view->window, '\n');
6939 if (n == s->selected && view->focussed)
6940 wstandend(view->window);
6941 free(line);
6942 free(wline);
6943 wline = NULL;
6944 n++;
6945 s->ndisplayed++;
6946 s->last_displayed_entry = te;
6947 if (--limit <= 0)
6948 break;
6951 return err;
6954 static void
6955 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6957 struct got_tree_entry *te;
6958 int isroot = s->tree == s->root;
6959 int i = 0;
6961 if (s->first_displayed_entry == NULL)
6962 return;
6964 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6965 while (i++ < maxscroll) {
6966 if (te == NULL) {
6967 if (!isroot)
6968 s->first_displayed_entry = NULL;
6969 break;
6971 s->first_displayed_entry = te;
6972 te = got_tree_entry_get_prev(s->tree, te);
6976 static const struct got_error *
6977 tree_scroll_down(struct tog_view *view, int maxscroll)
6979 struct tog_tree_view_state *s = &view->state.tree;
6980 struct got_tree_entry *next, *last;
6981 int n = 0;
6983 if (s->first_displayed_entry)
6984 next = got_tree_entry_get_next(s->tree,
6985 s->first_displayed_entry);
6986 else
6987 next = got_object_tree_get_first_entry(s->tree);
6989 last = s->last_displayed_entry;
6990 while (next && n++ < maxscroll) {
6991 if (last) {
6992 s->last_displayed_entry = last;
6993 last = got_tree_entry_get_next(s->tree, last);
6995 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6996 s->first_displayed_entry = next;
6997 next = got_tree_entry_get_next(s->tree, next);
7001 return NULL;
7004 static const struct got_error *
7005 tree_entry_path(char **path, struct tog_parent_trees *parents,
7006 struct got_tree_entry *te)
7008 const struct got_error *err = NULL;
7009 struct tog_parent_tree *pt;
7010 size_t len = 2; /* for leading slash and NUL */
7012 TAILQ_FOREACH(pt, parents, entry)
7013 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7014 + 1 /* slash */;
7015 if (te)
7016 len += strlen(got_tree_entry_get_name(te));
7018 *path = calloc(1, len);
7019 if (path == NULL)
7020 return got_error_from_errno("calloc");
7022 (*path)[0] = '/';
7023 pt = TAILQ_LAST(parents, tog_parent_trees);
7024 while (pt) {
7025 const char *name = got_tree_entry_get_name(pt->selected_entry);
7026 if (strlcat(*path, name, len) >= len) {
7027 err = got_error(GOT_ERR_NO_SPACE);
7028 goto done;
7030 if (strlcat(*path, "/", len) >= len) {
7031 err = got_error(GOT_ERR_NO_SPACE);
7032 goto done;
7034 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7036 if (te) {
7037 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7038 err = got_error(GOT_ERR_NO_SPACE);
7039 goto done;
7042 done:
7043 if (err) {
7044 free(*path);
7045 *path = NULL;
7047 return err;
7050 static const struct got_error *
7051 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7052 struct got_tree_entry *te, struct tog_parent_trees *parents,
7053 struct got_object_id *commit_id, struct got_repository *repo)
7055 const struct got_error *err = NULL;
7056 char *path;
7057 struct tog_view *blame_view;
7059 *new_view = NULL;
7061 err = tree_entry_path(&path, parents, te);
7062 if (err)
7063 return err;
7065 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7066 if (blame_view == NULL) {
7067 err = got_error_from_errno("view_open");
7068 goto done;
7071 err = open_blame_view(blame_view, path, commit_id, repo);
7072 if (err) {
7073 if (err->code == GOT_ERR_CANCELLED)
7074 err = NULL;
7075 view_close(blame_view);
7076 } else
7077 *new_view = blame_view;
7078 done:
7079 free(path);
7080 return err;
7083 static const struct got_error *
7084 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7085 struct tog_tree_view_state *s)
7087 struct tog_view *log_view;
7088 const struct got_error *err = NULL;
7089 char *path;
7091 *new_view = NULL;
7093 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7094 if (log_view == NULL)
7095 return got_error_from_errno("view_open");
7097 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7098 if (err)
7099 return err;
7101 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7102 path, 0);
7103 if (err)
7104 view_close(log_view);
7105 else
7106 *new_view = log_view;
7107 free(path);
7108 return err;
7111 static const struct got_error *
7112 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7113 const char *head_ref_name, struct got_repository *repo)
7115 const struct got_error *err = NULL;
7116 char *commit_id_str = NULL;
7117 struct tog_tree_view_state *s = &view->state.tree;
7118 struct got_commit_object *commit = NULL;
7120 TAILQ_INIT(&s->parents);
7121 STAILQ_INIT(&s->colors);
7123 s->commit_id = got_object_id_dup(commit_id);
7124 if (s->commit_id == NULL)
7125 return got_error_from_errno("got_object_id_dup");
7127 err = got_object_open_as_commit(&commit, repo, commit_id);
7128 if (err)
7129 goto done;
7132 * The root is opened here and will be closed when the view is closed.
7133 * Any visited subtrees and their path-wise parents are opened and
7134 * closed on demand.
7136 err = got_object_open_as_tree(&s->root, repo,
7137 got_object_commit_get_tree_id(commit));
7138 if (err)
7139 goto done;
7140 s->tree = s->root;
7142 err = got_object_id_str(&commit_id_str, commit_id);
7143 if (err != NULL)
7144 goto done;
7146 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7147 err = got_error_from_errno("asprintf");
7148 goto done;
7151 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7152 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7153 if (head_ref_name) {
7154 s->head_ref_name = strdup(head_ref_name);
7155 if (s->head_ref_name == NULL) {
7156 err = got_error_from_errno("strdup");
7157 goto done;
7160 s->repo = repo;
7162 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7163 err = add_color(&s->colors, "\\$$",
7164 TOG_COLOR_TREE_SUBMODULE,
7165 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7166 if (err)
7167 goto done;
7168 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7169 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7170 if (err)
7171 goto done;
7172 err = add_color(&s->colors, "/$",
7173 TOG_COLOR_TREE_DIRECTORY,
7174 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7175 if (err)
7176 goto done;
7178 err = add_color(&s->colors, "\\*$",
7179 TOG_COLOR_TREE_EXECUTABLE,
7180 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7181 if (err)
7182 goto done;
7184 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7185 get_color_value("TOG_COLOR_COMMIT"));
7186 if (err)
7187 goto done;
7190 view->show = show_tree_view;
7191 view->input = input_tree_view;
7192 view->close = close_tree_view;
7193 view->search_start = search_start_tree_view;
7194 view->search_next = search_next_tree_view;
7195 done:
7196 free(commit_id_str);
7197 if (commit)
7198 got_object_commit_close(commit);
7199 if (err)
7200 close_tree_view(view);
7201 return err;
7204 static const struct got_error *
7205 close_tree_view(struct tog_view *view)
7207 struct tog_tree_view_state *s = &view->state.tree;
7209 free_colors(&s->colors);
7210 free(s->tree_label);
7211 s->tree_label = NULL;
7212 free(s->commit_id);
7213 s->commit_id = NULL;
7214 free(s->head_ref_name);
7215 s->head_ref_name = NULL;
7216 while (!TAILQ_EMPTY(&s->parents)) {
7217 struct tog_parent_tree *parent;
7218 parent = TAILQ_FIRST(&s->parents);
7219 TAILQ_REMOVE(&s->parents, parent, entry);
7220 if (parent->tree != s->root)
7221 got_object_tree_close(parent->tree);
7222 free(parent);
7225 if (s->tree != NULL && s->tree != s->root)
7226 got_object_tree_close(s->tree);
7227 if (s->root)
7228 got_object_tree_close(s->root);
7229 return NULL;
7232 static const struct got_error *
7233 search_start_tree_view(struct tog_view *view)
7235 struct tog_tree_view_state *s = &view->state.tree;
7237 s->matched_entry = NULL;
7238 return NULL;
7241 static int
7242 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7244 regmatch_t regmatch;
7246 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7247 0) == 0;
7250 static const struct got_error *
7251 search_next_tree_view(struct tog_view *view)
7253 struct tog_tree_view_state *s = &view->state.tree;
7254 struct got_tree_entry *te = NULL;
7256 if (!view->searching) {
7257 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7258 return NULL;
7261 if (s->matched_entry) {
7262 if (view->searching == TOG_SEARCH_FORWARD) {
7263 if (s->selected_entry)
7264 te = got_tree_entry_get_next(s->tree,
7265 s->selected_entry);
7266 else
7267 te = got_object_tree_get_first_entry(s->tree);
7268 } else {
7269 if (s->selected_entry == NULL)
7270 te = got_object_tree_get_last_entry(s->tree);
7271 else
7272 te = got_tree_entry_get_prev(s->tree,
7273 s->selected_entry);
7275 } else {
7276 if (s->selected_entry)
7277 te = s->selected_entry;
7278 else if (view->searching == TOG_SEARCH_FORWARD)
7279 te = got_object_tree_get_first_entry(s->tree);
7280 else
7281 te = got_object_tree_get_last_entry(s->tree);
7284 while (1) {
7285 if (te == NULL) {
7286 if (s->matched_entry == NULL) {
7287 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7288 return NULL;
7290 if (view->searching == TOG_SEARCH_FORWARD)
7291 te = got_object_tree_get_first_entry(s->tree);
7292 else
7293 te = got_object_tree_get_last_entry(s->tree);
7296 if (match_tree_entry(te, &view->regex)) {
7297 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7298 s->matched_entry = te;
7299 break;
7302 if (view->searching == TOG_SEARCH_FORWARD)
7303 te = got_tree_entry_get_next(s->tree, te);
7304 else
7305 te = got_tree_entry_get_prev(s->tree, te);
7308 if (s->matched_entry) {
7309 s->first_displayed_entry = s->matched_entry;
7310 s->selected = 0;
7313 return NULL;
7316 static const struct got_error *
7317 show_tree_view(struct tog_view *view)
7319 const struct got_error *err = NULL;
7320 struct tog_tree_view_state *s = &view->state.tree;
7321 char *parent_path;
7323 err = tree_entry_path(&parent_path, &s->parents, NULL);
7324 if (err)
7325 return err;
7327 err = draw_tree_entries(view, parent_path);
7328 free(parent_path);
7330 view_border(view);
7331 return err;
7334 static const struct got_error *
7335 tree_goto_line(struct tog_view *view, int nlines)
7337 const struct got_error *err = NULL;
7338 struct tog_tree_view_state *s = &view->state.tree;
7339 struct got_tree_entry **fte, **lte, **ste;
7340 int g, last, first = 1, i = 1;
7341 int root = s->tree == s->root;
7342 int off = root ? 1 : 2;
7344 g = view->gline;
7345 view->gline = 0;
7347 if (g == 0)
7348 g = 1;
7349 else if (g > got_object_tree_get_nentries(s->tree))
7350 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7352 fte = &s->first_displayed_entry;
7353 lte = &s->last_displayed_entry;
7354 ste = &s->selected_entry;
7356 if (*fte != NULL) {
7357 first = got_tree_entry_get_index(*fte);
7358 first += off; /* account for ".." */
7360 last = got_tree_entry_get_index(*lte);
7361 last += off;
7363 if (g >= first && g <= last && g - first < nlines) {
7364 s->selected = g - first;
7365 return NULL; /* gline is on the current page */
7368 if (*ste != NULL) {
7369 i = got_tree_entry_get_index(*ste);
7370 i += off;
7373 if (i < g) {
7374 err = tree_scroll_down(view, g - i);
7375 if (err)
7376 return err;
7377 if (got_tree_entry_get_index(*lte) >=
7378 got_object_tree_get_nentries(s->tree) - 1 &&
7379 first + s->selected < g &&
7380 s->selected < s->ndisplayed - 1) {
7381 first = got_tree_entry_get_index(*fte);
7382 first += off;
7383 s->selected = g - first;
7385 } else if (i > g)
7386 tree_scroll_up(s, i - g);
7388 if (g < nlines &&
7389 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7390 s->selected = g - 1;
7392 return NULL;
7395 static const struct got_error *
7396 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7398 const struct got_error *err = NULL;
7399 struct tog_tree_view_state *s = &view->state.tree;
7400 struct got_tree_entry *te;
7401 int n, nscroll = view->nlines - 3;
7403 if (view->gline)
7404 return tree_goto_line(view, nscroll);
7406 switch (ch) {
7407 case '0':
7408 case '$':
7409 case KEY_RIGHT:
7410 case 'l':
7411 case KEY_LEFT:
7412 case 'h':
7413 horizontal_scroll_input(view, ch);
7414 break;
7415 case 'i':
7416 s->show_ids = !s->show_ids;
7417 view->count = 0;
7418 break;
7419 case 'L':
7420 view->count = 0;
7421 if (!s->selected_entry)
7422 break;
7423 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7424 break;
7425 case 'R':
7426 view->count = 0;
7427 err = view_request_new(new_view, view, TOG_VIEW_REF);
7428 break;
7429 case 'g':
7430 case '=':
7431 case KEY_HOME:
7432 s->selected = 0;
7433 view->count = 0;
7434 if (s->tree == s->root)
7435 s->first_displayed_entry =
7436 got_object_tree_get_first_entry(s->tree);
7437 else
7438 s->first_displayed_entry = NULL;
7439 break;
7440 case 'G':
7441 case '*':
7442 case KEY_END: {
7443 int eos = view->nlines - 3;
7445 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7446 --eos; /* border */
7447 s->selected = 0;
7448 view->count = 0;
7449 te = got_object_tree_get_last_entry(s->tree);
7450 for (n = 0; n < eos; n++) {
7451 if (te == NULL) {
7452 if (s->tree != s->root) {
7453 s->first_displayed_entry = NULL;
7454 n++;
7456 break;
7458 s->first_displayed_entry = te;
7459 te = got_tree_entry_get_prev(s->tree, te);
7461 if (n > 0)
7462 s->selected = n - 1;
7463 break;
7465 case 'k':
7466 case KEY_UP:
7467 case CTRL('p'):
7468 if (s->selected > 0) {
7469 s->selected--;
7470 break;
7472 tree_scroll_up(s, 1);
7473 if (s->selected_entry == NULL ||
7474 (s->tree == s->root && s->selected_entry ==
7475 got_object_tree_get_first_entry(s->tree)))
7476 view->count = 0;
7477 break;
7478 case CTRL('u'):
7479 case 'u':
7480 nscroll /= 2;
7481 /* FALL THROUGH */
7482 case KEY_PPAGE:
7483 case CTRL('b'):
7484 case 'b':
7485 if (s->tree == s->root) {
7486 if (got_object_tree_get_first_entry(s->tree) ==
7487 s->first_displayed_entry)
7488 s->selected -= MIN(s->selected, nscroll);
7489 } else {
7490 if (s->first_displayed_entry == NULL)
7491 s->selected -= MIN(s->selected, nscroll);
7493 tree_scroll_up(s, MAX(0, nscroll));
7494 if (s->selected_entry == NULL ||
7495 (s->tree == s->root && s->selected_entry ==
7496 got_object_tree_get_first_entry(s->tree)))
7497 view->count = 0;
7498 break;
7499 case 'j':
7500 case KEY_DOWN:
7501 case CTRL('n'):
7502 if (s->selected < s->ndisplayed - 1) {
7503 s->selected++;
7504 break;
7506 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7507 == NULL) {
7508 /* can't scroll any further */
7509 view->count = 0;
7510 break;
7512 tree_scroll_down(view, 1);
7513 break;
7514 case CTRL('d'):
7515 case 'd':
7516 nscroll /= 2;
7517 /* FALL THROUGH */
7518 case KEY_NPAGE:
7519 case CTRL('f'):
7520 case 'f':
7521 case ' ':
7522 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7523 == NULL) {
7524 /* can't scroll any further; move cursor down */
7525 if (s->selected < s->ndisplayed - 1)
7526 s->selected += MIN(nscroll,
7527 s->ndisplayed - s->selected - 1);
7528 else
7529 view->count = 0;
7530 break;
7532 tree_scroll_down(view, nscroll);
7533 break;
7534 case KEY_ENTER:
7535 case '\r':
7536 case KEY_BACKSPACE:
7537 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7538 struct tog_parent_tree *parent;
7539 /* user selected '..' */
7540 if (s->tree == s->root) {
7541 view->count = 0;
7542 break;
7544 parent = TAILQ_FIRST(&s->parents);
7545 TAILQ_REMOVE(&s->parents, parent,
7546 entry);
7547 got_object_tree_close(s->tree);
7548 s->tree = parent->tree;
7549 s->first_displayed_entry =
7550 parent->first_displayed_entry;
7551 s->selected_entry =
7552 parent->selected_entry;
7553 s->selected = parent->selected;
7554 if (s->selected > view->nlines - 3) {
7555 err = offset_selection_down(view);
7556 if (err)
7557 break;
7559 free(parent);
7560 } else if (S_ISDIR(got_tree_entry_get_mode(
7561 s->selected_entry))) {
7562 struct got_tree_object *subtree;
7563 view->count = 0;
7564 err = got_object_open_as_tree(&subtree, s->repo,
7565 got_tree_entry_get_id(s->selected_entry));
7566 if (err)
7567 break;
7568 err = tree_view_visit_subtree(s, subtree);
7569 if (err) {
7570 got_object_tree_close(subtree);
7571 break;
7573 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7574 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7575 break;
7576 case KEY_RESIZE:
7577 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7578 s->selected = view->nlines - 4;
7579 view->count = 0;
7580 break;
7581 default:
7582 view->count = 0;
7583 break;
7586 return err;
7589 __dead static void
7590 usage_tree(void)
7592 endwin();
7593 fprintf(stderr,
7594 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7595 getprogname());
7596 exit(1);
7599 static const struct got_error *
7600 cmd_tree(int argc, char *argv[])
7602 const struct got_error *error;
7603 struct got_repository *repo = NULL;
7604 struct got_worktree *worktree = NULL;
7605 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7606 struct got_object_id *commit_id = NULL;
7607 struct got_commit_object *commit = NULL;
7608 const char *commit_id_arg = NULL;
7609 char *label = NULL;
7610 struct got_reference *ref = NULL;
7611 const char *head_ref_name = NULL;
7612 int ch;
7613 struct tog_view *view;
7614 int *pack_fds = NULL;
7616 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7617 switch (ch) {
7618 case 'c':
7619 commit_id_arg = optarg;
7620 break;
7621 case 'r':
7622 repo_path = realpath(optarg, NULL);
7623 if (repo_path == NULL)
7624 return got_error_from_errno2("realpath",
7625 optarg);
7626 break;
7627 default:
7628 usage_tree();
7629 /* NOTREACHED */
7633 argc -= optind;
7634 argv += optind;
7636 if (argc > 1)
7637 usage_tree();
7639 error = got_repo_pack_fds_open(&pack_fds);
7640 if (error != NULL)
7641 goto done;
7643 if (repo_path == NULL) {
7644 cwd = getcwd(NULL, 0);
7645 if (cwd == NULL)
7646 return got_error_from_errno("getcwd");
7647 error = got_worktree_open(&worktree, cwd);
7648 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7649 goto done;
7650 if (worktree)
7651 repo_path =
7652 strdup(got_worktree_get_repo_path(worktree));
7653 else
7654 repo_path = strdup(cwd);
7655 if (repo_path == NULL) {
7656 error = got_error_from_errno("strdup");
7657 goto done;
7661 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7662 if (error != NULL)
7663 goto done;
7665 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7666 repo, worktree);
7667 if (error)
7668 goto done;
7670 init_curses();
7672 error = apply_unveil(got_repo_get_path(repo), NULL);
7673 if (error)
7674 goto done;
7676 error = tog_load_refs(repo, 0);
7677 if (error)
7678 goto done;
7680 if (commit_id_arg == NULL) {
7681 error = got_repo_match_object_id(&commit_id, &label,
7682 worktree ? got_worktree_get_head_ref_name(worktree) :
7683 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7684 if (error)
7685 goto done;
7686 head_ref_name = label;
7687 } else {
7688 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7689 if (error == NULL)
7690 head_ref_name = got_ref_get_name(ref);
7691 else if (error->code != GOT_ERR_NOT_REF)
7692 goto done;
7693 error = got_repo_match_object_id(&commit_id, NULL,
7694 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7695 if (error)
7696 goto done;
7699 error = got_object_open_as_commit(&commit, repo, commit_id);
7700 if (error)
7701 goto done;
7703 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7704 if (view == NULL) {
7705 error = got_error_from_errno("view_open");
7706 goto done;
7708 error = open_tree_view(view, commit_id, head_ref_name, repo);
7709 if (error)
7710 goto done;
7711 if (!got_path_is_root_dir(in_repo_path)) {
7712 error = tree_view_walk_path(&view->state.tree, commit,
7713 in_repo_path);
7714 if (error)
7715 goto done;
7718 if (worktree) {
7719 /* Release work tree lock. */
7720 got_worktree_close(worktree);
7721 worktree = NULL;
7723 error = view_loop(view);
7724 done:
7725 free(repo_path);
7726 free(cwd);
7727 free(commit_id);
7728 free(label);
7729 if (ref)
7730 got_ref_close(ref);
7731 if (repo) {
7732 const struct got_error *close_err = got_repo_close(repo);
7733 if (error == NULL)
7734 error = close_err;
7736 if (pack_fds) {
7737 const struct got_error *pack_err =
7738 got_repo_pack_fds_close(pack_fds);
7739 if (error == NULL)
7740 error = pack_err;
7742 tog_free_refs();
7743 return error;
7746 static const struct got_error *
7747 ref_view_load_refs(struct tog_ref_view_state *s)
7749 struct got_reflist_entry *sre;
7750 struct tog_reflist_entry *re;
7752 s->nrefs = 0;
7753 TAILQ_FOREACH(sre, &tog_refs, entry) {
7754 if (strncmp(got_ref_get_name(sre->ref),
7755 "refs/got/", 9) == 0 &&
7756 strncmp(got_ref_get_name(sre->ref),
7757 "refs/got/backup/", 16) != 0)
7758 continue;
7760 re = malloc(sizeof(*re));
7761 if (re == NULL)
7762 return got_error_from_errno("malloc");
7764 re->ref = got_ref_dup(sre->ref);
7765 if (re->ref == NULL)
7766 return got_error_from_errno("got_ref_dup");
7767 re->idx = s->nrefs++;
7768 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7771 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7772 return NULL;
7775 static void
7776 ref_view_free_refs(struct tog_ref_view_state *s)
7778 struct tog_reflist_entry *re;
7780 while (!TAILQ_EMPTY(&s->refs)) {
7781 re = TAILQ_FIRST(&s->refs);
7782 TAILQ_REMOVE(&s->refs, re, entry);
7783 got_ref_close(re->ref);
7784 free(re);
7788 static const struct got_error *
7789 open_ref_view(struct tog_view *view, struct got_repository *repo)
7791 const struct got_error *err = NULL;
7792 struct tog_ref_view_state *s = &view->state.ref;
7794 s->selected_entry = 0;
7795 s->repo = repo;
7797 TAILQ_INIT(&s->refs);
7798 STAILQ_INIT(&s->colors);
7800 err = ref_view_load_refs(s);
7801 if (err)
7802 return err;
7804 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7805 err = add_color(&s->colors, "^refs/heads/",
7806 TOG_COLOR_REFS_HEADS,
7807 get_color_value("TOG_COLOR_REFS_HEADS"));
7808 if (err)
7809 goto done;
7811 err = add_color(&s->colors, "^refs/tags/",
7812 TOG_COLOR_REFS_TAGS,
7813 get_color_value("TOG_COLOR_REFS_TAGS"));
7814 if (err)
7815 goto done;
7817 err = add_color(&s->colors, "^refs/remotes/",
7818 TOG_COLOR_REFS_REMOTES,
7819 get_color_value("TOG_COLOR_REFS_REMOTES"));
7820 if (err)
7821 goto done;
7823 err = add_color(&s->colors, "^refs/got/backup/",
7824 TOG_COLOR_REFS_BACKUP,
7825 get_color_value("TOG_COLOR_REFS_BACKUP"));
7826 if (err)
7827 goto done;
7830 view->show = show_ref_view;
7831 view->input = input_ref_view;
7832 view->close = close_ref_view;
7833 view->search_start = search_start_ref_view;
7834 view->search_next = search_next_ref_view;
7835 done:
7836 if (err)
7837 free_colors(&s->colors);
7838 return err;
7841 static const struct got_error *
7842 close_ref_view(struct tog_view *view)
7844 struct tog_ref_view_state *s = &view->state.ref;
7846 ref_view_free_refs(s);
7847 free_colors(&s->colors);
7849 return NULL;
7852 static const struct got_error *
7853 resolve_reflist_entry(struct got_object_id **commit_id,
7854 struct tog_reflist_entry *re, struct got_repository *repo)
7856 const struct got_error *err = NULL;
7857 struct got_object_id *obj_id;
7858 struct got_tag_object *tag = NULL;
7859 int obj_type;
7861 *commit_id = NULL;
7863 err = got_ref_resolve(&obj_id, repo, re->ref);
7864 if (err)
7865 return err;
7867 err = got_object_get_type(&obj_type, repo, obj_id);
7868 if (err)
7869 goto done;
7871 switch (obj_type) {
7872 case GOT_OBJ_TYPE_COMMIT:
7873 *commit_id = obj_id;
7874 break;
7875 case GOT_OBJ_TYPE_TAG:
7876 err = got_object_open_as_tag(&tag, repo, obj_id);
7877 if (err)
7878 goto done;
7879 free(obj_id);
7880 err = got_object_get_type(&obj_type, repo,
7881 got_object_tag_get_object_id(tag));
7882 if (err)
7883 goto done;
7884 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7885 err = got_error(GOT_ERR_OBJ_TYPE);
7886 goto done;
7888 *commit_id = got_object_id_dup(
7889 got_object_tag_get_object_id(tag));
7890 if (*commit_id == NULL) {
7891 err = got_error_from_errno("got_object_id_dup");
7892 goto done;
7894 break;
7895 default:
7896 err = got_error(GOT_ERR_OBJ_TYPE);
7897 break;
7900 done:
7901 if (tag)
7902 got_object_tag_close(tag);
7903 if (err) {
7904 free(*commit_id);
7905 *commit_id = NULL;
7907 return err;
7910 static const struct got_error *
7911 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7912 struct tog_reflist_entry *re, struct got_repository *repo)
7914 struct tog_view *log_view;
7915 const struct got_error *err = NULL;
7916 struct got_object_id *commit_id = NULL;
7918 *new_view = NULL;
7920 err = resolve_reflist_entry(&commit_id, re, repo);
7921 if (err) {
7922 if (err->code != GOT_ERR_OBJ_TYPE)
7923 return err;
7924 else
7925 return NULL;
7928 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7929 if (log_view == NULL) {
7930 err = got_error_from_errno("view_open");
7931 goto done;
7934 err = open_log_view(log_view, commit_id, repo,
7935 got_ref_get_name(re->ref), "", 0);
7936 done:
7937 if (err)
7938 view_close(log_view);
7939 else
7940 *new_view = log_view;
7941 free(commit_id);
7942 return err;
7945 static void
7946 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7948 struct tog_reflist_entry *re;
7949 int i = 0;
7951 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7952 return;
7954 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7955 while (i++ < maxscroll) {
7956 if (re == NULL)
7957 break;
7958 s->first_displayed_entry = re;
7959 re = TAILQ_PREV(re, tog_reflist_head, entry);
7963 static const struct got_error *
7964 ref_scroll_down(struct tog_view *view, int maxscroll)
7966 struct tog_ref_view_state *s = &view->state.ref;
7967 struct tog_reflist_entry *next, *last;
7968 int n = 0;
7970 if (s->first_displayed_entry)
7971 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7972 else
7973 next = TAILQ_FIRST(&s->refs);
7975 last = s->last_displayed_entry;
7976 while (next && n++ < maxscroll) {
7977 if (last) {
7978 s->last_displayed_entry = last;
7979 last = TAILQ_NEXT(last, entry);
7981 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7982 s->first_displayed_entry = next;
7983 next = TAILQ_NEXT(next, entry);
7987 return NULL;
7990 static const struct got_error *
7991 search_start_ref_view(struct tog_view *view)
7993 struct tog_ref_view_state *s = &view->state.ref;
7995 s->matched_entry = NULL;
7996 return NULL;
7999 static int
8000 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8002 regmatch_t regmatch;
8004 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8005 0) == 0;
8008 static const struct got_error *
8009 search_next_ref_view(struct tog_view *view)
8011 struct tog_ref_view_state *s = &view->state.ref;
8012 struct tog_reflist_entry *re = NULL;
8014 if (!view->searching) {
8015 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8016 return NULL;
8019 if (s->matched_entry) {
8020 if (view->searching == TOG_SEARCH_FORWARD) {
8021 if (s->selected_entry)
8022 re = TAILQ_NEXT(s->selected_entry, entry);
8023 else
8024 re = TAILQ_PREV(s->selected_entry,
8025 tog_reflist_head, entry);
8026 } else {
8027 if (s->selected_entry == NULL)
8028 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8029 else
8030 re = TAILQ_PREV(s->selected_entry,
8031 tog_reflist_head, entry);
8033 } else {
8034 if (s->selected_entry)
8035 re = s->selected_entry;
8036 else if (view->searching == TOG_SEARCH_FORWARD)
8037 re = TAILQ_FIRST(&s->refs);
8038 else
8039 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8042 while (1) {
8043 if (re == NULL) {
8044 if (s->matched_entry == NULL) {
8045 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8046 return NULL;
8048 if (view->searching == TOG_SEARCH_FORWARD)
8049 re = TAILQ_FIRST(&s->refs);
8050 else
8051 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8054 if (match_reflist_entry(re, &view->regex)) {
8055 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8056 s->matched_entry = re;
8057 break;
8060 if (view->searching == TOG_SEARCH_FORWARD)
8061 re = TAILQ_NEXT(re, entry);
8062 else
8063 re = TAILQ_PREV(re, tog_reflist_head, entry);
8066 if (s->matched_entry) {
8067 s->first_displayed_entry = s->matched_entry;
8068 s->selected = 0;
8071 return NULL;
8074 static const struct got_error *
8075 show_ref_view(struct tog_view *view)
8077 const struct got_error *err = NULL;
8078 struct tog_ref_view_state *s = &view->state.ref;
8079 struct tog_reflist_entry *re;
8080 char *line = NULL;
8081 wchar_t *wline;
8082 struct tog_color *tc;
8083 int width, n, scrollx;
8084 int limit = view->nlines;
8086 werase(view->window);
8088 s->ndisplayed = 0;
8089 if (view_is_hsplit_top(view))
8090 --limit; /* border */
8092 if (limit == 0)
8093 return NULL;
8095 re = s->first_displayed_entry;
8097 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8098 s->nrefs) == -1)
8099 return got_error_from_errno("asprintf");
8101 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8102 if (err) {
8103 free(line);
8104 return err;
8106 if (view_needs_focus_indication(view))
8107 wstandout(view->window);
8108 waddwstr(view->window, wline);
8109 while (width++ < view->ncols)
8110 waddch(view->window, ' ');
8111 if (view_needs_focus_indication(view))
8112 wstandend(view->window);
8113 free(wline);
8114 wline = NULL;
8115 free(line);
8116 line = NULL;
8117 if (--limit <= 0)
8118 return NULL;
8120 n = 0;
8121 view->maxx = 0;
8122 while (re && limit > 0) {
8123 char *line = NULL;
8124 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8126 if (s->show_date) {
8127 struct got_commit_object *ci;
8128 struct got_tag_object *tag;
8129 struct got_object_id *id;
8130 struct tm tm;
8131 time_t t;
8133 err = got_ref_resolve(&id, s->repo, re->ref);
8134 if (err)
8135 return err;
8136 err = got_object_open_as_tag(&tag, s->repo, id);
8137 if (err) {
8138 if (err->code != GOT_ERR_OBJ_TYPE) {
8139 free(id);
8140 return err;
8142 err = got_object_open_as_commit(&ci, s->repo,
8143 id);
8144 if (err) {
8145 free(id);
8146 return err;
8148 t = got_object_commit_get_committer_time(ci);
8149 got_object_commit_close(ci);
8150 } else {
8151 t = got_object_tag_get_tagger_time(tag);
8152 got_object_tag_close(tag);
8154 free(id);
8155 if (gmtime_r(&t, &tm) == NULL)
8156 return got_error_from_errno("gmtime_r");
8157 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8158 return got_error(GOT_ERR_NO_SPACE);
8160 if (got_ref_is_symbolic(re->ref)) {
8161 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8162 ymd : "", got_ref_get_name(re->ref),
8163 got_ref_get_symref_target(re->ref)) == -1)
8164 return got_error_from_errno("asprintf");
8165 } else if (s->show_ids) {
8166 struct got_object_id *id;
8167 char *id_str;
8168 err = got_ref_resolve(&id, s->repo, re->ref);
8169 if (err)
8170 return err;
8171 err = got_object_id_str(&id_str, id);
8172 if (err) {
8173 free(id);
8174 return err;
8176 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8177 got_ref_get_name(re->ref), id_str) == -1) {
8178 err = got_error_from_errno("asprintf");
8179 free(id);
8180 free(id_str);
8181 return err;
8183 free(id);
8184 free(id_str);
8185 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8186 got_ref_get_name(re->ref)) == -1)
8187 return got_error_from_errno("asprintf");
8189 /* use full line width to determine view->maxx */
8190 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8191 if (err) {
8192 free(line);
8193 return err;
8195 view->maxx = MAX(view->maxx, width);
8196 free(wline);
8197 wline = NULL;
8199 err = format_line(&wline, &width, &scrollx, line, view->x,
8200 view->ncols, 0, 0);
8201 if (err) {
8202 free(line);
8203 return err;
8205 if (n == s->selected) {
8206 if (view->focussed)
8207 wstandout(view->window);
8208 s->selected_entry = re;
8210 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8211 if (tc)
8212 wattr_on(view->window,
8213 COLOR_PAIR(tc->colorpair), NULL);
8214 waddwstr(view->window, &wline[scrollx]);
8215 if (tc)
8216 wattr_off(view->window,
8217 COLOR_PAIR(tc->colorpair), NULL);
8218 if (width < view->ncols)
8219 waddch(view->window, '\n');
8220 if (n == s->selected && view->focussed)
8221 wstandend(view->window);
8222 free(line);
8223 free(wline);
8224 wline = NULL;
8225 n++;
8226 s->ndisplayed++;
8227 s->last_displayed_entry = re;
8229 limit--;
8230 re = TAILQ_NEXT(re, entry);
8233 view_border(view);
8234 return err;
8237 static const struct got_error *
8238 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8239 struct tog_reflist_entry *re, struct got_repository *repo)
8241 const struct got_error *err = NULL;
8242 struct got_object_id *commit_id = NULL;
8243 struct tog_view *tree_view;
8245 *new_view = NULL;
8247 err = resolve_reflist_entry(&commit_id, re, repo);
8248 if (err) {
8249 if (err->code != GOT_ERR_OBJ_TYPE)
8250 return err;
8251 else
8252 return NULL;
8256 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8257 if (tree_view == NULL) {
8258 err = got_error_from_errno("view_open");
8259 goto done;
8262 err = open_tree_view(tree_view, commit_id,
8263 got_ref_get_name(re->ref), repo);
8264 if (err)
8265 goto done;
8267 *new_view = tree_view;
8268 done:
8269 free(commit_id);
8270 return err;
8273 static const struct got_error *
8274 ref_goto_line(struct tog_view *view, int nlines)
8276 const struct got_error *err = NULL;
8277 struct tog_ref_view_state *s = &view->state.ref;
8278 int g, idx = s->selected_entry->idx;
8280 g = view->gline;
8281 view->gline = 0;
8283 if (g == 0)
8284 g = 1;
8285 else if (g > s->nrefs)
8286 g = s->nrefs;
8288 if (g >= s->first_displayed_entry->idx + 1 &&
8289 g <= s->last_displayed_entry->idx + 1 &&
8290 g - s->first_displayed_entry->idx - 1 < nlines) {
8291 s->selected = g - s->first_displayed_entry->idx - 1;
8292 return NULL;
8295 if (idx + 1 < g) {
8296 err = ref_scroll_down(view, g - idx - 1);
8297 if (err)
8298 return err;
8299 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8300 s->first_displayed_entry->idx + s->selected < g &&
8301 s->selected < s->ndisplayed - 1)
8302 s->selected = g - s->first_displayed_entry->idx - 1;
8303 } else if (idx + 1 > g)
8304 ref_scroll_up(s, idx - g + 1);
8306 if (g < nlines && s->first_displayed_entry->idx == 0)
8307 s->selected = g - 1;
8309 return NULL;
8313 static const struct got_error *
8314 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8316 const struct got_error *err = NULL;
8317 struct tog_ref_view_state *s = &view->state.ref;
8318 struct tog_reflist_entry *re;
8319 int n, nscroll = view->nlines - 1;
8321 if (view->gline)
8322 return ref_goto_line(view, nscroll);
8324 switch (ch) {
8325 case '0':
8326 case '$':
8327 case KEY_RIGHT:
8328 case 'l':
8329 case KEY_LEFT:
8330 case 'h':
8331 horizontal_scroll_input(view, ch);
8332 break;
8333 case 'i':
8334 s->show_ids = !s->show_ids;
8335 view->count = 0;
8336 break;
8337 case 'm':
8338 s->show_date = !s->show_date;
8339 view->count = 0;
8340 break;
8341 case 'o':
8342 s->sort_by_date = !s->sort_by_date;
8343 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8344 view->count = 0;
8345 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8346 got_ref_cmp_by_commit_timestamp_descending :
8347 tog_ref_cmp_by_name, s->repo);
8348 if (err)
8349 break;
8350 got_reflist_object_id_map_free(tog_refs_idmap);
8351 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8352 &tog_refs, s->repo);
8353 if (err)
8354 break;
8355 ref_view_free_refs(s);
8356 err = ref_view_load_refs(s);
8357 break;
8358 case KEY_ENTER:
8359 case '\r':
8360 view->count = 0;
8361 if (!s->selected_entry)
8362 break;
8363 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8364 break;
8365 case 'T':
8366 view->count = 0;
8367 if (!s->selected_entry)
8368 break;
8369 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8370 break;
8371 case 'g':
8372 case '=':
8373 case KEY_HOME:
8374 s->selected = 0;
8375 view->count = 0;
8376 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8377 break;
8378 case 'G':
8379 case '*':
8380 case KEY_END: {
8381 int eos = view->nlines - 1;
8383 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8384 --eos; /* border */
8385 s->selected = 0;
8386 view->count = 0;
8387 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8388 for (n = 0; n < eos; n++) {
8389 if (re == NULL)
8390 break;
8391 s->first_displayed_entry = re;
8392 re = TAILQ_PREV(re, tog_reflist_head, entry);
8394 if (n > 0)
8395 s->selected = n - 1;
8396 break;
8398 case 'k':
8399 case KEY_UP:
8400 case CTRL('p'):
8401 if (s->selected > 0) {
8402 s->selected--;
8403 break;
8405 ref_scroll_up(s, 1);
8406 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8407 view->count = 0;
8408 break;
8409 case CTRL('u'):
8410 case 'u':
8411 nscroll /= 2;
8412 /* FALL THROUGH */
8413 case KEY_PPAGE:
8414 case CTRL('b'):
8415 case 'b':
8416 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8417 s->selected -= MIN(nscroll, s->selected);
8418 ref_scroll_up(s, MAX(0, nscroll));
8419 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8420 view->count = 0;
8421 break;
8422 case 'j':
8423 case KEY_DOWN:
8424 case CTRL('n'):
8425 if (s->selected < s->ndisplayed - 1) {
8426 s->selected++;
8427 break;
8429 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8430 /* can't scroll any further */
8431 view->count = 0;
8432 break;
8434 ref_scroll_down(view, 1);
8435 break;
8436 case CTRL('d'):
8437 case 'd':
8438 nscroll /= 2;
8439 /* FALL THROUGH */
8440 case KEY_NPAGE:
8441 case CTRL('f'):
8442 case 'f':
8443 case ' ':
8444 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8445 /* can't scroll any further; move cursor down */
8446 if (s->selected < s->ndisplayed - 1)
8447 s->selected += MIN(nscroll,
8448 s->ndisplayed - s->selected - 1);
8449 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8450 s->selected += s->ndisplayed - s->selected - 1;
8451 view->count = 0;
8452 break;
8454 ref_scroll_down(view, nscroll);
8455 break;
8456 case CTRL('l'):
8457 view->count = 0;
8458 tog_free_refs();
8459 err = tog_load_refs(s->repo, s->sort_by_date);
8460 if (err)
8461 break;
8462 ref_view_free_refs(s);
8463 err = ref_view_load_refs(s);
8464 break;
8465 case KEY_RESIZE:
8466 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8467 s->selected = view->nlines - 2;
8468 break;
8469 default:
8470 view->count = 0;
8471 break;
8474 return err;
8477 __dead static void
8478 usage_ref(void)
8480 endwin();
8481 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8482 getprogname());
8483 exit(1);
8486 static const struct got_error *
8487 cmd_ref(int argc, char *argv[])
8489 const struct got_error *error;
8490 struct got_repository *repo = NULL;
8491 struct got_worktree *worktree = NULL;
8492 char *cwd = NULL, *repo_path = NULL;
8493 int ch;
8494 struct tog_view *view;
8495 int *pack_fds = NULL;
8497 while ((ch = getopt(argc, argv, "r:")) != -1) {
8498 switch (ch) {
8499 case 'r':
8500 repo_path = realpath(optarg, NULL);
8501 if (repo_path == NULL)
8502 return got_error_from_errno2("realpath",
8503 optarg);
8504 break;
8505 default:
8506 usage_ref();
8507 /* NOTREACHED */
8511 argc -= optind;
8512 argv += optind;
8514 if (argc > 1)
8515 usage_ref();
8517 error = got_repo_pack_fds_open(&pack_fds);
8518 if (error != NULL)
8519 goto done;
8521 if (repo_path == NULL) {
8522 cwd = getcwd(NULL, 0);
8523 if (cwd == NULL)
8524 return got_error_from_errno("getcwd");
8525 error = got_worktree_open(&worktree, cwd);
8526 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8527 goto done;
8528 if (worktree)
8529 repo_path =
8530 strdup(got_worktree_get_repo_path(worktree));
8531 else
8532 repo_path = strdup(cwd);
8533 if (repo_path == NULL) {
8534 error = got_error_from_errno("strdup");
8535 goto done;
8539 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8540 if (error != NULL)
8541 goto done;
8543 init_curses();
8545 error = apply_unveil(got_repo_get_path(repo), NULL);
8546 if (error)
8547 goto done;
8549 error = tog_load_refs(repo, 0);
8550 if (error)
8551 goto done;
8553 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8554 if (view == NULL) {
8555 error = got_error_from_errno("view_open");
8556 goto done;
8559 error = open_ref_view(view, repo);
8560 if (error)
8561 goto done;
8563 if (worktree) {
8564 /* Release work tree lock. */
8565 got_worktree_close(worktree);
8566 worktree = NULL;
8568 error = view_loop(view);
8569 done:
8570 free(repo_path);
8571 free(cwd);
8572 if (repo) {
8573 const struct got_error *close_err = got_repo_close(repo);
8574 if (close_err)
8575 error = close_err;
8577 if (pack_fds) {
8578 const struct got_error *pack_err =
8579 got_repo_pack_fds_close(pack_fds);
8580 if (error == NULL)
8581 error = pack_err;
8583 tog_free_refs();
8584 return error;
8587 static const struct got_error*
8588 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8589 const char *str)
8591 size_t len;
8593 if (win == NULL)
8594 win = stdscr;
8596 len = strlen(str);
8597 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8599 if (focus)
8600 wstandout(win);
8601 if (mvwprintw(win, y, x, "%s", str) == ERR)
8602 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8603 if (focus)
8604 wstandend(win);
8606 return NULL;
8609 static const struct got_error *
8610 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8612 off_t *p;
8614 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8615 if (p == NULL) {
8616 free(*line_offsets);
8617 *line_offsets = NULL;
8618 return got_error_from_errno("reallocarray");
8621 *line_offsets = p;
8622 (*line_offsets)[*nlines] = off;
8623 ++(*nlines);
8624 return NULL;
8627 static const struct got_error *
8628 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8630 *ret = 0;
8632 for (;n > 0; --n, ++km) {
8633 char *t0, *t, *k;
8634 size_t len = 1;
8636 if (km->keys == NULL)
8637 continue;
8639 t = t0 = strdup(km->keys);
8640 if (t0 == NULL)
8641 return got_error_from_errno("strdup");
8643 len += strlen(t);
8644 while ((k = strsep(&t, " ")) != NULL)
8645 len += strlen(k) > 1 ? 2 : 0;
8646 free(t0);
8647 *ret = MAX(*ret, len);
8650 return NULL;
8654 * Write keymap section headers, keys, and key info in km to f.
8655 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8656 * wrap control and symbolic keys in guillemets, else use <>.
8658 static const struct got_error *
8659 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8661 int n, len = width;
8663 if (km->keys) {
8664 static const char *u8_glyph[] = {
8665 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8666 "\xe2\x80\xba" /* U+203A (utf8 >) */
8668 char *t0, *t, *k;
8669 int cs, s, first = 1;
8671 cs = got_locale_is_utf8();
8673 t = t0 = strdup(km->keys);
8674 if (t0 == NULL)
8675 return got_error_from_errno("strdup");
8677 len = strlen(km->keys);
8678 while ((k = strsep(&t, " ")) != NULL) {
8679 s = strlen(k) > 1; /* control or symbolic key */
8680 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8681 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8682 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8683 if (n < 0) {
8684 free(t0);
8685 return got_error_from_errno("fprintf");
8687 first = 0;
8688 len += s ? 2 : 0;
8689 *off += n;
8691 free(t0);
8693 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8694 if (n < 0)
8695 return got_error_from_errno("fprintf");
8696 *off += n;
8698 return NULL;
8701 static const struct got_error *
8702 format_help(struct tog_help_view_state *s)
8704 const struct got_error *err = NULL;
8705 off_t off = 0;
8706 int i, max, n, show = s->all;
8707 static const struct tog_key_map km[] = {
8708 #define KEYMAP_(info, type) { NULL, (info), type }
8709 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8710 GENERATE_HELP
8711 #undef KEYMAP_
8712 #undef KEY_
8715 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8716 if (err)
8717 return err;
8719 n = nitems(km);
8720 err = max_key_str(&max, km, n);
8721 if (err)
8722 return err;
8724 for (i = 0; i < n; ++i) {
8725 if (km[i].keys == NULL) {
8726 show = s->all;
8727 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8728 km[i].type == s->type || s->all)
8729 show = 1;
8731 if (show) {
8732 err = format_help_line(&off, s->f, &km[i], max);
8733 if (err)
8734 return err;
8735 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8736 if (err)
8737 return err;
8740 fputc('\n', s->f);
8741 ++off;
8742 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8743 return err;
8746 static const struct got_error *
8747 create_help(struct tog_help_view_state *s)
8749 FILE *f;
8750 const struct got_error *err;
8752 free(s->line_offsets);
8753 s->line_offsets = NULL;
8754 s->nlines = 0;
8756 f = got_opentemp();
8757 if (f == NULL)
8758 return got_error_from_errno("got_opentemp");
8759 s->f = f;
8761 err = format_help(s);
8762 if (err)
8763 return err;
8765 if (s->f && fflush(s->f) != 0)
8766 return got_error_from_errno("fflush");
8768 return NULL;
8771 static const struct got_error *
8772 search_start_help_view(struct tog_view *view)
8774 view->state.help.matched_line = 0;
8775 return NULL;
8778 static void
8779 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8780 size_t *nlines, int **first, int **last, int **match, int **selected)
8782 struct tog_help_view_state *s = &view->state.help;
8784 *f = s->f;
8785 *nlines = s->nlines;
8786 *line_offsets = s->line_offsets;
8787 *match = &s->matched_line;
8788 *first = &s->first_displayed_line;
8789 *last = &s->last_displayed_line;
8790 *selected = &s->selected_line;
8793 static const struct got_error *
8794 show_help_view(struct tog_view *view)
8796 struct tog_help_view_state *s = &view->state.help;
8797 const struct got_error *err;
8798 regmatch_t *regmatch = &view->regmatch;
8799 wchar_t *wline;
8800 char *line;
8801 ssize_t linelen;
8802 size_t linesz = 0;
8803 int width, nprinted = 0, rc = 0;
8804 int eos = view->nlines;
8806 if (view_is_hsplit_top(view))
8807 --eos; /* account for border */
8809 s->lineno = 0;
8810 rewind(s->f);
8811 werase(view->window);
8813 if (view->gline > s->nlines - 1)
8814 view->gline = s->nlines - 1;
8816 err = win_draw_center(view->window, 0, 0, view->ncols,
8817 view_needs_focus_indication(view),
8818 "tog help (press q to return to tog)");
8819 if (err)
8820 return err;
8821 if (eos <= 1)
8822 return NULL;
8823 waddstr(view->window, "\n\n");
8824 eos -= 2;
8826 s->eof = 0;
8827 view->maxx = 0;
8828 line = NULL;
8829 while (eos > 0 && nprinted < eos) {
8830 attr_t attr = 0;
8832 linelen = getline(&line, &linesz, s->f);
8833 if (linelen == -1) {
8834 if (!feof(s->f)) {
8835 free(line);
8836 return got_ferror(s->f, GOT_ERR_IO);
8838 s->eof = 1;
8839 break;
8841 if (++s->lineno < s->first_displayed_line)
8842 continue;
8843 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8844 continue;
8845 if (s->lineno == view->hiline)
8846 attr = A_STANDOUT;
8848 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8849 view->x ? 1 : 0);
8850 if (err) {
8851 free(line);
8852 return err;
8854 view->maxx = MAX(view->maxx, width);
8855 free(wline);
8856 wline = NULL;
8858 if (attr)
8859 wattron(view->window, attr);
8860 if (s->first_displayed_line + nprinted == s->matched_line &&
8861 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8862 err = add_matched_line(&width, line, view->ncols - 1, 0,
8863 view->window, view->x, regmatch);
8864 if (err) {
8865 free(line);
8866 return err;
8868 } else {
8869 int skip;
8871 err = format_line(&wline, &width, &skip, line,
8872 view->x, view->ncols, 0, view->x ? 1 : 0);
8873 if (err) {
8874 free(line);
8875 return err;
8877 waddwstr(view->window, &wline[skip]);
8878 free(wline);
8879 wline = NULL;
8881 if (s->lineno == view->hiline) {
8882 while (width++ < view->ncols)
8883 waddch(view->window, ' ');
8884 } else {
8885 if (width < view->ncols)
8886 waddch(view->window, '\n');
8888 if (attr)
8889 wattroff(view->window, attr);
8890 if (++nprinted == 1)
8891 s->first_displayed_line = s->lineno;
8893 free(line);
8894 if (nprinted > 0)
8895 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8896 else
8897 s->last_displayed_line = s->first_displayed_line;
8899 view_border(view);
8901 if (s->eof) {
8902 rc = waddnstr(view->window,
8903 "See the tog(1) manual page for full documentation",
8904 view->ncols - 1);
8905 if (rc == ERR)
8906 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8907 } else {
8908 wmove(view->window, view->nlines - 1, 0);
8909 wclrtoeol(view->window);
8910 wstandout(view->window);
8911 rc = waddnstr(view->window, "scroll down for more...",
8912 view->ncols - 1);
8913 if (rc == ERR)
8914 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8915 if (getcurx(view->window) < view->ncols - 6) {
8916 rc = wprintw(view->window, "[%.0f%%]",
8917 100.00 * s->last_displayed_line / s->nlines);
8918 if (rc == ERR)
8919 return got_error_msg(GOT_ERR_IO, "wprintw");
8921 wstandend(view->window);
8924 return NULL;
8927 static const struct got_error *
8928 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8930 struct tog_help_view_state *s = &view->state.help;
8931 const struct got_error *err = NULL;
8932 char *line = NULL;
8933 ssize_t linelen;
8934 size_t linesz = 0;
8935 int eos, nscroll;
8937 eos = nscroll = view->nlines;
8938 if (view_is_hsplit_top(view))
8939 --eos; /* border */
8941 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8943 switch (ch) {
8944 case '0':
8945 case '$':
8946 case KEY_RIGHT:
8947 case 'l':
8948 case KEY_LEFT:
8949 case 'h':
8950 horizontal_scroll_input(view, ch);
8951 break;
8952 case 'g':
8953 case KEY_HOME:
8954 s->first_displayed_line = 1;
8955 view->count = 0;
8956 break;
8957 case 'G':
8958 case KEY_END:
8959 view->count = 0;
8960 if (s->eof)
8961 break;
8962 s->first_displayed_line = (s->nlines - eos) + 3;
8963 s->eof = 1;
8964 break;
8965 case 'k':
8966 case KEY_UP:
8967 if (s->first_displayed_line > 1)
8968 --s->first_displayed_line;
8969 else
8970 view->count = 0;
8971 break;
8972 case CTRL('u'):
8973 case 'u':
8974 nscroll /= 2;
8975 /* FALL THROUGH */
8976 case KEY_PPAGE:
8977 case CTRL('b'):
8978 case 'b':
8979 if (s->first_displayed_line == 1) {
8980 view->count = 0;
8981 break;
8983 while (--nscroll > 0 && s->first_displayed_line > 1)
8984 s->first_displayed_line--;
8985 break;
8986 case 'j':
8987 case KEY_DOWN:
8988 case CTRL('n'):
8989 if (!s->eof)
8990 ++s->first_displayed_line;
8991 else
8992 view->count = 0;
8993 break;
8994 case CTRL('d'):
8995 case 'd':
8996 nscroll /= 2;
8997 /* FALL THROUGH */
8998 case KEY_NPAGE:
8999 case CTRL('f'):
9000 case 'f':
9001 case ' ':
9002 if (s->eof) {
9003 view->count = 0;
9004 break;
9006 while (!s->eof && --nscroll > 0) {
9007 linelen = getline(&line, &linesz, s->f);
9008 s->first_displayed_line++;
9009 if (linelen == -1) {
9010 if (feof(s->f))
9011 s->eof = 1;
9012 else
9013 err = got_ferror(s->f, GOT_ERR_IO);
9014 break;
9017 free(line);
9018 break;
9019 default:
9020 view->count = 0;
9021 break;
9024 return err;
9027 static const struct got_error *
9028 close_help_view(struct tog_view *view)
9030 struct tog_help_view_state *s = &view->state.help;
9032 free(s->line_offsets);
9033 s->line_offsets = NULL;
9034 if (fclose(s->f) == EOF)
9035 return got_error_from_errno("fclose");
9037 return NULL;
9040 static const struct got_error *
9041 reset_help_view(struct tog_view *view)
9043 struct tog_help_view_state *s = &view->state.help;
9046 if (s->f && fclose(s->f) == EOF)
9047 return got_error_from_errno("fclose");
9049 wclear(view->window);
9050 view->count = 0;
9051 view->x = 0;
9052 s->all = !s->all;
9053 s->first_displayed_line = 1;
9054 s->last_displayed_line = view->nlines;
9055 s->matched_line = 0;
9057 return create_help(s);
9060 static const struct got_error *
9061 open_help_view(struct tog_view *view, struct tog_view *parent)
9063 const struct got_error *err = NULL;
9064 struct tog_help_view_state *s = &view->state.help;
9066 s->type = (enum tog_keymap_type)parent->type;
9067 s->first_displayed_line = 1;
9068 s->last_displayed_line = view->nlines;
9069 s->selected_line = 1;
9071 view->show = show_help_view;
9072 view->input = input_help_view;
9073 view->reset = reset_help_view;
9074 view->close = close_help_view;
9075 view->search_start = search_start_help_view;
9076 view->search_setup = search_setup_help_view;
9077 view->search_next = search_next_view_match;
9079 err = create_help(s);
9080 return err;
9083 static const struct got_error *
9084 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9085 enum tog_view_type request, int y, int x)
9087 const struct got_error *err = NULL;
9089 *new_view = NULL;
9091 switch (request) {
9092 case TOG_VIEW_DIFF:
9093 if (view->type == TOG_VIEW_LOG) {
9094 struct tog_log_view_state *s = &view->state.log;
9096 err = open_diff_view_for_commit(new_view, y, x,
9097 s->selected_entry->commit, s->selected_entry->id,
9098 view, s->repo);
9099 } else
9100 return got_error_msg(GOT_ERR_NOT_IMPL,
9101 "parent/child view pair not supported");
9102 break;
9103 case TOG_VIEW_BLAME:
9104 if (view->type == TOG_VIEW_TREE) {
9105 struct tog_tree_view_state *s = &view->state.tree;
9107 err = blame_tree_entry(new_view, y, x,
9108 s->selected_entry, &s->parents, s->commit_id,
9109 s->repo);
9110 } else
9111 return got_error_msg(GOT_ERR_NOT_IMPL,
9112 "parent/child view pair not supported");
9113 break;
9114 case TOG_VIEW_LOG:
9115 if (view->type == TOG_VIEW_BLAME)
9116 err = log_annotated_line(new_view, y, x,
9117 view->state.blame.repo, view->state.blame.id_to_log);
9118 else if (view->type == TOG_VIEW_TREE)
9119 err = log_selected_tree_entry(new_view, y, x,
9120 &view->state.tree);
9121 else if (view->type == TOG_VIEW_REF)
9122 err = log_ref_entry(new_view, y, x,
9123 view->state.ref.selected_entry,
9124 view->state.ref.repo);
9125 else
9126 return got_error_msg(GOT_ERR_NOT_IMPL,
9127 "parent/child view pair not supported");
9128 break;
9129 case TOG_VIEW_TREE:
9130 if (view->type == TOG_VIEW_LOG)
9131 err = browse_commit_tree(new_view, y, x,
9132 view->state.log.selected_entry,
9133 view->state.log.in_repo_path,
9134 view->state.log.head_ref_name,
9135 view->state.log.repo);
9136 else if (view->type == TOG_VIEW_REF)
9137 err = browse_ref_tree(new_view, y, x,
9138 view->state.ref.selected_entry,
9139 view->state.ref.repo);
9140 else
9141 return got_error_msg(GOT_ERR_NOT_IMPL,
9142 "parent/child view pair not supported");
9143 break;
9144 case TOG_VIEW_REF:
9145 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9146 if (*new_view == NULL)
9147 return got_error_from_errno("view_open");
9148 if (view->type == TOG_VIEW_LOG)
9149 err = open_ref_view(*new_view, view->state.log.repo);
9150 else if (view->type == TOG_VIEW_TREE)
9151 err = open_ref_view(*new_view, view->state.tree.repo);
9152 else
9153 err = got_error_msg(GOT_ERR_NOT_IMPL,
9154 "parent/child view pair not supported");
9155 if (err)
9156 view_close(*new_view);
9157 break;
9158 case TOG_VIEW_HELP:
9159 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9160 if (*new_view == NULL)
9161 return got_error_from_errno("view_open");
9162 err = open_help_view(*new_view, view);
9163 if (err)
9164 view_close(*new_view);
9165 break;
9166 default:
9167 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9170 return err;
9174 * If view was scrolled down to move the selected line into view when opening a
9175 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9177 static void
9178 offset_selection_up(struct tog_view *view)
9180 switch (view->type) {
9181 case TOG_VIEW_BLAME: {
9182 struct tog_blame_view_state *s = &view->state.blame;
9183 if (s->first_displayed_line == 1) {
9184 s->selected_line = MAX(s->selected_line - view->offset,
9185 1);
9186 break;
9188 if (s->first_displayed_line > view->offset)
9189 s->first_displayed_line -= view->offset;
9190 else
9191 s->first_displayed_line = 1;
9192 s->selected_line += view->offset;
9193 break;
9195 case TOG_VIEW_LOG:
9196 log_scroll_up(&view->state.log, view->offset);
9197 view->state.log.selected += view->offset;
9198 break;
9199 case TOG_VIEW_REF:
9200 ref_scroll_up(&view->state.ref, view->offset);
9201 view->state.ref.selected += view->offset;
9202 break;
9203 case TOG_VIEW_TREE:
9204 tree_scroll_up(&view->state.tree, view->offset);
9205 view->state.tree.selected += view->offset;
9206 break;
9207 default:
9208 break;
9211 view->offset = 0;
9215 * If the selected line is in the section of screen covered by the bottom split,
9216 * scroll down offset lines to move it into view and index its new position.
9218 static const struct got_error *
9219 offset_selection_down(struct tog_view *view)
9221 const struct got_error *err = NULL;
9222 const struct got_error *(*scrolld)(struct tog_view *, int);
9223 int *selected = NULL;
9224 int header, offset;
9226 switch (view->type) {
9227 case TOG_VIEW_BLAME: {
9228 struct tog_blame_view_state *s = &view->state.blame;
9229 header = 3;
9230 scrolld = NULL;
9231 if (s->selected_line > view->nlines - header) {
9232 offset = abs(view->nlines - s->selected_line - header);
9233 s->first_displayed_line += offset;
9234 s->selected_line -= offset;
9235 view->offset = offset;
9237 break;
9239 case TOG_VIEW_LOG: {
9240 struct tog_log_view_state *s = &view->state.log;
9241 scrolld = &log_scroll_down;
9242 header = view_is_parent_view(view) ? 3 : 2;
9243 selected = &s->selected;
9244 break;
9246 case TOG_VIEW_REF: {
9247 struct tog_ref_view_state *s = &view->state.ref;
9248 scrolld = &ref_scroll_down;
9249 header = 3;
9250 selected = &s->selected;
9251 break;
9253 case TOG_VIEW_TREE: {
9254 struct tog_tree_view_state *s = &view->state.tree;
9255 scrolld = &tree_scroll_down;
9256 header = 5;
9257 selected = &s->selected;
9258 break;
9260 default:
9261 selected = NULL;
9262 scrolld = NULL;
9263 header = 0;
9264 break;
9267 if (selected && *selected > view->nlines - header) {
9268 offset = abs(view->nlines - *selected - header);
9269 view->offset = offset;
9270 if (scrolld && offset) {
9271 err = scrolld(view, offset);
9272 *selected -= offset;
9276 return err;
9279 static void
9280 list_commands(FILE *fp)
9282 size_t i;
9284 fprintf(fp, "commands:");
9285 for (i = 0; i < nitems(tog_commands); i++) {
9286 const struct tog_cmd *cmd = &tog_commands[i];
9287 fprintf(fp, " %s", cmd->name);
9289 fputc('\n', fp);
9292 __dead static void
9293 usage(int hflag, int status)
9295 FILE *fp = (status == 0) ? stdout : stderr;
9297 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9298 getprogname());
9299 if (hflag) {
9300 fprintf(fp, "lazy usage: %s path\n", getprogname());
9301 list_commands(fp);
9303 exit(status);
9306 static char **
9307 make_argv(int argc, ...)
9309 va_list ap;
9310 char **argv;
9311 int i;
9313 va_start(ap, argc);
9315 argv = calloc(argc, sizeof(char *));
9316 if (argv == NULL)
9317 err(1, "calloc");
9318 for (i = 0; i < argc; i++) {
9319 argv[i] = strdup(va_arg(ap, char *));
9320 if (argv[i] == NULL)
9321 err(1, "strdup");
9324 va_end(ap);
9325 return argv;
9329 * Try to convert 'tog path' into a 'tog log path' command.
9330 * The user could simply have mistyped the command rather than knowingly
9331 * provided a path. So check whether argv[0] can in fact be resolved
9332 * to a path in the HEAD commit and print a special error if not.
9333 * This hack is for mpi@ <3
9335 static const struct got_error *
9336 tog_log_with_path(int argc, char *argv[])
9338 const struct got_error *error = NULL, *close_err;
9339 const struct tog_cmd *cmd = NULL;
9340 struct got_repository *repo = NULL;
9341 struct got_worktree *worktree = NULL;
9342 struct got_object_id *commit_id = NULL, *id = NULL;
9343 struct got_commit_object *commit = NULL;
9344 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9345 char *commit_id_str = NULL, **cmd_argv = NULL;
9346 int *pack_fds = NULL;
9348 cwd = getcwd(NULL, 0);
9349 if (cwd == NULL)
9350 return got_error_from_errno("getcwd");
9352 error = got_repo_pack_fds_open(&pack_fds);
9353 if (error != NULL)
9354 goto done;
9356 error = got_worktree_open(&worktree, cwd);
9357 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9358 goto done;
9360 if (worktree)
9361 repo_path = strdup(got_worktree_get_repo_path(worktree));
9362 else
9363 repo_path = strdup(cwd);
9364 if (repo_path == NULL) {
9365 error = got_error_from_errno("strdup");
9366 goto done;
9369 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9370 if (error != NULL)
9371 goto done;
9373 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9374 repo, worktree);
9375 if (error)
9376 goto done;
9378 error = tog_load_refs(repo, 0);
9379 if (error)
9380 goto done;
9381 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9382 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9383 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9384 if (error)
9385 goto done;
9387 if (worktree) {
9388 got_worktree_close(worktree);
9389 worktree = NULL;
9392 error = got_object_open_as_commit(&commit, repo, commit_id);
9393 if (error)
9394 goto done;
9396 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9397 if (error) {
9398 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9399 goto done;
9400 fprintf(stderr, "%s: '%s' is no known command or path\n",
9401 getprogname(), argv[0]);
9402 usage(1, 1);
9403 /* not reached */
9406 error = got_object_id_str(&commit_id_str, commit_id);
9407 if (error)
9408 goto done;
9410 cmd = &tog_commands[0]; /* log */
9411 argc = 4;
9412 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9413 error = cmd->cmd_main(argc, cmd_argv);
9414 done:
9415 if (repo) {
9416 close_err = got_repo_close(repo);
9417 if (error == NULL)
9418 error = close_err;
9420 if (commit)
9421 got_object_commit_close(commit);
9422 if (worktree)
9423 got_worktree_close(worktree);
9424 if (pack_fds) {
9425 const struct got_error *pack_err =
9426 got_repo_pack_fds_close(pack_fds);
9427 if (error == NULL)
9428 error = pack_err;
9430 free(id);
9431 free(commit_id_str);
9432 free(commit_id);
9433 free(cwd);
9434 free(repo_path);
9435 free(in_repo_path);
9436 if (cmd_argv) {
9437 int i;
9438 for (i = 0; i < argc; i++)
9439 free(cmd_argv[i]);
9440 free(cmd_argv);
9442 tog_free_refs();
9443 return error;
9446 int
9447 main(int argc, char *argv[])
9449 const struct got_error *error = NULL;
9450 const struct tog_cmd *cmd = NULL;
9451 int ch, hflag = 0, Vflag = 0;
9452 char **cmd_argv = NULL;
9453 static const struct option longopts[] = {
9454 { "version", no_argument, NULL, 'V' },
9455 { NULL, 0, NULL, 0}
9457 char *diff_algo_str = NULL;
9459 setlocale(LC_CTYPE, "");
9461 #ifndef PROFILE
9462 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9463 NULL) == -1)
9464 err(1, "pledge");
9465 #endif
9467 if (!isatty(STDIN_FILENO))
9468 errx(1, "standard input is not a tty");
9470 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9471 switch (ch) {
9472 case 'h':
9473 hflag = 1;
9474 break;
9475 case 'V':
9476 Vflag = 1;
9477 break;
9478 default:
9479 usage(hflag, 1);
9480 /* NOTREACHED */
9484 argc -= optind;
9485 argv += optind;
9486 optind = 1;
9487 optreset = 1;
9489 if (Vflag) {
9490 got_version_print_str();
9491 return 0;
9494 if (argc == 0) {
9495 if (hflag)
9496 usage(hflag, 0);
9497 /* Build an argument vector which runs a default command. */
9498 cmd = &tog_commands[0];
9499 argc = 1;
9500 cmd_argv = make_argv(argc, cmd->name);
9501 } else {
9502 size_t i;
9504 /* Did the user specify a command? */
9505 for (i = 0; i < nitems(tog_commands); i++) {
9506 if (strncmp(tog_commands[i].name, argv[0],
9507 strlen(argv[0])) == 0) {
9508 cmd = &tog_commands[i];
9509 break;
9514 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9515 if (diff_algo_str) {
9516 if (strcasecmp(diff_algo_str, "patience") == 0)
9517 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9518 if (strcasecmp(diff_algo_str, "myers") == 0)
9519 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9522 if (cmd == NULL) {
9523 if (argc != 1)
9524 usage(0, 1);
9525 /* No command specified; try log with a path */
9526 error = tog_log_with_path(argc, argv);
9527 } else {
9528 if (hflag)
9529 cmd->cmd_usage();
9530 else
9531 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9534 endwin();
9535 if (cmd_argv) {
9536 int i;
9537 for (i = 0; i < argc; i++)
9538 free(cmd_argv[i]);
9539 free(cmd_argv);
9542 if (error && error->code != GOT_ERR_CANCELLED &&
9543 error->code != GOT_ERR_EOF &&
9544 error->code != GOT_ERR_PRIVSEP_EXIT &&
9545 error->code != GOT_ERR_PRIVSEP_PIPE &&
9546 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9547 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9548 return 0;