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 #define TOG_EOF_STRING "(END)"
110 struct commit_queue_entry {
111 TAILQ_ENTRY(commit_queue_entry) entry;
112 struct got_object_id *id;
113 struct got_commit_object *commit;
114 int idx;
115 };
116 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
117 struct commit_queue {
118 int ncommits;
119 struct commit_queue_head head;
120 };
122 struct tog_color {
123 STAILQ_ENTRY(tog_color) entry;
124 regex_t regex;
125 short colorpair;
126 };
127 STAILQ_HEAD(tog_colors, tog_color);
129 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
130 static struct got_reflist_object_id_map *tog_refs_idmap;
132 static const struct got_error *
133 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
134 struct got_reference* re2)
136 const char *name1 = got_ref_get_name(re1);
137 const char *name2 = got_ref_get_name(re2);
138 int isbackup1, isbackup2;
140 /* Sort backup refs towards the bottom of the list. */
141 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
142 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
143 if (!isbackup1 && isbackup2) {
144 *cmp = -1;
145 return NULL;
146 } else if (isbackup1 && !isbackup2) {
147 *cmp = 1;
148 return NULL;
151 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
152 return NULL;
155 static const struct got_error *
156 tog_load_refs(struct got_repository *repo, int sort_by_date)
158 const struct got_error *err;
160 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
161 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
162 repo);
163 if (err)
164 return err;
166 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
167 repo);
170 static void
171 tog_free_refs(void)
173 if (tog_refs_idmap) {
174 got_reflist_object_id_map_free(tog_refs_idmap);
175 tog_refs_idmap = NULL;
177 got_ref_list_free(&tog_refs);
180 static const struct got_error *
181 add_color(struct tog_colors *colors, const char *pattern,
182 int idx, short color)
184 const struct got_error *err = NULL;
185 struct tog_color *tc;
186 int regerr = 0;
188 if (idx < 1 || idx > COLOR_PAIRS - 1)
189 return NULL;
191 init_pair(idx, color, -1);
193 tc = calloc(1, sizeof(*tc));
194 if (tc == NULL)
195 return got_error_from_errno("calloc");
196 regerr = regcomp(&tc->regex, pattern,
197 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
198 if (regerr) {
199 static char regerr_msg[512];
200 static char err_msg[512];
201 regerror(regerr, &tc->regex, regerr_msg,
202 sizeof(regerr_msg));
203 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
204 regerr_msg);
205 err = got_error_msg(GOT_ERR_REGEX, err_msg);
206 free(tc);
207 return err;
209 tc->colorpair = idx;
210 STAILQ_INSERT_HEAD(colors, tc, entry);
211 return NULL;
214 static void
215 free_colors(struct tog_colors *colors)
217 struct tog_color *tc;
219 while (!STAILQ_EMPTY(colors)) {
220 tc = STAILQ_FIRST(colors);
221 STAILQ_REMOVE_HEAD(colors, entry);
222 regfree(&tc->regex);
223 free(tc);
227 static struct tog_color *
228 get_color(struct tog_colors *colors, int colorpair)
230 struct tog_color *tc = NULL;
232 STAILQ_FOREACH(tc, colors, entry) {
233 if (tc->colorpair == colorpair)
234 return tc;
237 return NULL;
240 static int
241 default_color_value(const char *envvar)
243 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
244 return COLOR_MAGENTA;
245 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
246 return COLOR_CYAN;
247 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
248 return COLOR_YELLOW;
249 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
250 return COLOR_GREEN;
251 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
252 return COLOR_MAGENTA;
253 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
254 return COLOR_MAGENTA;
255 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
256 return COLOR_CYAN;
257 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
258 return COLOR_GREEN;
259 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
260 return COLOR_GREEN;
261 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
262 return COLOR_CYAN;
263 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
264 return COLOR_YELLOW;
265 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
266 return COLOR_GREEN;
267 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
268 return COLOR_MAGENTA;
269 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
270 return COLOR_YELLOW;
271 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
272 return COLOR_CYAN;
274 return -1;
277 static int
278 get_color_value(const char *envvar)
280 const char *val = getenv(envvar);
282 if (val == NULL)
283 return default_color_value(envvar);
285 if (strcasecmp(val, "black") == 0)
286 return COLOR_BLACK;
287 if (strcasecmp(val, "red") == 0)
288 return COLOR_RED;
289 if (strcasecmp(val, "green") == 0)
290 return COLOR_GREEN;
291 if (strcasecmp(val, "yellow") == 0)
292 return COLOR_YELLOW;
293 if (strcasecmp(val, "blue") == 0)
294 return COLOR_BLUE;
295 if (strcasecmp(val, "magenta") == 0)
296 return COLOR_MAGENTA;
297 if (strcasecmp(val, "cyan") == 0)
298 return COLOR_CYAN;
299 if (strcasecmp(val, "white") == 0)
300 return COLOR_WHITE;
301 if (strcasecmp(val, "default") == 0)
302 return -1;
304 return default_color_value(envvar);
308 struct tog_diff_view_state {
309 struct got_object_id *id1, *id2;
310 const char *label1, *label2;
311 FILE *f, *f1, *f2;
312 int fd1, fd2;
313 int first_displayed_line;
314 int last_displayed_line;
315 int eof;
316 int diff_context;
317 int ignore_whitespace;
318 int force_text_diff;
319 struct got_repository *repo;
320 struct tog_colors colors;
321 size_t nlines;
322 off_t *line_offsets;
323 int matched_line;
324 int selected_line;
326 /* passed from log view; may be NULL */
327 struct tog_view *log_view;
328 };
330 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
332 struct tog_log_thread_args {
333 pthread_cond_t need_commits;
334 pthread_cond_t commit_loaded;
335 int commits_needed;
336 int load_all;
337 struct got_commit_graph *graph;
338 struct commit_queue *commits;
339 const char *in_repo_path;
340 struct got_object_id *start_id;
341 struct got_repository *repo;
342 int *pack_fds;
343 int log_complete;
344 sig_atomic_t *quit;
345 struct commit_queue_entry **first_displayed_entry;
346 struct commit_queue_entry **selected_entry;
347 int *searching;
348 int *search_next_done;
349 regex_t *regex;
350 };
352 struct tog_log_view_state {
353 struct commit_queue commits;
354 struct commit_queue_entry *first_displayed_entry;
355 struct commit_queue_entry *last_displayed_entry;
356 struct commit_queue_entry *selected_entry;
357 int selected;
358 char *in_repo_path;
359 char *head_ref_name;
360 int log_branches;
361 struct got_repository *repo;
362 struct got_object_id *start_id;
363 sig_atomic_t quit;
364 pthread_t thread;
365 struct tog_log_thread_args thread_args;
366 struct commit_queue_entry *matched_entry;
367 struct commit_queue_entry *search_entry;
368 struct tog_colors colors;
369 };
371 #define TOG_COLOR_DIFF_MINUS 1
372 #define TOG_COLOR_DIFF_PLUS 2
373 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
374 #define TOG_COLOR_DIFF_META 4
375 #define TOG_COLOR_TREE_SUBMODULE 5
376 #define TOG_COLOR_TREE_SYMLINK 6
377 #define TOG_COLOR_TREE_DIRECTORY 7
378 #define TOG_COLOR_TREE_EXECUTABLE 8
379 #define TOG_COLOR_COMMIT 9
380 #define TOG_COLOR_AUTHOR 10
381 #define TOG_COLOR_DATE 11
382 #define TOG_COLOR_REFS_HEADS 12
383 #define TOG_COLOR_REFS_TAGS 13
384 #define TOG_COLOR_REFS_REMOTES 14
385 #define TOG_COLOR_REFS_BACKUP 15
387 struct tog_blame_cb_args {
388 struct tog_blame_line *lines; /* one per line */
389 int nlines;
391 struct tog_view *view;
392 struct got_object_id *commit_id;
393 int *quit;
394 };
396 struct tog_blame_thread_args {
397 const char *path;
398 struct got_repository *repo;
399 struct tog_blame_cb_args *cb_args;
400 int *complete;
401 got_cancel_cb cancel_cb;
402 void *cancel_arg;
403 };
405 struct tog_blame {
406 FILE *f;
407 off_t filesize;
408 struct tog_blame_line *lines;
409 int nlines;
410 off_t *line_offsets;
411 pthread_t thread;
412 struct tog_blame_thread_args thread_args;
413 struct tog_blame_cb_args cb_args;
414 const char *path;
415 int *pack_fds;
416 };
418 struct tog_blame_view_state {
419 int first_displayed_line;
420 int last_displayed_line;
421 int selected_line;
422 int blame_complete;
423 int eof;
424 int done;
425 struct got_object_id_queue blamed_commits;
426 struct got_object_qid *blamed_commit;
427 char *path;
428 struct got_repository *repo;
429 struct got_object_id *commit_id;
430 struct tog_blame blame;
431 int matched_line;
432 struct tog_colors colors;
433 };
435 struct tog_parent_tree {
436 TAILQ_ENTRY(tog_parent_tree) entry;
437 struct got_tree_object *tree;
438 struct got_tree_entry *first_displayed_entry;
439 struct got_tree_entry *selected_entry;
440 int selected;
441 };
443 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
445 struct tog_tree_view_state {
446 char *tree_label;
447 struct got_object_id *commit_id;/* commit which this tree belongs to */
448 struct got_tree_object *root; /* the commit's root tree entry */
449 struct got_tree_object *tree; /* currently displayed (sub-)tree */
450 struct got_tree_entry *first_displayed_entry;
451 struct got_tree_entry *last_displayed_entry;
452 struct got_tree_entry *selected_entry;
453 int ndisplayed, selected, show_ids;
454 struct tog_parent_trees parents; /* parent trees of current sub-tree */
455 char *head_ref_name;
456 struct got_repository *repo;
457 struct got_tree_entry *matched_entry;
458 struct tog_colors colors;
459 };
461 struct tog_reflist_entry {
462 TAILQ_ENTRY(tog_reflist_entry) entry;
463 struct got_reference *ref;
464 int idx;
465 };
467 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
469 struct tog_ref_view_state {
470 struct tog_reflist_head refs;
471 struct tog_reflist_entry *first_displayed_entry;
472 struct tog_reflist_entry *last_displayed_entry;
473 struct tog_reflist_entry *selected_entry;
474 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
475 struct got_repository *repo;
476 struct tog_reflist_entry *matched_entry;
477 struct tog_colors colors;
478 };
480 /*
481 * We implement two types of views: parent views and child views.
483 * The 'Tab' key switches focus between a parent view and its child view.
484 * Child views are shown side-by-side to their parent view, provided
485 * there is enough screen estate.
487 * When a new view is opened from within a parent view, this new view
488 * becomes a child view of the parent view, replacing any existing child.
490 * When a new view is opened from within a child view, this new view
491 * becomes a parent view which will obscure the views below until the
492 * user quits the new parent view by typing 'q'.
494 * This list of views contains parent views only.
495 * Child views are only pointed to by their parent view.
496 */
497 TAILQ_HEAD(tog_view_list_head, tog_view);
499 struct tog_view {
500 TAILQ_ENTRY(tog_view) entry;
501 WINDOW *window;
502 PANEL *panel;
503 int nlines, ncols, begin_y, begin_x;
504 int maxx, x; /* max column and current start column */
505 int lines, cols; /* copies of LINES and COLS */
506 int ch, count; /* current keymap and count prefix */
507 int focussed; /* Only set on one parent or child view at a time. */
508 int dying;
509 struct tog_view *parent;
510 struct tog_view *child;
512 /*
513 * This flag is initially set on parent views when a new child view
514 * is created. It gets toggled when the 'Tab' key switches focus
515 * between parent and child.
516 * The flag indicates whether focus should be passed on to our child
517 * view if this parent view gets picked for focus after another parent
518 * view was closed. This prevents child views from losing focus in such
519 * situations.
520 */
521 int focus_child;
523 /* type-specific state */
524 enum tog_view_type type;
525 union {
526 struct tog_diff_view_state diff;
527 struct tog_log_view_state log;
528 struct tog_blame_view_state blame;
529 struct tog_tree_view_state tree;
530 struct tog_ref_view_state ref;
531 } state;
533 const struct got_error *(*show)(struct tog_view *);
534 const struct got_error *(*input)(struct tog_view **,
535 struct tog_view *, int);
536 const struct got_error *(*close)(struct tog_view *);
538 const struct got_error *(*search_start)(struct tog_view *);
539 const struct got_error *(*search_next)(struct tog_view *);
540 int search_started;
541 int searching;
542 #define TOG_SEARCH_FORWARD 1
543 #define TOG_SEARCH_BACKWARD 2
544 int search_next_done;
545 #define TOG_SEARCH_HAVE_MORE 1
546 #define TOG_SEARCH_NO_MORE 2
547 #define TOG_SEARCH_HAVE_NONE 3
548 regex_t regex;
549 regmatch_t regmatch;
550 };
552 static const struct got_error *open_diff_view(struct tog_view *,
553 struct got_object_id *, struct got_object_id *,
554 const char *, const char *, int, int, int, struct tog_view *,
555 struct got_repository *);
556 static const struct got_error *show_diff_view(struct tog_view *);
557 static const struct got_error *input_diff_view(struct tog_view **,
558 struct tog_view *, int);
559 static const struct got_error* close_diff_view(struct tog_view *);
560 static const struct got_error *search_start_diff_view(struct tog_view *);
561 static const struct got_error *search_next_diff_view(struct tog_view *);
563 static const struct got_error *open_log_view(struct tog_view *,
564 struct got_object_id *, struct got_repository *,
565 const char *, const char *, int);
566 static const struct got_error * show_log_view(struct tog_view *);
567 static const struct got_error *input_log_view(struct tog_view **,
568 struct tog_view *, int);
569 static const struct got_error *close_log_view(struct tog_view *);
570 static const struct got_error *search_start_log_view(struct tog_view *);
571 static const struct got_error *search_next_log_view(struct tog_view *);
573 static const struct got_error *open_blame_view(struct tog_view *, char *,
574 struct got_object_id *, struct got_repository *);
575 static const struct got_error *show_blame_view(struct tog_view *);
576 static const struct got_error *input_blame_view(struct tog_view **,
577 struct tog_view *, int);
578 static const struct got_error *close_blame_view(struct tog_view *);
579 static const struct got_error *search_start_blame_view(struct tog_view *);
580 static const struct got_error *search_next_blame_view(struct tog_view *);
582 static const struct got_error *open_tree_view(struct tog_view *,
583 struct got_object_id *, const char *, struct got_repository *);
584 static const struct got_error *show_tree_view(struct tog_view *);
585 static const struct got_error *input_tree_view(struct tog_view **,
586 struct tog_view *, int);
587 static const struct got_error *close_tree_view(struct tog_view *);
588 static const struct got_error *search_start_tree_view(struct tog_view *);
589 static const struct got_error *search_next_tree_view(struct tog_view *);
591 static const struct got_error *open_ref_view(struct tog_view *,
592 struct got_repository *);
593 static const struct got_error *show_ref_view(struct tog_view *);
594 static const struct got_error *input_ref_view(struct tog_view **,
595 struct tog_view *, int);
596 static const struct got_error *close_ref_view(struct tog_view *);
597 static const struct got_error *search_start_ref_view(struct tog_view *);
598 static const struct got_error *search_next_ref_view(struct tog_view *);
600 static volatile sig_atomic_t tog_sigwinch_received;
601 static volatile sig_atomic_t tog_sigpipe_received;
602 static volatile sig_atomic_t tog_sigcont_received;
603 static volatile sig_atomic_t tog_sigint_received;
604 static volatile sig_atomic_t tog_sigterm_received;
606 static void
607 tog_sigwinch(int signo)
609 tog_sigwinch_received = 1;
612 static void
613 tog_sigpipe(int signo)
615 tog_sigpipe_received = 1;
618 static void
619 tog_sigcont(int signo)
621 tog_sigcont_received = 1;
624 static void
625 tog_sigint(int signo)
627 tog_sigint_received = 1;
630 static void
631 tog_sigterm(int signo)
633 tog_sigterm_received = 1;
636 static int
637 tog_fatal_signal_received(void)
639 return (tog_sigpipe_received ||
640 tog_sigint_received || tog_sigint_received);
644 static const struct got_error *
645 view_close(struct tog_view *view)
647 const struct got_error *err = NULL;
649 if (view->child) {
650 view_close(view->child);
651 view->child = NULL;
653 if (view->close)
654 err = view->close(view);
655 if (view->panel)
656 del_panel(view->panel);
657 if (view->window)
658 delwin(view->window);
659 free(view);
660 return err;
663 static struct tog_view *
664 view_open(int nlines, int ncols, int begin_y, int begin_x,
665 enum tog_view_type type)
667 struct tog_view *view = calloc(1, sizeof(*view));
669 if (view == NULL)
670 return NULL;
672 view->ch = 0;
673 view->count = 0;
674 view->type = type;
675 view->lines = LINES;
676 view->cols = COLS;
677 view->nlines = nlines ? nlines : LINES - begin_y;
678 view->ncols = ncols ? ncols : COLS - begin_x;
679 view->begin_y = begin_y;
680 view->begin_x = begin_x;
681 view->window = newwin(nlines, ncols, begin_y, begin_x);
682 if (view->window == NULL) {
683 view_close(view);
684 return NULL;
686 view->panel = new_panel(view->window);
687 if (view->panel == NULL ||
688 set_panel_userptr(view->panel, view) != OK) {
689 view_close(view);
690 return NULL;
693 keypad(view->window, TRUE);
694 return view;
697 static int
698 view_split_begin_x(int begin_x)
700 if (begin_x > 0 || COLS < 120)
701 return 0;
702 return (COLS - MAX(COLS / 2, 80));
705 static const struct got_error *view_resize(struct tog_view *);
707 static const struct got_error *
708 view_splitscreen(struct tog_view *view)
710 const struct got_error *err = NULL;
712 view->begin_y = 0;
713 view->begin_x = view_split_begin_x(0);
714 view->nlines = LINES;
715 view->ncols = COLS - view->begin_x;
716 view->lines = LINES;
717 view->cols = COLS;
718 err = view_resize(view);
719 if (err)
720 return err;
722 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
723 return got_error_from_errno("mvwin");
725 return NULL;
728 static const struct got_error *
729 view_fullscreen(struct tog_view *view)
731 const struct got_error *err = NULL;
733 view->begin_x = 0;
734 view->begin_y = 0;
735 view->nlines = LINES;
736 view->ncols = COLS;
737 view->lines = LINES;
738 view->cols = COLS;
739 err = view_resize(view);
740 if (err)
741 return err;
743 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
744 return got_error_from_errno("mvwin");
746 return NULL;
749 static int
750 view_is_parent_view(struct tog_view *view)
752 return view->parent == NULL;
755 static int
756 view_is_splitscreen(struct tog_view *view)
758 return view->begin_x > 0;
762 static const struct got_error *
763 view_resize(struct tog_view *view)
765 int nlines, ncols;
767 if (view->lines > LINES)
768 nlines = view->nlines - (view->lines - LINES);
769 else
770 nlines = view->nlines + (LINES - view->lines);
772 if (view->cols > COLS)
773 ncols = view->ncols - (view->cols - COLS);
774 else
775 ncols = view->ncols + (COLS - view->cols);
777 if (view->child && view_is_splitscreen(view->child)) {
778 view->child->begin_x = view_split_begin_x(view->begin_x);
779 if (view->child->begin_x == 0) {
780 ncols = COLS;
782 view_fullscreen(view->child);
783 if (view->child->focussed)
784 show_panel(view->child->panel);
785 else
786 show_panel(view->panel);
787 } else {
788 ncols = view->child->begin_x;
790 view_splitscreen(view->child);
791 show_panel(view->child->panel);
793 } else if (view->parent == NULL)
794 ncols = COLS;
796 if (wresize(view->window, nlines, ncols) == ERR)
797 return got_error_from_errno("wresize");
798 if (replace_panel(view->panel, view->window) == ERR)
799 return got_error_from_errno("replace_panel");
800 wclear(view->window);
802 view->nlines = nlines;
803 view->ncols = ncols;
804 view->lines = LINES;
805 view->cols = COLS;
807 return NULL;
810 static const struct got_error *
811 view_close_child(struct tog_view *view)
813 const struct got_error *err = NULL;
815 if (view->child == NULL)
816 return NULL;
818 err = view_close(view->child);
819 view->child = NULL;
820 return err;
823 static const struct got_error *
824 view_set_child(struct tog_view *view, struct tog_view *child)
826 view->child = child;
827 child->parent = view;
829 return view_resize(view);
832 static void
833 tog_resizeterm(void)
835 int cols, lines;
836 struct winsize size;
838 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
839 cols = 80; /* Default */
840 lines = 24;
841 } else {
842 cols = size.ws_col;
843 lines = size.ws_row;
845 resize_term(lines, cols);
848 static const struct got_error *
849 view_search_start(struct tog_view *view)
851 const struct got_error *err = NULL;
852 char pattern[1024];
853 int ret;
855 if (view->search_started) {
856 regfree(&view->regex);
857 view->searching = 0;
858 memset(&view->regmatch, 0, sizeof(view->regmatch));
860 view->search_started = 0;
862 if (view->nlines < 1)
863 return NULL;
865 mvwaddstr(view->window, view->begin_y + view->nlines - 1, 0, "/");
866 wclrtoeol(view->window);
868 nocbreak();
869 echo();
870 ret = wgetnstr(view->window, pattern, sizeof(pattern));
871 cbreak();
872 noecho();
873 if (ret == ERR)
874 return NULL;
876 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
877 err = view->search_start(view);
878 if (err) {
879 regfree(&view->regex);
880 return err;
882 view->search_started = 1;
883 view->searching = TOG_SEARCH_FORWARD;
884 view->search_next_done = 0;
885 view->search_next(view);
888 return NULL;
891 /*
892 * Compute view->count from numeric user input. User has five-tenths of a
893 * second to follow each numeric keypress with another number to form count.
894 * Return first non-numeric input or ERR and assign total to view->count.
895 * XXX Should we add support for user-defined timeout?
896 */
897 static int
898 get_compound_key(struct tog_view *view, int c)
900 int x, n = 0;
902 view->count = 0;
903 halfdelay(5); /* block for half a second */
904 wattron(view->window, A_BOLD);
905 wmove(view->window, view->nlines - 1, 0);
906 wclrtoeol(view->window);
907 waddch(view->window, ':');
909 do {
910 x = getcurx(view->window);
911 if (x != ERR && x < view->ncols)
912 waddch(view->window, c);
913 /*
914 * Don't overflow. Max valid request should be the greatest
915 * between the longest and total lines; cap at 10 million.
916 */
917 if (n >= 9999999)
918 n = 9999999;
919 else
920 n = n * 10 + (c - '0');
921 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
923 /* Massage excessive or inapplicable values at the input handler. */
924 view->count = n;
926 wattroff(view->window, A_BOLD);
927 cbreak(); /* return to blocking */
928 return c;
931 static const struct got_error *
932 view_input(struct tog_view **new, int *done, struct tog_view *view,
933 struct tog_view_list_head *views)
935 const struct got_error *err = NULL;
936 struct tog_view *v;
937 int ch, errcode;
939 *new = NULL;
941 /* Clear "no matches" indicator. */
942 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
943 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
944 view->search_next_done = TOG_SEARCH_HAVE_MORE;
945 view->count = 0;
948 if (view->searching && !view->search_next_done) {
949 errcode = pthread_mutex_unlock(&tog_mutex);
950 if (errcode)
951 return got_error_set_errno(errcode,
952 "pthread_mutex_unlock");
953 sched_yield();
954 errcode = pthread_mutex_lock(&tog_mutex);
955 if (errcode)
956 return got_error_set_errno(errcode,
957 "pthread_mutex_lock");
958 view->search_next(view);
959 return NULL;
962 nodelay(stdscr, FALSE);
963 /* Allow threads to make progress while we are waiting for input. */
964 errcode = pthread_mutex_unlock(&tog_mutex);
965 if (errcode)
966 return got_error_set_errno(errcode, "pthread_mutex_unlock");
967 /* If we have an unfinished count, don't get a new key map. */
968 ch = view->ch;
969 if ((view->count && --view->count == 0) || !view->count) {
970 ch = wgetch(view->window);
971 if (ch >= '1' && ch <= '9')
972 view->ch = ch = get_compound_key(view, ch);
974 errcode = pthread_mutex_lock(&tog_mutex);
975 if (errcode)
976 return got_error_set_errno(errcode, "pthread_mutex_lock");
977 nodelay(stdscr, TRUE);
979 if (tog_sigwinch_received || tog_sigcont_received) {
980 tog_resizeterm();
981 tog_sigwinch_received = 0;
982 tog_sigcont_received = 0;
983 TAILQ_FOREACH(v, views, entry) {
984 err = view_resize(v);
985 if (err)
986 return err;
987 err = v->input(new, v, KEY_RESIZE);
988 if (err)
989 return err;
990 if (v->child) {
991 err = view_resize(v->child);
992 if (err)
993 return err;
994 err = v->child->input(new, v->child,
995 KEY_RESIZE);
996 if (err)
997 return err;
1002 switch (ch) {
1003 case '\t':
1004 view->count = 0;
1005 if (view->child) {
1006 view->focussed = 0;
1007 view->child->focussed = 1;
1008 view->focus_child = 1;
1009 } else if (view->parent) {
1010 view->focussed = 0;
1011 view->parent->focussed = 1;
1012 view->parent->focus_child = 0;
1013 if (!view_is_splitscreen(view))
1014 err = view_fullscreen(view->parent);
1016 break;
1017 case 'q':
1018 err = view->input(new, view, ch);
1019 view->dying = 1;
1020 break;
1021 case 'Q':
1022 *done = 1;
1023 break;
1024 case 'F':
1025 view->count = 0;
1026 if (view_is_parent_view(view)) {
1027 if (view->child == NULL)
1028 break;
1029 if (view_is_splitscreen(view->child)) {
1030 view->focussed = 0;
1031 view->child->focussed = 1;
1032 err = view_fullscreen(view->child);
1033 } else
1034 err = view_splitscreen(view->child);
1035 if (err)
1036 break;
1037 err = view->child->input(new, view->child,
1038 KEY_RESIZE);
1039 } else {
1040 if (view_is_splitscreen(view)) {
1041 view->parent->focussed = 0;
1042 view->focussed = 1;
1043 err = view_fullscreen(view);
1044 } else {
1045 err = view_splitscreen(view);
1046 if (!err)
1047 err = view_resize(view->parent);
1049 if (err)
1050 break;
1051 err = view->input(new, view, KEY_RESIZE);
1053 break;
1054 case KEY_RESIZE:
1055 break;
1056 case '/':
1057 view->count = 0;
1058 if (view->search_start)
1059 view_search_start(view);
1060 else
1061 err = view->input(new, view, ch);
1062 break;
1063 case 'N':
1064 case 'n':
1065 if (view->search_started && view->search_next) {
1066 view->searching = (ch == 'n' ?
1067 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1068 view->search_next_done = 0;
1069 view->search_next(view);
1070 } else
1071 err = view->input(new, view, ch);
1072 break;
1073 default:
1074 err = view->input(new, view, ch);
1075 break;
1078 return err;
1081 static void
1082 view_vborder(struct tog_view *view)
1084 PANEL *panel;
1085 const struct tog_view *view_above;
1087 if (view->parent)
1088 return view_vborder(view->parent);
1090 panel = panel_above(view->panel);
1091 if (panel == NULL)
1092 return;
1094 view_above = panel_userptr(panel);
1095 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
1096 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
1099 static int
1100 view_needs_focus_indication(struct tog_view *view)
1102 if (view_is_parent_view(view)) {
1103 if (view->child == NULL || view->child->focussed)
1104 return 0;
1105 if (!view_is_splitscreen(view->child))
1106 return 0;
1107 } else if (!view_is_splitscreen(view))
1108 return 0;
1110 return view->focussed;
1113 static const struct got_error *
1114 view_loop(struct tog_view *view)
1116 const struct got_error *err = NULL;
1117 struct tog_view_list_head views;
1118 struct tog_view *new_view;
1119 int fast_refresh = 10;
1120 int done = 0, errcode;
1122 errcode = pthread_mutex_lock(&tog_mutex);
1123 if (errcode)
1124 return got_error_set_errno(errcode, "pthread_mutex_lock");
1126 TAILQ_INIT(&views);
1127 TAILQ_INSERT_HEAD(&views, view, entry);
1129 view->focussed = 1;
1130 err = view->show(view);
1131 if (err)
1132 return err;
1133 update_panels();
1134 doupdate();
1135 while (!TAILQ_EMPTY(&views) && !done && !tog_fatal_signal_received()) {
1136 /* Refresh fast during initialization, then become slower. */
1137 if (fast_refresh && fast_refresh-- == 0)
1138 halfdelay(10); /* switch to once per second */
1140 err = view_input(&new_view, &done, view, &views);
1141 if (err)
1142 break;
1143 if (view->dying) {
1144 struct tog_view *v, *prev = NULL;
1146 if (view_is_parent_view(view))
1147 prev = TAILQ_PREV(view, tog_view_list_head,
1148 entry);
1149 else if (view->parent)
1150 prev = view->parent;
1152 if (view->parent) {
1153 view->parent->child = NULL;
1154 view->parent->focus_child = 0;
1156 err = view_resize(view->parent);
1157 if (err)
1158 break;
1159 } else
1160 TAILQ_REMOVE(&views, view, entry);
1162 err = view_close(view);
1163 if (err)
1164 goto done;
1166 view = NULL;
1167 TAILQ_FOREACH(v, &views, entry) {
1168 if (v->focussed)
1169 break;
1171 if (view == NULL && new_view == NULL) {
1172 /* No view has focus. Try to pick one. */
1173 if (prev)
1174 view = prev;
1175 else if (!TAILQ_EMPTY(&views)) {
1176 view = TAILQ_LAST(&views,
1177 tog_view_list_head);
1179 if (view) {
1180 if (view->focus_child) {
1181 view->child->focussed = 1;
1182 view = view->child;
1183 } else
1184 view->focussed = 1;
1188 if (new_view) {
1189 struct tog_view *v, *t;
1190 /* Only allow one parent view per type. */
1191 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1192 if (v->type != new_view->type)
1193 continue;
1194 TAILQ_REMOVE(&views, v, entry);
1195 err = view_close(v);
1196 if (err)
1197 goto done;
1198 break;
1200 TAILQ_INSERT_TAIL(&views, new_view, entry);
1201 view = new_view;
1203 if (view) {
1204 if (view_is_parent_view(view)) {
1205 if (view->child && view->child->focussed)
1206 view = view->child;
1207 } else {
1208 if (view->parent && view->parent->focussed)
1209 view = view->parent;
1211 show_panel(view->panel);
1212 if (view->child && view_is_splitscreen(view->child))
1213 show_panel(view->child->panel);
1214 if (view->parent && view_is_splitscreen(view)) {
1215 err = view->parent->show(view->parent);
1216 if (err)
1217 goto done;
1219 err = view->show(view);
1220 if (err)
1221 goto done;
1222 if (view->child) {
1223 err = view->child->show(view->child);
1224 if (err)
1225 goto done;
1227 update_panels();
1228 doupdate();
1231 done:
1232 while (!TAILQ_EMPTY(&views)) {
1233 view = TAILQ_FIRST(&views);
1234 TAILQ_REMOVE(&views, view, entry);
1235 view_close(view);
1238 errcode = pthread_mutex_unlock(&tog_mutex);
1239 if (errcode && err == NULL)
1240 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1242 return err;
1245 __dead static void
1246 usage_log(void)
1248 endwin();
1249 fprintf(stderr,
1250 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1251 getprogname());
1252 exit(1);
1255 /* Create newly allocated wide-character string equivalent to a byte string. */
1256 static const struct got_error *
1257 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1259 char *vis = NULL;
1260 const struct got_error *err = NULL;
1262 *ws = NULL;
1263 *wlen = mbstowcs(NULL, s, 0);
1264 if (*wlen == (size_t)-1) {
1265 int vislen;
1266 if (errno != EILSEQ)
1267 return got_error_from_errno("mbstowcs");
1269 /* byte string invalid in current encoding; try to "fix" it */
1270 err = got_mbsavis(&vis, &vislen, s);
1271 if (err)
1272 return err;
1273 *wlen = mbstowcs(NULL, vis, 0);
1274 if (*wlen == (size_t)-1) {
1275 err = got_error_from_errno("mbstowcs"); /* give up */
1276 goto done;
1280 *ws = calloc(*wlen + 1, sizeof(**ws));
1281 if (*ws == NULL) {
1282 err = got_error_from_errno("calloc");
1283 goto done;
1286 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1287 err = got_error_from_errno("mbstowcs");
1288 done:
1289 free(vis);
1290 if (err) {
1291 free(*ws);
1292 *ws = NULL;
1293 *wlen = 0;
1295 return err;
1298 static const struct got_error *
1299 expand_tab(char **ptr, const char *src)
1301 char *dst;
1302 size_t len, n, idx = 0, sz = 0;
1304 *ptr = NULL;
1305 n = len = strlen(src);
1306 dst = malloc(n + 1);
1307 if (dst == NULL)
1308 return got_error_from_errno("malloc");
1310 while (idx < len && src[idx]) {
1311 const char c = src[idx];
1313 if (c == '\t') {
1314 size_t nb = TABSIZE - sz % TABSIZE;
1315 char *p;
1317 p = realloc(dst, n + nb);
1318 if (p == NULL) {
1319 free(dst);
1320 return got_error_from_errno("realloc");
1323 dst = p;
1324 n += nb;
1325 memset(dst + sz, ' ', nb);
1326 sz += nb;
1327 } else
1328 dst[sz++] = src[idx];
1329 ++idx;
1332 dst[sz] = '\0';
1333 *ptr = dst;
1334 return NULL;
1338 * Advance at most n columns from wline starting at offset off.
1339 * Return the index to the first character after the span operation.
1340 * Return the combined column width of all spanned wide character in
1341 * *rcol.
1343 static int
1344 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1346 int width, i, cols = 0;
1348 if (n == 0) {
1349 *rcol = cols;
1350 return off;
1353 for (i = off; wline[i] != L'\0'; ++i) {
1354 if (wline[i] == L'\t')
1355 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1356 else
1357 width = wcwidth(wline[i]);
1359 if (width == -1) {
1360 width = 1;
1361 wline[i] = L'.';
1364 if (cols + width > n)
1365 break;
1366 cols += width;
1369 *rcol = cols;
1370 return i;
1374 * Format a line for display, ensuring that it won't overflow a width limit.
1375 * With scrolling, the width returned refers to the scrolled version of the
1376 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1378 static const struct got_error *
1379 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1380 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1382 const struct got_error *err = NULL;
1383 int cols;
1384 wchar_t *wline = NULL;
1385 char *exstr = NULL;
1386 size_t wlen;
1387 int i, scrollx;
1389 *wlinep = NULL;
1390 *widthp = 0;
1392 if (expand) {
1393 err = expand_tab(&exstr, line);
1394 if (err)
1395 return err;
1398 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1399 free(exstr);
1400 if (err)
1401 return err;
1403 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1405 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1406 wline[wlen - 1] = L'\0';
1407 wlen--;
1409 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1410 wline[wlen - 1] = L'\0';
1411 wlen--;
1414 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1415 wline[i] = L'\0';
1417 if (widthp)
1418 *widthp = cols;
1419 if (scrollxp)
1420 *scrollxp = scrollx;
1421 if (err)
1422 free(wline);
1423 else
1424 *wlinep = wline;
1425 return err;
1428 static const struct got_error*
1429 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1430 struct got_object_id *id, struct got_repository *repo)
1432 static const struct got_error *err = NULL;
1433 struct got_reflist_entry *re;
1434 char *s;
1435 const char *name;
1437 *refs_str = NULL;
1439 TAILQ_FOREACH(re, refs, entry) {
1440 struct got_tag_object *tag = NULL;
1441 struct got_object_id *ref_id;
1442 int cmp;
1444 name = got_ref_get_name(re->ref);
1445 if (strcmp(name, GOT_REF_HEAD) == 0)
1446 continue;
1447 if (strncmp(name, "refs/", 5) == 0)
1448 name += 5;
1449 if (strncmp(name, "got/", 4) == 0 &&
1450 strncmp(name, "got/backup/", 11) != 0)
1451 continue;
1452 if (strncmp(name, "heads/", 6) == 0)
1453 name += 6;
1454 if (strncmp(name, "remotes/", 8) == 0) {
1455 name += 8;
1456 s = strstr(name, "/" GOT_REF_HEAD);
1457 if (s != NULL && s[strlen(s)] == '\0')
1458 continue;
1460 err = got_ref_resolve(&ref_id, repo, re->ref);
1461 if (err)
1462 break;
1463 if (strncmp(name, "tags/", 5) == 0) {
1464 err = got_object_open_as_tag(&tag, repo, ref_id);
1465 if (err) {
1466 if (err->code != GOT_ERR_OBJ_TYPE) {
1467 free(ref_id);
1468 break;
1470 /* Ref points at something other than a tag. */
1471 err = NULL;
1472 tag = NULL;
1475 cmp = got_object_id_cmp(tag ?
1476 got_object_tag_get_object_id(tag) : ref_id, id);
1477 free(ref_id);
1478 if (tag)
1479 got_object_tag_close(tag);
1480 if (cmp != 0)
1481 continue;
1482 s = *refs_str;
1483 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1484 s ? ", " : "", name) == -1) {
1485 err = got_error_from_errno("asprintf");
1486 free(s);
1487 *refs_str = NULL;
1488 break;
1490 free(s);
1493 return err;
1496 static const struct got_error *
1497 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1498 int col_tab_align)
1500 char *smallerthan;
1502 smallerthan = strchr(author, '<');
1503 if (smallerthan && smallerthan[1] != '\0')
1504 author = smallerthan + 1;
1505 author[strcspn(author, "@>")] = '\0';
1506 return format_line(wauthor, author_width, NULL, author, 0, limit,
1507 col_tab_align, 0);
1510 static const struct got_error *
1511 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1512 struct got_object_id *id, const size_t date_display_cols,
1513 int author_display_cols)
1515 struct tog_log_view_state *s = &view->state.log;
1516 const struct got_error *err = NULL;
1517 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1518 char *logmsg0 = NULL, *logmsg = NULL;
1519 char *author = NULL;
1520 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1521 int author_width, logmsg_width;
1522 char *newline, *line = NULL;
1523 int col, limit, scrollx;
1524 const int avail = view->ncols;
1525 struct tm tm;
1526 time_t committer_time;
1527 struct tog_color *tc;
1529 committer_time = got_object_commit_get_committer_time(commit);
1530 if (gmtime_r(&committer_time, &tm) == NULL)
1531 return got_error_from_errno("gmtime_r");
1532 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1533 return got_error(GOT_ERR_NO_SPACE);
1535 if (avail <= date_display_cols)
1536 limit = MIN(sizeof(datebuf) - 1, avail);
1537 else
1538 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1539 tc = get_color(&s->colors, TOG_COLOR_DATE);
1540 if (tc)
1541 wattr_on(view->window,
1542 COLOR_PAIR(tc->colorpair), NULL);
1543 waddnstr(view->window, datebuf, limit);
1544 if (tc)
1545 wattr_off(view->window,
1546 COLOR_PAIR(tc->colorpair), NULL);
1547 col = limit;
1548 if (col > avail)
1549 goto done;
1551 if (avail >= 120) {
1552 char *id_str;
1553 err = got_object_id_str(&id_str, id);
1554 if (err)
1555 goto done;
1556 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1557 if (tc)
1558 wattr_on(view->window,
1559 COLOR_PAIR(tc->colorpair), NULL);
1560 wprintw(view->window, "%.8s ", id_str);
1561 if (tc)
1562 wattr_off(view->window,
1563 COLOR_PAIR(tc->colorpair), NULL);
1564 free(id_str);
1565 col += 9;
1566 if (col > avail)
1567 goto done;
1570 author = strdup(got_object_commit_get_author(commit));
1571 if (author == NULL) {
1572 err = got_error_from_errno("strdup");
1573 goto done;
1575 err = format_author(&wauthor, &author_width, author, avail - col, col);
1576 if (err)
1577 goto done;
1578 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1579 if (tc)
1580 wattr_on(view->window,
1581 COLOR_PAIR(tc->colorpair), NULL);
1582 waddwstr(view->window, wauthor);
1583 if (tc)
1584 wattr_off(view->window,
1585 COLOR_PAIR(tc->colorpair), NULL);
1586 col += author_width;
1587 while (col < avail && author_width < author_display_cols + 2) {
1588 waddch(view->window, ' ');
1589 col++;
1590 author_width++;
1592 if (col > avail)
1593 goto done;
1595 err = got_object_commit_get_logmsg(&logmsg0, commit);
1596 if (err)
1597 goto done;
1598 logmsg = logmsg0;
1599 while (*logmsg == '\n')
1600 logmsg++;
1601 newline = strchr(logmsg, '\n');
1602 if (newline)
1603 *newline = '\0';
1604 limit = avail - col;
1605 if (view->child && view_is_splitscreen(view->child) && limit > 0)
1606 limit--; /* for the border */
1607 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
1608 limit, col, 1);
1609 if (err)
1610 goto done;
1611 waddwstr(view->window, &wlogmsg[scrollx]);
1612 col += MAX(logmsg_width, 0);
1613 while (col < avail) {
1614 waddch(view->window, ' ');
1615 col++;
1617 done:
1618 free(logmsg0);
1619 free(wlogmsg);
1620 free(author);
1621 free(wauthor);
1622 free(line);
1623 return err;
1626 static struct commit_queue_entry *
1627 alloc_commit_queue_entry(struct got_commit_object *commit,
1628 struct got_object_id *id)
1630 struct commit_queue_entry *entry;
1632 entry = calloc(1, sizeof(*entry));
1633 if (entry == NULL)
1634 return NULL;
1636 entry->id = id;
1637 entry->commit = commit;
1638 return entry;
1641 static void
1642 pop_commit(struct commit_queue *commits)
1644 struct commit_queue_entry *entry;
1646 entry = TAILQ_FIRST(&commits->head);
1647 TAILQ_REMOVE(&commits->head, entry, entry);
1648 got_object_commit_close(entry->commit);
1649 commits->ncommits--;
1650 /* Don't free entry->id! It is owned by the commit graph. */
1651 free(entry);
1654 static void
1655 free_commits(struct commit_queue *commits)
1657 while (!TAILQ_EMPTY(&commits->head))
1658 pop_commit(commits);
1661 static const struct got_error *
1662 match_commit(int *have_match, struct got_object_id *id,
1663 struct got_commit_object *commit, regex_t *regex)
1665 const struct got_error *err = NULL;
1666 regmatch_t regmatch;
1667 char *id_str = NULL, *logmsg = NULL;
1669 *have_match = 0;
1671 err = got_object_id_str(&id_str, id);
1672 if (err)
1673 return err;
1675 err = got_object_commit_get_logmsg(&logmsg, commit);
1676 if (err)
1677 goto done;
1679 if (regexec(regex, got_object_commit_get_author(commit), 1,
1680 &regmatch, 0) == 0 ||
1681 regexec(regex, got_object_commit_get_committer(commit), 1,
1682 &regmatch, 0) == 0 ||
1683 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
1684 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
1685 *have_match = 1;
1686 done:
1687 free(id_str);
1688 free(logmsg);
1689 return err;
1692 static const struct got_error *
1693 queue_commits(struct tog_log_thread_args *a)
1695 const struct got_error *err = NULL;
1698 * We keep all commits open throughout the lifetime of the log
1699 * view in order to avoid having to re-fetch commits from disk
1700 * while updating the display.
1702 do {
1703 struct got_object_id *id;
1704 struct got_commit_object *commit;
1705 struct commit_queue_entry *entry;
1706 int errcode;
1708 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
1709 NULL, NULL);
1710 if (err || id == NULL)
1711 break;
1713 err = got_object_open_as_commit(&commit, a->repo, id);
1714 if (err)
1715 break;
1716 entry = alloc_commit_queue_entry(commit, id);
1717 if (entry == NULL) {
1718 err = got_error_from_errno("alloc_commit_queue_entry");
1719 break;
1722 errcode = pthread_mutex_lock(&tog_mutex);
1723 if (errcode) {
1724 err = got_error_set_errno(errcode,
1725 "pthread_mutex_lock");
1726 break;
1729 entry->idx = a->commits->ncommits;
1730 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
1731 a->commits->ncommits++;
1733 if (*a->searching == TOG_SEARCH_FORWARD &&
1734 !*a->search_next_done) {
1735 int have_match;
1736 err = match_commit(&have_match, id, commit, a->regex);
1737 if (err)
1738 break;
1739 if (have_match)
1740 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
1743 errcode = pthread_mutex_unlock(&tog_mutex);
1744 if (errcode && err == NULL)
1745 err = got_error_set_errno(errcode,
1746 "pthread_mutex_unlock");
1747 if (err)
1748 break;
1749 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
1751 return err;
1754 static void
1755 select_commit(struct tog_log_view_state *s)
1757 struct commit_queue_entry *entry;
1758 int ncommits = 0;
1760 entry = s->first_displayed_entry;
1761 while (entry) {
1762 if (ncommits == s->selected) {
1763 s->selected_entry = entry;
1764 break;
1766 entry = TAILQ_NEXT(entry, entry);
1767 ncommits++;
1771 static const struct got_error *
1772 draw_commits(struct tog_view *view)
1774 const struct got_error *err = NULL;
1775 struct tog_log_view_state *s = &view->state.log;
1776 struct commit_queue_entry *entry = s->selected_entry;
1777 const int limit = view->nlines;
1778 int width;
1779 int ncommits, author_cols = 4;
1780 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
1781 char *refs_str = NULL;
1782 wchar_t *wline;
1783 struct tog_color *tc;
1784 static const size_t date_display_cols = 12;
1786 if (s->selected_entry &&
1787 !(view->searching && view->search_next_done == 0)) {
1788 struct got_reflist_head *refs;
1789 err = got_object_id_str(&id_str, s->selected_entry->id);
1790 if (err)
1791 return err;
1792 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
1793 s->selected_entry->id);
1794 if (refs) {
1795 err = build_refs_str(&refs_str, refs,
1796 s->selected_entry->id, s->repo);
1797 if (err)
1798 goto done;
1802 if (s->thread_args.commits_needed == 0)
1803 halfdelay(10); /* disable fast refresh */
1805 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
1806 if (asprintf(&ncommits_str, " [%d/%d] %s",
1807 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1808 (view->searching && !view->search_next_done) ?
1809 "searching..." : "loading...") == -1) {
1810 err = got_error_from_errno("asprintf");
1811 goto done;
1813 } else {
1814 const char *search_str = NULL;
1816 if (view->searching) {
1817 if (view->search_next_done == TOG_SEARCH_NO_MORE)
1818 search_str = "no more matches";
1819 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
1820 search_str = "no matches found";
1821 else if (!view->search_next_done)
1822 search_str = "searching...";
1825 if (asprintf(&ncommits_str, " [%d/%d] %s",
1826 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1827 search_str ? search_str :
1828 (refs_str ? refs_str : "")) == -1) {
1829 err = got_error_from_errno("asprintf");
1830 goto done;
1834 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
1835 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
1836 "........................................",
1837 s->in_repo_path, ncommits_str) == -1) {
1838 err = got_error_from_errno("asprintf");
1839 header = NULL;
1840 goto done;
1842 } else if (asprintf(&header, "commit %s%s",
1843 id_str ? id_str : "........................................",
1844 ncommits_str) == -1) {
1845 err = got_error_from_errno("asprintf");
1846 header = NULL;
1847 goto done;
1849 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
1850 if (err)
1851 goto done;
1853 werase(view->window);
1855 if (view_needs_focus_indication(view))
1856 wstandout(view->window);
1857 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1858 if (tc)
1859 wattr_on(view->window,
1860 COLOR_PAIR(tc->colorpair), NULL);
1861 waddwstr(view->window, wline);
1862 if (tc)
1863 wattr_off(view->window,
1864 COLOR_PAIR(tc->colorpair), NULL);
1865 while (width < view->ncols) {
1866 waddch(view->window, ' ');
1867 width++;
1869 if (view_needs_focus_indication(view))
1870 wstandend(view->window);
1871 free(wline);
1872 if (limit <= 1)
1873 goto done;
1875 /* Grow author column size if necessary, and set view->maxx. */
1876 entry = s->first_displayed_entry;
1877 ncommits = 0;
1878 view->maxx = 0;
1879 while (entry) {
1880 char *author, *eol, *msg, *msg0;
1881 wchar_t *wauthor, *wmsg;
1882 int width;
1883 if (ncommits >= limit - 1)
1884 break;
1885 author = strdup(got_object_commit_get_author(entry->commit));
1886 if (author == NULL) {
1887 err = got_error_from_errno("strdup");
1888 goto done;
1890 err = format_author(&wauthor, &width, author, COLS,
1891 date_display_cols);
1892 if (author_cols < width)
1893 author_cols = width;
1894 free(wauthor);
1895 free(author);
1896 err = got_object_commit_get_logmsg(&msg0, entry->commit);
1897 if (err)
1898 goto done;
1899 msg = msg0;
1900 while (*msg == '\n')
1901 ++msg;
1902 if ((eol = strchr(msg, '\n')))
1903 *eol = '\0';
1904 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
1905 date_display_cols + author_cols, 0);
1906 if (err)
1907 goto done;
1908 view->maxx = MAX(view->maxx, width);
1909 free(msg0);
1910 free(wmsg);
1911 ncommits++;
1912 entry = TAILQ_NEXT(entry, entry);
1915 entry = s->first_displayed_entry;
1916 s->last_displayed_entry = s->first_displayed_entry;
1917 ncommits = 0;
1918 while (entry) {
1919 if (ncommits >= limit - 1)
1920 break;
1921 if (ncommits == s->selected)
1922 wstandout(view->window);
1923 err = draw_commit(view, entry->commit, entry->id,
1924 date_display_cols, author_cols);
1925 if (ncommits == s->selected)
1926 wstandend(view->window);
1927 if (err)
1928 goto done;
1929 ncommits++;
1930 s->last_displayed_entry = entry;
1931 entry = TAILQ_NEXT(entry, entry);
1934 view_vborder(view);
1935 done:
1936 free(id_str);
1937 free(refs_str);
1938 free(ncommits_str);
1939 free(header);
1940 return err;
1943 static void
1944 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
1946 struct commit_queue_entry *entry;
1947 int nscrolled = 0;
1949 entry = TAILQ_FIRST(&s->commits.head);
1950 if (s->first_displayed_entry == entry)
1951 return;
1953 entry = s->first_displayed_entry;
1954 while (entry && nscrolled < maxscroll) {
1955 entry = TAILQ_PREV(entry, commit_queue_head, entry);
1956 if (entry) {
1957 s->first_displayed_entry = entry;
1958 nscrolled++;
1963 static const struct got_error *
1964 trigger_log_thread(struct tog_view *view, int wait)
1966 struct tog_log_thread_args *ta = &view->state.log.thread_args;
1967 int errcode;
1969 halfdelay(1); /* fast refresh while loading commits */
1971 while (ta->commits_needed > 0 || ta->load_all) {
1972 if (ta->log_complete)
1973 break;
1975 /* Wake the log thread. */
1976 errcode = pthread_cond_signal(&ta->need_commits);
1977 if (errcode)
1978 return got_error_set_errno(errcode,
1979 "pthread_cond_signal");
1982 * The mutex will be released while the view loop waits
1983 * in wgetch(), at which time the log thread will run.
1985 if (!wait)
1986 break;
1988 /* Display progress update in log view. */
1989 show_log_view(view);
1990 update_panels();
1991 doupdate();
1993 /* Wait right here while next commit is being loaded. */
1994 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
1995 if (errcode)
1996 return got_error_set_errno(errcode,
1997 "pthread_cond_wait");
1999 /* Display progress update in log view. */
2000 show_log_view(view);
2001 update_panels();
2002 doupdate();
2005 return NULL;
2008 static const struct got_error *
2009 log_scroll_down(struct tog_view *view, int maxscroll)
2011 struct tog_log_view_state *s = &view->state.log;
2012 const struct got_error *err = NULL;
2013 struct commit_queue_entry *pentry;
2014 int nscrolled = 0, ncommits_needed;
2016 if (s->last_displayed_entry == NULL)
2017 return NULL;
2019 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2020 if (s->commits.ncommits < ncommits_needed &&
2021 !s->thread_args.log_complete) {
2023 * Ask the log thread for required amount of commits.
2025 s->thread_args.commits_needed += maxscroll;
2026 err = trigger_log_thread(view, 1);
2027 if (err)
2028 return err;
2031 do {
2032 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2033 if (pentry == NULL)
2034 break;
2036 s->last_displayed_entry = pentry;
2038 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2039 if (pentry == NULL)
2040 break;
2041 s->first_displayed_entry = pentry;
2042 } while (++nscrolled < maxscroll);
2044 return err;
2047 static const struct got_error *
2048 open_diff_view_for_commit(struct tog_view **new_view, int begin_x,
2049 struct got_commit_object *commit, struct got_object_id *commit_id,
2050 struct tog_view *log_view, struct got_repository *repo)
2052 const struct got_error *err;
2053 struct got_object_qid *parent_id;
2054 struct tog_view *diff_view;
2056 diff_view = view_open(0, 0, 0, begin_x, TOG_VIEW_DIFF);
2057 if (diff_view == NULL)
2058 return got_error_from_errno("view_open");
2060 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2061 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2062 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2063 if (err == NULL)
2064 *new_view = diff_view;
2065 return err;
2068 static const struct got_error *
2069 tree_view_visit_subtree(struct tog_tree_view_state *s,
2070 struct got_tree_object *subtree)
2072 struct tog_parent_tree *parent;
2074 parent = calloc(1, sizeof(*parent));
2075 if (parent == NULL)
2076 return got_error_from_errno("calloc");
2078 parent->tree = s->tree;
2079 parent->first_displayed_entry = s->first_displayed_entry;
2080 parent->selected_entry = s->selected_entry;
2081 parent->selected = s->selected;
2082 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2083 s->tree = subtree;
2084 s->selected = 0;
2085 s->first_displayed_entry = NULL;
2086 return NULL;
2089 static const struct got_error *
2090 tree_view_walk_path(struct tog_tree_view_state *s,
2091 struct got_commit_object *commit, const char *path)
2093 const struct got_error *err = NULL;
2094 struct got_tree_object *tree = NULL;
2095 const char *p;
2096 char *slash, *subpath = NULL;
2098 /* Walk the path and open corresponding tree objects. */
2099 p = path;
2100 while (*p) {
2101 struct got_tree_entry *te;
2102 struct got_object_id *tree_id;
2103 char *te_name;
2105 while (p[0] == '/')
2106 p++;
2108 /* Ensure the correct subtree entry is selected. */
2109 slash = strchr(p, '/');
2110 if (slash == NULL)
2111 te_name = strdup(p);
2112 else
2113 te_name = strndup(p, slash - p);
2114 if (te_name == NULL) {
2115 err = got_error_from_errno("strndup");
2116 break;
2118 te = got_object_tree_find_entry(s->tree, te_name);
2119 if (te == NULL) {
2120 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2121 free(te_name);
2122 break;
2124 free(te_name);
2125 s->first_displayed_entry = s->selected_entry = te;
2127 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2128 break; /* jump to this file's entry */
2130 slash = strchr(p, '/');
2131 if (slash)
2132 subpath = strndup(path, slash - path);
2133 else
2134 subpath = strdup(path);
2135 if (subpath == NULL) {
2136 err = got_error_from_errno("strdup");
2137 break;
2140 err = got_object_id_by_path(&tree_id, s->repo, commit,
2141 subpath);
2142 if (err)
2143 break;
2145 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2146 free(tree_id);
2147 if (err)
2148 break;
2150 err = tree_view_visit_subtree(s, tree);
2151 if (err) {
2152 got_object_tree_close(tree);
2153 break;
2155 if (slash == NULL)
2156 break;
2157 free(subpath);
2158 subpath = NULL;
2159 p = slash;
2162 free(subpath);
2163 return err;
2166 static const struct got_error *
2167 browse_commit_tree(struct tog_view **new_view, int begin_x,
2168 struct commit_queue_entry *entry, const char *path,
2169 const char *head_ref_name, struct got_repository *repo)
2171 const struct got_error *err = NULL;
2172 struct tog_tree_view_state *s;
2173 struct tog_view *tree_view;
2175 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
2176 if (tree_view == NULL)
2177 return got_error_from_errno("view_open");
2179 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2180 if (err)
2181 return err;
2182 s = &tree_view->state.tree;
2184 *new_view = tree_view;
2186 if (got_path_is_root_dir(path))
2187 return NULL;
2189 return tree_view_walk_path(s, entry->commit, path);
2192 static const struct got_error *
2193 block_signals_used_by_main_thread(void)
2195 sigset_t sigset;
2196 int errcode;
2198 if (sigemptyset(&sigset) == -1)
2199 return got_error_from_errno("sigemptyset");
2201 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2202 if (sigaddset(&sigset, SIGWINCH) == -1)
2203 return got_error_from_errno("sigaddset");
2204 if (sigaddset(&sigset, SIGCONT) == -1)
2205 return got_error_from_errno("sigaddset");
2206 if (sigaddset(&sigset, SIGINT) == -1)
2207 return got_error_from_errno("sigaddset");
2208 if (sigaddset(&sigset, SIGTERM) == -1)
2209 return got_error_from_errno("sigaddset");
2211 /* ncurses handles SIGTSTP */
2212 if (sigaddset(&sigset, SIGTSTP) == -1)
2213 return got_error_from_errno("sigaddset");
2215 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2216 if (errcode)
2217 return got_error_set_errno(errcode, "pthread_sigmask");
2219 return NULL;
2222 static void *
2223 log_thread(void *arg)
2225 const struct got_error *err = NULL;
2226 int errcode = 0;
2227 struct tog_log_thread_args *a = arg;
2228 int done = 0;
2230 err = block_signals_used_by_main_thread();
2231 if (err)
2232 return (void *)err;
2234 while (!done && !err && !tog_fatal_signal_received()) {
2235 err = queue_commits(a);
2236 if (err) {
2237 if (err->code != GOT_ERR_ITER_COMPLETED)
2238 return (void *)err;
2239 err = NULL;
2240 done = 1;
2241 } else if (a->commits_needed > 0 && !a->load_all)
2242 a->commits_needed--;
2244 errcode = pthread_mutex_lock(&tog_mutex);
2245 if (errcode) {
2246 err = got_error_set_errno(errcode,
2247 "pthread_mutex_lock");
2248 break;
2249 } else if (*a->quit)
2250 done = 1;
2251 else if (*a->first_displayed_entry == NULL) {
2252 *a->first_displayed_entry =
2253 TAILQ_FIRST(&a->commits->head);
2254 *a->selected_entry = *a->first_displayed_entry;
2257 errcode = pthread_cond_signal(&a->commit_loaded);
2258 if (errcode) {
2259 err = got_error_set_errno(errcode,
2260 "pthread_cond_signal");
2261 pthread_mutex_unlock(&tog_mutex);
2262 break;
2265 if (done)
2266 a->commits_needed = 0;
2267 else {
2268 if (a->commits_needed == 0 && !a->load_all) {
2269 errcode = pthread_cond_wait(&a->need_commits,
2270 &tog_mutex);
2271 if (errcode)
2272 err = got_error_set_errno(errcode,
2273 "pthread_cond_wait");
2274 if (*a->quit)
2275 done = 1;
2279 errcode = pthread_mutex_unlock(&tog_mutex);
2280 if (errcode && err == NULL)
2281 err = got_error_set_errno(errcode,
2282 "pthread_mutex_unlock");
2284 a->log_complete = 1;
2285 return (void *)err;
2288 static const struct got_error *
2289 stop_log_thread(struct tog_log_view_state *s)
2291 const struct got_error *err = NULL;
2292 int errcode;
2294 if (s->thread) {
2295 s->quit = 1;
2296 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2297 if (errcode)
2298 return got_error_set_errno(errcode,
2299 "pthread_cond_signal");
2300 errcode = pthread_mutex_unlock(&tog_mutex);
2301 if (errcode)
2302 return got_error_set_errno(errcode,
2303 "pthread_mutex_unlock");
2304 errcode = pthread_join(s->thread, (void **)&err);
2305 if (errcode)
2306 return got_error_set_errno(errcode, "pthread_join");
2307 errcode = pthread_mutex_lock(&tog_mutex);
2308 if (errcode)
2309 return got_error_set_errno(errcode,
2310 "pthread_mutex_lock");
2311 s->thread = NULL;
2314 if (s->thread_args.repo) {
2315 err = got_repo_close(s->thread_args.repo);
2316 s->thread_args.repo = NULL;
2319 if (s->thread_args.pack_fds) {
2320 const struct got_error *pack_err =
2321 got_repo_pack_fds_close(s->thread_args.pack_fds);
2322 if (err == NULL)
2323 err = pack_err;
2324 s->thread_args.pack_fds = NULL;
2327 if (s->thread_args.graph) {
2328 got_commit_graph_close(s->thread_args.graph);
2329 s->thread_args.graph = NULL;
2332 return err;
2335 static const struct got_error *
2336 close_log_view(struct tog_view *view)
2338 const struct got_error *err = NULL;
2339 struct tog_log_view_state *s = &view->state.log;
2340 int errcode;
2342 err = stop_log_thread(s);
2344 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2345 if (errcode && err == NULL)
2346 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2348 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2349 if (errcode && err == NULL)
2350 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2352 free_commits(&s->commits);
2353 free(s->in_repo_path);
2354 s->in_repo_path = NULL;
2355 free(s->start_id);
2356 s->start_id = NULL;
2357 free(s->head_ref_name);
2358 s->head_ref_name = NULL;
2359 return err;
2362 static const struct got_error *
2363 search_start_log_view(struct tog_view *view)
2365 struct tog_log_view_state *s = &view->state.log;
2367 s->matched_entry = NULL;
2368 s->search_entry = NULL;
2369 return NULL;
2372 static const struct got_error *
2373 search_next_log_view(struct tog_view *view)
2375 const struct got_error *err = NULL;
2376 struct tog_log_view_state *s = &view->state.log;
2377 struct commit_queue_entry *entry;
2379 /* Display progress update in log view. */
2380 show_log_view(view);
2381 update_panels();
2382 doupdate();
2384 if (s->search_entry) {
2385 int errcode, ch;
2386 errcode = pthread_mutex_unlock(&tog_mutex);
2387 if (errcode)
2388 return got_error_set_errno(errcode,
2389 "pthread_mutex_unlock");
2390 ch = wgetch(view->window);
2391 errcode = pthread_mutex_lock(&tog_mutex);
2392 if (errcode)
2393 return got_error_set_errno(errcode,
2394 "pthread_mutex_lock");
2395 if (ch == KEY_BACKSPACE) {
2396 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2397 return NULL;
2399 if (view->searching == TOG_SEARCH_FORWARD)
2400 entry = TAILQ_NEXT(s->search_entry, entry);
2401 else
2402 entry = TAILQ_PREV(s->search_entry,
2403 commit_queue_head, entry);
2404 } else if (s->matched_entry) {
2405 int matched_idx = s->matched_entry->idx;
2406 int selected_idx = s->selected_entry->idx;
2409 * If the user has moved the cursor after we hit a match,
2410 * the position from where we should continue searching
2411 * might have changed.
2413 if (view->searching == TOG_SEARCH_FORWARD) {
2414 if (matched_idx > selected_idx)
2415 entry = TAILQ_NEXT(s->selected_entry, entry);
2416 else
2417 entry = TAILQ_NEXT(s->matched_entry, entry);
2418 } else {
2419 if (matched_idx < selected_idx)
2420 entry = TAILQ_PREV(s->selected_entry,
2421 commit_queue_head, entry);
2422 else
2423 entry = TAILQ_PREV(s->matched_entry,
2424 commit_queue_head, entry);
2426 } else {
2427 entry = s->selected_entry;
2430 while (1) {
2431 int have_match = 0;
2433 if (entry == NULL) {
2434 if (s->thread_args.log_complete ||
2435 view->searching == TOG_SEARCH_BACKWARD) {
2436 view->search_next_done =
2437 (s->matched_entry == NULL ?
2438 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2439 s->search_entry = NULL;
2440 return NULL;
2443 * Poke the log thread for more commits and return,
2444 * allowing the main loop to make progress. Search
2445 * will resume at s->search_entry once we come back.
2447 s->thread_args.commits_needed++;
2448 return trigger_log_thread(view, 0);
2451 err = match_commit(&have_match, entry->id, entry->commit,
2452 &view->regex);
2453 if (err)
2454 break;
2455 if (have_match) {
2456 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2457 s->matched_entry = entry;
2458 break;
2461 s->search_entry = entry;
2462 if (view->searching == TOG_SEARCH_FORWARD)
2463 entry = TAILQ_NEXT(entry, entry);
2464 else
2465 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2468 if (s->matched_entry) {
2469 int cur = s->selected_entry->idx;
2470 while (cur < s->matched_entry->idx) {
2471 err = input_log_view(NULL, view, KEY_DOWN);
2472 if (err)
2473 return err;
2474 cur++;
2476 while (cur > s->matched_entry->idx) {
2477 err = input_log_view(NULL, view, KEY_UP);
2478 if (err)
2479 return err;
2480 cur--;
2484 s->search_entry = NULL;
2486 return NULL;
2489 static const struct got_error *
2490 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2491 struct got_repository *repo, const char *head_ref_name,
2492 const char *in_repo_path, int log_branches)
2494 const struct got_error *err = NULL;
2495 struct tog_log_view_state *s = &view->state.log;
2496 struct got_repository *thread_repo = NULL;
2497 struct got_commit_graph *thread_graph = NULL;
2498 int errcode;
2500 if (in_repo_path != s->in_repo_path) {
2501 free(s->in_repo_path);
2502 s->in_repo_path = strdup(in_repo_path);
2503 if (s->in_repo_path == NULL)
2504 return got_error_from_errno("strdup");
2507 /* The commit queue only contains commits being displayed. */
2508 TAILQ_INIT(&s->commits.head);
2509 s->commits.ncommits = 0;
2511 s->repo = repo;
2512 if (head_ref_name) {
2513 s->head_ref_name = strdup(head_ref_name);
2514 if (s->head_ref_name == NULL) {
2515 err = got_error_from_errno("strdup");
2516 goto done;
2519 s->start_id = got_object_id_dup(start_id);
2520 if (s->start_id == NULL) {
2521 err = got_error_from_errno("got_object_id_dup");
2522 goto done;
2524 s->log_branches = log_branches;
2526 STAILQ_INIT(&s->colors);
2527 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2528 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2529 get_color_value("TOG_COLOR_COMMIT"));
2530 if (err)
2531 goto done;
2532 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2533 get_color_value("TOG_COLOR_AUTHOR"));
2534 if (err) {
2535 free_colors(&s->colors);
2536 goto done;
2538 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
2539 get_color_value("TOG_COLOR_DATE"));
2540 if (err) {
2541 free_colors(&s->colors);
2542 goto done;
2546 view->show = show_log_view;
2547 view->input = input_log_view;
2548 view->close = close_log_view;
2549 view->search_start = search_start_log_view;
2550 view->search_next = search_next_log_view;
2552 if (s->thread_args.pack_fds == NULL) {
2553 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2554 if (err)
2555 goto done;
2557 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
2558 s->thread_args.pack_fds);
2559 if (err)
2560 goto done;
2561 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
2562 !s->log_branches);
2563 if (err)
2564 goto done;
2565 err = got_commit_graph_iter_start(thread_graph, s->start_id,
2566 s->repo, NULL, NULL);
2567 if (err)
2568 goto done;
2570 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
2571 if (errcode) {
2572 err = got_error_set_errno(errcode, "pthread_cond_init");
2573 goto done;
2575 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
2576 if (errcode) {
2577 err = got_error_set_errno(errcode, "pthread_cond_init");
2578 goto done;
2581 s->thread_args.commits_needed = view->nlines;
2582 s->thread_args.graph = thread_graph;
2583 s->thread_args.commits = &s->commits;
2584 s->thread_args.in_repo_path = s->in_repo_path;
2585 s->thread_args.start_id = s->start_id;
2586 s->thread_args.repo = thread_repo;
2587 s->thread_args.log_complete = 0;
2588 s->thread_args.quit = &s->quit;
2589 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
2590 s->thread_args.selected_entry = &s->selected_entry;
2591 s->thread_args.searching = &view->searching;
2592 s->thread_args.search_next_done = &view->search_next_done;
2593 s->thread_args.regex = &view->regex;
2594 done:
2595 if (err)
2596 close_log_view(view);
2597 return err;
2600 static const struct got_error *
2601 show_log_view(struct tog_view *view)
2603 const struct got_error *err;
2604 struct tog_log_view_state *s = &view->state.log;
2606 if (s->thread == NULL) {
2607 int errcode = pthread_create(&s->thread, NULL, log_thread,
2608 &s->thread_args);
2609 if (errcode)
2610 return got_error_set_errno(errcode, "pthread_create");
2611 if (s->thread_args.commits_needed > 0) {
2612 err = trigger_log_thread(view, 1);
2613 if (err)
2614 return err;
2618 return draw_commits(view);
2621 static const struct got_error *
2622 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
2624 const struct got_error *err = NULL;
2625 struct tog_log_view_state *s = &view->state.log;
2626 struct tog_view *diff_view = NULL, *tree_view = NULL;
2627 struct tog_view *ref_view = NULL;
2628 struct commit_queue_entry *entry;
2629 int begin_x = 0, n, nscroll = view->nlines - 1;
2631 if (s->thread_args.load_all) {
2632 if (ch == KEY_BACKSPACE)
2633 s->thread_args.load_all = 0;
2634 else if (s->thread_args.log_complete) {
2635 s->thread_args.load_all = 0;
2636 log_scroll_down(view, s->commits.ncommits);
2637 s->selected = MIN(view->nlines - 2,
2638 s->commits.ncommits - 1);
2639 select_commit(s);
2641 return NULL;
2644 switch (ch) {
2645 case 'q':
2646 s->quit = 1;
2647 break;
2648 case '0':
2649 view->x = 0;
2650 break;
2651 case '$':
2652 view->x = MAX(view->maxx - view->ncols / 2, 0);
2653 view->count = 0;
2654 break;
2655 case KEY_RIGHT:
2656 case 'l':
2657 if (view->x + view->ncols / 2 < view->maxx)
2658 view->x += 2; /* move two columns right */
2659 else
2660 view->count = 0;
2661 break;
2662 case KEY_LEFT:
2663 case 'h':
2664 view->x -= MIN(view->x, 2); /* move two columns back */
2665 if (view->x <= 0)
2666 view->count = 0;
2667 break;
2668 case 'k':
2669 case KEY_UP:
2670 case '<':
2671 case ',':
2672 case CTRL('p'):
2673 if (s->selected_entry->idx == 0)
2674 view->count = 0;
2675 if (s->first_displayed_entry == NULL)
2676 break;
2677 if (s->selected > 0)
2678 s->selected--;
2679 else
2680 log_scroll_up(s, 1);
2681 select_commit(s);
2682 break;
2683 case 'g':
2684 case KEY_HOME:
2685 s->selected = 0;
2686 s->first_displayed_entry = TAILQ_FIRST(&s->commits.head);
2687 select_commit(s);
2688 view->count = 0;
2689 break;
2690 case CTRL('u'):
2691 case 'u':
2692 nscroll /= 2;
2693 /* FALL THROUGH */
2694 case KEY_PPAGE:
2695 case CTRL('b'):
2696 case 'b':
2697 if (s->first_displayed_entry == NULL)
2698 break;
2699 if (TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
2700 s->selected = MAX(0, s->selected - nscroll - 1);
2701 else
2702 log_scroll_up(s, nscroll);
2703 select_commit(s);
2704 if (s->selected_entry->idx == 0)
2705 view->count = 0;
2706 break;
2707 case 'j':
2708 case KEY_DOWN:
2709 case '>':
2710 case '.':
2711 case CTRL('n'):
2712 if (s->first_displayed_entry == NULL)
2713 break;
2714 if (s->selected < MIN(view->nlines - 2,
2715 s->commits.ncommits - 1))
2716 s->selected++;
2717 else {
2718 err = log_scroll_down(view, 1);
2719 if (err)
2720 break;
2722 select_commit(s);
2723 if (s->thread_args.log_complete &&
2724 s->selected_entry->idx == s->commits.ncommits - 1)
2725 view->count = 0;
2726 break;
2727 case 'G':
2728 case KEY_END: {
2729 /* We don't know yet how many commits, so we're forced to
2730 * traverse them all. */
2731 view->count = 0;
2732 if (!s->thread_args.log_complete) {
2733 s->thread_args.load_all = 1;
2734 return trigger_log_thread(view, 0);
2737 s->selected = 0;
2738 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
2739 for (n = 0; n < view->nlines - 1; n++) {
2740 if (entry == NULL)
2741 break;
2742 s->first_displayed_entry = entry;
2743 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2745 if (n > 0)
2746 s->selected = n - 1;
2747 select_commit(s);
2748 break;
2750 case CTRL('d'):
2751 case 'd':
2752 nscroll /= 2;
2753 /* FALL THROUGH */
2754 case KEY_NPAGE:
2755 case CTRL('f'):
2756 case 'f':
2757 case ' ': {
2758 struct commit_queue_entry *first;
2759 first = s->first_displayed_entry;
2760 if (first == NULL) {
2761 view->count = 0;
2762 break;
2764 err = log_scroll_down(view, nscroll);
2765 if (err)
2766 break;
2767 if (first == s->first_displayed_entry &&
2768 s->selected < MIN(view->nlines - 2,
2769 s->commits.ncommits - 1)) {
2770 /* can't scroll further down */
2771 s->selected += MIN(s->last_displayed_entry->idx -
2772 s->selected_entry->idx, nscroll + 1);
2774 select_commit(s);
2775 if (s->thread_args.log_complete &&
2776 s->selected_entry->idx == s->commits.ncommits - 1)
2777 view->count = 0;
2778 break;
2780 case KEY_RESIZE:
2781 if (s->selected > view->nlines - 2)
2782 s->selected = view->nlines - 2;
2783 if (s->selected > s->commits.ncommits - 1)
2784 s->selected = s->commits.ncommits - 1;
2785 select_commit(s);
2786 if (s->commits.ncommits < view->nlines - 1 &&
2787 !s->thread_args.log_complete) {
2788 s->thread_args.commits_needed += (view->nlines - 1) -
2789 s->commits.ncommits;
2790 err = trigger_log_thread(view, 1);
2792 break;
2793 case KEY_ENTER:
2794 case '\r':
2795 view->count = 0;
2796 if (s->selected_entry == NULL)
2797 break;
2798 if (view_is_parent_view(view))
2799 begin_x = view_split_begin_x(view->begin_x);
2800 err = open_diff_view_for_commit(&diff_view, begin_x,
2801 s->selected_entry->commit, s->selected_entry->id,
2802 view, s->repo);
2803 if (err)
2804 break;
2805 view->focussed = 0;
2806 diff_view->focussed = 1;
2807 if (view_is_parent_view(view)) {
2808 err = view_close_child(view);
2809 if (err)
2810 return err;
2811 err = view_set_child(view, diff_view);
2812 if (err)
2813 return err;
2814 view->focus_child = 1;
2815 } else
2816 *new_view = diff_view;
2817 break;
2818 case 't':
2819 view->count = 0;
2820 if (s->selected_entry == NULL)
2821 break;
2822 if (view_is_parent_view(view))
2823 begin_x = view_split_begin_x(view->begin_x);
2824 err = browse_commit_tree(&tree_view, begin_x,
2825 s->selected_entry, s->in_repo_path, s->head_ref_name,
2826 s->repo);
2827 if (err)
2828 break;
2829 view->focussed = 0;
2830 tree_view->focussed = 1;
2831 if (view_is_parent_view(view)) {
2832 err = view_close_child(view);
2833 if (err)
2834 return err;
2835 err = view_set_child(view, tree_view);
2836 if (err)
2837 return err;
2838 view->focus_child = 1;
2839 } else
2840 *new_view = tree_view;
2841 break;
2842 case KEY_BACKSPACE:
2843 case CTRL('l'):
2844 case 'B':
2845 view->count = 0;
2846 if (ch == KEY_BACKSPACE &&
2847 got_path_is_root_dir(s->in_repo_path))
2848 break;
2849 err = stop_log_thread(s);
2850 if (err)
2851 return err;
2852 if (ch == KEY_BACKSPACE) {
2853 char *parent_path;
2854 err = got_path_dirname(&parent_path, s->in_repo_path);
2855 if (err)
2856 return err;
2857 free(s->in_repo_path);
2858 s->in_repo_path = parent_path;
2859 s->thread_args.in_repo_path = s->in_repo_path;
2860 } else if (ch == CTRL('l')) {
2861 struct got_object_id *start_id;
2862 err = got_repo_match_object_id(&start_id, NULL,
2863 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
2864 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
2865 if (err)
2866 return err;
2867 free(s->start_id);
2868 s->start_id = start_id;
2869 s->thread_args.start_id = s->start_id;
2870 } else /* 'B' */
2871 s->log_branches = !s->log_branches;
2873 if (s->thread_args.pack_fds == NULL) {
2874 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2875 if (err)
2876 return err;
2878 err = got_repo_open(&s->thread_args.repo,
2879 got_repo_get_path(s->repo), NULL,
2880 s->thread_args.pack_fds);
2881 if (err)
2882 return err;
2883 tog_free_refs();
2884 err = tog_load_refs(s->repo, 0);
2885 if (err)
2886 return err;
2887 err = got_commit_graph_open(&s->thread_args.graph,
2888 s->in_repo_path, !s->log_branches);
2889 if (err)
2890 return err;
2891 err = got_commit_graph_iter_start(s->thread_args.graph,
2892 s->start_id, s->repo, NULL, NULL);
2893 if (err)
2894 return err;
2895 free_commits(&s->commits);
2896 s->first_displayed_entry = NULL;
2897 s->last_displayed_entry = NULL;
2898 s->selected_entry = NULL;
2899 s->selected = 0;
2900 s->thread_args.log_complete = 0;
2901 s->quit = 0;
2902 s->thread_args.commits_needed = view->nlines;
2903 s->matched_entry = NULL;
2904 s->search_entry = NULL;
2905 break;
2906 case 'r':
2907 view->count = 0;
2908 if (view_is_parent_view(view))
2909 begin_x = view_split_begin_x(view->begin_x);
2910 ref_view = view_open(view->nlines, view->ncols,
2911 view->begin_y, begin_x, TOG_VIEW_REF);
2912 if (ref_view == NULL)
2913 return got_error_from_errno("view_open");
2914 err = open_ref_view(ref_view, s->repo);
2915 if (err) {
2916 view_close(ref_view);
2917 return err;
2919 view->focussed = 0;
2920 ref_view->focussed = 1;
2921 if (view_is_parent_view(view)) {
2922 err = view_close_child(view);
2923 if (err)
2924 return err;
2925 err = view_set_child(view, ref_view);
2926 if (err)
2927 return err;
2928 view->focus_child = 1;
2929 } else
2930 *new_view = ref_view;
2931 break;
2932 default:
2933 view->count = 0;
2934 break;
2937 return err;
2940 static const struct got_error *
2941 apply_unveil(const char *repo_path, const char *worktree_path)
2943 const struct got_error *error;
2945 #ifdef PROFILE
2946 if (unveil("gmon.out", "rwc") != 0)
2947 return got_error_from_errno2("unveil", "gmon.out");
2948 #endif
2949 if (repo_path && unveil(repo_path, "r") != 0)
2950 return got_error_from_errno2("unveil", repo_path);
2952 if (worktree_path && unveil(worktree_path, "rwc") != 0)
2953 return got_error_from_errno2("unveil", worktree_path);
2955 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
2956 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
2958 error = got_privsep_unveil_exec_helpers();
2959 if (error != NULL)
2960 return error;
2962 if (unveil(NULL, NULL) != 0)
2963 return got_error_from_errno("unveil");
2965 return NULL;
2968 static void
2969 init_curses(void)
2972 * Override default signal handlers before starting ncurses.
2973 * This should prevent ncurses from installing its own
2974 * broken cleanup() signal handler.
2976 signal(SIGWINCH, tog_sigwinch);
2977 signal(SIGPIPE, tog_sigpipe);
2978 signal(SIGCONT, tog_sigcont);
2979 signal(SIGINT, tog_sigint);
2980 signal(SIGTERM, tog_sigterm);
2982 initscr();
2983 cbreak();
2984 halfdelay(1); /* Do fast refresh while initial view is loading. */
2985 noecho();
2986 nonl();
2987 intrflush(stdscr, FALSE);
2988 keypad(stdscr, TRUE);
2989 curs_set(0);
2990 if (getenv("TOG_COLORS") != NULL) {
2991 start_color();
2992 use_default_colors();
2996 static const struct got_error *
2997 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
2998 struct got_repository *repo, struct got_worktree *worktree)
3000 const struct got_error *err = NULL;
3002 if (argc == 0) {
3003 *in_repo_path = strdup("/");
3004 if (*in_repo_path == NULL)
3005 return got_error_from_errno("strdup");
3006 return NULL;
3009 if (worktree) {
3010 const char *prefix = got_worktree_get_path_prefix(worktree);
3011 char *p;
3013 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3014 if (err)
3015 return err;
3016 if (asprintf(in_repo_path, "%s%s%s", prefix,
3017 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3018 p) == -1) {
3019 err = got_error_from_errno("asprintf");
3020 *in_repo_path = NULL;
3022 free(p);
3023 } else
3024 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3026 return err;
3029 static const struct got_error *
3030 cmd_log(int argc, char *argv[])
3032 const struct got_error *error;
3033 struct got_repository *repo = NULL;
3034 struct got_worktree *worktree = NULL;
3035 struct got_object_id *start_id = NULL;
3036 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3037 char *start_commit = NULL, *label = NULL;
3038 struct got_reference *ref = NULL;
3039 const char *head_ref_name = NULL;
3040 int ch, log_branches = 0;
3041 struct tog_view *view;
3042 int *pack_fds = NULL;
3044 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3045 switch (ch) {
3046 case 'b':
3047 log_branches = 1;
3048 break;
3049 case 'c':
3050 start_commit = optarg;
3051 break;
3052 case 'r':
3053 repo_path = realpath(optarg, NULL);
3054 if (repo_path == NULL)
3055 return got_error_from_errno2("realpath",
3056 optarg);
3057 break;
3058 default:
3059 usage_log();
3060 /* NOTREACHED */
3064 argc -= optind;
3065 argv += optind;
3067 if (argc > 1)
3068 usage_log();
3070 error = got_repo_pack_fds_open(&pack_fds);
3071 if (error != NULL)
3072 goto done;
3074 if (repo_path == NULL) {
3075 cwd = getcwd(NULL, 0);
3076 if (cwd == NULL)
3077 return got_error_from_errno("getcwd");
3078 error = got_worktree_open(&worktree, cwd);
3079 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3080 goto done;
3081 if (worktree)
3082 repo_path =
3083 strdup(got_worktree_get_repo_path(worktree));
3084 else
3085 repo_path = strdup(cwd);
3086 if (repo_path == NULL) {
3087 error = got_error_from_errno("strdup");
3088 goto done;
3092 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3093 if (error != NULL)
3094 goto done;
3096 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3097 repo, worktree);
3098 if (error)
3099 goto done;
3101 init_curses();
3103 error = apply_unveil(got_repo_get_path(repo),
3104 worktree ? got_worktree_get_root_path(worktree) : NULL);
3105 if (error)
3106 goto done;
3108 /* already loaded by tog_log_with_path()? */
3109 if (TAILQ_EMPTY(&tog_refs)) {
3110 error = tog_load_refs(repo, 0);
3111 if (error)
3112 goto done;
3115 if (start_commit == NULL) {
3116 error = got_repo_match_object_id(&start_id, &label,
3117 worktree ? got_worktree_get_head_ref_name(worktree) :
3118 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3119 if (error)
3120 goto done;
3121 head_ref_name = label;
3122 } else {
3123 error = got_ref_open(&ref, repo, start_commit, 0);
3124 if (error == NULL)
3125 head_ref_name = got_ref_get_name(ref);
3126 else if (error->code != GOT_ERR_NOT_REF)
3127 goto done;
3128 error = got_repo_match_object_id(&start_id, NULL,
3129 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3130 if (error)
3131 goto done;
3134 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3135 if (view == NULL) {
3136 error = got_error_from_errno("view_open");
3137 goto done;
3139 error = open_log_view(view, start_id, repo, head_ref_name,
3140 in_repo_path, log_branches);
3141 if (error)
3142 goto done;
3143 if (worktree) {
3144 /* Release work tree lock. */
3145 got_worktree_close(worktree);
3146 worktree = NULL;
3148 error = view_loop(view);
3149 done:
3150 free(in_repo_path);
3151 free(repo_path);
3152 free(cwd);
3153 free(start_id);
3154 free(label);
3155 if (ref)
3156 got_ref_close(ref);
3157 if (repo) {
3158 const struct got_error *close_err = got_repo_close(repo);
3159 if (error == NULL)
3160 error = close_err;
3162 if (worktree)
3163 got_worktree_close(worktree);
3164 if (pack_fds) {
3165 const struct got_error *pack_err =
3166 got_repo_pack_fds_close(pack_fds);
3167 if (error == NULL)
3168 error = pack_err;
3170 tog_free_refs();
3171 return error;
3174 __dead static void
3175 usage_diff(void)
3177 endwin();
3178 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3179 "[-w] object1 object2\n", getprogname());
3180 exit(1);
3183 static int
3184 match_line(const char *line, regex_t *regex, size_t nmatch,
3185 regmatch_t *regmatch)
3187 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3190 static struct tog_color *
3191 match_color(struct tog_colors *colors, const char *line)
3193 struct tog_color *tc = NULL;
3195 STAILQ_FOREACH(tc, colors, entry) {
3196 if (match_line(line, &tc->regex, 0, NULL))
3197 return tc;
3200 return NULL;
3203 static const struct got_error *
3204 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3205 WINDOW *window, int skipcol, regmatch_t *regmatch)
3207 const struct got_error *err = NULL;
3208 char *exstr = NULL;
3209 wchar_t *wline = NULL;
3210 int rme, rms, n, width, scrollx;
3211 int width0 = 0, width1 = 0, width2 = 0;
3212 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3214 *wtotal = 0;
3216 rms = regmatch->rm_so;
3217 rme = regmatch->rm_eo;
3219 err = expand_tab(&exstr, line);
3220 if (err)
3221 return err;
3223 /* Split the line into 3 segments, according to match offsets. */
3224 seg0 = strndup(exstr, rms);
3225 if (seg0 == NULL) {
3226 err = got_error_from_errno("strndup");
3227 goto done;
3229 seg1 = strndup(exstr + rms, rme - rms);
3230 if (seg1 == NULL) {
3231 err = got_error_from_errno("strndup");
3232 goto done;
3234 seg2 = strdup(exstr + rme);
3235 if (seg2 == NULL) {
3236 err = got_error_from_errno("strndup");
3237 goto done;
3240 /* draw up to matched token if we haven't scrolled past it */
3241 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3242 col_tab_align, 1);
3243 if (err)
3244 goto done;
3245 n = MAX(width0 - skipcol, 0);
3246 if (n) {
3247 free(wline);
3248 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3249 wlimit, col_tab_align, 1);
3250 if (err)
3251 goto done;
3252 waddwstr(window, &wline[scrollx]);
3253 wlimit -= width;
3254 *wtotal += width;
3257 if (wlimit > 0) {
3258 int i = 0, w = 0;
3259 size_t wlen;
3261 free(wline);
3262 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3263 col_tab_align, 1);
3264 if (err)
3265 goto done;
3266 wlen = wcslen(wline);
3267 while (i < wlen) {
3268 width = wcwidth(wline[i]);
3269 if (width == -1) {
3270 /* should not happen, tabs are expanded */
3271 err = got_error(GOT_ERR_RANGE);
3272 goto done;
3274 if (width0 + w + width > skipcol)
3275 break;
3276 w += width;
3277 i++;
3279 /* draw (visible part of) matched token (if scrolled into it) */
3280 if (width1 - w > 0) {
3281 wattron(window, A_STANDOUT);
3282 waddwstr(window, &wline[i]);
3283 wattroff(window, A_STANDOUT);
3284 wlimit -= (width1 - w);
3285 *wtotal += (width1 - w);
3289 if (wlimit > 0) { /* draw rest of line */
3290 free(wline);
3291 if (skipcol > width0 + width1) {
3292 err = format_line(&wline, &width2, &scrollx, seg2,
3293 skipcol - (width0 + width1), wlimit,
3294 col_tab_align, 1);
3295 if (err)
3296 goto done;
3297 waddwstr(window, &wline[scrollx]);
3298 } else {
3299 err = format_line(&wline, &width2, NULL, seg2, 0,
3300 wlimit, col_tab_align, 1);
3301 if (err)
3302 goto done;
3303 waddwstr(window, wline);
3305 *wtotal += width2;
3307 done:
3308 free(wline);
3309 free(exstr);
3310 free(seg0);
3311 free(seg1);
3312 free(seg2);
3313 return err;
3316 static const struct got_error *
3317 draw_file(struct tog_view *view, const char *header)
3319 struct tog_diff_view_state *s = &view->state.diff;
3320 regmatch_t *regmatch = &view->regmatch;
3321 const struct got_error *err;
3322 int nprinted = 0;
3323 char *line;
3324 size_t linesize = 0;
3325 ssize_t linelen;
3326 struct tog_color *tc;
3327 wchar_t *wline;
3328 int width;
3329 int max_lines = view->nlines;
3330 int nlines = s->nlines;
3331 off_t line_offset;
3333 line_offset = s->line_offsets[s->first_displayed_line - 1];
3334 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3335 return got_error_from_errno("fseek");
3337 werase(view->window);
3339 if (header) {
3340 if (asprintf(&line, "[%d/%d] %s",
3341 s->first_displayed_line - 1 + s->selected_line, nlines,
3342 header) == -1)
3343 return got_error_from_errno("asprintf");
3344 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3345 0, 0);
3346 free(line);
3347 if (err)
3348 return err;
3350 if (view_needs_focus_indication(view))
3351 wstandout(view->window);
3352 waddwstr(view->window, wline);
3353 free(wline);
3354 wline = NULL;
3355 if (view_needs_focus_indication(view))
3356 wstandend(view->window);
3357 if (width <= view->ncols - 1)
3358 waddch(view->window, '\n');
3360 if (max_lines <= 1)
3361 return NULL;
3362 max_lines--;
3365 s->eof = 0;
3366 view->maxx = 0;
3367 line = NULL;
3368 while (max_lines > 0 && nprinted < max_lines) {
3369 linelen = getline(&line, &linesize, s->f);
3370 if (linelen == -1) {
3371 if (feof(s->f)) {
3372 s->eof = 1;
3373 break;
3375 free(line);
3376 return got_ferror(s->f, GOT_ERR_IO);
3379 /* Set view->maxx based on full line length. */
3380 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3381 view->x ? 1 : 0);
3382 if (err) {
3383 free(line);
3384 return err;
3386 view->maxx = MAX(view->maxx, width);
3387 free(wline);
3388 wline = NULL;
3390 tc = match_color(&s->colors, line);
3391 if (tc)
3392 wattr_on(view->window,
3393 COLOR_PAIR(tc->colorpair), NULL);
3394 if (s->first_displayed_line + nprinted == s->matched_line &&
3395 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3396 err = add_matched_line(&width, line, view->ncols, 0,
3397 view->window, view->x, regmatch);
3398 if (err) {
3399 free(line);
3400 return err;
3402 } else {
3403 int skip;
3404 err = format_line(&wline, &width, &skip, line,
3405 view->x, view->ncols, 0, view->x ? 1 : 0);
3406 if (err) {
3407 free(line);
3408 return err;
3410 waddwstr(view->window, &wline[skip]);
3411 free(wline);
3412 wline = NULL;
3414 if (tc)
3415 wattr_off(view->window,
3416 COLOR_PAIR(tc->colorpair), NULL);
3417 if (width <= view->ncols - 1)
3418 waddch(view->window, '\n');
3419 nprinted++;
3421 free(line);
3422 if (nprinted >= 1)
3423 s->last_displayed_line = s->first_displayed_line +
3424 (nprinted - 1);
3425 else
3426 s->last_displayed_line = s->first_displayed_line;
3428 view_vborder(view);
3430 if (s->eof) {
3431 while (nprinted < view->nlines) {
3432 waddch(view->window, '\n');
3433 nprinted++;
3436 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3437 view->ncols, 0, 0);
3438 if (err) {
3439 return err;
3442 wstandout(view->window);
3443 waddwstr(view->window, wline);
3444 free(wline);
3445 wline = NULL;
3446 wstandend(view->window);
3449 return NULL;
3452 static char *
3453 get_datestr(time_t *time, char *datebuf)
3455 struct tm mytm, *tm;
3456 char *p, *s;
3458 tm = gmtime_r(time, &mytm);
3459 if (tm == NULL)
3460 return NULL;
3461 s = asctime_r(tm, datebuf);
3462 if (s == NULL)
3463 return NULL;
3464 p = strchr(s, '\n');
3465 if (p)
3466 *p = '\0';
3467 return s;
3470 static const struct got_error *
3471 get_changed_paths(struct got_pathlist_head *paths,
3472 struct got_commit_object *commit, struct got_repository *repo)
3474 const struct got_error *err = NULL;
3475 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3476 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3477 struct got_object_qid *qid;
3479 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3480 if (qid != NULL) {
3481 struct got_commit_object *pcommit;
3482 err = got_object_open_as_commit(&pcommit, repo,
3483 &qid->id);
3484 if (err)
3485 return err;
3487 tree_id1 = got_object_id_dup(
3488 got_object_commit_get_tree_id(pcommit));
3489 if (tree_id1 == NULL) {
3490 got_object_commit_close(pcommit);
3491 return got_error_from_errno("got_object_id_dup");
3493 got_object_commit_close(pcommit);
3497 if (tree_id1) {
3498 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3499 if (err)
3500 goto done;
3503 tree_id2 = got_object_commit_get_tree_id(commit);
3504 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3505 if (err)
3506 goto done;
3508 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3509 got_diff_tree_collect_changed_paths, paths, 0);
3510 done:
3511 if (tree1)
3512 got_object_tree_close(tree1);
3513 if (tree2)
3514 got_object_tree_close(tree2);
3515 free(tree_id1);
3516 return err;
3519 static const struct got_error *
3520 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
3522 off_t *p;
3524 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
3525 if (p == NULL)
3526 return got_error_from_errno("reallocarray");
3527 *line_offsets = p;
3528 (*line_offsets)[*nlines] = off;
3529 (*nlines)++;
3530 return NULL;
3533 static const struct got_error *
3534 write_commit_info(off_t **line_offsets, size_t *nlines,
3535 struct got_object_id *commit_id, struct got_reflist_head *refs,
3536 struct got_repository *repo, FILE *outfile)
3538 const struct got_error *err = NULL;
3539 char datebuf[26], *datestr;
3540 struct got_commit_object *commit;
3541 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
3542 time_t committer_time;
3543 const char *author, *committer;
3544 char *refs_str = NULL;
3545 struct got_pathlist_head changed_paths;
3546 struct got_pathlist_entry *pe;
3547 off_t outoff = 0;
3548 int n;
3550 TAILQ_INIT(&changed_paths);
3552 if (refs) {
3553 err = build_refs_str(&refs_str, refs, commit_id, repo);
3554 if (err)
3555 return err;
3558 err = got_object_open_as_commit(&commit, repo, commit_id);
3559 if (err)
3560 return err;
3562 err = got_object_id_str(&id_str, commit_id);
3563 if (err) {
3564 err = got_error_from_errno("got_object_id_str");
3565 goto done;
3568 err = add_line_offset(line_offsets, nlines, 0);
3569 if (err)
3570 goto done;
3572 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3573 refs_str ? refs_str : "", refs_str ? ")" : "");
3574 if (n < 0) {
3575 err = got_error_from_errno("fprintf");
3576 goto done;
3578 outoff += n;
3579 err = add_line_offset(line_offsets, nlines, outoff);
3580 if (err)
3581 goto done;
3583 n = fprintf(outfile, "from: %s\n",
3584 got_object_commit_get_author(commit));
3585 if (n < 0) {
3586 err = got_error_from_errno("fprintf");
3587 goto done;
3589 outoff += n;
3590 err = add_line_offset(line_offsets, nlines, outoff);
3591 if (err)
3592 goto done;
3594 committer_time = got_object_commit_get_committer_time(commit);
3595 datestr = get_datestr(&committer_time, datebuf);
3596 if (datestr) {
3597 n = fprintf(outfile, "date: %s UTC\n", datestr);
3598 if (n < 0) {
3599 err = got_error_from_errno("fprintf");
3600 goto done;
3602 outoff += n;
3603 err = add_line_offset(line_offsets, nlines, outoff);
3604 if (err)
3605 goto done;
3607 author = got_object_commit_get_author(commit);
3608 committer = got_object_commit_get_committer(commit);
3609 if (strcmp(author, committer) != 0) {
3610 n = fprintf(outfile, "via: %s\n", committer);
3611 if (n < 0) {
3612 err = got_error_from_errno("fprintf");
3613 goto done;
3615 outoff += n;
3616 err = add_line_offset(line_offsets, nlines, outoff);
3617 if (err)
3618 goto done;
3620 if (got_object_commit_get_nparents(commit) > 1) {
3621 const struct got_object_id_queue *parent_ids;
3622 struct got_object_qid *qid;
3623 int pn = 1;
3624 parent_ids = got_object_commit_get_parent_ids(commit);
3625 STAILQ_FOREACH(qid, parent_ids, entry) {
3626 err = got_object_id_str(&id_str, &qid->id);
3627 if (err)
3628 goto done;
3629 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
3630 if (n < 0) {
3631 err = got_error_from_errno("fprintf");
3632 goto done;
3634 outoff += n;
3635 err = add_line_offset(line_offsets, nlines, outoff);
3636 if (err)
3637 goto done;
3638 free(id_str);
3639 id_str = NULL;
3643 err = got_object_commit_get_logmsg(&logmsg, commit);
3644 if (err)
3645 goto done;
3646 s = logmsg;
3647 while ((line = strsep(&s, "\n")) != NULL) {
3648 n = fprintf(outfile, "%s\n", line);
3649 if (n < 0) {
3650 err = got_error_from_errno("fprintf");
3651 goto done;
3653 outoff += n;
3654 err = add_line_offset(line_offsets, nlines, outoff);
3655 if (err)
3656 goto done;
3659 err = get_changed_paths(&changed_paths, commit, repo);
3660 if (err)
3661 goto done;
3662 TAILQ_FOREACH(pe, &changed_paths, entry) {
3663 struct got_diff_changed_path *cp = pe->data;
3664 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
3665 if (n < 0) {
3666 err = got_error_from_errno("fprintf");
3667 goto done;
3669 outoff += n;
3670 err = add_line_offset(line_offsets, nlines, outoff);
3671 if (err)
3672 goto done;
3673 free((char *)pe->path);
3674 free(pe->data);
3677 fputc('\n', outfile);
3678 outoff++;
3679 err = add_line_offset(line_offsets, nlines, outoff);
3680 done:
3681 got_pathlist_free(&changed_paths);
3682 free(id_str);
3683 free(logmsg);
3684 free(refs_str);
3685 got_object_commit_close(commit);
3686 if (err) {
3687 free(*line_offsets);
3688 *line_offsets = NULL;
3689 *nlines = 0;
3691 return err;
3694 static const struct got_error *
3695 create_diff(struct tog_diff_view_state *s)
3697 const struct got_error *err = NULL;
3698 FILE *f = NULL;
3699 int obj_type;
3701 free(s->line_offsets);
3702 s->line_offsets = malloc(sizeof(off_t));
3703 if (s->line_offsets == NULL)
3704 return got_error_from_errno("malloc");
3705 s->nlines = 0;
3707 f = got_opentemp();
3708 if (f == NULL) {
3709 err = got_error_from_errno("got_opentemp");
3710 goto done;
3712 if (s->f && fclose(s->f) == EOF) {
3713 err = got_error_from_errno("fclose");
3714 goto done;
3716 s->f = f;
3718 if (s->id1)
3719 err = got_object_get_type(&obj_type, s->repo, s->id1);
3720 else
3721 err = got_object_get_type(&obj_type, s->repo, s->id2);
3722 if (err)
3723 goto done;
3725 switch (obj_type) {
3726 case GOT_OBJ_TYPE_BLOB:
3727 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
3728 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
3729 s->label1, s->label2, s->diff_context,
3730 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
3731 break;
3732 case GOT_OBJ_TYPE_TREE:
3733 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
3734 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
3735 s->diff_context, s->ignore_whitespace, s->force_text_diff,
3736 s->repo, s->f);
3737 break;
3738 case GOT_OBJ_TYPE_COMMIT: {
3739 const struct got_object_id_queue *parent_ids;
3740 struct got_object_qid *pid;
3741 struct got_commit_object *commit2;
3742 struct got_reflist_head *refs;
3744 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
3745 if (err)
3746 goto done;
3747 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
3748 /* Show commit info if we're diffing to a parent/root commit. */
3749 if (s->id1 == NULL) {
3750 err = write_commit_info(&s->line_offsets, &s->nlines,
3751 s->id2, refs, s->repo, s->f);
3752 if (err)
3753 goto done;
3754 } else {
3755 parent_ids = got_object_commit_get_parent_ids(commit2);
3756 STAILQ_FOREACH(pid, parent_ids, entry) {
3757 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
3758 err = write_commit_info(
3759 &s->line_offsets, &s->nlines,
3760 s->id2, refs, s->repo, s->f);
3761 if (err)
3762 goto done;
3763 break;
3767 got_object_commit_close(commit2);
3769 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
3770 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
3771 s->diff_context, s->ignore_whitespace, s->force_text_diff,
3772 s->repo, s->f);
3773 break;
3775 default:
3776 err = got_error(GOT_ERR_OBJ_TYPE);
3777 break;
3779 if (err)
3780 goto done;
3781 done:
3782 if (s->f && fflush(s->f) != 0 && err == NULL)
3783 err = got_error_from_errno("fflush");
3784 return err;
3787 static void
3788 diff_view_indicate_progress(struct tog_view *view)
3790 mvwaddstr(view->window, 0, 0, "diffing...");
3791 update_panels();
3792 doupdate();
3795 static const struct got_error *
3796 search_start_diff_view(struct tog_view *view)
3798 struct tog_diff_view_state *s = &view->state.diff;
3800 s->matched_line = 0;
3801 return NULL;
3804 static const struct got_error *
3805 search_next_diff_view(struct tog_view *view)
3807 struct tog_diff_view_state *s = &view->state.diff;
3808 const struct got_error *err = NULL;
3809 int lineno;
3810 char *line = NULL;
3811 size_t linesize = 0;
3812 ssize_t linelen;
3814 if (!view->searching) {
3815 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3816 return NULL;
3819 if (s->matched_line) {
3820 if (view->searching == TOG_SEARCH_FORWARD)
3821 lineno = s->matched_line + 1;
3822 else
3823 lineno = s->matched_line - 1;
3824 } else
3825 lineno = s->first_displayed_line;
3827 while (1) {
3828 off_t offset;
3830 if (lineno <= 0 || lineno > s->nlines) {
3831 if (s->matched_line == 0) {
3832 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3833 break;
3836 if (view->searching == TOG_SEARCH_FORWARD)
3837 lineno = 1;
3838 else
3839 lineno = s->nlines;
3842 offset = s->line_offsets[lineno - 1];
3843 if (fseeko(s->f, offset, SEEK_SET) != 0) {
3844 free(line);
3845 return got_error_from_errno("fseeko");
3847 linelen = getline(&line, &linesize, s->f);
3848 if (linelen != -1) {
3849 char *exstr;
3850 err = expand_tab(&exstr, line);
3851 if (err)
3852 break;
3853 if (match_line(exstr, &view->regex, 1,
3854 &view->regmatch)) {
3855 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3856 s->matched_line = lineno;
3857 free(exstr);
3858 break;
3860 free(exstr);
3862 if (view->searching == TOG_SEARCH_FORWARD)
3863 lineno++;
3864 else
3865 lineno--;
3867 free(line);
3869 if (s->matched_line) {
3870 s->first_displayed_line = s->matched_line;
3871 s->selected_line = 1;
3874 return err;
3877 static const struct got_error *
3878 close_diff_view(struct tog_view *view)
3880 const struct got_error *err = NULL;
3881 struct tog_diff_view_state *s = &view->state.diff;
3883 free(s->id1);
3884 s->id1 = NULL;
3885 free(s->id2);
3886 s->id2 = NULL;
3887 if (s->f && fclose(s->f) == EOF)
3888 err = got_error_from_errno("fclose");
3889 s->f = NULL;
3890 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
3891 err = got_error_from_errno("fclose");
3892 s->f1 = NULL;
3893 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
3894 err = got_error_from_errno("fclose");
3895 s->f2 = NULL;
3896 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
3897 err = got_error_from_errno("close");
3898 s->fd1 = -1;
3899 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
3900 err = got_error_from_errno("close");
3901 s->fd2 = -1;
3902 free_colors(&s->colors);
3903 free(s->line_offsets);
3904 s->line_offsets = NULL;
3905 s->nlines = 0;
3906 return err;
3909 static const struct got_error *
3910 open_diff_view(struct tog_view *view, struct got_object_id *id1,
3911 struct got_object_id *id2, const char *label1, const char *label2,
3912 int diff_context, int ignore_whitespace, int force_text_diff,
3913 struct tog_view *log_view, struct got_repository *repo)
3915 const struct got_error *err;
3916 struct tog_diff_view_state *s = &view->state.diff;
3918 memset(s, 0, sizeof(*s));
3919 s->fd1 = -1;
3920 s->fd2 = -1;
3922 if (id1 != NULL && id2 != NULL) {
3923 int type1, type2;
3924 err = got_object_get_type(&type1, repo, id1);
3925 if (err)
3926 return err;
3927 err = got_object_get_type(&type2, repo, id2);
3928 if (err)
3929 return err;
3931 if (type1 != type2)
3932 return got_error(GOT_ERR_OBJ_TYPE);
3934 s->first_displayed_line = 1;
3935 s->last_displayed_line = view->nlines;
3936 s->selected_line = 1;
3937 s->repo = repo;
3938 s->id1 = id1;
3939 s->id2 = id2;
3940 s->label1 = label1;
3941 s->label2 = label2;
3943 if (id1) {
3944 s->id1 = got_object_id_dup(id1);
3945 if (s->id1 == NULL)
3946 return got_error_from_errno("got_object_id_dup");
3947 } else
3948 s->id1 = NULL;
3950 s->id2 = got_object_id_dup(id2);
3951 if (s->id2 == NULL) {
3952 err = got_error_from_errno("got_object_id_dup");
3953 goto done;
3956 s->f1 = got_opentemp();
3957 if (s->f1 == NULL) {
3958 err = got_error_from_errno("got_opentemp");
3959 goto done;
3962 s->f2 = got_opentemp();
3963 if (s->f2 == NULL) {
3964 err = got_error_from_errno("got_opentemp");
3965 goto done;
3968 s->fd1 = got_opentempfd();
3969 if (s->fd1 == -1) {
3970 err = got_error_from_errno("got_opentempfd");
3971 goto done;
3974 s->fd2 = got_opentempfd();
3975 if (s->fd2 == -1) {
3976 err = got_error_from_errno("got_opentempfd");
3977 goto done;
3980 s->first_displayed_line = 1;
3981 s->last_displayed_line = view->nlines;
3982 s->diff_context = diff_context;
3983 s->ignore_whitespace = ignore_whitespace;
3984 s->force_text_diff = force_text_diff;
3985 s->log_view = log_view;
3986 s->repo = repo;
3988 STAILQ_INIT(&s->colors);
3989 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3990 err = add_color(&s->colors,
3991 "^-", TOG_COLOR_DIFF_MINUS,
3992 get_color_value("TOG_COLOR_DIFF_MINUS"));
3993 if (err)
3994 goto done;
3995 err = add_color(&s->colors, "^\\+",
3996 TOG_COLOR_DIFF_PLUS,
3997 get_color_value("TOG_COLOR_DIFF_PLUS"));
3998 if (err)
3999 goto done;
4000 err = add_color(&s->colors,
4001 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4002 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4003 if (err)
4004 goto done;
4006 err = add_color(&s->colors,
4007 "^(commit [0-9a-f]|parent [0-9]|"
4008 "(blob|file|tree|commit) [-+] |"
4009 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4010 get_color_value("TOG_COLOR_DIFF_META"));
4011 if (err)
4012 goto done;
4014 err = add_color(&s->colors,
4015 "^(from|via): ", TOG_COLOR_AUTHOR,
4016 get_color_value("TOG_COLOR_AUTHOR"));
4017 if (err)
4018 goto done;
4020 err = add_color(&s->colors,
4021 "^date: ", TOG_COLOR_DATE,
4022 get_color_value("TOG_COLOR_DATE"));
4023 if (err)
4024 goto done;
4027 if (log_view && view_is_splitscreen(view))
4028 show_log_view(log_view); /* draw vborder */
4029 diff_view_indicate_progress(view);
4031 err = create_diff(s);
4033 view->show = show_diff_view;
4034 view->input = input_diff_view;
4035 view->close = close_diff_view;
4036 view->search_start = search_start_diff_view;
4037 view->search_next = search_next_diff_view;
4038 done:
4039 if (err)
4040 close_diff_view(view);
4041 return err;
4044 static const struct got_error *
4045 show_diff_view(struct tog_view *view)
4047 const struct got_error *err;
4048 struct tog_diff_view_state *s = &view->state.diff;
4049 char *id_str1 = NULL, *id_str2, *header;
4050 const char *label1, *label2;
4052 if (s->id1) {
4053 err = got_object_id_str(&id_str1, s->id1);
4054 if (err)
4055 return err;
4056 label1 = s->label1 ? : id_str1;
4057 } else
4058 label1 = "/dev/null";
4060 err = got_object_id_str(&id_str2, s->id2);
4061 if (err)
4062 return err;
4063 label2 = s->label2 ? : id_str2;
4065 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4066 err = got_error_from_errno("asprintf");
4067 free(id_str1);
4068 free(id_str2);
4069 return err;
4071 free(id_str1);
4072 free(id_str2);
4074 err = draw_file(view, header);
4075 free(header);
4076 return err;
4079 static const struct got_error *
4080 set_selected_commit(struct tog_diff_view_state *s,
4081 struct commit_queue_entry *entry)
4083 const struct got_error *err;
4084 const struct got_object_id_queue *parent_ids;
4085 struct got_commit_object *selected_commit;
4086 struct got_object_qid *pid;
4088 free(s->id2);
4089 s->id2 = got_object_id_dup(entry->id);
4090 if (s->id2 == NULL)
4091 return got_error_from_errno("got_object_id_dup");
4093 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4094 if (err)
4095 return err;
4096 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4097 free(s->id1);
4098 pid = STAILQ_FIRST(parent_ids);
4099 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4100 got_object_commit_close(selected_commit);
4101 return NULL;
4104 static const struct got_error *
4105 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4107 const struct got_error *err = NULL;
4108 struct tog_diff_view_state *s = &view->state.diff;
4109 struct tog_log_view_state *ls;
4110 struct commit_queue_entry *old_selected_entry;
4111 char *line = NULL;
4112 size_t linesize = 0;
4113 ssize_t linelen;
4114 int i, nscroll = view->nlines - 1;
4116 switch (ch) {
4117 case '0':
4118 view->x = 0;
4119 break;
4120 case '$':
4121 view->x = MAX(view->maxx - view->ncols / 3, 0);
4122 view->count = 0;
4123 break;
4124 case KEY_RIGHT:
4125 case 'l':
4126 if (view->x + view->ncols / 3 < view->maxx)
4127 view->x += 2; /* move two columns right */
4128 else
4129 view->count = 0;
4130 break;
4131 case KEY_LEFT:
4132 case 'h':
4133 view->x -= MIN(view->x, 2); /* move two columns back */
4134 if (view->x <= 0)
4135 view->count = 0;
4136 break;
4137 case 'a':
4138 case 'w':
4139 if (ch == 'a')
4140 s->force_text_diff = !s->force_text_diff;
4141 if (ch == 'w')
4142 s->ignore_whitespace = !s->ignore_whitespace;
4143 wclear(view->window);
4144 s->first_displayed_line = 1;
4145 s->last_displayed_line = view->nlines;
4146 s->matched_line = 0;
4147 diff_view_indicate_progress(view);
4148 err = create_diff(s);
4149 view->count = 0;
4150 break;
4151 case 'g':
4152 case KEY_HOME:
4153 s->first_displayed_line = 1;
4154 view->count = 0;
4155 break;
4156 case 'G':
4157 case KEY_END:
4158 view->count = 0;
4159 if (s->eof)
4160 break;
4162 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4163 s->eof = 1;
4164 break;
4165 case 'k':
4166 case KEY_UP:
4167 case CTRL('p'):
4168 if (s->first_displayed_line > 1)
4169 s->first_displayed_line--;
4170 else
4171 view->count = 0;
4172 break;
4173 case CTRL('u'):
4174 case 'u':
4175 nscroll /= 2;
4176 /* FALL THROUGH */
4177 case KEY_PPAGE:
4178 case CTRL('b'):
4179 case 'b':
4180 if (s->first_displayed_line == 1) {
4181 view->count = 0;
4182 break;
4184 i = 0;
4185 while (i++ < nscroll && s->first_displayed_line > 1)
4186 s->first_displayed_line--;
4187 break;
4188 case 'j':
4189 case KEY_DOWN:
4190 case CTRL('n'):
4191 if (!s->eof)
4192 s->first_displayed_line++;
4193 else
4194 view->count = 0;
4195 break;
4196 case CTRL('d'):
4197 case 'd':
4198 nscroll /= 2;
4199 /* FALL THROUGH */
4200 case KEY_NPAGE:
4201 case CTRL('f'):
4202 case 'f':
4203 case ' ':
4204 if (s->eof) {
4205 view->count = 0;
4206 break;
4208 i = 0;
4209 while (!s->eof && i++ < nscroll) {
4210 linelen = getline(&line, &linesize, s->f);
4211 s->first_displayed_line++;
4212 if (linelen == -1) {
4213 if (feof(s->f)) {
4214 s->eof = 1;
4215 } else
4216 err = got_ferror(s->f, GOT_ERR_IO);
4217 break;
4220 free(line);
4221 break;
4222 case '[':
4223 if (s->diff_context > 0) {
4224 s->diff_context--;
4225 s->matched_line = 0;
4226 diff_view_indicate_progress(view);
4227 err = create_diff(s);
4228 if (s->first_displayed_line + view->nlines - 1 >
4229 s->nlines) {
4230 s->first_displayed_line = 1;
4231 s->last_displayed_line = view->nlines;
4233 } else
4234 view->count = 0;
4235 break;
4236 case ']':
4237 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4238 s->diff_context++;
4239 s->matched_line = 0;
4240 diff_view_indicate_progress(view);
4241 err = create_diff(s);
4242 } else
4243 view->count = 0;
4244 break;
4245 case '<':
4246 case ',':
4247 if (s->log_view == NULL) {
4248 view->count = 0;
4249 break;
4251 ls = &s->log_view->state.log;
4252 old_selected_entry = ls->selected_entry;
4254 /* view->count handled in input_log_view() */
4255 err = input_log_view(NULL, s->log_view, KEY_UP);
4256 if (err)
4257 break;
4259 if (old_selected_entry == ls->selected_entry)
4260 break;
4262 err = set_selected_commit(s, ls->selected_entry);
4263 if (err)
4264 break;
4266 s->first_displayed_line = 1;
4267 s->last_displayed_line = view->nlines;
4268 s->matched_line = 0;
4269 view->x = 0;
4271 diff_view_indicate_progress(view);
4272 err = create_diff(s);
4273 break;
4274 case '>':
4275 case '.':
4276 if (s->log_view == NULL) {
4277 view->count = 0;
4278 break;
4280 ls = &s->log_view->state.log;
4281 old_selected_entry = ls->selected_entry;
4283 /* view->count handled in input_log_view() */
4284 err = input_log_view(NULL, s->log_view, KEY_DOWN);
4285 if (err)
4286 break;
4288 if (old_selected_entry == ls->selected_entry)
4289 break;
4291 err = set_selected_commit(s, ls->selected_entry);
4292 if (err)
4293 break;
4295 s->first_displayed_line = 1;
4296 s->last_displayed_line = view->nlines;
4297 s->matched_line = 0;
4298 view->x = 0;
4300 diff_view_indicate_progress(view);
4301 err = create_diff(s);
4302 break;
4303 default:
4304 view->count = 0;
4305 break;
4308 return err;
4311 static const struct got_error *
4312 cmd_diff(int argc, char *argv[])
4314 const struct got_error *error = NULL;
4315 struct got_repository *repo = NULL;
4316 struct got_worktree *worktree = NULL;
4317 struct got_object_id *id1 = NULL, *id2 = NULL;
4318 char *repo_path = NULL, *cwd = NULL;
4319 char *id_str1 = NULL, *id_str2 = NULL;
4320 char *label1 = NULL, *label2 = NULL;
4321 int diff_context = 3, ignore_whitespace = 0;
4322 int ch, force_text_diff = 0;
4323 const char *errstr;
4324 struct tog_view *view;
4325 int *pack_fds = NULL;
4327 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4328 switch (ch) {
4329 case 'a':
4330 force_text_diff = 1;
4331 break;
4332 case 'C':
4333 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4334 &errstr);
4335 if (errstr != NULL)
4336 errx(1, "number of context lines is %s: %s",
4337 errstr, errstr);
4338 break;
4339 case 'r':
4340 repo_path = realpath(optarg, NULL);
4341 if (repo_path == NULL)
4342 return got_error_from_errno2("realpath",
4343 optarg);
4344 got_path_strip_trailing_slashes(repo_path);
4345 break;
4346 case 'w':
4347 ignore_whitespace = 1;
4348 break;
4349 default:
4350 usage_diff();
4351 /* NOTREACHED */
4355 argc -= optind;
4356 argv += optind;
4358 if (argc == 0) {
4359 usage_diff(); /* TODO show local worktree changes */
4360 } else if (argc == 2) {
4361 id_str1 = argv[0];
4362 id_str2 = argv[1];
4363 } else
4364 usage_diff();
4366 error = got_repo_pack_fds_open(&pack_fds);
4367 if (error)
4368 goto done;
4370 if (repo_path == NULL) {
4371 cwd = getcwd(NULL, 0);
4372 if (cwd == NULL)
4373 return got_error_from_errno("getcwd");
4374 error = got_worktree_open(&worktree, cwd);
4375 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4376 goto done;
4377 if (worktree)
4378 repo_path =
4379 strdup(got_worktree_get_repo_path(worktree));
4380 else
4381 repo_path = strdup(cwd);
4382 if (repo_path == NULL) {
4383 error = got_error_from_errno("strdup");
4384 goto done;
4388 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4389 if (error)
4390 goto done;
4392 init_curses();
4394 error = apply_unveil(got_repo_get_path(repo), NULL);
4395 if (error)
4396 goto done;
4398 error = tog_load_refs(repo, 0);
4399 if (error)
4400 goto done;
4402 error = got_repo_match_object_id(&id1, &label1, id_str1,
4403 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4404 if (error)
4405 goto done;
4407 error = got_repo_match_object_id(&id2, &label2, id_str2,
4408 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4409 if (error)
4410 goto done;
4412 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4413 if (view == NULL) {
4414 error = got_error_from_errno("view_open");
4415 goto done;
4417 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4418 ignore_whitespace, force_text_diff, NULL, repo);
4419 if (error)
4420 goto done;
4421 error = view_loop(view);
4422 done:
4423 free(label1);
4424 free(label2);
4425 free(repo_path);
4426 free(cwd);
4427 if (repo) {
4428 const struct got_error *close_err = got_repo_close(repo);
4429 if (error == NULL)
4430 error = close_err;
4432 if (worktree)
4433 got_worktree_close(worktree);
4434 if (pack_fds) {
4435 const struct got_error *pack_err =
4436 got_repo_pack_fds_close(pack_fds);
4437 if (error == NULL)
4438 error = pack_err;
4440 tog_free_refs();
4441 return error;
4444 __dead static void
4445 usage_blame(void)
4447 endwin();
4448 fprintf(stderr,
4449 "usage: %s blame [-c commit] [-r repository-path] path\n",
4450 getprogname());
4451 exit(1);
4454 struct tog_blame_line {
4455 int annotated;
4456 struct got_object_id *id;
4459 static const struct got_error *
4460 draw_blame(struct tog_view *view)
4462 struct tog_blame_view_state *s = &view->state.blame;
4463 struct tog_blame *blame = &s->blame;
4464 regmatch_t *regmatch = &view->regmatch;
4465 const struct got_error *err;
4466 int lineno = 0, nprinted = 0;
4467 char *line = NULL;
4468 size_t linesize = 0;
4469 ssize_t linelen;
4470 wchar_t *wline;
4471 int width;
4472 struct tog_blame_line *blame_line;
4473 struct got_object_id *prev_id = NULL;
4474 char *id_str;
4475 struct tog_color *tc;
4477 err = got_object_id_str(&id_str, &s->blamed_commit->id);
4478 if (err)
4479 return err;
4481 rewind(blame->f);
4482 werase(view->window);
4484 if (asprintf(&line, "commit %s", id_str) == -1) {
4485 err = got_error_from_errno("asprintf");
4486 free(id_str);
4487 return err;
4490 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4491 free(line);
4492 line = NULL;
4493 if (err)
4494 return err;
4495 if (view_needs_focus_indication(view))
4496 wstandout(view->window);
4497 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4498 if (tc)
4499 wattr_on(view->window,
4500 COLOR_PAIR(tc->colorpair), NULL);
4501 waddwstr(view->window, wline);
4502 if (tc)
4503 wattr_off(view->window,
4504 COLOR_PAIR(tc->colorpair), NULL);
4505 if (view_needs_focus_indication(view))
4506 wstandend(view->window);
4507 free(wline);
4508 wline = NULL;
4509 if (width < view->ncols - 1)
4510 waddch(view->window, '\n');
4512 if (asprintf(&line, "[%d/%d] %s%s",
4513 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
4514 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
4515 free(id_str);
4516 return got_error_from_errno("asprintf");
4518 free(id_str);
4519 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4520 free(line);
4521 line = NULL;
4522 if (err)
4523 return err;
4524 waddwstr(view->window, wline);
4525 free(wline);
4526 wline = NULL;
4527 if (width < view->ncols - 1)
4528 waddch(view->window, '\n');
4530 s->eof = 0;
4531 view->maxx = 0;
4532 while (nprinted < view->nlines - 2) {
4533 linelen = getline(&line, &linesize, blame->f);
4534 if (linelen == -1) {
4535 if (feof(blame->f)) {
4536 s->eof = 1;
4537 break;
4539 free(line);
4540 return got_ferror(blame->f, GOT_ERR_IO);
4542 if (++lineno < s->first_displayed_line)
4543 continue;
4545 /* Set view->maxx based on full line length. */
4546 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
4547 if (err) {
4548 free(line);
4549 return err;
4551 free(wline);
4552 wline = NULL;
4553 view->maxx = MAX(view->maxx, width);
4555 if (view->focussed && nprinted == s->selected_line - 1)
4556 wstandout(view->window);
4558 if (blame->nlines > 0) {
4559 blame_line = &blame->lines[lineno - 1];
4560 if (blame_line->annotated && prev_id &&
4561 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
4562 !(view->focussed &&
4563 nprinted == s->selected_line - 1)) {
4564 waddstr(view->window, " ");
4565 } else if (blame_line->annotated) {
4566 char *id_str;
4567 err = got_object_id_str(&id_str,
4568 blame_line->id);
4569 if (err) {
4570 free(line);
4571 return err;
4573 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4574 if (tc)
4575 wattr_on(view->window,
4576 COLOR_PAIR(tc->colorpair), NULL);
4577 wprintw(view->window, "%.8s", id_str);
4578 if (tc)
4579 wattr_off(view->window,
4580 COLOR_PAIR(tc->colorpair), NULL);
4581 free(id_str);
4582 prev_id = blame_line->id;
4583 } else {
4584 waddstr(view->window, "........");
4585 prev_id = NULL;
4587 } else {
4588 waddstr(view->window, "........");
4589 prev_id = NULL;
4592 if (view->focussed && nprinted == s->selected_line - 1)
4593 wstandend(view->window);
4594 waddstr(view->window, " ");
4596 if (view->ncols <= 9) {
4597 width = 9;
4598 } else if (s->first_displayed_line + nprinted ==
4599 s->matched_line &&
4600 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4601 err = add_matched_line(&width, line, view->ncols - 9, 9,
4602 view->window, view->x, regmatch);
4603 if (err) {
4604 free(line);
4605 return err;
4607 width += 9;
4608 } else {
4609 int skip;
4610 err = format_line(&wline, &width, &skip, line,
4611 view->x, view->ncols - 9, 9, 1);
4612 if (err) {
4613 free(line);
4614 return err;
4616 waddwstr(view->window, &wline[skip]);
4617 width += 9;
4618 free(wline);
4619 wline = NULL;
4622 if (width <= view->ncols - 1)
4623 waddch(view->window, '\n');
4624 if (++nprinted == 1)
4625 s->first_displayed_line = lineno;
4627 free(line);
4628 s->last_displayed_line = lineno;
4630 view_vborder(view);
4632 return NULL;
4635 static const struct got_error *
4636 blame_cb(void *arg, int nlines, int lineno,
4637 struct got_commit_object *commit, struct got_object_id *id)
4639 const struct got_error *err = NULL;
4640 struct tog_blame_cb_args *a = arg;
4641 struct tog_blame_line *line;
4642 int errcode;
4644 if (nlines != a->nlines ||
4645 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4646 return got_error(GOT_ERR_RANGE);
4648 errcode = pthread_mutex_lock(&tog_mutex);
4649 if (errcode)
4650 return got_error_set_errno(errcode, "pthread_mutex_lock");
4652 if (*a->quit) { /* user has quit the blame view */
4653 err = got_error(GOT_ERR_ITER_COMPLETED);
4654 goto done;
4657 if (lineno == -1)
4658 goto done; /* no change in this commit */
4660 line = &a->lines[lineno - 1];
4661 if (line->annotated)
4662 goto done;
4664 line->id = got_object_id_dup(id);
4665 if (line->id == NULL) {
4666 err = got_error_from_errno("got_object_id_dup");
4667 goto done;
4669 line->annotated = 1;
4670 done:
4671 errcode = pthread_mutex_unlock(&tog_mutex);
4672 if (errcode)
4673 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4674 return err;
4677 static void *
4678 blame_thread(void *arg)
4680 const struct got_error *err, *close_err;
4681 struct tog_blame_thread_args *ta = arg;
4682 struct tog_blame_cb_args *a = ta->cb_args;
4683 int errcode, fd = -1;
4685 fd = got_opentempfd();
4686 if (fd == -1)
4687 return (void *)got_error_from_errno("got_opentempfd");
4689 err = block_signals_used_by_main_thread();
4690 if (err)
4691 return (void *)err;
4693 err = got_blame(ta->path, a->commit_id, ta->repo,
4694 blame_cb, ta->cb_args, ta->cancel_cb, ta->cancel_arg, fd);
4695 if (err && err->code == GOT_ERR_CANCELLED)
4696 err = NULL;
4698 errcode = pthread_mutex_lock(&tog_mutex);
4699 if (errcode)
4700 return (void *)got_error_set_errno(errcode,
4701 "pthread_mutex_lock");
4703 close_err = got_repo_close(ta->repo);
4704 if (err == NULL)
4705 err = close_err;
4706 ta->repo = NULL;
4707 *ta->complete = 1;
4709 errcode = pthread_mutex_unlock(&tog_mutex);
4710 if (errcode && err == NULL)
4711 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4713 if (fd != -1 && close(fd) == -1 && err == NULL)
4714 err = got_error_from_errno("close");
4716 return (void *)err;
4719 static struct got_object_id *
4720 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
4721 int first_displayed_line, int selected_line)
4723 struct tog_blame_line *line;
4725 if (nlines <= 0)
4726 return NULL;
4728 line = &lines[first_displayed_line - 1 + selected_line - 1];
4729 if (!line->annotated)
4730 return NULL;
4732 return line->id;
4735 static const struct got_error *
4736 stop_blame(struct tog_blame *blame)
4738 const struct got_error *err = NULL;
4739 int i;
4741 if (blame->thread) {
4742 int errcode;
4743 errcode = pthread_mutex_unlock(&tog_mutex);
4744 if (errcode)
4745 return got_error_set_errno(errcode,
4746 "pthread_mutex_unlock");
4747 errcode = pthread_join(blame->thread, (void **)&err);
4748 if (errcode)
4749 return got_error_set_errno(errcode, "pthread_join");
4750 errcode = pthread_mutex_lock(&tog_mutex);
4751 if (errcode)
4752 return got_error_set_errno(errcode,
4753 "pthread_mutex_lock");
4754 if (err && err->code == GOT_ERR_ITER_COMPLETED)
4755 err = NULL;
4756 blame->thread = NULL;
4758 if (blame->thread_args.repo) {
4759 const struct got_error *close_err;
4760 close_err = got_repo_close(blame->thread_args.repo);
4761 if (err == NULL)
4762 err = close_err;
4763 blame->thread_args.repo = NULL;
4765 if (blame->f) {
4766 if (fclose(blame->f) == EOF && err == NULL)
4767 err = got_error_from_errno("fclose");
4768 blame->f = NULL;
4770 if (blame->lines) {
4771 for (i = 0; i < blame->nlines; i++)
4772 free(blame->lines[i].id);
4773 free(blame->lines);
4774 blame->lines = NULL;
4776 free(blame->cb_args.commit_id);
4777 blame->cb_args.commit_id = NULL;
4778 if (blame->pack_fds) {
4779 const struct got_error *pack_err =
4780 got_repo_pack_fds_close(blame->pack_fds);
4781 if (err == NULL)
4782 err = pack_err;
4783 blame->pack_fds = NULL;
4785 return err;
4788 static const struct got_error *
4789 cancel_blame_view(void *arg)
4791 const struct got_error *err = NULL;
4792 int *done = arg;
4793 int errcode;
4795 errcode = pthread_mutex_lock(&tog_mutex);
4796 if (errcode)
4797 return got_error_set_errno(errcode,
4798 "pthread_mutex_unlock");
4800 if (*done)
4801 err = got_error(GOT_ERR_CANCELLED);
4803 errcode = pthread_mutex_unlock(&tog_mutex);
4804 if (errcode)
4805 return got_error_set_errno(errcode,
4806 "pthread_mutex_lock");
4808 return err;
4811 static const struct got_error *
4812 run_blame(struct tog_view *view)
4814 struct tog_blame_view_state *s = &view->state.blame;
4815 struct tog_blame *blame = &s->blame;
4816 const struct got_error *err = NULL;
4817 struct got_commit_object *commit = NULL;
4818 struct got_blob_object *blob = NULL;
4819 struct got_repository *thread_repo = NULL;
4820 struct got_object_id *obj_id = NULL;
4821 int obj_type, fd = -1;
4822 int *pack_fds = NULL;
4824 err = got_object_open_as_commit(&commit, s->repo,
4825 &s->blamed_commit->id);
4826 if (err)
4827 return err;
4829 fd = got_opentempfd();
4830 if (fd == -1) {
4831 err = got_error_from_errno("got_opentempfd");
4832 goto done;
4835 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
4836 if (err)
4837 goto done;
4839 err = got_object_get_type(&obj_type, s->repo, obj_id);
4840 if (err)
4841 goto done;
4843 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4844 err = got_error(GOT_ERR_OBJ_TYPE);
4845 goto done;
4848 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
4849 if (err)
4850 goto done;
4851 blame->f = got_opentemp();
4852 if (blame->f == NULL) {
4853 err = got_error_from_errno("got_opentemp");
4854 goto done;
4856 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
4857 &blame->line_offsets, blame->f, blob);
4858 if (err)
4859 goto done;
4860 if (blame->nlines == 0) {
4861 s->blame_complete = 1;
4862 goto done;
4865 /* Don't include \n at EOF in the blame line count. */
4866 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
4867 blame->nlines--;
4869 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
4870 if (blame->lines == NULL) {
4871 err = got_error_from_errno("calloc");
4872 goto done;
4875 err = got_repo_pack_fds_open(&pack_fds);
4876 if (err)
4877 goto done;
4878 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
4879 pack_fds);
4880 if (err)
4881 goto done;
4883 blame->pack_fds = pack_fds;
4884 blame->cb_args.view = view;
4885 blame->cb_args.lines = blame->lines;
4886 blame->cb_args.nlines = blame->nlines;
4887 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
4888 if (blame->cb_args.commit_id == NULL) {
4889 err = got_error_from_errno("got_object_id_dup");
4890 goto done;
4892 blame->cb_args.quit = &s->done;
4894 blame->thread_args.path = s->path;
4895 blame->thread_args.repo = thread_repo;
4896 blame->thread_args.cb_args = &blame->cb_args;
4897 blame->thread_args.complete = &s->blame_complete;
4898 blame->thread_args.cancel_cb = cancel_blame_view;
4899 blame->thread_args.cancel_arg = &s->done;
4900 s->blame_complete = 0;
4902 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
4903 s->first_displayed_line = 1;
4904 s->last_displayed_line = view->nlines;
4905 s->selected_line = 1;
4907 s->matched_line = 0;
4909 done:
4910 if (commit)
4911 got_object_commit_close(commit);
4912 if (fd != -1 && close(fd) == -1 && err == NULL)
4913 err = got_error_from_errno("close");
4914 if (blob)
4915 got_object_blob_close(blob);
4916 free(obj_id);
4917 if (err)
4918 stop_blame(blame);
4919 return err;
4922 static const struct got_error *
4923 open_blame_view(struct tog_view *view, char *path,
4924 struct got_object_id *commit_id, struct got_repository *repo)
4926 const struct got_error *err = NULL;
4927 struct tog_blame_view_state *s = &view->state.blame;
4929 STAILQ_INIT(&s->blamed_commits);
4931 s->path = strdup(path);
4932 if (s->path == NULL)
4933 return got_error_from_errno("strdup");
4935 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
4936 if (err) {
4937 free(s->path);
4938 return err;
4941 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
4942 s->first_displayed_line = 1;
4943 s->last_displayed_line = view->nlines;
4944 s->selected_line = 1;
4945 s->blame_complete = 0;
4946 s->repo = repo;
4947 s->commit_id = commit_id;
4948 memset(&s->blame, 0, sizeof(s->blame));
4950 STAILQ_INIT(&s->colors);
4951 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4952 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
4953 get_color_value("TOG_COLOR_COMMIT"));
4954 if (err)
4955 return err;
4958 view->show = show_blame_view;
4959 view->input = input_blame_view;
4960 view->close = close_blame_view;
4961 view->search_start = search_start_blame_view;
4962 view->search_next = search_next_blame_view;
4964 return run_blame(view);
4967 static const struct got_error *
4968 close_blame_view(struct tog_view *view)
4970 const struct got_error *err = NULL;
4971 struct tog_blame_view_state *s = &view->state.blame;
4973 if (s->blame.thread)
4974 err = stop_blame(&s->blame);
4976 while (!STAILQ_EMPTY(&s->blamed_commits)) {
4977 struct got_object_qid *blamed_commit;
4978 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
4979 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
4980 got_object_qid_free(blamed_commit);
4983 free(s->path);
4984 free_colors(&s->colors);
4985 return err;
4988 static const struct got_error *
4989 search_start_blame_view(struct tog_view *view)
4991 struct tog_blame_view_state *s = &view->state.blame;
4993 s->matched_line = 0;
4994 return NULL;
4997 static const struct got_error *
4998 search_next_blame_view(struct tog_view *view)
5000 struct tog_blame_view_state *s = &view->state.blame;
5001 const struct got_error *err = NULL;
5002 int lineno;
5003 char *line = NULL;
5004 size_t linesize = 0;
5005 ssize_t linelen;
5007 if (!view->searching) {
5008 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5009 return NULL;
5012 if (s->matched_line) {
5013 if (view->searching == TOG_SEARCH_FORWARD)
5014 lineno = s->matched_line + 1;
5015 else
5016 lineno = s->matched_line - 1;
5017 } else
5018 lineno = s->first_displayed_line - 1 + s->selected_line;
5020 while (1) {
5021 off_t offset;
5023 if (lineno <= 0 || lineno > s->blame.nlines) {
5024 if (s->matched_line == 0) {
5025 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5026 break;
5029 if (view->searching == TOG_SEARCH_FORWARD)
5030 lineno = 1;
5031 else
5032 lineno = s->blame.nlines;
5035 offset = s->blame.line_offsets[lineno - 1];
5036 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5037 free(line);
5038 return got_error_from_errno("fseeko");
5040 linelen = getline(&line, &linesize, s->blame.f);
5041 if (linelen != -1) {
5042 char *exstr;
5043 err = expand_tab(&exstr, line);
5044 if (err)
5045 break;
5046 if (match_line(exstr, &view->regex, 1,
5047 &view->regmatch)) {
5048 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5049 s->matched_line = lineno;
5050 free(exstr);
5051 break;
5053 free(exstr);
5055 if (view->searching == TOG_SEARCH_FORWARD)
5056 lineno++;
5057 else
5058 lineno--;
5060 free(line);
5062 if (s->matched_line) {
5063 s->first_displayed_line = s->matched_line;
5064 s->selected_line = 1;
5067 return err;
5070 static const struct got_error *
5071 show_blame_view(struct tog_view *view)
5073 const struct got_error *err = NULL;
5074 struct tog_blame_view_state *s = &view->state.blame;
5075 int errcode;
5077 if (s->blame.thread == NULL && !s->blame_complete) {
5078 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5079 &s->blame.thread_args);
5080 if (errcode)
5081 return got_error_set_errno(errcode, "pthread_create");
5083 halfdelay(1); /* fast refresh while annotating */
5086 if (s->blame_complete)
5087 halfdelay(10); /* disable fast refresh */
5089 err = draw_blame(view);
5091 view_vborder(view);
5092 return err;
5095 static const struct got_error *
5096 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5098 const struct got_error *err = NULL, *thread_err = NULL;
5099 struct tog_view *diff_view;
5100 struct tog_blame_view_state *s = &view->state.blame;
5101 int begin_x = 0, nscroll = view->nlines - 2;
5103 switch (ch) {
5104 case '0':
5105 view->x = 0;
5106 break;
5107 case '$':
5108 view->x = MAX(view->maxx - view->ncols / 3, 0);
5109 view->count = 0;
5110 break;
5111 case KEY_RIGHT:
5112 case 'l':
5113 if (view->x + view->ncols / 3 < view->maxx)
5114 view->x += 2; /* move two columns right */
5115 else
5116 view->count = 0;
5117 break;
5118 case KEY_LEFT:
5119 case 'h':
5120 view->x -= MIN(view->x, 2); /* move two columns back */
5121 if (view->x <= 0)
5122 view->count = 0;
5123 break;
5124 case 'q':
5125 s->done = 1;
5126 break;
5127 case 'g':
5128 case KEY_HOME:
5129 s->selected_line = 1;
5130 s->first_displayed_line = 1;
5131 view->count = 0;
5132 break;
5133 case 'G':
5134 case KEY_END:
5135 if (s->blame.nlines < view->nlines - 2) {
5136 s->selected_line = s->blame.nlines;
5137 s->first_displayed_line = 1;
5138 } else {
5139 s->selected_line = view->nlines - 2;
5140 s->first_displayed_line = s->blame.nlines -
5141 (view->nlines - 3);
5143 view->count = 0;
5144 break;
5145 case 'k':
5146 case KEY_UP:
5147 case CTRL('p'):
5148 if (s->selected_line > 1)
5149 s->selected_line--;
5150 else if (s->selected_line == 1 &&
5151 s->first_displayed_line > 1)
5152 s->first_displayed_line--;
5153 else
5154 view->count = 0;
5155 break;
5156 case CTRL('u'):
5157 case 'u':
5158 nscroll /= 2;
5159 /* FALL THROUGH */
5160 case KEY_PPAGE:
5161 case CTRL('b'):
5162 case 'b':
5163 if (s->first_displayed_line == 1) {
5164 if (view->count > 1)
5165 nscroll += nscroll;
5166 s->selected_line = MAX(1, s->selected_line - nscroll);
5167 view->count = 0;
5168 break;
5170 if (s->first_displayed_line > nscroll)
5171 s->first_displayed_line -= nscroll;
5172 else
5173 s->first_displayed_line = 1;
5174 break;
5175 case 'j':
5176 case KEY_DOWN:
5177 case CTRL('n'):
5178 if (s->selected_line < view->nlines - 2 &&
5179 s->first_displayed_line +
5180 s->selected_line <= s->blame.nlines)
5181 s->selected_line++;
5182 else if (s->last_displayed_line <
5183 s->blame.nlines)
5184 s->first_displayed_line++;
5185 else
5186 view->count = 0;
5187 break;
5188 case 'c':
5189 case 'p': {
5190 struct got_object_id *id = NULL;
5192 view->count = 0;
5193 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5194 s->first_displayed_line, s->selected_line);
5195 if (id == NULL)
5196 break;
5197 if (ch == 'p') {
5198 struct got_commit_object *commit, *pcommit;
5199 struct got_object_qid *pid;
5200 struct got_object_id *blob_id = NULL;
5201 int obj_type;
5202 err = got_object_open_as_commit(&commit,
5203 s->repo, id);
5204 if (err)
5205 break;
5206 pid = STAILQ_FIRST(
5207 got_object_commit_get_parent_ids(commit));
5208 if (pid == NULL) {
5209 got_object_commit_close(commit);
5210 break;
5212 /* Check if path history ends here. */
5213 err = got_object_open_as_commit(&pcommit,
5214 s->repo, &pid->id);
5215 if (err)
5216 break;
5217 err = got_object_id_by_path(&blob_id, s->repo,
5218 pcommit, s->path);
5219 got_object_commit_close(pcommit);
5220 if (err) {
5221 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5222 err = NULL;
5223 got_object_commit_close(commit);
5224 break;
5226 err = got_object_get_type(&obj_type, s->repo,
5227 blob_id);
5228 free(blob_id);
5229 /* Can't blame non-blob type objects. */
5230 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5231 got_object_commit_close(commit);
5232 break;
5234 err = got_object_qid_alloc(&s->blamed_commit,
5235 &pid->id);
5236 got_object_commit_close(commit);
5237 } else {
5238 if (got_object_id_cmp(id,
5239 &s->blamed_commit->id) == 0)
5240 break;
5241 err = got_object_qid_alloc(&s->blamed_commit,
5242 id);
5244 if (err)
5245 break;
5246 s->done = 1;
5247 thread_err = stop_blame(&s->blame);
5248 s->done = 0;
5249 if (thread_err)
5250 break;
5251 STAILQ_INSERT_HEAD(&s->blamed_commits,
5252 s->blamed_commit, entry);
5253 err = run_blame(view);
5254 if (err)
5255 break;
5256 break;
5258 case 'C': {
5259 struct got_object_qid *first;
5261 view->count = 0;
5262 first = STAILQ_FIRST(&s->blamed_commits);
5263 if (!got_object_id_cmp(&first->id, s->commit_id))
5264 break;
5265 s->done = 1;
5266 thread_err = stop_blame(&s->blame);
5267 s->done = 0;
5268 if (thread_err)
5269 break;
5270 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5271 got_object_qid_free(s->blamed_commit);
5272 s->blamed_commit =
5273 STAILQ_FIRST(&s->blamed_commits);
5274 err = run_blame(view);
5275 if (err)
5276 break;
5277 break;
5279 case KEY_ENTER:
5280 case '\r': {
5281 struct got_object_id *id = NULL;
5282 struct got_object_qid *pid;
5283 struct got_commit_object *commit = NULL;
5285 view->count = 0;
5286 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5287 s->first_displayed_line, s->selected_line);
5288 if (id == NULL)
5289 break;
5290 err = got_object_open_as_commit(&commit, s->repo, id);
5291 if (err)
5292 break;
5293 pid = STAILQ_FIRST(
5294 got_object_commit_get_parent_ids(commit));
5295 if (view_is_parent_view(view))
5296 begin_x = view_split_begin_x(view->begin_x);
5297 diff_view = view_open(0, 0, 0, begin_x, TOG_VIEW_DIFF);
5298 if (diff_view == NULL) {
5299 got_object_commit_close(commit);
5300 err = got_error_from_errno("view_open");
5301 break;
5303 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5304 id, NULL, NULL, 3, 0, 0, NULL, s->repo);
5305 got_object_commit_close(commit);
5306 if (err) {
5307 view_close(diff_view);
5308 break;
5310 view->focussed = 0;
5311 diff_view->focussed = 1;
5312 if (view_is_parent_view(view)) {
5313 err = view_close_child(view);
5314 if (err)
5315 break;
5316 err = view_set_child(view, diff_view);
5317 if (err)
5318 break;
5319 view->focus_child = 1;
5320 } else
5321 *new_view = diff_view;
5322 if (err)
5323 break;
5324 break;
5326 case CTRL('d'):
5327 case 'd':
5328 nscroll /= 2;
5329 /* FALL THROUGH */
5330 case KEY_NPAGE:
5331 case CTRL('f'):
5332 case 'f':
5333 case ' ':
5334 if (s->last_displayed_line >= s->blame.nlines &&
5335 s->selected_line >= MIN(s->blame.nlines,
5336 view->nlines - 2)) {
5337 view->count = 0;
5338 break;
5340 if (s->last_displayed_line >= s->blame.nlines &&
5341 s->selected_line < view->nlines - 2) {
5342 s->selected_line +=
5343 MIN(nscroll, s->last_displayed_line -
5344 s->first_displayed_line - s->selected_line + 1);
5346 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5347 s->first_displayed_line += nscroll;
5348 else
5349 s->first_displayed_line =
5350 s->blame.nlines - (view->nlines - 3);
5351 break;
5352 case KEY_RESIZE:
5353 if (s->selected_line > view->nlines - 2) {
5354 s->selected_line = MIN(s->blame.nlines,
5355 view->nlines - 2);
5357 break;
5358 default:
5359 view->count = 0;
5360 break;
5362 return thread_err ? thread_err : err;
5365 static const struct got_error *
5366 cmd_blame(int argc, char *argv[])
5368 const struct got_error *error;
5369 struct got_repository *repo = NULL;
5370 struct got_worktree *worktree = NULL;
5371 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5372 char *link_target = NULL;
5373 struct got_object_id *commit_id = NULL;
5374 struct got_commit_object *commit = NULL;
5375 char *commit_id_str = NULL;
5376 int ch;
5377 struct tog_view *view;
5378 int *pack_fds = NULL;
5380 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5381 switch (ch) {
5382 case 'c':
5383 commit_id_str = optarg;
5384 break;
5385 case 'r':
5386 repo_path = realpath(optarg, NULL);
5387 if (repo_path == NULL)
5388 return got_error_from_errno2("realpath",
5389 optarg);
5390 break;
5391 default:
5392 usage_blame();
5393 /* NOTREACHED */
5397 argc -= optind;
5398 argv += optind;
5400 if (argc != 1)
5401 usage_blame();
5403 error = got_repo_pack_fds_open(&pack_fds);
5404 if (error != NULL)
5405 goto done;
5407 if (repo_path == NULL) {
5408 cwd = getcwd(NULL, 0);
5409 if (cwd == NULL)
5410 return got_error_from_errno("getcwd");
5411 error = got_worktree_open(&worktree, cwd);
5412 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5413 goto done;
5414 if (worktree)
5415 repo_path =
5416 strdup(got_worktree_get_repo_path(worktree));
5417 else
5418 repo_path = strdup(cwd);
5419 if (repo_path == NULL) {
5420 error = got_error_from_errno("strdup");
5421 goto done;
5425 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5426 if (error != NULL)
5427 goto done;
5429 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
5430 worktree);
5431 if (error)
5432 goto done;
5434 init_curses();
5436 error = apply_unveil(got_repo_get_path(repo), NULL);
5437 if (error)
5438 goto done;
5440 error = tog_load_refs(repo, 0);
5441 if (error)
5442 goto done;
5444 if (commit_id_str == NULL) {
5445 struct got_reference *head_ref;
5446 error = got_ref_open(&head_ref, repo, worktree ?
5447 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5448 if (error != NULL)
5449 goto done;
5450 error = got_ref_resolve(&commit_id, repo, head_ref);
5451 got_ref_close(head_ref);
5452 } else {
5453 error = got_repo_match_object_id(&commit_id, NULL,
5454 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
5456 if (error != NULL)
5457 goto done;
5459 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
5460 if (view == NULL) {
5461 error = got_error_from_errno("view_open");
5462 goto done;
5465 error = got_object_open_as_commit(&commit, repo, commit_id);
5466 if (error)
5467 goto done;
5469 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5470 commit, repo);
5471 if (error)
5472 goto done;
5474 error = open_blame_view(view, link_target ? link_target : in_repo_path,
5475 commit_id, repo);
5476 if (error)
5477 goto done;
5478 if (worktree) {
5479 /* Release work tree lock. */
5480 got_worktree_close(worktree);
5481 worktree = NULL;
5483 error = view_loop(view);
5484 done:
5485 free(repo_path);
5486 free(in_repo_path);
5487 free(link_target);
5488 free(cwd);
5489 free(commit_id);
5490 if (commit)
5491 got_object_commit_close(commit);
5492 if (worktree)
5493 got_worktree_close(worktree);
5494 if (repo) {
5495 const struct got_error *close_err = got_repo_close(repo);
5496 if (error == NULL)
5497 error = close_err;
5499 if (pack_fds) {
5500 const struct got_error *pack_err =
5501 got_repo_pack_fds_close(pack_fds);
5502 if (error == NULL)
5503 error = pack_err;
5505 tog_free_refs();
5506 return error;
5509 static const struct got_error *
5510 draw_tree_entries(struct tog_view *view, const char *parent_path)
5512 struct tog_tree_view_state *s = &view->state.tree;
5513 const struct got_error *err = NULL;
5514 struct got_tree_entry *te;
5515 wchar_t *wline;
5516 struct tog_color *tc;
5517 int width, n, i, nentries;
5518 int limit = view->nlines;
5520 s->ndisplayed = 0;
5522 werase(view->window);
5524 if (limit == 0)
5525 return NULL;
5527 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
5528 0, 0);
5529 if (err)
5530 return err;
5531 if (view_needs_focus_indication(view))
5532 wstandout(view->window);
5533 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5534 if (tc)
5535 wattr_on(view->window,
5536 COLOR_PAIR(tc->colorpair), NULL);
5537 waddwstr(view->window, wline);
5538 if (tc)
5539 wattr_off(view->window,
5540 COLOR_PAIR(tc->colorpair), NULL);
5541 if (view_needs_focus_indication(view))
5542 wstandend(view->window);
5543 free(wline);
5544 wline = NULL;
5545 if (width < view->ncols - 1)
5546 waddch(view->window, '\n');
5547 if (--limit <= 0)
5548 return NULL;
5549 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
5550 0, 0);
5551 if (err)
5552 return err;
5553 waddwstr(view->window, wline);
5554 free(wline);
5555 wline = NULL;
5556 if (width < view->ncols - 1)
5557 waddch(view->window, '\n');
5558 if (--limit <= 0)
5559 return NULL;
5560 waddch(view->window, '\n');
5561 if (--limit <= 0)
5562 return NULL;
5564 if (s->first_displayed_entry == NULL) {
5565 te = got_object_tree_get_first_entry(s->tree);
5566 if (s->selected == 0) {
5567 if (view->focussed)
5568 wstandout(view->window);
5569 s->selected_entry = NULL;
5571 waddstr(view->window, " ..\n"); /* parent directory */
5572 if (s->selected == 0 && view->focussed)
5573 wstandend(view->window);
5574 s->ndisplayed++;
5575 if (--limit <= 0)
5576 return NULL;
5577 n = 1;
5578 } else {
5579 n = 0;
5580 te = s->first_displayed_entry;
5583 nentries = got_object_tree_get_nentries(s->tree);
5584 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
5585 char *line = NULL, *id_str = NULL, *link_target = NULL;
5586 const char *modestr = "";
5587 mode_t mode;
5589 te = got_object_tree_get_entry(s->tree, i);
5590 mode = got_tree_entry_get_mode(te);
5592 if (s->show_ids) {
5593 err = got_object_id_str(&id_str,
5594 got_tree_entry_get_id(te));
5595 if (err)
5596 return got_error_from_errno(
5597 "got_object_id_str");
5599 if (got_object_tree_entry_is_submodule(te))
5600 modestr = "$";
5601 else if (S_ISLNK(mode)) {
5602 int i;
5604 err = got_tree_entry_get_symlink_target(&link_target,
5605 te, s->repo);
5606 if (err) {
5607 free(id_str);
5608 return err;
5610 for (i = 0; i < strlen(link_target); i++) {
5611 if (!isprint((unsigned char)link_target[i]))
5612 link_target[i] = '?';
5614 modestr = "@";
5616 else if (S_ISDIR(mode))
5617 modestr = "/";
5618 else if (mode & S_IXUSR)
5619 modestr = "*";
5620 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
5621 got_tree_entry_get_name(te), modestr,
5622 link_target ? " -> ": "",
5623 link_target ? link_target : "") == -1) {
5624 free(id_str);
5625 free(link_target);
5626 return got_error_from_errno("asprintf");
5628 free(id_str);
5629 free(link_target);
5630 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
5631 0, 0);
5632 if (err) {
5633 free(line);
5634 break;
5636 if (n == s->selected) {
5637 if (view->focussed)
5638 wstandout(view->window);
5639 s->selected_entry = te;
5641 tc = match_color(&s->colors, line);
5642 if (tc)
5643 wattr_on(view->window,
5644 COLOR_PAIR(tc->colorpair), NULL);
5645 waddwstr(view->window, wline);
5646 if (tc)
5647 wattr_off(view->window,
5648 COLOR_PAIR(tc->colorpair), NULL);
5649 if (width < view->ncols - 1)
5650 waddch(view->window, '\n');
5651 if (n == s->selected && view->focussed)
5652 wstandend(view->window);
5653 free(line);
5654 free(wline);
5655 wline = NULL;
5656 n++;
5657 s->ndisplayed++;
5658 s->last_displayed_entry = te;
5659 if (--limit <= 0)
5660 break;
5663 return err;
5666 static void
5667 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
5669 struct got_tree_entry *te;
5670 int isroot = s->tree == s->root;
5671 int i = 0;
5673 if (s->first_displayed_entry == NULL)
5674 return;
5676 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
5677 while (i++ < maxscroll) {
5678 if (te == NULL) {
5679 if (!isroot)
5680 s->first_displayed_entry = NULL;
5681 break;
5683 s->first_displayed_entry = te;
5684 te = got_tree_entry_get_prev(s->tree, te);
5688 static void
5689 tree_scroll_down(struct tog_tree_view_state *s, int maxscroll)
5691 struct got_tree_entry *next, *last;
5692 int n = 0;
5694 if (s->first_displayed_entry)
5695 next = got_tree_entry_get_next(s->tree,
5696 s->first_displayed_entry);
5697 else
5698 next = got_object_tree_get_first_entry(s->tree);
5700 last = s->last_displayed_entry;
5701 while (next && last && n++ < maxscroll) {
5702 last = got_tree_entry_get_next(s->tree, last);
5703 if (last) {
5704 s->first_displayed_entry = next;
5705 next = got_tree_entry_get_next(s->tree, next);
5710 static const struct got_error *
5711 tree_entry_path(char **path, struct tog_parent_trees *parents,
5712 struct got_tree_entry *te)
5714 const struct got_error *err = NULL;
5715 struct tog_parent_tree *pt;
5716 size_t len = 2; /* for leading slash and NUL */
5718 TAILQ_FOREACH(pt, parents, entry)
5719 len += strlen(got_tree_entry_get_name(pt->selected_entry))
5720 + 1 /* slash */;
5721 if (te)
5722 len += strlen(got_tree_entry_get_name(te));
5724 *path = calloc(1, len);
5725 if (path == NULL)
5726 return got_error_from_errno("calloc");
5728 (*path)[0] = '/';
5729 pt = TAILQ_LAST(parents, tog_parent_trees);
5730 while (pt) {
5731 const char *name = got_tree_entry_get_name(pt->selected_entry);
5732 if (strlcat(*path, name, len) >= len) {
5733 err = got_error(GOT_ERR_NO_SPACE);
5734 goto done;
5736 if (strlcat(*path, "/", len) >= len) {
5737 err = got_error(GOT_ERR_NO_SPACE);
5738 goto done;
5740 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
5742 if (te) {
5743 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
5744 err = got_error(GOT_ERR_NO_SPACE);
5745 goto done;
5748 done:
5749 if (err) {
5750 free(*path);
5751 *path = NULL;
5753 return err;
5756 static const struct got_error *
5757 blame_tree_entry(struct tog_view **new_view, int begin_x,
5758 struct got_tree_entry *te, struct tog_parent_trees *parents,
5759 struct got_object_id *commit_id, struct got_repository *repo)
5761 const struct got_error *err = NULL;
5762 char *path;
5763 struct tog_view *blame_view;
5765 *new_view = NULL;
5767 err = tree_entry_path(&path, parents, te);
5768 if (err)
5769 return err;
5771 blame_view = view_open(0, 0, 0, begin_x, TOG_VIEW_BLAME);
5772 if (blame_view == NULL) {
5773 err = got_error_from_errno("view_open");
5774 goto done;
5777 err = open_blame_view(blame_view, path, commit_id, repo);
5778 if (err) {
5779 if (err->code == GOT_ERR_CANCELLED)
5780 err = NULL;
5781 view_close(blame_view);
5782 } else
5783 *new_view = blame_view;
5784 done:
5785 free(path);
5786 return err;
5789 static const struct got_error *
5790 log_selected_tree_entry(struct tog_view **new_view, int begin_x,
5791 struct tog_tree_view_state *s)
5793 struct tog_view *log_view;
5794 const struct got_error *err = NULL;
5795 char *path;
5797 *new_view = NULL;
5799 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
5800 if (log_view == NULL)
5801 return got_error_from_errno("view_open");
5803 err = tree_entry_path(&path, &s->parents, s->selected_entry);
5804 if (err)
5805 return err;
5807 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
5808 path, 0);
5809 if (err)
5810 view_close(log_view);
5811 else
5812 *new_view = log_view;
5813 free(path);
5814 return err;
5817 static const struct got_error *
5818 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
5819 const char *head_ref_name, struct got_repository *repo)
5821 const struct got_error *err = NULL;
5822 char *commit_id_str = NULL;
5823 struct tog_tree_view_state *s = &view->state.tree;
5824 struct got_commit_object *commit = NULL;
5826 TAILQ_INIT(&s->parents);
5827 STAILQ_INIT(&s->colors);
5829 s->commit_id = got_object_id_dup(commit_id);
5830 if (s->commit_id == NULL)
5831 return got_error_from_errno("got_object_id_dup");
5833 err = got_object_open_as_commit(&commit, repo, commit_id);
5834 if (err)
5835 goto done;
5838 * The root is opened here and will be closed when the view is closed.
5839 * Any visited subtrees and their path-wise parents are opened and
5840 * closed on demand.
5842 err = got_object_open_as_tree(&s->root, repo,
5843 got_object_commit_get_tree_id(commit));
5844 if (err)
5845 goto done;
5846 s->tree = s->root;
5848 err = got_object_id_str(&commit_id_str, commit_id);
5849 if (err != NULL)
5850 goto done;
5852 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
5853 err = got_error_from_errno("asprintf");
5854 goto done;
5857 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
5858 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
5859 if (head_ref_name) {
5860 s->head_ref_name = strdup(head_ref_name);
5861 if (s->head_ref_name == NULL) {
5862 err = got_error_from_errno("strdup");
5863 goto done;
5866 s->repo = repo;
5868 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5869 err = add_color(&s->colors, "\\$$",
5870 TOG_COLOR_TREE_SUBMODULE,
5871 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
5872 if (err)
5873 goto done;
5874 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
5875 get_color_value("TOG_COLOR_TREE_SYMLINK"));
5876 if (err)
5877 goto done;
5878 err = add_color(&s->colors, "/$",
5879 TOG_COLOR_TREE_DIRECTORY,
5880 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
5881 if (err)
5882 goto done;
5884 err = add_color(&s->colors, "\\*$",
5885 TOG_COLOR_TREE_EXECUTABLE,
5886 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
5887 if (err)
5888 goto done;
5890 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
5891 get_color_value("TOG_COLOR_COMMIT"));
5892 if (err)
5893 goto done;
5896 view->show = show_tree_view;
5897 view->input = input_tree_view;
5898 view->close = close_tree_view;
5899 view->search_start = search_start_tree_view;
5900 view->search_next = search_next_tree_view;
5901 done:
5902 free(commit_id_str);
5903 if (commit)
5904 got_object_commit_close(commit);
5905 if (err)
5906 close_tree_view(view);
5907 return err;
5910 static const struct got_error *
5911 close_tree_view(struct tog_view *view)
5913 struct tog_tree_view_state *s = &view->state.tree;
5915 free_colors(&s->colors);
5916 free(s->tree_label);
5917 s->tree_label = NULL;
5918 free(s->commit_id);
5919 s->commit_id = NULL;
5920 free(s->head_ref_name);
5921 s->head_ref_name = NULL;
5922 while (!TAILQ_EMPTY(&s->parents)) {
5923 struct tog_parent_tree *parent;
5924 parent = TAILQ_FIRST(&s->parents);
5925 TAILQ_REMOVE(&s->parents, parent, entry);
5926 if (parent->tree != s->root)
5927 got_object_tree_close(parent->tree);
5928 free(parent);
5931 if (s->tree != NULL && s->tree != s->root)
5932 got_object_tree_close(s->tree);
5933 if (s->root)
5934 got_object_tree_close(s->root);
5935 return NULL;
5938 static const struct got_error *
5939 search_start_tree_view(struct tog_view *view)
5941 struct tog_tree_view_state *s = &view->state.tree;
5943 s->matched_entry = NULL;
5944 return NULL;
5947 static int
5948 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
5950 regmatch_t regmatch;
5952 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
5953 0) == 0;
5956 static const struct got_error *
5957 search_next_tree_view(struct tog_view *view)
5959 struct tog_tree_view_state *s = &view->state.tree;
5960 struct got_tree_entry *te = NULL;
5962 if (!view->searching) {
5963 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5964 return NULL;
5967 if (s->matched_entry) {
5968 if (view->searching == TOG_SEARCH_FORWARD) {
5969 if (s->selected_entry)
5970 te = got_tree_entry_get_next(s->tree,
5971 s->selected_entry);
5972 else
5973 te = got_object_tree_get_first_entry(s->tree);
5974 } else {
5975 if (s->selected_entry == NULL)
5976 te = got_object_tree_get_last_entry(s->tree);
5977 else
5978 te = got_tree_entry_get_prev(s->tree,
5979 s->selected_entry);
5981 } else {
5982 if (s->selected_entry)
5983 te = s->selected_entry;
5984 else if (view->searching == TOG_SEARCH_FORWARD)
5985 te = got_object_tree_get_first_entry(s->tree);
5986 else
5987 te = got_object_tree_get_last_entry(s->tree);
5990 while (1) {
5991 if (te == NULL) {
5992 if (s->matched_entry == NULL) {
5993 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5994 return NULL;
5996 if (view->searching == TOG_SEARCH_FORWARD)
5997 te = got_object_tree_get_first_entry(s->tree);
5998 else
5999 te = got_object_tree_get_last_entry(s->tree);
6002 if (match_tree_entry(te, &view->regex)) {
6003 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6004 s->matched_entry = te;
6005 break;
6008 if (view->searching == TOG_SEARCH_FORWARD)
6009 te = got_tree_entry_get_next(s->tree, te);
6010 else
6011 te = got_tree_entry_get_prev(s->tree, te);
6014 if (s->matched_entry) {
6015 s->first_displayed_entry = s->matched_entry;
6016 s->selected = 0;
6019 return NULL;
6022 static const struct got_error *
6023 show_tree_view(struct tog_view *view)
6025 const struct got_error *err = NULL;
6026 struct tog_tree_view_state *s = &view->state.tree;
6027 char *parent_path;
6029 err = tree_entry_path(&parent_path, &s->parents, NULL);
6030 if (err)
6031 return err;
6033 err = draw_tree_entries(view, parent_path);
6034 free(parent_path);
6036 view_vborder(view);
6037 return err;
6040 static const struct got_error *
6041 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6043 const struct got_error *err = NULL;
6044 struct tog_tree_view_state *s = &view->state.tree;
6045 struct tog_view *log_view, *ref_view;
6046 struct got_tree_entry *te;
6047 int begin_x = 0, n, nscroll = view->nlines - 3;
6049 switch (ch) {
6050 case 'i':
6051 s->show_ids = !s->show_ids;
6052 view->count = 0;
6053 break;
6054 case 'l':
6055 view->count = 0;
6056 if (!s->selected_entry)
6057 break;
6058 if (view_is_parent_view(view))
6059 begin_x = view_split_begin_x(view->begin_x);
6060 err = log_selected_tree_entry(&log_view, begin_x, s);
6061 view->focussed = 0;
6062 log_view->focussed = 1;
6063 if (view_is_parent_view(view)) {
6064 err = view_close_child(view);
6065 if (err)
6066 return err;
6067 err = view_set_child(view, log_view);
6068 if (err)
6069 return err;
6070 view->focus_child = 1;
6071 } else
6072 *new_view = log_view;
6073 break;
6074 case 'r':
6075 view->count = 0;
6076 if (view_is_parent_view(view))
6077 begin_x = view_split_begin_x(view->begin_x);
6078 ref_view = view_open(view->nlines, view->ncols,
6079 view->begin_y, begin_x, TOG_VIEW_REF);
6080 if (ref_view == NULL)
6081 return got_error_from_errno("view_open");
6082 err = open_ref_view(ref_view, s->repo);
6083 if (err) {
6084 view_close(ref_view);
6085 return err;
6087 view->focussed = 0;
6088 ref_view->focussed = 1;
6089 if (view_is_parent_view(view)) {
6090 err = view_close_child(view);
6091 if (err)
6092 return err;
6093 err = view_set_child(view, ref_view);
6094 if (err)
6095 return err;
6096 view->focus_child = 1;
6097 } else
6098 *new_view = ref_view;
6099 break;
6100 case 'g':
6101 case KEY_HOME:
6102 s->selected = 0;
6103 view->count = 0;
6104 if (s->tree == s->root)
6105 s->first_displayed_entry =
6106 got_object_tree_get_first_entry(s->tree);
6107 else
6108 s->first_displayed_entry = NULL;
6109 break;
6110 case 'G':
6111 case KEY_END:
6112 s->selected = 0;
6113 view->count = 0;
6114 te = got_object_tree_get_last_entry(s->tree);
6115 for (n = 0; n < view->nlines - 3; n++) {
6116 if (te == NULL) {
6117 if(s->tree != s->root) {
6118 s->first_displayed_entry = NULL;
6119 n++;
6121 break;
6123 s->first_displayed_entry = te;
6124 te = got_tree_entry_get_prev(s->tree, te);
6126 if (n > 0)
6127 s->selected = n - 1;
6128 break;
6129 case 'k':
6130 case KEY_UP:
6131 case CTRL('p'):
6132 if (s->selected > 0) {
6133 s->selected--;
6134 break;
6136 tree_scroll_up(s, 1);
6137 if (s->selected_entry == NULL ||
6138 (s->tree == s->root && s->selected_entry ==
6139 got_object_tree_get_first_entry(s->tree)))
6140 view->count = 0;
6141 break;
6142 case CTRL('u'):
6143 case 'u':
6144 nscroll /= 2;
6145 /* FALL THROUGH */
6146 case KEY_PPAGE:
6147 case CTRL('b'):
6148 case 'b':
6149 if (s->tree == s->root) {
6150 if (got_object_tree_get_first_entry(s->tree) ==
6151 s->first_displayed_entry)
6152 s->selected -= MIN(s->selected, nscroll);
6153 } else {
6154 if (s->first_displayed_entry == NULL)
6155 s->selected -= MIN(s->selected, nscroll);
6157 tree_scroll_up(s, MAX(0, nscroll));
6158 if (s->selected_entry == NULL ||
6159 (s->tree == s->root && s->selected_entry ==
6160 got_object_tree_get_first_entry(s->tree)))
6161 view->count = 0;
6162 break;
6163 case 'j':
6164 case KEY_DOWN:
6165 case CTRL('n'):
6166 if (s->selected < s->ndisplayed - 1) {
6167 s->selected++;
6168 break;
6170 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6171 == NULL) {
6172 /* can't scroll any further */
6173 view->count = 0;
6174 break;
6176 tree_scroll_down(s, 1);
6177 break;
6178 case CTRL('d'):
6179 case 'd':
6180 nscroll /= 2;
6181 /* FALL THROUGH */
6182 case KEY_NPAGE:
6183 case CTRL('f'):
6184 case 'f':
6185 case ' ':
6186 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6187 == NULL) {
6188 /* can't scroll any further; move cursor down */
6189 if (s->selected < s->ndisplayed - 1)
6190 s->selected += MIN(nscroll,
6191 s->ndisplayed - s->selected - 1);
6192 else
6193 view->count = 0;
6194 break;
6196 tree_scroll_down(s, nscroll);
6197 break;
6198 case KEY_ENTER:
6199 case '\r':
6200 case KEY_BACKSPACE:
6201 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6202 struct tog_parent_tree *parent;
6203 /* user selected '..' */
6204 if (s->tree == s->root) {
6205 view->count = 0;
6206 break;
6208 parent = TAILQ_FIRST(&s->parents);
6209 TAILQ_REMOVE(&s->parents, parent,
6210 entry);
6211 got_object_tree_close(s->tree);
6212 s->tree = parent->tree;
6213 s->first_displayed_entry =
6214 parent->first_displayed_entry;
6215 s->selected_entry =
6216 parent->selected_entry;
6217 s->selected = parent->selected;
6218 free(parent);
6219 } else if (S_ISDIR(got_tree_entry_get_mode(
6220 s->selected_entry))) {
6221 struct got_tree_object *subtree;
6222 view->count = 0;
6223 err = got_object_open_as_tree(&subtree, s->repo,
6224 got_tree_entry_get_id(s->selected_entry));
6225 if (err)
6226 break;
6227 err = tree_view_visit_subtree(s, subtree);
6228 if (err) {
6229 got_object_tree_close(subtree);
6230 break;
6232 } else if (S_ISREG(got_tree_entry_get_mode(
6233 s->selected_entry))) {
6234 struct tog_view *blame_view;
6235 int begin_x = view_is_parent_view(view) ?
6236 view_split_begin_x(view->begin_x) : 0;
6238 err = blame_tree_entry(&blame_view, begin_x,
6239 s->selected_entry, &s->parents,
6240 s->commit_id, s->repo);
6241 if (err)
6242 break;
6243 view->count = 0;
6244 view->focussed = 0;
6245 blame_view->focussed = 1;
6246 if (view_is_parent_view(view)) {
6247 err = view_close_child(view);
6248 if (err)
6249 return err;
6250 err = view_set_child(view, blame_view);
6251 if (err)
6252 return err;
6253 view->focus_child = 1;
6254 } else
6255 *new_view = blame_view;
6257 break;
6258 case KEY_RESIZE:
6259 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6260 s->selected = view->nlines - 4;
6261 view->count = 0;
6262 break;
6263 default:
6264 view->count = 0;
6265 break;
6268 return err;
6271 __dead static void
6272 usage_tree(void)
6274 endwin();
6275 fprintf(stderr,
6276 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6277 getprogname());
6278 exit(1);
6281 static const struct got_error *
6282 cmd_tree(int argc, char *argv[])
6284 const struct got_error *error;
6285 struct got_repository *repo = NULL;
6286 struct got_worktree *worktree = NULL;
6287 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6288 struct got_object_id *commit_id = NULL;
6289 struct got_commit_object *commit = NULL;
6290 const char *commit_id_arg = NULL;
6291 char *label = NULL;
6292 struct got_reference *ref = NULL;
6293 const char *head_ref_name = NULL;
6294 int ch;
6295 struct tog_view *view;
6296 int *pack_fds = NULL;
6298 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6299 switch (ch) {
6300 case 'c':
6301 commit_id_arg = optarg;
6302 break;
6303 case 'r':
6304 repo_path = realpath(optarg, NULL);
6305 if (repo_path == NULL)
6306 return got_error_from_errno2("realpath",
6307 optarg);
6308 break;
6309 default:
6310 usage_tree();
6311 /* NOTREACHED */
6315 argc -= optind;
6316 argv += optind;
6318 if (argc > 1)
6319 usage_tree();
6321 error = got_repo_pack_fds_open(&pack_fds);
6322 if (error != NULL)
6323 goto done;
6325 if (repo_path == NULL) {
6326 cwd = getcwd(NULL, 0);
6327 if (cwd == NULL)
6328 return got_error_from_errno("getcwd");
6329 error = got_worktree_open(&worktree, cwd);
6330 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6331 goto done;
6332 if (worktree)
6333 repo_path =
6334 strdup(got_worktree_get_repo_path(worktree));
6335 else
6336 repo_path = strdup(cwd);
6337 if (repo_path == NULL) {
6338 error = got_error_from_errno("strdup");
6339 goto done;
6343 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6344 if (error != NULL)
6345 goto done;
6347 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
6348 repo, worktree);
6349 if (error)
6350 goto done;
6352 init_curses();
6354 error = apply_unveil(got_repo_get_path(repo), NULL);
6355 if (error)
6356 goto done;
6358 error = tog_load_refs(repo, 0);
6359 if (error)
6360 goto done;
6362 if (commit_id_arg == NULL) {
6363 error = got_repo_match_object_id(&commit_id, &label,
6364 worktree ? got_worktree_get_head_ref_name(worktree) :
6365 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6366 if (error)
6367 goto done;
6368 head_ref_name = label;
6369 } else {
6370 error = got_ref_open(&ref, repo, commit_id_arg, 0);
6371 if (error == NULL)
6372 head_ref_name = got_ref_get_name(ref);
6373 else if (error->code != GOT_ERR_NOT_REF)
6374 goto done;
6375 error = got_repo_match_object_id(&commit_id, NULL,
6376 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6377 if (error)
6378 goto done;
6381 error = got_object_open_as_commit(&commit, repo, commit_id);
6382 if (error)
6383 goto done;
6385 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
6386 if (view == NULL) {
6387 error = got_error_from_errno("view_open");
6388 goto done;
6390 error = open_tree_view(view, commit_id, head_ref_name, repo);
6391 if (error)
6392 goto done;
6393 if (!got_path_is_root_dir(in_repo_path)) {
6394 error = tree_view_walk_path(&view->state.tree, commit,
6395 in_repo_path);
6396 if (error)
6397 goto done;
6400 if (worktree) {
6401 /* Release work tree lock. */
6402 got_worktree_close(worktree);
6403 worktree = NULL;
6405 error = view_loop(view);
6406 done:
6407 free(repo_path);
6408 free(cwd);
6409 free(commit_id);
6410 free(label);
6411 if (ref)
6412 got_ref_close(ref);
6413 if (repo) {
6414 const struct got_error *close_err = got_repo_close(repo);
6415 if (error == NULL)
6416 error = close_err;
6418 if (pack_fds) {
6419 const struct got_error *pack_err =
6420 got_repo_pack_fds_close(pack_fds);
6421 if (error == NULL)
6422 error = pack_err;
6424 tog_free_refs();
6425 return error;
6428 static const struct got_error *
6429 ref_view_load_refs(struct tog_ref_view_state *s)
6431 struct got_reflist_entry *sre;
6432 struct tog_reflist_entry *re;
6434 s->nrefs = 0;
6435 TAILQ_FOREACH(sre, &tog_refs, entry) {
6436 if (strncmp(got_ref_get_name(sre->ref),
6437 "refs/got/", 9) == 0 &&
6438 strncmp(got_ref_get_name(sre->ref),
6439 "refs/got/backup/", 16) != 0)
6440 continue;
6442 re = malloc(sizeof(*re));
6443 if (re == NULL)
6444 return got_error_from_errno("malloc");
6446 re->ref = got_ref_dup(sre->ref);
6447 if (re->ref == NULL)
6448 return got_error_from_errno("got_ref_dup");
6449 re->idx = s->nrefs++;
6450 TAILQ_INSERT_TAIL(&s->refs, re, entry);
6453 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6454 return NULL;
6457 static void
6458 ref_view_free_refs(struct tog_ref_view_state *s)
6460 struct tog_reflist_entry *re;
6462 while (!TAILQ_EMPTY(&s->refs)) {
6463 re = TAILQ_FIRST(&s->refs);
6464 TAILQ_REMOVE(&s->refs, re, entry);
6465 got_ref_close(re->ref);
6466 free(re);
6470 static const struct got_error *
6471 open_ref_view(struct tog_view *view, struct got_repository *repo)
6473 const struct got_error *err = NULL;
6474 struct tog_ref_view_state *s = &view->state.ref;
6476 s->selected_entry = 0;
6477 s->repo = repo;
6479 TAILQ_INIT(&s->refs);
6480 STAILQ_INIT(&s->colors);
6482 err = ref_view_load_refs(s);
6483 if (err)
6484 return err;
6486 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6487 err = add_color(&s->colors, "^refs/heads/",
6488 TOG_COLOR_REFS_HEADS,
6489 get_color_value("TOG_COLOR_REFS_HEADS"));
6490 if (err)
6491 goto done;
6493 err = add_color(&s->colors, "^refs/tags/",
6494 TOG_COLOR_REFS_TAGS,
6495 get_color_value("TOG_COLOR_REFS_TAGS"));
6496 if (err)
6497 goto done;
6499 err = add_color(&s->colors, "^refs/remotes/",
6500 TOG_COLOR_REFS_REMOTES,
6501 get_color_value("TOG_COLOR_REFS_REMOTES"));
6502 if (err)
6503 goto done;
6505 err = add_color(&s->colors, "^refs/got/backup/",
6506 TOG_COLOR_REFS_BACKUP,
6507 get_color_value("TOG_COLOR_REFS_BACKUP"));
6508 if (err)
6509 goto done;
6512 view->show = show_ref_view;
6513 view->input = input_ref_view;
6514 view->close = close_ref_view;
6515 view->search_start = search_start_ref_view;
6516 view->search_next = search_next_ref_view;
6517 done:
6518 if (err)
6519 free_colors(&s->colors);
6520 return err;
6523 static const struct got_error *
6524 close_ref_view(struct tog_view *view)
6526 struct tog_ref_view_state *s = &view->state.ref;
6528 ref_view_free_refs(s);
6529 free_colors(&s->colors);
6531 return NULL;
6534 static const struct got_error *
6535 resolve_reflist_entry(struct got_object_id **commit_id,
6536 struct tog_reflist_entry *re, struct got_repository *repo)
6538 const struct got_error *err = NULL;
6539 struct got_object_id *obj_id;
6540 struct got_tag_object *tag = NULL;
6541 int obj_type;
6543 *commit_id = NULL;
6545 err = got_ref_resolve(&obj_id, repo, re->ref);
6546 if (err)
6547 return err;
6549 err = got_object_get_type(&obj_type, repo, obj_id);
6550 if (err)
6551 goto done;
6553 switch (obj_type) {
6554 case GOT_OBJ_TYPE_COMMIT:
6555 *commit_id = obj_id;
6556 break;
6557 case GOT_OBJ_TYPE_TAG:
6558 err = got_object_open_as_tag(&tag, repo, obj_id);
6559 if (err)
6560 goto done;
6561 free(obj_id);
6562 err = got_object_get_type(&obj_type, repo,
6563 got_object_tag_get_object_id(tag));
6564 if (err)
6565 goto done;
6566 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
6567 err = got_error(GOT_ERR_OBJ_TYPE);
6568 goto done;
6570 *commit_id = got_object_id_dup(
6571 got_object_tag_get_object_id(tag));
6572 if (*commit_id == NULL) {
6573 err = got_error_from_errno("got_object_id_dup");
6574 goto done;
6576 break;
6577 default:
6578 err = got_error(GOT_ERR_OBJ_TYPE);
6579 break;
6582 done:
6583 if (tag)
6584 got_object_tag_close(tag);
6585 if (err) {
6586 free(*commit_id);
6587 *commit_id = NULL;
6589 return err;
6592 static const struct got_error *
6593 log_ref_entry(struct tog_view **new_view, int begin_x,
6594 struct tog_reflist_entry *re, struct got_repository *repo)
6596 struct tog_view *log_view;
6597 const struct got_error *err = NULL;
6598 struct got_object_id *commit_id = NULL;
6600 *new_view = NULL;
6602 err = resolve_reflist_entry(&commit_id, re, repo);
6603 if (err) {
6604 if (err->code != GOT_ERR_OBJ_TYPE)
6605 return err;
6606 else
6607 return NULL;
6610 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
6611 if (log_view == NULL) {
6612 err = got_error_from_errno("view_open");
6613 goto done;
6616 err = open_log_view(log_view, commit_id, repo,
6617 got_ref_get_name(re->ref), "", 0);
6618 done:
6619 if (err)
6620 view_close(log_view);
6621 else
6622 *new_view = log_view;
6623 free(commit_id);
6624 return err;
6627 static void
6628 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
6630 struct tog_reflist_entry *re;
6631 int i = 0;
6633 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
6634 return;
6636 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
6637 while (i++ < maxscroll) {
6638 if (re == NULL)
6639 break;
6640 s->first_displayed_entry = re;
6641 re = TAILQ_PREV(re, tog_reflist_head, entry);
6645 static void
6646 ref_scroll_down(struct tog_ref_view_state *s, int maxscroll)
6648 struct tog_reflist_entry *next, *last;
6649 int n = 0;
6651 if (s->first_displayed_entry)
6652 next = TAILQ_NEXT(s->first_displayed_entry, entry);
6653 else
6654 next = TAILQ_FIRST(&s->refs);
6656 last = s->last_displayed_entry;
6657 while (next && last && n++ < maxscroll) {
6658 last = TAILQ_NEXT(last, entry);
6659 if (last) {
6660 s->first_displayed_entry = next;
6661 next = TAILQ_NEXT(next, entry);
6666 static const struct got_error *
6667 search_start_ref_view(struct tog_view *view)
6669 struct tog_ref_view_state *s = &view->state.ref;
6671 s->matched_entry = NULL;
6672 return NULL;
6675 static int
6676 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
6678 regmatch_t regmatch;
6680 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
6681 0) == 0;
6684 static const struct got_error *
6685 search_next_ref_view(struct tog_view *view)
6687 struct tog_ref_view_state *s = &view->state.ref;
6688 struct tog_reflist_entry *re = NULL;
6690 if (!view->searching) {
6691 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6692 return NULL;
6695 if (s->matched_entry) {
6696 if (view->searching == TOG_SEARCH_FORWARD) {
6697 if (s->selected_entry)
6698 re = TAILQ_NEXT(s->selected_entry, entry);
6699 else
6700 re = TAILQ_PREV(s->selected_entry,
6701 tog_reflist_head, entry);
6702 } else {
6703 if (s->selected_entry == NULL)
6704 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6705 else
6706 re = TAILQ_PREV(s->selected_entry,
6707 tog_reflist_head, entry);
6709 } else {
6710 if (s->selected_entry)
6711 re = s->selected_entry;
6712 else if (view->searching == TOG_SEARCH_FORWARD)
6713 re = TAILQ_FIRST(&s->refs);
6714 else
6715 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6718 while (1) {
6719 if (re == NULL) {
6720 if (s->matched_entry == NULL) {
6721 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6722 return NULL;
6724 if (view->searching == TOG_SEARCH_FORWARD)
6725 re = TAILQ_FIRST(&s->refs);
6726 else
6727 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6730 if (match_reflist_entry(re, &view->regex)) {
6731 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6732 s->matched_entry = re;
6733 break;
6736 if (view->searching == TOG_SEARCH_FORWARD)
6737 re = TAILQ_NEXT(re, entry);
6738 else
6739 re = TAILQ_PREV(re, tog_reflist_head, entry);
6742 if (s->matched_entry) {
6743 s->first_displayed_entry = s->matched_entry;
6744 s->selected = 0;
6747 return NULL;
6750 static const struct got_error *
6751 show_ref_view(struct tog_view *view)
6753 const struct got_error *err = NULL;
6754 struct tog_ref_view_state *s = &view->state.ref;
6755 struct tog_reflist_entry *re;
6756 char *line = NULL;
6757 wchar_t *wline;
6758 struct tog_color *tc;
6759 int width, n;
6760 int limit = view->nlines;
6762 werase(view->window);
6764 s->ndisplayed = 0;
6766 if (limit == 0)
6767 return NULL;
6769 re = s->first_displayed_entry;
6771 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
6772 s->nrefs) == -1)
6773 return got_error_from_errno("asprintf");
6775 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6776 if (err) {
6777 free(line);
6778 return err;
6780 if (view_needs_focus_indication(view))
6781 wstandout(view->window);
6782 waddwstr(view->window, wline);
6783 if (view_needs_focus_indication(view))
6784 wstandend(view->window);
6785 free(wline);
6786 wline = NULL;
6787 free(line);
6788 line = NULL;
6789 if (width < view->ncols - 1)
6790 waddch(view->window, '\n');
6791 if (--limit <= 0)
6792 return NULL;
6794 n = 0;
6795 while (re && limit > 0) {
6796 char *line = NULL;
6797 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
6799 if (s->show_date) {
6800 struct got_commit_object *ci;
6801 struct got_tag_object *tag;
6802 struct got_object_id *id;
6803 struct tm tm;
6804 time_t t;
6806 err = got_ref_resolve(&id, s->repo, re->ref);
6807 if (err)
6808 return err;
6809 err = got_object_open_as_tag(&tag, s->repo, id);
6810 if (err) {
6811 if (err->code != GOT_ERR_OBJ_TYPE) {
6812 free(id);
6813 return err;
6815 err = got_object_open_as_commit(&ci, s->repo,
6816 id);
6817 if (err) {
6818 free(id);
6819 return err;
6821 t = got_object_commit_get_committer_time(ci);
6822 got_object_commit_close(ci);
6823 } else {
6824 t = got_object_tag_get_tagger_time(tag);
6825 got_object_tag_close(tag);
6827 free(id);
6828 if (gmtime_r(&t, &tm) == NULL)
6829 return got_error_from_errno("gmtime_r");
6830 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
6831 return got_error(GOT_ERR_NO_SPACE);
6833 if (got_ref_is_symbolic(re->ref)) {
6834 if (asprintf(&line, "%s%s -> %s", s->show_date ?
6835 ymd : "", got_ref_get_name(re->ref),
6836 got_ref_get_symref_target(re->ref)) == -1)
6837 return got_error_from_errno("asprintf");
6838 } else if (s->show_ids) {
6839 struct got_object_id *id;
6840 char *id_str;
6841 err = got_ref_resolve(&id, s->repo, re->ref);
6842 if (err)
6843 return err;
6844 err = got_object_id_str(&id_str, id);
6845 if (err) {
6846 free(id);
6847 return err;
6849 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
6850 got_ref_get_name(re->ref), id_str) == -1) {
6851 err = got_error_from_errno("asprintf");
6852 free(id);
6853 free(id_str);
6854 return err;
6856 free(id);
6857 free(id_str);
6858 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
6859 got_ref_get_name(re->ref)) == -1)
6860 return got_error_from_errno("asprintf");
6862 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6863 0, 0);
6864 if (err) {
6865 free(line);
6866 return err;
6868 if (n == s->selected) {
6869 if (view->focussed)
6870 wstandout(view->window);
6871 s->selected_entry = re;
6873 tc = match_color(&s->colors, got_ref_get_name(re->ref));
6874 if (tc)
6875 wattr_on(view->window,
6876 COLOR_PAIR(tc->colorpair), NULL);
6877 waddwstr(view->window, wline);
6878 if (tc)
6879 wattr_off(view->window,
6880 COLOR_PAIR(tc->colorpair), NULL);
6881 if (width < view->ncols - 1)
6882 waddch(view->window, '\n');
6883 if (n == s->selected && view->focussed)
6884 wstandend(view->window);
6885 free(line);
6886 free(wline);
6887 wline = NULL;
6888 n++;
6889 s->ndisplayed++;
6890 s->last_displayed_entry = re;
6892 limit--;
6893 re = TAILQ_NEXT(re, entry);
6896 view_vborder(view);
6897 return err;
6900 static const struct got_error *
6901 browse_ref_tree(struct tog_view **new_view, int begin_x,
6902 struct tog_reflist_entry *re, struct got_repository *repo)
6904 const struct got_error *err = NULL;
6905 struct got_object_id *commit_id = NULL;
6906 struct tog_view *tree_view;
6908 *new_view = NULL;
6910 err = resolve_reflist_entry(&commit_id, re, repo);
6911 if (err) {
6912 if (err->code != GOT_ERR_OBJ_TYPE)
6913 return err;
6914 else
6915 return NULL;
6919 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
6920 if (tree_view == NULL) {
6921 err = got_error_from_errno("view_open");
6922 goto done;
6925 err = open_tree_view(tree_view, commit_id,
6926 got_ref_get_name(re->ref), repo);
6927 if (err)
6928 goto done;
6930 *new_view = tree_view;
6931 done:
6932 free(commit_id);
6933 return err;
6935 static const struct got_error *
6936 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
6938 const struct got_error *err = NULL;
6939 struct tog_ref_view_state *s = &view->state.ref;
6940 struct tog_view *log_view, *tree_view;
6941 struct tog_reflist_entry *re;
6942 int begin_x = 0, n, nscroll = view->nlines - 1;
6944 switch (ch) {
6945 case 'i':
6946 s->show_ids = !s->show_ids;
6947 view->count = 0;
6948 break;
6949 case 'm':
6950 s->show_date = !s->show_date;
6951 view->count = 0;
6952 break;
6953 case 'o':
6954 s->sort_by_date = !s->sort_by_date;
6955 view->count = 0;
6956 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
6957 got_ref_cmp_by_commit_timestamp_descending :
6958 tog_ref_cmp_by_name, s->repo);
6959 if (err)
6960 break;
6961 got_reflist_object_id_map_free(tog_refs_idmap);
6962 err = got_reflist_object_id_map_create(&tog_refs_idmap,
6963 &tog_refs, s->repo);
6964 if (err)
6965 break;
6966 ref_view_free_refs(s);
6967 err = ref_view_load_refs(s);
6968 break;
6969 case KEY_ENTER:
6970 case '\r':
6971 view->count = 0;
6972 if (!s->selected_entry)
6973 break;
6974 if (view_is_parent_view(view))
6975 begin_x = view_split_begin_x(view->begin_x);
6976 err = log_ref_entry(&log_view, begin_x, s->selected_entry,
6977 s->repo);
6978 view->focussed = 0;
6979 log_view->focussed = 1;
6980 if (view_is_parent_view(view)) {
6981 err = view_close_child(view);
6982 if (err)
6983 return err;
6984 err = view_set_child(view, log_view);
6985 if (err)
6986 return err;
6987 view->focus_child = 1;
6988 } else
6989 *new_view = log_view;
6990 break;
6991 case 't':
6992 view->count = 0;
6993 if (!s->selected_entry)
6994 break;
6995 if (view_is_parent_view(view))
6996 begin_x = view_split_begin_x(view->begin_x);
6997 err = browse_ref_tree(&tree_view, begin_x, s->selected_entry,
6998 s->repo);
6999 if (err || tree_view == NULL)
7000 break;
7001 view->focussed = 0;
7002 tree_view->focussed = 1;
7003 if (view_is_parent_view(view)) {
7004 err = view_close_child(view);
7005 if (err)
7006 return err;
7007 err = view_set_child(view, tree_view);
7008 if (err)
7009 return err;
7010 view->focus_child = 1;
7011 } else
7012 *new_view = tree_view;
7013 break;
7014 case 'g':
7015 case KEY_HOME:
7016 s->selected = 0;
7017 view->count = 0;
7018 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7019 break;
7020 case 'G':
7021 case KEY_END:
7022 s->selected = 0;
7023 view->count = 0;
7024 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7025 for (n = 0; n < view->nlines - 1; n++) {
7026 if (re == NULL)
7027 break;
7028 s->first_displayed_entry = re;
7029 re = TAILQ_PREV(re, tog_reflist_head, entry);
7031 if (n > 0)
7032 s->selected = n - 1;
7033 break;
7034 case 'k':
7035 case KEY_UP:
7036 case CTRL('p'):
7037 if (s->selected > 0) {
7038 s->selected--;
7039 break;
7041 ref_scroll_up(s, 1);
7042 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7043 view->count = 0;
7044 break;
7045 case CTRL('u'):
7046 case 'u':
7047 nscroll /= 2;
7048 /* FALL THROUGH */
7049 case KEY_PPAGE:
7050 case CTRL('b'):
7051 case 'b':
7052 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7053 s->selected -= MIN(nscroll, s->selected);
7054 ref_scroll_up(s, MAX(0, nscroll));
7055 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7056 view->count = 0;
7057 break;
7058 case 'j':
7059 case KEY_DOWN:
7060 case CTRL('n'):
7061 if (s->selected < s->ndisplayed - 1) {
7062 s->selected++;
7063 break;
7065 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7066 /* can't scroll any further */
7067 view->count = 0;
7068 break;
7070 ref_scroll_down(s, 1);
7071 break;
7072 case CTRL('d'):
7073 case 'd':
7074 nscroll /= 2;
7075 /* FALL THROUGH */
7076 case KEY_NPAGE:
7077 case CTRL('f'):
7078 case 'f':
7079 case ' ':
7080 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7081 /* can't scroll any further; move cursor down */
7082 if (s->selected < s->ndisplayed - 1)
7083 s->selected += MIN(nscroll,
7084 s->ndisplayed - s->selected - 1);
7085 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7086 s->selected += s->ndisplayed - s->selected - 1;
7087 view->count = 0;
7088 break;
7090 ref_scroll_down(s, nscroll);
7091 break;
7092 case CTRL('l'):
7093 view->count = 0;
7094 tog_free_refs();
7095 err = tog_load_refs(s->repo, s->sort_by_date);
7096 if (err)
7097 break;
7098 ref_view_free_refs(s);
7099 err = ref_view_load_refs(s);
7100 break;
7101 case KEY_RESIZE:
7102 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7103 s->selected = view->nlines - 2;
7104 break;
7105 default:
7106 view->count = 0;
7107 break;
7110 return err;
7113 __dead static void
7114 usage_ref(void)
7116 endwin();
7117 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7118 getprogname());
7119 exit(1);
7122 static const struct got_error *
7123 cmd_ref(int argc, char *argv[])
7125 const struct got_error *error;
7126 struct got_repository *repo = NULL;
7127 struct got_worktree *worktree = NULL;
7128 char *cwd = NULL, *repo_path = NULL;
7129 int ch;
7130 struct tog_view *view;
7131 int *pack_fds = NULL;
7133 while ((ch = getopt(argc, argv, "r:")) != -1) {
7134 switch (ch) {
7135 case 'r':
7136 repo_path = realpath(optarg, NULL);
7137 if (repo_path == NULL)
7138 return got_error_from_errno2("realpath",
7139 optarg);
7140 break;
7141 default:
7142 usage_ref();
7143 /* NOTREACHED */
7147 argc -= optind;
7148 argv += optind;
7150 if (argc > 1)
7151 usage_ref();
7153 error = got_repo_pack_fds_open(&pack_fds);
7154 if (error != NULL)
7155 goto done;
7157 if (repo_path == NULL) {
7158 cwd = getcwd(NULL, 0);
7159 if (cwd == NULL)
7160 return got_error_from_errno("getcwd");
7161 error = got_worktree_open(&worktree, cwd);
7162 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7163 goto done;
7164 if (worktree)
7165 repo_path =
7166 strdup(got_worktree_get_repo_path(worktree));
7167 else
7168 repo_path = strdup(cwd);
7169 if (repo_path == NULL) {
7170 error = got_error_from_errno("strdup");
7171 goto done;
7175 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7176 if (error != NULL)
7177 goto done;
7179 init_curses();
7181 error = apply_unveil(got_repo_get_path(repo), NULL);
7182 if (error)
7183 goto done;
7185 error = tog_load_refs(repo, 0);
7186 if (error)
7187 goto done;
7189 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7190 if (view == NULL) {
7191 error = got_error_from_errno("view_open");
7192 goto done;
7195 error = open_ref_view(view, repo);
7196 if (error)
7197 goto done;
7199 if (worktree) {
7200 /* Release work tree lock. */
7201 got_worktree_close(worktree);
7202 worktree = NULL;
7204 error = view_loop(view);
7205 done:
7206 free(repo_path);
7207 free(cwd);
7208 if (repo) {
7209 const struct got_error *close_err = got_repo_close(repo);
7210 if (close_err)
7211 error = close_err;
7213 if (pack_fds) {
7214 const struct got_error *pack_err =
7215 got_repo_pack_fds_close(pack_fds);
7216 if (error == NULL)
7217 error = pack_err;
7219 tog_free_refs();
7220 return error;
7223 static void
7224 list_commands(FILE *fp)
7226 size_t i;
7228 fprintf(fp, "commands:");
7229 for (i = 0; i < nitems(tog_commands); i++) {
7230 const struct tog_cmd *cmd = &tog_commands[i];
7231 fprintf(fp, " %s", cmd->name);
7233 fputc('\n', fp);
7236 __dead static void
7237 usage(int hflag, int status)
7239 FILE *fp = (status == 0) ? stdout : stderr;
7241 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
7242 getprogname());
7243 if (hflag) {
7244 fprintf(fp, "lazy usage: %s path\n", getprogname());
7245 list_commands(fp);
7247 exit(status);
7250 static char **
7251 make_argv(int argc, ...)
7253 va_list ap;
7254 char **argv;
7255 int i;
7257 va_start(ap, argc);
7259 argv = calloc(argc, sizeof(char *));
7260 if (argv == NULL)
7261 err(1, "calloc");
7262 for (i = 0; i < argc; i++) {
7263 argv[i] = strdup(va_arg(ap, char *));
7264 if (argv[i] == NULL)
7265 err(1, "strdup");
7268 va_end(ap);
7269 return argv;
7273 * Try to convert 'tog path' into a 'tog log path' command.
7274 * The user could simply have mistyped the command rather than knowingly
7275 * provided a path. So check whether argv[0] can in fact be resolved
7276 * to a path in the HEAD commit and print a special error if not.
7277 * This hack is for mpi@ <3
7279 static const struct got_error *
7280 tog_log_with_path(int argc, char *argv[])
7282 const struct got_error *error = NULL, *close_err;
7283 const struct tog_cmd *cmd = NULL;
7284 struct got_repository *repo = NULL;
7285 struct got_worktree *worktree = NULL;
7286 struct got_object_id *commit_id = NULL, *id = NULL;
7287 struct got_commit_object *commit = NULL;
7288 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7289 char *commit_id_str = NULL, **cmd_argv = NULL;
7290 int *pack_fds = NULL;
7292 cwd = getcwd(NULL, 0);
7293 if (cwd == NULL)
7294 return got_error_from_errno("getcwd");
7296 error = got_repo_pack_fds_open(&pack_fds);
7297 if (error != NULL)
7298 goto done;
7300 error = got_worktree_open(&worktree, cwd);
7301 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7302 goto done;
7304 if (worktree)
7305 repo_path = strdup(got_worktree_get_repo_path(worktree));
7306 else
7307 repo_path = strdup(cwd);
7308 if (repo_path == NULL) {
7309 error = got_error_from_errno("strdup");
7310 goto done;
7313 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7314 if (error != NULL)
7315 goto done;
7317 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7318 repo, worktree);
7319 if (error)
7320 goto done;
7322 error = tog_load_refs(repo, 0);
7323 if (error)
7324 goto done;
7325 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
7326 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
7327 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7328 if (error)
7329 goto done;
7331 if (worktree) {
7332 got_worktree_close(worktree);
7333 worktree = NULL;
7336 error = got_object_open_as_commit(&commit, repo, commit_id);
7337 if (error)
7338 goto done;
7340 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
7341 if (error) {
7342 if (error->code != GOT_ERR_NO_TREE_ENTRY)
7343 goto done;
7344 fprintf(stderr, "%s: '%s' is no known command or path\n",
7345 getprogname(), argv[0]);
7346 usage(1, 1);
7347 /* not reached */
7350 close_err = got_repo_close(repo);
7351 if (error == NULL)
7352 error = close_err;
7353 repo = NULL;
7355 error = got_object_id_str(&commit_id_str, commit_id);
7356 if (error)
7357 goto done;
7359 cmd = &tog_commands[0]; /* log */
7360 argc = 4;
7361 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
7362 error = cmd->cmd_main(argc, cmd_argv);
7363 done:
7364 if (repo) {
7365 close_err = got_repo_close(repo);
7366 if (error == NULL)
7367 error = close_err;
7369 if (commit)
7370 got_object_commit_close(commit);
7371 if (worktree)
7372 got_worktree_close(worktree);
7373 if (pack_fds) {
7374 const struct got_error *pack_err =
7375 got_repo_pack_fds_close(pack_fds);
7376 if (error == NULL)
7377 error = pack_err;
7379 free(id);
7380 free(commit_id_str);
7381 free(commit_id);
7382 free(cwd);
7383 free(repo_path);
7384 free(in_repo_path);
7385 if (cmd_argv) {
7386 int i;
7387 for (i = 0; i < argc; i++)
7388 free(cmd_argv[i]);
7389 free(cmd_argv);
7391 tog_free_refs();
7392 return error;
7395 int
7396 main(int argc, char *argv[])
7398 const struct got_error *error = NULL;
7399 const struct tog_cmd *cmd = NULL;
7400 int ch, hflag = 0, Vflag = 0;
7401 char **cmd_argv = NULL;
7402 static const struct option longopts[] = {
7403 { "version", no_argument, NULL, 'V' },
7404 { NULL, 0, NULL, 0}
7407 setlocale(LC_CTYPE, "");
7409 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
7410 switch (ch) {
7411 case 'h':
7412 hflag = 1;
7413 break;
7414 case 'V':
7415 Vflag = 1;
7416 break;
7417 default:
7418 usage(hflag, 1);
7419 /* NOTREACHED */
7423 argc -= optind;
7424 argv += optind;
7425 optind = 1;
7426 optreset = 1;
7428 if (Vflag) {
7429 got_version_print_str();
7430 return 0;
7433 #ifndef PROFILE
7434 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
7435 NULL) == -1)
7436 err(1, "pledge");
7437 #endif
7439 if (argc == 0) {
7440 if (hflag)
7441 usage(hflag, 0);
7442 /* Build an argument vector which runs a default command. */
7443 cmd = &tog_commands[0];
7444 argc = 1;
7445 cmd_argv = make_argv(argc, cmd->name);
7446 } else {
7447 size_t i;
7449 /* Did the user specify a command? */
7450 for (i = 0; i < nitems(tog_commands); i++) {
7451 if (strncmp(tog_commands[i].name, argv[0],
7452 strlen(argv[0])) == 0) {
7453 cmd = &tog_commands[i];
7454 break;
7459 if (cmd == NULL) {
7460 if (argc != 1)
7461 usage(0, 1);
7462 /* No command specified; try log with a path */
7463 error = tog_log_with_path(argc, argv);
7464 } else {
7465 if (hflag)
7466 cmd->cmd_usage();
7467 else
7468 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
7471 endwin();
7472 putchar('\n');
7473 if (cmd_argv) {
7474 int i;
7475 for (i = 0; i < argc; i++)
7476 free(cmd_argv[i]);
7477 free(cmd_argv);
7480 if (error && error->code != GOT_ERR_CANCELLED)
7481 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7482 return 0;