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 first_displayed_line;
313 int last_displayed_line;
314 int eof;
315 int diff_context;
316 int ignore_whitespace;
317 int force_text_diff;
318 struct got_repository *repo;
319 struct tog_colors colors;
320 size_t nlines;
321 off_t *line_offsets;
322 int matched_line;
323 int selected_line;
325 /* passed from log view; may be NULL */
326 struct tog_view *log_view;
327 };
329 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
331 struct tog_log_thread_args {
332 pthread_cond_t need_commits;
333 pthread_cond_t commit_loaded;
334 int commits_needed;
335 int load_all;
336 struct got_commit_graph *graph;
337 struct commit_queue *commits;
338 const char *in_repo_path;
339 struct got_object_id *start_id;
340 struct got_repository *repo;
341 int *pack_fds;
342 int log_complete;
343 sig_atomic_t *quit;
344 struct commit_queue_entry **first_displayed_entry;
345 struct commit_queue_entry **selected_entry;
346 int *searching;
347 int *search_next_done;
348 regex_t *regex;
349 };
351 struct tog_log_view_state {
352 struct commit_queue commits;
353 struct commit_queue_entry *first_displayed_entry;
354 struct commit_queue_entry *last_displayed_entry;
355 struct commit_queue_entry *selected_entry;
356 int selected;
357 char *in_repo_path;
358 char *head_ref_name;
359 int log_branches;
360 struct got_repository *repo;
361 struct got_object_id *start_id;
362 sig_atomic_t quit;
363 pthread_t thread;
364 struct tog_log_thread_args thread_args;
365 struct commit_queue_entry *matched_entry;
366 struct commit_queue_entry *search_entry;
367 struct tog_colors colors;
368 };
370 #define TOG_COLOR_DIFF_MINUS 1
371 #define TOG_COLOR_DIFF_PLUS 2
372 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
373 #define TOG_COLOR_DIFF_META 4
374 #define TOG_COLOR_TREE_SUBMODULE 5
375 #define TOG_COLOR_TREE_SYMLINK 6
376 #define TOG_COLOR_TREE_DIRECTORY 7
377 #define TOG_COLOR_TREE_EXECUTABLE 8
378 #define TOG_COLOR_COMMIT 9
379 #define TOG_COLOR_AUTHOR 10
380 #define TOG_COLOR_DATE 11
381 #define TOG_COLOR_REFS_HEADS 12
382 #define TOG_COLOR_REFS_TAGS 13
383 #define TOG_COLOR_REFS_REMOTES 14
384 #define TOG_COLOR_REFS_BACKUP 15
386 struct tog_blame_cb_args {
387 struct tog_blame_line *lines; /* one per line */
388 int nlines;
390 struct tog_view *view;
391 struct got_object_id *commit_id;
392 int *quit;
393 };
395 struct tog_blame_thread_args {
396 const char *path;
397 struct got_repository *repo;
398 struct tog_blame_cb_args *cb_args;
399 int *complete;
400 got_cancel_cb cancel_cb;
401 void *cancel_arg;
402 };
404 struct tog_blame {
405 FILE *f;
406 off_t filesize;
407 struct tog_blame_line *lines;
408 int nlines;
409 off_t *line_offsets;
410 pthread_t thread;
411 struct tog_blame_thread_args thread_args;
412 struct tog_blame_cb_args cb_args;
413 const char *path;
414 int *pack_fds;
415 };
417 struct tog_blame_view_state {
418 int first_displayed_line;
419 int last_displayed_line;
420 int selected_line;
421 int blame_complete;
422 int eof;
423 int done;
424 struct got_object_id_queue blamed_commits;
425 struct got_object_qid *blamed_commit;
426 char *path;
427 struct got_repository *repo;
428 struct got_object_id *commit_id;
429 struct tog_blame blame;
430 int matched_line;
431 struct tog_colors colors;
432 };
434 struct tog_parent_tree {
435 TAILQ_ENTRY(tog_parent_tree) entry;
436 struct got_tree_object *tree;
437 struct got_tree_entry *first_displayed_entry;
438 struct got_tree_entry *selected_entry;
439 int selected;
440 };
442 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
444 struct tog_tree_view_state {
445 char *tree_label;
446 struct got_object_id *commit_id;/* commit which this tree belongs to */
447 struct got_tree_object *root; /* the commit's root tree entry */
448 struct got_tree_object *tree; /* currently displayed (sub-)tree */
449 struct got_tree_entry *first_displayed_entry;
450 struct got_tree_entry *last_displayed_entry;
451 struct got_tree_entry *selected_entry;
452 int ndisplayed, selected, show_ids;
453 struct tog_parent_trees parents; /* parent trees of current sub-tree */
454 char *head_ref_name;
455 struct got_repository *repo;
456 struct got_tree_entry *matched_entry;
457 struct tog_colors colors;
458 };
460 struct tog_reflist_entry {
461 TAILQ_ENTRY(tog_reflist_entry) entry;
462 struct got_reference *ref;
463 int idx;
464 };
466 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
468 struct tog_ref_view_state {
469 struct tog_reflist_head refs;
470 struct tog_reflist_entry *first_displayed_entry;
471 struct tog_reflist_entry *last_displayed_entry;
472 struct tog_reflist_entry *selected_entry;
473 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
474 struct got_repository *repo;
475 struct tog_reflist_entry *matched_entry;
476 struct tog_colors colors;
477 };
479 /*
480 * We implement two types of views: parent views and child views.
482 * The 'Tab' key switches focus between a parent view and its child view.
483 * Child views are shown side-by-side to their parent view, provided
484 * there is enough screen estate.
486 * When a new view is opened from within a parent view, this new view
487 * becomes a child view of the parent view, replacing any existing child.
489 * When a new view is opened from within a child view, this new view
490 * becomes a parent view which will obscure the views below until the
491 * user quits the new parent view by typing 'q'.
493 * This list of views contains parent views only.
494 * Child views are only pointed to by their parent view.
495 */
496 TAILQ_HEAD(tog_view_list_head, tog_view);
498 struct tog_view {
499 TAILQ_ENTRY(tog_view) entry;
500 WINDOW *window;
501 PANEL *panel;
502 int nlines, ncols, begin_y, begin_x;
503 int maxx, x; /* max column and current start column */
504 int lines, cols; /* copies of LINES and COLS */
505 int ch, count; /* current keymap and count prefix */
506 int focussed; /* Only set on one parent or child view at a time. */
507 int dying;
508 struct tog_view *parent;
509 struct tog_view *child;
511 /*
512 * This flag is initially set on parent views when a new child view
513 * is created. It gets toggled when the 'Tab' key switches focus
514 * between parent and child.
515 * The flag indicates whether focus should be passed on to our child
516 * view if this parent view gets picked for focus after another parent
517 * view was closed. This prevents child views from losing focus in such
518 * situations.
519 */
520 int focus_child;
522 /* type-specific state */
523 enum tog_view_type type;
524 union {
525 struct tog_diff_view_state diff;
526 struct tog_log_view_state log;
527 struct tog_blame_view_state blame;
528 struct tog_tree_view_state tree;
529 struct tog_ref_view_state ref;
530 } state;
532 const struct got_error *(*show)(struct tog_view *);
533 const struct got_error *(*input)(struct tog_view **,
534 struct tog_view *, int);
535 const struct got_error *(*close)(struct tog_view *);
537 const struct got_error *(*search_start)(struct tog_view *);
538 const struct got_error *(*search_next)(struct tog_view *);
539 int search_started;
540 int searching;
541 #define TOG_SEARCH_FORWARD 1
542 #define TOG_SEARCH_BACKWARD 2
543 int search_next_done;
544 #define TOG_SEARCH_HAVE_MORE 1
545 #define TOG_SEARCH_NO_MORE 2
546 #define TOG_SEARCH_HAVE_NONE 3
547 regex_t regex;
548 regmatch_t regmatch;
549 };
551 static const struct got_error *open_diff_view(struct tog_view *,
552 struct got_object_id *, struct got_object_id *,
553 const char *, const char *, int, int, int, struct tog_view *,
554 struct got_repository *);
555 static const struct got_error *show_diff_view(struct tog_view *);
556 static const struct got_error *input_diff_view(struct tog_view **,
557 struct tog_view *, int);
558 static const struct got_error* close_diff_view(struct tog_view *);
559 static const struct got_error *search_start_diff_view(struct tog_view *);
560 static const struct got_error *search_next_diff_view(struct tog_view *);
562 static const struct got_error *open_log_view(struct tog_view *,
563 struct got_object_id *, struct got_repository *,
564 const char *, const char *, int);
565 static const struct got_error * show_log_view(struct tog_view *);
566 static const struct got_error *input_log_view(struct tog_view **,
567 struct tog_view *, int);
568 static const struct got_error *close_log_view(struct tog_view *);
569 static const struct got_error *search_start_log_view(struct tog_view *);
570 static const struct got_error *search_next_log_view(struct tog_view *);
572 static const struct got_error *open_blame_view(struct tog_view *, char *,
573 struct got_object_id *, struct got_repository *);
574 static const struct got_error *show_blame_view(struct tog_view *);
575 static const struct got_error *input_blame_view(struct tog_view **,
576 struct tog_view *, int);
577 static const struct got_error *close_blame_view(struct tog_view *);
578 static const struct got_error *search_start_blame_view(struct tog_view *);
579 static const struct got_error *search_next_blame_view(struct tog_view *);
581 static const struct got_error *open_tree_view(struct tog_view *,
582 struct got_object_id *, const char *, struct got_repository *);
583 static const struct got_error *show_tree_view(struct tog_view *);
584 static const struct got_error *input_tree_view(struct tog_view **,
585 struct tog_view *, int);
586 static const struct got_error *close_tree_view(struct tog_view *);
587 static const struct got_error *search_start_tree_view(struct tog_view *);
588 static const struct got_error *search_next_tree_view(struct tog_view *);
590 static const struct got_error *open_ref_view(struct tog_view *,
591 struct got_repository *);
592 static const struct got_error *show_ref_view(struct tog_view *);
593 static const struct got_error *input_ref_view(struct tog_view **,
594 struct tog_view *, int);
595 static const struct got_error *close_ref_view(struct tog_view *);
596 static const struct got_error *search_start_ref_view(struct tog_view *);
597 static const struct got_error *search_next_ref_view(struct tog_view *);
599 static volatile sig_atomic_t tog_sigwinch_received;
600 static volatile sig_atomic_t tog_sigpipe_received;
601 static volatile sig_atomic_t tog_sigcont_received;
602 static volatile sig_atomic_t tog_sigint_received;
603 static volatile sig_atomic_t tog_sigterm_received;
605 static void
606 tog_sigwinch(int signo)
608 tog_sigwinch_received = 1;
611 static void
612 tog_sigpipe(int signo)
614 tog_sigpipe_received = 1;
617 static void
618 tog_sigcont(int signo)
620 tog_sigcont_received = 1;
623 static void
624 tog_sigint(int signo)
626 tog_sigint_received = 1;
629 static void
630 tog_sigterm(int signo)
632 tog_sigterm_received = 1;
635 static int
636 tog_fatal_signal_received(void)
638 return (tog_sigpipe_received ||
639 tog_sigint_received || tog_sigint_received);
643 static const struct got_error *
644 view_close(struct tog_view *view)
646 const struct got_error *err = NULL;
648 if (view->child) {
649 view_close(view->child);
650 view->child = NULL;
652 if (view->close)
653 err = view->close(view);
654 if (view->panel)
655 del_panel(view->panel);
656 if (view->window)
657 delwin(view->window);
658 free(view);
659 return err;
662 static struct tog_view *
663 view_open(int nlines, int ncols, int begin_y, int begin_x,
664 enum tog_view_type type)
666 struct tog_view *view = calloc(1, sizeof(*view));
668 if (view == NULL)
669 return NULL;
671 view->ch = 0;
672 view->count = 0;
673 view->type = type;
674 view->lines = LINES;
675 view->cols = COLS;
676 view->nlines = nlines ? nlines : LINES - begin_y;
677 view->ncols = ncols ? ncols : COLS - begin_x;
678 view->begin_y = begin_y;
679 view->begin_x = begin_x;
680 view->window = newwin(nlines, ncols, begin_y, begin_x);
681 if (view->window == NULL) {
682 view_close(view);
683 return NULL;
685 view->panel = new_panel(view->window);
686 if (view->panel == NULL ||
687 set_panel_userptr(view->panel, view) != OK) {
688 view_close(view);
689 return NULL;
692 keypad(view->window, TRUE);
693 return view;
696 static int
697 view_split_begin_x(int begin_x)
699 if (begin_x > 0 || COLS < 120)
700 return 0;
701 return (COLS - MAX(COLS / 2, 80));
704 static const struct got_error *view_resize(struct tog_view *);
706 static const struct got_error *
707 view_splitscreen(struct tog_view *view)
709 const struct got_error *err = NULL;
711 view->begin_y = 0;
712 view->begin_x = view_split_begin_x(0);
713 view->nlines = LINES;
714 view->ncols = COLS - view->begin_x;
715 view->lines = LINES;
716 view->cols = COLS;
717 err = view_resize(view);
718 if (err)
719 return err;
721 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
722 return got_error_from_errno("mvwin");
724 return NULL;
727 static const struct got_error *
728 view_fullscreen(struct tog_view *view)
730 const struct got_error *err = NULL;
732 view->begin_x = 0;
733 view->begin_y = 0;
734 view->nlines = LINES;
735 view->ncols = COLS;
736 view->lines = LINES;
737 view->cols = COLS;
738 err = view_resize(view);
739 if (err)
740 return err;
742 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
743 return got_error_from_errno("mvwin");
745 return NULL;
748 static int
749 view_is_parent_view(struct tog_view *view)
751 return view->parent == NULL;
754 static int
755 view_is_splitscreen(struct tog_view *view)
757 return view->begin_x > 0;
761 static const struct got_error *
762 view_resize(struct tog_view *view)
764 int nlines, ncols;
766 if (view->lines > LINES)
767 nlines = view->nlines - (view->lines - LINES);
768 else
769 nlines = view->nlines + (LINES - view->lines);
771 if (view->cols > COLS)
772 ncols = view->ncols - (view->cols - COLS);
773 else
774 ncols = view->ncols + (COLS - view->cols);
776 if (view->child && view_is_splitscreen(view->child)) {
777 view->child->begin_x = view_split_begin_x(view->begin_x);
778 if (view->child->begin_x == 0) {
779 ncols = COLS;
781 view_fullscreen(view->child);
782 if (view->child->focussed)
783 show_panel(view->child->panel);
784 else
785 show_panel(view->panel);
786 } else {
787 ncols = view->child->begin_x;
789 view_splitscreen(view->child);
790 show_panel(view->child->panel);
792 } else if (view->parent == NULL)
793 ncols = COLS;
795 if (wresize(view->window, nlines, ncols) == ERR)
796 return got_error_from_errno("wresize");
797 if (replace_panel(view->panel, view->window) == ERR)
798 return got_error_from_errno("replace_panel");
799 wclear(view->window);
801 view->nlines = nlines;
802 view->ncols = ncols;
803 view->lines = LINES;
804 view->cols = COLS;
806 return NULL;
809 static const struct got_error *
810 view_close_child(struct tog_view *view)
812 const struct got_error *err = NULL;
814 if (view->child == NULL)
815 return NULL;
817 err = view_close(view->child);
818 view->child = NULL;
819 return err;
822 static const struct got_error *
823 view_set_child(struct tog_view *view, struct tog_view *child)
825 view->child = child;
826 child->parent = view;
828 return view_resize(view);
831 static void
832 tog_resizeterm(void)
834 int cols, lines;
835 struct winsize size;
837 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
838 cols = 80; /* Default */
839 lines = 24;
840 } else {
841 cols = size.ws_col;
842 lines = size.ws_row;
844 resize_term(lines, cols);
847 static const struct got_error *
848 view_search_start(struct tog_view *view)
850 const struct got_error *err = NULL;
851 char pattern[1024];
852 int ret;
854 if (view->search_started) {
855 regfree(&view->regex);
856 view->searching = 0;
857 memset(&view->regmatch, 0, sizeof(view->regmatch));
859 view->search_started = 0;
861 if (view->nlines < 1)
862 return NULL;
864 mvwaddstr(view->window, view->begin_y + view->nlines - 1, 0, "/");
865 wclrtoeol(view->window);
867 nocbreak();
868 echo();
869 ret = wgetnstr(view->window, pattern, sizeof(pattern));
870 cbreak();
871 noecho();
872 if (ret == ERR)
873 return NULL;
875 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
876 err = view->search_start(view);
877 if (err) {
878 regfree(&view->regex);
879 return err;
881 view->search_started = 1;
882 view->searching = TOG_SEARCH_FORWARD;
883 view->search_next_done = 0;
884 view->search_next(view);
887 return NULL;
890 /*
891 * Compute view->count from numeric user input. User has five-tenths of a
892 * second to follow each numeric keypress with another number to form count.
893 * Return first non-numeric input or ERR and assign total to view->count.
894 * XXX Should we add support for user-defined timeout?
895 */
896 static int
897 get_compound_key(struct tog_view *view, int c)
899 int x, n = 0;
901 view->count = 0;
902 halfdelay(5); /* block for half a second */
903 wattron(view->window, A_BOLD);
904 wmove(view->window, view->nlines - 1, 0);
905 wclrtoeol(view->window);
906 waddch(view->window, ':');
908 do {
909 x = getcurx(view->window);
910 if (x != ERR && x < view->ncols)
911 waddch(view->window, c);
912 /*
913 * Don't overflow. Max valid request should be the greatest
914 * between the longest and total lines; cap at 10 million.
915 */
916 if (n >= 9999999)
917 n = 9999999;
918 else
919 n = n * 10 + (c - '0');
920 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
922 /* Massage excessive or inapplicable values at the input handler. */
923 view->count = n;
925 wattroff(view->window, A_BOLD);
926 cbreak(); /* return to blocking */
927 return c;
930 static const struct got_error *
931 view_input(struct tog_view **new, int *done, struct tog_view *view,
932 struct tog_view_list_head *views)
934 const struct got_error *err = NULL;
935 struct tog_view *v;
936 int ch, errcode;
938 *new = NULL;
940 /* Clear "no matches" indicator. */
941 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
942 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
943 view->search_next_done = TOG_SEARCH_HAVE_MORE;
944 view->count = 0;
947 if (view->searching && !view->search_next_done) {
948 errcode = pthread_mutex_unlock(&tog_mutex);
949 if (errcode)
950 return got_error_set_errno(errcode,
951 "pthread_mutex_unlock");
952 sched_yield();
953 errcode = pthread_mutex_lock(&tog_mutex);
954 if (errcode)
955 return got_error_set_errno(errcode,
956 "pthread_mutex_lock");
957 view->search_next(view);
958 return NULL;
961 nodelay(stdscr, FALSE);
962 /* Allow threads to make progress while we are waiting for input. */
963 errcode = pthread_mutex_unlock(&tog_mutex);
964 if (errcode)
965 return got_error_set_errno(errcode, "pthread_mutex_unlock");
966 /* If we have an unfinished count, don't get a new key map. */
967 ch = view->ch;
968 if ((view->count && --view->count == 0) || !view->count) {
969 ch = wgetch(view->window);
970 if (ch >= '1' && ch <= '9')
971 view->ch = ch = get_compound_key(view, ch);
973 errcode = pthread_mutex_lock(&tog_mutex);
974 if (errcode)
975 return got_error_set_errno(errcode, "pthread_mutex_lock");
976 nodelay(stdscr, TRUE);
978 if (tog_sigwinch_received || tog_sigcont_received) {
979 tog_resizeterm();
980 tog_sigwinch_received = 0;
981 tog_sigcont_received = 0;
982 TAILQ_FOREACH(v, views, entry) {
983 err = view_resize(v);
984 if (err)
985 return err;
986 err = v->input(new, v, KEY_RESIZE);
987 if (err)
988 return err;
989 if (v->child) {
990 err = view_resize(v->child);
991 if (err)
992 return err;
993 err = v->child->input(new, v->child,
994 KEY_RESIZE);
995 if (err)
996 return err;
1001 switch (ch) {
1002 case '\t':
1003 view->count = 0;
1004 if (view->child) {
1005 view->focussed = 0;
1006 view->child->focussed = 1;
1007 view->focus_child = 1;
1008 } else if (view->parent) {
1009 view->focussed = 0;
1010 view->parent->focussed = 1;
1011 view->parent->focus_child = 0;
1012 if (!view_is_splitscreen(view))
1013 err = view_fullscreen(view->parent);
1015 break;
1016 case 'q':
1017 err = view->input(new, view, ch);
1018 view->dying = 1;
1019 break;
1020 case 'Q':
1021 *done = 1;
1022 break;
1023 case 'F':
1024 view->count = 0;
1025 if (view_is_parent_view(view)) {
1026 if (view->child == NULL)
1027 break;
1028 if (view_is_splitscreen(view->child)) {
1029 view->focussed = 0;
1030 view->child->focussed = 1;
1031 err = view_fullscreen(view->child);
1032 } else
1033 err = view_splitscreen(view->child);
1034 if (err)
1035 break;
1036 err = view->child->input(new, view->child,
1037 KEY_RESIZE);
1038 } else {
1039 if (view_is_splitscreen(view)) {
1040 view->parent->focussed = 0;
1041 view->focussed = 1;
1042 err = view_fullscreen(view);
1043 } else {
1044 err = view_splitscreen(view);
1045 if (!err)
1046 err = view_resize(view->parent);
1048 if (err)
1049 break;
1050 err = view->input(new, view, KEY_RESIZE);
1052 break;
1053 case KEY_RESIZE:
1054 break;
1055 case '/':
1056 view->count = 0;
1057 if (view->search_start)
1058 view_search_start(view);
1059 else
1060 err = view->input(new, view, ch);
1061 break;
1062 case 'N':
1063 case 'n':
1064 if (view->search_started && view->search_next) {
1065 view->searching = (ch == 'n' ?
1066 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1067 view->search_next_done = 0;
1068 view->search_next(view);
1069 } else
1070 err = view->input(new, view, ch);
1071 break;
1072 default:
1073 err = view->input(new, view, ch);
1074 break;
1077 return err;
1080 static void
1081 view_vborder(struct tog_view *view)
1083 PANEL *panel;
1084 const struct tog_view *view_above;
1086 if (view->parent)
1087 return view_vborder(view->parent);
1089 panel = panel_above(view->panel);
1090 if (panel == NULL)
1091 return;
1093 view_above = panel_userptr(panel);
1094 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
1095 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
1098 static int
1099 view_needs_focus_indication(struct tog_view *view)
1101 if (view_is_parent_view(view)) {
1102 if (view->child == NULL || view->child->focussed)
1103 return 0;
1104 if (!view_is_splitscreen(view->child))
1105 return 0;
1106 } else if (!view_is_splitscreen(view))
1107 return 0;
1109 return view->focussed;
1112 static const struct got_error *
1113 view_loop(struct tog_view *view)
1115 const struct got_error *err = NULL;
1116 struct tog_view_list_head views;
1117 struct tog_view *new_view;
1118 int fast_refresh = 10;
1119 int done = 0, errcode;
1121 errcode = pthread_mutex_lock(&tog_mutex);
1122 if (errcode)
1123 return got_error_set_errno(errcode, "pthread_mutex_lock");
1125 TAILQ_INIT(&views);
1126 TAILQ_INSERT_HEAD(&views, view, entry);
1128 view->focussed = 1;
1129 err = view->show(view);
1130 if (err)
1131 return err;
1132 update_panels();
1133 doupdate();
1134 while (!TAILQ_EMPTY(&views) && !done && !tog_fatal_signal_received()) {
1135 /* Refresh fast during initialization, then become slower. */
1136 if (fast_refresh && fast_refresh-- == 0)
1137 halfdelay(10); /* switch to once per second */
1139 err = view_input(&new_view, &done, view, &views);
1140 if (err)
1141 break;
1142 if (view->dying) {
1143 struct tog_view *v, *prev = NULL;
1145 if (view_is_parent_view(view))
1146 prev = TAILQ_PREV(view, tog_view_list_head,
1147 entry);
1148 else if (view->parent)
1149 prev = view->parent;
1151 if (view->parent) {
1152 view->parent->child = NULL;
1153 view->parent->focus_child = 0;
1155 err = view_resize(view->parent);
1156 if (err)
1157 break;
1158 } else
1159 TAILQ_REMOVE(&views, view, entry);
1161 err = view_close(view);
1162 if (err)
1163 goto done;
1165 view = NULL;
1166 TAILQ_FOREACH(v, &views, entry) {
1167 if (v->focussed)
1168 break;
1170 if (view == NULL && new_view == NULL) {
1171 /* No view has focus. Try to pick one. */
1172 if (prev)
1173 view = prev;
1174 else if (!TAILQ_EMPTY(&views)) {
1175 view = TAILQ_LAST(&views,
1176 tog_view_list_head);
1178 if (view) {
1179 if (view->focus_child) {
1180 view->child->focussed = 1;
1181 view = view->child;
1182 } else
1183 view->focussed = 1;
1187 if (new_view) {
1188 struct tog_view *v, *t;
1189 /* Only allow one parent view per type. */
1190 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1191 if (v->type != new_view->type)
1192 continue;
1193 TAILQ_REMOVE(&views, v, entry);
1194 err = view_close(v);
1195 if (err)
1196 goto done;
1197 break;
1199 TAILQ_INSERT_TAIL(&views, new_view, entry);
1200 view = new_view;
1202 if (view) {
1203 if (view_is_parent_view(view)) {
1204 if (view->child && view->child->focussed)
1205 view = view->child;
1206 } else {
1207 if (view->parent && view->parent->focussed)
1208 view = view->parent;
1210 show_panel(view->panel);
1211 if (view->child && view_is_splitscreen(view->child))
1212 show_panel(view->child->panel);
1213 if (view->parent && view_is_splitscreen(view)) {
1214 err = view->parent->show(view->parent);
1215 if (err)
1216 goto done;
1218 err = view->show(view);
1219 if (err)
1220 goto done;
1221 if (view->child) {
1222 err = view->child->show(view->child);
1223 if (err)
1224 goto done;
1226 update_panels();
1227 doupdate();
1230 done:
1231 while (!TAILQ_EMPTY(&views)) {
1232 view = TAILQ_FIRST(&views);
1233 TAILQ_REMOVE(&views, view, entry);
1234 view_close(view);
1237 errcode = pthread_mutex_unlock(&tog_mutex);
1238 if (errcode && err == NULL)
1239 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1241 return err;
1244 __dead static void
1245 usage_log(void)
1247 endwin();
1248 fprintf(stderr,
1249 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1250 getprogname());
1251 exit(1);
1254 /* Create newly allocated wide-character string equivalent to a byte string. */
1255 static const struct got_error *
1256 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1258 char *vis = NULL;
1259 const struct got_error *err = NULL;
1261 *ws = NULL;
1262 *wlen = mbstowcs(NULL, s, 0);
1263 if (*wlen == (size_t)-1) {
1264 int vislen;
1265 if (errno != EILSEQ)
1266 return got_error_from_errno("mbstowcs");
1268 /* byte string invalid in current encoding; try to "fix" it */
1269 err = got_mbsavis(&vis, &vislen, s);
1270 if (err)
1271 return err;
1272 *wlen = mbstowcs(NULL, vis, 0);
1273 if (*wlen == (size_t)-1) {
1274 err = got_error_from_errno("mbstowcs"); /* give up */
1275 goto done;
1279 *ws = calloc(*wlen + 1, sizeof(**ws));
1280 if (*ws == NULL) {
1281 err = got_error_from_errno("calloc");
1282 goto done;
1285 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1286 err = got_error_from_errno("mbstowcs");
1287 done:
1288 free(vis);
1289 if (err) {
1290 free(*ws);
1291 *ws = NULL;
1292 *wlen = 0;
1294 return err;
1297 static const struct got_error *
1298 expand_tab(char **ptr, const char *src)
1300 char *dst;
1301 size_t len, n, idx = 0, sz = 0;
1303 *ptr = NULL;
1304 n = len = strlen(src);
1305 dst = malloc(n + 1);
1306 if (dst == NULL)
1307 return got_error_from_errno("malloc");
1309 while (idx < len && src[idx]) {
1310 const char c = src[idx];
1312 if (c == '\t') {
1313 size_t nb = TABSIZE - sz % TABSIZE;
1314 char *p;
1316 p = realloc(dst, n + nb);
1317 if (p == NULL) {
1318 free(dst);
1319 return got_error_from_errno("realloc");
1322 dst = p;
1323 n += nb;
1324 memset(dst + sz, ' ', nb);
1325 sz += nb;
1326 } else
1327 dst[sz++] = src[idx];
1328 ++idx;
1331 dst[sz] = '\0';
1332 *ptr = dst;
1333 return NULL;
1337 * Advance at most n columns from wline starting at offset off.
1338 * Return the index to the first character after the span operation.
1339 * Return the combined column width of all spanned wide character in
1340 * *rcol.
1342 static int
1343 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1345 int width, i, cols = 0;
1347 if (n == 0) {
1348 *rcol = cols;
1349 return off;
1352 for (i = off; wline[i] != L'\0'; ++i) {
1353 if (wline[i] == L'\t')
1354 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1355 else
1356 width = wcwidth(wline[i]);
1358 if (width == -1) {
1359 width = 1;
1360 wline[i] = L'.';
1363 if (cols + width > n)
1364 break;
1365 cols += width;
1368 *rcol = cols;
1369 return i;
1373 * Format a line for display, ensuring that it won't overflow a width limit.
1374 * With scrolling, the width returned refers to the scrolled version of the
1375 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1377 static const struct got_error *
1378 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1379 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1381 const struct got_error *err = NULL;
1382 int cols;
1383 wchar_t *wline = NULL;
1384 char *exstr = NULL;
1385 size_t wlen;
1386 int i, scrollx;
1388 *wlinep = NULL;
1389 *widthp = 0;
1391 if (expand) {
1392 err = expand_tab(&exstr, line);
1393 if (err)
1394 return err;
1397 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1398 free(exstr);
1399 if (err)
1400 return err;
1402 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1404 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1405 wline[wlen - 1] = L'\0';
1406 wlen--;
1408 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1409 wline[wlen - 1] = L'\0';
1410 wlen--;
1413 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1414 wline[i] = L'\0';
1416 if (widthp)
1417 *widthp = cols;
1418 if (scrollxp)
1419 *scrollxp = scrollx;
1420 if (err)
1421 free(wline);
1422 else
1423 *wlinep = wline;
1424 return err;
1427 static const struct got_error*
1428 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1429 struct got_object_id *id, struct got_repository *repo)
1431 static const struct got_error *err = NULL;
1432 struct got_reflist_entry *re;
1433 char *s;
1434 const char *name;
1436 *refs_str = NULL;
1438 TAILQ_FOREACH(re, refs, entry) {
1439 struct got_tag_object *tag = NULL;
1440 struct got_object_id *ref_id;
1441 int cmp;
1443 name = got_ref_get_name(re->ref);
1444 if (strcmp(name, GOT_REF_HEAD) == 0)
1445 continue;
1446 if (strncmp(name, "refs/", 5) == 0)
1447 name += 5;
1448 if (strncmp(name, "got/", 4) == 0 &&
1449 strncmp(name, "got/backup/", 11) != 0)
1450 continue;
1451 if (strncmp(name, "heads/", 6) == 0)
1452 name += 6;
1453 if (strncmp(name, "remotes/", 8) == 0) {
1454 name += 8;
1455 s = strstr(name, "/" GOT_REF_HEAD);
1456 if (s != NULL && s[strlen(s)] == '\0')
1457 continue;
1459 err = got_ref_resolve(&ref_id, repo, re->ref);
1460 if (err)
1461 break;
1462 if (strncmp(name, "tags/", 5) == 0) {
1463 err = got_object_open_as_tag(&tag, repo, ref_id);
1464 if (err) {
1465 if (err->code != GOT_ERR_OBJ_TYPE) {
1466 free(ref_id);
1467 break;
1469 /* Ref points at something other than a tag. */
1470 err = NULL;
1471 tag = NULL;
1474 cmp = got_object_id_cmp(tag ?
1475 got_object_tag_get_object_id(tag) : ref_id, id);
1476 free(ref_id);
1477 if (tag)
1478 got_object_tag_close(tag);
1479 if (cmp != 0)
1480 continue;
1481 s = *refs_str;
1482 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1483 s ? ", " : "", name) == -1) {
1484 err = got_error_from_errno("asprintf");
1485 free(s);
1486 *refs_str = NULL;
1487 break;
1489 free(s);
1492 return err;
1495 static const struct got_error *
1496 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1497 int col_tab_align)
1499 char *smallerthan;
1501 smallerthan = strchr(author, '<');
1502 if (smallerthan && smallerthan[1] != '\0')
1503 author = smallerthan + 1;
1504 author[strcspn(author, "@>")] = '\0';
1505 return format_line(wauthor, author_width, NULL, author, 0, limit,
1506 col_tab_align, 0);
1509 static const struct got_error *
1510 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1511 struct got_object_id *id, const size_t date_display_cols,
1512 int author_display_cols)
1514 struct tog_log_view_state *s = &view->state.log;
1515 const struct got_error *err = NULL;
1516 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1517 char *logmsg0 = NULL, *logmsg = NULL;
1518 char *author = NULL;
1519 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1520 int author_width, logmsg_width;
1521 char *newline, *line = NULL;
1522 int col, limit, scrollx;
1523 const int avail = view->ncols;
1524 struct tm tm;
1525 time_t committer_time;
1526 struct tog_color *tc;
1528 committer_time = got_object_commit_get_committer_time(commit);
1529 if (gmtime_r(&committer_time, &tm) == NULL)
1530 return got_error_from_errno("gmtime_r");
1531 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1532 return got_error(GOT_ERR_NO_SPACE);
1534 if (avail <= date_display_cols)
1535 limit = MIN(sizeof(datebuf) - 1, avail);
1536 else
1537 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1538 tc = get_color(&s->colors, TOG_COLOR_DATE);
1539 if (tc)
1540 wattr_on(view->window,
1541 COLOR_PAIR(tc->colorpair), NULL);
1542 waddnstr(view->window, datebuf, limit);
1543 if (tc)
1544 wattr_off(view->window,
1545 COLOR_PAIR(tc->colorpair), NULL);
1546 col = limit;
1547 if (col > avail)
1548 goto done;
1550 if (avail >= 120) {
1551 char *id_str;
1552 err = got_object_id_str(&id_str, id);
1553 if (err)
1554 goto done;
1555 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1556 if (tc)
1557 wattr_on(view->window,
1558 COLOR_PAIR(tc->colorpair), NULL);
1559 wprintw(view->window, "%.8s ", id_str);
1560 if (tc)
1561 wattr_off(view->window,
1562 COLOR_PAIR(tc->colorpair), NULL);
1563 free(id_str);
1564 col += 9;
1565 if (col > avail)
1566 goto done;
1569 author = strdup(got_object_commit_get_author(commit));
1570 if (author == NULL) {
1571 err = got_error_from_errno("strdup");
1572 goto done;
1574 err = format_author(&wauthor, &author_width, author, avail - col, col);
1575 if (err)
1576 goto done;
1577 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1578 if (tc)
1579 wattr_on(view->window,
1580 COLOR_PAIR(tc->colorpair), NULL);
1581 waddwstr(view->window, wauthor);
1582 if (tc)
1583 wattr_off(view->window,
1584 COLOR_PAIR(tc->colorpair), NULL);
1585 col += author_width;
1586 while (col < avail && author_width < author_display_cols + 2) {
1587 waddch(view->window, ' ');
1588 col++;
1589 author_width++;
1591 if (col > avail)
1592 goto done;
1594 err = got_object_commit_get_logmsg(&logmsg0, commit);
1595 if (err)
1596 goto done;
1597 logmsg = logmsg0;
1598 while (*logmsg == '\n')
1599 logmsg++;
1600 newline = strchr(logmsg, '\n');
1601 if (newline)
1602 *newline = '\0';
1603 limit = avail - col;
1604 if (view->child && view_is_splitscreen(view->child) && limit > 0)
1605 limit--; /* for the border */
1606 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
1607 limit, col, 1);
1608 if (err)
1609 goto done;
1610 waddwstr(view->window, &wlogmsg[scrollx]);
1611 col += MAX(logmsg_width, 0);
1612 while (col < avail) {
1613 waddch(view->window, ' ');
1614 col++;
1616 done:
1617 free(logmsg0);
1618 free(wlogmsg);
1619 free(author);
1620 free(wauthor);
1621 free(line);
1622 return err;
1625 static struct commit_queue_entry *
1626 alloc_commit_queue_entry(struct got_commit_object *commit,
1627 struct got_object_id *id)
1629 struct commit_queue_entry *entry;
1631 entry = calloc(1, sizeof(*entry));
1632 if (entry == NULL)
1633 return NULL;
1635 entry->id = id;
1636 entry->commit = commit;
1637 return entry;
1640 static void
1641 pop_commit(struct commit_queue *commits)
1643 struct commit_queue_entry *entry;
1645 entry = TAILQ_FIRST(&commits->head);
1646 TAILQ_REMOVE(&commits->head, entry, entry);
1647 got_object_commit_close(entry->commit);
1648 commits->ncommits--;
1649 /* Don't free entry->id! It is owned by the commit graph. */
1650 free(entry);
1653 static void
1654 free_commits(struct commit_queue *commits)
1656 while (!TAILQ_EMPTY(&commits->head))
1657 pop_commit(commits);
1660 static const struct got_error *
1661 match_commit(int *have_match, struct got_object_id *id,
1662 struct got_commit_object *commit, regex_t *regex)
1664 const struct got_error *err = NULL;
1665 regmatch_t regmatch;
1666 char *id_str = NULL, *logmsg = NULL;
1668 *have_match = 0;
1670 err = got_object_id_str(&id_str, id);
1671 if (err)
1672 return err;
1674 err = got_object_commit_get_logmsg(&logmsg, commit);
1675 if (err)
1676 goto done;
1678 if (regexec(regex, got_object_commit_get_author(commit), 1,
1679 &regmatch, 0) == 0 ||
1680 regexec(regex, got_object_commit_get_committer(commit), 1,
1681 &regmatch, 0) == 0 ||
1682 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
1683 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
1684 *have_match = 1;
1685 done:
1686 free(id_str);
1687 free(logmsg);
1688 return err;
1691 static const struct got_error *
1692 queue_commits(struct tog_log_thread_args *a)
1694 const struct got_error *err = NULL;
1697 * We keep all commits open throughout the lifetime of the log
1698 * view in order to avoid having to re-fetch commits from disk
1699 * while updating the display.
1701 do {
1702 struct got_object_id *id;
1703 struct got_commit_object *commit;
1704 struct commit_queue_entry *entry;
1705 int errcode;
1707 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
1708 NULL, NULL);
1709 if (err || id == NULL)
1710 break;
1712 err = got_object_open_as_commit(&commit, a->repo, id);
1713 if (err)
1714 break;
1715 entry = alloc_commit_queue_entry(commit, id);
1716 if (entry == NULL) {
1717 err = got_error_from_errno("alloc_commit_queue_entry");
1718 break;
1721 errcode = pthread_mutex_lock(&tog_mutex);
1722 if (errcode) {
1723 err = got_error_set_errno(errcode,
1724 "pthread_mutex_lock");
1725 break;
1728 entry->idx = a->commits->ncommits;
1729 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
1730 a->commits->ncommits++;
1732 if (*a->searching == TOG_SEARCH_FORWARD &&
1733 !*a->search_next_done) {
1734 int have_match;
1735 err = match_commit(&have_match, id, commit, a->regex);
1736 if (err)
1737 break;
1738 if (have_match)
1739 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
1742 errcode = pthread_mutex_unlock(&tog_mutex);
1743 if (errcode && err == NULL)
1744 err = got_error_set_errno(errcode,
1745 "pthread_mutex_unlock");
1746 if (err)
1747 break;
1748 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
1750 return err;
1753 static void
1754 select_commit(struct tog_log_view_state *s)
1756 struct commit_queue_entry *entry;
1757 int ncommits = 0;
1759 entry = s->first_displayed_entry;
1760 while (entry) {
1761 if (ncommits == s->selected) {
1762 s->selected_entry = entry;
1763 break;
1765 entry = TAILQ_NEXT(entry, entry);
1766 ncommits++;
1770 static const struct got_error *
1771 draw_commits(struct tog_view *view)
1773 const struct got_error *err = NULL;
1774 struct tog_log_view_state *s = &view->state.log;
1775 struct commit_queue_entry *entry = s->selected_entry;
1776 const int limit = view->nlines;
1777 int width;
1778 int ncommits, author_cols = 4;
1779 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
1780 char *refs_str = NULL;
1781 wchar_t *wline;
1782 struct tog_color *tc;
1783 static const size_t date_display_cols = 12;
1785 if (s->selected_entry &&
1786 !(view->searching && view->search_next_done == 0)) {
1787 struct got_reflist_head *refs;
1788 err = got_object_id_str(&id_str, s->selected_entry->id);
1789 if (err)
1790 return err;
1791 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
1792 s->selected_entry->id);
1793 if (refs) {
1794 err = build_refs_str(&refs_str, refs,
1795 s->selected_entry->id, s->repo);
1796 if (err)
1797 goto done;
1801 if (s->thread_args.commits_needed == 0)
1802 halfdelay(10); /* disable fast refresh */
1804 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
1805 if (asprintf(&ncommits_str, " [%d/%d] %s",
1806 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1807 (view->searching && !view->search_next_done) ?
1808 "searching..." : "loading...") == -1) {
1809 err = got_error_from_errno("asprintf");
1810 goto done;
1812 } else {
1813 const char *search_str = NULL;
1815 if (view->searching) {
1816 if (view->search_next_done == TOG_SEARCH_NO_MORE)
1817 search_str = "no more matches";
1818 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
1819 search_str = "no matches found";
1820 else if (!view->search_next_done)
1821 search_str = "searching...";
1824 if (asprintf(&ncommits_str, " [%d/%d] %s",
1825 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1826 search_str ? search_str :
1827 (refs_str ? refs_str : "")) == -1) {
1828 err = got_error_from_errno("asprintf");
1829 goto done;
1833 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
1834 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
1835 "........................................",
1836 s->in_repo_path, ncommits_str) == -1) {
1837 err = got_error_from_errno("asprintf");
1838 header = NULL;
1839 goto done;
1841 } else if (asprintf(&header, "commit %s%s",
1842 id_str ? id_str : "........................................",
1843 ncommits_str) == -1) {
1844 err = got_error_from_errno("asprintf");
1845 header = NULL;
1846 goto done;
1848 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
1849 if (err)
1850 goto done;
1852 werase(view->window);
1854 if (view_needs_focus_indication(view))
1855 wstandout(view->window);
1856 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1857 if (tc)
1858 wattr_on(view->window,
1859 COLOR_PAIR(tc->colorpair), NULL);
1860 waddwstr(view->window, wline);
1861 if (tc)
1862 wattr_off(view->window,
1863 COLOR_PAIR(tc->colorpair), NULL);
1864 while (width < view->ncols) {
1865 waddch(view->window, ' ');
1866 width++;
1868 if (view_needs_focus_indication(view))
1869 wstandend(view->window);
1870 free(wline);
1871 if (limit <= 1)
1872 goto done;
1874 /* Grow author column size if necessary, and set view->maxx. */
1875 entry = s->first_displayed_entry;
1876 ncommits = 0;
1877 view->maxx = 0;
1878 while (entry) {
1879 char *author, *eol, *msg, *msg0;
1880 wchar_t *wauthor, *wmsg;
1881 int width;
1882 if (ncommits >= limit - 1)
1883 break;
1884 author = strdup(got_object_commit_get_author(entry->commit));
1885 if (author == NULL) {
1886 err = got_error_from_errno("strdup");
1887 goto done;
1889 err = format_author(&wauthor, &width, author, COLS,
1890 date_display_cols);
1891 if (author_cols < width)
1892 author_cols = width;
1893 free(wauthor);
1894 free(author);
1895 err = got_object_commit_get_logmsg(&msg0, entry->commit);
1896 if (err)
1897 goto done;
1898 msg = msg0;
1899 while (*msg == '\n')
1900 ++msg;
1901 if ((eol = strchr(msg, '\n')))
1902 *eol = '\0';
1903 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
1904 date_display_cols + author_cols, 0);
1905 if (err)
1906 goto done;
1907 view->maxx = MAX(view->maxx, width);
1908 free(msg0);
1909 free(wmsg);
1910 ncommits++;
1911 entry = TAILQ_NEXT(entry, entry);
1914 entry = s->first_displayed_entry;
1915 s->last_displayed_entry = s->first_displayed_entry;
1916 ncommits = 0;
1917 while (entry) {
1918 if (ncommits >= limit - 1)
1919 break;
1920 if (ncommits == s->selected)
1921 wstandout(view->window);
1922 err = draw_commit(view, entry->commit, entry->id,
1923 date_display_cols, author_cols);
1924 if (ncommits == s->selected)
1925 wstandend(view->window);
1926 if (err)
1927 goto done;
1928 ncommits++;
1929 s->last_displayed_entry = entry;
1930 entry = TAILQ_NEXT(entry, entry);
1933 view_vborder(view);
1934 done:
1935 free(id_str);
1936 free(refs_str);
1937 free(ncommits_str);
1938 free(header);
1939 return err;
1942 static void
1943 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
1945 struct commit_queue_entry *entry;
1946 int nscrolled = 0;
1948 entry = TAILQ_FIRST(&s->commits.head);
1949 if (s->first_displayed_entry == entry)
1950 return;
1952 entry = s->first_displayed_entry;
1953 while (entry && nscrolled < maxscroll) {
1954 entry = TAILQ_PREV(entry, commit_queue_head, entry);
1955 if (entry) {
1956 s->first_displayed_entry = entry;
1957 nscrolled++;
1962 static const struct got_error *
1963 trigger_log_thread(struct tog_view *view, int wait)
1965 struct tog_log_thread_args *ta = &view->state.log.thread_args;
1966 int errcode;
1968 halfdelay(1); /* fast refresh while loading commits */
1970 while (ta->commits_needed > 0 || ta->load_all) {
1971 if (ta->log_complete)
1972 break;
1974 /* Wake the log thread. */
1975 errcode = pthread_cond_signal(&ta->need_commits);
1976 if (errcode)
1977 return got_error_set_errno(errcode,
1978 "pthread_cond_signal");
1981 * The mutex will be released while the view loop waits
1982 * in wgetch(), at which time the log thread will run.
1984 if (!wait)
1985 break;
1987 /* Display progress update in log view. */
1988 show_log_view(view);
1989 update_panels();
1990 doupdate();
1992 /* Wait right here while next commit is being loaded. */
1993 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
1994 if (errcode)
1995 return got_error_set_errno(errcode,
1996 "pthread_cond_wait");
1998 /* Display progress update in log view. */
1999 show_log_view(view);
2000 update_panels();
2001 doupdate();
2004 return NULL;
2007 static const struct got_error *
2008 log_scroll_down(struct tog_view *view, int maxscroll)
2010 struct tog_log_view_state *s = &view->state.log;
2011 const struct got_error *err = NULL;
2012 struct commit_queue_entry *pentry;
2013 int nscrolled = 0, ncommits_needed;
2015 if (s->last_displayed_entry == NULL)
2016 return NULL;
2018 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2019 if (s->commits.ncommits < ncommits_needed &&
2020 !s->thread_args.log_complete) {
2022 * Ask the log thread for required amount of commits.
2024 s->thread_args.commits_needed += maxscroll;
2025 err = trigger_log_thread(view, 1);
2026 if (err)
2027 return err;
2030 do {
2031 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2032 if (pentry == NULL)
2033 break;
2035 s->last_displayed_entry = pentry;
2037 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2038 if (pentry == NULL)
2039 break;
2040 s->first_displayed_entry = pentry;
2041 } while (++nscrolled < maxscroll);
2043 return err;
2046 static const struct got_error *
2047 open_diff_view_for_commit(struct tog_view **new_view, int begin_x,
2048 struct got_commit_object *commit, struct got_object_id *commit_id,
2049 struct tog_view *log_view, struct got_repository *repo)
2051 const struct got_error *err;
2052 struct got_object_qid *parent_id;
2053 struct tog_view *diff_view;
2055 diff_view = view_open(0, 0, 0, begin_x, TOG_VIEW_DIFF);
2056 if (diff_view == NULL)
2057 return got_error_from_errno("view_open");
2059 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2060 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2061 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2062 if (err == NULL)
2063 *new_view = diff_view;
2064 return err;
2067 static const struct got_error *
2068 tree_view_visit_subtree(struct tog_tree_view_state *s,
2069 struct got_tree_object *subtree)
2071 struct tog_parent_tree *parent;
2073 parent = calloc(1, sizeof(*parent));
2074 if (parent == NULL)
2075 return got_error_from_errno("calloc");
2077 parent->tree = s->tree;
2078 parent->first_displayed_entry = s->first_displayed_entry;
2079 parent->selected_entry = s->selected_entry;
2080 parent->selected = s->selected;
2081 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2082 s->tree = subtree;
2083 s->selected = 0;
2084 s->first_displayed_entry = NULL;
2085 return NULL;
2088 static const struct got_error *
2089 tree_view_walk_path(struct tog_tree_view_state *s,
2090 struct got_commit_object *commit, const char *path)
2092 const struct got_error *err = NULL;
2093 struct got_tree_object *tree = NULL;
2094 const char *p;
2095 char *slash, *subpath = NULL;
2097 /* Walk the path and open corresponding tree objects. */
2098 p = path;
2099 while (*p) {
2100 struct got_tree_entry *te;
2101 struct got_object_id *tree_id;
2102 char *te_name;
2104 while (p[0] == '/')
2105 p++;
2107 /* Ensure the correct subtree entry is selected. */
2108 slash = strchr(p, '/');
2109 if (slash == NULL)
2110 te_name = strdup(p);
2111 else
2112 te_name = strndup(p, slash - p);
2113 if (te_name == NULL) {
2114 err = got_error_from_errno("strndup");
2115 break;
2117 te = got_object_tree_find_entry(s->tree, te_name);
2118 if (te == NULL) {
2119 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2120 free(te_name);
2121 break;
2123 free(te_name);
2124 s->first_displayed_entry = s->selected_entry = te;
2126 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2127 break; /* jump to this file's entry */
2129 slash = strchr(p, '/');
2130 if (slash)
2131 subpath = strndup(path, slash - path);
2132 else
2133 subpath = strdup(path);
2134 if (subpath == NULL) {
2135 err = got_error_from_errno("strdup");
2136 break;
2139 err = got_object_id_by_path(&tree_id, s->repo, commit,
2140 subpath);
2141 if (err)
2142 break;
2144 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2145 free(tree_id);
2146 if (err)
2147 break;
2149 err = tree_view_visit_subtree(s, tree);
2150 if (err) {
2151 got_object_tree_close(tree);
2152 break;
2154 if (slash == NULL)
2155 break;
2156 free(subpath);
2157 subpath = NULL;
2158 p = slash;
2161 free(subpath);
2162 return err;
2165 static const struct got_error *
2166 browse_commit_tree(struct tog_view **new_view, int begin_x,
2167 struct commit_queue_entry *entry, const char *path,
2168 const char *head_ref_name, struct got_repository *repo)
2170 const struct got_error *err = NULL;
2171 struct tog_tree_view_state *s;
2172 struct tog_view *tree_view;
2174 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
2175 if (tree_view == NULL)
2176 return got_error_from_errno("view_open");
2178 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2179 if (err)
2180 return err;
2181 s = &tree_view->state.tree;
2183 *new_view = tree_view;
2185 if (got_path_is_root_dir(path))
2186 return NULL;
2188 return tree_view_walk_path(s, entry->commit, path);
2191 static const struct got_error *
2192 block_signals_used_by_main_thread(void)
2194 sigset_t sigset;
2195 int errcode;
2197 if (sigemptyset(&sigset) == -1)
2198 return got_error_from_errno("sigemptyset");
2200 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2201 if (sigaddset(&sigset, SIGWINCH) == -1)
2202 return got_error_from_errno("sigaddset");
2203 if (sigaddset(&sigset, SIGCONT) == -1)
2204 return got_error_from_errno("sigaddset");
2205 if (sigaddset(&sigset, SIGINT) == -1)
2206 return got_error_from_errno("sigaddset");
2207 if (sigaddset(&sigset, SIGTERM) == -1)
2208 return got_error_from_errno("sigaddset");
2210 /* ncurses handles SIGTSTP */
2211 if (sigaddset(&sigset, SIGTSTP) == -1)
2212 return got_error_from_errno("sigaddset");
2214 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2215 if (errcode)
2216 return got_error_set_errno(errcode, "pthread_sigmask");
2218 return NULL;
2221 static void *
2222 log_thread(void *arg)
2224 const struct got_error *err = NULL;
2225 int errcode = 0;
2226 struct tog_log_thread_args *a = arg;
2227 int done = 0;
2229 err = block_signals_used_by_main_thread();
2230 if (err)
2231 return (void *)err;
2233 while (!done && !err && !tog_fatal_signal_received()) {
2234 err = queue_commits(a);
2235 if (err) {
2236 if (err->code != GOT_ERR_ITER_COMPLETED)
2237 return (void *)err;
2238 err = NULL;
2239 done = 1;
2240 } else if (a->commits_needed > 0 && !a->load_all)
2241 a->commits_needed--;
2243 errcode = pthread_mutex_lock(&tog_mutex);
2244 if (errcode) {
2245 err = got_error_set_errno(errcode,
2246 "pthread_mutex_lock");
2247 break;
2248 } else if (*a->quit)
2249 done = 1;
2250 else if (*a->first_displayed_entry == NULL) {
2251 *a->first_displayed_entry =
2252 TAILQ_FIRST(&a->commits->head);
2253 *a->selected_entry = *a->first_displayed_entry;
2256 errcode = pthread_cond_signal(&a->commit_loaded);
2257 if (errcode) {
2258 err = got_error_set_errno(errcode,
2259 "pthread_cond_signal");
2260 pthread_mutex_unlock(&tog_mutex);
2261 break;
2264 if (done)
2265 a->commits_needed = 0;
2266 else {
2267 if (a->commits_needed == 0 && !a->load_all) {
2268 errcode = pthread_cond_wait(&a->need_commits,
2269 &tog_mutex);
2270 if (errcode)
2271 err = got_error_set_errno(errcode,
2272 "pthread_cond_wait");
2273 if (*a->quit)
2274 done = 1;
2278 errcode = pthread_mutex_unlock(&tog_mutex);
2279 if (errcode && err == NULL)
2280 err = got_error_set_errno(errcode,
2281 "pthread_mutex_unlock");
2283 a->log_complete = 1;
2284 return (void *)err;
2287 static const struct got_error *
2288 stop_log_thread(struct tog_log_view_state *s)
2290 const struct got_error *err = NULL;
2291 int errcode;
2293 if (s->thread) {
2294 s->quit = 1;
2295 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2296 if (errcode)
2297 return got_error_set_errno(errcode,
2298 "pthread_cond_signal");
2299 errcode = pthread_mutex_unlock(&tog_mutex);
2300 if (errcode)
2301 return got_error_set_errno(errcode,
2302 "pthread_mutex_unlock");
2303 errcode = pthread_join(s->thread, (void **)&err);
2304 if (errcode)
2305 return got_error_set_errno(errcode, "pthread_join");
2306 errcode = pthread_mutex_lock(&tog_mutex);
2307 if (errcode)
2308 return got_error_set_errno(errcode,
2309 "pthread_mutex_lock");
2310 s->thread = NULL;
2313 if (s->thread_args.repo) {
2314 err = got_repo_close(s->thread_args.repo);
2315 s->thread_args.repo = NULL;
2318 if (s->thread_args.pack_fds) {
2319 const struct got_error *pack_err =
2320 got_repo_pack_fds_close(s->thread_args.pack_fds);
2321 if (err == NULL)
2322 err = pack_err;
2323 s->thread_args.pack_fds = NULL;
2326 if (s->thread_args.graph) {
2327 got_commit_graph_close(s->thread_args.graph);
2328 s->thread_args.graph = NULL;
2331 return err;
2334 static const struct got_error *
2335 close_log_view(struct tog_view *view)
2337 const struct got_error *err = NULL;
2338 struct tog_log_view_state *s = &view->state.log;
2339 int errcode;
2341 err = stop_log_thread(s);
2343 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2344 if (errcode && err == NULL)
2345 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2347 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2348 if (errcode && err == NULL)
2349 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2351 free_commits(&s->commits);
2352 free(s->in_repo_path);
2353 s->in_repo_path = NULL;
2354 free(s->start_id);
2355 s->start_id = NULL;
2356 free(s->head_ref_name);
2357 s->head_ref_name = NULL;
2358 return err;
2361 static const struct got_error *
2362 search_start_log_view(struct tog_view *view)
2364 struct tog_log_view_state *s = &view->state.log;
2366 s->matched_entry = NULL;
2367 s->search_entry = NULL;
2368 return NULL;
2371 static const struct got_error *
2372 search_next_log_view(struct tog_view *view)
2374 const struct got_error *err = NULL;
2375 struct tog_log_view_state *s = &view->state.log;
2376 struct commit_queue_entry *entry;
2378 /* Display progress update in log view. */
2379 show_log_view(view);
2380 update_panels();
2381 doupdate();
2383 if (s->search_entry) {
2384 int errcode, ch;
2385 errcode = pthread_mutex_unlock(&tog_mutex);
2386 if (errcode)
2387 return got_error_set_errno(errcode,
2388 "pthread_mutex_unlock");
2389 ch = wgetch(view->window);
2390 errcode = pthread_mutex_lock(&tog_mutex);
2391 if (errcode)
2392 return got_error_set_errno(errcode,
2393 "pthread_mutex_lock");
2394 if (ch == KEY_BACKSPACE) {
2395 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2396 return NULL;
2398 if (view->searching == TOG_SEARCH_FORWARD)
2399 entry = TAILQ_NEXT(s->search_entry, entry);
2400 else
2401 entry = TAILQ_PREV(s->search_entry,
2402 commit_queue_head, entry);
2403 } else if (s->matched_entry) {
2404 int matched_idx = s->matched_entry->idx;
2405 int selected_idx = s->selected_entry->idx;
2408 * If the user has moved the cursor after we hit a match,
2409 * the position from where we should continue searching
2410 * might have changed.
2412 if (view->searching == TOG_SEARCH_FORWARD) {
2413 if (matched_idx > selected_idx)
2414 entry = TAILQ_NEXT(s->selected_entry, entry);
2415 else
2416 entry = TAILQ_NEXT(s->matched_entry, entry);
2417 } else {
2418 if (matched_idx < selected_idx)
2419 entry = TAILQ_PREV(s->selected_entry,
2420 commit_queue_head, entry);
2421 else
2422 entry = TAILQ_PREV(s->matched_entry,
2423 commit_queue_head, entry);
2425 } else {
2426 entry = s->selected_entry;
2429 while (1) {
2430 int have_match = 0;
2432 if (entry == NULL) {
2433 if (s->thread_args.log_complete ||
2434 view->searching == TOG_SEARCH_BACKWARD) {
2435 view->search_next_done =
2436 (s->matched_entry == NULL ?
2437 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2438 s->search_entry = NULL;
2439 return NULL;
2442 * Poke the log thread for more commits and return,
2443 * allowing the main loop to make progress. Search
2444 * will resume at s->search_entry once we come back.
2446 s->thread_args.commits_needed++;
2447 return trigger_log_thread(view, 0);
2450 err = match_commit(&have_match, entry->id, entry->commit,
2451 &view->regex);
2452 if (err)
2453 break;
2454 if (have_match) {
2455 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2456 s->matched_entry = entry;
2457 break;
2460 s->search_entry = entry;
2461 if (view->searching == TOG_SEARCH_FORWARD)
2462 entry = TAILQ_NEXT(entry, entry);
2463 else
2464 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2467 if (s->matched_entry) {
2468 int cur = s->selected_entry->idx;
2469 while (cur < s->matched_entry->idx) {
2470 err = input_log_view(NULL, view, KEY_DOWN);
2471 if (err)
2472 return err;
2473 cur++;
2475 while (cur > s->matched_entry->idx) {
2476 err = input_log_view(NULL, view, KEY_UP);
2477 if (err)
2478 return err;
2479 cur--;
2483 s->search_entry = NULL;
2485 return NULL;
2488 static const struct got_error *
2489 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2490 struct got_repository *repo, const char *head_ref_name,
2491 const char *in_repo_path, int log_branches)
2493 const struct got_error *err = NULL;
2494 struct tog_log_view_state *s = &view->state.log;
2495 struct got_repository *thread_repo = NULL;
2496 struct got_commit_graph *thread_graph = NULL;
2497 int errcode;
2499 if (in_repo_path != s->in_repo_path) {
2500 free(s->in_repo_path);
2501 s->in_repo_path = strdup(in_repo_path);
2502 if (s->in_repo_path == NULL)
2503 return got_error_from_errno("strdup");
2506 /* The commit queue only contains commits being displayed. */
2507 TAILQ_INIT(&s->commits.head);
2508 s->commits.ncommits = 0;
2510 s->repo = repo;
2511 if (head_ref_name) {
2512 s->head_ref_name = strdup(head_ref_name);
2513 if (s->head_ref_name == NULL) {
2514 err = got_error_from_errno("strdup");
2515 goto done;
2518 s->start_id = got_object_id_dup(start_id);
2519 if (s->start_id == NULL) {
2520 err = got_error_from_errno("got_object_id_dup");
2521 goto done;
2523 s->log_branches = log_branches;
2525 STAILQ_INIT(&s->colors);
2526 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2527 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2528 get_color_value("TOG_COLOR_COMMIT"));
2529 if (err)
2530 goto done;
2531 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2532 get_color_value("TOG_COLOR_AUTHOR"));
2533 if (err) {
2534 free_colors(&s->colors);
2535 goto done;
2537 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
2538 get_color_value("TOG_COLOR_DATE"));
2539 if (err) {
2540 free_colors(&s->colors);
2541 goto done;
2545 view->show = show_log_view;
2546 view->input = input_log_view;
2547 view->close = close_log_view;
2548 view->search_start = search_start_log_view;
2549 view->search_next = search_next_log_view;
2551 if (s->thread_args.pack_fds == NULL) {
2552 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2553 if (err)
2554 goto done;
2556 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
2557 s->thread_args.pack_fds);
2558 if (err)
2559 goto done;
2560 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
2561 !s->log_branches);
2562 if (err)
2563 goto done;
2564 err = got_commit_graph_iter_start(thread_graph, s->start_id,
2565 s->repo, NULL, NULL);
2566 if (err)
2567 goto done;
2569 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
2570 if (errcode) {
2571 err = got_error_set_errno(errcode, "pthread_cond_init");
2572 goto done;
2574 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
2575 if (errcode) {
2576 err = got_error_set_errno(errcode, "pthread_cond_init");
2577 goto done;
2580 s->thread_args.commits_needed = view->nlines;
2581 s->thread_args.graph = thread_graph;
2582 s->thread_args.commits = &s->commits;
2583 s->thread_args.in_repo_path = s->in_repo_path;
2584 s->thread_args.start_id = s->start_id;
2585 s->thread_args.repo = thread_repo;
2586 s->thread_args.log_complete = 0;
2587 s->thread_args.quit = &s->quit;
2588 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
2589 s->thread_args.selected_entry = &s->selected_entry;
2590 s->thread_args.searching = &view->searching;
2591 s->thread_args.search_next_done = &view->search_next_done;
2592 s->thread_args.regex = &view->regex;
2593 done:
2594 if (err)
2595 close_log_view(view);
2596 return err;
2599 static const struct got_error *
2600 show_log_view(struct tog_view *view)
2602 const struct got_error *err;
2603 struct tog_log_view_state *s = &view->state.log;
2605 if (s->thread == NULL) {
2606 int errcode = pthread_create(&s->thread, NULL, log_thread,
2607 &s->thread_args);
2608 if (errcode)
2609 return got_error_set_errno(errcode, "pthread_create");
2610 if (s->thread_args.commits_needed > 0) {
2611 err = trigger_log_thread(view, 1);
2612 if (err)
2613 return err;
2617 return draw_commits(view);
2620 static const struct got_error *
2621 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
2623 const struct got_error *err = NULL;
2624 struct tog_log_view_state *s = &view->state.log;
2625 struct tog_view *diff_view = NULL, *tree_view = NULL;
2626 struct tog_view *ref_view = NULL;
2627 struct commit_queue_entry *entry;
2628 int begin_x = 0, n, nscroll = view->nlines - 1;
2630 if (s->thread_args.load_all) {
2631 if (ch == KEY_BACKSPACE)
2632 s->thread_args.load_all = 0;
2633 else if (s->thread_args.log_complete) {
2634 s->thread_args.load_all = 0;
2635 log_scroll_down(view, s->commits.ncommits);
2636 s->selected = MIN(view->nlines - 2,
2637 s->commits.ncommits - 1);
2638 select_commit(s);
2640 return NULL;
2643 switch (ch) {
2644 case 'q':
2645 s->quit = 1;
2646 break;
2647 case '0':
2648 view->x = 0;
2649 break;
2650 case '$':
2651 view->x = MAX(view->maxx - view->ncols / 2, 0);
2652 view->count = 0;
2653 break;
2654 case KEY_RIGHT:
2655 case 'l':
2656 if (view->x + view->ncols / 2 < view->maxx)
2657 view->x += 2; /* move two columns right */
2658 else
2659 view->count = 0;
2660 break;
2661 case KEY_LEFT:
2662 case 'h':
2663 view->x -= MIN(view->x, 2); /* move two columns back */
2664 if (view->x <= 0)
2665 view->count = 0;
2666 break;
2667 case 'k':
2668 case KEY_UP:
2669 case '<':
2670 case ',':
2671 case CTRL('p'):
2672 if (s->selected_entry->idx == 0)
2673 view->count = 0;
2674 if (s->first_displayed_entry == NULL)
2675 break;
2676 if (s->selected > 0)
2677 s->selected--;
2678 else
2679 log_scroll_up(s, 1);
2680 select_commit(s);
2681 break;
2682 case 'g':
2683 case KEY_HOME:
2684 s->selected = 0;
2685 s->first_displayed_entry = TAILQ_FIRST(&s->commits.head);
2686 select_commit(s);
2687 view->count = 0;
2688 break;
2689 case CTRL('u'):
2690 case 'u':
2691 nscroll /= 2;
2692 /* FALL THROUGH */
2693 case KEY_PPAGE:
2694 case CTRL('b'):
2695 case 'b':
2696 if (s->first_displayed_entry == NULL)
2697 break;
2698 if (TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
2699 s->selected = MAX(0, s->selected - nscroll - 1);
2700 else
2701 log_scroll_up(s, nscroll);
2702 select_commit(s);
2703 if (s->selected_entry->idx == 0)
2704 view->count = 0;
2705 break;
2706 case 'j':
2707 case KEY_DOWN:
2708 case '>':
2709 case '.':
2710 case CTRL('n'):
2711 if (s->first_displayed_entry == NULL)
2712 break;
2713 if (s->selected < MIN(view->nlines - 2,
2714 s->commits.ncommits - 1))
2715 s->selected++;
2716 else {
2717 err = log_scroll_down(view, 1);
2718 if (err)
2719 break;
2721 select_commit(s);
2722 if (s->thread_args.log_complete &&
2723 s->selected_entry->idx == s->commits.ncommits - 1)
2724 view->count = 0;
2725 break;
2726 case 'G':
2727 case KEY_END: {
2728 /* We don't know yet how many commits, so we're forced to
2729 * traverse them all. */
2730 view->count = 0;
2731 if (!s->thread_args.log_complete) {
2732 s->thread_args.load_all = 1;
2733 return trigger_log_thread(view, 0);
2736 s->selected = 0;
2737 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
2738 for (n = 0; n < view->nlines - 1; n++) {
2739 if (entry == NULL)
2740 break;
2741 s->first_displayed_entry = entry;
2742 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2744 if (n > 0)
2745 s->selected = n - 1;
2746 select_commit(s);
2747 break;
2749 case CTRL('d'):
2750 case 'd':
2751 nscroll /= 2;
2752 /* FALL THROUGH */
2753 case KEY_NPAGE:
2754 case CTRL('f'):
2755 case 'f':
2756 case ' ': {
2757 struct commit_queue_entry *first;
2758 first = s->first_displayed_entry;
2759 if (first == NULL) {
2760 view->count = 0;
2761 break;
2763 err = log_scroll_down(view, nscroll);
2764 if (err)
2765 break;
2766 if (first == s->first_displayed_entry &&
2767 s->selected < MIN(view->nlines - 2,
2768 s->commits.ncommits - 1)) {
2769 /* can't scroll further down */
2770 s->selected += MIN(s->last_displayed_entry->idx -
2771 s->selected_entry->idx, nscroll + 1);
2773 select_commit(s);
2774 if (s->thread_args.log_complete &&
2775 s->selected_entry->idx == s->commits.ncommits - 1)
2776 view->count = 0;
2777 break;
2779 case KEY_RESIZE:
2780 if (s->selected > view->nlines - 2)
2781 s->selected = view->nlines - 2;
2782 if (s->selected > s->commits.ncommits - 1)
2783 s->selected = s->commits.ncommits - 1;
2784 select_commit(s);
2785 if (s->commits.ncommits < view->nlines - 1 &&
2786 !s->thread_args.log_complete) {
2787 s->thread_args.commits_needed += (view->nlines - 1) -
2788 s->commits.ncommits;
2789 err = trigger_log_thread(view, 1);
2791 break;
2792 case KEY_ENTER:
2793 case '\r':
2794 view->count = 0;
2795 if (s->selected_entry == NULL)
2796 break;
2797 if (view_is_parent_view(view))
2798 begin_x = view_split_begin_x(view->begin_x);
2799 err = open_diff_view_for_commit(&diff_view, begin_x,
2800 s->selected_entry->commit, s->selected_entry->id,
2801 view, s->repo);
2802 if (err)
2803 break;
2804 view->focussed = 0;
2805 diff_view->focussed = 1;
2806 if (view_is_parent_view(view)) {
2807 err = view_close_child(view);
2808 if (err)
2809 return err;
2810 err = view_set_child(view, diff_view);
2811 if (err)
2812 return err;
2813 view->focus_child = 1;
2814 } else
2815 *new_view = diff_view;
2816 break;
2817 case 't':
2818 view->count = 0;
2819 if (s->selected_entry == NULL)
2820 break;
2821 if (view_is_parent_view(view))
2822 begin_x = view_split_begin_x(view->begin_x);
2823 err = browse_commit_tree(&tree_view, begin_x,
2824 s->selected_entry, s->in_repo_path, s->head_ref_name,
2825 s->repo);
2826 if (err)
2827 break;
2828 view->focussed = 0;
2829 tree_view->focussed = 1;
2830 if (view_is_parent_view(view)) {
2831 err = view_close_child(view);
2832 if (err)
2833 return err;
2834 err = view_set_child(view, tree_view);
2835 if (err)
2836 return err;
2837 view->focus_child = 1;
2838 } else
2839 *new_view = tree_view;
2840 break;
2841 case KEY_BACKSPACE:
2842 case CTRL('l'):
2843 case 'B':
2844 view->count = 0;
2845 if (ch == KEY_BACKSPACE &&
2846 got_path_is_root_dir(s->in_repo_path))
2847 break;
2848 err = stop_log_thread(s);
2849 if (err)
2850 return err;
2851 if (ch == KEY_BACKSPACE) {
2852 char *parent_path;
2853 err = got_path_dirname(&parent_path, s->in_repo_path);
2854 if (err)
2855 return err;
2856 free(s->in_repo_path);
2857 s->in_repo_path = parent_path;
2858 s->thread_args.in_repo_path = s->in_repo_path;
2859 } else if (ch == CTRL('l')) {
2860 struct got_object_id *start_id;
2861 err = got_repo_match_object_id(&start_id, NULL,
2862 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
2863 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
2864 if (err)
2865 return err;
2866 free(s->start_id);
2867 s->start_id = start_id;
2868 s->thread_args.start_id = s->start_id;
2869 } else /* 'B' */
2870 s->log_branches = !s->log_branches;
2872 if (s->thread_args.pack_fds == NULL) {
2873 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2874 if (err)
2875 return err;
2877 err = got_repo_open(&s->thread_args.repo,
2878 got_repo_get_path(s->repo), NULL,
2879 s->thread_args.pack_fds);
2880 if (err)
2881 return err;
2882 tog_free_refs();
2883 err = tog_load_refs(s->repo, 0);
2884 if (err)
2885 return err;
2886 err = got_commit_graph_open(&s->thread_args.graph,
2887 s->in_repo_path, !s->log_branches);
2888 if (err)
2889 return err;
2890 err = got_commit_graph_iter_start(s->thread_args.graph,
2891 s->start_id, s->repo, NULL, NULL);
2892 if (err)
2893 return err;
2894 free_commits(&s->commits);
2895 s->first_displayed_entry = NULL;
2896 s->last_displayed_entry = NULL;
2897 s->selected_entry = NULL;
2898 s->selected = 0;
2899 s->thread_args.log_complete = 0;
2900 s->quit = 0;
2901 s->thread_args.commits_needed = view->nlines;
2902 s->matched_entry = NULL;
2903 s->search_entry = NULL;
2904 break;
2905 case 'r':
2906 view->count = 0;
2907 if (view_is_parent_view(view))
2908 begin_x = view_split_begin_x(view->begin_x);
2909 ref_view = view_open(view->nlines, view->ncols,
2910 view->begin_y, begin_x, TOG_VIEW_REF);
2911 if (ref_view == NULL)
2912 return got_error_from_errno("view_open");
2913 err = open_ref_view(ref_view, s->repo);
2914 if (err) {
2915 view_close(ref_view);
2916 return err;
2918 view->focussed = 0;
2919 ref_view->focussed = 1;
2920 if (view_is_parent_view(view)) {
2921 err = view_close_child(view);
2922 if (err)
2923 return err;
2924 err = view_set_child(view, ref_view);
2925 if (err)
2926 return err;
2927 view->focus_child = 1;
2928 } else
2929 *new_view = ref_view;
2930 break;
2931 default:
2932 view->count = 0;
2933 break;
2936 return err;
2939 static const struct got_error *
2940 apply_unveil(const char *repo_path, const char *worktree_path)
2942 const struct got_error *error;
2944 #ifdef PROFILE
2945 if (unveil("gmon.out", "rwc") != 0)
2946 return got_error_from_errno2("unveil", "gmon.out");
2947 #endif
2948 if (repo_path && unveil(repo_path, "r") != 0)
2949 return got_error_from_errno2("unveil", repo_path);
2951 if (worktree_path && unveil(worktree_path, "rwc") != 0)
2952 return got_error_from_errno2("unveil", worktree_path);
2954 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
2955 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
2957 error = got_privsep_unveil_exec_helpers();
2958 if (error != NULL)
2959 return error;
2961 if (unveil(NULL, NULL) != 0)
2962 return got_error_from_errno("unveil");
2964 return NULL;
2967 static void
2968 init_curses(void)
2971 * Override default signal handlers before starting ncurses.
2972 * This should prevent ncurses from installing its own
2973 * broken cleanup() signal handler.
2975 signal(SIGWINCH, tog_sigwinch);
2976 signal(SIGPIPE, tog_sigpipe);
2977 signal(SIGCONT, tog_sigcont);
2978 signal(SIGINT, tog_sigint);
2979 signal(SIGTERM, tog_sigterm);
2981 initscr();
2982 cbreak();
2983 halfdelay(1); /* Do fast refresh while initial view is loading. */
2984 noecho();
2985 nonl();
2986 intrflush(stdscr, FALSE);
2987 keypad(stdscr, TRUE);
2988 curs_set(0);
2989 if (getenv("TOG_COLORS") != NULL) {
2990 start_color();
2991 use_default_colors();
2995 static const struct got_error *
2996 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
2997 struct got_repository *repo, struct got_worktree *worktree)
2999 const struct got_error *err = NULL;
3001 if (argc == 0) {
3002 *in_repo_path = strdup("/");
3003 if (*in_repo_path == NULL)
3004 return got_error_from_errno("strdup");
3005 return NULL;
3008 if (worktree) {
3009 const char *prefix = got_worktree_get_path_prefix(worktree);
3010 char *p;
3012 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3013 if (err)
3014 return err;
3015 if (asprintf(in_repo_path, "%s%s%s", prefix,
3016 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3017 p) == -1) {
3018 err = got_error_from_errno("asprintf");
3019 *in_repo_path = NULL;
3021 free(p);
3022 } else
3023 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3025 return err;
3028 static const struct got_error *
3029 cmd_log(int argc, char *argv[])
3031 const struct got_error *error;
3032 struct got_repository *repo = NULL;
3033 struct got_worktree *worktree = NULL;
3034 struct got_object_id *start_id = NULL;
3035 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3036 char *start_commit = NULL, *label = NULL;
3037 struct got_reference *ref = NULL;
3038 const char *head_ref_name = NULL;
3039 int ch, log_branches = 0;
3040 struct tog_view *view;
3041 int *pack_fds = NULL;
3043 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3044 switch (ch) {
3045 case 'b':
3046 log_branches = 1;
3047 break;
3048 case 'c':
3049 start_commit = optarg;
3050 break;
3051 case 'r':
3052 repo_path = realpath(optarg, NULL);
3053 if (repo_path == NULL)
3054 return got_error_from_errno2("realpath",
3055 optarg);
3056 break;
3057 default:
3058 usage_log();
3059 /* NOTREACHED */
3063 argc -= optind;
3064 argv += optind;
3066 if (argc > 1)
3067 usage_log();
3069 error = got_repo_pack_fds_open(&pack_fds);
3070 if (error != NULL)
3071 goto done;
3073 if (repo_path == NULL) {
3074 cwd = getcwd(NULL, 0);
3075 if (cwd == NULL)
3076 return got_error_from_errno("getcwd");
3077 error = got_worktree_open(&worktree, cwd);
3078 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3079 goto done;
3080 if (worktree)
3081 repo_path =
3082 strdup(got_worktree_get_repo_path(worktree));
3083 else
3084 repo_path = strdup(cwd);
3085 if (repo_path == NULL) {
3086 error = got_error_from_errno("strdup");
3087 goto done;
3091 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3092 if (error != NULL)
3093 goto done;
3095 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3096 repo, worktree);
3097 if (error)
3098 goto done;
3100 init_curses();
3102 error = apply_unveil(got_repo_get_path(repo),
3103 worktree ? got_worktree_get_root_path(worktree) : NULL);
3104 if (error)
3105 goto done;
3107 /* already loaded by tog_log_with_path()? */
3108 if (TAILQ_EMPTY(&tog_refs)) {
3109 error = tog_load_refs(repo, 0);
3110 if (error)
3111 goto done;
3114 if (start_commit == NULL) {
3115 error = got_repo_match_object_id(&start_id, &label,
3116 worktree ? got_worktree_get_head_ref_name(worktree) :
3117 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3118 if (error)
3119 goto done;
3120 head_ref_name = label;
3121 } else {
3122 error = got_ref_open(&ref, repo, start_commit, 0);
3123 if (error == NULL)
3124 head_ref_name = got_ref_get_name(ref);
3125 else if (error->code != GOT_ERR_NOT_REF)
3126 goto done;
3127 error = got_repo_match_object_id(&start_id, NULL,
3128 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3129 if (error)
3130 goto done;
3133 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3134 if (view == NULL) {
3135 error = got_error_from_errno("view_open");
3136 goto done;
3138 error = open_log_view(view, start_id, repo, head_ref_name,
3139 in_repo_path, log_branches);
3140 if (error)
3141 goto done;
3142 if (worktree) {
3143 /* Release work tree lock. */
3144 got_worktree_close(worktree);
3145 worktree = NULL;
3147 error = view_loop(view);
3148 done:
3149 free(in_repo_path);
3150 free(repo_path);
3151 free(cwd);
3152 free(start_id);
3153 free(label);
3154 if (ref)
3155 got_ref_close(ref);
3156 if (repo) {
3157 const struct got_error *close_err = got_repo_close(repo);
3158 if (error == NULL)
3159 error = close_err;
3161 if (worktree)
3162 got_worktree_close(worktree);
3163 if (pack_fds) {
3164 const struct got_error *pack_err =
3165 got_repo_pack_fds_close(pack_fds);
3166 if (error == NULL)
3167 error = pack_err;
3169 tog_free_refs();
3170 return error;
3173 __dead static void
3174 usage_diff(void)
3176 endwin();
3177 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3178 "[-w] object1 object2\n", getprogname());
3179 exit(1);
3182 static int
3183 match_line(const char *line, regex_t *regex, size_t nmatch,
3184 regmatch_t *regmatch)
3186 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3189 static struct tog_color *
3190 match_color(struct tog_colors *colors, const char *line)
3192 struct tog_color *tc = NULL;
3194 STAILQ_FOREACH(tc, colors, entry) {
3195 if (match_line(line, &tc->regex, 0, NULL))
3196 return tc;
3199 return NULL;
3202 static const struct got_error *
3203 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3204 WINDOW *window, int skipcol, regmatch_t *regmatch)
3206 const struct got_error *err = NULL;
3207 char *exstr = NULL;
3208 wchar_t *wline = NULL;
3209 int rme, rms, n, width, scrollx;
3210 int width0 = 0, width1 = 0, width2 = 0;
3211 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3213 *wtotal = 0;
3215 rms = regmatch->rm_so;
3216 rme = regmatch->rm_eo;
3218 err = expand_tab(&exstr, line);
3219 if (err)
3220 return err;
3222 /* Split the line into 3 segments, according to match offsets. */
3223 seg0 = strndup(exstr, rms);
3224 if (seg0 == NULL) {
3225 err = got_error_from_errno("strndup");
3226 goto done;
3228 seg1 = strndup(exstr + rms, rme - rms);
3229 if (seg1 == NULL) {
3230 err = got_error_from_errno("strndup");
3231 goto done;
3233 seg2 = strdup(exstr + rme);
3234 if (seg2 == NULL) {
3235 err = got_error_from_errno("strndup");
3236 goto done;
3239 /* draw up to matched token if we haven't scrolled past it */
3240 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3241 col_tab_align, 1);
3242 if (err)
3243 goto done;
3244 n = MAX(width0 - skipcol, 0);
3245 if (n) {
3246 free(wline);
3247 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3248 wlimit, col_tab_align, 1);
3249 if (err)
3250 goto done;
3251 waddwstr(window, &wline[scrollx]);
3252 wlimit -= width;
3253 *wtotal += width;
3256 if (wlimit > 0) {
3257 int i = 0, w = 0;
3258 size_t wlen;
3260 free(wline);
3261 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3262 col_tab_align, 1);
3263 if (err)
3264 goto done;
3265 wlen = wcslen(wline);
3266 while (i < wlen) {
3267 width = wcwidth(wline[i]);
3268 if (width == -1) {
3269 /* should not happen, tabs are expanded */
3270 err = got_error(GOT_ERR_RANGE);
3271 goto done;
3273 if (width0 + w + width > skipcol)
3274 break;
3275 w += width;
3276 i++;
3278 /* draw (visible part of) matched token (if scrolled into it) */
3279 if (width1 - w > 0) {
3280 wattron(window, A_STANDOUT);
3281 waddwstr(window, &wline[i]);
3282 wattroff(window, A_STANDOUT);
3283 wlimit -= (width1 - w);
3284 *wtotal += (width1 - w);
3288 if (wlimit > 0) { /* draw rest of line */
3289 free(wline);
3290 if (skipcol > width0 + width1) {
3291 err = format_line(&wline, &width2, &scrollx, seg2,
3292 skipcol - (width0 + width1), wlimit,
3293 col_tab_align, 1);
3294 if (err)
3295 goto done;
3296 waddwstr(window, &wline[scrollx]);
3297 } else {
3298 err = format_line(&wline, &width2, NULL, seg2, 0,
3299 wlimit, col_tab_align, 1);
3300 if (err)
3301 goto done;
3302 waddwstr(window, wline);
3304 *wtotal += width2;
3306 done:
3307 free(wline);
3308 free(exstr);
3309 free(seg0);
3310 free(seg1);
3311 free(seg2);
3312 return err;
3315 static const struct got_error *
3316 draw_file(struct tog_view *view, const char *header)
3318 struct tog_diff_view_state *s = &view->state.diff;
3319 regmatch_t *regmatch = &view->regmatch;
3320 const struct got_error *err;
3321 int nprinted = 0;
3322 char *line;
3323 size_t linesize = 0;
3324 ssize_t linelen;
3325 struct tog_color *tc;
3326 wchar_t *wline;
3327 int width;
3328 int max_lines = view->nlines;
3329 int nlines = s->nlines;
3330 off_t line_offset;
3332 line_offset = s->line_offsets[s->first_displayed_line - 1];
3333 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3334 return got_error_from_errno("fseek");
3336 werase(view->window);
3338 if (header) {
3339 if (asprintf(&line, "[%d/%d] %s",
3340 s->first_displayed_line - 1 + s->selected_line, nlines,
3341 header) == -1)
3342 return got_error_from_errno("asprintf");
3343 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3344 0, 0);
3345 free(line);
3346 if (err)
3347 return err;
3349 if (view_needs_focus_indication(view))
3350 wstandout(view->window);
3351 waddwstr(view->window, wline);
3352 free(wline);
3353 wline = NULL;
3354 if (view_needs_focus_indication(view))
3355 wstandend(view->window);
3356 if (width <= view->ncols - 1)
3357 waddch(view->window, '\n');
3359 if (max_lines <= 1)
3360 return NULL;
3361 max_lines--;
3364 s->eof = 0;
3365 view->maxx = 0;
3366 line = NULL;
3367 while (max_lines > 0 && nprinted < max_lines) {
3368 linelen = getline(&line, &linesize, s->f);
3369 if (linelen == -1) {
3370 if (feof(s->f)) {
3371 s->eof = 1;
3372 break;
3374 free(line);
3375 return got_ferror(s->f, GOT_ERR_IO);
3378 /* Set view->maxx based on full line length. */
3379 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3380 view->x ? 1 : 0);
3381 if (err) {
3382 free(line);
3383 return err;
3385 view->maxx = MAX(view->maxx, width);
3386 free(wline);
3387 wline = NULL;
3389 tc = match_color(&s->colors, line);
3390 if (tc)
3391 wattr_on(view->window,
3392 COLOR_PAIR(tc->colorpair), NULL);
3393 if (s->first_displayed_line + nprinted == s->matched_line &&
3394 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3395 err = add_matched_line(&width, line, view->ncols, 0,
3396 view->window, view->x, regmatch);
3397 if (err) {
3398 free(line);
3399 return err;
3401 } else {
3402 int skip;
3403 err = format_line(&wline, &width, &skip, line,
3404 view->x, view->ncols, 0, view->x ? 1 : 0);
3405 if (err) {
3406 free(line);
3407 return err;
3409 waddwstr(view->window, &wline[skip]);
3410 free(wline);
3411 wline = NULL;
3413 if (tc)
3414 wattr_off(view->window,
3415 COLOR_PAIR(tc->colorpair), NULL);
3416 if (width <= view->ncols - 1)
3417 waddch(view->window, '\n');
3418 nprinted++;
3420 free(line);
3421 if (nprinted >= 1)
3422 s->last_displayed_line = s->first_displayed_line +
3423 (nprinted - 1);
3424 else
3425 s->last_displayed_line = s->first_displayed_line;
3427 view_vborder(view);
3429 if (s->eof) {
3430 while (nprinted < view->nlines) {
3431 waddch(view->window, '\n');
3432 nprinted++;
3435 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3436 view->ncols, 0, 0);
3437 if (err) {
3438 return err;
3441 wstandout(view->window);
3442 waddwstr(view->window, wline);
3443 free(wline);
3444 wline = NULL;
3445 wstandend(view->window);
3448 return NULL;
3451 static char *
3452 get_datestr(time_t *time, char *datebuf)
3454 struct tm mytm, *tm;
3455 char *p, *s;
3457 tm = gmtime_r(time, &mytm);
3458 if (tm == NULL)
3459 return NULL;
3460 s = asctime_r(tm, datebuf);
3461 if (s == NULL)
3462 return NULL;
3463 p = strchr(s, '\n');
3464 if (p)
3465 *p = '\0';
3466 return s;
3469 static const struct got_error *
3470 get_changed_paths(struct got_pathlist_head *paths,
3471 struct got_commit_object *commit, struct got_repository *repo)
3473 const struct got_error *err = NULL;
3474 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3475 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3476 struct got_object_qid *qid;
3478 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3479 if (qid != NULL) {
3480 struct got_commit_object *pcommit;
3481 err = got_object_open_as_commit(&pcommit, repo,
3482 &qid->id);
3483 if (err)
3484 return err;
3486 tree_id1 = got_object_id_dup(
3487 got_object_commit_get_tree_id(pcommit));
3488 if (tree_id1 == NULL) {
3489 got_object_commit_close(pcommit);
3490 return got_error_from_errno("got_object_id_dup");
3492 got_object_commit_close(pcommit);
3496 if (tree_id1) {
3497 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3498 if (err)
3499 goto done;
3502 tree_id2 = got_object_commit_get_tree_id(commit);
3503 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3504 if (err)
3505 goto done;
3507 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
3508 got_diff_tree_collect_changed_paths, paths, 0);
3509 done:
3510 if (tree1)
3511 got_object_tree_close(tree1);
3512 if (tree2)
3513 got_object_tree_close(tree2);
3514 free(tree_id1);
3515 return err;
3518 static const struct got_error *
3519 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
3521 off_t *p;
3523 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
3524 if (p == NULL)
3525 return got_error_from_errno("reallocarray");
3526 *line_offsets = p;
3527 (*line_offsets)[*nlines] = off;
3528 (*nlines)++;
3529 return NULL;
3532 static const struct got_error *
3533 write_commit_info(off_t **line_offsets, size_t *nlines,
3534 struct got_object_id *commit_id, struct got_reflist_head *refs,
3535 struct got_repository *repo, FILE *outfile)
3537 const struct got_error *err = NULL;
3538 char datebuf[26], *datestr;
3539 struct got_commit_object *commit;
3540 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
3541 time_t committer_time;
3542 const char *author, *committer;
3543 char *refs_str = NULL;
3544 struct got_pathlist_head changed_paths;
3545 struct got_pathlist_entry *pe;
3546 off_t outoff = 0;
3547 int n;
3549 TAILQ_INIT(&changed_paths);
3551 if (refs) {
3552 err = build_refs_str(&refs_str, refs, commit_id, repo);
3553 if (err)
3554 return err;
3557 err = got_object_open_as_commit(&commit, repo, commit_id);
3558 if (err)
3559 return err;
3561 err = got_object_id_str(&id_str, commit_id);
3562 if (err) {
3563 err = got_error_from_errno("got_object_id_str");
3564 goto done;
3567 err = add_line_offset(line_offsets, nlines, 0);
3568 if (err)
3569 goto done;
3571 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3572 refs_str ? refs_str : "", refs_str ? ")" : "");
3573 if (n < 0) {
3574 err = got_error_from_errno("fprintf");
3575 goto done;
3577 outoff += n;
3578 err = add_line_offset(line_offsets, nlines, outoff);
3579 if (err)
3580 goto done;
3582 n = fprintf(outfile, "from: %s\n",
3583 got_object_commit_get_author(commit));
3584 if (n < 0) {
3585 err = got_error_from_errno("fprintf");
3586 goto done;
3588 outoff += n;
3589 err = add_line_offset(line_offsets, nlines, outoff);
3590 if (err)
3591 goto done;
3593 committer_time = got_object_commit_get_committer_time(commit);
3594 datestr = get_datestr(&committer_time, datebuf);
3595 if (datestr) {
3596 n = fprintf(outfile, "date: %s UTC\n", datestr);
3597 if (n < 0) {
3598 err = got_error_from_errno("fprintf");
3599 goto done;
3601 outoff += n;
3602 err = add_line_offset(line_offsets, nlines, outoff);
3603 if (err)
3604 goto done;
3606 author = got_object_commit_get_author(commit);
3607 committer = got_object_commit_get_committer(commit);
3608 if (strcmp(author, committer) != 0) {
3609 n = fprintf(outfile, "via: %s\n", committer);
3610 if (n < 0) {
3611 err = got_error_from_errno("fprintf");
3612 goto done;
3614 outoff += n;
3615 err = add_line_offset(line_offsets, nlines, outoff);
3616 if (err)
3617 goto done;
3619 if (got_object_commit_get_nparents(commit) > 1) {
3620 const struct got_object_id_queue *parent_ids;
3621 struct got_object_qid *qid;
3622 int pn = 1;
3623 parent_ids = got_object_commit_get_parent_ids(commit);
3624 STAILQ_FOREACH(qid, parent_ids, entry) {
3625 err = got_object_id_str(&id_str, &qid->id);
3626 if (err)
3627 goto done;
3628 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
3629 if (n < 0) {
3630 err = got_error_from_errno("fprintf");
3631 goto done;
3633 outoff += n;
3634 err = add_line_offset(line_offsets, nlines, outoff);
3635 if (err)
3636 goto done;
3637 free(id_str);
3638 id_str = NULL;
3642 err = got_object_commit_get_logmsg(&logmsg, commit);
3643 if (err)
3644 goto done;
3645 s = logmsg;
3646 while ((line = strsep(&s, "\n")) != NULL) {
3647 n = fprintf(outfile, "%s\n", line);
3648 if (n < 0) {
3649 err = got_error_from_errno("fprintf");
3650 goto done;
3652 outoff += n;
3653 err = add_line_offset(line_offsets, nlines, outoff);
3654 if (err)
3655 goto done;
3658 err = get_changed_paths(&changed_paths, commit, repo);
3659 if (err)
3660 goto done;
3661 TAILQ_FOREACH(pe, &changed_paths, entry) {
3662 struct got_diff_changed_path *cp = pe->data;
3663 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
3664 if (n < 0) {
3665 err = got_error_from_errno("fprintf");
3666 goto done;
3668 outoff += n;
3669 err = add_line_offset(line_offsets, nlines, outoff);
3670 if (err)
3671 goto done;
3672 free((char *)pe->path);
3673 free(pe->data);
3676 fputc('\n', outfile);
3677 outoff++;
3678 err = add_line_offset(line_offsets, nlines, outoff);
3679 done:
3680 got_pathlist_free(&changed_paths);
3681 free(id_str);
3682 free(logmsg);
3683 free(refs_str);
3684 got_object_commit_close(commit);
3685 if (err) {
3686 free(*line_offsets);
3687 *line_offsets = NULL;
3688 *nlines = 0;
3690 return err;
3693 static const struct got_error *
3694 create_diff(struct tog_diff_view_state *s)
3696 const struct got_error *err = NULL;
3697 FILE *f = NULL;
3698 int obj_type;
3700 free(s->line_offsets);
3701 s->line_offsets = malloc(sizeof(off_t));
3702 if (s->line_offsets == NULL)
3703 return got_error_from_errno("malloc");
3704 s->nlines = 0;
3706 f = got_opentemp();
3707 if (f == NULL) {
3708 err = got_error_from_errno("got_opentemp");
3709 goto done;
3711 if (s->f && fclose(s->f) == EOF) {
3712 err = got_error_from_errno("fclose");
3713 goto done;
3715 s->f = f;
3717 if (s->id1)
3718 err = got_object_get_type(&obj_type, s->repo, s->id1);
3719 else
3720 err = got_object_get_type(&obj_type, s->repo, s->id2);
3721 if (err)
3722 goto done;
3724 switch (obj_type) {
3725 case GOT_OBJ_TYPE_BLOB:
3726 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
3727 s->f1, s->f2, s->id1, s->id2, s->label1, s->label2,
3728 s->diff_context, s->ignore_whitespace, s->force_text_diff,
3729 s->repo, s->f);
3730 break;
3731 case GOT_OBJ_TYPE_TREE:
3732 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
3733 s->f1, s->f2, s->id1, s->id2, NULL, "", "", s->diff_context,
3734 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
3735 break;
3736 case GOT_OBJ_TYPE_COMMIT: {
3737 const struct got_object_id_queue *parent_ids;
3738 struct got_object_qid *pid;
3739 struct got_commit_object *commit2;
3740 struct got_reflist_head *refs;
3742 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
3743 if (err)
3744 goto done;
3745 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
3746 /* Show commit info if we're diffing to a parent/root commit. */
3747 if (s->id1 == NULL) {
3748 err = write_commit_info(&s->line_offsets, &s->nlines,
3749 s->id2, refs, s->repo, s->f);
3750 if (err)
3751 goto done;
3752 } else {
3753 parent_ids = got_object_commit_get_parent_ids(commit2);
3754 STAILQ_FOREACH(pid, parent_ids, entry) {
3755 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
3756 err = write_commit_info(
3757 &s->line_offsets, &s->nlines,
3758 s->id2, refs, s->repo, s->f);
3759 if (err)
3760 goto done;
3761 break;
3765 got_object_commit_close(commit2);
3767 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
3768 s->f1, s->f2, s->id1, s->id2, NULL, s->diff_context,
3769 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
3770 break;
3772 default:
3773 err = got_error(GOT_ERR_OBJ_TYPE);
3774 break;
3776 if (err)
3777 goto done;
3778 done:
3779 if (s->f && fflush(s->f) != 0 && err == NULL)
3780 err = got_error_from_errno("fflush");
3781 return err;
3784 static void
3785 diff_view_indicate_progress(struct tog_view *view)
3787 mvwaddstr(view->window, 0, 0, "diffing...");
3788 update_panels();
3789 doupdate();
3792 static const struct got_error *
3793 search_start_diff_view(struct tog_view *view)
3795 struct tog_diff_view_state *s = &view->state.diff;
3797 s->matched_line = 0;
3798 return NULL;
3801 static const struct got_error *
3802 search_next_diff_view(struct tog_view *view)
3804 struct tog_diff_view_state *s = &view->state.diff;
3805 const struct got_error *err = NULL;
3806 int lineno;
3807 char *line = NULL;
3808 size_t linesize = 0;
3809 ssize_t linelen;
3811 if (!view->searching) {
3812 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3813 return NULL;
3816 if (s->matched_line) {
3817 if (view->searching == TOG_SEARCH_FORWARD)
3818 lineno = s->matched_line + 1;
3819 else
3820 lineno = s->matched_line - 1;
3821 } else
3822 lineno = s->first_displayed_line;
3824 while (1) {
3825 off_t offset;
3827 if (lineno <= 0 || lineno > s->nlines) {
3828 if (s->matched_line == 0) {
3829 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3830 break;
3833 if (view->searching == TOG_SEARCH_FORWARD)
3834 lineno = 1;
3835 else
3836 lineno = s->nlines;
3839 offset = s->line_offsets[lineno - 1];
3840 if (fseeko(s->f, offset, SEEK_SET) != 0) {
3841 free(line);
3842 return got_error_from_errno("fseeko");
3844 linelen = getline(&line, &linesize, s->f);
3845 if (linelen != -1) {
3846 char *exstr;
3847 err = expand_tab(&exstr, line);
3848 if (err)
3849 break;
3850 if (match_line(exstr, &view->regex, 1,
3851 &view->regmatch)) {
3852 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3853 s->matched_line = lineno;
3854 free(exstr);
3855 break;
3857 free(exstr);
3859 if (view->searching == TOG_SEARCH_FORWARD)
3860 lineno++;
3861 else
3862 lineno--;
3864 free(line);
3866 if (s->matched_line) {
3867 s->first_displayed_line = s->matched_line;
3868 s->selected_line = 1;
3871 return err;
3874 static const struct got_error *
3875 close_diff_view(struct tog_view *view)
3877 const struct got_error *err = NULL;
3878 struct tog_diff_view_state *s = &view->state.diff;
3880 free(s->id1);
3881 s->id1 = NULL;
3882 free(s->id2);
3883 s->id2 = NULL;
3884 if (s->f && fclose(s->f) == EOF)
3885 err = got_error_from_errno("fclose");
3886 s->f = NULL;
3887 if (s->f1 && fclose(s->f1) == EOF)
3888 err = got_error_from_errno("fclose");
3889 s->f1 = NULL;
3890 if (s->f2 && fclose(s->f2) == EOF)
3891 err = got_error_from_errno("fclose");
3892 s->f2 = NULL;
3893 free_colors(&s->colors);
3894 free(s->line_offsets);
3895 s->line_offsets = NULL;
3896 s->nlines = 0;
3897 return err;
3900 static const struct got_error *
3901 open_diff_view(struct tog_view *view, struct got_object_id *id1,
3902 struct got_object_id *id2, const char *label1, const char *label2,
3903 int diff_context, int ignore_whitespace, int force_text_diff,
3904 struct tog_view *log_view, struct got_repository *repo)
3906 const struct got_error *err;
3907 struct tog_diff_view_state *s = &view->state.diff;
3909 memset(s, 0, sizeof(*s));
3911 if (id1 != NULL && id2 != NULL) {
3912 int type1, type2;
3913 err = got_object_get_type(&type1, repo, id1);
3914 if (err)
3915 return err;
3916 err = got_object_get_type(&type2, repo, id2);
3917 if (err)
3918 return err;
3920 if (type1 != type2)
3921 return got_error(GOT_ERR_OBJ_TYPE);
3923 s->first_displayed_line = 1;
3924 s->last_displayed_line = view->nlines;
3925 s->selected_line = 1;
3926 s->repo = repo;
3927 s->id1 = id1;
3928 s->id2 = id2;
3929 s->label1 = label1;
3930 s->label2 = label2;
3932 if (id1) {
3933 s->id1 = got_object_id_dup(id1);
3934 if (s->id1 == NULL)
3935 return got_error_from_errno("got_object_id_dup");
3936 } else
3937 s->id1 = NULL;
3939 s->id2 = got_object_id_dup(id2);
3940 if (s->id2 == NULL) {
3941 err = got_error_from_errno("got_object_id_dup");
3942 goto done;
3945 s->f1 = got_opentemp();
3946 if (s->f1 == NULL) {
3947 err = got_error_from_errno("got_opentemp");
3948 goto done;
3951 s->f2 = got_opentemp();
3952 if (s->f2 == NULL) {
3953 err = got_error_from_errno("got_opentemp");
3954 goto done;
3957 s->first_displayed_line = 1;
3958 s->last_displayed_line = view->nlines;
3959 s->diff_context = diff_context;
3960 s->ignore_whitespace = ignore_whitespace;
3961 s->force_text_diff = force_text_diff;
3962 s->log_view = log_view;
3963 s->repo = repo;
3965 STAILQ_INIT(&s->colors);
3966 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3967 err = add_color(&s->colors,
3968 "^-", TOG_COLOR_DIFF_MINUS,
3969 get_color_value("TOG_COLOR_DIFF_MINUS"));
3970 if (err)
3971 goto done;
3972 err = add_color(&s->colors, "^\\+",
3973 TOG_COLOR_DIFF_PLUS,
3974 get_color_value("TOG_COLOR_DIFF_PLUS"));
3975 if (err)
3976 goto done;
3977 err = add_color(&s->colors,
3978 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
3979 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
3980 if (err)
3981 goto done;
3983 err = add_color(&s->colors,
3984 "^(commit [0-9a-f]|parent [0-9]|"
3985 "(blob|file|tree|commit) [-+] |"
3986 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
3987 get_color_value("TOG_COLOR_DIFF_META"));
3988 if (err)
3989 goto done;
3991 err = add_color(&s->colors,
3992 "^(from|via): ", TOG_COLOR_AUTHOR,
3993 get_color_value("TOG_COLOR_AUTHOR"));
3994 if (err)
3995 goto done;
3997 err = add_color(&s->colors,
3998 "^date: ", TOG_COLOR_DATE,
3999 get_color_value("TOG_COLOR_DATE"));
4000 if (err)
4001 goto done;
4004 if (log_view && view_is_splitscreen(view))
4005 show_log_view(log_view); /* draw vborder */
4006 diff_view_indicate_progress(view);
4008 err = create_diff(s);
4010 view->show = show_diff_view;
4011 view->input = input_diff_view;
4012 view->close = close_diff_view;
4013 view->search_start = search_start_diff_view;
4014 view->search_next = search_next_diff_view;
4015 done:
4016 if (err)
4017 close_diff_view(view);
4018 return err;
4021 static const struct got_error *
4022 show_diff_view(struct tog_view *view)
4024 const struct got_error *err;
4025 struct tog_diff_view_state *s = &view->state.diff;
4026 char *id_str1 = NULL, *id_str2, *header;
4027 const char *label1, *label2;
4029 if (s->id1) {
4030 err = got_object_id_str(&id_str1, s->id1);
4031 if (err)
4032 return err;
4033 label1 = s->label1 ? : id_str1;
4034 } else
4035 label1 = "/dev/null";
4037 err = got_object_id_str(&id_str2, s->id2);
4038 if (err)
4039 return err;
4040 label2 = s->label2 ? : id_str2;
4042 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4043 err = got_error_from_errno("asprintf");
4044 free(id_str1);
4045 free(id_str2);
4046 return err;
4048 free(id_str1);
4049 free(id_str2);
4051 err = draw_file(view, header);
4052 free(header);
4053 return err;
4056 static const struct got_error *
4057 set_selected_commit(struct tog_diff_view_state *s,
4058 struct commit_queue_entry *entry)
4060 const struct got_error *err;
4061 const struct got_object_id_queue *parent_ids;
4062 struct got_commit_object *selected_commit;
4063 struct got_object_qid *pid;
4065 free(s->id2);
4066 s->id2 = got_object_id_dup(entry->id);
4067 if (s->id2 == NULL)
4068 return got_error_from_errno("got_object_id_dup");
4070 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4071 if (err)
4072 return err;
4073 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4074 free(s->id1);
4075 pid = STAILQ_FIRST(parent_ids);
4076 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4077 got_object_commit_close(selected_commit);
4078 return NULL;
4081 static const struct got_error *
4082 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4084 const struct got_error *err = NULL;
4085 struct tog_diff_view_state *s = &view->state.diff;
4086 struct tog_log_view_state *ls;
4087 struct commit_queue_entry *old_selected_entry;
4088 char *line = NULL;
4089 size_t linesize = 0;
4090 ssize_t linelen;
4091 int i, nscroll = view->nlines - 1;
4093 switch (ch) {
4094 case '0':
4095 view->x = 0;
4096 break;
4097 case '$':
4098 view->x = MAX(view->maxx - view->ncols / 3, 0);
4099 view->count = 0;
4100 break;
4101 case KEY_RIGHT:
4102 case 'l':
4103 if (view->x + view->ncols / 3 < view->maxx)
4104 view->x += 2; /* move two columns right */
4105 else
4106 view->count = 0;
4107 break;
4108 case KEY_LEFT:
4109 case 'h':
4110 view->x -= MIN(view->x, 2); /* move two columns back */
4111 if (view->x <= 0)
4112 view->count = 0;
4113 break;
4114 case 'a':
4115 case 'w':
4116 if (ch == 'a')
4117 s->force_text_diff = !s->force_text_diff;
4118 if (ch == 'w')
4119 s->ignore_whitespace = !s->ignore_whitespace;
4120 wclear(view->window);
4121 s->first_displayed_line = 1;
4122 s->last_displayed_line = view->nlines;
4123 s->matched_line = 0;
4124 diff_view_indicate_progress(view);
4125 err = create_diff(s);
4126 view->count = 0;
4127 break;
4128 case 'g':
4129 case KEY_HOME:
4130 s->first_displayed_line = 1;
4131 view->count = 0;
4132 break;
4133 case 'G':
4134 case KEY_END:
4135 view->count = 0;
4136 if (s->eof)
4137 break;
4139 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4140 s->eof = 1;
4141 break;
4142 case 'k':
4143 case KEY_UP:
4144 case CTRL('p'):
4145 if (s->first_displayed_line > 1)
4146 s->first_displayed_line--;
4147 else
4148 view->count = 0;
4149 break;
4150 case CTRL('u'):
4151 case 'u':
4152 nscroll /= 2;
4153 /* FALL THROUGH */
4154 case KEY_PPAGE:
4155 case CTRL('b'):
4156 case 'b':
4157 if (s->first_displayed_line == 1) {
4158 view->count = 0;
4159 break;
4161 i = 0;
4162 while (i++ < nscroll && s->first_displayed_line > 1)
4163 s->first_displayed_line--;
4164 break;
4165 case 'j':
4166 case KEY_DOWN:
4167 case CTRL('n'):
4168 if (!s->eof)
4169 s->first_displayed_line++;
4170 else
4171 view->count = 0;
4172 break;
4173 case CTRL('d'):
4174 case 'd':
4175 nscroll /= 2;
4176 /* FALL THROUGH */
4177 case KEY_NPAGE:
4178 case CTRL('f'):
4179 case 'f':
4180 case ' ':
4181 if (s->eof) {
4182 view->count = 0;
4183 break;
4185 i = 0;
4186 while (!s->eof && i++ < nscroll) {
4187 linelen = getline(&line, &linesize, s->f);
4188 s->first_displayed_line++;
4189 if (linelen == -1) {
4190 if (feof(s->f)) {
4191 s->eof = 1;
4192 } else
4193 err = got_ferror(s->f, GOT_ERR_IO);
4194 break;
4197 free(line);
4198 break;
4199 case '[':
4200 if (s->diff_context > 0) {
4201 s->diff_context--;
4202 s->matched_line = 0;
4203 diff_view_indicate_progress(view);
4204 err = create_diff(s);
4205 if (s->first_displayed_line + view->nlines - 1 >
4206 s->nlines) {
4207 s->first_displayed_line = 1;
4208 s->last_displayed_line = view->nlines;
4210 } else
4211 view->count = 0;
4212 break;
4213 case ']':
4214 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4215 s->diff_context++;
4216 s->matched_line = 0;
4217 diff_view_indicate_progress(view);
4218 err = create_diff(s);
4219 } else
4220 view->count = 0;
4221 break;
4222 case '<':
4223 case ',':
4224 if (s->log_view == NULL) {
4225 view->count = 0;
4226 break;
4228 ls = &s->log_view->state.log;
4229 old_selected_entry = ls->selected_entry;
4231 /* view->count handled in input_log_view() */
4232 err = input_log_view(NULL, s->log_view, KEY_UP);
4233 if (err)
4234 break;
4236 if (old_selected_entry == ls->selected_entry)
4237 break;
4239 err = set_selected_commit(s, ls->selected_entry);
4240 if (err)
4241 break;
4243 s->first_displayed_line = 1;
4244 s->last_displayed_line = view->nlines;
4245 s->matched_line = 0;
4246 view->x = 0;
4248 diff_view_indicate_progress(view);
4249 err = create_diff(s);
4250 break;
4251 case '>':
4252 case '.':
4253 if (s->log_view == NULL) {
4254 view->count = 0;
4255 break;
4257 ls = &s->log_view->state.log;
4258 old_selected_entry = ls->selected_entry;
4260 /* view->count handled in input_log_view() */
4261 err = input_log_view(NULL, s->log_view, KEY_DOWN);
4262 if (err)
4263 break;
4265 if (old_selected_entry == ls->selected_entry)
4266 break;
4268 err = set_selected_commit(s, ls->selected_entry);
4269 if (err)
4270 break;
4272 s->first_displayed_line = 1;
4273 s->last_displayed_line = view->nlines;
4274 s->matched_line = 0;
4275 view->x = 0;
4277 diff_view_indicate_progress(view);
4278 err = create_diff(s);
4279 break;
4280 default:
4281 view->count = 0;
4282 break;
4285 return err;
4288 static const struct got_error *
4289 cmd_diff(int argc, char *argv[])
4291 const struct got_error *error = NULL;
4292 struct got_repository *repo = NULL;
4293 struct got_worktree *worktree = NULL;
4294 struct got_object_id *id1 = NULL, *id2 = NULL;
4295 char *repo_path = NULL, *cwd = NULL;
4296 char *id_str1 = NULL, *id_str2 = NULL;
4297 char *label1 = NULL, *label2 = NULL;
4298 int diff_context = 3, ignore_whitespace = 0;
4299 int ch, force_text_diff = 0;
4300 const char *errstr;
4301 struct tog_view *view;
4302 int *pack_fds = NULL;
4304 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4305 switch (ch) {
4306 case 'a':
4307 force_text_diff = 1;
4308 break;
4309 case 'C':
4310 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4311 &errstr);
4312 if (errstr != NULL)
4313 errx(1, "number of context lines is %s: %s",
4314 errstr, errstr);
4315 break;
4316 case 'r':
4317 repo_path = realpath(optarg, NULL);
4318 if (repo_path == NULL)
4319 return got_error_from_errno2("realpath",
4320 optarg);
4321 got_path_strip_trailing_slashes(repo_path);
4322 break;
4323 case 'w':
4324 ignore_whitespace = 1;
4325 break;
4326 default:
4327 usage_diff();
4328 /* NOTREACHED */
4332 argc -= optind;
4333 argv += optind;
4335 if (argc == 0) {
4336 usage_diff(); /* TODO show local worktree changes */
4337 } else if (argc == 2) {
4338 id_str1 = argv[0];
4339 id_str2 = argv[1];
4340 } else
4341 usage_diff();
4343 error = got_repo_pack_fds_open(&pack_fds);
4344 if (error)
4345 goto done;
4347 if (repo_path == NULL) {
4348 cwd = getcwd(NULL, 0);
4349 if (cwd == NULL)
4350 return got_error_from_errno("getcwd");
4351 error = got_worktree_open(&worktree, cwd);
4352 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4353 goto done;
4354 if (worktree)
4355 repo_path =
4356 strdup(got_worktree_get_repo_path(worktree));
4357 else
4358 repo_path = strdup(cwd);
4359 if (repo_path == NULL) {
4360 error = got_error_from_errno("strdup");
4361 goto done;
4365 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4366 if (error)
4367 goto done;
4369 init_curses();
4371 error = apply_unveil(got_repo_get_path(repo), NULL);
4372 if (error)
4373 goto done;
4375 error = tog_load_refs(repo, 0);
4376 if (error)
4377 goto done;
4379 error = got_repo_match_object_id(&id1, &label1, id_str1,
4380 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4381 if (error)
4382 goto done;
4384 error = got_repo_match_object_id(&id2, &label2, id_str2,
4385 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4386 if (error)
4387 goto done;
4389 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4390 if (view == NULL) {
4391 error = got_error_from_errno("view_open");
4392 goto done;
4394 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4395 ignore_whitespace, force_text_diff, NULL, repo);
4396 if (error)
4397 goto done;
4398 error = view_loop(view);
4399 done:
4400 free(label1);
4401 free(label2);
4402 free(repo_path);
4403 free(cwd);
4404 if (repo) {
4405 const struct got_error *close_err = got_repo_close(repo);
4406 if (error == NULL)
4407 error = close_err;
4409 if (worktree)
4410 got_worktree_close(worktree);
4411 if (pack_fds) {
4412 const struct got_error *pack_err =
4413 got_repo_pack_fds_close(pack_fds);
4414 if (error == NULL)
4415 error = pack_err;
4417 tog_free_refs();
4418 return error;
4421 __dead static void
4422 usage_blame(void)
4424 endwin();
4425 fprintf(stderr,
4426 "usage: %s blame [-c commit] [-r repository-path] path\n",
4427 getprogname());
4428 exit(1);
4431 struct tog_blame_line {
4432 int annotated;
4433 struct got_object_id *id;
4436 static const struct got_error *
4437 draw_blame(struct tog_view *view)
4439 struct tog_blame_view_state *s = &view->state.blame;
4440 struct tog_blame *blame = &s->blame;
4441 regmatch_t *regmatch = &view->regmatch;
4442 const struct got_error *err;
4443 int lineno = 0, nprinted = 0;
4444 char *line = NULL;
4445 size_t linesize = 0;
4446 ssize_t linelen;
4447 wchar_t *wline;
4448 int width;
4449 struct tog_blame_line *blame_line;
4450 struct got_object_id *prev_id = NULL;
4451 char *id_str;
4452 struct tog_color *tc;
4454 err = got_object_id_str(&id_str, &s->blamed_commit->id);
4455 if (err)
4456 return err;
4458 rewind(blame->f);
4459 werase(view->window);
4461 if (asprintf(&line, "commit %s", id_str) == -1) {
4462 err = got_error_from_errno("asprintf");
4463 free(id_str);
4464 return err;
4467 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4468 free(line);
4469 line = NULL;
4470 if (err)
4471 return err;
4472 if (view_needs_focus_indication(view))
4473 wstandout(view->window);
4474 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4475 if (tc)
4476 wattr_on(view->window,
4477 COLOR_PAIR(tc->colorpair), NULL);
4478 waddwstr(view->window, wline);
4479 if (tc)
4480 wattr_off(view->window,
4481 COLOR_PAIR(tc->colorpair), NULL);
4482 if (view_needs_focus_indication(view))
4483 wstandend(view->window);
4484 free(wline);
4485 wline = NULL;
4486 if (width < view->ncols - 1)
4487 waddch(view->window, '\n');
4489 if (asprintf(&line, "[%d/%d] %s%s",
4490 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
4491 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
4492 free(id_str);
4493 return got_error_from_errno("asprintf");
4495 free(id_str);
4496 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4497 free(line);
4498 line = NULL;
4499 if (err)
4500 return err;
4501 waddwstr(view->window, wline);
4502 free(wline);
4503 wline = NULL;
4504 if (width < view->ncols - 1)
4505 waddch(view->window, '\n');
4507 s->eof = 0;
4508 view->maxx = 0;
4509 while (nprinted < view->nlines - 2) {
4510 linelen = getline(&line, &linesize, blame->f);
4511 if (linelen == -1) {
4512 if (feof(blame->f)) {
4513 s->eof = 1;
4514 break;
4516 free(line);
4517 return got_ferror(blame->f, GOT_ERR_IO);
4519 if (++lineno < s->first_displayed_line)
4520 continue;
4522 /* Set view->maxx based on full line length. */
4523 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
4524 if (err) {
4525 free(line);
4526 return err;
4528 free(wline);
4529 wline = NULL;
4530 view->maxx = MAX(view->maxx, width);
4532 if (view->focussed && nprinted == s->selected_line - 1)
4533 wstandout(view->window);
4535 if (blame->nlines > 0) {
4536 blame_line = &blame->lines[lineno - 1];
4537 if (blame_line->annotated && prev_id &&
4538 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
4539 !(view->focussed &&
4540 nprinted == s->selected_line - 1)) {
4541 waddstr(view->window, " ");
4542 } else if (blame_line->annotated) {
4543 char *id_str;
4544 err = got_object_id_str(&id_str,
4545 blame_line->id);
4546 if (err) {
4547 free(line);
4548 return err;
4550 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4551 if (tc)
4552 wattr_on(view->window,
4553 COLOR_PAIR(tc->colorpair), NULL);
4554 wprintw(view->window, "%.8s", id_str);
4555 if (tc)
4556 wattr_off(view->window,
4557 COLOR_PAIR(tc->colorpair), NULL);
4558 free(id_str);
4559 prev_id = blame_line->id;
4560 } else {
4561 waddstr(view->window, "........");
4562 prev_id = NULL;
4564 } else {
4565 waddstr(view->window, "........");
4566 prev_id = NULL;
4569 if (view->focussed && nprinted == s->selected_line - 1)
4570 wstandend(view->window);
4571 waddstr(view->window, " ");
4573 if (view->ncols <= 9) {
4574 width = 9;
4575 } else if (s->first_displayed_line + nprinted ==
4576 s->matched_line &&
4577 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4578 err = add_matched_line(&width, line, view->ncols - 9, 9,
4579 view->window, view->x, regmatch);
4580 if (err) {
4581 free(line);
4582 return err;
4584 width += 9;
4585 } else {
4586 int skip;
4587 err = format_line(&wline, &width, &skip, line,
4588 view->x, view->ncols - 9, 9, 1);
4589 if (err) {
4590 free(line);
4591 return err;
4593 waddwstr(view->window, &wline[skip]);
4594 width += 9;
4595 free(wline);
4596 wline = NULL;
4599 if (width <= view->ncols - 1)
4600 waddch(view->window, '\n');
4601 if (++nprinted == 1)
4602 s->first_displayed_line = lineno;
4604 free(line);
4605 s->last_displayed_line = lineno;
4607 view_vborder(view);
4609 return NULL;
4612 static const struct got_error *
4613 blame_cb(void *arg, int nlines, int lineno,
4614 struct got_commit_object *commit, struct got_object_id *id)
4616 const struct got_error *err = NULL;
4617 struct tog_blame_cb_args *a = arg;
4618 struct tog_blame_line *line;
4619 int errcode;
4621 if (nlines != a->nlines ||
4622 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4623 return got_error(GOT_ERR_RANGE);
4625 errcode = pthread_mutex_lock(&tog_mutex);
4626 if (errcode)
4627 return got_error_set_errno(errcode, "pthread_mutex_lock");
4629 if (*a->quit) { /* user has quit the blame view */
4630 err = got_error(GOT_ERR_ITER_COMPLETED);
4631 goto done;
4634 if (lineno == -1)
4635 goto done; /* no change in this commit */
4637 line = &a->lines[lineno - 1];
4638 if (line->annotated)
4639 goto done;
4641 line->id = got_object_id_dup(id);
4642 if (line->id == NULL) {
4643 err = got_error_from_errno("got_object_id_dup");
4644 goto done;
4646 line->annotated = 1;
4647 done:
4648 errcode = pthread_mutex_unlock(&tog_mutex);
4649 if (errcode)
4650 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4651 return err;
4654 static void *
4655 blame_thread(void *arg)
4657 const struct got_error *err, *close_err;
4658 struct tog_blame_thread_args *ta = arg;
4659 struct tog_blame_cb_args *a = ta->cb_args;
4660 int errcode;
4662 err = block_signals_used_by_main_thread();
4663 if (err)
4664 return (void *)err;
4666 err = got_blame(ta->path, a->commit_id, ta->repo,
4667 blame_cb, ta->cb_args, ta->cancel_cb, ta->cancel_arg);
4668 if (err && err->code == GOT_ERR_CANCELLED)
4669 err = NULL;
4671 errcode = pthread_mutex_lock(&tog_mutex);
4672 if (errcode)
4673 return (void *)got_error_set_errno(errcode,
4674 "pthread_mutex_lock");
4676 close_err = got_repo_close(ta->repo);
4677 if (err == NULL)
4678 err = close_err;
4679 ta->repo = NULL;
4680 *ta->complete = 1;
4682 errcode = pthread_mutex_unlock(&tog_mutex);
4683 if (errcode && err == NULL)
4684 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4686 return (void *)err;
4689 static struct got_object_id *
4690 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
4691 int first_displayed_line, int selected_line)
4693 struct tog_blame_line *line;
4695 if (nlines <= 0)
4696 return NULL;
4698 line = &lines[first_displayed_line - 1 + selected_line - 1];
4699 if (!line->annotated)
4700 return NULL;
4702 return line->id;
4705 static const struct got_error *
4706 stop_blame(struct tog_blame *blame)
4708 const struct got_error *err = NULL;
4709 int i;
4711 if (blame->thread) {
4712 int errcode;
4713 errcode = pthread_mutex_unlock(&tog_mutex);
4714 if (errcode)
4715 return got_error_set_errno(errcode,
4716 "pthread_mutex_unlock");
4717 errcode = pthread_join(blame->thread, (void **)&err);
4718 if (errcode)
4719 return got_error_set_errno(errcode, "pthread_join");
4720 errcode = pthread_mutex_lock(&tog_mutex);
4721 if (errcode)
4722 return got_error_set_errno(errcode,
4723 "pthread_mutex_lock");
4724 if (err && err->code == GOT_ERR_ITER_COMPLETED)
4725 err = NULL;
4726 blame->thread = NULL;
4728 if (blame->thread_args.repo) {
4729 const struct got_error *close_err;
4730 close_err = got_repo_close(blame->thread_args.repo);
4731 if (err == NULL)
4732 err = close_err;
4733 blame->thread_args.repo = NULL;
4735 if (blame->f) {
4736 if (fclose(blame->f) == EOF && err == NULL)
4737 err = got_error_from_errno("fclose");
4738 blame->f = NULL;
4740 if (blame->lines) {
4741 for (i = 0; i < blame->nlines; i++)
4742 free(blame->lines[i].id);
4743 free(blame->lines);
4744 blame->lines = NULL;
4746 free(blame->cb_args.commit_id);
4747 blame->cb_args.commit_id = NULL;
4748 if (blame->pack_fds) {
4749 const struct got_error *pack_err =
4750 got_repo_pack_fds_close(blame->pack_fds);
4751 if (err == NULL)
4752 err = pack_err;
4753 blame->pack_fds = NULL;
4755 return err;
4758 static const struct got_error *
4759 cancel_blame_view(void *arg)
4761 const struct got_error *err = NULL;
4762 int *done = arg;
4763 int errcode;
4765 errcode = pthread_mutex_lock(&tog_mutex);
4766 if (errcode)
4767 return got_error_set_errno(errcode,
4768 "pthread_mutex_unlock");
4770 if (*done)
4771 err = got_error(GOT_ERR_CANCELLED);
4773 errcode = pthread_mutex_unlock(&tog_mutex);
4774 if (errcode)
4775 return got_error_set_errno(errcode,
4776 "pthread_mutex_lock");
4778 return err;
4781 static const struct got_error *
4782 run_blame(struct tog_view *view)
4784 struct tog_blame_view_state *s = &view->state.blame;
4785 struct tog_blame *blame = &s->blame;
4786 const struct got_error *err = NULL;
4787 struct got_commit_object *commit = NULL;
4788 struct got_blob_object *blob = NULL;
4789 struct got_repository *thread_repo = NULL;
4790 struct got_object_id *obj_id = NULL;
4791 int obj_type, fd = -1;
4792 int *pack_fds = NULL;
4794 err = got_object_open_as_commit(&commit, s->repo,
4795 &s->blamed_commit->id);
4796 if (err)
4797 return err;
4799 fd = got_opentempfd();
4800 if (fd == -1) {
4801 err = got_error_from_errno("got_opentempfd");
4802 goto done;
4805 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
4806 if (err)
4807 goto done;
4809 err = got_object_get_type(&obj_type, s->repo, obj_id);
4810 if (err)
4811 goto done;
4813 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4814 err = got_error(GOT_ERR_OBJ_TYPE);
4815 goto done;
4818 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
4819 if (err)
4820 goto done;
4821 blame->f = got_opentemp();
4822 if (blame->f == NULL) {
4823 err = got_error_from_errno("got_opentemp");
4824 goto done;
4826 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
4827 &blame->line_offsets, blame->f, blob);
4828 if (err)
4829 goto done;
4830 if (blame->nlines == 0) {
4831 s->blame_complete = 1;
4832 goto done;
4835 /* Don't include \n at EOF in the blame line count. */
4836 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
4837 blame->nlines--;
4839 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
4840 if (blame->lines == NULL) {
4841 err = got_error_from_errno("calloc");
4842 goto done;
4845 err = got_repo_pack_fds_open(&pack_fds);
4846 if (err)
4847 goto done;
4848 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
4849 pack_fds);
4850 if (err)
4851 goto done;
4853 blame->pack_fds = pack_fds;
4854 blame->cb_args.view = view;
4855 blame->cb_args.lines = blame->lines;
4856 blame->cb_args.nlines = blame->nlines;
4857 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
4858 if (blame->cb_args.commit_id == NULL) {
4859 err = got_error_from_errno("got_object_id_dup");
4860 goto done;
4862 blame->cb_args.quit = &s->done;
4864 blame->thread_args.path = s->path;
4865 blame->thread_args.repo = thread_repo;
4866 blame->thread_args.cb_args = &blame->cb_args;
4867 blame->thread_args.complete = &s->blame_complete;
4868 blame->thread_args.cancel_cb = cancel_blame_view;
4869 blame->thread_args.cancel_arg = &s->done;
4870 s->blame_complete = 0;
4872 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
4873 s->first_displayed_line = 1;
4874 s->last_displayed_line = view->nlines;
4875 s->selected_line = 1;
4877 s->matched_line = 0;
4879 done:
4880 if (commit)
4881 got_object_commit_close(commit);
4882 if (fd != -1 && close(fd) == -1 && err == NULL)
4883 err = got_error_from_errno("close");
4884 if (blob)
4885 got_object_blob_close(blob);
4886 free(obj_id);
4887 if (err)
4888 stop_blame(blame);
4889 return err;
4892 static const struct got_error *
4893 open_blame_view(struct tog_view *view, char *path,
4894 struct got_object_id *commit_id, struct got_repository *repo)
4896 const struct got_error *err = NULL;
4897 struct tog_blame_view_state *s = &view->state.blame;
4899 STAILQ_INIT(&s->blamed_commits);
4901 s->path = strdup(path);
4902 if (s->path == NULL)
4903 return got_error_from_errno("strdup");
4905 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
4906 if (err) {
4907 free(s->path);
4908 return err;
4911 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
4912 s->first_displayed_line = 1;
4913 s->last_displayed_line = view->nlines;
4914 s->selected_line = 1;
4915 s->blame_complete = 0;
4916 s->repo = repo;
4917 s->commit_id = commit_id;
4918 memset(&s->blame, 0, sizeof(s->blame));
4920 STAILQ_INIT(&s->colors);
4921 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4922 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
4923 get_color_value("TOG_COLOR_COMMIT"));
4924 if (err)
4925 return err;
4928 view->show = show_blame_view;
4929 view->input = input_blame_view;
4930 view->close = close_blame_view;
4931 view->search_start = search_start_blame_view;
4932 view->search_next = search_next_blame_view;
4934 return run_blame(view);
4937 static const struct got_error *
4938 close_blame_view(struct tog_view *view)
4940 const struct got_error *err = NULL;
4941 struct tog_blame_view_state *s = &view->state.blame;
4943 if (s->blame.thread)
4944 err = stop_blame(&s->blame);
4946 while (!STAILQ_EMPTY(&s->blamed_commits)) {
4947 struct got_object_qid *blamed_commit;
4948 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
4949 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
4950 got_object_qid_free(blamed_commit);
4953 free(s->path);
4954 free_colors(&s->colors);
4955 return err;
4958 static const struct got_error *
4959 search_start_blame_view(struct tog_view *view)
4961 struct tog_blame_view_state *s = &view->state.blame;
4963 s->matched_line = 0;
4964 return NULL;
4967 static const struct got_error *
4968 search_next_blame_view(struct tog_view *view)
4970 struct tog_blame_view_state *s = &view->state.blame;
4971 const struct got_error *err = NULL;
4972 int lineno;
4973 char *line = NULL;
4974 size_t linesize = 0;
4975 ssize_t linelen;
4977 if (!view->searching) {
4978 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4979 return NULL;
4982 if (s->matched_line) {
4983 if (view->searching == TOG_SEARCH_FORWARD)
4984 lineno = s->matched_line + 1;
4985 else
4986 lineno = s->matched_line - 1;
4987 } else
4988 lineno = s->first_displayed_line - 1 + s->selected_line;
4990 while (1) {
4991 off_t offset;
4993 if (lineno <= 0 || lineno > s->blame.nlines) {
4994 if (s->matched_line == 0) {
4995 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4996 break;
4999 if (view->searching == TOG_SEARCH_FORWARD)
5000 lineno = 1;
5001 else
5002 lineno = s->blame.nlines;
5005 offset = s->blame.line_offsets[lineno - 1];
5006 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5007 free(line);
5008 return got_error_from_errno("fseeko");
5010 linelen = getline(&line, &linesize, s->blame.f);
5011 if (linelen != -1) {
5012 char *exstr;
5013 err = expand_tab(&exstr, line);
5014 if (err)
5015 break;
5016 if (match_line(exstr, &view->regex, 1,
5017 &view->regmatch)) {
5018 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5019 s->matched_line = lineno;
5020 free(exstr);
5021 break;
5023 free(exstr);
5025 if (view->searching == TOG_SEARCH_FORWARD)
5026 lineno++;
5027 else
5028 lineno--;
5030 free(line);
5032 if (s->matched_line) {
5033 s->first_displayed_line = s->matched_line;
5034 s->selected_line = 1;
5037 return err;
5040 static const struct got_error *
5041 show_blame_view(struct tog_view *view)
5043 const struct got_error *err = NULL;
5044 struct tog_blame_view_state *s = &view->state.blame;
5045 int errcode;
5047 if (s->blame.thread == NULL && !s->blame_complete) {
5048 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5049 &s->blame.thread_args);
5050 if (errcode)
5051 return got_error_set_errno(errcode, "pthread_create");
5053 halfdelay(1); /* fast refresh while annotating */
5056 if (s->blame_complete)
5057 halfdelay(10); /* disable fast refresh */
5059 err = draw_blame(view);
5061 view_vborder(view);
5062 return err;
5065 static const struct got_error *
5066 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5068 const struct got_error *err = NULL, *thread_err = NULL;
5069 struct tog_view *diff_view;
5070 struct tog_blame_view_state *s = &view->state.blame;
5071 int begin_x = 0, nscroll = view->nlines - 2;
5073 switch (ch) {
5074 case '0':
5075 view->x = 0;
5076 break;
5077 case '$':
5078 view->x = MAX(view->maxx - view->ncols / 3, 0);
5079 view->count = 0;
5080 break;
5081 case KEY_RIGHT:
5082 case 'l':
5083 if (view->x + view->ncols / 3 < view->maxx)
5084 view->x += 2; /* move two columns right */
5085 else
5086 view->count = 0;
5087 break;
5088 case KEY_LEFT:
5089 case 'h':
5090 view->x -= MIN(view->x, 2); /* move two columns back */
5091 if (view->x <= 0)
5092 view->count = 0;
5093 break;
5094 case 'q':
5095 s->done = 1;
5096 break;
5097 case 'g':
5098 case KEY_HOME:
5099 s->selected_line = 1;
5100 s->first_displayed_line = 1;
5101 view->count = 0;
5102 break;
5103 case 'G':
5104 case KEY_END:
5105 if (s->blame.nlines < view->nlines - 2) {
5106 s->selected_line = s->blame.nlines;
5107 s->first_displayed_line = 1;
5108 } else {
5109 s->selected_line = view->nlines - 2;
5110 s->first_displayed_line = s->blame.nlines -
5111 (view->nlines - 3);
5113 view->count = 0;
5114 break;
5115 case 'k':
5116 case KEY_UP:
5117 case CTRL('p'):
5118 if (s->selected_line > 1)
5119 s->selected_line--;
5120 else if (s->selected_line == 1 &&
5121 s->first_displayed_line > 1)
5122 s->first_displayed_line--;
5123 else
5124 view->count = 0;
5125 break;
5126 case CTRL('u'):
5127 case 'u':
5128 nscroll /= 2;
5129 /* FALL THROUGH */
5130 case KEY_PPAGE:
5131 case CTRL('b'):
5132 case 'b':
5133 if (s->first_displayed_line == 1) {
5134 if (view->count > 1)
5135 nscroll += nscroll;
5136 s->selected_line = MAX(1, s->selected_line - nscroll);
5137 view->count = 0;
5138 break;
5140 if (s->first_displayed_line > nscroll)
5141 s->first_displayed_line -= nscroll;
5142 else
5143 s->first_displayed_line = 1;
5144 break;
5145 case 'j':
5146 case KEY_DOWN:
5147 case CTRL('n'):
5148 if (s->selected_line < view->nlines - 2 &&
5149 s->first_displayed_line +
5150 s->selected_line <= s->blame.nlines)
5151 s->selected_line++;
5152 else if (s->last_displayed_line <
5153 s->blame.nlines)
5154 s->first_displayed_line++;
5155 else
5156 view->count = 0;
5157 break;
5158 case 'c':
5159 case 'p': {
5160 struct got_object_id *id = NULL;
5162 view->count = 0;
5163 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5164 s->first_displayed_line, s->selected_line);
5165 if (id == NULL)
5166 break;
5167 if (ch == 'p') {
5168 struct got_commit_object *commit, *pcommit;
5169 struct got_object_qid *pid;
5170 struct got_object_id *blob_id = NULL;
5171 int obj_type;
5172 err = got_object_open_as_commit(&commit,
5173 s->repo, id);
5174 if (err)
5175 break;
5176 pid = STAILQ_FIRST(
5177 got_object_commit_get_parent_ids(commit));
5178 if (pid == NULL) {
5179 got_object_commit_close(commit);
5180 break;
5182 /* Check if path history ends here. */
5183 err = got_object_open_as_commit(&pcommit,
5184 s->repo, &pid->id);
5185 if (err)
5186 break;
5187 err = got_object_id_by_path(&blob_id, s->repo,
5188 pcommit, s->path);
5189 got_object_commit_close(pcommit);
5190 if (err) {
5191 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5192 err = NULL;
5193 got_object_commit_close(commit);
5194 break;
5196 err = got_object_get_type(&obj_type, s->repo,
5197 blob_id);
5198 free(blob_id);
5199 /* Can't blame non-blob type objects. */
5200 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5201 got_object_commit_close(commit);
5202 break;
5204 err = got_object_qid_alloc(&s->blamed_commit,
5205 &pid->id);
5206 got_object_commit_close(commit);
5207 } else {
5208 if (got_object_id_cmp(id,
5209 &s->blamed_commit->id) == 0)
5210 break;
5211 err = got_object_qid_alloc(&s->blamed_commit,
5212 id);
5214 if (err)
5215 break;
5216 s->done = 1;
5217 thread_err = stop_blame(&s->blame);
5218 s->done = 0;
5219 if (thread_err)
5220 break;
5221 STAILQ_INSERT_HEAD(&s->blamed_commits,
5222 s->blamed_commit, entry);
5223 err = run_blame(view);
5224 if (err)
5225 break;
5226 break;
5228 case 'C': {
5229 struct got_object_qid *first;
5231 view->count = 0;
5232 first = STAILQ_FIRST(&s->blamed_commits);
5233 if (!got_object_id_cmp(&first->id, s->commit_id))
5234 break;
5235 s->done = 1;
5236 thread_err = stop_blame(&s->blame);
5237 s->done = 0;
5238 if (thread_err)
5239 break;
5240 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5241 got_object_qid_free(s->blamed_commit);
5242 s->blamed_commit =
5243 STAILQ_FIRST(&s->blamed_commits);
5244 err = run_blame(view);
5245 if (err)
5246 break;
5247 break;
5249 case KEY_ENTER:
5250 case '\r': {
5251 struct got_object_id *id = NULL;
5252 struct got_object_qid *pid;
5253 struct got_commit_object *commit = NULL;
5255 view->count = 0;
5256 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5257 s->first_displayed_line, s->selected_line);
5258 if (id == NULL)
5259 break;
5260 err = got_object_open_as_commit(&commit, s->repo, id);
5261 if (err)
5262 break;
5263 pid = STAILQ_FIRST(
5264 got_object_commit_get_parent_ids(commit));
5265 if (view_is_parent_view(view))
5266 begin_x = view_split_begin_x(view->begin_x);
5267 diff_view = view_open(0, 0, 0, begin_x, TOG_VIEW_DIFF);
5268 if (diff_view == NULL) {
5269 got_object_commit_close(commit);
5270 err = got_error_from_errno("view_open");
5271 break;
5273 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5274 id, NULL, NULL, 3, 0, 0, NULL, s->repo);
5275 got_object_commit_close(commit);
5276 if (err) {
5277 view_close(diff_view);
5278 break;
5280 view->focussed = 0;
5281 diff_view->focussed = 1;
5282 if (view_is_parent_view(view)) {
5283 err = view_close_child(view);
5284 if (err)
5285 break;
5286 err = view_set_child(view, diff_view);
5287 if (err)
5288 break;
5289 view->focus_child = 1;
5290 } else
5291 *new_view = diff_view;
5292 if (err)
5293 break;
5294 break;
5296 case CTRL('d'):
5297 case 'd':
5298 nscroll /= 2;
5299 /* FALL THROUGH */
5300 case KEY_NPAGE:
5301 case CTRL('f'):
5302 case 'f':
5303 case ' ':
5304 if (s->last_displayed_line >= s->blame.nlines &&
5305 s->selected_line >= MIN(s->blame.nlines,
5306 view->nlines - 2)) {
5307 view->count = 0;
5308 break;
5310 if (s->last_displayed_line >= s->blame.nlines &&
5311 s->selected_line < view->nlines - 2) {
5312 s->selected_line +=
5313 MIN(nscroll, s->last_displayed_line -
5314 s->first_displayed_line - s->selected_line + 1);
5316 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5317 s->first_displayed_line += nscroll;
5318 else
5319 s->first_displayed_line =
5320 s->blame.nlines - (view->nlines - 3);
5321 break;
5322 case KEY_RESIZE:
5323 if (s->selected_line > view->nlines - 2) {
5324 s->selected_line = MIN(s->blame.nlines,
5325 view->nlines - 2);
5327 break;
5328 default:
5329 view->count = 0;
5330 break;
5332 return thread_err ? thread_err : err;
5335 static const struct got_error *
5336 cmd_blame(int argc, char *argv[])
5338 const struct got_error *error;
5339 struct got_repository *repo = NULL;
5340 struct got_worktree *worktree = NULL;
5341 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5342 char *link_target = NULL;
5343 struct got_object_id *commit_id = NULL;
5344 struct got_commit_object *commit = NULL;
5345 char *commit_id_str = NULL;
5346 int ch;
5347 struct tog_view *view;
5348 int *pack_fds = NULL;
5350 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5351 switch (ch) {
5352 case 'c':
5353 commit_id_str = optarg;
5354 break;
5355 case 'r':
5356 repo_path = realpath(optarg, NULL);
5357 if (repo_path == NULL)
5358 return got_error_from_errno2("realpath",
5359 optarg);
5360 break;
5361 default:
5362 usage_blame();
5363 /* NOTREACHED */
5367 argc -= optind;
5368 argv += optind;
5370 if (argc != 1)
5371 usage_blame();
5373 error = got_repo_pack_fds_open(&pack_fds);
5374 if (error != NULL)
5375 goto done;
5377 if (repo_path == NULL) {
5378 cwd = getcwd(NULL, 0);
5379 if (cwd == NULL)
5380 return got_error_from_errno("getcwd");
5381 error = got_worktree_open(&worktree, cwd);
5382 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5383 goto done;
5384 if (worktree)
5385 repo_path =
5386 strdup(got_worktree_get_repo_path(worktree));
5387 else
5388 repo_path = strdup(cwd);
5389 if (repo_path == NULL) {
5390 error = got_error_from_errno("strdup");
5391 goto done;
5395 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5396 if (error != NULL)
5397 goto done;
5399 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
5400 worktree);
5401 if (error)
5402 goto done;
5404 init_curses();
5406 error = apply_unveil(got_repo_get_path(repo), NULL);
5407 if (error)
5408 goto done;
5410 error = tog_load_refs(repo, 0);
5411 if (error)
5412 goto done;
5414 if (commit_id_str == NULL) {
5415 struct got_reference *head_ref;
5416 error = got_ref_open(&head_ref, repo, worktree ?
5417 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5418 if (error != NULL)
5419 goto done;
5420 error = got_ref_resolve(&commit_id, repo, head_ref);
5421 got_ref_close(head_ref);
5422 } else {
5423 error = got_repo_match_object_id(&commit_id, NULL,
5424 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
5426 if (error != NULL)
5427 goto done;
5429 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
5430 if (view == NULL) {
5431 error = got_error_from_errno("view_open");
5432 goto done;
5435 error = got_object_open_as_commit(&commit, repo, commit_id);
5436 if (error)
5437 goto done;
5439 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5440 commit, repo);
5441 if (error)
5442 goto done;
5444 error = open_blame_view(view, link_target ? link_target : in_repo_path,
5445 commit_id, repo);
5446 if (error)
5447 goto done;
5448 if (worktree) {
5449 /* Release work tree lock. */
5450 got_worktree_close(worktree);
5451 worktree = NULL;
5453 error = view_loop(view);
5454 done:
5455 free(repo_path);
5456 free(in_repo_path);
5457 free(link_target);
5458 free(cwd);
5459 free(commit_id);
5460 if (commit)
5461 got_object_commit_close(commit);
5462 if (worktree)
5463 got_worktree_close(worktree);
5464 if (repo) {
5465 const struct got_error *close_err = got_repo_close(repo);
5466 if (error == NULL)
5467 error = close_err;
5469 if (pack_fds) {
5470 const struct got_error *pack_err =
5471 got_repo_pack_fds_close(pack_fds);
5472 if (error == NULL)
5473 error = pack_err;
5475 tog_free_refs();
5476 return error;
5479 static const struct got_error *
5480 draw_tree_entries(struct tog_view *view, const char *parent_path)
5482 struct tog_tree_view_state *s = &view->state.tree;
5483 const struct got_error *err = NULL;
5484 struct got_tree_entry *te;
5485 wchar_t *wline;
5486 struct tog_color *tc;
5487 int width, n, i, nentries;
5488 int limit = view->nlines;
5490 s->ndisplayed = 0;
5492 werase(view->window);
5494 if (limit == 0)
5495 return NULL;
5497 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
5498 0, 0);
5499 if (err)
5500 return err;
5501 if (view_needs_focus_indication(view))
5502 wstandout(view->window);
5503 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5504 if (tc)
5505 wattr_on(view->window,
5506 COLOR_PAIR(tc->colorpair), NULL);
5507 waddwstr(view->window, wline);
5508 if (tc)
5509 wattr_off(view->window,
5510 COLOR_PAIR(tc->colorpair), NULL);
5511 if (view_needs_focus_indication(view))
5512 wstandend(view->window);
5513 free(wline);
5514 wline = NULL;
5515 if (width < view->ncols - 1)
5516 waddch(view->window, '\n');
5517 if (--limit <= 0)
5518 return NULL;
5519 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
5520 0, 0);
5521 if (err)
5522 return err;
5523 waddwstr(view->window, wline);
5524 free(wline);
5525 wline = NULL;
5526 if (width < view->ncols - 1)
5527 waddch(view->window, '\n');
5528 if (--limit <= 0)
5529 return NULL;
5530 waddch(view->window, '\n');
5531 if (--limit <= 0)
5532 return NULL;
5534 if (s->first_displayed_entry == NULL) {
5535 te = got_object_tree_get_first_entry(s->tree);
5536 if (s->selected == 0) {
5537 if (view->focussed)
5538 wstandout(view->window);
5539 s->selected_entry = NULL;
5541 waddstr(view->window, " ..\n"); /* parent directory */
5542 if (s->selected == 0 && view->focussed)
5543 wstandend(view->window);
5544 s->ndisplayed++;
5545 if (--limit <= 0)
5546 return NULL;
5547 n = 1;
5548 } else {
5549 n = 0;
5550 te = s->first_displayed_entry;
5553 nentries = got_object_tree_get_nentries(s->tree);
5554 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
5555 char *line = NULL, *id_str = NULL, *link_target = NULL;
5556 const char *modestr = "";
5557 mode_t mode;
5559 te = got_object_tree_get_entry(s->tree, i);
5560 mode = got_tree_entry_get_mode(te);
5562 if (s->show_ids) {
5563 err = got_object_id_str(&id_str,
5564 got_tree_entry_get_id(te));
5565 if (err)
5566 return got_error_from_errno(
5567 "got_object_id_str");
5569 if (got_object_tree_entry_is_submodule(te))
5570 modestr = "$";
5571 else if (S_ISLNK(mode)) {
5572 int i;
5574 err = got_tree_entry_get_symlink_target(&link_target,
5575 te, s->repo);
5576 if (err) {
5577 free(id_str);
5578 return err;
5580 for (i = 0; i < strlen(link_target); i++) {
5581 if (!isprint((unsigned char)link_target[i]))
5582 link_target[i] = '?';
5584 modestr = "@";
5586 else if (S_ISDIR(mode))
5587 modestr = "/";
5588 else if (mode & S_IXUSR)
5589 modestr = "*";
5590 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
5591 got_tree_entry_get_name(te), modestr,
5592 link_target ? " -> ": "",
5593 link_target ? link_target : "") == -1) {
5594 free(id_str);
5595 free(link_target);
5596 return got_error_from_errno("asprintf");
5598 free(id_str);
5599 free(link_target);
5600 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
5601 0, 0);
5602 if (err) {
5603 free(line);
5604 break;
5606 if (n == s->selected) {
5607 if (view->focussed)
5608 wstandout(view->window);
5609 s->selected_entry = te;
5611 tc = match_color(&s->colors, line);
5612 if (tc)
5613 wattr_on(view->window,
5614 COLOR_PAIR(tc->colorpair), NULL);
5615 waddwstr(view->window, wline);
5616 if (tc)
5617 wattr_off(view->window,
5618 COLOR_PAIR(tc->colorpair), NULL);
5619 if (width < view->ncols - 1)
5620 waddch(view->window, '\n');
5621 if (n == s->selected && view->focussed)
5622 wstandend(view->window);
5623 free(line);
5624 free(wline);
5625 wline = NULL;
5626 n++;
5627 s->ndisplayed++;
5628 s->last_displayed_entry = te;
5629 if (--limit <= 0)
5630 break;
5633 return err;
5636 static void
5637 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
5639 struct got_tree_entry *te;
5640 int isroot = s->tree == s->root;
5641 int i = 0;
5643 if (s->first_displayed_entry == NULL)
5644 return;
5646 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
5647 while (i++ < maxscroll) {
5648 if (te == NULL) {
5649 if (!isroot)
5650 s->first_displayed_entry = NULL;
5651 break;
5653 s->first_displayed_entry = te;
5654 te = got_tree_entry_get_prev(s->tree, te);
5658 static void
5659 tree_scroll_down(struct tog_tree_view_state *s, int maxscroll)
5661 struct got_tree_entry *next, *last;
5662 int n = 0;
5664 if (s->first_displayed_entry)
5665 next = got_tree_entry_get_next(s->tree,
5666 s->first_displayed_entry);
5667 else
5668 next = got_object_tree_get_first_entry(s->tree);
5670 last = s->last_displayed_entry;
5671 while (next && last && n++ < maxscroll) {
5672 last = got_tree_entry_get_next(s->tree, last);
5673 if (last) {
5674 s->first_displayed_entry = next;
5675 next = got_tree_entry_get_next(s->tree, next);
5680 static const struct got_error *
5681 tree_entry_path(char **path, struct tog_parent_trees *parents,
5682 struct got_tree_entry *te)
5684 const struct got_error *err = NULL;
5685 struct tog_parent_tree *pt;
5686 size_t len = 2; /* for leading slash and NUL */
5688 TAILQ_FOREACH(pt, parents, entry)
5689 len += strlen(got_tree_entry_get_name(pt->selected_entry))
5690 + 1 /* slash */;
5691 if (te)
5692 len += strlen(got_tree_entry_get_name(te));
5694 *path = calloc(1, len);
5695 if (path == NULL)
5696 return got_error_from_errno("calloc");
5698 (*path)[0] = '/';
5699 pt = TAILQ_LAST(parents, tog_parent_trees);
5700 while (pt) {
5701 const char *name = got_tree_entry_get_name(pt->selected_entry);
5702 if (strlcat(*path, name, len) >= len) {
5703 err = got_error(GOT_ERR_NO_SPACE);
5704 goto done;
5706 if (strlcat(*path, "/", len) >= len) {
5707 err = got_error(GOT_ERR_NO_SPACE);
5708 goto done;
5710 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
5712 if (te) {
5713 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
5714 err = got_error(GOT_ERR_NO_SPACE);
5715 goto done;
5718 done:
5719 if (err) {
5720 free(*path);
5721 *path = NULL;
5723 return err;
5726 static const struct got_error *
5727 blame_tree_entry(struct tog_view **new_view, int begin_x,
5728 struct got_tree_entry *te, struct tog_parent_trees *parents,
5729 struct got_object_id *commit_id, struct got_repository *repo)
5731 const struct got_error *err = NULL;
5732 char *path;
5733 struct tog_view *blame_view;
5735 *new_view = NULL;
5737 err = tree_entry_path(&path, parents, te);
5738 if (err)
5739 return err;
5741 blame_view = view_open(0, 0, 0, begin_x, TOG_VIEW_BLAME);
5742 if (blame_view == NULL) {
5743 err = got_error_from_errno("view_open");
5744 goto done;
5747 err = open_blame_view(blame_view, path, commit_id, repo);
5748 if (err) {
5749 if (err->code == GOT_ERR_CANCELLED)
5750 err = NULL;
5751 view_close(blame_view);
5752 } else
5753 *new_view = blame_view;
5754 done:
5755 free(path);
5756 return err;
5759 static const struct got_error *
5760 log_selected_tree_entry(struct tog_view **new_view, int begin_x,
5761 struct tog_tree_view_state *s)
5763 struct tog_view *log_view;
5764 const struct got_error *err = NULL;
5765 char *path;
5767 *new_view = NULL;
5769 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
5770 if (log_view == NULL)
5771 return got_error_from_errno("view_open");
5773 err = tree_entry_path(&path, &s->parents, s->selected_entry);
5774 if (err)
5775 return err;
5777 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
5778 path, 0);
5779 if (err)
5780 view_close(log_view);
5781 else
5782 *new_view = log_view;
5783 free(path);
5784 return err;
5787 static const struct got_error *
5788 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
5789 const char *head_ref_name, struct got_repository *repo)
5791 const struct got_error *err = NULL;
5792 char *commit_id_str = NULL;
5793 struct tog_tree_view_state *s = &view->state.tree;
5794 struct got_commit_object *commit = NULL;
5796 TAILQ_INIT(&s->parents);
5797 STAILQ_INIT(&s->colors);
5799 s->commit_id = got_object_id_dup(commit_id);
5800 if (s->commit_id == NULL)
5801 return got_error_from_errno("got_object_id_dup");
5803 err = got_object_open_as_commit(&commit, repo, commit_id);
5804 if (err)
5805 goto done;
5808 * The root is opened here and will be closed when the view is closed.
5809 * Any visited subtrees and their path-wise parents are opened and
5810 * closed on demand.
5812 err = got_object_open_as_tree(&s->root, repo,
5813 got_object_commit_get_tree_id(commit));
5814 if (err)
5815 goto done;
5816 s->tree = s->root;
5818 err = got_object_id_str(&commit_id_str, commit_id);
5819 if (err != NULL)
5820 goto done;
5822 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
5823 err = got_error_from_errno("asprintf");
5824 goto done;
5827 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
5828 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
5829 if (head_ref_name) {
5830 s->head_ref_name = strdup(head_ref_name);
5831 if (s->head_ref_name == NULL) {
5832 err = got_error_from_errno("strdup");
5833 goto done;
5836 s->repo = repo;
5838 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5839 err = add_color(&s->colors, "\\$$",
5840 TOG_COLOR_TREE_SUBMODULE,
5841 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
5842 if (err)
5843 goto done;
5844 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
5845 get_color_value("TOG_COLOR_TREE_SYMLINK"));
5846 if (err)
5847 goto done;
5848 err = add_color(&s->colors, "/$",
5849 TOG_COLOR_TREE_DIRECTORY,
5850 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
5851 if (err)
5852 goto done;
5854 err = add_color(&s->colors, "\\*$",
5855 TOG_COLOR_TREE_EXECUTABLE,
5856 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
5857 if (err)
5858 goto done;
5860 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
5861 get_color_value("TOG_COLOR_COMMIT"));
5862 if (err)
5863 goto done;
5866 view->show = show_tree_view;
5867 view->input = input_tree_view;
5868 view->close = close_tree_view;
5869 view->search_start = search_start_tree_view;
5870 view->search_next = search_next_tree_view;
5871 done:
5872 free(commit_id_str);
5873 if (commit)
5874 got_object_commit_close(commit);
5875 if (err)
5876 close_tree_view(view);
5877 return err;
5880 static const struct got_error *
5881 close_tree_view(struct tog_view *view)
5883 struct tog_tree_view_state *s = &view->state.tree;
5885 free_colors(&s->colors);
5886 free(s->tree_label);
5887 s->tree_label = NULL;
5888 free(s->commit_id);
5889 s->commit_id = NULL;
5890 free(s->head_ref_name);
5891 s->head_ref_name = NULL;
5892 while (!TAILQ_EMPTY(&s->parents)) {
5893 struct tog_parent_tree *parent;
5894 parent = TAILQ_FIRST(&s->parents);
5895 TAILQ_REMOVE(&s->parents, parent, entry);
5896 if (parent->tree != s->root)
5897 got_object_tree_close(parent->tree);
5898 free(parent);
5901 if (s->tree != NULL && s->tree != s->root)
5902 got_object_tree_close(s->tree);
5903 if (s->root)
5904 got_object_tree_close(s->root);
5905 return NULL;
5908 static const struct got_error *
5909 search_start_tree_view(struct tog_view *view)
5911 struct tog_tree_view_state *s = &view->state.tree;
5913 s->matched_entry = NULL;
5914 return NULL;
5917 static int
5918 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
5920 regmatch_t regmatch;
5922 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
5923 0) == 0;
5926 static const struct got_error *
5927 search_next_tree_view(struct tog_view *view)
5929 struct tog_tree_view_state *s = &view->state.tree;
5930 struct got_tree_entry *te = NULL;
5932 if (!view->searching) {
5933 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5934 return NULL;
5937 if (s->matched_entry) {
5938 if (view->searching == TOG_SEARCH_FORWARD) {
5939 if (s->selected_entry)
5940 te = got_tree_entry_get_next(s->tree,
5941 s->selected_entry);
5942 else
5943 te = got_object_tree_get_first_entry(s->tree);
5944 } else {
5945 if (s->selected_entry == NULL)
5946 te = got_object_tree_get_last_entry(s->tree);
5947 else
5948 te = got_tree_entry_get_prev(s->tree,
5949 s->selected_entry);
5951 } else {
5952 if (s->selected_entry)
5953 te = s->selected_entry;
5954 else if (view->searching == TOG_SEARCH_FORWARD)
5955 te = got_object_tree_get_first_entry(s->tree);
5956 else
5957 te = got_object_tree_get_last_entry(s->tree);
5960 while (1) {
5961 if (te == NULL) {
5962 if (s->matched_entry == NULL) {
5963 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5964 return NULL;
5966 if (view->searching == TOG_SEARCH_FORWARD)
5967 te = got_object_tree_get_first_entry(s->tree);
5968 else
5969 te = got_object_tree_get_last_entry(s->tree);
5972 if (match_tree_entry(te, &view->regex)) {
5973 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5974 s->matched_entry = te;
5975 break;
5978 if (view->searching == TOG_SEARCH_FORWARD)
5979 te = got_tree_entry_get_next(s->tree, te);
5980 else
5981 te = got_tree_entry_get_prev(s->tree, te);
5984 if (s->matched_entry) {
5985 s->first_displayed_entry = s->matched_entry;
5986 s->selected = 0;
5989 return NULL;
5992 static const struct got_error *
5993 show_tree_view(struct tog_view *view)
5995 const struct got_error *err = NULL;
5996 struct tog_tree_view_state *s = &view->state.tree;
5997 char *parent_path;
5999 err = tree_entry_path(&parent_path, &s->parents, NULL);
6000 if (err)
6001 return err;
6003 err = draw_tree_entries(view, parent_path);
6004 free(parent_path);
6006 view_vborder(view);
6007 return err;
6010 static const struct got_error *
6011 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6013 const struct got_error *err = NULL;
6014 struct tog_tree_view_state *s = &view->state.tree;
6015 struct tog_view *log_view, *ref_view;
6016 struct got_tree_entry *te;
6017 int begin_x = 0, n, nscroll = view->nlines - 3;
6019 switch (ch) {
6020 case 'i':
6021 s->show_ids = !s->show_ids;
6022 view->count = 0;
6023 break;
6024 case 'l':
6025 view->count = 0;
6026 if (!s->selected_entry)
6027 break;
6028 if (view_is_parent_view(view))
6029 begin_x = view_split_begin_x(view->begin_x);
6030 err = log_selected_tree_entry(&log_view, begin_x, s);
6031 view->focussed = 0;
6032 log_view->focussed = 1;
6033 if (view_is_parent_view(view)) {
6034 err = view_close_child(view);
6035 if (err)
6036 return err;
6037 err = view_set_child(view, log_view);
6038 if (err)
6039 return err;
6040 view->focus_child = 1;
6041 } else
6042 *new_view = log_view;
6043 break;
6044 case 'r':
6045 view->count = 0;
6046 if (view_is_parent_view(view))
6047 begin_x = view_split_begin_x(view->begin_x);
6048 ref_view = view_open(view->nlines, view->ncols,
6049 view->begin_y, begin_x, TOG_VIEW_REF);
6050 if (ref_view == NULL)
6051 return got_error_from_errno("view_open");
6052 err = open_ref_view(ref_view, s->repo);
6053 if (err) {
6054 view_close(ref_view);
6055 return err;
6057 view->focussed = 0;
6058 ref_view->focussed = 1;
6059 if (view_is_parent_view(view)) {
6060 err = view_close_child(view);
6061 if (err)
6062 return err;
6063 err = view_set_child(view, ref_view);
6064 if (err)
6065 return err;
6066 view->focus_child = 1;
6067 } else
6068 *new_view = ref_view;
6069 break;
6070 case 'g':
6071 case KEY_HOME:
6072 s->selected = 0;
6073 view->count = 0;
6074 if (s->tree == s->root)
6075 s->first_displayed_entry =
6076 got_object_tree_get_first_entry(s->tree);
6077 else
6078 s->first_displayed_entry = NULL;
6079 break;
6080 case 'G':
6081 case KEY_END:
6082 s->selected = 0;
6083 view->count = 0;
6084 te = got_object_tree_get_last_entry(s->tree);
6085 for (n = 0; n < view->nlines - 3; n++) {
6086 if (te == NULL) {
6087 if(s->tree != s->root) {
6088 s->first_displayed_entry = NULL;
6089 n++;
6091 break;
6093 s->first_displayed_entry = te;
6094 te = got_tree_entry_get_prev(s->tree, te);
6096 if (n > 0)
6097 s->selected = n - 1;
6098 break;
6099 case 'k':
6100 case KEY_UP:
6101 case CTRL('p'):
6102 if (s->selected > 0) {
6103 s->selected--;
6104 break;
6106 tree_scroll_up(s, 1);
6107 if (s->selected_entry == NULL ||
6108 (s->tree == s->root && s->selected_entry ==
6109 got_object_tree_get_first_entry(s->tree)))
6110 view->count = 0;
6111 break;
6112 case CTRL('u'):
6113 case 'u':
6114 nscroll /= 2;
6115 /* FALL THROUGH */
6116 case KEY_PPAGE:
6117 case CTRL('b'):
6118 case 'b':
6119 if (s->tree == s->root) {
6120 if (got_object_tree_get_first_entry(s->tree) ==
6121 s->first_displayed_entry)
6122 s->selected -= MIN(s->selected, nscroll);
6123 } else {
6124 if (s->first_displayed_entry == NULL)
6125 s->selected -= MIN(s->selected, nscroll);
6127 tree_scroll_up(s, MAX(0, nscroll));
6128 if (s->selected_entry == NULL ||
6129 (s->tree == s->root && s->selected_entry ==
6130 got_object_tree_get_first_entry(s->tree)))
6131 view->count = 0;
6132 break;
6133 case 'j':
6134 case KEY_DOWN:
6135 case CTRL('n'):
6136 if (s->selected < s->ndisplayed - 1) {
6137 s->selected++;
6138 break;
6140 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6141 == NULL) {
6142 /* can't scroll any further */
6143 view->count = 0;
6144 break;
6146 tree_scroll_down(s, 1);
6147 break;
6148 case CTRL('d'):
6149 case 'd':
6150 nscroll /= 2;
6151 /* FALL THROUGH */
6152 case KEY_NPAGE:
6153 case CTRL('f'):
6154 case 'f':
6155 case ' ':
6156 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6157 == NULL) {
6158 /* can't scroll any further; move cursor down */
6159 if (s->selected < s->ndisplayed - 1)
6160 s->selected += MIN(nscroll,
6161 s->ndisplayed - s->selected - 1);
6162 else
6163 view->count = 0;
6164 break;
6166 tree_scroll_down(s, nscroll);
6167 break;
6168 case KEY_ENTER:
6169 case '\r':
6170 case KEY_BACKSPACE:
6171 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6172 struct tog_parent_tree *parent;
6173 /* user selected '..' */
6174 if (s->tree == s->root) {
6175 view->count = 0;
6176 break;
6178 parent = TAILQ_FIRST(&s->parents);
6179 TAILQ_REMOVE(&s->parents, parent,
6180 entry);
6181 got_object_tree_close(s->tree);
6182 s->tree = parent->tree;
6183 s->first_displayed_entry =
6184 parent->first_displayed_entry;
6185 s->selected_entry =
6186 parent->selected_entry;
6187 s->selected = parent->selected;
6188 free(parent);
6189 } else if (S_ISDIR(got_tree_entry_get_mode(
6190 s->selected_entry))) {
6191 struct got_tree_object *subtree;
6192 view->count = 0;
6193 err = got_object_open_as_tree(&subtree, s->repo,
6194 got_tree_entry_get_id(s->selected_entry));
6195 if (err)
6196 break;
6197 err = tree_view_visit_subtree(s, subtree);
6198 if (err) {
6199 got_object_tree_close(subtree);
6200 break;
6202 } else if (S_ISREG(got_tree_entry_get_mode(
6203 s->selected_entry))) {
6204 struct tog_view *blame_view;
6205 int begin_x = view_is_parent_view(view) ?
6206 view_split_begin_x(view->begin_x) : 0;
6208 err = blame_tree_entry(&blame_view, begin_x,
6209 s->selected_entry, &s->parents,
6210 s->commit_id, s->repo);
6211 if (err)
6212 break;
6213 view->count = 0;
6214 view->focussed = 0;
6215 blame_view->focussed = 1;
6216 if (view_is_parent_view(view)) {
6217 err = view_close_child(view);
6218 if (err)
6219 return err;
6220 err = view_set_child(view, blame_view);
6221 if (err)
6222 return err;
6223 view->focus_child = 1;
6224 } else
6225 *new_view = blame_view;
6227 break;
6228 case KEY_RESIZE:
6229 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6230 s->selected = view->nlines - 4;
6231 view->count = 0;
6232 break;
6233 default:
6234 view->count = 0;
6235 break;
6238 return err;
6241 __dead static void
6242 usage_tree(void)
6244 endwin();
6245 fprintf(stderr,
6246 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6247 getprogname());
6248 exit(1);
6251 static const struct got_error *
6252 cmd_tree(int argc, char *argv[])
6254 const struct got_error *error;
6255 struct got_repository *repo = NULL;
6256 struct got_worktree *worktree = NULL;
6257 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6258 struct got_object_id *commit_id = NULL;
6259 struct got_commit_object *commit = NULL;
6260 const char *commit_id_arg = NULL;
6261 char *label = NULL;
6262 struct got_reference *ref = NULL;
6263 const char *head_ref_name = NULL;
6264 int ch;
6265 struct tog_view *view;
6266 int *pack_fds = NULL;
6268 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6269 switch (ch) {
6270 case 'c':
6271 commit_id_arg = optarg;
6272 break;
6273 case 'r':
6274 repo_path = realpath(optarg, NULL);
6275 if (repo_path == NULL)
6276 return got_error_from_errno2("realpath",
6277 optarg);
6278 break;
6279 default:
6280 usage_tree();
6281 /* NOTREACHED */
6285 argc -= optind;
6286 argv += optind;
6288 if (argc > 1)
6289 usage_tree();
6291 error = got_repo_pack_fds_open(&pack_fds);
6292 if (error != NULL)
6293 goto done;
6295 if (repo_path == NULL) {
6296 cwd = getcwd(NULL, 0);
6297 if (cwd == NULL)
6298 return got_error_from_errno("getcwd");
6299 error = got_worktree_open(&worktree, cwd);
6300 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6301 goto done;
6302 if (worktree)
6303 repo_path =
6304 strdup(got_worktree_get_repo_path(worktree));
6305 else
6306 repo_path = strdup(cwd);
6307 if (repo_path == NULL) {
6308 error = got_error_from_errno("strdup");
6309 goto done;
6313 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6314 if (error != NULL)
6315 goto done;
6317 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
6318 repo, worktree);
6319 if (error)
6320 goto done;
6322 init_curses();
6324 error = apply_unveil(got_repo_get_path(repo), NULL);
6325 if (error)
6326 goto done;
6328 error = tog_load_refs(repo, 0);
6329 if (error)
6330 goto done;
6332 if (commit_id_arg == NULL) {
6333 error = got_repo_match_object_id(&commit_id, &label,
6334 worktree ? got_worktree_get_head_ref_name(worktree) :
6335 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6336 if (error)
6337 goto done;
6338 head_ref_name = label;
6339 } else {
6340 error = got_ref_open(&ref, repo, commit_id_arg, 0);
6341 if (error == NULL)
6342 head_ref_name = got_ref_get_name(ref);
6343 else if (error->code != GOT_ERR_NOT_REF)
6344 goto done;
6345 error = got_repo_match_object_id(&commit_id, NULL,
6346 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6347 if (error)
6348 goto done;
6351 error = got_object_open_as_commit(&commit, repo, commit_id);
6352 if (error)
6353 goto done;
6355 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
6356 if (view == NULL) {
6357 error = got_error_from_errno("view_open");
6358 goto done;
6360 error = open_tree_view(view, commit_id, head_ref_name, repo);
6361 if (error)
6362 goto done;
6363 if (!got_path_is_root_dir(in_repo_path)) {
6364 error = tree_view_walk_path(&view->state.tree, commit,
6365 in_repo_path);
6366 if (error)
6367 goto done;
6370 if (worktree) {
6371 /* Release work tree lock. */
6372 got_worktree_close(worktree);
6373 worktree = NULL;
6375 error = view_loop(view);
6376 done:
6377 free(repo_path);
6378 free(cwd);
6379 free(commit_id);
6380 free(label);
6381 if (ref)
6382 got_ref_close(ref);
6383 if (repo) {
6384 const struct got_error *close_err = got_repo_close(repo);
6385 if (error == NULL)
6386 error = close_err;
6388 if (pack_fds) {
6389 const struct got_error *pack_err =
6390 got_repo_pack_fds_close(pack_fds);
6391 if (error == NULL)
6392 error = pack_err;
6394 tog_free_refs();
6395 return error;
6398 static const struct got_error *
6399 ref_view_load_refs(struct tog_ref_view_state *s)
6401 struct got_reflist_entry *sre;
6402 struct tog_reflist_entry *re;
6404 s->nrefs = 0;
6405 TAILQ_FOREACH(sre, &tog_refs, entry) {
6406 if (strncmp(got_ref_get_name(sre->ref),
6407 "refs/got/", 9) == 0 &&
6408 strncmp(got_ref_get_name(sre->ref),
6409 "refs/got/backup/", 16) != 0)
6410 continue;
6412 re = malloc(sizeof(*re));
6413 if (re == NULL)
6414 return got_error_from_errno("malloc");
6416 re->ref = got_ref_dup(sre->ref);
6417 if (re->ref == NULL)
6418 return got_error_from_errno("got_ref_dup");
6419 re->idx = s->nrefs++;
6420 TAILQ_INSERT_TAIL(&s->refs, re, entry);
6423 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6424 return NULL;
6427 static void
6428 ref_view_free_refs(struct tog_ref_view_state *s)
6430 struct tog_reflist_entry *re;
6432 while (!TAILQ_EMPTY(&s->refs)) {
6433 re = TAILQ_FIRST(&s->refs);
6434 TAILQ_REMOVE(&s->refs, re, entry);
6435 got_ref_close(re->ref);
6436 free(re);
6440 static const struct got_error *
6441 open_ref_view(struct tog_view *view, struct got_repository *repo)
6443 const struct got_error *err = NULL;
6444 struct tog_ref_view_state *s = &view->state.ref;
6446 s->selected_entry = 0;
6447 s->repo = repo;
6449 TAILQ_INIT(&s->refs);
6450 STAILQ_INIT(&s->colors);
6452 err = ref_view_load_refs(s);
6453 if (err)
6454 return err;
6456 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6457 err = add_color(&s->colors, "^refs/heads/",
6458 TOG_COLOR_REFS_HEADS,
6459 get_color_value("TOG_COLOR_REFS_HEADS"));
6460 if (err)
6461 goto done;
6463 err = add_color(&s->colors, "^refs/tags/",
6464 TOG_COLOR_REFS_TAGS,
6465 get_color_value("TOG_COLOR_REFS_TAGS"));
6466 if (err)
6467 goto done;
6469 err = add_color(&s->colors, "^refs/remotes/",
6470 TOG_COLOR_REFS_REMOTES,
6471 get_color_value("TOG_COLOR_REFS_REMOTES"));
6472 if (err)
6473 goto done;
6475 err = add_color(&s->colors, "^refs/got/backup/",
6476 TOG_COLOR_REFS_BACKUP,
6477 get_color_value("TOG_COLOR_REFS_BACKUP"));
6478 if (err)
6479 goto done;
6482 view->show = show_ref_view;
6483 view->input = input_ref_view;
6484 view->close = close_ref_view;
6485 view->search_start = search_start_ref_view;
6486 view->search_next = search_next_ref_view;
6487 done:
6488 if (err)
6489 free_colors(&s->colors);
6490 return err;
6493 static const struct got_error *
6494 close_ref_view(struct tog_view *view)
6496 struct tog_ref_view_state *s = &view->state.ref;
6498 ref_view_free_refs(s);
6499 free_colors(&s->colors);
6501 return NULL;
6504 static const struct got_error *
6505 resolve_reflist_entry(struct got_object_id **commit_id,
6506 struct tog_reflist_entry *re, struct got_repository *repo)
6508 const struct got_error *err = NULL;
6509 struct got_object_id *obj_id;
6510 struct got_tag_object *tag = NULL;
6511 int obj_type;
6513 *commit_id = NULL;
6515 err = got_ref_resolve(&obj_id, repo, re->ref);
6516 if (err)
6517 return err;
6519 err = got_object_get_type(&obj_type, repo, obj_id);
6520 if (err)
6521 goto done;
6523 switch (obj_type) {
6524 case GOT_OBJ_TYPE_COMMIT:
6525 *commit_id = obj_id;
6526 break;
6527 case GOT_OBJ_TYPE_TAG:
6528 err = got_object_open_as_tag(&tag, repo, obj_id);
6529 if (err)
6530 goto done;
6531 free(obj_id);
6532 err = got_object_get_type(&obj_type, repo,
6533 got_object_tag_get_object_id(tag));
6534 if (err)
6535 goto done;
6536 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
6537 err = got_error(GOT_ERR_OBJ_TYPE);
6538 goto done;
6540 *commit_id = got_object_id_dup(
6541 got_object_tag_get_object_id(tag));
6542 if (*commit_id == NULL) {
6543 err = got_error_from_errno("got_object_id_dup");
6544 goto done;
6546 break;
6547 default:
6548 err = got_error(GOT_ERR_OBJ_TYPE);
6549 break;
6552 done:
6553 if (tag)
6554 got_object_tag_close(tag);
6555 if (err) {
6556 free(*commit_id);
6557 *commit_id = NULL;
6559 return err;
6562 static const struct got_error *
6563 log_ref_entry(struct tog_view **new_view, int begin_x,
6564 struct tog_reflist_entry *re, struct got_repository *repo)
6566 struct tog_view *log_view;
6567 const struct got_error *err = NULL;
6568 struct got_object_id *commit_id = NULL;
6570 *new_view = NULL;
6572 err = resolve_reflist_entry(&commit_id, re, repo);
6573 if (err) {
6574 if (err->code != GOT_ERR_OBJ_TYPE)
6575 return err;
6576 else
6577 return NULL;
6580 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
6581 if (log_view == NULL) {
6582 err = got_error_from_errno("view_open");
6583 goto done;
6586 err = open_log_view(log_view, commit_id, repo,
6587 got_ref_get_name(re->ref), "", 0);
6588 done:
6589 if (err)
6590 view_close(log_view);
6591 else
6592 *new_view = log_view;
6593 free(commit_id);
6594 return err;
6597 static void
6598 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
6600 struct tog_reflist_entry *re;
6601 int i = 0;
6603 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
6604 return;
6606 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
6607 while (i++ < maxscroll) {
6608 if (re == NULL)
6609 break;
6610 s->first_displayed_entry = re;
6611 re = TAILQ_PREV(re, tog_reflist_head, entry);
6615 static void
6616 ref_scroll_down(struct tog_ref_view_state *s, int maxscroll)
6618 struct tog_reflist_entry *next, *last;
6619 int n = 0;
6621 if (s->first_displayed_entry)
6622 next = TAILQ_NEXT(s->first_displayed_entry, entry);
6623 else
6624 next = TAILQ_FIRST(&s->refs);
6626 last = s->last_displayed_entry;
6627 while (next && last && n++ < maxscroll) {
6628 last = TAILQ_NEXT(last, entry);
6629 if (last) {
6630 s->first_displayed_entry = next;
6631 next = TAILQ_NEXT(next, entry);
6636 static const struct got_error *
6637 search_start_ref_view(struct tog_view *view)
6639 struct tog_ref_view_state *s = &view->state.ref;
6641 s->matched_entry = NULL;
6642 return NULL;
6645 static int
6646 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
6648 regmatch_t regmatch;
6650 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
6651 0) == 0;
6654 static const struct got_error *
6655 search_next_ref_view(struct tog_view *view)
6657 struct tog_ref_view_state *s = &view->state.ref;
6658 struct tog_reflist_entry *re = NULL;
6660 if (!view->searching) {
6661 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6662 return NULL;
6665 if (s->matched_entry) {
6666 if (view->searching == TOG_SEARCH_FORWARD) {
6667 if (s->selected_entry)
6668 re = TAILQ_NEXT(s->selected_entry, entry);
6669 else
6670 re = TAILQ_PREV(s->selected_entry,
6671 tog_reflist_head, entry);
6672 } else {
6673 if (s->selected_entry == NULL)
6674 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6675 else
6676 re = TAILQ_PREV(s->selected_entry,
6677 tog_reflist_head, entry);
6679 } else {
6680 if (s->selected_entry)
6681 re = s->selected_entry;
6682 else if (view->searching == TOG_SEARCH_FORWARD)
6683 re = TAILQ_FIRST(&s->refs);
6684 else
6685 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6688 while (1) {
6689 if (re == NULL) {
6690 if (s->matched_entry == NULL) {
6691 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6692 return NULL;
6694 if (view->searching == TOG_SEARCH_FORWARD)
6695 re = TAILQ_FIRST(&s->refs);
6696 else
6697 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6700 if (match_reflist_entry(re, &view->regex)) {
6701 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6702 s->matched_entry = re;
6703 break;
6706 if (view->searching == TOG_SEARCH_FORWARD)
6707 re = TAILQ_NEXT(re, entry);
6708 else
6709 re = TAILQ_PREV(re, tog_reflist_head, entry);
6712 if (s->matched_entry) {
6713 s->first_displayed_entry = s->matched_entry;
6714 s->selected = 0;
6717 return NULL;
6720 static const struct got_error *
6721 show_ref_view(struct tog_view *view)
6723 const struct got_error *err = NULL;
6724 struct tog_ref_view_state *s = &view->state.ref;
6725 struct tog_reflist_entry *re;
6726 char *line = NULL;
6727 wchar_t *wline;
6728 struct tog_color *tc;
6729 int width, n;
6730 int limit = view->nlines;
6732 werase(view->window);
6734 s->ndisplayed = 0;
6736 if (limit == 0)
6737 return NULL;
6739 re = s->first_displayed_entry;
6741 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
6742 s->nrefs) == -1)
6743 return got_error_from_errno("asprintf");
6745 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6746 if (err) {
6747 free(line);
6748 return err;
6750 if (view_needs_focus_indication(view))
6751 wstandout(view->window);
6752 waddwstr(view->window, wline);
6753 if (view_needs_focus_indication(view))
6754 wstandend(view->window);
6755 free(wline);
6756 wline = NULL;
6757 free(line);
6758 line = NULL;
6759 if (width < view->ncols - 1)
6760 waddch(view->window, '\n');
6761 if (--limit <= 0)
6762 return NULL;
6764 n = 0;
6765 while (re && limit > 0) {
6766 char *line = NULL;
6767 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
6769 if (s->show_date) {
6770 struct got_commit_object *ci;
6771 struct got_tag_object *tag;
6772 struct got_object_id *id;
6773 struct tm tm;
6774 time_t t;
6776 err = got_ref_resolve(&id, s->repo, re->ref);
6777 if (err)
6778 return err;
6779 err = got_object_open_as_tag(&tag, s->repo, id);
6780 if (err) {
6781 if (err->code != GOT_ERR_OBJ_TYPE) {
6782 free(id);
6783 return err;
6785 err = got_object_open_as_commit(&ci, s->repo,
6786 id);
6787 if (err) {
6788 free(id);
6789 return err;
6791 t = got_object_commit_get_committer_time(ci);
6792 got_object_commit_close(ci);
6793 } else {
6794 t = got_object_tag_get_tagger_time(tag);
6795 got_object_tag_close(tag);
6797 free(id);
6798 if (gmtime_r(&t, &tm) == NULL)
6799 return got_error_from_errno("gmtime_r");
6800 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
6801 return got_error(GOT_ERR_NO_SPACE);
6803 if (got_ref_is_symbolic(re->ref)) {
6804 if (asprintf(&line, "%s%s -> %s", s->show_date ?
6805 ymd : "", got_ref_get_name(re->ref),
6806 got_ref_get_symref_target(re->ref)) == -1)
6807 return got_error_from_errno("asprintf");
6808 } else if (s->show_ids) {
6809 struct got_object_id *id;
6810 char *id_str;
6811 err = got_ref_resolve(&id, s->repo, re->ref);
6812 if (err)
6813 return err;
6814 err = got_object_id_str(&id_str, id);
6815 if (err) {
6816 free(id);
6817 return err;
6819 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
6820 got_ref_get_name(re->ref), id_str) == -1) {
6821 err = got_error_from_errno("asprintf");
6822 free(id);
6823 free(id_str);
6824 return err;
6826 free(id);
6827 free(id_str);
6828 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
6829 got_ref_get_name(re->ref)) == -1)
6830 return got_error_from_errno("asprintf");
6832 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6833 0, 0);
6834 if (err) {
6835 free(line);
6836 return err;
6838 if (n == s->selected) {
6839 if (view->focussed)
6840 wstandout(view->window);
6841 s->selected_entry = re;
6843 tc = match_color(&s->colors, got_ref_get_name(re->ref));
6844 if (tc)
6845 wattr_on(view->window,
6846 COLOR_PAIR(tc->colorpair), NULL);
6847 waddwstr(view->window, wline);
6848 if (tc)
6849 wattr_off(view->window,
6850 COLOR_PAIR(tc->colorpair), NULL);
6851 if (width < view->ncols - 1)
6852 waddch(view->window, '\n');
6853 if (n == s->selected && view->focussed)
6854 wstandend(view->window);
6855 free(line);
6856 free(wline);
6857 wline = NULL;
6858 n++;
6859 s->ndisplayed++;
6860 s->last_displayed_entry = re;
6862 limit--;
6863 re = TAILQ_NEXT(re, entry);
6866 view_vborder(view);
6867 return err;
6870 static const struct got_error *
6871 browse_ref_tree(struct tog_view **new_view, int begin_x,
6872 struct tog_reflist_entry *re, struct got_repository *repo)
6874 const struct got_error *err = NULL;
6875 struct got_object_id *commit_id = NULL;
6876 struct tog_view *tree_view;
6878 *new_view = NULL;
6880 err = resolve_reflist_entry(&commit_id, re, repo);
6881 if (err) {
6882 if (err->code != GOT_ERR_OBJ_TYPE)
6883 return err;
6884 else
6885 return NULL;
6889 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
6890 if (tree_view == NULL) {
6891 err = got_error_from_errno("view_open");
6892 goto done;
6895 err = open_tree_view(tree_view, commit_id,
6896 got_ref_get_name(re->ref), repo);
6897 if (err)
6898 goto done;
6900 *new_view = tree_view;
6901 done:
6902 free(commit_id);
6903 return err;
6905 static const struct got_error *
6906 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
6908 const struct got_error *err = NULL;
6909 struct tog_ref_view_state *s = &view->state.ref;
6910 struct tog_view *log_view, *tree_view;
6911 struct tog_reflist_entry *re;
6912 int begin_x = 0, n, nscroll = view->nlines - 1;
6914 switch (ch) {
6915 case 'i':
6916 s->show_ids = !s->show_ids;
6917 view->count = 0;
6918 break;
6919 case 'm':
6920 s->show_date = !s->show_date;
6921 view->count = 0;
6922 break;
6923 case 'o':
6924 s->sort_by_date = !s->sort_by_date;
6925 view->count = 0;
6926 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
6927 got_ref_cmp_by_commit_timestamp_descending :
6928 tog_ref_cmp_by_name, s->repo);
6929 if (err)
6930 break;
6931 got_reflist_object_id_map_free(tog_refs_idmap);
6932 err = got_reflist_object_id_map_create(&tog_refs_idmap,
6933 &tog_refs, s->repo);
6934 if (err)
6935 break;
6936 ref_view_free_refs(s);
6937 err = ref_view_load_refs(s);
6938 break;
6939 case KEY_ENTER:
6940 case '\r':
6941 view->count = 0;
6942 if (!s->selected_entry)
6943 break;
6944 if (view_is_parent_view(view))
6945 begin_x = view_split_begin_x(view->begin_x);
6946 err = log_ref_entry(&log_view, begin_x, s->selected_entry,
6947 s->repo);
6948 view->focussed = 0;
6949 log_view->focussed = 1;
6950 if (view_is_parent_view(view)) {
6951 err = view_close_child(view);
6952 if (err)
6953 return err;
6954 err = view_set_child(view, log_view);
6955 if (err)
6956 return err;
6957 view->focus_child = 1;
6958 } else
6959 *new_view = log_view;
6960 break;
6961 case 't':
6962 view->count = 0;
6963 if (!s->selected_entry)
6964 break;
6965 if (view_is_parent_view(view))
6966 begin_x = view_split_begin_x(view->begin_x);
6967 err = browse_ref_tree(&tree_view, begin_x, s->selected_entry,
6968 s->repo);
6969 if (err || tree_view == NULL)
6970 break;
6971 view->focussed = 0;
6972 tree_view->focussed = 1;
6973 if (view_is_parent_view(view)) {
6974 err = view_close_child(view);
6975 if (err)
6976 return err;
6977 err = view_set_child(view, tree_view);
6978 if (err)
6979 return err;
6980 view->focus_child = 1;
6981 } else
6982 *new_view = tree_view;
6983 break;
6984 case 'g':
6985 case KEY_HOME:
6986 s->selected = 0;
6987 view->count = 0;
6988 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6989 break;
6990 case 'G':
6991 case KEY_END:
6992 s->selected = 0;
6993 view->count = 0;
6994 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6995 for (n = 0; n < view->nlines - 1; n++) {
6996 if (re == NULL)
6997 break;
6998 s->first_displayed_entry = re;
6999 re = TAILQ_PREV(re, tog_reflist_head, entry);
7001 if (n > 0)
7002 s->selected = n - 1;
7003 break;
7004 case 'k':
7005 case KEY_UP:
7006 case CTRL('p'):
7007 if (s->selected > 0) {
7008 s->selected--;
7009 break;
7011 ref_scroll_up(s, 1);
7012 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7013 view->count = 0;
7014 break;
7015 case CTRL('u'):
7016 case 'u':
7017 nscroll /= 2;
7018 /* FALL THROUGH */
7019 case KEY_PPAGE:
7020 case CTRL('b'):
7021 case 'b':
7022 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7023 s->selected -= MIN(nscroll, s->selected);
7024 ref_scroll_up(s, MAX(0, nscroll));
7025 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7026 view->count = 0;
7027 break;
7028 case 'j':
7029 case KEY_DOWN:
7030 case CTRL('n'):
7031 if (s->selected < s->ndisplayed - 1) {
7032 s->selected++;
7033 break;
7035 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7036 /* can't scroll any further */
7037 view->count = 0;
7038 break;
7040 ref_scroll_down(s, 1);
7041 break;
7042 case CTRL('d'):
7043 case 'd':
7044 nscroll /= 2;
7045 /* FALL THROUGH */
7046 case KEY_NPAGE:
7047 case CTRL('f'):
7048 case 'f':
7049 case ' ':
7050 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7051 /* can't scroll any further; move cursor down */
7052 if (s->selected < s->ndisplayed - 1)
7053 s->selected += MIN(nscroll,
7054 s->ndisplayed - s->selected - 1);
7055 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7056 s->selected += s->ndisplayed - s->selected - 1;
7057 view->count = 0;
7058 break;
7060 ref_scroll_down(s, nscroll);
7061 break;
7062 case CTRL('l'):
7063 view->count = 0;
7064 tog_free_refs();
7065 err = tog_load_refs(s->repo, s->sort_by_date);
7066 if (err)
7067 break;
7068 ref_view_free_refs(s);
7069 err = ref_view_load_refs(s);
7070 break;
7071 case KEY_RESIZE:
7072 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7073 s->selected = view->nlines - 2;
7074 break;
7075 default:
7076 view->count = 0;
7077 break;
7080 return err;
7083 __dead static void
7084 usage_ref(void)
7086 endwin();
7087 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7088 getprogname());
7089 exit(1);
7092 static const struct got_error *
7093 cmd_ref(int argc, char *argv[])
7095 const struct got_error *error;
7096 struct got_repository *repo = NULL;
7097 struct got_worktree *worktree = NULL;
7098 char *cwd = NULL, *repo_path = NULL;
7099 int ch;
7100 struct tog_view *view;
7101 int *pack_fds = NULL;
7103 while ((ch = getopt(argc, argv, "r:")) != -1) {
7104 switch (ch) {
7105 case 'r':
7106 repo_path = realpath(optarg, NULL);
7107 if (repo_path == NULL)
7108 return got_error_from_errno2("realpath",
7109 optarg);
7110 break;
7111 default:
7112 usage_ref();
7113 /* NOTREACHED */
7117 argc -= optind;
7118 argv += optind;
7120 if (argc > 1)
7121 usage_ref();
7123 error = got_repo_pack_fds_open(&pack_fds);
7124 if (error != NULL)
7125 goto done;
7127 if (repo_path == NULL) {
7128 cwd = getcwd(NULL, 0);
7129 if (cwd == NULL)
7130 return got_error_from_errno("getcwd");
7131 error = got_worktree_open(&worktree, cwd);
7132 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7133 goto done;
7134 if (worktree)
7135 repo_path =
7136 strdup(got_worktree_get_repo_path(worktree));
7137 else
7138 repo_path = strdup(cwd);
7139 if (repo_path == NULL) {
7140 error = got_error_from_errno("strdup");
7141 goto done;
7145 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7146 if (error != NULL)
7147 goto done;
7149 init_curses();
7151 error = apply_unveil(got_repo_get_path(repo), NULL);
7152 if (error)
7153 goto done;
7155 error = tog_load_refs(repo, 0);
7156 if (error)
7157 goto done;
7159 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7160 if (view == NULL) {
7161 error = got_error_from_errno("view_open");
7162 goto done;
7165 error = open_ref_view(view, repo);
7166 if (error)
7167 goto done;
7169 if (worktree) {
7170 /* Release work tree lock. */
7171 got_worktree_close(worktree);
7172 worktree = NULL;
7174 error = view_loop(view);
7175 done:
7176 free(repo_path);
7177 free(cwd);
7178 if (repo) {
7179 const struct got_error *close_err = got_repo_close(repo);
7180 if (close_err)
7181 error = close_err;
7183 if (pack_fds) {
7184 const struct got_error *pack_err =
7185 got_repo_pack_fds_close(pack_fds);
7186 if (error == NULL)
7187 error = pack_err;
7189 tog_free_refs();
7190 return error;
7193 static void
7194 list_commands(FILE *fp)
7196 size_t i;
7198 fprintf(fp, "commands:");
7199 for (i = 0; i < nitems(tog_commands); i++) {
7200 const struct tog_cmd *cmd = &tog_commands[i];
7201 fprintf(fp, " %s", cmd->name);
7203 fputc('\n', fp);
7206 __dead static void
7207 usage(int hflag, int status)
7209 FILE *fp = (status == 0) ? stdout : stderr;
7211 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
7212 getprogname());
7213 if (hflag) {
7214 fprintf(fp, "lazy usage: %s path\n", getprogname());
7215 list_commands(fp);
7217 exit(status);
7220 static char **
7221 make_argv(int argc, ...)
7223 va_list ap;
7224 char **argv;
7225 int i;
7227 va_start(ap, argc);
7229 argv = calloc(argc, sizeof(char *));
7230 if (argv == NULL)
7231 err(1, "calloc");
7232 for (i = 0; i < argc; i++) {
7233 argv[i] = strdup(va_arg(ap, char *));
7234 if (argv[i] == NULL)
7235 err(1, "strdup");
7238 va_end(ap);
7239 return argv;
7243 * Try to convert 'tog path' into a 'tog log path' command.
7244 * The user could simply have mistyped the command rather than knowingly
7245 * provided a path. So check whether argv[0] can in fact be resolved
7246 * to a path in the HEAD commit and print a special error if not.
7247 * This hack is for mpi@ <3
7249 static const struct got_error *
7250 tog_log_with_path(int argc, char *argv[])
7252 const struct got_error *error = NULL, *close_err;
7253 const struct tog_cmd *cmd = NULL;
7254 struct got_repository *repo = NULL;
7255 struct got_worktree *worktree = NULL;
7256 struct got_object_id *commit_id = NULL, *id = NULL;
7257 struct got_commit_object *commit = NULL;
7258 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7259 char *commit_id_str = NULL, **cmd_argv = NULL;
7260 int *pack_fds = NULL;
7262 cwd = getcwd(NULL, 0);
7263 if (cwd == NULL)
7264 return got_error_from_errno("getcwd");
7266 error = got_repo_pack_fds_open(&pack_fds);
7267 if (error != NULL)
7268 goto done;
7270 error = got_worktree_open(&worktree, cwd);
7271 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7272 goto done;
7274 if (worktree)
7275 repo_path = strdup(got_worktree_get_repo_path(worktree));
7276 else
7277 repo_path = strdup(cwd);
7278 if (repo_path == NULL) {
7279 error = got_error_from_errno("strdup");
7280 goto done;
7283 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7284 if (error != NULL)
7285 goto done;
7287 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7288 repo, worktree);
7289 if (error)
7290 goto done;
7292 error = tog_load_refs(repo, 0);
7293 if (error)
7294 goto done;
7295 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
7296 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
7297 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7298 if (error)
7299 goto done;
7301 if (worktree) {
7302 got_worktree_close(worktree);
7303 worktree = NULL;
7306 error = got_object_open_as_commit(&commit, repo, commit_id);
7307 if (error)
7308 goto done;
7310 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
7311 if (error) {
7312 if (error->code != GOT_ERR_NO_TREE_ENTRY)
7313 goto done;
7314 fprintf(stderr, "%s: '%s' is no known command or path\n",
7315 getprogname(), argv[0]);
7316 usage(1, 1);
7317 /* not reached */
7320 close_err = got_repo_close(repo);
7321 if (error == NULL)
7322 error = close_err;
7323 repo = NULL;
7325 error = got_object_id_str(&commit_id_str, commit_id);
7326 if (error)
7327 goto done;
7329 cmd = &tog_commands[0]; /* log */
7330 argc = 4;
7331 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
7332 error = cmd->cmd_main(argc, cmd_argv);
7333 done:
7334 if (repo) {
7335 close_err = got_repo_close(repo);
7336 if (error == NULL)
7337 error = close_err;
7339 if (commit)
7340 got_object_commit_close(commit);
7341 if (worktree)
7342 got_worktree_close(worktree);
7343 if (pack_fds) {
7344 const struct got_error *pack_err =
7345 got_repo_pack_fds_close(pack_fds);
7346 if (error == NULL)
7347 error = pack_err;
7349 free(id);
7350 free(commit_id_str);
7351 free(commit_id);
7352 free(cwd);
7353 free(repo_path);
7354 free(in_repo_path);
7355 if (cmd_argv) {
7356 int i;
7357 for (i = 0; i < argc; i++)
7358 free(cmd_argv[i]);
7359 free(cmd_argv);
7361 tog_free_refs();
7362 return error;
7365 int
7366 main(int argc, char *argv[])
7368 const struct got_error *error = NULL;
7369 const struct tog_cmd *cmd = NULL;
7370 int ch, hflag = 0, Vflag = 0;
7371 char **cmd_argv = NULL;
7372 static const struct option longopts[] = {
7373 { "version", no_argument, NULL, 'V' },
7374 { NULL, 0, NULL, 0}
7377 setlocale(LC_CTYPE, "");
7379 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
7380 switch (ch) {
7381 case 'h':
7382 hflag = 1;
7383 break;
7384 case 'V':
7385 Vflag = 1;
7386 break;
7387 default:
7388 usage(hflag, 1);
7389 /* NOTREACHED */
7393 argc -= optind;
7394 argv += optind;
7395 optind = 1;
7396 optreset = 1;
7398 if (Vflag) {
7399 got_version_print_str();
7400 return 0;
7403 #ifndef PROFILE
7404 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
7405 NULL) == -1)
7406 err(1, "pledge");
7407 #endif
7409 if (argc == 0) {
7410 if (hflag)
7411 usage(hflag, 0);
7412 /* Build an argument vector which runs a default command. */
7413 cmd = &tog_commands[0];
7414 argc = 1;
7415 cmd_argv = make_argv(argc, cmd->name);
7416 } else {
7417 size_t i;
7419 /* Did the user specify a command? */
7420 for (i = 0; i < nitems(tog_commands); i++) {
7421 if (strncmp(tog_commands[i].name, argv[0],
7422 strlen(argv[0])) == 0) {
7423 cmd = &tog_commands[i];
7424 break;
7429 if (cmd == NULL) {
7430 if (argc != 1)
7431 usage(0, 1);
7432 /* No command specified; try log with a path */
7433 error = tog_log_with_path(argc, argv);
7434 } else {
7435 if (hflag)
7436 cmd->cmd_usage();
7437 else
7438 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
7441 endwin();
7442 putchar('\n');
7443 if (cmd_argv) {
7444 int i;
7445 for (i = 0; i < argc; i++)
7446 free(cmd_argv[i]);
7447 free(cmd_argv);
7450 if (error && error->code != GOT_ERR_CANCELLED)
7451 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7452 return 0;