Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <getopt.h>
33 #include <string.h>
34 #include <err.h>
35 #include <unistd.h>
36 #include <limits.h>
37 #include <wchar.h>
38 #include <time.h>
39 #include <pthread.h>
40 #include <libgen.h>
41 #include <regex.h>
42 #include <sched.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_diff.h"
50 #include "got_opentemp.h"
51 #include "got_utf8.h"
52 #include "got_cancel.h"
53 #include "got_commit_graph.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_path.h"
57 #include "got_worktree.h"
59 #ifndef MIN
60 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
61 #endif
63 #ifndef MAX
64 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
65 #endif
67 #define CTRL(x) ((x) & 0x1f)
69 #ifndef nitems
70 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
71 #endif
73 struct tog_cmd {
74 const char *name;
75 const struct got_error *(*cmd_main)(int, char *[]);
76 void (*cmd_usage)(void);
77 };
79 __dead static void usage(int, int);
80 __dead static void usage_log(void);
81 __dead static void usage_diff(void);
82 __dead static void usage_blame(void);
83 __dead static void usage_tree(void);
84 __dead static void usage_ref(void);
86 static const struct got_error* cmd_log(int, char *[]);
87 static const struct got_error* cmd_diff(int, char *[]);
88 static const struct got_error* cmd_blame(int, char *[]);
89 static const struct got_error* cmd_tree(int, char *[]);
90 static const struct got_error* cmd_ref(int, char *[]);
92 static const struct tog_cmd tog_commands[] = {
93 { "log", cmd_log, usage_log },
94 { "diff", cmd_diff, usage_diff },
95 { "blame", cmd_blame, usage_blame },
96 { "tree", cmd_tree, usage_tree },
97 { "ref", cmd_ref, usage_ref },
98 };
100 enum tog_view_type {
101 TOG_VIEW_DIFF,
102 TOG_VIEW_LOG,
103 TOG_VIEW_BLAME,
104 TOG_VIEW_TREE,
105 TOG_VIEW_REF,
106 };
108 enum tog_view_mode {
109 TOG_VIEW_SPLIT_NONE,
110 TOG_VIEW_SPLIT_VERT,
111 TOG_VIEW_SPLIT_HRZN
112 };
114 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
116 #define TOG_EOF_STRING "(END)"
118 struct commit_queue_entry {
119 TAILQ_ENTRY(commit_queue_entry) entry;
120 struct got_object_id *id;
121 struct got_commit_object *commit;
122 int idx;
123 };
124 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
125 struct commit_queue {
126 int ncommits;
127 struct commit_queue_head head;
128 };
130 struct tog_color {
131 STAILQ_ENTRY(tog_color) entry;
132 regex_t regex;
133 short colorpair;
134 };
135 STAILQ_HEAD(tog_colors, tog_color);
137 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
138 static struct got_reflist_object_id_map *tog_refs_idmap;
140 static const struct got_error *
141 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
142 struct got_reference* re2)
144 const char *name1 = got_ref_get_name(re1);
145 const char *name2 = got_ref_get_name(re2);
146 int isbackup1, isbackup2;
148 /* Sort backup refs towards the bottom of the list. */
149 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
150 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
151 if (!isbackup1 && isbackup2) {
152 *cmp = -1;
153 return NULL;
154 } else if (isbackup1 && !isbackup2) {
155 *cmp = 1;
156 return NULL;
159 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
160 return NULL;
163 static const struct got_error *
164 tog_load_refs(struct got_repository *repo, int sort_by_date)
166 const struct got_error *err;
168 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
169 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
170 repo);
171 if (err)
172 return err;
174 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
175 repo);
178 static void
179 tog_free_refs(void)
181 if (tog_refs_idmap) {
182 got_reflist_object_id_map_free(tog_refs_idmap);
183 tog_refs_idmap = NULL;
185 got_ref_list_free(&tog_refs);
188 static const struct got_error *
189 add_color(struct tog_colors *colors, const char *pattern,
190 int idx, short color)
192 const struct got_error *err = NULL;
193 struct tog_color *tc;
194 int regerr = 0;
196 if (idx < 1 || idx > COLOR_PAIRS - 1)
197 return NULL;
199 init_pair(idx, color, -1);
201 tc = calloc(1, sizeof(*tc));
202 if (tc == NULL)
203 return got_error_from_errno("calloc");
204 regerr = regcomp(&tc->regex, pattern,
205 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
206 if (regerr) {
207 static char regerr_msg[512];
208 static char err_msg[512];
209 regerror(regerr, &tc->regex, regerr_msg,
210 sizeof(regerr_msg));
211 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
212 regerr_msg);
213 err = got_error_msg(GOT_ERR_REGEX, err_msg);
214 free(tc);
215 return err;
217 tc->colorpair = idx;
218 STAILQ_INSERT_HEAD(colors, tc, entry);
219 return NULL;
222 static void
223 free_colors(struct tog_colors *colors)
225 struct tog_color *tc;
227 while (!STAILQ_EMPTY(colors)) {
228 tc = STAILQ_FIRST(colors);
229 STAILQ_REMOVE_HEAD(colors, entry);
230 regfree(&tc->regex);
231 free(tc);
235 static struct tog_color *
236 get_color(struct tog_colors *colors, int colorpair)
238 struct tog_color *tc = NULL;
240 STAILQ_FOREACH(tc, colors, entry) {
241 if (tc->colorpair == colorpair)
242 return tc;
245 return NULL;
248 static int
249 default_color_value(const char *envvar)
251 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
252 return COLOR_MAGENTA;
253 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
254 return COLOR_CYAN;
255 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
256 return COLOR_YELLOW;
257 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
258 return COLOR_GREEN;
259 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
260 return COLOR_MAGENTA;
261 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
262 return COLOR_MAGENTA;
263 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
264 return COLOR_CYAN;
265 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
266 return COLOR_GREEN;
267 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
268 return COLOR_GREEN;
269 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
270 return COLOR_CYAN;
271 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
272 return COLOR_YELLOW;
273 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
274 return COLOR_GREEN;
275 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
276 return COLOR_MAGENTA;
277 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
278 return COLOR_YELLOW;
279 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
280 return COLOR_CYAN;
282 return -1;
285 static int
286 get_color_value(const char *envvar)
288 const char *val = getenv(envvar);
290 if (val == NULL)
291 return default_color_value(envvar);
293 if (strcasecmp(val, "black") == 0)
294 return COLOR_BLACK;
295 if (strcasecmp(val, "red") == 0)
296 return COLOR_RED;
297 if (strcasecmp(val, "green") == 0)
298 return COLOR_GREEN;
299 if (strcasecmp(val, "yellow") == 0)
300 return COLOR_YELLOW;
301 if (strcasecmp(val, "blue") == 0)
302 return COLOR_BLUE;
303 if (strcasecmp(val, "magenta") == 0)
304 return COLOR_MAGENTA;
305 if (strcasecmp(val, "cyan") == 0)
306 return COLOR_CYAN;
307 if (strcasecmp(val, "white") == 0)
308 return COLOR_WHITE;
309 if (strcasecmp(val, "default") == 0)
310 return -1;
312 return default_color_value(envvar);
316 struct tog_diff_view_state {
317 struct got_object_id *id1, *id2;
318 const char *label1, *label2;
319 FILE *f, *f1, *f2;
320 int fd1, fd2;
321 int first_displayed_line;
322 int last_displayed_line;
323 int eof;
324 int diff_context;
325 int ignore_whitespace;
326 int force_text_diff;
327 struct got_repository *repo;
328 struct tog_colors colors;
329 size_t nlines;
330 off_t *line_offsets;
331 int matched_line;
332 int selected_line;
334 /* passed from log view; may be NULL */
335 struct tog_view *log_view;
336 };
338 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
340 struct tog_log_thread_args {
341 pthread_cond_t need_commits;
342 pthread_cond_t commit_loaded;
343 int commits_needed;
344 int load_all;
345 struct got_commit_graph *graph;
346 struct commit_queue *commits;
347 const char *in_repo_path;
348 struct got_object_id *start_id;
349 struct got_repository *repo;
350 int *pack_fds;
351 int log_complete;
352 sig_atomic_t *quit;
353 struct commit_queue_entry **first_displayed_entry;
354 struct commit_queue_entry **selected_entry;
355 int *searching;
356 int *search_next_done;
357 regex_t *regex;
358 };
360 struct tog_log_view_state {
361 struct commit_queue commits;
362 struct commit_queue_entry *first_displayed_entry;
363 struct commit_queue_entry *last_displayed_entry;
364 struct commit_queue_entry *selected_entry;
365 int selected;
366 char *in_repo_path;
367 char *head_ref_name;
368 int log_branches;
369 struct got_repository *repo;
370 struct got_object_id *start_id;
371 sig_atomic_t quit;
372 pthread_t thread;
373 struct tog_log_thread_args thread_args;
374 struct commit_queue_entry *matched_entry;
375 struct commit_queue_entry *search_entry;
376 struct tog_colors colors;
377 };
379 #define TOG_COLOR_DIFF_MINUS 1
380 #define TOG_COLOR_DIFF_PLUS 2
381 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
382 #define TOG_COLOR_DIFF_META 4
383 #define TOG_COLOR_TREE_SUBMODULE 5
384 #define TOG_COLOR_TREE_SYMLINK 6
385 #define TOG_COLOR_TREE_DIRECTORY 7
386 #define TOG_COLOR_TREE_EXECUTABLE 8
387 #define TOG_COLOR_COMMIT 9
388 #define TOG_COLOR_AUTHOR 10
389 #define TOG_COLOR_DATE 11
390 #define TOG_COLOR_REFS_HEADS 12
391 #define TOG_COLOR_REFS_TAGS 13
392 #define TOG_COLOR_REFS_REMOTES 14
393 #define TOG_COLOR_REFS_BACKUP 15
395 struct tog_blame_cb_args {
396 struct tog_blame_line *lines; /* one per line */
397 int nlines;
399 struct tog_view *view;
400 struct got_object_id *commit_id;
401 int *quit;
402 };
404 struct tog_blame_thread_args {
405 const char *path;
406 struct got_repository *repo;
407 struct tog_blame_cb_args *cb_args;
408 int *complete;
409 got_cancel_cb cancel_cb;
410 void *cancel_arg;
411 };
413 struct tog_blame {
414 FILE *f;
415 off_t filesize;
416 struct tog_blame_line *lines;
417 int nlines;
418 off_t *line_offsets;
419 pthread_t thread;
420 struct tog_blame_thread_args thread_args;
421 struct tog_blame_cb_args cb_args;
422 const char *path;
423 int *pack_fds;
424 };
426 struct tog_blame_view_state {
427 int first_displayed_line;
428 int last_displayed_line;
429 int selected_line;
430 int blame_complete;
431 int eof;
432 int done;
433 struct got_object_id_queue blamed_commits;
434 struct got_object_qid *blamed_commit;
435 char *path;
436 struct got_repository *repo;
437 struct got_object_id *commit_id;
438 struct tog_blame blame;
439 int matched_line;
440 struct tog_colors colors;
441 };
443 struct tog_parent_tree {
444 TAILQ_ENTRY(tog_parent_tree) entry;
445 struct got_tree_object *tree;
446 struct got_tree_entry *first_displayed_entry;
447 struct got_tree_entry *selected_entry;
448 int selected;
449 };
451 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
453 struct tog_tree_view_state {
454 char *tree_label;
455 struct got_object_id *commit_id;/* commit which this tree belongs to */
456 struct got_tree_object *root; /* the commit's root tree entry */
457 struct got_tree_object *tree; /* currently displayed (sub-)tree */
458 struct got_tree_entry *first_displayed_entry;
459 struct got_tree_entry *last_displayed_entry;
460 struct got_tree_entry *selected_entry;
461 int ndisplayed, selected, show_ids;
462 struct tog_parent_trees parents; /* parent trees of current sub-tree */
463 char *head_ref_name;
464 struct got_repository *repo;
465 struct got_tree_entry *matched_entry;
466 struct tog_colors colors;
467 };
469 struct tog_reflist_entry {
470 TAILQ_ENTRY(tog_reflist_entry) entry;
471 struct got_reference *ref;
472 int idx;
473 };
475 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
477 struct tog_ref_view_state {
478 struct tog_reflist_head refs;
479 struct tog_reflist_entry *first_displayed_entry;
480 struct tog_reflist_entry *last_displayed_entry;
481 struct tog_reflist_entry *selected_entry;
482 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
483 struct got_repository *repo;
484 struct tog_reflist_entry *matched_entry;
485 struct tog_colors colors;
486 };
488 /*
489 * We implement two types of views: parent views and child views.
491 * The 'Tab' key switches focus between a parent view and its child view.
492 * Child views are shown side-by-side to their parent view, provided
493 * there is enough screen estate.
495 * When a new view is opened from within a parent view, this new view
496 * becomes a child view of the parent view, replacing any existing child.
498 * When a new view is opened from within a child view, this new view
499 * becomes a parent view which will obscure the views below until the
500 * user quits the new parent view by typing 'q'.
502 * This list of views contains parent views only.
503 * Child views are only pointed to by their parent view.
504 */
505 TAILQ_HEAD(tog_view_list_head, tog_view);
507 struct tog_view {
508 TAILQ_ENTRY(tog_view) entry;
509 WINDOW *window;
510 PANEL *panel;
511 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
512 int maxx, x; /* max column and current start column */
513 int lines, cols; /* copies of LINES and COLS */
514 int nscrolled, offset; /* lines scrolled and hsplit line offset */
515 int ch, count; /* current keymap and count prefix */
516 int focussed; /* Only set on one parent or child view at a time. */
517 int dying;
518 struct tog_view *parent;
519 struct tog_view *child;
521 /*
522 * This flag is initially set on parent views when a new child view
523 * is created. It gets toggled when the 'Tab' key switches focus
524 * between parent and child.
525 * The flag indicates whether focus should be passed on to our child
526 * view if this parent view gets picked for focus after another parent
527 * view was closed. This prevents child views from losing focus in such
528 * situations.
529 */
530 int focus_child;
532 enum tog_view_mode mode;
533 /* type-specific state */
534 enum tog_view_type type;
535 union {
536 struct tog_diff_view_state diff;
537 struct tog_log_view_state log;
538 struct tog_blame_view_state blame;
539 struct tog_tree_view_state tree;
540 struct tog_ref_view_state ref;
541 } state;
543 const struct got_error *(*show)(struct tog_view *);
544 const struct got_error *(*input)(struct tog_view **,
545 struct tog_view *, int);
546 const struct got_error *(*close)(struct tog_view *);
548 const struct got_error *(*search_start)(struct tog_view *);
549 const struct got_error *(*search_next)(struct tog_view *);
550 int search_started;
551 int searching;
552 #define TOG_SEARCH_FORWARD 1
553 #define TOG_SEARCH_BACKWARD 2
554 int search_next_done;
555 #define TOG_SEARCH_HAVE_MORE 1
556 #define TOG_SEARCH_NO_MORE 2
557 #define TOG_SEARCH_HAVE_NONE 3
558 regex_t regex;
559 regmatch_t regmatch;
560 };
562 static const struct got_error *open_diff_view(struct tog_view *,
563 struct got_object_id *, struct got_object_id *,
564 const char *, const char *, int, int, int, struct tog_view *,
565 struct got_repository *);
566 static const struct got_error *show_diff_view(struct tog_view *);
567 static const struct got_error *input_diff_view(struct tog_view **,
568 struct tog_view *, int);
569 static const struct got_error* close_diff_view(struct tog_view *);
570 static const struct got_error *search_start_diff_view(struct tog_view *);
571 static const struct got_error *search_next_diff_view(struct tog_view *);
573 static const struct got_error *open_log_view(struct tog_view *,
574 struct got_object_id *, struct got_repository *,
575 const char *, const char *, int);
576 static const struct got_error * show_log_view(struct tog_view *);
577 static const struct got_error *input_log_view(struct tog_view **,
578 struct tog_view *, int);
579 static const struct got_error *close_log_view(struct tog_view *);
580 static const struct got_error *search_start_log_view(struct tog_view *);
581 static const struct got_error *search_next_log_view(struct tog_view *);
583 static const struct got_error *open_blame_view(struct tog_view *, char *,
584 struct got_object_id *, struct got_repository *);
585 static const struct got_error *show_blame_view(struct tog_view *);
586 static const struct got_error *input_blame_view(struct tog_view **,
587 struct tog_view *, int);
588 static const struct got_error *close_blame_view(struct tog_view *);
589 static const struct got_error *search_start_blame_view(struct tog_view *);
590 static const struct got_error *search_next_blame_view(struct tog_view *);
592 static const struct got_error *open_tree_view(struct tog_view *,
593 struct got_object_id *, const char *, struct got_repository *);
594 static const struct got_error *show_tree_view(struct tog_view *);
595 static const struct got_error *input_tree_view(struct tog_view **,
596 struct tog_view *, int);
597 static const struct got_error *close_tree_view(struct tog_view *);
598 static const struct got_error *search_start_tree_view(struct tog_view *);
599 static const struct got_error *search_next_tree_view(struct tog_view *);
601 static const struct got_error *open_ref_view(struct tog_view *,
602 struct got_repository *);
603 static const struct got_error *show_ref_view(struct tog_view *);
604 static const struct got_error *input_ref_view(struct tog_view **,
605 struct tog_view *, int);
606 static const struct got_error *close_ref_view(struct tog_view *);
607 static const struct got_error *search_start_ref_view(struct tog_view *);
608 static const struct got_error *search_next_ref_view(struct tog_view *);
610 static volatile sig_atomic_t tog_sigwinch_received;
611 static volatile sig_atomic_t tog_sigpipe_received;
612 static volatile sig_atomic_t tog_sigcont_received;
613 static volatile sig_atomic_t tog_sigint_received;
614 static volatile sig_atomic_t tog_sigterm_received;
616 static void
617 tog_sigwinch(int signo)
619 tog_sigwinch_received = 1;
622 static void
623 tog_sigpipe(int signo)
625 tog_sigpipe_received = 1;
628 static void
629 tog_sigcont(int signo)
631 tog_sigcont_received = 1;
634 static void
635 tog_sigint(int signo)
637 tog_sigint_received = 1;
640 static void
641 tog_sigterm(int signo)
643 tog_sigterm_received = 1;
646 static int
647 tog_fatal_signal_received(void)
649 return (tog_sigpipe_received ||
650 tog_sigint_received || tog_sigint_received);
654 static const struct got_error *
655 view_close(struct tog_view *view)
657 const struct got_error *err = NULL;
659 if (view->child) {
660 view_close(view->child);
661 view->child = NULL;
663 if (view->close)
664 err = view->close(view);
665 if (view->panel)
666 del_panel(view->panel);
667 if (view->window)
668 delwin(view->window);
669 free(view);
670 return err;
673 static struct tog_view *
674 view_open(int nlines, int ncols, int begin_y, int begin_x,
675 enum tog_view_type type)
677 struct tog_view *view = calloc(1, sizeof(*view));
679 if (view == NULL)
680 return NULL;
682 view->type = type;
683 view->lines = LINES;
684 view->cols = COLS;
685 view->nlines = nlines ? nlines : LINES - begin_y;
686 view->ncols = ncols ? ncols : COLS - begin_x;
687 view->begin_y = begin_y;
688 view->begin_x = begin_x;
689 view->window = newwin(nlines, ncols, begin_y, begin_x);
690 if (view->window == NULL) {
691 view_close(view);
692 return NULL;
694 view->panel = new_panel(view->window);
695 if (view->panel == NULL ||
696 set_panel_userptr(view->panel, view) != OK) {
697 view_close(view);
698 return NULL;
701 keypad(view->window, TRUE);
702 return view;
705 static int
706 view_split_begin_x(int begin_x)
708 if (begin_x > 0 || COLS < 120)
709 return 0;
710 return (COLS - MAX(COLS / 2, 80));
713 /* XXX Stub till we decide what to do. */
714 static int
715 view_split_begin_y(int lines)
717 return lines * HSPLIT_SCALE;
720 static const struct got_error *view_resize(struct tog_view *);
722 static const struct got_error *
723 view_splitscreen(struct tog_view *view)
725 const struct got_error *err = NULL;
727 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
728 view->begin_y = view_split_begin_y(view->nlines);
729 view->begin_x = 0;
730 } else {
731 view->begin_x = view_split_begin_x(0);
732 view->begin_y = 0;
734 view->nlines = LINES - view->begin_y;
735 view->ncols = COLS - view->begin_x;
736 view->lines = LINES;
737 view->cols = COLS;
738 err = view_resize(view);
739 if (err)
740 return err;
742 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
743 view->parent->nlines = view->begin_y;
745 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
746 return got_error_from_errno("mvwin");
748 return NULL;
751 static const struct got_error *
752 view_fullscreen(struct tog_view *view)
754 const struct got_error *err = NULL;
756 view->begin_x = 0;
757 view->begin_y = 0;
758 view->nlines = LINES;
759 view->ncols = COLS;
760 view->lines = LINES;
761 view->cols = COLS;
762 err = view_resize(view);
763 if (err)
764 return err;
766 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
767 return got_error_from_errno("mvwin");
769 return NULL;
772 static int
773 view_is_parent_view(struct tog_view *view)
775 return view->parent == NULL;
778 static int
779 view_is_splitscreen(struct tog_view *view)
781 return view->begin_x > 0 || view->begin_y > 0;
784 static int
785 view_is_fullscreen(struct tog_view *view)
787 return view->nlines == LINES && view->ncols == COLS;
790 static void
791 view_border(struct tog_view *view)
793 PANEL *panel;
794 const struct tog_view *view_above;
796 if (view->parent)
797 return view_border(view->parent);
799 panel = panel_above(view->panel);
800 if (panel == NULL)
801 return;
803 view_above = panel_userptr(panel);
804 if (view->mode == TOG_VIEW_SPLIT_HRZN)
805 mvwhline(view->window, view_above->begin_y - 1,
806 view->begin_x, got_locale_is_utf8() ?
807 ACS_HLINE : '-', view->ncols);
808 else
809 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
810 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
813 static const struct got_error *request_log_commits(struct tog_view *);
814 static const struct got_error *offset_selection_down(struct tog_view *);
815 static void offset_selection_up(struct tog_view *);
817 static const struct got_error *
818 view_resize(struct tog_view *view)
820 const struct got_error *err = NULL;
821 int dif, nlines, ncols;
823 dif = LINES - view->lines; /* line difference */
825 if (view->lines > LINES)
826 nlines = view->nlines - (view->lines - LINES);
827 else
828 nlines = view->nlines + (LINES - view->lines);
829 if (view->cols > COLS)
830 ncols = view->ncols - (view->cols - COLS);
831 else
832 ncols = view->ncols + (COLS - view->cols);
834 if (view->child) {
835 int hs = view->child->begin_y;
837 if (!view_is_fullscreen(view))
838 view->child->begin_x = view_split_begin_x(view->begin_x);
839 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
840 view->child->begin_x == 0) {
841 ncols = COLS;
843 view_fullscreen(view->child);
844 if (view->child->focussed)
845 show_panel(view->child->panel);
846 else
847 show_panel(view->panel);
848 } else {
849 ncols = view->child->begin_x;
851 view_splitscreen(view->child);
852 show_panel(view->child->panel);
854 /*
855 * Request commits if terminal height was increased in a log
856 * view so we have enough commits loaded to populate the view.
857 */
858 if (view->type == TOG_VIEW_LOG && dif > 0) {
859 struct tog_log_view_state *ts = &view->state.log;
861 if (ts->commits.ncommits < ts->selected_entry->idx +
862 view->lines - ts->selected) {
863 view->nscrolled = ts->selected_entry->idx +
864 view->lines - ts->selected -
865 ts->commits.ncommits + dif;
866 err = request_log_commits(view);
867 if (err)
868 return err;
872 /*
873 * XXX This is ugly and needs to be moved into the above
874 * logic but "works" for now and my attempts at moving it
875 * break either 'tab' or 'F' key maps in horizontal splits.
876 */
877 if (hs) {
878 err = view_splitscreen(view->child);
879 if (err)
880 return err;
881 if (dif < 0) { /* top split decreased */
882 err = offset_selection_down(view);
883 if (err)
884 return err;
886 view_border(view);
887 update_panels();
888 doupdate();
889 show_panel(view->child->panel);
890 nlines = view->nlines;
892 } else if (view->parent == NULL)
893 ncols = COLS;
895 if (wresize(view->window, nlines, ncols) == ERR)
896 return got_error_from_errno("wresize");
897 if (replace_panel(view->panel, view->window) == ERR)
898 return got_error_from_errno("replace_panel");
899 wclear(view->window);
901 view->nlines = nlines;
902 view->ncols = ncols;
903 view->lines = LINES;
904 view->cols = COLS;
906 return NULL;
909 static const struct got_error *
910 view_close_child(struct tog_view *view)
912 const struct got_error *err = NULL;
914 if (view->child == NULL)
915 return NULL;
917 err = view_close(view->child);
918 view->child = NULL;
919 return err;
922 static const struct got_error *
923 view_set_child(struct tog_view *view, struct tog_view *child)
925 view->child = child;
926 child->parent = view;
928 return view_resize(view);
931 static void
932 tog_resizeterm(void)
934 int cols, lines;
935 struct winsize size;
937 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
938 cols = 80; /* Default */
939 lines = 24;
940 } else {
941 cols = size.ws_col;
942 lines = size.ws_row;
944 resize_term(lines, cols);
947 static const struct got_error *
948 view_search_start(struct tog_view *view)
950 const struct got_error *err = NULL;
951 struct tog_view *v = view;
952 char pattern[1024];
953 int ret;
955 if (view->search_started) {
956 regfree(&view->regex);
957 view->searching = 0;
958 memset(&view->regmatch, 0, sizeof(view->regmatch));
960 view->search_started = 0;
962 if (view->nlines < 1)
963 return NULL;
965 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
966 view_is_splitscreen(view->child))
967 v = view->child;
969 mvwaddstr(v->window, v->nlines - 1, 0, "/");
970 wclrtoeol(v->window);
972 nocbreak();
973 echo();
974 ret = wgetnstr(v->window, pattern, sizeof(pattern));
975 wrefresh(v->window);
976 cbreak();
977 noecho();
978 if (ret == ERR)
979 return NULL;
981 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
982 err = view->search_start(view);
983 if (err) {
984 regfree(&view->regex);
985 return err;
987 view->search_started = 1;
988 view->searching = TOG_SEARCH_FORWARD;
989 view->search_next_done = 0;
990 view->search_next(view);
993 return NULL;
996 /*
997 * Compute view->count from numeric user input. User has five-tenths of a
998 * second to follow each numeric keypress with another number to form count.
999 * Return first non-numeric input or ERR and assign total to view->count.
1000 * XXX Should we add support for user-defined timeout?
1002 static int
1003 get_compound_key(struct tog_view *view, int c)
1005 struct tog_view *v = view;
1006 int x, n = 0;
1008 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
1009 view_is_splitscreen(view->child))
1010 v = view->child;
1011 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1012 v = view->parent;
1014 view->count = 0;
1015 halfdelay(5); /* block for half a second */
1016 wattron(v->window, A_BOLD);
1017 wmove(v->window, v->nlines - 1, 0);
1018 wclrtoeol(v->window);
1019 waddch(v->window, ':');
1021 do {
1022 x = getcurx(v->window);
1023 if (x != ERR && x < view->ncols) {
1024 waddch(v->window, c);
1025 wrefresh(v->window);
1029 * Don't overflow. Max valid request should be the greatest
1030 * between the longest and total lines; cap at 10 million.
1032 if (n >= 9999999)
1033 n = 9999999;
1034 else
1035 n = n * 10 + (c - '0');
1036 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1038 /* Massage excessive or inapplicable values at the input handler. */
1039 view->count = n;
1041 wattroff(v->window, A_BOLD);
1042 cbreak(); /* return to blocking */
1043 return c;
1046 static const struct got_error *
1047 view_input(struct tog_view **new, int *done, struct tog_view *view,
1048 struct tog_view_list_head *views)
1050 const struct got_error *err = NULL;
1051 struct tog_view *v;
1052 int ch, errcode;
1054 *new = NULL;
1056 /* Clear "no matches" indicator. */
1057 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1058 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1059 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1060 view->count = 0;
1063 if (view->searching && !view->search_next_done) {
1064 errcode = pthread_mutex_unlock(&tog_mutex);
1065 if (errcode)
1066 return got_error_set_errno(errcode,
1067 "pthread_mutex_unlock");
1068 sched_yield();
1069 errcode = pthread_mutex_lock(&tog_mutex);
1070 if (errcode)
1071 return got_error_set_errno(errcode,
1072 "pthread_mutex_lock");
1073 view->search_next(view);
1074 return NULL;
1077 nodelay(stdscr, FALSE);
1078 /* Allow threads to make progress while we are waiting for input. */
1079 errcode = pthread_mutex_unlock(&tog_mutex);
1080 if (errcode)
1081 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1082 /* If we have an unfinished count, don't get a new key map. */
1083 ch = view->ch;
1084 if ((view->count && --view->count == 0) || !view->count) {
1085 ch = wgetch(view->window);
1086 if (ch >= '1' && ch <= '9')
1087 view->ch = ch = get_compound_key(view, ch);
1089 errcode = pthread_mutex_lock(&tog_mutex);
1090 if (errcode)
1091 return got_error_set_errno(errcode, "pthread_mutex_lock");
1092 nodelay(stdscr, TRUE);
1094 if (tog_sigwinch_received || tog_sigcont_received) {
1095 tog_resizeterm();
1096 tog_sigwinch_received = 0;
1097 tog_sigcont_received = 0;
1098 TAILQ_FOREACH(v, views, entry) {
1099 err = view_resize(v);
1100 if (err)
1101 return err;
1102 err = v->input(new, v, KEY_RESIZE);
1103 if (err)
1104 return err;
1105 if (v->child) {
1106 err = view_resize(v->child);
1107 if (err)
1108 return err;
1109 err = v->child->input(new, v->child,
1110 KEY_RESIZE);
1111 if (err)
1112 return err;
1117 switch (ch) {
1118 case '\t':
1119 view->count = 0;
1120 if (view->child) {
1121 view->focussed = 0;
1122 view->child->focussed = 1;
1123 view->focus_child = 1;
1124 } else if (view->parent) {
1125 view->focussed = 0;
1126 view->parent->focussed = 1;
1127 view->parent->focus_child = 0;
1128 if (!view_is_splitscreen(view)) {
1129 if (view->mode == TOG_VIEW_SPLIT_HRZN &&
1130 view->parent->type == TOG_VIEW_LOG) {
1131 err = request_log_commits(view->parent);
1132 if (err)
1133 return err;
1135 offset_selection_up(view->parent);
1136 err = view_fullscreen(view->parent);
1137 if (err)
1138 return err;
1141 break;
1142 case 'q':
1143 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1144 if (view->parent->type == TOG_VIEW_LOG) {
1145 /* might need more commits to fill fullscreen */
1146 err = request_log_commits(view->parent);
1147 if (err)
1148 break;
1150 offset_selection_up(view->parent);
1151 view->parent->mode = TOG_VIEW_SPLIT_NONE;
1153 err = view->input(new, view, ch);
1154 view->dying = 1;
1155 break;
1156 case 'Q':
1157 *done = 1;
1158 break;
1159 case 'F':
1160 view->count = 0;
1161 if (view_is_parent_view(view)) {
1162 if (view->child == NULL)
1163 break;
1164 if (view_is_splitscreen(view->child)) {
1165 view->focussed = 0;
1166 view->child->focussed = 1;
1167 err = view_fullscreen(view->child);
1168 } else
1169 err = view_splitscreen(view->child);
1170 if (err)
1171 break;
1172 err = view->child->input(new, view->child,
1173 KEY_RESIZE);
1174 } else {
1175 if (view_is_splitscreen(view)) {
1176 view->parent->focussed = 0;
1177 view->focussed = 1;
1178 err = view_fullscreen(view);
1179 } else {
1180 err = view_splitscreen(view);
1181 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1182 err = view_resize(view->parent);
1184 if (err)
1185 break;
1186 err = view->input(new, view, KEY_RESIZE);
1188 if (err)
1189 break;
1190 if (view->type == TOG_VIEW_LOG) {
1191 err = request_log_commits(view);
1192 if (err)
1193 break;
1195 if (view->parent)
1196 err = offset_selection_down(view->parent);
1197 if (!err)
1198 err = offset_selection_down(view);
1199 break;
1200 case KEY_RESIZE:
1201 break;
1202 case '/':
1203 view->count = 0;
1204 if (view->search_start)
1205 view_search_start(view);
1206 else
1207 err = view->input(new, view, ch);
1208 break;
1209 case 'N':
1210 case 'n':
1211 if (view->search_started && view->search_next) {
1212 view->searching = (ch == 'n' ?
1213 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1214 view->search_next_done = 0;
1215 view->search_next(view);
1216 } else
1217 err = view->input(new, view, ch);
1218 break;
1219 default:
1220 err = view->input(new, view, ch);
1221 break;
1224 return err;
1227 static int
1228 view_needs_focus_indication(struct tog_view *view)
1230 if (view_is_parent_view(view)) {
1231 if (view->child == NULL || view->child->focussed)
1232 return 0;
1233 if (!view_is_splitscreen(view->child))
1234 return 0;
1235 } else if (!view_is_splitscreen(view))
1236 return 0;
1238 return view->focussed;
1241 static const struct got_error *
1242 view_loop(struct tog_view *view)
1244 const struct got_error *err = NULL;
1245 struct tog_view_list_head views;
1246 struct tog_view *new_view;
1247 int fast_refresh = 10;
1248 int done = 0, errcode;
1250 errcode = pthread_mutex_lock(&tog_mutex);
1251 if (errcode)
1252 return got_error_set_errno(errcode, "pthread_mutex_lock");
1254 TAILQ_INIT(&views);
1255 TAILQ_INSERT_HEAD(&views, view, entry);
1257 view->focussed = 1;
1258 err = view->show(view);
1259 if (err)
1260 return err;
1261 update_panels();
1262 doupdate();
1263 while (!TAILQ_EMPTY(&views) && !done && !tog_fatal_signal_received()) {
1264 /* Refresh fast during initialization, then become slower. */
1265 if (fast_refresh && fast_refresh-- == 0)
1266 halfdelay(10); /* switch to once per second */
1268 err = view_input(&new_view, &done, view, &views);
1269 if (err)
1270 break;
1271 if (view->dying) {
1272 struct tog_view *v, *prev = NULL;
1274 if (view_is_parent_view(view))
1275 prev = TAILQ_PREV(view, tog_view_list_head,
1276 entry);
1277 else if (view->parent)
1278 prev = view->parent;
1280 if (view->parent) {
1281 view->parent->child = NULL;
1282 view->parent->focus_child = 0;
1283 /* Restore fullscreen line height. */
1284 view->parent->nlines = view->parent->lines;
1285 err = view_resize(view->parent);
1286 if (err)
1287 break;
1288 } else
1289 TAILQ_REMOVE(&views, view, entry);
1291 err = view_close(view);
1292 if (err)
1293 goto done;
1295 view = NULL;
1296 TAILQ_FOREACH(v, &views, entry) {
1297 if (v->focussed)
1298 break;
1300 if (view == NULL && new_view == NULL) {
1301 /* No view has focus. Try to pick one. */
1302 if (prev)
1303 view = prev;
1304 else if (!TAILQ_EMPTY(&views)) {
1305 view = TAILQ_LAST(&views,
1306 tog_view_list_head);
1308 if (view) {
1309 if (view->focus_child) {
1310 view->child->focussed = 1;
1311 view = view->child;
1312 } else
1313 view->focussed = 1;
1317 if (new_view) {
1318 struct tog_view *v, *t;
1319 /* Only allow one parent view per type. */
1320 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1321 if (v->type != new_view->type)
1322 continue;
1323 TAILQ_REMOVE(&views, v, entry);
1324 err = view_close(v);
1325 if (err)
1326 goto done;
1327 break;
1329 TAILQ_INSERT_TAIL(&views, new_view, entry);
1330 view = new_view;
1332 if (view) {
1333 if (view_is_parent_view(view)) {
1334 if (view->child && view->child->focussed)
1335 view = view->child;
1336 } else {
1337 if (view->parent && view->parent->focussed)
1338 view = view->parent;
1340 show_panel(view->panel);
1341 if (view->child && view_is_splitscreen(view->child))
1342 show_panel(view->child->panel);
1343 if (view->parent && view_is_splitscreen(view)) {
1344 err = view->parent->show(view->parent);
1345 if (err)
1346 goto done;
1348 err = view->show(view);
1349 if (err)
1350 goto done;
1351 if (view->child) {
1352 err = view->child->show(view->child);
1353 if (err)
1354 goto done;
1356 update_panels();
1357 doupdate();
1360 done:
1361 while (!TAILQ_EMPTY(&views)) {
1362 view = TAILQ_FIRST(&views);
1363 TAILQ_REMOVE(&views, view, entry);
1364 view_close(view);
1367 errcode = pthread_mutex_unlock(&tog_mutex);
1368 if (errcode && err == NULL)
1369 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1371 return err;
1374 __dead static void
1375 usage_log(void)
1377 endwin();
1378 fprintf(stderr,
1379 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1380 getprogname());
1381 exit(1);
1384 /* Create newly allocated wide-character string equivalent to a byte string. */
1385 static const struct got_error *
1386 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1388 char *vis = NULL;
1389 const struct got_error *err = NULL;
1391 *ws = NULL;
1392 *wlen = mbstowcs(NULL, s, 0);
1393 if (*wlen == (size_t)-1) {
1394 int vislen;
1395 if (errno != EILSEQ)
1396 return got_error_from_errno("mbstowcs");
1398 /* byte string invalid in current encoding; try to "fix" it */
1399 err = got_mbsavis(&vis, &vislen, s);
1400 if (err)
1401 return err;
1402 *wlen = mbstowcs(NULL, vis, 0);
1403 if (*wlen == (size_t)-1) {
1404 err = got_error_from_errno("mbstowcs"); /* give up */
1405 goto done;
1409 *ws = calloc(*wlen + 1, sizeof(**ws));
1410 if (*ws == NULL) {
1411 err = got_error_from_errno("calloc");
1412 goto done;
1415 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1416 err = got_error_from_errno("mbstowcs");
1417 done:
1418 free(vis);
1419 if (err) {
1420 free(*ws);
1421 *ws = NULL;
1422 *wlen = 0;
1424 return err;
1427 static const struct got_error *
1428 expand_tab(char **ptr, const char *src)
1430 char *dst;
1431 size_t len, n, idx = 0, sz = 0;
1433 *ptr = NULL;
1434 n = len = strlen(src);
1435 dst = malloc(n + 1);
1436 if (dst == NULL)
1437 return got_error_from_errno("malloc");
1439 while (idx < len && src[idx]) {
1440 const char c = src[idx];
1442 if (c == '\t') {
1443 size_t nb = TABSIZE - sz % TABSIZE;
1444 char *p;
1446 p = realloc(dst, n + nb);
1447 if (p == NULL) {
1448 free(dst);
1449 return got_error_from_errno("realloc");
1452 dst = p;
1453 n += nb;
1454 memset(dst + sz, ' ', nb);
1455 sz += nb;
1456 } else
1457 dst[sz++] = src[idx];
1458 ++idx;
1461 dst[sz] = '\0';
1462 *ptr = dst;
1463 return NULL;
1467 * Advance at most n columns from wline starting at offset off.
1468 * Return the index to the first character after the span operation.
1469 * Return the combined column width of all spanned wide character in
1470 * *rcol.
1472 static int
1473 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1475 int width, i, cols = 0;
1477 if (n == 0) {
1478 *rcol = cols;
1479 return off;
1482 for (i = off; wline[i] != L'\0'; ++i) {
1483 if (wline[i] == L'\t')
1484 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1485 else
1486 width = wcwidth(wline[i]);
1488 if (width == -1) {
1489 width = 1;
1490 wline[i] = L'.';
1493 if (cols + width > n)
1494 break;
1495 cols += width;
1498 *rcol = cols;
1499 return i;
1503 * Format a line for display, ensuring that it won't overflow a width limit.
1504 * With scrolling, the width returned refers to the scrolled version of the
1505 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1507 static const struct got_error *
1508 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1509 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1511 const struct got_error *err = NULL;
1512 int cols;
1513 wchar_t *wline = NULL;
1514 char *exstr = NULL;
1515 size_t wlen;
1516 int i, scrollx;
1518 *wlinep = NULL;
1519 *widthp = 0;
1521 if (expand) {
1522 err = expand_tab(&exstr, line);
1523 if (err)
1524 return err;
1527 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1528 free(exstr);
1529 if (err)
1530 return err;
1532 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1534 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1535 wline[wlen - 1] = L'\0';
1536 wlen--;
1538 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1539 wline[wlen - 1] = L'\0';
1540 wlen--;
1543 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1544 wline[i] = L'\0';
1546 if (widthp)
1547 *widthp = cols;
1548 if (scrollxp)
1549 *scrollxp = scrollx;
1550 if (err)
1551 free(wline);
1552 else
1553 *wlinep = wline;
1554 return err;
1557 static const struct got_error*
1558 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1559 struct got_object_id *id, struct got_repository *repo)
1561 static const struct got_error *err = NULL;
1562 struct got_reflist_entry *re;
1563 char *s;
1564 const char *name;
1566 *refs_str = NULL;
1568 TAILQ_FOREACH(re, refs, entry) {
1569 struct got_tag_object *tag = NULL;
1570 struct got_object_id *ref_id;
1571 int cmp;
1573 name = got_ref_get_name(re->ref);
1574 if (strcmp(name, GOT_REF_HEAD) == 0)
1575 continue;
1576 if (strncmp(name, "refs/", 5) == 0)
1577 name += 5;
1578 if (strncmp(name, "got/", 4) == 0 &&
1579 strncmp(name, "got/backup/", 11) != 0)
1580 continue;
1581 if (strncmp(name, "heads/", 6) == 0)
1582 name += 6;
1583 if (strncmp(name, "remotes/", 8) == 0) {
1584 name += 8;
1585 s = strstr(name, "/" GOT_REF_HEAD);
1586 if (s != NULL && s[strlen(s)] == '\0')
1587 continue;
1589 err = got_ref_resolve(&ref_id, repo, re->ref);
1590 if (err)
1591 break;
1592 if (strncmp(name, "tags/", 5) == 0) {
1593 err = got_object_open_as_tag(&tag, repo, ref_id);
1594 if (err) {
1595 if (err->code != GOT_ERR_OBJ_TYPE) {
1596 free(ref_id);
1597 break;
1599 /* Ref points at something other than a tag. */
1600 err = NULL;
1601 tag = NULL;
1604 cmp = got_object_id_cmp(tag ?
1605 got_object_tag_get_object_id(tag) : ref_id, id);
1606 free(ref_id);
1607 if (tag)
1608 got_object_tag_close(tag);
1609 if (cmp != 0)
1610 continue;
1611 s = *refs_str;
1612 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1613 s ? ", " : "", name) == -1) {
1614 err = got_error_from_errno("asprintf");
1615 free(s);
1616 *refs_str = NULL;
1617 break;
1619 free(s);
1622 return err;
1625 static const struct got_error *
1626 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1627 int col_tab_align)
1629 char *smallerthan;
1631 smallerthan = strchr(author, '<');
1632 if (smallerthan && smallerthan[1] != '\0')
1633 author = smallerthan + 1;
1634 author[strcspn(author, "@>")] = '\0';
1635 return format_line(wauthor, author_width, NULL, author, 0, limit,
1636 col_tab_align, 0);
1639 static const struct got_error *
1640 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1641 struct got_object_id *id, const size_t date_display_cols,
1642 int author_display_cols)
1644 struct tog_log_view_state *s = &view->state.log;
1645 const struct got_error *err = NULL;
1646 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1647 char *logmsg0 = NULL, *logmsg = NULL;
1648 char *author = NULL;
1649 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1650 int author_width, logmsg_width;
1651 char *newline, *line = NULL;
1652 int col, limit, scrollx;
1653 const int avail = view->ncols;
1654 struct tm tm;
1655 time_t committer_time;
1656 struct tog_color *tc;
1658 committer_time = got_object_commit_get_committer_time(commit);
1659 if (gmtime_r(&committer_time, &tm) == NULL)
1660 return got_error_from_errno("gmtime_r");
1661 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1662 return got_error(GOT_ERR_NO_SPACE);
1664 if (avail <= date_display_cols)
1665 limit = MIN(sizeof(datebuf) - 1, avail);
1666 else
1667 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1668 tc = get_color(&s->colors, TOG_COLOR_DATE);
1669 if (tc)
1670 wattr_on(view->window,
1671 COLOR_PAIR(tc->colorpair), NULL);
1672 waddnstr(view->window, datebuf, limit);
1673 if (tc)
1674 wattr_off(view->window,
1675 COLOR_PAIR(tc->colorpair), NULL);
1676 col = limit;
1677 if (col > avail)
1678 goto done;
1680 if (avail >= 120) {
1681 char *id_str;
1682 err = got_object_id_str(&id_str, id);
1683 if (err)
1684 goto done;
1685 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1686 if (tc)
1687 wattr_on(view->window,
1688 COLOR_PAIR(tc->colorpair), NULL);
1689 wprintw(view->window, "%.8s ", id_str);
1690 if (tc)
1691 wattr_off(view->window,
1692 COLOR_PAIR(tc->colorpair), NULL);
1693 free(id_str);
1694 col += 9;
1695 if (col > avail)
1696 goto done;
1699 author = strdup(got_object_commit_get_author(commit));
1700 if (author == NULL) {
1701 err = got_error_from_errno("strdup");
1702 goto done;
1704 err = format_author(&wauthor, &author_width, author, avail - col, col);
1705 if (err)
1706 goto done;
1707 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1708 if (tc)
1709 wattr_on(view->window,
1710 COLOR_PAIR(tc->colorpair), NULL);
1711 waddwstr(view->window, wauthor);
1712 if (tc)
1713 wattr_off(view->window,
1714 COLOR_PAIR(tc->colorpair), NULL);
1715 col += author_width;
1716 while (col < avail && author_width < author_display_cols + 2) {
1717 waddch(view->window, ' ');
1718 col++;
1719 author_width++;
1721 if (col > avail)
1722 goto done;
1724 err = got_object_commit_get_logmsg(&logmsg0, commit);
1725 if (err)
1726 goto done;
1727 logmsg = logmsg0;
1728 while (*logmsg == '\n')
1729 logmsg++;
1730 newline = strchr(logmsg, '\n');
1731 if (newline)
1732 *newline = '\0';
1733 limit = avail - col;
1734 if (view->child && view_is_splitscreen(view->child) && limit > 0)
1735 limit--; /* for the border */
1736 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
1737 limit, col, 1);
1738 if (err)
1739 goto done;
1740 waddwstr(view->window, &wlogmsg[scrollx]);
1741 col += MAX(logmsg_width, 0);
1742 while (col < avail) {
1743 waddch(view->window, ' ');
1744 col++;
1746 done:
1747 free(logmsg0);
1748 free(wlogmsg);
1749 free(author);
1750 free(wauthor);
1751 free(line);
1752 return err;
1755 static struct commit_queue_entry *
1756 alloc_commit_queue_entry(struct got_commit_object *commit,
1757 struct got_object_id *id)
1759 struct commit_queue_entry *entry;
1761 entry = calloc(1, sizeof(*entry));
1762 if (entry == NULL)
1763 return NULL;
1765 entry->id = id;
1766 entry->commit = commit;
1767 return entry;
1770 static void
1771 pop_commit(struct commit_queue *commits)
1773 struct commit_queue_entry *entry;
1775 entry = TAILQ_FIRST(&commits->head);
1776 TAILQ_REMOVE(&commits->head, entry, entry);
1777 got_object_commit_close(entry->commit);
1778 commits->ncommits--;
1779 /* Don't free entry->id! It is owned by the commit graph. */
1780 free(entry);
1783 static void
1784 free_commits(struct commit_queue *commits)
1786 while (!TAILQ_EMPTY(&commits->head))
1787 pop_commit(commits);
1790 static const struct got_error *
1791 match_commit(int *have_match, struct got_object_id *id,
1792 struct got_commit_object *commit, regex_t *regex)
1794 const struct got_error *err = NULL;
1795 regmatch_t regmatch;
1796 char *id_str = NULL, *logmsg = NULL;
1798 *have_match = 0;
1800 err = got_object_id_str(&id_str, id);
1801 if (err)
1802 return err;
1804 err = got_object_commit_get_logmsg(&logmsg, commit);
1805 if (err)
1806 goto done;
1808 if (regexec(regex, got_object_commit_get_author(commit), 1,
1809 &regmatch, 0) == 0 ||
1810 regexec(regex, got_object_commit_get_committer(commit), 1,
1811 &regmatch, 0) == 0 ||
1812 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
1813 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
1814 *have_match = 1;
1815 done:
1816 free(id_str);
1817 free(logmsg);
1818 return err;
1821 static const struct got_error *
1822 queue_commits(struct tog_log_thread_args *a)
1824 const struct got_error *err = NULL;
1827 * We keep all commits open throughout the lifetime of the log
1828 * view in order to avoid having to re-fetch commits from disk
1829 * while updating the display.
1831 do {
1832 struct got_object_id *id;
1833 struct got_commit_object *commit;
1834 struct commit_queue_entry *entry;
1835 int errcode;
1837 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
1838 NULL, NULL);
1839 if (err || id == NULL)
1840 break;
1842 err = got_object_open_as_commit(&commit, a->repo, id);
1843 if (err)
1844 break;
1845 entry = alloc_commit_queue_entry(commit, id);
1846 if (entry == NULL) {
1847 err = got_error_from_errno("alloc_commit_queue_entry");
1848 break;
1851 errcode = pthread_mutex_lock(&tog_mutex);
1852 if (errcode) {
1853 err = got_error_set_errno(errcode,
1854 "pthread_mutex_lock");
1855 break;
1858 entry->idx = a->commits->ncommits;
1859 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
1860 a->commits->ncommits++;
1862 if (*a->searching == TOG_SEARCH_FORWARD &&
1863 !*a->search_next_done) {
1864 int have_match;
1865 err = match_commit(&have_match, id, commit, a->regex);
1866 if (err)
1867 break;
1868 if (have_match)
1869 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
1872 errcode = pthread_mutex_unlock(&tog_mutex);
1873 if (errcode && err == NULL)
1874 err = got_error_set_errno(errcode,
1875 "pthread_mutex_unlock");
1876 if (err)
1877 break;
1878 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
1880 return err;
1883 static void
1884 select_commit(struct tog_log_view_state *s)
1886 struct commit_queue_entry *entry;
1887 int ncommits = 0;
1889 entry = s->first_displayed_entry;
1890 while (entry) {
1891 if (ncommits == s->selected) {
1892 s->selected_entry = entry;
1893 break;
1895 entry = TAILQ_NEXT(entry, entry);
1896 ncommits++;
1900 static const struct got_error *
1901 draw_commits(struct tog_view *view)
1903 const struct got_error *err = NULL;
1904 struct tog_log_view_state *s = &view->state.log;
1905 struct commit_queue_entry *entry = s->selected_entry;
1906 const int limit = view->nlines;
1907 int width;
1908 int ncommits, author_cols = 4;
1909 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
1910 char *refs_str = NULL;
1911 wchar_t *wline;
1912 struct tog_color *tc;
1913 static const size_t date_display_cols = 12;
1915 if (s->selected_entry &&
1916 !(view->searching && view->search_next_done == 0)) {
1917 struct got_reflist_head *refs;
1918 err = got_object_id_str(&id_str, s->selected_entry->id);
1919 if (err)
1920 return err;
1921 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
1922 s->selected_entry->id);
1923 if (refs) {
1924 err = build_refs_str(&refs_str, refs,
1925 s->selected_entry->id, s->repo);
1926 if (err)
1927 goto done;
1931 if (s->thread_args.commits_needed == 0)
1932 halfdelay(10); /* disable fast refresh */
1934 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
1935 if (asprintf(&ncommits_str, " [%d/%d] %s",
1936 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1937 (view->searching && !view->search_next_done) ?
1938 "searching..." : "loading...") == -1) {
1939 err = got_error_from_errno("asprintf");
1940 goto done;
1942 } else {
1943 const char *search_str = NULL;
1945 if (view->searching) {
1946 if (view->search_next_done == TOG_SEARCH_NO_MORE)
1947 search_str = "no more matches";
1948 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
1949 search_str = "no matches found";
1950 else if (!view->search_next_done)
1951 search_str = "searching...";
1954 if (asprintf(&ncommits_str, " [%d/%d] %s",
1955 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1956 search_str ? search_str :
1957 (refs_str ? refs_str : "")) == -1) {
1958 err = got_error_from_errno("asprintf");
1959 goto done;
1963 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
1964 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
1965 "........................................",
1966 s->in_repo_path, ncommits_str) == -1) {
1967 err = got_error_from_errno("asprintf");
1968 header = NULL;
1969 goto done;
1971 } else if (asprintf(&header, "commit %s%s",
1972 id_str ? id_str : "........................................",
1973 ncommits_str) == -1) {
1974 err = got_error_from_errno("asprintf");
1975 header = NULL;
1976 goto done;
1978 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
1979 if (err)
1980 goto done;
1982 werase(view->window);
1984 if (view_needs_focus_indication(view))
1985 wstandout(view->window);
1986 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1987 if (tc)
1988 wattr_on(view->window,
1989 COLOR_PAIR(tc->colorpair), NULL);
1990 waddwstr(view->window, wline);
1991 if (tc)
1992 wattr_off(view->window,
1993 COLOR_PAIR(tc->colorpair), NULL);
1994 while (width < view->ncols) {
1995 waddch(view->window, ' ');
1996 width++;
1998 if (view_needs_focus_indication(view))
1999 wstandend(view->window);
2000 free(wline);
2001 if (limit <= 1)
2002 goto done;
2004 /* Grow author column size if necessary, and set view->maxx. */
2005 entry = s->first_displayed_entry;
2006 ncommits = 0;
2007 view->maxx = 0;
2008 while (entry) {
2009 char *author, *eol, *msg, *msg0;
2010 wchar_t *wauthor, *wmsg;
2011 int width;
2012 if (ncommits >= limit - 1)
2013 break;
2014 author = strdup(got_object_commit_get_author(entry->commit));
2015 if (author == NULL) {
2016 err = got_error_from_errno("strdup");
2017 goto done;
2019 err = format_author(&wauthor, &width, author, COLS,
2020 date_display_cols);
2021 if (author_cols < width)
2022 author_cols = width;
2023 free(wauthor);
2024 free(author);
2025 err = got_object_commit_get_logmsg(&msg0, entry->commit);
2026 if (err)
2027 goto done;
2028 msg = msg0;
2029 while (*msg == '\n')
2030 ++msg;
2031 if ((eol = strchr(msg, '\n')))
2032 *eol = '\0';
2033 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2034 date_display_cols + author_cols, 0);
2035 if (err)
2036 goto done;
2037 view->maxx = MAX(view->maxx, width);
2038 free(msg0);
2039 free(wmsg);
2040 ncommits++;
2041 entry = TAILQ_NEXT(entry, entry);
2044 entry = s->first_displayed_entry;
2045 s->last_displayed_entry = s->first_displayed_entry;
2046 ncommits = 0;
2047 while (entry) {
2048 if (ncommits >= limit - 1)
2049 break;
2050 if (ncommits == s->selected)
2051 wstandout(view->window);
2052 err = draw_commit(view, entry->commit, entry->id,
2053 date_display_cols, author_cols);
2054 if (ncommits == s->selected)
2055 wstandend(view->window);
2056 if (err)
2057 goto done;
2058 ncommits++;
2059 s->last_displayed_entry = entry;
2060 entry = TAILQ_NEXT(entry, entry);
2063 view_border(view);
2064 done:
2065 free(id_str);
2066 free(refs_str);
2067 free(ncommits_str);
2068 free(header);
2069 return err;
2072 static void
2073 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2075 struct commit_queue_entry *entry;
2076 int nscrolled = 0;
2078 entry = TAILQ_FIRST(&s->commits.head);
2079 if (s->first_displayed_entry == entry)
2080 return;
2082 entry = s->first_displayed_entry;
2083 while (entry && nscrolled < maxscroll) {
2084 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2085 if (entry) {
2086 s->first_displayed_entry = entry;
2087 nscrolled++;
2092 static const struct got_error *
2093 trigger_log_thread(struct tog_view *view, int wait)
2095 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2096 int errcode;
2098 halfdelay(1); /* fast refresh while loading commits */
2100 while (ta->commits_needed > 0 || ta->load_all) {
2101 if (ta->log_complete)
2102 break;
2104 /* Wake the log thread. */
2105 errcode = pthread_cond_signal(&ta->need_commits);
2106 if (errcode)
2107 return got_error_set_errno(errcode,
2108 "pthread_cond_signal");
2111 * The mutex will be released while the view loop waits
2112 * in wgetch(), at which time the log thread will run.
2114 if (!wait)
2115 break;
2117 /* Display progress update in log view. */
2118 show_log_view(view);
2119 update_panels();
2120 doupdate();
2122 /* Wait right here while next commit is being loaded. */
2123 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2124 if (errcode)
2125 return got_error_set_errno(errcode,
2126 "pthread_cond_wait");
2128 /* Display progress update in log view. */
2129 show_log_view(view);
2130 update_panels();
2131 doupdate();
2134 return NULL;
2137 static const struct got_error *
2138 request_log_commits(struct tog_view *view)
2140 struct tog_log_view_state *state = &view->state.log;
2141 const struct got_error *err = NULL;
2143 state->thread_args.commits_needed = view->nscrolled;
2144 err = trigger_log_thread(view, 1);
2145 view->nscrolled = 0;
2147 return err;
2150 static const struct got_error *
2151 log_scroll_down(struct tog_view *view, int maxscroll)
2153 struct tog_log_view_state *s = &view->state.log;
2154 const struct got_error *err = NULL;
2155 struct commit_queue_entry *pentry;
2156 int nscrolled = 0, ncommits_needed;
2158 if (s->last_displayed_entry == NULL)
2159 return NULL;
2161 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2162 if (s->commits.ncommits < ncommits_needed &&
2163 !s->thread_args.log_complete) {
2165 * Ask the log thread for required amount of commits.
2167 s->thread_args.commits_needed += maxscroll;
2168 err = trigger_log_thread(view, 1);
2169 if (err)
2170 return err;
2173 do {
2174 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2175 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2176 break;
2178 s->last_displayed_entry = pentry ?
2179 pentry : s->last_displayed_entry;;
2181 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2182 if (pentry == NULL)
2183 break;
2184 s->first_displayed_entry = pentry;
2185 } while (++nscrolled < maxscroll);
2187 if (view->mode == TOG_VIEW_SPLIT_HRZN)
2188 view->nscrolled += nscrolled;
2189 else
2190 view->nscrolled = 0;
2192 return err;
2195 static const struct got_error *
2196 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2197 struct got_commit_object *commit, struct got_object_id *commit_id,
2198 struct tog_view *log_view, struct got_repository *repo)
2200 const struct got_error *err;
2201 struct got_object_qid *parent_id;
2202 struct tog_view *diff_view;
2204 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2205 if (diff_view == NULL)
2206 return got_error_from_errno("view_open");
2208 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2209 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2210 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2211 if (err == NULL)
2212 *new_view = diff_view;
2213 return err;
2216 static const struct got_error *
2217 tree_view_visit_subtree(struct tog_tree_view_state *s,
2218 struct got_tree_object *subtree)
2220 struct tog_parent_tree *parent;
2222 parent = calloc(1, sizeof(*parent));
2223 if (parent == NULL)
2224 return got_error_from_errno("calloc");
2226 parent->tree = s->tree;
2227 parent->first_displayed_entry = s->first_displayed_entry;
2228 parent->selected_entry = s->selected_entry;
2229 parent->selected = s->selected;
2230 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2231 s->tree = subtree;
2232 s->selected = 0;
2233 s->first_displayed_entry = NULL;
2234 return NULL;
2237 static const struct got_error *
2238 tree_view_walk_path(struct tog_tree_view_state *s,
2239 struct got_commit_object *commit, const char *path)
2241 const struct got_error *err = NULL;
2242 struct got_tree_object *tree = NULL;
2243 const char *p;
2244 char *slash, *subpath = NULL;
2246 /* Walk the path and open corresponding tree objects. */
2247 p = path;
2248 while (*p) {
2249 struct got_tree_entry *te;
2250 struct got_object_id *tree_id;
2251 char *te_name;
2253 while (p[0] == '/')
2254 p++;
2256 /* Ensure the correct subtree entry is selected. */
2257 slash = strchr(p, '/');
2258 if (slash == NULL)
2259 te_name = strdup(p);
2260 else
2261 te_name = strndup(p, slash - p);
2262 if (te_name == NULL) {
2263 err = got_error_from_errno("strndup");
2264 break;
2266 te = got_object_tree_find_entry(s->tree, te_name);
2267 if (te == NULL) {
2268 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2269 free(te_name);
2270 break;
2272 free(te_name);
2273 s->first_displayed_entry = s->selected_entry = te;
2275 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2276 break; /* jump to this file's entry */
2278 slash = strchr(p, '/');
2279 if (slash)
2280 subpath = strndup(path, slash - path);
2281 else
2282 subpath = strdup(path);
2283 if (subpath == NULL) {
2284 err = got_error_from_errno("strdup");
2285 break;
2288 err = got_object_id_by_path(&tree_id, s->repo, commit,
2289 subpath);
2290 if (err)
2291 break;
2293 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2294 free(tree_id);
2295 if (err)
2296 break;
2298 err = tree_view_visit_subtree(s, tree);
2299 if (err) {
2300 got_object_tree_close(tree);
2301 break;
2303 if (slash == NULL)
2304 break;
2305 free(subpath);
2306 subpath = NULL;
2307 p = slash;
2310 free(subpath);
2311 return err;
2314 static const struct got_error *
2315 browse_commit_tree(struct tog_view **new_view, int begin_x,
2316 struct commit_queue_entry *entry, const char *path,
2317 const char *head_ref_name, struct got_repository *repo)
2319 const struct got_error *err = NULL;
2320 struct tog_tree_view_state *s;
2321 struct tog_view *tree_view;
2323 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
2324 if (tree_view == NULL)
2325 return got_error_from_errno("view_open");
2327 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2328 if (err)
2329 return err;
2330 s = &tree_view->state.tree;
2332 *new_view = tree_view;
2334 if (got_path_is_root_dir(path))
2335 return NULL;
2337 return tree_view_walk_path(s, entry->commit, path);
2340 static const struct got_error *
2341 block_signals_used_by_main_thread(void)
2343 sigset_t sigset;
2344 int errcode;
2346 if (sigemptyset(&sigset) == -1)
2347 return got_error_from_errno("sigemptyset");
2349 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2350 if (sigaddset(&sigset, SIGWINCH) == -1)
2351 return got_error_from_errno("sigaddset");
2352 if (sigaddset(&sigset, SIGCONT) == -1)
2353 return got_error_from_errno("sigaddset");
2354 if (sigaddset(&sigset, SIGINT) == -1)
2355 return got_error_from_errno("sigaddset");
2356 if (sigaddset(&sigset, SIGTERM) == -1)
2357 return got_error_from_errno("sigaddset");
2359 /* ncurses handles SIGTSTP */
2360 if (sigaddset(&sigset, SIGTSTP) == -1)
2361 return got_error_from_errno("sigaddset");
2363 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2364 if (errcode)
2365 return got_error_set_errno(errcode, "pthread_sigmask");
2367 return NULL;
2370 static void *
2371 log_thread(void *arg)
2373 const struct got_error *err = NULL;
2374 int errcode = 0;
2375 struct tog_log_thread_args *a = arg;
2376 int done = 0;
2378 err = block_signals_used_by_main_thread();
2379 if (err)
2380 return (void *)err;
2382 while (!done && !err && !tog_fatal_signal_received()) {
2383 err = queue_commits(a);
2384 if (err) {
2385 if (err->code != GOT_ERR_ITER_COMPLETED)
2386 return (void *)err;
2387 err = NULL;
2388 done = 1;
2389 } else if (a->commits_needed > 0 && !a->load_all)
2390 a->commits_needed--;
2392 errcode = pthread_mutex_lock(&tog_mutex);
2393 if (errcode) {
2394 err = got_error_set_errno(errcode,
2395 "pthread_mutex_lock");
2396 break;
2397 } else if (*a->quit)
2398 done = 1;
2399 else if (*a->first_displayed_entry == NULL) {
2400 *a->first_displayed_entry =
2401 TAILQ_FIRST(&a->commits->head);
2402 *a->selected_entry = *a->first_displayed_entry;
2405 errcode = pthread_cond_signal(&a->commit_loaded);
2406 if (errcode) {
2407 err = got_error_set_errno(errcode,
2408 "pthread_cond_signal");
2409 pthread_mutex_unlock(&tog_mutex);
2410 break;
2413 if (done)
2414 a->commits_needed = 0;
2415 else {
2416 if (a->commits_needed == 0 && !a->load_all) {
2417 errcode = pthread_cond_wait(&a->need_commits,
2418 &tog_mutex);
2419 if (errcode)
2420 err = got_error_set_errno(errcode,
2421 "pthread_cond_wait");
2422 if (*a->quit)
2423 done = 1;
2427 errcode = pthread_mutex_unlock(&tog_mutex);
2428 if (errcode && err == NULL)
2429 err = got_error_set_errno(errcode,
2430 "pthread_mutex_unlock");
2432 a->log_complete = 1;
2433 return (void *)err;
2436 static const struct got_error *
2437 stop_log_thread(struct tog_log_view_state *s)
2439 const struct got_error *err = NULL;
2440 int errcode;
2442 if (s->thread) {
2443 s->quit = 1;
2444 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2445 if (errcode)
2446 return got_error_set_errno(errcode,
2447 "pthread_cond_signal");
2448 errcode = pthread_mutex_unlock(&tog_mutex);
2449 if (errcode)
2450 return got_error_set_errno(errcode,
2451 "pthread_mutex_unlock");
2452 errcode = pthread_join(s->thread, (void **)&err);
2453 if (errcode)
2454 return got_error_set_errno(errcode, "pthread_join");
2455 errcode = pthread_mutex_lock(&tog_mutex);
2456 if (errcode)
2457 return got_error_set_errno(errcode,
2458 "pthread_mutex_lock");
2459 s->thread = NULL;
2462 if (s->thread_args.repo) {
2463 err = got_repo_close(s->thread_args.repo);
2464 s->thread_args.repo = NULL;
2467 if (s->thread_args.pack_fds) {
2468 const struct got_error *pack_err =
2469 got_repo_pack_fds_close(s->thread_args.pack_fds);
2470 if (err == NULL)
2471 err = pack_err;
2472 s->thread_args.pack_fds = NULL;
2475 if (s->thread_args.graph) {
2476 got_commit_graph_close(s->thread_args.graph);
2477 s->thread_args.graph = NULL;
2480 return err;
2483 static const struct got_error *
2484 close_log_view(struct tog_view *view)
2486 const struct got_error *err = NULL;
2487 struct tog_log_view_state *s = &view->state.log;
2488 int errcode;
2490 err = stop_log_thread(s);
2492 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2493 if (errcode && err == NULL)
2494 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2496 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2497 if (errcode && err == NULL)
2498 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2500 free_commits(&s->commits);
2501 free(s->in_repo_path);
2502 s->in_repo_path = NULL;
2503 free(s->start_id);
2504 s->start_id = NULL;
2505 free(s->head_ref_name);
2506 s->head_ref_name = NULL;
2507 return err;
2510 static const struct got_error *
2511 search_start_log_view(struct tog_view *view)
2513 struct tog_log_view_state *s = &view->state.log;
2515 s->matched_entry = NULL;
2516 s->search_entry = NULL;
2517 return NULL;
2520 static const struct got_error *
2521 search_next_log_view(struct tog_view *view)
2523 const struct got_error *err = NULL;
2524 struct tog_log_view_state *s = &view->state.log;
2525 struct commit_queue_entry *entry;
2527 /* Display progress update in log view. */
2528 show_log_view(view);
2529 update_panels();
2530 doupdate();
2532 if (s->search_entry) {
2533 int errcode, ch;
2534 errcode = pthread_mutex_unlock(&tog_mutex);
2535 if (errcode)
2536 return got_error_set_errno(errcode,
2537 "pthread_mutex_unlock");
2538 ch = wgetch(view->window);
2539 errcode = pthread_mutex_lock(&tog_mutex);
2540 if (errcode)
2541 return got_error_set_errno(errcode,
2542 "pthread_mutex_lock");
2543 if (ch == KEY_BACKSPACE) {
2544 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2545 return NULL;
2547 if (view->searching == TOG_SEARCH_FORWARD)
2548 entry = TAILQ_NEXT(s->search_entry, entry);
2549 else
2550 entry = TAILQ_PREV(s->search_entry,
2551 commit_queue_head, entry);
2552 } else if (s->matched_entry) {
2553 int matched_idx = s->matched_entry->idx;
2554 int selected_idx = s->selected_entry->idx;
2557 * If the user has moved the cursor after we hit a match,
2558 * the position from where we should continue searching
2559 * might have changed.
2561 if (view->searching == TOG_SEARCH_FORWARD) {
2562 if (matched_idx > selected_idx)
2563 entry = TAILQ_NEXT(s->selected_entry, entry);
2564 else
2565 entry = TAILQ_NEXT(s->matched_entry, entry);
2566 } else {
2567 if (matched_idx < selected_idx)
2568 entry = TAILQ_PREV(s->selected_entry,
2569 commit_queue_head, entry);
2570 else
2571 entry = TAILQ_PREV(s->matched_entry,
2572 commit_queue_head, entry);
2574 } else {
2575 entry = s->selected_entry;
2578 while (1) {
2579 int have_match = 0;
2581 if (entry == NULL) {
2582 if (s->thread_args.log_complete ||
2583 view->searching == TOG_SEARCH_BACKWARD) {
2584 view->search_next_done =
2585 (s->matched_entry == NULL ?
2586 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2587 s->search_entry = NULL;
2588 return NULL;
2591 * Poke the log thread for more commits and return,
2592 * allowing the main loop to make progress. Search
2593 * will resume at s->search_entry once we come back.
2595 s->thread_args.commits_needed++;
2596 return trigger_log_thread(view, 0);
2599 err = match_commit(&have_match, entry->id, entry->commit,
2600 &view->regex);
2601 if (err)
2602 break;
2603 if (have_match) {
2604 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2605 s->matched_entry = entry;
2606 break;
2609 s->search_entry = entry;
2610 if (view->searching == TOG_SEARCH_FORWARD)
2611 entry = TAILQ_NEXT(entry, entry);
2612 else
2613 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2616 if (s->matched_entry) {
2617 int cur = s->selected_entry->idx;
2618 while (cur < s->matched_entry->idx) {
2619 err = input_log_view(NULL, view, KEY_DOWN);
2620 if (err)
2621 return err;
2622 cur++;
2624 while (cur > s->matched_entry->idx) {
2625 err = input_log_view(NULL, view, KEY_UP);
2626 if (err)
2627 return err;
2628 cur--;
2632 s->search_entry = NULL;
2634 return NULL;
2637 static const struct got_error *
2638 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2639 struct got_repository *repo, const char *head_ref_name,
2640 const char *in_repo_path, int log_branches)
2642 const struct got_error *err = NULL;
2643 struct tog_log_view_state *s = &view->state.log;
2644 struct got_repository *thread_repo = NULL;
2645 struct got_commit_graph *thread_graph = NULL;
2646 int errcode;
2648 if (in_repo_path != s->in_repo_path) {
2649 free(s->in_repo_path);
2650 s->in_repo_path = strdup(in_repo_path);
2651 if (s->in_repo_path == NULL)
2652 return got_error_from_errno("strdup");
2655 /* The commit queue only contains commits being displayed. */
2656 TAILQ_INIT(&s->commits.head);
2657 s->commits.ncommits = 0;
2659 s->repo = repo;
2660 if (head_ref_name) {
2661 s->head_ref_name = strdup(head_ref_name);
2662 if (s->head_ref_name == NULL) {
2663 err = got_error_from_errno("strdup");
2664 goto done;
2667 s->start_id = got_object_id_dup(start_id);
2668 if (s->start_id == NULL) {
2669 err = got_error_from_errno("got_object_id_dup");
2670 goto done;
2672 s->log_branches = log_branches;
2674 STAILQ_INIT(&s->colors);
2675 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2676 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2677 get_color_value("TOG_COLOR_COMMIT"));
2678 if (err)
2679 goto done;
2680 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2681 get_color_value("TOG_COLOR_AUTHOR"));
2682 if (err) {
2683 free_colors(&s->colors);
2684 goto done;
2686 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
2687 get_color_value("TOG_COLOR_DATE"));
2688 if (err) {
2689 free_colors(&s->colors);
2690 goto done;
2694 view->show = show_log_view;
2695 view->input = input_log_view;
2696 view->close = close_log_view;
2697 view->search_start = search_start_log_view;
2698 view->search_next = search_next_log_view;
2700 if (s->thread_args.pack_fds == NULL) {
2701 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2702 if (err)
2703 goto done;
2705 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
2706 s->thread_args.pack_fds);
2707 if (err)
2708 goto done;
2709 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
2710 !s->log_branches);
2711 if (err)
2712 goto done;
2713 err = got_commit_graph_iter_start(thread_graph, s->start_id,
2714 s->repo, NULL, NULL);
2715 if (err)
2716 goto done;
2718 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
2719 if (errcode) {
2720 err = got_error_set_errno(errcode, "pthread_cond_init");
2721 goto done;
2723 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
2724 if (errcode) {
2725 err = got_error_set_errno(errcode, "pthread_cond_init");
2726 goto done;
2729 s->thread_args.commits_needed = view->nlines;
2730 s->thread_args.graph = thread_graph;
2731 s->thread_args.commits = &s->commits;
2732 s->thread_args.in_repo_path = s->in_repo_path;
2733 s->thread_args.start_id = s->start_id;
2734 s->thread_args.repo = thread_repo;
2735 s->thread_args.log_complete = 0;
2736 s->thread_args.quit = &s->quit;
2737 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
2738 s->thread_args.selected_entry = &s->selected_entry;
2739 s->thread_args.searching = &view->searching;
2740 s->thread_args.search_next_done = &view->search_next_done;
2741 s->thread_args.regex = &view->regex;
2742 done:
2743 if (err)
2744 close_log_view(view);
2745 return err;
2748 static const struct got_error *
2749 show_log_view(struct tog_view *view)
2751 const struct got_error *err;
2752 struct tog_log_view_state *s = &view->state.log;
2754 if (s->thread == NULL) {
2755 int errcode = pthread_create(&s->thread, NULL, log_thread,
2756 &s->thread_args);
2757 if (errcode)
2758 return got_error_set_errno(errcode, "pthread_create");
2759 if (s->thread_args.commits_needed > 0) {
2760 err = trigger_log_thread(view, 1);
2761 if (err)
2762 return err;
2766 return draw_commits(view);
2769 static void
2770 log_move_cursor_up(struct tog_view *view, int page, int home)
2772 struct tog_log_view_state *s = &view->state.log;
2774 if (s->selected_entry->idx == 0)
2775 view->count = 0;
2776 if (s->first_displayed_entry == NULL)
2777 return;
2779 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
2780 || home)
2781 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
2783 if (!page && !home && s->selected > 0)
2784 --s->selected;
2785 else
2786 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
2788 select_commit(s);
2789 return;
2792 static const struct got_error *
2793 log_move_cursor_down(struct tog_view *view, int page)
2795 struct tog_log_view_state *s = &view->state.log;
2796 struct commit_queue_entry *first;
2797 const struct got_error *err = NULL;
2799 first = s->first_displayed_entry;
2800 if (first == NULL) {
2801 view->count = 0;
2802 return NULL;
2805 if (s->thread_args.log_complete &&
2806 s->selected_entry->idx >= s->commits.ncommits - 1)
2807 return NULL;
2809 if (!page) {
2810 int eos = view->nlines - 2;
2812 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
2813 view_is_splitscreen(view->child))
2814 --eos; /* border consumes the last line */
2815 if (s->selected < MIN(eos, s->commits.ncommits - 1))
2816 ++s->selected;
2817 else
2818 err = log_scroll_down(view, 1);
2819 } else if (s->thread_args.log_complete) {
2820 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
2821 s->selected += MIN(s->last_displayed_entry->idx -
2822 s->selected_entry->idx, page + 1);
2823 else
2824 err = log_scroll_down(view, MIN(page,
2825 s->commits.ncommits - s->selected_entry->idx - 1));
2826 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
2827 } else {
2828 err = log_scroll_down(view, page);
2829 if (err)
2830 return err;
2831 if (first == s->first_displayed_entry && s->selected <
2832 MIN(view->nlines - 2, s->commits.ncommits - 1)) {
2833 s->selected = MIN(s->commits.ncommits - 1, page);
2836 if (err)
2837 return err;
2840 * We might necessarily overshoot in horizontal
2841 * splits; if so, select the last displayed commit.
2843 s->selected = MIN(s->selected,
2844 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
2846 select_commit(s);
2848 if (s->thread_args.log_complete &&
2849 s->selected_entry->idx == s->commits.ncommits - 1)
2850 view->count = 0;
2852 return NULL;
2856 * Get splitscreen dimensions based on TOG_VIEW_SPLIT_MODE:
2857 * TOG_VIEW_SPLIT_VERT vertical split if COLS > 119 (default)
2858 * TOG_VIEW_SPLIT_HRZN horizontal split
2859 * Assign start column and line of the new split to *x and *y, respectively,
2860 * and assign view mode to view->mode.
2862 static void
2863 view_get_split(struct tog_view *view, int *y, int *x)
2865 char *mode;
2867 mode = getenv("TOG_VIEW_SPLIT_MODE");
2869 if (!mode || mode[0] != 'h') {
2870 view->mode = TOG_VIEW_SPLIT_VERT;
2871 *x = view_split_begin_x(view->begin_x);
2872 } else if (mode && mode[0] == 'h') {
2873 view->mode = TOG_VIEW_SPLIT_HRZN;
2874 *y = view_split_begin_y(view->lines);
2878 /* Split view horizontally at y and offset view->state->selected line. */
2879 static const struct got_error *
2880 view_init_hsplit(struct tog_view *view, int y)
2882 const struct got_error *err = NULL;
2884 view->nlines = y;
2885 err = view_resize(view);
2886 if (err)
2887 return err;
2889 err = offset_selection_down(view);
2891 return err;
2894 static const struct got_error *
2895 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
2897 const struct got_error *err = NULL;
2898 struct tog_log_view_state *s = &view->state.log;
2899 struct tog_view *diff_view = NULL, *tree_view = NULL;
2900 struct tog_view *ref_view = NULL;
2901 struct commit_queue_entry *entry;
2902 int begin_x = 0, begin_y = 0, n, nscroll = view->nlines - 1;
2904 if (s->thread_args.load_all) {
2905 if (ch == KEY_BACKSPACE)
2906 s->thread_args.load_all = 0;
2907 else if (s->thread_args.log_complete) {
2908 s->thread_args.load_all = 0;
2909 err = log_move_cursor_down(view, s->commits.ncommits);
2911 return err;
2914 switch (ch) {
2915 case 'q':
2916 s->quit = 1;
2917 break;
2918 case '0':
2919 view->x = 0;
2920 break;
2921 case '$':
2922 view->x = MAX(view->maxx - view->ncols / 2, 0);
2923 view->count = 0;
2924 break;
2925 case KEY_RIGHT:
2926 case 'l':
2927 if (view->x + view->ncols / 2 < view->maxx)
2928 view->x += 2; /* move two columns right */
2929 else
2930 view->count = 0;
2931 break;
2932 case KEY_LEFT:
2933 case 'h':
2934 view->x -= MIN(view->x, 2); /* move two columns back */
2935 if (view->x <= 0)
2936 view->count = 0;
2937 break;
2938 case 'k':
2939 case KEY_UP:
2940 case '<':
2941 case ',':
2942 case CTRL('p'):
2943 log_move_cursor_up(view, 0, 0);
2944 break;
2945 case 'g':
2946 case KEY_HOME:
2947 log_move_cursor_up(view, 0, 1);
2948 view->count = 0;
2949 break;
2950 case CTRL('u'):
2951 case 'u':
2952 nscroll /= 2;
2953 /* FALL THROUGH */
2954 case KEY_PPAGE:
2955 case CTRL('b'):
2956 case 'b':
2957 log_move_cursor_up(view, nscroll, 0);
2958 break;
2959 case 'j':
2960 case KEY_DOWN:
2961 case '>':
2962 case '.':
2963 case CTRL('n'):
2964 err = log_move_cursor_down(view, 0);
2965 break;
2966 case 'G':
2967 case KEY_END: {
2968 /* We don't know yet how many commits, so we're forced to
2969 * traverse them all. */
2970 view->count = 0;
2971 if (!s->thread_args.log_complete) {
2972 s->thread_args.load_all = 1;
2973 return trigger_log_thread(view, 0);
2976 s->selected = 0;
2977 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
2978 for (n = 0; n < view->nlines - 1; n++) {
2979 if (entry == NULL)
2980 break;
2981 s->first_displayed_entry = entry;
2982 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2984 if (n > 0)
2985 s->selected = n - 1;
2986 select_commit(s);
2987 break;
2989 case CTRL('d'):
2990 case 'd':
2991 nscroll /= 2;
2992 /* FALL THROUGH */
2993 case KEY_NPAGE:
2994 case CTRL('f'):
2995 case 'f':
2996 case ' ':
2997 err = log_move_cursor_down(view, nscroll);
2998 break;
2999 case KEY_RESIZE:
3000 if (s->selected > view->nlines - 2)
3001 s->selected = view->nlines - 2;
3002 if (s->selected > s->commits.ncommits - 1)
3003 s->selected = s->commits.ncommits - 1;
3004 select_commit(s);
3005 if (s->commits.ncommits < view->nlines - 1 &&
3006 !s->thread_args.log_complete) {
3007 s->thread_args.commits_needed += (view->nlines - 1) -
3008 s->commits.ncommits;
3009 err = trigger_log_thread(view, 1);
3011 break;
3012 case KEY_ENTER:
3013 case '\r': {
3014 view->count = 0;
3015 if (s->selected_entry == NULL)
3016 break;
3018 /* get dimensions--don't split till initialisation succeeds */
3019 if (view_is_parent_view(view))
3020 view_get_split(view, &begin_y, &begin_x);
3022 err = open_diff_view_for_commit(&diff_view, begin_y, begin_x,
3023 s->selected_entry->commit, s->selected_entry->id,
3024 view, s->repo);
3025 if (err)
3026 break;
3028 if (view->mode == TOG_VIEW_SPLIT_HRZN) { /* safe to split */
3029 err = view_init_hsplit(view, begin_y);
3030 if (err)
3031 break;
3034 view->focussed = 0;
3035 diff_view->focussed = 1;
3036 diff_view->mode = view->mode;
3037 diff_view->nlines = view->lines - begin_y;
3039 if (view_is_parent_view(view)) {
3040 err = view_close_child(view);
3041 if (err)
3042 return err;
3043 err = view_set_child(view, diff_view);
3044 if (err)
3045 return err;
3046 view->focus_child = 1;
3047 } else
3048 *new_view = diff_view;
3049 break;
3051 case 't':
3052 view->count = 0;
3053 if (s->selected_entry == NULL)
3054 break;
3055 if (view_is_parent_view(view))
3056 begin_x = view_split_begin_x(view->begin_x);
3057 err = browse_commit_tree(&tree_view, begin_x,
3058 s->selected_entry, s->in_repo_path, s->head_ref_name,
3059 s->repo);
3060 if (err)
3061 break;
3062 view->focussed = 0;
3063 tree_view->focussed = 1;
3064 if (view_is_parent_view(view)) {
3065 err = view_close_child(view);
3066 if (err)
3067 return err;
3068 err = view_set_child(view, tree_view);
3069 if (err)
3070 return err;
3071 view->focus_child = 1;
3072 } else
3073 *new_view = tree_view;
3074 break;
3075 case KEY_BACKSPACE:
3076 case CTRL('l'):
3077 case 'B':
3078 view->count = 0;
3079 if (ch == KEY_BACKSPACE &&
3080 got_path_is_root_dir(s->in_repo_path))
3081 break;
3082 err = stop_log_thread(s);
3083 if (err)
3084 return err;
3085 if (ch == KEY_BACKSPACE) {
3086 char *parent_path;
3087 err = got_path_dirname(&parent_path, s->in_repo_path);
3088 if (err)
3089 return err;
3090 free(s->in_repo_path);
3091 s->in_repo_path = parent_path;
3092 s->thread_args.in_repo_path = s->in_repo_path;
3093 } else if (ch == CTRL('l')) {
3094 struct got_object_id *start_id;
3095 err = got_repo_match_object_id(&start_id, NULL,
3096 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3097 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3098 if (err)
3099 return err;
3100 free(s->start_id);
3101 s->start_id = start_id;
3102 s->thread_args.start_id = s->start_id;
3103 } else /* 'B' */
3104 s->log_branches = !s->log_branches;
3106 if (s->thread_args.pack_fds == NULL) {
3107 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3108 if (err)
3109 return err;
3111 err = got_repo_open(&s->thread_args.repo,
3112 got_repo_get_path(s->repo), NULL,
3113 s->thread_args.pack_fds);
3114 if (err)
3115 return err;
3116 tog_free_refs();
3117 err = tog_load_refs(s->repo, 0);
3118 if (err)
3119 return err;
3120 err = got_commit_graph_open(&s->thread_args.graph,
3121 s->in_repo_path, !s->log_branches);
3122 if (err)
3123 return err;
3124 err = got_commit_graph_iter_start(s->thread_args.graph,
3125 s->start_id, s->repo, NULL, NULL);
3126 if (err)
3127 return err;
3128 free_commits(&s->commits);
3129 s->first_displayed_entry = NULL;
3130 s->last_displayed_entry = NULL;
3131 s->selected_entry = NULL;
3132 s->selected = 0;
3133 s->thread_args.log_complete = 0;
3134 s->quit = 0;
3135 s->thread_args.commits_needed = view->lines;
3136 s->matched_entry = NULL;
3137 s->search_entry = NULL;
3138 break;
3139 case 'r':
3140 view->count = 0;
3141 if (view_is_parent_view(view))
3142 begin_x = view_split_begin_x(view->begin_x);
3143 ref_view = view_open(view->nlines, view->ncols,
3144 view->begin_y, begin_x, TOG_VIEW_REF);
3145 if (ref_view == NULL)
3146 return got_error_from_errno("view_open");
3147 err = open_ref_view(ref_view, s->repo);
3148 if (err) {
3149 view_close(ref_view);
3150 return err;
3152 view->focussed = 0;
3153 ref_view->focussed = 1;
3154 if (view_is_parent_view(view)) {
3155 err = view_close_child(view);
3156 if (err)
3157 return err;
3158 err = view_set_child(view, ref_view);
3159 if (err)
3160 return err;
3161 view->focus_child = 1;
3162 } else
3163 *new_view = ref_view;
3164 break;
3165 default:
3166 view->count = 0;
3167 break;
3170 return err;
3173 static const struct got_error *
3174 apply_unveil(const char *repo_path, const char *worktree_path)
3176 const struct got_error *error;
3178 #ifdef PROFILE
3179 if (unveil("gmon.out", "rwc") != 0)
3180 return got_error_from_errno2("unveil", "gmon.out");
3181 #endif
3182 if (repo_path && unveil(repo_path, "r") != 0)
3183 return got_error_from_errno2("unveil", repo_path);
3185 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3186 return got_error_from_errno2("unveil", worktree_path);
3188 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3189 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3191 error = got_privsep_unveil_exec_helpers();
3192 if (error != NULL)
3193 return error;
3195 if (unveil(NULL, NULL) != 0)
3196 return got_error_from_errno("unveil");
3198 return NULL;
3201 static void
3202 init_curses(void)
3205 * Override default signal handlers before starting ncurses.
3206 * This should prevent ncurses from installing its own
3207 * broken cleanup() signal handler.
3209 signal(SIGWINCH, tog_sigwinch);
3210 signal(SIGPIPE, tog_sigpipe);
3211 signal(SIGCONT, tog_sigcont);
3212 signal(SIGINT, tog_sigint);
3213 signal(SIGTERM, tog_sigterm);
3215 initscr();
3216 cbreak();
3217 halfdelay(1); /* Do fast refresh while initial view is loading. */
3218 noecho();
3219 nonl();
3220 intrflush(stdscr, FALSE);
3221 keypad(stdscr, TRUE);
3222 curs_set(0);
3223 if (getenv("TOG_COLORS") != NULL) {
3224 start_color();
3225 use_default_colors();
3229 static const struct got_error *
3230 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3231 struct got_repository *repo, struct got_worktree *worktree)
3233 const struct got_error *err = NULL;
3235 if (argc == 0) {
3236 *in_repo_path = strdup("/");
3237 if (*in_repo_path == NULL)
3238 return got_error_from_errno("strdup");
3239 return NULL;
3242 if (worktree) {
3243 const char *prefix = got_worktree_get_path_prefix(worktree);
3244 char *p;
3246 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3247 if (err)
3248 return err;
3249 if (asprintf(in_repo_path, "%s%s%s", prefix,
3250 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3251 p) == -1) {
3252 err = got_error_from_errno("asprintf");
3253 *in_repo_path = NULL;
3255 free(p);
3256 } else
3257 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3259 return err;
3262 static const struct got_error *
3263 cmd_log(int argc, char *argv[])
3265 const struct got_error *error;
3266 struct got_repository *repo = NULL;
3267 struct got_worktree *worktree = NULL;
3268 struct got_object_id *start_id = NULL;
3269 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3270 char *start_commit = NULL, *label = NULL;
3271 struct got_reference *ref = NULL;
3272 const char *head_ref_name = NULL;
3273 int ch, log_branches = 0;
3274 struct tog_view *view;
3275 int *pack_fds = NULL;
3277 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3278 switch (ch) {
3279 case 'b':
3280 log_branches = 1;
3281 break;
3282 case 'c':
3283 start_commit = optarg;
3284 break;
3285 case 'r':
3286 repo_path = realpath(optarg, NULL);
3287 if (repo_path == NULL)
3288 return got_error_from_errno2("realpath",
3289 optarg);
3290 break;
3291 default:
3292 usage_log();
3293 /* NOTREACHED */
3297 argc -= optind;
3298 argv += optind;
3300 if (argc > 1)
3301 usage_log();
3303 error = got_repo_pack_fds_open(&pack_fds);
3304 if (error != NULL)
3305 goto done;
3307 if (repo_path == NULL) {
3308 cwd = getcwd(NULL, 0);
3309 if (cwd == NULL)
3310 return got_error_from_errno("getcwd");
3311 error = got_worktree_open(&worktree, cwd);
3312 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3313 goto done;
3314 if (worktree)
3315 repo_path =
3316 strdup(got_worktree_get_repo_path(worktree));
3317 else
3318 repo_path = strdup(cwd);
3319 if (repo_path == NULL) {
3320 error = got_error_from_errno("strdup");
3321 goto done;
3325 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3326 if (error != NULL)
3327 goto done;
3329 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3330 repo, worktree);
3331 if (error)
3332 goto done;
3334 init_curses();
3336 error = apply_unveil(got_repo_get_path(repo),
3337 worktree ? got_worktree_get_root_path(worktree) : NULL);
3338 if (error)
3339 goto done;
3341 /* already loaded by tog_log_with_path()? */
3342 if (TAILQ_EMPTY(&tog_refs)) {
3343 error = tog_load_refs(repo, 0);
3344 if (error)
3345 goto done;
3348 if (start_commit == NULL) {
3349 error = got_repo_match_object_id(&start_id, &label,
3350 worktree ? got_worktree_get_head_ref_name(worktree) :
3351 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3352 if (error)
3353 goto done;
3354 head_ref_name = label;
3355 } else {
3356 error = got_ref_open(&ref, repo, start_commit, 0);
3357 if (error == NULL)
3358 head_ref_name = got_ref_get_name(ref);
3359 else if (error->code != GOT_ERR_NOT_REF)
3360 goto done;
3361 error = got_repo_match_object_id(&start_id, NULL,
3362 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3363 if (error)
3364 goto done;
3367 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3368 if (view == NULL) {
3369 error = got_error_from_errno("view_open");
3370 goto done;
3372 error = open_log_view(view, start_id, repo, head_ref_name,
3373 in_repo_path, log_branches);
3374 if (error)
3375 goto done;
3376 if (worktree) {
3377 /* Release work tree lock. */
3378 got_worktree_close(worktree);
3379 worktree = NULL;
3381 error = view_loop(view);
3382 done:
3383 free(in_repo_path);
3384 free(repo_path);
3385 free(cwd);
3386 free(start_id);
3387 free(label);
3388 if (ref)
3389 got_ref_close(ref);
3390 if (repo) {
3391 const struct got_error *close_err = got_repo_close(repo);
3392 if (error == NULL)
3393 error = close_err;
3395 if (worktree)
3396 got_worktree_close(worktree);
3397 if (pack_fds) {
3398 const struct got_error *pack_err =
3399 got_repo_pack_fds_close(pack_fds);
3400 if (error == NULL)
3401 error = pack_err;
3403 tog_free_refs();
3404 return error;
3407 __dead static void
3408 usage_diff(void)
3410 endwin();
3411 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3412 "[-w] object1 object2\n", getprogname());
3413 exit(1);
3416 static int
3417 match_line(const char *line, regex_t *regex, size_t nmatch,
3418 regmatch_t *regmatch)
3420 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3423 static struct tog_color *
3424 match_color(struct tog_colors *colors, const char *line)
3426 struct tog_color *tc = NULL;
3428 STAILQ_FOREACH(tc, colors, entry) {
3429 if (match_line(line, &tc->regex, 0, NULL))
3430 return tc;
3433 return NULL;
3436 static const struct got_error *
3437 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3438 WINDOW *window, int skipcol, regmatch_t *regmatch)
3440 const struct got_error *err = NULL;
3441 char *exstr = NULL;
3442 wchar_t *wline = NULL;
3443 int rme, rms, n, width, scrollx;
3444 int width0 = 0, width1 = 0, width2 = 0;
3445 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3447 *wtotal = 0;
3449 rms = regmatch->rm_so;
3450 rme = regmatch->rm_eo;
3452 err = expand_tab(&exstr, line);
3453 if (err)
3454 return err;
3456 /* Split the line into 3 segments, according to match offsets. */
3457 seg0 = strndup(exstr, rms);
3458 if (seg0 == NULL) {
3459 err = got_error_from_errno("strndup");
3460 goto done;
3462 seg1 = strndup(exstr + rms, rme - rms);
3463 if (seg1 == NULL) {
3464 err = got_error_from_errno("strndup");
3465 goto done;
3467 seg2 = strdup(exstr + rme);
3468 if (seg2 == NULL) {
3469 err = got_error_from_errno("strndup");
3470 goto done;
3473 /* draw up to matched token if we haven't scrolled past it */
3474 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3475 col_tab_align, 1);
3476 if (err)
3477 goto done;
3478 n = MAX(width0 - skipcol, 0);
3479 if (n) {
3480 free(wline);
3481 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3482 wlimit, col_tab_align, 1);
3483 if (err)
3484 goto done;
3485 waddwstr(window, &wline[scrollx]);
3486 wlimit -= width;
3487 *wtotal += width;
3490 if (wlimit > 0) {
3491 int i = 0, w = 0;
3492 size_t wlen;
3494 free(wline);
3495 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3496 col_tab_align, 1);
3497 if (err)
3498 goto done;
3499 wlen = wcslen(wline);
3500 while (i < wlen) {
3501 width = wcwidth(wline[i]);
3502 if (width == -1) {
3503 /* should not happen, tabs are expanded */
3504 err = got_error(GOT_ERR_RANGE);
3505 goto done;
3507 if (width0 + w + width > skipcol)
3508 break;
3509 w += width;
3510 i++;
3512 /* draw (visible part of) matched token (if scrolled into it) */
3513 if (width1 - w > 0) {
3514 wattron(window, A_STANDOUT);
3515 waddwstr(window, &wline[i]);
3516 wattroff(window, A_STANDOUT);
3517 wlimit -= (width1 - w);
3518 *wtotal += (width1 - w);
3522 if (wlimit > 0) { /* draw rest of line */
3523 free(wline);
3524 if (skipcol > width0 + width1) {
3525 err = format_line(&wline, &width2, &scrollx, seg2,
3526 skipcol - (width0 + width1), wlimit,
3527 col_tab_align, 1);
3528 if (err)
3529 goto done;
3530 waddwstr(window, &wline[scrollx]);
3531 } else {
3532 err = format_line(&wline, &width2, NULL, seg2, 0,
3533 wlimit, col_tab_align, 1);
3534 if (err)
3535 goto done;
3536 waddwstr(window, wline);
3538 *wtotal += width2;
3540 done:
3541 free(wline);
3542 free(exstr);
3543 free(seg0);
3544 free(seg1);
3545 free(seg2);
3546 return err;
3549 static const struct got_error *
3550 draw_file(struct tog_view *view, const char *header)
3552 struct tog_diff_view_state *s = &view->state.diff;
3553 regmatch_t *regmatch = &view->regmatch;
3554 const struct got_error *err;
3555 int nprinted = 0;
3556 char *line;
3557 size_t linesize = 0;
3558 ssize_t linelen;
3559 struct tog_color *tc;
3560 wchar_t *wline;
3561 int width;
3562 int max_lines = view->nlines;
3563 int nlines = s->nlines;
3564 off_t line_offset;
3566 line_offset = s->line_offsets[s->first_displayed_line - 1];
3567 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3568 return got_error_from_errno("fseek");
3570 werase(view->window);
3572 if (header) {
3573 if (asprintf(&line, "[%d/%d] %s",
3574 s->first_displayed_line - 1 + s->selected_line, nlines,
3575 header) == -1)
3576 return got_error_from_errno("asprintf");
3577 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3578 0, 0);
3579 free(line);
3580 if (err)
3581 return err;
3583 if (view_needs_focus_indication(view))
3584 wstandout(view->window);
3585 waddwstr(view->window, wline);
3586 free(wline);
3587 wline = NULL;
3588 if (view_needs_focus_indication(view))
3589 wstandend(view->window);
3590 if (width <= view->ncols - 1)
3591 waddch(view->window, '\n');
3593 if (max_lines <= 1)
3594 return NULL;
3595 max_lines--;
3598 s->eof = 0;
3599 view->maxx = 0;
3600 line = NULL;
3601 while (max_lines > 0 && nprinted < max_lines) {
3602 linelen = getline(&line, &linesize, s->f);
3603 if (linelen == -1) {
3604 if (feof(s->f)) {
3605 s->eof = 1;
3606 break;
3608 free(line);
3609 return got_ferror(s->f, GOT_ERR_IO);
3612 /* Set view->maxx based on full line length. */
3613 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3614 view->x ? 1 : 0);
3615 if (err) {
3616 free(line);
3617 return err;
3619 view->maxx = MAX(view->maxx, width);
3620 free(wline);
3621 wline = NULL;
3623 tc = match_color(&s->colors, line);
3624 if (tc)
3625 wattr_on(view->window,
3626 COLOR_PAIR(tc->colorpair), NULL);
3627 if (s->first_displayed_line + nprinted == s->matched_line &&
3628 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3629 err = add_matched_line(&width, line, view->ncols, 0,
3630 view->window, view->x, regmatch);
3631 if (err) {
3632 free(line);
3633 return err;
3635 } else {
3636 int skip;
3637 err = format_line(&wline, &width, &skip, line,
3638 view->x, view->ncols, 0, view->x ? 1 : 0);
3639 if (err) {
3640 free(line);
3641 return err;
3643 waddwstr(view->window, &wline[skip]);
3644 free(wline);
3645 wline = NULL;
3647 if (tc)
3648 wattr_off(view->window,
3649 COLOR_PAIR(tc->colorpair), NULL);
3650 if (width <= view->ncols - 1)
3651 waddch(view->window, '\n');
3652 nprinted++;
3654 free(line);
3655 if (nprinted >= 1)
3656 s->last_displayed_line = s->first_displayed_line +
3657 (nprinted - 1);
3658 else
3659 s->last_displayed_line = s->first_displayed_line;
3661 view_border(view);
3663 if (s->eof) {
3664 while (nprinted < view->nlines) {
3665 waddch(view->window, '\n');
3666 nprinted++;
3669 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3670 view->ncols, 0, 0);
3671 if (err) {
3672 return err;
3675 wstandout(view->window);
3676 waddwstr(view->window, wline);
3677 free(wline);
3678 wline = NULL;
3679 wstandend(view->window);
3682 return NULL;
3685 static char *
3686 get_datestr(time_t *time, char *datebuf)
3688 struct tm mytm, *tm;
3689 char *p, *s;
3691 tm = gmtime_r(time, &mytm);
3692 if (tm == NULL)
3693 return NULL;
3694 s = asctime_r(tm, datebuf);
3695 if (s == NULL)
3696 return NULL;
3697 p = strchr(s, '\n');
3698 if (p)
3699 *p = '\0';
3700 return s;
3703 static const struct got_error *
3704 get_changed_paths(struct got_pathlist_head *paths,
3705 struct got_commit_object *commit, struct got_repository *repo)
3707 const struct got_error *err = NULL;
3708 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3709 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3710 struct got_object_qid *qid;
3712 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3713 if (qid != NULL) {
3714 struct got_commit_object *pcommit;
3715 err = got_object_open_as_commit(&pcommit, repo,
3716 &qid->id);
3717 if (err)
3718 return err;
3720 tree_id1 = got_object_id_dup(
3721 got_object_commit_get_tree_id(pcommit));
3722 if (tree_id1 == NULL) {
3723 got_object_commit_close(pcommit);
3724 return got_error_from_errno("got_object_id_dup");
3726 got_object_commit_close(pcommit);
3730 if (tree_id1) {
3731 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3732 if (err)
3733 goto done;
3736 tree_id2 = got_object_commit_get_tree_id(commit);
3737 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3738 if (err)
3739 goto done;
3741 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3742 got_diff_tree_collect_changed_paths, paths, 0);
3743 done:
3744 if (tree1)
3745 got_object_tree_close(tree1);
3746 if (tree2)
3747 got_object_tree_close(tree2);
3748 free(tree_id1);
3749 return err;
3752 static const struct got_error *
3753 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
3755 off_t *p;
3757 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
3758 if (p == NULL)
3759 return got_error_from_errno("reallocarray");
3760 *line_offsets = p;
3761 (*line_offsets)[*nlines] = off;
3762 (*nlines)++;
3763 return NULL;
3766 static const struct got_error *
3767 write_commit_info(off_t **line_offsets, size_t *nlines,
3768 struct got_object_id *commit_id, struct got_reflist_head *refs,
3769 struct got_repository *repo, FILE *outfile)
3771 const struct got_error *err = NULL;
3772 char datebuf[26], *datestr;
3773 struct got_commit_object *commit;
3774 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
3775 time_t committer_time;
3776 const char *author, *committer;
3777 char *refs_str = NULL;
3778 struct got_pathlist_head changed_paths;
3779 struct got_pathlist_entry *pe;
3780 off_t outoff = 0;
3781 int n;
3783 TAILQ_INIT(&changed_paths);
3785 if (refs) {
3786 err = build_refs_str(&refs_str, refs, commit_id, repo);
3787 if (err)
3788 return err;
3791 err = got_object_open_as_commit(&commit, repo, commit_id);
3792 if (err)
3793 return err;
3795 err = got_object_id_str(&id_str, commit_id);
3796 if (err) {
3797 err = got_error_from_errno("got_object_id_str");
3798 goto done;
3801 err = add_line_offset(line_offsets, nlines, 0);
3802 if (err)
3803 goto done;
3805 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3806 refs_str ? refs_str : "", refs_str ? ")" : "");
3807 if (n < 0) {
3808 err = got_error_from_errno("fprintf");
3809 goto done;
3811 outoff += n;
3812 err = add_line_offset(line_offsets, nlines, outoff);
3813 if (err)
3814 goto done;
3816 n = fprintf(outfile, "from: %s\n",
3817 got_object_commit_get_author(commit));
3818 if (n < 0) {
3819 err = got_error_from_errno("fprintf");
3820 goto done;
3822 outoff += n;
3823 err = add_line_offset(line_offsets, nlines, outoff);
3824 if (err)
3825 goto done;
3827 committer_time = got_object_commit_get_committer_time(commit);
3828 datestr = get_datestr(&committer_time, datebuf);
3829 if (datestr) {
3830 n = fprintf(outfile, "date: %s UTC\n", datestr);
3831 if (n < 0) {
3832 err = got_error_from_errno("fprintf");
3833 goto done;
3835 outoff += n;
3836 err = add_line_offset(line_offsets, nlines, outoff);
3837 if (err)
3838 goto done;
3840 author = got_object_commit_get_author(commit);
3841 committer = got_object_commit_get_committer(commit);
3842 if (strcmp(author, committer) != 0) {
3843 n = fprintf(outfile, "via: %s\n", committer);
3844 if (n < 0) {
3845 err = got_error_from_errno("fprintf");
3846 goto done;
3848 outoff += n;
3849 err = add_line_offset(line_offsets, nlines, outoff);
3850 if (err)
3851 goto done;
3853 if (got_object_commit_get_nparents(commit) > 1) {
3854 const struct got_object_id_queue *parent_ids;
3855 struct got_object_qid *qid;
3856 int pn = 1;
3857 parent_ids = got_object_commit_get_parent_ids(commit);
3858 STAILQ_FOREACH(qid, parent_ids, entry) {
3859 err = got_object_id_str(&id_str, &qid->id);
3860 if (err)
3861 goto done;
3862 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
3863 if (n < 0) {
3864 err = got_error_from_errno("fprintf");
3865 goto done;
3867 outoff += n;
3868 err = add_line_offset(line_offsets, nlines, outoff);
3869 if (err)
3870 goto done;
3871 free(id_str);
3872 id_str = NULL;
3876 err = got_object_commit_get_logmsg(&logmsg, commit);
3877 if (err)
3878 goto done;
3879 s = logmsg;
3880 while ((line = strsep(&s, "\n")) != NULL) {
3881 n = fprintf(outfile, "%s\n", line);
3882 if (n < 0) {
3883 err = got_error_from_errno("fprintf");
3884 goto done;
3886 outoff += n;
3887 err = add_line_offset(line_offsets, nlines, outoff);
3888 if (err)
3889 goto done;
3892 err = get_changed_paths(&changed_paths, commit, repo);
3893 if (err)
3894 goto done;
3895 TAILQ_FOREACH(pe, &changed_paths, entry) {
3896 struct got_diff_changed_path *cp = pe->data;
3897 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
3898 if (n < 0) {
3899 err = got_error_from_errno("fprintf");
3900 goto done;
3902 outoff += n;
3903 err = add_line_offset(line_offsets, nlines, outoff);
3904 if (err)
3905 goto done;
3906 free((char *)pe->path);
3907 free(pe->data);
3910 fputc('\n', outfile);
3911 outoff++;
3912 err = add_line_offset(line_offsets, nlines, outoff);
3913 done:
3914 got_pathlist_free(&changed_paths);
3915 free(id_str);
3916 free(logmsg);
3917 free(refs_str);
3918 got_object_commit_close(commit);
3919 if (err) {
3920 free(*line_offsets);
3921 *line_offsets = NULL;
3922 *nlines = 0;
3924 return err;
3927 static const struct got_error *
3928 create_diff(struct tog_diff_view_state *s)
3930 const struct got_error *err = NULL;
3931 FILE *f = NULL;
3932 int obj_type;
3934 free(s->line_offsets);
3935 s->line_offsets = malloc(sizeof(off_t));
3936 if (s->line_offsets == NULL)
3937 return got_error_from_errno("malloc");
3938 s->nlines = 0;
3940 f = got_opentemp();
3941 if (f == NULL) {
3942 err = got_error_from_errno("got_opentemp");
3943 goto done;
3945 if (s->f && fclose(s->f) == EOF) {
3946 err = got_error_from_errno("fclose");
3947 goto done;
3949 s->f = f;
3951 if (s->id1)
3952 err = got_object_get_type(&obj_type, s->repo, s->id1);
3953 else
3954 err = got_object_get_type(&obj_type, s->repo, s->id2);
3955 if (err)
3956 goto done;
3958 switch (obj_type) {
3959 case GOT_OBJ_TYPE_BLOB:
3960 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
3961 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
3962 s->label1, s->label2, s->diff_context,
3963 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
3964 break;
3965 case GOT_OBJ_TYPE_TREE:
3966 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
3967 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
3968 s->diff_context, s->ignore_whitespace, s->force_text_diff,
3969 s->repo, s->f);
3970 break;
3971 case GOT_OBJ_TYPE_COMMIT: {
3972 const struct got_object_id_queue *parent_ids;
3973 struct got_object_qid *pid;
3974 struct got_commit_object *commit2;
3975 struct got_reflist_head *refs;
3977 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
3978 if (err)
3979 goto done;
3980 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
3981 /* Show commit info if we're diffing to a parent/root commit. */
3982 if (s->id1 == NULL) {
3983 err = write_commit_info(&s->line_offsets, &s->nlines,
3984 s->id2, refs, s->repo, s->f);
3985 if (err)
3986 goto done;
3987 } else {
3988 parent_ids = got_object_commit_get_parent_ids(commit2);
3989 STAILQ_FOREACH(pid, parent_ids, entry) {
3990 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
3991 err = write_commit_info(
3992 &s->line_offsets, &s->nlines,
3993 s->id2, refs, s->repo, s->f);
3994 if (err)
3995 goto done;
3996 break;
4000 got_object_commit_close(commit2);
4002 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
4003 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4004 s->diff_context, s->ignore_whitespace, s->force_text_diff,
4005 s->repo, s->f);
4006 break;
4008 default:
4009 err = got_error(GOT_ERR_OBJ_TYPE);
4010 break;
4012 if (err)
4013 goto done;
4014 done:
4015 if (s->f && fflush(s->f) != 0 && err == NULL)
4016 err = got_error_from_errno("fflush");
4017 return err;
4020 static void
4021 diff_view_indicate_progress(struct tog_view *view)
4023 mvwaddstr(view->window, 0, 0, "diffing...");
4024 update_panels();
4025 doupdate();
4028 static const struct got_error *
4029 search_start_diff_view(struct tog_view *view)
4031 struct tog_diff_view_state *s = &view->state.diff;
4033 s->matched_line = 0;
4034 return NULL;
4037 static const struct got_error *
4038 search_next_diff_view(struct tog_view *view)
4040 struct tog_diff_view_state *s = &view->state.diff;
4041 const struct got_error *err = NULL;
4042 int lineno;
4043 char *line = NULL;
4044 size_t linesize = 0;
4045 ssize_t linelen;
4047 if (!view->searching) {
4048 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4049 return NULL;
4052 if (s->matched_line) {
4053 if (view->searching == TOG_SEARCH_FORWARD)
4054 lineno = s->matched_line + 1;
4055 else
4056 lineno = s->matched_line - 1;
4057 } else
4058 lineno = s->first_displayed_line;
4060 while (1) {
4061 off_t offset;
4063 if (lineno <= 0 || lineno > s->nlines) {
4064 if (s->matched_line == 0) {
4065 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4066 break;
4069 if (view->searching == TOG_SEARCH_FORWARD)
4070 lineno = 1;
4071 else
4072 lineno = s->nlines;
4075 offset = s->line_offsets[lineno - 1];
4076 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4077 free(line);
4078 return got_error_from_errno("fseeko");
4080 linelen = getline(&line, &linesize, s->f);
4081 if (linelen != -1) {
4082 char *exstr;
4083 err = expand_tab(&exstr, line);
4084 if (err)
4085 break;
4086 if (match_line(exstr, &view->regex, 1,
4087 &view->regmatch)) {
4088 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4089 s->matched_line = lineno;
4090 free(exstr);
4091 break;
4093 free(exstr);
4095 if (view->searching == TOG_SEARCH_FORWARD)
4096 lineno++;
4097 else
4098 lineno--;
4100 free(line);
4102 if (s->matched_line) {
4103 s->first_displayed_line = s->matched_line;
4104 s->selected_line = 1;
4107 return err;
4110 static const struct got_error *
4111 close_diff_view(struct tog_view *view)
4113 const struct got_error *err = NULL;
4114 struct tog_diff_view_state *s = &view->state.diff;
4116 free(s->id1);
4117 s->id1 = NULL;
4118 free(s->id2);
4119 s->id2 = NULL;
4120 if (s->f && fclose(s->f) == EOF)
4121 err = got_error_from_errno("fclose");
4122 s->f = NULL;
4123 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4124 err = got_error_from_errno("fclose");
4125 s->f1 = NULL;
4126 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4127 err = got_error_from_errno("fclose");
4128 s->f2 = NULL;
4129 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4130 err = got_error_from_errno("close");
4131 s->fd1 = -1;
4132 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4133 err = got_error_from_errno("close");
4134 s->fd2 = -1;
4135 free_colors(&s->colors);
4136 free(s->line_offsets);
4137 s->line_offsets = NULL;
4138 s->nlines = 0;
4139 return err;
4142 static const struct got_error *
4143 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4144 struct got_object_id *id2, const char *label1, const char *label2,
4145 int diff_context, int ignore_whitespace, int force_text_diff,
4146 struct tog_view *log_view, struct got_repository *repo)
4148 const struct got_error *err;
4149 struct tog_diff_view_state *s = &view->state.diff;
4151 memset(s, 0, sizeof(*s));
4152 s->fd1 = -1;
4153 s->fd2 = -1;
4155 if (id1 != NULL && id2 != NULL) {
4156 int type1, type2;
4157 err = got_object_get_type(&type1, repo, id1);
4158 if (err)
4159 return err;
4160 err = got_object_get_type(&type2, repo, id2);
4161 if (err)
4162 return err;
4164 if (type1 != type2)
4165 return got_error(GOT_ERR_OBJ_TYPE);
4167 s->first_displayed_line = 1;
4168 s->last_displayed_line = view->nlines;
4169 s->selected_line = 1;
4170 s->repo = repo;
4171 s->id1 = id1;
4172 s->id2 = id2;
4173 s->label1 = label1;
4174 s->label2 = label2;
4176 if (id1) {
4177 s->id1 = got_object_id_dup(id1);
4178 if (s->id1 == NULL)
4179 return got_error_from_errno("got_object_id_dup");
4180 } else
4181 s->id1 = NULL;
4183 s->id2 = got_object_id_dup(id2);
4184 if (s->id2 == NULL) {
4185 err = got_error_from_errno("got_object_id_dup");
4186 goto done;
4189 s->f1 = got_opentemp();
4190 if (s->f1 == NULL) {
4191 err = got_error_from_errno("got_opentemp");
4192 goto done;
4195 s->f2 = got_opentemp();
4196 if (s->f2 == NULL) {
4197 err = got_error_from_errno("got_opentemp");
4198 goto done;
4201 s->fd1 = got_opentempfd();
4202 if (s->fd1 == -1) {
4203 err = got_error_from_errno("got_opentempfd");
4204 goto done;
4207 s->fd2 = got_opentempfd();
4208 if (s->fd2 == -1) {
4209 err = got_error_from_errno("got_opentempfd");
4210 goto done;
4213 s->first_displayed_line = 1;
4214 s->last_displayed_line = view->nlines;
4215 s->diff_context = diff_context;
4216 s->ignore_whitespace = ignore_whitespace;
4217 s->force_text_diff = force_text_diff;
4218 s->log_view = log_view;
4219 s->repo = repo;
4221 STAILQ_INIT(&s->colors);
4222 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4223 err = add_color(&s->colors,
4224 "^-", TOG_COLOR_DIFF_MINUS,
4225 get_color_value("TOG_COLOR_DIFF_MINUS"));
4226 if (err)
4227 goto done;
4228 err = add_color(&s->colors, "^\\+",
4229 TOG_COLOR_DIFF_PLUS,
4230 get_color_value("TOG_COLOR_DIFF_PLUS"));
4231 if (err)
4232 goto done;
4233 err = add_color(&s->colors,
4234 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4235 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4236 if (err)
4237 goto done;
4239 err = add_color(&s->colors,
4240 "^(commit [0-9a-f]|parent [0-9]|"
4241 "(blob|file|tree|commit) [-+] |"
4242 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4243 get_color_value("TOG_COLOR_DIFF_META"));
4244 if (err)
4245 goto done;
4247 err = add_color(&s->colors,
4248 "^(from|via): ", TOG_COLOR_AUTHOR,
4249 get_color_value("TOG_COLOR_AUTHOR"));
4250 if (err)
4251 goto done;
4253 err = add_color(&s->colors,
4254 "^date: ", TOG_COLOR_DATE,
4255 get_color_value("TOG_COLOR_DATE"));
4256 if (err)
4257 goto done;
4260 if (log_view && view_is_splitscreen(view))
4261 show_log_view(log_view); /* draw vborder */
4262 diff_view_indicate_progress(view);
4264 err = create_diff(s);
4266 view->show = show_diff_view;
4267 view->input = input_diff_view;
4268 view->close = close_diff_view;
4269 view->search_start = search_start_diff_view;
4270 view->search_next = search_next_diff_view;
4271 done:
4272 if (err)
4273 close_diff_view(view);
4274 return err;
4277 static const struct got_error *
4278 show_diff_view(struct tog_view *view)
4280 const struct got_error *err;
4281 struct tog_diff_view_state *s = &view->state.diff;
4282 char *id_str1 = NULL, *id_str2, *header;
4283 const char *label1, *label2;
4285 if (s->id1) {
4286 err = got_object_id_str(&id_str1, s->id1);
4287 if (err)
4288 return err;
4289 label1 = s->label1 ? : id_str1;
4290 } else
4291 label1 = "/dev/null";
4293 err = got_object_id_str(&id_str2, s->id2);
4294 if (err)
4295 return err;
4296 label2 = s->label2 ? : id_str2;
4298 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4299 err = got_error_from_errno("asprintf");
4300 free(id_str1);
4301 free(id_str2);
4302 return err;
4304 free(id_str1);
4305 free(id_str2);
4307 err = draw_file(view, header);
4308 free(header);
4309 return err;
4312 static const struct got_error *
4313 set_selected_commit(struct tog_diff_view_state *s,
4314 struct commit_queue_entry *entry)
4316 const struct got_error *err;
4317 const struct got_object_id_queue *parent_ids;
4318 struct got_commit_object *selected_commit;
4319 struct got_object_qid *pid;
4321 free(s->id2);
4322 s->id2 = got_object_id_dup(entry->id);
4323 if (s->id2 == NULL)
4324 return got_error_from_errno("got_object_id_dup");
4326 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4327 if (err)
4328 return err;
4329 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4330 free(s->id1);
4331 pid = STAILQ_FIRST(parent_ids);
4332 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4333 got_object_commit_close(selected_commit);
4334 return NULL;
4337 static const struct got_error *
4338 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4340 const struct got_error *err = NULL;
4341 struct tog_diff_view_state *s = &view->state.diff;
4342 struct tog_log_view_state *ls;
4343 struct commit_queue_entry *old_selected_entry;
4344 char *line = NULL;
4345 size_t linesize = 0;
4346 ssize_t linelen;
4347 int i, nscroll = view->nlines - 1;
4349 switch (ch) {
4350 case '0':
4351 view->x = 0;
4352 break;
4353 case '$':
4354 view->x = MAX(view->maxx - view->ncols / 3, 0);
4355 view->count = 0;
4356 break;
4357 case KEY_RIGHT:
4358 case 'l':
4359 if (view->x + view->ncols / 3 < view->maxx)
4360 view->x += 2; /* move two columns right */
4361 else
4362 view->count = 0;
4363 break;
4364 case KEY_LEFT:
4365 case 'h':
4366 view->x -= MIN(view->x, 2); /* move two columns back */
4367 if (view->x <= 0)
4368 view->count = 0;
4369 break;
4370 case 'a':
4371 case 'w':
4372 if (ch == 'a')
4373 s->force_text_diff = !s->force_text_diff;
4374 if (ch == 'w')
4375 s->ignore_whitespace = !s->ignore_whitespace;
4376 wclear(view->window);
4377 s->first_displayed_line = 1;
4378 s->last_displayed_line = view->nlines;
4379 s->matched_line = 0;
4380 diff_view_indicate_progress(view);
4381 err = create_diff(s);
4382 view->count = 0;
4383 break;
4384 case 'g':
4385 case KEY_HOME:
4386 s->first_displayed_line = 1;
4387 view->count = 0;
4388 break;
4389 case 'G':
4390 case KEY_END:
4391 view->count = 0;
4392 if (s->eof)
4393 break;
4395 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4396 s->eof = 1;
4397 break;
4398 case 'k':
4399 case KEY_UP:
4400 case CTRL('p'):
4401 if (s->first_displayed_line > 1)
4402 s->first_displayed_line--;
4403 else
4404 view->count = 0;
4405 break;
4406 case CTRL('u'):
4407 case 'u':
4408 nscroll /= 2;
4409 /* FALL THROUGH */
4410 case KEY_PPAGE:
4411 case CTRL('b'):
4412 case 'b':
4413 if (s->first_displayed_line == 1) {
4414 view->count = 0;
4415 break;
4417 i = 0;
4418 while (i++ < nscroll && s->first_displayed_line > 1)
4419 s->first_displayed_line--;
4420 break;
4421 case 'j':
4422 case KEY_DOWN:
4423 case CTRL('n'):
4424 if (!s->eof)
4425 s->first_displayed_line++;
4426 else
4427 view->count = 0;
4428 break;
4429 case CTRL('d'):
4430 case 'd':
4431 nscroll /= 2;
4432 /* FALL THROUGH */
4433 case KEY_NPAGE:
4434 case CTRL('f'):
4435 case 'f':
4436 case ' ':
4437 if (s->eof) {
4438 view->count = 0;
4439 break;
4441 i = 0;
4442 while (!s->eof && i++ < nscroll) {
4443 linelen = getline(&line, &linesize, s->f);
4444 s->first_displayed_line++;
4445 if (linelen == -1) {
4446 if (feof(s->f)) {
4447 s->eof = 1;
4448 } else
4449 err = got_ferror(s->f, GOT_ERR_IO);
4450 break;
4453 free(line);
4454 break;
4455 case '[':
4456 if (s->diff_context > 0) {
4457 s->diff_context--;
4458 s->matched_line = 0;
4459 diff_view_indicate_progress(view);
4460 err = create_diff(s);
4461 if (s->first_displayed_line + view->nlines - 1 >
4462 s->nlines) {
4463 s->first_displayed_line = 1;
4464 s->last_displayed_line = view->nlines;
4466 } else
4467 view->count = 0;
4468 break;
4469 case ']':
4470 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4471 s->diff_context++;
4472 s->matched_line = 0;
4473 diff_view_indicate_progress(view);
4474 err = create_diff(s);
4475 } else
4476 view->count = 0;
4477 break;
4478 case '<':
4479 case ',':
4480 if (s->log_view == NULL) {
4481 view->count = 0;
4482 break;
4484 ls = &s->log_view->state.log;
4485 old_selected_entry = ls->selected_entry;
4487 /* view->count handled in input_log_view() */
4488 err = input_log_view(NULL, s->log_view, KEY_UP);
4489 if (err)
4490 break;
4492 if (old_selected_entry == ls->selected_entry)
4493 break;
4495 err = set_selected_commit(s, ls->selected_entry);
4496 if (err)
4497 break;
4499 s->first_displayed_line = 1;
4500 s->last_displayed_line = view->nlines;
4501 s->matched_line = 0;
4502 view->x = 0;
4504 diff_view_indicate_progress(view);
4505 err = create_diff(s);
4506 break;
4507 case '>':
4508 case '.':
4509 if (s->log_view == NULL) {
4510 view->count = 0;
4511 break;
4513 ls = &s->log_view->state.log;
4514 old_selected_entry = ls->selected_entry;
4516 /* view->count handled in input_log_view() */
4517 err = input_log_view(NULL, s->log_view, KEY_DOWN);
4518 if (err)
4519 break;
4521 if (old_selected_entry == ls->selected_entry)
4522 break;
4524 err = set_selected_commit(s, ls->selected_entry);
4525 if (err)
4526 break;
4528 s->first_displayed_line = 1;
4529 s->last_displayed_line = view->nlines;
4530 s->matched_line = 0;
4531 view->x = 0;
4533 diff_view_indicate_progress(view);
4534 err = create_diff(s);
4535 break;
4536 default:
4537 view->count = 0;
4538 break;
4541 return err;
4544 static const struct got_error *
4545 cmd_diff(int argc, char *argv[])
4547 const struct got_error *error = NULL;
4548 struct got_repository *repo = NULL;
4549 struct got_worktree *worktree = NULL;
4550 struct got_object_id *id1 = NULL, *id2 = NULL;
4551 char *repo_path = NULL, *cwd = NULL;
4552 char *id_str1 = NULL, *id_str2 = NULL;
4553 char *label1 = NULL, *label2 = NULL;
4554 int diff_context = 3, ignore_whitespace = 0;
4555 int ch, force_text_diff = 0;
4556 const char *errstr;
4557 struct tog_view *view;
4558 int *pack_fds = NULL;
4560 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4561 switch (ch) {
4562 case 'a':
4563 force_text_diff = 1;
4564 break;
4565 case 'C':
4566 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4567 &errstr);
4568 if (errstr != NULL)
4569 errx(1, "number of context lines is %s: %s",
4570 errstr, errstr);
4571 break;
4572 case 'r':
4573 repo_path = realpath(optarg, NULL);
4574 if (repo_path == NULL)
4575 return got_error_from_errno2("realpath",
4576 optarg);
4577 got_path_strip_trailing_slashes(repo_path);
4578 break;
4579 case 'w':
4580 ignore_whitespace = 1;
4581 break;
4582 default:
4583 usage_diff();
4584 /* NOTREACHED */
4588 argc -= optind;
4589 argv += optind;
4591 if (argc == 0) {
4592 usage_diff(); /* TODO show local worktree changes */
4593 } else if (argc == 2) {
4594 id_str1 = argv[0];
4595 id_str2 = argv[1];
4596 } else
4597 usage_diff();
4599 error = got_repo_pack_fds_open(&pack_fds);
4600 if (error)
4601 goto done;
4603 if (repo_path == NULL) {
4604 cwd = getcwd(NULL, 0);
4605 if (cwd == NULL)
4606 return got_error_from_errno("getcwd");
4607 error = got_worktree_open(&worktree, cwd);
4608 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4609 goto done;
4610 if (worktree)
4611 repo_path =
4612 strdup(got_worktree_get_repo_path(worktree));
4613 else
4614 repo_path = strdup(cwd);
4615 if (repo_path == NULL) {
4616 error = got_error_from_errno("strdup");
4617 goto done;
4621 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4622 if (error)
4623 goto done;
4625 init_curses();
4627 error = apply_unveil(got_repo_get_path(repo), NULL);
4628 if (error)
4629 goto done;
4631 error = tog_load_refs(repo, 0);
4632 if (error)
4633 goto done;
4635 error = got_repo_match_object_id(&id1, &label1, id_str1,
4636 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4637 if (error)
4638 goto done;
4640 error = got_repo_match_object_id(&id2, &label2, id_str2,
4641 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4642 if (error)
4643 goto done;
4645 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4646 if (view == NULL) {
4647 error = got_error_from_errno("view_open");
4648 goto done;
4650 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4651 ignore_whitespace, force_text_diff, NULL, repo);
4652 if (error)
4653 goto done;
4654 error = view_loop(view);
4655 done:
4656 free(label1);
4657 free(label2);
4658 free(repo_path);
4659 free(cwd);
4660 if (repo) {
4661 const struct got_error *close_err = got_repo_close(repo);
4662 if (error == NULL)
4663 error = close_err;
4665 if (worktree)
4666 got_worktree_close(worktree);
4667 if (pack_fds) {
4668 const struct got_error *pack_err =
4669 got_repo_pack_fds_close(pack_fds);
4670 if (error == NULL)
4671 error = pack_err;
4673 tog_free_refs();
4674 return error;
4677 __dead static void
4678 usage_blame(void)
4680 endwin();
4681 fprintf(stderr,
4682 "usage: %s blame [-c commit] [-r repository-path] path\n",
4683 getprogname());
4684 exit(1);
4687 struct tog_blame_line {
4688 int annotated;
4689 struct got_object_id *id;
4692 static const struct got_error *
4693 draw_blame(struct tog_view *view)
4695 struct tog_blame_view_state *s = &view->state.blame;
4696 struct tog_blame *blame = &s->blame;
4697 regmatch_t *regmatch = &view->regmatch;
4698 const struct got_error *err;
4699 int lineno = 0, nprinted = 0;
4700 char *line = NULL;
4701 size_t linesize = 0;
4702 ssize_t linelen;
4703 wchar_t *wline;
4704 int width;
4705 struct tog_blame_line *blame_line;
4706 struct got_object_id *prev_id = NULL;
4707 char *id_str;
4708 struct tog_color *tc;
4710 err = got_object_id_str(&id_str, &s->blamed_commit->id);
4711 if (err)
4712 return err;
4714 rewind(blame->f);
4715 werase(view->window);
4717 if (asprintf(&line, "commit %s", id_str) == -1) {
4718 err = got_error_from_errno("asprintf");
4719 free(id_str);
4720 return err;
4723 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4724 free(line);
4725 line = NULL;
4726 if (err)
4727 return err;
4728 if (view_needs_focus_indication(view))
4729 wstandout(view->window);
4730 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4731 if (tc)
4732 wattr_on(view->window,
4733 COLOR_PAIR(tc->colorpair), NULL);
4734 waddwstr(view->window, wline);
4735 if (tc)
4736 wattr_off(view->window,
4737 COLOR_PAIR(tc->colorpair), NULL);
4738 if (view_needs_focus_indication(view))
4739 wstandend(view->window);
4740 free(wline);
4741 wline = NULL;
4742 if (width < view->ncols - 1)
4743 waddch(view->window, '\n');
4745 if (asprintf(&line, "[%d/%d] %s%s",
4746 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
4747 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
4748 free(id_str);
4749 return got_error_from_errno("asprintf");
4751 free(id_str);
4752 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4753 free(line);
4754 line = NULL;
4755 if (err)
4756 return err;
4757 waddwstr(view->window, wline);
4758 free(wline);
4759 wline = NULL;
4760 if (width < view->ncols - 1)
4761 waddch(view->window, '\n');
4763 s->eof = 0;
4764 view->maxx = 0;
4765 while (nprinted < view->nlines - 2) {
4766 linelen = getline(&line, &linesize, blame->f);
4767 if (linelen == -1) {
4768 if (feof(blame->f)) {
4769 s->eof = 1;
4770 break;
4772 free(line);
4773 return got_ferror(blame->f, GOT_ERR_IO);
4775 if (++lineno < s->first_displayed_line)
4776 continue;
4778 /* Set view->maxx based on full line length. */
4779 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
4780 if (err) {
4781 free(line);
4782 return err;
4784 free(wline);
4785 wline = NULL;
4786 view->maxx = MAX(view->maxx, width);
4788 if (view->focussed && nprinted == s->selected_line - 1)
4789 wstandout(view->window);
4791 if (blame->nlines > 0) {
4792 blame_line = &blame->lines[lineno - 1];
4793 if (blame_line->annotated && prev_id &&
4794 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
4795 !(view->focussed &&
4796 nprinted == s->selected_line - 1)) {
4797 waddstr(view->window, " ");
4798 } else if (blame_line->annotated) {
4799 char *id_str;
4800 err = got_object_id_str(&id_str,
4801 blame_line->id);
4802 if (err) {
4803 free(line);
4804 return err;
4806 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4807 if (tc)
4808 wattr_on(view->window,
4809 COLOR_PAIR(tc->colorpair), NULL);
4810 wprintw(view->window, "%.8s", id_str);
4811 if (tc)
4812 wattr_off(view->window,
4813 COLOR_PAIR(tc->colorpair), NULL);
4814 free(id_str);
4815 prev_id = blame_line->id;
4816 } else {
4817 waddstr(view->window, "........");
4818 prev_id = NULL;
4820 } else {
4821 waddstr(view->window, "........");
4822 prev_id = NULL;
4825 if (view->focussed && nprinted == s->selected_line - 1)
4826 wstandend(view->window);
4827 waddstr(view->window, " ");
4829 if (view->ncols <= 9) {
4830 width = 9;
4831 } else if (s->first_displayed_line + nprinted ==
4832 s->matched_line &&
4833 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4834 err = add_matched_line(&width, line, view->ncols - 9, 9,
4835 view->window, view->x, regmatch);
4836 if (err) {
4837 free(line);
4838 return err;
4840 width += 9;
4841 } else {
4842 int skip;
4843 err = format_line(&wline, &width, &skip, line,
4844 view->x, view->ncols - 9, 9, 1);
4845 if (err) {
4846 free(line);
4847 return err;
4849 waddwstr(view->window, &wline[skip]);
4850 width += 9;
4851 free(wline);
4852 wline = NULL;
4855 if (width <= view->ncols - 1)
4856 waddch(view->window, '\n');
4857 if (++nprinted == 1)
4858 s->first_displayed_line = lineno;
4860 free(line);
4861 s->last_displayed_line = lineno;
4863 view_border(view);
4865 return NULL;
4868 static const struct got_error *
4869 blame_cb(void *arg, int nlines, int lineno,
4870 struct got_commit_object *commit, struct got_object_id *id)
4872 const struct got_error *err = NULL;
4873 struct tog_blame_cb_args *a = arg;
4874 struct tog_blame_line *line;
4875 int errcode;
4877 if (nlines != a->nlines ||
4878 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4879 return got_error(GOT_ERR_RANGE);
4881 errcode = pthread_mutex_lock(&tog_mutex);
4882 if (errcode)
4883 return got_error_set_errno(errcode, "pthread_mutex_lock");
4885 if (*a->quit) { /* user has quit the blame view */
4886 err = got_error(GOT_ERR_ITER_COMPLETED);
4887 goto done;
4890 if (lineno == -1)
4891 goto done; /* no change in this commit */
4893 line = &a->lines[lineno - 1];
4894 if (line->annotated)
4895 goto done;
4897 line->id = got_object_id_dup(id);
4898 if (line->id == NULL) {
4899 err = got_error_from_errno("got_object_id_dup");
4900 goto done;
4902 line->annotated = 1;
4903 done:
4904 errcode = pthread_mutex_unlock(&tog_mutex);
4905 if (errcode)
4906 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4907 return err;
4910 static void *
4911 blame_thread(void *arg)
4913 const struct got_error *err, *close_err;
4914 struct tog_blame_thread_args *ta = arg;
4915 struct tog_blame_cb_args *a = ta->cb_args;
4916 int errcode, fd1 = -1, fd2 = -1;
4917 FILE *f1 = NULL, *f2 = NULL;
4919 fd1 = got_opentempfd();
4920 if (fd1 == -1)
4921 return (void *)got_error_from_errno("got_opentempfd");
4923 fd2 = got_opentempfd();
4924 if (fd2 == -1) {
4925 err = got_error_from_errno("got_opentempfd");
4926 goto done;
4929 f1 = got_opentemp();
4930 if (f1 == NULL) {
4931 err = (void *)got_error_from_errno("got_opentemp");
4932 goto done;
4934 f2 = got_opentemp();
4935 if (f2 == NULL) {
4936 err = (void *)got_error_from_errno("got_opentemp");
4937 goto done;
4940 err = block_signals_used_by_main_thread();
4941 if (err)
4942 goto done;
4944 err = got_blame(ta->path, a->commit_id, ta->repo,
4945 blame_cb, ta->cb_args, ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1,
4946 f2);
4947 if (err && err->code == GOT_ERR_CANCELLED)
4948 err = NULL;
4950 errcode = pthread_mutex_lock(&tog_mutex);
4951 if (errcode) {
4952 err = got_error_set_errno(errcode, "pthread_mutex_lock");
4953 goto done;
4956 close_err = got_repo_close(ta->repo);
4957 if (err == NULL)
4958 err = close_err;
4959 ta->repo = NULL;
4960 *ta->complete = 1;
4962 errcode = pthread_mutex_unlock(&tog_mutex);
4963 if (errcode && err == NULL)
4964 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4966 done:
4967 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4968 err = got_error_from_errno("close");
4969 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4970 err = got_error_from_errno("close");
4971 if (f1 && fclose(f1) == EOF && err == NULL)
4972 err = got_error_from_errno("fclose");
4973 if (f2 && fclose(f2) == EOF && err == NULL)
4974 err = got_error_from_errno("fclose");
4976 return (void *)err;
4979 static struct got_object_id *
4980 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
4981 int first_displayed_line, int selected_line)
4983 struct tog_blame_line *line;
4985 if (nlines <= 0)
4986 return NULL;
4988 line = &lines[first_displayed_line - 1 + selected_line - 1];
4989 if (!line->annotated)
4990 return NULL;
4992 return line->id;
4995 static const struct got_error *
4996 stop_blame(struct tog_blame *blame)
4998 const struct got_error *err = NULL;
4999 int i;
5001 if (blame->thread) {
5002 int errcode;
5003 errcode = pthread_mutex_unlock(&tog_mutex);
5004 if (errcode)
5005 return got_error_set_errno(errcode,
5006 "pthread_mutex_unlock");
5007 errcode = pthread_join(blame->thread, (void **)&err);
5008 if (errcode)
5009 return got_error_set_errno(errcode, "pthread_join");
5010 errcode = pthread_mutex_lock(&tog_mutex);
5011 if (errcode)
5012 return got_error_set_errno(errcode,
5013 "pthread_mutex_lock");
5014 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5015 err = NULL;
5016 blame->thread = NULL;
5018 if (blame->thread_args.repo) {
5019 const struct got_error *close_err;
5020 close_err = got_repo_close(blame->thread_args.repo);
5021 if (err == NULL)
5022 err = close_err;
5023 blame->thread_args.repo = NULL;
5025 if (blame->f) {
5026 if (fclose(blame->f) == EOF && err == NULL)
5027 err = got_error_from_errno("fclose");
5028 blame->f = NULL;
5030 if (blame->lines) {
5031 for (i = 0; i < blame->nlines; i++)
5032 free(blame->lines[i].id);
5033 free(blame->lines);
5034 blame->lines = NULL;
5036 free(blame->cb_args.commit_id);
5037 blame->cb_args.commit_id = NULL;
5038 if (blame->pack_fds) {
5039 const struct got_error *pack_err =
5040 got_repo_pack_fds_close(blame->pack_fds);
5041 if (err == NULL)
5042 err = pack_err;
5043 blame->pack_fds = NULL;
5045 return err;
5048 static const struct got_error *
5049 cancel_blame_view(void *arg)
5051 const struct got_error *err = NULL;
5052 int *done = arg;
5053 int errcode;
5055 errcode = pthread_mutex_lock(&tog_mutex);
5056 if (errcode)
5057 return got_error_set_errno(errcode,
5058 "pthread_mutex_unlock");
5060 if (*done)
5061 err = got_error(GOT_ERR_CANCELLED);
5063 errcode = pthread_mutex_unlock(&tog_mutex);
5064 if (errcode)
5065 return got_error_set_errno(errcode,
5066 "pthread_mutex_lock");
5068 return err;
5071 static const struct got_error *
5072 run_blame(struct tog_view *view)
5074 struct tog_blame_view_state *s = &view->state.blame;
5075 struct tog_blame *blame = &s->blame;
5076 const struct got_error *err = NULL;
5077 struct got_commit_object *commit = NULL;
5078 struct got_blob_object *blob = NULL;
5079 struct got_repository *thread_repo = NULL;
5080 struct got_object_id *obj_id = NULL;
5081 int obj_type, fd = -1;
5082 int *pack_fds = NULL;
5084 err = got_object_open_as_commit(&commit, s->repo,
5085 &s->blamed_commit->id);
5086 if (err)
5087 return err;
5089 fd = got_opentempfd();
5090 if (fd == -1) {
5091 err = got_error_from_errno("got_opentempfd");
5092 goto done;
5095 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5096 if (err)
5097 goto done;
5099 err = got_object_get_type(&obj_type, s->repo, obj_id);
5100 if (err)
5101 goto done;
5103 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5104 err = got_error(GOT_ERR_OBJ_TYPE);
5105 goto done;
5108 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5109 if (err)
5110 goto done;
5111 blame->f = got_opentemp();
5112 if (blame->f == NULL) {
5113 err = got_error_from_errno("got_opentemp");
5114 goto done;
5116 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5117 &blame->line_offsets, blame->f, blob);
5118 if (err)
5119 goto done;
5120 if (blame->nlines == 0) {
5121 s->blame_complete = 1;
5122 goto done;
5125 /* Don't include \n at EOF in the blame line count. */
5126 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5127 blame->nlines--;
5129 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5130 if (blame->lines == NULL) {
5131 err = got_error_from_errno("calloc");
5132 goto done;
5135 err = got_repo_pack_fds_open(&pack_fds);
5136 if (err)
5137 goto done;
5138 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5139 pack_fds);
5140 if (err)
5141 goto done;
5143 blame->pack_fds = pack_fds;
5144 blame->cb_args.view = view;
5145 blame->cb_args.lines = blame->lines;
5146 blame->cb_args.nlines = blame->nlines;
5147 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5148 if (blame->cb_args.commit_id == NULL) {
5149 err = got_error_from_errno("got_object_id_dup");
5150 goto done;
5152 blame->cb_args.quit = &s->done;
5154 blame->thread_args.path = s->path;
5155 blame->thread_args.repo = thread_repo;
5156 blame->thread_args.cb_args = &blame->cb_args;
5157 blame->thread_args.complete = &s->blame_complete;
5158 blame->thread_args.cancel_cb = cancel_blame_view;
5159 blame->thread_args.cancel_arg = &s->done;
5160 s->blame_complete = 0;
5162 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5163 s->first_displayed_line = 1;
5164 s->last_displayed_line = view->nlines;
5165 s->selected_line = 1;
5167 s->matched_line = 0;
5169 done:
5170 if (commit)
5171 got_object_commit_close(commit);
5172 if (fd != -1 && close(fd) == -1 && err == NULL)
5173 err = got_error_from_errno("close");
5174 if (blob)
5175 got_object_blob_close(blob);
5176 free(obj_id);
5177 if (err)
5178 stop_blame(blame);
5179 return err;
5182 static const struct got_error *
5183 open_blame_view(struct tog_view *view, char *path,
5184 struct got_object_id *commit_id, struct got_repository *repo)
5186 const struct got_error *err = NULL;
5187 struct tog_blame_view_state *s = &view->state.blame;
5189 STAILQ_INIT(&s->blamed_commits);
5191 s->path = strdup(path);
5192 if (s->path == NULL)
5193 return got_error_from_errno("strdup");
5195 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5196 if (err) {
5197 free(s->path);
5198 return err;
5201 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5202 s->first_displayed_line = 1;
5203 s->last_displayed_line = view->nlines;
5204 s->selected_line = 1;
5205 s->blame_complete = 0;
5206 s->repo = repo;
5207 s->commit_id = commit_id;
5208 memset(&s->blame, 0, sizeof(s->blame));
5210 STAILQ_INIT(&s->colors);
5211 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5212 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5213 get_color_value("TOG_COLOR_COMMIT"));
5214 if (err)
5215 return err;
5218 view->show = show_blame_view;
5219 view->input = input_blame_view;
5220 view->close = close_blame_view;
5221 view->search_start = search_start_blame_view;
5222 view->search_next = search_next_blame_view;
5224 return run_blame(view);
5227 static const struct got_error *
5228 close_blame_view(struct tog_view *view)
5230 const struct got_error *err = NULL;
5231 struct tog_blame_view_state *s = &view->state.blame;
5233 if (s->blame.thread)
5234 err = stop_blame(&s->blame);
5236 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5237 struct got_object_qid *blamed_commit;
5238 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5239 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5240 got_object_qid_free(blamed_commit);
5243 free(s->path);
5244 free_colors(&s->colors);
5245 return err;
5248 static const struct got_error *
5249 search_start_blame_view(struct tog_view *view)
5251 struct tog_blame_view_state *s = &view->state.blame;
5253 s->matched_line = 0;
5254 return NULL;
5257 static const struct got_error *
5258 search_next_blame_view(struct tog_view *view)
5260 struct tog_blame_view_state *s = &view->state.blame;
5261 const struct got_error *err = NULL;
5262 int lineno;
5263 char *line = NULL;
5264 size_t linesize = 0;
5265 ssize_t linelen;
5267 if (!view->searching) {
5268 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5269 return NULL;
5272 if (s->matched_line) {
5273 if (view->searching == TOG_SEARCH_FORWARD)
5274 lineno = s->matched_line + 1;
5275 else
5276 lineno = s->matched_line - 1;
5277 } else
5278 lineno = s->first_displayed_line - 1 + s->selected_line;
5280 while (1) {
5281 off_t offset;
5283 if (lineno <= 0 || lineno > s->blame.nlines) {
5284 if (s->matched_line == 0) {
5285 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5286 break;
5289 if (view->searching == TOG_SEARCH_FORWARD)
5290 lineno = 1;
5291 else
5292 lineno = s->blame.nlines;
5295 offset = s->blame.line_offsets[lineno - 1];
5296 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5297 free(line);
5298 return got_error_from_errno("fseeko");
5300 linelen = getline(&line, &linesize, s->blame.f);
5301 if (linelen != -1) {
5302 char *exstr;
5303 err = expand_tab(&exstr, line);
5304 if (err)
5305 break;
5306 if (match_line(exstr, &view->regex, 1,
5307 &view->regmatch)) {
5308 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5309 s->matched_line = lineno;
5310 free(exstr);
5311 break;
5313 free(exstr);
5315 if (view->searching == TOG_SEARCH_FORWARD)
5316 lineno++;
5317 else
5318 lineno--;
5320 free(line);
5322 if (s->matched_line) {
5323 s->first_displayed_line = s->matched_line;
5324 s->selected_line = 1;
5327 return err;
5330 static const struct got_error *
5331 show_blame_view(struct tog_view *view)
5333 const struct got_error *err = NULL;
5334 struct tog_blame_view_state *s = &view->state.blame;
5335 int errcode;
5337 if (s->blame.thread == NULL && !s->blame_complete) {
5338 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5339 &s->blame.thread_args);
5340 if (errcode)
5341 return got_error_set_errno(errcode, "pthread_create");
5343 halfdelay(1); /* fast refresh while annotating */
5346 if (s->blame_complete)
5347 halfdelay(10); /* disable fast refresh */
5349 err = draw_blame(view);
5351 view_border(view);
5352 return err;
5355 static const struct got_error *
5356 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5358 const struct got_error *err = NULL, *thread_err = NULL;
5359 struct tog_view *diff_view;
5360 struct tog_blame_view_state *s = &view->state.blame;
5361 int eos, nscroll, begin_y = 0, begin_x = 0;
5363 eos = nscroll = view->nlines - 2;
5364 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
5365 view_is_splitscreen(view->child))
5366 --eos; /* border */
5368 switch (ch) {
5369 case '0':
5370 view->x = 0;
5371 break;
5372 case '$':
5373 view->x = MAX(view->maxx - view->ncols / 3, 0);
5374 view->count = 0;
5375 break;
5376 case KEY_RIGHT:
5377 case 'l':
5378 if (view->x + view->ncols / 3 < view->maxx)
5379 view->x += 2; /* move two columns right */
5380 else
5381 view->count = 0;
5382 break;
5383 case KEY_LEFT:
5384 case 'h':
5385 view->x -= MIN(view->x, 2); /* move two columns back */
5386 if (view->x <= 0)
5387 view->count = 0;
5388 break;
5389 case 'q':
5390 s->done = 1;
5391 break;
5392 case 'g':
5393 case KEY_HOME:
5394 s->selected_line = 1;
5395 s->first_displayed_line = 1;
5396 view->count = 0;
5397 break;
5398 case 'G':
5399 case KEY_END:
5400 if (s->blame.nlines < eos) {
5401 s->selected_line = s->blame.nlines;
5402 s->first_displayed_line = 1;
5403 } else {
5404 s->selected_line = eos;
5405 s->first_displayed_line = s->blame.nlines - (eos - 1);
5407 view->count = 0;
5408 break;
5409 case 'k':
5410 case KEY_UP:
5411 case CTRL('p'):
5412 if (s->selected_line > 1)
5413 s->selected_line--;
5414 else if (s->selected_line == 1 &&
5415 s->first_displayed_line > 1)
5416 s->first_displayed_line--;
5417 else
5418 view->count = 0;
5419 break;
5420 case CTRL('u'):
5421 case 'u':
5422 nscroll /= 2;
5423 /* FALL THROUGH */
5424 case KEY_PPAGE:
5425 case CTRL('b'):
5426 case 'b':
5427 if (s->first_displayed_line == 1) {
5428 if (view->count > 1)
5429 nscroll += nscroll;
5430 s->selected_line = MAX(1, s->selected_line - nscroll);
5431 view->count = 0;
5432 break;
5434 if (s->first_displayed_line > nscroll)
5435 s->first_displayed_line -= nscroll;
5436 else
5437 s->first_displayed_line = 1;
5438 break;
5439 case 'j':
5440 case KEY_DOWN:
5441 case CTRL('n'):
5442 if (s->selected_line < eos && s->first_displayed_line +
5443 s->selected_line <= s->blame.nlines)
5444 s->selected_line++;
5445 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5446 s->first_displayed_line++;
5447 else
5448 view->count = 0;
5449 break;
5450 case 'c':
5451 case 'p': {
5452 struct got_object_id *id = NULL;
5454 view->count = 0;
5455 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5456 s->first_displayed_line, s->selected_line);
5457 if (id == NULL)
5458 break;
5459 if (ch == 'p') {
5460 struct got_commit_object *commit, *pcommit;
5461 struct got_object_qid *pid;
5462 struct got_object_id *blob_id = NULL;
5463 int obj_type;
5464 err = got_object_open_as_commit(&commit,
5465 s->repo, id);
5466 if (err)
5467 break;
5468 pid = STAILQ_FIRST(
5469 got_object_commit_get_parent_ids(commit));
5470 if (pid == NULL) {
5471 got_object_commit_close(commit);
5472 break;
5474 /* Check if path history ends here. */
5475 err = got_object_open_as_commit(&pcommit,
5476 s->repo, &pid->id);
5477 if (err)
5478 break;
5479 err = got_object_id_by_path(&blob_id, s->repo,
5480 pcommit, s->path);
5481 got_object_commit_close(pcommit);
5482 if (err) {
5483 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5484 err = NULL;
5485 got_object_commit_close(commit);
5486 break;
5488 err = got_object_get_type(&obj_type, s->repo,
5489 blob_id);
5490 free(blob_id);
5491 /* Can't blame non-blob type objects. */
5492 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5493 got_object_commit_close(commit);
5494 break;
5496 err = got_object_qid_alloc(&s->blamed_commit,
5497 &pid->id);
5498 got_object_commit_close(commit);
5499 } else {
5500 if (got_object_id_cmp(id,
5501 &s->blamed_commit->id) == 0)
5502 break;
5503 err = got_object_qid_alloc(&s->blamed_commit,
5504 id);
5506 if (err)
5507 break;
5508 s->done = 1;
5509 thread_err = stop_blame(&s->blame);
5510 s->done = 0;
5511 if (thread_err)
5512 break;
5513 STAILQ_INSERT_HEAD(&s->blamed_commits,
5514 s->blamed_commit, entry);
5515 err = run_blame(view);
5516 if (err)
5517 break;
5518 break;
5520 case 'C': {
5521 struct got_object_qid *first;
5523 view->count = 0;
5524 first = STAILQ_FIRST(&s->blamed_commits);
5525 if (!got_object_id_cmp(&first->id, s->commit_id))
5526 break;
5527 s->done = 1;
5528 thread_err = stop_blame(&s->blame);
5529 s->done = 0;
5530 if (thread_err)
5531 break;
5532 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5533 got_object_qid_free(s->blamed_commit);
5534 s->blamed_commit =
5535 STAILQ_FIRST(&s->blamed_commits);
5536 err = run_blame(view);
5537 if (err)
5538 break;
5539 break;
5541 case KEY_ENTER:
5542 case '\r': {
5543 struct got_object_id *id = NULL;
5544 struct got_object_qid *pid;
5545 struct got_commit_object *commit = NULL;
5547 view->count = 0;
5548 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5549 s->first_displayed_line, s->selected_line);
5550 if (id == NULL)
5551 break;
5552 err = got_object_open_as_commit(&commit, s->repo, id);
5553 if (err)
5554 break;
5555 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
5556 if (view_is_parent_view(view))
5557 view_get_split(view, &begin_y, &begin_x);
5559 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
5560 if (diff_view == NULL) {
5561 got_object_commit_close(commit);
5562 err = got_error_from_errno("view_open");
5563 break;
5565 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5566 id, NULL, NULL, 3, 0, 0, NULL, s->repo);
5567 got_object_commit_close(commit);
5568 if (err) {
5569 view_close(diff_view);
5570 break;
5572 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
5573 err = view_init_hsplit(view, begin_y);
5574 if (err)
5575 break;
5578 view->focussed = 0;
5579 diff_view->focussed = 1;
5580 diff_view->mode = view->mode;
5581 diff_view->nlines = view->lines - begin_y;
5582 if (view_is_parent_view(view)) {
5583 err = view_close_child(view);
5584 if (err)
5585 break;
5586 err = view_set_child(view, diff_view);
5587 if (err)
5588 break;
5589 view->focus_child = 1;
5590 } else
5591 *new_view = diff_view;
5592 if (err)
5593 break;
5594 break;
5596 case CTRL('d'):
5597 case 'd':
5598 nscroll /= 2;
5599 /* FALL THROUGH */
5600 case KEY_NPAGE:
5601 case CTRL('f'):
5602 case 'f':
5603 case ' ':
5604 if (s->last_displayed_line >= s->blame.nlines &&
5605 s->selected_line >= MIN(s->blame.nlines,
5606 view->nlines - 2)) {
5607 view->count = 0;
5608 break;
5610 if (s->last_displayed_line >= s->blame.nlines &&
5611 s->selected_line < view->nlines - 2) {
5612 s->selected_line +=
5613 MIN(nscroll, s->last_displayed_line -
5614 s->first_displayed_line - s->selected_line + 1);
5616 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5617 s->first_displayed_line += nscroll;
5618 else
5619 s->first_displayed_line =
5620 s->blame.nlines - (view->nlines - 3);
5621 break;
5622 case KEY_RESIZE:
5623 if (s->selected_line > view->nlines - 2) {
5624 s->selected_line = MIN(s->blame.nlines,
5625 view->nlines - 2);
5627 break;
5628 default:
5629 view->count = 0;
5630 break;
5632 return thread_err ? thread_err : err;
5635 static const struct got_error *
5636 cmd_blame(int argc, char *argv[])
5638 const struct got_error *error;
5639 struct got_repository *repo = NULL;
5640 struct got_worktree *worktree = NULL;
5641 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5642 char *link_target = NULL;
5643 struct got_object_id *commit_id = NULL;
5644 struct got_commit_object *commit = NULL;
5645 char *commit_id_str = NULL;
5646 int ch;
5647 struct tog_view *view;
5648 int *pack_fds = NULL;
5650 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5651 switch (ch) {
5652 case 'c':
5653 commit_id_str = optarg;
5654 break;
5655 case 'r':
5656 repo_path = realpath(optarg, NULL);
5657 if (repo_path == NULL)
5658 return got_error_from_errno2("realpath",
5659 optarg);
5660 break;
5661 default:
5662 usage_blame();
5663 /* NOTREACHED */
5667 argc -= optind;
5668 argv += optind;
5670 if (argc != 1)
5671 usage_blame();
5673 error = got_repo_pack_fds_open(&pack_fds);
5674 if (error != NULL)
5675 goto done;
5677 if (repo_path == NULL) {
5678 cwd = getcwd(NULL, 0);
5679 if (cwd == NULL)
5680 return got_error_from_errno("getcwd");
5681 error = got_worktree_open(&worktree, cwd);
5682 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5683 goto done;
5684 if (worktree)
5685 repo_path =
5686 strdup(got_worktree_get_repo_path(worktree));
5687 else
5688 repo_path = strdup(cwd);
5689 if (repo_path == NULL) {
5690 error = got_error_from_errno("strdup");
5691 goto done;
5695 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5696 if (error != NULL)
5697 goto done;
5699 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
5700 worktree);
5701 if (error)
5702 goto done;
5704 init_curses();
5706 error = apply_unveil(got_repo_get_path(repo), NULL);
5707 if (error)
5708 goto done;
5710 error = tog_load_refs(repo, 0);
5711 if (error)
5712 goto done;
5714 if (commit_id_str == NULL) {
5715 struct got_reference *head_ref;
5716 error = got_ref_open(&head_ref, repo, worktree ?
5717 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5718 if (error != NULL)
5719 goto done;
5720 error = got_ref_resolve(&commit_id, repo, head_ref);
5721 got_ref_close(head_ref);
5722 } else {
5723 error = got_repo_match_object_id(&commit_id, NULL,
5724 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
5726 if (error != NULL)
5727 goto done;
5729 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
5730 if (view == NULL) {
5731 error = got_error_from_errno("view_open");
5732 goto done;
5735 error = got_object_open_as_commit(&commit, repo, commit_id);
5736 if (error)
5737 goto done;
5739 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5740 commit, repo);
5741 if (error)
5742 goto done;
5744 error = open_blame_view(view, link_target ? link_target : in_repo_path,
5745 commit_id, repo);
5746 if (error)
5747 goto done;
5748 if (worktree) {
5749 /* Release work tree lock. */
5750 got_worktree_close(worktree);
5751 worktree = NULL;
5753 error = view_loop(view);
5754 done:
5755 free(repo_path);
5756 free(in_repo_path);
5757 free(link_target);
5758 free(cwd);
5759 free(commit_id);
5760 if (commit)
5761 got_object_commit_close(commit);
5762 if (worktree)
5763 got_worktree_close(worktree);
5764 if (repo) {
5765 const struct got_error *close_err = got_repo_close(repo);
5766 if (error == NULL)
5767 error = close_err;
5769 if (pack_fds) {
5770 const struct got_error *pack_err =
5771 got_repo_pack_fds_close(pack_fds);
5772 if (error == NULL)
5773 error = pack_err;
5775 tog_free_refs();
5776 return error;
5779 static const struct got_error *
5780 draw_tree_entries(struct tog_view *view, const char *parent_path)
5782 struct tog_tree_view_state *s = &view->state.tree;
5783 const struct got_error *err = NULL;
5784 struct got_tree_entry *te;
5785 wchar_t *wline;
5786 struct tog_color *tc;
5787 int width, n, i, nentries;
5788 int limit = view->nlines;
5790 s->ndisplayed = 0;
5791 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
5792 view_is_splitscreen(view->child))
5793 --limit; /* border */
5795 werase(view->window);
5797 if (limit == 0)
5798 return NULL;
5800 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
5801 0, 0);
5802 if (err)
5803 return err;
5804 if (view_needs_focus_indication(view))
5805 wstandout(view->window);
5806 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5807 if (tc)
5808 wattr_on(view->window,
5809 COLOR_PAIR(tc->colorpair), NULL);
5810 waddwstr(view->window, wline);
5811 if (tc)
5812 wattr_off(view->window,
5813 COLOR_PAIR(tc->colorpair), NULL);
5814 if (view_needs_focus_indication(view))
5815 wstandend(view->window);
5816 free(wline);
5817 wline = NULL;
5818 if (width < view->ncols - 1)
5819 waddch(view->window, '\n');
5820 if (--limit <= 0)
5821 return NULL;
5822 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
5823 0, 0);
5824 if (err)
5825 return err;
5826 waddwstr(view->window, wline);
5827 free(wline);
5828 wline = NULL;
5829 if (width < view->ncols - 1)
5830 waddch(view->window, '\n');
5831 if (--limit <= 0)
5832 return NULL;
5833 waddch(view->window, '\n');
5834 if (--limit <= 0)
5835 return NULL;
5837 if (s->first_displayed_entry == NULL) {
5838 te = got_object_tree_get_first_entry(s->tree);
5839 if (s->selected == 0) {
5840 if (view->focussed)
5841 wstandout(view->window);
5842 s->selected_entry = NULL;
5844 waddstr(view->window, " ..\n"); /* parent directory */
5845 if (s->selected == 0 && view->focussed)
5846 wstandend(view->window);
5847 s->ndisplayed++;
5848 if (--limit <= 0)
5849 return NULL;
5850 n = 1;
5851 } else {
5852 n = 0;
5853 te = s->first_displayed_entry;
5856 nentries = got_object_tree_get_nentries(s->tree);
5857 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
5858 char *line = NULL, *id_str = NULL, *link_target = NULL;
5859 const char *modestr = "";
5860 mode_t mode;
5862 te = got_object_tree_get_entry(s->tree, i);
5863 mode = got_tree_entry_get_mode(te);
5865 if (s->show_ids) {
5866 err = got_object_id_str(&id_str,
5867 got_tree_entry_get_id(te));
5868 if (err)
5869 return got_error_from_errno(
5870 "got_object_id_str");
5872 if (got_object_tree_entry_is_submodule(te))
5873 modestr = "$";
5874 else if (S_ISLNK(mode)) {
5875 int i;
5877 err = got_tree_entry_get_symlink_target(&link_target,
5878 te, s->repo);
5879 if (err) {
5880 free(id_str);
5881 return err;
5883 for (i = 0; i < strlen(link_target); i++) {
5884 if (!isprint((unsigned char)link_target[i]))
5885 link_target[i] = '?';
5887 modestr = "@";
5889 else if (S_ISDIR(mode))
5890 modestr = "/";
5891 else if (mode & S_IXUSR)
5892 modestr = "*";
5893 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
5894 got_tree_entry_get_name(te), modestr,
5895 link_target ? " -> ": "",
5896 link_target ? link_target : "") == -1) {
5897 free(id_str);
5898 free(link_target);
5899 return got_error_from_errno("asprintf");
5901 free(id_str);
5902 free(link_target);
5903 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
5904 0, 0);
5905 if (err) {
5906 free(line);
5907 break;
5909 if (n == s->selected) {
5910 if (view->focussed)
5911 wstandout(view->window);
5912 s->selected_entry = te;
5914 tc = match_color(&s->colors, line);
5915 if (tc)
5916 wattr_on(view->window,
5917 COLOR_PAIR(tc->colorpair), NULL);
5918 waddwstr(view->window, wline);
5919 if (tc)
5920 wattr_off(view->window,
5921 COLOR_PAIR(tc->colorpair), NULL);
5922 if (width < view->ncols - 1)
5923 waddch(view->window, '\n');
5924 if (n == s->selected && view->focussed)
5925 wstandend(view->window);
5926 free(line);
5927 free(wline);
5928 wline = NULL;
5929 n++;
5930 s->ndisplayed++;
5931 s->last_displayed_entry = te;
5932 if (--limit <= 0)
5933 break;
5936 return err;
5939 static void
5940 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
5942 struct got_tree_entry *te;
5943 int isroot = s->tree == s->root;
5944 int i = 0;
5946 if (s->first_displayed_entry == NULL)
5947 return;
5949 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
5950 while (i++ < maxscroll) {
5951 if (te == NULL) {
5952 if (!isroot)
5953 s->first_displayed_entry = NULL;
5954 break;
5956 s->first_displayed_entry = te;
5957 te = got_tree_entry_get_prev(s->tree, te);
5961 static const struct got_error *
5962 tree_scroll_down(struct tog_view *view, int maxscroll)
5964 struct tog_tree_view_state *s = &view->state.tree;
5965 struct got_tree_entry *next, *last;
5966 int n = 0;
5968 if (s->first_displayed_entry)
5969 next = got_tree_entry_get_next(s->tree,
5970 s->first_displayed_entry);
5971 else
5972 next = got_object_tree_get_first_entry(s->tree);
5974 last = s->last_displayed_entry;
5975 while (next && n++ < maxscroll) {
5976 if (last)
5977 last = got_tree_entry_get_next(s->tree, last);
5978 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
5979 s->first_displayed_entry = next;
5980 next = got_tree_entry_get_next(s->tree, next);
5984 return NULL;
5987 static const struct got_error *
5988 tree_entry_path(char **path, struct tog_parent_trees *parents,
5989 struct got_tree_entry *te)
5991 const struct got_error *err = NULL;
5992 struct tog_parent_tree *pt;
5993 size_t len = 2; /* for leading slash and NUL */
5995 TAILQ_FOREACH(pt, parents, entry)
5996 len += strlen(got_tree_entry_get_name(pt->selected_entry))
5997 + 1 /* slash */;
5998 if (te)
5999 len += strlen(got_tree_entry_get_name(te));
6001 *path = calloc(1, len);
6002 if (path == NULL)
6003 return got_error_from_errno("calloc");
6005 (*path)[0] = '/';
6006 pt = TAILQ_LAST(parents, tog_parent_trees);
6007 while (pt) {
6008 const char *name = got_tree_entry_get_name(pt->selected_entry);
6009 if (strlcat(*path, name, len) >= len) {
6010 err = got_error(GOT_ERR_NO_SPACE);
6011 goto done;
6013 if (strlcat(*path, "/", len) >= len) {
6014 err = got_error(GOT_ERR_NO_SPACE);
6015 goto done;
6017 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6019 if (te) {
6020 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6021 err = got_error(GOT_ERR_NO_SPACE);
6022 goto done;
6025 done:
6026 if (err) {
6027 free(*path);
6028 *path = NULL;
6030 return err;
6033 static const struct got_error *
6034 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6035 struct got_tree_entry *te, struct tog_parent_trees *parents,
6036 struct got_object_id *commit_id, struct got_repository *repo)
6038 const struct got_error *err = NULL;
6039 char *path;
6040 struct tog_view *blame_view;
6042 *new_view = NULL;
6044 err = tree_entry_path(&path, parents, te);
6045 if (err)
6046 return err;
6048 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6049 if (blame_view == NULL) {
6050 err = got_error_from_errno("view_open");
6051 goto done;
6054 err = open_blame_view(blame_view, path, commit_id, repo);
6055 if (err) {
6056 if (err->code == GOT_ERR_CANCELLED)
6057 err = NULL;
6058 view_close(blame_view);
6059 } else
6060 *new_view = blame_view;
6061 done:
6062 free(path);
6063 return err;
6066 static const struct got_error *
6067 log_selected_tree_entry(struct tog_view **new_view, int begin_x,
6068 struct tog_tree_view_state *s)
6070 struct tog_view *log_view;
6071 const struct got_error *err = NULL;
6072 char *path;
6074 *new_view = NULL;
6076 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
6077 if (log_view == NULL)
6078 return got_error_from_errno("view_open");
6080 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6081 if (err)
6082 return err;
6084 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6085 path, 0);
6086 if (err)
6087 view_close(log_view);
6088 else
6089 *new_view = log_view;
6090 free(path);
6091 return err;
6094 static const struct got_error *
6095 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6096 const char *head_ref_name, struct got_repository *repo)
6098 const struct got_error *err = NULL;
6099 char *commit_id_str = NULL;
6100 struct tog_tree_view_state *s = &view->state.tree;
6101 struct got_commit_object *commit = NULL;
6103 TAILQ_INIT(&s->parents);
6104 STAILQ_INIT(&s->colors);
6106 s->commit_id = got_object_id_dup(commit_id);
6107 if (s->commit_id == NULL)
6108 return got_error_from_errno("got_object_id_dup");
6110 err = got_object_open_as_commit(&commit, repo, commit_id);
6111 if (err)
6112 goto done;
6115 * The root is opened here and will be closed when the view is closed.
6116 * Any visited subtrees and their path-wise parents are opened and
6117 * closed on demand.
6119 err = got_object_open_as_tree(&s->root, repo,
6120 got_object_commit_get_tree_id(commit));
6121 if (err)
6122 goto done;
6123 s->tree = s->root;
6125 err = got_object_id_str(&commit_id_str, commit_id);
6126 if (err != NULL)
6127 goto done;
6129 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6130 err = got_error_from_errno("asprintf");
6131 goto done;
6134 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6135 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6136 if (head_ref_name) {
6137 s->head_ref_name = strdup(head_ref_name);
6138 if (s->head_ref_name == NULL) {
6139 err = got_error_from_errno("strdup");
6140 goto done;
6143 s->repo = repo;
6145 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6146 err = add_color(&s->colors, "\\$$",
6147 TOG_COLOR_TREE_SUBMODULE,
6148 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6149 if (err)
6150 goto done;
6151 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6152 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6153 if (err)
6154 goto done;
6155 err = add_color(&s->colors, "/$",
6156 TOG_COLOR_TREE_DIRECTORY,
6157 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6158 if (err)
6159 goto done;
6161 err = add_color(&s->colors, "\\*$",
6162 TOG_COLOR_TREE_EXECUTABLE,
6163 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6164 if (err)
6165 goto done;
6167 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6168 get_color_value("TOG_COLOR_COMMIT"));
6169 if (err)
6170 goto done;
6173 view->show = show_tree_view;
6174 view->input = input_tree_view;
6175 view->close = close_tree_view;
6176 view->search_start = search_start_tree_view;
6177 view->search_next = search_next_tree_view;
6178 done:
6179 free(commit_id_str);
6180 if (commit)
6181 got_object_commit_close(commit);
6182 if (err)
6183 close_tree_view(view);
6184 return err;
6187 static const struct got_error *
6188 close_tree_view(struct tog_view *view)
6190 struct tog_tree_view_state *s = &view->state.tree;
6192 free_colors(&s->colors);
6193 free(s->tree_label);
6194 s->tree_label = NULL;
6195 free(s->commit_id);
6196 s->commit_id = NULL;
6197 free(s->head_ref_name);
6198 s->head_ref_name = NULL;
6199 while (!TAILQ_EMPTY(&s->parents)) {
6200 struct tog_parent_tree *parent;
6201 parent = TAILQ_FIRST(&s->parents);
6202 TAILQ_REMOVE(&s->parents, parent, entry);
6203 if (parent->tree != s->root)
6204 got_object_tree_close(parent->tree);
6205 free(parent);
6208 if (s->tree != NULL && s->tree != s->root)
6209 got_object_tree_close(s->tree);
6210 if (s->root)
6211 got_object_tree_close(s->root);
6212 return NULL;
6215 static const struct got_error *
6216 search_start_tree_view(struct tog_view *view)
6218 struct tog_tree_view_state *s = &view->state.tree;
6220 s->matched_entry = NULL;
6221 return NULL;
6224 static int
6225 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6227 regmatch_t regmatch;
6229 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6230 0) == 0;
6233 static const struct got_error *
6234 search_next_tree_view(struct tog_view *view)
6236 struct tog_tree_view_state *s = &view->state.tree;
6237 struct got_tree_entry *te = NULL;
6239 if (!view->searching) {
6240 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6241 return NULL;
6244 if (s->matched_entry) {
6245 if (view->searching == TOG_SEARCH_FORWARD) {
6246 if (s->selected_entry)
6247 te = got_tree_entry_get_next(s->tree,
6248 s->selected_entry);
6249 else
6250 te = got_object_tree_get_first_entry(s->tree);
6251 } else {
6252 if (s->selected_entry == NULL)
6253 te = got_object_tree_get_last_entry(s->tree);
6254 else
6255 te = got_tree_entry_get_prev(s->tree,
6256 s->selected_entry);
6258 } else {
6259 if (s->selected_entry)
6260 te = s->selected_entry;
6261 else if (view->searching == TOG_SEARCH_FORWARD)
6262 te = got_object_tree_get_first_entry(s->tree);
6263 else
6264 te = got_object_tree_get_last_entry(s->tree);
6267 while (1) {
6268 if (te == NULL) {
6269 if (s->matched_entry == NULL) {
6270 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6271 return NULL;
6273 if (view->searching == TOG_SEARCH_FORWARD)
6274 te = got_object_tree_get_first_entry(s->tree);
6275 else
6276 te = got_object_tree_get_last_entry(s->tree);
6279 if (match_tree_entry(te, &view->regex)) {
6280 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6281 s->matched_entry = te;
6282 break;
6285 if (view->searching == TOG_SEARCH_FORWARD)
6286 te = got_tree_entry_get_next(s->tree, te);
6287 else
6288 te = got_tree_entry_get_prev(s->tree, te);
6291 if (s->matched_entry) {
6292 s->first_displayed_entry = s->matched_entry;
6293 s->selected = 0;
6296 return NULL;
6299 static const struct got_error *
6300 show_tree_view(struct tog_view *view)
6302 const struct got_error *err = NULL;
6303 struct tog_tree_view_state *s = &view->state.tree;
6304 char *parent_path;
6306 err = tree_entry_path(&parent_path, &s->parents, NULL);
6307 if (err)
6308 return err;
6310 err = draw_tree_entries(view, parent_path);
6311 free(parent_path);
6313 view_border(view);
6314 return err;
6317 static const struct got_error *
6318 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6320 const struct got_error *err = NULL;
6321 struct tog_tree_view_state *s = &view->state.tree;
6322 struct tog_view *log_view, *ref_view;
6323 struct got_tree_entry *te;
6324 int begin_x = 0, n, nscroll = view->nlines - 3;
6326 switch (ch) {
6327 case 'i':
6328 s->show_ids = !s->show_ids;
6329 view->count = 0;
6330 break;
6331 case 'l':
6332 view->count = 0;
6333 if (!s->selected_entry)
6334 break;
6335 if (view_is_parent_view(view))
6336 begin_x = view_split_begin_x(view->begin_x);
6337 err = log_selected_tree_entry(&log_view, begin_x, s);
6338 view->focussed = 0;
6339 log_view->focussed = 1;
6340 if (view_is_parent_view(view)) {
6341 err = view_close_child(view);
6342 if (err)
6343 return err;
6344 err = view_set_child(view, log_view);
6345 if (err)
6346 return err;
6347 view->focus_child = 1;
6348 } else
6349 *new_view = log_view;
6350 break;
6351 case 'r':
6352 view->count = 0;
6353 if (view_is_parent_view(view))
6354 begin_x = view_split_begin_x(view->begin_x);
6355 ref_view = view_open(view->nlines, view->ncols,
6356 view->begin_y, begin_x, TOG_VIEW_REF);
6357 if (ref_view == NULL)
6358 return got_error_from_errno("view_open");
6359 err = open_ref_view(ref_view, s->repo);
6360 if (err) {
6361 view_close(ref_view);
6362 return err;
6364 view->focussed = 0;
6365 ref_view->focussed = 1;
6366 if (view_is_parent_view(view)) {
6367 err = view_close_child(view);
6368 if (err)
6369 return err;
6370 err = view_set_child(view, ref_view);
6371 if (err)
6372 return err;
6373 view->focus_child = 1;
6374 } else
6375 *new_view = ref_view;
6376 break;
6377 case 'g':
6378 case KEY_HOME:
6379 s->selected = 0;
6380 view->count = 0;
6381 if (s->tree == s->root)
6382 s->first_displayed_entry =
6383 got_object_tree_get_first_entry(s->tree);
6384 else
6385 s->first_displayed_entry = NULL;
6386 break;
6387 case 'G':
6388 case KEY_END: {
6389 int eos = view->nlines - 3;
6391 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6392 --eos; /* border */
6393 s->selected = 0;
6394 view->count = 0;
6395 te = got_object_tree_get_last_entry(s->tree);
6396 for (n = 0; n < eos; n++) {
6397 if (te == NULL) {
6398 if(s->tree != s->root) {
6399 s->first_displayed_entry = NULL;
6400 n++;
6402 break;
6404 s->first_displayed_entry = te;
6405 te = got_tree_entry_get_prev(s->tree, te);
6407 if (n > 0)
6408 s->selected = n - 1;
6409 break;
6411 case 'k':
6412 case KEY_UP:
6413 case CTRL('p'):
6414 if (s->selected > 0) {
6415 s->selected--;
6416 break;
6418 tree_scroll_up(s, 1);
6419 if (s->selected_entry == NULL ||
6420 (s->tree == s->root && s->selected_entry ==
6421 got_object_tree_get_first_entry(s->tree)))
6422 view->count = 0;
6423 break;
6424 case CTRL('u'):
6425 case 'u':
6426 nscroll /= 2;
6427 /* FALL THROUGH */
6428 case KEY_PPAGE:
6429 case CTRL('b'):
6430 case 'b':
6431 if (s->tree == s->root) {
6432 if (got_object_tree_get_first_entry(s->tree) ==
6433 s->first_displayed_entry)
6434 s->selected -= MIN(s->selected, nscroll);
6435 } else {
6436 if (s->first_displayed_entry == NULL)
6437 s->selected -= MIN(s->selected, nscroll);
6439 tree_scroll_up(s, MAX(0, nscroll));
6440 if (s->selected_entry == NULL ||
6441 (s->tree == s->root && s->selected_entry ==
6442 got_object_tree_get_first_entry(s->tree)))
6443 view->count = 0;
6444 break;
6445 case 'j':
6446 case KEY_DOWN:
6447 case CTRL('n'):
6448 if (s->selected < s->ndisplayed - 1) {
6449 s->selected++;
6450 break;
6452 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6453 == NULL) {
6454 /* can't scroll any further */
6455 view->count = 0;
6456 break;
6458 tree_scroll_down(view, 1);
6459 break;
6460 case CTRL('d'):
6461 case 'd':
6462 nscroll /= 2;
6463 /* FALL THROUGH */
6464 case KEY_NPAGE:
6465 case CTRL('f'):
6466 case 'f':
6467 case ' ':
6468 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6469 == NULL) {
6470 /* can't scroll any further; move cursor down */
6471 if (s->selected < s->ndisplayed - 1)
6472 s->selected += MIN(nscroll,
6473 s->ndisplayed - s->selected - 1);
6474 else
6475 view->count = 0;
6476 break;
6478 tree_scroll_down(view, nscroll);
6479 break;
6480 case KEY_ENTER:
6481 case '\r':
6482 case KEY_BACKSPACE:
6483 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6484 struct tog_parent_tree *parent;
6485 /* user selected '..' */
6486 if (s->tree == s->root) {
6487 view->count = 0;
6488 break;
6490 parent = TAILQ_FIRST(&s->parents);
6491 TAILQ_REMOVE(&s->parents, parent,
6492 entry);
6493 got_object_tree_close(s->tree);
6494 s->tree = parent->tree;
6495 s->first_displayed_entry =
6496 parent->first_displayed_entry;
6497 s->selected_entry =
6498 parent->selected_entry;
6499 s->selected = parent->selected;
6500 if (s->selected > view->nlines - 3) {
6501 err = offset_selection_down(view);
6502 if (err)
6503 break;
6505 free(parent);
6506 } else if (S_ISDIR(got_tree_entry_get_mode(
6507 s->selected_entry))) {
6508 struct got_tree_object *subtree;
6509 view->count = 0;
6510 err = got_object_open_as_tree(&subtree, s->repo,
6511 got_tree_entry_get_id(s->selected_entry));
6512 if (err)
6513 break;
6514 err = tree_view_visit_subtree(s, subtree);
6515 if (err) {
6516 got_object_tree_close(subtree);
6517 break;
6519 } else if (S_ISREG(got_tree_entry_get_mode(
6520 s->selected_entry))) {
6521 struct tog_view *blame_view;
6522 int begin_x = 0, begin_y = 0;
6524 if (view_is_parent_view(view))
6525 view_get_split(view, &begin_y, &begin_x);
6527 err = blame_tree_entry(&blame_view, begin_y, begin_x,
6528 s->selected_entry, &s->parents,
6529 s->commit_id, s->repo);
6530 if (err)
6531 break;
6533 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
6534 err = view_init_hsplit(view, begin_y);
6535 if (err)
6536 break;
6539 view->count = 0;
6540 view->focussed = 0;
6541 blame_view->focussed = 1;
6542 blame_view->mode = view->mode;
6543 blame_view->nlines = view->lines - begin_y;
6544 if (view_is_parent_view(view)) {
6545 err = view_close_child(view);
6546 if (err)
6547 return err;
6548 err = view_set_child(view, blame_view);
6549 if (err)
6550 return err;
6551 view->focus_child = 1;
6552 } else
6553 *new_view = blame_view;
6555 break;
6556 case KEY_RESIZE:
6557 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6558 s->selected = view->nlines - 4;
6559 view->count = 0;
6560 break;
6561 default:
6562 view->count = 0;
6563 break;
6566 return err;
6569 __dead static void
6570 usage_tree(void)
6572 endwin();
6573 fprintf(stderr,
6574 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6575 getprogname());
6576 exit(1);
6579 static const struct got_error *
6580 cmd_tree(int argc, char *argv[])
6582 const struct got_error *error;
6583 struct got_repository *repo = NULL;
6584 struct got_worktree *worktree = NULL;
6585 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6586 struct got_object_id *commit_id = NULL;
6587 struct got_commit_object *commit = NULL;
6588 const char *commit_id_arg = NULL;
6589 char *label = NULL;
6590 struct got_reference *ref = NULL;
6591 const char *head_ref_name = NULL;
6592 int ch;
6593 struct tog_view *view;
6594 int *pack_fds = NULL;
6596 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6597 switch (ch) {
6598 case 'c':
6599 commit_id_arg = optarg;
6600 break;
6601 case 'r':
6602 repo_path = realpath(optarg, NULL);
6603 if (repo_path == NULL)
6604 return got_error_from_errno2("realpath",
6605 optarg);
6606 break;
6607 default:
6608 usage_tree();
6609 /* NOTREACHED */
6613 argc -= optind;
6614 argv += optind;
6616 if (argc > 1)
6617 usage_tree();
6619 error = got_repo_pack_fds_open(&pack_fds);
6620 if (error != NULL)
6621 goto done;
6623 if (repo_path == NULL) {
6624 cwd = getcwd(NULL, 0);
6625 if (cwd == NULL)
6626 return got_error_from_errno("getcwd");
6627 error = got_worktree_open(&worktree, cwd);
6628 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6629 goto done;
6630 if (worktree)
6631 repo_path =
6632 strdup(got_worktree_get_repo_path(worktree));
6633 else
6634 repo_path = strdup(cwd);
6635 if (repo_path == NULL) {
6636 error = got_error_from_errno("strdup");
6637 goto done;
6641 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6642 if (error != NULL)
6643 goto done;
6645 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
6646 repo, worktree);
6647 if (error)
6648 goto done;
6650 init_curses();
6652 error = apply_unveil(got_repo_get_path(repo), NULL);
6653 if (error)
6654 goto done;
6656 error = tog_load_refs(repo, 0);
6657 if (error)
6658 goto done;
6660 if (commit_id_arg == NULL) {
6661 error = got_repo_match_object_id(&commit_id, &label,
6662 worktree ? got_worktree_get_head_ref_name(worktree) :
6663 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6664 if (error)
6665 goto done;
6666 head_ref_name = label;
6667 } else {
6668 error = got_ref_open(&ref, repo, commit_id_arg, 0);
6669 if (error == NULL)
6670 head_ref_name = got_ref_get_name(ref);
6671 else if (error->code != GOT_ERR_NOT_REF)
6672 goto done;
6673 error = got_repo_match_object_id(&commit_id, NULL,
6674 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6675 if (error)
6676 goto done;
6679 error = got_object_open_as_commit(&commit, repo, commit_id);
6680 if (error)
6681 goto done;
6683 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
6684 if (view == NULL) {
6685 error = got_error_from_errno("view_open");
6686 goto done;
6688 error = open_tree_view(view, commit_id, head_ref_name, repo);
6689 if (error)
6690 goto done;
6691 if (!got_path_is_root_dir(in_repo_path)) {
6692 error = tree_view_walk_path(&view->state.tree, commit,
6693 in_repo_path);
6694 if (error)
6695 goto done;
6698 if (worktree) {
6699 /* Release work tree lock. */
6700 got_worktree_close(worktree);
6701 worktree = NULL;
6703 error = view_loop(view);
6704 done:
6705 free(repo_path);
6706 free(cwd);
6707 free(commit_id);
6708 free(label);
6709 if (ref)
6710 got_ref_close(ref);
6711 if (repo) {
6712 const struct got_error *close_err = got_repo_close(repo);
6713 if (error == NULL)
6714 error = close_err;
6716 if (pack_fds) {
6717 const struct got_error *pack_err =
6718 got_repo_pack_fds_close(pack_fds);
6719 if (error == NULL)
6720 error = pack_err;
6722 tog_free_refs();
6723 return error;
6726 static const struct got_error *
6727 ref_view_load_refs(struct tog_ref_view_state *s)
6729 struct got_reflist_entry *sre;
6730 struct tog_reflist_entry *re;
6732 s->nrefs = 0;
6733 TAILQ_FOREACH(sre, &tog_refs, entry) {
6734 if (strncmp(got_ref_get_name(sre->ref),
6735 "refs/got/", 9) == 0 &&
6736 strncmp(got_ref_get_name(sre->ref),
6737 "refs/got/backup/", 16) != 0)
6738 continue;
6740 re = malloc(sizeof(*re));
6741 if (re == NULL)
6742 return got_error_from_errno("malloc");
6744 re->ref = got_ref_dup(sre->ref);
6745 if (re->ref == NULL)
6746 return got_error_from_errno("got_ref_dup");
6747 re->idx = s->nrefs++;
6748 TAILQ_INSERT_TAIL(&s->refs, re, entry);
6751 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6752 return NULL;
6755 static void
6756 ref_view_free_refs(struct tog_ref_view_state *s)
6758 struct tog_reflist_entry *re;
6760 while (!TAILQ_EMPTY(&s->refs)) {
6761 re = TAILQ_FIRST(&s->refs);
6762 TAILQ_REMOVE(&s->refs, re, entry);
6763 got_ref_close(re->ref);
6764 free(re);
6768 static const struct got_error *
6769 open_ref_view(struct tog_view *view, struct got_repository *repo)
6771 const struct got_error *err = NULL;
6772 struct tog_ref_view_state *s = &view->state.ref;
6774 s->selected_entry = 0;
6775 s->repo = repo;
6777 TAILQ_INIT(&s->refs);
6778 STAILQ_INIT(&s->colors);
6780 err = ref_view_load_refs(s);
6781 if (err)
6782 return err;
6784 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6785 err = add_color(&s->colors, "^refs/heads/",
6786 TOG_COLOR_REFS_HEADS,
6787 get_color_value("TOG_COLOR_REFS_HEADS"));
6788 if (err)
6789 goto done;
6791 err = add_color(&s->colors, "^refs/tags/",
6792 TOG_COLOR_REFS_TAGS,
6793 get_color_value("TOG_COLOR_REFS_TAGS"));
6794 if (err)
6795 goto done;
6797 err = add_color(&s->colors, "^refs/remotes/",
6798 TOG_COLOR_REFS_REMOTES,
6799 get_color_value("TOG_COLOR_REFS_REMOTES"));
6800 if (err)
6801 goto done;
6803 err = add_color(&s->colors, "^refs/got/backup/",
6804 TOG_COLOR_REFS_BACKUP,
6805 get_color_value("TOG_COLOR_REFS_BACKUP"));
6806 if (err)
6807 goto done;
6810 view->show = show_ref_view;
6811 view->input = input_ref_view;
6812 view->close = close_ref_view;
6813 view->search_start = search_start_ref_view;
6814 view->search_next = search_next_ref_view;
6815 done:
6816 if (err)
6817 free_colors(&s->colors);
6818 return err;
6821 static const struct got_error *
6822 close_ref_view(struct tog_view *view)
6824 struct tog_ref_view_state *s = &view->state.ref;
6826 ref_view_free_refs(s);
6827 free_colors(&s->colors);
6829 return NULL;
6832 static const struct got_error *
6833 resolve_reflist_entry(struct got_object_id **commit_id,
6834 struct tog_reflist_entry *re, struct got_repository *repo)
6836 const struct got_error *err = NULL;
6837 struct got_object_id *obj_id;
6838 struct got_tag_object *tag = NULL;
6839 int obj_type;
6841 *commit_id = NULL;
6843 err = got_ref_resolve(&obj_id, repo, re->ref);
6844 if (err)
6845 return err;
6847 err = got_object_get_type(&obj_type, repo, obj_id);
6848 if (err)
6849 goto done;
6851 switch (obj_type) {
6852 case GOT_OBJ_TYPE_COMMIT:
6853 *commit_id = obj_id;
6854 break;
6855 case GOT_OBJ_TYPE_TAG:
6856 err = got_object_open_as_tag(&tag, repo, obj_id);
6857 if (err)
6858 goto done;
6859 free(obj_id);
6860 err = got_object_get_type(&obj_type, repo,
6861 got_object_tag_get_object_id(tag));
6862 if (err)
6863 goto done;
6864 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
6865 err = got_error(GOT_ERR_OBJ_TYPE);
6866 goto done;
6868 *commit_id = got_object_id_dup(
6869 got_object_tag_get_object_id(tag));
6870 if (*commit_id == NULL) {
6871 err = got_error_from_errno("got_object_id_dup");
6872 goto done;
6874 break;
6875 default:
6876 err = got_error(GOT_ERR_OBJ_TYPE);
6877 break;
6880 done:
6881 if (tag)
6882 got_object_tag_close(tag);
6883 if (err) {
6884 free(*commit_id);
6885 *commit_id = NULL;
6887 return err;
6890 static const struct got_error *
6891 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
6892 struct tog_reflist_entry *re, struct got_repository *repo)
6894 struct tog_view *log_view;
6895 const struct got_error *err = NULL;
6896 struct got_object_id *commit_id = NULL;
6898 *new_view = NULL;
6900 err = resolve_reflist_entry(&commit_id, re, repo);
6901 if (err) {
6902 if (err->code != GOT_ERR_OBJ_TYPE)
6903 return err;
6904 else
6905 return NULL;
6908 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6909 if (log_view == NULL) {
6910 err = got_error_from_errno("view_open");
6911 goto done;
6914 err = open_log_view(log_view, commit_id, repo,
6915 got_ref_get_name(re->ref), "", 0);
6916 done:
6917 if (err)
6918 view_close(log_view);
6919 else
6920 *new_view = log_view;
6921 free(commit_id);
6922 return err;
6925 static void
6926 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
6928 struct tog_reflist_entry *re;
6929 int i = 0;
6931 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
6932 return;
6934 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
6935 while (i++ < maxscroll) {
6936 if (re == NULL)
6937 break;
6938 s->first_displayed_entry = re;
6939 re = TAILQ_PREV(re, tog_reflist_head, entry);
6943 static const struct got_error *
6944 ref_scroll_down(struct tog_view *view, int maxscroll)
6946 struct tog_ref_view_state *s = &view->state.ref;
6947 struct tog_reflist_entry *next, *last;
6948 int n = 0;
6950 if (s->first_displayed_entry)
6951 next = TAILQ_NEXT(s->first_displayed_entry, entry);
6952 else
6953 next = TAILQ_FIRST(&s->refs);
6955 last = s->last_displayed_entry;
6956 while (next && n++ < maxscroll) {
6957 if (last)
6958 last = TAILQ_NEXT(last, entry);
6959 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
6960 s->first_displayed_entry = next;
6961 next = TAILQ_NEXT(next, entry);
6965 return NULL;
6968 static const struct got_error *
6969 search_start_ref_view(struct tog_view *view)
6971 struct tog_ref_view_state *s = &view->state.ref;
6973 s->matched_entry = NULL;
6974 return NULL;
6977 static int
6978 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
6980 regmatch_t regmatch;
6982 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
6983 0) == 0;
6986 static const struct got_error *
6987 search_next_ref_view(struct tog_view *view)
6989 struct tog_ref_view_state *s = &view->state.ref;
6990 struct tog_reflist_entry *re = NULL;
6992 if (!view->searching) {
6993 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6994 return NULL;
6997 if (s->matched_entry) {
6998 if (view->searching == TOG_SEARCH_FORWARD) {
6999 if (s->selected_entry)
7000 re = TAILQ_NEXT(s->selected_entry, entry);
7001 else
7002 re = TAILQ_PREV(s->selected_entry,
7003 tog_reflist_head, entry);
7004 } else {
7005 if (s->selected_entry == NULL)
7006 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7007 else
7008 re = TAILQ_PREV(s->selected_entry,
7009 tog_reflist_head, entry);
7011 } else {
7012 if (s->selected_entry)
7013 re = s->selected_entry;
7014 else if (view->searching == TOG_SEARCH_FORWARD)
7015 re = TAILQ_FIRST(&s->refs);
7016 else
7017 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7020 while (1) {
7021 if (re == NULL) {
7022 if (s->matched_entry == NULL) {
7023 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7024 return NULL;
7026 if (view->searching == TOG_SEARCH_FORWARD)
7027 re = TAILQ_FIRST(&s->refs);
7028 else
7029 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7032 if (match_reflist_entry(re, &view->regex)) {
7033 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7034 s->matched_entry = re;
7035 break;
7038 if (view->searching == TOG_SEARCH_FORWARD)
7039 re = TAILQ_NEXT(re, entry);
7040 else
7041 re = TAILQ_PREV(re, tog_reflist_head, entry);
7044 if (s->matched_entry) {
7045 s->first_displayed_entry = s->matched_entry;
7046 s->selected = 0;
7049 return NULL;
7052 static const struct got_error *
7053 show_ref_view(struct tog_view *view)
7055 const struct got_error *err = NULL;
7056 struct tog_ref_view_state *s = &view->state.ref;
7057 struct tog_reflist_entry *re;
7058 char *line = NULL;
7059 wchar_t *wline;
7060 struct tog_color *tc;
7061 int width, n;
7062 int limit = view->nlines;
7064 werase(view->window);
7066 s->ndisplayed = 0;
7067 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
7068 view_is_splitscreen(view->child))
7069 --limit; /* border */
7071 if (limit == 0)
7072 return NULL;
7074 re = s->first_displayed_entry;
7076 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7077 s->nrefs) == -1)
7078 return got_error_from_errno("asprintf");
7080 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7081 if (err) {
7082 free(line);
7083 return err;
7085 if (view_needs_focus_indication(view))
7086 wstandout(view->window);
7087 waddwstr(view->window, wline);
7088 if (view_needs_focus_indication(view))
7089 wstandend(view->window);
7090 free(wline);
7091 wline = NULL;
7092 free(line);
7093 line = NULL;
7094 if (width < view->ncols - 1)
7095 waddch(view->window, '\n');
7096 if (--limit <= 0)
7097 return NULL;
7099 n = 0;
7100 while (re && limit > 0) {
7101 char *line = NULL;
7102 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7104 if (s->show_date) {
7105 struct got_commit_object *ci;
7106 struct got_tag_object *tag;
7107 struct got_object_id *id;
7108 struct tm tm;
7109 time_t t;
7111 err = got_ref_resolve(&id, s->repo, re->ref);
7112 if (err)
7113 return err;
7114 err = got_object_open_as_tag(&tag, s->repo, id);
7115 if (err) {
7116 if (err->code != GOT_ERR_OBJ_TYPE) {
7117 free(id);
7118 return err;
7120 err = got_object_open_as_commit(&ci, s->repo,
7121 id);
7122 if (err) {
7123 free(id);
7124 return err;
7126 t = got_object_commit_get_committer_time(ci);
7127 got_object_commit_close(ci);
7128 } else {
7129 t = got_object_tag_get_tagger_time(tag);
7130 got_object_tag_close(tag);
7132 free(id);
7133 if (gmtime_r(&t, &tm) == NULL)
7134 return got_error_from_errno("gmtime_r");
7135 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7136 return got_error(GOT_ERR_NO_SPACE);
7138 if (got_ref_is_symbolic(re->ref)) {
7139 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7140 ymd : "", got_ref_get_name(re->ref),
7141 got_ref_get_symref_target(re->ref)) == -1)
7142 return got_error_from_errno("asprintf");
7143 } else if (s->show_ids) {
7144 struct got_object_id *id;
7145 char *id_str;
7146 err = got_ref_resolve(&id, s->repo, re->ref);
7147 if (err)
7148 return err;
7149 err = got_object_id_str(&id_str, id);
7150 if (err) {
7151 free(id);
7152 return err;
7154 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7155 got_ref_get_name(re->ref), id_str) == -1) {
7156 err = got_error_from_errno("asprintf");
7157 free(id);
7158 free(id_str);
7159 return err;
7161 free(id);
7162 free(id_str);
7163 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7164 got_ref_get_name(re->ref)) == -1)
7165 return got_error_from_errno("asprintf");
7167 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7168 0, 0);
7169 if (err) {
7170 free(line);
7171 return err;
7173 if (n == s->selected) {
7174 if (view->focussed)
7175 wstandout(view->window);
7176 s->selected_entry = re;
7178 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7179 if (tc)
7180 wattr_on(view->window,
7181 COLOR_PAIR(tc->colorpair), NULL);
7182 waddwstr(view->window, wline);
7183 if (tc)
7184 wattr_off(view->window,
7185 COLOR_PAIR(tc->colorpair), NULL);
7186 if (width < view->ncols - 1)
7187 waddch(view->window, '\n');
7188 if (n == s->selected && view->focussed)
7189 wstandend(view->window);
7190 free(line);
7191 free(wline);
7192 wline = NULL;
7193 n++;
7194 s->ndisplayed++;
7195 s->last_displayed_entry = re;
7197 limit--;
7198 re = TAILQ_NEXT(re, entry);
7201 view_border(view);
7202 return err;
7205 static const struct got_error *
7206 browse_ref_tree(struct tog_view **new_view, int begin_x,
7207 struct tog_reflist_entry *re, struct got_repository *repo)
7209 const struct got_error *err = NULL;
7210 struct got_object_id *commit_id = NULL;
7211 struct tog_view *tree_view;
7213 *new_view = NULL;
7215 err = resolve_reflist_entry(&commit_id, re, repo);
7216 if (err) {
7217 if (err->code != GOT_ERR_OBJ_TYPE)
7218 return err;
7219 else
7220 return NULL;
7224 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
7225 if (tree_view == NULL) {
7226 err = got_error_from_errno("view_open");
7227 goto done;
7230 err = open_tree_view(tree_view, commit_id,
7231 got_ref_get_name(re->ref), repo);
7232 if (err)
7233 goto done;
7235 *new_view = tree_view;
7236 done:
7237 free(commit_id);
7238 return err;
7240 static const struct got_error *
7241 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7243 const struct got_error *err = NULL;
7244 struct tog_ref_view_state *s = &view->state.ref;
7245 struct tog_view *log_view, *tree_view;
7246 struct tog_reflist_entry *re;
7247 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 1;
7249 switch (ch) {
7250 case 'i':
7251 s->show_ids = !s->show_ids;
7252 view->count = 0;
7253 break;
7254 case 'm':
7255 s->show_date = !s->show_date;
7256 view->count = 0;
7257 break;
7258 case 'o':
7259 s->sort_by_date = !s->sort_by_date;
7260 view->count = 0;
7261 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7262 got_ref_cmp_by_commit_timestamp_descending :
7263 tog_ref_cmp_by_name, s->repo);
7264 if (err)
7265 break;
7266 got_reflist_object_id_map_free(tog_refs_idmap);
7267 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7268 &tog_refs, s->repo);
7269 if (err)
7270 break;
7271 ref_view_free_refs(s);
7272 err = ref_view_load_refs(s);
7273 break;
7274 case KEY_ENTER:
7275 case '\r':
7276 view->count = 0;
7277 if (!s->selected_entry)
7278 break;
7279 if (view_is_parent_view(view))
7280 view_get_split(view, &begin_y, &begin_x);
7282 err = log_ref_entry(&log_view, begin_y, begin_x,
7283 s->selected_entry, s->repo);
7284 if (err)
7285 break;
7287 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
7288 err = view_init_hsplit(view, begin_y);
7289 if (err)
7290 break;
7293 view->focussed = 0;
7294 log_view->focussed = 1;
7295 log_view->mode = view->mode;
7296 log_view->nlines = view->lines - begin_y;
7297 if (view_is_parent_view(view)) {
7298 err = view_close_child(view);
7299 if (err)
7300 return err;
7301 err = view_set_child(view, log_view);
7302 if (err)
7303 return err;
7304 view->focus_child = 1;
7305 } else
7306 *new_view = log_view;
7307 break;
7308 case 't':
7309 view->count = 0;
7310 if (!s->selected_entry)
7311 break;
7312 if (view_is_parent_view(view))
7313 begin_x = view_split_begin_x(view->begin_x);
7314 err = browse_ref_tree(&tree_view, begin_x, s->selected_entry,
7315 s->repo);
7316 if (err || tree_view == NULL)
7317 break;
7318 view->focussed = 0;
7319 tree_view->focussed = 1;
7320 if (view_is_parent_view(view)) {
7321 err = view_close_child(view);
7322 if (err)
7323 return err;
7324 err = view_set_child(view, tree_view);
7325 if (err)
7326 return err;
7327 view->focus_child = 1;
7328 } else
7329 *new_view = tree_view;
7330 break;
7331 case 'g':
7332 case KEY_HOME:
7333 s->selected = 0;
7334 view->count = 0;
7335 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7336 break;
7337 case 'G':
7338 case KEY_END: {
7339 int eos = view->nlines - 1;
7341 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7342 --eos; /* border */
7343 s->selected = 0;
7344 view->count = 0;
7345 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7346 for (n = 0; n < eos; n++) {
7347 if (re == NULL)
7348 break;
7349 s->first_displayed_entry = re;
7350 re = TAILQ_PREV(re, tog_reflist_head, entry);
7352 if (n > 0)
7353 s->selected = n - 1;
7354 break;
7356 case 'k':
7357 case KEY_UP:
7358 case CTRL('p'):
7359 if (s->selected > 0) {
7360 s->selected--;
7361 break;
7363 ref_scroll_up(s, 1);
7364 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7365 view->count = 0;
7366 break;
7367 case CTRL('u'):
7368 case 'u':
7369 nscroll /= 2;
7370 /* FALL THROUGH */
7371 case KEY_PPAGE:
7372 case CTRL('b'):
7373 case 'b':
7374 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7375 s->selected -= MIN(nscroll, s->selected);
7376 ref_scroll_up(s, MAX(0, nscroll));
7377 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7378 view->count = 0;
7379 break;
7380 case 'j':
7381 case KEY_DOWN:
7382 case CTRL('n'):
7383 if (s->selected < s->ndisplayed - 1) {
7384 s->selected++;
7385 break;
7387 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7388 /* can't scroll any further */
7389 view->count = 0;
7390 break;
7392 ref_scroll_down(view, 1);
7393 break;
7394 case CTRL('d'):
7395 case 'd':
7396 nscroll /= 2;
7397 /* FALL THROUGH */
7398 case KEY_NPAGE:
7399 case CTRL('f'):
7400 case 'f':
7401 case ' ':
7402 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7403 /* can't scroll any further; move cursor down */
7404 if (s->selected < s->ndisplayed - 1)
7405 s->selected += MIN(nscroll,
7406 s->ndisplayed - s->selected - 1);
7407 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7408 s->selected += s->ndisplayed - s->selected - 1;
7409 view->count = 0;
7410 break;
7412 ref_scroll_down(view, nscroll);
7413 break;
7414 case CTRL('l'):
7415 view->count = 0;
7416 tog_free_refs();
7417 err = tog_load_refs(s->repo, s->sort_by_date);
7418 if (err)
7419 break;
7420 ref_view_free_refs(s);
7421 err = ref_view_load_refs(s);
7422 break;
7423 case KEY_RESIZE:
7424 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7425 s->selected = view->nlines - 2;
7426 break;
7427 default:
7428 view->count = 0;
7429 break;
7432 return err;
7435 __dead static void
7436 usage_ref(void)
7438 endwin();
7439 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7440 getprogname());
7441 exit(1);
7444 static const struct got_error *
7445 cmd_ref(int argc, char *argv[])
7447 const struct got_error *error;
7448 struct got_repository *repo = NULL;
7449 struct got_worktree *worktree = NULL;
7450 char *cwd = NULL, *repo_path = NULL;
7451 int ch;
7452 struct tog_view *view;
7453 int *pack_fds = NULL;
7455 while ((ch = getopt(argc, argv, "r:")) != -1) {
7456 switch (ch) {
7457 case 'r':
7458 repo_path = realpath(optarg, NULL);
7459 if (repo_path == NULL)
7460 return got_error_from_errno2("realpath",
7461 optarg);
7462 break;
7463 default:
7464 usage_ref();
7465 /* NOTREACHED */
7469 argc -= optind;
7470 argv += optind;
7472 if (argc > 1)
7473 usage_ref();
7475 error = got_repo_pack_fds_open(&pack_fds);
7476 if (error != NULL)
7477 goto done;
7479 if (repo_path == NULL) {
7480 cwd = getcwd(NULL, 0);
7481 if (cwd == NULL)
7482 return got_error_from_errno("getcwd");
7483 error = got_worktree_open(&worktree, cwd);
7484 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7485 goto done;
7486 if (worktree)
7487 repo_path =
7488 strdup(got_worktree_get_repo_path(worktree));
7489 else
7490 repo_path = strdup(cwd);
7491 if (repo_path == NULL) {
7492 error = got_error_from_errno("strdup");
7493 goto done;
7497 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7498 if (error != NULL)
7499 goto done;
7501 init_curses();
7503 error = apply_unveil(got_repo_get_path(repo), NULL);
7504 if (error)
7505 goto done;
7507 error = tog_load_refs(repo, 0);
7508 if (error)
7509 goto done;
7511 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7512 if (view == NULL) {
7513 error = got_error_from_errno("view_open");
7514 goto done;
7517 error = open_ref_view(view, repo);
7518 if (error)
7519 goto done;
7521 if (worktree) {
7522 /* Release work tree lock. */
7523 got_worktree_close(worktree);
7524 worktree = NULL;
7526 error = view_loop(view);
7527 done:
7528 free(repo_path);
7529 free(cwd);
7530 if (repo) {
7531 const struct got_error *close_err = got_repo_close(repo);
7532 if (close_err)
7533 error = close_err;
7535 if (pack_fds) {
7536 const struct got_error *pack_err =
7537 got_repo_pack_fds_close(pack_fds);
7538 if (error == NULL)
7539 error = pack_err;
7541 tog_free_refs();
7542 return error;
7546 * If view was scrolled down to move the selected line into view when opening a
7547 * horizontal split, scroll back up when closing the split/toggling fullscreen.
7549 static void
7550 offset_selection_up(struct tog_view *view)
7552 switch (view->type) {
7553 case TOG_VIEW_BLAME: {
7554 struct tog_blame_view_state *s = &view->state.blame;
7555 if (s->first_displayed_line == 1) {
7556 s->selected_line = MAX(s->selected_line - view->offset,
7557 1);
7558 break;
7560 if (s->first_displayed_line > view->offset)
7561 s->first_displayed_line -= view->offset;
7562 else
7563 s->first_displayed_line = 1;
7564 s->selected_line += view->offset;
7565 break;
7567 case TOG_VIEW_LOG:
7568 log_scroll_up(&view->state.log, view->offset);
7569 view->state.log.selected += view->offset;
7570 break;
7571 case TOG_VIEW_REF:
7572 ref_scroll_up(&view->state.ref, view->offset);
7573 view->state.ref.selected += view->offset;
7574 break;
7575 case TOG_VIEW_TREE:
7576 tree_scroll_up(&view->state.tree, view->offset);
7577 view->state.tree.selected += view->offset;
7578 break;
7579 default:
7580 break;
7583 view->offset = 0;
7587 * If the selected line is in the section of screen covered by the bottom split,
7588 * scroll down offset lines to move it into view and index its new position.
7590 static const struct got_error *
7591 offset_selection_down(struct tog_view *view)
7593 const struct got_error *err = NULL;
7594 const struct got_error *(*scrolld)(struct tog_view *, int);
7595 int *selected = NULL;
7596 int header, offset;
7598 switch (view->type) {
7599 case TOG_VIEW_BLAME: {
7600 struct tog_blame_view_state *s = &view->state.blame;
7601 header = 3;
7602 scrolld = NULL;
7603 if (s->selected_line > view->nlines - header) {
7604 offset = abs(view->nlines - s->selected_line - header);
7605 s->first_displayed_line += offset;
7606 s->selected_line -= offset;
7607 view->offset = offset;
7609 break;
7611 case TOG_VIEW_LOG: {
7612 struct tog_log_view_state *s = &view->state.log;
7613 scrolld = &log_scroll_down;
7614 header = 3;
7615 selected = &s->selected;
7616 break;
7618 case TOG_VIEW_REF: {
7619 struct tog_ref_view_state *s = &view->state.ref;
7620 scrolld = &ref_scroll_down;
7621 header = 3;
7622 selected = &s->selected;
7623 break;
7625 case TOG_VIEW_TREE: {
7626 struct tog_tree_view_state *s = &view->state.tree;
7627 scrolld = &tree_scroll_down;
7628 header = 5;
7629 selected = &s->selected;
7630 break;
7632 default:
7633 selected = NULL;
7634 scrolld = NULL;
7635 header = 0;
7636 break;
7639 if (selected && *selected > view->nlines - header) {
7640 offset = abs(view->nlines - *selected - header);
7641 view->offset = offset;
7642 if (scrolld && offset) {
7643 err = scrolld(view, offset);
7644 *selected -= offset;
7648 return err;
7651 static void
7652 list_commands(FILE *fp)
7654 size_t i;
7656 fprintf(fp, "commands:");
7657 for (i = 0; i < nitems(tog_commands); i++) {
7658 const struct tog_cmd *cmd = &tog_commands[i];
7659 fprintf(fp, " %s", cmd->name);
7661 fputc('\n', fp);
7664 __dead static void
7665 usage(int hflag, int status)
7667 FILE *fp = (status == 0) ? stdout : stderr;
7669 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
7670 getprogname());
7671 if (hflag) {
7672 fprintf(fp, "lazy usage: %s path\n", getprogname());
7673 list_commands(fp);
7675 exit(status);
7678 static char **
7679 make_argv(int argc, ...)
7681 va_list ap;
7682 char **argv;
7683 int i;
7685 va_start(ap, argc);
7687 argv = calloc(argc, sizeof(char *));
7688 if (argv == NULL)
7689 err(1, "calloc");
7690 for (i = 0; i < argc; i++) {
7691 argv[i] = strdup(va_arg(ap, char *));
7692 if (argv[i] == NULL)
7693 err(1, "strdup");
7696 va_end(ap);
7697 return argv;
7701 * Try to convert 'tog path' into a 'tog log path' command.
7702 * The user could simply have mistyped the command rather than knowingly
7703 * provided a path. So check whether argv[0] can in fact be resolved
7704 * to a path in the HEAD commit and print a special error if not.
7705 * This hack is for mpi@ <3
7707 static const struct got_error *
7708 tog_log_with_path(int argc, char *argv[])
7710 const struct got_error *error = NULL, *close_err;
7711 const struct tog_cmd *cmd = NULL;
7712 struct got_repository *repo = NULL;
7713 struct got_worktree *worktree = NULL;
7714 struct got_object_id *commit_id = NULL, *id = NULL;
7715 struct got_commit_object *commit = NULL;
7716 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7717 char *commit_id_str = NULL, **cmd_argv = NULL;
7718 int *pack_fds = NULL;
7720 cwd = getcwd(NULL, 0);
7721 if (cwd == NULL)
7722 return got_error_from_errno("getcwd");
7724 error = got_repo_pack_fds_open(&pack_fds);
7725 if (error != NULL)
7726 goto done;
7728 error = got_worktree_open(&worktree, cwd);
7729 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7730 goto done;
7732 if (worktree)
7733 repo_path = strdup(got_worktree_get_repo_path(worktree));
7734 else
7735 repo_path = strdup(cwd);
7736 if (repo_path == NULL) {
7737 error = got_error_from_errno("strdup");
7738 goto done;
7741 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7742 if (error != NULL)
7743 goto done;
7745 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7746 repo, worktree);
7747 if (error)
7748 goto done;
7750 error = tog_load_refs(repo, 0);
7751 if (error)
7752 goto done;
7753 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
7754 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
7755 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7756 if (error)
7757 goto done;
7759 if (worktree) {
7760 got_worktree_close(worktree);
7761 worktree = NULL;
7764 error = got_object_open_as_commit(&commit, repo, commit_id);
7765 if (error)
7766 goto done;
7768 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
7769 if (error) {
7770 if (error->code != GOT_ERR_NO_TREE_ENTRY)
7771 goto done;
7772 fprintf(stderr, "%s: '%s' is no known command or path\n",
7773 getprogname(), argv[0]);
7774 usage(1, 1);
7775 /* not reached */
7778 close_err = got_repo_close(repo);
7779 if (error == NULL)
7780 error = close_err;
7781 repo = NULL;
7783 error = got_object_id_str(&commit_id_str, commit_id);
7784 if (error)
7785 goto done;
7787 cmd = &tog_commands[0]; /* log */
7788 argc = 4;
7789 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
7790 error = cmd->cmd_main(argc, cmd_argv);
7791 done:
7792 if (repo) {
7793 close_err = got_repo_close(repo);
7794 if (error == NULL)
7795 error = close_err;
7797 if (commit)
7798 got_object_commit_close(commit);
7799 if (worktree)
7800 got_worktree_close(worktree);
7801 if (pack_fds) {
7802 const struct got_error *pack_err =
7803 got_repo_pack_fds_close(pack_fds);
7804 if (error == NULL)
7805 error = pack_err;
7807 free(id);
7808 free(commit_id_str);
7809 free(commit_id);
7810 free(cwd);
7811 free(repo_path);
7812 free(in_repo_path);
7813 if (cmd_argv) {
7814 int i;
7815 for (i = 0; i < argc; i++)
7816 free(cmd_argv[i]);
7817 free(cmd_argv);
7819 tog_free_refs();
7820 return error;
7823 int
7824 main(int argc, char *argv[])
7826 const struct got_error *error = NULL;
7827 const struct tog_cmd *cmd = NULL;
7828 int ch, hflag = 0, Vflag = 0;
7829 char **cmd_argv = NULL;
7830 static const struct option longopts[] = {
7831 { "version", no_argument, NULL, 'V' },
7832 { NULL, 0, NULL, 0}
7835 setlocale(LC_CTYPE, "");
7837 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
7838 switch (ch) {
7839 case 'h':
7840 hflag = 1;
7841 break;
7842 case 'V':
7843 Vflag = 1;
7844 break;
7845 default:
7846 usage(hflag, 1);
7847 /* NOTREACHED */
7851 argc -= optind;
7852 argv += optind;
7853 optind = 1;
7854 optreset = 1;
7856 if (Vflag) {
7857 got_version_print_str();
7858 return 0;
7861 #ifndef PROFILE
7862 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
7863 NULL) == -1)
7864 err(1, "pledge");
7865 #endif
7867 if (argc == 0) {
7868 if (hflag)
7869 usage(hflag, 0);
7870 /* Build an argument vector which runs a default command. */
7871 cmd = &tog_commands[0];
7872 argc = 1;
7873 cmd_argv = make_argv(argc, cmd->name);
7874 } else {
7875 size_t i;
7877 /* Did the user specify a command? */
7878 for (i = 0; i < nitems(tog_commands); i++) {
7879 if (strncmp(tog_commands[i].name, argv[0],
7880 strlen(argv[0])) == 0) {
7881 cmd = &tog_commands[i];
7882 break;
7887 if (cmd == NULL) {
7888 if (argc != 1)
7889 usage(0, 1);
7890 /* No command specified; try log with a path */
7891 error = tog_log_with_path(argc, argv);
7892 } else {
7893 if (hflag)
7894 cmd->cmd_usage();
7895 else
7896 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
7899 endwin();
7900 putchar('\n');
7901 if (cmd_argv) {
7902 int i;
7903 for (i = 0; i < argc; i++)
7904 free(cmd_argv[i]);
7905 free(cmd_argv);
7908 if (error && error->code != GOT_ERR_CANCELLED)
7909 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7910 return 0;