Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <getopt.h>
33 #include <string.h>
34 #include <err.h>
35 #include <unistd.h>
36 #include <limits.h>
37 #include <wchar.h>
38 #include <time.h>
39 #include <pthread.h>
40 #include <libgen.h>
41 #include <regex.h>
42 #include <sched.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_diff.h"
50 #include "got_opentemp.h"
51 #include "got_utf8.h"
52 #include "got_cancel.h"
53 #include "got_commit_graph.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_path.h"
57 #include "got_worktree.h"
59 #ifndef MIN
60 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
61 #endif
63 #ifndef MAX
64 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
65 #endif
67 #define CTRL(x) ((x) & 0x1f)
69 #ifndef nitems
70 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
71 #endif
73 struct tog_cmd {
74 const char *name;
75 const struct got_error *(*cmd_main)(int, char *[]);
76 void (*cmd_usage)(void);
77 };
79 __dead static void usage(int, int);
80 __dead static void usage_log(void);
81 __dead static void usage_diff(void);
82 __dead static void usage_blame(void);
83 __dead static void usage_tree(void);
84 __dead static void usage_ref(void);
86 static const struct got_error* cmd_log(int, char *[]);
87 static const struct got_error* cmd_diff(int, char *[]);
88 static const struct got_error* cmd_blame(int, char *[]);
89 static const struct got_error* cmd_tree(int, char *[]);
90 static const struct got_error* cmd_ref(int, char *[]);
92 static const struct tog_cmd tog_commands[] = {
93 { "log", cmd_log, usage_log },
94 { "diff", cmd_diff, usage_diff },
95 { "blame", cmd_blame, usage_blame },
96 { "tree", cmd_tree, usage_tree },
97 { "ref", cmd_ref, usage_ref },
98 };
100 enum tog_view_type {
101 TOG_VIEW_DIFF,
102 TOG_VIEW_LOG,
103 TOG_VIEW_BLAME,
104 TOG_VIEW_TREE,
105 TOG_VIEW_REF,
106 };
108 enum tog_view_mode {
109 TOG_VIEW_SPLIT_NONE,
110 TOG_VIEW_SPLIT_VERT,
111 TOG_VIEW_SPLIT_HRZN
112 };
114 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
116 #define TOG_EOF_STRING "(END)"
118 struct commit_queue_entry {
119 TAILQ_ENTRY(commit_queue_entry) entry;
120 struct got_object_id *id;
121 struct got_commit_object *commit;
122 int idx;
123 };
124 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
125 struct commit_queue {
126 int ncommits;
127 struct commit_queue_head head;
128 };
130 struct tog_color {
131 STAILQ_ENTRY(tog_color) entry;
132 regex_t regex;
133 short colorpair;
134 };
135 STAILQ_HEAD(tog_colors, tog_color);
137 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
138 static struct got_reflist_object_id_map *tog_refs_idmap;
140 static const struct got_error *
141 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
142 struct got_reference* re2)
144 const char *name1 = got_ref_get_name(re1);
145 const char *name2 = got_ref_get_name(re2);
146 int isbackup1, isbackup2;
148 /* Sort backup refs towards the bottom of the list. */
149 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
150 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
151 if (!isbackup1 && isbackup2) {
152 *cmp = -1;
153 return NULL;
154 } else if (isbackup1 && !isbackup2) {
155 *cmp = 1;
156 return NULL;
159 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
160 return NULL;
163 static const struct got_error *
164 tog_load_refs(struct got_repository *repo, int sort_by_date)
166 const struct got_error *err;
168 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
169 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
170 repo);
171 if (err)
172 return err;
174 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
175 repo);
178 static void
179 tog_free_refs(void)
181 if (tog_refs_idmap) {
182 got_reflist_object_id_map_free(tog_refs_idmap);
183 tog_refs_idmap = NULL;
185 got_ref_list_free(&tog_refs);
188 static const struct got_error *
189 add_color(struct tog_colors *colors, const char *pattern,
190 int idx, short color)
192 const struct got_error *err = NULL;
193 struct tog_color *tc;
194 int regerr = 0;
196 if (idx < 1 || idx > COLOR_PAIRS - 1)
197 return NULL;
199 init_pair(idx, color, -1);
201 tc = calloc(1, sizeof(*tc));
202 if (tc == NULL)
203 return got_error_from_errno("calloc");
204 regerr = regcomp(&tc->regex, pattern,
205 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
206 if (regerr) {
207 static char regerr_msg[512];
208 static char err_msg[512];
209 regerror(regerr, &tc->regex, regerr_msg,
210 sizeof(regerr_msg));
211 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
212 regerr_msg);
213 err = got_error_msg(GOT_ERR_REGEX, err_msg);
214 free(tc);
215 return err;
217 tc->colorpair = idx;
218 STAILQ_INSERT_HEAD(colors, tc, entry);
219 return NULL;
222 static void
223 free_colors(struct tog_colors *colors)
225 struct tog_color *tc;
227 while (!STAILQ_EMPTY(colors)) {
228 tc = STAILQ_FIRST(colors);
229 STAILQ_REMOVE_HEAD(colors, entry);
230 regfree(&tc->regex);
231 free(tc);
235 static struct tog_color *
236 get_color(struct tog_colors *colors, int colorpair)
238 struct tog_color *tc = NULL;
240 STAILQ_FOREACH(tc, colors, entry) {
241 if (tc->colorpair == colorpair)
242 return tc;
245 return NULL;
248 static int
249 default_color_value(const char *envvar)
251 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
252 return COLOR_MAGENTA;
253 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
254 return COLOR_CYAN;
255 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
256 return COLOR_YELLOW;
257 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
258 return COLOR_GREEN;
259 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
260 return COLOR_MAGENTA;
261 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
262 return COLOR_MAGENTA;
263 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
264 return COLOR_CYAN;
265 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
266 return COLOR_GREEN;
267 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
268 return COLOR_GREEN;
269 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
270 return COLOR_CYAN;
271 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
272 return COLOR_YELLOW;
273 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
274 return COLOR_GREEN;
275 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
276 return COLOR_MAGENTA;
277 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
278 return COLOR_YELLOW;
279 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
280 return COLOR_CYAN;
282 return -1;
285 static int
286 get_color_value(const char *envvar)
288 const char *val = getenv(envvar);
290 if (val == NULL)
291 return default_color_value(envvar);
293 if (strcasecmp(val, "black") == 0)
294 return COLOR_BLACK;
295 if (strcasecmp(val, "red") == 0)
296 return COLOR_RED;
297 if (strcasecmp(val, "green") == 0)
298 return COLOR_GREEN;
299 if (strcasecmp(val, "yellow") == 0)
300 return COLOR_YELLOW;
301 if (strcasecmp(val, "blue") == 0)
302 return COLOR_BLUE;
303 if (strcasecmp(val, "magenta") == 0)
304 return COLOR_MAGENTA;
305 if (strcasecmp(val, "cyan") == 0)
306 return COLOR_CYAN;
307 if (strcasecmp(val, "white") == 0)
308 return COLOR_WHITE;
309 if (strcasecmp(val, "default") == 0)
310 return -1;
312 return default_color_value(envvar);
316 struct tog_diff_view_state {
317 struct got_object_id *id1, *id2;
318 const char *label1, *label2;
319 FILE *f, *f1, *f2;
320 int fd1, fd2;
321 int first_displayed_line;
322 int last_displayed_line;
323 int eof;
324 int diff_context;
325 int ignore_whitespace;
326 int force_text_diff;
327 struct got_repository *repo;
328 struct tog_colors colors;
329 size_t nlines;
330 off_t *line_offsets;
331 int matched_line;
332 int selected_line;
334 /* passed from log view; may be NULL */
335 struct tog_view *log_view;
336 };
338 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
340 struct tog_log_thread_args {
341 pthread_cond_t need_commits;
342 pthread_cond_t commit_loaded;
343 int commits_needed;
344 int load_all;
345 struct got_commit_graph *graph;
346 struct commit_queue *commits;
347 const char *in_repo_path;
348 struct got_object_id *start_id;
349 struct got_repository *repo;
350 int *pack_fds;
351 int log_complete;
352 sig_atomic_t *quit;
353 struct commit_queue_entry **first_displayed_entry;
354 struct commit_queue_entry **selected_entry;
355 int *searching;
356 int *search_next_done;
357 regex_t *regex;
358 };
360 struct tog_log_view_state {
361 struct commit_queue commits;
362 struct commit_queue_entry *first_displayed_entry;
363 struct commit_queue_entry *last_displayed_entry;
364 struct commit_queue_entry *selected_entry;
365 int selected;
366 char *in_repo_path;
367 char *head_ref_name;
368 int log_branches;
369 struct got_repository *repo;
370 struct got_object_id *start_id;
371 sig_atomic_t quit;
372 pthread_t thread;
373 struct tog_log_thread_args thread_args;
374 struct commit_queue_entry *matched_entry;
375 struct commit_queue_entry *search_entry;
376 struct tog_colors colors;
377 };
379 #define TOG_COLOR_DIFF_MINUS 1
380 #define TOG_COLOR_DIFF_PLUS 2
381 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
382 #define TOG_COLOR_DIFF_META 4
383 #define TOG_COLOR_TREE_SUBMODULE 5
384 #define TOG_COLOR_TREE_SYMLINK 6
385 #define TOG_COLOR_TREE_DIRECTORY 7
386 #define TOG_COLOR_TREE_EXECUTABLE 8
387 #define TOG_COLOR_COMMIT 9
388 #define TOG_COLOR_AUTHOR 10
389 #define TOG_COLOR_DATE 11
390 #define TOG_COLOR_REFS_HEADS 12
391 #define TOG_COLOR_REFS_TAGS 13
392 #define TOG_COLOR_REFS_REMOTES 14
393 #define TOG_COLOR_REFS_BACKUP 15
395 struct tog_blame_cb_args {
396 struct tog_blame_line *lines; /* one per line */
397 int nlines;
399 struct tog_view *view;
400 struct got_object_id *commit_id;
401 int *quit;
402 };
404 struct tog_blame_thread_args {
405 const char *path;
406 struct got_repository *repo;
407 struct tog_blame_cb_args *cb_args;
408 int *complete;
409 got_cancel_cb cancel_cb;
410 void *cancel_arg;
411 };
413 struct tog_blame {
414 FILE *f;
415 off_t filesize;
416 struct tog_blame_line *lines;
417 int nlines;
418 off_t *line_offsets;
419 pthread_t thread;
420 struct tog_blame_thread_args thread_args;
421 struct tog_blame_cb_args cb_args;
422 const char *path;
423 int *pack_fds;
424 };
426 struct tog_blame_view_state {
427 int first_displayed_line;
428 int last_displayed_line;
429 int selected_line;
430 int blame_complete;
431 int eof;
432 int done;
433 struct got_object_id_queue blamed_commits;
434 struct got_object_qid *blamed_commit;
435 char *path;
436 struct got_repository *repo;
437 struct got_object_id *commit_id;
438 struct tog_blame blame;
439 int matched_line;
440 struct tog_colors colors;
441 };
443 struct tog_parent_tree {
444 TAILQ_ENTRY(tog_parent_tree) entry;
445 struct got_tree_object *tree;
446 struct got_tree_entry *first_displayed_entry;
447 struct got_tree_entry *selected_entry;
448 int selected;
449 };
451 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
453 struct tog_tree_view_state {
454 char *tree_label;
455 struct got_object_id *commit_id;/* commit which this tree belongs to */
456 struct got_tree_object *root; /* the commit's root tree entry */
457 struct got_tree_object *tree; /* currently displayed (sub-)tree */
458 struct got_tree_entry *first_displayed_entry;
459 struct got_tree_entry *last_displayed_entry;
460 struct got_tree_entry *selected_entry;
461 int ndisplayed, selected, show_ids;
462 struct tog_parent_trees parents; /* parent trees of current sub-tree */
463 char *head_ref_name;
464 struct got_repository *repo;
465 struct got_tree_entry *matched_entry;
466 struct tog_colors colors;
467 };
469 struct tog_reflist_entry {
470 TAILQ_ENTRY(tog_reflist_entry) entry;
471 struct got_reference *ref;
472 int idx;
473 };
475 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
477 struct tog_ref_view_state {
478 struct tog_reflist_head refs;
479 struct tog_reflist_entry *first_displayed_entry;
480 struct tog_reflist_entry *last_displayed_entry;
481 struct tog_reflist_entry *selected_entry;
482 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
483 struct got_repository *repo;
484 struct tog_reflist_entry *matched_entry;
485 struct tog_colors colors;
486 };
488 /*
489 * We implement two types of views: parent views and child views.
491 * The 'Tab' key switches focus between a parent view and its child view.
492 * Child views are shown side-by-side to their parent view, provided
493 * there is enough screen estate.
495 * When a new view is opened from within a parent view, this new view
496 * becomes a child view of the parent view, replacing any existing child.
498 * When a new view is opened from within a child view, this new view
499 * becomes a parent view which will obscure the views below until the
500 * user quits the new parent view by typing 'q'.
502 * This list of views contains parent views only.
503 * Child views are only pointed to by their parent view.
504 */
505 TAILQ_HEAD(tog_view_list_head, tog_view);
507 struct tog_view {
508 TAILQ_ENTRY(tog_view) entry;
509 WINDOW *window;
510 PANEL *panel;
511 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
512 int maxx, x; /* max column and current start column */
513 int lines, cols; /* copies of LINES and COLS */
514 int nscrolled, offset; /* lines scrolled and hsplit line offset */
515 int ch, count; /* current keymap and count prefix */
516 int focussed; /* Only set on one parent or child view at a time. */
517 int dying;
518 struct tog_view *parent;
519 struct tog_view *child;
521 /*
522 * This flag is initially set on parent views when a new child view
523 * is created. It gets toggled when the 'Tab' key switches focus
524 * between parent and child.
525 * The flag indicates whether focus should be passed on to our child
526 * view if this parent view gets picked for focus after another parent
527 * view was closed. This prevents child views from losing focus in such
528 * situations.
529 */
530 int focus_child;
532 enum tog_view_mode mode;
533 /* type-specific state */
534 enum tog_view_type type;
535 union {
536 struct tog_diff_view_state diff;
537 struct tog_log_view_state log;
538 struct tog_blame_view_state blame;
539 struct tog_tree_view_state tree;
540 struct tog_ref_view_state ref;
541 } state;
543 const struct got_error *(*show)(struct tog_view *);
544 const struct got_error *(*input)(struct tog_view **,
545 struct tog_view *, int);
546 const struct got_error *(*close)(struct tog_view *);
548 const struct got_error *(*search_start)(struct tog_view *);
549 const struct got_error *(*search_next)(struct tog_view *);
550 int search_started;
551 int searching;
552 #define TOG_SEARCH_FORWARD 1
553 #define TOG_SEARCH_BACKWARD 2
554 int search_next_done;
555 #define TOG_SEARCH_HAVE_MORE 1
556 #define TOG_SEARCH_NO_MORE 2
557 #define TOG_SEARCH_HAVE_NONE 3
558 regex_t regex;
559 regmatch_t regmatch;
560 };
562 static const struct got_error *open_diff_view(struct tog_view *,
563 struct got_object_id *, struct got_object_id *,
564 const char *, const char *, int, int, int, struct tog_view *,
565 struct got_repository *);
566 static const struct got_error *show_diff_view(struct tog_view *);
567 static const struct got_error *input_diff_view(struct tog_view **,
568 struct tog_view *, int);
569 static const struct got_error* close_diff_view(struct tog_view *);
570 static const struct got_error *search_start_diff_view(struct tog_view *);
571 static const struct got_error *search_next_diff_view(struct tog_view *);
573 static const struct got_error *open_log_view(struct tog_view *,
574 struct got_object_id *, struct got_repository *,
575 const char *, const char *, int);
576 static const struct got_error * show_log_view(struct tog_view *);
577 static const struct got_error *input_log_view(struct tog_view **,
578 struct tog_view *, int);
579 static const struct got_error *close_log_view(struct tog_view *);
580 static const struct got_error *search_start_log_view(struct tog_view *);
581 static const struct got_error *search_next_log_view(struct tog_view *);
583 static const struct got_error *open_blame_view(struct tog_view *, char *,
584 struct got_object_id *, struct got_repository *);
585 static const struct got_error *show_blame_view(struct tog_view *);
586 static const struct got_error *input_blame_view(struct tog_view **,
587 struct tog_view *, int);
588 static const struct got_error *close_blame_view(struct tog_view *);
589 static const struct got_error *search_start_blame_view(struct tog_view *);
590 static const struct got_error *search_next_blame_view(struct tog_view *);
592 static const struct got_error *open_tree_view(struct tog_view *,
593 struct got_object_id *, const char *, struct got_repository *);
594 static const struct got_error *show_tree_view(struct tog_view *);
595 static const struct got_error *input_tree_view(struct tog_view **,
596 struct tog_view *, int);
597 static const struct got_error *close_tree_view(struct tog_view *);
598 static const struct got_error *search_start_tree_view(struct tog_view *);
599 static const struct got_error *search_next_tree_view(struct tog_view *);
601 static const struct got_error *open_ref_view(struct tog_view *,
602 struct got_repository *);
603 static const struct got_error *show_ref_view(struct tog_view *);
604 static const struct got_error *input_ref_view(struct tog_view **,
605 struct tog_view *, int);
606 static const struct got_error *close_ref_view(struct tog_view *);
607 static const struct got_error *search_start_ref_view(struct tog_view *);
608 static const struct got_error *search_next_ref_view(struct tog_view *);
610 static volatile sig_atomic_t tog_sigwinch_received;
611 static volatile sig_atomic_t tog_sigpipe_received;
612 static volatile sig_atomic_t tog_sigcont_received;
613 static volatile sig_atomic_t tog_sigint_received;
614 static volatile sig_atomic_t tog_sigterm_received;
616 static void
617 tog_sigwinch(int signo)
619 tog_sigwinch_received = 1;
622 static void
623 tog_sigpipe(int signo)
625 tog_sigpipe_received = 1;
628 static void
629 tog_sigcont(int signo)
631 tog_sigcont_received = 1;
634 static void
635 tog_sigint(int signo)
637 tog_sigint_received = 1;
640 static void
641 tog_sigterm(int signo)
643 tog_sigterm_received = 1;
646 static int
647 tog_fatal_signal_received(void)
649 return (tog_sigpipe_received ||
650 tog_sigint_received || tog_sigint_received);
654 static const struct got_error *
655 view_close(struct tog_view *view)
657 const struct got_error *err = NULL;
659 if (view->child) {
660 view_close(view->child);
661 view->child = NULL;
663 if (view->close)
664 err = view->close(view);
665 if (view->panel)
666 del_panel(view->panel);
667 if (view->window)
668 delwin(view->window);
669 free(view);
670 return err;
673 static struct tog_view *
674 view_open(int nlines, int ncols, int begin_y, int begin_x,
675 enum tog_view_type type)
677 struct tog_view *view = calloc(1, sizeof(*view));
679 if (view == NULL)
680 return NULL;
682 view->type = type;
683 view->lines = LINES;
684 view->cols = COLS;
685 view->nlines = nlines ? nlines : LINES - begin_y;
686 view->ncols = ncols ? ncols : COLS - begin_x;
687 view->begin_y = begin_y;
688 view->begin_x = begin_x;
689 view->window = newwin(nlines, ncols, begin_y, begin_x);
690 if (view->window == NULL) {
691 view_close(view);
692 return NULL;
694 view->panel = new_panel(view->window);
695 if (view->panel == NULL ||
696 set_panel_userptr(view->panel, view) != OK) {
697 view_close(view);
698 return NULL;
701 keypad(view->window, TRUE);
702 return view;
705 static int
706 view_split_begin_x(int begin_x)
708 if (begin_x > 0 || COLS < 120)
709 return 0;
710 return (COLS - MAX(COLS / 2, 80));
713 /* XXX Stub till we decide what to do. */
714 static int
715 view_split_begin_y(int lines)
717 return lines * HSPLIT_SCALE;
720 static const struct got_error *view_resize(struct tog_view *);
722 static const struct got_error *
723 view_splitscreen(struct tog_view *view)
725 const struct got_error *err = NULL;
727 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
728 view->begin_y = view_split_begin_y(view->nlines);
729 view->begin_x = 0;
730 } else {
731 view->begin_x = view_split_begin_x(0);
732 view->begin_y = 0;
734 view->nlines = LINES - view->begin_y;
735 view->ncols = COLS - view->begin_x;
736 view->lines = LINES;
737 view->cols = COLS;
738 err = view_resize(view);
739 if (err)
740 return err;
742 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
743 view->parent->nlines = view->begin_y;
745 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
746 return got_error_from_errno("mvwin");
748 return NULL;
751 static const struct got_error *
752 view_fullscreen(struct tog_view *view)
754 const struct got_error *err = NULL;
756 view->begin_x = 0;
757 view->begin_y = 0;
758 view->nlines = LINES;
759 view->ncols = COLS;
760 view->lines = LINES;
761 view->cols = COLS;
762 err = view_resize(view);
763 if (err)
764 return err;
766 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
767 return got_error_from_errno("mvwin");
769 return NULL;
772 static int
773 view_is_parent_view(struct tog_view *view)
775 return view->parent == NULL;
778 static int
779 view_is_splitscreen(struct tog_view *view)
781 return view->begin_x > 0 || view->begin_y > 0;
784 static void
785 view_border(struct tog_view *view)
787 PANEL *panel;
788 const struct tog_view *view_above;
790 if (view->parent)
791 return view_border(view->parent);
793 panel = panel_above(view->panel);
794 if (panel == NULL)
795 return;
797 view_above = panel_userptr(panel);
798 if (view->mode == TOG_VIEW_SPLIT_HRZN)
799 mvwhline(view->window, view_above->begin_y - 1,
800 view->begin_x, got_locale_is_utf8() ?
801 ACS_HLINE : '-', view->ncols);
802 else
803 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
804 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
807 static const struct got_error *request_log_commits(struct tog_view *);
808 static const struct got_error *offset_selection_down(struct tog_view *);
809 static void offset_selection_up(struct tog_view *);
811 static const struct got_error *
812 view_resize(struct tog_view *view)
814 const struct got_error *err = NULL;
815 int dif, nlines, ncols;
817 dif = LINES - view->lines; /* line difference */
819 if (view->lines > LINES)
820 nlines = view->nlines - (view->lines - LINES);
821 else
822 nlines = view->nlines + (LINES - view->lines);
823 if (view->cols > COLS)
824 ncols = view->ncols - (view->cols - COLS);
825 else
826 ncols = view->ncols + (COLS - view->cols);
828 if (view->child) {
829 int hs = view->child->begin_y;
831 if (view->child->focussed)
832 view->child->begin_x = view_split_begin_x(view->begin_x);
833 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
834 view->child->begin_x == 0) {
835 ncols = COLS;
837 view_fullscreen(view->child);
838 if (view->child->focussed)
839 show_panel(view->child->panel);
840 else
841 show_panel(view->panel);
842 } else {
843 ncols = view->child->begin_x;
845 view_splitscreen(view->child);
846 show_panel(view->child->panel);
848 /*
849 * Request commits if terminal height was increased in a log
850 * view so we have enough commits loaded to populate the view.
851 */
852 if (view->type == TOG_VIEW_LOG && dif > 0) {
853 struct tog_log_view_state *ts = &view->state.log;
855 if (ts->commits.ncommits < ts->selected_entry->idx +
856 view->lines - ts->selected) {
857 view->nscrolled = ts->selected_entry->idx +
858 view->lines - ts->selected -
859 ts->commits.ncommits + dif;
860 err = request_log_commits(view);
861 if (err)
862 return err;
866 /*
867 * XXX This is ugly and needs to be moved into the above
868 * logic but "works" for now and my attempts at moving it
869 * break either 'tab' or 'F' key maps in horizontal splits.
870 */
871 if (hs) {
872 err = view_splitscreen(view->child);
873 if (err)
874 return err;
875 if (dif < 0) { /* top split decreased */
876 err = offset_selection_down(view);
877 if (err)
878 return err;
880 view_border(view);
881 update_panels();
882 doupdate();
883 show_panel(view->child->panel);
884 nlines = view->nlines;
886 } else if (view->parent == NULL)
887 ncols = COLS;
889 if (wresize(view->window, nlines, ncols) == ERR)
890 return got_error_from_errno("wresize");
891 if (replace_panel(view->panel, view->window) == ERR)
892 return got_error_from_errno("replace_panel");
893 wclear(view->window);
895 view->nlines = nlines;
896 view->ncols = ncols;
897 view->lines = LINES;
898 view->cols = COLS;
900 return NULL;
903 static const struct got_error *
904 view_close_child(struct tog_view *view)
906 const struct got_error *err = NULL;
908 if (view->child == NULL)
909 return NULL;
911 err = view_close(view->child);
912 view->child = NULL;
913 return err;
916 static const struct got_error *
917 view_set_child(struct tog_view *view, struct tog_view *child)
919 view->child = child;
920 child->parent = view;
922 return view_resize(view);
925 static void
926 tog_resizeterm(void)
928 int cols, lines;
929 struct winsize size;
931 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
932 cols = 80; /* Default */
933 lines = 24;
934 } else {
935 cols = size.ws_col;
936 lines = size.ws_row;
938 resize_term(lines, cols);
941 static const struct got_error *
942 view_search_start(struct tog_view *view)
944 const struct got_error *err = NULL;
945 struct tog_view *v = view;
946 char pattern[1024];
947 int ret;
949 if (view->search_started) {
950 regfree(&view->regex);
951 view->searching = 0;
952 memset(&view->regmatch, 0, sizeof(view->regmatch));
954 view->search_started = 0;
956 if (view->nlines < 1)
957 return NULL;
959 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
960 view_is_splitscreen(view->child))
961 v = view->child;
963 mvwaddstr(v->window, v->nlines - 1, 0, "/");
964 wclrtoeol(v->window);
966 nocbreak();
967 echo();
968 ret = wgetnstr(v->window, pattern, sizeof(pattern));
969 wrefresh(v->window);
970 cbreak();
971 noecho();
972 if (ret == ERR)
973 return NULL;
975 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
976 err = view->search_start(view);
977 if (err) {
978 regfree(&view->regex);
979 return err;
981 view->search_started = 1;
982 view->searching = TOG_SEARCH_FORWARD;
983 view->search_next_done = 0;
984 view->search_next(view);
987 return NULL;
990 /*
991 * Compute view->count from numeric user input. User has five-tenths of a
992 * second to follow each numeric keypress with another number to form count.
993 * Return first non-numeric input or ERR and assign total to view->count.
994 * XXX Should we add support for user-defined timeout?
995 */
996 static int
997 get_compound_key(struct tog_view *view, int c)
999 struct tog_view *v = view;
1000 int x, n = 0;
1002 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
1003 view_is_splitscreen(view->child))
1004 v = view->child;
1005 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1006 v = view->parent;
1008 view->count = 0;
1009 halfdelay(5); /* block for half a second */
1010 wattron(v->window, A_BOLD);
1011 wmove(v->window, v->nlines - 1, 0);
1012 wclrtoeol(v->window);
1013 waddch(v->window, ':');
1015 do {
1016 x = getcurx(v->window);
1017 if (x != ERR && x < view->ncols) {
1018 waddch(v->window, c);
1019 wrefresh(v->window);
1023 * Don't overflow. Max valid request should be the greatest
1024 * between the longest and total lines; cap at 10 million.
1026 if (n >= 9999999)
1027 n = 9999999;
1028 else
1029 n = n * 10 + (c - '0');
1030 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1032 /* Massage excessive or inapplicable values at the input handler. */
1033 view->count = n;
1035 wattroff(v->window, A_BOLD);
1036 cbreak(); /* return to blocking */
1037 return c;
1040 static const struct got_error *
1041 view_input(struct tog_view **new, int *done, struct tog_view *view,
1042 struct tog_view_list_head *views)
1044 const struct got_error *err = NULL;
1045 struct tog_view *v;
1046 int ch, errcode;
1048 *new = NULL;
1050 /* Clear "no matches" indicator. */
1051 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1052 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1053 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1054 view->count = 0;
1057 if (view->searching && !view->search_next_done) {
1058 errcode = pthread_mutex_unlock(&tog_mutex);
1059 if (errcode)
1060 return got_error_set_errno(errcode,
1061 "pthread_mutex_unlock");
1062 sched_yield();
1063 errcode = pthread_mutex_lock(&tog_mutex);
1064 if (errcode)
1065 return got_error_set_errno(errcode,
1066 "pthread_mutex_lock");
1067 view->search_next(view);
1068 return NULL;
1071 nodelay(stdscr, FALSE);
1072 /* Allow threads to make progress while we are waiting for input. */
1073 errcode = pthread_mutex_unlock(&tog_mutex);
1074 if (errcode)
1075 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1076 /* If we have an unfinished count, don't get a new key map. */
1077 ch = view->ch;
1078 if ((view->count && --view->count == 0) || !view->count) {
1079 ch = wgetch(view->window);
1080 if (ch >= '1' && ch <= '9')
1081 view->ch = ch = get_compound_key(view, ch);
1083 errcode = pthread_mutex_lock(&tog_mutex);
1084 if (errcode)
1085 return got_error_set_errno(errcode, "pthread_mutex_lock");
1086 nodelay(stdscr, TRUE);
1088 if (tog_sigwinch_received || tog_sigcont_received) {
1089 tog_resizeterm();
1090 tog_sigwinch_received = 0;
1091 tog_sigcont_received = 0;
1092 TAILQ_FOREACH(v, views, entry) {
1093 err = view_resize(v);
1094 if (err)
1095 return err;
1096 err = v->input(new, v, KEY_RESIZE);
1097 if (err)
1098 return err;
1099 if (v->child) {
1100 err = view_resize(v->child);
1101 if (err)
1102 return err;
1103 err = v->child->input(new, v->child,
1104 KEY_RESIZE);
1105 if (err)
1106 return err;
1111 switch (ch) {
1112 case '\t':
1113 view->count = 0;
1114 if (view->child) {
1115 view->focussed = 0;
1116 view->child->focussed = 1;
1117 view->focus_child = 1;
1118 } else if (view->parent) {
1119 view->focussed = 0;
1120 view->parent->focussed = 1;
1121 view->parent->focus_child = 0;
1122 if (!view_is_splitscreen(view)) {
1123 if (view->mode == TOG_VIEW_SPLIT_HRZN &&
1124 view->parent->type == TOG_VIEW_LOG) {
1125 err = request_log_commits(view->parent);
1126 if (err)
1127 return err;
1129 offset_selection_up(view->parent);
1130 err = view_fullscreen(view->parent);
1131 if (err)
1132 return err;
1135 break;
1136 case 'q':
1137 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1138 if (view->parent->type == TOG_VIEW_LOG) {
1139 /* might need more commits to fill fullscreen */
1140 err = request_log_commits(view->parent);
1141 if (err)
1142 break;
1144 offset_selection_up(view->parent);
1145 view->parent->mode = TOG_VIEW_SPLIT_NONE;
1147 err = view->input(new, view, ch);
1148 view->dying = 1;
1149 break;
1150 case 'Q':
1151 *done = 1;
1152 break;
1153 case 'F':
1154 view->count = 0;
1155 if (view_is_parent_view(view)) {
1156 if (view->child == NULL)
1157 break;
1158 if (view_is_splitscreen(view->child)) {
1159 view->focussed = 0;
1160 view->child->focussed = 1;
1161 err = view_fullscreen(view->child);
1162 } else
1163 err = view_splitscreen(view->child);
1164 if (err)
1165 break;
1166 err = view->child->input(new, view->child,
1167 KEY_RESIZE);
1168 } else {
1169 if (view_is_splitscreen(view)) {
1170 view->parent->focussed = 0;
1171 view->focussed = 1;
1172 err = view_fullscreen(view);
1173 } else {
1174 err = view_splitscreen(view);
1175 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1176 err = view_resize(view->parent);
1178 if (err)
1179 break;
1180 err = view->input(new, view, KEY_RESIZE);
1182 if (err)
1183 break;
1184 if (view->type == TOG_VIEW_LOG) {
1185 err = request_log_commits(view);
1186 if (err)
1187 break;
1189 if (view->parent)
1190 err = offset_selection_down(view->parent);
1191 if (!err)
1192 err = offset_selection_down(view);
1193 break;
1194 case KEY_RESIZE:
1195 break;
1196 case '/':
1197 view->count = 0;
1198 if (view->search_start)
1199 view_search_start(view);
1200 else
1201 err = view->input(new, view, ch);
1202 break;
1203 case 'N':
1204 case 'n':
1205 if (view->search_started && view->search_next) {
1206 view->searching = (ch == 'n' ?
1207 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1208 view->search_next_done = 0;
1209 view->search_next(view);
1210 } else
1211 err = view->input(new, view, ch);
1212 break;
1213 default:
1214 err = view->input(new, view, ch);
1215 break;
1218 return err;
1221 static int
1222 view_needs_focus_indication(struct tog_view *view)
1224 if (view_is_parent_view(view)) {
1225 if (view->child == NULL || view->child->focussed)
1226 return 0;
1227 if (!view_is_splitscreen(view->child))
1228 return 0;
1229 } else if (!view_is_splitscreen(view))
1230 return 0;
1232 return view->focussed;
1235 static const struct got_error *
1236 view_loop(struct tog_view *view)
1238 const struct got_error *err = NULL;
1239 struct tog_view_list_head views;
1240 struct tog_view *new_view;
1241 int fast_refresh = 10;
1242 int done = 0, errcode;
1244 errcode = pthread_mutex_lock(&tog_mutex);
1245 if (errcode)
1246 return got_error_set_errno(errcode, "pthread_mutex_lock");
1248 TAILQ_INIT(&views);
1249 TAILQ_INSERT_HEAD(&views, view, entry);
1251 view->focussed = 1;
1252 err = view->show(view);
1253 if (err)
1254 return err;
1255 update_panels();
1256 doupdate();
1257 while (!TAILQ_EMPTY(&views) && !done && !tog_fatal_signal_received()) {
1258 /* Refresh fast during initialization, then become slower. */
1259 if (fast_refresh && fast_refresh-- == 0)
1260 halfdelay(10); /* switch to once per second */
1262 err = view_input(&new_view, &done, view, &views);
1263 if (err)
1264 break;
1265 if (view->dying) {
1266 struct tog_view *v, *prev = NULL;
1268 if (view_is_parent_view(view))
1269 prev = TAILQ_PREV(view, tog_view_list_head,
1270 entry);
1271 else if (view->parent)
1272 prev = view->parent;
1274 if (view->parent) {
1275 view->parent->child = NULL;
1276 view->parent->focus_child = 0;
1277 /* Restore fullscreen line height. */
1278 view->parent->nlines = view->parent->lines;
1279 err = view_resize(view->parent);
1280 if (err)
1281 break;
1282 } else
1283 TAILQ_REMOVE(&views, view, entry);
1285 err = view_close(view);
1286 if (err)
1287 goto done;
1289 view = NULL;
1290 TAILQ_FOREACH(v, &views, entry) {
1291 if (v->focussed)
1292 break;
1294 if (view == NULL && new_view == NULL) {
1295 /* No view has focus. Try to pick one. */
1296 if (prev)
1297 view = prev;
1298 else if (!TAILQ_EMPTY(&views)) {
1299 view = TAILQ_LAST(&views,
1300 tog_view_list_head);
1302 if (view) {
1303 if (view->focus_child) {
1304 view->child->focussed = 1;
1305 view = view->child;
1306 } else
1307 view->focussed = 1;
1311 if (new_view) {
1312 struct tog_view *v, *t;
1313 /* Only allow one parent view per type. */
1314 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1315 if (v->type != new_view->type)
1316 continue;
1317 TAILQ_REMOVE(&views, v, entry);
1318 err = view_close(v);
1319 if (err)
1320 goto done;
1321 break;
1323 TAILQ_INSERT_TAIL(&views, new_view, entry);
1324 view = new_view;
1326 if (view) {
1327 if (view_is_parent_view(view)) {
1328 if (view->child && view->child->focussed)
1329 view = view->child;
1330 } else {
1331 if (view->parent && view->parent->focussed)
1332 view = view->parent;
1334 show_panel(view->panel);
1335 if (view->child && view_is_splitscreen(view->child))
1336 show_panel(view->child->panel);
1337 if (view->parent && view_is_splitscreen(view)) {
1338 err = view->parent->show(view->parent);
1339 if (err)
1340 goto done;
1342 err = view->show(view);
1343 if (err)
1344 goto done;
1345 if (view->child) {
1346 err = view->child->show(view->child);
1347 if (err)
1348 goto done;
1350 update_panels();
1351 doupdate();
1354 done:
1355 while (!TAILQ_EMPTY(&views)) {
1356 view = TAILQ_FIRST(&views);
1357 TAILQ_REMOVE(&views, view, entry);
1358 view_close(view);
1361 errcode = pthread_mutex_unlock(&tog_mutex);
1362 if (errcode && err == NULL)
1363 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1365 return err;
1368 __dead static void
1369 usage_log(void)
1371 endwin();
1372 fprintf(stderr,
1373 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1374 getprogname());
1375 exit(1);
1378 /* Create newly allocated wide-character string equivalent to a byte string. */
1379 static const struct got_error *
1380 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1382 char *vis = NULL;
1383 const struct got_error *err = NULL;
1385 *ws = NULL;
1386 *wlen = mbstowcs(NULL, s, 0);
1387 if (*wlen == (size_t)-1) {
1388 int vislen;
1389 if (errno != EILSEQ)
1390 return got_error_from_errno("mbstowcs");
1392 /* byte string invalid in current encoding; try to "fix" it */
1393 err = got_mbsavis(&vis, &vislen, s);
1394 if (err)
1395 return err;
1396 *wlen = mbstowcs(NULL, vis, 0);
1397 if (*wlen == (size_t)-1) {
1398 err = got_error_from_errno("mbstowcs"); /* give up */
1399 goto done;
1403 *ws = calloc(*wlen + 1, sizeof(**ws));
1404 if (*ws == NULL) {
1405 err = got_error_from_errno("calloc");
1406 goto done;
1409 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1410 err = got_error_from_errno("mbstowcs");
1411 done:
1412 free(vis);
1413 if (err) {
1414 free(*ws);
1415 *ws = NULL;
1416 *wlen = 0;
1418 return err;
1421 static const struct got_error *
1422 expand_tab(char **ptr, const char *src)
1424 char *dst;
1425 size_t len, n, idx = 0, sz = 0;
1427 *ptr = NULL;
1428 n = len = strlen(src);
1429 dst = malloc(n + 1);
1430 if (dst == NULL)
1431 return got_error_from_errno("malloc");
1433 while (idx < len && src[idx]) {
1434 const char c = src[idx];
1436 if (c == '\t') {
1437 size_t nb = TABSIZE - sz % TABSIZE;
1438 char *p;
1440 p = realloc(dst, n + nb);
1441 if (p == NULL) {
1442 free(dst);
1443 return got_error_from_errno("realloc");
1446 dst = p;
1447 n += nb;
1448 memset(dst + sz, ' ', nb);
1449 sz += nb;
1450 } else
1451 dst[sz++] = src[idx];
1452 ++idx;
1455 dst[sz] = '\0';
1456 *ptr = dst;
1457 return NULL;
1461 * Advance at most n columns from wline starting at offset off.
1462 * Return the index to the first character after the span operation.
1463 * Return the combined column width of all spanned wide character in
1464 * *rcol.
1466 static int
1467 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1469 int width, i, cols = 0;
1471 if (n == 0) {
1472 *rcol = cols;
1473 return off;
1476 for (i = off; wline[i] != L'\0'; ++i) {
1477 if (wline[i] == L'\t')
1478 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1479 else
1480 width = wcwidth(wline[i]);
1482 if (width == -1) {
1483 width = 1;
1484 wline[i] = L'.';
1487 if (cols + width > n)
1488 break;
1489 cols += width;
1492 *rcol = cols;
1493 return i;
1497 * Format a line for display, ensuring that it won't overflow a width limit.
1498 * With scrolling, the width returned refers to the scrolled version of the
1499 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1501 static const struct got_error *
1502 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1503 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1505 const struct got_error *err = NULL;
1506 int cols;
1507 wchar_t *wline = NULL;
1508 char *exstr = NULL;
1509 size_t wlen;
1510 int i, scrollx;
1512 *wlinep = NULL;
1513 *widthp = 0;
1515 if (expand) {
1516 err = expand_tab(&exstr, line);
1517 if (err)
1518 return err;
1521 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1522 free(exstr);
1523 if (err)
1524 return err;
1526 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1528 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1529 wline[wlen - 1] = L'\0';
1530 wlen--;
1532 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1533 wline[wlen - 1] = L'\0';
1534 wlen--;
1537 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1538 wline[i] = L'\0';
1540 if (widthp)
1541 *widthp = cols;
1542 if (scrollxp)
1543 *scrollxp = scrollx;
1544 if (err)
1545 free(wline);
1546 else
1547 *wlinep = wline;
1548 return err;
1551 static const struct got_error*
1552 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1553 struct got_object_id *id, struct got_repository *repo)
1555 static const struct got_error *err = NULL;
1556 struct got_reflist_entry *re;
1557 char *s;
1558 const char *name;
1560 *refs_str = NULL;
1562 TAILQ_FOREACH(re, refs, entry) {
1563 struct got_tag_object *tag = NULL;
1564 struct got_object_id *ref_id;
1565 int cmp;
1567 name = got_ref_get_name(re->ref);
1568 if (strcmp(name, GOT_REF_HEAD) == 0)
1569 continue;
1570 if (strncmp(name, "refs/", 5) == 0)
1571 name += 5;
1572 if (strncmp(name, "got/", 4) == 0 &&
1573 strncmp(name, "got/backup/", 11) != 0)
1574 continue;
1575 if (strncmp(name, "heads/", 6) == 0)
1576 name += 6;
1577 if (strncmp(name, "remotes/", 8) == 0) {
1578 name += 8;
1579 s = strstr(name, "/" GOT_REF_HEAD);
1580 if (s != NULL && s[strlen(s)] == '\0')
1581 continue;
1583 err = got_ref_resolve(&ref_id, repo, re->ref);
1584 if (err)
1585 break;
1586 if (strncmp(name, "tags/", 5) == 0) {
1587 err = got_object_open_as_tag(&tag, repo, ref_id);
1588 if (err) {
1589 if (err->code != GOT_ERR_OBJ_TYPE) {
1590 free(ref_id);
1591 break;
1593 /* Ref points at something other than a tag. */
1594 err = NULL;
1595 tag = NULL;
1598 cmp = got_object_id_cmp(tag ?
1599 got_object_tag_get_object_id(tag) : ref_id, id);
1600 free(ref_id);
1601 if (tag)
1602 got_object_tag_close(tag);
1603 if (cmp != 0)
1604 continue;
1605 s = *refs_str;
1606 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1607 s ? ", " : "", name) == -1) {
1608 err = got_error_from_errno("asprintf");
1609 free(s);
1610 *refs_str = NULL;
1611 break;
1613 free(s);
1616 return err;
1619 static const struct got_error *
1620 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1621 int col_tab_align)
1623 char *smallerthan;
1625 smallerthan = strchr(author, '<');
1626 if (smallerthan && smallerthan[1] != '\0')
1627 author = smallerthan + 1;
1628 author[strcspn(author, "@>")] = '\0';
1629 return format_line(wauthor, author_width, NULL, author, 0, limit,
1630 col_tab_align, 0);
1633 static const struct got_error *
1634 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1635 struct got_object_id *id, const size_t date_display_cols,
1636 int author_display_cols)
1638 struct tog_log_view_state *s = &view->state.log;
1639 const struct got_error *err = NULL;
1640 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1641 char *logmsg0 = NULL, *logmsg = NULL;
1642 char *author = NULL;
1643 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1644 int author_width, logmsg_width;
1645 char *newline, *line = NULL;
1646 int col, limit, scrollx;
1647 const int avail = view->ncols;
1648 struct tm tm;
1649 time_t committer_time;
1650 struct tog_color *tc;
1652 committer_time = got_object_commit_get_committer_time(commit);
1653 if (gmtime_r(&committer_time, &tm) == NULL)
1654 return got_error_from_errno("gmtime_r");
1655 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1656 return got_error(GOT_ERR_NO_SPACE);
1658 if (avail <= date_display_cols)
1659 limit = MIN(sizeof(datebuf) - 1, avail);
1660 else
1661 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1662 tc = get_color(&s->colors, TOG_COLOR_DATE);
1663 if (tc)
1664 wattr_on(view->window,
1665 COLOR_PAIR(tc->colorpair), NULL);
1666 waddnstr(view->window, datebuf, limit);
1667 if (tc)
1668 wattr_off(view->window,
1669 COLOR_PAIR(tc->colorpair), NULL);
1670 col = limit;
1671 if (col > avail)
1672 goto done;
1674 if (avail >= 120) {
1675 char *id_str;
1676 err = got_object_id_str(&id_str, id);
1677 if (err)
1678 goto done;
1679 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1680 if (tc)
1681 wattr_on(view->window,
1682 COLOR_PAIR(tc->colorpair), NULL);
1683 wprintw(view->window, "%.8s ", id_str);
1684 if (tc)
1685 wattr_off(view->window,
1686 COLOR_PAIR(tc->colorpair), NULL);
1687 free(id_str);
1688 col += 9;
1689 if (col > avail)
1690 goto done;
1693 author = strdup(got_object_commit_get_author(commit));
1694 if (author == NULL) {
1695 err = got_error_from_errno("strdup");
1696 goto done;
1698 err = format_author(&wauthor, &author_width, author, avail - col, col);
1699 if (err)
1700 goto done;
1701 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1702 if (tc)
1703 wattr_on(view->window,
1704 COLOR_PAIR(tc->colorpair), NULL);
1705 waddwstr(view->window, wauthor);
1706 if (tc)
1707 wattr_off(view->window,
1708 COLOR_PAIR(tc->colorpair), NULL);
1709 col += author_width;
1710 while (col < avail && author_width < author_display_cols + 2) {
1711 waddch(view->window, ' ');
1712 col++;
1713 author_width++;
1715 if (col > avail)
1716 goto done;
1718 err = got_object_commit_get_logmsg(&logmsg0, commit);
1719 if (err)
1720 goto done;
1721 logmsg = logmsg0;
1722 while (*logmsg == '\n')
1723 logmsg++;
1724 newline = strchr(logmsg, '\n');
1725 if (newline)
1726 *newline = '\0';
1727 limit = avail - col;
1728 if (view->child && view_is_splitscreen(view->child) && limit > 0)
1729 limit--; /* for the border */
1730 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
1731 limit, col, 1);
1732 if (err)
1733 goto done;
1734 waddwstr(view->window, &wlogmsg[scrollx]);
1735 col += MAX(logmsg_width, 0);
1736 while (col < avail) {
1737 waddch(view->window, ' ');
1738 col++;
1740 done:
1741 free(logmsg0);
1742 free(wlogmsg);
1743 free(author);
1744 free(wauthor);
1745 free(line);
1746 return err;
1749 static struct commit_queue_entry *
1750 alloc_commit_queue_entry(struct got_commit_object *commit,
1751 struct got_object_id *id)
1753 struct commit_queue_entry *entry;
1755 entry = calloc(1, sizeof(*entry));
1756 if (entry == NULL)
1757 return NULL;
1759 entry->id = id;
1760 entry->commit = commit;
1761 return entry;
1764 static void
1765 pop_commit(struct commit_queue *commits)
1767 struct commit_queue_entry *entry;
1769 entry = TAILQ_FIRST(&commits->head);
1770 TAILQ_REMOVE(&commits->head, entry, entry);
1771 got_object_commit_close(entry->commit);
1772 commits->ncommits--;
1773 /* Don't free entry->id! It is owned by the commit graph. */
1774 free(entry);
1777 static void
1778 free_commits(struct commit_queue *commits)
1780 while (!TAILQ_EMPTY(&commits->head))
1781 pop_commit(commits);
1784 static const struct got_error *
1785 match_commit(int *have_match, struct got_object_id *id,
1786 struct got_commit_object *commit, regex_t *regex)
1788 const struct got_error *err = NULL;
1789 regmatch_t regmatch;
1790 char *id_str = NULL, *logmsg = NULL;
1792 *have_match = 0;
1794 err = got_object_id_str(&id_str, id);
1795 if (err)
1796 return err;
1798 err = got_object_commit_get_logmsg(&logmsg, commit);
1799 if (err)
1800 goto done;
1802 if (regexec(regex, got_object_commit_get_author(commit), 1,
1803 &regmatch, 0) == 0 ||
1804 regexec(regex, got_object_commit_get_committer(commit), 1,
1805 &regmatch, 0) == 0 ||
1806 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
1807 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
1808 *have_match = 1;
1809 done:
1810 free(id_str);
1811 free(logmsg);
1812 return err;
1815 static const struct got_error *
1816 queue_commits(struct tog_log_thread_args *a)
1818 const struct got_error *err = NULL;
1821 * We keep all commits open throughout the lifetime of the log
1822 * view in order to avoid having to re-fetch commits from disk
1823 * while updating the display.
1825 do {
1826 struct got_object_id *id;
1827 struct got_commit_object *commit;
1828 struct commit_queue_entry *entry;
1829 int errcode;
1831 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
1832 NULL, NULL);
1833 if (err || id == NULL)
1834 break;
1836 err = got_object_open_as_commit(&commit, a->repo, id);
1837 if (err)
1838 break;
1839 entry = alloc_commit_queue_entry(commit, id);
1840 if (entry == NULL) {
1841 err = got_error_from_errno("alloc_commit_queue_entry");
1842 break;
1845 errcode = pthread_mutex_lock(&tog_mutex);
1846 if (errcode) {
1847 err = got_error_set_errno(errcode,
1848 "pthread_mutex_lock");
1849 break;
1852 entry->idx = a->commits->ncommits;
1853 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
1854 a->commits->ncommits++;
1856 if (*a->searching == TOG_SEARCH_FORWARD &&
1857 !*a->search_next_done) {
1858 int have_match;
1859 err = match_commit(&have_match, id, commit, a->regex);
1860 if (err)
1861 break;
1862 if (have_match)
1863 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
1866 errcode = pthread_mutex_unlock(&tog_mutex);
1867 if (errcode && err == NULL)
1868 err = got_error_set_errno(errcode,
1869 "pthread_mutex_unlock");
1870 if (err)
1871 break;
1872 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
1874 return err;
1877 static void
1878 select_commit(struct tog_log_view_state *s)
1880 struct commit_queue_entry *entry;
1881 int ncommits = 0;
1883 entry = s->first_displayed_entry;
1884 while (entry) {
1885 if (ncommits == s->selected) {
1886 s->selected_entry = entry;
1887 break;
1889 entry = TAILQ_NEXT(entry, entry);
1890 ncommits++;
1894 static const struct got_error *
1895 draw_commits(struct tog_view *view)
1897 const struct got_error *err = NULL;
1898 struct tog_log_view_state *s = &view->state.log;
1899 struct commit_queue_entry *entry = s->selected_entry;
1900 const int limit = view->nlines;
1901 int width;
1902 int ncommits, author_cols = 4;
1903 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
1904 char *refs_str = NULL;
1905 wchar_t *wline;
1906 struct tog_color *tc;
1907 static const size_t date_display_cols = 12;
1909 if (s->selected_entry &&
1910 !(view->searching && view->search_next_done == 0)) {
1911 struct got_reflist_head *refs;
1912 err = got_object_id_str(&id_str, s->selected_entry->id);
1913 if (err)
1914 return err;
1915 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
1916 s->selected_entry->id);
1917 if (refs) {
1918 err = build_refs_str(&refs_str, refs,
1919 s->selected_entry->id, s->repo);
1920 if (err)
1921 goto done;
1925 if (s->thread_args.commits_needed == 0)
1926 halfdelay(10); /* disable fast refresh */
1928 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
1929 if (asprintf(&ncommits_str, " [%d/%d] %s",
1930 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1931 (view->searching && !view->search_next_done) ?
1932 "searching..." : "loading...") == -1) {
1933 err = got_error_from_errno("asprintf");
1934 goto done;
1936 } else {
1937 const char *search_str = NULL;
1939 if (view->searching) {
1940 if (view->search_next_done == TOG_SEARCH_NO_MORE)
1941 search_str = "no more matches";
1942 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
1943 search_str = "no matches found";
1944 else if (!view->search_next_done)
1945 search_str = "searching...";
1948 if (asprintf(&ncommits_str, " [%d/%d] %s",
1949 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1950 search_str ? search_str :
1951 (refs_str ? refs_str : "")) == -1) {
1952 err = got_error_from_errno("asprintf");
1953 goto done;
1957 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
1958 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
1959 "........................................",
1960 s->in_repo_path, ncommits_str) == -1) {
1961 err = got_error_from_errno("asprintf");
1962 header = NULL;
1963 goto done;
1965 } else if (asprintf(&header, "commit %s%s",
1966 id_str ? id_str : "........................................",
1967 ncommits_str) == -1) {
1968 err = got_error_from_errno("asprintf");
1969 header = NULL;
1970 goto done;
1972 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
1973 if (err)
1974 goto done;
1976 werase(view->window);
1978 if (view_needs_focus_indication(view))
1979 wstandout(view->window);
1980 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1981 if (tc)
1982 wattr_on(view->window,
1983 COLOR_PAIR(tc->colorpair), NULL);
1984 waddwstr(view->window, wline);
1985 if (tc)
1986 wattr_off(view->window,
1987 COLOR_PAIR(tc->colorpair), NULL);
1988 while (width < view->ncols) {
1989 waddch(view->window, ' ');
1990 width++;
1992 if (view_needs_focus_indication(view))
1993 wstandend(view->window);
1994 free(wline);
1995 if (limit <= 1)
1996 goto done;
1998 /* Grow author column size if necessary, and set view->maxx. */
1999 entry = s->first_displayed_entry;
2000 ncommits = 0;
2001 view->maxx = 0;
2002 while (entry) {
2003 char *author, *eol, *msg, *msg0;
2004 wchar_t *wauthor, *wmsg;
2005 int width;
2006 if (ncommits >= limit - 1)
2007 break;
2008 author = strdup(got_object_commit_get_author(entry->commit));
2009 if (author == NULL) {
2010 err = got_error_from_errno("strdup");
2011 goto done;
2013 err = format_author(&wauthor, &width, author, COLS,
2014 date_display_cols);
2015 if (author_cols < width)
2016 author_cols = width;
2017 free(wauthor);
2018 free(author);
2019 err = got_object_commit_get_logmsg(&msg0, entry->commit);
2020 if (err)
2021 goto done;
2022 msg = msg0;
2023 while (*msg == '\n')
2024 ++msg;
2025 if ((eol = strchr(msg, '\n')))
2026 *eol = '\0';
2027 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2028 date_display_cols + author_cols, 0);
2029 if (err)
2030 goto done;
2031 view->maxx = MAX(view->maxx, width);
2032 free(msg0);
2033 free(wmsg);
2034 ncommits++;
2035 entry = TAILQ_NEXT(entry, entry);
2038 entry = s->first_displayed_entry;
2039 s->last_displayed_entry = s->first_displayed_entry;
2040 ncommits = 0;
2041 while (entry) {
2042 if (ncommits >= limit - 1)
2043 break;
2044 if (ncommits == s->selected)
2045 wstandout(view->window);
2046 err = draw_commit(view, entry->commit, entry->id,
2047 date_display_cols, author_cols);
2048 if (ncommits == s->selected)
2049 wstandend(view->window);
2050 if (err)
2051 goto done;
2052 ncommits++;
2053 s->last_displayed_entry = entry;
2054 entry = TAILQ_NEXT(entry, entry);
2057 view_border(view);
2058 done:
2059 free(id_str);
2060 free(refs_str);
2061 free(ncommits_str);
2062 free(header);
2063 return err;
2066 static void
2067 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2069 struct commit_queue_entry *entry;
2070 int nscrolled = 0;
2072 entry = TAILQ_FIRST(&s->commits.head);
2073 if (s->first_displayed_entry == entry)
2074 return;
2076 entry = s->first_displayed_entry;
2077 while (entry && nscrolled < maxscroll) {
2078 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2079 if (entry) {
2080 s->first_displayed_entry = entry;
2081 nscrolled++;
2086 static const struct got_error *
2087 trigger_log_thread(struct tog_view *view, int wait)
2089 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2090 int errcode;
2092 halfdelay(1); /* fast refresh while loading commits */
2094 while (ta->commits_needed > 0 || ta->load_all) {
2095 if (ta->log_complete)
2096 break;
2098 /* Wake the log thread. */
2099 errcode = pthread_cond_signal(&ta->need_commits);
2100 if (errcode)
2101 return got_error_set_errno(errcode,
2102 "pthread_cond_signal");
2105 * The mutex will be released while the view loop waits
2106 * in wgetch(), at which time the log thread will run.
2108 if (!wait)
2109 break;
2111 /* Display progress update in log view. */
2112 show_log_view(view);
2113 update_panels();
2114 doupdate();
2116 /* Wait right here while next commit is being loaded. */
2117 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2118 if (errcode)
2119 return got_error_set_errno(errcode,
2120 "pthread_cond_wait");
2122 /* Display progress update in log view. */
2123 show_log_view(view);
2124 update_panels();
2125 doupdate();
2128 return NULL;
2131 static const struct got_error *
2132 request_log_commits(struct tog_view *view)
2134 struct tog_log_view_state *state = &view->state.log;
2135 const struct got_error *err = NULL;
2137 state->thread_args.commits_needed = view->nscrolled;
2138 err = trigger_log_thread(view, 1);
2139 view->nscrolled = 0;
2141 return err;
2144 static const struct got_error *
2145 log_scroll_down(struct tog_view *view, int maxscroll)
2147 struct tog_log_view_state *s = &view->state.log;
2148 const struct got_error *err = NULL;
2149 struct commit_queue_entry *pentry;
2150 int nscrolled = 0, ncommits_needed;
2152 if (s->last_displayed_entry == NULL)
2153 return NULL;
2155 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2156 if (s->commits.ncommits < ncommits_needed &&
2157 !s->thread_args.log_complete) {
2159 * Ask the log thread for required amount of commits.
2161 s->thread_args.commits_needed += maxscroll;
2162 err = trigger_log_thread(view, 1);
2163 if (err)
2164 return err;
2167 do {
2168 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2169 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2170 break;
2172 s->last_displayed_entry = pentry ?
2173 pentry : s->last_displayed_entry;;
2175 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2176 if (pentry == NULL)
2177 break;
2178 s->first_displayed_entry = pentry;
2179 } while (++nscrolled < maxscroll);
2181 if (view->mode == TOG_VIEW_SPLIT_HRZN)
2182 view->nscrolled += nscrolled;
2183 else
2184 view->nscrolled = 0;
2186 return err;
2189 static const struct got_error *
2190 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2191 struct got_commit_object *commit, struct got_object_id *commit_id,
2192 struct tog_view *log_view, struct got_repository *repo)
2194 const struct got_error *err;
2195 struct got_object_qid *parent_id;
2196 struct tog_view *diff_view;
2198 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2199 if (diff_view == NULL)
2200 return got_error_from_errno("view_open");
2202 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2203 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2204 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2205 if (err == NULL)
2206 *new_view = diff_view;
2207 return err;
2210 static const struct got_error *
2211 tree_view_visit_subtree(struct tog_tree_view_state *s,
2212 struct got_tree_object *subtree)
2214 struct tog_parent_tree *parent;
2216 parent = calloc(1, sizeof(*parent));
2217 if (parent == NULL)
2218 return got_error_from_errno("calloc");
2220 parent->tree = s->tree;
2221 parent->first_displayed_entry = s->first_displayed_entry;
2222 parent->selected_entry = s->selected_entry;
2223 parent->selected = s->selected;
2224 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2225 s->tree = subtree;
2226 s->selected = 0;
2227 s->first_displayed_entry = NULL;
2228 return NULL;
2231 static const struct got_error *
2232 tree_view_walk_path(struct tog_tree_view_state *s,
2233 struct got_commit_object *commit, const char *path)
2235 const struct got_error *err = NULL;
2236 struct got_tree_object *tree = NULL;
2237 const char *p;
2238 char *slash, *subpath = NULL;
2240 /* Walk the path and open corresponding tree objects. */
2241 p = path;
2242 while (*p) {
2243 struct got_tree_entry *te;
2244 struct got_object_id *tree_id;
2245 char *te_name;
2247 while (p[0] == '/')
2248 p++;
2250 /* Ensure the correct subtree entry is selected. */
2251 slash = strchr(p, '/');
2252 if (slash == NULL)
2253 te_name = strdup(p);
2254 else
2255 te_name = strndup(p, slash - p);
2256 if (te_name == NULL) {
2257 err = got_error_from_errno("strndup");
2258 break;
2260 te = got_object_tree_find_entry(s->tree, te_name);
2261 if (te == NULL) {
2262 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2263 free(te_name);
2264 break;
2266 free(te_name);
2267 s->first_displayed_entry = s->selected_entry = te;
2269 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2270 break; /* jump to this file's entry */
2272 slash = strchr(p, '/');
2273 if (slash)
2274 subpath = strndup(path, slash - path);
2275 else
2276 subpath = strdup(path);
2277 if (subpath == NULL) {
2278 err = got_error_from_errno("strdup");
2279 break;
2282 err = got_object_id_by_path(&tree_id, s->repo, commit,
2283 subpath);
2284 if (err)
2285 break;
2287 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2288 free(tree_id);
2289 if (err)
2290 break;
2292 err = tree_view_visit_subtree(s, tree);
2293 if (err) {
2294 got_object_tree_close(tree);
2295 break;
2297 if (slash == NULL)
2298 break;
2299 free(subpath);
2300 subpath = NULL;
2301 p = slash;
2304 free(subpath);
2305 return err;
2308 static const struct got_error *
2309 browse_commit_tree(struct tog_view **new_view, int begin_x,
2310 struct commit_queue_entry *entry, const char *path,
2311 const char *head_ref_name, struct got_repository *repo)
2313 const struct got_error *err = NULL;
2314 struct tog_tree_view_state *s;
2315 struct tog_view *tree_view;
2317 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
2318 if (tree_view == NULL)
2319 return got_error_from_errno("view_open");
2321 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2322 if (err)
2323 return err;
2324 s = &tree_view->state.tree;
2326 *new_view = tree_view;
2328 if (got_path_is_root_dir(path))
2329 return NULL;
2331 return tree_view_walk_path(s, entry->commit, path);
2334 static const struct got_error *
2335 block_signals_used_by_main_thread(void)
2337 sigset_t sigset;
2338 int errcode;
2340 if (sigemptyset(&sigset) == -1)
2341 return got_error_from_errno("sigemptyset");
2343 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2344 if (sigaddset(&sigset, SIGWINCH) == -1)
2345 return got_error_from_errno("sigaddset");
2346 if (sigaddset(&sigset, SIGCONT) == -1)
2347 return got_error_from_errno("sigaddset");
2348 if (sigaddset(&sigset, SIGINT) == -1)
2349 return got_error_from_errno("sigaddset");
2350 if (sigaddset(&sigset, SIGTERM) == -1)
2351 return got_error_from_errno("sigaddset");
2353 /* ncurses handles SIGTSTP */
2354 if (sigaddset(&sigset, SIGTSTP) == -1)
2355 return got_error_from_errno("sigaddset");
2357 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2358 if (errcode)
2359 return got_error_set_errno(errcode, "pthread_sigmask");
2361 return NULL;
2364 static void *
2365 log_thread(void *arg)
2367 const struct got_error *err = NULL;
2368 int errcode = 0;
2369 struct tog_log_thread_args *a = arg;
2370 int done = 0;
2372 err = block_signals_used_by_main_thread();
2373 if (err)
2374 return (void *)err;
2376 while (!done && !err && !tog_fatal_signal_received()) {
2377 err = queue_commits(a);
2378 if (err) {
2379 if (err->code != GOT_ERR_ITER_COMPLETED)
2380 return (void *)err;
2381 err = NULL;
2382 done = 1;
2383 } else if (a->commits_needed > 0 && !a->load_all)
2384 a->commits_needed--;
2386 errcode = pthread_mutex_lock(&tog_mutex);
2387 if (errcode) {
2388 err = got_error_set_errno(errcode,
2389 "pthread_mutex_lock");
2390 break;
2391 } else if (*a->quit)
2392 done = 1;
2393 else if (*a->first_displayed_entry == NULL) {
2394 *a->first_displayed_entry =
2395 TAILQ_FIRST(&a->commits->head);
2396 *a->selected_entry = *a->first_displayed_entry;
2399 errcode = pthread_cond_signal(&a->commit_loaded);
2400 if (errcode) {
2401 err = got_error_set_errno(errcode,
2402 "pthread_cond_signal");
2403 pthread_mutex_unlock(&tog_mutex);
2404 break;
2407 if (done)
2408 a->commits_needed = 0;
2409 else {
2410 if (a->commits_needed == 0 && !a->load_all) {
2411 errcode = pthread_cond_wait(&a->need_commits,
2412 &tog_mutex);
2413 if (errcode)
2414 err = got_error_set_errno(errcode,
2415 "pthread_cond_wait");
2416 if (*a->quit)
2417 done = 1;
2421 errcode = pthread_mutex_unlock(&tog_mutex);
2422 if (errcode && err == NULL)
2423 err = got_error_set_errno(errcode,
2424 "pthread_mutex_unlock");
2426 a->log_complete = 1;
2427 return (void *)err;
2430 static const struct got_error *
2431 stop_log_thread(struct tog_log_view_state *s)
2433 const struct got_error *err = NULL;
2434 int errcode;
2436 if (s->thread) {
2437 s->quit = 1;
2438 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2439 if (errcode)
2440 return got_error_set_errno(errcode,
2441 "pthread_cond_signal");
2442 errcode = pthread_mutex_unlock(&tog_mutex);
2443 if (errcode)
2444 return got_error_set_errno(errcode,
2445 "pthread_mutex_unlock");
2446 errcode = pthread_join(s->thread, (void **)&err);
2447 if (errcode)
2448 return got_error_set_errno(errcode, "pthread_join");
2449 errcode = pthread_mutex_lock(&tog_mutex);
2450 if (errcode)
2451 return got_error_set_errno(errcode,
2452 "pthread_mutex_lock");
2453 s->thread = NULL;
2456 if (s->thread_args.repo) {
2457 err = got_repo_close(s->thread_args.repo);
2458 s->thread_args.repo = NULL;
2461 if (s->thread_args.pack_fds) {
2462 const struct got_error *pack_err =
2463 got_repo_pack_fds_close(s->thread_args.pack_fds);
2464 if (err == NULL)
2465 err = pack_err;
2466 s->thread_args.pack_fds = NULL;
2469 if (s->thread_args.graph) {
2470 got_commit_graph_close(s->thread_args.graph);
2471 s->thread_args.graph = NULL;
2474 return err;
2477 static const struct got_error *
2478 close_log_view(struct tog_view *view)
2480 const struct got_error *err = NULL;
2481 struct tog_log_view_state *s = &view->state.log;
2482 int errcode;
2484 err = stop_log_thread(s);
2486 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2487 if (errcode && err == NULL)
2488 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2490 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2491 if (errcode && err == NULL)
2492 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2494 free_commits(&s->commits);
2495 free(s->in_repo_path);
2496 s->in_repo_path = NULL;
2497 free(s->start_id);
2498 s->start_id = NULL;
2499 free(s->head_ref_name);
2500 s->head_ref_name = NULL;
2501 return err;
2504 static const struct got_error *
2505 search_start_log_view(struct tog_view *view)
2507 struct tog_log_view_state *s = &view->state.log;
2509 s->matched_entry = NULL;
2510 s->search_entry = NULL;
2511 return NULL;
2514 static const struct got_error *
2515 search_next_log_view(struct tog_view *view)
2517 const struct got_error *err = NULL;
2518 struct tog_log_view_state *s = &view->state.log;
2519 struct commit_queue_entry *entry;
2521 /* Display progress update in log view. */
2522 show_log_view(view);
2523 update_panels();
2524 doupdate();
2526 if (s->search_entry) {
2527 int errcode, ch;
2528 errcode = pthread_mutex_unlock(&tog_mutex);
2529 if (errcode)
2530 return got_error_set_errno(errcode,
2531 "pthread_mutex_unlock");
2532 ch = wgetch(view->window);
2533 errcode = pthread_mutex_lock(&tog_mutex);
2534 if (errcode)
2535 return got_error_set_errno(errcode,
2536 "pthread_mutex_lock");
2537 if (ch == KEY_BACKSPACE) {
2538 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2539 return NULL;
2541 if (view->searching == TOG_SEARCH_FORWARD)
2542 entry = TAILQ_NEXT(s->search_entry, entry);
2543 else
2544 entry = TAILQ_PREV(s->search_entry,
2545 commit_queue_head, entry);
2546 } else if (s->matched_entry) {
2547 int matched_idx = s->matched_entry->idx;
2548 int selected_idx = s->selected_entry->idx;
2551 * If the user has moved the cursor after we hit a match,
2552 * the position from where we should continue searching
2553 * might have changed.
2555 if (view->searching == TOG_SEARCH_FORWARD) {
2556 if (matched_idx > selected_idx)
2557 entry = TAILQ_NEXT(s->selected_entry, entry);
2558 else
2559 entry = TAILQ_NEXT(s->matched_entry, entry);
2560 } else {
2561 if (matched_idx < selected_idx)
2562 entry = TAILQ_PREV(s->selected_entry,
2563 commit_queue_head, entry);
2564 else
2565 entry = TAILQ_PREV(s->matched_entry,
2566 commit_queue_head, entry);
2568 } else {
2569 entry = s->selected_entry;
2572 while (1) {
2573 int have_match = 0;
2575 if (entry == NULL) {
2576 if (s->thread_args.log_complete ||
2577 view->searching == TOG_SEARCH_BACKWARD) {
2578 view->search_next_done =
2579 (s->matched_entry == NULL ?
2580 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2581 s->search_entry = NULL;
2582 return NULL;
2585 * Poke the log thread for more commits and return,
2586 * allowing the main loop to make progress. Search
2587 * will resume at s->search_entry once we come back.
2589 s->thread_args.commits_needed++;
2590 return trigger_log_thread(view, 0);
2593 err = match_commit(&have_match, entry->id, entry->commit,
2594 &view->regex);
2595 if (err)
2596 break;
2597 if (have_match) {
2598 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2599 s->matched_entry = entry;
2600 break;
2603 s->search_entry = entry;
2604 if (view->searching == TOG_SEARCH_FORWARD)
2605 entry = TAILQ_NEXT(entry, entry);
2606 else
2607 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2610 if (s->matched_entry) {
2611 int cur = s->selected_entry->idx;
2612 while (cur < s->matched_entry->idx) {
2613 err = input_log_view(NULL, view, KEY_DOWN);
2614 if (err)
2615 return err;
2616 cur++;
2618 while (cur > s->matched_entry->idx) {
2619 err = input_log_view(NULL, view, KEY_UP);
2620 if (err)
2621 return err;
2622 cur--;
2626 s->search_entry = NULL;
2628 return NULL;
2631 static const struct got_error *
2632 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2633 struct got_repository *repo, const char *head_ref_name,
2634 const char *in_repo_path, int log_branches)
2636 const struct got_error *err = NULL;
2637 struct tog_log_view_state *s = &view->state.log;
2638 struct got_repository *thread_repo = NULL;
2639 struct got_commit_graph *thread_graph = NULL;
2640 int errcode;
2642 if (in_repo_path != s->in_repo_path) {
2643 free(s->in_repo_path);
2644 s->in_repo_path = strdup(in_repo_path);
2645 if (s->in_repo_path == NULL)
2646 return got_error_from_errno("strdup");
2649 /* The commit queue only contains commits being displayed. */
2650 TAILQ_INIT(&s->commits.head);
2651 s->commits.ncommits = 0;
2653 s->repo = repo;
2654 if (head_ref_name) {
2655 s->head_ref_name = strdup(head_ref_name);
2656 if (s->head_ref_name == NULL) {
2657 err = got_error_from_errno("strdup");
2658 goto done;
2661 s->start_id = got_object_id_dup(start_id);
2662 if (s->start_id == NULL) {
2663 err = got_error_from_errno("got_object_id_dup");
2664 goto done;
2666 s->log_branches = log_branches;
2668 STAILQ_INIT(&s->colors);
2669 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2670 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2671 get_color_value("TOG_COLOR_COMMIT"));
2672 if (err)
2673 goto done;
2674 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2675 get_color_value("TOG_COLOR_AUTHOR"));
2676 if (err) {
2677 free_colors(&s->colors);
2678 goto done;
2680 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
2681 get_color_value("TOG_COLOR_DATE"));
2682 if (err) {
2683 free_colors(&s->colors);
2684 goto done;
2688 view->show = show_log_view;
2689 view->input = input_log_view;
2690 view->close = close_log_view;
2691 view->search_start = search_start_log_view;
2692 view->search_next = search_next_log_view;
2694 if (s->thread_args.pack_fds == NULL) {
2695 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2696 if (err)
2697 goto done;
2699 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
2700 s->thread_args.pack_fds);
2701 if (err)
2702 goto done;
2703 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
2704 !s->log_branches);
2705 if (err)
2706 goto done;
2707 err = got_commit_graph_iter_start(thread_graph, s->start_id,
2708 s->repo, NULL, NULL);
2709 if (err)
2710 goto done;
2712 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
2713 if (errcode) {
2714 err = got_error_set_errno(errcode, "pthread_cond_init");
2715 goto done;
2717 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
2718 if (errcode) {
2719 err = got_error_set_errno(errcode, "pthread_cond_init");
2720 goto done;
2723 s->thread_args.commits_needed = view->nlines;
2724 s->thread_args.graph = thread_graph;
2725 s->thread_args.commits = &s->commits;
2726 s->thread_args.in_repo_path = s->in_repo_path;
2727 s->thread_args.start_id = s->start_id;
2728 s->thread_args.repo = thread_repo;
2729 s->thread_args.log_complete = 0;
2730 s->thread_args.quit = &s->quit;
2731 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
2732 s->thread_args.selected_entry = &s->selected_entry;
2733 s->thread_args.searching = &view->searching;
2734 s->thread_args.search_next_done = &view->search_next_done;
2735 s->thread_args.regex = &view->regex;
2736 done:
2737 if (err)
2738 close_log_view(view);
2739 return err;
2742 static const struct got_error *
2743 show_log_view(struct tog_view *view)
2745 const struct got_error *err;
2746 struct tog_log_view_state *s = &view->state.log;
2748 if (s->thread == NULL) {
2749 int errcode = pthread_create(&s->thread, NULL, log_thread,
2750 &s->thread_args);
2751 if (errcode)
2752 return got_error_set_errno(errcode, "pthread_create");
2753 if (s->thread_args.commits_needed > 0) {
2754 err = trigger_log_thread(view, 1);
2755 if (err)
2756 return err;
2760 return draw_commits(view);
2763 static void
2764 log_move_cursor_up(struct tog_view *view, int page, int home)
2766 struct tog_log_view_state *s = &view->state.log;
2768 if (s->selected_entry->idx == 0)
2769 view->count = 0;
2770 if (s->first_displayed_entry == NULL)
2771 return;
2773 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
2774 || home)
2775 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
2777 if (!page && !home && s->selected > 0)
2778 --s->selected;
2779 else
2780 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
2782 select_commit(s);
2783 return;
2786 static const struct got_error *
2787 log_move_cursor_down(struct tog_view *view, int page)
2789 struct tog_log_view_state *s = &view->state.log;
2790 struct commit_queue_entry *first;
2791 const struct got_error *err = NULL;
2793 first = s->first_displayed_entry;
2794 if (first == NULL) {
2795 view->count = 0;
2796 return NULL;
2799 if (s->thread_args.log_complete &&
2800 s->selected_entry->idx >= s->commits.ncommits - 1)
2801 return NULL;
2803 if (!page) {
2804 int eos = view->nlines - 2;
2806 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
2807 view_is_splitscreen(view->child))
2808 --eos; /* border consumes the last line */
2809 if (s->selected < MIN(eos, s->commits.ncommits - 1))
2810 ++s->selected;
2811 else
2812 err = log_scroll_down(view, 1);
2813 } else if (s->thread_args.log_complete) {
2814 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
2815 s->selected += MIN(s->last_displayed_entry->idx -
2816 s->selected_entry->idx, page + 1);
2817 else
2818 err = log_scroll_down(view, MIN(page,
2819 s->commits.ncommits - s->selected_entry->idx - 1));
2820 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
2821 } else {
2822 err = log_scroll_down(view, page);
2823 if (err)
2824 return err;
2825 if (first == s->first_displayed_entry && s->selected <
2826 MIN(view->nlines - 2, s->commits.ncommits - 1)) {
2827 s->selected = MIN(s->commits.ncommits - 1, page);
2830 if (err)
2831 return err;
2834 * We might necessarily overshoot in horizontal
2835 * splits; if so, select the last displayed commit.
2837 s->selected = MIN(s->selected,
2838 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
2840 select_commit(s);
2842 if (s->thread_args.log_complete &&
2843 s->selected_entry->idx == s->commits.ncommits - 1)
2844 view->count = 0;
2846 return NULL;
2850 * Get splitscreen dimensions based on TOG_VIEW_SPLIT_MODE:
2851 * TOG_VIEW_SPLIT_VERT vertical split if COLS > 119 (default)
2852 * TOG_VIEW_SPLIT_HRZN horizontal split
2853 * Assign start column and line of the new split to *x and *y, respectively,
2854 * and assign view mode to view->mode.
2856 static void
2857 view_get_split(struct tog_view *view, int *y, int *x)
2859 char *mode;
2861 mode = getenv("TOG_VIEW_SPLIT_MODE");
2863 if (!mode || mode[0] != 'h') {
2864 view->mode = TOG_VIEW_SPLIT_VERT;
2865 *x = view_split_begin_x(view->begin_x);
2866 } else if (mode && mode[0] == 'h') {
2867 view->mode = TOG_VIEW_SPLIT_HRZN;
2868 *y = view_split_begin_y(view->lines);
2872 /* Split view horizontally at y and offset view->state->selected line. */
2873 static const struct got_error *
2874 view_init_hsplit(struct tog_view *view, int y)
2876 const struct got_error *err = NULL;
2878 view->nlines = y;
2879 err = view_resize(view);
2880 if (err)
2881 return err;
2883 err = offset_selection_down(view);
2885 return err;
2888 static const struct got_error *
2889 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
2891 const struct got_error *err = NULL;
2892 struct tog_log_view_state *s = &view->state.log;
2893 struct tog_view *diff_view = NULL, *tree_view = NULL;
2894 struct tog_view *ref_view = NULL;
2895 struct commit_queue_entry *entry;
2896 int begin_x = 0, begin_y = 0, n, nscroll = view->nlines - 1;
2898 if (s->thread_args.load_all) {
2899 if (ch == KEY_BACKSPACE)
2900 s->thread_args.load_all = 0;
2901 else if (s->thread_args.log_complete) {
2902 s->thread_args.load_all = 0;
2903 err = log_move_cursor_down(view, s->commits.ncommits);
2905 return err;
2908 switch (ch) {
2909 case 'q':
2910 s->quit = 1;
2911 break;
2912 case '0':
2913 view->x = 0;
2914 break;
2915 case '$':
2916 view->x = MAX(view->maxx - view->ncols / 2, 0);
2917 view->count = 0;
2918 break;
2919 case KEY_RIGHT:
2920 case 'l':
2921 if (view->x + view->ncols / 2 < view->maxx)
2922 view->x += 2; /* move two columns right */
2923 else
2924 view->count = 0;
2925 break;
2926 case KEY_LEFT:
2927 case 'h':
2928 view->x -= MIN(view->x, 2); /* move two columns back */
2929 if (view->x <= 0)
2930 view->count = 0;
2931 break;
2932 case 'k':
2933 case KEY_UP:
2934 case '<':
2935 case ',':
2936 case CTRL('p'):
2937 log_move_cursor_up(view, 0, 0);
2938 break;
2939 case 'g':
2940 case KEY_HOME:
2941 log_move_cursor_up(view, 0, 1);
2942 view->count = 0;
2943 break;
2944 case CTRL('u'):
2945 case 'u':
2946 nscroll /= 2;
2947 /* FALL THROUGH */
2948 case KEY_PPAGE:
2949 case CTRL('b'):
2950 case 'b':
2951 log_move_cursor_up(view, nscroll, 0);
2952 break;
2953 case 'j':
2954 case KEY_DOWN:
2955 case '>':
2956 case '.':
2957 case CTRL('n'):
2958 err = log_move_cursor_down(view, 0);
2959 break;
2960 case 'G':
2961 case KEY_END: {
2962 /* We don't know yet how many commits, so we're forced to
2963 * traverse them all. */
2964 view->count = 0;
2965 if (!s->thread_args.log_complete) {
2966 s->thread_args.load_all = 1;
2967 return trigger_log_thread(view, 0);
2970 s->selected = 0;
2971 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
2972 for (n = 0; n < view->nlines - 1; n++) {
2973 if (entry == NULL)
2974 break;
2975 s->first_displayed_entry = entry;
2976 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2978 if (n > 0)
2979 s->selected = n - 1;
2980 select_commit(s);
2981 break;
2983 case CTRL('d'):
2984 case 'd':
2985 nscroll /= 2;
2986 /* FALL THROUGH */
2987 case KEY_NPAGE:
2988 case CTRL('f'):
2989 case 'f':
2990 case ' ':
2991 err = log_move_cursor_down(view, nscroll);
2992 break;
2993 case KEY_RESIZE:
2994 if (s->selected > view->nlines - 2)
2995 s->selected = view->nlines - 2;
2996 if (s->selected > s->commits.ncommits - 1)
2997 s->selected = s->commits.ncommits - 1;
2998 select_commit(s);
2999 if (s->commits.ncommits < view->nlines - 1 &&
3000 !s->thread_args.log_complete) {
3001 s->thread_args.commits_needed += (view->nlines - 1) -
3002 s->commits.ncommits;
3003 err = trigger_log_thread(view, 1);
3005 break;
3006 case KEY_ENTER:
3007 case '\r': {
3008 view->count = 0;
3009 if (s->selected_entry == NULL)
3010 break;
3012 /* get dimensions--don't split till initialisation succeeds */
3013 if (view_is_parent_view(view))
3014 view_get_split(view, &begin_y, &begin_x);
3016 err = open_diff_view_for_commit(&diff_view, begin_y, begin_x,
3017 s->selected_entry->commit, s->selected_entry->id,
3018 view, s->repo);
3019 if (err)
3020 break;
3022 if (view->mode == TOG_VIEW_SPLIT_HRZN) { /* safe to split */
3023 err = view_init_hsplit(view, begin_y);
3024 if (err)
3025 break;
3028 view->focussed = 0;
3029 diff_view->focussed = 1;
3030 diff_view->mode = view->mode;
3031 diff_view->nlines = view->lines - begin_y;
3033 if (view_is_parent_view(view)) {
3034 err = view_close_child(view);
3035 if (err)
3036 return err;
3037 err = view_set_child(view, diff_view);
3038 if (err)
3039 return err;
3040 view->focus_child = 1;
3041 } else
3042 *new_view = diff_view;
3043 break;
3045 case 't':
3046 view->count = 0;
3047 if (s->selected_entry == NULL)
3048 break;
3049 if (view_is_parent_view(view))
3050 begin_x = view_split_begin_x(view->begin_x);
3051 err = browse_commit_tree(&tree_view, begin_x,
3052 s->selected_entry, s->in_repo_path, s->head_ref_name,
3053 s->repo);
3054 if (err)
3055 break;
3056 view->focussed = 0;
3057 tree_view->focussed = 1;
3058 if (view_is_parent_view(view)) {
3059 err = view_close_child(view);
3060 if (err)
3061 return err;
3062 err = view_set_child(view, tree_view);
3063 if (err)
3064 return err;
3065 view->focus_child = 1;
3066 } else
3067 *new_view = tree_view;
3068 break;
3069 case KEY_BACKSPACE:
3070 case CTRL('l'):
3071 case 'B':
3072 view->count = 0;
3073 if (ch == KEY_BACKSPACE &&
3074 got_path_is_root_dir(s->in_repo_path))
3075 break;
3076 err = stop_log_thread(s);
3077 if (err)
3078 return err;
3079 if (ch == KEY_BACKSPACE) {
3080 char *parent_path;
3081 err = got_path_dirname(&parent_path, s->in_repo_path);
3082 if (err)
3083 return err;
3084 free(s->in_repo_path);
3085 s->in_repo_path = parent_path;
3086 s->thread_args.in_repo_path = s->in_repo_path;
3087 } else if (ch == CTRL('l')) {
3088 struct got_object_id *start_id;
3089 err = got_repo_match_object_id(&start_id, NULL,
3090 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3091 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3092 if (err)
3093 return err;
3094 free(s->start_id);
3095 s->start_id = start_id;
3096 s->thread_args.start_id = s->start_id;
3097 } else /* 'B' */
3098 s->log_branches = !s->log_branches;
3100 if (s->thread_args.pack_fds == NULL) {
3101 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3102 if (err)
3103 return err;
3105 err = got_repo_open(&s->thread_args.repo,
3106 got_repo_get_path(s->repo), NULL,
3107 s->thread_args.pack_fds);
3108 if (err)
3109 return err;
3110 tog_free_refs();
3111 err = tog_load_refs(s->repo, 0);
3112 if (err)
3113 return err;
3114 err = got_commit_graph_open(&s->thread_args.graph,
3115 s->in_repo_path, !s->log_branches);
3116 if (err)
3117 return err;
3118 err = got_commit_graph_iter_start(s->thread_args.graph,
3119 s->start_id, s->repo, NULL, NULL);
3120 if (err)
3121 return err;
3122 free_commits(&s->commits);
3123 s->first_displayed_entry = NULL;
3124 s->last_displayed_entry = NULL;
3125 s->selected_entry = NULL;
3126 s->selected = 0;
3127 s->thread_args.log_complete = 0;
3128 s->quit = 0;
3129 s->thread_args.commits_needed = view->lines;
3130 s->matched_entry = NULL;
3131 s->search_entry = NULL;
3132 break;
3133 case 'r':
3134 view->count = 0;
3135 if (view_is_parent_view(view))
3136 begin_x = view_split_begin_x(view->begin_x);
3137 ref_view = view_open(view->nlines, view->ncols,
3138 view->begin_y, begin_x, TOG_VIEW_REF);
3139 if (ref_view == NULL)
3140 return got_error_from_errno("view_open");
3141 err = open_ref_view(ref_view, s->repo);
3142 if (err) {
3143 view_close(ref_view);
3144 return err;
3146 view->focussed = 0;
3147 ref_view->focussed = 1;
3148 if (view_is_parent_view(view)) {
3149 err = view_close_child(view);
3150 if (err)
3151 return err;
3152 err = view_set_child(view, ref_view);
3153 if (err)
3154 return err;
3155 view->focus_child = 1;
3156 } else
3157 *new_view = ref_view;
3158 break;
3159 default:
3160 view->count = 0;
3161 break;
3164 return err;
3167 static const struct got_error *
3168 apply_unveil(const char *repo_path, const char *worktree_path)
3170 const struct got_error *error;
3172 #ifdef PROFILE
3173 if (unveil("gmon.out", "rwc") != 0)
3174 return got_error_from_errno2("unveil", "gmon.out");
3175 #endif
3176 if (repo_path && unveil(repo_path, "r") != 0)
3177 return got_error_from_errno2("unveil", repo_path);
3179 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3180 return got_error_from_errno2("unveil", worktree_path);
3182 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3183 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3185 error = got_privsep_unveil_exec_helpers();
3186 if (error != NULL)
3187 return error;
3189 if (unveil(NULL, NULL) != 0)
3190 return got_error_from_errno("unveil");
3192 return NULL;
3195 static void
3196 init_curses(void)
3199 * Override default signal handlers before starting ncurses.
3200 * This should prevent ncurses from installing its own
3201 * broken cleanup() signal handler.
3203 signal(SIGWINCH, tog_sigwinch);
3204 signal(SIGPIPE, tog_sigpipe);
3205 signal(SIGCONT, tog_sigcont);
3206 signal(SIGINT, tog_sigint);
3207 signal(SIGTERM, tog_sigterm);
3209 initscr();
3210 cbreak();
3211 halfdelay(1); /* Do fast refresh while initial view is loading. */
3212 noecho();
3213 nonl();
3214 intrflush(stdscr, FALSE);
3215 keypad(stdscr, TRUE);
3216 curs_set(0);
3217 if (getenv("TOG_COLORS") != NULL) {
3218 start_color();
3219 use_default_colors();
3223 static const struct got_error *
3224 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3225 struct got_repository *repo, struct got_worktree *worktree)
3227 const struct got_error *err = NULL;
3229 if (argc == 0) {
3230 *in_repo_path = strdup("/");
3231 if (*in_repo_path == NULL)
3232 return got_error_from_errno("strdup");
3233 return NULL;
3236 if (worktree) {
3237 const char *prefix = got_worktree_get_path_prefix(worktree);
3238 char *p;
3240 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3241 if (err)
3242 return err;
3243 if (asprintf(in_repo_path, "%s%s%s", prefix,
3244 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3245 p) == -1) {
3246 err = got_error_from_errno("asprintf");
3247 *in_repo_path = NULL;
3249 free(p);
3250 } else
3251 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3253 return err;
3256 static const struct got_error *
3257 cmd_log(int argc, char *argv[])
3259 const struct got_error *error;
3260 struct got_repository *repo = NULL;
3261 struct got_worktree *worktree = NULL;
3262 struct got_object_id *start_id = NULL;
3263 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3264 char *start_commit = NULL, *label = NULL;
3265 struct got_reference *ref = NULL;
3266 const char *head_ref_name = NULL;
3267 int ch, log_branches = 0;
3268 struct tog_view *view;
3269 int *pack_fds = NULL;
3271 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3272 switch (ch) {
3273 case 'b':
3274 log_branches = 1;
3275 break;
3276 case 'c':
3277 start_commit = optarg;
3278 break;
3279 case 'r':
3280 repo_path = realpath(optarg, NULL);
3281 if (repo_path == NULL)
3282 return got_error_from_errno2("realpath",
3283 optarg);
3284 break;
3285 default:
3286 usage_log();
3287 /* NOTREACHED */
3291 argc -= optind;
3292 argv += optind;
3294 if (argc > 1)
3295 usage_log();
3297 error = got_repo_pack_fds_open(&pack_fds);
3298 if (error != NULL)
3299 goto done;
3301 if (repo_path == NULL) {
3302 cwd = getcwd(NULL, 0);
3303 if (cwd == NULL)
3304 return got_error_from_errno("getcwd");
3305 error = got_worktree_open(&worktree, cwd);
3306 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3307 goto done;
3308 if (worktree)
3309 repo_path =
3310 strdup(got_worktree_get_repo_path(worktree));
3311 else
3312 repo_path = strdup(cwd);
3313 if (repo_path == NULL) {
3314 error = got_error_from_errno("strdup");
3315 goto done;
3319 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3320 if (error != NULL)
3321 goto done;
3323 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3324 repo, worktree);
3325 if (error)
3326 goto done;
3328 init_curses();
3330 error = apply_unveil(got_repo_get_path(repo),
3331 worktree ? got_worktree_get_root_path(worktree) : NULL);
3332 if (error)
3333 goto done;
3335 /* already loaded by tog_log_with_path()? */
3336 if (TAILQ_EMPTY(&tog_refs)) {
3337 error = tog_load_refs(repo, 0);
3338 if (error)
3339 goto done;
3342 if (start_commit == NULL) {
3343 error = got_repo_match_object_id(&start_id, &label,
3344 worktree ? got_worktree_get_head_ref_name(worktree) :
3345 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3346 if (error)
3347 goto done;
3348 head_ref_name = label;
3349 } else {
3350 error = got_ref_open(&ref, repo, start_commit, 0);
3351 if (error == NULL)
3352 head_ref_name = got_ref_get_name(ref);
3353 else if (error->code != GOT_ERR_NOT_REF)
3354 goto done;
3355 error = got_repo_match_object_id(&start_id, NULL,
3356 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3357 if (error)
3358 goto done;
3361 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3362 if (view == NULL) {
3363 error = got_error_from_errno("view_open");
3364 goto done;
3366 error = open_log_view(view, start_id, repo, head_ref_name,
3367 in_repo_path, log_branches);
3368 if (error)
3369 goto done;
3370 if (worktree) {
3371 /* Release work tree lock. */
3372 got_worktree_close(worktree);
3373 worktree = NULL;
3375 error = view_loop(view);
3376 done:
3377 free(in_repo_path);
3378 free(repo_path);
3379 free(cwd);
3380 free(start_id);
3381 free(label);
3382 if (ref)
3383 got_ref_close(ref);
3384 if (repo) {
3385 const struct got_error *close_err = got_repo_close(repo);
3386 if (error == NULL)
3387 error = close_err;
3389 if (worktree)
3390 got_worktree_close(worktree);
3391 if (pack_fds) {
3392 const struct got_error *pack_err =
3393 got_repo_pack_fds_close(pack_fds);
3394 if (error == NULL)
3395 error = pack_err;
3397 tog_free_refs();
3398 return error;
3401 __dead static void
3402 usage_diff(void)
3404 endwin();
3405 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3406 "[-w] object1 object2\n", getprogname());
3407 exit(1);
3410 static int
3411 match_line(const char *line, regex_t *regex, size_t nmatch,
3412 regmatch_t *regmatch)
3414 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3417 static struct tog_color *
3418 match_color(struct tog_colors *colors, const char *line)
3420 struct tog_color *tc = NULL;
3422 STAILQ_FOREACH(tc, colors, entry) {
3423 if (match_line(line, &tc->regex, 0, NULL))
3424 return tc;
3427 return NULL;
3430 static const struct got_error *
3431 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3432 WINDOW *window, int skipcol, regmatch_t *regmatch)
3434 const struct got_error *err = NULL;
3435 char *exstr = NULL;
3436 wchar_t *wline = NULL;
3437 int rme, rms, n, width, scrollx;
3438 int width0 = 0, width1 = 0, width2 = 0;
3439 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3441 *wtotal = 0;
3443 rms = regmatch->rm_so;
3444 rme = regmatch->rm_eo;
3446 err = expand_tab(&exstr, line);
3447 if (err)
3448 return err;
3450 /* Split the line into 3 segments, according to match offsets. */
3451 seg0 = strndup(exstr, rms);
3452 if (seg0 == NULL) {
3453 err = got_error_from_errno("strndup");
3454 goto done;
3456 seg1 = strndup(exstr + rms, rme - rms);
3457 if (seg1 == NULL) {
3458 err = got_error_from_errno("strndup");
3459 goto done;
3461 seg2 = strdup(exstr + rme);
3462 if (seg2 == NULL) {
3463 err = got_error_from_errno("strndup");
3464 goto done;
3467 /* draw up to matched token if we haven't scrolled past it */
3468 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3469 col_tab_align, 1);
3470 if (err)
3471 goto done;
3472 n = MAX(width0 - skipcol, 0);
3473 if (n) {
3474 free(wline);
3475 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3476 wlimit, col_tab_align, 1);
3477 if (err)
3478 goto done;
3479 waddwstr(window, &wline[scrollx]);
3480 wlimit -= width;
3481 *wtotal += width;
3484 if (wlimit > 0) {
3485 int i = 0, w = 0;
3486 size_t wlen;
3488 free(wline);
3489 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3490 col_tab_align, 1);
3491 if (err)
3492 goto done;
3493 wlen = wcslen(wline);
3494 while (i < wlen) {
3495 width = wcwidth(wline[i]);
3496 if (width == -1) {
3497 /* should not happen, tabs are expanded */
3498 err = got_error(GOT_ERR_RANGE);
3499 goto done;
3501 if (width0 + w + width > skipcol)
3502 break;
3503 w += width;
3504 i++;
3506 /* draw (visible part of) matched token (if scrolled into it) */
3507 if (width1 - w > 0) {
3508 wattron(window, A_STANDOUT);
3509 waddwstr(window, &wline[i]);
3510 wattroff(window, A_STANDOUT);
3511 wlimit -= (width1 - w);
3512 *wtotal += (width1 - w);
3516 if (wlimit > 0) { /* draw rest of line */
3517 free(wline);
3518 if (skipcol > width0 + width1) {
3519 err = format_line(&wline, &width2, &scrollx, seg2,
3520 skipcol - (width0 + width1), wlimit,
3521 col_tab_align, 1);
3522 if (err)
3523 goto done;
3524 waddwstr(window, &wline[scrollx]);
3525 } else {
3526 err = format_line(&wline, &width2, NULL, seg2, 0,
3527 wlimit, col_tab_align, 1);
3528 if (err)
3529 goto done;
3530 waddwstr(window, wline);
3532 *wtotal += width2;
3534 done:
3535 free(wline);
3536 free(exstr);
3537 free(seg0);
3538 free(seg1);
3539 free(seg2);
3540 return err;
3543 static const struct got_error *
3544 draw_file(struct tog_view *view, const char *header)
3546 struct tog_diff_view_state *s = &view->state.diff;
3547 regmatch_t *regmatch = &view->regmatch;
3548 const struct got_error *err;
3549 int nprinted = 0;
3550 char *line;
3551 size_t linesize = 0;
3552 ssize_t linelen;
3553 struct tog_color *tc;
3554 wchar_t *wline;
3555 int width;
3556 int max_lines = view->nlines;
3557 int nlines = s->nlines;
3558 off_t line_offset;
3560 line_offset = s->line_offsets[s->first_displayed_line - 1];
3561 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3562 return got_error_from_errno("fseek");
3564 werase(view->window);
3566 if (header) {
3567 if (asprintf(&line, "[%d/%d] %s",
3568 s->first_displayed_line - 1 + s->selected_line, nlines,
3569 header) == -1)
3570 return got_error_from_errno("asprintf");
3571 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3572 0, 0);
3573 free(line);
3574 if (err)
3575 return err;
3577 if (view_needs_focus_indication(view))
3578 wstandout(view->window);
3579 waddwstr(view->window, wline);
3580 free(wline);
3581 wline = NULL;
3582 if (view_needs_focus_indication(view))
3583 wstandend(view->window);
3584 if (width <= view->ncols - 1)
3585 waddch(view->window, '\n');
3587 if (max_lines <= 1)
3588 return NULL;
3589 max_lines--;
3592 s->eof = 0;
3593 view->maxx = 0;
3594 line = NULL;
3595 while (max_lines > 0 && nprinted < max_lines) {
3596 linelen = getline(&line, &linesize, s->f);
3597 if (linelen == -1) {
3598 if (feof(s->f)) {
3599 s->eof = 1;
3600 break;
3602 free(line);
3603 return got_ferror(s->f, GOT_ERR_IO);
3606 /* Set view->maxx based on full line length. */
3607 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3608 view->x ? 1 : 0);
3609 if (err) {
3610 free(line);
3611 return err;
3613 view->maxx = MAX(view->maxx, width);
3614 free(wline);
3615 wline = NULL;
3617 tc = match_color(&s->colors, line);
3618 if (tc)
3619 wattr_on(view->window,
3620 COLOR_PAIR(tc->colorpair), NULL);
3621 if (s->first_displayed_line + nprinted == s->matched_line &&
3622 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3623 err = add_matched_line(&width, line, view->ncols, 0,
3624 view->window, view->x, regmatch);
3625 if (err) {
3626 free(line);
3627 return err;
3629 } else {
3630 int skip;
3631 err = format_line(&wline, &width, &skip, line,
3632 view->x, view->ncols, 0, view->x ? 1 : 0);
3633 if (err) {
3634 free(line);
3635 return err;
3637 waddwstr(view->window, &wline[skip]);
3638 free(wline);
3639 wline = NULL;
3641 if (tc)
3642 wattr_off(view->window,
3643 COLOR_PAIR(tc->colorpair), NULL);
3644 if (width <= view->ncols - 1)
3645 waddch(view->window, '\n');
3646 nprinted++;
3648 free(line);
3649 if (nprinted >= 1)
3650 s->last_displayed_line = s->first_displayed_line +
3651 (nprinted - 1);
3652 else
3653 s->last_displayed_line = s->first_displayed_line;
3655 view_border(view);
3657 if (s->eof) {
3658 while (nprinted < view->nlines) {
3659 waddch(view->window, '\n');
3660 nprinted++;
3663 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3664 view->ncols, 0, 0);
3665 if (err) {
3666 return err;
3669 wstandout(view->window);
3670 waddwstr(view->window, wline);
3671 free(wline);
3672 wline = NULL;
3673 wstandend(view->window);
3676 return NULL;
3679 static char *
3680 get_datestr(time_t *time, char *datebuf)
3682 struct tm mytm, *tm;
3683 char *p, *s;
3685 tm = gmtime_r(time, &mytm);
3686 if (tm == NULL)
3687 return NULL;
3688 s = asctime_r(tm, datebuf);
3689 if (s == NULL)
3690 return NULL;
3691 p = strchr(s, '\n');
3692 if (p)
3693 *p = '\0';
3694 return s;
3697 static const struct got_error *
3698 get_changed_paths(struct got_pathlist_head *paths,
3699 struct got_commit_object *commit, struct got_repository *repo)
3701 const struct got_error *err = NULL;
3702 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3703 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3704 struct got_object_qid *qid;
3706 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3707 if (qid != NULL) {
3708 struct got_commit_object *pcommit;
3709 err = got_object_open_as_commit(&pcommit, repo,
3710 &qid->id);
3711 if (err)
3712 return err;
3714 tree_id1 = got_object_id_dup(
3715 got_object_commit_get_tree_id(pcommit));
3716 if (tree_id1 == NULL) {
3717 got_object_commit_close(pcommit);
3718 return got_error_from_errno("got_object_id_dup");
3720 got_object_commit_close(pcommit);
3724 if (tree_id1) {
3725 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3726 if (err)
3727 goto done;
3730 tree_id2 = got_object_commit_get_tree_id(commit);
3731 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3732 if (err)
3733 goto done;
3735 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3736 got_diff_tree_collect_changed_paths, paths, 0);
3737 done:
3738 if (tree1)
3739 got_object_tree_close(tree1);
3740 if (tree2)
3741 got_object_tree_close(tree2);
3742 free(tree_id1);
3743 return err;
3746 static const struct got_error *
3747 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
3749 off_t *p;
3751 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
3752 if (p == NULL)
3753 return got_error_from_errno("reallocarray");
3754 *line_offsets = p;
3755 (*line_offsets)[*nlines] = off;
3756 (*nlines)++;
3757 return NULL;
3760 static const struct got_error *
3761 write_commit_info(off_t **line_offsets, size_t *nlines,
3762 struct got_object_id *commit_id, struct got_reflist_head *refs,
3763 struct got_repository *repo, FILE *outfile)
3765 const struct got_error *err = NULL;
3766 char datebuf[26], *datestr;
3767 struct got_commit_object *commit;
3768 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
3769 time_t committer_time;
3770 const char *author, *committer;
3771 char *refs_str = NULL;
3772 struct got_pathlist_head changed_paths;
3773 struct got_pathlist_entry *pe;
3774 off_t outoff = 0;
3775 int n;
3777 TAILQ_INIT(&changed_paths);
3779 if (refs) {
3780 err = build_refs_str(&refs_str, refs, commit_id, repo);
3781 if (err)
3782 return err;
3785 err = got_object_open_as_commit(&commit, repo, commit_id);
3786 if (err)
3787 return err;
3789 err = got_object_id_str(&id_str, commit_id);
3790 if (err) {
3791 err = got_error_from_errno("got_object_id_str");
3792 goto done;
3795 err = add_line_offset(line_offsets, nlines, 0);
3796 if (err)
3797 goto done;
3799 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3800 refs_str ? refs_str : "", refs_str ? ")" : "");
3801 if (n < 0) {
3802 err = got_error_from_errno("fprintf");
3803 goto done;
3805 outoff += n;
3806 err = add_line_offset(line_offsets, nlines, outoff);
3807 if (err)
3808 goto done;
3810 n = fprintf(outfile, "from: %s\n",
3811 got_object_commit_get_author(commit));
3812 if (n < 0) {
3813 err = got_error_from_errno("fprintf");
3814 goto done;
3816 outoff += n;
3817 err = add_line_offset(line_offsets, nlines, outoff);
3818 if (err)
3819 goto done;
3821 committer_time = got_object_commit_get_committer_time(commit);
3822 datestr = get_datestr(&committer_time, datebuf);
3823 if (datestr) {
3824 n = fprintf(outfile, "date: %s UTC\n", datestr);
3825 if (n < 0) {
3826 err = got_error_from_errno("fprintf");
3827 goto done;
3829 outoff += n;
3830 err = add_line_offset(line_offsets, nlines, outoff);
3831 if (err)
3832 goto done;
3834 author = got_object_commit_get_author(commit);
3835 committer = got_object_commit_get_committer(commit);
3836 if (strcmp(author, committer) != 0) {
3837 n = fprintf(outfile, "via: %s\n", committer);
3838 if (n < 0) {
3839 err = got_error_from_errno("fprintf");
3840 goto done;
3842 outoff += n;
3843 err = add_line_offset(line_offsets, nlines, outoff);
3844 if (err)
3845 goto done;
3847 if (got_object_commit_get_nparents(commit) > 1) {
3848 const struct got_object_id_queue *parent_ids;
3849 struct got_object_qid *qid;
3850 int pn = 1;
3851 parent_ids = got_object_commit_get_parent_ids(commit);
3852 STAILQ_FOREACH(qid, parent_ids, entry) {
3853 err = got_object_id_str(&id_str, &qid->id);
3854 if (err)
3855 goto done;
3856 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
3857 if (n < 0) {
3858 err = got_error_from_errno("fprintf");
3859 goto done;
3861 outoff += n;
3862 err = add_line_offset(line_offsets, nlines, outoff);
3863 if (err)
3864 goto done;
3865 free(id_str);
3866 id_str = NULL;
3870 err = got_object_commit_get_logmsg(&logmsg, commit);
3871 if (err)
3872 goto done;
3873 s = logmsg;
3874 while ((line = strsep(&s, "\n")) != NULL) {
3875 n = fprintf(outfile, "%s\n", line);
3876 if (n < 0) {
3877 err = got_error_from_errno("fprintf");
3878 goto done;
3880 outoff += n;
3881 err = add_line_offset(line_offsets, nlines, outoff);
3882 if (err)
3883 goto done;
3886 err = get_changed_paths(&changed_paths, commit, repo);
3887 if (err)
3888 goto done;
3889 TAILQ_FOREACH(pe, &changed_paths, entry) {
3890 struct got_diff_changed_path *cp = pe->data;
3891 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
3892 if (n < 0) {
3893 err = got_error_from_errno("fprintf");
3894 goto done;
3896 outoff += n;
3897 err = add_line_offset(line_offsets, nlines, outoff);
3898 if (err)
3899 goto done;
3900 free((char *)pe->path);
3901 free(pe->data);
3904 fputc('\n', outfile);
3905 outoff++;
3906 err = add_line_offset(line_offsets, nlines, outoff);
3907 done:
3908 got_pathlist_free(&changed_paths);
3909 free(id_str);
3910 free(logmsg);
3911 free(refs_str);
3912 got_object_commit_close(commit);
3913 if (err) {
3914 free(*line_offsets);
3915 *line_offsets = NULL;
3916 *nlines = 0;
3918 return err;
3921 static const struct got_error *
3922 create_diff(struct tog_diff_view_state *s)
3924 const struct got_error *err = NULL;
3925 FILE *f = NULL;
3926 int obj_type;
3928 free(s->line_offsets);
3929 s->line_offsets = malloc(sizeof(off_t));
3930 if (s->line_offsets == NULL)
3931 return got_error_from_errno("malloc");
3932 s->nlines = 0;
3934 f = got_opentemp();
3935 if (f == NULL) {
3936 err = got_error_from_errno("got_opentemp");
3937 goto done;
3939 if (s->f && fclose(s->f) == EOF) {
3940 err = got_error_from_errno("fclose");
3941 goto done;
3943 s->f = f;
3945 if (s->id1)
3946 err = got_object_get_type(&obj_type, s->repo, s->id1);
3947 else
3948 err = got_object_get_type(&obj_type, s->repo, s->id2);
3949 if (err)
3950 goto done;
3952 switch (obj_type) {
3953 case GOT_OBJ_TYPE_BLOB:
3954 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
3955 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
3956 s->label1, s->label2, s->diff_context,
3957 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
3958 break;
3959 case GOT_OBJ_TYPE_TREE:
3960 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
3961 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
3962 s->diff_context, s->ignore_whitespace, s->force_text_diff,
3963 s->repo, s->f);
3964 break;
3965 case GOT_OBJ_TYPE_COMMIT: {
3966 const struct got_object_id_queue *parent_ids;
3967 struct got_object_qid *pid;
3968 struct got_commit_object *commit2;
3969 struct got_reflist_head *refs;
3971 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
3972 if (err)
3973 goto done;
3974 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
3975 /* Show commit info if we're diffing to a parent/root commit. */
3976 if (s->id1 == NULL) {
3977 err = write_commit_info(&s->line_offsets, &s->nlines,
3978 s->id2, refs, s->repo, s->f);
3979 if (err)
3980 goto done;
3981 } else {
3982 parent_ids = got_object_commit_get_parent_ids(commit2);
3983 STAILQ_FOREACH(pid, parent_ids, entry) {
3984 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
3985 err = write_commit_info(
3986 &s->line_offsets, &s->nlines,
3987 s->id2, refs, s->repo, s->f);
3988 if (err)
3989 goto done;
3990 break;
3994 got_object_commit_close(commit2);
3996 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
3997 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
3998 s->diff_context, s->ignore_whitespace, s->force_text_diff,
3999 s->repo, s->f);
4000 break;
4002 default:
4003 err = got_error(GOT_ERR_OBJ_TYPE);
4004 break;
4006 if (err)
4007 goto done;
4008 done:
4009 if (s->f && fflush(s->f) != 0 && err == NULL)
4010 err = got_error_from_errno("fflush");
4011 return err;
4014 static void
4015 diff_view_indicate_progress(struct tog_view *view)
4017 mvwaddstr(view->window, 0, 0, "diffing...");
4018 update_panels();
4019 doupdate();
4022 static const struct got_error *
4023 search_start_diff_view(struct tog_view *view)
4025 struct tog_diff_view_state *s = &view->state.diff;
4027 s->matched_line = 0;
4028 return NULL;
4031 static const struct got_error *
4032 search_next_diff_view(struct tog_view *view)
4034 struct tog_diff_view_state *s = &view->state.diff;
4035 const struct got_error *err = NULL;
4036 int lineno;
4037 char *line = NULL;
4038 size_t linesize = 0;
4039 ssize_t linelen;
4041 if (!view->searching) {
4042 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4043 return NULL;
4046 if (s->matched_line) {
4047 if (view->searching == TOG_SEARCH_FORWARD)
4048 lineno = s->matched_line + 1;
4049 else
4050 lineno = s->matched_line - 1;
4051 } else
4052 lineno = s->first_displayed_line;
4054 while (1) {
4055 off_t offset;
4057 if (lineno <= 0 || lineno > s->nlines) {
4058 if (s->matched_line == 0) {
4059 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4060 break;
4063 if (view->searching == TOG_SEARCH_FORWARD)
4064 lineno = 1;
4065 else
4066 lineno = s->nlines;
4069 offset = s->line_offsets[lineno - 1];
4070 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4071 free(line);
4072 return got_error_from_errno("fseeko");
4074 linelen = getline(&line, &linesize, s->f);
4075 if (linelen != -1) {
4076 char *exstr;
4077 err = expand_tab(&exstr, line);
4078 if (err)
4079 break;
4080 if (match_line(exstr, &view->regex, 1,
4081 &view->regmatch)) {
4082 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4083 s->matched_line = lineno;
4084 free(exstr);
4085 break;
4087 free(exstr);
4089 if (view->searching == TOG_SEARCH_FORWARD)
4090 lineno++;
4091 else
4092 lineno--;
4094 free(line);
4096 if (s->matched_line) {
4097 s->first_displayed_line = s->matched_line;
4098 s->selected_line = 1;
4101 return err;
4104 static const struct got_error *
4105 close_diff_view(struct tog_view *view)
4107 const struct got_error *err = NULL;
4108 struct tog_diff_view_state *s = &view->state.diff;
4110 free(s->id1);
4111 s->id1 = NULL;
4112 free(s->id2);
4113 s->id2 = NULL;
4114 if (s->f && fclose(s->f) == EOF)
4115 err = got_error_from_errno("fclose");
4116 s->f = NULL;
4117 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4118 err = got_error_from_errno("fclose");
4119 s->f1 = NULL;
4120 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4121 err = got_error_from_errno("fclose");
4122 s->f2 = NULL;
4123 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4124 err = got_error_from_errno("close");
4125 s->fd1 = -1;
4126 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4127 err = got_error_from_errno("close");
4128 s->fd2 = -1;
4129 free_colors(&s->colors);
4130 free(s->line_offsets);
4131 s->line_offsets = NULL;
4132 s->nlines = 0;
4133 return err;
4136 static const struct got_error *
4137 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4138 struct got_object_id *id2, const char *label1, const char *label2,
4139 int diff_context, int ignore_whitespace, int force_text_diff,
4140 struct tog_view *log_view, struct got_repository *repo)
4142 const struct got_error *err;
4143 struct tog_diff_view_state *s = &view->state.diff;
4145 memset(s, 0, sizeof(*s));
4146 s->fd1 = -1;
4147 s->fd2 = -1;
4149 if (id1 != NULL && id2 != NULL) {
4150 int type1, type2;
4151 err = got_object_get_type(&type1, repo, id1);
4152 if (err)
4153 return err;
4154 err = got_object_get_type(&type2, repo, id2);
4155 if (err)
4156 return err;
4158 if (type1 != type2)
4159 return got_error(GOT_ERR_OBJ_TYPE);
4161 s->first_displayed_line = 1;
4162 s->last_displayed_line = view->nlines;
4163 s->selected_line = 1;
4164 s->repo = repo;
4165 s->id1 = id1;
4166 s->id2 = id2;
4167 s->label1 = label1;
4168 s->label2 = label2;
4170 if (id1) {
4171 s->id1 = got_object_id_dup(id1);
4172 if (s->id1 == NULL)
4173 return got_error_from_errno("got_object_id_dup");
4174 } else
4175 s->id1 = NULL;
4177 s->id2 = got_object_id_dup(id2);
4178 if (s->id2 == NULL) {
4179 err = got_error_from_errno("got_object_id_dup");
4180 goto done;
4183 s->f1 = got_opentemp();
4184 if (s->f1 == NULL) {
4185 err = got_error_from_errno("got_opentemp");
4186 goto done;
4189 s->f2 = got_opentemp();
4190 if (s->f2 == NULL) {
4191 err = got_error_from_errno("got_opentemp");
4192 goto done;
4195 s->fd1 = got_opentempfd();
4196 if (s->fd1 == -1) {
4197 err = got_error_from_errno("got_opentempfd");
4198 goto done;
4201 s->fd2 = got_opentempfd();
4202 if (s->fd2 == -1) {
4203 err = got_error_from_errno("got_opentempfd");
4204 goto done;
4207 s->first_displayed_line = 1;
4208 s->last_displayed_line = view->nlines;
4209 s->diff_context = diff_context;
4210 s->ignore_whitespace = ignore_whitespace;
4211 s->force_text_diff = force_text_diff;
4212 s->log_view = log_view;
4213 s->repo = repo;
4215 STAILQ_INIT(&s->colors);
4216 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4217 err = add_color(&s->colors,
4218 "^-", TOG_COLOR_DIFF_MINUS,
4219 get_color_value("TOG_COLOR_DIFF_MINUS"));
4220 if (err)
4221 goto done;
4222 err = add_color(&s->colors, "^\\+",
4223 TOG_COLOR_DIFF_PLUS,
4224 get_color_value("TOG_COLOR_DIFF_PLUS"));
4225 if (err)
4226 goto done;
4227 err = add_color(&s->colors,
4228 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4229 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4230 if (err)
4231 goto done;
4233 err = add_color(&s->colors,
4234 "^(commit [0-9a-f]|parent [0-9]|"
4235 "(blob|file|tree|commit) [-+] |"
4236 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4237 get_color_value("TOG_COLOR_DIFF_META"));
4238 if (err)
4239 goto done;
4241 err = add_color(&s->colors,
4242 "^(from|via): ", TOG_COLOR_AUTHOR,
4243 get_color_value("TOG_COLOR_AUTHOR"));
4244 if (err)
4245 goto done;
4247 err = add_color(&s->colors,
4248 "^date: ", TOG_COLOR_DATE,
4249 get_color_value("TOG_COLOR_DATE"));
4250 if (err)
4251 goto done;
4254 if (log_view && view_is_splitscreen(view))
4255 show_log_view(log_view); /* draw vborder */
4256 diff_view_indicate_progress(view);
4258 err = create_diff(s);
4260 view->show = show_diff_view;
4261 view->input = input_diff_view;
4262 view->close = close_diff_view;
4263 view->search_start = search_start_diff_view;
4264 view->search_next = search_next_diff_view;
4265 done:
4266 if (err)
4267 close_diff_view(view);
4268 return err;
4271 static const struct got_error *
4272 show_diff_view(struct tog_view *view)
4274 const struct got_error *err;
4275 struct tog_diff_view_state *s = &view->state.diff;
4276 char *id_str1 = NULL, *id_str2, *header;
4277 const char *label1, *label2;
4279 if (s->id1) {
4280 err = got_object_id_str(&id_str1, s->id1);
4281 if (err)
4282 return err;
4283 label1 = s->label1 ? : id_str1;
4284 } else
4285 label1 = "/dev/null";
4287 err = got_object_id_str(&id_str2, s->id2);
4288 if (err)
4289 return err;
4290 label2 = s->label2 ? : id_str2;
4292 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4293 err = got_error_from_errno("asprintf");
4294 free(id_str1);
4295 free(id_str2);
4296 return err;
4298 free(id_str1);
4299 free(id_str2);
4301 err = draw_file(view, header);
4302 free(header);
4303 return err;
4306 static const struct got_error *
4307 set_selected_commit(struct tog_diff_view_state *s,
4308 struct commit_queue_entry *entry)
4310 const struct got_error *err;
4311 const struct got_object_id_queue *parent_ids;
4312 struct got_commit_object *selected_commit;
4313 struct got_object_qid *pid;
4315 free(s->id2);
4316 s->id2 = got_object_id_dup(entry->id);
4317 if (s->id2 == NULL)
4318 return got_error_from_errno("got_object_id_dup");
4320 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4321 if (err)
4322 return err;
4323 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4324 free(s->id1);
4325 pid = STAILQ_FIRST(parent_ids);
4326 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4327 got_object_commit_close(selected_commit);
4328 return NULL;
4331 static const struct got_error *
4332 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4334 const struct got_error *err = NULL;
4335 struct tog_diff_view_state *s = &view->state.diff;
4336 struct tog_log_view_state *ls;
4337 struct commit_queue_entry *old_selected_entry;
4338 char *line = NULL;
4339 size_t linesize = 0;
4340 ssize_t linelen;
4341 int i, nscroll = view->nlines - 1;
4343 switch (ch) {
4344 case '0':
4345 view->x = 0;
4346 break;
4347 case '$':
4348 view->x = MAX(view->maxx - view->ncols / 3, 0);
4349 view->count = 0;
4350 break;
4351 case KEY_RIGHT:
4352 case 'l':
4353 if (view->x + view->ncols / 3 < view->maxx)
4354 view->x += 2; /* move two columns right */
4355 else
4356 view->count = 0;
4357 break;
4358 case KEY_LEFT:
4359 case 'h':
4360 view->x -= MIN(view->x, 2); /* move two columns back */
4361 if (view->x <= 0)
4362 view->count = 0;
4363 break;
4364 case 'a':
4365 case 'w':
4366 if (ch == 'a')
4367 s->force_text_diff = !s->force_text_diff;
4368 if (ch == 'w')
4369 s->ignore_whitespace = !s->ignore_whitespace;
4370 wclear(view->window);
4371 s->first_displayed_line = 1;
4372 s->last_displayed_line = view->nlines;
4373 s->matched_line = 0;
4374 diff_view_indicate_progress(view);
4375 err = create_diff(s);
4376 view->count = 0;
4377 break;
4378 case 'g':
4379 case KEY_HOME:
4380 s->first_displayed_line = 1;
4381 view->count = 0;
4382 break;
4383 case 'G':
4384 case KEY_END:
4385 view->count = 0;
4386 if (s->eof)
4387 break;
4389 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4390 s->eof = 1;
4391 break;
4392 case 'k':
4393 case KEY_UP:
4394 case CTRL('p'):
4395 if (s->first_displayed_line > 1)
4396 s->first_displayed_line--;
4397 else
4398 view->count = 0;
4399 break;
4400 case CTRL('u'):
4401 case 'u':
4402 nscroll /= 2;
4403 /* FALL THROUGH */
4404 case KEY_PPAGE:
4405 case CTRL('b'):
4406 case 'b':
4407 if (s->first_displayed_line == 1) {
4408 view->count = 0;
4409 break;
4411 i = 0;
4412 while (i++ < nscroll && s->first_displayed_line > 1)
4413 s->first_displayed_line--;
4414 break;
4415 case 'j':
4416 case KEY_DOWN:
4417 case CTRL('n'):
4418 if (!s->eof)
4419 s->first_displayed_line++;
4420 else
4421 view->count = 0;
4422 break;
4423 case CTRL('d'):
4424 case 'd':
4425 nscroll /= 2;
4426 /* FALL THROUGH */
4427 case KEY_NPAGE:
4428 case CTRL('f'):
4429 case 'f':
4430 case ' ':
4431 if (s->eof) {
4432 view->count = 0;
4433 break;
4435 i = 0;
4436 while (!s->eof && i++ < nscroll) {
4437 linelen = getline(&line, &linesize, s->f);
4438 s->first_displayed_line++;
4439 if (linelen == -1) {
4440 if (feof(s->f)) {
4441 s->eof = 1;
4442 } else
4443 err = got_ferror(s->f, GOT_ERR_IO);
4444 break;
4447 free(line);
4448 break;
4449 case '[':
4450 if (s->diff_context > 0) {
4451 s->diff_context--;
4452 s->matched_line = 0;
4453 diff_view_indicate_progress(view);
4454 err = create_diff(s);
4455 if (s->first_displayed_line + view->nlines - 1 >
4456 s->nlines) {
4457 s->first_displayed_line = 1;
4458 s->last_displayed_line = view->nlines;
4460 } else
4461 view->count = 0;
4462 break;
4463 case ']':
4464 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4465 s->diff_context++;
4466 s->matched_line = 0;
4467 diff_view_indicate_progress(view);
4468 err = create_diff(s);
4469 } else
4470 view->count = 0;
4471 break;
4472 case '<':
4473 case ',':
4474 if (s->log_view == NULL) {
4475 view->count = 0;
4476 break;
4478 ls = &s->log_view->state.log;
4479 old_selected_entry = ls->selected_entry;
4481 /* view->count handled in input_log_view() */
4482 err = input_log_view(NULL, s->log_view, KEY_UP);
4483 if (err)
4484 break;
4486 if (old_selected_entry == ls->selected_entry)
4487 break;
4489 err = set_selected_commit(s, ls->selected_entry);
4490 if (err)
4491 break;
4493 s->first_displayed_line = 1;
4494 s->last_displayed_line = view->nlines;
4495 s->matched_line = 0;
4496 view->x = 0;
4498 diff_view_indicate_progress(view);
4499 err = create_diff(s);
4500 break;
4501 case '>':
4502 case '.':
4503 if (s->log_view == NULL) {
4504 view->count = 0;
4505 break;
4507 ls = &s->log_view->state.log;
4508 old_selected_entry = ls->selected_entry;
4510 /* view->count handled in input_log_view() */
4511 err = input_log_view(NULL, s->log_view, KEY_DOWN);
4512 if (err)
4513 break;
4515 if (old_selected_entry == ls->selected_entry)
4516 break;
4518 err = set_selected_commit(s, ls->selected_entry);
4519 if (err)
4520 break;
4522 s->first_displayed_line = 1;
4523 s->last_displayed_line = view->nlines;
4524 s->matched_line = 0;
4525 view->x = 0;
4527 diff_view_indicate_progress(view);
4528 err = create_diff(s);
4529 break;
4530 default:
4531 view->count = 0;
4532 break;
4535 return err;
4538 static const struct got_error *
4539 cmd_diff(int argc, char *argv[])
4541 const struct got_error *error = NULL;
4542 struct got_repository *repo = NULL;
4543 struct got_worktree *worktree = NULL;
4544 struct got_object_id *id1 = NULL, *id2 = NULL;
4545 char *repo_path = NULL, *cwd = NULL;
4546 char *id_str1 = NULL, *id_str2 = NULL;
4547 char *label1 = NULL, *label2 = NULL;
4548 int diff_context = 3, ignore_whitespace = 0;
4549 int ch, force_text_diff = 0;
4550 const char *errstr;
4551 struct tog_view *view;
4552 int *pack_fds = NULL;
4554 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4555 switch (ch) {
4556 case 'a':
4557 force_text_diff = 1;
4558 break;
4559 case 'C':
4560 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4561 &errstr);
4562 if (errstr != NULL)
4563 errx(1, "number of context lines is %s: %s",
4564 errstr, errstr);
4565 break;
4566 case 'r':
4567 repo_path = realpath(optarg, NULL);
4568 if (repo_path == NULL)
4569 return got_error_from_errno2("realpath",
4570 optarg);
4571 got_path_strip_trailing_slashes(repo_path);
4572 break;
4573 case 'w':
4574 ignore_whitespace = 1;
4575 break;
4576 default:
4577 usage_diff();
4578 /* NOTREACHED */
4582 argc -= optind;
4583 argv += optind;
4585 if (argc == 0) {
4586 usage_diff(); /* TODO show local worktree changes */
4587 } else if (argc == 2) {
4588 id_str1 = argv[0];
4589 id_str2 = argv[1];
4590 } else
4591 usage_diff();
4593 error = got_repo_pack_fds_open(&pack_fds);
4594 if (error)
4595 goto done;
4597 if (repo_path == NULL) {
4598 cwd = getcwd(NULL, 0);
4599 if (cwd == NULL)
4600 return got_error_from_errno("getcwd");
4601 error = got_worktree_open(&worktree, cwd);
4602 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4603 goto done;
4604 if (worktree)
4605 repo_path =
4606 strdup(got_worktree_get_repo_path(worktree));
4607 else
4608 repo_path = strdup(cwd);
4609 if (repo_path == NULL) {
4610 error = got_error_from_errno("strdup");
4611 goto done;
4615 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4616 if (error)
4617 goto done;
4619 init_curses();
4621 error = apply_unveil(got_repo_get_path(repo), NULL);
4622 if (error)
4623 goto done;
4625 error = tog_load_refs(repo, 0);
4626 if (error)
4627 goto done;
4629 error = got_repo_match_object_id(&id1, &label1, id_str1,
4630 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4631 if (error)
4632 goto done;
4634 error = got_repo_match_object_id(&id2, &label2, id_str2,
4635 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4636 if (error)
4637 goto done;
4639 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4640 if (view == NULL) {
4641 error = got_error_from_errno("view_open");
4642 goto done;
4644 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4645 ignore_whitespace, force_text_diff, NULL, repo);
4646 if (error)
4647 goto done;
4648 error = view_loop(view);
4649 done:
4650 free(label1);
4651 free(label2);
4652 free(repo_path);
4653 free(cwd);
4654 if (repo) {
4655 const struct got_error *close_err = got_repo_close(repo);
4656 if (error == NULL)
4657 error = close_err;
4659 if (worktree)
4660 got_worktree_close(worktree);
4661 if (pack_fds) {
4662 const struct got_error *pack_err =
4663 got_repo_pack_fds_close(pack_fds);
4664 if (error == NULL)
4665 error = pack_err;
4667 tog_free_refs();
4668 return error;
4671 __dead static void
4672 usage_blame(void)
4674 endwin();
4675 fprintf(stderr,
4676 "usage: %s blame [-c commit] [-r repository-path] path\n",
4677 getprogname());
4678 exit(1);
4681 struct tog_blame_line {
4682 int annotated;
4683 struct got_object_id *id;
4686 static const struct got_error *
4687 draw_blame(struct tog_view *view)
4689 struct tog_blame_view_state *s = &view->state.blame;
4690 struct tog_blame *blame = &s->blame;
4691 regmatch_t *regmatch = &view->regmatch;
4692 const struct got_error *err;
4693 int lineno = 0, nprinted = 0;
4694 char *line = NULL;
4695 size_t linesize = 0;
4696 ssize_t linelen;
4697 wchar_t *wline;
4698 int width;
4699 struct tog_blame_line *blame_line;
4700 struct got_object_id *prev_id = NULL;
4701 char *id_str;
4702 struct tog_color *tc;
4704 err = got_object_id_str(&id_str, &s->blamed_commit->id);
4705 if (err)
4706 return err;
4708 rewind(blame->f);
4709 werase(view->window);
4711 if (asprintf(&line, "commit %s", id_str) == -1) {
4712 err = got_error_from_errno("asprintf");
4713 free(id_str);
4714 return err;
4717 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4718 free(line);
4719 line = NULL;
4720 if (err)
4721 return err;
4722 if (view_needs_focus_indication(view))
4723 wstandout(view->window);
4724 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4725 if (tc)
4726 wattr_on(view->window,
4727 COLOR_PAIR(tc->colorpair), NULL);
4728 waddwstr(view->window, wline);
4729 if (tc)
4730 wattr_off(view->window,
4731 COLOR_PAIR(tc->colorpair), NULL);
4732 if (view_needs_focus_indication(view))
4733 wstandend(view->window);
4734 free(wline);
4735 wline = NULL;
4736 if (width < view->ncols - 1)
4737 waddch(view->window, '\n');
4739 if (asprintf(&line, "[%d/%d] %s%s",
4740 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
4741 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
4742 free(id_str);
4743 return got_error_from_errno("asprintf");
4745 free(id_str);
4746 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4747 free(line);
4748 line = NULL;
4749 if (err)
4750 return err;
4751 waddwstr(view->window, wline);
4752 free(wline);
4753 wline = NULL;
4754 if (width < view->ncols - 1)
4755 waddch(view->window, '\n');
4757 s->eof = 0;
4758 view->maxx = 0;
4759 while (nprinted < view->nlines - 2) {
4760 linelen = getline(&line, &linesize, blame->f);
4761 if (linelen == -1) {
4762 if (feof(blame->f)) {
4763 s->eof = 1;
4764 break;
4766 free(line);
4767 return got_ferror(blame->f, GOT_ERR_IO);
4769 if (++lineno < s->first_displayed_line)
4770 continue;
4772 /* Set view->maxx based on full line length. */
4773 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
4774 if (err) {
4775 free(line);
4776 return err;
4778 free(wline);
4779 wline = NULL;
4780 view->maxx = MAX(view->maxx, width);
4782 if (view->focussed && nprinted == s->selected_line - 1)
4783 wstandout(view->window);
4785 if (blame->nlines > 0) {
4786 blame_line = &blame->lines[lineno - 1];
4787 if (blame_line->annotated && prev_id &&
4788 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
4789 !(view->focussed &&
4790 nprinted == s->selected_line - 1)) {
4791 waddstr(view->window, " ");
4792 } else if (blame_line->annotated) {
4793 char *id_str;
4794 err = got_object_id_str(&id_str,
4795 blame_line->id);
4796 if (err) {
4797 free(line);
4798 return err;
4800 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4801 if (tc)
4802 wattr_on(view->window,
4803 COLOR_PAIR(tc->colorpair), NULL);
4804 wprintw(view->window, "%.8s", id_str);
4805 if (tc)
4806 wattr_off(view->window,
4807 COLOR_PAIR(tc->colorpair), NULL);
4808 free(id_str);
4809 prev_id = blame_line->id;
4810 } else {
4811 waddstr(view->window, "........");
4812 prev_id = NULL;
4814 } else {
4815 waddstr(view->window, "........");
4816 prev_id = NULL;
4819 if (view->focussed && nprinted == s->selected_line - 1)
4820 wstandend(view->window);
4821 waddstr(view->window, " ");
4823 if (view->ncols <= 9) {
4824 width = 9;
4825 } else if (s->first_displayed_line + nprinted ==
4826 s->matched_line &&
4827 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4828 err = add_matched_line(&width, line, view->ncols - 9, 9,
4829 view->window, view->x, regmatch);
4830 if (err) {
4831 free(line);
4832 return err;
4834 width += 9;
4835 } else {
4836 int skip;
4837 err = format_line(&wline, &width, &skip, line,
4838 view->x, view->ncols - 9, 9, 1);
4839 if (err) {
4840 free(line);
4841 return err;
4843 waddwstr(view->window, &wline[skip]);
4844 width += 9;
4845 free(wline);
4846 wline = NULL;
4849 if (width <= view->ncols - 1)
4850 waddch(view->window, '\n');
4851 if (++nprinted == 1)
4852 s->first_displayed_line = lineno;
4854 free(line);
4855 s->last_displayed_line = lineno;
4857 view_border(view);
4859 return NULL;
4862 static const struct got_error *
4863 blame_cb(void *arg, int nlines, int lineno,
4864 struct got_commit_object *commit, struct got_object_id *id)
4866 const struct got_error *err = NULL;
4867 struct tog_blame_cb_args *a = arg;
4868 struct tog_blame_line *line;
4869 int errcode;
4871 if (nlines != a->nlines ||
4872 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4873 return got_error(GOT_ERR_RANGE);
4875 errcode = pthread_mutex_lock(&tog_mutex);
4876 if (errcode)
4877 return got_error_set_errno(errcode, "pthread_mutex_lock");
4879 if (*a->quit) { /* user has quit the blame view */
4880 err = got_error(GOT_ERR_ITER_COMPLETED);
4881 goto done;
4884 if (lineno == -1)
4885 goto done; /* no change in this commit */
4887 line = &a->lines[lineno - 1];
4888 if (line->annotated)
4889 goto done;
4891 line->id = got_object_id_dup(id);
4892 if (line->id == NULL) {
4893 err = got_error_from_errno("got_object_id_dup");
4894 goto done;
4896 line->annotated = 1;
4897 done:
4898 errcode = pthread_mutex_unlock(&tog_mutex);
4899 if (errcode)
4900 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4901 return err;
4904 static void *
4905 blame_thread(void *arg)
4907 const struct got_error *err, *close_err;
4908 struct tog_blame_thread_args *ta = arg;
4909 struct tog_blame_cb_args *a = ta->cb_args;
4910 int errcode, fd = -1;
4912 fd = got_opentempfd();
4913 if (fd == -1)
4914 return (void *)got_error_from_errno("got_opentempfd");
4916 err = block_signals_used_by_main_thread();
4917 if (err)
4918 return (void *)err;
4920 err = got_blame(ta->path, a->commit_id, ta->repo,
4921 blame_cb, ta->cb_args, ta->cancel_cb, ta->cancel_arg, fd);
4922 if (err && err->code == GOT_ERR_CANCELLED)
4923 err = NULL;
4925 errcode = pthread_mutex_lock(&tog_mutex);
4926 if (errcode)
4927 return (void *)got_error_set_errno(errcode,
4928 "pthread_mutex_lock");
4930 close_err = got_repo_close(ta->repo);
4931 if (err == NULL)
4932 err = close_err;
4933 ta->repo = NULL;
4934 *ta->complete = 1;
4936 errcode = pthread_mutex_unlock(&tog_mutex);
4937 if (errcode && err == NULL)
4938 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4940 if (fd != -1 && close(fd) == -1 && err == NULL)
4941 err = got_error_from_errno("close");
4943 return (void *)err;
4946 static struct got_object_id *
4947 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
4948 int first_displayed_line, int selected_line)
4950 struct tog_blame_line *line;
4952 if (nlines <= 0)
4953 return NULL;
4955 line = &lines[first_displayed_line - 1 + selected_line - 1];
4956 if (!line->annotated)
4957 return NULL;
4959 return line->id;
4962 static const struct got_error *
4963 stop_blame(struct tog_blame *blame)
4965 const struct got_error *err = NULL;
4966 int i;
4968 if (blame->thread) {
4969 int errcode;
4970 errcode = pthread_mutex_unlock(&tog_mutex);
4971 if (errcode)
4972 return got_error_set_errno(errcode,
4973 "pthread_mutex_unlock");
4974 errcode = pthread_join(blame->thread, (void **)&err);
4975 if (errcode)
4976 return got_error_set_errno(errcode, "pthread_join");
4977 errcode = pthread_mutex_lock(&tog_mutex);
4978 if (errcode)
4979 return got_error_set_errno(errcode,
4980 "pthread_mutex_lock");
4981 if (err && err->code == GOT_ERR_ITER_COMPLETED)
4982 err = NULL;
4983 blame->thread = NULL;
4985 if (blame->thread_args.repo) {
4986 const struct got_error *close_err;
4987 close_err = got_repo_close(blame->thread_args.repo);
4988 if (err == NULL)
4989 err = close_err;
4990 blame->thread_args.repo = NULL;
4992 if (blame->f) {
4993 if (fclose(blame->f) == EOF && err == NULL)
4994 err = got_error_from_errno("fclose");
4995 blame->f = NULL;
4997 if (blame->lines) {
4998 for (i = 0; i < blame->nlines; i++)
4999 free(blame->lines[i].id);
5000 free(blame->lines);
5001 blame->lines = NULL;
5003 free(blame->cb_args.commit_id);
5004 blame->cb_args.commit_id = NULL;
5005 if (blame->pack_fds) {
5006 const struct got_error *pack_err =
5007 got_repo_pack_fds_close(blame->pack_fds);
5008 if (err == NULL)
5009 err = pack_err;
5010 blame->pack_fds = NULL;
5012 return err;
5015 static const struct got_error *
5016 cancel_blame_view(void *arg)
5018 const struct got_error *err = NULL;
5019 int *done = arg;
5020 int errcode;
5022 errcode = pthread_mutex_lock(&tog_mutex);
5023 if (errcode)
5024 return got_error_set_errno(errcode,
5025 "pthread_mutex_unlock");
5027 if (*done)
5028 err = got_error(GOT_ERR_CANCELLED);
5030 errcode = pthread_mutex_unlock(&tog_mutex);
5031 if (errcode)
5032 return got_error_set_errno(errcode,
5033 "pthread_mutex_lock");
5035 return err;
5038 static const struct got_error *
5039 run_blame(struct tog_view *view)
5041 struct tog_blame_view_state *s = &view->state.blame;
5042 struct tog_blame *blame = &s->blame;
5043 const struct got_error *err = NULL;
5044 struct got_commit_object *commit = NULL;
5045 struct got_blob_object *blob = NULL;
5046 struct got_repository *thread_repo = NULL;
5047 struct got_object_id *obj_id = NULL;
5048 int obj_type, fd = -1;
5049 int *pack_fds = NULL;
5051 err = got_object_open_as_commit(&commit, s->repo,
5052 &s->blamed_commit->id);
5053 if (err)
5054 return err;
5056 fd = got_opentempfd();
5057 if (fd == -1) {
5058 err = got_error_from_errno("got_opentempfd");
5059 goto done;
5062 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5063 if (err)
5064 goto done;
5066 err = got_object_get_type(&obj_type, s->repo, obj_id);
5067 if (err)
5068 goto done;
5070 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5071 err = got_error(GOT_ERR_OBJ_TYPE);
5072 goto done;
5075 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5076 if (err)
5077 goto done;
5078 blame->f = got_opentemp();
5079 if (blame->f == NULL) {
5080 err = got_error_from_errno("got_opentemp");
5081 goto done;
5083 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5084 &blame->line_offsets, blame->f, blob);
5085 if (err)
5086 goto done;
5087 if (blame->nlines == 0) {
5088 s->blame_complete = 1;
5089 goto done;
5092 /* Don't include \n at EOF in the blame line count. */
5093 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5094 blame->nlines--;
5096 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5097 if (blame->lines == NULL) {
5098 err = got_error_from_errno("calloc");
5099 goto done;
5102 err = got_repo_pack_fds_open(&pack_fds);
5103 if (err)
5104 goto done;
5105 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5106 pack_fds);
5107 if (err)
5108 goto done;
5110 blame->pack_fds = pack_fds;
5111 blame->cb_args.view = view;
5112 blame->cb_args.lines = blame->lines;
5113 blame->cb_args.nlines = blame->nlines;
5114 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5115 if (blame->cb_args.commit_id == NULL) {
5116 err = got_error_from_errno("got_object_id_dup");
5117 goto done;
5119 blame->cb_args.quit = &s->done;
5121 blame->thread_args.path = s->path;
5122 blame->thread_args.repo = thread_repo;
5123 blame->thread_args.cb_args = &blame->cb_args;
5124 blame->thread_args.complete = &s->blame_complete;
5125 blame->thread_args.cancel_cb = cancel_blame_view;
5126 blame->thread_args.cancel_arg = &s->done;
5127 s->blame_complete = 0;
5129 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5130 s->first_displayed_line = 1;
5131 s->last_displayed_line = view->nlines;
5132 s->selected_line = 1;
5134 s->matched_line = 0;
5136 done:
5137 if (commit)
5138 got_object_commit_close(commit);
5139 if (fd != -1 && close(fd) == -1 && err == NULL)
5140 err = got_error_from_errno("close");
5141 if (blob)
5142 got_object_blob_close(blob);
5143 free(obj_id);
5144 if (err)
5145 stop_blame(blame);
5146 return err;
5149 static const struct got_error *
5150 open_blame_view(struct tog_view *view, char *path,
5151 struct got_object_id *commit_id, struct got_repository *repo)
5153 const struct got_error *err = NULL;
5154 struct tog_blame_view_state *s = &view->state.blame;
5156 STAILQ_INIT(&s->blamed_commits);
5158 s->path = strdup(path);
5159 if (s->path == NULL)
5160 return got_error_from_errno("strdup");
5162 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5163 if (err) {
5164 free(s->path);
5165 return err;
5168 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5169 s->first_displayed_line = 1;
5170 s->last_displayed_line = view->nlines;
5171 s->selected_line = 1;
5172 s->blame_complete = 0;
5173 s->repo = repo;
5174 s->commit_id = commit_id;
5175 memset(&s->blame, 0, sizeof(s->blame));
5177 STAILQ_INIT(&s->colors);
5178 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5179 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5180 get_color_value("TOG_COLOR_COMMIT"));
5181 if (err)
5182 return err;
5185 view->show = show_blame_view;
5186 view->input = input_blame_view;
5187 view->close = close_blame_view;
5188 view->search_start = search_start_blame_view;
5189 view->search_next = search_next_blame_view;
5191 return run_blame(view);
5194 static const struct got_error *
5195 close_blame_view(struct tog_view *view)
5197 const struct got_error *err = NULL;
5198 struct tog_blame_view_state *s = &view->state.blame;
5200 if (s->blame.thread)
5201 err = stop_blame(&s->blame);
5203 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5204 struct got_object_qid *blamed_commit;
5205 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5206 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5207 got_object_qid_free(blamed_commit);
5210 free(s->path);
5211 free_colors(&s->colors);
5212 return err;
5215 static const struct got_error *
5216 search_start_blame_view(struct tog_view *view)
5218 struct tog_blame_view_state *s = &view->state.blame;
5220 s->matched_line = 0;
5221 return NULL;
5224 static const struct got_error *
5225 search_next_blame_view(struct tog_view *view)
5227 struct tog_blame_view_state *s = &view->state.blame;
5228 const struct got_error *err = NULL;
5229 int lineno;
5230 char *line = NULL;
5231 size_t linesize = 0;
5232 ssize_t linelen;
5234 if (!view->searching) {
5235 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5236 return NULL;
5239 if (s->matched_line) {
5240 if (view->searching == TOG_SEARCH_FORWARD)
5241 lineno = s->matched_line + 1;
5242 else
5243 lineno = s->matched_line - 1;
5244 } else
5245 lineno = s->first_displayed_line - 1 + s->selected_line;
5247 while (1) {
5248 off_t offset;
5250 if (lineno <= 0 || lineno > s->blame.nlines) {
5251 if (s->matched_line == 0) {
5252 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5253 break;
5256 if (view->searching == TOG_SEARCH_FORWARD)
5257 lineno = 1;
5258 else
5259 lineno = s->blame.nlines;
5262 offset = s->blame.line_offsets[lineno - 1];
5263 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5264 free(line);
5265 return got_error_from_errno("fseeko");
5267 linelen = getline(&line, &linesize, s->blame.f);
5268 if (linelen != -1) {
5269 char *exstr;
5270 err = expand_tab(&exstr, line);
5271 if (err)
5272 break;
5273 if (match_line(exstr, &view->regex, 1,
5274 &view->regmatch)) {
5275 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5276 s->matched_line = lineno;
5277 free(exstr);
5278 break;
5280 free(exstr);
5282 if (view->searching == TOG_SEARCH_FORWARD)
5283 lineno++;
5284 else
5285 lineno--;
5287 free(line);
5289 if (s->matched_line) {
5290 s->first_displayed_line = s->matched_line;
5291 s->selected_line = 1;
5294 return err;
5297 static const struct got_error *
5298 show_blame_view(struct tog_view *view)
5300 const struct got_error *err = NULL;
5301 struct tog_blame_view_state *s = &view->state.blame;
5302 int errcode;
5304 if (s->blame.thread == NULL && !s->blame_complete) {
5305 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5306 &s->blame.thread_args);
5307 if (errcode)
5308 return got_error_set_errno(errcode, "pthread_create");
5310 halfdelay(1); /* fast refresh while annotating */
5313 if (s->blame_complete)
5314 halfdelay(10); /* disable fast refresh */
5316 err = draw_blame(view);
5318 view_border(view);
5319 return err;
5322 static const struct got_error *
5323 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5325 const struct got_error *err = NULL, *thread_err = NULL;
5326 struct tog_view *diff_view;
5327 struct tog_blame_view_state *s = &view->state.blame;
5328 int eos, nscroll, begin_y = 0, begin_x = 0;
5330 eos = nscroll = view->nlines - 2;
5331 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
5332 view_is_splitscreen(view->child))
5333 --eos; /* border */
5335 switch (ch) {
5336 case '0':
5337 view->x = 0;
5338 break;
5339 case '$':
5340 view->x = MAX(view->maxx - view->ncols / 3, 0);
5341 view->count = 0;
5342 break;
5343 case KEY_RIGHT:
5344 case 'l':
5345 if (view->x + view->ncols / 3 < view->maxx)
5346 view->x += 2; /* move two columns right */
5347 else
5348 view->count = 0;
5349 break;
5350 case KEY_LEFT:
5351 case 'h':
5352 view->x -= MIN(view->x, 2); /* move two columns back */
5353 if (view->x <= 0)
5354 view->count = 0;
5355 break;
5356 case 'q':
5357 s->done = 1;
5358 break;
5359 case 'g':
5360 case KEY_HOME:
5361 s->selected_line = 1;
5362 s->first_displayed_line = 1;
5363 view->count = 0;
5364 break;
5365 case 'G':
5366 case KEY_END:
5367 if (s->blame.nlines < eos) {
5368 s->selected_line = s->blame.nlines;
5369 s->first_displayed_line = 1;
5370 } else {
5371 s->selected_line = eos;
5372 s->first_displayed_line = s->blame.nlines - (eos - 1);
5374 view->count = 0;
5375 break;
5376 case 'k':
5377 case KEY_UP:
5378 case CTRL('p'):
5379 if (s->selected_line > 1)
5380 s->selected_line--;
5381 else if (s->selected_line == 1 &&
5382 s->first_displayed_line > 1)
5383 s->first_displayed_line--;
5384 else
5385 view->count = 0;
5386 break;
5387 case CTRL('u'):
5388 case 'u':
5389 nscroll /= 2;
5390 /* FALL THROUGH */
5391 case KEY_PPAGE:
5392 case CTRL('b'):
5393 case 'b':
5394 if (s->first_displayed_line == 1) {
5395 if (view->count > 1)
5396 nscroll += nscroll;
5397 s->selected_line = MAX(1, s->selected_line - nscroll);
5398 view->count = 0;
5399 break;
5401 if (s->first_displayed_line > nscroll)
5402 s->first_displayed_line -= nscroll;
5403 else
5404 s->first_displayed_line = 1;
5405 break;
5406 case 'j':
5407 case KEY_DOWN:
5408 case CTRL('n'):
5409 if (s->selected_line < eos && s->first_displayed_line +
5410 s->selected_line <= s->blame.nlines)
5411 s->selected_line++;
5412 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5413 s->first_displayed_line++;
5414 else
5415 view->count = 0;
5416 break;
5417 case 'c':
5418 case 'p': {
5419 struct got_object_id *id = NULL;
5421 view->count = 0;
5422 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5423 s->first_displayed_line, s->selected_line);
5424 if (id == NULL)
5425 break;
5426 if (ch == 'p') {
5427 struct got_commit_object *commit, *pcommit;
5428 struct got_object_qid *pid;
5429 struct got_object_id *blob_id = NULL;
5430 int obj_type;
5431 err = got_object_open_as_commit(&commit,
5432 s->repo, id);
5433 if (err)
5434 break;
5435 pid = STAILQ_FIRST(
5436 got_object_commit_get_parent_ids(commit));
5437 if (pid == NULL) {
5438 got_object_commit_close(commit);
5439 break;
5441 /* Check if path history ends here. */
5442 err = got_object_open_as_commit(&pcommit,
5443 s->repo, &pid->id);
5444 if (err)
5445 break;
5446 err = got_object_id_by_path(&blob_id, s->repo,
5447 pcommit, s->path);
5448 got_object_commit_close(pcommit);
5449 if (err) {
5450 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5451 err = NULL;
5452 got_object_commit_close(commit);
5453 break;
5455 err = got_object_get_type(&obj_type, s->repo,
5456 blob_id);
5457 free(blob_id);
5458 /* Can't blame non-blob type objects. */
5459 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5460 got_object_commit_close(commit);
5461 break;
5463 err = got_object_qid_alloc(&s->blamed_commit,
5464 &pid->id);
5465 got_object_commit_close(commit);
5466 } else {
5467 if (got_object_id_cmp(id,
5468 &s->blamed_commit->id) == 0)
5469 break;
5470 err = got_object_qid_alloc(&s->blamed_commit,
5471 id);
5473 if (err)
5474 break;
5475 s->done = 1;
5476 thread_err = stop_blame(&s->blame);
5477 s->done = 0;
5478 if (thread_err)
5479 break;
5480 STAILQ_INSERT_HEAD(&s->blamed_commits,
5481 s->blamed_commit, entry);
5482 err = run_blame(view);
5483 if (err)
5484 break;
5485 break;
5487 case 'C': {
5488 struct got_object_qid *first;
5490 view->count = 0;
5491 first = STAILQ_FIRST(&s->blamed_commits);
5492 if (!got_object_id_cmp(&first->id, s->commit_id))
5493 break;
5494 s->done = 1;
5495 thread_err = stop_blame(&s->blame);
5496 s->done = 0;
5497 if (thread_err)
5498 break;
5499 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5500 got_object_qid_free(s->blamed_commit);
5501 s->blamed_commit =
5502 STAILQ_FIRST(&s->blamed_commits);
5503 err = run_blame(view);
5504 if (err)
5505 break;
5506 break;
5508 case KEY_ENTER:
5509 case '\r': {
5510 struct got_object_id *id = NULL;
5511 struct got_object_qid *pid;
5512 struct got_commit_object *commit = NULL;
5514 view->count = 0;
5515 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5516 s->first_displayed_line, s->selected_line);
5517 if (id == NULL)
5518 break;
5519 err = got_object_open_as_commit(&commit, s->repo, id);
5520 if (err)
5521 break;
5522 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
5523 if (view_is_parent_view(view))
5524 view_get_split(view, &begin_y, &begin_x);
5526 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
5527 if (diff_view == NULL) {
5528 got_object_commit_close(commit);
5529 err = got_error_from_errno("view_open");
5530 break;
5532 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5533 id, NULL, NULL, 3, 0, 0, NULL, s->repo);
5534 got_object_commit_close(commit);
5535 if (err) {
5536 view_close(diff_view);
5537 break;
5539 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
5540 err = view_init_hsplit(view, begin_y);
5541 if (err)
5542 break;
5545 view->focussed = 0;
5546 diff_view->focussed = 1;
5547 diff_view->mode = view->mode;
5548 diff_view->nlines = view->lines - begin_y;
5549 if (view_is_parent_view(view)) {
5550 err = view_close_child(view);
5551 if (err)
5552 break;
5553 err = view_set_child(view, diff_view);
5554 if (err)
5555 break;
5556 view->focus_child = 1;
5557 } else
5558 *new_view = diff_view;
5559 if (err)
5560 break;
5561 break;
5563 case CTRL('d'):
5564 case 'd':
5565 nscroll /= 2;
5566 /* FALL THROUGH */
5567 case KEY_NPAGE:
5568 case CTRL('f'):
5569 case 'f':
5570 case ' ':
5571 if (s->last_displayed_line >= s->blame.nlines &&
5572 s->selected_line >= MIN(s->blame.nlines,
5573 view->nlines - 2)) {
5574 view->count = 0;
5575 break;
5577 if (s->last_displayed_line >= s->blame.nlines &&
5578 s->selected_line < view->nlines - 2) {
5579 s->selected_line +=
5580 MIN(nscroll, s->last_displayed_line -
5581 s->first_displayed_line - s->selected_line + 1);
5583 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5584 s->first_displayed_line += nscroll;
5585 else
5586 s->first_displayed_line =
5587 s->blame.nlines - (view->nlines - 3);
5588 break;
5589 case KEY_RESIZE:
5590 if (s->selected_line > view->nlines - 2) {
5591 s->selected_line = MIN(s->blame.nlines,
5592 view->nlines - 2);
5594 break;
5595 default:
5596 view->count = 0;
5597 break;
5599 return thread_err ? thread_err : err;
5602 static const struct got_error *
5603 cmd_blame(int argc, char *argv[])
5605 const struct got_error *error;
5606 struct got_repository *repo = NULL;
5607 struct got_worktree *worktree = NULL;
5608 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5609 char *link_target = NULL;
5610 struct got_object_id *commit_id = NULL;
5611 struct got_commit_object *commit = NULL;
5612 char *commit_id_str = NULL;
5613 int ch;
5614 struct tog_view *view;
5615 int *pack_fds = NULL;
5617 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5618 switch (ch) {
5619 case 'c':
5620 commit_id_str = optarg;
5621 break;
5622 case 'r':
5623 repo_path = realpath(optarg, NULL);
5624 if (repo_path == NULL)
5625 return got_error_from_errno2("realpath",
5626 optarg);
5627 break;
5628 default:
5629 usage_blame();
5630 /* NOTREACHED */
5634 argc -= optind;
5635 argv += optind;
5637 if (argc != 1)
5638 usage_blame();
5640 error = got_repo_pack_fds_open(&pack_fds);
5641 if (error != NULL)
5642 goto done;
5644 if (repo_path == NULL) {
5645 cwd = getcwd(NULL, 0);
5646 if (cwd == NULL)
5647 return got_error_from_errno("getcwd");
5648 error = got_worktree_open(&worktree, cwd);
5649 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5650 goto done;
5651 if (worktree)
5652 repo_path =
5653 strdup(got_worktree_get_repo_path(worktree));
5654 else
5655 repo_path = strdup(cwd);
5656 if (repo_path == NULL) {
5657 error = got_error_from_errno("strdup");
5658 goto done;
5662 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5663 if (error != NULL)
5664 goto done;
5666 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
5667 worktree);
5668 if (error)
5669 goto done;
5671 init_curses();
5673 error = apply_unveil(got_repo_get_path(repo), NULL);
5674 if (error)
5675 goto done;
5677 error = tog_load_refs(repo, 0);
5678 if (error)
5679 goto done;
5681 if (commit_id_str == NULL) {
5682 struct got_reference *head_ref;
5683 error = got_ref_open(&head_ref, repo, worktree ?
5684 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5685 if (error != NULL)
5686 goto done;
5687 error = got_ref_resolve(&commit_id, repo, head_ref);
5688 got_ref_close(head_ref);
5689 } else {
5690 error = got_repo_match_object_id(&commit_id, NULL,
5691 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
5693 if (error != NULL)
5694 goto done;
5696 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
5697 if (view == NULL) {
5698 error = got_error_from_errno("view_open");
5699 goto done;
5702 error = got_object_open_as_commit(&commit, repo, commit_id);
5703 if (error)
5704 goto done;
5706 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5707 commit, repo);
5708 if (error)
5709 goto done;
5711 error = open_blame_view(view, link_target ? link_target : in_repo_path,
5712 commit_id, repo);
5713 if (error)
5714 goto done;
5715 if (worktree) {
5716 /* Release work tree lock. */
5717 got_worktree_close(worktree);
5718 worktree = NULL;
5720 error = view_loop(view);
5721 done:
5722 free(repo_path);
5723 free(in_repo_path);
5724 free(link_target);
5725 free(cwd);
5726 free(commit_id);
5727 if (commit)
5728 got_object_commit_close(commit);
5729 if (worktree)
5730 got_worktree_close(worktree);
5731 if (repo) {
5732 const struct got_error *close_err = got_repo_close(repo);
5733 if (error == NULL)
5734 error = close_err;
5736 if (pack_fds) {
5737 const struct got_error *pack_err =
5738 got_repo_pack_fds_close(pack_fds);
5739 if (error == NULL)
5740 error = pack_err;
5742 tog_free_refs();
5743 return error;
5746 static const struct got_error *
5747 draw_tree_entries(struct tog_view *view, const char *parent_path)
5749 struct tog_tree_view_state *s = &view->state.tree;
5750 const struct got_error *err = NULL;
5751 struct got_tree_entry *te;
5752 wchar_t *wline;
5753 struct tog_color *tc;
5754 int width, n, i, nentries;
5755 int limit = view->nlines;
5757 s->ndisplayed = 0;
5758 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
5759 view_is_splitscreen(view->child))
5760 --limit; /* border */
5762 werase(view->window);
5764 if (limit == 0)
5765 return NULL;
5767 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
5768 0, 0);
5769 if (err)
5770 return err;
5771 if (view_needs_focus_indication(view))
5772 wstandout(view->window);
5773 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5774 if (tc)
5775 wattr_on(view->window,
5776 COLOR_PAIR(tc->colorpair), NULL);
5777 waddwstr(view->window, wline);
5778 if (tc)
5779 wattr_off(view->window,
5780 COLOR_PAIR(tc->colorpair), NULL);
5781 if (view_needs_focus_indication(view))
5782 wstandend(view->window);
5783 free(wline);
5784 wline = NULL;
5785 if (width < view->ncols - 1)
5786 waddch(view->window, '\n');
5787 if (--limit <= 0)
5788 return NULL;
5789 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
5790 0, 0);
5791 if (err)
5792 return err;
5793 waddwstr(view->window, wline);
5794 free(wline);
5795 wline = NULL;
5796 if (width < view->ncols - 1)
5797 waddch(view->window, '\n');
5798 if (--limit <= 0)
5799 return NULL;
5800 waddch(view->window, '\n');
5801 if (--limit <= 0)
5802 return NULL;
5804 if (s->first_displayed_entry == NULL) {
5805 te = got_object_tree_get_first_entry(s->tree);
5806 if (s->selected == 0) {
5807 if (view->focussed)
5808 wstandout(view->window);
5809 s->selected_entry = NULL;
5811 waddstr(view->window, " ..\n"); /* parent directory */
5812 if (s->selected == 0 && view->focussed)
5813 wstandend(view->window);
5814 s->ndisplayed++;
5815 if (--limit <= 0)
5816 return NULL;
5817 n = 1;
5818 } else {
5819 n = 0;
5820 te = s->first_displayed_entry;
5823 nentries = got_object_tree_get_nentries(s->tree);
5824 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
5825 char *line = NULL, *id_str = NULL, *link_target = NULL;
5826 const char *modestr = "";
5827 mode_t mode;
5829 te = got_object_tree_get_entry(s->tree, i);
5830 mode = got_tree_entry_get_mode(te);
5832 if (s->show_ids) {
5833 err = got_object_id_str(&id_str,
5834 got_tree_entry_get_id(te));
5835 if (err)
5836 return got_error_from_errno(
5837 "got_object_id_str");
5839 if (got_object_tree_entry_is_submodule(te))
5840 modestr = "$";
5841 else if (S_ISLNK(mode)) {
5842 int i;
5844 err = got_tree_entry_get_symlink_target(&link_target,
5845 te, s->repo);
5846 if (err) {
5847 free(id_str);
5848 return err;
5850 for (i = 0; i < strlen(link_target); i++) {
5851 if (!isprint((unsigned char)link_target[i]))
5852 link_target[i] = '?';
5854 modestr = "@";
5856 else if (S_ISDIR(mode))
5857 modestr = "/";
5858 else if (mode & S_IXUSR)
5859 modestr = "*";
5860 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
5861 got_tree_entry_get_name(te), modestr,
5862 link_target ? " -> ": "",
5863 link_target ? link_target : "") == -1) {
5864 free(id_str);
5865 free(link_target);
5866 return got_error_from_errno("asprintf");
5868 free(id_str);
5869 free(link_target);
5870 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
5871 0, 0);
5872 if (err) {
5873 free(line);
5874 break;
5876 if (n == s->selected) {
5877 if (view->focussed)
5878 wstandout(view->window);
5879 s->selected_entry = te;
5881 tc = match_color(&s->colors, line);
5882 if (tc)
5883 wattr_on(view->window,
5884 COLOR_PAIR(tc->colorpair), NULL);
5885 waddwstr(view->window, wline);
5886 if (tc)
5887 wattr_off(view->window,
5888 COLOR_PAIR(tc->colorpair), NULL);
5889 if (width < view->ncols - 1)
5890 waddch(view->window, '\n');
5891 if (n == s->selected && view->focussed)
5892 wstandend(view->window);
5893 free(line);
5894 free(wline);
5895 wline = NULL;
5896 n++;
5897 s->ndisplayed++;
5898 s->last_displayed_entry = te;
5899 if (--limit <= 0)
5900 break;
5903 return err;
5906 static void
5907 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
5909 struct got_tree_entry *te;
5910 int isroot = s->tree == s->root;
5911 int i = 0;
5913 if (s->first_displayed_entry == NULL)
5914 return;
5916 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
5917 while (i++ < maxscroll) {
5918 if (te == NULL) {
5919 if (!isroot)
5920 s->first_displayed_entry = NULL;
5921 break;
5923 s->first_displayed_entry = te;
5924 te = got_tree_entry_get_prev(s->tree, te);
5928 static const struct got_error *
5929 tree_scroll_down(struct tog_view *view, int maxscroll)
5931 struct tog_tree_view_state *s = &view->state.tree;
5932 struct got_tree_entry *next, *last;
5933 int n = 0;
5935 if (s->first_displayed_entry)
5936 next = got_tree_entry_get_next(s->tree,
5937 s->first_displayed_entry);
5938 else
5939 next = got_object_tree_get_first_entry(s->tree);
5941 last = s->last_displayed_entry;
5942 while (next && n++ < maxscroll) {
5943 if (last)
5944 last = got_tree_entry_get_next(s->tree, last);
5945 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
5946 s->first_displayed_entry = next;
5947 next = got_tree_entry_get_next(s->tree, next);
5951 return NULL;
5954 static const struct got_error *
5955 tree_entry_path(char **path, struct tog_parent_trees *parents,
5956 struct got_tree_entry *te)
5958 const struct got_error *err = NULL;
5959 struct tog_parent_tree *pt;
5960 size_t len = 2; /* for leading slash and NUL */
5962 TAILQ_FOREACH(pt, parents, entry)
5963 len += strlen(got_tree_entry_get_name(pt->selected_entry))
5964 + 1 /* slash */;
5965 if (te)
5966 len += strlen(got_tree_entry_get_name(te));
5968 *path = calloc(1, len);
5969 if (path == NULL)
5970 return got_error_from_errno("calloc");
5972 (*path)[0] = '/';
5973 pt = TAILQ_LAST(parents, tog_parent_trees);
5974 while (pt) {
5975 const char *name = got_tree_entry_get_name(pt->selected_entry);
5976 if (strlcat(*path, name, len) >= len) {
5977 err = got_error(GOT_ERR_NO_SPACE);
5978 goto done;
5980 if (strlcat(*path, "/", len) >= len) {
5981 err = got_error(GOT_ERR_NO_SPACE);
5982 goto done;
5984 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
5986 if (te) {
5987 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
5988 err = got_error(GOT_ERR_NO_SPACE);
5989 goto done;
5992 done:
5993 if (err) {
5994 free(*path);
5995 *path = NULL;
5997 return err;
6000 static const struct got_error *
6001 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6002 struct got_tree_entry *te, struct tog_parent_trees *parents,
6003 struct got_object_id *commit_id, struct got_repository *repo)
6005 const struct got_error *err = NULL;
6006 char *path;
6007 struct tog_view *blame_view;
6009 *new_view = NULL;
6011 err = tree_entry_path(&path, parents, te);
6012 if (err)
6013 return err;
6015 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6016 if (blame_view == NULL) {
6017 err = got_error_from_errno("view_open");
6018 goto done;
6021 err = open_blame_view(blame_view, path, commit_id, repo);
6022 if (err) {
6023 if (err->code == GOT_ERR_CANCELLED)
6024 err = NULL;
6025 view_close(blame_view);
6026 } else
6027 *new_view = blame_view;
6028 done:
6029 free(path);
6030 return err;
6033 static const struct got_error *
6034 log_selected_tree_entry(struct tog_view **new_view, int begin_x,
6035 struct tog_tree_view_state *s)
6037 struct tog_view *log_view;
6038 const struct got_error *err = NULL;
6039 char *path;
6041 *new_view = NULL;
6043 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
6044 if (log_view == NULL)
6045 return got_error_from_errno("view_open");
6047 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6048 if (err)
6049 return err;
6051 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6052 path, 0);
6053 if (err)
6054 view_close(log_view);
6055 else
6056 *new_view = log_view;
6057 free(path);
6058 return err;
6061 static const struct got_error *
6062 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6063 const char *head_ref_name, struct got_repository *repo)
6065 const struct got_error *err = NULL;
6066 char *commit_id_str = NULL;
6067 struct tog_tree_view_state *s = &view->state.tree;
6068 struct got_commit_object *commit = NULL;
6070 TAILQ_INIT(&s->parents);
6071 STAILQ_INIT(&s->colors);
6073 s->commit_id = got_object_id_dup(commit_id);
6074 if (s->commit_id == NULL)
6075 return got_error_from_errno("got_object_id_dup");
6077 err = got_object_open_as_commit(&commit, repo, commit_id);
6078 if (err)
6079 goto done;
6082 * The root is opened here and will be closed when the view is closed.
6083 * Any visited subtrees and their path-wise parents are opened and
6084 * closed on demand.
6086 err = got_object_open_as_tree(&s->root, repo,
6087 got_object_commit_get_tree_id(commit));
6088 if (err)
6089 goto done;
6090 s->tree = s->root;
6092 err = got_object_id_str(&commit_id_str, commit_id);
6093 if (err != NULL)
6094 goto done;
6096 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6097 err = got_error_from_errno("asprintf");
6098 goto done;
6101 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6102 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6103 if (head_ref_name) {
6104 s->head_ref_name = strdup(head_ref_name);
6105 if (s->head_ref_name == NULL) {
6106 err = got_error_from_errno("strdup");
6107 goto done;
6110 s->repo = repo;
6112 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6113 err = add_color(&s->colors, "\\$$",
6114 TOG_COLOR_TREE_SUBMODULE,
6115 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6116 if (err)
6117 goto done;
6118 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6119 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6120 if (err)
6121 goto done;
6122 err = add_color(&s->colors, "/$",
6123 TOG_COLOR_TREE_DIRECTORY,
6124 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6125 if (err)
6126 goto done;
6128 err = add_color(&s->colors, "\\*$",
6129 TOG_COLOR_TREE_EXECUTABLE,
6130 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6131 if (err)
6132 goto done;
6134 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6135 get_color_value("TOG_COLOR_COMMIT"));
6136 if (err)
6137 goto done;
6140 view->show = show_tree_view;
6141 view->input = input_tree_view;
6142 view->close = close_tree_view;
6143 view->search_start = search_start_tree_view;
6144 view->search_next = search_next_tree_view;
6145 done:
6146 free(commit_id_str);
6147 if (commit)
6148 got_object_commit_close(commit);
6149 if (err)
6150 close_tree_view(view);
6151 return err;
6154 static const struct got_error *
6155 close_tree_view(struct tog_view *view)
6157 struct tog_tree_view_state *s = &view->state.tree;
6159 free_colors(&s->colors);
6160 free(s->tree_label);
6161 s->tree_label = NULL;
6162 free(s->commit_id);
6163 s->commit_id = NULL;
6164 free(s->head_ref_name);
6165 s->head_ref_name = NULL;
6166 while (!TAILQ_EMPTY(&s->parents)) {
6167 struct tog_parent_tree *parent;
6168 parent = TAILQ_FIRST(&s->parents);
6169 TAILQ_REMOVE(&s->parents, parent, entry);
6170 if (parent->tree != s->root)
6171 got_object_tree_close(parent->tree);
6172 free(parent);
6175 if (s->tree != NULL && s->tree != s->root)
6176 got_object_tree_close(s->tree);
6177 if (s->root)
6178 got_object_tree_close(s->root);
6179 return NULL;
6182 static const struct got_error *
6183 search_start_tree_view(struct tog_view *view)
6185 struct tog_tree_view_state *s = &view->state.tree;
6187 s->matched_entry = NULL;
6188 return NULL;
6191 static int
6192 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6194 regmatch_t regmatch;
6196 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6197 0) == 0;
6200 static const struct got_error *
6201 search_next_tree_view(struct tog_view *view)
6203 struct tog_tree_view_state *s = &view->state.tree;
6204 struct got_tree_entry *te = NULL;
6206 if (!view->searching) {
6207 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6208 return NULL;
6211 if (s->matched_entry) {
6212 if (view->searching == TOG_SEARCH_FORWARD) {
6213 if (s->selected_entry)
6214 te = got_tree_entry_get_next(s->tree,
6215 s->selected_entry);
6216 else
6217 te = got_object_tree_get_first_entry(s->tree);
6218 } else {
6219 if (s->selected_entry == NULL)
6220 te = got_object_tree_get_last_entry(s->tree);
6221 else
6222 te = got_tree_entry_get_prev(s->tree,
6223 s->selected_entry);
6225 } else {
6226 if (s->selected_entry)
6227 te = s->selected_entry;
6228 else if (view->searching == TOG_SEARCH_FORWARD)
6229 te = got_object_tree_get_first_entry(s->tree);
6230 else
6231 te = got_object_tree_get_last_entry(s->tree);
6234 while (1) {
6235 if (te == NULL) {
6236 if (s->matched_entry == NULL) {
6237 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6238 return NULL;
6240 if (view->searching == TOG_SEARCH_FORWARD)
6241 te = got_object_tree_get_first_entry(s->tree);
6242 else
6243 te = got_object_tree_get_last_entry(s->tree);
6246 if (match_tree_entry(te, &view->regex)) {
6247 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6248 s->matched_entry = te;
6249 break;
6252 if (view->searching == TOG_SEARCH_FORWARD)
6253 te = got_tree_entry_get_next(s->tree, te);
6254 else
6255 te = got_tree_entry_get_prev(s->tree, te);
6258 if (s->matched_entry) {
6259 s->first_displayed_entry = s->matched_entry;
6260 s->selected = 0;
6263 return NULL;
6266 static const struct got_error *
6267 show_tree_view(struct tog_view *view)
6269 const struct got_error *err = NULL;
6270 struct tog_tree_view_state *s = &view->state.tree;
6271 char *parent_path;
6273 err = tree_entry_path(&parent_path, &s->parents, NULL);
6274 if (err)
6275 return err;
6277 err = draw_tree_entries(view, parent_path);
6278 free(parent_path);
6280 view_border(view);
6281 return err;
6284 static const struct got_error *
6285 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6287 const struct got_error *err = NULL;
6288 struct tog_tree_view_state *s = &view->state.tree;
6289 struct tog_view *log_view, *ref_view;
6290 struct got_tree_entry *te;
6291 int begin_x = 0, n, nscroll = view->nlines - 3;
6293 switch (ch) {
6294 case 'i':
6295 s->show_ids = !s->show_ids;
6296 view->count = 0;
6297 break;
6298 case 'l':
6299 view->count = 0;
6300 if (!s->selected_entry)
6301 break;
6302 if (view_is_parent_view(view))
6303 begin_x = view_split_begin_x(view->begin_x);
6304 err = log_selected_tree_entry(&log_view, begin_x, s);
6305 view->focussed = 0;
6306 log_view->focussed = 1;
6307 if (view_is_parent_view(view)) {
6308 err = view_close_child(view);
6309 if (err)
6310 return err;
6311 err = view_set_child(view, log_view);
6312 if (err)
6313 return err;
6314 view->focus_child = 1;
6315 } else
6316 *new_view = log_view;
6317 break;
6318 case 'r':
6319 view->count = 0;
6320 if (view_is_parent_view(view))
6321 begin_x = view_split_begin_x(view->begin_x);
6322 ref_view = view_open(view->nlines, view->ncols,
6323 view->begin_y, begin_x, TOG_VIEW_REF);
6324 if (ref_view == NULL)
6325 return got_error_from_errno("view_open");
6326 err = open_ref_view(ref_view, s->repo);
6327 if (err) {
6328 view_close(ref_view);
6329 return err;
6331 view->focussed = 0;
6332 ref_view->focussed = 1;
6333 if (view_is_parent_view(view)) {
6334 err = view_close_child(view);
6335 if (err)
6336 return err;
6337 err = view_set_child(view, ref_view);
6338 if (err)
6339 return err;
6340 view->focus_child = 1;
6341 } else
6342 *new_view = ref_view;
6343 break;
6344 case 'g':
6345 case KEY_HOME:
6346 s->selected = 0;
6347 view->count = 0;
6348 if (s->tree == s->root)
6349 s->first_displayed_entry =
6350 got_object_tree_get_first_entry(s->tree);
6351 else
6352 s->first_displayed_entry = NULL;
6353 break;
6354 case 'G':
6355 case KEY_END: {
6356 int eos = view->nlines - 3;
6358 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6359 --eos; /* border */
6360 s->selected = 0;
6361 view->count = 0;
6362 te = got_object_tree_get_last_entry(s->tree);
6363 for (n = 0; n < eos; n++) {
6364 if (te == NULL) {
6365 if(s->tree != s->root) {
6366 s->first_displayed_entry = NULL;
6367 n++;
6369 break;
6371 s->first_displayed_entry = te;
6372 te = got_tree_entry_get_prev(s->tree, te);
6374 if (n > 0)
6375 s->selected = n - 1;
6376 break;
6378 case 'k':
6379 case KEY_UP:
6380 case CTRL('p'):
6381 if (s->selected > 0) {
6382 s->selected--;
6383 break;
6385 tree_scroll_up(s, 1);
6386 if (s->selected_entry == NULL ||
6387 (s->tree == s->root && s->selected_entry ==
6388 got_object_tree_get_first_entry(s->tree)))
6389 view->count = 0;
6390 break;
6391 case CTRL('u'):
6392 case 'u':
6393 nscroll /= 2;
6394 /* FALL THROUGH */
6395 case KEY_PPAGE:
6396 case CTRL('b'):
6397 case 'b':
6398 if (s->tree == s->root) {
6399 if (got_object_tree_get_first_entry(s->tree) ==
6400 s->first_displayed_entry)
6401 s->selected -= MIN(s->selected, nscroll);
6402 } else {
6403 if (s->first_displayed_entry == NULL)
6404 s->selected -= MIN(s->selected, nscroll);
6406 tree_scroll_up(s, MAX(0, nscroll));
6407 if (s->selected_entry == NULL ||
6408 (s->tree == s->root && s->selected_entry ==
6409 got_object_tree_get_first_entry(s->tree)))
6410 view->count = 0;
6411 break;
6412 case 'j':
6413 case KEY_DOWN:
6414 case CTRL('n'):
6415 if (s->selected < s->ndisplayed - 1) {
6416 s->selected++;
6417 break;
6419 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6420 == NULL) {
6421 /* can't scroll any further */
6422 view->count = 0;
6423 break;
6425 tree_scroll_down(view, 1);
6426 break;
6427 case CTRL('d'):
6428 case 'd':
6429 nscroll /= 2;
6430 /* FALL THROUGH */
6431 case KEY_NPAGE:
6432 case CTRL('f'):
6433 case 'f':
6434 case ' ':
6435 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6436 == NULL) {
6437 /* can't scroll any further; move cursor down */
6438 if (s->selected < s->ndisplayed - 1)
6439 s->selected += MIN(nscroll,
6440 s->ndisplayed - s->selected - 1);
6441 else
6442 view->count = 0;
6443 break;
6445 tree_scroll_down(view, nscroll);
6446 break;
6447 case KEY_ENTER:
6448 case '\r':
6449 case KEY_BACKSPACE:
6450 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6451 struct tog_parent_tree *parent;
6452 /* user selected '..' */
6453 if (s->tree == s->root) {
6454 view->count = 0;
6455 break;
6457 parent = TAILQ_FIRST(&s->parents);
6458 TAILQ_REMOVE(&s->parents, parent,
6459 entry);
6460 got_object_tree_close(s->tree);
6461 s->tree = parent->tree;
6462 s->first_displayed_entry =
6463 parent->first_displayed_entry;
6464 s->selected_entry =
6465 parent->selected_entry;
6466 s->selected = parent->selected;
6467 if (s->selected > view->nlines - 3) {
6468 err = offset_selection_down(view);
6469 if (err)
6470 break;
6472 free(parent);
6473 } else if (S_ISDIR(got_tree_entry_get_mode(
6474 s->selected_entry))) {
6475 struct got_tree_object *subtree;
6476 view->count = 0;
6477 err = got_object_open_as_tree(&subtree, s->repo,
6478 got_tree_entry_get_id(s->selected_entry));
6479 if (err)
6480 break;
6481 err = tree_view_visit_subtree(s, subtree);
6482 if (err) {
6483 got_object_tree_close(subtree);
6484 break;
6486 } else if (S_ISREG(got_tree_entry_get_mode(
6487 s->selected_entry))) {
6488 struct tog_view *blame_view;
6489 int begin_x = 0, begin_y = 0;
6491 if (view_is_parent_view(view))
6492 view_get_split(view, &begin_y, &begin_x);
6494 err = blame_tree_entry(&blame_view, begin_y, begin_x,
6495 s->selected_entry, &s->parents,
6496 s->commit_id, s->repo);
6497 if (err)
6498 break;
6500 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
6501 err = view_init_hsplit(view, begin_y);
6502 if (err)
6503 break;
6506 view->count = 0;
6507 view->focussed = 0;
6508 blame_view->focussed = 1;
6509 blame_view->mode = view->mode;
6510 blame_view->nlines = view->lines - begin_y;
6511 if (view_is_parent_view(view)) {
6512 err = view_close_child(view);
6513 if (err)
6514 return err;
6515 err = view_set_child(view, blame_view);
6516 if (err)
6517 return err;
6518 view->focus_child = 1;
6519 } else
6520 *new_view = blame_view;
6522 break;
6523 case KEY_RESIZE:
6524 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6525 s->selected = view->nlines - 4;
6526 view->count = 0;
6527 break;
6528 default:
6529 view->count = 0;
6530 break;
6533 return err;
6536 __dead static void
6537 usage_tree(void)
6539 endwin();
6540 fprintf(stderr,
6541 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6542 getprogname());
6543 exit(1);
6546 static const struct got_error *
6547 cmd_tree(int argc, char *argv[])
6549 const struct got_error *error;
6550 struct got_repository *repo = NULL;
6551 struct got_worktree *worktree = NULL;
6552 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6553 struct got_object_id *commit_id = NULL;
6554 struct got_commit_object *commit = NULL;
6555 const char *commit_id_arg = NULL;
6556 char *label = NULL;
6557 struct got_reference *ref = NULL;
6558 const char *head_ref_name = NULL;
6559 int ch;
6560 struct tog_view *view;
6561 int *pack_fds = NULL;
6563 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6564 switch (ch) {
6565 case 'c':
6566 commit_id_arg = optarg;
6567 break;
6568 case 'r':
6569 repo_path = realpath(optarg, NULL);
6570 if (repo_path == NULL)
6571 return got_error_from_errno2("realpath",
6572 optarg);
6573 break;
6574 default:
6575 usage_tree();
6576 /* NOTREACHED */
6580 argc -= optind;
6581 argv += optind;
6583 if (argc > 1)
6584 usage_tree();
6586 error = got_repo_pack_fds_open(&pack_fds);
6587 if (error != NULL)
6588 goto done;
6590 if (repo_path == NULL) {
6591 cwd = getcwd(NULL, 0);
6592 if (cwd == NULL)
6593 return got_error_from_errno("getcwd");
6594 error = got_worktree_open(&worktree, cwd);
6595 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6596 goto done;
6597 if (worktree)
6598 repo_path =
6599 strdup(got_worktree_get_repo_path(worktree));
6600 else
6601 repo_path = strdup(cwd);
6602 if (repo_path == NULL) {
6603 error = got_error_from_errno("strdup");
6604 goto done;
6608 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6609 if (error != NULL)
6610 goto done;
6612 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
6613 repo, worktree);
6614 if (error)
6615 goto done;
6617 init_curses();
6619 error = apply_unveil(got_repo_get_path(repo), NULL);
6620 if (error)
6621 goto done;
6623 error = tog_load_refs(repo, 0);
6624 if (error)
6625 goto done;
6627 if (commit_id_arg == NULL) {
6628 error = got_repo_match_object_id(&commit_id, &label,
6629 worktree ? got_worktree_get_head_ref_name(worktree) :
6630 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6631 if (error)
6632 goto done;
6633 head_ref_name = label;
6634 } else {
6635 error = got_ref_open(&ref, repo, commit_id_arg, 0);
6636 if (error == NULL)
6637 head_ref_name = got_ref_get_name(ref);
6638 else if (error->code != GOT_ERR_NOT_REF)
6639 goto done;
6640 error = got_repo_match_object_id(&commit_id, NULL,
6641 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6642 if (error)
6643 goto done;
6646 error = got_object_open_as_commit(&commit, repo, commit_id);
6647 if (error)
6648 goto done;
6650 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
6651 if (view == NULL) {
6652 error = got_error_from_errno("view_open");
6653 goto done;
6655 error = open_tree_view(view, commit_id, head_ref_name, repo);
6656 if (error)
6657 goto done;
6658 if (!got_path_is_root_dir(in_repo_path)) {
6659 error = tree_view_walk_path(&view->state.tree, commit,
6660 in_repo_path);
6661 if (error)
6662 goto done;
6665 if (worktree) {
6666 /* Release work tree lock. */
6667 got_worktree_close(worktree);
6668 worktree = NULL;
6670 error = view_loop(view);
6671 done:
6672 free(repo_path);
6673 free(cwd);
6674 free(commit_id);
6675 free(label);
6676 if (ref)
6677 got_ref_close(ref);
6678 if (repo) {
6679 const struct got_error *close_err = got_repo_close(repo);
6680 if (error == NULL)
6681 error = close_err;
6683 if (pack_fds) {
6684 const struct got_error *pack_err =
6685 got_repo_pack_fds_close(pack_fds);
6686 if (error == NULL)
6687 error = pack_err;
6689 tog_free_refs();
6690 return error;
6693 static const struct got_error *
6694 ref_view_load_refs(struct tog_ref_view_state *s)
6696 struct got_reflist_entry *sre;
6697 struct tog_reflist_entry *re;
6699 s->nrefs = 0;
6700 TAILQ_FOREACH(sre, &tog_refs, entry) {
6701 if (strncmp(got_ref_get_name(sre->ref),
6702 "refs/got/", 9) == 0 &&
6703 strncmp(got_ref_get_name(sre->ref),
6704 "refs/got/backup/", 16) != 0)
6705 continue;
6707 re = malloc(sizeof(*re));
6708 if (re == NULL)
6709 return got_error_from_errno("malloc");
6711 re->ref = got_ref_dup(sre->ref);
6712 if (re->ref == NULL)
6713 return got_error_from_errno("got_ref_dup");
6714 re->idx = s->nrefs++;
6715 TAILQ_INSERT_TAIL(&s->refs, re, entry);
6718 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6719 return NULL;
6722 static void
6723 ref_view_free_refs(struct tog_ref_view_state *s)
6725 struct tog_reflist_entry *re;
6727 while (!TAILQ_EMPTY(&s->refs)) {
6728 re = TAILQ_FIRST(&s->refs);
6729 TAILQ_REMOVE(&s->refs, re, entry);
6730 got_ref_close(re->ref);
6731 free(re);
6735 static const struct got_error *
6736 open_ref_view(struct tog_view *view, struct got_repository *repo)
6738 const struct got_error *err = NULL;
6739 struct tog_ref_view_state *s = &view->state.ref;
6741 s->selected_entry = 0;
6742 s->repo = repo;
6744 TAILQ_INIT(&s->refs);
6745 STAILQ_INIT(&s->colors);
6747 err = ref_view_load_refs(s);
6748 if (err)
6749 return err;
6751 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6752 err = add_color(&s->colors, "^refs/heads/",
6753 TOG_COLOR_REFS_HEADS,
6754 get_color_value("TOG_COLOR_REFS_HEADS"));
6755 if (err)
6756 goto done;
6758 err = add_color(&s->colors, "^refs/tags/",
6759 TOG_COLOR_REFS_TAGS,
6760 get_color_value("TOG_COLOR_REFS_TAGS"));
6761 if (err)
6762 goto done;
6764 err = add_color(&s->colors, "^refs/remotes/",
6765 TOG_COLOR_REFS_REMOTES,
6766 get_color_value("TOG_COLOR_REFS_REMOTES"));
6767 if (err)
6768 goto done;
6770 err = add_color(&s->colors, "^refs/got/backup/",
6771 TOG_COLOR_REFS_BACKUP,
6772 get_color_value("TOG_COLOR_REFS_BACKUP"));
6773 if (err)
6774 goto done;
6777 view->show = show_ref_view;
6778 view->input = input_ref_view;
6779 view->close = close_ref_view;
6780 view->search_start = search_start_ref_view;
6781 view->search_next = search_next_ref_view;
6782 done:
6783 if (err)
6784 free_colors(&s->colors);
6785 return err;
6788 static const struct got_error *
6789 close_ref_view(struct tog_view *view)
6791 struct tog_ref_view_state *s = &view->state.ref;
6793 ref_view_free_refs(s);
6794 free_colors(&s->colors);
6796 return NULL;
6799 static const struct got_error *
6800 resolve_reflist_entry(struct got_object_id **commit_id,
6801 struct tog_reflist_entry *re, struct got_repository *repo)
6803 const struct got_error *err = NULL;
6804 struct got_object_id *obj_id;
6805 struct got_tag_object *tag = NULL;
6806 int obj_type;
6808 *commit_id = NULL;
6810 err = got_ref_resolve(&obj_id, repo, re->ref);
6811 if (err)
6812 return err;
6814 err = got_object_get_type(&obj_type, repo, obj_id);
6815 if (err)
6816 goto done;
6818 switch (obj_type) {
6819 case GOT_OBJ_TYPE_COMMIT:
6820 *commit_id = obj_id;
6821 break;
6822 case GOT_OBJ_TYPE_TAG:
6823 err = got_object_open_as_tag(&tag, repo, obj_id);
6824 if (err)
6825 goto done;
6826 free(obj_id);
6827 err = got_object_get_type(&obj_type, repo,
6828 got_object_tag_get_object_id(tag));
6829 if (err)
6830 goto done;
6831 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
6832 err = got_error(GOT_ERR_OBJ_TYPE);
6833 goto done;
6835 *commit_id = got_object_id_dup(
6836 got_object_tag_get_object_id(tag));
6837 if (*commit_id == NULL) {
6838 err = got_error_from_errno("got_object_id_dup");
6839 goto done;
6841 break;
6842 default:
6843 err = got_error(GOT_ERR_OBJ_TYPE);
6844 break;
6847 done:
6848 if (tag)
6849 got_object_tag_close(tag);
6850 if (err) {
6851 free(*commit_id);
6852 *commit_id = NULL;
6854 return err;
6857 static const struct got_error *
6858 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
6859 struct tog_reflist_entry *re, struct got_repository *repo)
6861 struct tog_view *log_view;
6862 const struct got_error *err = NULL;
6863 struct got_object_id *commit_id = NULL;
6865 *new_view = NULL;
6867 err = resolve_reflist_entry(&commit_id, re, repo);
6868 if (err) {
6869 if (err->code != GOT_ERR_OBJ_TYPE)
6870 return err;
6871 else
6872 return NULL;
6875 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6876 if (log_view == NULL) {
6877 err = got_error_from_errno("view_open");
6878 goto done;
6881 err = open_log_view(log_view, commit_id, repo,
6882 got_ref_get_name(re->ref), "", 0);
6883 done:
6884 if (err)
6885 view_close(log_view);
6886 else
6887 *new_view = log_view;
6888 free(commit_id);
6889 return err;
6892 static void
6893 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
6895 struct tog_reflist_entry *re;
6896 int i = 0;
6898 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
6899 return;
6901 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
6902 while (i++ < maxscroll) {
6903 if (re == NULL)
6904 break;
6905 s->first_displayed_entry = re;
6906 re = TAILQ_PREV(re, tog_reflist_head, entry);
6910 static const struct got_error *
6911 ref_scroll_down(struct tog_view *view, int maxscroll)
6913 struct tog_ref_view_state *s = &view->state.ref;
6914 struct tog_reflist_entry *next, *last;
6915 int n = 0;
6917 if (s->first_displayed_entry)
6918 next = TAILQ_NEXT(s->first_displayed_entry, entry);
6919 else
6920 next = TAILQ_FIRST(&s->refs);
6922 last = s->last_displayed_entry;
6923 while (next && n++ < maxscroll) {
6924 if (last)
6925 last = TAILQ_NEXT(last, entry);
6926 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
6927 s->first_displayed_entry = next;
6928 next = TAILQ_NEXT(next, entry);
6932 return NULL;
6935 static const struct got_error *
6936 search_start_ref_view(struct tog_view *view)
6938 struct tog_ref_view_state *s = &view->state.ref;
6940 s->matched_entry = NULL;
6941 return NULL;
6944 static int
6945 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
6947 regmatch_t regmatch;
6949 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
6950 0) == 0;
6953 static const struct got_error *
6954 search_next_ref_view(struct tog_view *view)
6956 struct tog_ref_view_state *s = &view->state.ref;
6957 struct tog_reflist_entry *re = NULL;
6959 if (!view->searching) {
6960 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6961 return NULL;
6964 if (s->matched_entry) {
6965 if (view->searching == TOG_SEARCH_FORWARD) {
6966 if (s->selected_entry)
6967 re = TAILQ_NEXT(s->selected_entry, entry);
6968 else
6969 re = TAILQ_PREV(s->selected_entry,
6970 tog_reflist_head, entry);
6971 } else {
6972 if (s->selected_entry == NULL)
6973 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6974 else
6975 re = TAILQ_PREV(s->selected_entry,
6976 tog_reflist_head, entry);
6978 } else {
6979 if (s->selected_entry)
6980 re = s->selected_entry;
6981 else if (view->searching == TOG_SEARCH_FORWARD)
6982 re = TAILQ_FIRST(&s->refs);
6983 else
6984 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6987 while (1) {
6988 if (re == NULL) {
6989 if (s->matched_entry == NULL) {
6990 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6991 return NULL;
6993 if (view->searching == TOG_SEARCH_FORWARD)
6994 re = TAILQ_FIRST(&s->refs);
6995 else
6996 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6999 if (match_reflist_entry(re, &view->regex)) {
7000 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7001 s->matched_entry = re;
7002 break;
7005 if (view->searching == TOG_SEARCH_FORWARD)
7006 re = TAILQ_NEXT(re, entry);
7007 else
7008 re = TAILQ_PREV(re, tog_reflist_head, entry);
7011 if (s->matched_entry) {
7012 s->first_displayed_entry = s->matched_entry;
7013 s->selected = 0;
7016 return NULL;
7019 static const struct got_error *
7020 show_ref_view(struct tog_view *view)
7022 const struct got_error *err = NULL;
7023 struct tog_ref_view_state *s = &view->state.ref;
7024 struct tog_reflist_entry *re;
7025 char *line = NULL;
7026 wchar_t *wline;
7027 struct tog_color *tc;
7028 int width, n;
7029 int limit = view->nlines;
7031 werase(view->window);
7033 s->ndisplayed = 0;
7034 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
7035 view_is_splitscreen(view->child))
7036 --limit; /* border */
7038 if (limit == 0)
7039 return NULL;
7041 re = s->first_displayed_entry;
7043 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7044 s->nrefs) == -1)
7045 return got_error_from_errno("asprintf");
7047 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7048 if (err) {
7049 free(line);
7050 return err;
7052 if (view_needs_focus_indication(view))
7053 wstandout(view->window);
7054 waddwstr(view->window, wline);
7055 if (view_needs_focus_indication(view))
7056 wstandend(view->window);
7057 free(wline);
7058 wline = NULL;
7059 free(line);
7060 line = NULL;
7061 if (width < view->ncols - 1)
7062 waddch(view->window, '\n');
7063 if (--limit <= 0)
7064 return NULL;
7066 n = 0;
7067 while (re && limit > 0) {
7068 char *line = NULL;
7069 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7071 if (s->show_date) {
7072 struct got_commit_object *ci;
7073 struct got_tag_object *tag;
7074 struct got_object_id *id;
7075 struct tm tm;
7076 time_t t;
7078 err = got_ref_resolve(&id, s->repo, re->ref);
7079 if (err)
7080 return err;
7081 err = got_object_open_as_tag(&tag, s->repo, id);
7082 if (err) {
7083 if (err->code != GOT_ERR_OBJ_TYPE) {
7084 free(id);
7085 return err;
7087 err = got_object_open_as_commit(&ci, s->repo,
7088 id);
7089 if (err) {
7090 free(id);
7091 return err;
7093 t = got_object_commit_get_committer_time(ci);
7094 got_object_commit_close(ci);
7095 } else {
7096 t = got_object_tag_get_tagger_time(tag);
7097 got_object_tag_close(tag);
7099 free(id);
7100 if (gmtime_r(&t, &tm) == NULL)
7101 return got_error_from_errno("gmtime_r");
7102 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7103 return got_error(GOT_ERR_NO_SPACE);
7105 if (got_ref_is_symbolic(re->ref)) {
7106 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7107 ymd : "", got_ref_get_name(re->ref),
7108 got_ref_get_symref_target(re->ref)) == -1)
7109 return got_error_from_errno("asprintf");
7110 } else if (s->show_ids) {
7111 struct got_object_id *id;
7112 char *id_str;
7113 err = got_ref_resolve(&id, s->repo, re->ref);
7114 if (err)
7115 return err;
7116 err = got_object_id_str(&id_str, id);
7117 if (err) {
7118 free(id);
7119 return err;
7121 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7122 got_ref_get_name(re->ref), id_str) == -1) {
7123 err = got_error_from_errno("asprintf");
7124 free(id);
7125 free(id_str);
7126 return err;
7128 free(id);
7129 free(id_str);
7130 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7131 got_ref_get_name(re->ref)) == -1)
7132 return got_error_from_errno("asprintf");
7134 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7135 0, 0);
7136 if (err) {
7137 free(line);
7138 return err;
7140 if (n == s->selected) {
7141 if (view->focussed)
7142 wstandout(view->window);
7143 s->selected_entry = re;
7145 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7146 if (tc)
7147 wattr_on(view->window,
7148 COLOR_PAIR(tc->colorpair), NULL);
7149 waddwstr(view->window, wline);
7150 if (tc)
7151 wattr_off(view->window,
7152 COLOR_PAIR(tc->colorpair), NULL);
7153 if (width < view->ncols - 1)
7154 waddch(view->window, '\n');
7155 if (n == s->selected && view->focussed)
7156 wstandend(view->window);
7157 free(line);
7158 free(wline);
7159 wline = NULL;
7160 n++;
7161 s->ndisplayed++;
7162 s->last_displayed_entry = re;
7164 limit--;
7165 re = TAILQ_NEXT(re, entry);
7168 view_border(view);
7169 return err;
7172 static const struct got_error *
7173 browse_ref_tree(struct tog_view **new_view, int begin_x,
7174 struct tog_reflist_entry *re, struct got_repository *repo)
7176 const struct got_error *err = NULL;
7177 struct got_object_id *commit_id = NULL;
7178 struct tog_view *tree_view;
7180 *new_view = NULL;
7182 err = resolve_reflist_entry(&commit_id, re, repo);
7183 if (err) {
7184 if (err->code != GOT_ERR_OBJ_TYPE)
7185 return err;
7186 else
7187 return NULL;
7191 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
7192 if (tree_view == NULL) {
7193 err = got_error_from_errno("view_open");
7194 goto done;
7197 err = open_tree_view(tree_view, commit_id,
7198 got_ref_get_name(re->ref), repo);
7199 if (err)
7200 goto done;
7202 *new_view = tree_view;
7203 done:
7204 free(commit_id);
7205 return err;
7207 static const struct got_error *
7208 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7210 const struct got_error *err = NULL;
7211 struct tog_ref_view_state *s = &view->state.ref;
7212 struct tog_view *log_view, *tree_view;
7213 struct tog_reflist_entry *re;
7214 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 1;
7216 switch (ch) {
7217 case 'i':
7218 s->show_ids = !s->show_ids;
7219 view->count = 0;
7220 break;
7221 case 'm':
7222 s->show_date = !s->show_date;
7223 view->count = 0;
7224 break;
7225 case 'o':
7226 s->sort_by_date = !s->sort_by_date;
7227 view->count = 0;
7228 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7229 got_ref_cmp_by_commit_timestamp_descending :
7230 tog_ref_cmp_by_name, s->repo);
7231 if (err)
7232 break;
7233 got_reflist_object_id_map_free(tog_refs_idmap);
7234 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7235 &tog_refs, s->repo);
7236 if (err)
7237 break;
7238 ref_view_free_refs(s);
7239 err = ref_view_load_refs(s);
7240 break;
7241 case KEY_ENTER:
7242 case '\r':
7243 view->count = 0;
7244 if (!s->selected_entry)
7245 break;
7246 if (view_is_parent_view(view))
7247 view_get_split(view, &begin_y, &begin_x);
7249 err = log_ref_entry(&log_view, begin_y, begin_x,
7250 s->selected_entry, s->repo);
7251 if (err)
7252 break;
7254 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
7255 err = view_init_hsplit(view, begin_y);
7256 if (err)
7257 break;
7260 view->focussed = 0;
7261 log_view->focussed = 1;
7262 log_view->mode = view->mode;
7263 log_view->nlines = view->lines - begin_y;
7264 if (view_is_parent_view(view)) {
7265 err = view_close_child(view);
7266 if (err)
7267 return err;
7268 err = view_set_child(view, log_view);
7269 if (err)
7270 return err;
7271 view->focus_child = 1;
7272 } else
7273 *new_view = log_view;
7274 break;
7275 case 't':
7276 view->count = 0;
7277 if (!s->selected_entry)
7278 break;
7279 if (view_is_parent_view(view))
7280 begin_x = view_split_begin_x(view->begin_x);
7281 err = browse_ref_tree(&tree_view, begin_x, s->selected_entry,
7282 s->repo);
7283 if (err || tree_view == NULL)
7284 break;
7285 view->focussed = 0;
7286 tree_view->focussed = 1;
7287 if (view_is_parent_view(view)) {
7288 err = view_close_child(view);
7289 if (err)
7290 return err;
7291 err = view_set_child(view, tree_view);
7292 if (err)
7293 return err;
7294 view->focus_child = 1;
7295 } else
7296 *new_view = tree_view;
7297 break;
7298 case 'g':
7299 case KEY_HOME:
7300 s->selected = 0;
7301 view->count = 0;
7302 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7303 break;
7304 case 'G':
7305 case KEY_END: {
7306 int eos = view->nlines - 1;
7308 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7309 --eos; /* border */
7310 s->selected = 0;
7311 view->count = 0;
7312 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7313 for (n = 0; n < eos; n++) {
7314 if (re == NULL)
7315 break;
7316 s->first_displayed_entry = re;
7317 re = TAILQ_PREV(re, tog_reflist_head, entry);
7319 if (n > 0)
7320 s->selected = n - 1;
7321 break;
7323 case 'k':
7324 case KEY_UP:
7325 case CTRL('p'):
7326 if (s->selected > 0) {
7327 s->selected--;
7328 break;
7330 ref_scroll_up(s, 1);
7331 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7332 view->count = 0;
7333 break;
7334 case CTRL('u'):
7335 case 'u':
7336 nscroll /= 2;
7337 /* FALL THROUGH */
7338 case KEY_PPAGE:
7339 case CTRL('b'):
7340 case 'b':
7341 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7342 s->selected -= MIN(nscroll, s->selected);
7343 ref_scroll_up(s, MAX(0, nscroll));
7344 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7345 view->count = 0;
7346 break;
7347 case 'j':
7348 case KEY_DOWN:
7349 case CTRL('n'):
7350 if (s->selected < s->ndisplayed - 1) {
7351 s->selected++;
7352 break;
7354 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7355 /* can't scroll any further */
7356 view->count = 0;
7357 break;
7359 ref_scroll_down(view, 1);
7360 break;
7361 case CTRL('d'):
7362 case 'd':
7363 nscroll /= 2;
7364 /* FALL THROUGH */
7365 case KEY_NPAGE:
7366 case CTRL('f'):
7367 case 'f':
7368 case ' ':
7369 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7370 /* can't scroll any further; move cursor down */
7371 if (s->selected < s->ndisplayed - 1)
7372 s->selected += MIN(nscroll,
7373 s->ndisplayed - s->selected - 1);
7374 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7375 s->selected += s->ndisplayed - s->selected - 1;
7376 view->count = 0;
7377 break;
7379 ref_scroll_down(view, nscroll);
7380 break;
7381 case CTRL('l'):
7382 view->count = 0;
7383 tog_free_refs();
7384 err = tog_load_refs(s->repo, s->sort_by_date);
7385 if (err)
7386 break;
7387 ref_view_free_refs(s);
7388 err = ref_view_load_refs(s);
7389 break;
7390 case KEY_RESIZE:
7391 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7392 s->selected = view->nlines - 2;
7393 break;
7394 default:
7395 view->count = 0;
7396 break;
7399 return err;
7402 __dead static void
7403 usage_ref(void)
7405 endwin();
7406 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7407 getprogname());
7408 exit(1);
7411 static const struct got_error *
7412 cmd_ref(int argc, char *argv[])
7414 const struct got_error *error;
7415 struct got_repository *repo = NULL;
7416 struct got_worktree *worktree = NULL;
7417 char *cwd = NULL, *repo_path = NULL;
7418 int ch;
7419 struct tog_view *view;
7420 int *pack_fds = NULL;
7422 while ((ch = getopt(argc, argv, "r:")) != -1) {
7423 switch (ch) {
7424 case 'r':
7425 repo_path = realpath(optarg, NULL);
7426 if (repo_path == NULL)
7427 return got_error_from_errno2("realpath",
7428 optarg);
7429 break;
7430 default:
7431 usage_ref();
7432 /* NOTREACHED */
7436 argc -= optind;
7437 argv += optind;
7439 if (argc > 1)
7440 usage_ref();
7442 error = got_repo_pack_fds_open(&pack_fds);
7443 if (error != NULL)
7444 goto done;
7446 if (repo_path == NULL) {
7447 cwd = getcwd(NULL, 0);
7448 if (cwd == NULL)
7449 return got_error_from_errno("getcwd");
7450 error = got_worktree_open(&worktree, cwd);
7451 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7452 goto done;
7453 if (worktree)
7454 repo_path =
7455 strdup(got_worktree_get_repo_path(worktree));
7456 else
7457 repo_path = strdup(cwd);
7458 if (repo_path == NULL) {
7459 error = got_error_from_errno("strdup");
7460 goto done;
7464 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7465 if (error != NULL)
7466 goto done;
7468 init_curses();
7470 error = apply_unveil(got_repo_get_path(repo), NULL);
7471 if (error)
7472 goto done;
7474 error = tog_load_refs(repo, 0);
7475 if (error)
7476 goto done;
7478 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7479 if (view == NULL) {
7480 error = got_error_from_errno("view_open");
7481 goto done;
7484 error = open_ref_view(view, repo);
7485 if (error)
7486 goto done;
7488 if (worktree) {
7489 /* Release work tree lock. */
7490 got_worktree_close(worktree);
7491 worktree = NULL;
7493 error = view_loop(view);
7494 done:
7495 free(repo_path);
7496 free(cwd);
7497 if (repo) {
7498 const struct got_error *close_err = got_repo_close(repo);
7499 if (close_err)
7500 error = close_err;
7502 if (pack_fds) {
7503 const struct got_error *pack_err =
7504 got_repo_pack_fds_close(pack_fds);
7505 if (error == NULL)
7506 error = pack_err;
7508 tog_free_refs();
7509 return error;
7513 * If view was scrolled down to move the selected line into view when opening a
7514 * horizontal split, scroll back up when closing the split/toggling fullscreen.
7516 static void
7517 offset_selection_up(struct tog_view *view)
7519 switch (view->type) {
7520 case TOG_VIEW_BLAME: {
7521 struct tog_blame_view_state *s = &view->state.blame;
7522 if (s->first_displayed_line == 1) {
7523 s->selected_line = MAX(s->selected_line - view->offset,
7524 1);
7525 break;
7527 if (s->first_displayed_line > view->offset)
7528 s->first_displayed_line -= view->offset;
7529 else
7530 s->first_displayed_line = 1;
7531 s->selected_line += view->offset;
7532 break;
7534 case TOG_VIEW_LOG:
7535 log_scroll_up(&view->state.log, view->offset);
7536 view->state.log.selected += view->offset;
7537 break;
7538 case TOG_VIEW_REF:
7539 ref_scroll_up(&view->state.ref, view->offset);
7540 view->state.ref.selected += view->offset;
7541 break;
7542 case TOG_VIEW_TREE:
7543 tree_scroll_up(&view->state.tree, view->offset);
7544 view->state.tree.selected += view->offset;
7545 break;
7546 default:
7547 break;
7550 view->offset = 0;
7554 * If the selected line is in the section of screen covered by the bottom split,
7555 * scroll down offset lines to move it into view and index its new position.
7557 static const struct got_error *
7558 offset_selection_down(struct tog_view *view)
7560 const struct got_error *err = NULL;
7561 const struct got_error *(*scrolld)(struct tog_view *, int);
7562 int *selected = NULL;
7563 int header, offset;
7565 switch (view->type) {
7566 case TOG_VIEW_BLAME: {
7567 struct tog_blame_view_state *s = &view->state.blame;
7568 header = 3;
7569 scrolld = NULL;
7570 if (s->selected_line > view->nlines - header) {
7571 offset = abs(view->nlines - s->selected_line - header);
7572 s->first_displayed_line += offset;
7573 s->selected_line -= offset;
7574 view->offset = offset;
7576 break;
7578 case TOG_VIEW_LOG: {
7579 struct tog_log_view_state *s = &view->state.log;
7580 scrolld = &log_scroll_down;
7581 header = 3;
7582 selected = &s->selected;
7583 break;
7585 case TOG_VIEW_REF: {
7586 struct tog_ref_view_state *s = &view->state.ref;
7587 scrolld = &ref_scroll_down;
7588 header = 3;
7589 selected = &s->selected;
7590 break;
7592 case TOG_VIEW_TREE: {
7593 struct tog_tree_view_state *s = &view->state.tree;
7594 scrolld = &tree_scroll_down;
7595 header = 5;
7596 selected = &s->selected;
7597 break;
7599 default:
7600 selected = NULL;
7601 scrolld = NULL;
7602 header = 0;
7603 break;
7606 if (selected && *selected > view->nlines - header) {
7607 offset = abs(view->nlines - *selected - header);
7608 view->offset = offset;
7609 if (scrolld && offset) {
7610 err = scrolld(view, offset);
7611 *selected -= offset;
7615 return err;
7618 static void
7619 list_commands(FILE *fp)
7621 size_t i;
7623 fprintf(fp, "commands:");
7624 for (i = 0; i < nitems(tog_commands); i++) {
7625 const struct tog_cmd *cmd = &tog_commands[i];
7626 fprintf(fp, " %s", cmd->name);
7628 fputc('\n', fp);
7631 __dead static void
7632 usage(int hflag, int status)
7634 FILE *fp = (status == 0) ? stdout : stderr;
7636 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
7637 getprogname());
7638 if (hflag) {
7639 fprintf(fp, "lazy usage: %s path\n", getprogname());
7640 list_commands(fp);
7642 exit(status);
7645 static char **
7646 make_argv(int argc, ...)
7648 va_list ap;
7649 char **argv;
7650 int i;
7652 va_start(ap, argc);
7654 argv = calloc(argc, sizeof(char *));
7655 if (argv == NULL)
7656 err(1, "calloc");
7657 for (i = 0; i < argc; i++) {
7658 argv[i] = strdup(va_arg(ap, char *));
7659 if (argv[i] == NULL)
7660 err(1, "strdup");
7663 va_end(ap);
7664 return argv;
7668 * Try to convert 'tog path' into a 'tog log path' command.
7669 * The user could simply have mistyped the command rather than knowingly
7670 * provided a path. So check whether argv[0] can in fact be resolved
7671 * to a path in the HEAD commit and print a special error if not.
7672 * This hack is for mpi@ <3
7674 static const struct got_error *
7675 tog_log_with_path(int argc, char *argv[])
7677 const struct got_error *error = NULL, *close_err;
7678 const struct tog_cmd *cmd = NULL;
7679 struct got_repository *repo = NULL;
7680 struct got_worktree *worktree = NULL;
7681 struct got_object_id *commit_id = NULL, *id = NULL;
7682 struct got_commit_object *commit = NULL;
7683 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7684 char *commit_id_str = NULL, **cmd_argv = NULL;
7685 int *pack_fds = NULL;
7687 cwd = getcwd(NULL, 0);
7688 if (cwd == NULL)
7689 return got_error_from_errno("getcwd");
7691 error = got_repo_pack_fds_open(&pack_fds);
7692 if (error != NULL)
7693 goto done;
7695 error = got_worktree_open(&worktree, cwd);
7696 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7697 goto done;
7699 if (worktree)
7700 repo_path = strdup(got_worktree_get_repo_path(worktree));
7701 else
7702 repo_path = strdup(cwd);
7703 if (repo_path == NULL) {
7704 error = got_error_from_errno("strdup");
7705 goto done;
7708 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7709 if (error != NULL)
7710 goto done;
7712 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7713 repo, worktree);
7714 if (error)
7715 goto done;
7717 error = tog_load_refs(repo, 0);
7718 if (error)
7719 goto done;
7720 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
7721 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
7722 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7723 if (error)
7724 goto done;
7726 if (worktree) {
7727 got_worktree_close(worktree);
7728 worktree = NULL;
7731 error = got_object_open_as_commit(&commit, repo, commit_id);
7732 if (error)
7733 goto done;
7735 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
7736 if (error) {
7737 if (error->code != GOT_ERR_NO_TREE_ENTRY)
7738 goto done;
7739 fprintf(stderr, "%s: '%s' is no known command or path\n",
7740 getprogname(), argv[0]);
7741 usage(1, 1);
7742 /* not reached */
7745 close_err = got_repo_close(repo);
7746 if (error == NULL)
7747 error = close_err;
7748 repo = NULL;
7750 error = got_object_id_str(&commit_id_str, commit_id);
7751 if (error)
7752 goto done;
7754 cmd = &tog_commands[0]; /* log */
7755 argc = 4;
7756 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
7757 error = cmd->cmd_main(argc, cmd_argv);
7758 done:
7759 if (repo) {
7760 close_err = got_repo_close(repo);
7761 if (error == NULL)
7762 error = close_err;
7764 if (commit)
7765 got_object_commit_close(commit);
7766 if (worktree)
7767 got_worktree_close(worktree);
7768 if (pack_fds) {
7769 const struct got_error *pack_err =
7770 got_repo_pack_fds_close(pack_fds);
7771 if (error == NULL)
7772 error = pack_err;
7774 free(id);
7775 free(commit_id_str);
7776 free(commit_id);
7777 free(cwd);
7778 free(repo_path);
7779 free(in_repo_path);
7780 if (cmd_argv) {
7781 int i;
7782 for (i = 0; i < argc; i++)
7783 free(cmd_argv[i]);
7784 free(cmd_argv);
7786 tog_free_refs();
7787 return error;
7790 int
7791 main(int argc, char *argv[])
7793 const struct got_error *error = NULL;
7794 const struct tog_cmd *cmd = NULL;
7795 int ch, hflag = 0, Vflag = 0;
7796 char **cmd_argv = NULL;
7797 static const struct option longopts[] = {
7798 { "version", no_argument, NULL, 'V' },
7799 { NULL, 0, NULL, 0}
7802 setlocale(LC_CTYPE, "");
7804 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
7805 switch (ch) {
7806 case 'h':
7807 hflag = 1;
7808 break;
7809 case 'V':
7810 Vflag = 1;
7811 break;
7812 default:
7813 usage(hflag, 1);
7814 /* NOTREACHED */
7818 argc -= optind;
7819 argv += optind;
7820 optind = 1;
7821 optreset = 1;
7823 if (Vflag) {
7824 got_version_print_str();
7825 return 0;
7828 #ifndef PROFILE
7829 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
7830 NULL) == -1)
7831 err(1, "pledge");
7832 #endif
7834 if (argc == 0) {
7835 if (hflag)
7836 usage(hflag, 0);
7837 /* Build an argument vector which runs a default command. */
7838 cmd = &tog_commands[0];
7839 argc = 1;
7840 cmd_argv = make_argv(argc, cmd->name);
7841 } else {
7842 size_t i;
7844 /* Did the user specify a command? */
7845 for (i = 0; i < nitems(tog_commands); i++) {
7846 if (strncmp(tog_commands[i].name, argv[0],
7847 strlen(argv[0])) == 0) {
7848 cmd = &tog_commands[i];
7849 break;
7854 if (cmd == NULL) {
7855 if (argc != 1)
7856 usage(0, 1);
7857 /* No command specified; try log with a path */
7858 error = tog_log_with_path(argc, argv);
7859 } else {
7860 if (hflag)
7861 cmd->cmd_usage();
7862 else
7863 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
7866 endwin();
7867 putchar('\n');
7868 if (cmd_argv) {
7869 int i;
7870 for (i = 0; i < argc; i++)
7871 free(cmd_argv[i]);
7872 free(cmd_argv);
7875 if (error && error->code != GOT_ERR_CANCELLED)
7876 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7877 return 0;