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) {
778 if (view->child->focussed)
779 view->child->begin_x = view_split_begin_x(view->begin_x);
780 if (view->child->begin_x == 0) {
781 ncols = COLS;
783 view_fullscreen(view->child);
784 if (view->child->focussed)
785 show_panel(view->child->panel);
786 else
787 show_panel(view->panel);
788 } else {
789 ncols = view->child->begin_x;
791 view_splitscreen(view->child);
792 show_panel(view->child->panel);
794 } else if (view->parent == NULL)
795 ncols = COLS;
797 if (wresize(view->window, nlines, ncols) == ERR)
798 return got_error_from_errno("wresize");
799 if (replace_panel(view->panel, view->window) == ERR)
800 return got_error_from_errno("replace_panel");
801 wclear(view->window);
803 view->nlines = nlines;
804 view->ncols = ncols;
805 view->lines = LINES;
806 view->cols = COLS;
808 return NULL;
811 static const struct got_error *
812 view_close_child(struct tog_view *view)
814 const struct got_error *err = NULL;
816 if (view->child == NULL)
817 return NULL;
819 err = view_close(view->child);
820 view->child = NULL;
821 return err;
824 static const struct got_error *
825 view_set_child(struct tog_view *view, struct tog_view *child)
827 view->child = child;
828 child->parent = view;
830 return view_resize(view);
833 static void
834 tog_resizeterm(void)
836 int cols, lines;
837 struct winsize size;
839 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
840 cols = 80; /* Default */
841 lines = 24;
842 } else {
843 cols = size.ws_col;
844 lines = size.ws_row;
846 resize_term(lines, cols);
849 static const struct got_error *
850 view_search_start(struct tog_view *view)
852 const struct got_error *err = NULL;
853 char pattern[1024];
854 int ret;
856 if (view->search_started) {
857 regfree(&view->regex);
858 view->searching = 0;
859 memset(&view->regmatch, 0, sizeof(view->regmatch));
861 view->search_started = 0;
863 if (view->nlines < 1)
864 return NULL;
866 mvwaddstr(view->window, view->begin_y + view->nlines - 1, 0, "/");
867 wclrtoeol(view->window);
869 nocbreak();
870 echo();
871 ret = wgetnstr(view->window, pattern, sizeof(pattern));
872 cbreak();
873 noecho();
874 if (ret == ERR)
875 return NULL;
877 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
878 err = view->search_start(view);
879 if (err) {
880 regfree(&view->regex);
881 return err;
883 view->search_started = 1;
884 view->searching = TOG_SEARCH_FORWARD;
885 view->search_next_done = 0;
886 view->search_next(view);
889 return NULL;
892 /*
893 * Compute view->count from numeric user input. User has five-tenths of a
894 * second to follow each numeric keypress with another number to form count.
895 * Return first non-numeric input or ERR and assign total to view->count.
896 * XXX Should we add support for user-defined timeout?
897 */
898 static int
899 get_compound_key(struct tog_view *view, int c)
901 int x, n = 0;
903 view->count = 0;
904 halfdelay(5); /* block for half a second */
905 wattron(view->window, A_BOLD);
906 wmove(view->window, view->nlines - 1, 0);
907 wclrtoeol(view->window);
908 waddch(view->window, ':');
910 do {
911 x = getcurx(view->window);
912 if (x != ERR && x < view->ncols)
913 waddch(view->window, c);
914 /*
915 * Don't overflow. Max valid request should be the greatest
916 * between the longest and total lines; cap at 10 million.
917 */
918 if (n >= 9999999)
919 n = 9999999;
920 else
921 n = n * 10 + (c - '0');
922 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
924 /* Massage excessive or inapplicable values at the input handler. */
925 view->count = n;
927 wattroff(view->window, A_BOLD);
928 cbreak(); /* return to blocking */
929 return c;
932 static const struct got_error *
933 view_input(struct tog_view **new, int *done, struct tog_view *view,
934 struct tog_view_list_head *views)
936 const struct got_error *err = NULL;
937 struct tog_view *v;
938 int ch, errcode;
940 *new = NULL;
942 /* Clear "no matches" indicator. */
943 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
944 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
945 view->search_next_done = TOG_SEARCH_HAVE_MORE;
946 view->count = 0;
949 if (view->searching && !view->search_next_done) {
950 errcode = pthread_mutex_unlock(&tog_mutex);
951 if (errcode)
952 return got_error_set_errno(errcode,
953 "pthread_mutex_unlock");
954 sched_yield();
955 errcode = pthread_mutex_lock(&tog_mutex);
956 if (errcode)
957 return got_error_set_errno(errcode,
958 "pthread_mutex_lock");
959 view->search_next(view);
960 return NULL;
963 nodelay(stdscr, FALSE);
964 /* Allow threads to make progress while we are waiting for input. */
965 errcode = pthread_mutex_unlock(&tog_mutex);
966 if (errcode)
967 return got_error_set_errno(errcode, "pthread_mutex_unlock");
968 /* If we have an unfinished count, don't get a new key map. */
969 ch = view->ch;
970 if ((view->count && --view->count == 0) || !view->count) {
971 ch = wgetch(view->window);
972 if (ch >= '1' && ch <= '9')
973 view->ch = ch = get_compound_key(view, ch);
975 errcode = pthread_mutex_lock(&tog_mutex);
976 if (errcode)
977 return got_error_set_errno(errcode, "pthread_mutex_lock");
978 nodelay(stdscr, TRUE);
980 if (tog_sigwinch_received || tog_sigcont_received) {
981 tog_resizeterm();
982 tog_sigwinch_received = 0;
983 tog_sigcont_received = 0;
984 TAILQ_FOREACH(v, views, entry) {
985 err = view_resize(v);
986 if (err)
987 return err;
988 err = v->input(new, v, KEY_RESIZE);
989 if (err)
990 return err;
991 if (v->child) {
992 err = view_resize(v->child);
993 if (err)
994 return err;
995 err = v->child->input(new, v->child,
996 KEY_RESIZE);
997 if (err)
998 return err;
1003 switch (ch) {
1004 case '\t':
1005 view->count = 0;
1006 if (view->child) {
1007 view->focussed = 0;
1008 view->child->focussed = 1;
1009 view->focus_child = 1;
1010 } else if (view->parent) {
1011 view->focussed = 0;
1012 view->parent->focussed = 1;
1013 view->parent->focus_child = 0;
1014 if (!view_is_splitscreen(view))
1015 err = view_fullscreen(view->parent);
1017 break;
1018 case 'q':
1019 err = view->input(new, view, ch);
1020 view->dying = 1;
1021 break;
1022 case 'Q':
1023 *done = 1;
1024 break;
1025 case 'F':
1026 view->count = 0;
1027 if (view_is_parent_view(view)) {
1028 if (view->child == NULL)
1029 break;
1030 if (view_is_splitscreen(view->child)) {
1031 view->focussed = 0;
1032 view->child->focussed = 1;
1033 err = view_fullscreen(view->child);
1034 } else
1035 err = view_splitscreen(view->child);
1036 if (err)
1037 break;
1038 err = view->child->input(new, view->child,
1039 KEY_RESIZE);
1040 } else {
1041 if (view_is_splitscreen(view)) {
1042 view->parent->focussed = 0;
1043 view->focussed = 1;
1044 err = view_fullscreen(view);
1045 } else {
1046 err = view_splitscreen(view);
1047 if (!err)
1048 err = view_resize(view->parent);
1050 if (err)
1051 break;
1052 err = view->input(new, view, KEY_RESIZE);
1054 break;
1055 case KEY_RESIZE:
1056 break;
1057 case '/':
1058 view->count = 0;
1059 if (view->search_start)
1060 view_search_start(view);
1061 else
1062 err = view->input(new, view, ch);
1063 break;
1064 case 'N':
1065 case 'n':
1066 if (view->search_started && view->search_next) {
1067 view->searching = (ch == 'n' ?
1068 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1069 view->search_next_done = 0;
1070 view->search_next(view);
1071 } else
1072 err = view->input(new, view, ch);
1073 break;
1074 default:
1075 err = view->input(new, view, ch);
1076 break;
1079 return err;
1082 static void
1083 view_vborder(struct tog_view *view)
1085 PANEL *panel;
1086 const struct tog_view *view_above;
1088 if (view->parent)
1089 return view_vborder(view->parent);
1091 panel = panel_above(view->panel);
1092 if (panel == NULL)
1093 return;
1095 view_above = panel_userptr(panel);
1096 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
1097 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
1100 static int
1101 view_needs_focus_indication(struct tog_view *view)
1103 if (view_is_parent_view(view)) {
1104 if (view->child == NULL || view->child->focussed)
1105 return 0;
1106 if (!view_is_splitscreen(view->child))
1107 return 0;
1108 } else if (!view_is_splitscreen(view))
1109 return 0;
1111 return view->focussed;
1114 static const struct got_error *
1115 view_loop(struct tog_view *view)
1117 const struct got_error *err = NULL;
1118 struct tog_view_list_head views;
1119 struct tog_view *new_view;
1120 int fast_refresh = 10;
1121 int done = 0, errcode;
1123 errcode = pthread_mutex_lock(&tog_mutex);
1124 if (errcode)
1125 return got_error_set_errno(errcode, "pthread_mutex_lock");
1127 TAILQ_INIT(&views);
1128 TAILQ_INSERT_HEAD(&views, view, entry);
1130 view->focussed = 1;
1131 err = view->show(view);
1132 if (err)
1133 return err;
1134 update_panels();
1135 doupdate();
1136 while (!TAILQ_EMPTY(&views) && !done && !tog_fatal_signal_received()) {
1137 /* Refresh fast during initialization, then become slower. */
1138 if (fast_refresh && fast_refresh-- == 0)
1139 halfdelay(10); /* switch to once per second */
1141 err = view_input(&new_view, &done, view, &views);
1142 if (err)
1143 break;
1144 if (view->dying) {
1145 struct tog_view *v, *prev = NULL;
1147 if (view_is_parent_view(view))
1148 prev = TAILQ_PREV(view, tog_view_list_head,
1149 entry);
1150 else if (view->parent)
1151 prev = view->parent;
1153 if (view->parent) {
1154 view->parent->child = NULL;
1155 view->parent->focus_child = 0;
1157 err = view_resize(view->parent);
1158 if (err)
1159 break;
1160 } else
1161 TAILQ_REMOVE(&views, view, entry);
1163 err = view_close(view);
1164 if (err)
1165 goto done;
1167 view = NULL;
1168 TAILQ_FOREACH(v, &views, entry) {
1169 if (v->focussed)
1170 break;
1172 if (view == NULL && new_view == NULL) {
1173 /* No view has focus. Try to pick one. */
1174 if (prev)
1175 view = prev;
1176 else if (!TAILQ_EMPTY(&views)) {
1177 view = TAILQ_LAST(&views,
1178 tog_view_list_head);
1180 if (view) {
1181 if (view->focus_child) {
1182 view->child->focussed = 1;
1183 view = view->child;
1184 } else
1185 view->focussed = 1;
1189 if (new_view) {
1190 struct tog_view *v, *t;
1191 /* Only allow one parent view per type. */
1192 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1193 if (v->type != new_view->type)
1194 continue;
1195 TAILQ_REMOVE(&views, v, entry);
1196 err = view_close(v);
1197 if (err)
1198 goto done;
1199 break;
1201 TAILQ_INSERT_TAIL(&views, new_view, entry);
1202 view = new_view;
1204 if (view) {
1205 if (view_is_parent_view(view)) {
1206 if (view->child && view->child->focussed)
1207 view = view->child;
1208 } else {
1209 if (view->parent && view->parent->focussed)
1210 view = view->parent;
1212 show_panel(view->panel);
1213 if (view->child && view_is_splitscreen(view->child))
1214 show_panel(view->child->panel);
1215 if (view->parent && view_is_splitscreen(view)) {
1216 err = view->parent->show(view->parent);
1217 if (err)
1218 goto done;
1220 err = view->show(view);
1221 if (err)
1222 goto done;
1223 if (view->child) {
1224 err = view->child->show(view->child);
1225 if (err)
1226 goto done;
1228 update_panels();
1229 doupdate();
1232 done:
1233 while (!TAILQ_EMPTY(&views)) {
1234 view = TAILQ_FIRST(&views);
1235 TAILQ_REMOVE(&views, view, entry);
1236 view_close(view);
1239 errcode = pthread_mutex_unlock(&tog_mutex);
1240 if (errcode && err == NULL)
1241 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1243 return err;
1246 __dead static void
1247 usage_log(void)
1249 endwin();
1250 fprintf(stderr,
1251 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1252 getprogname());
1253 exit(1);
1256 /* Create newly allocated wide-character string equivalent to a byte string. */
1257 static const struct got_error *
1258 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1260 char *vis = NULL;
1261 const struct got_error *err = NULL;
1263 *ws = NULL;
1264 *wlen = mbstowcs(NULL, s, 0);
1265 if (*wlen == (size_t)-1) {
1266 int vislen;
1267 if (errno != EILSEQ)
1268 return got_error_from_errno("mbstowcs");
1270 /* byte string invalid in current encoding; try to "fix" it */
1271 err = got_mbsavis(&vis, &vislen, s);
1272 if (err)
1273 return err;
1274 *wlen = mbstowcs(NULL, vis, 0);
1275 if (*wlen == (size_t)-1) {
1276 err = got_error_from_errno("mbstowcs"); /* give up */
1277 goto done;
1281 *ws = calloc(*wlen + 1, sizeof(**ws));
1282 if (*ws == NULL) {
1283 err = got_error_from_errno("calloc");
1284 goto done;
1287 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1288 err = got_error_from_errno("mbstowcs");
1289 done:
1290 free(vis);
1291 if (err) {
1292 free(*ws);
1293 *ws = NULL;
1294 *wlen = 0;
1296 return err;
1299 static const struct got_error *
1300 expand_tab(char **ptr, const char *src)
1302 char *dst;
1303 size_t len, n, idx = 0, sz = 0;
1305 *ptr = NULL;
1306 n = len = strlen(src);
1307 dst = malloc(n + 1);
1308 if (dst == NULL)
1309 return got_error_from_errno("malloc");
1311 while (idx < len && src[idx]) {
1312 const char c = src[idx];
1314 if (c == '\t') {
1315 size_t nb = TABSIZE - sz % TABSIZE;
1316 char *p;
1318 p = realloc(dst, n + nb);
1319 if (p == NULL) {
1320 free(dst);
1321 return got_error_from_errno("realloc");
1324 dst = p;
1325 n += nb;
1326 memset(dst + sz, ' ', nb);
1327 sz += nb;
1328 } else
1329 dst[sz++] = src[idx];
1330 ++idx;
1333 dst[sz] = '\0';
1334 *ptr = dst;
1335 return NULL;
1339 * Advance at most n columns from wline starting at offset off.
1340 * Return the index to the first character after the span operation.
1341 * Return the combined column width of all spanned wide character in
1342 * *rcol.
1344 static int
1345 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1347 int width, i, cols = 0;
1349 if (n == 0) {
1350 *rcol = cols;
1351 return off;
1354 for (i = off; wline[i] != L'\0'; ++i) {
1355 if (wline[i] == L'\t')
1356 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1357 else
1358 width = wcwidth(wline[i]);
1360 if (width == -1) {
1361 width = 1;
1362 wline[i] = L'.';
1365 if (cols + width > n)
1366 break;
1367 cols += width;
1370 *rcol = cols;
1371 return i;
1375 * Format a line for display, ensuring that it won't overflow a width limit.
1376 * With scrolling, the width returned refers to the scrolled version of the
1377 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1379 static const struct got_error *
1380 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1381 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1383 const struct got_error *err = NULL;
1384 int cols;
1385 wchar_t *wline = NULL;
1386 char *exstr = NULL;
1387 size_t wlen;
1388 int i, scrollx;
1390 *wlinep = NULL;
1391 *widthp = 0;
1393 if (expand) {
1394 err = expand_tab(&exstr, line);
1395 if (err)
1396 return err;
1399 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1400 free(exstr);
1401 if (err)
1402 return err;
1404 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1406 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1407 wline[wlen - 1] = L'\0';
1408 wlen--;
1410 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1411 wline[wlen - 1] = L'\0';
1412 wlen--;
1415 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1416 wline[i] = L'\0';
1418 if (widthp)
1419 *widthp = cols;
1420 if (scrollxp)
1421 *scrollxp = scrollx;
1422 if (err)
1423 free(wline);
1424 else
1425 *wlinep = wline;
1426 return err;
1429 static const struct got_error*
1430 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1431 struct got_object_id *id, struct got_repository *repo)
1433 static const struct got_error *err = NULL;
1434 struct got_reflist_entry *re;
1435 char *s;
1436 const char *name;
1438 *refs_str = NULL;
1440 TAILQ_FOREACH(re, refs, entry) {
1441 struct got_tag_object *tag = NULL;
1442 struct got_object_id *ref_id;
1443 int cmp;
1445 name = got_ref_get_name(re->ref);
1446 if (strcmp(name, GOT_REF_HEAD) == 0)
1447 continue;
1448 if (strncmp(name, "refs/", 5) == 0)
1449 name += 5;
1450 if (strncmp(name, "got/", 4) == 0 &&
1451 strncmp(name, "got/backup/", 11) != 0)
1452 continue;
1453 if (strncmp(name, "heads/", 6) == 0)
1454 name += 6;
1455 if (strncmp(name, "remotes/", 8) == 0) {
1456 name += 8;
1457 s = strstr(name, "/" GOT_REF_HEAD);
1458 if (s != NULL && s[strlen(s)] == '\0')
1459 continue;
1461 err = got_ref_resolve(&ref_id, repo, re->ref);
1462 if (err)
1463 break;
1464 if (strncmp(name, "tags/", 5) == 0) {
1465 err = got_object_open_as_tag(&tag, repo, ref_id);
1466 if (err) {
1467 if (err->code != GOT_ERR_OBJ_TYPE) {
1468 free(ref_id);
1469 break;
1471 /* Ref points at something other than a tag. */
1472 err = NULL;
1473 tag = NULL;
1476 cmp = got_object_id_cmp(tag ?
1477 got_object_tag_get_object_id(tag) : ref_id, id);
1478 free(ref_id);
1479 if (tag)
1480 got_object_tag_close(tag);
1481 if (cmp != 0)
1482 continue;
1483 s = *refs_str;
1484 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1485 s ? ", " : "", name) == -1) {
1486 err = got_error_from_errno("asprintf");
1487 free(s);
1488 *refs_str = NULL;
1489 break;
1491 free(s);
1494 return err;
1497 static const struct got_error *
1498 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1499 int col_tab_align)
1501 char *smallerthan;
1503 smallerthan = strchr(author, '<');
1504 if (smallerthan && smallerthan[1] != '\0')
1505 author = smallerthan + 1;
1506 author[strcspn(author, "@>")] = '\0';
1507 return format_line(wauthor, author_width, NULL, author, 0, limit,
1508 col_tab_align, 0);
1511 static const struct got_error *
1512 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1513 struct got_object_id *id, const size_t date_display_cols,
1514 int author_display_cols)
1516 struct tog_log_view_state *s = &view->state.log;
1517 const struct got_error *err = NULL;
1518 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1519 char *logmsg0 = NULL, *logmsg = NULL;
1520 char *author = NULL;
1521 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1522 int author_width, logmsg_width;
1523 char *newline, *line = NULL;
1524 int col, limit, scrollx;
1525 const int avail = view->ncols;
1526 struct tm tm;
1527 time_t committer_time;
1528 struct tog_color *tc;
1530 committer_time = got_object_commit_get_committer_time(commit);
1531 if (gmtime_r(&committer_time, &tm) == NULL)
1532 return got_error_from_errno("gmtime_r");
1533 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1534 return got_error(GOT_ERR_NO_SPACE);
1536 if (avail <= date_display_cols)
1537 limit = MIN(sizeof(datebuf) - 1, avail);
1538 else
1539 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1540 tc = get_color(&s->colors, TOG_COLOR_DATE);
1541 if (tc)
1542 wattr_on(view->window,
1543 COLOR_PAIR(tc->colorpair), NULL);
1544 waddnstr(view->window, datebuf, limit);
1545 if (tc)
1546 wattr_off(view->window,
1547 COLOR_PAIR(tc->colorpair), NULL);
1548 col = limit;
1549 if (col > avail)
1550 goto done;
1552 if (avail >= 120) {
1553 char *id_str;
1554 err = got_object_id_str(&id_str, id);
1555 if (err)
1556 goto done;
1557 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1558 if (tc)
1559 wattr_on(view->window,
1560 COLOR_PAIR(tc->colorpair), NULL);
1561 wprintw(view->window, "%.8s ", id_str);
1562 if (tc)
1563 wattr_off(view->window,
1564 COLOR_PAIR(tc->colorpair), NULL);
1565 free(id_str);
1566 col += 9;
1567 if (col > avail)
1568 goto done;
1571 author = strdup(got_object_commit_get_author(commit));
1572 if (author == NULL) {
1573 err = got_error_from_errno("strdup");
1574 goto done;
1576 err = format_author(&wauthor, &author_width, author, avail - col, col);
1577 if (err)
1578 goto done;
1579 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1580 if (tc)
1581 wattr_on(view->window,
1582 COLOR_PAIR(tc->colorpair), NULL);
1583 waddwstr(view->window, wauthor);
1584 if (tc)
1585 wattr_off(view->window,
1586 COLOR_PAIR(tc->colorpair), NULL);
1587 col += author_width;
1588 while (col < avail && author_width < author_display_cols + 2) {
1589 waddch(view->window, ' ');
1590 col++;
1591 author_width++;
1593 if (col > avail)
1594 goto done;
1596 err = got_object_commit_get_logmsg(&logmsg0, commit);
1597 if (err)
1598 goto done;
1599 logmsg = logmsg0;
1600 while (*logmsg == '\n')
1601 logmsg++;
1602 newline = strchr(logmsg, '\n');
1603 if (newline)
1604 *newline = '\0';
1605 limit = avail - col;
1606 if (view->child && view_is_splitscreen(view->child) && limit > 0)
1607 limit--; /* for the border */
1608 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
1609 limit, col, 1);
1610 if (err)
1611 goto done;
1612 waddwstr(view->window, &wlogmsg[scrollx]);
1613 col += MAX(logmsg_width, 0);
1614 while (col < avail) {
1615 waddch(view->window, ' ');
1616 col++;
1618 done:
1619 free(logmsg0);
1620 free(wlogmsg);
1621 free(author);
1622 free(wauthor);
1623 free(line);
1624 return err;
1627 static struct commit_queue_entry *
1628 alloc_commit_queue_entry(struct got_commit_object *commit,
1629 struct got_object_id *id)
1631 struct commit_queue_entry *entry;
1633 entry = calloc(1, sizeof(*entry));
1634 if (entry == NULL)
1635 return NULL;
1637 entry->id = id;
1638 entry->commit = commit;
1639 return entry;
1642 static void
1643 pop_commit(struct commit_queue *commits)
1645 struct commit_queue_entry *entry;
1647 entry = TAILQ_FIRST(&commits->head);
1648 TAILQ_REMOVE(&commits->head, entry, entry);
1649 got_object_commit_close(entry->commit);
1650 commits->ncommits--;
1651 /* Don't free entry->id! It is owned by the commit graph. */
1652 free(entry);
1655 static void
1656 free_commits(struct commit_queue *commits)
1658 while (!TAILQ_EMPTY(&commits->head))
1659 pop_commit(commits);
1662 static const struct got_error *
1663 match_commit(int *have_match, struct got_object_id *id,
1664 struct got_commit_object *commit, regex_t *regex)
1666 const struct got_error *err = NULL;
1667 regmatch_t regmatch;
1668 char *id_str = NULL, *logmsg = NULL;
1670 *have_match = 0;
1672 err = got_object_id_str(&id_str, id);
1673 if (err)
1674 return err;
1676 err = got_object_commit_get_logmsg(&logmsg, commit);
1677 if (err)
1678 goto done;
1680 if (regexec(regex, got_object_commit_get_author(commit), 1,
1681 &regmatch, 0) == 0 ||
1682 regexec(regex, got_object_commit_get_committer(commit), 1,
1683 &regmatch, 0) == 0 ||
1684 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
1685 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
1686 *have_match = 1;
1687 done:
1688 free(id_str);
1689 free(logmsg);
1690 return err;
1693 static const struct got_error *
1694 queue_commits(struct tog_log_thread_args *a)
1696 const struct got_error *err = NULL;
1699 * We keep all commits open throughout the lifetime of the log
1700 * view in order to avoid having to re-fetch commits from disk
1701 * while updating the display.
1703 do {
1704 struct got_object_id *id;
1705 struct got_commit_object *commit;
1706 struct commit_queue_entry *entry;
1707 int errcode;
1709 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
1710 NULL, NULL);
1711 if (err || id == NULL)
1712 break;
1714 err = got_object_open_as_commit(&commit, a->repo, id);
1715 if (err)
1716 break;
1717 entry = alloc_commit_queue_entry(commit, id);
1718 if (entry == NULL) {
1719 err = got_error_from_errno("alloc_commit_queue_entry");
1720 break;
1723 errcode = pthread_mutex_lock(&tog_mutex);
1724 if (errcode) {
1725 err = got_error_set_errno(errcode,
1726 "pthread_mutex_lock");
1727 break;
1730 entry->idx = a->commits->ncommits;
1731 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
1732 a->commits->ncommits++;
1734 if (*a->searching == TOG_SEARCH_FORWARD &&
1735 !*a->search_next_done) {
1736 int have_match;
1737 err = match_commit(&have_match, id, commit, a->regex);
1738 if (err)
1739 break;
1740 if (have_match)
1741 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
1744 errcode = pthread_mutex_unlock(&tog_mutex);
1745 if (errcode && err == NULL)
1746 err = got_error_set_errno(errcode,
1747 "pthread_mutex_unlock");
1748 if (err)
1749 break;
1750 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
1752 return err;
1755 static void
1756 select_commit(struct tog_log_view_state *s)
1758 struct commit_queue_entry *entry;
1759 int ncommits = 0;
1761 entry = s->first_displayed_entry;
1762 while (entry) {
1763 if (ncommits == s->selected) {
1764 s->selected_entry = entry;
1765 break;
1767 entry = TAILQ_NEXT(entry, entry);
1768 ncommits++;
1772 static const struct got_error *
1773 draw_commits(struct tog_view *view)
1775 const struct got_error *err = NULL;
1776 struct tog_log_view_state *s = &view->state.log;
1777 struct commit_queue_entry *entry = s->selected_entry;
1778 const int limit = view->nlines;
1779 int width;
1780 int ncommits, author_cols = 4;
1781 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
1782 char *refs_str = NULL;
1783 wchar_t *wline;
1784 struct tog_color *tc;
1785 static const size_t date_display_cols = 12;
1787 if (s->selected_entry &&
1788 !(view->searching && view->search_next_done == 0)) {
1789 struct got_reflist_head *refs;
1790 err = got_object_id_str(&id_str, s->selected_entry->id);
1791 if (err)
1792 return err;
1793 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
1794 s->selected_entry->id);
1795 if (refs) {
1796 err = build_refs_str(&refs_str, refs,
1797 s->selected_entry->id, s->repo);
1798 if (err)
1799 goto done;
1803 if (s->thread_args.commits_needed == 0)
1804 halfdelay(10); /* disable fast refresh */
1806 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
1807 if (asprintf(&ncommits_str, " [%d/%d] %s",
1808 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1809 (view->searching && !view->search_next_done) ?
1810 "searching..." : "loading...") == -1) {
1811 err = got_error_from_errno("asprintf");
1812 goto done;
1814 } else {
1815 const char *search_str = NULL;
1817 if (view->searching) {
1818 if (view->search_next_done == TOG_SEARCH_NO_MORE)
1819 search_str = "no more matches";
1820 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
1821 search_str = "no matches found";
1822 else if (!view->search_next_done)
1823 search_str = "searching...";
1826 if (asprintf(&ncommits_str, " [%d/%d] %s",
1827 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1828 search_str ? search_str :
1829 (refs_str ? refs_str : "")) == -1) {
1830 err = got_error_from_errno("asprintf");
1831 goto done;
1835 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
1836 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
1837 "........................................",
1838 s->in_repo_path, ncommits_str) == -1) {
1839 err = got_error_from_errno("asprintf");
1840 header = NULL;
1841 goto done;
1843 } else if (asprintf(&header, "commit %s%s",
1844 id_str ? id_str : "........................................",
1845 ncommits_str) == -1) {
1846 err = got_error_from_errno("asprintf");
1847 header = NULL;
1848 goto done;
1850 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
1851 if (err)
1852 goto done;
1854 werase(view->window);
1856 if (view_needs_focus_indication(view))
1857 wstandout(view->window);
1858 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1859 if (tc)
1860 wattr_on(view->window,
1861 COLOR_PAIR(tc->colorpair), NULL);
1862 waddwstr(view->window, wline);
1863 if (tc)
1864 wattr_off(view->window,
1865 COLOR_PAIR(tc->colorpair), NULL);
1866 while (width < view->ncols) {
1867 waddch(view->window, ' ');
1868 width++;
1870 if (view_needs_focus_indication(view))
1871 wstandend(view->window);
1872 free(wline);
1873 if (limit <= 1)
1874 goto done;
1876 /* Grow author column size if necessary, and set view->maxx. */
1877 entry = s->first_displayed_entry;
1878 ncommits = 0;
1879 view->maxx = 0;
1880 while (entry) {
1881 char *author, *eol, *msg, *msg0;
1882 wchar_t *wauthor, *wmsg;
1883 int width;
1884 if (ncommits >= limit - 1)
1885 break;
1886 author = strdup(got_object_commit_get_author(entry->commit));
1887 if (author == NULL) {
1888 err = got_error_from_errno("strdup");
1889 goto done;
1891 err = format_author(&wauthor, &width, author, COLS,
1892 date_display_cols);
1893 if (author_cols < width)
1894 author_cols = width;
1895 free(wauthor);
1896 free(author);
1897 err = got_object_commit_get_logmsg(&msg0, entry->commit);
1898 if (err)
1899 goto done;
1900 msg = msg0;
1901 while (*msg == '\n')
1902 ++msg;
1903 if ((eol = strchr(msg, '\n')))
1904 *eol = '\0';
1905 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
1906 date_display_cols + author_cols, 0);
1907 if (err)
1908 goto done;
1909 view->maxx = MAX(view->maxx, width);
1910 free(msg0);
1911 free(wmsg);
1912 ncommits++;
1913 entry = TAILQ_NEXT(entry, entry);
1916 entry = s->first_displayed_entry;
1917 s->last_displayed_entry = s->first_displayed_entry;
1918 ncommits = 0;
1919 while (entry) {
1920 if (ncommits >= limit - 1)
1921 break;
1922 if (ncommits == s->selected)
1923 wstandout(view->window);
1924 err = draw_commit(view, entry->commit, entry->id,
1925 date_display_cols, author_cols);
1926 if (ncommits == s->selected)
1927 wstandend(view->window);
1928 if (err)
1929 goto done;
1930 ncommits++;
1931 s->last_displayed_entry = entry;
1932 entry = TAILQ_NEXT(entry, entry);
1935 view_vborder(view);
1936 done:
1937 free(id_str);
1938 free(refs_str);
1939 free(ncommits_str);
1940 free(header);
1941 return err;
1944 static void
1945 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
1947 struct commit_queue_entry *entry;
1948 int nscrolled = 0;
1950 entry = TAILQ_FIRST(&s->commits.head);
1951 if (s->first_displayed_entry == entry)
1952 return;
1954 entry = s->first_displayed_entry;
1955 while (entry && nscrolled < maxscroll) {
1956 entry = TAILQ_PREV(entry, commit_queue_head, entry);
1957 if (entry) {
1958 s->first_displayed_entry = entry;
1959 nscrolled++;
1964 static const struct got_error *
1965 trigger_log_thread(struct tog_view *view, int wait)
1967 struct tog_log_thread_args *ta = &view->state.log.thread_args;
1968 int errcode;
1970 halfdelay(1); /* fast refresh while loading commits */
1972 while (ta->commits_needed > 0 || ta->load_all) {
1973 if (ta->log_complete)
1974 break;
1976 /* Wake the log thread. */
1977 errcode = pthread_cond_signal(&ta->need_commits);
1978 if (errcode)
1979 return got_error_set_errno(errcode,
1980 "pthread_cond_signal");
1983 * The mutex will be released while the view loop waits
1984 * in wgetch(), at which time the log thread will run.
1986 if (!wait)
1987 break;
1989 /* Display progress update in log view. */
1990 show_log_view(view);
1991 update_panels();
1992 doupdate();
1994 /* Wait right here while next commit is being loaded. */
1995 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
1996 if (errcode)
1997 return got_error_set_errno(errcode,
1998 "pthread_cond_wait");
2000 /* Display progress update in log view. */
2001 show_log_view(view);
2002 update_panels();
2003 doupdate();
2006 return NULL;
2009 static const struct got_error *
2010 log_scroll_down(struct tog_view *view, int maxscroll)
2012 struct tog_log_view_state *s = &view->state.log;
2013 const struct got_error *err = NULL;
2014 struct commit_queue_entry *pentry;
2015 int nscrolled = 0, ncommits_needed;
2017 if (s->last_displayed_entry == NULL)
2018 return NULL;
2020 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2021 if (s->commits.ncommits < ncommits_needed &&
2022 !s->thread_args.log_complete) {
2024 * Ask the log thread for required amount of commits.
2026 s->thread_args.commits_needed += maxscroll;
2027 err = trigger_log_thread(view, 1);
2028 if (err)
2029 return err;
2032 do {
2033 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2034 if (pentry == NULL)
2035 break;
2037 s->last_displayed_entry = pentry;
2039 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2040 if (pentry == NULL)
2041 break;
2042 s->first_displayed_entry = pentry;
2043 } while (++nscrolled < maxscroll);
2045 return err;
2048 static const struct got_error *
2049 open_diff_view_for_commit(struct tog_view **new_view, int begin_x,
2050 struct got_commit_object *commit, struct got_object_id *commit_id,
2051 struct tog_view *log_view, struct got_repository *repo)
2053 const struct got_error *err;
2054 struct got_object_qid *parent_id;
2055 struct tog_view *diff_view;
2057 diff_view = view_open(0, 0, 0, begin_x, TOG_VIEW_DIFF);
2058 if (diff_view == NULL)
2059 return got_error_from_errno("view_open");
2061 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2062 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2063 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2064 if (err == NULL)
2065 *new_view = diff_view;
2066 return err;
2069 static const struct got_error *
2070 tree_view_visit_subtree(struct tog_tree_view_state *s,
2071 struct got_tree_object *subtree)
2073 struct tog_parent_tree *parent;
2075 parent = calloc(1, sizeof(*parent));
2076 if (parent == NULL)
2077 return got_error_from_errno("calloc");
2079 parent->tree = s->tree;
2080 parent->first_displayed_entry = s->first_displayed_entry;
2081 parent->selected_entry = s->selected_entry;
2082 parent->selected = s->selected;
2083 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2084 s->tree = subtree;
2085 s->selected = 0;
2086 s->first_displayed_entry = NULL;
2087 return NULL;
2090 static const struct got_error *
2091 tree_view_walk_path(struct tog_tree_view_state *s,
2092 struct got_commit_object *commit, const char *path)
2094 const struct got_error *err = NULL;
2095 struct got_tree_object *tree = NULL;
2096 const char *p;
2097 char *slash, *subpath = NULL;
2099 /* Walk the path and open corresponding tree objects. */
2100 p = path;
2101 while (*p) {
2102 struct got_tree_entry *te;
2103 struct got_object_id *tree_id;
2104 char *te_name;
2106 while (p[0] == '/')
2107 p++;
2109 /* Ensure the correct subtree entry is selected. */
2110 slash = strchr(p, '/');
2111 if (slash == NULL)
2112 te_name = strdup(p);
2113 else
2114 te_name = strndup(p, slash - p);
2115 if (te_name == NULL) {
2116 err = got_error_from_errno("strndup");
2117 break;
2119 te = got_object_tree_find_entry(s->tree, te_name);
2120 if (te == NULL) {
2121 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2122 free(te_name);
2123 break;
2125 free(te_name);
2126 s->first_displayed_entry = s->selected_entry = te;
2128 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2129 break; /* jump to this file's entry */
2131 slash = strchr(p, '/');
2132 if (slash)
2133 subpath = strndup(path, slash - path);
2134 else
2135 subpath = strdup(path);
2136 if (subpath == NULL) {
2137 err = got_error_from_errno("strdup");
2138 break;
2141 err = got_object_id_by_path(&tree_id, s->repo, commit,
2142 subpath);
2143 if (err)
2144 break;
2146 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2147 free(tree_id);
2148 if (err)
2149 break;
2151 err = tree_view_visit_subtree(s, tree);
2152 if (err) {
2153 got_object_tree_close(tree);
2154 break;
2156 if (slash == NULL)
2157 break;
2158 free(subpath);
2159 subpath = NULL;
2160 p = slash;
2163 free(subpath);
2164 return err;
2167 static const struct got_error *
2168 browse_commit_tree(struct tog_view **new_view, int begin_x,
2169 struct commit_queue_entry *entry, const char *path,
2170 const char *head_ref_name, struct got_repository *repo)
2172 const struct got_error *err = NULL;
2173 struct tog_tree_view_state *s;
2174 struct tog_view *tree_view;
2176 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
2177 if (tree_view == NULL)
2178 return got_error_from_errno("view_open");
2180 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2181 if (err)
2182 return err;
2183 s = &tree_view->state.tree;
2185 *new_view = tree_view;
2187 if (got_path_is_root_dir(path))
2188 return NULL;
2190 return tree_view_walk_path(s, entry->commit, path);
2193 static const struct got_error *
2194 block_signals_used_by_main_thread(void)
2196 sigset_t sigset;
2197 int errcode;
2199 if (sigemptyset(&sigset) == -1)
2200 return got_error_from_errno("sigemptyset");
2202 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2203 if (sigaddset(&sigset, SIGWINCH) == -1)
2204 return got_error_from_errno("sigaddset");
2205 if (sigaddset(&sigset, SIGCONT) == -1)
2206 return got_error_from_errno("sigaddset");
2207 if (sigaddset(&sigset, SIGINT) == -1)
2208 return got_error_from_errno("sigaddset");
2209 if (sigaddset(&sigset, SIGTERM) == -1)
2210 return got_error_from_errno("sigaddset");
2212 /* ncurses handles SIGTSTP */
2213 if (sigaddset(&sigset, SIGTSTP) == -1)
2214 return got_error_from_errno("sigaddset");
2216 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2217 if (errcode)
2218 return got_error_set_errno(errcode, "pthread_sigmask");
2220 return NULL;
2223 static void *
2224 log_thread(void *arg)
2226 const struct got_error *err = NULL;
2227 int errcode = 0;
2228 struct tog_log_thread_args *a = arg;
2229 int done = 0;
2231 err = block_signals_used_by_main_thread();
2232 if (err)
2233 return (void *)err;
2235 while (!done && !err && !tog_fatal_signal_received()) {
2236 err = queue_commits(a);
2237 if (err) {
2238 if (err->code != GOT_ERR_ITER_COMPLETED)
2239 return (void *)err;
2240 err = NULL;
2241 done = 1;
2242 } else if (a->commits_needed > 0 && !a->load_all)
2243 a->commits_needed--;
2245 errcode = pthread_mutex_lock(&tog_mutex);
2246 if (errcode) {
2247 err = got_error_set_errno(errcode,
2248 "pthread_mutex_lock");
2249 break;
2250 } else if (*a->quit)
2251 done = 1;
2252 else if (*a->first_displayed_entry == NULL) {
2253 *a->first_displayed_entry =
2254 TAILQ_FIRST(&a->commits->head);
2255 *a->selected_entry = *a->first_displayed_entry;
2258 errcode = pthread_cond_signal(&a->commit_loaded);
2259 if (errcode) {
2260 err = got_error_set_errno(errcode,
2261 "pthread_cond_signal");
2262 pthread_mutex_unlock(&tog_mutex);
2263 break;
2266 if (done)
2267 a->commits_needed = 0;
2268 else {
2269 if (a->commits_needed == 0 && !a->load_all) {
2270 errcode = pthread_cond_wait(&a->need_commits,
2271 &tog_mutex);
2272 if (errcode)
2273 err = got_error_set_errno(errcode,
2274 "pthread_cond_wait");
2275 if (*a->quit)
2276 done = 1;
2280 errcode = pthread_mutex_unlock(&tog_mutex);
2281 if (errcode && err == NULL)
2282 err = got_error_set_errno(errcode,
2283 "pthread_mutex_unlock");
2285 a->log_complete = 1;
2286 return (void *)err;
2289 static const struct got_error *
2290 stop_log_thread(struct tog_log_view_state *s)
2292 const struct got_error *err = NULL;
2293 int errcode;
2295 if (s->thread) {
2296 s->quit = 1;
2297 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2298 if (errcode)
2299 return got_error_set_errno(errcode,
2300 "pthread_cond_signal");
2301 errcode = pthread_mutex_unlock(&tog_mutex);
2302 if (errcode)
2303 return got_error_set_errno(errcode,
2304 "pthread_mutex_unlock");
2305 errcode = pthread_join(s->thread, (void **)&err);
2306 if (errcode)
2307 return got_error_set_errno(errcode, "pthread_join");
2308 errcode = pthread_mutex_lock(&tog_mutex);
2309 if (errcode)
2310 return got_error_set_errno(errcode,
2311 "pthread_mutex_lock");
2312 s->thread = NULL;
2315 if (s->thread_args.repo) {
2316 err = got_repo_close(s->thread_args.repo);
2317 s->thread_args.repo = NULL;
2320 if (s->thread_args.pack_fds) {
2321 const struct got_error *pack_err =
2322 got_repo_pack_fds_close(s->thread_args.pack_fds);
2323 if (err == NULL)
2324 err = pack_err;
2325 s->thread_args.pack_fds = NULL;
2328 if (s->thread_args.graph) {
2329 got_commit_graph_close(s->thread_args.graph);
2330 s->thread_args.graph = NULL;
2333 return err;
2336 static const struct got_error *
2337 close_log_view(struct tog_view *view)
2339 const struct got_error *err = NULL;
2340 struct tog_log_view_state *s = &view->state.log;
2341 int errcode;
2343 err = stop_log_thread(s);
2345 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2346 if (errcode && err == NULL)
2347 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2349 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2350 if (errcode && err == NULL)
2351 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2353 free_commits(&s->commits);
2354 free(s->in_repo_path);
2355 s->in_repo_path = NULL;
2356 free(s->start_id);
2357 s->start_id = NULL;
2358 free(s->head_ref_name);
2359 s->head_ref_name = NULL;
2360 return err;
2363 static const struct got_error *
2364 search_start_log_view(struct tog_view *view)
2366 struct tog_log_view_state *s = &view->state.log;
2368 s->matched_entry = NULL;
2369 s->search_entry = NULL;
2370 return NULL;
2373 static const struct got_error *
2374 search_next_log_view(struct tog_view *view)
2376 const struct got_error *err = NULL;
2377 struct tog_log_view_state *s = &view->state.log;
2378 struct commit_queue_entry *entry;
2380 /* Display progress update in log view. */
2381 show_log_view(view);
2382 update_panels();
2383 doupdate();
2385 if (s->search_entry) {
2386 int errcode, ch;
2387 errcode = pthread_mutex_unlock(&tog_mutex);
2388 if (errcode)
2389 return got_error_set_errno(errcode,
2390 "pthread_mutex_unlock");
2391 ch = wgetch(view->window);
2392 errcode = pthread_mutex_lock(&tog_mutex);
2393 if (errcode)
2394 return got_error_set_errno(errcode,
2395 "pthread_mutex_lock");
2396 if (ch == KEY_BACKSPACE) {
2397 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2398 return NULL;
2400 if (view->searching == TOG_SEARCH_FORWARD)
2401 entry = TAILQ_NEXT(s->search_entry, entry);
2402 else
2403 entry = TAILQ_PREV(s->search_entry,
2404 commit_queue_head, entry);
2405 } else if (s->matched_entry) {
2406 int matched_idx = s->matched_entry->idx;
2407 int selected_idx = s->selected_entry->idx;
2410 * If the user has moved the cursor after we hit a match,
2411 * the position from where we should continue searching
2412 * might have changed.
2414 if (view->searching == TOG_SEARCH_FORWARD) {
2415 if (matched_idx > selected_idx)
2416 entry = TAILQ_NEXT(s->selected_entry, entry);
2417 else
2418 entry = TAILQ_NEXT(s->matched_entry, entry);
2419 } else {
2420 if (matched_idx < selected_idx)
2421 entry = TAILQ_PREV(s->selected_entry,
2422 commit_queue_head, entry);
2423 else
2424 entry = TAILQ_PREV(s->matched_entry,
2425 commit_queue_head, entry);
2427 } else {
2428 entry = s->selected_entry;
2431 while (1) {
2432 int have_match = 0;
2434 if (entry == NULL) {
2435 if (s->thread_args.log_complete ||
2436 view->searching == TOG_SEARCH_BACKWARD) {
2437 view->search_next_done =
2438 (s->matched_entry == NULL ?
2439 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2440 s->search_entry = NULL;
2441 return NULL;
2444 * Poke the log thread for more commits and return,
2445 * allowing the main loop to make progress. Search
2446 * will resume at s->search_entry once we come back.
2448 s->thread_args.commits_needed++;
2449 return trigger_log_thread(view, 0);
2452 err = match_commit(&have_match, entry->id, entry->commit,
2453 &view->regex);
2454 if (err)
2455 break;
2456 if (have_match) {
2457 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2458 s->matched_entry = entry;
2459 break;
2462 s->search_entry = entry;
2463 if (view->searching == TOG_SEARCH_FORWARD)
2464 entry = TAILQ_NEXT(entry, entry);
2465 else
2466 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2469 if (s->matched_entry) {
2470 int cur = s->selected_entry->idx;
2471 while (cur < s->matched_entry->idx) {
2472 err = input_log_view(NULL, view, KEY_DOWN);
2473 if (err)
2474 return err;
2475 cur++;
2477 while (cur > s->matched_entry->idx) {
2478 err = input_log_view(NULL, view, KEY_UP);
2479 if (err)
2480 return err;
2481 cur--;
2485 s->search_entry = NULL;
2487 return NULL;
2490 static const struct got_error *
2491 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2492 struct got_repository *repo, const char *head_ref_name,
2493 const char *in_repo_path, int log_branches)
2495 const struct got_error *err = NULL;
2496 struct tog_log_view_state *s = &view->state.log;
2497 struct got_repository *thread_repo = NULL;
2498 struct got_commit_graph *thread_graph = NULL;
2499 int errcode;
2501 if (in_repo_path != s->in_repo_path) {
2502 free(s->in_repo_path);
2503 s->in_repo_path = strdup(in_repo_path);
2504 if (s->in_repo_path == NULL)
2505 return got_error_from_errno("strdup");
2508 /* The commit queue only contains commits being displayed. */
2509 TAILQ_INIT(&s->commits.head);
2510 s->commits.ncommits = 0;
2512 s->repo = repo;
2513 if (head_ref_name) {
2514 s->head_ref_name = strdup(head_ref_name);
2515 if (s->head_ref_name == NULL) {
2516 err = got_error_from_errno("strdup");
2517 goto done;
2520 s->start_id = got_object_id_dup(start_id);
2521 if (s->start_id == NULL) {
2522 err = got_error_from_errno("got_object_id_dup");
2523 goto done;
2525 s->log_branches = log_branches;
2527 STAILQ_INIT(&s->colors);
2528 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2529 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2530 get_color_value("TOG_COLOR_COMMIT"));
2531 if (err)
2532 goto done;
2533 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2534 get_color_value("TOG_COLOR_AUTHOR"));
2535 if (err) {
2536 free_colors(&s->colors);
2537 goto done;
2539 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
2540 get_color_value("TOG_COLOR_DATE"));
2541 if (err) {
2542 free_colors(&s->colors);
2543 goto done;
2547 view->show = show_log_view;
2548 view->input = input_log_view;
2549 view->close = close_log_view;
2550 view->search_start = search_start_log_view;
2551 view->search_next = search_next_log_view;
2553 if (s->thread_args.pack_fds == NULL) {
2554 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2555 if (err)
2556 goto done;
2558 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
2559 s->thread_args.pack_fds);
2560 if (err)
2561 goto done;
2562 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
2563 !s->log_branches);
2564 if (err)
2565 goto done;
2566 err = got_commit_graph_iter_start(thread_graph, s->start_id,
2567 s->repo, NULL, NULL);
2568 if (err)
2569 goto done;
2571 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
2572 if (errcode) {
2573 err = got_error_set_errno(errcode, "pthread_cond_init");
2574 goto done;
2576 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
2577 if (errcode) {
2578 err = got_error_set_errno(errcode, "pthread_cond_init");
2579 goto done;
2582 s->thread_args.commits_needed = view->nlines;
2583 s->thread_args.graph = thread_graph;
2584 s->thread_args.commits = &s->commits;
2585 s->thread_args.in_repo_path = s->in_repo_path;
2586 s->thread_args.start_id = s->start_id;
2587 s->thread_args.repo = thread_repo;
2588 s->thread_args.log_complete = 0;
2589 s->thread_args.quit = &s->quit;
2590 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
2591 s->thread_args.selected_entry = &s->selected_entry;
2592 s->thread_args.searching = &view->searching;
2593 s->thread_args.search_next_done = &view->search_next_done;
2594 s->thread_args.regex = &view->regex;
2595 done:
2596 if (err)
2597 close_log_view(view);
2598 return err;
2601 static const struct got_error *
2602 show_log_view(struct tog_view *view)
2604 const struct got_error *err;
2605 struct tog_log_view_state *s = &view->state.log;
2607 if (s->thread == NULL) {
2608 int errcode = pthread_create(&s->thread, NULL, log_thread,
2609 &s->thread_args);
2610 if (errcode)
2611 return got_error_set_errno(errcode, "pthread_create");
2612 if (s->thread_args.commits_needed > 0) {
2613 err = trigger_log_thread(view, 1);
2614 if (err)
2615 return err;
2619 return draw_commits(view);
2622 static const struct got_error *
2623 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
2625 const struct got_error *err = NULL;
2626 struct tog_log_view_state *s = &view->state.log;
2627 struct tog_view *diff_view = NULL, *tree_view = NULL;
2628 struct tog_view *ref_view = NULL;
2629 struct commit_queue_entry *entry;
2630 int begin_x = 0, n, nscroll = view->nlines - 1;
2632 if (s->thread_args.load_all) {
2633 if (ch == KEY_BACKSPACE)
2634 s->thread_args.load_all = 0;
2635 else if (s->thread_args.log_complete) {
2636 s->thread_args.load_all = 0;
2637 log_scroll_down(view, s->commits.ncommits);
2638 s->selected = MIN(view->nlines - 2,
2639 s->commits.ncommits - 1);
2640 select_commit(s);
2642 return NULL;
2645 switch (ch) {
2646 case 'q':
2647 s->quit = 1;
2648 break;
2649 case '0':
2650 view->x = 0;
2651 break;
2652 case '$':
2653 view->x = MAX(view->maxx - view->ncols / 2, 0);
2654 view->count = 0;
2655 break;
2656 case KEY_RIGHT:
2657 case 'l':
2658 if (view->x + view->ncols / 2 < view->maxx)
2659 view->x += 2; /* move two columns right */
2660 else
2661 view->count = 0;
2662 break;
2663 case KEY_LEFT:
2664 case 'h':
2665 view->x -= MIN(view->x, 2); /* move two columns back */
2666 if (view->x <= 0)
2667 view->count = 0;
2668 break;
2669 case 'k':
2670 case KEY_UP:
2671 case '<':
2672 case ',':
2673 case CTRL('p'):
2674 if (s->selected_entry->idx == 0)
2675 view->count = 0;
2676 if (s->first_displayed_entry == NULL)
2677 break;
2678 if (s->selected > 0)
2679 s->selected--;
2680 else
2681 log_scroll_up(s, 1);
2682 select_commit(s);
2683 break;
2684 case 'g':
2685 case KEY_HOME:
2686 s->selected = 0;
2687 s->first_displayed_entry = TAILQ_FIRST(&s->commits.head);
2688 select_commit(s);
2689 view->count = 0;
2690 break;
2691 case CTRL('u'):
2692 case 'u':
2693 nscroll /= 2;
2694 /* FALL THROUGH */
2695 case KEY_PPAGE:
2696 case CTRL('b'):
2697 case 'b':
2698 if (s->first_displayed_entry == NULL)
2699 break;
2700 if (TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
2701 s->selected = MAX(0, s->selected - nscroll - 1);
2702 else
2703 log_scroll_up(s, nscroll);
2704 select_commit(s);
2705 if (s->selected_entry->idx == 0)
2706 view->count = 0;
2707 break;
2708 case 'j':
2709 case KEY_DOWN:
2710 case '>':
2711 case '.':
2712 case CTRL('n'):
2713 if (s->first_displayed_entry == NULL)
2714 break;
2715 if (s->selected < MIN(view->nlines - 2,
2716 s->commits.ncommits - 1))
2717 s->selected++;
2718 else {
2719 err = log_scroll_down(view, 1);
2720 if (err)
2721 break;
2723 select_commit(s);
2724 if (s->thread_args.log_complete &&
2725 s->selected_entry->idx == s->commits.ncommits - 1)
2726 view->count = 0;
2727 break;
2728 case 'G':
2729 case KEY_END: {
2730 /* We don't know yet how many commits, so we're forced to
2731 * traverse them all. */
2732 view->count = 0;
2733 if (!s->thread_args.log_complete) {
2734 s->thread_args.load_all = 1;
2735 return trigger_log_thread(view, 0);
2738 s->selected = 0;
2739 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
2740 for (n = 0; n < view->nlines - 1; n++) {
2741 if (entry == NULL)
2742 break;
2743 s->first_displayed_entry = entry;
2744 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2746 if (n > 0)
2747 s->selected = n - 1;
2748 select_commit(s);
2749 break;
2751 case CTRL('d'):
2752 case 'd':
2753 nscroll /= 2;
2754 /* FALL THROUGH */
2755 case KEY_NPAGE:
2756 case CTRL('f'):
2757 case 'f':
2758 case ' ': {
2759 struct commit_queue_entry *first;
2760 first = s->first_displayed_entry;
2761 if (first == NULL) {
2762 view->count = 0;
2763 break;
2765 err = log_scroll_down(view, nscroll);
2766 if (err)
2767 break;
2768 if (first == s->first_displayed_entry &&
2769 s->selected < MIN(view->nlines - 2,
2770 s->commits.ncommits - 1)) {
2771 /* can't scroll further down */
2772 s->selected += MIN(s->last_displayed_entry->idx -
2773 s->selected_entry->idx, nscroll + 1);
2775 select_commit(s);
2776 if (s->thread_args.log_complete &&
2777 s->selected_entry->idx == s->commits.ncommits - 1)
2778 view->count = 0;
2779 break;
2781 case KEY_RESIZE:
2782 if (s->selected > view->nlines - 2)
2783 s->selected = view->nlines - 2;
2784 if (s->selected > s->commits.ncommits - 1)
2785 s->selected = s->commits.ncommits - 1;
2786 select_commit(s);
2787 if (s->commits.ncommits < view->nlines - 1 &&
2788 !s->thread_args.log_complete) {
2789 s->thread_args.commits_needed += (view->nlines - 1) -
2790 s->commits.ncommits;
2791 err = trigger_log_thread(view, 1);
2793 break;
2794 case KEY_ENTER:
2795 case '\r':
2796 view->count = 0;
2797 if (s->selected_entry == NULL)
2798 break;
2799 if (view_is_parent_view(view))
2800 begin_x = view_split_begin_x(view->begin_x);
2801 err = open_diff_view_for_commit(&diff_view, begin_x,
2802 s->selected_entry->commit, s->selected_entry->id,
2803 view, s->repo);
2804 if (err)
2805 break;
2806 view->focussed = 0;
2807 diff_view->focussed = 1;
2808 if (view_is_parent_view(view)) {
2809 err = view_close_child(view);
2810 if (err)
2811 return err;
2812 err = view_set_child(view, diff_view);
2813 if (err)
2814 return err;
2815 view->focus_child = 1;
2816 } else
2817 *new_view = diff_view;
2818 break;
2819 case 't':
2820 view->count = 0;
2821 if (s->selected_entry == NULL)
2822 break;
2823 if (view_is_parent_view(view))
2824 begin_x = view_split_begin_x(view->begin_x);
2825 err = browse_commit_tree(&tree_view, begin_x,
2826 s->selected_entry, s->in_repo_path, s->head_ref_name,
2827 s->repo);
2828 if (err)
2829 break;
2830 view->focussed = 0;
2831 tree_view->focussed = 1;
2832 if (view_is_parent_view(view)) {
2833 err = view_close_child(view);
2834 if (err)
2835 return err;
2836 err = view_set_child(view, tree_view);
2837 if (err)
2838 return err;
2839 view->focus_child = 1;
2840 } else
2841 *new_view = tree_view;
2842 break;
2843 case KEY_BACKSPACE:
2844 case CTRL('l'):
2845 case 'B':
2846 view->count = 0;
2847 if (ch == KEY_BACKSPACE &&
2848 got_path_is_root_dir(s->in_repo_path))
2849 break;
2850 err = stop_log_thread(s);
2851 if (err)
2852 return err;
2853 if (ch == KEY_BACKSPACE) {
2854 char *parent_path;
2855 err = got_path_dirname(&parent_path, s->in_repo_path);
2856 if (err)
2857 return err;
2858 free(s->in_repo_path);
2859 s->in_repo_path = parent_path;
2860 s->thread_args.in_repo_path = s->in_repo_path;
2861 } else if (ch == CTRL('l')) {
2862 struct got_object_id *start_id;
2863 err = got_repo_match_object_id(&start_id, NULL,
2864 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
2865 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
2866 if (err)
2867 return err;
2868 free(s->start_id);
2869 s->start_id = start_id;
2870 s->thread_args.start_id = s->start_id;
2871 } else /* 'B' */
2872 s->log_branches = !s->log_branches;
2874 if (s->thread_args.pack_fds == NULL) {
2875 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2876 if (err)
2877 return err;
2879 err = got_repo_open(&s->thread_args.repo,
2880 got_repo_get_path(s->repo), NULL,
2881 s->thread_args.pack_fds);
2882 if (err)
2883 return err;
2884 tog_free_refs();
2885 err = tog_load_refs(s->repo, 0);
2886 if (err)
2887 return err;
2888 err = got_commit_graph_open(&s->thread_args.graph,
2889 s->in_repo_path, !s->log_branches);
2890 if (err)
2891 return err;
2892 err = got_commit_graph_iter_start(s->thread_args.graph,
2893 s->start_id, s->repo, NULL, NULL);
2894 if (err)
2895 return err;
2896 free_commits(&s->commits);
2897 s->first_displayed_entry = NULL;
2898 s->last_displayed_entry = NULL;
2899 s->selected_entry = NULL;
2900 s->selected = 0;
2901 s->thread_args.log_complete = 0;
2902 s->quit = 0;
2903 s->thread_args.commits_needed = view->nlines;
2904 s->matched_entry = NULL;
2905 s->search_entry = NULL;
2906 break;
2907 case 'r':
2908 view->count = 0;
2909 if (view_is_parent_view(view))
2910 begin_x = view_split_begin_x(view->begin_x);
2911 ref_view = view_open(view->nlines, view->ncols,
2912 view->begin_y, begin_x, TOG_VIEW_REF);
2913 if (ref_view == NULL)
2914 return got_error_from_errno("view_open");
2915 err = open_ref_view(ref_view, s->repo);
2916 if (err) {
2917 view_close(ref_view);
2918 return err;
2920 view->focussed = 0;
2921 ref_view->focussed = 1;
2922 if (view_is_parent_view(view)) {
2923 err = view_close_child(view);
2924 if (err)
2925 return err;
2926 err = view_set_child(view, ref_view);
2927 if (err)
2928 return err;
2929 view->focus_child = 1;
2930 } else
2931 *new_view = ref_view;
2932 break;
2933 default:
2934 view->count = 0;
2935 break;
2938 return err;
2941 static const struct got_error *
2942 apply_unveil(const char *repo_path, const char *worktree_path)
2944 const struct got_error *error;
2946 #ifdef PROFILE
2947 if (unveil("gmon.out", "rwc") != 0)
2948 return got_error_from_errno2("unveil", "gmon.out");
2949 #endif
2950 if (repo_path && unveil(repo_path, "r") != 0)
2951 return got_error_from_errno2("unveil", repo_path);
2953 if (worktree_path && unveil(worktree_path, "rwc") != 0)
2954 return got_error_from_errno2("unveil", worktree_path);
2956 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
2957 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
2959 error = got_privsep_unveil_exec_helpers();
2960 if (error != NULL)
2961 return error;
2963 if (unveil(NULL, NULL) != 0)
2964 return got_error_from_errno("unveil");
2966 return NULL;
2969 static void
2970 init_curses(void)
2973 * Override default signal handlers before starting ncurses.
2974 * This should prevent ncurses from installing its own
2975 * broken cleanup() signal handler.
2977 signal(SIGWINCH, tog_sigwinch);
2978 signal(SIGPIPE, tog_sigpipe);
2979 signal(SIGCONT, tog_sigcont);
2980 signal(SIGINT, tog_sigint);
2981 signal(SIGTERM, tog_sigterm);
2983 initscr();
2984 cbreak();
2985 halfdelay(1); /* Do fast refresh while initial view is loading. */
2986 noecho();
2987 nonl();
2988 intrflush(stdscr, FALSE);
2989 keypad(stdscr, TRUE);
2990 curs_set(0);
2991 if (getenv("TOG_COLORS") != NULL) {
2992 start_color();
2993 use_default_colors();
2997 static const struct got_error *
2998 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
2999 struct got_repository *repo, struct got_worktree *worktree)
3001 const struct got_error *err = NULL;
3003 if (argc == 0) {
3004 *in_repo_path = strdup("/");
3005 if (*in_repo_path == NULL)
3006 return got_error_from_errno("strdup");
3007 return NULL;
3010 if (worktree) {
3011 const char *prefix = got_worktree_get_path_prefix(worktree);
3012 char *p;
3014 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3015 if (err)
3016 return err;
3017 if (asprintf(in_repo_path, "%s%s%s", prefix,
3018 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3019 p) == -1) {
3020 err = got_error_from_errno("asprintf");
3021 *in_repo_path = NULL;
3023 free(p);
3024 } else
3025 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3027 return err;
3030 static const struct got_error *
3031 cmd_log(int argc, char *argv[])
3033 const struct got_error *error;
3034 struct got_repository *repo = NULL;
3035 struct got_worktree *worktree = NULL;
3036 struct got_object_id *start_id = NULL;
3037 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3038 char *start_commit = NULL, *label = NULL;
3039 struct got_reference *ref = NULL;
3040 const char *head_ref_name = NULL;
3041 int ch, log_branches = 0;
3042 struct tog_view *view;
3043 int *pack_fds = NULL;
3045 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3046 switch (ch) {
3047 case 'b':
3048 log_branches = 1;
3049 break;
3050 case 'c':
3051 start_commit = optarg;
3052 break;
3053 case 'r':
3054 repo_path = realpath(optarg, NULL);
3055 if (repo_path == NULL)
3056 return got_error_from_errno2("realpath",
3057 optarg);
3058 break;
3059 default:
3060 usage_log();
3061 /* NOTREACHED */
3065 argc -= optind;
3066 argv += optind;
3068 if (argc > 1)
3069 usage_log();
3071 error = got_repo_pack_fds_open(&pack_fds);
3072 if (error != NULL)
3073 goto done;
3075 if (repo_path == NULL) {
3076 cwd = getcwd(NULL, 0);
3077 if (cwd == NULL)
3078 return got_error_from_errno("getcwd");
3079 error = got_worktree_open(&worktree, cwd);
3080 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3081 goto done;
3082 if (worktree)
3083 repo_path =
3084 strdup(got_worktree_get_repo_path(worktree));
3085 else
3086 repo_path = strdup(cwd);
3087 if (repo_path == NULL) {
3088 error = got_error_from_errno("strdup");
3089 goto done;
3093 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3094 if (error != NULL)
3095 goto done;
3097 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3098 repo, worktree);
3099 if (error)
3100 goto done;
3102 init_curses();
3104 error = apply_unveil(got_repo_get_path(repo),
3105 worktree ? got_worktree_get_root_path(worktree) : NULL);
3106 if (error)
3107 goto done;
3109 /* already loaded by tog_log_with_path()? */
3110 if (TAILQ_EMPTY(&tog_refs)) {
3111 error = tog_load_refs(repo, 0);
3112 if (error)
3113 goto done;
3116 if (start_commit == NULL) {
3117 error = got_repo_match_object_id(&start_id, &label,
3118 worktree ? got_worktree_get_head_ref_name(worktree) :
3119 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3120 if (error)
3121 goto done;
3122 head_ref_name = label;
3123 } else {
3124 error = got_ref_open(&ref, repo, start_commit, 0);
3125 if (error == NULL)
3126 head_ref_name = got_ref_get_name(ref);
3127 else if (error->code != GOT_ERR_NOT_REF)
3128 goto done;
3129 error = got_repo_match_object_id(&start_id, NULL,
3130 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3131 if (error)
3132 goto done;
3135 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3136 if (view == NULL) {
3137 error = got_error_from_errno("view_open");
3138 goto done;
3140 error = open_log_view(view, start_id, repo, head_ref_name,
3141 in_repo_path, log_branches);
3142 if (error)
3143 goto done;
3144 if (worktree) {
3145 /* Release work tree lock. */
3146 got_worktree_close(worktree);
3147 worktree = NULL;
3149 error = view_loop(view);
3150 done:
3151 free(in_repo_path);
3152 free(repo_path);
3153 free(cwd);
3154 free(start_id);
3155 free(label);
3156 if (ref)
3157 got_ref_close(ref);
3158 if (repo) {
3159 const struct got_error *close_err = got_repo_close(repo);
3160 if (error == NULL)
3161 error = close_err;
3163 if (worktree)
3164 got_worktree_close(worktree);
3165 if (pack_fds) {
3166 const struct got_error *pack_err =
3167 got_repo_pack_fds_close(pack_fds);
3168 if (error == NULL)
3169 error = pack_err;
3171 tog_free_refs();
3172 return error;
3175 __dead static void
3176 usage_diff(void)
3178 endwin();
3179 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3180 "[-w] object1 object2\n", getprogname());
3181 exit(1);
3184 static int
3185 match_line(const char *line, regex_t *regex, size_t nmatch,
3186 regmatch_t *regmatch)
3188 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3191 static struct tog_color *
3192 match_color(struct tog_colors *colors, const char *line)
3194 struct tog_color *tc = NULL;
3196 STAILQ_FOREACH(tc, colors, entry) {
3197 if (match_line(line, &tc->regex, 0, NULL))
3198 return tc;
3201 return NULL;
3204 static const struct got_error *
3205 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3206 WINDOW *window, int skipcol, regmatch_t *regmatch)
3208 const struct got_error *err = NULL;
3209 char *exstr = NULL;
3210 wchar_t *wline = NULL;
3211 int rme, rms, n, width, scrollx;
3212 int width0 = 0, width1 = 0, width2 = 0;
3213 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3215 *wtotal = 0;
3217 rms = regmatch->rm_so;
3218 rme = regmatch->rm_eo;
3220 err = expand_tab(&exstr, line);
3221 if (err)
3222 return err;
3224 /* Split the line into 3 segments, according to match offsets. */
3225 seg0 = strndup(exstr, rms);
3226 if (seg0 == NULL) {
3227 err = got_error_from_errno("strndup");
3228 goto done;
3230 seg1 = strndup(exstr + rms, rme - rms);
3231 if (seg1 == NULL) {
3232 err = got_error_from_errno("strndup");
3233 goto done;
3235 seg2 = strdup(exstr + rme);
3236 if (seg2 == NULL) {
3237 err = got_error_from_errno("strndup");
3238 goto done;
3241 /* draw up to matched token if we haven't scrolled past it */
3242 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3243 col_tab_align, 1);
3244 if (err)
3245 goto done;
3246 n = MAX(width0 - skipcol, 0);
3247 if (n) {
3248 free(wline);
3249 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3250 wlimit, col_tab_align, 1);
3251 if (err)
3252 goto done;
3253 waddwstr(window, &wline[scrollx]);
3254 wlimit -= width;
3255 *wtotal += width;
3258 if (wlimit > 0) {
3259 int i = 0, w = 0;
3260 size_t wlen;
3262 free(wline);
3263 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3264 col_tab_align, 1);
3265 if (err)
3266 goto done;
3267 wlen = wcslen(wline);
3268 while (i < wlen) {
3269 width = wcwidth(wline[i]);
3270 if (width == -1) {
3271 /* should not happen, tabs are expanded */
3272 err = got_error(GOT_ERR_RANGE);
3273 goto done;
3275 if (width0 + w + width > skipcol)
3276 break;
3277 w += width;
3278 i++;
3280 /* draw (visible part of) matched token (if scrolled into it) */
3281 if (width1 - w > 0) {
3282 wattron(window, A_STANDOUT);
3283 waddwstr(window, &wline[i]);
3284 wattroff(window, A_STANDOUT);
3285 wlimit -= (width1 - w);
3286 *wtotal += (width1 - w);
3290 if (wlimit > 0) { /* draw rest of line */
3291 free(wline);
3292 if (skipcol > width0 + width1) {
3293 err = format_line(&wline, &width2, &scrollx, seg2,
3294 skipcol - (width0 + width1), wlimit,
3295 col_tab_align, 1);
3296 if (err)
3297 goto done;
3298 waddwstr(window, &wline[scrollx]);
3299 } else {
3300 err = format_line(&wline, &width2, NULL, seg2, 0,
3301 wlimit, col_tab_align, 1);
3302 if (err)
3303 goto done;
3304 waddwstr(window, wline);
3306 *wtotal += width2;
3308 done:
3309 free(wline);
3310 free(exstr);
3311 free(seg0);
3312 free(seg1);
3313 free(seg2);
3314 return err;
3317 static const struct got_error *
3318 draw_file(struct tog_view *view, const char *header)
3320 struct tog_diff_view_state *s = &view->state.diff;
3321 regmatch_t *regmatch = &view->regmatch;
3322 const struct got_error *err;
3323 int nprinted = 0;
3324 char *line;
3325 size_t linesize = 0;
3326 ssize_t linelen;
3327 struct tog_color *tc;
3328 wchar_t *wline;
3329 int width;
3330 int max_lines = view->nlines;
3331 int nlines = s->nlines;
3332 off_t line_offset;
3334 line_offset = s->line_offsets[s->first_displayed_line - 1];
3335 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3336 return got_error_from_errno("fseek");
3338 werase(view->window);
3340 if (header) {
3341 if (asprintf(&line, "[%d/%d] %s",
3342 s->first_displayed_line - 1 + s->selected_line, nlines,
3343 header) == -1)
3344 return got_error_from_errno("asprintf");
3345 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3346 0, 0);
3347 free(line);
3348 if (err)
3349 return err;
3351 if (view_needs_focus_indication(view))
3352 wstandout(view->window);
3353 waddwstr(view->window, wline);
3354 free(wline);
3355 wline = NULL;
3356 if (view_needs_focus_indication(view))
3357 wstandend(view->window);
3358 if (width <= view->ncols - 1)
3359 waddch(view->window, '\n');
3361 if (max_lines <= 1)
3362 return NULL;
3363 max_lines--;
3366 s->eof = 0;
3367 view->maxx = 0;
3368 line = NULL;
3369 while (max_lines > 0 && nprinted < max_lines) {
3370 linelen = getline(&line, &linesize, s->f);
3371 if (linelen == -1) {
3372 if (feof(s->f)) {
3373 s->eof = 1;
3374 break;
3376 free(line);
3377 return got_ferror(s->f, GOT_ERR_IO);
3380 /* Set view->maxx based on full line length. */
3381 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3382 view->x ? 1 : 0);
3383 if (err) {
3384 free(line);
3385 return err;
3387 view->maxx = MAX(view->maxx, width);
3388 free(wline);
3389 wline = NULL;
3391 tc = match_color(&s->colors, line);
3392 if (tc)
3393 wattr_on(view->window,
3394 COLOR_PAIR(tc->colorpair), NULL);
3395 if (s->first_displayed_line + nprinted == s->matched_line &&
3396 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3397 err = add_matched_line(&width, line, view->ncols, 0,
3398 view->window, view->x, regmatch);
3399 if (err) {
3400 free(line);
3401 return err;
3403 } else {
3404 int skip;
3405 err = format_line(&wline, &width, &skip, line,
3406 view->x, view->ncols, 0, view->x ? 1 : 0);
3407 if (err) {
3408 free(line);
3409 return err;
3411 waddwstr(view->window, &wline[skip]);
3412 free(wline);
3413 wline = NULL;
3415 if (tc)
3416 wattr_off(view->window,
3417 COLOR_PAIR(tc->colorpair), NULL);
3418 if (width <= view->ncols - 1)
3419 waddch(view->window, '\n');
3420 nprinted++;
3422 free(line);
3423 if (nprinted >= 1)
3424 s->last_displayed_line = s->first_displayed_line +
3425 (nprinted - 1);
3426 else
3427 s->last_displayed_line = s->first_displayed_line;
3429 view_vborder(view);
3431 if (s->eof) {
3432 while (nprinted < view->nlines) {
3433 waddch(view->window, '\n');
3434 nprinted++;
3437 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3438 view->ncols, 0, 0);
3439 if (err) {
3440 return err;
3443 wstandout(view->window);
3444 waddwstr(view->window, wline);
3445 free(wline);
3446 wline = NULL;
3447 wstandend(view->window);
3450 return NULL;
3453 static char *
3454 get_datestr(time_t *time, char *datebuf)
3456 struct tm mytm, *tm;
3457 char *p, *s;
3459 tm = gmtime_r(time, &mytm);
3460 if (tm == NULL)
3461 return NULL;
3462 s = asctime_r(tm, datebuf);
3463 if (s == NULL)
3464 return NULL;
3465 p = strchr(s, '\n');
3466 if (p)
3467 *p = '\0';
3468 return s;
3471 static const struct got_error *
3472 get_changed_paths(struct got_pathlist_head *paths,
3473 struct got_commit_object *commit, struct got_repository *repo)
3475 const struct got_error *err = NULL;
3476 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3477 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3478 struct got_object_qid *qid;
3480 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3481 if (qid != NULL) {
3482 struct got_commit_object *pcommit;
3483 err = got_object_open_as_commit(&pcommit, repo,
3484 &qid->id);
3485 if (err)
3486 return err;
3488 tree_id1 = got_object_id_dup(
3489 got_object_commit_get_tree_id(pcommit));
3490 if (tree_id1 == NULL) {
3491 got_object_commit_close(pcommit);
3492 return got_error_from_errno("got_object_id_dup");
3494 got_object_commit_close(pcommit);
3498 if (tree_id1) {
3499 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3500 if (err)
3501 goto done;
3504 tree_id2 = got_object_commit_get_tree_id(commit);
3505 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3506 if (err)
3507 goto done;
3509 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3510 got_diff_tree_collect_changed_paths, paths, 0);
3511 done:
3512 if (tree1)
3513 got_object_tree_close(tree1);
3514 if (tree2)
3515 got_object_tree_close(tree2);
3516 free(tree_id1);
3517 return err;
3520 static const struct got_error *
3521 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
3523 off_t *p;
3525 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
3526 if (p == NULL)
3527 return got_error_from_errno("reallocarray");
3528 *line_offsets = p;
3529 (*line_offsets)[*nlines] = off;
3530 (*nlines)++;
3531 return NULL;
3534 static const struct got_error *
3535 write_commit_info(off_t **line_offsets, size_t *nlines,
3536 struct got_object_id *commit_id, struct got_reflist_head *refs,
3537 struct got_repository *repo, FILE *outfile)
3539 const struct got_error *err = NULL;
3540 char datebuf[26], *datestr;
3541 struct got_commit_object *commit;
3542 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
3543 time_t committer_time;
3544 const char *author, *committer;
3545 char *refs_str = NULL;
3546 struct got_pathlist_head changed_paths;
3547 struct got_pathlist_entry *pe;
3548 off_t outoff = 0;
3549 int n;
3551 TAILQ_INIT(&changed_paths);
3553 if (refs) {
3554 err = build_refs_str(&refs_str, refs, commit_id, repo);
3555 if (err)
3556 return err;
3559 err = got_object_open_as_commit(&commit, repo, commit_id);
3560 if (err)
3561 return err;
3563 err = got_object_id_str(&id_str, commit_id);
3564 if (err) {
3565 err = got_error_from_errno("got_object_id_str");
3566 goto done;
3569 err = add_line_offset(line_offsets, nlines, 0);
3570 if (err)
3571 goto done;
3573 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3574 refs_str ? refs_str : "", refs_str ? ")" : "");
3575 if (n < 0) {
3576 err = got_error_from_errno("fprintf");
3577 goto done;
3579 outoff += n;
3580 err = add_line_offset(line_offsets, nlines, outoff);
3581 if (err)
3582 goto done;
3584 n = fprintf(outfile, "from: %s\n",
3585 got_object_commit_get_author(commit));
3586 if (n < 0) {
3587 err = got_error_from_errno("fprintf");
3588 goto done;
3590 outoff += n;
3591 err = add_line_offset(line_offsets, nlines, outoff);
3592 if (err)
3593 goto done;
3595 committer_time = got_object_commit_get_committer_time(commit);
3596 datestr = get_datestr(&committer_time, datebuf);
3597 if (datestr) {
3598 n = fprintf(outfile, "date: %s UTC\n", datestr);
3599 if (n < 0) {
3600 err = got_error_from_errno("fprintf");
3601 goto done;
3603 outoff += n;
3604 err = add_line_offset(line_offsets, nlines, outoff);
3605 if (err)
3606 goto done;
3608 author = got_object_commit_get_author(commit);
3609 committer = got_object_commit_get_committer(commit);
3610 if (strcmp(author, committer) != 0) {
3611 n = fprintf(outfile, "via: %s\n", committer);
3612 if (n < 0) {
3613 err = got_error_from_errno("fprintf");
3614 goto done;
3616 outoff += n;
3617 err = add_line_offset(line_offsets, nlines, outoff);
3618 if (err)
3619 goto done;
3621 if (got_object_commit_get_nparents(commit) > 1) {
3622 const struct got_object_id_queue *parent_ids;
3623 struct got_object_qid *qid;
3624 int pn = 1;
3625 parent_ids = got_object_commit_get_parent_ids(commit);
3626 STAILQ_FOREACH(qid, parent_ids, entry) {
3627 err = got_object_id_str(&id_str, &qid->id);
3628 if (err)
3629 goto done;
3630 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
3631 if (n < 0) {
3632 err = got_error_from_errno("fprintf");
3633 goto done;
3635 outoff += n;
3636 err = add_line_offset(line_offsets, nlines, outoff);
3637 if (err)
3638 goto done;
3639 free(id_str);
3640 id_str = NULL;
3644 err = got_object_commit_get_logmsg(&logmsg, commit);
3645 if (err)
3646 goto done;
3647 s = logmsg;
3648 while ((line = strsep(&s, "\n")) != NULL) {
3649 n = fprintf(outfile, "%s\n", line);
3650 if (n < 0) {
3651 err = got_error_from_errno("fprintf");
3652 goto done;
3654 outoff += n;
3655 err = add_line_offset(line_offsets, nlines, outoff);
3656 if (err)
3657 goto done;
3660 err = get_changed_paths(&changed_paths, commit, repo);
3661 if (err)
3662 goto done;
3663 TAILQ_FOREACH(pe, &changed_paths, entry) {
3664 struct got_diff_changed_path *cp = pe->data;
3665 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
3666 if (n < 0) {
3667 err = got_error_from_errno("fprintf");
3668 goto done;
3670 outoff += n;
3671 err = add_line_offset(line_offsets, nlines, outoff);
3672 if (err)
3673 goto done;
3674 free((char *)pe->path);
3675 free(pe->data);
3678 fputc('\n', outfile);
3679 outoff++;
3680 err = add_line_offset(line_offsets, nlines, outoff);
3681 done:
3682 got_pathlist_free(&changed_paths);
3683 free(id_str);
3684 free(logmsg);
3685 free(refs_str);
3686 got_object_commit_close(commit);
3687 if (err) {
3688 free(*line_offsets);
3689 *line_offsets = NULL;
3690 *nlines = 0;
3692 return err;
3695 static const struct got_error *
3696 create_diff(struct tog_diff_view_state *s)
3698 const struct got_error *err = NULL;
3699 FILE *f = NULL;
3700 int obj_type;
3702 free(s->line_offsets);
3703 s->line_offsets = malloc(sizeof(off_t));
3704 if (s->line_offsets == NULL)
3705 return got_error_from_errno("malloc");
3706 s->nlines = 0;
3708 f = got_opentemp();
3709 if (f == NULL) {
3710 err = got_error_from_errno("got_opentemp");
3711 goto done;
3713 if (s->f && fclose(s->f) == EOF) {
3714 err = got_error_from_errno("fclose");
3715 goto done;
3717 s->f = f;
3719 if (s->id1)
3720 err = got_object_get_type(&obj_type, s->repo, s->id1);
3721 else
3722 err = got_object_get_type(&obj_type, s->repo, s->id2);
3723 if (err)
3724 goto done;
3726 switch (obj_type) {
3727 case GOT_OBJ_TYPE_BLOB:
3728 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
3729 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
3730 s->label1, s->label2, s->diff_context,
3731 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
3732 break;
3733 case GOT_OBJ_TYPE_TREE:
3734 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
3735 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
3736 s->diff_context, s->ignore_whitespace, s->force_text_diff,
3737 s->repo, s->f);
3738 break;
3739 case GOT_OBJ_TYPE_COMMIT: {
3740 const struct got_object_id_queue *parent_ids;
3741 struct got_object_qid *pid;
3742 struct got_commit_object *commit2;
3743 struct got_reflist_head *refs;
3745 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
3746 if (err)
3747 goto done;
3748 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
3749 /* Show commit info if we're diffing to a parent/root commit. */
3750 if (s->id1 == NULL) {
3751 err = write_commit_info(&s->line_offsets, &s->nlines,
3752 s->id2, refs, s->repo, s->f);
3753 if (err)
3754 goto done;
3755 } else {
3756 parent_ids = got_object_commit_get_parent_ids(commit2);
3757 STAILQ_FOREACH(pid, parent_ids, entry) {
3758 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
3759 err = write_commit_info(
3760 &s->line_offsets, &s->nlines,
3761 s->id2, refs, s->repo, s->f);
3762 if (err)
3763 goto done;
3764 break;
3768 got_object_commit_close(commit2);
3770 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
3771 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
3772 s->diff_context, s->ignore_whitespace, s->force_text_diff,
3773 s->repo, s->f);
3774 break;
3776 default:
3777 err = got_error(GOT_ERR_OBJ_TYPE);
3778 break;
3780 if (err)
3781 goto done;
3782 done:
3783 if (s->f && fflush(s->f) != 0 && err == NULL)
3784 err = got_error_from_errno("fflush");
3785 return err;
3788 static void
3789 diff_view_indicate_progress(struct tog_view *view)
3791 mvwaddstr(view->window, 0, 0, "diffing...");
3792 update_panels();
3793 doupdate();
3796 static const struct got_error *
3797 search_start_diff_view(struct tog_view *view)
3799 struct tog_diff_view_state *s = &view->state.diff;
3801 s->matched_line = 0;
3802 return NULL;
3805 static const struct got_error *
3806 search_next_diff_view(struct tog_view *view)
3808 struct tog_diff_view_state *s = &view->state.diff;
3809 const struct got_error *err = NULL;
3810 int lineno;
3811 char *line = NULL;
3812 size_t linesize = 0;
3813 ssize_t linelen;
3815 if (!view->searching) {
3816 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3817 return NULL;
3820 if (s->matched_line) {
3821 if (view->searching == TOG_SEARCH_FORWARD)
3822 lineno = s->matched_line + 1;
3823 else
3824 lineno = s->matched_line - 1;
3825 } else
3826 lineno = s->first_displayed_line;
3828 while (1) {
3829 off_t offset;
3831 if (lineno <= 0 || lineno > s->nlines) {
3832 if (s->matched_line == 0) {
3833 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3834 break;
3837 if (view->searching == TOG_SEARCH_FORWARD)
3838 lineno = 1;
3839 else
3840 lineno = s->nlines;
3843 offset = s->line_offsets[lineno - 1];
3844 if (fseeko(s->f, offset, SEEK_SET) != 0) {
3845 free(line);
3846 return got_error_from_errno("fseeko");
3848 linelen = getline(&line, &linesize, s->f);
3849 if (linelen != -1) {
3850 char *exstr;
3851 err = expand_tab(&exstr, line);
3852 if (err)
3853 break;
3854 if (match_line(exstr, &view->regex, 1,
3855 &view->regmatch)) {
3856 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3857 s->matched_line = lineno;
3858 free(exstr);
3859 break;
3861 free(exstr);
3863 if (view->searching == TOG_SEARCH_FORWARD)
3864 lineno++;
3865 else
3866 lineno--;
3868 free(line);
3870 if (s->matched_line) {
3871 s->first_displayed_line = s->matched_line;
3872 s->selected_line = 1;
3875 return err;
3878 static const struct got_error *
3879 close_diff_view(struct tog_view *view)
3881 const struct got_error *err = NULL;
3882 struct tog_diff_view_state *s = &view->state.diff;
3884 free(s->id1);
3885 s->id1 = NULL;
3886 free(s->id2);
3887 s->id2 = NULL;
3888 if (s->f && fclose(s->f) == EOF)
3889 err = got_error_from_errno("fclose");
3890 s->f = NULL;
3891 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
3892 err = got_error_from_errno("fclose");
3893 s->f1 = NULL;
3894 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
3895 err = got_error_from_errno("fclose");
3896 s->f2 = NULL;
3897 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
3898 err = got_error_from_errno("close");
3899 s->fd1 = -1;
3900 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
3901 err = got_error_from_errno("close");
3902 s->fd2 = -1;
3903 free_colors(&s->colors);
3904 free(s->line_offsets);
3905 s->line_offsets = NULL;
3906 s->nlines = 0;
3907 return err;
3910 static const struct got_error *
3911 open_diff_view(struct tog_view *view, struct got_object_id *id1,
3912 struct got_object_id *id2, const char *label1, const char *label2,
3913 int diff_context, int ignore_whitespace, int force_text_diff,
3914 struct tog_view *log_view, struct got_repository *repo)
3916 const struct got_error *err;
3917 struct tog_diff_view_state *s = &view->state.diff;
3919 memset(s, 0, sizeof(*s));
3920 s->fd1 = -1;
3921 s->fd2 = -1;
3923 if (id1 != NULL && id2 != NULL) {
3924 int type1, type2;
3925 err = got_object_get_type(&type1, repo, id1);
3926 if (err)
3927 return err;
3928 err = got_object_get_type(&type2, repo, id2);
3929 if (err)
3930 return err;
3932 if (type1 != type2)
3933 return got_error(GOT_ERR_OBJ_TYPE);
3935 s->first_displayed_line = 1;
3936 s->last_displayed_line = view->nlines;
3937 s->selected_line = 1;
3938 s->repo = repo;
3939 s->id1 = id1;
3940 s->id2 = id2;
3941 s->label1 = label1;
3942 s->label2 = label2;
3944 if (id1) {
3945 s->id1 = got_object_id_dup(id1);
3946 if (s->id1 == NULL)
3947 return got_error_from_errno("got_object_id_dup");
3948 } else
3949 s->id1 = NULL;
3951 s->id2 = got_object_id_dup(id2);
3952 if (s->id2 == NULL) {
3953 err = got_error_from_errno("got_object_id_dup");
3954 goto done;
3957 s->f1 = got_opentemp();
3958 if (s->f1 == NULL) {
3959 err = got_error_from_errno("got_opentemp");
3960 goto done;
3963 s->f2 = got_opentemp();
3964 if (s->f2 == NULL) {
3965 err = got_error_from_errno("got_opentemp");
3966 goto done;
3969 s->fd1 = got_opentempfd();
3970 if (s->fd1 == -1) {
3971 err = got_error_from_errno("got_opentempfd");
3972 goto done;
3975 s->fd2 = got_opentempfd();
3976 if (s->fd2 == -1) {
3977 err = got_error_from_errno("got_opentempfd");
3978 goto done;
3981 s->first_displayed_line = 1;
3982 s->last_displayed_line = view->nlines;
3983 s->diff_context = diff_context;
3984 s->ignore_whitespace = ignore_whitespace;
3985 s->force_text_diff = force_text_diff;
3986 s->log_view = log_view;
3987 s->repo = repo;
3989 STAILQ_INIT(&s->colors);
3990 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3991 err = add_color(&s->colors,
3992 "^-", TOG_COLOR_DIFF_MINUS,
3993 get_color_value("TOG_COLOR_DIFF_MINUS"));
3994 if (err)
3995 goto done;
3996 err = add_color(&s->colors, "^\\+",
3997 TOG_COLOR_DIFF_PLUS,
3998 get_color_value("TOG_COLOR_DIFF_PLUS"));
3999 if (err)
4000 goto done;
4001 err = add_color(&s->colors,
4002 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4003 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4004 if (err)
4005 goto done;
4007 err = add_color(&s->colors,
4008 "^(commit [0-9a-f]|parent [0-9]|"
4009 "(blob|file|tree|commit) [-+] |"
4010 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4011 get_color_value("TOG_COLOR_DIFF_META"));
4012 if (err)
4013 goto done;
4015 err = add_color(&s->colors,
4016 "^(from|via): ", TOG_COLOR_AUTHOR,
4017 get_color_value("TOG_COLOR_AUTHOR"));
4018 if (err)
4019 goto done;
4021 err = add_color(&s->colors,
4022 "^date: ", TOG_COLOR_DATE,
4023 get_color_value("TOG_COLOR_DATE"));
4024 if (err)
4025 goto done;
4028 if (log_view && view_is_splitscreen(view))
4029 show_log_view(log_view); /* draw vborder */
4030 diff_view_indicate_progress(view);
4032 err = create_diff(s);
4034 view->show = show_diff_view;
4035 view->input = input_diff_view;
4036 view->close = close_diff_view;
4037 view->search_start = search_start_diff_view;
4038 view->search_next = search_next_diff_view;
4039 done:
4040 if (err)
4041 close_diff_view(view);
4042 return err;
4045 static const struct got_error *
4046 show_diff_view(struct tog_view *view)
4048 const struct got_error *err;
4049 struct tog_diff_view_state *s = &view->state.diff;
4050 char *id_str1 = NULL, *id_str2, *header;
4051 const char *label1, *label2;
4053 if (s->id1) {
4054 err = got_object_id_str(&id_str1, s->id1);
4055 if (err)
4056 return err;
4057 label1 = s->label1 ? : id_str1;
4058 } else
4059 label1 = "/dev/null";
4061 err = got_object_id_str(&id_str2, s->id2);
4062 if (err)
4063 return err;
4064 label2 = s->label2 ? : id_str2;
4066 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4067 err = got_error_from_errno("asprintf");
4068 free(id_str1);
4069 free(id_str2);
4070 return err;
4072 free(id_str1);
4073 free(id_str2);
4075 err = draw_file(view, header);
4076 free(header);
4077 return err;
4080 static const struct got_error *
4081 set_selected_commit(struct tog_diff_view_state *s,
4082 struct commit_queue_entry *entry)
4084 const struct got_error *err;
4085 const struct got_object_id_queue *parent_ids;
4086 struct got_commit_object *selected_commit;
4087 struct got_object_qid *pid;
4089 free(s->id2);
4090 s->id2 = got_object_id_dup(entry->id);
4091 if (s->id2 == NULL)
4092 return got_error_from_errno("got_object_id_dup");
4094 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4095 if (err)
4096 return err;
4097 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4098 free(s->id1);
4099 pid = STAILQ_FIRST(parent_ids);
4100 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4101 got_object_commit_close(selected_commit);
4102 return NULL;
4105 static const struct got_error *
4106 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4108 const struct got_error *err = NULL;
4109 struct tog_diff_view_state *s = &view->state.diff;
4110 struct tog_log_view_state *ls;
4111 struct commit_queue_entry *old_selected_entry;
4112 char *line = NULL;
4113 size_t linesize = 0;
4114 ssize_t linelen;
4115 int i, nscroll = view->nlines - 1;
4117 switch (ch) {
4118 case '0':
4119 view->x = 0;
4120 break;
4121 case '$':
4122 view->x = MAX(view->maxx - view->ncols / 3, 0);
4123 view->count = 0;
4124 break;
4125 case KEY_RIGHT:
4126 case 'l':
4127 if (view->x + view->ncols / 3 < view->maxx)
4128 view->x += 2; /* move two columns right */
4129 else
4130 view->count = 0;
4131 break;
4132 case KEY_LEFT:
4133 case 'h':
4134 view->x -= MIN(view->x, 2); /* move two columns back */
4135 if (view->x <= 0)
4136 view->count = 0;
4137 break;
4138 case 'a':
4139 case 'w':
4140 if (ch == 'a')
4141 s->force_text_diff = !s->force_text_diff;
4142 if (ch == 'w')
4143 s->ignore_whitespace = !s->ignore_whitespace;
4144 wclear(view->window);
4145 s->first_displayed_line = 1;
4146 s->last_displayed_line = view->nlines;
4147 s->matched_line = 0;
4148 diff_view_indicate_progress(view);
4149 err = create_diff(s);
4150 view->count = 0;
4151 break;
4152 case 'g':
4153 case KEY_HOME:
4154 s->first_displayed_line = 1;
4155 view->count = 0;
4156 break;
4157 case 'G':
4158 case KEY_END:
4159 view->count = 0;
4160 if (s->eof)
4161 break;
4163 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4164 s->eof = 1;
4165 break;
4166 case 'k':
4167 case KEY_UP:
4168 case CTRL('p'):
4169 if (s->first_displayed_line > 1)
4170 s->first_displayed_line--;
4171 else
4172 view->count = 0;
4173 break;
4174 case CTRL('u'):
4175 case 'u':
4176 nscroll /= 2;
4177 /* FALL THROUGH */
4178 case KEY_PPAGE:
4179 case CTRL('b'):
4180 case 'b':
4181 if (s->first_displayed_line == 1) {
4182 view->count = 0;
4183 break;
4185 i = 0;
4186 while (i++ < nscroll && s->first_displayed_line > 1)
4187 s->first_displayed_line--;
4188 break;
4189 case 'j':
4190 case KEY_DOWN:
4191 case CTRL('n'):
4192 if (!s->eof)
4193 s->first_displayed_line++;
4194 else
4195 view->count = 0;
4196 break;
4197 case CTRL('d'):
4198 case 'd':
4199 nscroll /= 2;
4200 /* FALL THROUGH */
4201 case KEY_NPAGE:
4202 case CTRL('f'):
4203 case 'f':
4204 case ' ':
4205 if (s->eof) {
4206 view->count = 0;
4207 break;
4209 i = 0;
4210 while (!s->eof && i++ < nscroll) {
4211 linelen = getline(&line, &linesize, s->f);
4212 s->first_displayed_line++;
4213 if (linelen == -1) {
4214 if (feof(s->f)) {
4215 s->eof = 1;
4216 } else
4217 err = got_ferror(s->f, GOT_ERR_IO);
4218 break;
4221 free(line);
4222 break;
4223 case '[':
4224 if (s->diff_context > 0) {
4225 s->diff_context--;
4226 s->matched_line = 0;
4227 diff_view_indicate_progress(view);
4228 err = create_diff(s);
4229 if (s->first_displayed_line + view->nlines - 1 >
4230 s->nlines) {
4231 s->first_displayed_line = 1;
4232 s->last_displayed_line = view->nlines;
4234 } else
4235 view->count = 0;
4236 break;
4237 case ']':
4238 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4239 s->diff_context++;
4240 s->matched_line = 0;
4241 diff_view_indicate_progress(view);
4242 err = create_diff(s);
4243 } else
4244 view->count = 0;
4245 break;
4246 case '<':
4247 case ',':
4248 if (s->log_view == NULL) {
4249 view->count = 0;
4250 break;
4252 ls = &s->log_view->state.log;
4253 old_selected_entry = ls->selected_entry;
4255 /* view->count handled in input_log_view() */
4256 err = input_log_view(NULL, s->log_view, KEY_UP);
4257 if (err)
4258 break;
4260 if (old_selected_entry == ls->selected_entry)
4261 break;
4263 err = set_selected_commit(s, ls->selected_entry);
4264 if (err)
4265 break;
4267 s->first_displayed_line = 1;
4268 s->last_displayed_line = view->nlines;
4269 s->matched_line = 0;
4270 view->x = 0;
4272 diff_view_indicate_progress(view);
4273 err = create_diff(s);
4274 break;
4275 case '>':
4276 case '.':
4277 if (s->log_view == NULL) {
4278 view->count = 0;
4279 break;
4281 ls = &s->log_view->state.log;
4282 old_selected_entry = ls->selected_entry;
4284 /* view->count handled in input_log_view() */
4285 err = input_log_view(NULL, s->log_view, KEY_DOWN);
4286 if (err)
4287 break;
4289 if (old_selected_entry == ls->selected_entry)
4290 break;
4292 err = set_selected_commit(s, ls->selected_entry);
4293 if (err)
4294 break;
4296 s->first_displayed_line = 1;
4297 s->last_displayed_line = view->nlines;
4298 s->matched_line = 0;
4299 view->x = 0;
4301 diff_view_indicate_progress(view);
4302 err = create_diff(s);
4303 break;
4304 default:
4305 view->count = 0;
4306 break;
4309 return err;
4312 static const struct got_error *
4313 cmd_diff(int argc, char *argv[])
4315 const struct got_error *error = NULL;
4316 struct got_repository *repo = NULL;
4317 struct got_worktree *worktree = NULL;
4318 struct got_object_id *id1 = NULL, *id2 = NULL;
4319 char *repo_path = NULL, *cwd = NULL;
4320 char *id_str1 = NULL, *id_str2 = NULL;
4321 char *label1 = NULL, *label2 = NULL;
4322 int diff_context = 3, ignore_whitespace = 0;
4323 int ch, force_text_diff = 0;
4324 const char *errstr;
4325 struct tog_view *view;
4326 int *pack_fds = NULL;
4328 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4329 switch (ch) {
4330 case 'a':
4331 force_text_diff = 1;
4332 break;
4333 case 'C':
4334 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4335 &errstr);
4336 if (errstr != NULL)
4337 errx(1, "number of context lines is %s: %s",
4338 errstr, errstr);
4339 break;
4340 case 'r':
4341 repo_path = realpath(optarg, NULL);
4342 if (repo_path == NULL)
4343 return got_error_from_errno2("realpath",
4344 optarg);
4345 got_path_strip_trailing_slashes(repo_path);
4346 break;
4347 case 'w':
4348 ignore_whitespace = 1;
4349 break;
4350 default:
4351 usage_diff();
4352 /* NOTREACHED */
4356 argc -= optind;
4357 argv += optind;
4359 if (argc == 0) {
4360 usage_diff(); /* TODO show local worktree changes */
4361 } else if (argc == 2) {
4362 id_str1 = argv[0];
4363 id_str2 = argv[1];
4364 } else
4365 usage_diff();
4367 error = got_repo_pack_fds_open(&pack_fds);
4368 if (error)
4369 goto done;
4371 if (repo_path == NULL) {
4372 cwd = getcwd(NULL, 0);
4373 if (cwd == NULL)
4374 return got_error_from_errno("getcwd");
4375 error = got_worktree_open(&worktree, cwd);
4376 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4377 goto done;
4378 if (worktree)
4379 repo_path =
4380 strdup(got_worktree_get_repo_path(worktree));
4381 else
4382 repo_path = strdup(cwd);
4383 if (repo_path == NULL) {
4384 error = got_error_from_errno("strdup");
4385 goto done;
4389 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4390 if (error)
4391 goto done;
4393 init_curses();
4395 error = apply_unveil(got_repo_get_path(repo), NULL);
4396 if (error)
4397 goto done;
4399 error = tog_load_refs(repo, 0);
4400 if (error)
4401 goto done;
4403 error = got_repo_match_object_id(&id1, &label1, id_str1,
4404 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4405 if (error)
4406 goto done;
4408 error = got_repo_match_object_id(&id2, &label2, id_str2,
4409 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4410 if (error)
4411 goto done;
4413 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4414 if (view == NULL) {
4415 error = got_error_from_errno("view_open");
4416 goto done;
4418 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4419 ignore_whitespace, force_text_diff, NULL, repo);
4420 if (error)
4421 goto done;
4422 error = view_loop(view);
4423 done:
4424 free(label1);
4425 free(label2);
4426 free(repo_path);
4427 free(cwd);
4428 if (repo) {
4429 const struct got_error *close_err = got_repo_close(repo);
4430 if (error == NULL)
4431 error = close_err;
4433 if (worktree)
4434 got_worktree_close(worktree);
4435 if (pack_fds) {
4436 const struct got_error *pack_err =
4437 got_repo_pack_fds_close(pack_fds);
4438 if (error == NULL)
4439 error = pack_err;
4441 tog_free_refs();
4442 return error;
4445 __dead static void
4446 usage_blame(void)
4448 endwin();
4449 fprintf(stderr,
4450 "usage: %s blame [-c commit] [-r repository-path] path\n",
4451 getprogname());
4452 exit(1);
4455 struct tog_blame_line {
4456 int annotated;
4457 struct got_object_id *id;
4460 static const struct got_error *
4461 draw_blame(struct tog_view *view)
4463 struct tog_blame_view_state *s = &view->state.blame;
4464 struct tog_blame *blame = &s->blame;
4465 regmatch_t *regmatch = &view->regmatch;
4466 const struct got_error *err;
4467 int lineno = 0, nprinted = 0;
4468 char *line = NULL;
4469 size_t linesize = 0;
4470 ssize_t linelen;
4471 wchar_t *wline;
4472 int width;
4473 struct tog_blame_line *blame_line;
4474 struct got_object_id *prev_id = NULL;
4475 char *id_str;
4476 struct tog_color *tc;
4478 err = got_object_id_str(&id_str, &s->blamed_commit->id);
4479 if (err)
4480 return err;
4482 rewind(blame->f);
4483 werase(view->window);
4485 if (asprintf(&line, "commit %s", id_str) == -1) {
4486 err = got_error_from_errno("asprintf");
4487 free(id_str);
4488 return err;
4491 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4492 free(line);
4493 line = NULL;
4494 if (err)
4495 return err;
4496 if (view_needs_focus_indication(view))
4497 wstandout(view->window);
4498 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4499 if (tc)
4500 wattr_on(view->window,
4501 COLOR_PAIR(tc->colorpair), NULL);
4502 waddwstr(view->window, wline);
4503 if (tc)
4504 wattr_off(view->window,
4505 COLOR_PAIR(tc->colorpair), NULL);
4506 if (view_needs_focus_indication(view))
4507 wstandend(view->window);
4508 free(wline);
4509 wline = NULL;
4510 if (width < view->ncols - 1)
4511 waddch(view->window, '\n');
4513 if (asprintf(&line, "[%d/%d] %s%s",
4514 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
4515 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
4516 free(id_str);
4517 return got_error_from_errno("asprintf");
4519 free(id_str);
4520 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4521 free(line);
4522 line = NULL;
4523 if (err)
4524 return err;
4525 waddwstr(view->window, wline);
4526 free(wline);
4527 wline = NULL;
4528 if (width < view->ncols - 1)
4529 waddch(view->window, '\n');
4531 s->eof = 0;
4532 view->maxx = 0;
4533 while (nprinted < view->nlines - 2) {
4534 linelen = getline(&line, &linesize, blame->f);
4535 if (linelen == -1) {
4536 if (feof(blame->f)) {
4537 s->eof = 1;
4538 break;
4540 free(line);
4541 return got_ferror(blame->f, GOT_ERR_IO);
4543 if (++lineno < s->first_displayed_line)
4544 continue;
4546 /* Set view->maxx based on full line length. */
4547 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
4548 if (err) {
4549 free(line);
4550 return err;
4552 free(wline);
4553 wline = NULL;
4554 view->maxx = MAX(view->maxx, width);
4556 if (view->focussed && nprinted == s->selected_line - 1)
4557 wstandout(view->window);
4559 if (blame->nlines > 0) {
4560 blame_line = &blame->lines[lineno - 1];
4561 if (blame_line->annotated && prev_id &&
4562 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
4563 !(view->focussed &&
4564 nprinted == s->selected_line - 1)) {
4565 waddstr(view->window, " ");
4566 } else if (blame_line->annotated) {
4567 char *id_str;
4568 err = got_object_id_str(&id_str,
4569 blame_line->id);
4570 if (err) {
4571 free(line);
4572 return err;
4574 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4575 if (tc)
4576 wattr_on(view->window,
4577 COLOR_PAIR(tc->colorpair), NULL);
4578 wprintw(view->window, "%.8s", id_str);
4579 if (tc)
4580 wattr_off(view->window,
4581 COLOR_PAIR(tc->colorpair), NULL);
4582 free(id_str);
4583 prev_id = blame_line->id;
4584 } else {
4585 waddstr(view->window, "........");
4586 prev_id = NULL;
4588 } else {
4589 waddstr(view->window, "........");
4590 prev_id = NULL;
4593 if (view->focussed && nprinted == s->selected_line - 1)
4594 wstandend(view->window);
4595 waddstr(view->window, " ");
4597 if (view->ncols <= 9) {
4598 width = 9;
4599 } else if (s->first_displayed_line + nprinted ==
4600 s->matched_line &&
4601 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4602 err = add_matched_line(&width, line, view->ncols - 9, 9,
4603 view->window, view->x, regmatch);
4604 if (err) {
4605 free(line);
4606 return err;
4608 width += 9;
4609 } else {
4610 int skip;
4611 err = format_line(&wline, &width, &skip, line,
4612 view->x, view->ncols - 9, 9, 1);
4613 if (err) {
4614 free(line);
4615 return err;
4617 waddwstr(view->window, &wline[skip]);
4618 width += 9;
4619 free(wline);
4620 wline = NULL;
4623 if (width <= view->ncols - 1)
4624 waddch(view->window, '\n');
4625 if (++nprinted == 1)
4626 s->first_displayed_line = lineno;
4628 free(line);
4629 s->last_displayed_line = lineno;
4631 view_vborder(view);
4633 return NULL;
4636 static const struct got_error *
4637 blame_cb(void *arg, int nlines, int lineno,
4638 struct got_commit_object *commit, struct got_object_id *id)
4640 const struct got_error *err = NULL;
4641 struct tog_blame_cb_args *a = arg;
4642 struct tog_blame_line *line;
4643 int errcode;
4645 if (nlines != a->nlines ||
4646 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4647 return got_error(GOT_ERR_RANGE);
4649 errcode = pthread_mutex_lock(&tog_mutex);
4650 if (errcode)
4651 return got_error_set_errno(errcode, "pthread_mutex_lock");
4653 if (*a->quit) { /* user has quit the blame view */
4654 err = got_error(GOT_ERR_ITER_COMPLETED);
4655 goto done;
4658 if (lineno == -1)
4659 goto done; /* no change in this commit */
4661 line = &a->lines[lineno - 1];
4662 if (line->annotated)
4663 goto done;
4665 line->id = got_object_id_dup(id);
4666 if (line->id == NULL) {
4667 err = got_error_from_errno("got_object_id_dup");
4668 goto done;
4670 line->annotated = 1;
4671 done:
4672 errcode = pthread_mutex_unlock(&tog_mutex);
4673 if (errcode)
4674 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4675 return err;
4678 static void *
4679 blame_thread(void *arg)
4681 const struct got_error *err, *close_err;
4682 struct tog_blame_thread_args *ta = arg;
4683 struct tog_blame_cb_args *a = ta->cb_args;
4684 int errcode, fd = -1;
4686 fd = got_opentempfd();
4687 if (fd == -1)
4688 return (void *)got_error_from_errno("got_opentempfd");
4690 err = block_signals_used_by_main_thread();
4691 if (err)
4692 return (void *)err;
4694 err = got_blame(ta->path, a->commit_id, ta->repo,
4695 blame_cb, ta->cb_args, ta->cancel_cb, ta->cancel_arg, fd);
4696 if (err && err->code == GOT_ERR_CANCELLED)
4697 err = NULL;
4699 errcode = pthread_mutex_lock(&tog_mutex);
4700 if (errcode)
4701 return (void *)got_error_set_errno(errcode,
4702 "pthread_mutex_lock");
4704 close_err = got_repo_close(ta->repo);
4705 if (err == NULL)
4706 err = close_err;
4707 ta->repo = NULL;
4708 *ta->complete = 1;
4710 errcode = pthread_mutex_unlock(&tog_mutex);
4711 if (errcode && err == NULL)
4712 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4714 if (fd != -1 && close(fd) == -1 && err == NULL)
4715 err = got_error_from_errno("close");
4717 return (void *)err;
4720 static struct got_object_id *
4721 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
4722 int first_displayed_line, int selected_line)
4724 struct tog_blame_line *line;
4726 if (nlines <= 0)
4727 return NULL;
4729 line = &lines[first_displayed_line - 1 + selected_line - 1];
4730 if (!line->annotated)
4731 return NULL;
4733 return line->id;
4736 static const struct got_error *
4737 stop_blame(struct tog_blame *blame)
4739 const struct got_error *err = NULL;
4740 int i;
4742 if (blame->thread) {
4743 int errcode;
4744 errcode = pthread_mutex_unlock(&tog_mutex);
4745 if (errcode)
4746 return got_error_set_errno(errcode,
4747 "pthread_mutex_unlock");
4748 errcode = pthread_join(blame->thread, (void **)&err);
4749 if (errcode)
4750 return got_error_set_errno(errcode, "pthread_join");
4751 errcode = pthread_mutex_lock(&tog_mutex);
4752 if (errcode)
4753 return got_error_set_errno(errcode,
4754 "pthread_mutex_lock");
4755 if (err && err->code == GOT_ERR_ITER_COMPLETED)
4756 err = NULL;
4757 blame->thread = NULL;
4759 if (blame->thread_args.repo) {
4760 const struct got_error *close_err;
4761 close_err = got_repo_close(blame->thread_args.repo);
4762 if (err == NULL)
4763 err = close_err;
4764 blame->thread_args.repo = NULL;
4766 if (blame->f) {
4767 if (fclose(blame->f) == EOF && err == NULL)
4768 err = got_error_from_errno("fclose");
4769 blame->f = NULL;
4771 if (blame->lines) {
4772 for (i = 0; i < blame->nlines; i++)
4773 free(blame->lines[i].id);
4774 free(blame->lines);
4775 blame->lines = NULL;
4777 free(blame->cb_args.commit_id);
4778 blame->cb_args.commit_id = NULL;
4779 if (blame->pack_fds) {
4780 const struct got_error *pack_err =
4781 got_repo_pack_fds_close(blame->pack_fds);
4782 if (err == NULL)
4783 err = pack_err;
4784 blame->pack_fds = NULL;
4786 return err;
4789 static const struct got_error *
4790 cancel_blame_view(void *arg)
4792 const struct got_error *err = NULL;
4793 int *done = arg;
4794 int errcode;
4796 errcode = pthread_mutex_lock(&tog_mutex);
4797 if (errcode)
4798 return got_error_set_errno(errcode,
4799 "pthread_mutex_unlock");
4801 if (*done)
4802 err = got_error(GOT_ERR_CANCELLED);
4804 errcode = pthread_mutex_unlock(&tog_mutex);
4805 if (errcode)
4806 return got_error_set_errno(errcode,
4807 "pthread_mutex_lock");
4809 return err;
4812 static const struct got_error *
4813 run_blame(struct tog_view *view)
4815 struct tog_blame_view_state *s = &view->state.blame;
4816 struct tog_blame *blame = &s->blame;
4817 const struct got_error *err = NULL;
4818 struct got_commit_object *commit = NULL;
4819 struct got_blob_object *blob = NULL;
4820 struct got_repository *thread_repo = NULL;
4821 struct got_object_id *obj_id = NULL;
4822 int obj_type, fd = -1;
4823 int *pack_fds = NULL;
4825 err = got_object_open_as_commit(&commit, s->repo,
4826 &s->blamed_commit->id);
4827 if (err)
4828 return err;
4830 fd = got_opentempfd();
4831 if (fd == -1) {
4832 err = got_error_from_errno("got_opentempfd");
4833 goto done;
4836 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
4837 if (err)
4838 goto done;
4840 err = got_object_get_type(&obj_type, s->repo, obj_id);
4841 if (err)
4842 goto done;
4844 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4845 err = got_error(GOT_ERR_OBJ_TYPE);
4846 goto done;
4849 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
4850 if (err)
4851 goto done;
4852 blame->f = got_opentemp();
4853 if (blame->f == NULL) {
4854 err = got_error_from_errno("got_opentemp");
4855 goto done;
4857 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
4858 &blame->line_offsets, blame->f, blob);
4859 if (err)
4860 goto done;
4861 if (blame->nlines == 0) {
4862 s->blame_complete = 1;
4863 goto done;
4866 /* Don't include \n at EOF in the blame line count. */
4867 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
4868 blame->nlines--;
4870 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
4871 if (blame->lines == NULL) {
4872 err = got_error_from_errno("calloc");
4873 goto done;
4876 err = got_repo_pack_fds_open(&pack_fds);
4877 if (err)
4878 goto done;
4879 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
4880 pack_fds);
4881 if (err)
4882 goto done;
4884 blame->pack_fds = pack_fds;
4885 blame->cb_args.view = view;
4886 blame->cb_args.lines = blame->lines;
4887 blame->cb_args.nlines = blame->nlines;
4888 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
4889 if (blame->cb_args.commit_id == NULL) {
4890 err = got_error_from_errno("got_object_id_dup");
4891 goto done;
4893 blame->cb_args.quit = &s->done;
4895 blame->thread_args.path = s->path;
4896 blame->thread_args.repo = thread_repo;
4897 blame->thread_args.cb_args = &blame->cb_args;
4898 blame->thread_args.complete = &s->blame_complete;
4899 blame->thread_args.cancel_cb = cancel_blame_view;
4900 blame->thread_args.cancel_arg = &s->done;
4901 s->blame_complete = 0;
4903 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
4904 s->first_displayed_line = 1;
4905 s->last_displayed_line = view->nlines;
4906 s->selected_line = 1;
4908 s->matched_line = 0;
4910 done:
4911 if (commit)
4912 got_object_commit_close(commit);
4913 if (fd != -1 && close(fd) == -1 && err == NULL)
4914 err = got_error_from_errno("close");
4915 if (blob)
4916 got_object_blob_close(blob);
4917 free(obj_id);
4918 if (err)
4919 stop_blame(blame);
4920 return err;
4923 static const struct got_error *
4924 open_blame_view(struct tog_view *view, char *path,
4925 struct got_object_id *commit_id, struct got_repository *repo)
4927 const struct got_error *err = NULL;
4928 struct tog_blame_view_state *s = &view->state.blame;
4930 STAILQ_INIT(&s->blamed_commits);
4932 s->path = strdup(path);
4933 if (s->path == NULL)
4934 return got_error_from_errno("strdup");
4936 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
4937 if (err) {
4938 free(s->path);
4939 return err;
4942 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
4943 s->first_displayed_line = 1;
4944 s->last_displayed_line = view->nlines;
4945 s->selected_line = 1;
4946 s->blame_complete = 0;
4947 s->repo = repo;
4948 s->commit_id = commit_id;
4949 memset(&s->blame, 0, sizeof(s->blame));
4951 STAILQ_INIT(&s->colors);
4952 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4953 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
4954 get_color_value("TOG_COLOR_COMMIT"));
4955 if (err)
4956 return err;
4959 view->show = show_blame_view;
4960 view->input = input_blame_view;
4961 view->close = close_blame_view;
4962 view->search_start = search_start_blame_view;
4963 view->search_next = search_next_blame_view;
4965 return run_blame(view);
4968 static const struct got_error *
4969 close_blame_view(struct tog_view *view)
4971 const struct got_error *err = NULL;
4972 struct tog_blame_view_state *s = &view->state.blame;
4974 if (s->blame.thread)
4975 err = stop_blame(&s->blame);
4977 while (!STAILQ_EMPTY(&s->blamed_commits)) {
4978 struct got_object_qid *blamed_commit;
4979 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
4980 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
4981 got_object_qid_free(blamed_commit);
4984 free(s->path);
4985 free_colors(&s->colors);
4986 return err;
4989 static const struct got_error *
4990 search_start_blame_view(struct tog_view *view)
4992 struct tog_blame_view_state *s = &view->state.blame;
4994 s->matched_line = 0;
4995 return NULL;
4998 static const struct got_error *
4999 search_next_blame_view(struct tog_view *view)
5001 struct tog_blame_view_state *s = &view->state.blame;
5002 const struct got_error *err = NULL;
5003 int lineno;
5004 char *line = NULL;
5005 size_t linesize = 0;
5006 ssize_t linelen;
5008 if (!view->searching) {
5009 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5010 return NULL;
5013 if (s->matched_line) {
5014 if (view->searching == TOG_SEARCH_FORWARD)
5015 lineno = s->matched_line + 1;
5016 else
5017 lineno = s->matched_line - 1;
5018 } else
5019 lineno = s->first_displayed_line - 1 + s->selected_line;
5021 while (1) {
5022 off_t offset;
5024 if (lineno <= 0 || lineno > s->blame.nlines) {
5025 if (s->matched_line == 0) {
5026 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5027 break;
5030 if (view->searching == TOG_SEARCH_FORWARD)
5031 lineno = 1;
5032 else
5033 lineno = s->blame.nlines;
5036 offset = s->blame.line_offsets[lineno - 1];
5037 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5038 free(line);
5039 return got_error_from_errno("fseeko");
5041 linelen = getline(&line, &linesize, s->blame.f);
5042 if (linelen != -1) {
5043 char *exstr;
5044 err = expand_tab(&exstr, line);
5045 if (err)
5046 break;
5047 if (match_line(exstr, &view->regex, 1,
5048 &view->regmatch)) {
5049 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5050 s->matched_line = lineno;
5051 free(exstr);
5052 break;
5054 free(exstr);
5056 if (view->searching == TOG_SEARCH_FORWARD)
5057 lineno++;
5058 else
5059 lineno--;
5061 free(line);
5063 if (s->matched_line) {
5064 s->first_displayed_line = s->matched_line;
5065 s->selected_line = 1;
5068 return err;
5071 static const struct got_error *
5072 show_blame_view(struct tog_view *view)
5074 const struct got_error *err = NULL;
5075 struct tog_blame_view_state *s = &view->state.blame;
5076 int errcode;
5078 if (s->blame.thread == NULL && !s->blame_complete) {
5079 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5080 &s->blame.thread_args);
5081 if (errcode)
5082 return got_error_set_errno(errcode, "pthread_create");
5084 halfdelay(1); /* fast refresh while annotating */
5087 if (s->blame_complete)
5088 halfdelay(10); /* disable fast refresh */
5090 err = draw_blame(view);
5092 view_vborder(view);
5093 return err;
5096 static const struct got_error *
5097 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5099 const struct got_error *err = NULL, *thread_err = NULL;
5100 struct tog_view *diff_view;
5101 struct tog_blame_view_state *s = &view->state.blame;
5102 int begin_x = 0, nscroll = view->nlines - 2;
5104 switch (ch) {
5105 case '0':
5106 view->x = 0;
5107 break;
5108 case '$':
5109 view->x = MAX(view->maxx - view->ncols / 3, 0);
5110 view->count = 0;
5111 break;
5112 case KEY_RIGHT:
5113 case 'l':
5114 if (view->x + view->ncols / 3 < view->maxx)
5115 view->x += 2; /* move two columns right */
5116 else
5117 view->count = 0;
5118 break;
5119 case KEY_LEFT:
5120 case 'h':
5121 view->x -= MIN(view->x, 2); /* move two columns back */
5122 if (view->x <= 0)
5123 view->count = 0;
5124 break;
5125 case 'q':
5126 s->done = 1;
5127 break;
5128 case 'g':
5129 case KEY_HOME:
5130 s->selected_line = 1;
5131 s->first_displayed_line = 1;
5132 view->count = 0;
5133 break;
5134 case 'G':
5135 case KEY_END:
5136 if (s->blame.nlines < view->nlines - 2) {
5137 s->selected_line = s->blame.nlines;
5138 s->first_displayed_line = 1;
5139 } else {
5140 s->selected_line = view->nlines - 2;
5141 s->first_displayed_line = s->blame.nlines -
5142 (view->nlines - 3);
5144 view->count = 0;
5145 break;
5146 case 'k':
5147 case KEY_UP:
5148 case CTRL('p'):
5149 if (s->selected_line > 1)
5150 s->selected_line--;
5151 else if (s->selected_line == 1 &&
5152 s->first_displayed_line > 1)
5153 s->first_displayed_line--;
5154 else
5155 view->count = 0;
5156 break;
5157 case CTRL('u'):
5158 case 'u':
5159 nscroll /= 2;
5160 /* FALL THROUGH */
5161 case KEY_PPAGE:
5162 case CTRL('b'):
5163 case 'b':
5164 if (s->first_displayed_line == 1) {
5165 if (view->count > 1)
5166 nscroll += nscroll;
5167 s->selected_line = MAX(1, s->selected_line - nscroll);
5168 view->count = 0;
5169 break;
5171 if (s->first_displayed_line > nscroll)
5172 s->first_displayed_line -= nscroll;
5173 else
5174 s->first_displayed_line = 1;
5175 break;
5176 case 'j':
5177 case KEY_DOWN:
5178 case CTRL('n'):
5179 if (s->selected_line < view->nlines - 2 &&
5180 s->first_displayed_line +
5181 s->selected_line <= s->blame.nlines)
5182 s->selected_line++;
5183 else if (s->last_displayed_line <
5184 s->blame.nlines)
5185 s->first_displayed_line++;
5186 else
5187 view->count = 0;
5188 break;
5189 case 'c':
5190 case 'p': {
5191 struct got_object_id *id = NULL;
5193 view->count = 0;
5194 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5195 s->first_displayed_line, s->selected_line);
5196 if (id == NULL)
5197 break;
5198 if (ch == 'p') {
5199 struct got_commit_object *commit, *pcommit;
5200 struct got_object_qid *pid;
5201 struct got_object_id *blob_id = NULL;
5202 int obj_type;
5203 err = got_object_open_as_commit(&commit,
5204 s->repo, id);
5205 if (err)
5206 break;
5207 pid = STAILQ_FIRST(
5208 got_object_commit_get_parent_ids(commit));
5209 if (pid == NULL) {
5210 got_object_commit_close(commit);
5211 break;
5213 /* Check if path history ends here. */
5214 err = got_object_open_as_commit(&pcommit,
5215 s->repo, &pid->id);
5216 if (err)
5217 break;
5218 err = got_object_id_by_path(&blob_id, s->repo,
5219 pcommit, s->path);
5220 got_object_commit_close(pcommit);
5221 if (err) {
5222 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5223 err = NULL;
5224 got_object_commit_close(commit);
5225 break;
5227 err = got_object_get_type(&obj_type, s->repo,
5228 blob_id);
5229 free(blob_id);
5230 /* Can't blame non-blob type objects. */
5231 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5232 got_object_commit_close(commit);
5233 break;
5235 err = got_object_qid_alloc(&s->blamed_commit,
5236 &pid->id);
5237 got_object_commit_close(commit);
5238 } else {
5239 if (got_object_id_cmp(id,
5240 &s->blamed_commit->id) == 0)
5241 break;
5242 err = got_object_qid_alloc(&s->blamed_commit,
5243 id);
5245 if (err)
5246 break;
5247 s->done = 1;
5248 thread_err = stop_blame(&s->blame);
5249 s->done = 0;
5250 if (thread_err)
5251 break;
5252 STAILQ_INSERT_HEAD(&s->blamed_commits,
5253 s->blamed_commit, entry);
5254 err = run_blame(view);
5255 if (err)
5256 break;
5257 break;
5259 case 'C': {
5260 struct got_object_qid *first;
5262 view->count = 0;
5263 first = STAILQ_FIRST(&s->blamed_commits);
5264 if (!got_object_id_cmp(&first->id, s->commit_id))
5265 break;
5266 s->done = 1;
5267 thread_err = stop_blame(&s->blame);
5268 s->done = 0;
5269 if (thread_err)
5270 break;
5271 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5272 got_object_qid_free(s->blamed_commit);
5273 s->blamed_commit =
5274 STAILQ_FIRST(&s->blamed_commits);
5275 err = run_blame(view);
5276 if (err)
5277 break;
5278 break;
5280 case KEY_ENTER:
5281 case '\r': {
5282 struct got_object_id *id = NULL;
5283 struct got_object_qid *pid;
5284 struct got_commit_object *commit = NULL;
5286 view->count = 0;
5287 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5288 s->first_displayed_line, s->selected_line);
5289 if (id == NULL)
5290 break;
5291 err = got_object_open_as_commit(&commit, s->repo, id);
5292 if (err)
5293 break;
5294 pid = STAILQ_FIRST(
5295 got_object_commit_get_parent_ids(commit));
5296 if (view_is_parent_view(view))
5297 begin_x = view_split_begin_x(view->begin_x);
5298 diff_view = view_open(0, 0, 0, begin_x, TOG_VIEW_DIFF);
5299 if (diff_view == NULL) {
5300 got_object_commit_close(commit);
5301 err = got_error_from_errno("view_open");
5302 break;
5304 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5305 id, NULL, NULL, 3, 0, 0, NULL, s->repo);
5306 got_object_commit_close(commit);
5307 if (err) {
5308 view_close(diff_view);
5309 break;
5311 view->focussed = 0;
5312 diff_view->focussed = 1;
5313 if (view_is_parent_view(view)) {
5314 err = view_close_child(view);
5315 if (err)
5316 break;
5317 err = view_set_child(view, diff_view);
5318 if (err)
5319 break;
5320 view->focus_child = 1;
5321 } else
5322 *new_view = diff_view;
5323 if (err)
5324 break;
5325 break;
5327 case CTRL('d'):
5328 case 'd':
5329 nscroll /= 2;
5330 /* FALL THROUGH */
5331 case KEY_NPAGE:
5332 case CTRL('f'):
5333 case 'f':
5334 case ' ':
5335 if (s->last_displayed_line >= s->blame.nlines &&
5336 s->selected_line >= MIN(s->blame.nlines,
5337 view->nlines - 2)) {
5338 view->count = 0;
5339 break;
5341 if (s->last_displayed_line >= s->blame.nlines &&
5342 s->selected_line < view->nlines - 2) {
5343 s->selected_line +=
5344 MIN(nscroll, s->last_displayed_line -
5345 s->first_displayed_line - s->selected_line + 1);
5347 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5348 s->first_displayed_line += nscroll;
5349 else
5350 s->first_displayed_line =
5351 s->blame.nlines - (view->nlines - 3);
5352 break;
5353 case KEY_RESIZE:
5354 if (s->selected_line > view->nlines - 2) {
5355 s->selected_line = MIN(s->blame.nlines,
5356 view->nlines - 2);
5358 break;
5359 default:
5360 view->count = 0;
5361 break;
5363 return thread_err ? thread_err : err;
5366 static const struct got_error *
5367 cmd_blame(int argc, char *argv[])
5369 const struct got_error *error;
5370 struct got_repository *repo = NULL;
5371 struct got_worktree *worktree = NULL;
5372 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5373 char *link_target = NULL;
5374 struct got_object_id *commit_id = NULL;
5375 struct got_commit_object *commit = NULL;
5376 char *commit_id_str = NULL;
5377 int ch;
5378 struct tog_view *view;
5379 int *pack_fds = NULL;
5381 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5382 switch (ch) {
5383 case 'c':
5384 commit_id_str = optarg;
5385 break;
5386 case 'r':
5387 repo_path = realpath(optarg, NULL);
5388 if (repo_path == NULL)
5389 return got_error_from_errno2("realpath",
5390 optarg);
5391 break;
5392 default:
5393 usage_blame();
5394 /* NOTREACHED */
5398 argc -= optind;
5399 argv += optind;
5401 if (argc != 1)
5402 usage_blame();
5404 error = got_repo_pack_fds_open(&pack_fds);
5405 if (error != NULL)
5406 goto done;
5408 if (repo_path == NULL) {
5409 cwd = getcwd(NULL, 0);
5410 if (cwd == NULL)
5411 return got_error_from_errno("getcwd");
5412 error = got_worktree_open(&worktree, cwd);
5413 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5414 goto done;
5415 if (worktree)
5416 repo_path =
5417 strdup(got_worktree_get_repo_path(worktree));
5418 else
5419 repo_path = strdup(cwd);
5420 if (repo_path == NULL) {
5421 error = got_error_from_errno("strdup");
5422 goto done;
5426 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5427 if (error != NULL)
5428 goto done;
5430 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
5431 worktree);
5432 if (error)
5433 goto done;
5435 init_curses();
5437 error = apply_unveil(got_repo_get_path(repo), NULL);
5438 if (error)
5439 goto done;
5441 error = tog_load_refs(repo, 0);
5442 if (error)
5443 goto done;
5445 if (commit_id_str == NULL) {
5446 struct got_reference *head_ref;
5447 error = got_ref_open(&head_ref, repo, worktree ?
5448 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5449 if (error != NULL)
5450 goto done;
5451 error = got_ref_resolve(&commit_id, repo, head_ref);
5452 got_ref_close(head_ref);
5453 } else {
5454 error = got_repo_match_object_id(&commit_id, NULL,
5455 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
5457 if (error != NULL)
5458 goto done;
5460 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
5461 if (view == NULL) {
5462 error = got_error_from_errno("view_open");
5463 goto done;
5466 error = got_object_open_as_commit(&commit, repo, commit_id);
5467 if (error)
5468 goto done;
5470 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5471 commit, repo);
5472 if (error)
5473 goto done;
5475 error = open_blame_view(view, link_target ? link_target : in_repo_path,
5476 commit_id, repo);
5477 if (error)
5478 goto done;
5479 if (worktree) {
5480 /* Release work tree lock. */
5481 got_worktree_close(worktree);
5482 worktree = NULL;
5484 error = view_loop(view);
5485 done:
5486 free(repo_path);
5487 free(in_repo_path);
5488 free(link_target);
5489 free(cwd);
5490 free(commit_id);
5491 if (commit)
5492 got_object_commit_close(commit);
5493 if (worktree)
5494 got_worktree_close(worktree);
5495 if (repo) {
5496 const struct got_error *close_err = got_repo_close(repo);
5497 if (error == NULL)
5498 error = close_err;
5500 if (pack_fds) {
5501 const struct got_error *pack_err =
5502 got_repo_pack_fds_close(pack_fds);
5503 if (error == NULL)
5504 error = pack_err;
5506 tog_free_refs();
5507 return error;
5510 static const struct got_error *
5511 draw_tree_entries(struct tog_view *view, const char *parent_path)
5513 struct tog_tree_view_state *s = &view->state.tree;
5514 const struct got_error *err = NULL;
5515 struct got_tree_entry *te;
5516 wchar_t *wline;
5517 struct tog_color *tc;
5518 int width, n, i, nentries;
5519 int limit = view->nlines;
5521 s->ndisplayed = 0;
5523 werase(view->window);
5525 if (limit == 0)
5526 return NULL;
5528 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
5529 0, 0);
5530 if (err)
5531 return err;
5532 if (view_needs_focus_indication(view))
5533 wstandout(view->window);
5534 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5535 if (tc)
5536 wattr_on(view->window,
5537 COLOR_PAIR(tc->colorpair), NULL);
5538 waddwstr(view->window, wline);
5539 if (tc)
5540 wattr_off(view->window,
5541 COLOR_PAIR(tc->colorpair), NULL);
5542 if (view_needs_focus_indication(view))
5543 wstandend(view->window);
5544 free(wline);
5545 wline = NULL;
5546 if (width < view->ncols - 1)
5547 waddch(view->window, '\n');
5548 if (--limit <= 0)
5549 return NULL;
5550 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
5551 0, 0);
5552 if (err)
5553 return err;
5554 waddwstr(view->window, wline);
5555 free(wline);
5556 wline = NULL;
5557 if (width < view->ncols - 1)
5558 waddch(view->window, '\n');
5559 if (--limit <= 0)
5560 return NULL;
5561 waddch(view->window, '\n');
5562 if (--limit <= 0)
5563 return NULL;
5565 if (s->first_displayed_entry == NULL) {
5566 te = got_object_tree_get_first_entry(s->tree);
5567 if (s->selected == 0) {
5568 if (view->focussed)
5569 wstandout(view->window);
5570 s->selected_entry = NULL;
5572 waddstr(view->window, " ..\n"); /* parent directory */
5573 if (s->selected == 0 && view->focussed)
5574 wstandend(view->window);
5575 s->ndisplayed++;
5576 if (--limit <= 0)
5577 return NULL;
5578 n = 1;
5579 } else {
5580 n = 0;
5581 te = s->first_displayed_entry;
5584 nentries = got_object_tree_get_nentries(s->tree);
5585 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
5586 char *line = NULL, *id_str = NULL, *link_target = NULL;
5587 const char *modestr = "";
5588 mode_t mode;
5590 te = got_object_tree_get_entry(s->tree, i);
5591 mode = got_tree_entry_get_mode(te);
5593 if (s->show_ids) {
5594 err = got_object_id_str(&id_str,
5595 got_tree_entry_get_id(te));
5596 if (err)
5597 return got_error_from_errno(
5598 "got_object_id_str");
5600 if (got_object_tree_entry_is_submodule(te))
5601 modestr = "$";
5602 else if (S_ISLNK(mode)) {
5603 int i;
5605 err = got_tree_entry_get_symlink_target(&link_target,
5606 te, s->repo);
5607 if (err) {
5608 free(id_str);
5609 return err;
5611 for (i = 0; i < strlen(link_target); i++) {
5612 if (!isprint((unsigned char)link_target[i]))
5613 link_target[i] = '?';
5615 modestr = "@";
5617 else if (S_ISDIR(mode))
5618 modestr = "/";
5619 else if (mode & S_IXUSR)
5620 modestr = "*";
5621 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
5622 got_tree_entry_get_name(te), modestr,
5623 link_target ? " -> ": "",
5624 link_target ? link_target : "") == -1) {
5625 free(id_str);
5626 free(link_target);
5627 return got_error_from_errno("asprintf");
5629 free(id_str);
5630 free(link_target);
5631 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
5632 0, 0);
5633 if (err) {
5634 free(line);
5635 break;
5637 if (n == s->selected) {
5638 if (view->focussed)
5639 wstandout(view->window);
5640 s->selected_entry = te;
5642 tc = match_color(&s->colors, line);
5643 if (tc)
5644 wattr_on(view->window,
5645 COLOR_PAIR(tc->colorpair), NULL);
5646 waddwstr(view->window, wline);
5647 if (tc)
5648 wattr_off(view->window,
5649 COLOR_PAIR(tc->colorpair), NULL);
5650 if (width < view->ncols - 1)
5651 waddch(view->window, '\n');
5652 if (n == s->selected && view->focussed)
5653 wstandend(view->window);
5654 free(line);
5655 free(wline);
5656 wline = NULL;
5657 n++;
5658 s->ndisplayed++;
5659 s->last_displayed_entry = te;
5660 if (--limit <= 0)
5661 break;
5664 return err;
5667 static void
5668 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
5670 struct got_tree_entry *te;
5671 int isroot = s->tree == s->root;
5672 int i = 0;
5674 if (s->first_displayed_entry == NULL)
5675 return;
5677 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
5678 while (i++ < maxscroll) {
5679 if (te == NULL) {
5680 if (!isroot)
5681 s->first_displayed_entry = NULL;
5682 break;
5684 s->first_displayed_entry = te;
5685 te = got_tree_entry_get_prev(s->tree, te);
5689 static void
5690 tree_scroll_down(struct tog_tree_view_state *s, int maxscroll)
5692 struct got_tree_entry *next, *last;
5693 int n = 0;
5695 if (s->first_displayed_entry)
5696 next = got_tree_entry_get_next(s->tree,
5697 s->first_displayed_entry);
5698 else
5699 next = got_object_tree_get_first_entry(s->tree);
5701 last = s->last_displayed_entry;
5702 while (next && last && n++ < maxscroll) {
5703 last = got_tree_entry_get_next(s->tree, last);
5704 if (last) {
5705 s->first_displayed_entry = next;
5706 next = got_tree_entry_get_next(s->tree, next);
5711 static const struct got_error *
5712 tree_entry_path(char **path, struct tog_parent_trees *parents,
5713 struct got_tree_entry *te)
5715 const struct got_error *err = NULL;
5716 struct tog_parent_tree *pt;
5717 size_t len = 2; /* for leading slash and NUL */
5719 TAILQ_FOREACH(pt, parents, entry)
5720 len += strlen(got_tree_entry_get_name(pt->selected_entry))
5721 + 1 /* slash */;
5722 if (te)
5723 len += strlen(got_tree_entry_get_name(te));
5725 *path = calloc(1, len);
5726 if (path == NULL)
5727 return got_error_from_errno("calloc");
5729 (*path)[0] = '/';
5730 pt = TAILQ_LAST(parents, tog_parent_trees);
5731 while (pt) {
5732 const char *name = got_tree_entry_get_name(pt->selected_entry);
5733 if (strlcat(*path, name, len) >= len) {
5734 err = got_error(GOT_ERR_NO_SPACE);
5735 goto done;
5737 if (strlcat(*path, "/", len) >= len) {
5738 err = got_error(GOT_ERR_NO_SPACE);
5739 goto done;
5741 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
5743 if (te) {
5744 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
5745 err = got_error(GOT_ERR_NO_SPACE);
5746 goto done;
5749 done:
5750 if (err) {
5751 free(*path);
5752 *path = NULL;
5754 return err;
5757 static const struct got_error *
5758 blame_tree_entry(struct tog_view **new_view, int begin_x,
5759 struct got_tree_entry *te, struct tog_parent_trees *parents,
5760 struct got_object_id *commit_id, struct got_repository *repo)
5762 const struct got_error *err = NULL;
5763 char *path;
5764 struct tog_view *blame_view;
5766 *new_view = NULL;
5768 err = tree_entry_path(&path, parents, te);
5769 if (err)
5770 return err;
5772 blame_view = view_open(0, 0, 0, begin_x, TOG_VIEW_BLAME);
5773 if (blame_view == NULL) {
5774 err = got_error_from_errno("view_open");
5775 goto done;
5778 err = open_blame_view(blame_view, path, commit_id, repo);
5779 if (err) {
5780 if (err->code == GOT_ERR_CANCELLED)
5781 err = NULL;
5782 view_close(blame_view);
5783 } else
5784 *new_view = blame_view;
5785 done:
5786 free(path);
5787 return err;
5790 static const struct got_error *
5791 log_selected_tree_entry(struct tog_view **new_view, int begin_x,
5792 struct tog_tree_view_state *s)
5794 struct tog_view *log_view;
5795 const struct got_error *err = NULL;
5796 char *path;
5798 *new_view = NULL;
5800 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
5801 if (log_view == NULL)
5802 return got_error_from_errno("view_open");
5804 err = tree_entry_path(&path, &s->parents, s->selected_entry);
5805 if (err)
5806 return err;
5808 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
5809 path, 0);
5810 if (err)
5811 view_close(log_view);
5812 else
5813 *new_view = log_view;
5814 free(path);
5815 return err;
5818 static const struct got_error *
5819 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
5820 const char *head_ref_name, struct got_repository *repo)
5822 const struct got_error *err = NULL;
5823 char *commit_id_str = NULL;
5824 struct tog_tree_view_state *s = &view->state.tree;
5825 struct got_commit_object *commit = NULL;
5827 TAILQ_INIT(&s->parents);
5828 STAILQ_INIT(&s->colors);
5830 s->commit_id = got_object_id_dup(commit_id);
5831 if (s->commit_id == NULL)
5832 return got_error_from_errno("got_object_id_dup");
5834 err = got_object_open_as_commit(&commit, repo, commit_id);
5835 if (err)
5836 goto done;
5839 * The root is opened here and will be closed when the view is closed.
5840 * Any visited subtrees and their path-wise parents are opened and
5841 * closed on demand.
5843 err = got_object_open_as_tree(&s->root, repo,
5844 got_object_commit_get_tree_id(commit));
5845 if (err)
5846 goto done;
5847 s->tree = s->root;
5849 err = got_object_id_str(&commit_id_str, commit_id);
5850 if (err != NULL)
5851 goto done;
5853 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
5854 err = got_error_from_errno("asprintf");
5855 goto done;
5858 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
5859 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
5860 if (head_ref_name) {
5861 s->head_ref_name = strdup(head_ref_name);
5862 if (s->head_ref_name == NULL) {
5863 err = got_error_from_errno("strdup");
5864 goto done;
5867 s->repo = repo;
5869 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5870 err = add_color(&s->colors, "\\$$",
5871 TOG_COLOR_TREE_SUBMODULE,
5872 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
5873 if (err)
5874 goto done;
5875 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
5876 get_color_value("TOG_COLOR_TREE_SYMLINK"));
5877 if (err)
5878 goto done;
5879 err = add_color(&s->colors, "/$",
5880 TOG_COLOR_TREE_DIRECTORY,
5881 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
5882 if (err)
5883 goto done;
5885 err = add_color(&s->colors, "\\*$",
5886 TOG_COLOR_TREE_EXECUTABLE,
5887 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
5888 if (err)
5889 goto done;
5891 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
5892 get_color_value("TOG_COLOR_COMMIT"));
5893 if (err)
5894 goto done;
5897 view->show = show_tree_view;
5898 view->input = input_tree_view;
5899 view->close = close_tree_view;
5900 view->search_start = search_start_tree_view;
5901 view->search_next = search_next_tree_view;
5902 done:
5903 free(commit_id_str);
5904 if (commit)
5905 got_object_commit_close(commit);
5906 if (err)
5907 close_tree_view(view);
5908 return err;
5911 static const struct got_error *
5912 close_tree_view(struct tog_view *view)
5914 struct tog_tree_view_state *s = &view->state.tree;
5916 free_colors(&s->colors);
5917 free(s->tree_label);
5918 s->tree_label = NULL;
5919 free(s->commit_id);
5920 s->commit_id = NULL;
5921 free(s->head_ref_name);
5922 s->head_ref_name = NULL;
5923 while (!TAILQ_EMPTY(&s->parents)) {
5924 struct tog_parent_tree *parent;
5925 parent = TAILQ_FIRST(&s->parents);
5926 TAILQ_REMOVE(&s->parents, parent, entry);
5927 if (parent->tree != s->root)
5928 got_object_tree_close(parent->tree);
5929 free(parent);
5932 if (s->tree != NULL && s->tree != s->root)
5933 got_object_tree_close(s->tree);
5934 if (s->root)
5935 got_object_tree_close(s->root);
5936 return NULL;
5939 static const struct got_error *
5940 search_start_tree_view(struct tog_view *view)
5942 struct tog_tree_view_state *s = &view->state.tree;
5944 s->matched_entry = NULL;
5945 return NULL;
5948 static int
5949 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
5951 regmatch_t regmatch;
5953 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
5954 0) == 0;
5957 static const struct got_error *
5958 search_next_tree_view(struct tog_view *view)
5960 struct tog_tree_view_state *s = &view->state.tree;
5961 struct got_tree_entry *te = NULL;
5963 if (!view->searching) {
5964 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5965 return NULL;
5968 if (s->matched_entry) {
5969 if (view->searching == TOG_SEARCH_FORWARD) {
5970 if (s->selected_entry)
5971 te = got_tree_entry_get_next(s->tree,
5972 s->selected_entry);
5973 else
5974 te = got_object_tree_get_first_entry(s->tree);
5975 } else {
5976 if (s->selected_entry == NULL)
5977 te = got_object_tree_get_last_entry(s->tree);
5978 else
5979 te = got_tree_entry_get_prev(s->tree,
5980 s->selected_entry);
5982 } else {
5983 if (s->selected_entry)
5984 te = s->selected_entry;
5985 else if (view->searching == TOG_SEARCH_FORWARD)
5986 te = got_object_tree_get_first_entry(s->tree);
5987 else
5988 te = got_object_tree_get_last_entry(s->tree);
5991 while (1) {
5992 if (te == NULL) {
5993 if (s->matched_entry == NULL) {
5994 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5995 return NULL;
5997 if (view->searching == TOG_SEARCH_FORWARD)
5998 te = got_object_tree_get_first_entry(s->tree);
5999 else
6000 te = got_object_tree_get_last_entry(s->tree);
6003 if (match_tree_entry(te, &view->regex)) {
6004 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6005 s->matched_entry = te;
6006 break;
6009 if (view->searching == TOG_SEARCH_FORWARD)
6010 te = got_tree_entry_get_next(s->tree, te);
6011 else
6012 te = got_tree_entry_get_prev(s->tree, te);
6015 if (s->matched_entry) {
6016 s->first_displayed_entry = s->matched_entry;
6017 s->selected = 0;
6020 return NULL;
6023 static const struct got_error *
6024 show_tree_view(struct tog_view *view)
6026 const struct got_error *err = NULL;
6027 struct tog_tree_view_state *s = &view->state.tree;
6028 char *parent_path;
6030 err = tree_entry_path(&parent_path, &s->parents, NULL);
6031 if (err)
6032 return err;
6034 err = draw_tree_entries(view, parent_path);
6035 free(parent_path);
6037 view_vborder(view);
6038 return err;
6041 static const struct got_error *
6042 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6044 const struct got_error *err = NULL;
6045 struct tog_tree_view_state *s = &view->state.tree;
6046 struct tog_view *log_view, *ref_view;
6047 struct got_tree_entry *te;
6048 int begin_x = 0, n, nscroll = view->nlines - 3;
6050 switch (ch) {
6051 case 'i':
6052 s->show_ids = !s->show_ids;
6053 view->count = 0;
6054 break;
6055 case 'l':
6056 view->count = 0;
6057 if (!s->selected_entry)
6058 break;
6059 if (view_is_parent_view(view))
6060 begin_x = view_split_begin_x(view->begin_x);
6061 err = log_selected_tree_entry(&log_view, begin_x, s);
6062 view->focussed = 0;
6063 log_view->focussed = 1;
6064 if (view_is_parent_view(view)) {
6065 err = view_close_child(view);
6066 if (err)
6067 return err;
6068 err = view_set_child(view, log_view);
6069 if (err)
6070 return err;
6071 view->focus_child = 1;
6072 } else
6073 *new_view = log_view;
6074 break;
6075 case 'r':
6076 view->count = 0;
6077 if (view_is_parent_view(view))
6078 begin_x = view_split_begin_x(view->begin_x);
6079 ref_view = view_open(view->nlines, view->ncols,
6080 view->begin_y, begin_x, TOG_VIEW_REF);
6081 if (ref_view == NULL)
6082 return got_error_from_errno("view_open");
6083 err = open_ref_view(ref_view, s->repo);
6084 if (err) {
6085 view_close(ref_view);
6086 return err;
6088 view->focussed = 0;
6089 ref_view->focussed = 1;
6090 if (view_is_parent_view(view)) {
6091 err = view_close_child(view);
6092 if (err)
6093 return err;
6094 err = view_set_child(view, ref_view);
6095 if (err)
6096 return err;
6097 view->focus_child = 1;
6098 } else
6099 *new_view = ref_view;
6100 break;
6101 case 'g':
6102 case KEY_HOME:
6103 s->selected = 0;
6104 view->count = 0;
6105 if (s->tree == s->root)
6106 s->first_displayed_entry =
6107 got_object_tree_get_first_entry(s->tree);
6108 else
6109 s->first_displayed_entry = NULL;
6110 break;
6111 case 'G':
6112 case KEY_END:
6113 s->selected = 0;
6114 view->count = 0;
6115 te = got_object_tree_get_last_entry(s->tree);
6116 for (n = 0; n < view->nlines - 3; n++) {
6117 if (te == NULL) {
6118 if(s->tree != s->root) {
6119 s->first_displayed_entry = NULL;
6120 n++;
6122 break;
6124 s->first_displayed_entry = te;
6125 te = got_tree_entry_get_prev(s->tree, te);
6127 if (n > 0)
6128 s->selected = n - 1;
6129 break;
6130 case 'k':
6131 case KEY_UP:
6132 case CTRL('p'):
6133 if (s->selected > 0) {
6134 s->selected--;
6135 break;
6137 tree_scroll_up(s, 1);
6138 if (s->selected_entry == NULL ||
6139 (s->tree == s->root && s->selected_entry ==
6140 got_object_tree_get_first_entry(s->tree)))
6141 view->count = 0;
6142 break;
6143 case CTRL('u'):
6144 case 'u':
6145 nscroll /= 2;
6146 /* FALL THROUGH */
6147 case KEY_PPAGE:
6148 case CTRL('b'):
6149 case 'b':
6150 if (s->tree == s->root) {
6151 if (got_object_tree_get_first_entry(s->tree) ==
6152 s->first_displayed_entry)
6153 s->selected -= MIN(s->selected, nscroll);
6154 } else {
6155 if (s->first_displayed_entry == NULL)
6156 s->selected -= MIN(s->selected, nscroll);
6158 tree_scroll_up(s, MAX(0, nscroll));
6159 if (s->selected_entry == NULL ||
6160 (s->tree == s->root && s->selected_entry ==
6161 got_object_tree_get_first_entry(s->tree)))
6162 view->count = 0;
6163 break;
6164 case 'j':
6165 case KEY_DOWN:
6166 case CTRL('n'):
6167 if (s->selected < s->ndisplayed - 1) {
6168 s->selected++;
6169 break;
6171 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6172 == NULL) {
6173 /* can't scroll any further */
6174 view->count = 0;
6175 break;
6177 tree_scroll_down(s, 1);
6178 break;
6179 case CTRL('d'):
6180 case 'd':
6181 nscroll /= 2;
6182 /* FALL THROUGH */
6183 case KEY_NPAGE:
6184 case CTRL('f'):
6185 case 'f':
6186 case ' ':
6187 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6188 == NULL) {
6189 /* can't scroll any further; move cursor down */
6190 if (s->selected < s->ndisplayed - 1)
6191 s->selected += MIN(nscroll,
6192 s->ndisplayed - s->selected - 1);
6193 else
6194 view->count = 0;
6195 break;
6197 tree_scroll_down(s, nscroll);
6198 break;
6199 case KEY_ENTER:
6200 case '\r':
6201 case KEY_BACKSPACE:
6202 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6203 struct tog_parent_tree *parent;
6204 /* user selected '..' */
6205 if (s->tree == s->root) {
6206 view->count = 0;
6207 break;
6209 parent = TAILQ_FIRST(&s->parents);
6210 TAILQ_REMOVE(&s->parents, parent,
6211 entry);
6212 got_object_tree_close(s->tree);
6213 s->tree = parent->tree;
6214 s->first_displayed_entry =
6215 parent->first_displayed_entry;
6216 s->selected_entry =
6217 parent->selected_entry;
6218 s->selected = parent->selected;
6219 free(parent);
6220 } else if (S_ISDIR(got_tree_entry_get_mode(
6221 s->selected_entry))) {
6222 struct got_tree_object *subtree;
6223 view->count = 0;
6224 err = got_object_open_as_tree(&subtree, s->repo,
6225 got_tree_entry_get_id(s->selected_entry));
6226 if (err)
6227 break;
6228 err = tree_view_visit_subtree(s, subtree);
6229 if (err) {
6230 got_object_tree_close(subtree);
6231 break;
6233 } else if (S_ISREG(got_tree_entry_get_mode(
6234 s->selected_entry))) {
6235 struct tog_view *blame_view;
6236 int begin_x = view_is_parent_view(view) ?
6237 view_split_begin_x(view->begin_x) : 0;
6239 err = blame_tree_entry(&blame_view, begin_x,
6240 s->selected_entry, &s->parents,
6241 s->commit_id, s->repo);
6242 if (err)
6243 break;
6244 view->count = 0;
6245 view->focussed = 0;
6246 blame_view->focussed = 1;
6247 if (view_is_parent_view(view)) {
6248 err = view_close_child(view);
6249 if (err)
6250 return err;
6251 err = view_set_child(view, blame_view);
6252 if (err)
6253 return err;
6254 view->focus_child = 1;
6255 } else
6256 *new_view = blame_view;
6258 break;
6259 case KEY_RESIZE:
6260 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6261 s->selected = view->nlines - 4;
6262 view->count = 0;
6263 break;
6264 default:
6265 view->count = 0;
6266 break;
6269 return err;
6272 __dead static void
6273 usage_tree(void)
6275 endwin();
6276 fprintf(stderr,
6277 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6278 getprogname());
6279 exit(1);
6282 static const struct got_error *
6283 cmd_tree(int argc, char *argv[])
6285 const struct got_error *error;
6286 struct got_repository *repo = NULL;
6287 struct got_worktree *worktree = NULL;
6288 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6289 struct got_object_id *commit_id = NULL;
6290 struct got_commit_object *commit = NULL;
6291 const char *commit_id_arg = NULL;
6292 char *label = NULL;
6293 struct got_reference *ref = NULL;
6294 const char *head_ref_name = NULL;
6295 int ch;
6296 struct tog_view *view;
6297 int *pack_fds = NULL;
6299 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6300 switch (ch) {
6301 case 'c':
6302 commit_id_arg = optarg;
6303 break;
6304 case 'r':
6305 repo_path = realpath(optarg, NULL);
6306 if (repo_path == NULL)
6307 return got_error_from_errno2("realpath",
6308 optarg);
6309 break;
6310 default:
6311 usage_tree();
6312 /* NOTREACHED */
6316 argc -= optind;
6317 argv += optind;
6319 if (argc > 1)
6320 usage_tree();
6322 error = got_repo_pack_fds_open(&pack_fds);
6323 if (error != NULL)
6324 goto done;
6326 if (repo_path == NULL) {
6327 cwd = getcwd(NULL, 0);
6328 if (cwd == NULL)
6329 return got_error_from_errno("getcwd");
6330 error = got_worktree_open(&worktree, cwd);
6331 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6332 goto done;
6333 if (worktree)
6334 repo_path =
6335 strdup(got_worktree_get_repo_path(worktree));
6336 else
6337 repo_path = strdup(cwd);
6338 if (repo_path == NULL) {
6339 error = got_error_from_errno("strdup");
6340 goto done;
6344 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6345 if (error != NULL)
6346 goto done;
6348 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
6349 repo, worktree);
6350 if (error)
6351 goto done;
6353 init_curses();
6355 error = apply_unveil(got_repo_get_path(repo), NULL);
6356 if (error)
6357 goto done;
6359 error = tog_load_refs(repo, 0);
6360 if (error)
6361 goto done;
6363 if (commit_id_arg == NULL) {
6364 error = got_repo_match_object_id(&commit_id, &label,
6365 worktree ? got_worktree_get_head_ref_name(worktree) :
6366 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6367 if (error)
6368 goto done;
6369 head_ref_name = label;
6370 } else {
6371 error = got_ref_open(&ref, repo, commit_id_arg, 0);
6372 if (error == NULL)
6373 head_ref_name = got_ref_get_name(ref);
6374 else if (error->code != GOT_ERR_NOT_REF)
6375 goto done;
6376 error = got_repo_match_object_id(&commit_id, NULL,
6377 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6378 if (error)
6379 goto done;
6382 error = got_object_open_as_commit(&commit, repo, commit_id);
6383 if (error)
6384 goto done;
6386 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
6387 if (view == NULL) {
6388 error = got_error_from_errno("view_open");
6389 goto done;
6391 error = open_tree_view(view, commit_id, head_ref_name, repo);
6392 if (error)
6393 goto done;
6394 if (!got_path_is_root_dir(in_repo_path)) {
6395 error = tree_view_walk_path(&view->state.tree, commit,
6396 in_repo_path);
6397 if (error)
6398 goto done;
6401 if (worktree) {
6402 /* Release work tree lock. */
6403 got_worktree_close(worktree);
6404 worktree = NULL;
6406 error = view_loop(view);
6407 done:
6408 free(repo_path);
6409 free(cwd);
6410 free(commit_id);
6411 free(label);
6412 if (ref)
6413 got_ref_close(ref);
6414 if (repo) {
6415 const struct got_error *close_err = got_repo_close(repo);
6416 if (error == NULL)
6417 error = close_err;
6419 if (pack_fds) {
6420 const struct got_error *pack_err =
6421 got_repo_pack_fds_close(pack_fds);
6422 if (error == NULL)
6423 error = pack_err;
6425 tog_free_refs();
6426 return error;
6429 static const struct got_error *
6430 ref_view_load_refs(struct tog_ref_view_state *s)
6432 struct got_reflist_entry *sre;
6433 struct tog_reflist_entry *re;
6435 s->nrefs = 0;
6436 TAILQ_FOREACH(sre, &tog_refs, entry) {
6437 if (strncmp(got_ref_get_name(sre->ref),
6438 "refs/got/", 9) == 0 &&
6439 strncmp(got_ref_get_name(sre->ref),
6440 "refs/got/backup/", 16) != 0)
6441 continue;
6443 re = malloc(sizeof(*re));
6444 if (re == NULL)
6445 return got_error_from_errno("malloc");
6447 re->ref = got_ref_dup(sre->ref);
6448 if (re->ref == NULL)
6449 return got_error_from_errno("got_ref_dup");
6450 re->idx = s->nrefs++;
6451 TAILQ_INSERT_TAIL(&s->refs, re, entry);
6454 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6455 return NULL;
6458 static void
6459 ref_view_free_refs(struct tog_ref_view_state *s)
6461 struct tog_reflist_entry *re;
6463 while (!TAILQ_EMPTY(&s->refs)) {
6464 re = TAILQ_FIRST(&s->refs);
6465 TAILQ_REMOVE(&s->refs, re, entry);
6466 got_ref_close(re->ref);
6467 free(re);
6471 static const struct got_error *
6472 open_ref_view(struct tog_view *view, struct got_repository *repo)
6474 const struct got_error *err = NULL;
6475 struct tog_ref_view_state *s = &view->state.ref;
6477 s->selected_entry = 0;
6478 s->repo = repo;
6480 TAILQ_INIT(&s->refs);
6481 STAILQ_INIT(&s->colors);
6483 err = ref_view_load_refs(s);
6484 if (err)
6485 return err;
6487 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6488 err = add_color(&s->colors, "^refs/heads/",
6489 TOG_COLOR_REFS_HEADS,
6490 get_color_value("TOG_COLOR_REFS_HEADS"));
6491 if (err)
6492 goto done;
6494 err = add_color(&s->colors, "^refs/tags/",
6495 TOG_COLOR_REFS_TAGS,
6496 get_color_value("TOG_COLOR_REFS_TAGS"));
6497 if (err)
6498 goto done;
6500 err = add_color(&s->colors, "^refs/remotes/",
6501 TOG_COLOR_REFS_REMOTES,
6502 get_color_value("TOG_COLOR_REFS_REMOTES"));
6503 if (err)
6504 goto done;
6506 err = add_color(&s->colors, "^refs/got/backup/",
6507 TOG_COLOR_REFS_BACKUP,
6508 get_color_value("TOG_COLOR_REFS_BACKUP"));
6509 if (err)
6510 goto done;
6513 view->show = show_ref_view;
6514 view->input = input_ref_view;
6515 view->close = close_ref_view;
6516 view->search_start = search_start_ref_view;
6517 view->search_next = search_next_ref_view;
6518 done:
6519 if (err)
6520 free_colors(&s->colors);
6521 return err;
6524 static const struct got_error *
6525 close_ref_view(struct tog_view *view)
6527 struct tog_ref_view_state *s = &view->state.ref;
6529 ref_view_free_refs(s);
6530 free_colors(&s->colors);
6532 return NULL;
6535 static const struct got_error *
6536 resolve_reflist_entry(struct got_object_id **commit_id,
6537 struct tog_reflist_entry *re, struct got_repository *repo)
6539 const struct got_error *err = NULL;
6540 struct got_object_id *obj_id;
6541 struct got_tag_object *tag = NULL;
6542 int obj_type;
6544 *commit_id = NULL;
6546 err = got_ref_resolve(&obj_id, repo, re->ref);
6547 if (err)
6548 return err;
6550 err = got_object_get_type(&obj_type, repo, obj_id);
6551 if (err)
6552 goto done;
6554 switch (obj_type) {
6555 case GOT_OBJ_TYPE_COMMIT:
6556 *commit_id = obj_id;
6557 break;
6558 case GOT_OBJ_TYPE_TAG:
6559 err = got_object_open_as_tag(&tag, repo, obj_id);
6560 if (err)
6561 goto done;
6562 free(obj_id);
6563 err = got_object_get_type(&obj_type, repo,
6564 got_object_tag_get_object_id(tag));
6565 if (err)
6566 goto done;
6567 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
6568 err = got_error(GOT_ERR_OBJ_TYPE);
6569 goto done;
6571 *commit_id = got_object_id_dup(
6572 got_object_tag_get_object_id(tag));
6573 if (*commit_id == NULL) {
6574 err = got_error_from_errno("got_object_id_dup");
6575 goto done;
6577 break;
6578 default:
6579 err = got_error(GOT_ERR_OBJ_TYPE);
6580 break;
6583 done:
6584 if (tag)
6585 got_object_tag_close(tag);
6586 if (err) {
6587 free(*commit_id);
6588 *commit_id = NULL;
6590 return err;
6593 static const struct got_error *
6594 log_ref_entry(struct tog_view **new_view, int begin_x,
6595 struct tog_reflist_entry *re, struct got_repository *repo)
6597 struct tog_view *log_view;
6598 const struct got_error *err = NULL;
6599 struct got_object_id *commit_id = NULL;
6601 *new_view = NULL;
6603 err = resolve_reflist_entry(&commit_id, re, repo);
6604 if (err) {
6605 if (err->code != GOT_ERR_OBJ_TYPE)
6606 return err;
6607 else
6608 return NULL;
6611 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
6612 if (log_view == NULL) {
6613 err = got_error_from_errno("view_open");
6614 goto done;
6617 err = open_log_view(log_view, commit_id, repo,
6618 got_ref_get_name(re->ref), "", 0);
6619 done:
6620 if (err)
6621 view_close(log_view);
6622 else
6623 *new_view = log_view;
6624 free(commit_id);
6625 return err;
6628 static void
6629 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
6631 struct tog_reflist_entry *re;
6632 int i = 0;
6634 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
6635 return;
6637 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
6638 while (i++ < maxscroll) {
6639 if (re == NULL)
6640 break;
6641 s->first_displayed_entry = re;
6642 re = TAILQ_PREV(re, tog_reflist_head, entry);
6646 static void
6647 ref_scroll_down(struct tog_ref_view_state *s, int maxscroll)
6649 struct tog_reflist_entry *next, *last;
6650 int n = 0;
6652 if (s->first_displayed_entry)
6653 next = TAILQ_NEXT(s->first_displayed_entry, entry);
6654 else
6655 next = TAILQ_FIRST(&s->refs);
6657 last = s->last_displayed_entry;
6658 while (next && last && n++ < maxscroll) {
6659 last = TAILQ_NEXT(last, entry);
6660 if (last) {
6661 s->first_displayed_entry = next;
6662 next = TAILQ_NEXT(next, entry);
6667 static const struct got_error *
6668 search_start_ref_view(struct tog_view *view)
6670 struct tog_ref_view_state *s = &view->state.ref;
6672 s->matched_entry = NULL;
6673 return NULL;
6676 static int
6677 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
6679 regmatch_t regmatch;
6681 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
6682 0) == 0;
6685 static const struct got_error *
6686 search_next_ref_view(struct tog_view *view)
6688 struct tog_ref_view_state *s = &view->state.ref;
6689 struct tog_reflist_entry *re = NULL;
6691 if (!view->searching) {
6692 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6693 return NULL;
6696 if (s->matched_entry) {
6697 if (view->searching == TOG_SEARCH_FORWARD) {
6698 if (s->selected_entry)
6699 re = TAILQ_NEXT(s->selected_entry, entry);
6700 else
6701 re = TAILQ_PREV(s->selected_entry,
6702 tog_reflist_head, entry);
6703 } else {
6704 if (s->selected_entry == NULL)
6705 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6706 else
6707 re = TAILQ_PREV(s->selected_entry,
6708 tog_reflist_head, entry);
6710 } else {
6711 if (s->selected_entry)
6712 re = s->selected_entry;
6713 else if (view->searching == TOG_SEARCH_FORWARD)
6714 re = TAILQ_FIRST(&s->refs);
6715 else
6716 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6719 while (1) {
6720 if (re == NULL) {
6721 if (s->matched_entry == NULL) {
6722 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6723 return NULL;
6725 if (view->searching == TOG_SEARCH_FORWARD)
6726 re = TAILQ_FIRST(&s->refs);
6727 else
6728 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6731 if (match_reflist_entry(re, &view->regex)) {
6732 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6733 s->matched_entry = re;
6734 break;
6737 if (view->searching == TOG_SEARCH_FORWARD)
6738 re = TAILQ_NEXT(re, entry);
6739 else
6740 re = TAILQ_PREV(re, tog_reflist_head, entry);
6743 if (s->matched_entry) {
6744 s->first_displayed_entry = s->matched_entry;
6745 s->selected = 0;
6748 return NULL;
6751 static const struct got_error *
6752 show_ref_view(struct tog_view *view)
6754 const struct got_error *err = NULL;
6755 struct tog_ref_view_state *s = &view->state.ref;
6756 struct tog_reflist_entry *re;
6757 char *line = NULL;
6758 wchar_t *wline;
6759 struct tog_color *tc;
6760 int width, n;
6761 int limit = view->nlines;
6763 werase(view->window);
6765 s->ndisplayed = 0;
6767 if (limit == 0)
6768 return NULL;
6770 re = s->first_displayed_entry;
6772 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
6773 s->nrefs) == -1)
6774 return got_error_from_errno("asprintf");
6776 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6777 if (err) {
6778 free(line);
6779 return err;
6781 if (view_needs_focus_indication(view))
6782 wstandout(view->window);
6783 waddwstr(view->window, wline);
6784 if (view_needs_focus_indication(view))
6785 wstandend(view->window);
6786 free(wline);
6787 wline = NULL;
6788 free(line);
6789 line = NULL;
6790 if (width < view->ncols - 1)
6791 waddch(view->window, '\n');
6792 if (--limit <= 0)
6793 return NULL;
6795 n = 0;
6796 while (re && limit > 0) {
6797 char *line = NULL;
6798 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
6800 if (s->show_date) {
6801 struct got_commit_object *ci;
6802 struct got_tag_object *tag;
6803 struct got_object_id *id;
6804 struct tm tm;
6805 time_t t;
6807 err = got_ref_resolve(&id, s->repo, re->ref);
6808 if (err)
6809 return err;
6810 err = got_object_open_as_tag(&tag, s->repo, id);
6811 if (err) {
6812 if (err->code != GOT_ERR_OBJ_TYPE) {
6813 free(id);
6814 return err;
6816 err = got_object_open_as_commit(&ci, s->repo,
6817 id);
6818 if (err) {
6819 free(id);
6820 return err;
6822 t = got_object_commit_get_committer_time(ci);
6823 got_object_commit_close(ci);
6824 } else {
6825 t = got_object_tag_get_tagger_time(tag);
6826 got_object_tag_close(tag);
6828 free(id);
6829 if (gmtime_r(&t, &tm) == NULL)
6830 return got_error_from_errno("gmtime_r");
6831 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
6832 return got_error(GOT_ERR_NO_SPACE);
6834 if (got_ref_is_symbolic(re->ref)) {
6835 if (asprintf(&line, "%s%s -> %s", s->show_date ?
6836 ymd : "", got_ref_get_name(re->ref),
6837 got_ref_get_symref_target(re->ref)) == -1)
6838 return got_error_from_errno("asprintf");
6839 } else if (s->show_ids) {
6840 struct got_object_id *id;
6841 char *id_str;
6842 err = got_ref_resolve(&id, s->repo, re->ref);
6843 if (err)
6844 return err;
6845 err = got_object_id_str(&id_str, id);
6846 if (err) {
6847 free(id);
6848 return err;
6850 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
6851 got_ref_get_name(re->ref), id_str) == -1) {
6852 err = got_error_from_errno("asprintf");
6853 free(id);
6854 free(id_str);
6855 return err;
6857 free(id);
6858 free(id_str);
6859 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
6860 got_ref_get_name(re->ref)) == -1)
6861 return got_error_from_errno("asprintf");
6863 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6864 0, 0);
6865 if (err) {
6866 free(line);
6867 return err;
6869 if (n == s->selected) {
6870 if (view->focussed)
6871 wstandout(view->window);
6872 s->selected_entry = re;
6874 tc = match_color(&s->colors, got_ref_get_name(re->ref));
6875 if (tc)
6876 wattr_on(view->window,
6877 COLOR_PAIR(tc->colorpair), NULL);
6878 waddwstr(view->window, wline);
6879 if (tc)
6880 wattr_off(view->window,
6881 COLOR_PAIR(tc->colorpair), NULL);
6882 if (width < view->ncols - 1)
6883 waddch(view->window, '\n');
6884 if (n == s->selected && view->focussed)
6885 wstandend(view->window);
6886 free(line);
6887 free(wline);
6888 wline = NULL;
6889 n++;
6890 s->ndisplayed++;
6891 s->last_displayed_entry = re;
6893 limit--;
6894 re = TAILQ_NEXT(re, entry);
6897 view_vborder(view);
6898 return err;
6901 static const struct got_error *
6902 browse_ref_tree(struct tog_view **new_view, int begin_x,
6903 struct tog_reflist_entry *re, struct got_repository *repo)
6905 const struct got_error *err = NULL;
6906 struct got_object_id *commit_id = NULL;
6907 struct tog_view *tree_view;
6909 *new_view = NULL;
6911 err = resolve_reflist_entry(&commit_id, re, repo);
6912 if (err) {
6913 if (err->code != GOT_ERR_OBJ_TYPE)
6914 return err;
6915 else
6916 return NULL;
6920 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
6921 if (tree_view == NULL) {
6922 err = got_error_from_errno("view_open");
6923 goto done;
6926 err = open_tree_view(tree_view, commit_id,
6927 got_ref_get_name(re->ref), repo);
6928 if (err)
6929 goto done;
6931 *new_view = tree_view;
6932 done:
6933 free(commit_id);
6934 return err;
6936 static const struct got_error *
6937 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
6939 const struct got_error *err = NULL;
6940 struct tog_ref_view_state *s = &view->state.ref;
6941 struct tog_view *log_view, *tree_view;
6942 struct tog_reflist_entry *re;
6943 int begin_x = 0, n, nscroll = view->nlines - 1;
6945 switch (ch) {
6946 case 'i':
6947 s->show_ids = !s->show_ids;
6948 view->count = 0;
6949 break;
6950 case 'm':
6951 s->show_date = !s->show_date;
6952 view->count = 0;
6953 break;
6954 case 'o':
6955 s->sort_by_date = !s->sort_by_date;
6956 view->count = 0;
6957 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
6958 got_ref_cmp_by_commit_timestamp_descending :
6959 tog_ref_cmp_by_name, s->repo);
6960 if (err)
6961 break;
6962 got_reflist_object_id_map_free(tog_refs_idmap);
6963 err = got_reflist_object_id_map_create(&tog_refs_idmap,
6964 &tog_refs, s->repo);
6965 if (err)
6966 break;
6967 ref_view_free_refs(s);
6968 err = ref_view_load_refs(s);
6969 break;
6970 case KEY_ENTER:
6971 case '\r':
6972 view->count = 0;
6973 if (!s->selected_entry)
6974 break;
6975 if (view_is_parent_view(view))
6976 begin_x = view_split_begin_x(view->begin_x);
6977 err = log_ref_entry(&log_view, begin_x, s->selected_entry,
6978 s->repo);
6979 view->focussed = 0;
6980 log_view->focussed = 1;
6981 if (view_is_parent_view(view)) {
6982 err = view_close_child(view);
6983 if (err)
6984 return err;
6985 err = view_set_child(view, log_view);
6986 if (err)
6987 return err;
6988 view->focus_child = 1;
6989 } else
6990 *new_view = log_view;
6991 break;
6992 case 't':
6993 view->count = 0;
6994 if (!s->selected_entry)
6995 break;
6996 if (view_is_parent_view(view))
6997 begin_x = view_split_begin_x(view->begin_x);
6998 err = browse_ref_tree(&tree_view, begin_x, s->selected_entry,
6999 s->repo);
7000 if (err || tree_view == NULL)
7001 break;
7002 view->focussed = 0;
7003 tree_view->focussed = 1;
7004 if (view_is_parent_view(view)) {
7005 err = view_close_child(view);
7006 if (err)
7007 return err;
7008 err = view_set_child(view, tree_view);
7009 if (err)
7010 return err;
7011 view->focus_child = 1;
7012 } else
7013 *new_view = tree_view;
7014 break;
7015 case 'g':
7016 case KEY_HOME:
7017 s->selected = 0;
7018 view->count = 0;
7019 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7020 break;
7021 case 'G':
7022 case KEY_END:
7023 s->selected = 0;
7024 view->count = 0;
7025 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7026 for (n = 0; n < view->nlines - 1; n++) {
7027 if (re == NULL)
7028 break;
7029 s->first_displayed_entry = re;
7030 re = TAILQ_PREV(re, tog_reflist_head, entry);
7032 if (n > 0)
7033 s->selected = n - 1;
7034 break;
7035 case 'k':
7036 case KEY_UP:
7037 case CTRL('p'):
7038 if (s->selected > 0) {
7039 s->selected--;
7040 break;
7042 ref_scroll_up(s, 1);
7043 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7044 view->count = 0;
7045 break;
7046 case CTRL('u'):
7047 case 'u':
7048 nscroll /= 2;
7049 /* FALL THROUGH */
7050 case KEY_PPAGE:
7051 case CTRL('b'):
7052 case 'b':
7053 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7054 s->selected -= MIN(nscroll, s->selected);
7055 ref_scroll_up(s, MAX(0, nscroll));
7056 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7057 view->count = 0;
7058 break;
7059 case 'j':
7060 case KEY_DOWN:
7061 case CTRL('n'):
7062 if (s->selected < s->ndisplayed - 1) {
7063 s->selected++;
7064 break;
7066 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7067 /* can't scroll any further */
7068 view->count = 0;
7069 break;
7071 ref_scroll_down(s, 1);
7072 break;
7073 case CTRL('d'):
7074 case 'd':
7075 nscroll /= 2;
7076 /* FALL THROUGH */
7077 case KEY_NPAGE:
7078 case CTRL('f'):
7079 case 'f':
7080 case ' ':
7081 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7082 /* can't scroll any further; move cursor down */
7083 if (s->selected < s->ndisplayed - 1)
7084 s->selected += MIN(nscroll,
7085 s->ndisplayed - s->selected - 1);
7086 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7087 s->selected += s->ndisplayed - s->selected - 1;
7088 view->count = 0;
7089 break;
7091 ref_scroll_down(s, nscroll);
7092 break;
7093 case CTRL('l'):
7094 view->count = 0;
7095 tog_free_refs();
7096 err = tog_load_refs(s->repo, s->sort_by_date);
7097 if (err)
7098 break;
7099 ref_view_free_refs(s);
7100 err = ref_view_load_refs(s);
7101 break;
7102 case KEY_RESIZE:
7103 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7104 s->selected = view->nlines - 2;
7105 break;
7106 default:
7107 view->count = 0;
7108 break;
7111 return err;
7114 __dead static void
7115 usage_ref(void)
7117 endwin();
7118 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7119 getprogname());
7120 exit(1);
7123 static const struct got_error *
7124 cmd_ref(int argc, char *argv[])
7126 const struct got_error *error;
7127 struct got_repository *repo = NULL;
7128 struct got_worktree *worktree = NULL;
7129 char *cwd = NULL, *repo_path = NULL;
7130 int ch;
7131 struct tog_view *view;
7132 int *pack_fds = NULL;
7134 while ((ch = getopt(argc, argv, "r:")) != -1) {
7135 switch (ch) {
7136 case 'r':
7137 repo_path = realpath(optarg, NULL);
7138 if (repo_path == NULL)
7139 return got_error_from_errno2("realpath",
7140 optarg);
7141 break;
7142 default:
7143 usage_ref();
7144 /* NOTREACHED */
7148 argc -= optind;
7149 argv += optind;
7151 if (argc > 1)
7152 usage_ref();
7154 error = got_repo_pack_fds_open(&pack_fds);
7155 if (error != NULL)
7156 goto done;
7158 if (repo_path == NULL) {
7159 cwd = getcwd(NULL, 0);
7160 if (cwd == NULL)
7161 return got_error_from_errno("getcwd");
7162 error = got_worktree_open(&worktree, cwd);
7163 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7164 goto done;
7165 if (worktree)
7166 repo_path =
7167 strdup(got_worktree_get_repo_path(worktree));
7168 else
7169 repo_path = strdup(cwd);
7170 if (repo_path == NULL) {
7171 error = got_error_from_errno("strdup");
7172 goto done;
7176 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7177 if (error != NULL)
7178 goto done;
7180 init_curses();
7182 error = apply_unveil(got_repo_get_path(repo), NULL);
7183 if (error)
7184 goto done;
7186 error = tog_load_refs(repo, 0);
7187 if (error)
7188 goto done;
7190 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7191 if (view == NULL) {
7192 error = got_error_from_errno("view_open");
7193 goto done;
7196 error = open_ref_view(view, repo);
7197 if (error)
7198 goto done;
7200 if (worktree) {
7201 /* Release work tree lock. */
7202 got_worktree_close(worktree);
7203 worktree = NULL;
7205 error = view_loop(view);
7206 done:
7207 free(repo_path);
7208 free(cwd);
7209 if (repo) {
7210 const struct got_error *close_err = got_repo_close(repo);
7211 if (close_err)
7212 error = close_err;
7214 if (pack_fds) {
7215 const struct got_error *pack_err =
7216 got_repo_pack_fds_close(pack_fds);
7217 if (error == NULL)
7218 error = pack_err;
7220 tog_free_refs();
7221 return error;
7224 static void
7225 list_commands(FILE *fp)
7227 size_t i;
7229 fprintf(fp, "commands:");
7230 for (i = 0; i < nitems(tog_commands); i++) {
7231 const struct tog_cmd *cmd = &tog_commands[i];
7232 fprintf(fp, " %s", cmd->name);
7234 fputc('\n', fp);
7237 __dead static void
7238 usage(int hflag, int status)
7240 FILE *fp = (status == 0) ? stdout : stderr;
7242 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
7243 getprogname());
7244 if (hflag) {
7245 fprintf(fp, "lazy usage: %s path\n", getprogname());
7246 list_commands(fp);
7248 exit(status);
7251 static char **
7252 make_argv(int argc, ...)
7254 va_list ap;
7255 char **argv;
7256 int i;
7258 va_start(ap, argc);
7260 argv = calloc(argc, sizeof(char *));
7261 if (argv == NULL)
7262 err(1, "calloc");
7263 for (i = 0; i < argc; i++) {
7264 argv[i] = strdup(va_arg(ap, char *));
7265 if (argv[i] == NULL)
7266 err(1, "strdup");
7269 va_end(ap);
7270 return argv;
7274 * Try to convert 'tog path' into a 'tog log path' command.
7275 * The user could simply have mistyped the command rather than knowingly
7276 * provided a path. So check whether argv[0] can in fact be resolved
7277 * to a path in the HEAD commit and print a special error if not.
7278 * This hack is for mpi@ <3
7280 static const struct got_error *
7281 tog_log_with_path(int argc, char *argv[])
7283 const struct got_error *error = NULL, *close_err;
7284 const struct tog_cmd *cmd = NULL;
7285 struct got_repository *repo = NULL;
7286 struct got_worktree *worktree = NULL;
7287 struct got_object_id *commit_id = NULL, *id = NULL;
7288 struct got_commit_object *commit = NULL;
7289 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7290 char *commit_id_str = NULL, **cmd_argv = NULL;
7291 int *pack_fds = NULL;
7293 cwd = getcwd(NULL, 0);
7294 if (cwd == NULL)
7295 return got_error_from_errno("getcwd");
7297 error = got_repo_pack_fds_open(&pack_fds);
7298 if (error != NULL)
7299 goto done;
7301 error = got_worktree_open(&worktree, cwd);
7302 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7303 goto done;
7305 if (worktree)
7306 repo_path = strdup(got_worktree_get_repo_path(worktree));
7307 else
7308 repo_path = strdup(cwd);
7309 if (repo_path == NULL) {
7310 error = got_error_from_errno("strdup");
7311 goto done;
7314 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7315 if (error != NULL)
7316 goto done;
7318 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7319 repo, worktree);
7320 if (error)
7321 goto done;
7323 error = tog_load_refs(repo, 0);
7324 if (error)
7325 goto done;
7326 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
7327 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
7328 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7329 if (error)
7330 goto done;
7332 if (worktree) {
7333 got_worktree_close(worktree);
7334 worktree = NULL;
7337 error = got_object_open_as_commit(&commit, repo, commit_id);
7338 if (error)
7339 goto done;
7341 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
7342 if (error) {
7343 if (error->code != GOT_ERR_NO_TREE_ENTRY)
7344 goto done;
7345 fprintf(stderr, "%s: '%s' is no known command or path\n",
7346 getprogname(), argv[0]);
7347 usage(1, 1);
7348 /* not reached */
7351 close_err = got_repo_close(repo);
7352 if (error == NULL)
7353 error = close_err;
7354 repo = NULL;
7356 error = got_object_id_str(&commit_id_str, commit_id);
7357 if (error)
7358 goto done;
7360 cmd = &tog_commands[0]; /* log */
7361 argc = 4;
7362 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
7363 error = cmd->cmd_main(argc, cmd_argv);
7364 done:
7365 if (repo) {
7366 close_err = got_repo_close(repo);
7367 if (error == NULL)
7368 error = close_err;
7370 if (commit)
7371 got_object_commit_close(commit);
7372 if (worktree)
7373 got_worktree_close(worktree);
7374 if (pack_fds) {
7375 const struct got_error *pack_err =
7376 got_repo_pack_fds_close(pack_fds);
7377 if (error == NULL)
7378 error = pack_err;
7380 free(id);
7381 free(commit_id_str);
7382 free(commit_id);
7383 free(cwd);
7384 free(repo_path);
7385 free(in_repo_path);
7386 if (cmd_argv) {
7387 int i;
7388 for (i = 0; i < argc; i++)
7389 free(cmd_argv[i]);
7390 free(cmd_argv);
7392 tog_free_refs();
7393 return error;
7396 int
7397 main(int argc, char *argv[])
7399 const struct got_error *error = NULL;
7400 const struct tog_cmd *cmd = NULL;
7401 int ch, hflag = 0, Vflag = 0;
7402 char **cmd_argv = NULL;
7403 static const struct option longopts[] = {
7404 { "version", no_argument, NULL, 'V' },
7405 { NULL, 0, NULL, 0}
7408 setlocale(LC_CTYPE, "");
7410 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
7411 switch (ch) {
7412 case 'h':
7413 hflag = 1;
7414 break;
7415 case 'V':
7416 Vflag = 1;
7417 break;
7418 default:
7419 usage(hflag, 1);
7420 /* NOTREACHED */
7424 argc -= optind;
7425 argv += optind;
7426 optind = 1;
7427 optreset = 1;
7429 if (Vflag) {
7430 got_version_print_str();
7431 return 0;
7434 #ifndef PROFILE
7435 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
7436 NULL) == -1)
7437 err(1, "pledge");
7438 #endif
7440 if (argc == 0) {
7441 if (hflag)
7442 usage(hflag, 0);
7443 /* Build an argument vector which runs a default command. */
7444 cmd = &tog_commands[0];
7445 argc = 1;
7446 cmd_argv = make_argv(argc, cmd->name);
7447 } else {
7448 size_t i;
7450 /* Did the user specify a command? */
7451 for (i = 0; i < nitems(tog_commands); i++) {
7452 if (strncmp(tog_commands[i].name, argv[0],
7453 strlen(argv[0])) == 0) {
7454 cmd = &tog_commands[i];
7455 break;
7460 if (cmd == NULL) {
7461 if (argc != 1)
7462 usage(0, 1);
7463 /* No command specified; try log with a path */
7464 error = tog_log_with_path(argc, argv);
7465 } else {
7466 if (hflag)
7467 cmd->cmd_usage();
7468 else
7469 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
7472 endwin();
7473 putchar('\n');
7474 if (cmd_argv) {
7475 int i;
7476 for (i = 0; i < argc; i++)
7477 free(cmd_argv[i]);
7478 free(cmd_argv);
7481 if (error && error->code != GOT_ERR_CANCELLED)
7482 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7483 return 0;