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 int
785 view_is_fullscreen(struct tog_view *view)
787 return view->nlines == LINES && view->ncols == COLS;
790 static void
791 view_border(struct tog_view *view)
793 PANEL *panel;
794 const struct tog_view *view_above;
796 if (view->parent)
797 return view_border(view->parent);
799 panel = panel_above(view->panel);
800 if (panel == NULL)
801 return;
803 view_above = panel_userptr(panel);
804 if (view->mode == TOG_VIEW_SPLIT_HRZN)
805 mvwhline(view->window, view_above->begin_y - 1,
806 view->begin_x, got_locale_is_utf8() ?
807 ACS_HLINE : '-', view->ncols);
808 else
809 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
810 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
813 static const struct got_error *request_log_commits(struct tog_view *);
814 static const struct got_error *offset_selection_down(struct tog_view *);
815 static void offset_selection_up(struct tog_view *);
817 static const struct got_error *
818 view_resize(struct tog_view *view)
820 const struct got_error *err = NULL;
821 int dif, nlines, ncols;
823 dif = LINES - view->lines; /* line difference */
825 if (view->lines > LINES)
826 nlines = view->nlines - (view->lines - LINES);
827 else
828 nlines = view->nlines + (LINES - view->lines);
829 if (view->cols > COLS)
830 ncols = view->ncols - (view->cols - COLS);
831 else
832 ncols = view->ncols + (COLS - view->cols);
834 if (view->child) {
835 int hs = view->child->begin_y;
837 if (!view_is_fullscreen(view))
838 view->child->begin_x = view_split_begin_x(view->begin_x);
839 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
840 view->child->begin_x == 0) {
841 ncols = COLS;
843 view_fullscreen(view->child);
844 if (view->child->focussed)
845 show_panel(view->child->panel);
846 else
847 show_panel(view->panel);
848 } else {
849 ncols = view->child->begin_x;
851 view_splitscreen(view->child);
852 show_panel(view->child->panel);
854 /*
855 * Request commits if terminal height was increased in a log
856 * view so we have enough commits loaded to populate the view.
857 */
858 if (view->type == TOG_VIEW_LOG && dif > 0) {
859 struct tog_log_view_state *ts = &view->state.log;
861 if (ts->commits.ncommits < ts->selected_entry->idx +
862 view->lines - ts->selected) {
863 view->nscrolled = ts->selected_entry->idx +
864 view->lines - ts->selected -
865 ts->commits.ncommits + dif;
866 err = request_log_commits(view);
867 if (err)
868 return err;
872 /*
873 * XXX This is ugly and needs to be moved into the above
874 * logic but "works" for now and my attempts at moving it
875 * break either 'tab' or 'F' key maps in horizontal splits.
876 */
877 if (hs) {
878 err = view_splitscreen(view->child);
879 if (err)
880 return err;
881 if (dif < 0) { /* top split decreased */
882 err = offset_selection_down(view);
883 if (err)
884 return err;
886 view_border(view);
887 update_panels();
888 doupdate();
889 show_panel(view->child->panel);
890 nlines = view->nlines;
892 } else if (view->parent == NULL)
893 ncols = COLS;
895 if (wresize(view->window, nlines, ncols) == ERR)
896 return got_error_from_errno("wresize");
897 if (replace_panel(view->panel, view->window) == ERR)
898 return got_error_from_errno("replace_panel");
899 wclear(view->window);
901 view->nlines = nlines;
902 view->ncols = ncols;
903 view->lines = LINES;
904 view->cols = COLS;
906 return NULL;
909 static const struct got_error *
910 view_close_child(struct tog_view *view)
912 const struct got_error *err = NULL;
914 if (view->child == NULL)
915 return NULL;
917 err = view_close(view->child);
918 view->child = NULL;
919 return err;
922 static const struct got_error *
923 view_set_child(struct tog_view *view, struct tog_view *child)
925 view->child = child;
926 child->parent = view;
928 return view_resize(view);
931 static void
932 tog_resizeterm(void)
934 int cols, lines;
935 struct winsize size;
937 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
938 cols = 80; /* Default */
939 lines = 24;
940 } else {
941 cols = size.ws_col;
942 lines = size.ws_row;
944 resize_term(lines, cols);
947 static const struct got_error *
948 view_search_start(struct tog_view *view)
950 const struct got_error *err = NULL;
951 struct tog_view *v = view;
952 char pattern[1024];
953 int ret;
955 if (view->search_started) {
956 regfree(&view->regex);
957 view->searching = 0;
958 memset(&view->regmatch, 0, sizeof(view->regmatch));
960 view->search_started = 0;
962 if (view->nlines < 1)
963 return NULL;
965 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
966 view_is_splitscreen(view->child))
967 v = view->child;
969 mvwaddstr(v->window, v->nlines - 1, 0, "/");
970 wclrtoeol(v->window);
972 nocbreak();
973 echo();
974 ret = wgetnstr(v->window, pattern, sizeof(pattern));
975 wrefresh(v->window);
976 cbreak();
977 noecho();
978 if (ret == ERR)
979 return NULL;
981 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
982 err = view->search_start(view);
983 if (err) {
984 regfree(&view->regex);
985 return err;
987 view->search_started = 1;
988 view->searching = TOG_SEARCH_FORWARD;
989 view->search_next_done = 0;
990 view->search_next(view);
993 return NULL;
996 /*
997 * Compute view->count from numeric user input. User has five-tenths of a
998 * second to follow each numeric keypress with another number to form count.
999 * Return first non-numeric input or ERR and assign total to view->count.
1000 * XXX Should we add support for user-defined timeout?
1002 static int
1003 get_compound_key(struct tog_view *view, int c)
1005 struct tog_view *v = view;
1006 int x, n = 0;
1008 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
1009 view_is_splitscreen(view->child))
1010 v = view->child;
1011 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1012 v = view->parent;
1014 view->count = 0;
1015 halfdelay(5); /* block for half a second */
1016 wattron(v->window, A_BOLD);
1017 wmove(v->window, v->nlines - 1, 0);
1018 wclrtoeol(v->window);
1019 waddch(v->window, ':');
1021 do {
1022 x = getcurx(v->window);
1023 if (x != ERR && x < view->ncols) {
1024 waddch(v->window, c);
1025 wrefresh(v->window);
1029 * Don't overflow. Max valid request should be the greatest
1030 * between the longest and total lines; cap at 10 million.
1032 if (n >= 9999999)
1033 n = 9999999;
1034 else
1035 n = n * 10 + (c - '0');
1036 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1038 /* Massage excessive or inapplicable values at the input handler. */
1039 view->count = n;
1041 wattroff(v->window, A_BOLD);
1042 cbreak(); /* return to blocking */
1043 return c;
1046 static const struct got_error *
1047 view_input(struct tog_view **new, int *done, struct tog_view *view,
1048 struct tog_view_list_head *views)
1050 const struct got_error *err = NULL;
1051 struct tog_view *v;
1052 int ch, errcode;
1054 *new = NULL;
1056 /* Clear "no matches" indicator. */
1057 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1058 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1059 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1060 view->count = 0;
1063 if (view->searching && !view->search_next_done) {
1064 errcode = pthread_mutex_unlock(&tog_mutex);
1065 if (errcode)
1066 return got_error_set_errno(errcode,
1067 "pthread_mutex_unlock");
1068 sched_yield();
1069 errcode = pthread_mutex_lock(&tog_mutex);
1070 if (errcode)
1071 return got_error_set_errno(errcode,
1072 "pthread_mutex_lock");
1073 view->search_next(view);
1074 return NULL;
1077 nodelay(stdscr, FALSE);
1078 /* Allow threads to make progress while we are waiting for input. */
1079 errcode = pthread_mutex_unlock(&tog_mutex);
1080 if (errcode)
1081 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1082 /* If we have an unfinished count, don't get a new key map. */
1083 ch = view->ch;
1084 if ((view->count && --view->count == 0) || !view->count) {
1085 ch = wgetch(view->window);
1086 if (ch >= '1' && ch <= '9')
1087 view->ch = ch = get_compound_key(view, ch);
1089 errcode = pthread_mutex_lock(&tog_mutex);
1090 if (errcode)
1091 return got_error_set_errno(errcode, "pthread_mutex_lock");
1092 nodelay(stdscr, TRUE);
1094 if (tog_sigwinch_received || tog_sigcont_received) {
1095 tog_resizeterm();
1096 tog_sigwinch_received = 0;
1097 tog_sigcont_received = 0;
1098 TAILQ_FOREACH(v, views, entry) {
1099 err = view_resize(v);
1100 if (err)
1101 return err;
1102 err = v->input(new, v, KEY_RESIZE);
1103 if (err)
1104 return err;
1105 if (v->child) {
1106 err = view_resize(v->child);
1107 if (err)
1108 return err;
1109 err = v->child->input(new, v->child,
1110 KEY_RESIZE);
1111 if (err)
1112 return err;
1117 switch (ch) {
1118 case '\t':
1119 view->count = 0;
1120 if (view->child) {
1121 view->focussed = 0;
1122 view->child->focussed = 1;
1123 view->focus_child = 1;
1124 } else if (view->parent) {
1125 view->focussed = 0;
1126 view->parent->focussed = 1;
1127 view->parent->focus_child = 0;
1128 if (!view_is_splitscreen(view)) {
1129 if (view->mode == TOG_VIEW_SPLIT_HRZN &&
1130 view->parent->type == TOG_VIEW_LOG) {
1131 err = request_log_commits(view->parent);
1132 if (err)
1133 return err;
1135 offset_selection_up(view->parent);
1136 err = view_fullscreen(view->parent);
1137 if (err)
1138 return err;
1141 break;
1142 case 'q':
1143 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1144 if (view->parent->type == TOG_VIEW_LOG) {
1145 /* might need more commits to fill fullscreen */
1146 err = request_log_commits(view->parent);
1147 if (err)
1148 break;
1150 offset_selection_up(view->parent);
1151 view->parent->mode = TOG_VIEW_SPLIT_NONE;
1153 err = view->input(new, view, ch);
1154 view->dying = 1;
1155 break;
1156 case 'Q':
1157 *done = 1;
1158 break;
1159 case 'F':
1160 view->count = 0;
1161 if (view_is_parent_view(view)) {
1162 if (view->child == NULL)
1163 break;
1164 if (view_is_splitscreen(view->child)) {
1165 view->focussed = 0;
1166 view->child->focussed = 1;
1167 err = view_fullscreen(view->child);
1168 } else
1169 err = view_splitscreen(view->child);
1170 if (err)
1171 break;
1172 err = view->child->input(new, view->child,
1173 KEY_RESIZE);
1174 } else {
1175 if (view_is_splitscreen(view)) {
1176 view->parent->focussed = 0;
1177 view->focussed = 1;
1178 err = view_fullscreen(view);
1179 } else {
1180 err = view_splitscreen(view);
1181 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1182 err = view_resize(view->parent);
1184 if (err)
1185 break;
1186 err = view->input(new, view, KEY_RESIZE);
1188 if (err)
1189 break;
1190 if (view->type == TOG_VIEW_LOG) {
1191 err = request_log_commits(view);
1192 if (err)
1193 break;
1195 if (view->parent)
1196 err = offset_selection_down(view->parent);
1197 if (!err)
1198 err = offset_selection_down(view);
1199 break;
1200 case KEY_RESIZE:
1201 break;
1202 case '/':
1203 view->count = 0;
1204 if (view->search_start)
1205 view_search_start(view);
1206 else
1207 err = view->input(new, view, ch);
1208 break;
1209 case 'N':
1210 case 'n':
1211 if (view->search_started && view->search_next) {
1212 view->searching = (ch == 'n' ?
1213 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1214 view->search_next_done = 0;
1215 view->search_next(view);
1216 } else
1217 err = view->input(new, view, ch);
1218 break;
1219 default:
1220 err = view->input(new, view, ch);
1221 break;
1224 return err;
1227 static int
1228 view_needs_focus_indication(struct tog_view *view)
1230 if (view_is_parent_view(view)) {
1231 if (view->child == NULL || view->child->focussed)
1232 return 0;
1233 if (!view_is_splitscreen(view->child))
1234 return 0;
1235 } else if (!view_is_splitscreen(view))
1236 return 0;
1238 return view->focussed;
1241 static const struct got_error *
1242 view_loop(struct tog_view *view)
1244 const struct got_error *err = NULL;
1245 struct tog_view_list_head views;
1246 struct tog_view *new_view;
1247 int fast_refresh = 10;
1248 int done = 0, errcode;
1250 errcode = pthread_mutex_lock(&tog_mutex);
1251 if (errcode)
1252 return got_error_set_errno(errcode, "pthread_mutex_lock");
1254 TAILQ_INIT(&views);
1255 TAILQ_INSERT_HEAD(&views, view, entry);
1257 view->focussed = 1;
1258 err = view->show(view);
1259 if (err)
1260 return err;
1261 update_panels();
1262 doupdate();
1263 while (!TAILQ_EMPTY(&views) && !done && !tog_fatal_signal_received()) {
1264 /* Refresh fast during initialization, then become slower. */
1265 if (fast_refresh && fast_refresh-- == 0)
1266 halfdelay(10); /* switch to once per second */
1268 err = view_input(&new_view, &done, view, &views);
1269 if (err)
1270 break;
1271 if (view->dying) {
1272 struct tog_view *v, *prev = NULL;
1274 if (view_is_parent_view(view))
1275 prev = TAILQ_PREV(view, tog_view_list_head,
1276 entry);
1277 else if (view->parent)
1278 prev = view->parent;
1280 if (view->parent) {
1281 view->parent->child = NULL;
1282 view->parent->focus_child = 0;
1283 /* Restore fullscreen line height. */
1284 view->parent->nlines = view->parent->lines;
1285 err = view_resize(view->parent);
1286 if (err)
1287 break;
1288 } else
1289 TAILQ_REMOVE(&views, view, entry);
1291 err = view_close(view);
1292 if (err)
1293 goto done;
1295 view = NULL;
1296 TAILQ_FOREACH(v, &views, entry) {
1297 if (v->focussed)
1298 break;
1300 if (view == NULL && new_view == NULL) {
1301 /* No view has focus. Try to pick one. */
1302 if (prev)
1303 view = prev;
1304 else if (!TAILQ_EMPTY(&views)) {
1305 view = TAILQ_LAST(&views,
1306 tog_view_list_head);
1308 if (view) {
1309 if (view->focus_child) {
1310 view->child->focussed = 1;
1311 view = view->child;
1312 } else
1313 view->focussed = 1;
1317 if (new_view) {
1318 struct tog_view *v, *t;
1319 /* Only allow one parent view per type. */
1320 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1321 if (v->type != new_view->type)
1322 continue;
1323 TAILQ_REMOVE(&views, v, entry);
1324 err = view_close(v);
1325 if (err)
1326 goto done;
1327 break;
1329 TAILQ_INSERT_TAIL(&views, new_view, entry);
1330 view = new_view;
1332 if (view) {
1333 if (view_is_parent_view(view)) {
1334 if (view->child && view->child->focussed)
1335 view = view->child;
1336 } else {
1337 if (view->parent && view->parent->focussed)
1338 view = view->parent;
1340 show_panel(view->panel);
1341 if (view->child && view_is_splitscreen(view->child))
1342 show_panel(view->child->panel);
1343 if (view->parent && view_is_splitscreen(view)) {
1344 err = view->parent->show(view->parent);
1345 if (err)
1346 goto done;
1348 err = view->show(view);
1349 if (err)
1350 goto done;
1351 if (view->child) {
1352 err = view->child->show(view->child);
1353 if (err)
1354 goto done;
1356 update_panels();
1357 doupdate();
1360 done:
1361 while (!TAILQ_EMPTY(&views)) {
1362 view = TAILQ_FIRST(&views);
1363 TAILQ_REMOVE(&views, view, entry);
1364 view_close(view);
1367 errcode = pthread_mutex_unlock(&tog_mutex);
1368 if (errcode && err == NULL)
1369 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1371 return err;
1374 __dead static void
1375 usage_log(void)
1377 endwin();
1378 fprintf(stderr,
1379 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1380 getprogname());
1381 exit(1);
1384 /* Create newly allocated wide-character string equivalent to a byte string. */
1385 static const struct got_error *
1386 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1388 char *vis = NULL;
1389 const struct got_error *err = NULL;
1391 *ws = NULL;
1392 *wlen = mbstowcs(NULL, s, 0);
1393 if (*wlen == (size_t)-1) {
1394 int vislen;
1395 if (errno != EILSEQ)
1396 return got_error_from_errno("mbstowcs");
1398 /* byte string invalid in current encoding; try to "fix" it */
1399 err = got_mbsavis(&vis, &vislen, s);
1400 if (err)
1401 return err;
1402 *wlen = mbstowcs(NULL, vis, 0);
1403 if (*wlen == (size_t)-1) {
1404 err = got_error_from_errno("mbstowcs"); /* give up */
1405 goto done;
1409 *ws = calloc(*wlen + 1, sizeof(**ws));
1410 if (*ws == NULL) {
1411 err = got_error_from_errno("calloc");
1412 goto done;
1415 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1416 err = got_error_from_errno("mbstowcs");
1417 done:
1418 free(vis);
1419 if (err) {
1420 free(*ws);
1421 *ws = NULL;
1422 *wlen = 0;
1424 return err;
1427 static const struct got_error *
1428 expand_tab(char **ptr, const char *src)
1430 char *dst;
1431 size_t len, n, idx = 0, sz = 0;
1433 *ptr = NULL;
1434 n = len = strlen(src);
1435 dst = malloc(n + 1);
1436 if (dst == NULL)
1437 return got_error_from_errno("malloc");
1439 while (idx < len && src[idx]) {
1440 const char c = src[idx];
1442 if (c == '\t') {
1443 size_t nb = TABSIZE - sz % TABSIZE;
1444 char *p;
1446 p = realloc(dst, n + nb);
1447 if (p == NULL) {
1448 free(dst);
1449 return got_error_from_errno("realloc");
1452 dst = p;
1453 n += nb;
1454 memset(dst + sz, ' ', nb);
1455 sz += nb;
1456 } else
1457 dst[sz++] = src[idx];
1458 ++idx;
1461 dst[sz] = '\0';
1462 *ptr = dst;
1463 return NULL;
1467 * Advance at most n columns from wline starting at offset off.
1468 * Return the index to the first character after the span operation.
1469 * Return the combined column width of all spanned wide character in
1470 * *rcol.
1472 static int
1473 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1475 int width, i, cols = 0;
1477 if (n == 0) {
1478 *rcol = cols;
1479 return off;
1482 for (i = off; wline[i] != L'\0'; ++i) {
1483 if (wline[i] == L'\t')
1484 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1485 else
1486 width = wcwidth(wline[i]);
1488 if (width == -1) {
1489 width = 1;
1490 wline[i] = L'.';
1493 if (cols + width > n)
1494 break;
1495 cols += width;
1498 *rcol = cols;
1499 return i;
1503 * Format a line for display, ensuring that it won't overflow a width limit.
1504 * With scrolling, the width returned refers to the scrolled version of the
1505 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1507 static const struct got_error *
1508 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1509 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1511 const struct got_error *err = NULL;
1512 int cols;
1513 wchar_t *wline = NULL;
1514 char *exstr = NULL;
1515 size_t wlen;
1516 int i, scrollx;
1518 *wlinep = NULL;
1519 *widthp = 0;
1521 if (expand) {
1522 err = expand_tab(&exstr, line);
1523 if (err)
1524 return err;
1527 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1528 free(exstr);
1529 if (err)
1530 return err;
1532 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1534 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1535 wline[wlen - 1] = L'\0';
1536 wlen--;
1538 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1539 wline[wlen - 1] = L'\0';
1540 wlen--;
1543 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1544 wline[i] = L'\0';
1546 if (widthp)
1547 *widthp = cols;
1548 if (scrollxp)
1549 *scrollxp = scrollx;
1550 if (err)
1551 free(wline);
1552 else
1553 *wlinep = wline;
1554 return err;
1557 static const struct got_error*
1558 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1559 struct got_object_id *id, struct got_repository *repo)
1561 static const struct got_error *err = NULL;
1562 struct got_reflist_entry *re;
1563 char *s;
1564 const char *name;
1566 *refs_str = NULL;
1568 TAILQ_FOREACH(re, refs, entry) {
1569 struct got_tag_object *tag = NULL;
1570 struct got_object_id *ref_id;
1571 int cmp;
1573 name = got_ref_get_name(re->ref);
1574 if (strcmp(name, GOT_REF_HEAD) == 0)
1575 continue;
1576 if (strncmp(name, "refs/", 5) == 0)
1577 name += 5;
1578 if (strncmp(name, "got/", 4) == 0 &&
1579 strncmp(name, "got/backup/", 11) != 0)
1580 continue;
1581 if (strncmp(name, "heads/", 6) == 0)
1582 name += 6;
1583 if (strncmp(name, "remotes/", 8) == 0) {
1584 name += 8;
1585 s = strstr(name, "/" GOT_REF_HEAD);
1586 if (s != NULL && s[strlen(s)] == '\0')
1587 continue;
1589 err = got_ref_resolve(&ref_id, repo, re->ref);
1590 if (err)
1591 break;
1592 if (strncmp(name, "tags/", 5) == 0) {
1593 err = got_object_open_as_tag(&tag, repo, ref_id);
1594 if (err) {
1595 if (err->code != GOT_ERR_OBJ_TYPE) {
1596 free(ref_id);
1597 break;
1599 /* Ref points at something other than a tag. */
1600 err = NULL;
1601 tag = NULL;
1604 cmp = got_object_id_cmp(tag ?
1605 got_object_tag_get_object_id(tag) : ref_id, id);
1606 free(ref_id);
1607 if (tag)
1608 got_object_tag_close(tag);
1609 if (cmp != 0)
1610 continue;
1611 s = *refs_str;
1612 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1613 s ? ", " : "", name) == -1) {
1614 err = got_error_from_errno("asprintf");
1615 free(s);
1616 *refs_str = NULL;
1617 break;
1619 free(s);
1622 return err;
1625 static const struct got_error *
1626 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1627 int col_tab_align)
1629 char *smallerthan;
1631 smallerthan = strchr(author, '<');
1632 if (smallerthan && smallerthan[1] != '\0')
1633 author = smallerthan + 1;
1634 author[strcspn(author, "@>")] = '\0';
1635 return format_line(wauthor, author_width, NULL, author, 0, limit,
1636 col_tab_align, 0);
1639 static const struct got_error *
1640 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1641 struct got_object_id *id, const size_t date_display_cols,
1642 int author_display_cols)
1644 struct tog_log_view_state *s = &view->state.log;
1645 const struct got_error *err = NULL;
1646 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1647 char *logmsg0 = NULL, *logmsg = NULL;
1648 char *author = NULL;
1649 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1650 int author_width, logmsg_width;
1651 char *newline, *line = NULL;
1652 int col, limit, scrollx;
1653 const int avail = view->ncols;
1654 struct tm tm;
1655 time_t committer_time;
1656 struct tog_color *tc;
1658 committer_time = got_object_commit_get_committer_time(commit);
1659 if (gmtime_r(&committer_time, &tm) == NULL)
1660 return got_error_from_errno("gmtime_r");
1661 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1662 return got_error(GOT_ERR_NO_SPACE);
1664 if (avail <= date_display_cols)
1665 limit = MIN(sizeof(datebuf) - 1, avail);
1666 else
1667 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1668 tc = get_color(&s->colors, TOG_COLOR_DATE);
1669 if (tc)
1670 wattr_on(view->window,
1671 COLOR_PAIR(tc->colorpair), NULL);
1672 waddnstr(view->window, datebuf, limit);
1673 if (tc)
1674 wattr_off(view->window,
1675 COLOR_PAIR(tc->colorpair), NULL);
1676 col = limit;
1677 if (col > avail)
1678 goto done;
1680 if (avail >= 120) {
1681 char *id_str;
1682 err = got_object_id_str(&id_str, id);
1683 if (err)
1684 goto done;
1685 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1686 if (tc)
1687 wattr_on(view->window,
1688 COLOR_PAIR(tc->colorpair), NULL);
1689 wprintw(view->window, "%.8s ", id_str);
1690 if (tc)
1691 wattr_off(view->window,
1692 COLOR_PAIR(tc->colorpair), NULL);
1693 free(id_str);
1694 col += 9;
1695 if (col > avail)
1696 goto done;
1699 author = strdup(got_object_commit_get_author(commit));
1700 if (author == NULL) {
1701 err = got_error_from_errno("strdup");
1702 goto done;
1704 err = format_author(&wauthor, &author_width, author, avail - col, col);
1705 if (err)
1706 goto done;
1707 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1708 if (tc)
1709 wattr_on(view->window,
1710 COLOR_PAIR(tc->colorpair), NULL);
1711 waddwstr(view->window, wauthor);
1712 if (tc)
1713 wattr_off(view->window,
1714 COLOR_PAIR(tc->colorpair), NULL);
1715 col += author_width;
1716 while (col < avail && author_width < author_display_cols + 2) {
1717 waddch(view->window, ' ');
1718 col++;
1719 author_width++;
1721 if (col > avail)
1722 goto done;
1724 err = got_object_commit_get_logmsg(&logmsg0, commit);
1725 if (err)
1726 goto done;
1727 logmsg = logmsg0;
1728 while (*logmsg == '\n')
1729 logmsg++;
1730 newline = strchr(logmsg, '\n');
1731 if (newline)
1732 *newline = '\0';
1733 limit = avail - col;
1734 if (view->child && view_is_splitscreen(view->child) && limit > 0)
1735 limit--; /* for the border */
1736 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
1737 limit, col, 1);
1738 if (err)
1739 goto done;
1740 waddwstr(view->window, &wlogmsg[scrollx]);
1741 col += MAX(logmsg_width, 0);
1742 while (col < avail) {
1743 waddch(view->window, ' ');
1744 col++;
1746 done:
1747 free(logmsg0);
1748 free(wlogmsg);
1749 free(author);
1750 free(wauthor);
1751 free(line);
1752 return err;
1755 static struct commit_queue_entry *
1756 alloc_commit_queue_entry(struct got_commit_object *commit,
1757 struct got_object_id *id)
1759 struct commit_queue_entry *entry;
1761 entry = calloc(1, sizeof(*entry));
1762 if (entry == NULL)
1763 return NULL;
1765 entry->id = id;
1766 entry->commit = commit;
1767 return entry;
1770 static void
1771 pop_commit(struct commit_queue *commits)
1773 struct commit_queue_entry *entry;
1775 entry = TAILQ_FIRST(&commits->head);
1776 TAILQ_REMOVE(&commits->head, entry, entry);
1777 got_object_commit_close(entry->commit);
1778 commits->ncommits--;
1779 /* Don't free entry->id! It is owned by the commit graph. */
1780 free(entry);
1783 static void
1784 free_commits(struct commit_queue *commits)
1786 while (!TAILQ_EMPTY(&commits->head))
1787 pop_commit(commits);
1790 static const struct got_error *
1791 match_commit(int *have_match, struct got_object_id *id,
1792 struct got_commit_object *commit, regex_t *regex)
1794 const struct got_error *err = NULL;
1795 regmatch_t regmatch;
1796 char *id_str = NULL, *logmsg = NULL;
1798 *have_match = 0;
1800 err = got_object_id_str(&id_str, id);
1801 if (err)
1802 return err;
1804 err = got_object_commit_get_logmsg(&logmsg, commit);
1805 if (err)
1806 goto done;
1808 if (regexec(regex, got_object_commit_get_author(commit), 1,
1809 &regmatch, 0) == 0 ||
1810 regexec(regex, got_object_commit_get_committer(commit), 1,
1811 &regmatch, 0) == 0 ||
1812 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
1813 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
1814 *have_match = 1;
1815 done:
1816 free(id_str);
1817 free(logmsg);
1818 return err;
1821 static const struct got_error *
1822 queue_commits(struct tog_log_thread_args *a)
1824 const struct got_error *err = NULL;
1827 * We keep all commits open throughout the lifetime of the log
1828 * view in order to avoid having to re-fetch commits from disk
1829 * while updating the display.
1831 do {
1832 struct got_object_id *id;
1833 struct got_commit_object *commit;
1834 struct commit_queue_entry *entry;
1835 int errcode;
1837 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
1838 NULL, NULL);
1839 if (err || id == NULL)
1840 break;
1842 err = got_object_open_as_commit(&commit, a->repo, id);
1843 if (err)
1844 break;
1845 entry = alloc_commit_queue_entry(commit, id);
1846 if (entry == NULL) {
1847 err = got_error_from_errno("alloc_commit_queue_entry");
1848 break;
1851 errcode = pthread_mutex_lock(&tog_mutex);
1852 if (errcode) {
1853 err = got_error_set_errno(errcode,
1854 "pthread_mutex_lock");
1855 break;
1858 entry->idx = a->commits->ncommits;
1859 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
1860 a->commits->ncommits++;
1862 if (*a->searching == TOG_SEARCH_FORWARD &&
1863 !*a->search_next_done) {
1864 int have_match;
1865 err = match_commit(&have_match, id, commit, a->regex);
1866 if (err)
1867 break;
1868 if (have_match)
1869 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
1872 errcode = pthread_mutex_unlock(&tog_mutex);
1873 if (errcode && err == NULL)
1874 err = got_error_set_errno(errcode,
1875 "pthread_mutex_unlock");
1876 if (err)
1877 break;
1878 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
1880 return err;
1883 static void
1884 select_commit(struct tog_log_view_state *s)
1886 struct commit_queue_entry *entry;
1887 int ncommits = 0;
1889 entry = s->first_displayed_entry;
1890 while (entry) {
1891 if (ncommits == s->selected) {
1892 s->selected_entry = entry;
1893 break;
1895 entry = TAILQ_NEXT(entry, entry);
1896 ncommits++;
1900 static const struct got_error *
1901 draw_commits(struct tog_view *view)
1903 const struct got_error *err = NULL;
1904 struct tog_log_view_state *s = &view->state.log;
1905 struct commit_queue_entry *entry = s->selected_entry;
1906 const int limit = view->nlines;
1907 int width;
1908 int ncommits, author_cols = 4;
1909 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
1910 char *refs_str = NULL;
1911 wchar_t *wline;
1912 struct tog_color *tc;
1913 static const size_t date_display_cols = 12;
1915 if (s->selected_entry &&
1916 !(view->searching && view->search_next_done == 0)) {
1917 struct got_reflist_head *refs;
1918 err = got_object_id_str(&id_str, s->selected_entry->id);
1919 if (err)
1920 return err;
1921 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
1922 s->selected_entry->id);
1923 if (refs) {
1924 err = build_refs_str(&refs_str, refs,
1925 s->selected_entry->id, s->repo);
1926 if (err)
1927 goto done;
1931 if (s->thread_args.commits_needed == 0)
1932 halfdelay(10); /* disable fast refresh */
1934 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
1935 if (asprintf(&ncommits_str, " [%d/%d] %s",
1936 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1937 (view->searching && !view->search_next_done) ?
1938 "searching..." : "loading...") == -1) {
1939 err = got_error_from_errno("asprintf");
1940 goto done;
1942 } else {
1943 const char *search_str = NULL;
1945 if (view->searching) {
1946 if (view->search_next_done == TOG_SEARCH_NO_MORE)
1947 search_str = "no more matches";
1948 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
1949 search_str = "no matches found";
1950 else if (!view->search_next_done)
1951 search_str = "searching...";
1954 if (asprintf(&ncommits_str, " [%d/%d] %s",
1955 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1956 search_str ? search_str :
1957 (refs_str ? refs_str : "")) == -1) {
1958 err = got_error_from_errno("asprintf");
1959 goto done;
1963 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
1964 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
1965 "........................................",
1966 s->in_repo_path, ncommits_str) == -1) {
1967 err = got_error_from_errno("asprintf");
1968 header = NULL;
1969 goto done;
1971 } else if (asprintf(&header, "commit %s%s",
1972 id_str ? id_str : "........................................",
1973 ncommits_str) == -1) {
1974 err = got_error_from_errno("asprintf");
1975 header = NULL;
1976 goto done;
1978 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
1979 if (err)
1980 goto done;
1982 werase(view->window);
1984 if (view_needs_focus_indication(view))
1985 wstandout(view->window);
1986 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1987 if (tc)
1988 wattr_on(view->window,
1989 COLOR_PAIR(tc->colorpair), NULL);
1990 waddwstr(view->window, wline);
1991 if (tc)
1992 wattr_off(view->window,
1993 COLOR_PAIR(tc->colorpair), NULL);
1994 while (width < view->ncols) {
1995 waddch(view->window, ' ');
1996 width++;
1998 if (view_needs_focus_indication(view))
1999 wstandend(view->window);
2000 free(wline);
2001 if (limit <= 1)
2002 goto done;
2004 /* Grow author column size if necessary, and set view->maxx. */
2005 entry = s->first_displayed_entry;
2006 ncommits = 0;
2007 view->maxx = 0;
2008 while (entry) {
2009 char *author, *eol, *msg, *msg0;
2010 wchar_t *wauthor, *wmsg;
2011 int width;
2012 if (ncommits >= limit - 1)
2013 break;
2014 author = strdup(got_object_commit_get_author(entry->commit));
2015 if (author == NULL) {
2016 err = got_error_from_errno("strdup");
2017 goto done;
2019 err = format_author(&wauthor, &width, author, COLS,
2020 date_display_cols);
2021 if (author_cols < width)
2022 author_cols = width;
2023 free(wauthor);
2024 free(author);
2025 err = got_object_commit_get_logmsg(&msg0, entry->commit);
2026 if (err)
2027 goto done;
2028 msg = msg0;
2029 while (*msg == '\n')
2030 ++msg;
2031 if ((eol = strchr(msg, '\n')))
2032 *eol = '\0';
2033 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2034 date_display_cols + author_cols, 0);
2035 if (err)
2036 goto done;
2037 view->maxx = MAX(view->maxx, width);
2038 free(msg0);
2039 free(wmsg);
2040 ncommits++;
2041 entry = TAILQ_NEXT(entry, entry);
2044 entry = s->first_displayed_entry;
2045 s->last_displayed_entry = s->first_displayed_entry;
2046 ncommits = 0;
2047 while (entry) {
2048 if (ncommits >= limit - 1)
2049 break;
2050 if (ncommits == s->selected)
2051 wstandout(view->window);
2052 err = draw_commit(view, entry->commit, entry->id,
2053 date_display_cols, author_cols);
2054 if (ncommits == s->selected)
2055 wstandend(view->window);
2056 if (err)
2057 goto done;
2058 ncommits++;
2059 s->last_displayed_entry = entry;
2060 entry = TAILQ_NEXT(entry, entry);
2063 view_border(view);
2064 done:
2065 free(id_str);
2066 free(refs_str);
2067 free(ncommits_str);
2068 free(header);
2069 return err;
2072 static void
2073 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2075 struct commit_queue_entry *entry;
2076 int nscrolled = 0;
2078 entry = TAILQ_FIRST(&s->commits.head);
2079 if (s->first_displayed_entry == entry)
2080 return;
2082 entry = s->first_displayed_entry;
2083 while (entry && nscrolled < maxscroll) {
2084 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2085 if (entry) {
2086 s->first_displayed_entry = entry;
2087 nscrolled++;
2092 static const struct got_error *
2093 trigger_log_thread(struct tog_view *view, int wait)
2095 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2096 int errcode;
2098 halfdelay(1); /* fast refresh while loading commits */
2100 while (ta->commits_needed > 0 || ta->load_all) {
2101 if (ta->log_complete)
2102 break;
2104 /* Wake the log thread. */
2105 errcode = pthread_cond_signal(&ta->need_commits);
2106 if (errcode)
2107 return got_error_set_errno(errcode,
2108 "pthread_cond_signal");
2111 * The mutex will be released while the view loop waits
2112 * in wgetch(), at which time the log thread will run.
2114 if (!wait)
2115 break;
2117 /* Display progress update in log view. */
2118 show_log_view(view);
2119 update_panels();
2120 doupdate();
2122 /* Wait right here while next commit is being loaded. */
2123 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2124 if (errcode)
2125 return got_error_set_errno(errcode,
2126 "pthread_cond_wait");
2128 /* Display progress update in log view. */
2129 show_log_view(view);
2130 update_panels();
2131 doupdate();
2134 return NULL;
2137 static const struct got_error *
2138 request_log_commits(struct tog_view *view)
2140 struct tog_log_view_state *state = &view->state.log;
2141 const struct got_error *err = NULL;
2143 state->thread_args.commits_needed = view->nscrolled;
2144 err = trigger_log_thread(view, 1);
2145 view->nscrolled = 0;
2147 return err;
2150 static const struct got_error *
2151 log_scroll_down(struct tog_view *view, int maxscroll)
2153 struct tog_log_view_state *s = &view->state.log;
2154 const struct got_error *err = NULL;
2155 struct commit_queue_entry *pentry;
2156 int nscrolled = 0, ncommits_needed;
2158 if (s->last_displayed_entry == NULL)
2159 return NULL;
2161 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2162 if (s->commits.ncommits < ncommits_needed &&
2163 !s->thread_args.log_complete) {
2165 * Ask the log thread for required amount of commits.
2167 s->thread_args.commits_needed += maxscroll;
2168 err = trigger_log_thread(view, 1);
2169 if (err)
2170 return err;
2173 do {
2174 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2175 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2176 break;
2178 s->last_displayed_entry = pentry ?
2179 pentry : s->last_displayed_entry;;
2181 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2182 if (pentry == NULL)
2183 break;
2184 s->first_displayed_entry = pentry;
2185 } while (++nscrolled < maxscroll);
2187 if (view->mode == TOG_VIEW_SPLIT_HRZN)
2188 view->nscrolled += nscrolled;
2189 else
2190 view->nscrolled = 0;
2192 return err;
2195 static const struct got_error *
2196 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2197 struct got_commit_object *commit, struct got_object_id *commit_id,
2198 struct tog_view *log_view, struct got_repository *repo)
2200 const struct got_error *err;
2201 struct got_object_qid *parent_id;
2202 struct tog_view *diff_view;
2204 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2205 if (diff_view == NULL)
2206 return got_error_from_errno("view_open");
2208 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2209 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2210 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2211 if (err == NULL)
2212 *new_view = diff_view;
2213 return err;
2216 static const struct got_error *
2217 tree_view_visit_subtree(struct tog_tree_view_state *s,
2218 struct got_tree_object *subtree)
2220 struct tog_parent_tree *parent;
2222 parent = calloc(1, sizeof(*parent));
2223 if (parent == NULL)
2224 return got_error_from_errno("calloc");
2226 parent->tree = s->tree;
2227 parent->first_displayed_entry = s->first_displayed_entry;
2228 parent->selected_entry = s->selected_entry;
2229 parent->selected = s->selected;
2230 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2231 s->tree = subtree;
2232 s->selected = 0;
2233 s->first_displayed_entry = NULL;
2234 return NULL;
2237 static const struct got_error *
2238 tree_view_walk_path(struct tog_tree_view_state *s,
2239 struct got_commit_object *commit, const char *path)
2241 const struct got_error *err = NULL;
2242 struct got_tree_object *tree = NULL;
2243 const char *p;
2244 char *slash, *subpath = NULL;
2246 /* Walk the path and open corresponding tree objects. */
2247 p = path;
2248 while (*p) {
2249 struct got_tree_entry *te;
2250 struct got_object_id *tree_id;
2251 char *te_name;
2253 while (p[0] == '/')
2254 p++;
2256 /* Ensure the correct subtree entry is selected. */
2257 slash = strchr(p, '/');
2258 if (slash == NULL)
2259 te_name = strdup(p);
2260 else
2261 te_name = strndup(p, slash - p);
2262 if (te_name == NULL) {
2263 err = got_error_from_errno("strndup");
2264 break;
2266 te = got_object_tree_find_entry(s->tree, te_name);
2267 if (te == NULL) {
2268 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2269 free(te_name);
2270 break;
2272 free(te_name);
2273 s->first_displayed_entry = s->selected_entry = te;
2275 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2276 break; /* jump to this file's entry */
2278 slash = strchr(p, '/');
2279 if (slash)
2280 subpath = strndup(path, slash - path);
2281 else
2282 subpath = strdup(path);
2283 if (subpath == NULL) {
2284 err = got_error_from_errno("strdup");
2285 break;
2288 err = got_object_id_by_path(&tree_id, s->repo, commit,
2289 subpath);
2290 if (err)
2291 break;
2293 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2294 free(tree_id);
2295 if (err)
2296 break;
2298 err = tree_view_visit_subtree(s, tree);
2299 if (err) {
2300 got_object_tree_close(tree);
2301 break;
2303 if (slash == NULL)
2304 break;
2305 free(subpath);
2306 subpath = NULL;
2307 p = slash;
2310 free(subpath);
2311 return err;
2314 static const struct got_error *
2315 browse_commit_tree(struct tog_view **new_view, int begin_x,
2316 struct commit_queue_entry *entry, const char *path,
2317 const char *head_ref_name, struct got_repository *repo)
2319 const struct got_error *err = NULL;
2320 struct tog_tree_view_state *s;
2321 struct tog_view *tree_view;
2323 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
2324 if (tree_view == NULL)
2325 return got_error_from_errno("view_open");
2327 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2328 if (err)
2329 return err;
2330 s = &tree_view->state.tree;
2332 *new_view = tree_view;
2334 if (got_path_is_root_dir(path))
2335 return NULL;
2337 return tree_view_walk_path(s, entry->commit, path);
2340 static const struct got_error *
2341 block_signals_used_by_main_thread(void)
2343 sigset_t sigset;
2344 int errcode;
2346 if (sigemptyset(&sigset) == -1)
2347 return got_error_from_errno("sigemptyset");
2349 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2350 if (sigaddset(&sigset, SIGWINCH) == -1)
2351 return got_error_from_errno("sigaddset");
2352 if (sigaddset(&sigset, SIGCONT) == -1)
2353 return got_error_from_errno("sigaddset");
2354 if (sigaddset(&sigset, SIGINT) == -1)
2355 return got_error_from_errno("sigaddset");
2356 if (sigaddset(&sigset, SIGTERM) == -1)
2357 return got_error_from_errno("sigaddset");
2359 /* ncurses handles SIGTSTP */
2360 if (sigaddset(&sigset, SIGTSTP) == -1)
2361 return got_error_from_errno("sigaddset");
2363 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2364 if (errcode)
2365 return got_error_set_errno(errcode, "pthread_sigmask");
2367 return NULL;
2370 static void *
2371 log_thread(void *arg)
2373 const struct got_error *err = NULL;
2374 int errcode = 0;
2375 struct tog_log_thread_args *a = arg;
2376 int done = 0;
2378 err = block_signals_used_by_main_thread();
2379 if (err)
2380 return (void *)err;
2382 while (!done && !err && !tog_fatal_signal_received()) {
2383 err = queue_commits(a);
2384 if (err) {
2385 if (err->code != GOT_ERR_ITER_COMPLETED)
2386 return (void *)err;
2387 err = NULL;
2388 done = 1;
2389 } else if (a->commits_needed > 0 && !a->load_all)
2390 a->commits_needed--;
2392 errcode = pthread_mutex_lock(&tog_mutex);
2393 if (errcode) {
2394 err = got_error_set_errno(errcode,
2395 "pthread_mutex_lock");
2396 break;
2397 } else if (*a->quit)
2398 done = 1;
2399 else if (*a->first_displayed_entry == NULL) {
2400 *a->first_displayed_entry =
2401 TAILQ_FIRST(&a->commits->head);
2402 *a->selected_entry = *a->first_displayed_entry;
2405 errcode = pthread_cond_signal(&a->commit_loaded);
2406 if (errcode) {
2407 err = got_error_set_errno(errcode,
2408 "pthread_cond_signal");
2409 pthread_mutex_unlock(&tog_mutex);
2410 break;
2413 if (done)
2414 a->commits_needed = 0;
2415 else {
2416 if (a->commits_needed == 0 && !a->load_all) {
2417 errcode = pthread_cond_wait(&a->need_commits,
2418 &tog_mutex);
2419 if (errcode)
2420 err = got_error_set_errno(errcode,
2421 "pthread_cond_wait");
2422 if (*a->quit)
2423 done = 1;
2427 errcode = pthread_mutex_unlock(&tog_mutex);
2428 if (errcode && err == NULL)
2429 err = got_error_set_errno(errcode,
2430 "pthread_mutex_unlock");
2432 a->log_complete = 1;
2433 return (void *)err;
2436 static const struct got_error *
2437 stop_log_thread(struct tog_log_view_state *s)
2439 const struct got_error *err = NULL;
2440 int errcode;
2442 if (s->thread) {
2443 s->quit = 1;
2444 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2445 if (errcode)
2446 return got_error_set_errno(errcode,
2447 "pthread_cond_signal");
2448 errcode = pthread_mutex_unlock(&tog_mutex);
2449 if (errcode)
2450 return got_error_set_errno(errcode,
2451 "pthread_mutex_unlock");
2452 errcode = pthread_join(s->thread, (void **)&err);
2453 if (errcode)
2454 return got_error_set_errno(errcode, "pthread_join");
2455 errcode = pthread_mutex_lock(&tog_mutex);
2456 if (errcode)
2457 return got_error_set_errno(errcode,
2458 "pthread_mutex_lock");
2459 s->thread = NULL;
2462 if (s->thread_args.repo) {
2463 err = got_repo_close(s->thread_args.repo);
2464 s->thread_args.repo = NULL;
2467 if (s->thread_args.pack_fds) {
2468 const struct got_error *pack_err =
2469 got_repo_pack_fds_close(s->thread_args.pack_fds);
2470 if (err == NULL)
2471 err = pack_err;
2472 s->thread_args.pack_fds = NULL;
2475 if (s->thread_args.graph) {
2476 got_commit_graph_close(s->thread_args.graph);
2477 s->thread_args.graph = NULL;
2480 return err;
2483 static const struct got_error *
2484 close_log_view(struct tog_view *view)
2486 const struct got_error *err = NULL;
2487 struct tog_log_view_state *s = &view->state.log;
2488 int errcode;
2490 err = stop_log_thread(s);
2492 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2493 if (errcode && err == NULL)
2494 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2496 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2497 if (errcode && err == NULL)
2498 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2500 free_commits(&s->commits);
2501 free(s->in_repo_path);
2502 s->in_repo_path = NULL;
2503 free(s->start_id);
2504 s->start_id = NULL;
2505 free(s->head_ref_name);
2506 s->head_ref_name = NULL;
2507 return err;
2510 static const struct got_error *
2511 search_start_log_view(struct tog_view *view)
2513 struct tog_log_view_state *s = &view->state.log;
2515 s->matched_entry = NULL;
2516 s->search_entry = NULL;
2517 return NULL;
2520 static const struct got_error *
2521 search_next_log_view(struct tog_view *view)
2523 const struct got_error *err = NULL;
2524 struct tog_log_view_state *s = &view->state.log;
2525 struct commit_queue_entry *entry;
2527 /* Display progress update in log view. */
2528 show_log_view(view);
2529 update_panels();
2530 doupdate();
2532 if (s->search_entry) {
2533 int errcode, ch;
2534 errcode = pthread_mutex_unlock(&tog_mutex);
2535 if (errcode)
2536 return got_error_set_errno(errcode,
2537 "pthread_mutex_unlock");
2538 ch = wgetch(view->window);
2539 errcode = pthread_mutex_lock(&tog_mutex);
2540 if (errcode)
2541 return got_error_set_errno(errcode,
2542 "pthread_mutex_lock");
2543 if (ch == KEY_BACKSPACE) {
2544 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2545 return NULL;
2547 if (view->searching == TOG_SEARCH_FORWARD)
2548 entry = TAILQ_NEXT(s->search_entry, entry);
2549 else
2550 entry = TAILQ_PREV(s->search_entry,
2551 commit_queue_head, entry);
2552 } else if (s->matched_entry) {
2553 int matched_idx = s->matched_entry->idx;
2554 int selected_idx = s->selected_entry->idx;
2557 * If the user has moved the cursor after we hit a match,
2558 * the position from where we should continue searching
2559 * might have changed.
2561 if (view->searching == TOG_SEARCH_FORWARD) {
2562 if (matched_idx > selected_idx)
2563 entry = TAILQ_NEXT(s->selected_entry, entry);
2564 else
2565 entry = TAILQ_NEXT(s->matched_entry, entry);
2566 } else {
2567 if (matched_idx < selected_idx)
2568 entry = TAILQ_PREV(s->selected_entry,
2569 commit_queue_head, entry);
2570 else
2571 entry = TAILQ_PREV(s->matched_entry,
2572 commit_queue_head, entry);
2574 } else {
2575 entry = s->selected_entry;
2578 while (1) {
2579 int have_match = 0;
2581 if (entry == NULL) {
2582 if (s->thread_args.log_complete ||
2583 view->searching == TOG_SEARCH_BACKWARD) {
2584 view->search_next_done =
2585 (s->matched_entry == NULL ?
2586 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2587 s->search_entry = NULL;
2588 return NULL;
2591 * Poke the log thread for more commits and return,
2592 * allowing the main loop to make progress. Search
2593 * will resume at s->search_entry once we come back.
2595 s->thread_args.commits_needed++;
2596 return trigger_log_thread(view, 0);
2599 err = match_commit(&have_match, entry->id, entry->commit,
2600 &view->regex);
2601 if (err)
2602 break;
2603 if (have_match) {
2604 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2605 s->matched_entry = entry;
2606 break;
2609 s->search_entry = entry;
2610 if (view->searching == TOG_SEARCH_FORWARD)
2611 entry = TAILQ_NEXT(entry, entry);
2612 else
2613 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2616 if (s->matched_entry) {
2617 int cur = s->selected_entry->idx;
2618 while (cur < s->matched_entry->idx) {
2619 err = input_log_view(NULL, view, KEY_DOWN);
2620 if (err)
2621 return err;
2622 cur++;
2624 while (cur > s->matched_entry->idx) {
2625 err = input_log_view(NULL, view, KEY_UP);
2626 if (err)
2627 return err;
2628 cur--;
2632 s->search_entry = NULL;
2634 return NULL;
2637 static const struct got_error *
2638 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2639 struct got_repository *repo, const char *head_ref_name,
2640 const char *in_repo_path, int log_branches)
2642 const struct got_error *err = NULL;
2643 struct tog_log_view_state *s = &view->state.log;
2644 struct got_repository *thread_repo = NULL;
2645 struct got_commit_graph *thread_graph = NULL;
2646 int errcode;
2648 if (in_repo_path != s->in_repo_path) {
2649 free(s->in_repo_path);
2650 s->in_repo_path = strdup(in_repo_path);
2651 if (s->in_repo_path == NULL)
2652 return got_error_from_errno("strdup");
2655 /* The commit queue only contains commits being displayed. */
2656 TAILQ_INIT(&s->commits.head);
2657 s->commits.ncommits = 0;
2659 s->repo = repo;
2660 if (head_ref_name) {
2661 s->head_ref_name = strdup(head_ref_name);
2662 if (s->head_ref_name == NULL) {
2663 err = got_error_from_errno("strdup");
2664 goto done;
2667 s->start_id = got_object_id_dup(start_id);
2668 if (s->start_id == NULL) {
2669 err = got_error_from_errno("got_object_id_dup");
2670 goto done;
2672 s->log_branches = log_branches;
2674 STAILQ_INIT(&s->colors);
2675 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2676 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2677 get_color_value("TOG_COLOR_COMMIT"));
2678 if (err)
2679 goto done;
2680 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2681 get_color_value("TOG_COLOR_AUTHOR"));
2682 if (err) {
2683 free_colors(&s->colors);
2684 goto done;
2686 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
2687 get_color_value("TOG_COLOR_DATE"));
2688 if (err) {
2689 free_colors(&s->colors);
2690 goto done;
2694 view->show = show_log_view;
2695 view->input = input_log_view;
2696 view->close = close_log_view;
2697 view->search_start = search_start_log_view;
2698 view->search_next = search_next_log_view;
2700 if (s->thread_args.pack_fds == NULL) {
2701 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2702 if (err)
2703 goto done;
2705 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
2706 s->thread_args.pack_fds);
2707 if (err)
2708 goto done;
2709 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
2710 !s->log_branches);
2711 if (err)
2712 goto done;
2713 err = got_commit_graph_iter_start(thread_graph, s->start_id,
2714 s->repo, NULL, NULL);
2715 if (err)
2716 goto done;
2718 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
2719 if (errcode) {
2720 err = got_error_set_errno(errcode, "pthread_cond_init");
2721 goto done;
2723 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
2724 if (errcode) {
2725 err = got_error_set_errno(errcode, "pthread_cond_init");
2726 goto done;
2729 s->thread_args.commits_needed = view->nlines;
2730 s->thread_args.graph = thread_graph;
2731 s->thread_args.commits = &s->commits;
2732 s->thread_args.in_repo_path = s->in_repo_path;
2733 s->thread_args.start_id = s->start_id;
2734 s->thread_args.repo = thread_repo;
2735 s->thread_args.log_complete = 0;
2736 s->thread_args.quit = &s->quit;
2737 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
2738 s->thread_args.selected_entry = &s->selected_entry;
2739 s->thread_args.searching = &view->searching;
2740 s->thread_args.search_next_done = &view->search_next_done;
2741 s->thread_args.regex = &view->regex;
2742 done:
2743 if (err)
2744 close_log_view(view);
2745 return err;
2748 static const struct got_error *
2749 show_log_view(struct tog_view *view)
2751 const struct got_error *err;
2752 struct tog_log_view_state *s = &view->state.log;
2754 if (s->thread == NULL) {
2755 int errcode = pthread_create(&s->thread, NULL, log_thread,
2756 &s->thread_args);
2757 if (errcode)
2758 return got_error_set_errno(errcode, "pthread_create");
2759 if (s->thread_args.commits_needed > 0) {
2760 err = trigger_log_thread(view, 1);
2761 if (err)
2762 return err;
2766 return draw_commits(view);
2769 static void
2770 log_move_cursor_up(struct tog_view *view, int page, int home)
2772 struct tog_log_view_state *s = &view->state.log;
2774 if (s->selected_entry->idx == 0)
2775 view->count = 0;
2776 if (s->first_displayed_entry == NULL)
2777 return;
2779 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
2780 || home)
2781 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
2783 if (!page && !home && s->selected > 0)
2784 --s->selected;
2785 else
2786 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
2788 select_commit(s);
2789 return;
2792 static const struct got_error *
2793 log_move_cursor_down(struct tog_view *view, int page)
2795 struct tog_log_view_state *s = &view->state.log;
2796 struct commit_queue_entry *first;
2797 const struct got_error *err = NULL;
2799 first = s->first_displayed_entry;
2800 if (first == NULL) {
2801 view->count = 0;
2802 return NULL;
2805 if (s->thread_args.log_complete &&
2806 s->selected_entry->idx >= s->commits.ncommits - 1)
2807 return NULL;
2809 if (!page) {
2810 int eos = view->nlines - 2;
2812 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
2813 view_is_splitscreen(view->child))
2814 --eos; /* border consumes the last line */
2815 if (s->selected < MIN(eos, s->commits.ncommits - 1))
2816 ++s->selected;
2817 else
2818 err = log_scroll_down(view, 1);
2819 } else if (s->thread_args.load_all) {
2820 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
2821 s->selected += MIN(s->last_displayed_entry->idx -
2822 s->selected_entry->idx, page + 1);
2823 else
2824 err = log_scroll_down(view, MIN(page,
2825 s->commits.ncommits - s->selected_entry->idx - 1));
2826 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
2827 } else {
2828 err = log_scroll_down(view, page);
2829 if (err)
2830 return err;
2831 if (first == s->first_displayed_entry && s->selected <
2832 MIN(view->nlines - 2, s->commits.ncommits - 1)) {
2833 s->selected = MIN(s->commits.ncommits - 1, page);
2836 if (err)
2837 return err;
2840 * We might necessarily overshoot in horizontal
2841 * splits; if so, select the last displayed commit.
2843 s->selected = MIN(s->selected,
2844 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
2846 select_commit(s);
2848 if (s->thread_args.log_complete &&
2849 s->selected_entry->idx == s->commits.ncommits - 1)
2850 view->count = 0;
2852 return NULL;
2856 * Get splitscreen dimensions based on TOG_VIEW_SPLIT_MODE:
2857 * TOG_VIEW_SPLIT_VERT vertical split if COLS > 119 (default)
2858 * TOG_VIEW_SPLIT_HRZN horizontal split
2859 * Assign start column and line of the new split to *x and *y, respectively,
2860 * and assign view mode to view->mode.
2862 static void
2863 view_get_split(struct tog_view *view, int *y, int *x)
2865 char *mode;
2867 mode = getenv("TOG_VIEW_SPLIT_MODE");
2869 if (!mode || mode[0] != 'h') {
2870 view->mode = TOG_VIEW_SPLIT_VERT;
2871 *x = view_split_begin_x(view->begin_x);
2872 } else if (mode && mode[0] == 'h') {
2873 view->mode = TOG_VIEW_SPLIT_HRZN;
2874 *y = view_split_begin_y(view->lines);
2878 /* Split view horizontally at y and offset view->state->selected line. */
2879 static const struct got_error *
2880 view_init_hsplit(struct tog_view *view, int y)
2882 const struct got_error *err = NULL;
2884 view->nlines = y;
2885 err = view_resize(view);
2886 if (err)
2887 return err;
2889 err = offset_selection_down(view);
2891 return err;
2894 static const struct got_error *
2895 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
2897 const struct got_error *err = NULL;
2898 struct tog_log_view_state *s = &view->state.log;
2899 struct tog_view *diff_view = NULL, *tree_view = NULL;
2900 struct tog_view *ref_view = NULL;
2901 struct commit_queue_entry *entry;
2902 int begin_x = 0, begin_y = 0, eos, n, nscroll;
2904 if (s->thread_args.load_all) {
2905 if (ch == KEY_BACKSPACE)
2906 s->thread_args.load_all = 0;
2907 else if (s->thread_args.log_complete) {
2908 err = log_move_cursor_down(view, s->commits.ncommits);
2909 s->thread_args.load_all = 0;
2911 return err;
2914 eos = nscroll = view->nlines - 1;
2915 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
2916 view_is_splitscreen(view->child))
2917 --eos; /* border */
2920 switch (ch) {
2921 case 'q':
2922 s->quit = 1;
2923 break;
2924 case '0':
2925 view->x = 0;
2926 break;
2927 case '$':
2928 view->x = MAX(view->maxx - view->ncols / 2, 0);
2929 view->count = 0;
2930 break;
2931 case KEY_RIGHT:
2932 case 'l':
2933 if (view->x + view->ncols / 2 < view->maxx)
2934 view->x += 2; /* move two columns right */
2935 else
2936 view->count = 0;
2937 break;
2938 case KEY_LEFT:
2939 case 'h':
2940 view->x -= MIN(view->x, 2); /* move two columns back */
2941 if (view->x <= 0)
2942 view->count = 0;
2943 break;
2944 case 'k':
2945 case KEY_UP:
2946 case '<':
2947 case ',':
2948 case CTRL('p'):
2949 log_move_cursor_up(view, 0, 0);
2950 break;
2951 case 'g':
2952 case KEY_HOME:
2953 log_move_cursor_up(view, 0, 1);
2954 view->count = 0;
2955 break;
2956 case CTRL('u'):
2957 case 'u':
2958 nscroll /= 2;
2959 /* FALL THROUGH */
2960 case KEY_PPAGE:
2961 case CTRL('b'):
2962 case 'b':
2963 log_move_cursor_up(view, nscroll, 0);
2964 break;
2965 case 'j':
2966 case KEY_DOWN:
2967 case '>':
2968 case '.':
2969 case CTRL('n'):
2970 err = log_move_cursor_down(view, 0);
2971 break;
2972 case 'G':
2973 case KEY_END: {
2974 /* We don't know yet how many commits, so we're forced to
2975 * traverse them all. */
2976 view->count = 0;
2977 if (!s->thread_args.log_complete) {
2978 s->thread_args.load_all = 1;
2979 return trigger_log_thread(view, 0);
2982 s->selected = 0;
2983 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
2984 for (n = 0; n < eos; n++) {
2985 if (entry == NULL)
2986 break;
2987 s->first_displayed_entry = entry;
2988 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2990 if (n > 0)
2991 s->selected = n - 1;
2992 select_commit(s);
2993 break;
2995 case CTRL('d'):
2996 case 'd':
2997 nscroll /= 2;
2998 /* FALL THROUGH */
2999 case KEY_NPAGE:
3000 case CTRL('f'):
3001 case 'f':
3002 case ' ':
3003 err = log_move_cursor_down(view, nscroll);
3004 break;
3005 case KEY_RESIZE:
3006 if (s->selected > view->nlines - 2)
3007 s->selected = view->nlines - 2;
3008 if (s->selected > s->commits.ncommits - 1)
3009 s->selected = s->commits.ncommits - 1;
3010 select_commit(s);
3011 if (s->commits.ncommits < view->nlines - 1 &&
3012 !s->thread_args.log_complete) {
3013 s->thread_args.commits_needed += (view->nlines - 1) -
3014 s->commits.ncommits;
3015 err = trigger_log_thread(view, 1);
3017 break;
3018 case KEY_ENTER:
3019 case '\r': {
3020 view->count = 0;
3021 if (s->selected_entry == NULL)
3022 break;
3024 /* get dimensions--don't split till initialisation succeeds */
3025 if (view_is_parent_view(view))
3026 view_get_split(view, &begin_y, &begin_x);
3028 err = open_diff_view_for_commit(&diff_view, begin_y, begin_x,
3029 s->selected_entry->commit, s->selected_entry->id,
3030 view, s->repo);
3031 if (err)
3032 break;
3034 if (view->mode == TOG_VIEW_SPLIT_HRZN) { /* safe to split */
3035 err = view_init_hsplit(view, begin_y);
3036 if (err)
3037 break;
3040 view->focussed = 0;
3041 diff_view->focussed = 1;
3042 diff_view->mode = view->mode;
3043 diff_view->nlines = view->lines - begin_y;
3045 if (view_is_parent_view(view)) {
3046 err = view_close_child(view);
3047 if (err)
3048 return err;
3049 err = view_set_child(view, diff_view);
3050 if (err)
3051 return err;
3052 view->focus_child = 1;
3053 } else
3054 *new_view = diff_view;
3055 break;
3057 case 't':
3058 view->count = 0;
3059 if (s->selected_entry == NULL)
3060 break;
3061 if (view_is_parent_view(view))
3062 begin_x = view_split_begin_x(view->begin_x);
3063 err = browse_commit_tree(&tree_view, begin_x,
3064 s->selected_entry, s->in_repo_path, s->head_ref_name,
3065 s->repo);
3066 if (err)
3067 break;
3068 view->focussed = 0;
3069 tree_view->focussed = 1;
3070 if (view_is_parent_view(view)) {
3071 err = view_close_child(view);
3072 if (err)
3073 return err;
3074 err = view_set_child(view, tree_view);
3075 if (err)
3076 return err;
3077 view->focus_child = 1;
3078 } else
3079 *new_view = tree_view;
3080 break;
3081 case KEY_BACKSPACE:
3082 case CTRL('l'):
3083 case 'B':
3084 view->count = 0;
3085 if (ch == KEY_BACKSPACE &&
3086 got_path_is_root_dir(s->in_repo_path))
3087 break;
3088 err = stop_log_thread(s);
3089 if (err)
3090 return err;
3091 if (ch == KEY_BACKSPACE) {
3092 char *parent_path;
3093 err = got_path_dirname(&parent_path, s->in_repo_path);
3094 if (err)
3095 return err;
3096 free(s->in_repo_path);
3097 s->in_repo_path = parent_path;
3098 s->thread_args.in_repo_path = s->in_repo_path;
3099 } else if (ch == CTRL('l')) {
3100 struct got_object_id *start_id;
3101 err = got_repo_match_object_id(&start_id, NULL,
3102 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3103 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3104 if (err)
3105 return err;
3106 free(s->start_id);
3107 s->start_id = start_id;
3108 s->thread_args.start_id = s->start_id;
3109 } else /* 'B' */
3110 s->log_branches = !s->log_branches;
3112 if (s->thread_args.pack_fds == NULL) {
3113 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3114 if (err)
3115 return err;
3117 err = got_repo_open(&s->thread_args.repo,
3118 got_repo_get_path(s->repo), NULL,
3119 s->thread_args.pack_fds);
3120 if (err)
3121 return err;
3122 tog_free_refs();
3123 err = tog_load_refs(s->repo, 0);
3124 if (err)
3125 return err;
3126 err = got_commit_graph_open(&s->thread_args.graph,
3127 s->in_repo_path, !s->log_branches);
3128 if (err)
3129 return err;
3130 err = got_commit_graph_iter_start(s->thread_args.graph,
3131 s->start_id, s->repo, NULL, NULL);
3132 if (err)
3133 return err;
3134 free_commits(&s->commits);
3135 s->first_displayed_entry = NULL;
3136 s->last_displayed_entry = NULL;
3137 s->selected_entry = NULL;
3138 s->selected = 0;
3139 s->thread_args.log_complete = 0;
3140 s->quit = 0;
3141 s->thread_args.commits_needed = view->lines;
3142 s->matched_entry = NULL;
3143 s->search_entry = NULL;
3144 break;
3145 case 'r':
3146 view->count = 0;
3147 if (view_is_parent_view(view))
3148 begin_x = view_split_begin_x(view->begin_x);
3149 ref_view = view_open(view->nlines, view->ncols,
3150 view->begin_y, begin_x, TOG_VIEW_REF);
3151 if (ref_view == NULL)
3152 return got_error_from_errno("view_open");
3153 err = open_ref_view(ref_view, s->repo);
3154 if (err) {
3155 view_close(ref_view);
3156 return err;
3158 view->focussed = 0;
3159 ref_view->focussed = 1;
3160 if (view_is_parent_view(view)) {
3161 err = view_close_child(view);
3162 if (err)
3163 return err;
3164 err = view_set_child(view, ref_view);
3165 if (err)
3166 return err;
3167 view->focus_child = 1;
3168 } else
3169 *new_view = ref_view;
3170 break;
3171 default:
3172 view->count = 0;
3173 break;
3176 return err;
3179 static const struct got_error *
3180 apply_unveil(const char *repo_path, const char *worktree_path)
3182 const struct got_error *error;
3184 #ifdef PROFILE
3185 if (unveil("gmon.out", "rwc") != 0)
3186 return got_error_from_errno2("unveil", "gmon.out");
3187 #endif
3188 if (repo_path && unveil(repo_path, "r") != 0)
3189 return got_error_from_errno2("unveil", repo_path);
3191 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3192 return got_error_from_errno2("unveil", worktree_path);
3194 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3195 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3197 error = got_privsep_unveil_exec_helpers();
3198 if (error != NULL)
3199 return error;
3201 if (unveil(NULL, NULL) != 0)
3202 return got_error_from_errno("unveil");
3204 return NULL;
3207 static void
3208 init_curses(void)
3211 * Override default signal handlers before starting ncurses.
3212 * This should prevent ncurses from installing its own
3213 * broken cleanup() signal handler.
3215 signal(SIGWINCH, tog_sigwinch);
3216 signal(SIGPIPE, tog_sigpipe);
3217 signal(SIGCONT, tog_sigcont);
3218 signal(SIGINT, tog_sigint);
3219 signal(SIGTERM, tog_sigterm);
3221 initscr();
3222 cbreak();
3223 halfdelay(1); /* Do fast refresh while initial view is loading. */
3224 noecho();
3225 nonl();
3226 intrflush(stdscr, FALSE);
3227 keypad(stdscr, TRUE);
3228 curs_set(0);
3229 if (getenv("TOG_COLORS") != NULL) {
3230 start_color();
3231 use_default_colors();
3235 static const struct got_error *
3236 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3237 struct got_repository *repo, struct got_worktree *worktree)
3239 const struct got_error *err = NULL;
3241 if (argc == 0) {
3242 *in_repo_path = strdup("/");
3243 if (*in_repo_path == NULL)
3244 return got_error_from_errno("strdup");
3245 return NULL;
3248 if (worktree) {
3249 const char *prefix = got_worktree_get_path_prefix(worktree);
3250 char *p;
3252 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3253 if (err)
3254 return err;
3255 if (asprintf(in_repo_path, "%s%s%s", prefix,
3256 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3257 p) == -1) {
3258 err = got_error_from_errno("asprintf");
3259 *in_repo_path = NULL;
3261 free(p);
3262 } else
3263 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3265 return err;
3268 static const struct got_error *
3269 cmd_log(int argc, char *argv[])
3271 const struct got_error *error;
3272 struct got_repository *repo = NULL;
3273 struct got_worktree *worktree = NULL;
3274 struct got_object_id *start_id = NULL;
3275 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3276 char *start_commit = NULL, *label = NULL;
3277 struct got_reference *ref = NULL;
3278 const char *head_ref_name = NULL;
3279 int ch, log_branches = 0;
3280 struct tog_view *view;
3281 int *pack_fds = NULL;
3283 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3284 switch (ch) {
3285 case 'b':
3286 log_branches = 1;
3287 break;
3288 case 'c':
3289 start_commit = optarg;
3290 break;
3291 case 'r':
3292 repo_path = realpath(optarg, NULL);
3293 if (repo_path == NULL)
3294 return got_error_from_errno2("realpath",
3295 optarg);
3296 break;
3297 default:
3298 usage_log();
3299 /* NOTREACHED */
3303 argc -= optind;
3304 argv += optind;
3306 if (argc > 1)
3307 usage_log();
3309 error = got_repo_pack_fds_open(&pack_fds);
3310 if (error != NULL)
3311 goto done;
3313 if (repo_path == NULL) {
3314 cwd = getcwd(NULL, 0);
3315 if (cwd == NULL)
3316 return got_error_from_errno("getcwd");
3317 error = got_worktree_open(&worktree, cwd);
3318 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3319 goto done;
3320 if (worktree)
3321 repo_path =
3322 strdup(got_worktree_get_repo_path(worktree));
3323 else
3324 repo_path = strdup(cwd);
3325 if (repo_path == NULL) {
3326 error = got_error_from_errno("strdup");
3327 goto done;
3331 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3332 if (error != NULL)
3333 goto done;
3335 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3336 repo, worktree);
3337 if (error)
3338 goto done;
3340 init_curses();
3342 error = apply_unveil(got_repo_get_path(repo),
3343 worktree ? got_worktree_get_root_path(worktree) : NULL);
3344 if (error)
3345 goto done;
3347 /* already loaded by tog_log_with_path()? */
3348 if (TAILQ_EMPTY(&tog_refs)) {
3349 error = tog_load_refs(repo, 0);
3350 if (error)
3351 goto done;
3354 if (start_commit == NULL) {
3355 error = got_repo_match_object_id(&start_id, &label,
3356 worktree ? got_worktree_get_head_ref_name(worktree) :
3357 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3358 if (error)
3359 goto done;
3360 head_ref_name = label;
3361 } else {
3362 error = got_ref_open(&ref, repo, start_commit, 0);
3363 if (error == NULL)
3364 head_ref_name = got_ref_get_name(ref);
3365 else if (error->code != GOT_ERR_NOT_REF)
3366 goto done;
3367 error = got_repo_match_object_id(&start_id, NULL,
3368 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3369 if (error)
3370 goto done;
3373 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3374 if (view == NULL) {
3375 error = got_error_from_errno("view_open");
3376 goto done;
3378 error = open_log_view(view, start_id, repo, head_ref_name,
3379 in_repo_path, log_branches);
3380 if (error)
3381 goto done;
3382 if (worktree) {
3383 /* Release work tree lock. */
3384 got_worktree_close(worktree);
3385 worktree = NULL;
3387 error = view_loop(view);
3388 done:
3389 free(in_repo_path);
3390 free(repo_path);
3391 free(cwd);
3392 free(start_id);
3393 free(label);
3394 if (ref)
3395 got_ref_close(ref);
3396 if (repo) {
3397 const struct got_error *close_err = got_repo_close(repo);
3398 if (error == NULL)
3399 error = close_err;
3401 if (worktree)
3402 got_worktree_close(worktree);
3403 if (pack_fds) {
3404 const struct got_error *pack_err =
3405 got_repo_pack_fds_close(pack_fds);
3406 if (error == NULL)
3407 error = pack_err;
3409 tog_free_refs();
3410 return error;
3413 __dead static void
3414 usage_diff(void)
3416 endwin();
3417 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3418 "[-w] object1 object2\n", getprogname());
3419 exit(1);
3422 static int
3423 match_line(const char *line, regex_t *regex, size_t nmatch,
3424 regmatch_t *regmatch)
3426 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3429 static struct tog_color *
3430 match_color(struct tog_colors *colors, const char *line)
3432 struct tog_color *tc = NULL;
3434 STAILQ_FOREACH(tc, colors, entry) {
3435 if (match_line(line, &tc->regex, 0, NULL))
3436 return tc;
3439 return NULL;
3442 static const struct got_error *
3443 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3444 WINDOW *window, int skipcol, regmatch_t *regmatch)
3446 const struct got_error *err = NULL;
3447 char *exstr = NULL;
3448 wchar_t *wline = NULL;
3449 int rme, rms, n, width, scrollx;
3450 int width0 = 0, width1 = 0, width2 = 0;
3451 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3453 *wtotal = 0;
3455 rms = regmatch->rm_so;
3456 rme = regmatch->rm_eo;
3458 err = expand_tab(&exstr, line);
3459 if (err)
3460 return err;
3462 /* Split the line into 3 segments, according to match offsets. */
3463 seg0 = strndup(exstr, rms);
3464 if (seg0 == NULL) {
3465 err = got_error_from_errno("strndup");
3466 goto done;
3468 seg1 = strndup(exstr + rms, rme - rms);
3469 if (seg1 == NULL) {
3470 err = got_error_from_errno("strndup");
3471 goto done;
3473 seg2 = strdup(exstr + rme);
3474 if (seg2 == NULL) {
3475 err = got_error_from_errno("strndup");
3476 goto done;
3479 /* draw up to matched token if we haven't scrolled past it */
3480 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3481 col_tab_align, 1);
3482 if (err)
3483 goto done;
3484 n = MAX(width0 - skipcol, 0);
3485 if (n) {
3486 free(wline);
3487 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3488 wlimit, col_tab_align, 1);
3489 if (err)
3490 goto done;
3491 waddwstr(window, &wline[scrollx]);
3492 wlimit -= width;
3493 *wtotal += width;
3496 if (wlimit > 0) {
3497 int i = 0, w = 0;
3498 size_t wlen;
3500 free(wline);
3501 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3502 col_tab_align, 1);
3503 if (err)
3504 goto done;
3505 wlen = wcslen(wline);
3506 while (i < wlen) {
3507 width = wcwidth(wline[i]);
3508 if (width == -1) {
3509 /* should not happen, tabs are expanded */
3510 err = got_error(GOT_ERR_RANGE);
3511 goto done;
3513 if (width0 + w + width > skipcol)
3514 break;
3515 w += width;
3516 i++;
3518 /* draw (visible part of) matched token (if scrolled into it) */
3519 if (width1 - w > 0) {
3520 wattron(window, A_STANDOUT);
3521 waddwstr(window, &wline[i]);
3522 wattroff(window, A_STANDOUT);
3523 wlimit -= (width1 - w);
3524 *wtotal += (width1 - w);
3528 if (wlimit > 0) { /* draw rest of line */
3529 free(wline);
3530 if (skipcol > width0 + width1) {
3531 err = format_line(&wline, &width2, &scrollx, seg2,
3532 skipcol - (width0 + width1), wlimit,
3533 col_tab_align, 1);
3534 if (err)
3535 goto done;
3536 waddwstr(window, &wline[scrollx]);
3537 } else {
3538 err = format_line(&wline, &width2, NULL, seg2, 0,
3539 wlimit, col_tab_align, 1);
3540 if (err)
3541 goto done;
3542 waddwstr(window, wline);
3544 *wtotal += width2;
3546 done:
3547 free(wline);
3548 free(exstr);
3549 free(seg0);
3550 free(seg1);
3551 free(seg2);
3552 return err;
3555 static const struct got_error *
3556 draw_file(struct tog_view *view, const char *header)
3558 struct tog_diff_view_state *s = &view->state.diff;
3559 regmatch_t *regmatch = &view->regmatch;
3560 const struct got_error *err;
3561 int nprinted = 0;
3562 char *line;
3563 size_t linesize = 0;
3564 ssize_t linelen;
3565 struct tog_color *tc;
3566 wchar_t *wline;
3567 int width;
3568 int max_lines = view->nlines;
3569 int nlines = s->nlines;
3570 off_t line_offset;
3572 line_offset = s->line_offsets[s->first_displayed_line - 1];
3573 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3574 return got_error_from_errno("fseek");
3576 werase(view->window);
3578 if (header) {
3579 if (asprintf(&line, "[%d/%d] %s",
3580 s->first_displayed_line - 1 + s->selected_line, nlines,
3581 header) == -1)
3582 return got_error_from_errno("asprintf");
3583 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3584 0, 0);
3585 free(line);
3586 if (err)
3587 return err;
3589 if (view_needs_focus_indication(view))
3590 wstandout(view->window);
3591 waddwstr(view->window, wline);
3592 free(wline);
3593 wline = NULL;
3594 if (view_needs_focus_indication(view))
3595 wstandend(view->window);
3596 if (width <= view->ncols - 1)
3597 waddch(view->window, '\n');
3599 if (max_lines <= 1)
3600 return NULL;
3601 max_lines--;
3604 s->eof = 0;
3605 view->maxx = 0;
3606 line = NULL;
3607 while (max_lines > 0 && nprinted < max_lines) {
3608 linelen = getline(&line, &linesize, s->f);
3609 if (linelen == -1) {
3610 if (feof(s->f)) {
3611 s->eof = 1;
3612 break;
3614 free(line);
3615 return got_ferror(s->f, GOT_ERR_IO);
3618 /* Set view->maxx based on full line length. */
3619 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3620 view->x ? 1 : 0);
3621 if (err) {
3622 free(line);
3623 return err;
3625 view->maxx = MAX(view->maxx, width);
3626 free(wline);
3627 wline = NULL;
3629 tc = match_color(&s->colors, line);
3630 if (tc)
3631 wattr_on(view->window,
3632 COLOR_PAIR(tc->colorpair), NULL);
3633 if (s->first_displayed_line + nprinted == s->matched_line &&
3634 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3635 err = add_matched_line(&width, line, view->ncols, 0,
3636 view->window, view->x, regmatch);
3637 if (err) {
3638 free(line);
3639 return err;
3641 } else {
3642 int skip;
3643 err = format_line(&wline, &width, &skip, line,
3644 view->x, view->ncols, 0, view->x ? 1 : 0);
3645 if (err) {
3646 free(line);
3647 return err;
3649 waddwstr(view->window, &wline[skip]);
3650 free(wline);
3651 wline = NULL;
3653 if (tc)
3654 wattr_off(view->window,
3655 COLOR_PAIR(tc->colorpair), NULL);
3656 if (width <= view->ncols - 1)
3657 waddch(view->window, '\n');
3658 nprinted++;
3660 free(line);
3661 if (nprinted >= 1)
3662 s->last_displayed_line = s->first_displayed_line +
3663 (nprinted - 1);
3664 else
3665 s->last_displayed_line = s->first_displayed_line;
3667 view_border(view);
3669 if (s->eof) {
3670 while (nprinted < view->nlines) {
3671 waddch(view->window, '\n');
3672 nprinted++;
3675 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3676 view->ncols, 0, 0);
3677 if (err) {
3678 return err;
3681 wstandout(view->window);
3682 waddwstr(view->window, wline);
3683 free(wline);
3684 wline = NULL;
3685 wstandend(view->window);
3688 return NULL;
3691 static char *
3692 get_datestr(time_t *time, char *datebuf)
3694 struct tm mytm, *tm;
3695 char *p, *s;
3697 tm = gmtime_r(time, &mytm);
3698 if (tm == NULL)
3699 return NULL;
3700 s = asctime_r(tm, datebuf);
3701 if (s == NULL)
3702 return NULL;
3703 p = strchr(s, '\n');
3704 if (p)
3705 *p = '\0';
3706 return s;
3709 static const struct got_error *
3710 get_changed_paths(struct got_pathlist_head *paths,
3711 struct got_commit_object *commit, struct got_repository *repo)
3713 const struct got_error *err = NULL;
3714 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3715 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3716 struct got_object_qid *qid;
3718 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3719 if (qid != NULL) {
3720 struct got_commit_object *pcommit;
3721 err = got_object_open_as_commit(&pcommit, repo,
3722 &qid->id);
3723 if (err)
3724 return err;
3726 tree_id1 = got_object_id_dup(
3727 got_object_commit_get_tree_id(pcommit));
3728 if (tree_id1 == NULL) {
3729 got_object_commit_close(pcommit);
3730 return got_error_from_errno("got_object_id_dup");
3732 got_object_commit_close(pcommit);
3736 if (tree_id1) {
3737 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3738 if (err)
3739 goto done;
3742 tree_id2 = got_object_commit_get_tree_id(commit);
3743 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3744 if (err)
3745 goto done;
3747 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3748 got_diff_tree_collect_changed_paths, paths, 0);
3749 done:
3750 if (tree1)
3751 got_object_tree_close(tree1);
3752 if (tree2)
3753 got_object_tree_close(tree2);
3754 free(tree_id1);
3755 return err;
3758 static const struct got_error *
3759 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
3761 off_t *p;
3763 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
3764 if (p == NULL)
3765 return got_error_from_errno("reallocarray");
3766 *line_offsets = p;
3767 (*line_offsets)[*nlines] = off;
3768 (*nlines)++;
3769 return NULL;
3772 static const struct got_error *
3773 write_commit_info(off_t **line_offsets, size_t *nlines,
3774 struct got_object_id *commit_id, struct got_reflist_head *refs,
3775 struct got_repository *repo, FILE *outfile)
3777 const struct got_error *err = NULL;
3778 char datebuf[26], *datestr;
3779 struct got_commit_object *commit;
3780 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
3781 time_t committer_time;
3782 const char *author, *committer;
3783 char *refs_str = NULL;
3784 struct got_pathlist_head changed_paths;
3785 struct got_pathlist_entry *pe;
3786 off_t outoff = 0;
3787 int n;
3789 TAILQ_INIT(&changed_paths);
3791 if (refs) {
3792 err = build_refs_str(&refs_str, refs, commit_id, repo);
3793 if (err)
3794 return err;
3797 err = got_object_open_as_commit(&commit, repo, commit_id);
3798 if (err)
3799 return err;
3801 err = got_object_id_str(&id_str, commit_id);
3802 if (err) {
3803 err = got_error_from_errno("got_object_id_str");
3804 goto done;
3807 err = add_line_offset(line_offsets, nlines, 0);
3808 if (err)
3809 goto done;
3811 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3812 refs_str ? refs_str : "", refs_str ? ")" : "");
3813 if (n < 0) {
3814 err = got_error_from_errno("fprintf");
3815 goto done;
3817 outoff += n;
3818 err = add_line_offset(line_offsets, nlines, outoff);
3819 if (err)
3820 goto done;
3822 n = fprintf(outfile, "from: %s\n",
3823 got_object_commit_get_author(commit));
3824 if (n < 0) {
3825 err = got_error_from_errno("fprintf");
3826 goto done;
3828 outoff += n;
3829 err = add_line_offset(line_offsets, nlines, outoff);
3830 if (err)
3831 goto done;
3833 committer_time = got_object_commit_get_committer_time(commit);
3834 datestr = get_datestr(&committer_time, datebuf);
3835 if (datestr) {
3836 n = fprintf(outfile, "date: %s UTC\n", datestr);
3837 if (n < 0) {
3838 err = got_error_from_errno("fprintf");
3839 goto done;
3841 outoff += n;
3842 err = add_line_offset(line_offsets, nlines, outoff);
3843 if (err)
3844 goto done;
3846 author = got_object_commit_get_author(commit);
3847 committer = got_object_commit_get_committer(commit);
3848 if (strcmp(author, committer) != 0) {
3849 n = fprintf(outfile, "via: %s\n", committer);
3850 if (n < 0) {
3851 err = got_error_from_errno("fprintf");
3852 goto done;
3854 outoff += n;
3855 err = add_line_offset(line_offsets, nlines, outoff);
3856 if (err)
3857 goto done;
3859 if (got_object_commit_get_nparents(commit) > 1) {
3860 const struct got_object_id_queue *parent_ids;
3861 struct got_object_qid *qid;
3862 int pn = 1;
3863 parent_ids = got_object_commit_get_parent_ids(commit);
3864 STAILQ_FOREACH(qid, parent_ids, entry) {
3865 err = got_object_id_str(&id_str, &qid->id);
3866 if (err)
3867 goto done;
3868 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
3869 if (n < 0) {
3870 err = got_error_from_errno("fprintf");
3871 goto done;
3873 outoff += n;
3874 err = add_line_offset(line_offsets, nlines, outoff);
3875 if (err)
3876 goto done;
3877 free(id_str);
3878 id_str = NULL;
3882 err = got_object_commit_get_logmsg(&logmsg, commit);
3883 if (err)
3884 goto done;
3885 s = logmsg;
3886 while ((line = strsep(&s, "\n")) != NULL) {
3887 n = fprintf(outfile, "%s\n", line);
3888 if (n < 0) {
3889 err = got_error_from_errno("fprintf");
3890 goto done;
3892 outoff += n;
3893 err = add_line_offset(line_offsets, nlines, outoff);
3894 if (err)
3895 goto done;
3898 err = get_changed_paths(&changed_paths, commit, repo);
3899 if (err)
3900 goto done;
3901 TAILQ_FOREACH(pe, &changed_paths, entry) {
3902 struct got_diff_changed_path *cp = pe->data;
3903 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
3904 if (n < 0) {
3905 err = got_error_from_errno("fprintf");
3906 goto done;
3908 outoff += n;
3909 err = add_line_offset(line_offsets, nlines, outoff);
3910 if (err)
3911 goto done;
3912 free((char *)pe->path);
3913 free(pe->data);
3916 fputc('\n', outfile);
3917 outoff++;
3918 err = add_line_offset(line_offsets, nlines, outoff);
3919 done:
3920 got_pathlist_free(&changed_paths);
3921 free(id_str);
3922 free(logmsg);
3923 free(refs_str);
3924 got_object_commit_close(commit);
3925 if (err) {
3926 free(*line_offsets);
3927 *line_offsets = NULL;
3928 *nlines = 0;
3930 return err;
3933 static const struct got_error *
3934 create_diff(struct tog_diff_view_state *s)
3936 const struct got_error *err = NULL;
3937 FILE *f = NULL;
3938 int obj_type;
3940 free(s->line_offsets);
3941 s->line_offsets = malloc(sizeof(off_t));
3942 if (s->line_offsets == NULL)
3943 return got_error_from_errno("malloc");
3944 s->nlines = 0;
3946 f = got_opentemp();
3947 if (f == NULL) {
3948 err = got_error_from_errno("got_opentemp");
3949 goto done;
3951 if (s->f && fclose(s->f) == EOF) {
3952 err = got_error_from_errno("fclose");
3953 goto done;
3955 s->f = f;
3957 if (s->id1)
3958 err = got_object_get_type(&obj_type, s->repo, s->id1);
3959 else
3960 err = got_object_get_type(&obj_type, s->repo, s->id2);
3961 if (err)
3962 goto done;
3964 switch (obj_type) {
3965 case GOT_OBJ_TYPE_BLOB:
3966 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
3967 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
3968 s->label1, s->label2, s->diff_context,
3969 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
3970 break;
3971 case GOT_OBJ_TYPE_TREE:
3972 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
3973 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
3974 s->diff_context, s->ignore_whitespace, s->force_text_diff,
3975 s->repo, s->f);
3976 break;
3977 case GOT_OBJ_TYPE_COMMIT: {
3978 const struct got_object_id_queue *parent_ids;
3979 struct got_object_qid *pid;
3980 struct got_commit_object *commit2;
3981 struct got_reflist_head *refs;
3983 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
3984 if (err)
3985 goto done;
3986 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
3987 /* Show commit info if we're diffing to a parent/root commit. */
3988 if (s->id1 == NULL) {
3989 err = write_commit_info(&s->line_offsets, &s->nlines,
3990 s->id2, refs, s->repo, s->f);
3991 if (err)
3992 goto done;
3993 } else {
3994 parent_ids = got_object_commit_get_parent_ids(commit2);
3995 STAILQ_FOREACH(pid, parent_ids, entry) {
3996 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
3997 err = write_commit_info(
3998 &s->line_offsets, &s->nlines,
3999 s->id2, refs, s->repo, s->f);
4000 if (err)
4001 goto done;
4002 break;
4006 got_object_commit_close(commit2);
4008 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
4009 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4010 s->diff_context, s->ignore_whitespace, s->force_text_diff,
4011 s->repo, s->f);
4012 break;
4014 default:
4015 err = got_error(GOT_ERR_OBJ_TYPE);
4016 break;
4018 if (err)
4019 goto done;
4020 done:
4021 if (s->f && fflush(s->f) != 0 && err == NULL)
4022 err = got_error_from_errno("fflush");
4023 return err;
4026 static void
4027 diff_view_indicate_progress(struct tog_view *view)
4029 mvwaddstr(view->window, 0, 0, "diffing...");
4030 update_panels();
4031 doupdate();
4034 static const struct got_error *
4035 search_start_diff_view(struct tog_view *view)
4037 struct tog_diff_view_state *s = &view->state.diff;
4039 s->matched_line = 0;
4040 return NULL;
4043 static const struct got_error *
4044 search_next_diff_view(struct tog_view *view)
4046 struct tog_diff_view_state *s = &view->state.diff;
4047 const struct got_error *err = NULL;
4048 int lineno;
4049 char *line = NULL;
4050 size_t linesize = 0;
4051 ssize_t linelen;
4053 if (!view->searching) {
4054 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4055 return NULL;
4058 if (s->matched_line) {
4059 if (view->searching == TOG_SEARCH_FORWARD)
4060 lineno = s->matched_line + 1;
4061 else
4062 lineno = s->matched_line - 1;
4063 } else
4064 lineno = s->first_displayed_line;
4066 while (1) {
4067 off_t offset;
4069 if (lineno <= 0 || lineno > s->nlines) {
4070 if (s->matched_line == 0) {
4071 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4072 break;
4075 if (view->searching == TOG_SEARCH_FORWARD)
4076 lineno = 1;
4077 else
4078 lineno = s->nlines;
4081 offset = s->line_offsets[lineno - 1];
4082 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4083 free(line);
4084 return got_error_from_errno("fseeko");
4086 linelen = getline(&line, &linesize, s->f);
4087 if (linelen != -1) {
4088 char *exstr;
4089 err = expand_tab(&exstr, line);
4090 if (err)
4091 break;
4092 if (match_line(exstr, &view->regex, 1,
4093 &view->regmatch)) {
4094 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4095 s->matched_line = lineno;
4096 free(exstr);
4097 break;
4099 free(exstr);
4101 if (view->searching == TOG_SEARCH_FORWARD)
4102 lineno++;
4103 else
4104 lineno--;
4106 free(line);
4108 if (s->matched_line) {
4109 s->first_displayed_line = s->matched_line;
4110 s->selected_line = 1;
4113 return err;
4116 static const struct got_error *
4117 close_diff_view(struct tog_view *view)
4119 const struct got_error *err = NULL;
4120 struct tog_diff_view_state *s = &view->state.diff;
4122 free(s->id1);
4123 s->id1 = NULL;
4124 free(s->id2);
4125 s->id2 = NULL;
4126 if (s->f && fclose(s->f) == EOF)
4127 err = got_error_from_errno("fclose");
4128 s->f = NULL;
4129 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4130 err = got_error_from_errno("fclose");
4131 s->f1 = NULL;
4132 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4133 err = got_error_from_errno("fclose");
4134 s->f2 = NULL;
4135 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4136 err = got_error_from_errno("close");
4137 s->fd1 = -1;
4138 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4139 err = got_error_from_errno("close");
4140 s->fd2 = -1;
4141 free_colors(&s->colors);
4142 free(s->line_offsets);
4143 s->line_offsets = NULL;
4144 s->nlines = 0;
4145 return err;
4148 static const struct got_error *
4149 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4150 struct got_object_id *id2, const char *label1, const char *label2,
4151 int diff_context, int ignore_whitespace, int force_text_diff,
4152 struct tog_view *log_view, struct got_repository *repo)
4154 const struct got_error *err;
4155 struct tog_diff_view_state *s = &view->state.diff;
4157 memset(s, 0, sizeof(*s));
4158 s->fd1 = -1;
4159 s->fd2 = -1;
4161 if (id1 != NULL && id2 != NULL) {
4162 int type1, type2;
4163 err = got_object_get_type(&type1, repo, id1);
4164 if (err)
4165 return err;
4166 err = got_object_get_type(&type2, repo, id2);
4167 if (err)
4168 return err;
4170 if (type1 != type2)
4171 return got_error(GOT_ERR_OBJ_TYPE);
4173 s->first_displayed_line = 1;
4174 s->last_displayed_line = view->nlines;
4175 s->selected_line = 1;
4176 s->repo = repo;
4177 s->id1 = id1;
4178 s->id2 = id2;
4179 s->label1 = label1;
4180 s->label2 = label2;
4182 if (id1) {
4183 s->id1 = got_object_id_dup(id1);
4184 if (s->id1 == NULL)
4185 return got_error_from_errno("got_object_id_dup");
4186 } else
4187 s->id1 = NULL;
4189 s->id2 = got_object_id_dup(id2);
4190 if (s->id2 == NULL) {
4191 err = got_error_from_errno("got_object_id_dup");
4192 goto done;
4195 s->f1 = got_opentemp();
4196 if (s->f1 == NULL) {
4197 err = got_error_from_errno("got_opentemp");
4198 goto done;
4201 s->f2 = got_opentemp();
4202 if (s->f2 == NULL) {
4203 err = got_error_from_errno("got_opentemp");
4204 goto done;
4207 s->fd1 = got_opentempfd();
4208 if (s->fd1 == -1) {
4209 err = got_error_from_errno("got_opentempfd");
4210 goto done;
4213 s->fd2 = got_opentempfd();
4214 if (s->fd2 == -1) {
4215 err = got_error_from_errno("got_opentempfd");
4216 goto done;
4219 s->first_displayed_line = 1;
4220 s->last_displayed_line = view->nlines;
4221 s->diff_context = diff_context;
4222 s->ignore_whitespace = ignore_whitespace;
4223 s->force_text_diff = force_text_diff;
4224 s->log_view = log_view;
4225 s->repo = repo;
4227 STAILQ_INIT(&s->colors);
4228 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4229 err = add_color(&s->colors,
4230 "^-", TOG_COLOR_DIFF_MINUS,
4231 get_color_value("TOG_COLOR_DIFF_MINUS"));
4232 if (err)
4233 goto done;
4234 err = add_color(&s->colors, "^\\+",
4235 TOG_COLOR_DIFF_PLUS,
4236 get_color_value("TOG_COLOR_DIFF_PLUS"));
4237 if (err)
4238 goto done;
4239 err = add_color(&s->colors,
4240 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4241 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4242 if (err)
4243 goto done;
4245 err = add_color(&s->colors,
4246 "^(commit [0-9a-f]|parent [0-9]|"
4247 "(blob|file|tree|commit) [-+] |"
4248 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4249 get_color_value("TOG_COLOR_DIFF_META"));
4250 if (err)
4251 goto done;
4253 err = add_color(&s->colors,
4254 "^(from|via): ", TOG_COLOR_AUTHOR,
4255 get_color_value("TOG_COLOR_AUTHOR"));
4256 if (err)
4257 goto done;
4259 err = add_color(&s->colors,
4260 "^date: ", TOG_COLOR_DATE,
4261 get_color_value("TOG_COLOR_DATE"));
4262 if (err)
4263 goto done;
4266 if (log_view && view_is_splitscreen(view))
4267 show_log_view(log_view); /* draw vborder */
4268 diff_view_indicate_progress(view);
4270 err = create_diff(s);
4272 view->show = show_diff_view;
4273 view->input = input_diff_view;
4274 view->close = close_diff_view;
4275 view->search_start = search_start_diff_view;
4276 view->search_next = search_next_diff_view;
4277 done:
4278 if (err)
4279 close_diff_view(view);
4280 return err;
4283 static const struct got_error *
4284 show_diff_view(struct tog_view *view)
4286 const struct got_error *err;
4287 struct tog_diff_view_state *s = &view->state.diff;
4288 char *id_str1 = NULL, *id_str2, *header;
4289 const char *label1, *label2;
4291 if (s->id1) {
4292 err = got_object_id_str(&id_str1, s->id1);
4293 if (err)
4294 return err;
4295 label1 = s->label1 ? : id_str1;
4296 } else
4297 label1 = "/dev/null";
4299 err = got_object_id_str(&id_str2, s->id2);
4300 if (err)
4301 return err;
4302 label2 = s->label2 ? : id_str2;
4304 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4305 err = got_error_from_errno("asprintf");
4306 free(id_str1);
4307 free(id_str2);
4308 return err;
4310 free(id_str1);
4311 free(id_str2);
4313 err = draw_file(view, header);
4314 free(header);
4315 return err;
4318 static const struct got_error *
4319 set_selected_commit(struct tog_diff_view_state *s,
4320 struct commit_queue_entry *entry)
4322 const struct got_error *err;
4323 const struct got_object_id_queue *parent_ids;
4324 struct got_commit_object *selected_commit;
4325 struct got_object_qid *pid;
4327 free(s->id2);
4328 s->id2 = got_object_id_dup(entry->id);
4329 if (s->id2 == NULL)
4330 return got_error_from_errno("got_object_id_dup");
4332 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4333 if (err)
4334 return err;
4335 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4336 free(s->id1);
4337 pid = STAILQ_FIRST(parent_ids);
4338 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4339 got_object_commit_close(selected_commit);
4340 return NULL;
4343 static const struct got_error *
4344 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4346 const struct got_error *err = NULL;
4347 struct tog_diff_view_state *s = &view->state.diff;
4348 struct tog_log_view_state *ls;
4349 struct commit_queue_entry *old_selected_entry;
4350 char *line = NULL;
4351 size_t linesize = 0;
4352 ssize_t linelen;
4353 int i, nscroll = view->nlines - 1;
4355 switch (ch) {
4356 case '0':
4357 view->x = 0;
4358 break;
4359 case '$':
4360 view->x = MAX(view->maxx - view->ncols / 3, 0);
4361 view->count = 0;
4362 break;
4363 case KEY_RIGHT:
4364 case 'l':
4365 if (view->x + view->ncols / 3 < view->maxx)
4366 view->x += 2; /* move two columns right */
4367 else
4368 view->count = 0;
4369 break;
4370 case KEY_LEFT:
4371 case 'h':
4372 view->x -= MIN(view->x, 2); /* move two columns back */
4373 if (view->x <= 0)
4374 view->count = 0;
4375 break;
4376 case 'a':
4377 case 'w':
4378 if (ch == 'a')
4379 s->force_text_diff = !s->force_text_diff;
4380 if (ch == 'w')
4381 s->ignore_whitespace = !s->ignore_whitespace;
4382 wclear(view->window);
4383 s->first_displayed_line = 1;
4384 s->last_displayed_line = view->nlines;
4385 s->matched_line = 0;
4386 diff_view_indicate_progress(view);
4387 err = create_diff(s);
4388 view->count = 0;
4389 break;
4390 case 'g':
4391 case KEY_HOME:
4392 s->first_displayed_line = 1;
4393 view->count = 0;
4394 break;
4395 case 'G':
4396 case KEY_END:
4397 view->count = 0;
4398 if (s->eof)
4399 break;
4401 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4402 s->eof = 1;
4403 break;
4404 case 'k':
4405 case KEY_UP:
4406 case CTRL('p'):
4407 if (s->first_displayed_line > 1)
4408 s->first_displayed_line--;
4409 else
4410 view->count = 0;
4411 break;
4412 case CTRL('u'):
4413 case 'u':
4414 nscroll /= 2;
4415 /* FALL THROUGH */
4416 case KEY_PPAGE:
4417 case CTRL('b'):
4418 case 'b':
4419 if (s->first_displayed_line == 1) {
4420 view->count = 0;
4421 break;
4423 i = 0;
4424 while (i++ < nscroll && s->first_displayed_line > 1)
4425 s->first_displayed_line--;
4426 break;
4427 case 'j':
4428 case KEY_DOWN:
4429 case CTRL('n'):
4430 if (!s->eof)
4431 s->first_displayed_line++;
4432 else
4433 view->count = 0;
4434 break;
4435 case CTRL('d'):
4436 case 'd':
4437 nscroll /= 2;
4438 /* FALL THROUGH */
4439 case KEY_NPAGE:
4440 case CTRL('f'):
4441 case 'f':
4442 case ' ':
4443 if (s->eof) {
4444 view->count = 0;
4445 break;
4447 i = 0;
4448 while (!s->eof && i++ < nscroll) {
4449 linelen = getline(&line, &linesize, s->f);
4450 s->first_displayed_line++;
4451 if (linelen == -1) {
4452 if (feof(s->f)) {
4453 s->eof = 1;
4454 } else
4455 err = got_ferror(s->f, GOT_ERR_IO);
4456 break;
4459 free(line);
4460 break;
4461 case '[':
4462 if (s->diff_context > 0) {
4463 s->diff_context--;
4464 s->matched_line = 0;
4465 diff_view_indicate_progress(view);
4466 err = create_diff(s);
4467 if (s->first_displayed_line + view->nlines - 1 >
4468 s->nlines) {
4469 s->first_displayed_line = 1;
4470 s->last_displayed_line = view->nlines;
4472 } else
4473 view->count = 0;
4474 break;
4475 case ']':
4476 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4477 s->diff_context++;
4478 s->matched_line = 0;
4479 diff_view_indicate_progress(view);
4480 err = create_diff(s);
4481 } else
4482 view->count = 0;
4483 break;
4484 case '<':
4485 case ',':
4486 if (s->log_view == NULL) {
4487 view->count = 0;
4488 break;
4490 ls = &s->log_view->state.log;
4491 old_selected_entry = ls->selected_entry;
4493 /* view->count handled in input_log_view() */
4494 err = input_log_view(NULL, s->log_view, KEY_UP);
4495 if (err)
4496 break;
4498 if (old_selected_entry == ls->selected_entry)
4499 break;
4501 err = set_selected_commit(s, ls->selected_entry);
4502 if (err)
4503 break;
4505 s->first_displayed_line = 1;
4506 s->last_displayed_line = view->nlines;
4507 s->matched_line = 0;
4508 view->x = 0;
4510 diff_view_indicate_progress(view);
4511 err = create_diff(s);
4512 break;
4513 case '>':
4514 case '.':
4515 if (s->log_view == NULL) {
4516 view->count = 0;
4517 break;
4519 ls = &s->log_view->state.log;
4520 old_selected_entry = ls->selected_entry;
4522 /* view->count handled in input_log_view() */
4523 err = input_log_view(NULL, s->log_view, KEY_DOWN);
4524 if (err)
4525 break;
4527 if (old_selected_entry == ls->selected_entry)
4528 break;
4530 err = set_selected_commit(s, ls->selected_entry);
4531 if (err)
4532 break;
4534 s->first_displayed_line = 1;
4535 s->last_displayed_line = view->nlines;
4536 s->matched_line = 0;
4537 view->x = 0;
4539 diff_view_indicate_progress(view);
4540 err = create_diff(s);
4541 break;
4542 default:
4543 view->count = 0;
4544 break;
4547 return err;
4550 static const struct got_error *
4551 cmd_diff(int argc, char *argv[])
4553 const struct got_error *error = NULL;
4554 struct got_repository *repo = NULL;
4555 struct got_worktree *worktree = NULL;
4556 struct got_object_id *id1 = NULL, *id2 = NULL;
4557 char *repo_path = NULL, *cwd = NULL;
4558 char *id_str1 = NULL, *id_str2 = NULL;
4559 char *label1 = NULL, *label2 = NULL;
4560 int diff_context = 3, ignore_whitespace = 0;
4561 int ch, force_text_diff = 0;
4562 const char *errstr;
4563 struct tog_view *view;
4564 int *pack_fds = NULL;
4566 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4567 switch (ch) {
4568 case 'a':
4569 force_text_diff = 1;
4570 break;
4571 case 'C':
4572 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4573 &errstr);
4574 if (errstr != NULL)
4575 errx(1, "number of context lines is %s: %s",
4576 errstr, errstr);
4577 break;
4578 case 'r':
4579 repo_path = realpath(optarg, NULL);
4580 if (repo_path == NULL)
4581 return got_error_from_errno2("realpath",
4582 optarg);
4583 got_path_strip_trailing_slashes(repo_path);
4584 break;
4585 case 'w':
4586 ignore_whitespace = 1;
4587 break;
4588 default:
4589 usage_diff();
4590 /* NOTREACHED */
4594 argc -= optind;
4595 argv += optind;
4597 if (argc == 0) {
4598 usage_diff(); /* TODO show local worktree changes */
4599 } else if (argc == 2) {
4600 id_str1 = argv[0];
4601 id_str2 = argv[1];
4602 } else
4603 usage_diff();
4605 error = got_repo_pack_fds_open(&pack_fds);
4606 if (error)
4607 goto done;
4609 if (repo_path == NULL) {
4610 cwd = getcwd(NULL, 0);
4611 if (cwd == NULL)
4612 return got_error_from_errno("getcwd");
4613 error = got_worktree_open(&worktree, cwd);
4614 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4615 goto done;
4616 if (worktree)
4617 repo_path =
4618 strdup(got_worktree_get_repo_path(worktree));
4619 else
4620 repo_path = strdup(cwd);
4621 if (repo_path == NULL) {
4622 error = got_error_from_errno("strdup");
4623 goto done;
4627 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4628 if (error)
4629 goto done;
4631 init_curses();
4633 error = apply_unveil(got_repo_get_path(repo), NULL);
4634 if (error)
4635 goto done;
4637 error = tog_load_refs(repo, 0);
4638 if (error)
4639 goto done;
4641 error = got_repo_match_object_id(&id1, &label1, id_str1,
4642 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4643 if (error)
4644 goto done;
4646 error = got_repo_match_object_id(&id2, &label2, id_str2,
4647 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4648 if (error)
4649 goto done;
4651 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4652 if (view == NULL) {
4653 error = got_error_from_errno("view_open");
4654 goto done;
4656 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4657 ignore_whitespace, force_text_diff, NULL, repo);
4658 if (error)
4659 goto done;
4660 error = view_loop(view);
4661 done:
4662 free(label1);
4663 free(label2);
4664 free(repo_path);
4665 free(cwd);
4666 if (repo) {
4667 const struct got_error *close_err = got_repo_close(repo);
4668 if (error == NULL)
4669 error = close_err;
4671 if (worktree)
4672 got_worktree_close(worktree);
4673 if (pack_fds) {
4674 const struct got_error *pack_err =
4675 got_repo_pack_fds_close(pack_fds);
4676 if (error == NULL)
4677 error = pack_err;
4679 tog_free_refs();
4680 return error;
4683 __dead static void
4684 usage_blame(void)
4686 endwin();
4687 fprintf(stderr,
4688 "usage: %s blame [-c commit] [-r repository-path] path\n",
4689 getprogname());
4690 exit(1);
4693 struct tog_blame_line {
4694 int annotated;
4695 struct got_object_id *id;
4698 static const struct got_error *
4699 draw_blame(struct tog_view *view)
4701 struct tog_blame_view_state *s = &view->state.blame;
4702 struct tog_blame *blame = &s->blame;
4703 regmatch_t *regmatch = &view->regmatch;
4704 const struct got_error *err;
4705 int lineno = 0, nprinted = 0;
4706 char *line = NULL;
4707 size_t linesize = 0;
4708 ssize_t linelen;
4709 wchar_t *wline;
4710 int width;
4711 struct tog_blame_line *blame_line;
4712 struct got_object_id *prev_id = NULL;
4713 char *id_str;
4714 struct tog_color *tc;
4716 err = got_object_id_str(&id_str, &s->blamed_commit->id);
4717 if (err)
4718 return err;
4720 rewind(blame->f);
4721 werase(view->window);
4723 if (asprintf(&line, "commit %s", id_str) == -1) {
4724 err = got_error_from_errno("asprintf");
4725 free(id_str);
4726 return err;
4729 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4730 free(line);
4731 line = NULL;
4732 if (err)
4733 return err;
4734 if (view_needs_focus_indication(view))
4735 wstandout(view->window);
4736 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4737 if (tc)
4738 wattr_on(view->window,
4739 COLOR_PAIR(tc->colorpair), NULL);
4740 waddwstr(view->window, wline);
4741 if (tc)
4742 wattr_off(view->window,
4743 COLOR_PAIR(tc->colorpair), NULL);
4744 if (view_needs_focus_indication(view))
4745 wstandend(view->window);
4746 free(wline);
4747 wline = NULL;
4748 if (width < view->ncols - 1)
4749 waddch(view->window, '\n');
4751 if (asprintf(&line, "[%d/%d] %s%s",
4752 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
4753 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
4754 free(id_str);
4755 return got_error_from_errno("asprintf");
4757 free(id_str);
4758 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4759 free(line);
4760 line = NULL;
4761 if (err)
4762 return err;
4763 waddwstr(view->window, wline);
4764 free(wline);
4765 wline = NULL;
4766 if (width < view->ncols - 1)
4767 waddch(view->window, '\n');
4769 s->eof = 0;
4770 view->maxx = 0;
4771 while (nprinted < view->nlines - 2) {
4772 linelen = getline(&line, &linesize, blame->f);
4773 if (linelen == -1) {
4774 if (feof(blame->f)) {
4775 s->eof = 1;
4776 break;
4778 free(line);
4779 return got_ferror(blame->f, GOT_ERR_IO);
4781 if (++lineno < s->first_displayed_line)
4782 continue;
4784 /* Set view->maxx based on full line length. */
4785 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
4786 if (err) {
4787 free(line);
4788 return err;
4790 free(wline);
4791 wline = NULL;
4792 view->maxx = MAX(view->maxx, width);
4794 if (view->focussed && nprinted == s->selected_line - 1)
4795 wstandout(view->window);
4797 if (blame->nlines > 0) {
4798 blame_line = &blame->lines[lineno - 1];
4799 if (blame_line->annotated && prev_id &&
4800 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
4801 !(view->focussed &&
4802 nprinted == s->selected_line - 1)) {
4803 waddstr(view->window, " ");
4804 } else if (blame_line->annotated) {
4805 char *id_str;
4806 err = got_object_id_str(&id_str,
4807 blame_line->id);
4808 if (err) {
4809 free(line);
4810 return err;
4812 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4813 if (tc)
4814 wattr_on(view->window,
4815 COLOR_PAIR(tc->colorpair), NULL);
4816 wprintw(view->window, "%.8s", id_str);
4817 if (tc)
4818 wattr_off(view->window,
4819 COLOR_PAIR(tc->colorpair), NULL);
4820 free(id_str);
4821 prev_id = blame_line->id;
4822 } else {
4823 waddstr(view->window, "........");
4824 prev_id = NULL;
4826 } else {
4827 waddstr(view->window, "........");
4828 prev_id = NULL;
4831 if (view->focussed && nprinted == s->selected_line - 1)
4832 wstandend(view->window);
4833 waddstr(view->window, " ");
4835 if (view->ncols <= 9) {
4836 width = 9;
4837 } else if (s->first_displayed_line + nprinted ==
4838 s->matched_line &&
4839 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4840 err = add_matched_line(&width, line, view->ncols - 9, 9,
4841 view->window, view->x, regmatch);
4842 if (err) {
4843 free(line);
4844 return err;
4846 width += 9;
4847 } else {
4848 int skip;
4849 err = format_line(&wline, &width, &skip, line,
4850 view->x, view->ncols - 9, 9, 1);
4851 if (err) {
4852 free(line);
4853 return err;
4855 waddwstr(view->window, &wline[skip]);
4856 width += 9;
4857 free(wline);
4858 wline = NULL;
4861 if (width <= view->ncols - 1)
4862 waddch(view->window, '\n');
4863 if (++nprinted == 1)
4864 s->first_displayed_line = lineno;
4866 free(line);
4867 s->last_displayed_line = lineno;
4869 view_border(view);
4871 return NULL;
4874 static const struct got_error *
4875 blame_cb(void *arg, int nlines, int lineno,
4876 struct got_commit_object *commit, struct got_object_id *id)
4878 const struct got_error *err = NULL;
4879 struct tog_blame_cb_args *a = arg;
4880 struct tog_blame_line *line;
4881 int errcode;
4883 if (nlines != a->nlines ||
4884 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4885 return got_error(GOT_ERR_RANGE);
4887 errcode = pthread_mutex_lock(&tog_mutex);
4888 if (errcode)
4889 return got_error_set_errno(errcode, "pthread_mutex_lock");
4891 if (*a->quit) { /* user has quit the blame view */
4892 err = got_error(GOT_ERR_ITER_COMPLETED);
4893 goto done;
4896 if (lineno == -1)
4897 goto done; /* no change in this commit */
4899 line = &a->lines[lineno - 1];
4900 if (line->annotated)
4901 goto done;
4903 line->id = got_object_id_dup(id);
4904 if (line->id == NULL) {
4905 err = got_error_from_errno("got_object_id_dup");
4906 goto done;
4908 line->annotated = 1;
4909 done:
4910 errcode = pthread_mutex_unlock(&tog_mutex);
4911 if (errcode)
4912 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4913 return err;
4916 static void *
4917 blame_thread(void *arg)
4919 const struct got_error *err, *close_err;
4920 struct tog_blame_thread_args *ta = arg;
4921 struct tog_blame_cb_args *a = ta->cb_args;
4922 int errcode, fd1 = -1, fd2 = -1;
4923 FILE *f1 = NULL, *f2 = NULL;
4925 fd1 = got_opentempfd();
4926 if (fd1 == -1)
4927 return (void *)got_error_from_errno("got_opentempfd");
4929 fd2 = got_opentempfd();
4930 if (fd2 == -1) {
4931 err = got_error_from_errno("got_opentempfd");
4932 goto done;
4935 f1 = got_opentemp();
4936 if (f1 == NULL) {
4937 err = (void *)got_error_from_errno("got_opentemp");
4938 goto done;
4940 f2 = got_opentemp();
4941 if (f2 == NULL) {
4942 err = (void *)got_error_from_errno("got_opentemp");
4943 goto done;
4946 err = block_signals_used_by_main_thread();
4947 if (err)
4948 goto done;
4950 err = got_blame(ta->path, a->commit_id, ta->repo,
4951 blame_cb, ta->cb_args, ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1,
4952 f2);
4953 if (err && err->code == GOT_ERR_CANCELLED)
4954 err = NULL;
4956 errcode = pthread_mutex_lock(&tog_mutex);
4957 if (errcode) {
4958 err = got_error_set_errno(errcode, "pthread_mutex_lock");
4959 goto done;
4962 close_err = got_repo_close(ta->repo);
4963 if (err == NULL)
4964 err = close_err;
4965 ta->repo = NULL;
4966 *ta->complete = 1;
4968 errcode = pthread_mutex_unlock(&tog_mutex);
4969 if (errcode && err == NULL)
4970 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4972 done:
4973 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4974 err = got_error_from_errno("close");
4975 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4976 err = got_error_from_errno("close");
4977 if (f1 && fclose(f1) == EOF && err == NULL)
4978 err = got_error_from_errno("fclose");
4979 if (f2 && fclose(f2) == EOF && err == NULL)
4980 err = got_error_from_errno("fclose");
4982 return (void *)err;
4985 static struct got_object_id *
4986 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
4987 int first_displayed_line, int selected_line)
4989 struct tog_blame_line *line;
4991 if (nlines <= 0)
4992 return NULL;
4994 line = &lines[first_displayed_line - 1 + selected_line - 1];
4995 if (!line->annotated)
4996 return NULL;
4998 return line->id;
5001 static const struct got_error *
5002 stop_blame(struct tog_blame *blame)
5004 const struct got_error *err = NULL;
5005 int i;
5007 if (blame->thread) {
5008 int errcode;
5009 errcode = pthread_mutex_unlock(&tog_mutex);
5010 if (errcode)
5011 return got_error_set_errno(errcode,
5012 "pthread_mutex_unlock");
5013 errcode = pthread_join(blame->thread, (void **)&err);
5014 if (errcode)
5015 return got_error_set_errno(errcode, "pthread_join");
5016 errcode = pthread_mutex_lock(&tog_mutex);
5017 if (errcode)
5018 return got_error_set_errno(errcode,
5019 "pthread_mutex_lock");
5020 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5021 err = NULL;
5022 blame->thread = NULL;
5024 if (blame->thread_args.repo) {
5025 const struct got_error *close_err;
5026 close_err = got_repo_close(blame->thread_args.repo);
5027 if (err == NULL)
5028 err = close_err;
5029 blame->thread_args.repo = NULL;
5031 if (blame->f) {
5032 if (fclose(blame->f) == EOF && err == NULL)
5033 err = got_error_from_errno("fclose");
5034 blame->f = NULL;
5036 if (blame->lines) {
5037 for (i = 0; i < blame->nlines; i++)
5038 free(blame->lines[i].id);
5039 free(blame->lines);
5040 blame->lines = NULL;
5042 free(blame->cb_args.commit_id);
5043 blame->cb_args.commit_id = NULL;
5044 if (blame->pack_fds) {
5045 const struct got_error *pack_err =
5046 got_repo_pack_fds_close(blame->pack_fds);
5047 if (err == NULL)
5048 err = pack_err;
5049 blame->pack_fds = NULL;
5051 return err;
5054 static const struct got_error *
5055 cancel_blame_view(void *arg)
5057 const struct got_error *err = NULL;
5058 int *done = arg;
5059 int errcode;
5061 errcode = pthread_mutex_lock(&tog_mutex);
5062 if (errcode)
5063 return got_error_set_errno(errcode,
5064 "pthread_mutex_unlock");
5066 if (*done)
5067 err = got_error(GOT_ERR_CANCELLED);
5069 errcode = pthread_mutex_unlock(&tog_mutex);
5070 if (errcode)
5071 return got_error_set_errno(errcode,
5072 "pthread_mutex_lock");
5074 return err;
5077 static const struct got_error *
5078 run_blame(struct tog_view *view)
5080 struct tog_blame_view_state *s = &view->state.blame;
5081 struct tog_blame *blame = &s->blame;
5082 const struct got_error *err = NULL;
5083 struct got_commit_object *commit = NULL;
5084 struct got_blob_object *blob = NULL;
5085 struct got_repository *thread_repo = NULL;
5086 struct got_object_id *obj_id = NULL;
5087 int obj_type, fd = -1;
5088 int *pack_fds = NULL;
5090 err = got_object_open_as_commit(&commit, s->repo,
5091 &s->blamed_commit->id);
5092 if (err)
5093 return err;
5095 fd = got_opentempfd();
5096 if (fd == -1) {
5097 err = got_error_from_errno("got_opentempfd");
5098 goto done;
5101 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5102 if (err)
5103 goto done;
5105 err = got_object_get_type(&obj_type, s->repo, obj_id);
5106 if (err)
5107 goto done;
5109 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5110 err = got_error(GOT_ERR_OBJ_TYPE);
5111 goto done;
5114 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5115 if (err)
5116 goto done;
5117 blame->f = got_opentemp();
5118 if (blame->f == NULL) {
5119 err = got_error_from_errno("got_opentemp");
5120 goto done;
5122 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5123 &blame->line_offsets, blame->f, blob);
5124 if (err)
5125 goto done;
5126 if (blame->nlines == 0) {
5127 s->blame_complete = 1;
5128 goto done;
5131 /* Don't include \n at EOF in the blame line count. */
5132 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5133 blame->nlines--;
5135 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5136 if (blame->lines == NULL) {
5137 err = got_error_from_errno("calloc");
5138 goto done;
5141 err = got_repo_pack_fds_open(&pack_fds);
5142 if (err)
5143 goto done;
5144 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5145 pack_fds);
5146 if (err)
5147 goto done;
5149 blame->pack_fds = pack_fds;
5150 blame->cb_args.view = view;
5151 blame->cb_args.lines = blame->lines;
5152 blame->cb_args.nlines = blame->nlines;
5153 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5154 if (blame->cb_args.commit_id == NULL) {
5155 err = got_error_from_errno("got_object_id_dup");
5156 goto done;
5158 blame->cb_args.quit = &s->done;
5160 blame->thread_args.path = s->path;
5161 blame->thread_args.repo = thread_repo;
5162 blame->thread_args.cb_args = &blame->cb_args;
5163 blame->thread_args.complete = &s->blame_complete;
5164 blame->thread_args.cancel_cb = cancel_blame_view;
5165 blame->thread_args.cancel_arg = &s->done;
5166 s->blame_complete = 0;
5168 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5169 s->first_displayed_line = 1;
5170 s->last_displayed_line = view->nlines;
5171 s->selected_line = 1;
5173 s->matched_line = 0;
5175 done:
5176 if (commit)
5177 got_object_commit_close(commit);
5178 if (fd != -1 && close(fd) == -1 && err == NULL)
5179 err = got_error_from_errno("close");
5180 if (blob)
5181 got_object_blob_close(blob);
5182 free(obj_id);
5183 if (err)
5184 stop_blame(blame);
5185 return err;
5188 static const struct got_error *
5189 open_blame_view(struct tog_view *view, char *path,
5190 struct got_object_id *commit_id, struct got_repository *repo)
5192 const struct got_error *err = NULL;
5193 struct tog_blame_view_state *s = &view->state.blame;
5195 STAILQ_INIT(&s->blamed_commits);
5197 s->path = strdup(path);
5198 if (s->path == NULL)
5199 return got_error_from_errno("strdup");
5201 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5202 if (err) {
5203 free(s->path);
5204 return err;
5207 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5208 s->first_displayed_line = 1;
5209 s->last_displayed_line = view->nlines;
5210 s->selected_line = 1;
5211 s->blame_complete = 0;
5212 s->repo = repo;
5213 s->commit_id = commit_id;
5214 memset(&s->blame, 0, sizeof(s->blame));
5216 STAILQ_INIT(&s->colors);
5217 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5218 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5219 get_color_value("TOG_COLOR_COMMIT"));
5220 if (err)
5221 return err;
5224 view->show = show_blame_view;
5225 view->input = input_blame_view;
5226 view->close = close_blame_view;
5227 view->search_start = search_start_blame_view;
5228 view->search_next = search_next_blame_view;
5230 return run_blame(view);
5233 static const struct got_error *
5234 close_blame_view(struct tog_view *view)
5236 const struct got_error *err = NULL;
5237 struct tog_blame_view_state *s = &view->state.blame;
5239 if (s->blame.thread)
5240 err = stop_blame(&s->blame);
5242 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5243 struct got_object_qid *blamed_commit;
5244 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5245 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5246 got_object_qid_free(blamed_commit);
5249 free(s->path);
5250 free_colors(&s->colors);
5251 return err;
5254 static const struct got_error *
5255 search_start_blame_view(struct tog_view *view)
5257 struct tog_blame_view_state *s = &view->state.blame;
5259 s->matched_line = 0;
5260 return NULL;
5263 static const struct got_error *
5264 search_next_blame_view(struct tog_view *view)
5266 struct tog_blame_view_state *s = &view->state.blame;
5267 const struct got_error *err = NULL;
5268 int lineno;
5269 char *line = NULL;
5270 size_t linesize = 0;
5271 ssize_t linelen;
5273 if (!view->searching) {
5274 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5275 return NULL;
5278 if (s->matched_line) {
5279 if (view->searching == TOG_SEARCH_FORWARD)
5280 lineno = s->matched_line + 1;
5281 else
5282 lineno = s->matched_line - 1;
5283 } else
5284 lineno = s->first_displayed_line - 1 + s->selected_line;
5286 while (1) {
5287 off_t offset;
5289 if (lineno <= 0 || lineno > s->blame.nlines) {
5290 if (s->matched_line == 0) {
5291 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5292 break;
5295 if (view->searching == TOG_SEARCH_FORWARD)
5296 lineno = 1;
5297 else
5298 lineno = s->blame.nlines;
5301 offset = s->blame.line_offsets[lineno - 1];
5302 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5303 free(line);
5304 return got_error_from_errno("fseeko");
5306 linelen = getline(&line, &linesize, s->blame.f);
5307 if (linelen != -1) {
5308 char *exstr;
5309 err = expand_tab(&exstr, line);
5310 if (err)
5311 break;
5312 if (match_line(exstr, &view->regex, 1,
5313 &view->regmatch)) {
5314 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5315 s->matched_line = lineno;
5316 free(exstr);
5317 break;
5319 free(exstr);
5321 if (view->searching == TOG_SEARCH_FORWARD)
5322 lineno++;
5323 else
5324 lineno--;
5326 free(line);
5328 if (s->matched_line) {
5329 s->first_displayed_line = s->matched_line;
5330 s->selected_line = 1;
5333 return err;
5336 static const struct got_error *
5337 show_blame_view(struct tog_view *view)
5339 const struct got_error *err = NULL;
5340 struct tog_blame_view_state *s = &view->state.blame;
5341 int errcode;
5343 if (s->blame.thread == NULL && !s->blame_complete) {
5344 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5345 &s->blame.thread_args);
5346 if (errcode)
5347 return got_error_set_errno(errcode, "pthread_create");
5349 halfdelay(1); /* fast refresh while annotating */
5352 if (s->blame_complete)
5353 halfdelay(10); /* disable fast refresh */
5355 err = draw_blame(view);
5357 view_border(view);
5358 return err;
5361 static const struct got_error *
5362 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5364 const struct got_error *err = NULL, *thread_err = NULL;
5365 struct tog_view *diff_view;
5366 struct tog_blame_view_state *s = &view->state.blame;
5367 int eos, nscroll, begin_y = 0, begin_x = 0;
5369 eos = nscroll = view->nlines - 2;
5370 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
5371 view_is_splitscreen(view->child))
5372 --eos; /* border */
5374 switch (ch) {
5375 case '0':
5376 view->x = 0;
5377 break;
5378 case '$':
5379 view->x = MAX(view->maxx - view->ncols / 3, 0);
5380 view->count = 0;
5381 break;
5382 case KEY_RIGHT:
5383 case 'l':
5384 if (view->x + view->ncols / 3 < view->maxx)
5385 view->x += 2; /* move two columns right */
5386 else
5387 view->count = 0;
5388 break;
5389 case KEY_LEFT:
5390 case 'h':
5391 view->x -= MIN(view->x, 2); /* move two columns back */
5392 if (view->x <= 0)
5393 view->count = 0;
5394 break;
5395 case 'q':
5396 s->done = 1;
5397 break;
5398 case 'g':
5399 case KEY_HOME:
5400 s->selected_line = 1;
5401 s->first_displayed_line = 1;
5402 view->count = 0;
5403 break;
5404 case 'G':
5405 case KEY_END:
5406 if (s->blame.nlines < eos) {
5407 s->selected_line = s->blame.nlines;
5408 s->first_displayed_line = 1;
5409 } else {
5410 s->selected_line = eos;
5411 s->first_displayed_line = s->blame.nlines - (eos - 1);
5413 view->count = 0;
5414 break;
5415 case 'k':
5416 case KEY_UP:
5417 case CTRL('p'):
5418 if (s->selected_line > 1)
5419 s->selected_line--;
5420 else if (s->selected_line == 1 &&
5421 s->first_displayed_line > 1)
5422 s->first_displayed_line--;
5423 else
5424 view->count = 0;
5425 break;
5426 case CTRL('u'):
5427 case 'u':
5428 nscroll /= 2;
5429 /* FALL THROUGH */
5430 case KEY_PPAGE:
5431 case CTRL('b'):
5432 case 'b':
5433 if (s->first_displayed_line == 1) {
5434 if (view->count > 1)
5435 nscroll += nscroll;
5436 s->selected_line = MAX(1, s->selected_line - nscroll);
5437 view->count = 0;
5438 break;
5440 if (s->first_displayed_line > nscroll)
5441 s->first_displayed_line -= nscroll;
5442 else
5443 s->first_displayed_line = 1;
5444 break;
5445 case 'j':
5446 case KEY_DOWN:
5447 case CTRL('n'):
5448 if (s->selected_line < eos && s->first_displayed_line +
5449 s->selected_line <= s->blame.nlines)
5450 s->selected_line++;
5451 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5452 s->first_displayed_line++;
5453 else
5454 view->count = 0;
5455 break;
5456 case 'c':
5457 case 'p': {
5458 struct got_object_id *id = NULL;
5460 view->count = 0;
5461 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5462 s->first_displayed_line, s->selected_line);
5463 if (id == NULL)
5464 break;
5465 if (ch == 'p') {
5466 struct got_commit_object *commit, *pcommit;
5467 struct got_object_qid *pid;
5468 struct got_object_id *blob_id = NULL;
5469 int obj_type;
5470 err = got_object_open_as_commit(&commit,
5471 s->repo, id);
5472 if (err)
5473 break;
5474 pid = STAILQ_FIRST(
5475 got_object_commit_get_parent_ids(commit));
5476 if (pid == NULL) {
5477 got_object_commit_close(commit);
5478 break;
5480 /* Check if path history ends here. */
5481 err = got_object_open_as_commit(&pcommit,
5482 s->repo, &pid->id);
5483 if (err)
5484 break;
5485 err = got_object_id_by_path(&blob_id, s->repo,
5486 pcommit, s->path);
5487 got_object_commit_close(pcommit);
5488 if (err) {
5489 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5490 err = NULL;
5491 got_object_commit_close(commit);
5492 break;
5494 err = got_object_get_type(&obj_type, s->repo,
5495 blob_id);
5496 free(blob_id);
5497 /* Can't blame non-blob type objects. */
5498 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5499 got_object_commit_close(commit);
5500 break;
5502 err = got_object_qid_alloc(&s->blamed_commit,
5503 &pid->id);
5504 got_object_commit_close(commit);
5505 } else {
5506 if (got_object_id_cmp(id,
5507 &s->blamed_commit->id) == 0)
5508 break;
5509 err = got_object_qid_alloc(&s->blamed_commit,
5510 id);
5512 if (err)
5513 break;
5514 s->done = 1;
5515 thread_err = stop_blame(&s->blame);
5516 s->done = 0;
5517 if (thread_err)
5518 break;
5519 STAILQ_INSERT_HEAD(&s->blamed_commits,
5520 s->blamed_commit, entry);
5521 err = run_blame(view);
5522 if (err)
5523 break;
5524 break;
5526 case 'C': {
5527 struct got_object_qid *first;
5529 view->count = 0;
5530 first = STAILQ_FIRST(&s->blamed_commits);
5531 if (!got_object_id_cmp(&first->id, s->commit_id))
5532 break;
5533 s->done = 1;
5534 thread_err = stop_blame(&s->blame);
5535 s->done = 0;
5536 if (thread_err)
5537 break;
5538 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5539 got_object_qid_free(s->blamed_commit);
5540 s->blamed_commit =
5541 STAILQ_FIRST(&s->blamed_commits);
5542 err = run_blame(view);
5543 if (err)
5544 break;
5545 break;
5547 case KEY_ENTER:
5548 case '\r': {
5549 struct got_object_id *id = NULL;
5550 struct got_object_qid *pid;
5551 struct got_commit_object *commit = NULL;
5553 view->count = 0;
5554 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5555 s->first_displayed_line, s->selected_line);
5556 if (id == NULL)
5557 break;
5558 err = got_object_open_as_commit(&commit, s->repo, id);
5559 if (err)
5560 break;
5561 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
5562 if (view_is_parent_view(view))
5563 view_get_split(view, &begin_y, &begin_x);
5565 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
5566 if (diff_view == NULL) {
5567 got_object_commit_close(commit);
5568 err = got_error_from_errno("view_open");
5569 break;
5571 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5572 id, NULL, NULL, 3, 0, 0, NULL, s->repo);
5573 got_object_commit_close(commit);
5574 if (err) {
5575 view_close(diff_view);
5576 break;
5578 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
5579 err = view_init_hsplit(view, begin_y);
5580 if (err)
5581 break;
5584 view->focussed = 0;
5585 diff_view->focussed = 1;
5586 diff_view->mode = view->mode;
5587 diff_view->nlines = view->lines - begin_y;
5588 if (view_is_parent_view(view)) {
5589 err = view_close_child(view);
5590 if (err)
5591 break;
5592 err = view_set_child(view, diff_view);
5593 if (err)
5594 break;
5595 view->focus_child = 1;
5596 } else
5597 *new_view = diff_view;
5598 if (err)
5599 break;
5600 break;
5602 case CTRL('d'):
5603 case 'd':
5604 nscroll /= 2;
5605 /* FALL THROUGH */
5606 case KEY_NPAGE:
5607 case CTRL('f'):
5608 case 'f':
5609 case ' ':
5610 if (s->last_displayed_line >= s->blame.nlines &&
5611 s->selected_line >= MIN(s->blame.nlines,
5612 view->nlines - 2)) {
5613 view->count = 0;
5614 break;
5616 if (s->last_displayed_line >= s->blame.nlines &&
5617 s->selected_line < view->nlines - 2) {
5618 s->selected_line +=
5619 MIN(nscroll, s->last_displayed_line -
5620 s->first_displayed_line - s->selected_line + 1);
5622 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5623 s->first_displayed_line += nscroll;
5624 else
5625 s->first_displayed_line =
5626 s->blame.nlines - (view->nlines - 3);
5627 break;
5628 case KEY_RESIZE:
5629 if (s->selected_line > view->nlines - 2) {
5630 s->selected_line = MIN(s->blame.nlines,
5631 view->nlines - 2);
5633 break;
5634 default:
5635 view->count = 0;
5636 break;
5638 return thread_err ? thread_err : err;
5641 static const struct got_error *
5642 cmd_blame(int argc, char *argv[])
5644 const struct got_error *error;
5645 struct got_repository *repo = NULL;
5646 struct got_worktree *worktree = NULL;
5647 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5648 char *link_target = NULL;
5649 struct got_object_id *commit_id = NULL;
5650 struct got_commit_object *commit = NULL;
5651 char *commit_id_str = NULL;
5652 int ch;
5653 struct tog_view *view;
5654 int *pack_fds = NULL;
5656 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5657 switch (ch) {
5658 case 'c':
5659 commit_id_str = optarg;
5660 break;
5661 case 'r':
5662 repo_path = realpath(optarg, NULL);
5663 if (repo_path == NULL)
5664 return got_error_from_errno2("realpath",
5665 optarg);
5666 break;
5667 default:
5668 usage_blame();
5669 /* NOTREACHED */
5673 argc -= optind;
5674 argv += optind;
5676 if (argc != 1)
5677 usage_blame();
5679 error = got_repo_pack_fds_open(&pack_fds);
5680 if (error != NULL)
5681 goto done;
5683 if (repo_path == NULL) {
5684 cwd = getcwd(NULL, 0);
5685 if (cwd == NULL)
5686 return got_error_from_errno("getcwd");
5687 error = got_worktree_open(&worktree, cwd);
5688 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5689 goto done;
5690 if (worktree)
5691 repo_path =
5692 strdup(got_worktree_get_repo_path(worktree));
5693 else
5694 repo_path = strdup(cwd);
5695 if (repo_path == NULL) {
5696 error = got_error_from_errno("strdup");
5697 goto done;
5701 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5702 if (error != NULL)
5703 goto done;
5705 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
5706 worktree);
5707 if (error)
5708 goto done;
5710 init_curses();
5712 error = apply_unveil(got_repo_get_path(repo), NULL);
5713 if (error)
5714 goto done;
5716 error = tog_load_refs(repo, 0);
5717 if (error)
5718 goto done;
5720 if (commit_id_str == NULL) {
5721 struct got_reference *head_ref;
5722 error = got_ref_open(&head_ref, repo, worktree ?
5723 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5724 if (error != NULL)
5725 goto done;
5726 error = got_ref_resolve(&commit_id, repo, head_ref);
5727 got_ref_close(head_ref);
5728 } else {
5729 error = got_repo_match_object_id(&commit_id, NULL,
5730 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
5732 if (error != NULL)
5733 goto done;
5735 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
5736 if (view == NULL) {
5737 error = got_error_from_errno("view_open");
5738 goto done;
5741 error = got_object_open_as_commit(&commit, repo, commit_id);
5742 if (error)
5743 goto done;
5745 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5746 commit, repo);
5747 if (error)
5748 goto done;
5750 error = open_blame_view(view, link_target ? link_target : in_repo_path,
5751 commit_id, repo);
5752 if (error)
5753 goto done;
5754 if (worktree) {
5755 /* Release work tree lock. */
5756 got_worktree_close(worktree);
5757 worktree = NULL;
5759 error = view_loop(view);
5760 done:
5761 free(repo_path);
5762 free(in_repo_path);
5763 free(link_target);
5764 free(cwd);
5765 free(commit_id);
5766 if (commit)
5767 got_object_commit_close(commit);
5768 if (worktree)
5769 got_worktree_close(worktree);
5770 if (repo) {
5771 const struct got_error *close_err = got_repo_close(repo);
5772 if (error == NULL)
5773 error = close_err;
5775 if (pack_fds) {
5776 const struct got_error *pack_err =
5777 got_repo_pack_fds_close(pack_fds);
5778 if (error == NULL)
5779 error = pack_err;
5781 tog_free_refs();
5782 return error;
5785 static const struct got_error *
5786 draw_tree_entries(struct tog_view *view, const char *parent_path)
5788 struct tog_tree_view_state *s = &view->state.tree;
5789 const struct got_error *err = NULL;
5790 struct got_tree_entry *te;
5791 wchar_t *wline;
5792 struct tog_color *tc;
5793 int width, n, i, nentries;
5794 int limit = view->nlines;
5796 s->ndisplayed = 0;
5797 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
5798 view_is_splitscreen(view->child))
5799 --limit; /* border */
5801 werase(view->window);
5803 if (limit == 0)
5804 return NULL;
5806 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
5807 0, 0);
5808 if (err)
5809 return err;
5810 if (view_needs_focus_indication(view))
5811 wstandout(view->window);
5812 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5813 if (tc)
5814 wattr_on(view->window,
5815 COLOR_PAIR(tc->colorpair), NULL);
5816 waddwstr(view->window, wline);
5817 if (tc)
5818 wattr_off(view->window,
5819 COLOR_PAIR(tc->colorpair), NULL);
5820 if (view_needs_focus_indication(view))
5821 wstandend(view->window);
5822 free(wline);
5823 wline = NULL;
5824 if (width < view->ncols - 1)
5825 waddch(view->window, '\n');
5826 if (--limit <= 0)
5827 return NULL;
5828 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
5829 0, 0);
5830 if (err)
5831 return err;
5832 waddwstr(view->window, wline);
5833 free(wline);
5834 wline = NULL;
5835 if (width < view->ncols - 1)
5836 waddch(view->window, '\n');
5837 if (--limit <= 0)
5838 return NULL;
5839 waddch(view->window, '\n');
5840 if (--limit <= 0)
5841 return NULL;
5843 if (s->first_displayed_entry == NULL) {
5844 te = got_object_tree_get_first_entry(s->tree);
5845 if (s->selected == 0) {
5846 if (view->focussed)
5847 wstandout(view->window);
5848 s->selected_entry = NULL;
5850 waddstr(view->window, " ..\n"); /* parent directory */
5851 if (s->selected == 0 && view->focussed)
5852 wstandend(view->window);
5853 s->ndisplayed++;
5854 if (--limit <= 0)
5855 return NULL;
5856 n = 1;
5857 } else {
5858 n = 0;
5859 te = s->first_displayed_entry;
5862 nentries = got_object_tree_get_nentries(s->tree);
5863 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
5864 char *line = NULL, *id_str = NULL, *link_target = NULL;
5865 const char *modestr = "";
5866 mode_t mode;
5868 te = got_object_tree_get_entry(s->tree, i);
5869 mode = got_tree_entry_get_mode(te);
5871 if (s->show_ids) {
5872 err = got_object_id_str(&id_str,
5873 got_tree_entry_get_id(te));
5874 if (err)
5875 return got_error_from_errno(
5876 "got_object_id_str");
5878 if (got_object_tree_entry_is_submodule(te))
5879 modestr = "$";
5880 else if (S_ISLNK(mode)) {
5881 int i;
5883 err = got_tree_entry_get_symlink_target(&link_target,
5884 te, s->repo);
5885 if (err) {
5886 free(id_str);
5887 return err;
5889 for (i = 0; i < strlen(link_target); i++) {
5890 if (!isprint((unsigned char)link_target[i]))
5891 link_target[i] = '?';
5893 modestr = "@";
5895 else if (S_ISDIR(mode))
5896 modestr = "/";
5897 else if (mode & S_IXUSR)
5898 modestr = "*";
5899 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
5900 got_tree_entry_get_name(te), modestr,
5901 link_target ? " -> ": "",
5902 link_target ? link_target : "") == -1) {
5903 free(id_str);
5904 free(link_target);
5905 return got_error_from_errno("asprintf");
5907 free(id_str);
5908 free(link_target);
5909 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
5910 0, 0);
5911 if (err) {
5912 free(line);
5913 break;
5915 if (n == s->selected) {
5916 if (view->focussed)
5917 wstandout(view->window);
5918 s->selected_entry = te;
5920 tc = match_color(&s->colors, line);
5921 if (tc)
5922 wattr_on(view->window,
5923 COLOR_PAIR(tc->colorpair), NULL);
5924 waddwstr(view->window, wline);
5925 if (tc)
5926 wattr_off(view->window,
5927 COLOR_PAIR(tc->colorpair), NULL);
5928 if (width < view->ncols - 1)
5929 waddch(view->window, '\n');
5930 if (n == s->selected && view->focussed)
5931 wstandend(view->window);
5932 free(line);
5933 free(wline);
5934 wline = NULL;
5935 n++;
5936 s->ndisplayed++;
5937 s->last_displayed_entry = te;
5938 if (--limit <= 0)
5939 break;
5942 return err;
5945 static void
5946 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
5948 struct got_tree_entry *te;
5949 int isroot = s->tree == s->root;
5950 int i = 0;
5952 if (s->first_displayed_entry == NULL)
5953 return;
5955 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
5956 while (i++ < maxscroll) {
5957 if (te == NULL) {
5958 if (!isroot)
5959 s->first_displayed_entry = NULL;
5960 break;
5962 s->first_displayed_entry = te;
5963 te = got_tree_entry_get_prev(s->tree, te);
5967 static const struct got_error *
5968 tree_scroll_down(struct tog_view *view, int maxscroll)
5970 struct tog_tree_view_state *s = &view->state.tree;
5971 struct got_tree_entry *next, *last;
5972 int n = 0;
5974 if (s->first_displayed_entry)
5975 next = got_tree_entry_get_next(s->tree,
5976 s->first_displayed_entry);
5977 else
5978 next = got_object_tree_get_first_entry(s->tree);
5980 last = s->last_displayed_entry;
5981 while (next && n++ < maxscroll) {
5982 if (last)
5983 last = got_tree_entry_get_next(s->tree, last);
5984 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
5985 s->first_displayed_entry = next;
5986 next = got_tree_entry_get_next(s->tree, next);
5990 return NULL;
5993 static const struct got_error *
5994 tree_entry_path(char **path, struct tog_parent_trees *parents,
5995 struct got_tree_entry *te)
5997 const struct got_error *err = NULL;
5998 struct tog_parent_tree *pt;
5999 size_t len = 2; /* for leading slash and NUL */
6001 TAILQ_FOREACH(pt, parents, entry)
6002 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6003 + 1 /* slash */;
6004 if (te)
6005 len += strlen(got_tree_entry_get_name(te));
6007 *path = calloc(1, len);
6008 if (path == NULL)
6009 return got_error_from_errno("calloc");
6011 (*path)[0] = '/';
6012 pt = TAILQ_LAST(parents, tog_parent_trees);
6013 while (pt) {
6014 const char *name = got_tree_entry_get_name(pt->selected_entry);
6015 if (strlcat(*path, name, len) >= len) {
6016 err = got_error(GOT_ERR_NO_SPACE);
6017 goto done;
6019 if (strlcat(*path, "/", len) >= len) {
6020 err = got_error(GOT_ERR_NO_SPACE);
6021 goto done;
6023 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6025 if (te) {
6026 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6027 err = got_error(GOT_ERR_NO_SPACE);
6028 goto done;
6031 done:
6032 if (err) {
6033 free(*path);
6034 *path = NULL;
6036 return err;
6039 static const struct got_error *
6040 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6041 struct got_tree_entry *te, struct tog_parent_trees *parents,
6042 struct got_object_id *commit_id, struct got_repository *repo)
6044 const struct got_error *err = NULL;
6045 char *path;
6046 struct tog_view *blame_view;
6048 *new_view = NULL;
6050 err = tree_entry_path(&path, parents, te);
6051 if (err)
6052 return err;
6054 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6055 if (blame_view == NULL) {
6056 err = got_error_from_errno("view_open");
6057 goto done;
6060 err = open_blame_view(blame_view, path, commit_id, repo);
6061 if (err) {
6062 if (err->code == GOT_ERR_CANCELLED)
6063 err = NULL;
6064 view_close(blame_view);
6065 } else
6066 *new_view = blame_view;
6067 done:
6068 free(path);
6069 return err;
6072 static const struct got_error *
6073 log_selected_tree_entry(struct tog_view **new_view, int begin_x,
6074 struct tog_tree_view_state *s)
6076 struct tog_view *log_view;
6077 const struct got_error *err = NULL;
6078 char *path;
6080 *new_view = NULL;
6082 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
6083 if (log_view == NULL)
6084 return got_error_from_errno("view_open");
6086 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6087 if (err)
6088 return err;
6090 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6091 path, 0);
6092 if (err)
6093 view_close(log_view);
6094 else
6095 *new_view = log_view;
6096 free(path);
6097 return err;
6100 static const struct got_error *
6101 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6102 const char *head_ref_name, struct got_repository *repo)
6104 const struct got_error *err = NULL;
6105 char *commit_id_str = NULL;
6106 struct tog_tree_view_state *s = &view->state.tree;
6107 struct got_commit_object *commit = NULL;
6109 TAILQ_INIT(&s->parents);
6110 STAILQ_INIT(&s->colors);
6112 s->commit_id = got_object_id_dup(commit_id);
6113 if (s->commit_id == NULL)
6114 return got_error_from_errno("got_object_id_dup");
6116 err = got_object_open_as_commit(&commit, repo, commit_id);
6117 if (err)
6118 goto done;
6121 * The root is opened here and will be closed when the view is closed.
6122 * Any visited subtrees and their path-wise parents are opened and
6123 * closed on demand.
6125 err = got_object_open_as_tree(&s->root, repo,
6126 got_object_commit_get_tree_id(commit));
6127 if (err)
6128 goto done;
6129 s->tree = s->root;
6131 err = got_object_id_str(&commit_id_str, commit_id);
6132 if (err != NULL)
6133 goto done;
6135 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6136 err = got_error_from_errno("asprintf");
6137 goto done;
6140 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6141 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6142 if (head_ref_name) {
6143 s->head_ref_name = strdup(head_ref_name);
6144 if (s->head_ref_name == NULL) {
6145 err = got_error_from_errno("strdup");
6146 goto done;
6149 s->repo = repo;
6151 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6152 err = add_color(&s->colors, "\\$$",
6153 TOG_COLOR_TREE_SUBMODULE,
6154 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6155 if (err)
6156 goto done;
6157 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6158 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6159 if (err)
6160 goto done;
6161 err = add_color(&s->colors, "/$",
6162 TOG_COLOR_TREE_DIRECTORY,
6163 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6164 if (err)
6165 goto done;
6167 err = add_color(&s->colors, "\\*$",
6168 TOG_COLOR_TREE_EXECUTABLE,
6169 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6170 if (err)
6171 goto done;
6173 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6174 get_color_value("TOG_COLOR_COMMIT"));
6175 if (err)
6176 goto done;
6179 view->show = show_tree_view;
6180 view->input = input_tree_view;
6181 view->close = close_tree_view;
6182 view->search_start = search_start_tree_view;
6183 view->search_next = search_next_tree_view;
6184 done:
6185 free(commit_id_str);
6186 if (commit)
6187 got_object_commit_close(commit);
6188 if (err)
6189 close_tree_view(view);
6190 return err;
6193 static const struct got_error *
6194 close_tree_view(struct tog_view *view)
6196 struct tog_tree_view_state *s = &view->state.tree;
6198 free_colors(&s->colors);
6199 free(s->tree_label);
6200 s->tree_label = NULL;
6201 free(s->commit_id);
6202 s->commit_id = NULL;
6203 free(s->head_ref_name);
6204 s->head_ref_name = NULL;
6205 while (!TAILQ_EMPTY(&s->parents)) {
6206 struct tog_parent_tree *parent;
6207 parent = TAILQ_FIRST(&s->parents);
6208 TAILQ_REMOVE(&s->parents, parent, entry);
6209 if (parent->tree != s->root)
6210 got_object_tree_close(parent->tree);
6211 free(parent);
6214 if (s->tree != NULL && s->tree != s->root)
6215 got_object_tree_close(s->tree);
6216 if (s->root)
6217 got_object_tree_close(s->root);
6218 return NULL;
6221 static const struct got_error *
6222 search_start_tree_view(struct tog_view *view)
6224 struct tog_tree_view_state *s = &view->state.tree;
6226 s->matched_entry = NULL;
6227 return NULL;
6230 static int
6231 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6233 regmatch_t regmatch;
6235 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6236 0) == 0;
6239 static const struct got_error *
6240 search_next_tree_view(struct tog_view *view)
6242 struct tog_tree_view_state *s = &view->state.tree;
6243 struct got_tree_entry *te = NULL;
6245 if (!view->searching) {
6246 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6247 return NULL;
6250 if (s->matched_entry) {
6251 if (view->searching == TOG_SEARCH_FORWARD) {
6252 if (s->selected_entry)
6253 te = got_tree_entry_get_next(s->tree,
6254 s->selected_entry);
6255 else
6256 te = got_object_tree_get_first_entry(s->tree);
6257 } else {
6258 if (s->selected_entry == NULL)
6259 te = got_object_tree_get_last_entry(s->tree);
6260 else
6261 te = got_tree_entry_get_prev(s->tree,
6262 s->selected_entry);
6264 } else {
6265 if (s->selected_entry)
6266 te = s->selected_entry;
6267 else if (view->searching == TOG_SEARCH_FORWARD)
6268 te = got_object_tree_get_first_entry(s->tree);
6269 else
6270 te = got_object_tree_get_last_entry(s->tree);
6273 while (1) {
6274 if (te == NULL) {
6275 if (s->matched_entry == NULL) {
6276 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6277 return NULL;
6279 if (view->searching == TOG_SEARCH_FORWARD)
6280 te = got_object_tree_get_first_entry(s->tree);
6281 else
6282 te = got_object_tree_get_last_entry(s->tree);
6285 if (match_tree_entry(te, &view->regex)) {
6286 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6287 s->matched_entry = te;
6288 break;
6291 if (view->searching == TOG_SEARCH_FORWARD)
6292 te = got_tree_entry_get_next(s->tree, te);
6293 else
6294 te = got_tree_entry_get_prev(s->tree, te);
6297 if (s->matched_entry) {
6298 s->first_displayed_entry = s->matched_entry;
6299 s->selected = 0;
6302 return NULL;
6305 static const struct got_error *
6306 show_tree_view(struct tog_view *view)
6308 const struct got_error *err = NULL;
6309 struct tog_tree_view_state *s = &view->state.tree;
6310 char *parent_path;
6312 err = tree_entry_path(&parent_path, &s->parents, NULL);
6313 if (err)
6314 return err;
6316 err = draw_tree_entries(view, parent_path);
6317 free(parent_path);
6319 view_border(view);
6320 return err;
6323 static const struct got_error *
6324 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6326 const struct got_error *err = NULL;
6327 struct tog_tree_view_state *s = &view->state.tree;
6328 struct tog_view *log_view, *ref_view;
6329 struct got_tree_entry *te;
6330 int begin_x = 0, n, nscroll = view->nlines - 3;
6332 switch (ch) {
6333 case 'i':
6334 s->show_ids = !s->show_ids;
6335 view->count = 0;
6336 break;
6337 case 'l':
6338 view->count = 0;
6339 if (!s->selected_entry)
6340 break;
6341 if (view_is_parent_view(view))
6342 begin_x = view_split_begin_x(view->begin_x);
6343 err = log_selected_tree_entry(&log_view, begin_x, s);
6344 view->focussed = 0;
6345 log_view->focussed = 1;
6346 if (view_is_parent_view(view)) {
6347 err = view_close_child(view);
6348 if (err)
6349 return err;
6350 err = view_set_child(view, log_view);
6351 if (err)
6352 return err;
6353 view->focus_child = 1;
6354 } else
6355 *new_view = log_view;
6356 break;
6357 case 'r':
6358 view->count = 0;
6359 if (view_is_parent_view(view))
6360 begin_x = view_split_begin_x(view->begin_x);
6361 ref_view = view_open(view->nlines, view->ncols,
6362 view->begin_y, begin_x, TOG_VIEW_REF);
6363 if (ref_view == NULL)
6364 return got_error_from_errno("view_open");
6365 err = open_ref_view(ref_view, s->repo);
6366 if (err) {
6367 view_close(ref_view);
6368 return err;
6370 view->focussed = 0;
6371 ref_view->focussed = 1;
6372 if (view_is_parent_view(view)) {
6373 err = view_close_child(view);
6374 if (err)
6375 return err;
6376 err = view_set_child(view, ref_view);
6377 if (err)
6378 return err;
6379 view->focus_child = 1;
6380 } else
6381 *new_view = ref_view;
6382 break;
6383 case 'g':
6384 case KEY_HOME:
6385 s->selected = 0;
6386 view->count = 0;
6387 if (s->tree == s->root)
6388 s->first_displayed_entry =
6389 got_object_tree_get_first_entry(s->tree);
6390 else
6391 s->first_displayed_entry = NULL;
6392 break;
6393 case 'G':
6394 case KEY_END: {
6395 int eos = view->nlines - 3;
6397 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6398 --eos; /* border */
6399 s->selected = 0;
6400 view->count = 0;
6401 te = got_object_tree_get_last_entry(s->tree);
6402 for (n = 0; n < eos; n++) {
6403 if (te == NULL) {
6404 if(s->tree != s->root) {
6405 s->first_displayed_entry = NULL;
6406 n++;
6408 break;
6410 s->first_displayed_entry = te;
6411 te = got_tree_entry_get_prev(s->tree, te);
6413 if (n > 0)
6414 s->selected = n - 1;
6415 break;
6417 case 'k':
6418 case KEY_UP:
6419 case CTRL('p'):
6420 if (s->selected > 0) {
6421 s->selected--;
6422 break;
6424 tree_scroll_up(s, 1);
6425 if (s->selected_entry == NULL ||
6426 (s->tree == s->root && s->selected_entry ==
6427 got_object_tree_get_first_entry(s->tree)))
6428 view->count = 0;
6429 break;
6430 case CTRL('u'):
6431 case 'u':
6432 nscroll /= 2;
6433 /* FALL THROUGH */
6434 case KEY_PPAGE:
6435 case CTRL('b'):
6436 case 'b':
6437 if (s->tree == s->root) {
6438 if (got_object_tree_get_first_entry(s->tree) ==
6439 s->first_displayed_entry)
6440 s->selected -= MIN(s->selected, nscroll);
6441 } else {
6442 if (s->first_displayed_entry == NULL)
6443 s->selected -= MIN(s->selected, nscroll);
6445 tree_scroll_up(s, MAX(0, nscroll));
6446 if (s->selected_entry == NULL ||
6447 (s->tree == s->root && s->selected_entry ==
6448 got_object_tree_get_first_entry(s->tree)))
6449 view->count = 0;
6450 break;
6451 case 'j':
6452 case KEY_DOWN:
6453 case CTRL('n'):
6454 if (s->selected < s->ndisplayed - 1) {
6455 s->selected++;
6456 break;
6458 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6459 == NULL) {
6460 /* can't scroll any further */
6461 view->count = 0;
6462 break;
6464 tree_scroll_down(view, 1);
6465 break;
6466 case CTRL('d'):
6467 case 'd':
6468 nscroll /= 2;
6469 /* FALL THROUGH */
6470 case KEY_NPAGE:
6471 case CTRL('f'):
6472 case 'f':
6473 case ' ':
6474 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6475 == NULL) {
6476 /* can't scroll any further; move cursor down */
6477 if (s->selected < s->ndisplayed - 1)
6478 s->selected += MIN(nscroll,
6479 s->ndisplayed - s->selected - 1);
6480 else
6481 view->count = 0;
6482 break;
6484 tree_scroll_down(view, nscroll);
6485 break;
6486 case KEY_ENTER:
6487 case '\r':
6488 case KEY_BACKSPACE:
6489 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6490 struct tog_parent_tree *parent;
6491 /* user selected '..' */
6492 if (s->tree == s->root) {
6493 view->count = 0;
6494 break;
6496 parent = TAILQ_FIRST(&s->parents);
6497 TAILQ_REMOVE(&s->parents, parent,
6498 entry);
6499 got_object_tree_close(s->tree);
6500 s->tree = parent->tree;
6501 s->first_displayed_entry =
6502 parent->first_displayed_entry;
6503 s->selected_entry =
6504 parent->selected_entry;
6505 s->selected = parent->selected;
6506 if (s->selected > view->nlines - 3) {
6507 err = offset_selection_down(view);
6508 if (err)
6509 break;
6511 free(parent);
6512 } else if (S_ISDIR(got_tree_entry_get_mode(
6513 s->selected_entry))) {
6514 struct got_tree_object *subtree;
6515 view->count = 0;
6516 err = got_object_open_as_tree(&subtree, s->repo,
6517 got_tree_entry_get_id(s->selected_entry));
6518 if (err)
6519 break;
6520 err = tree_view_visit_subtree(s, subtree);
6521 if (err) {
6522 got_object_tree_close(subtree);
6523 break;
6525 } else if (S_ISREG(got_tree_entry_get_mode(
6526 s->selected_entry))) {
6527 struct tog_view *blame_view;
6528 int begin_x = 0, begin_y = 0;
6530 if (view_is_parent_view(view))
6531 view_get_split(view, &begin_y, &begin_x);
6533 err = blame_tree_entry(&blame_view, begin_y, begin_x,
6534 s->selected_entry, &s->parents,
6535 s->commit_id, s->repo);
6536 if (err)
6537 break;
6539 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
6540 err = view_init_hsplit(view, begin_y);
6541 if (err)
6542 break;
6545 view->count = 0;
6546 view->focussed = 0;
6547 blame_view->focussed = 1;
6548 blame_view->mode = view->mode;
6549 blame_view->nlines = view->lines - begin_y;
6550 if (view_is_parent_view(view)) {
6551 err = view_close_child(view);
6552 if (err)
6553 return err;
6554 err = view_set_child(view, blame_view);
6555 if (err)
6556 return err;
6557 view->focus_child = 1;
6558 } else
6559 *new_view = blame_view;
6561 break;
6562 case KEY_RESIZE:
6563 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6564 s->selected = view->nlines - 4;
6565 view->count = 0;
6566 break;
6567 default:
6568 view->count = 0;
6569 break;
6572 return err;
6575 __dead static void
6576 usage_tree(void)
6578 endwin();
6579 fprintf(stderr,
6580 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6581 getprogname());
6582 exit(1);
6585 static const struct got_error *
6586 cmd_tree(int argc, char *argv[])
6588 const struct got_error *error;
6589 struct got_repository *repo = NULL;
6590 struct got_worktree *worktree = NULL;
6591 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6592 struct got_object_id *commit_id = NULL;
6593 struct got_commit_object *commit = NULL;
6594 const char *commit_id_arg = NULL;
6595 char *label = NULL;
6596 struct got_reference *ref = NULL;
6597 const char *head_ref_name = NULL;
6598 int ch;
6599 struct tog_view *view;
6600 int *pack_fds = NULL;
6602 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6603 switch (ch) {
6604 case 'c':
6605 commit_id_arg = optarg;
6606 break;
6607 case 'r':
6608 repo_path = realpath(optarg, NULL);
6609 if (repo_path == NULL)
6610 return got_error_from_errno2("realpath",
6611 optarg);
6612 break;
6613 default:
6614 usage_tree();
6615 /* NOTREACHED */
6619 argc -= optind;
6620 argv += optind;
6622 if (argc > 1)
6623 usage_tree();
6625 error = got_repo_pack_fds_open(&pack_fds);
6626 if (error != NULL)
6627 goto done;
6629 if (repo_path == NULL) {
6630 cwd = getcwd(NULL, 0);
6631 if (cwd == NULL)
6632 return got_error_from_errno("getcwd");
6633 error = got_worktree_open(&worktree, cwd);
6634 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6635 goto done;
6636 if (worktree)
6637 repo_path =
6638 strdup(got_worktree_get_repo_path(worktree));
6639 else
6640 repo_path = strdup(cwd);
6641 if (repo_path == NULL) {
6642 error = got_error_from_errno("strdup");
6643 goto done;
6647 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6648 if (error != NULL)
6649 goto done;
6651 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
6652 repo, worktree);
6653 if (error)
6654 goto done;
6656 init_curses();
6658 error = apply_unveil(got_repo_get_path(repo), NULL);
6659 if (error)
6660 goto done;
6662 error = tog_load_refs(repo, 0);
6663 if (error)
6664 goto done;
6666 if (commit_id_arg == NULL) {
6667 error = got_repo_match_object_id(&commit_id, &label,
6668 worktree ? got_worktree_get_head_ref_name(worktree) :
6669 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6670 if (error)
6671 goto done;
6672 head_ref_name = label;
6673 } else {
6674 error = got_ref_open(&ref, repo, commit_id_arg, 0);
6675 if (error == NULL)
6676 head_ref_name = got_ref_get_name(ref);
6677 else if (error->code != GOT_ERR_NOT_REF)
6678 goto done;
6679 error = got_repo_match_object_id(&commit_id, NULL,
6680 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6681 if (error)
6682 goto done;
6685 error = got_object_open_as_commit(&commit, repo, commit_id);
6686 if (error)
6687 goto done;
6689 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
6690 if (view == NULL) {
6691 error = got_error_from_errno("view_open");
6692 goto done;
6694 error = open_tree_view(view, commit_id, head_ref_name, repo);
6695 if (error)
6696 goto done;
6697 if (!got_path_is_root_dir(in_repo_path)) {
6698 error = tree_view_walk_path(&view->state.tree, commit,
6699 in_repo_path);
6700 if (error)
6701 goto done;
6704 if (worktree) {
6705 /* Release work tree lock. */
6706 got_worktree_close(worktree);
6707 worktree = NULL;
6709 error = view_loop(view);
6710 done:
6711 free(repo_path);
6712 free(cwd);
6713 free(commit_id);
6714 free(label);
6715 if (ref)
6716 got_ref_close(ref);
6717 if (repo) {
6718 const struct got_error *close_err = got_repo_close(repo);
6719 if (error == NULL)
6720 error = close_err;
6722 if (pack_fds) {
6723 const struct got_error *pack_err =
6724 got_repo_pack_fds_close(pack_fds);
6725 if (error == NULL)
6726 error = pack_err;
6728 tog_free_refs();
6729 return error;
6732 static const struct got_error *
6733 ref_view_load_refs(struct tog_ref_view_state *s)
6735 struct got_reflist_entry *sre;
6736 struct tog_reflist_entry *re;
6738 s->nrefs = 0;
6739 TAILQ_FOREACH(sre, &tog_refs, entry) {
6740 if (strncmp(got_ref_get_name(sre->ref),
6741 "refs/got/", 9) == 0 &&
6742 strncmp(got_ref_get_name(sre->ref),
6743 "refs/got/backup/", 16) != 0)
6744 continue;
6746 re = malloc(sizeof(*re));
6747 if (re == NULL)
6748 return got_error_from_errno("malloc");
6750 re->ref = got_ref_dup(sre->ref);
6751 if (re->ref == NULL)
6752 return got_error_from_errno("got_ref_dup");
6753 re->idx = s->nrefs++;
6754 TAILQ_INSERT_TAIL(&s->refs, re, entry);
6757 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6758 return NULL;
6761 static void
6762 ref_view_free_refs(struct tog_ref_view_state *s)
6764 struct tog_reflist_entry *re;
6766 while (!TAILQ_EMPTY(&s->refs)) {
6767 re = TAILQ_FIRST(&s->refs);
6768 TAILQ_REMOVE(&s->refs, re, entry);
6769 got_ref_close(re->ref);
6770 free(re);
6774 static const struct got_error *
6775 open_ref_view(struct tog_view *view, struct got_repository *repo)
6777 const struct got_error *err = NULL;
6778 struct tog_ref_view_state *s = &view->state.ref;
6780 s->selected_entry = 0;
6781 s->repo = repo;
6783 TAILQ_INIT(&s->refs);
6784 STAILQ_INIT(&s->colors);
6786 err = ref_view_load_refs(s);
6787 if (err)
6788 return err;
6790 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6791 err = add_color(&s->colors, "^refs/heads/",
6792 TOG_COLOR_REFS_HEADS,
6793 get_color_value("TOG_COLOR_REFS_HEADS"));
6794 if (err)
6795 goto done;
6797 err = add_color(&s->colors, "^refs/tags/",
6798 TOG_COLOR_REFS_TAGS,
6799 get_color_value("TOG_COLOR_REFS_TAGS"));
6800 if (err)
6801 goto done;
6803 err = add_color(&s->colors, "^refs/remotes/",
6804 TOG_COLOR_REFS_REMOTES,
6805 get_color_value("TOG_COLOR_REFS_REMOTES"));
6806 if (err)
6807 goto done;
6809 err = add_color(&s->colors, "^refs/got/backup/",
6810 TOG_COLOR_REFS_BACKUP,
6811 get_color_value("TOG_COLOR_REFS_BACKUP"));
6812 if (err)
6813 goto done;
6816 view->show = show_ref_view;
6817 view->input = input_ref_view;
6818 view->close = close_ref_view;
6819 view->search_start = search_start_ref_view;
6820 view->search_next = search_next_ref_view;
6821 done:
6822 if (err)
6823 free_colors(&s->colors);
6824 return err;
6827 static const struct got_error *
6828 close_ref_view(struct tog_view *view)
6830 struct tog_ref_view_state *s = &view->state.ref;
6832 ref_view_free_refs(s);
6833 free_colors(&s->colors);
6835 return NULL;
6838 static const struct got_error *
6839 resolve_reflist_entry(struct got_object_id **commit_id,
6840 struct tog_reflist_entry *re, struct got_repository *repo)
6842 const struct got_error *err = NULL;
6843 struct got_object_id *obj_id;
6844 struct got_tag_object *tag = NULL;
6845 int obj_type;
6847 *commit_id = NULL;
6849 err = got_ref_resolve(&obj_id, repo, re->ref);
6850 if (err)
6851 return err;
6853 err = got_object_get_type(&obj_type, repo, obj_id);
6854 if (err)
6855 goto done;
6857 switch (obj_type) {
6858 case GOT_OBJ_TYPE_COMMIT:
6859 *commit_id = obj_id;
6860 break;
6861 case GOT_OBJ_TYPE_TAG:
6862 err = got_object_open_as_tag(&tag, repo, obj_id);
6863 if (err)
6864 goto done;
6865 free(obj_id);
6866 err = got_object_get_type(&obj_type, repo,
6867 got_object_tag_get_object_id(tag));
6868 if (err)
6869 goto done;
6870 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
6871 err = got_error(GOT_ERR_OBJ_TYPE);
6872 goto done;
6874 *commit_id = got_object_id_dup(
6875 got_object_tag_get_object_id(tag));
6876 if (*commit_id == NULL) {
6877 err = got_error_from_errno("got_object_id_dup");
6878 goto done;
6880 break;
6881 default:
6882 err = got_error(GOT_ERR_OBJ_TYPE);
6883 break;
6886 done:
6887 if (tag)
6888 got_object_tag_close(tag);
6889 if (err) {
6890 free(*commit_id);
6891 *commit_id = NULL;
6893 return err;
6896 static const struct got_error *
6897 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
6898 struct tog_reflist_entry *re, struct got_repository *repo)
6900 struct tog_view *log_view;
6901 const struct got_error *err = NULL;
6902 struct got_object_id *commit_id = NULL;
6904 *new_view = NULL;
6906 err = resolve_reflist_entry(&commit_id, re, repo);
6907 if (err) {
6908 if (err->code != GOT_ERR_OBJ_TYPE)
6909 return err;
6910 else
6911 return NULL;
6914 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6915 if (log_view == NULL) {
6916 err = got_error_from_errno("view_open");
6917 goto done;
6920 err = open_log_view(log_view, commit_id, repo,
6921 got_ref_get_name(re->ref), "", 0);
6922 done:
6923 if (err)
6924 view_close(log_view);
6925 else
6926 *new_view = log_view;
6927 free(commit_id);
6928 return err;
6931 static void
6932 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
6934 struct tog_reflist_entry *re;
6935 int i = 0;
6937 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
6938 return;
6940 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
6941 while (i++ < maxscroll) {
6942 if (re == NULL)
6943 break;
6944 s->first_displayed_entry = re;
6945 re = TAILQ_PREV(re, tog_reflist_head, entry);
6949 static const struct got_error *
6950 ref_scroll_down(struct tog_view *view, int maxscroll)
6952 struct tog_ref_view_state *s = &view->state.ref;
6953 struct tog_reflist_entry *next, *last;
6954 int n = 0;
6956 if (s->first_displayed_entry)
6957 next = TAILQ_NEXT(s->first_displayed_entry, entry);
6958 else
6959 next = TAILQ_FIRST(&s->refs);
6961 last = s->last_displayed_entry;
6962 while (next && n++ < maxscroll) {
6963 if (last)
6964 last = TAILQ_NEXT(last, entry);
6965 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
6966 s->first_displayed_entry = next;
6967 next = TAILQ_NEXT(next, entry);
6971 return NULL;
6974 static const struct got_error *
6975 search_start_ref_view(struct tog_view *view)
6977 struct tog_ref_view_state *s = &view->state.ref;
6979 s->matched_entry = NULL;
6980 return NULL;
6983 static int
6984 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
6986 regmatch_t regmatch;
6988 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
6989 0) == 0;
6992 static const struct got_error *
6993 search_next_ref_view(struct tog_view *view)
6995 struct tog_ref_view_state *s = &view->state.ref;
6996 struct tog_reflist_entry *re = NULL;
6998 if (!view->searching) {
6999 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7000 return NULL;
7003 if (s->matched_entry) {
7004 if (view->searching == TOG_SEARCH_FORWARD) {
7005 if (s->selected_entry)
7006 re = TAILQ_NEXT(s->selected_entry, entry);
7007 else
7008 re = TAILQ_PREV(s->selected_entry,
7009 tog_reflist_head, entry);
7010 } else {
7011 if (s->selected_entry == NULL)
7012 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7013 else
7014 re = TAILQ_PREV(s->selected_entry,
7015 tog_reflist_head, entry);
7017 } else {
7018 if (s->selected_entry)
7019 re = s->selected_entry;
7020 else if (view->searching == TOG_SEARCH_FORWARD)
7021 re = TAILQ_FIRST(&s->refs);
7022 else
7023 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7026 while (1) {
7027 if (re == NULL) {
7028 if (s->matched_entry == NULL) {
7029 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7030 return NULL;
7032 if (view->searching == TOG_SEARCH_FORWARD)
7033 re = TAILQ_FIRST(&s->refs);
7034 else
7035 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7038 if (match_reflist_entry(re, &view->regex)) {
7039 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7040 s->matched_entry = re;
7041 break;
7044 if (view->searching == TOG_SEARCH_FORWARD)
7045 re = TAILQ_NEXT(re, entry);
7046 else
7047 re = TAILQ_PREV(re, tog_reflist_head, entry);
7050 if (s->matched_entry) {
7051 s->first_displayed_entry = s->matched_entry;
7052 s->selected = 0;
7055 return NULL;
7058 static const struct got_error *
7059 show_ref_view(struct tog_view *view)
7061 const struct got_error *err = NULL;
7062 struct tog_ref_view_state *s = &view->state.ref;
7063 struct tog_reflist_entry *re;
7064 char *line = NULL;
7065 wchar_t *wline;
7066 struct tog_color *tc;
7067 int width, n;
7068 int limit = view->nlines;
7070 werase(view->window);
7072 s->ndisplayed = 0;
7073 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
7074 view_is_splitscreen(view->child))
7075 --limit; /* border */
7077 if (limit == 0)
7078 return NULL;
7080 re = s->first_displayed_entry;
7082 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7083 s->nrefs) == -1)
7084 return got_error_from_errno("asprintf");
7086 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7087 if (err) {
7088 free(line);
7089 return err;
7091 if (view_needs_focus_indication(view))
7092 wstandout(view->window);
7093 waddwstr(view->window, wline);
7094 if (view_needs_focus_indication(view))
7095 wstandend(view->window);
7096 free(wline);
7097 wline = NULL;
7098 free(line);
7099 line = NULL;
7100 if (width < view->ncols - 1)
7101 waddch(view->window, '\n');
7102 if (--limit <= 0)
7103 return NULL;
7105 n = 0;
7106 while (re && limit > 0) {
7107 char *line = NULL;
7108 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7110 if (s->show_date) {
7111 struct got_commit_object *ci;
7112 struct got_tag_object *tag;
7113 struct got_object_id *id;
7114 struct tm tm;
7115 time_t t;
7117 err = got_ref_resolve(&id, s->repo, re->ref);
7118 if (err)
7119 return err;
7120 err = got_object_open_as_tag(&tag, s->repo, id);
7121 if (err) {
7122 if (err->code != GOT_ERR_OBJ_TYPE) {
7123 free(id);
7124 return err;
7126 err = got_object_open_as_commit(&ci, s->repo,
7127 id);
7128 if (err) {
7129 free(id);
7130 return err;
7132 t = got_object_commit_get_committer_time(ci);
7133 got_object_commit_close(ci);
7134 } else {
7135 t = got_object_tag_get_tagger_time(tag);
7136 got_object_tag_close(tag);
7138 free(id);
7139 if (gmtime_r(&t, &tm) == NULL)
7140 return got_error_from_errno("gmtime_r");
7141 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7142 return got_error(GOT_ERR_NO_SPACE);
7144 if (got_ref_is_symbolic(re->ref)) {
7145 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7146 ymd : "", got_ref_get_name(re->ref),
7147 got_ref_get_symref_target(re->ref)) == -1)
7148 return got_error_from_errno("asprintf");
7149 } else if (s->show_ids) {
7150 struct got_object_id *id;
7151 char *id_str;
7152 err = got_ref_resolve(&id, s->repo, re->ref);
7153 if (err)
7154 return err;
7155 err = got_object_id_str(&id_str, id);
7156 if (err) {
7157 free(id);
7158 return err;
7160 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7161 got_ref_get_name(re->ref), id_str) == -1) {
7162 err = got_error_from_errno("asprintf");
7163 free(id);
7164 free(id_str);
7165 return err;
7167 free(id);
7168 free(id_str);
7169 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7170 got_ref_get_name(re->ref)) == -1)
7171 return got_error_from_errno("asprintf");
7173 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7174 0, 0);
7175 if (err) {
7176 free(line);
7177 return err;
7179 if (n == s->selected) {
7180 if (view->focussed)
7181 wstandout(view->window);
7182 s->selected_entry = re;
7184 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7185 if (tc)
7186 wattr_on(view->window,
7187 COLOR_PAIR(tc->colorpair), NULL);
7188 waddwstr(view->window, wline);
7189 if (tc)
7190 wattr_off(view->window,
7191 COLOR_PAIR(tc->colorpair), NULL);
7192 if (width < view->ncols - 1)
7193 waddch(view->window, '\n');
7194 if (n == s->selected && view->focussed)
7195 wstandend(view->window);
7196 free(line);
7197 free(wline);
7198 wline = NULL;
7199 n++;
7200 s->ndisplayed++;
7201 s->last_displayed_entry = re;
7203 limit--;
7204 re = TAILQ_NEXT(re, entry);
7207 view_border(view);
7208 return err;
7211 static const struct got_error *
7212 browse_ref_tree(struct tog_view **new_view, int begin_x,
7213 struct tog_reflist_entry *re, struct got_repository *repo)
7215 const struct got_error *err = NULL;
7216 struct got_object_id *commit_id = NULL;
7217 struct tog_view *tree_view;
7219 *new_view = NULL;
7221 err = resolve_reflist_entry(&commit_id, re, repo);
7222 if (err) {
7223 if (err->code != GOT_ERR_OBJ_TYPE)
7224 return err;
7225 else
7226 return NULL;
7230 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
7231 if (tree_view == NULL) {
7232 err = got_error_from_errno("view_open");
7233 goto done;
7236 err = open_tree_view(tree_view, commit_id,
7237 got_ref_get_name(re->ref), repo);
7238 if (err)
7239 goto done;
7241 *new_view = tree_view;
7242 done:
7243 free(commit_id);
7244 return err;
7246 static const struct got_error *
7247 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7249 const struct got_error *err = NULL;
7250 struct tog_ref_view_state *s = &view->state.ref;
7251 struct tog_view *log_view, *tree_view;
7252 struct tog_reflist_entry *re;
7253 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 1;
7255 switch (ch) {
7256 case 'i':
7257 s->show_ids = !s->show_ids;
7258 view->count = 0;
7259 break;
7260 case 'm':
7261 s->show_date = !s->show_date;
7262 view->count = 0;
7263 break;
7264 case 'o':
7265 s->sort_by_date = !s->sort_by_date;
7266 view->count = 0;
7267 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7268 got_ref_cmp_by_commit_timestamp_descending :
7269 tog_ref_cmp_by_name, s->repo);
7270 if (err)
7271 break;
7272 got_reflist_object_id_map_free(tog_refs_idmap);
7273 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7274 &tog_refs, s->repo);
7275 if (err)
7276 break;
7277 ref_view_free_refs(s);
7278 err = ref_view_load_refs(s);
7279 break;
7280 case KEY_ENTER:
7281 case '\r':
7282 view->count = 0;
7283 if (!s->selected_entry)
7284 break;
7285 if (view_is_parent_view(view))
7286 view_get_split(view, &begin_y, &begin_x);
7288 err = log_ref_entry(&log_view, begin_y, begin_x,
7289 s->selected_entry, s->repo);
7290 if (err)
7291 break;
7293 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
7294 err = view_init_hsplit(view, begin_y);
7295 if (err)
7296 break;
7299 view->focussed = 0;
7300 log_view->focussed = 1;
7301 log_view->mode = view->mode;
7302 log_view->nlines = view->lines - begin_y;
7303 if (view_is_parent_view(view)) {
7304 err = view_close_child(view);
7305 if (err)
7306 return err;
7307 err = view_set_child(view, log_view);
7308 if (err)
7309 return err;
7310 view->focus_child = 1;
7311 } else
7312 *new_view = log_view;
7313 break;
7314 case 't':
7315 view->count = 0;
7316 if (!s->selected_entry)
7317 break;
7318 if (view_is_parent_view(view))
7319 begin_x = view_split_begin_x(view->begin_x);
7320 err = browse_ref_tree(&tree_view, begin_x, s->selected_entry,
7321 s->repo);
7322 if (err || tree_view == NULL)
7323 break;
7324 view->focussed = 0;
7325 tree_view->focussed = 1;
7326 if (view_is_parent_view(view)) {
7327 err = view_close_child(view);
7328 if (err)
7329 return err;
7330 err = view_set_child(view, tree_view);
7331 if (err)
7332 return err;
7333 view->focus_child = 1;
7334 } else
7335 *new_view = tree_view;
7336 break;
7337 case 'g':
7338 case KEY_HOME:
7339 s->selected = 0;
7340 view->count = 0;
7341 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7342 break;
7343 case 'G':
7344 case KEY_END: {
7345 int eos = view->nlines - 1;
7347 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7348 --eos; /* border */
7349 s->selected = 0;
7350 view->count = 0;
7351 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7352 for (n = 0; n < eos; n++) {
7353 if (re == NULL)
7354 break;
7355 s->first_displayed_entry = re;
7356 re = TAILQ_PREV(re, tog_reflist_head, entry);
7358 if (n > 0)
7359 s->selected = n - 1;
7360 break;
7362 case 'k':
7363 case KEY_UP:
7364 case CTRL('p'):
7365 if (s->selected > 0) {
7366 s->selected--;
7367 break;
7369 ref_scroll_up(s, 1);
7370 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7371 view->count = 0;
7372 break;
7373 case CTRL('u'):
7374 case 'u':
7375 nscroll /= 2;
7376 /* FALL THROUGH */
7377 case KEY_PPAGE:
7378 case CTRL('b'):
7379 case 'b':
7380 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7381 s->selected -= MIN(nscroll, s->selected);
7382 ref_scroll_up(s, MAX(0, nscroll));
7383 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7384 view->count = 0;
7385 break;
7386 case 'j':
7387 case KEY_DOWN:
7388 case CTRL('n'):
7389 if (s->selected < s->ndisplayed - 1) {
7390 s->selected++;
7391 break;
7393 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7394 /* can't scroll any further */
7395 view->count = 0;
7396 break;
7398 ref_scroll_down(view, 1);
7399 break;
7400 case CTRL('d'):
7401 case 'd':
7402 nscroll /= 2;
7403 /* FALL THROUGH */
7404 case KEY_NPAGE:
7405 case CTRL('f'):
7406 case 'f':
7407 case ' ':
7408 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7409 /* can't scroll any further; move cursor down */
7410 if (s->selected < s->ndisplayed - 1)
7411 s->selected += MIN(nscroll,
7412 s->ndisplayed - s->selected - 1);
7413 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7414 s->selected += s->ndisplayed - s->selected - 1;
7415 view->count = 0;
7416 break;
7418 ref_scroll_down(view, nscroll);
7419 break;
7420 case CTRL('l'):
7421 view->count = 0;
7422 tog_free_refs();
7423 err = tog_load_refs(s->repo, s->sort_by_date);
7424 if (err)
7425 break;
7426 ref_view_free_refs(s);
7427 err = ref_view_load_refs(s);
7428 break;
7429 case KEY_RESIZE:
7430 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7431 s->selected = view->nlines - 2;
7432 break;
7433 default:
7434 view->count = 0;
7435 break;
7438 return err;
7441 __dead static void
7442 usage_ref(void)
7444 endwin();
7445 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7446 getprogname());
7447 exit(1);
7450 static const struct got_error *
7451 cmd_ref(int argc, char *argv[])
7453 const struct got_error *error;
7454 struct got_repository *repo = NULL;
7455 struct got_worktree *worktree = NULL;
7456 char *cwd = NULL, *repo_path = NULL;
7457 int ch;
7458 struct tog_view *view;
7459 int *pack_fds = NULL;
7461 while ((ch = getopt(argc, argv, "r:")) != -1) {
7462 switch (ch) {
7463 case 'r':
7464 repo_path = realpath(optarg, NULL);
7465 if (repo_path == NULL)
7466 return got_error_from_errno2("realpath",
7467 optarg);
7468 break;
7469 default:
7470 usage_ref();
7471 /* NOTREACHED */
7475 argc -= optind;
7476 argv += optind;
7478 if (argc > 1)
7479 usage_ref();
7481 error = got_repo_pack_fds_open(&pack_fds);
7482 if (error != NULL)
7483 goto done;
7485 if (repo_path == NULL) {
7486 cwd = getcwd(NULL, 0);
7487 if (cwd == NULL)
7488 return got_error_from_errno("getcwd");
7489 error = got_worktree_open(&worktree, cwd);
7490 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7491 goto done;
7492 if (worktree)
7493 repo_path =
7494 strdup(got_worktree_get_repo_path(worktree));
7495 else
7496 repo_path = strdup(cwd);
7497 if (repo_path == NULL) {
7498 error = got_error_from_errno("strdup");
7499 goto done;
7503 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7504 if (error != NULL)
7505 goto done;
7507 init_curses();
7509 error = apply_unveil(got_repo_get_path(repo), NULL);
7510 if (error)
7511 goto done;
7513 error = tog_load_refs(repo, 0);
7514 if (error)
7515 goto done;
7517 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7518 if (view == NULL) {
7519 error = got_error_from_errno("view_open");
7520 goto done;
7523 error = open_ref_view(view, repo);
7524 if (error)
7525 goto done;
7527 if (worktree) {
7528 /* Release work tree lock. */
7529 got_worktree_close(worktree);
7530 worktree = NULL;
7532 error = view_loop(view);
7533 done:
7534 free(repo_path);
7535 free(cwd);
7536 if (repo) {
7537 const struct got_error *close_err = got_repo_close(repo);
7538 if (close_err)
7539 error = close_err;
7541 if (pack_fds) {
7542 const struct got_error *pack_err =
7543 got_repo_pack_fds_close(pack_fds);
7544 if (error == NULL)
7545 error = pack_err;
7547 tog_free_refs();
7548 return error;
7552 * If view was scrolled down to move the selected line into view when opening a
7553 * horizontal split, scroll back up when closing the split/toggling fullscreen.
7555 static void
7556 offset_selection_up(struct tog_view *view)
7558 switch (view->type) {
7559 case TOG_VIEW_BLAME: {
7560 struct tog_blame_view_state *s = &view->state.blame;
7561 if (s->first_displayed_line == 1) {
7562 s->selected_line = MAX(s->selected_line - view->offset,
7563 1);
7564 break;
7566 if (s->first_displayed_line > view->offset)
7567 s->first_displayed_line -= view->offset;
7568 else
7569 s->first_displayed_line = 1;
7570 s->selected_line += view->offset;
7571 break;
7573 case TOG_VIEW_LOG:
7574 log_scroll_up(&view->state.log, view->offset);
7575 view->state.log.selected += view->offset;
7576 break;
7577 case TOG_VIEW_REF:
7578 ref_scroll_up(&view->state.ref, view->offset);
7579 view->state.ref.selected += view->offset;
7580 break;
7581 case TOG_VIEW_TREE:
7582 tree_scroll_up(&view->state.tree, view->offset);
7583 view->state.tree.selected += view->offset;
7584 break;
7585 default:
7586 break;
7589 view->offset = 0;
7593 * If the selected line is in the section of screen covered by the bottom split,
7594 * scroll down offset lines to move it into view and index its new position.
7596 static const struct got_error *
7597 offset_selection_down(struct tog_view *view)
7599 const struct got_error *err = NULL;
7600 const struct got_error *(*scrolld)(struct tog_view *, int);
7601 int *selected = NULL;
7602 int header, offset;
7604 switch (view->type) {
7605 case TOG_VIEW_BLAME: {
7606 struct tog_blame_view_state *s = &view->state.blame;
7607 header = 3;
7608 scrolld = NULL;
7609 if (s->selected_line > view->nlines - header) {
7610 offset = abs(view->nlines - s->selected_line - header);
7611 s->first_displayed_line += offset;
7612 s->selected_line -= offset;
7613 view->offset = offset;
7615 break;
7617 case TOG_VIEW_LOG: {
7618 struct tog_log_view_state *s = &view->state.log;
7619 scrolld = &log_scroll_down;
7620 header = 3;
7621 selected = &s->selected;
7622 break;
7624 case TOG_VIEW_REF: {
7625 struct tog_ref_view_state *s = &view->state.ref;
7626 scrolld = &ref_scroll_down;
7627 header = 3;
7628 selected = &s->selected;
7629 break;
7631 case TOG_VIEW_TREE: {
7632 struct tog_tree_view_state *s = &view->state.tree;
7633 scrolld = &tree_scroll_down;
7634 header = 5;
7635 selected = &s->selected;
7636 break;
7638 default:
7639 selected = NULL;
7640 scrolld = NULL;
7641 header = 0;
7642 break;
7645 if (selected && *selected > view->nlines - header) {
7646 offset = abs(view->nlines - *selected - header);
7647 view->offset = offset;
7648 if (scrolld && offset) {
7649 err = scrolld(view, offset);
7650 *selected -= offset;
7654 return err;
7657 static void
7658 list_commands(FILE *fp)
7660 size_t i;
7662 fprintf(fp, "commands:");
7663 for (i = 0; i < nitems(tog_commands); i++) {
7664 const struct tog_cmd *cmd = &tog_commands[i];
7665 fprintf(fp, " %s", cmd->name);
7667 fputc('\n', fp);
7670 __dead static void
7671 usage(int hflag, int status)
7673 FILE *fp = (status == 0) ? stdout : stderr;
7675 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
7676 getprogname());
7677 if (hflag) {
7678 fprintf(fp, "lazy usage: %s path\n", getprogname());
7679 list_commands(fp);
7681 exit(status);
7684 static char **
7685 make_argv(int argc, ...)
7687 va_list ap;
7688 char **argv;
7689 int i;
7691 va_start(ap, argc);
7693 argv = calloc(argc, sizeof(char *));
7694 if (argv == NULL)
7695 err(1, "calloc");
7696 for (i = 0; i < argc; i++) {
7697 argv[i] = strdup(va_arg(ap, char *));
7698 if (argv[i] == NULL)
7699 err(1, "strdup");
7702 va_end(ap);
7703 return argv;
7707 * Try to convert 'tog path' into a 'tog log path' command.
7708 * The user could simply have mistyped the command rather than knowingly
7709 * provided a path. So check whether argv[0] can in fact be resolved
7710 * to a path in the HEAD commit and print a special error if not.
7711 * This hack is for mpi@ <3
7713 static const struct got_error *
7714 tog_log_with_path(int argc, char *argv[])
7716 const struct got_error *error = NULL, *close_err;
7717 const struct tog_cmd *cmd = NULL;
7718 struct got_repository *repo = NULL;
7719 struct got_worktree *worktree = NULL;
7720 struct got_object_id *commit_id = NULL, *id = NULL;
7721 struct got_commit_object *commit = NULL;
7722 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7723 char *commit_id_str = NULL, **cmd_argv = NULL;
7724 int *pack_fds = NULL;
7726 cwd = getcwd(NULL, 0);
7727 if (cwd == NULL)
7728 return got_error_from_errno("getcwd");
7730 error = got_repo_pack_fds_open(&pack_fds);
7731 if (error != NULL)
7732 goto done;
7734 error = got_worktree_open(&worktree, cwd);
7735 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7736 goto done;
7738 if (worktree)
7739 repo_path = strdup(got_worktree_get_repo_path(worktree));
7740 else
7741 repo_path = strdup(cwd);
7742 if (repo_path == NULL) {
7743 error = got_error_from_errno("strdup");
7744 goto done;
7747 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7748 if (error != NULL)
7749 goto done;
7751 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7752 repo, worktree);
7753 if (error)
7754 goto done;
7756 error = tog_load_refs(repo, 0);
7757 if (error)
7758 goto done;
7759 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
7760 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
7761 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7762 if (error)
7763 goto done;
7765 if (worktree) {
7766 got_worktree_close(worktree);
7767 worktree = NULL;
7770 error = got_object_open_as_commit(&commit, repo, commit_id);
7771 if (error)
7772 goto done;
7774 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
7775 if (error) {
7776 if (error->code != GOT_ERR_NO_TREE_ENTRY)
7777 goto done;
7778 fprintf(stderr, "%s: '%s' is no known command or path\n",
7779 getprogname(), argv[0]);
7780 usage(1, 1);
7781 /* not reached */
7784 close_err = got_repo_close(repo);
7785 if (error == NULL)
7786 error = close_err;
7787 repo = NULL;
7789 error = got_object_id_str(&commit_id_str, commit_id);
7790 if (error)
7791 goto done;
7793 cmd = &tog_commands[0]; /* log */
7794 argc = 4;
7795 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
7796 error = cmd->cmd_main(argc, cmd_argv);
7797 done:
7798 if (repo) {
7799 close_err = got_repo_close(repo);
7800 if (error == NULL)
7801 error = close_err;
7803 if (commit)
7804 got_object_commit_close(commit);
7805 if (worktree)
7806 got_worktree_close(worktree);
7807 if (pack_fds) {
7808 const struct got_error *pack_err =
7809 got_repo_pack_fds_close(pack_fds);
7810 if (error == NULL)
7811 error = pack_err;
7813 free(id);
7814 free(commit_id_str);
7815 free(commit_id);
7816 free(cwd);
7817 free(repo_path);
7818 free(in_repo_path);
7819 if (cmd_argv) {
7820 int i;
7821 for (i = 0; i < argc; i++)
7822 free(cmd_argv[i]);
7823 free(cmd_argv);
7825 tog_free_refs();
7826 return error;
7829 int
7830 main(int argc, char *argv[])
7832 const struct got_error *error = NULL;
7833 const struct tog_cmd *cmd = NULL;
7834 int ch, hflag = 0, Vflag = 0;
7835 char **cmd_argv = NULL;
7836 static const struct option longopts[] = {
7837 { "version", no_argument, NULL, 'V' },
7838 { NULL, 0, NULL, 0}
7841 setlocale(LC_CTYPE, "");
7843 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
7844 switch (ch) {
7845 case 'h':
7846 hflag = 1;
7847 break;
7848 case 'V':
7849 Vflag = 1;
7850 break;
7851 default:
7852 usage(hflag, 1);
7853 /* NOTREACHED */
7857 argc -= optind;
7858 argv += optind;
7859 optind = 1;
7860 optreset = 1;
7862 if (Vflag) {
7863 got_version_print_str();
7864 return 0;
7867 #ifndef PROFILE
7868 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
7869 NULL) == -1)
7870 err(1, "pledge");
7871 #endif
7873 if (argc == 0) {
7874 if (hflag)
7875 usage(hflag, 0);
7876 /* Build an argument vector which runs a default command. */
7877 cmd = &tog_commands[0];
7878 argc = 1;
7879 cmd_argv = make_argv(argc, cmd->name);
7880 } else {
7881 size_t i;
7883 /* Did the user specify a command? */
7884 for (i = 0; i < nitems(tog_commands); i++) {
7885 if (strncmp(tog_commands[i].name, argv[0],
7886 strlen(argv[0])) == 0) {
7887 cmd = &tog_commands[i];
7888 break;
7893 if (cmd == NULL) {
7894 if (argc != 1)
7895 usage(0, 1);
7896 /* No command specified; try log with a path */
7897 error = tog_log_with_path(argc, argv);
7898 } else {
7899 if (hflag)
7900 cmd->cmd_usage();
7901 else
7902 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
7905 endwin();
7906 putchar('\n');
7907 if (cmd_argv) {
7908 int i;
7909 for (i = 0; i < argc; i++)
7910 free(cmd_argv[i]);
7911 free(cmd_argv);
7914 if (error && error->code != GOT_ERR_CANCELLED)
7915 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7916 return 0;