Blob


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