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 n = 0;
901 view->count = 0;
902 halfdelay(5); /* block for half a second */
904 do {
905 /*
906 * Don't overflow. Max valid request should be the greatest
907 * between the longest and total lines; cap at 10 million.
908 */
909 if (n >= 9999999)
910 n = 9999999;
911 else
912 n = n * 10 + (c - '0');
913 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
915 /* Massage excessive or inapplicable values at the input handler. */
916 view->count = n;
918 cbreak(); /* return to blocking */
919 return c;
922 static const struct got_error *
923 view_input(struct tog_view **new, int *done, struct tog_view *view,
924 struct tog_view_list_head *views)
926 const struct got_error *err = NULL;
927 struct tog_view *v;
928 int ch, errcode;
930 *new = NULL;
932 /* Clear "no matches" indicator. */
933 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
934 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
935 view->search_next_done = TOG_SEARCH_HAVE_MORE;
936 view->count = 0;
939 if (view->searching && !view->search_next_done) {
940 errcode = pthread_mutex_unlock(&tog_mutex);
941 if (errcode)
942 return got_error_set_errno(errcode,
943 "pthread_mutex_unlock");
944 sched_yield();
945 errcode = pthread_mutex_lock(&tog_mutex);
946 if (errcode)
947 return got_error_set_errno(errcode,
948 "pthread_mutex_lock");
949 view->search_next(view);
950 return NULL;
953 nodelay(stdscr, FALSE);
954 /* Allow threads to make progress while we are waiting for input. */
955 errcode = pthread_mutex_unlock(&tog_mutex);
956 if (errcode)
957 return got_error_set_errno(errcode, "pthread_mutex_unlock");
958 /* If we have an unfinished count, don't get a new key map. */
959 ch = view->ch;
960 if ((view->count && --view->count == 0) || !view->count) {
961 ch = wgetch(view->window);
962 if (ch >= '1' && ch <= '9')
963 view->ch = ch = get_compound_key(view, ch);
965 errcode = pthread_mutex_lock(&tog_mutex);
966 if (errcode)
967 return got_error_set_errno(errcode, "pthread_mutex_lock");
968 nodelay(stdscr, TRUE);
970 if (tog_sigwinch_received || tog_sigcont_received) {
971 tog_resizeterm();
972 tog_sigwinch_received = 0;
973 tog_sigcont_received = 0;
974 TAILQ_FOREACH(v, views, entry) {
975 err = view_resize(v);
976 if (err)
977 return err;
978 err = v->input(new, v, KEY_RESIZE);
979 if (err)
980 return err;
981 if (v->child) {
982 err = view_resize(v->child);
983 if (err)
984 return err;
985 err = v->child->input(new, v->child,
986 KEY_RESIZE);
987 if (err)
988 return err;
993 switch (ch) {
994 case '\t':
995 view->count = 0;
996 if (view->child) {
997 view->focussed = 0;
998 view->child->focussed = 1;
999 view->focus_child = 1;
1000 } else if (view->parent) {
1001 view->focussed = 0;
1002 view->parent->focussed = 1;
1003 view->parent->focus_child = 0;
1004 if (!view_is_splitscreen(view))
1005 err = view_fullscreen(view->parent);
1007 break;
1008 case 'q':
1009 err = view->input(new, view, ch);
1010 view->dying = 1;
1011 break;
1012 case 'Q':
1013 *done = 1;
1014 break;
1015 case 'F':
1016 view->count = 0;
1017 if (view_is_parent_view(view)) {
1018 if (view->child == NULL)
1019 break;
1020 if (view_is_splitscreen(view->child)) {
1021 view->focussed = 0;
1022 view->child->focussed = 1;
1023 err = view_fullscreen(view->child);
1024 } else
1025 err = view_splitscreen(view->child);
1026 if (err)
1027 break;
1028 err = view->child->input(new, view->child,
1029 KEY_RESIZE);
1030 } else {
1031 if (view_is_splitscreen(view)) {
1032 view->parent->focussed = 0;
1033 view->focussed = 1;
1034 err = view_fullscreen(view);
1035 } else {
1036 err = view_splitscreen(view);
1037 if (!err)
1038 err = view_resize(view->parent);
1040 if (err)
1041 break;
1042 err = view->input(new, view, KEY_RESIZE);
1044 break;
1045 case KEY_RESIZE:
1046 break;
1047 case '/':
1048 view->count = 0;
1049 if (view->search_start)
1050 view_search_start(view);
1051 else
1052 err = view->input(new, view, ch);
1053 break;
1054 case 'N':
1055 case 'n':
1056 if (view->search_started && view->search_next) {
1057 view->searching = (ch == 'n' ?
1058 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1059 view->search_next_done = 0;
1060 view->search_next(view);
1061 } else
1062 err = view->input(new, view, ch);
1063 break;
1064 default:
1065 err = view->input(new, view, ch);
1066 break;
1069 return err;
1072 static void
1073 view_vborder(struct tog_view *view)
1075 PANEL *panel;
1076 const struct tog_view *view_above;
1078 if (view->parent)
1079 return view_vborder(view->parent);
1081 panel = panel_above(view->panel);
1082 if (panel == NULL)
1083 return;
1085 view_above = panel_userptr(panel);
1086 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
1087 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
1090 static int
1091 view_needs_focus_indication(struct tog_view *view)
1093 if (view_is_parent_view(view)) {
1094 if (view->child == NULL || view->child->focussed)
1095 return 0;
1096 if (!view_is_splitscreen(view->child))
1097 return 0;
1098 } else if (!view_is_splitscreen(view))
1099 return 0;
1101 return view->focussed;
1104 static const struct got_error *
1105 view_loop(struct tog_view *view)
1107 const struct got_error *err = NULL;
1108 struct tog_view_list_head views;
1109 struct tog_view *new_view;
1110 int fast_refresh = 10;
1111 int done = 0, errcode;
1113 errcode = pthread_mutex_lock(&tog_mutex);
1114 if (errcode)
1115 return got_error_set_errno(errcode, "pthread_mutex_lock");
1117 TAILQ_INIT(&views);
1118 TAILQ_INSERT_HEAD(&views, view, entry);
1120 view->focussed = 1;
1121 err = view->show(view);
1122 if (err)
1123 return err;
1124 update_panels();
1125 doupdate();
1126 while (!TAILQ_EMPTY(&views) && !done && !tog_fatal_signal_received()) {
1127 /* Refresh fast during initialization, then become slower. */
1128 if (fast_refresh && fast_refresh-- == 0)
1129 halfdelay(10); /* switch to once per second */
1131 err = view_input(&new_view, &done, view, &views);
1132 if (err)
1133 break;
1134 if (view->dying) {
1135 struct tog_view *v, *prev = NULL;
1137 if (view_is_parent_view(view))
1138 prev = TAILQ_PREV(view, tog_view_list_head,
1139 entry);
1140 else if (view->parent)
1141 prev = view->parent;
1143 if (view->parent) {
1144 view->parent->child = NULL;
1145 view->parent->focus_child = 0;
1147 err = view_resize(view->parent);
1148 if (err)
1149 break;
1150 } else
1151 TAILQ_REMOVE(&views, view, entry);
1153 err = view_close(view);
1154 if (err)
1155 goto done;
1157 view = NULL;
1158 TAILQ_FOREACH(v, &views, entry) {
1159 if (v->focussed)
1160 break;
1162 if (view == NULL && new_view == NULL) {
1163 /* No view has focus. Try to pick one. */
1164 if (prev)
1165 view = prev;
1166 else if (!TAILQ_EMPTY(&views)) {
1167 view = TAILQ_LAST(&views,
1168 tog_view_list_head);
1170 if (view) {
1171 if (view->focus_child) {
1172 view->child->focussed = 1;
1173 view = view->child;
1174 } else
1175 view->focussed = 1;
1179 if (new_view) {
1180 struct tog_view *v, *t;
1181 /* Only allow one parent view per type. */
1182 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1183 if (v->type != new_view->type)
1184 continue;
1185 TAILQ_REMOVE(&views, v, entry);
1186 err = view_close(v);
1187 if (err)
1188 goto done;
1189 break;
1191 TAILQ_INSERT_TAIL(&views, new_view, entry);
1192 view = new_view;
1194 if (view) {
1195 if (view_is_parent_view(view)) {
1196 if (view->child && view->child->focussed)
1197 view = view->child;
1198 } else {
1199 if (view->parent && view->parent->focussed)
1200 view = view->parent;
1202 show_panel(view->panel);
1203 if (view->child && view_is_splitscreen(view->child))
1204 show_panel(view->child->panel);
1205 if (view->parent && view_is_splitscreen(view)) {
1206 err = view->parent->show(view->parent);
1207 if (err)
1208 goto done;
1210 err = view->show(view);
1211 if (err)
1212 goto done;
1213 if (view->child) {
1214 err = view->child->show(view->child);
1215 if (err)
1216 goto done;
1218 update_panels();
1219 doupdate();
1222 done:
1223 while (!TAILQ_EMPTY(&views)) {
1224 view = TAILQ_FIRST(&views);
1225 TAILQ_REMOVE(&views, view, entry);
1226 view_close(view);
1229 errcode = pthread_mutex_unlock(&tog_mutex);
1230 if (errcode && err == NULL)
1231 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1233 return err;
1236 __dead static void
1237 usage_log(void)
1239 endwin();
1240 fprintf(stderr,
1241 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1242 getprogname());
1243 exit(1);
1246 /* Create newly allocated wide-character string equivalent to a byte string. */
1247 static const struct got_error *
1248 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1250 char *vis = NULL;
1251 const struct got_error *err = NULL;
1253 *ws = NULL;
1254 *wlen = mbstowcs(NULL, s, 0);
1255 if (*wlen == (size_t)-1) {
1256 int vislen;
1257 if (errno != EILSEQ)
1258 return got_error_from_errno("mbstowcs");
1260 /* byte string invalid in current encoding; try to "fix" it */
1261 err = got_mbsavis(&vis, &vislen, s);
1262 if (err)
1263 return err;
1264 *wlen = mbstowcs(NULL, vis, 0);
1265 if (*wlen == (size_t)-1) {
1266 err = got_error_from_errno("mbstowcs"); /* give up */
1267 goto done;
1271 *ws = calloc(*wlen + 1, sizeof(**ws));
1272 if (*ws == NULL) {
1273 err = got_error_from_errno("calloc");
1274 goto done;
1277 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1278 err = got_error_from_errno("mbstowcs");
1279 done:
1280 free(vis);
1281 if (err) {
1282 free(*ws);
1283 *ws = NULL;
1284 *wlen = 0;
1286 return err;
1289 static const struct got_error *
1290 expand_tab(char **ptr, const char *src)
1292 char *dst;
1293 size_t len, n, idx = 0, sz = 0;
1295 *ptr = NULL;
1296 n = len = strlen(src);
1297 dst = malloc(n + 1);
1298 if (dst == NULL)
1299 return got_error_from_errno("malloc");
1301 while (idx < len && src[idx]) {
1302 const char c = src[idx];
1304 if (c == '\t') {
1305 size_t nb = TABSIZE - sz % TABSIZE;
1306 char *p;
1308 p = realloc(dst, n + nb);
1309 if (p == NULL) {
1310 free(dst);
1311 return got_error_from_errno("realloc");
1314 dst = p;
1315 n += nb;
1316 memset(dst + sz, ' ', nb);
1317 sz += nb;
1318 } else
1319 dst[sz++] = src[idx];
1320 ++idx;
1323 dst[sz] = '\0';
1324 *ptr = dst;
1325 return NULL;
1329 * Advance at most n columns from wline starting at offset off.
1330 * Return the index to the first character after the span operation.
1331 * Return the combined column width of all spanned wide character in
1332 * *rcol.
1334 static int
1335 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1337 int width, i, cols = 0;
1339 if (n == 0) {
1340 *rcol = cols;
1341 return off;
1344 for (i = off; wline[i] != L'\0'; ++i) {
1345 if (wline[i] == L'\t')
1346 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1347 else
1348 width = wcwidth(wline[i]);
1350 if (width == -1) {
1351 width = 1;
1352 wline[i] = L'.';
1355 if (cols + width > n)
1356 break;
1357 cols += width;
1360 *rcol = cols;
1361 return i;
1365 * Format a line for display, ensuring that it won't overflow a width limit.
1366 * With scrolling, the width returned refers to the scrolled version of the
1367 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1369 static const struct got_error *
1370 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1371 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1373 const struct got_error *err = NULL;
1374 int cols;
1375 wchar_t *wline = NULL;
1376 char *exstr = NULL;
1377 size_t wlen;
1378 int i, scrollx;
1380 *wlinep = NULL;
1381 *widthp = 0;
1383 if (expand) {
1384 err = expand_tab(&exstr, line);
1385 if (err)
1386 return err;
1389 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1390 free(exstr);
1391 if (err)
1392 return err;
1394 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1396 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1397 wline[wlen - 1] = L'\0';
1398 wlen--;
1400 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1401 wline[wlen - 1] = L'\0';
1402 wlen--;
1405 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1406 wline[i] = L'\0';
1408 if (widthp)
1409 *widthp = cols;
1410 if (scrollxp)
1411 *scrollxp = scrollx;
1412 if (err)
1413 free(wline);
1414 else
1415 *wlinep = wline;
1416 return err;
1419 static const struct got_error*
1420 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1421 struct got_object_id *id, struct got_repository *repo)
1423 static const struct got_error *err = NULL;
1424 struct got_reflist_entry *re;
1425 char *s;
1426 const char *name;
1428 *refs_str = NULL;
1430 TAILQ_FOREACH(re, refs, entry) {
1431 struct got_tag_object *tag = NULL;
1432 struct got_object_id *ref_id;
1433 int cmp;
1435 name = got_ref_get_name(re->ref);
1436 if (strcmp(name, GOT_REF_HEAD) == 0)
1437 continue;
1438 if (strncmp(name, "refs/", 5) == 0)
1439 name += 5;
1440 if (strncmp(name, "got/", 4) == 0 &&
1441 strncmp(name, "got/backup/", 11) != 0)
1442 continue;
1443 if (strncmp(name, "heads/", 6) == 0)
1444 name += 6;
1445 if (strncmp(name, "remotes/", 8) == 0) {
1446 name += 8;
1447 s = strstr(name, "/" GOT_REF_HEAD);
1448 if (s != NULL && s[strlen(s)] == '\0')
1449 continue;
1451 err = got_ref_resolve(&ref_id, repo, re->ref);
1452 if (err)
1453 break;
1454 if (strncmp(name, "tags/", 5) == 0) {
1455 err = got_object_open_as_tag(&tag, repo, ref_id);
1456 if (err) {
1457 if (err->code != GOT_ERR_OBJ_TYPE) {
1458 free(ref_id);
1459 break;
1461 /* Ref points at something other than a tag. */
1462 err = NULL;
1463 tag = NULL;
1466 cmp = got_object_id_cmp(tag ?
1467 got_object_tag_get_object_id(tag) : ref_id, id);
1468 free(ref_id);
1469 if (tag)
1470 got_object_tag_close(tag);
1471 if (cmp != 0)
1472 continue;
1473 s = *refs_str;
1474 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1475 s ? ", " : "", name) == -1) {
1476 err = got_error_from_errno("asprintf");
1477 free(s);
1478 *refs_str = NULL;
1479 break;
1481 free(s);
1484 return err;
1487 static const struct got_error *
1488 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1489 int col_tab_align)
1491 char *smallerthan;
1493 smallerthan = strchr(author, '<');
1494 if (smallerthan && smallerthan[1] != '\0')
1495 author = smallerthan + 1;
1496 author[strcspn(author, "@>")] = '\0';
1497 return format_line(wauthor, author_width, NULL, author, 0, limit,
1498 col_tab_align, 0);
1501 static const struct got_error *
1502 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1503 struct got_object_id *id, const size_t date_display_cols,
1504 int author_display_cols)
1506 struct tog_log_view_state *s = &view->state.log;
1507 const struct got_error *err = NULL;
1508 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1509 char *logmsg0 = NULL, *logmsg = NULL;
1510 char *author = NULL;
1511 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1512 int author_width, logmsg_width;
1513 char *newline, *line = NULL;
1514 int col, limit, scrollx;
1515 const int avail = view->ncols;
1516 struct tm tm;
1517 time_t committer_time;
1518 struct tog_color *tc;
1520 committer_time = got_object_commit_get_committer_time(commit);
1521 if (gmtime_r(&committer_time, &tm) == NULL)
1522 return got_error_from_errno("gmtime_r");
1523 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1524 return got_error(GOT_ERR_NO_SPACE);
1526 if (avail <= date_display_cols)
1527 limit = MIN(sizeof(datebuf) - 1, avail);
1528 else
1529 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1530 tc = get_color(&s->colors, TOG_COLOR_DATE);
1531 if (tc)
1532 wattr_on(view->window,
1533 COLOR_PAIR(tc->colorpair), NULL);
1534 waddnstr(view->window, datebuf, limit);
1535 if (tc)
1536 wattr_off(view->window,
1537 COLOR_PAIR(tc->colorpair), NULL);
1538 col = limit;
1539 if (col > avail)
1540 goto done;
1542 if (avail >= 120) {
1543 char *id_str;
1544 err = got_object_id_str(&id_str, id);
1545 if (err)
1546 goto done;
1547 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1548 if (tc)
1549 wattr_on(view->window,
1550 COLOR_PAIR(tc->colorpair), NULL);
1551 wprintw(view->window, "%.8s ", id_str);
1552 if (tc)
1553 wattr_off(view->window,
1554 COLOR_PAIR(tc->colorpair), NULL);
1555 free(id_str);
1556 col += 9;
1557 if (col > avail)
1558 goto done;
1561 author = strdup(got_object_commit_get_author(commit));
1562 if (author == NULL) {
1563 err = got_error_from_errno("strdup");
1564 goto done;
1566 err = format_author(&wauthor, &author_width, author, avail - col, col);
1567 if (err)
1568 goto done;
1569 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1570 if (tc)
1571 wattr_on(view->window,
1572 COLOR_PAIR(tc->colorpair), NULL);
1573 waddwstr(view->window, wauthor);
1574 if (tc)
1575 wattr_off(view->window,
1576 COLOR_PAIR(tc->colorpair), NULL);
1577 col += author_width;
1578 while (col < avail && author_width < author_display_cols + 2) {
1579 waddch(view->window, ' ');
1580 col++;
1581 author_width++;
1583 if (col > avail)
1584 goto done;
1586 err = got_object_commit_get_logmsg(&logmsg0, commit);
1587 if (err)
1588 goto done;
1589 logmsg = logmsg0;
1590 while (*logmsg == '\n')
1591 logmsg++;
1592 newline = strchr(logmsg, '\n');
1593 if (newline)
1594 *newline = '\0';
1595 limit = avail - col;
1596 if (view->child && view_is_splitscreen(view->child) && limit > 0)
1597 limit--; /* for the border */
1598 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
1599 limit, col, 1);
1600 if (err)
1601 goto done;
1602 waddwstr(view->window, &wlogmsg[scrollx]);
1603 col += MAX(logmsg_width, 0);
1604 while (col < avail) {
1605 waddch(view->window, ' ');
1606 col++;
1608 done:
1609 free(logmsg0);
1610 free(wlogmsg);
1611 free(author);
1612 free(wauthor);
1613 free(line);
1614 return err;
1617 static struct commit_queue_entry *
1618 alloc_commit_queue_entry(struct got_commit_object *commit,
1619 struct got_object_id *id)
1621 struct commit_queue_entry *entry;
1623 entry = calloc(1, sizeof(*entry));
1624 if (entry == NULL)
1625 return NULL;
1627 entry->id = id;
1628 entry->commit = commit;
1629 return entry;
1632 static void
1633 pop_commit(struct commit_queue *commits)
1635 struct commit_queue_entry *entry;
1637 entry = TAILQ_FIRST(&commits->head);
1638 TAILQ_REMOVE(&commits->head, entry, entry);
1639 got_object_commit_close(entry->commit);
1640 commits->ncommits--;
1641 /* Don't free entry->id! It is owned by the commit graph. */
1642 free(entry);
1645 static void
1646 free_commits(struct commit_queue *commits)
1648 while (!TAILQ_EMPTY(&commits->head))
1649 pop_commit(commits);
1652 static const struct got_error *
1653 match_commit(int *have_match, struct got_object_id *id,
1654 struct got_commit_object *commit, regex_t *regex)
1656 const struct got_error *err = NULL;
1657 regmatch_t regmatch;
1658 char *id_str = NULL, *logmsg = NULL;
1660 *have_match = 0;
1662 err = got_object_id_str(&id_str, id);
1663 if (err)
1664 return err;
1666 err = got_object_commit_get_logmsg(&logmsg, commit);
1667 if (err)
1668 goto done;
1670 if (regexec(regex, got_object_commit_get_author(commit), 1,
1671 &regmatch, 0) == 0 ||
1672 regexec(regex, got_object_commit_get_committer(commit), 1,
1673 &regmatch, 0) == 0 ||
1674 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
1675 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
1676 *have_match = 1;
1677 done:
1678 free(id_str);
1679 free(logmsg);
1680 return err;
1683 static const struct got_error *
1684 queue_commits(struct tog_log_thread_args *a)
1686 const struct got_error *err = NULL;
1689 * We keep all commits open throughout the lifetime of the log
1690 * view in order to avoid having to re-fetch commits from disk
1691 * while updating the display.
1693 do {
1694 struct got_object_id *id;
1695 struct got_commit_object *commit;
1696 struct commit_queue_entry *entry;
1697 int errcode;
1699 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
1700 NULL, NULL);
1701 if (err || id == NULL)
1702 break;
1704 err = got_object_open_as_commit(&commit, a->repo, id);
1705 if (err)
1706 break;
1707 entry = alloc_commit_queue_entry(commit, id);
1708 if (entry == NULL) {
1709 err = got_error_from_errno("alloc_commit_queue_entry");
1710 break;
1713 errcode = pthread_mutex_lock(&tog_mutex);
1714 if (errcode) {
1715 err = got_error_set_errno(errcode,
1716 "pthread_mutex_lock");
1717 break;
1720 entry->idx = a->commits->ncommits;
1721 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
1722 a->commits->ncommits++;
1724 if (*a->searching == TOG_SEARCH_FORWARD &&
1725 !*a->search_next_done) {
1726 int have_match;
1727 err = match_commit(&have_match, id, commit, a->regex);
1728 if (err)
1729 break;
1730 if (have_match)
1731 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
1734 errcode = pthread_mutex_unlock(&tog_mutex);
1735 if (errcode && err == NULL)
1736 err = got_error_set_errno(errcode,
1737 "pthread_mutex_unlock");
1738 if (err)
1739 break;
1740 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
1742 return err;
1745 static void
1746 select_commit(struct tog_log_view_state *s)
1748 struct commit_queue_entry *entry;
1749 int ncommits = 0;
1751 entry = s->first_displayed_entry;
1752 while (entry) {
1753 if (ncommits == s->selected) {
1754 s->selected_entry = entry;
1755 break;
1757 entry = TAILQ_NEXT(entry, entry);
1758 ncommits++;
1762 static const struct got_error *
1763 draw_commits(struct tog_view *view)
1765 const struct got_error *err = NULL;
1766 struct tog_log_view_state *s = &view->state.log;
1767 struct commit_queue_entry *entry = s->selected_entry;
1768 const int limit = view->nlines;
1769 int width;
1770 int ncommits, author_cols = 4;
1771 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
1772 char *refs_str = NULL;
1773 wchar_t *wline;
1774 struct tog_color *tc;
1775 static const size_t date_display_cols = 12;
1777 if (s->selected_entry &&
1778 !(view->searching && view->search_next_done == 0)) {
1779 struct got_reflist_head *refs;
1780 err = got_object_id_str(&id_str, s->selected_entry->id);
1781 if (err)
1782 return err;
1783 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
1784 s->selected_entry->id);
1785 if (refs) {
1786 err = build_refs_str(&refs_str, refs,
1787 s->selected_entry->id, s->repo);
1788 if (err)
1789 goto done;
1793 if (s->thread_args.commits_needed == 0)
1794 halfdelay(10); /* disable fast refresh */
1796 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
1797 if (asprintf(&ncommits_str, " [%d/%d] %s",
1798 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1799 (view->searching && !view->search_next_done) ?
1800 "searching..." : "loading...") == -1) {
1801 err = got_error_from_errno("asprintf");
1802 goto done;
1804 } else {
1805 const char *search_str = NULL;
1807 if (view->searching) {
1808 if (view->search_next_done == TOG_SEARCH_NO_MORE)
1809 search_str = "no more matches";
1810 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
1811 search_str = "no matches found";
1812 else if (!view->search_next_done)
1813 search_str = "searching...";
1816 if (asprintf(&ncommits_str, " [%d/%d] %s",
1817 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1818 search_str ? search_str :
1819 (refs_str ? refs_str : "")) == -1) {
1820 err = got_error_from_errno("asprintf");
1821 goto done;
1825 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
1826 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
1827 "........................................",
1828 s->in_repo_path, ncommits_str) == -1) {
1829 err = got_error_from_errno("asprintf");
1830 header = NULL;
1831 goto done;
1833 } else if (asprintf(&header, "commit %s%s",
1834 id_str ? id_str : "........................................",
1835 ncommits_str) == -1) {
1836 err = got_error_from_errno("asprintf");
1837 header = NULL;
1838 goto done;
1840 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
1841 if (err)
1842 goto done;
1844 werase(view->window);
1846 if (view_needs_focus_indication(view))
1847 wstandout(view->window);
1848 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1849 if (tc)
1850 wattr_on(view->window,
1851 COLOR_PAIR(tc->colorpair), NULL);
1852 waddwstr(view->window, wline);
1853 if (tc)
1854 wattr_off(view->window,
1855 COLOR_PAIR(tc->colorpair), NULL);
1856 while (width < view->ncols) {
1857 waddch(view->window, ' ');
1858 width++;
1860 if (view_needs_focus_indication(view))
1861 wstandend(view->window);
1862 free(wline);
1863 if (limit <= 1)
1864 goto done;
1866 /* Grow author column size if necessary, and set view->maxx. */
1867 entry = s->first_displayed_entry;
1868 ncommits = 0;
1869 view->maxx = 0;
1870 while (entry) {
1871 char *author, *eol, *msg, *msg0;
1872 wchar_t *wauthor, *wmsg;
1873 int width;
1874 if (ncommits >= limit - 1)
1875 break;
1876 author = strdup(got_object_commit_get_author(entry->commit));
1877 if (author == NULL) {
1878 err = got_error_from_errno("strdup");
1879 goto done;
1881 err = format_author(&wauthor, &width, author, COLS,
1882 date_display_cols);
1883 if (author_cols < width)
1884 author_cols = width;
1885 free(wauthor);
1886 free(author);
1887 err = got_object_commit_get_logmsg(&msg0, entry->commit);
1888 if (err)
1889 goto done;
1890 msg = msg0;
1891 while (*msg == '\n')
1892 ++msg;
1893 if ((eol = strchr(msg, '\n')))
1894 *eol = '\0';
1895 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
1896 date_display_cols + author_cols, 0);
1897 if (err)
1898 goto done;
1899 view->maxx = MAX(view->maxx, width);
1900 free(msg0);
1901 free(wmsg);
1902 ncommits++;
1903 entry = TAILQ_NEXT(entry, entry);
1906 entry = s->first_displayed_entry;
1907 s->last_displayed_entry = s->first_displayed_entry;
1908 ncommits = 0;
1909 while (entry) {
1910 if (ncommits >= limit - 1)
1911 break;
1912 if (ncommits == s->selected)
1913 wstandout(view->window);
1914 err = draw_commit(view, entry->commit, entry->id,
1915 date_display_cols, author_cols);
1916 if (ncommits == s->selected)
1917 wstandend(view->window);
1918 if (err)
1919 goto done;
1920 ncommits++;
1921 s->last_displayed_entry = entry;
1922 entry = TAILQ_NEXT(entry, entry);
1925 view_vborder(view);
1926 done:
1927 free(id_str);
1928 free(refs_str);
1929 free(ncommits_str);
1930 free(header);
1931 return err;
1934 static void
1935 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
1937 struct commit_queue_entry *entry;
1938 int nscrolled = 0;
1940 entry = TAILQ_FIRST(&s->commits.head);
1941 if (s->first_displayed_entry == entry)
1942 return;
1944 entry = s->first_displayed_entry;
1945 while (entry && nscrolled < maxscroll) {
1946 entry = TAILQ_PREV(entry, commit_queue_head, entry);
1947 if (entry) {
1948 s->first_displayed_entry = entry;
1949 nscrolled++;
1954 static const struct got_error *
1955 trigger_log_thread(struct tog_view *view, int wait)
1957 struct tog_log_thread_args *ta = &view->state.log.thread_args;
1958 int errcode;
1960 halfdelay(1); /* fast refresh while loading commits */
1962 while (ta->commits_needed > 0 || ta->load_all) {
1963 if (ta->log_complete)
1964 break;
1966 /* Wake the log thread. */
1967 errcode = pthread_cond_signal(&ta->need_commits);
1968 if (errcode)
1969 return got_error_set_errno(errcode,
1970 "pthread_cond_signal");
1973 * The mutex will be released while the view loop waits
1974 * in wgetch(), at which time the log thread will run.
1976 if (!wait)
1977 break;
1979 /* Display progress update in log view. */
1980 show_log_view(view);
1981 update_panels();
1982 doupdate();
1984 /* Wait right here while next commit is being loaded. */
1985 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
1986 if (errcode)
1987 return got_error_set_errno(errcode,
1988 "pthread_cond_wait");
1990 /* Display progress update in log view. */
1991 show_log_view(view);
1992 update_panels();
1993 doupdate();
1996 return NULL;
1999 static const struct got_error *
2000 log_scroll_down(struct tog_view *view, int maxscroll)
2002 struct tog_log_view_state *s = &view->state.log;
2003 const struct got_error *err = NULL;
2004 struct commit_queue_entry *pentry;
2005 int nscrolled = 0, ncommits_needed;
2007 if (s->last_displayed_entry == NULL)
2008 return NULL;
2010 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2011 if (s->commits.ncommits < ncommits_needed &&
2012 !s->thread_args.log_complete) {
2014 * Ask the log thread for required amount of commits.
2016 s->thread_args.commits_needed += maxscroll;
2017 err = trigger_log_thread(view, 1);
2018 if (err)
2019 return err;
2022 do {
2023 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2024 if (pentry == NULL)
2025 break;
2027 s->last_displayed_entry = pentry;
2029 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2030 if (pentry == NULL)
2031 break;
2032 s->first_displayed_entry = pentry;
2033 } while (++nscrolled < maxscroll);
2035 return err;
2038 static const struct got_error *
2039 open_diff_view_for_commit(struct tog_view **new_view, int begin_x,
2040 struct got_commit_object *commit, struct got_object_id *commit_id,
2041 struct tog_view *log_view, struct got_repository *repo)
2043 const struct got_error *err;
2044 struct got_object_qid *parent_id;
2045 struct tog_view *diff_view;
2047 diff_view = view_open(0, 0, 0, begin_x, TOG_VIEW_DIFF);
2048 if (diff_view == NULL)
2049 return got_error_from_errno("view_open");
2051 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2052 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2053 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2054 if (err == NULL)
2055 *new_view = diff_view;
2056 return err;
2059 static const struct got_error *
2060 tree_view_visit_subtree(struct tog_tree_view_state *s,
2061 struct got_tree_object *subtree)
2063 struct tog_parent_tree *parent;
2065 parent = calloc(1, sizeof(*parent));
2066 if (parent == NULL)
2067 return got_error_from_errno("calloc");
2069 parent->tree = s->tree;
2070 parent->first_displayed_entry = s->first_displayed_entry;
2071 parent->selected_entry = s->selected_entry;
2072 parent->selected = s->selected;
2073 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2074 s->tree = subtree;
2075 s->selected = 0;
2076 s->first_displayed_entry = NULL;
2077 return NULL;
2080 static const struct got_error *
2081 tree_view_walk_path(struct tog_tree_view_state *s,
2082 struct got_commit_object *commit, const char *path)
2084 const struct got_error *err = NULL;
2085 struct got_tree_object *tree = NULL;
2086 const char *p;
2087 char *slash, *subpath = NULL;
2089 /* Walk the path and open corresponding tree objects. */
2090 p = path;
2091 while (*p) {
2092 struct got_tree_entry *te;
2093 struct got_object_id *tree_id;
2094 char *te_name;
2096 while (p[0] == '/')
2097 p++;
2099 /* Ensure the correct subtree entry is selected. */
2100 slash = strchr(p, '/');
2101 if (slash == NULL)
2102 te_name = strdup(p);
2103 else
2104 te_name = strndup(p, slash - p);
2105 if (te_name == NULL) {
2106 err = got_error_from_errno("strndup");
2107 break;
2109 te = got_object_tree_find_entry(s->tree, te_name);
2110 if (te == NULL) {
2111 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2112 free(te_name);
2113 break;
2115 free(te_name);
2116 s->first_displayed_entry = s->selected_entry = te;
2118 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2119 break; /* jump to this file's entry */
2121 slash = strchr(p, '/');
2122 if (slash)
2123 subpath = strndup(path, slash - path);
2124 else
2125 subpath = strdup(path);
2126 if (subpath == NULL) {
2127 err = got_error_from_errno("strdup");
2128 break;
2131 err = got_object_id_by_path(&tree_id, s->repo, commit,
2132 subpath);
2133 if (err)
2134 break;
2136 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2137 free(tree_id);
2138 if (err)
2139 break;
2141 err = tree_view_visit_subtree(s, tree);
2142 if (err) {
2143 got_object_tree_close(tree);
2144 break;
2146 if (slash == NULL)
2147 break;
2148 free(subpath);
2149 subpath = NULL;
2150 p = slash;
2153 free(subpath);
2154 return err;
2157 static const struct got_error *
2158 browse_commit_tree(struct tog_view **new_view, int begin_x,
2159 struct commit_queue_entry *entry, const char *path,
2160 const char *head_ref_name, struct got_repository *repo)
2162 const struct got_error *err = NULL;
2163 struct tog_tree_view_state *s;
2164 struct tog_view *tree_view;
2166 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
2167 if (tree_view == NULL)
2168 return got_error_from_errno("view_open");
2170 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2171 if (err)
2172 return err;
2173 s = &tree_view->state.tree;
2175 *new_view = tree_view;
2177 if (got_path_is_root_dir(path))
2178 return NULL;
2180 return tree_view_walk_path(s, entry->commit, path);
2183 static const struct got_error *
2184 block_signals_used_by_main_thread(void)
2186 sigset_t sigset;
2187 int errcode;
2189 if (sigemptyset(&sigset) == -1)
2190 return got_error_from_errno("sigemptyset");
2192 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2193 if (sigaddset(&sigset, SIGWINCH) == -1)
2194 return got_error_from_errno("sigaddset");
2195 if (sigaddset(&sigset, SIGCONT) == -1)
2196 return got_error_from_errno("sigaddset");
2197 if (sigaddset(&sigset, SIGINT) == -1)
2198 return got_error_from_errno("sigaddset");
2199 if (sigaddset(&sigset, SIGTERM) == -1)
2200 return got_error_from_errno("sigaddset");
2202 /* ncurses handles SIGTSTP */
2203 if (sigaddset(&sigset, SIGTSTP) == -1)
2204 return got_error_from_errno("sigaddset");
2206 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2207 if (errcode)
2208 return got_error_set_errno(errcode, "pthread_sigmask");
2210 return NULL;
2213 static void *
2214 log_thread(void *arg)
2216 const struct got_error *err = NULL;
2217 int errcode = 0;
2218 struct tog_log_thread_args *a = arg;
2219 int done = 0;
2221 err = block_signals_used_by_main_thread();
2222 if (err)
2223 return (void *)err;
2225 while (!done && !err && !tog_fatal_signal_received()) {
2226 err = queue_commits(a);
2227 if (err) {
2228 if (err->code != GOT_ERR_ITER_COMPLETED)
2229 return (void *)err;
2230 err = NULL;
2231 done = 1;
2232 } else if (a->commits_needed > 0 && !a->load_all)
2233 a->commits_needed--;
2235 errcode = pthread_mutex_lock(&tog_mutex);
2236 if (errcode) {
2237 err = got_error_set_errno(errcode,
2238 "pthread_mutex_lock");
2239 break;
2240 } else if (*a->quit)
2241 done = 1;
2242 else if (*a->first_displayed_entry == NULL) {
2243 *a->first_displayed_entry =
2244 TAILQ_FIRST(&a->commits->head);
2245 *a->selected_entry = *a->first_displayed_entry;
2248 errcode = pthread_cond_signal(&a->commit_loaded);
2249 if (errcode) {
2250 err = got_error_set_errno(errcode,
2251 "pthread_cond_signal");
2252 pthread_mutex_unlock(&tog_mutex);
2253 break;
2256 if (done)
2257 a->commits_needed = 0;
2258 else {
2259 if (a->commits_needed == 0 && !a->load_all) {
2260 errcode = pthread_cond_wait(&a->need_commits,
2261 &tog_mutex);
2262 if (errcode)
2263 err = got_error_set_errno(errcode,
2264 "pthread_cond_wait");
2265 if (*a->quit)
2266 done = 1;
2270 errcode = pthread_mutex_unlock(&tog_mutex);
2271 if (errcode && err == NULL)
2272 err = got_error_set_errno(errcode,
2273 "pthread_mutex_unlock");
2275 a->log_complete = 1;
2276 return (void *)err;
2279 static const struct got_error *
2280 stop_log_thread(struct tog_log_view_state *s)
2282 const struct got_error *err = NULL;
2283 int errcode;
2285 if (s->thread) {
2286 s->quit = 1;
2287 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2288 if (errcode)
2289 return got_error_set_errno(errcode,
2290 "pthread_cond_signal");
2291 errcode = pthread_mutex_unlock(&tog_mutex);
2292 if (errcode)
2293 return got_error_set_errno(errcode,
2294 "pthread_mutex_unlock");
2295 errcode = pthread_join(s->thread, (void **)&err);
2296 if (errcode)
2297 return got_error_set_errno(errcode, "pthread_join");
2298 errcode = pthread_mutex_lock(&tog_mutex);
2299 if (errcode)
2300 return got_error_set_errno(errcode,
2301 "pthread_mutex_lock");
2302 s->thread = NULL;
2305 if (s->thread_args.repo) {
2306 err = got_repo_close(s->thread_args.repo);
2307 s->thread_args.repo = NULL;
2310 if (s->thread_args.pack_fds) {
2311 const struct got_error *pack_err =
2312 got_repo_pack_fds_close(s->thread_args.pack_fds);
2313 if (err == NULL)
2314 err = pack_err;
2315 s->thread_args.pack_fds = NULL;
2318 if (s->thread_args.graph) {
2319 got_commit_graph_close(s->thread_args.graph);
2320 s->thread_args.graph = NULL;
2323 return err;
2326 static const struct got_error *
2327 close_log_view(struct tog_view *view)
2329 const struct got_error *err = NULL;
2330 struct tog_log_view_state *s = &view->state.log;
2331 int errcode;
2333 err = stop_log_thread(s);
2335 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2336 if (errcode && err == NULL)
2337 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2339 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2340 if (errcode && err == NULL)
2341 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2343 free_commits(&s->commits);
2344 free(s->in_repo_path);
2345 s->in_repo_path = NULL;
2346 free(s->start_id);
2347 s->start_id = NULL;
2348 free(s->head_ref_name);
2349 s->head_ref_name = NULL;
2350 return err;
2353 static const struct got_error *
2354 search_start_log_view(struct tog_view *view)
2356 struct tog_log_view_state *s = &view->state.log;
2358 s->matched_entry = NULL;
2359 s->search_entry = NULL;
2360 return NULL;
2363 static const struct got_error *
2364 search_next_log_view(struct tog_view *view)
2366 const struct got_error *err = NULL;
2367 struct tog_log_view_state *s = &view->state.log;
2368 struct commit_queue_entry *entry;
2370 /* Display progress update in log view. */
2371 show_log_view(view);
2372 update_panels();
2373 doupdate();
2375 if (s->search_entry) {
2376 int errcode, ch;
2377 errcode = pthread_mutex_unlock(&tog_mutex);
2378 if (errcode)
2379 return got_error_set_errno(errcode,
2380 "pthread_mutex_unlock");
2381 ch = wgetch(view->window);
2382 errcode = pthread_mutex_lock(&tog_mutex);
2383 if (errcode)
2384 return got_error_set_errno(errcode,
2385 "pthread_mutex_lock");
2386 if (ch == KEY_BACKSPACE) {
2387 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2388 return NULL;
2390 if (view->searching == TOG_SEARCH_FORWARD)
2391 entry = TAILQ_NEXT(s->search_entry, entry);
2392 else
2393 entry = TAILQ_PREV(s->search_entry,
2394 commit_queue_head, entry);
2395 } else if (s->matched_entry) {
2396 int matched_idx = s->matched_entry->idx;
2397 int selected_idx = s->selected_entry->idx;
2400 * If the user has moved the cursor after we hit a match,
2401 * the position from where we should continue searching
2402 * might have changed.
2404 if (view->searching == TOG_SEARCH_FORWARD) {
2405 if (matched_idx > selected_idx)
2406 entry = TAILQ_NEXT(s->selected_entry, entry);
2407 else
2408 entry = TAILQ_NEXT(s->matched_entry, entry);
2409 } else {
2410 if (matched_idx < selected_idx)
2411 entry = TAILQ_PREV(s->selected_entry,
2412 commit_queue_head, entry);
2413 else
2414 entry = TAILQ_PREV(s->matched_entry,
2415 commit_queue_head, entry);
2417 } else {
2418 entry = s->selected_entry;
2421 while (1) {
2422 int have_match = 0;
2424 if (entry == NULL) {
2425 if (s->thread_args.log_complete ||
2426 view->searching == TOG_SEARCH_BACKWARD) {
2427 view->search_next_done =
2428 (s->matched_entry == NULL ?
2429 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2430 s->search_entry = NULL;
2431 return NULL;
2434 * Poke the log thread for more commits and return,
2435 * allowing the main loop to make progress. Search
2436 * will resume at s->search_entry once we come back.
2438 s->thread_args.commits_needed++;
2439 return trigger_log_thread(view, 0);
2442 err = match_commit(&have_match, entry->id, entry->commit,
2443 &view->regex);
2444 if (err)
2445 break;
2446 if (have_match) {
2447 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2448 s->matched_entry = entry;
2449 break;
2452 s->search_entry = entry;
2453 if (view->searching == TOG_SEARCH_FORWARD)
2454 entry = TAILQ_NEXT(entry, entry);
2455 else
2456 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2459 if (s->matched_entry) {
2460 int cur = s->selected_entry->idx;
2461 while (cur < s->matched_entry->idx) {
2462 err = input_log_view(NULL, view, KEY_DOWN);
2463 if (err)
2464 return err;
2465 cur++;
2467 while (cur > s->matched_entry->idx) {
2468 err = input_log_view(NULL, view, KEY_UP);
2469 if (err)
2470 return err;
2471 cur--;
2475 s->search_entry = NULL;
2477 return NULL;
2480 static const struct got_error *
2481 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2482 struct got_repository *repo, const char *head_ref_name,
2483 const char *in_repo_path, int log_branches)
2485 const struct got_error *err = NULL;
2486 struct tog_log_view_state *s = &view->state.log;
2487 struct got_repository *thread_repo = NULL;
2488 struct got_commit_graph *thread_graph = NULL;
2489 int errcode;
2491 if (in_repo_path != s->in_repo_path) {
2492 free(s->in_repo_path);
2493 s->in_repo_path = strdup(in_repo_path);
2494 if (s->in_repo_path == NULL)
2495 return got_error_from_errno("strdup");
2498 /* The commit queue only contains commits being displayed. */
2499 TAILQ_INIT(&s->commits.head);
2500 s->commits.ncommits = 0;
2502 s->repo = repo;
2503 if (head_ref_name) {
2504 s->head_ref_name = strdup(head_ref_name);
2505 if (s->head_ref_name == NULL) {
2506 err = got_error_from_errno("strdup");
2507 goto done;
2510 s->start_id = got_object_id_dup(start_id);
2511 if (s->start_id == NULL) {
2512 err = got_error_from_errno("got_object_id_dup");
2513 goto done;
2515 s->log_branches = log_branches;
2517 STAILQ_INIT(&s->colors);
2518 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2519 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2520 get_color_value("TOG_COLOR_COMMIT"));
2521 if (err)
2522 goto done;
2523 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2524 get_color_value("TOG_COLOR_AUTHOR"));
2525 if (err) {
2526 free_colors(&s->colors);
2527 goto done;
2529 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
2530 get_color_value("TOG_COLOR_DATE"));
2531 if (err) {
2532 free_colors(&s->colors);
2533 goto done;
2537 view->show = show_log_view;
2538 view->input = input_log_view;
2539 view->close = close_log_view;
2540 view->search_start = search_start_log_view;
2541 view->search_next = search_next_log_view;
2543 if (s->thread_args.pack_fds == NULL) {
2544 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2545 if (err)
2546 goto done;
2548 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
2549 s->thread_args.pack_fds);
2550 if (err)
2551 goto done;
2552 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
2553 !s->log_branches);
2554 if (err)
2555 goto done;
2556 err = got_commit_graph_iter_start(thread_graph, s->start_id,
2557 s->repo, NULL, NULL);
2558 if (err)
2559 goto done;
2561 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
2562 if (errcode) {
2563 err = got_error_set_errno(errcode, "pthread_cond_init");
2564 goto done;
2566 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
2567 if (errcode) {
2568 err = got_error_set_errno(errcode, "pthread_cond_init");
2569 goto done;
2572 s->thread_args.commits_needed = view->nlines;
2573 s->thread_args.graph = thread_graph;
2574 s->thread_args.commits = &s->commits;
2575 s->thread_args.in_repo_path = s->in_repo_path;
2576 s->thread_args.start_id = s->start_id;
2577 s->thread_args.repo = thread_repo;
2578 s->thread_args.log_complete = 0;
2579 s->thread_args.quit = &s->quit;
2580 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
2581 s->thread_args.selected_entry = &s->selected_entry;
2582 s->thread_args.searching = &view->searching;
2583 s->thread_args.search_next_done = &view->search_next_done;
2584 s->thread_args.regex = &view->regex;
2585 done:
2586 if (err)
2587 close_log_view(view);
2588 return err;
2591 static const struct got_error *
2592 show_log_view(struct tog_view *view)
2594 const struct got_error *err;
2595 struct tog_log_view_state *s = &view->state.log;
2597 if (s->thread == NULL) {
2598 int errcode = pthread_create(&s->thread, NULL, log_thread,
2599 &s->thread_args);
2600 if (errcode)
2601 return got_error_set_errno(errcode, "pthread_create");
2602 if (s->thread_args.commits_needed > 0) {
2603 err = trigger_log_thread(view, 1);
2604 if (err)
2605 return err;
2609 return draw_commits(view);
2612 static const struct got_error *
2613 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
2615 const struct got_error *err = NULL;
2616 struct tog_log_view_state *s = &view->state.log;
2617 struct tog_view *diff_view = NULL, *tree_view = NULL;
2618 struct tog_view *ref_view = NULL;
2619 struct commit_queue_entry *entry;
2620 int begin_x = 0, n, nscroll = view->nlines - 1;
2622 if (s->thread_args.load_all) {
2623 if (ch == KEY_BACKSPACE)
2624 s->thread_args.load_all = 0;
2625 else if (s->thread_args.log_complete) {
2626 s->thread_args.load_all = 0;
2627 log_scroll_down(view, s->commits.ncommits);
2628 s->selected = MIN(view->nlines - 2,
2629 s->commits.ncommits - 1);
2630 select_commit(s);
2632 return NULL;
2635 switch (ch) {
2636 case 'q':
2637 s->quit = 1;
2638 break;
2639 case '0':
2640 view->x = 0;
2641 break;
2642 case '$':
2643 view->x = MAX(view->maxx - view->ncols / 2, 0);
2644 view->count = 0;
2645 break;
2646 case KEY_RIGHT:
2647 case 'l':
2648 if (view->x + view->ncols / 2 < view->maxx)
2649 view->x += 2; /* move two columns right */
2650 else
2651 view->count = 0;
2652 break;
2653 case KEY_LEFT:
2654 case 'h':
2655 view->x -= MIN(view->x, 2); /* move two columns back */
2656 if (view->x <= 0)
2657 view->count = 0;
2658 break;
2659 case 'k':
2660 case KEY_UP:
2661 case '<':
2662 case ',':
2663 case CTRL('p'):
2664 if (s->selected_entry->idx == 0)
2665 view->count = 0;
2666 if (s->first_displayed_entry == NULL)
2667 break;
2668 if (s->selected > 0)
2669 s->selected--;
2670 else
2671 log_scroll_up(s, 1);
2672 select_commit(s);
2673 break;
2674 case 'g':
2675 case KEY_HOME:
2676 s->selected = 0;
2677 s->first_displayed_entry = TAILQ_FIRST(&s->commits.head);
2678 select_commit(s);
2679 view->count = 0;
2680 break;
2681 case CTRL('u'):
2682 case 'u':
2683 nscroll /= 2;
2684 /* FALL THROUGH */
2685 case KEY_PPAGE:
2686 case CTRL('b'):
2687 case 'b':
2688 if (s->first_displayed_entry == NULL)
2689 break;
2690 if (TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
2691 s->selected = MAX(0, s->selected - nscroll - 1);
2692 else
2693 log_scroll_up(s, nscroll);
2694 select_commit(s);
2695 if (s->selected_entry->idx == 0)
2696 view->count = 0;
2697 break;
2698 case 'j':
2699 case KEY_DOWN:
2700 case '>':
2701 case '.':
2702 case CTRL('n'):
2703 if (s->first_displayed_entry == NULL)
2704 break;
2705 if (s->selected < MIN(view->nlines - 2,
2706 s->commits.ncommits - 1))
2707 s->selected++;
2708 else {
2709 err = log_scroll_down(view, 1);
2710 if (err)
2711 break;
2713 select_commit(s);
2714 if (s->thread_args.log_complete &&
2715 s->selected_entry->idx == s->commits.ncommits - 1)
2716 view->count = 0;
2717 break;
2718 case 'G':
2719 case KEY_END: {
2720 /* We don't know yet how many commits, so we're forced to
2721 * traverse them all. */
2722 view->count = 0;
2723 if (!s->thread_args.log_complete) {
2724 s->thread_args.load_all = 1;
2725 return trigger_log_thread(view, 0);
2728 s->selected = 0;
2729 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
2730 for (n = 0; n < view->nlines - 1; n++) {
2731 if (entry == NULL)
2732 break;
2733 s->first_displayed_entry = entry;
2734 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2736 if (n > 0)
2737 s->selected = n - 1;
2738 select_commit(s);
2739 break;
2741 case CTRL('d'):
2742 case 'd':
2743 nscroll /= 2;
2744 /* FALL THROUGH */
2745 case KEY_NPAGE:
2746 case CTRL('f'):
2747 case 'f':
2748 case ' ': {
2749 struct commit_queue_entry *first;
2750 first = s->first_displayed_entry;
2751 if (first == NULL) {
2752 view->count = 0;
2753 break;
2755 err = log_scroll_down(view, nscroll);
2756 if (err)
2757 break;
2758 if (first == s->first_displayed_entry &&
2759 s->selected < MIN(view->nlines - 2,
2760 s->commits.ncommits - 1)) {
2761 /* can't scroll further down */
2762 s->selected += MIN(s->last_displayed_entry->idx -
2763 s->selected_entry->idx, nscroll + 1);
2765 select_commit(s);
2766 if (s->thread_args.log_complete &&
2767 s->selected_entry->idx == s->commits.ncommits - 1)
2768 view->count = 0;
2769 break;
2771 case KEY_RESIZE:
2772 if (s->selected > view->nlines - 2)
2773 s->selected = view->nlines - 2;
2774 if (s->selected > s->commits.ncommits - 1)
2775 s->selected = s->commits.ncommits - 1;
2776 select_commit(s);
2777 if (s->commits.ncommits < view->nlines - 1 &&
2778 !s->thread_args.log_complete) {
2779 s->thread_args.commits_needed += (view->nlines - 1) -
2780 s->commits.ncommits;
2781 err = trigger_log_thread(view, 1);
2783 break;
2784 case KEY_ENTER:
2785 case '\r':
2786 view->count = 0;
2787 if (s->selected_entry == NULL)
2788 break;
2789 if (view_is_parent_view(view))
2790 begin_x = view_split_begin_x(view->begin_x);
2791 err = open_diff_view_for_commit(&diff_view, begin_x,
2792 s->selected_entry->commit, s->selected_entry->id,
2793 view, s->repo);
2794 if (err)
2795 break;
2796 view->focussed = 0;
2797 diff_view->focussed = 1;
2798 if (view_is_parent_view(view)) {
2799 err = view_close_child(view);
2800 if (err)
2801 return err;
2802 err = view_set_child(view, diff_view);
2803 if (err)
2804 return err;
2805 view->focus_child = 1;
2806 } else
2807 *new_view = diff_view;
2808 break;
2809 case 't':
2810 view->count = 0;
2811 if (s->selected_entry == NULL)
2812 break;
2813 if (view_is_parent_view(view))
2814 begin_x = view_split_begin_x(view->begin_x);
2815 err = browse_commit_tree(&tree_view, begin_x,
2816 s->selected_entry, s->in_repo_path, s->head_ref_name,
2817 s->repo);
2818 if (err)
2819 break;
2820 view->focussed = 0;
2821 tree_view->focussed = 1;
2822 if (view_is_parent_view(view)) {
2823 err = view_close_child(view);
2824 if (err)
2825 return err;
2826 err = view_set_child(view, tree_view);
2827 if (err)
2828 return err;
2829 view->focus_child = 1;
2830 } else
2831 *new_view = tree_view;
2832 break;
2833 case KEY_BACKSPACE:
2834 case CTRL('l'):
2835 case 'B':
2836 view->count = 0;
2837 if (ch == KEY_BACKSPACE &&
2838 got_path_is_root_dir(s->in_repo_path))
2839 break;
2840 err = stop_log_thread(s);
2841 if (err)
2842 return err;
2843 if (ch == KEY_BACKSPACE) {
2844 char *parent_path;
2845 err = got_path_dirname(&parent_path, s->in_repo_path);
2846 if (err)
2847 return err;
2848 free(s->in_repo_path);
2849 s->in_repo_path = parent_path;
2850 s->thread_args.in_repo_path = s->in_repo_path;
2851 } else if (ch == CTRL('l')) {
2852 struct got_object_id *start_id;
2853 err = got_repo_match_object_id(&start_id, NULL,
2854 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
2855 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
2856 if (err)
2857 return err;
2858 free(s->start_id);
2859 s->start_id = start_id;
2860 s->thread_args.start_id = s->start_id;
2861 } else /* 'B' */
2862 s->log_branches = !s->log_branches;
2864 if (s->thread_args.pack_fds == NULL) {
2865 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2866 if (err)
2867 return err;
2869 err = got_repo_open(&s->thread_args.repo,
2870 got_repo_get_path(s->repo), NULL,
2871 s->thread_args.pack_fds);
2872 if (err)
2873 return err;
2874 tog_free_refs();
2875 err = tog_load_refs(s->repo, 0);
2876 if (err)
2877 return err;
2878 err = got_commit_graph_open(&s->thread_args.graph,
2879 s->in_repo_path, !s->log_branches);
2880 if (err)
2881 return err;
2882 err = got_commit_graph_iter_start(s->thread_args.graph,
2883 s->start_id, s->repo, NULL, NULL);
2884 if (err)
2885 return err;
2886 free_commits(&s->commits);
2887 s->first_displayed_entry = NULL;
2888 s->last_displayed_entry = NULL;
2889 s->selected_entry = NULL;
2890 s->selected = 0;
2891 s->thread_args.log_complete = 0;
2892 s->quit = 0;
2893 s->thread_args.commits_needed = view->nlines;
2894 s->matched_entry = NULL;
2895 s->search_entry = NULL;
2896 break;
2897 case 'r':
2898 view->count = 0;
2899 if (view_is_parent_view(view))
2900 begin_x = view_split_begin_x(view->begin_x);
2901 ref_view = view_open(view->nlines, view->ncols,
2902 view->begin_y, begin_x, TOG_VIEW_REF);
2903 if (ref_view == NULL)
2904 return got_error_from_errno("view_open");
2905 err = open_ref_view(ref_view, s->repo);
2906 if (err) {
2907 view_close(ref_view);
2908 return err;
2910 view->focussed = 0;
2911 ref_view->focussed = 1;
2912 if (view_is_parent_view(view)) {
2913 err = view_close_child(view);
2914 if (err)
2915 return err;
2916 err = view_set_child(view, ref_view);
2917 if (err)
2918 return err;
2919 view->focus_child = 1;
2920 } else
2921 *new_view = ref_view;
2922 break;
2923 default:
2924 view->count = 0;
2925 break;
2928 return err;
2931 static const struct got_error *
2932 apply_unveil(const char *repo_path, const char *worktree_path)
2934 const struct got_error *error;
2936 #ifdef PROFILE
2937 if (unveil("gmon.out", "rwc") != 0)
2938 return got_error_from_errno2("unveil", "gmon.out");
2939 #endif
2940 if (repo_path && unveil(repo_path, "r") != 0)
2941 return got_error_from_errno2("unveil", repo_path);
2943 if (worktree_path && unveil(worktree_path, "rwc") != 0)
2944 return got_error_from_errno2("unveil", worktree_path);
2946 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
2947 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
2949 error = got_privsep_unveil_exec_helpers();
2950 if (error != NULL)
2951 return error;
2953 if (unveil(NULL, NULL) != 0)
2954 return got_error_from_errno("unveil");
2956 return NULL;
2959 static void
2960 init_curses(void)
2963 * Override default signal handlers before starting ncurses.
2964 * This should prevent ncurses from installing its own
2965 * broken cleanup() signal handler.
2967 signal(SIGWINCH, tog_sigwinch);
2968 signal(SIGPIPE, tog_sigpipe);
2969 signal(SIGCONT, tog_sigcont);
2970 signal(SIGINT, tog_sigint);
2971 signal(SIGTERM, tog_sigterm);
2973 initscr();
2974 cbreak();
2975 halfdelay(1); /* Do fast refresh while initial view is loading. */
2976 noecho();
2977 nonl();
2978 intrflush(stdscr, FALSE);
2979 keypad(stdscr, TRUE);
2980 curs_set(0);
2981 if (getenv("TOG_COLORS") != NULL) {
2982 start_color();
2983 use_default_colors();
2987 static const struct got_error *
2988 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
2989 struct got_repository *repo, struct got_worktree *worktree)
2991 const struct got_error *err = NULL;
2993 if (argc == 0) {
2994 *in_repo_path = strdup("/");
2995 if (*in_repo_path == NULL)
2996 return got_error_from_errno("strdup");
2997 return NULL;
3000 if (worktree) {
3001 const char *prefix = got_worktree_get_path_prefix(worktree);
3002 char *p;
3004 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3005 if (err)
3006 return err;
3007 if (asprintf(in_repo_path, "%s%s%s", prefix,
3008 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3009 p) == -1) {
3010 err = got_error_from_errno("asprintf");
3011 *in_repo_path = NULL;
3013 free(p);
3014 } else
3015 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3017 return err;
3020 static const struct got_error *
3021 cmd_log(int argc, char *argv[])
3023 const struct got_error *error;
3024 struct got_repository *repo = NULL;
3025 struct got_worktree *worktree = NULL;
3026 struct got_object_id *start_id = NULL;
3027 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3028 char *start_commit = NULL, *label = NULL;
3029 struct got_reference *ref = NULL;
3030 const char *head_ref_name = NULL;
3031 int ch, log_branches = 0;
3032 struct tog_view *view;
3033 int *pack_fds = NULL;
3035 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3036 switch (ch) {
3037 case 'b':
3038 log_branches = 1;
3039 break;
3040 case 'c':
3041 start_commit = optarg;
3042 break;
3043 case 'r':
3044 repo_path = realpath(optarg, NULL);
3045 if (repo_path == NULL)
3046 return got_error_from_errno2("realpath",
3047 optarg);
3048 break;
3049 default:
3050 usage_log();
3051 /* NOTREACHED */
3055 argc -= optind;
3056 argv += optind;
3058 if (argc > 1)
3059 usage_log();
3061 error = got_repo_pack_fds_open(&pack_fds);
3062 if (error != NULL)
3063 goto done;
3065 if (repo_path == NULL) {
3066 cwd = getcwd(NULL, 0);
3067 if (cwd == NULL)
3068 return got_error_from_errno("getcwd");
3069 error = got_worktree_open(&worktree, cwd);
3070 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3071 goto done;
3072 if (worktree)
3073 repo_path =
3074 strdup(got_worktree_get_repo_path(worktree));
3075 else
3076 repo_path = strdup(cwd);
3077 if (repo_path == NULL) {
3078 error = got_error_from_errno("strdup");
3079 goto done;
3083 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3084 if (error != NULL)
3085 goto done;
3087 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3088 repo, worktree);
3089 if (error)
3090 goto done;
3092 init_curses();
3094 error = apply_unveil(got_repo_get_path(repo),
3095 worktree ? got_worktree_get_root_path(worktree) : NULL);
3096 if (error)
3097 goto done;
3099 /* already loaded by tog_log_with_path()? */
3100 if (TAILQ_EMPTY(&tog_refs)) {
3101 error = tog_load_refs(repo, 0);
3102 if (error)
3103 goto done;
3106 if (start_commit == NULL) {
3107 error = got_repo_match_object_id(&start_id, &label,
3108 worktree ? got_worktree_get_head_ref_name(worktree) :
3109 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3110 if (error)
3111 goto done;
3112 head_ref_name = label;
3113 } else {
3114 error = got_ref_open(&ref, repo, start_commit, 0);
3115 if (error == NULL)
3116 head_ref_name = got_ref_get_name(ref);
3117 else if (error->code != GOT_ERR_NOT_REF)
3118 goto done;
3119 error = got_repo_match_object_id(&start_id, NULL,
3120 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3121 if (error)
3122 goto done;
3125 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3126 if (view == NULL) {
3127 error = got_error_from_errno("view_open");
3128 goto done;
3130 error = open_log_view(view, start_id, repo, head_ref_name,
3131 in_repo_path, log_branches);
3132 if (error)
3133 goto done;
3134 if (worktree) {
3135 /* Release work tree lock. */
3136 got_worktree_close(worktree);
3137 worktree = NULL;
3139 error = view_loop(view);
3140 done:
3141 free(in_repo_path);
3142 free(repo_path);
3143 free(cwd);
3144 free(start_id);
3145 free(label);
3146 if (ref)
3147 got_ref_close(ref);
3148 if (repo) {
3149 const struct got_error *close_err = got_repo_close(repo);
3150 if (error == NULL)
3151 error = close_err;
3153 if (worktree)
3154 got_worktree_close(worktree);
3155 if (pack_fds) {
3156 const struct got_error *pack_err =
3157 got_repo_pack_fds_close(pack_fds);
3158 if (error == NULL)
3159 error = pack_err;
3161 tog_free_refs();
3162 return error;
3165 __dead static void
3166 usage_diff(void)
3168 endwin();
3169 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3170 "[-w] object1 object2\n", getprogname());
3171 exit(1);
3174 static int
3175 match_line(const char *line, regex_t *regex, size_t nmatch,
3176 regmatch_t *regmatch)
3178 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3181 static struct tog_color *
3182 match_color(struct tog_colors *colors, const char *line)
3184 struct tog_color *tc = NULL;
3186 STAILQ_FOREACH(tc, colors, entry) {
3187 if (match_line(line, &tc->regex, 0, NULL))
3188 return tc;
3191 return NULL;
3194 static const struct got_error *
3195 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3196 WINDOW *window, int skipcol, regmatch_t *regmatch)
3198 const struct got_error *err = NULL;
3199 char *exstr = NULL;
3200 wchar_t *wline = NULL;
3201 int rme, rms, n, width, scrollx;
3202 int width0 = 0, width1 = 0, width2 = 0;
3203 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3205 *wtotal = 0;
3207 rms = regmatch->rm_so;
3208 rme = regmatch->rm_eo;
3210 err = expand_tab(&exstr, line);
3211 if (err)
3212 return err;
3214 /* Split the line into 3 segments, according to match offsets. */
3215 seg0 = strndup(exstr, rms);
3216 if (seg0 == NULL) {
3217 err = got_error_from_errno("strndup");
3218 goto done;
3220 seg1 = strndup(exstr + rms, rme - rms);
3221 if (seg1 == NULL) {
3222 err = got_error_from_errno("strndup");
3223 goto done;
3225 seg2 = strdup(exstr + rme);
3226 if (seg2 == NULL) {
3227 err = got_error_from_errno("strndup");
3228 goto done;
3231 /* draw up to matched token if we haven't scrolled past it */
3232 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3233 col_tab_align, 1);
3234 if (err)
3235 goto done;
3236 n = MAX(width0 - skipcol, 0);
3237 if (n) {
3238 free(wline);
3239 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3240 wlimit, col_tab_align, 1);
3241 if (err)
3242 goto done;
3243 waddwstr(window, &wline[scrollx]);
3244 wlimit -= width;
3245 *wtotal += width;
3248 if (wlimit > 0) {
3249 int i = 0, w = 0;
3250 size_t wlen;
3252 free(wline);
3253 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3254 col_tab_align, 1);
3255 if (err)
3256 goto done;
3257 wlen = wcslen(wline);
3258 while (i < wlen) {
3259 width = wcwidth(wline[i]);
3260 if (width == -1) {
3261 /* should not happen, tabs are expanded */
3262 err = got_error(GOT_ERR_RANGE);
3263 goto done;
3265 if (width0 + w + width > skipcol)
3266 break;
3267 w += width;
3268 i++;
3270 /* draw (visible part of) matched token (if scrolled into it) */
3271 if (width1 - w > 0) {
3272 wattron(window, A_STANDOUT);
3273 waddwstr(window, &wline[i]);
3274 wattroff(window, A_STANDOUT);
3275 wlimit -= (width1 - w);
3276 *wtotal += (width1 - w);
3280 if (wlimit > 0) { /* draw rest of line */
3281 free(wline);
3282 if (skipcol > width0 + width1) {
3283 err = format_line(&wline, &width2, &scrollx, seg2,
3284 skipcol - (width0 + width1), wlimit,
3285 col_tab_align, 1);
3286 if (err)
3287 goto done;
3288 waddwstr(window, &wline[scrollx]);
3289 } else {
3290 err = format_line(&wline, &width2, NULL, seg2, 0,
3291 wlimit, col_tab_align, 1);
3292 if (err)
3293 goto done;
3294 waddwstr(window, wline);
3296 *wtotal += width2;
3298 done:
3299 free(wline);
3300 free(exstr);
3301 free(seg0);
3302 free(seg1);
3303 free(seg2);
3304 return err;
3307 static const struct got_error *
3308 draw_file(struct tog_view *view, const char *header)
3310 struct tog_diff_view_state *s = &view->state.diff;
3311 regmatch_t *regmatch = &view->regmatch;
3312 const struct got_error *err;
3313 int nprinted = 0;
3314 char *line;
3315 size_t linesize = 0;
3316 ssize_t linelen;
3317 struct tog_color *tc;
3318 wchar_t *wline;
3319 int width;
3320 int max_lines = view->nlines;
3321 int nlines = s->nlines;
3322 off_t line_offset;
3324 line_offset = s->line_offsets[s->first_displayed_line - 1];
3325 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3326 return got_error_from_errno("fseek");
3328 werase(view->window);
3330 if (header) {
3331 if (asprintf(&line, "[%d/%d] %s",
3332 s->first_displayed_line - 1 + s->selected_line, nlines,
3333 header) == -1)
3334 return got_error_from_errno("asprintf");
3335 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3336 0, 0);
3337 free(line);
3338 if (err)
3339 return err;
3341 if (view_needs_focus_indication(view))
3342 wstandout(view->window);
3343 waddwstr(view->window, wline);
3344 free(wline);
3345 wline = NULL;
3346 if (view_needs_focus_indication(view))
3347 wstandend(view->window);
3348 if (width <= view->ncols - 1)
3349 waddch(view->window, '\n');
3351 if (max_lines <= 1)
3352 return NULL;
3353 max_lines--;
3356 s->eof = 0;
3357 view->maxx = 0;
3358 line = NULL;
3359 while (max_lines > 0 && nprinted < max_lines) {
3360 linelen = getline(&line, &linesize, s->f);
3361 if (linelen == -1) {
3362 if (feof(s->f)) {
3363 s->eof = 1;
3364 break;
3366 free(line);
3367 return got_ferror(s->f, GOT_ERR_IO);
3370 /* Set view->maxx based on full line length. */
3371 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3372 view->x ? 1 : 0);
3373 if (err) {
3374 free(line);
3375 return err;
3377 view->maxx = MAX(view->maxx, width);
3378 free(wline);
3379 wline = NULL;
3381 tc = match_color(&s->colors, line);
3382 if (tc)
3383 wattr_on(view->window,
3384 COLOR_PAIR(tc->colorpair), NULL);
3385 if (s->first_displayed_line + nprinted == s->matched_line &&
3386 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3387 err = add_matched_line(&width, line, view->ncols, 0,
3388 view->window, view->x, regmatch);
3389 if (err) {
3390 free(line);
3391 return err;
3393 } else {
3394 int skip;
3395 err = format_line(&wline, &width, &skip, line,
3396 view->x, view->ncols, 0, view->x ? 1 : 0);
3397 if (err) {
3398 free(line);
3399 return err;
3401 waddwstr(view->window, &wline[skip]);
3402 free(wline);
3403 wline = NULL;
3405 if (tc)
3406 wattr_off(view->window,
3407 COLOR_PAIR(tc->colorpair), NULL);
3408 if (width <= view->ncols - 1)
3409 waddch(view->window, '\n');
3410 nprinted++;
3412 free(line);
3413 if (nprinted >= 1)
3414 s->last_displayed_line = s->first_displayed_line +
3415 (nprinted - 1);
3416 else
3417 s->last_displayed_line = s->first_displayed_line;
3419 view_vborder(view);
3421 if (s->eof) {
3422 while (nprinted < view->nlines) {
3423 waddch(view->window, '\n');
3424 nprinted++;
3427 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3428 view->ncols, 0, 0);
3429 if (err) {
3430 return err;
3433 wstandout(view->window);
3434 waddwstr(view->window, wline);
3435 free(wline);
3436 wline = NULL;
3437 wstandend(view->window);
3440 return NULL;
3443 static char *
3444 get_datestr(time_t *time, char *datebuf)
3446 struct tm mytm, *tm;
3447 char *p, *s;
3449 tm = gmtime_r(time, &mytm);
3450 if (tm == NULL)
3451 return NULL;
3452 s = asctime_r(tm, datebuf);
3453 if (s == NULL)
3454 return NULL;
3455 p = strchr(s, '\n');
3456 if (p)
3457 *p = '\0';
3458 return s;
3461 static const struct got_error *
3462 get_changed_paths(struct got_pathlist_head *paths,
3463 struct got_commit_object *commit, struct got_repository *repo)
3465 const struct got_error *err = NULL;
3466 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3467 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3468 struct got_object_qid *qid;
3470 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3471 if (qid != NULL) {
3472 struct got_commit_object *pcommit;
3473 err = got_object_open_as_commit(&pcommit, repo,
3474 &qid->id);
3475 if (err)
3476 return err;
3478 tree_id1 = got_object_id_dup(
3479 got_object_commit_get_tree_id(pcommit));
3480 if (tree_id1 == NULL) {
3481 got_object_commit_close(pcommit);
3482 return got_error_from_errno("got_object_id_dup");
3484 got_object_commit_close(pcommit);
3488 if (tree_id1) {
3489 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3490 if (err)
3491 goto done;
3494 tree_id2 = got_object_commit_get_tree_id(commit);
3495 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3496 if (err)
3497 goto done;
3499 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
3500 got_diff_tree_collect_changed_paths, paths, 0);
3501 done:
3502 if (tree1)
3503 got_object_tree_close(tree1);
3504 if (tree2)
3505 got_object_tree_close(tree2);
3506 free(tree_id1);
3507 return err;
3510 static const struct got_error *
3511 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
3513 off_t *p;
3515 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
3516 if (p == NULL)
3517 return got_error_from_errno("reallocarray");
3518 *line_offsets = p;
3519 (*line_offsets)[*nlines] = off;
3520 (*nlines)++;
3521 return NULL;
3524 static const struct got_error *
3525 write_commit_info(off_t **line_offsets, size_t *nlines,
3526 struct got_object_id *commit_id, struct got_reflist_head *refs,
3527 struct got_repository *repo, FILE *outfile)
3529 const struct got_error *err = NULL;
3530 char datebuf[26], *datestr;
3531 struct got_commit_object *commit;
3532 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
3533 time_t committer_time;
3534 const char *author, *committer;
3535 char *refs_str = NULL;
3536 struct got_pathlist_head changed_paths;
3537 struct got_pathlist_entry *pe;
3538 off_t outoff = 0;
3539 int n;
3541 TAILQ_INIT(&changed_paths);
3543 if (refs) {
3544 err = build_refs_str(&refs_str, refs, commit_id, repo);
3545 if (err)
3546 return err;
3549 err = got_object_open_as_commit(&commit, repo, commit_id);
3550 if (err)
3551 return err;
3553 err = got_object_id_str(&id_str, commit_id);
3554 if (err) {
3555 err = got_error_from_errno("got_object_id_str");
3556 goto done;
3559 err = add_line_offset(line_offsets, nlines, 0);
3560 if (err)
3561 goto done;
3563 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3564 refs_str ? refs_str : "", refs_str ? ")" : "");
3565 if (n < 0) {
3566 err = got_error_from_errno("fprintf");
3567 goto done;
3569 outoff += n;
3570 err = add_line_offset(line_offsets, nlines, outoff);
3571 if (err)
3572 goto done;
3574 n = fprintf(outfile, "from: %s\n",
3575 got_object_commit_get_author(commit));
3576 if (n < 0) {
3577 err = got_error_from_errno("fprintf");
3578 goto done;
3580 outoff += n;
3581 err = add_line_offset(line_offsets, nlines, outoff);
3582 if (err)
3583 goto done;
3585 committer_time = got_object_commit_get_committer_time(commit);
3586 datestr = get_datestr(&committer_time, datebuf);
3587 if (datestr) {
3588 n = fprintf(outfile, "date: %s UTC\n", datestr);
3589 if (n < 0) {
3590 err = got_error_from_errno("fprintf");
3591 goto done;
3593 outoff += n;
3594 err = add_line_offset(line_offsets, nlines, outoff);
3595 if (err)
3596 goto done;
3598 author = got_object_commit_get_author(commit);
3599 committer = got_object_commit_get_committer(commit);
3600 if (strcmp(author, committer) != 0) {
3601 n = fprintf(outfile, "via: %s\n", committer);
3602 if (n < 0) {
3603 err = got_error_from_errno("fprintf");
3604 goto done;
3606 outoff += n;
3607 err = add_line_offset(line_offsets, nlines, outoff);
3608 if (err)
3609 goto done;
3611 if (got_object_commit_get_nparents(commit) > 1) {
3612 const struct got_object_id_queue *parent_ids;
3613 struct got_object_qid *qid;
3614 int pn = 1;
3615 parent_ids = got_object_commit_get_parent_ids(commit);
3616 STAILQ_FOREACH(qid, parent_ids, entry) {
3617 err = got_object_id_str(&id_str, &qid->id);
3618 if (err)
3619 goto done;
3620 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
3621 if (n < 0) {
3622 err = got_error_from_errno("fprintf");
3623 goto done;
3625 outoff += n;
3626 err = add_line_offset(line_offsets, nlines, outoff);
3627 if (err)
3628 goto done;
3629 free(id_str);
3630 id_str = NULL;
3634 err = got_object_commit_get_logmsg(&logmsg, commit);
3635 if (err)
3636 goto done;
3637 s = logmsg;
3638 while ((line = strsep(&s, "\n")) != NULL) {
3639 n = fprintf(outfile, "%s\n", line);
3640 if (n < 0) {
3641 err = got_error_from_errno("fprintf");
3642 goto done;
3644 outoff += n;
3645 err = add_line_offset(line_offsets, nlines, outoff);
3646 if (err)
3647 goto done;
3650 err = get_changed_paths(&changed_paths, commit, repo);
3651 if (err)
3652 goto done;
3653 TAILQ_FOREACH(pe, &changed_paths, entry) {
3654 struct got_diff_changed_path *cp = pe->data;
3655 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
3656 if (n < 0) {
3657 err = got_error_from_errno("fprintf");
3658 goto done;
3660 outoff += n;
3661 err = add_line_offset(line_offsets, nlines, outoff);
3662 if (err)
3663 goto done;
3664 free((char *)pe->path);
3665 free(pe->data);
3668 fputc('\n', outfile);
3669 outoff++;
3670 err = add_line_offset(line_offsets, nlines, outoff);
3671 done:
3672 got_pathlist_free(&changed_paths);
3673 free(id_str);
3674 free(logmsg);
3675 free(refs_str);
3676 got_object_commit_close(commit);
3677 if (err) {
3678 free(*line_offsets);
3679 *line_offsets = NULL;
3680 *nlines = 0;
3682 return err;
3685 static const struct got_error *
3686 create_diff(struct tog_diff_view_state *s)
3688 const struct got_error *err = NULL;
3689 FILE *f = NULL;
3690 int obj_type;
3692 free(s->line_offsets);
3693 s->line_offsets = malloc(sizeof(off_t));
3694 if (s->line_offsets == NULL)
3695 return got_error_from_errno("malloc");
3696 s->nlines = 0;
3698 f = got_opentemp();
3699 if (f == NULL) {
3700 err = got_error_from_errno("got_opentemp");
3701 goto done;
3703 if (s->f && fclose(s->f) == EOF) {
3704 err = got_error_from_errno("fclose");
3705 goto done;
3707 s->f = f;
3709 if (s->id1)
3710 err = got_object_get_type(&obj_type, s->repo, s->id1);
3711 else
3712 err = got_object_get_type(&obj_type, s->repo, s->id2);
3713 if (err)
3714 goto done;
3716 switch (obj_type) {
3717 case GOT_OBJ_TYPE_BLOB:
3718 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
3719 s->f1, s->f2, s->id1, s->id2, s->label1, s->label2,
3720 s->diff_context, s->ignore_whitespace, s->force_text_diff,
3721 s->repo, s->f);
3722 break;
3723 case GOT_OBJ_TYPE_TREE:
3724 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
3725 s->f1, s->f2, s->id1, s->id2, NULL, "", "", s->diff_context,
3726 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
3727 break;
3728 case GOT_OBJ_TYPE_COMMIT: {
3729 const struct got_object_id_queue *parent_ids;
3730 struct got_object_qid *pid;
3731 struct got_commit_object *commit2;
3732 struct got_reflist_head *refs;
3734 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
3735 if (err)
3736 goto done;
3737 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
3738 /* Show commit info if we're diffing to a parent/root commit. */
3739 if (s->id1 == NULL) {
3740 err = write_commit_info(&s->line_offsets, &s->nlines,
3741 s->id2, refs, s->repo, s->f);
3742 if (err)
3743 goto done;
3744 } else {
3745 parent_ids = got_object_commit_get_parent_ids(commit2);
3746 STAILQ_FOREACH(pid, parent_ids, entry) {
3747 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
3748 err = write_commit_info(
3749 &s->line_offsets, &s->nlines,
3750 s->id2, refs, s->repo, s->f);
3751 if (err)
3752 goto done;
3753 break;
3757 got_object_commit_close(commit2);
3759 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
3760 s->f1, s->f2, s->id1, s->id2, NULL, s->diff_context,
3761 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
3762 break;
3764 default:
3765 err = got_error(GOT_ERR_OBJ_TYPE);
3766 break;
3768 if (err)
3769 goto done;
3770 done:
3771 if (s->f && fflush(s->f) != 0 && err == NULL)
3772 err = got_error_from_errno("fflush");
3773 return err;
3776 static void
3777 diff_view_indicate_progress(struct tog_view *view)
3779 mvwaddstr(view->window, 0, 0, "diffing...");
3780 update_panels();
3781 doupdate();
3784 static const struct got_error *
3785 search_start_diff_view(struct tog_view *view)
3787 struct tog_diff_view_state *s = &view->state.diff;
3789 s->matched_line = 0;
3790 return NULL;
3793 static const struct got_error *
3794 search_next_diff_view(struct tog_view *view)
3796 struct tog_diff_view_state *s = &view->state.diff;
3797 const struct got_error *err = NULL;
3798 int lineno;
3799 char *line = NULL;
3800 size_t linesize = 0;
3801 ssize_t linelen;
3803 if (!view->searching) {
3804 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3805 return NULL;
3808 if (s->matched_line) {
3809 if (view->searching == TOG_SEARCH_FORWARD)
3810 lineno = s->matched_line + 1;
3811 else
3812 lineno = s->matched_line - 1;
3813 } else
3814 lineno = s->first_displayed_line;
3816 while (1) {
3817 off_t offset;
3819 if (lineno <= 0 || lineno > s->nlines) {
3820 if (s->matched_line == 0) {
3821 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3822 break;
3825 if (view->searching == TOG_SEARCH_FORWARD)
3826 lineno = 1;
3827 else
3828 lineno = s->nlines;
3831 offset = s->line_offsets[lineno - 1];
3832 if (fseeko(s->f, offset, SEEK_SET) != 0) {
3833 free(line);
3834 return got_error_from_errno("fseeko");
3836 linelen = getline(&line, &linesize, s->f);
3837 if (linelen != -1) {
3838 char *exstr;
3839 err = expand_tab(&exstr, line);
3840 if (err)
3841 break;
3842 if (match_line(exstr, &view->regex, 1,
3843 &view->regmatch)) {
3844 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3845 s->matched_line = lineno;
3846 free(exstr);
3847 break;
3849 free(exstr);
3851 if (view->searching == TOG_SEARCH_FORWARD)
3852 lineno++;
3853 else
3854 lineno--;
3856 free(line);
3858 if (s->matched_line) {
3859 s->first_displayed_line = s->matched_line;
3860 s->selected_line = 1;
3863 return err;
3866 static const struct got_error *
3867 close_diff_view(struct tog_view *view)
3869 const struct got_error *err = NULL;
3870 struct tog_diff_view_state *s = &view->state.diff;
3872 free(s->id1);
3873 s->id1 = NULL;
3874 free(s->id2);
3875 s->id2 = NULL;
3876 if (s->f && fclose(s->f) == EOF)
3877 err = got_error_from_errno("fclose");
3878 s->f = NULL;
3879 if (s->f1 && fclose(s->f1) == EOF)
3880 err = got_error_from_errno("fclose");
3881 s->f1 = NULL;
3882 if (s->f2 && fclose(s->f2) == EOF)
3883 err = got_error_from_errno("fclose");
3884 s->f2 = NULL;
3885 free_colors(&s->colors);
3886 free(s->line_offsets);
3887 s->line_offsets = NULL;
3888 s->nlines = 0;
3889 return err;
3892 static const struct got_error *
3893 open_diff_view(struct tog_view *view, struct got_object_id *id1,
3894 struct got_object_id *id2, const char *label1, const char *label2,
3895 int diff_context, int ignore_whitespace, int force_text_diff,
3896 struct tog_view *log_view, struct got_repository *repo)
3898 const struct got_error *err;
3899 struct tog_diff_view_state *s = &view->state.diff;
3901 memset(s, 0, sizeof(*s));
3903 if (id1 != NULL && id2 != NULL) {
3904 int type1, type2;
3905 err = got_object_get_type(&type1, repo, id1);
3906 if (err)
3907 return err;
3908 err = got_object_get_type(&type2, repo, id2);
3909 if (err)
3910 return err;
3912 if (type1 != type2)
3913 return got_error(GOT_ERR_OBJ_TYPE);
3915 s->first_displayed_line = 1;
3916 s->last_displayed_line = view->nlines;
3917 s->selected_line = 1;
3918 s->repo = repo;
3919 s->id1 = id1;
3920 s->id2 = id2;
3921 s->label1 = label1;
3922 s->label2 = label2;
3924 if (id1) {
3925 s->id1 = got_object_id_dup(id1);
3926 if (s->id1 == NULL)
3927 return got_error_from_errno("got_object_id_dup");
3928 } else
3929 s->id1 = NULL;
3931 s->id2 = got_object_id_dup(id2);
3932 if (s->id2 == NULL) {
3933 err = got_error_from_errno("got_object_id_dup");
3934 goto done;
3937 s->f1 = got_opentemp();
3938 if (s->f1 == NULL) {
3939 err = got_error_from_errno("got_opentemp");
3940 goto done;
3943 s->f2 = got_opentemp();
3944 if (s->f2 == NULL) {
3945 err = got_error_from_errno("got_opentemp");
3946 goto done;
3949 s->first_displayed_line = 1;
3950 s->last_displayed_line = view->nlines;
3951 s->diff_context = diff_context;
3952 s->ignore_whitespace = ignore_whitespace;
3953 s->force_text_diff = force_text_diff;
3954 s->log_view = log_view;
3955 s->repo = repo;
3957 STAILQ_INIT(&s->colors);
3958 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3959 err = add_color(&s->colors,
3960 "^-", TOG_COLOR_DIFF_MINUS,
3961 get_color_value("TOG_COLOR_DIFF_MINUS"));
3962 if (err)
3963 goto done;
3964 err = add_color(&s->colors, "^\\+",
3965 TOG_COLOR_DIFF_PLUS,
3966 get_color_value("TOG_COLOR_DIFF_PLUS"));
3967 if (err)
3968 goto done;
3969 err = add_color(&s->colors,
3970 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
3971 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
3972 if (err)
3973 goto done;
3975 err = add_color(&s->colors,
3976 "^(commit [0-9a-f]|parent [0-9]|"
3977 "(blob|file|tree|commit) [-+] |"
3978 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
3979 get_color_value("TOG_COLOR_DIFF_META"));
3980 if (err)
3981 goto done;
3983 err = add_color(&s->colors,
3984 "^(from|via): ", TOG_COLOR_AUTHOR,
3985 get_color_value("TOG_COLOR_AUTHOR"));
3986 if (err)
3987 goto done;
3989 err = add_color(&s->colors,
3990 "^date: ", TOG_COLOR_DATE,
3991 get_color_value("TOG_COLOR_DATE"));
3992 if (err)
3993 goto done;
3996 if (log_view && view_is_splitscreen(view))
3997 show_log_view(log_view); /* draw vborder */
3998 diff_view_indicate_progress(view);
4000 err = create_diff(s);
4002 view->show = show_diff_view;
4003 view->input = input_diff_view;
4004 view->close = close_diff_view;
4005 view->search_start = search_start_diff_view;
4006 view->search_next = search_next_diff_view;
4007 done:
4008 if (err)
4009 close_diff_view(view);
4010 return err;
4013 static const struct got_error *
4014 show_diff_view(struct tog_view *view)
4016 const struct got_error *err;
4017 struct tog_diff_view_state *s = &view->state.diff;
4018 char *id_str1 = NULL, *id_str2, *header;
4019 const char *label1, *label2;
4021 if (s->id1) {
4022 err = got_object_id_str(&id_str1, s->id1);
4023 if (err)
4024 return err;
4025 label1 = s->label1 ? : id_str1;
4026 } else
4027 label1 = "/dev/null";
4029 err = got_object_id_str(&id_str2, s->id2);
4030 if (err)
4031 return err;
4032 label2 = s->label2 ? : id_str2;
4034 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4035 err = got_error_from_errno("asprintf");
4036 free(id_str1);
4037 free(id_str2);
4038 return err;
4040 free(id_str1);
4041 free(id_str2);
4043 err = draw_file(view, header);
4044 free(header);
4045 return err;
4048 static const struct got_error *
4049 set_selected_commit(struct tog_diff_view_state *s,
4050 struct commit_queue_entry *entry)
4052 const struct got_error *err;
4053 const struct got_object_id_queue *parent_ids;
4054 struct got_commit_object *selected_commit;
4055 struct got_object_qid *pid;
4057 free(s->id2);
4058 s->id2 = got_object_id_dup(entry->id);
4059 if (s->id2 == NULL)
4060 return got_error_from_errno("got_object_id_dup");
4062 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4063 if (err)
4064 return err;
4065 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4066 free(s->id1);
4067 pid = STAILQ_FIRST(parent_ids);
4068 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4069 got_object_commit_close(selected_commit);
4070 return NULL;
4073 static const struct got_error *
4074 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4076 const struct got_error *err = NULL;
4077 struct tog_diff_view_state *s = &view->state.diff;
4078 struct tog_log_view_state *ls;
4079 struct commit_queue_entry *old_selected_entry;
4080 char *line = NULL;
4081 size_t linesize = 0;
4082 ssize_t linelen;
4083 int i, nscroll = view->nlines - 1;
4085 switch (ch) {
4086 case '0':
4087 view->x = 0;
4088 break;
4089 case '$':
4090 view->x = MAX(view->maxx - view->ncols / 3, 0);
4091 view->count = 0;
4092 break;
4093 case KEY_RIGHT:
4094 case 'l':
4095 if (view->x + view->ncols / 3 < view->maxx)
4096 view->x += 2; /* move two columns right */
4097 else
4098 view->count = 0;
4099 break;
4100 case KEY_LEFT:
4101 case 'h':
4102 view->x -= MIN(view->x, 2); /* move two columns back */
4103 if (view->x <= 0)
4104 view->count = 0;
4105 break;
4106 case 'a':
4107 case 'w':
4108 if (ch == 'a')
4109 s->force_text_diff = !s->force_text_diff;
4110 if (ch == 'w')
4111 s->ignore_whitespace = !s->ignore_whitespace;
4112 wclear(view->window);
4113 s->first_displayed_line = 1;
4114 s->last_displayed_line = view->nlines;
4115 s->matched_line = 0;
4116 diff_view_indicate_progress(view);
4117 err = create_diff(s);
4118 view->count = 0;
4119 break;
4120 case 'g':
4121 case KEY_HOME:
4122 s->first_displayed_line = 1;
4123 view->count = 0;
4124 break;
4125 case 'G':
4126 case KEY_END:
4127 view->count = 0;
4128 if (s->eof)
4129 break;
4131 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4132 s->eof = 1;
4133 break;
4134 case 'k':
4135 case KEY_UP:
4136 case CTRL('p'):
4137 if (s->first_displayed_line > 1)
4138 s->first_displayed_line--;
4139 else
4140 view->count = 0;
4141 break;
4142 case CTRL('u'):
4143 case 'u':
4144 nscroll /= 2;
4145 /* FALL THROUGH */
4146 case KEY_PPAGE:
4147 case CTRL('b'):
4148 case 'b':
4149 if (s->first_displayed_line == 1) {
4150 view->count = 0;
4151 break;
4153 i = 0;
4154 while (i++ < nscroll && s->first_displayed_line > 1)
4155 s->first_displayed_line--;
4156 break;
4157 case 'j':
4158 case KEY_DOWN:
4159 case CTRL('n'):
4160 if (!s->eof)
4161 s->first_displayed_line++;
4162 else
4163 view->count = 0;
4164 break;
4165 case CTRL('d'):
4166 case 'd':
4167 nscroll /= 2;
4168 /* FALL THROUGH */
4169 case KEY_NPAGE:
4170 case CTRL('f'):
4171 case 'f':
4172 case ' ':
4173 if (s->eof) {
4174 view->count = 0;
4175 break;
4177 i = 0;
4178 while (!s->eof && i++ < nscroll) {
4179 linelen = getline(&line, &linesize, s->f);
4180 s->first_displayed_line++;
4181 if (linelen == -1) {
4182 if (feof(s->f)) {
4183 s->eof = 1;
4184 } else
4185 err = got_ferror(s->f, GOT_ERR_IO);
4186 break;
4189 free(line);
4190 break;
4191 case '[':
4192 if (s->diff_context > 0) {
4193 s->diff_context--;
4194 s->matched_line = 0;
4195 diff_view_indicate_progress(view);
4196 err = create_diff(s);
4197 if (s->first_displayed_line + view->nlines - 1 >
4198 s->nlines) {
4199 s->first_displayed_line = 1;
4200 s->last_displayed_line = view->nlines;
4202 } else
4203 view->count = 0;
4204 break;
4205 case ']':
4206 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4207 s->diff_context++;
4208 s->matched_line = 0;
4209 diff_view_indicate_progress(view);
4210 err = create_diff(s);
4211 } else
4212 view->count = 0;
4213 break;
4214 case '<':
4215 case ',':
4216 if (s->log_view == NULL) {
4217 view->count = 0;
4218 break;
4220 ls = &s->log_view->state.log;
4221 old_selected_entry = ls->selected_entry;
4223 /* view->count handled in input_log_view() */
4224 err = input_log_view(NULL, s->log_view, KEY_UP);
4225 if (err)
4226 break;
4228 if (old_selected_entry == ls->selected_entry)
4229 break;
4231 err = set_selected_commit(s, ls->selected_entry);
4232 if (err)
4233 break;
4235 s->first_displayed_line = 1;
4236 s->last_displayed_line = view->nlines;
4237 s->matched_line = 0;
4238 view->x = 0;
4240 diff_view_indicate_progress(view);
4241 err = create_diff(s);
4242 break;
4243 case '>':
4244 case '.':
4245 if (s->log_view == NULL) {
4246 view->count = 0;
4247 break;
4249 ls = &s->log_view->state.log;
4250 old_selected_entry = ls->selected_entry;
4252 /* view->count handled in input_log_view() */
4253 err = input_log_view(NULL, s->log_view, KEY_DOWN);
4254 if (err)
4255 break;
4257 if (old_selected_entry == ls->selected_entry)
4258 break;
4260 err = set_selected_commit(s, ls->selected_entry);
4261 if (err)
4262 break;
4264 s->first_displayed_line = 1;
4265 s->last_displayed_line = view->nlines;
4266 s->matched_line = 0;
4267 view->x = 0;
4269 diff_view_indicate_progress(view);
4270 err = create_diff(s);
4271 break;
4272 default:
4273 view->count = 0;
4274 break;
4277 return err;
4280 static const struct got_error *
4281 cmd_diff(int argc, char *argv[])
4283 const struct got_error *error = NULL;
4284 struct got_repository *repo = NULL;
4285 struct got_worktree *worktree = NULL;
4286 struct got_object_id *id1 = NULL, *id2 = NULL;
4287 char *repo_path = NULL, *cwd = NULL;
4288 char *id_str1 = NULL, *id_str2 = NULL;
4289 char *label1 = NULL, *label2 = NULL;
4290 int diff_context = 3, ignore_whitespace = 0;
4291 int ch, force_text_diff = 0;
4292 const char *errstr;
4293 struct tog_view *view;
4294 int *pack_fds = NULL;
4296 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4297 switch (ch) {
4298 case 'a':
4299 force_text_diff = 1;
4300 break;
4301 case 'C':
4302 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4303 &errstr);
4304 if (errstr != NULL)
4305 errx(1, "number of context lines is %s: %s",
4306 errstr, errstr);
4307 break;
4308 case 'r':
4309 repo_path = realpath(optarg, NULL);
4310 if (repo_path == NULL)
4311 return got_error_from_errno2("realpath",
4312 optarg);
4313 got_path_strip_trailing_slashes(repo_path);
4314 break;
4315 case 'w':
4316 ignore_whitespace = 1;
4317 break;
4318 default:
4319 usage_diff();
4320 /* NOTREACHED */
4324 argc -= optind;
4325 argv += optind;
4327 if (argc == 0) {
4328 usage_diff(); /* TODO show local worktree changes */
4329 } else if (argc == 2) {
4330 id_str1 = argv[0];
4331 id_str2 = argv[1];
4332 } else
4333 usage_diff();
4335 error = got_repo_pack_fds_open(&pack_fds);
4336 if (error)
4337 goto done;
4339 if (repo_path == NULL) {
4340 cwd = getcwd(NULL, 0);
4341 if (cwd == NULL)
4342 return got_error_from_errno("getcwd");
4343 error = got_worktree_open(&worktree, cwd);
4344 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4345 goto done;
4346 if (worktree)
4347 repo_path =
4348 strdup(got_worktree_get_repo_path(worktree));
4349 else
4350 repo_path = strdup(cwd);
4351 if (repo_path == NULL) {
4352 error = got_error_from_errno("strdup");
4353 goto done;
4357 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4358 if (error)
4359 goto done;
4361 init_curses();
4363 error = apply_unveil(got_repo_get_path(repo), NULL);
4364 if (error)
4365 goto done;
4367 error = tog_load_refs(repo, 0);
4368 if (error)
4369 goto done;
4371 error = got_repo_match_object_id(&id1, &label1, id_str1,
4372 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4373 if (error)
4374 goto done;
4376 error = got_repo_match_object_id(&id2, &label2, id_str2,
4377 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4378 if (error)
4379 goto done;
4381 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4382 if (view == NULL) {
4383 error = got_error_from_errno("view_open");
4384 goto done;
4386 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4387 ignore_whitespace, force_text_diff, NULL, repo);
4388 if (error)
4389 goto done;
4390 error = view_loop(view);
4391 done:
4392 free(label1);
4393 free(label2);
4394 free(repo_path);
4395 free(cwd);
4396 if (repo) {
4397 const struct got_error *close_err = got_repo_close(repo);
4398 if (error == NULL)
4399 error = close_err;
4401 if (worktree)
4402 got_worktree_close(worktree);
4403 if (pack_fds) {
4404 const struct got_error *pack_err =
4405 got_repo_pack_fds_close(pack_fds);
4406 if (error == NULL)
4407 error = pack_err;
4409 tog_free_refs();
4410 return error;
4413 __dead static void
4414 usage_blame(void)
4416 endwin();
4417 fprintf(stderr,
4418 "usage: %s blame [-c commit] [-r repository-path] path\n",
4419 getprogname());
4420 exit(1);
4423 struct tog_blame_line {
4424 int annotated;
4425 struct got_object_id *id;
4428 static const struct got_error *
4429 draw_blame(struct tog_view *view)
4431 struct tog_blame_view_state *s = &view->state.blame;
4432 struct tog_blame *blame = &s->blame;
4433 regmatch_t *regmatch = &view->regmatch;
4434 const struct got_error *err;
4435 int lineno = 0, nprinted = 0;
4436 char *line = NULL;
4437 size_t linesize = 0;
4438 ssize_t linelen;
4439 wchar_t *wline;
4440 int width;
4441 struct tog_blame_line *blame_line;
4442 struct got_object_id *prev_id = NULL;
4443 char *id_str;
4444 struct tog_color *tc;
4446 err = got_object_id_str(&id_str, &s->blamed_commit->id);
4447 if (err)
4448 return err;
4450 rewind(blame->f);
4451 werase(view->window);
4453 if (asprintf(&line, "commit %s", id_str) == -1) {
4454 err = got_error_from_errno("asprintf");
4455 free(id_str);
4456 return err;
4459 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4460 free(line);
4461 line = NULL;
4462 if (err)
4463 return err;
4464 if (view_needs_focus_indication(view))
4465 wstandout(view->window);
4466 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4467 if (tc)
4468 wattr_on(view->window,
4469 COLOR_PAIR(tc->colorpair), NULL);
4470 waddwstr(view->window, wline);
4471 if (tc)
4472 wattr_off(view->window,
4473 COLOR_PAIR(tc->colorpair), NULL);
4474 if (view_needs_focus_indication(view))
4475 wstandend(view->window);
4476 free(wline);
4477 wline = NULL;
4478 if (width < view->ncols - 1)
4479 waddch(view->window, '\n');
4481 if (asprintf(&line, "[%d/%d] %s%s",
4482 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
4483 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
4484 free(id_str);
4485 return got_error_from_errno("asprintf");
4487 free(id_str);
4488 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4489 free(line);
4490 line = NULL;
4491 if (err)
4492 return err;
4493 waddwstr(view->window, wline);
4494 free(wline);
4495 wline = NULL;
4496 if (width < view->ncols - 1)
4497 waddch(view->window, '\n');
4499 s->eof = 0;
4500 view->maxx = 0;
4501 while (nprinted < view->nlines - 2) {
4502 linelen = getline(&line, &linesize, blame->f);
4503 if (linelen == -1) {
4504 if (feof(blame->f)) {
4505 s->eof = 1;
4506 break;
4508 free(line);
4509 return got_ferror(blame->f, GOT_ERR_IO);
4511 if (++lineno < s->first_displayed_line)
4512 continue;
4514 /* Set view->maxx based on full line length. */
4515 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
4516 if (err) {
4517 free(line);
4518 return err;
4520 free(wline);
4521 wline = NULL;
4522 view->maxx = MAX(view->maxx, width);
4524 if (view->focussed && nprinted == s->selected_line - 1)
4525 wstandout(view->window);
4527 if (blame->nlines > 0) {
4528 blame_line = &blame->lines[lineno - 1];
4529 if (blame_line->annotated && prev_id &&
4530 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
4531 !(view->focussed &&
4532 nprinted == s->selected_line - 1)) {
4533 waddstr(view->window, " ");
4534 } else if (blame_line->annotated) {
4535 char *id_str;
4536 err = got_object_id_str(&id_str,
4537 blame_line->id);
4538 if (err) {
4539 free(line);
4540 return err;
4542 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4543 if (tc)
4544 wattr_on(view->window,
4545 COLOR_PAIR(tc->colorpair), NULL);
4546 wprintw(view->window, "%.8s", id_str);
4547 if (tc)
4548 wattr_off(view->window,
4549 COLOR_PAIR(tc->colorpair), NULL);
4550 free(id_str);
4551 prev_id = blame_line->id;
4552 } else {
4553 waddstr(view->window, "........");
4554 prev_id = NULL;
4556 } else {
4557 waddstr(view->window, "........");
4558 prev_id = NULL;
4561 if (view->focussed && nprinted == s->selected_line - 1)
4562 wstandend(view->window);
4563 waddstr(view->window, " ");
4565 if (view->ncols <= 9) {
4566 width = 9;
4567 } else if (s->first_displayed_line + nprinted ==
4568 s->matched_line &&
4569 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4570 err = add_matched_line(&width, line, view->ncols - 9, 9,
4571 view->window, view->x, regmatch);
4572 if (err) {
4573 free(line);
4574 return err;
4576 width += 9;
4577 } else {
4578 int skip;
4579 err = format_line(&wline, &width, &skip, line,
4580 view->x, view->ncols - 9, 9, 1);
4581 if (err) {
4582 free(line);
4583 return err;
4585 waddwstr(view->window, &wline[skip]);
4586 width += 9;
4587 free(wline);
4588 wline = NULL;
4591 if (width <= view->ncols - 1)
4592 waddch(view->window, '\n');
4593 if (++nprinted == 1)
4594 s->first_displayed_line = lineno;
4596 free(line);
4597 s->last_displayed_line = lineno;
4599 view_vborder(view);
4601 return NULL;
4604 static const struct got_error *
4605 blame_cb(void *arg, int nlines, int lineno,
4606 struct got_commit_object *commit, struct got_object_id *id)
4608 const struct got_error *err = NULL;
4609 struct tog_blame_cb_args *a = arg;
4610 struct tog_blame_line *line;
4611 int errcode;
4613 if (nlines != a->nlines ||
4614 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4615 return got_error(GOT_ERR_RANGE);
4617 errcode = pthread_mutex_lock(&tog_mutex);
4618 if (errcode)
4619 return got_error_set_errno(errcode, "pthread_mutex_lock");
4621 if (*a->quit) { /* user has quit the blame view */
4622 err = got_error(GOT_ERR_ITER_COMPLETED);
4623 goto done;
4626 if (lineno == -1)
4627 goto done; /* no change in this commit */
4629 line = &a->lines[lineno - 1];
4630 if (line->annotated)
4631 goto done;
4633 line->id = got_object_id_dup(id);
4634 if (line->id == NULL) {
4635 err = got_error_from_errno("got_object_id_dup");
4636 goto done;
4638 line->annotated = 1;
4639 done:
4640 errcode = pthread_mutex_unlock(&tog_mutex);
4641 if (errcode)
4642 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4643 return err;
4646 static void *
4647 blame_thread(void *arg)
4649 const struct got_error *err, *close_err;
4650 struct tog_blame_thread_args *ta = arg;
4651 struct tog_blame_cb_args *a = ta->cb_args;
4652 int errcode;
4654 err = block_signals_used_by_main_thread();
4655 if (err)
4656 return (void *)err;
4658 err = got_blame(ta->path, a->commit_id, ta->repo,
4659 blame_cb, ta->cb_args, ta->cancel_cb, ta->cancel_arg);
4660 if (err && err->code == GOT_ERR_CANCELLED)
4661 err = NULL;
4663 errcode = pthread_mutex_lock(&tog_mutex);
4664 if (errcode)
4665 return (void *)got_error_set_errno(errcode,
4666 "pthread_mutex_lock");
4668 close_err = got_repo_close(ta->repo);
4669 if (err == NULL)
4670 err = close_err;
4671 ta->repo = NULL;
4672 *ta->complete = 1;
4674 errcode = pthread_mutex_unlock(&tog_mutex);
4675 if (errcode && err == NULL)
4676 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4678 return (void *)err;
4681 static struct got_object_id *
4682 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
4683 int first_displayed_line, int selected_line)
4685 struct tog_blame_line *line;
4687 if (nlines <= 0)
4688 return NULL;
4690 line = &lines[first_displayed_line - 1 + selected_line - 1];
4691 if (!line->annotated)
4692 return NULL;
4694 return line->id;
4697 static const struct got_error *
4698 stop_blame(struct tog_blame *blame)
4700 const struct got_error *err = NULL;
4701 int i;
4703 if (blame->thread) {
4704 int errcode;
4705 errcode = pthread_mutex_unlock(&tog_mutex);
4706 if (errcode)
4707 return got_error_set_errno(errcode,
4708 "pthread_mutex_unlock");
4709 errcode = pthread_join(blame->thread, (void **)&err);
4710 if (errcode)
4711 return got_error_set_errno(errcode, "pthread_join");
4712 errcode = pthread_mutex_lock(&tog_mutex);
4713 if (errcode)
4714 return got_error_set_errno(errcode,
4715 "pthread_mutex_lock");
4716 if (err && err->code == GOT_ERR_ITER_COMPLETED)
4717 err = NULL;
4718 blame->thread = NULL;
4720 if (blame->thread_args.repo) {
4721 const struct got_error *close_err;
4722 close_err = got_repo_close(blame->thread_args.repo);
4723 if (err == NULL)
4724 err = close_err;
4725 blame->thread_args.repo = NULL;
4727 if (blame->f) {
4728 if (fclose(blame->f) == EOF && err == NULL)
4729 err = got_error_from_errno("fclose");
4730 blame->f = NULL;
4732 if (blame->lines) {
4733 for (i = 0; i < blame->nlines; i++)
4734 free(blame->lines[i].id);
4735 free(blame->lines);
4736 blame->lines = NULL;
4738 free(blame->cb_args.commit_id);
4739 blame->cb_args.commit_id = NULL;
4740 if (blame->pack_fds) {
4741 const struct got_error *pack_err =
4742 got_repo_pack_fds_close(blame->pack_fds);
4743 if (err == NULL)
4744 err = pack_err;
4745 blame->pack_fds = NULL;
4747 return err;
4750 static const struct got_error *
4751 cancel_blame_view(void *arg)
4753 const struct got_error *err = NULL;
4754 int *done = arg;
4755 int errcode;
4757 errcode = pthread_mutex_lock(&tog_mutex);
4758 if (errcode)
4759 return got_error_set_errno(errcode,
4760 "pthread_mutex_unlock");
4762 if (*done)
4763 err = got_error(GOT_ERR_CANCELLED);
4765 errcode = pthread_mutex_unlock(&tog_mutex);
4766 if (errcode)
4767 return got_error_set_errno(errcode,
4768 "pthread_mutex_lock");
4770 return err;
4773 static const struct got_error *
4774 run_blame(struct tog_view *view)
4776 struct tog_blame_view_state *s = &view->state.blame;
4777 struct tog_blame *blame = &s->blame;
4778 const struct got_error *err = NULL;
4779 struct got_commit_object *commit = NULL;
4780 struct got_blob_object *blob = NULL;
4781 struct got_repository *thread_repo = NULL;
4782 struct got_object_id *obj_id = NULL;
4783 int obj_type;
4784 int *pack_fds = NULL;
4786 err = got_object_open_as_commit(&commit, s->repo,
4787 &s->blamed_commit->id);
4788 if (err)
4789 return err;
4791 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
4792 if (err)
4793 goto done;
4795 err = got_object_get_type(&obj_type, s->repo, obj_id);
4796 if (err)
4797 goto done;
4799 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4800 err = got_error(GOT_ERR_OBJ_TYPE);
4801 goto done;
4804 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192);
4805 if (err)
4806 goto done;
4807 blame->f = got_opentemp();
4808 if (blame->f == NULL) {
4809 err = got_error_from_errno("got_opentemp");
4810 goto done;
4812 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
4813 &blame->line_offsets, blame->f, blob);
4814 if (err)
4815 goto done;
4816 if (blame->nlines == 0) {
4817 s->blame_complete = 1;
4818 goto done;
4821 /* Don't include \n at EOF in the blame line count. */
4822 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
4823 blame->nlines--;
4825 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
4826 if (blame->lines == NULL) {
4827 err = got_error_from_errno("calloc");
4828 goto done;
4831 err = got_repo_pack_fds_open(&pack_fds);
4832 if (err)
4833 goto done;
4834 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
4835 pack_fds);
4836 if (err)
4837 goto done;
4839 blame->pack_fds = pack_fds;
4840 blame->cb_args.view = view;
4841 blame->cb_args.lines = blame->lines;
4842 blame->cb_args.nlines = blame->nlines;
4843 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
4844 if (blame->cb_args.commit_id == NULL) {
4845 err = got_error_from_errno("got_object_id_dup");
4846 goto done;
4848 blame->cb_args.quit = &s->done;
4850 blame->thread_args.path = s->path;
4851 blame->thread_args.repo = thread_repo;
4852 blame->thread_args.cb_args = &blame->cb_args;
4853 blame->thread_args.complete = &s->blame_complete;
4854 blame->thread_args.cancel_cb = cancel_blame_view;
4855 blame->thread_args.cancel_arg = &s->done;
4856 s->blame_complete = 0;
4858 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
4859 s->first_displayed_line = 1;
4860 s->last_displayed_line = view->nlines;
4861 s->selected_line = 1;
4863 s->matched_line = 0;
4865 done:
4866 if (commit)
4867 got_object_commit_close(commit);
4868 if (blob)
4869 got_object_blob_close(blob);
4870 free(obj_id);
4871 if (err)
4872 stop_blame(blame);
4873 return err;
4876 static const struct got_error *
4877 open_blame_view(struct tog_view *view, char *path,
4878 struct got_object_id *commit_id, struct got_repository *repo)
4880 const struct got_error *err = NULL;
4881 struct tog_blame_view_state *s = &view->state.blame;
4883 STAILQ_INIT(&s->blamed_commits);
4885 s->path = strdup(path);
4886 if (s->path == NULL)
4887 return got_error_from_errno("strdup");
4889 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
4890 if (err) {
4891 free(s->path);
4892 return err;
4895 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
4896 s->first_displayed_line = 1;
4897 s->last_displayed_line = view->nlines;
4898 s->selected_line = 1;
4899 s->blame_complete = 0;
4900 s->repo = repo;
4901 s->commit_id = commit_id;
4902 memset(&s->blame, 0, sizeof(s->blame));
4904 STAILQ_INIT(&s->colors);
4905 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4906 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
4907 get_color_value("TOG_COLOR_COMMIT"));
4908 if (err)
4909 return err;
4912 view->show = show_blame_view;
4913 view->input = input_blame_view;
4914 view->close = close_blame_view;
4915 view->search_start = search_start_blame_view;
4916 view->search_next = search_next_blame_view;
4918 return run_blame(view);
4921 static const struct got_error *
4922 close_blame_view(struct tog_view *view)
4924 const struct got_error *err = NULL;
4925 struct tog_blame_view_state *s = &view->state.blame;
4927 if (s->blame.thread)
4928 err = stop_blame(&s->blame);
4930 while (!STAILQ_EMPTY(&s->blamed_commits)) {
4931 struct got_object_qid *blamed_commit;
4932 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
4933 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
4934 got_object_qid_free(blamed_commit);
4937 free(s->path);
4938 free_colors(&s->colors);
4939 return err;
4942 static const struct got_error *
4943 search_start_blame_view(struct tog_view *view)
4945 struct tog_blame_view_state *s = &view->state.blame;
4947 s->matched_line = 0;
4948 return NULL;
4951 static const struct got_error *
4952 search_next_blame_view(struct tog_view *view)
4954 struct tog_blame_view_state *s = &view->state.blame;
4955 const struct got_error *err = NULL;
4956 int lineno;
4957 char *line = NULL;
4958 size_t linesize = 0;
4959 ssize_t linelen;
4961 if (!view->searching) {
4962 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4963 return NULL;
4966 if (s->matched_line) {
4967 if (view->searching == TOG_SEARCH_FORWARD)
4968 lineno = s->matched_line + 1;
4969 else
4970 lineno = s->matched_line - 1;
4971 } else
4972 lineno = s->first_displayed_line - 1 + s->selected_line;
4974 while (1) {
4975 off_t offset;
4977 if (lineno <= 0 || lineno > s->blame.nlines) {
4978 if (s->matched_line == 0) {
4979 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4980 break;
4983 if (view->searching == TOG_SEARCH_FORWARD)
4984 lineno = 1;
4985 else
4986 lineno = s->blame.nlines;
4989 offset = s->blame.line_offsets[lineno - 1];
4990 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
4991 free(line);
4992 return got_error_from_errno("fseeko");
4994 linelen = getline(&line, &linesize, s->blame.f);
4995 if (linelen != -1) {
4996 char *exstr;
4997 err = expand_tab(&exstr, line);
4998 if (err)
4999 break;
5000 if (match_line(exstr, &view->regex, 1,
5001 &view->regmatch)) {
5002 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5003 s->matched_line = lineno;
5004 free(exstr);
5005 break;
5007 free(exstr);
5009 if (view->searching == TOG_SEARCH_FORWARD)
5010 lineno++;
5011 else
5012 lineno--;
5014 free(line);
5016 if (s->matched_line) {
5017 s->first_displayed_line = s->matched_line;
5018 s->selected_line = 1;
5021 return err;
5024 static const struct got_error *
5025 show_blame_view(struct tog_view *view)
5027 const struct got_error *err = NULL;
5028 struct tog_blame_view_state *s = &view->state.blame;
5029 int errcode;
5031 if (s->blame.thread == NULL && !s->blame_complete) {
5032 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5033 &s->blame.thread_args);
5034 if (errcode)
5035 return got_error_set_errno(errcode, "pthread_create");
5037 halfdelay(1); /* fast refresh while annotating */
5040 if (s->blame_complete)
5041 halfdelay(10); /* disable fast refresh */
5043 err = draw_blame(view);
5045 view_vborder(view);
5046 return err;
5049 static const struct got_error *
5050 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5052 const struct got_error *err = NULL, *thread_err = NULL;
5053 struct tog_view *diff_view;
5054 struct tog_blame_view_state *s = &view->state.blame;
5055 int begin_x = 0, nscroll = view->nlines - 2;
5057 switch (ch) {
5058 case '0':
5059 view->x = 0;
5060 break;
5061 case '$':
5062 view->x = MAX(view->maxx - view->ncols / 3, 0);
5063 view->count = 0;
5064 break;
5065 case KEY_RIGHT:
5066 case 'l':
5067 if (view->x + view->ncols / 3 < view->maxx)
5068 view->x += 2; /* move two columns right */
5069 else
5070 view->count = 0;
5071 break;
5072 case KEY_LEFT:
5073 case 'h':
5074 view->x -= MIN(view->x, 2); /* move two columns back */
5075 if (view->x <= 0)
5076 view->count = 0;
5077 break;
5078 case 'q':
5079 s->done = 1;
5080 break;
5081 case 'g':
5082 case KEY_HOME:
5083 s->selected_line = 1;
5084 s->first_displayed_line = 1;
5085 view->count = 0;
5086 break;
5087 case 'G':
5088 case KEY_END:
5089 if (s->blame.nlines < view->nlines - 2) {
5090 s->selected_line = s->blame.nlines;
5091 s->first_displayed_line = 1;
5092 } else {
5093 s->selected_line = view->nlines - 2;
5094 s->first_displayed_line = s->blame.nlines -
5095 (view->nlines - 3);
5097 view->count = 0;
5098 break;
5099 case 'k':
5100 case KEY_UP:
5101 case CTRL('p'):
5102 if (s->selected_line > 1)
5103 s->selected_line--;
5104 else if (s->selected_line == 1 &&
5105 s->first_displayed_line > 1)
5106 s->first_displayed_line--;
5107 else
5108 view->count = 0;
5109 break;
5110 case CTRL('u'):
5111 case 'u':
5112 nscroll /= 2;
5113 /* FALL THROUGH */
5114 case KEY_PPAGE:
5115 case CTRL('b'):
5116 case 'b':
5117 if (s->first_displayed_line == 1) {
5118 if (view->count > 1)
5119 nscroll += nscroll;
5120 s->selected_line = MAX(1, s->selected_line - nscroll);
5121 view->count = 0;
5122 break;
5124 if (s->first_displayed_line > nscroll)
5125 s->first_displayed_line -= nscroll;
5126 else
5127 s->first_displayed_line = 1;
5128 break;
5129 case 'j':
5130 case KEY_DOWN:
5131 case CTRL('n'):
5132 if (s->selected_line < view->nlines - 2 &&
5133 s->first_displayed_line +
5134 s->selected_line <= s->blame.nlines)
5135 s->selected_line++;
5136 else if (s->last_displayed_line <
5137 s->blame.nlines)
5138 s->first_displayed_line++;
5139 else
5140 view->count = 0;
5141 break;
5142 case 'c':
5143 case 'p': {
5144 struct got_object_id *id = NULL;
5146 view->count = 0;
5147 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5148 s->first_displayed_line, s->selected_line);
5149 if (id == NULL)
5150 break;
5151 if (ch == 'p') {
5152 struct got_commit_object *commit, *pcommit;
5153 struct got_object_qid *pid;
5154 struct got_object_id *blob_id = NULL;
5155 int obj_type;
5156 err = got_object_open_as_commit(&commit,
5157 s->repo, id);
5158 if (err)
5159 break;
5160 pid = STAILQ_FIRST(
5161 got_object_commit_get_parent_ids(commit));
5162 if (pid == NULL) {
5163 got_object_commit_close(commit);
5164 break;
5166 /* Check if path history ends here. */
5167 err = got_object_open_as_commit(&pcommit,
5168 s->repo, &pid->id);
5169 if (err)
5170 break;
5171 err = got_object_id_by_path(&blob_id, s->repo,
5172 pcommit, s->path);
5173 got_object_commit_close(pcommit);
5174 if (err) {
5175 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5176 err = NULL;
5177 got_object_commit_close(commit);
5178 break;
5180 err = got_object_get_type(&obj_type, s->repo,
5181 blob_id);
5182 free(blob_id);
5183 /* Can't blame non-blob type objects. */
5184 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5185 got_object_commit_close(commit);
5186 break;
5188 err = got_object_qid_alloc(&s->blamed_commit,
5189 &pid->id);
5190 got_object_commit_close(commit);
5191 } else {
5192 if (got_object_id_cmp(id,
5193 &s->blamed_commit->id) == 0)
5194 break;
5195 err = got_object_qid_alloc(&s->blamed_commit,
5196 id);
5198 if (err)
5199 break;
5200 s->done = 1;
5201 thread_err = stop_blame(&s->blame);
5202 s->done = 0;
5203 if (thread_err)
5204 break;
5205 STAILQ_INSERT_HEAD(&s->blamed_commits,
5206 s->blamed_commit, entry);
5207 err = run_blame(view);
5208 if (err)
5209 break;
5210 break;
5212 case 'C': {
5213 struct got_object_qid *first;
5215 view->count = 0;
5216 first = STAILQ_FIRST(&s->blamed_commits);
5217 if (!got_object_id_cmp(&first->id, s->commit_id))
5218 break;
5219 s->done = 1;
5220 thread_err = stop_blame(&s->blame);
5221 s->done = 0;
5222 if (thread_err)
5223 break;
5224 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5225 got_object_qid_free(s->blamed_commit);
5226 s->blamed_commit =
5227 STAILQ_FIRST(&s->blamed_commits);
5228 err = run_blame(view);
5229 if (err)
5230 break;
5231 break;
5233 case KEY_ENTER:
5234 case '\r': {
5235 struct got_object_id *id = NULL;
5236 struct got_object_qid *pid;
5237 struct got_commit_object *commit = NULL;
5239 view->count = 0;
5240 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5241 s->first_displayed_line, s->selected_line);
5242 if (id == NULL)
5243 break;
5244 err = got_object_open_as_commit(&commit, s->repo, id);
5245 if (err)
5246 break;
5247 pid = STAILQ_FIRST(
5248 got_object_commit_get_parent_ids(commit));
5249 if (view_is_parent_view(view))
5250 begin_x = view_split_begin_x(view->begin_x);
5251 diff_view = view_open(0, 0, 0, begin_x, TOG_VIEW_DIFF);
5252 if (diff_view == NULL) {
5253 got_object_commit_close(commit);
5254 err = got_error_from_errno("view_open");
5255 break;
5257 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5258 id, NULL, NULL, 3, 0, 0, NULL, s->repo);
5259 got_object_commit_close(commit);
5260 if (err) {
5261 view_close(diff_view);
5262 break;
5264 view->focussed = 0;
5265 diff_view->focussed = 1;
5266 if (view_is_parent_view(view)) {
5267 err = view_close_child(view);
5268 if (err)
5269 break;
5270 err = view_set_child(view, diff_view);
5271 if (err)
5272 break;
5273 view->focus_child = 1;
5274 } else
5275 *new_view = diff_view;
5276 if (err)
5277 break;
5278 break;
5280 case CTRL('d'):
5281 case 'd':
5282 nscroll /= 2;
5283 /* FALL THROUGH */
5284 case KEY_NPAGE:
5285 case CTRL('f'):
5286 case 'f':
5287 case ' ':
5288 if (s->last_displayed_line >= s->blame.nlines &&
5289 s->selected_line >= MIN(s->blame.nlines,
5290 view->nlines - 2)) {
5291 view->count = 0;
5292 break;
5294 if (s->last_displayed_line >= s->blame.nlines &&
5295 s->selected_line < view->nlines - 2) {
5296 s->selected_line +=
5297 MIN(nscroll, s->last_displayed_line -
5298 s->first_displayed_line - s->selected_line + 1);
5300 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5301 s->first_displayed_line += nscroll;
5302 else
5303 s->first_displayed_line =
5304 s->blame.nlines - (view->nlines - 3);
5305 break;
5306 case KEY_RESIZE:
5307 if (s->selected_line > view->nlines - 2) {
5308 s->selected_line = MIN(s->blame.nlines,
5309 view->nlines - 2);
5311 break;
5312 default:
5313 view->count = 0;
5314 break;
5316 return thread_err ? thread_err : err;
5319 static const struct got_error *
5320 cmd_blame(int argc, char *argv[])
5322 const struct got_error *error;
5323 struct got_repository *repo = NULL;
5324 struct got_worktree *worktree = NULL;
5325 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5326 char *link_target = NULL;
5327 struct got_object_id *commit_id = NULL;
5328 struct got_commit_object *commit = NULL;
5329 char *commit_id_str = NULL;
5330 int ch;
5331 struct tog_view *view;
5332 int *pack_fds = NULL;
5334 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5335 switch (ch) {
5336 case 'c':
5337 commit_id_str = optarg;
5338 break;
5339 case 'r':
5340 repo_path = realpath(optarg, NULL);
5341 if (repo_path == NULL)
5342 return got_error_from_errno2("realpath",
5343 optarg);
5344 break;
5345 default:
5346 usage_blame();
5347 /* NOTREACHED */
5351 argc -= optind;
5352 argv += optind;
5354 if (argc != 1)
5355 usage_blame();
5357 error = got_repo_pack_fds_open(&pack_fds);
5358 if (error != NULL)
5359 goto done;
5361 if (repo_path == NULL) {
5362 cwd = getcwd(NULL, 0);
5363 if (cwd == NULL)
5364 return got_error_from_errno("getcwd");
5365 error = got_worktree_open(&worktree, cwd);
5366 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5367 goto done;
5368 if (worktree)
5369 repo_path =
5370 strdup(got_worktree_get_repo_path(worktree));
5371 else
5372 repo_path = strdup(cwd);
5373 if (repo_path == NULL) {
5374 error = got_error_from_errno("strdup");
5375 goto done;
5379 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5380 if (error != NULL)
5381 goto done;
5383 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
5384 worktree);
5385 if (error)
5386 goto done;
5388 init_curses();
5390 error = apply_unveil(got_repo_get_path(repo), NULL);
5391 if (error)
5392 goto done;
5394 error = tog_load_refs(repo, 0);
5395 if (error)
5396 goto done;
5398 if (commit_id_str == NULL) {
5399 struct got_reference *head_ref;
5400 error = got_ref_open(&head_ref, repo, worktree ?
5401 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5402 if (error != NULL)
5403 goto done;
5404 error = got_ref_resolve(&commit_id, repo, head_ref);
5405 got_ref_close(head_ref);
5406 } else {
5407 error = got_repo_match_object_id(&commit_id, NULL,
5408 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
5410 if (error != NULL)
5411 goto done;
5413 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
5414 if (view == NULL) {
5415 error = got_error_from_errno("view_open");
5416 goto done;
5419 error = got_object_open_as_commit(&commit, repo, commit_id);
5420 if (error)
5421 goto done;
5423 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5424 commit, repo);
5425 if (error)
5426 goto done;
5428 error = open_blame_view(view, link_target ? link_target : in_repo_path,
5429 commit_id, repo);
5430 if (error)
5431 goto done;
5432 if (worktree) {
5433 /* Release work tree lock. */
5434 got_worktree_close(worktree);
5435 worktree = NULL;
5437 error = view_loop(view);
5438 done:
5439 free(repo_path);
5440 free(in_repo_path);
5441 free(link_target);
5442 free(cwd);
5443 free(commit_id);
5444 if (commit)
5445 got_object_commit_close(commit);
5446 if (worktree)
5447 got_worktree_close(worktree);
5448 if (repo) {
5449 const struct got_error *close_err = got_repo_close(repo);
5450 if (error == NULL)
5451 error = close_err;
5453 if (pack_fds) {
5454 const struct got_error *pack_err =
5455 got_repo_pack_fds_close(pack_fds);
5456 if (error == NULL)
5457 error = pack_err;
5459 tog_free_refs();
5460 return error;
5463 static const struct got_error *
5464 draw_tree_entries(struct tog_view *view, const char *parent_path)
5466 struct tog_tree_view_state *s = &view->state.tree;
5467 const struct got_error *err = NULL;
5468 struct got_tree_entry *te;
5469 wchar_t *wline;
5470 struct tog_color *tc;
5471 int width, n, i, nentries;
5472 int limit = view->nlines;
5474 s->ndisplayed = 0;
5476 werase(view->window);
5478 if (limit == 0)
5479 return NULL;
5481 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
5482 0, 0);
5483 if (err)
5484 return err;
5485 if (view_needs_focus_indication(view))
5486 wstandout(view->window);
5487 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5488 if (tc)
5489 wattr_on(view->window,
5490 COLOR_PAIR(tc->colorpair), NULL);
5491 waddwstr(view->window, wline);
5492 if (tc)
5493 wattr_off(view->window,
5494 COLOR_PAIR(tc->colorpair), NULL);
5495 if (view_needs_focus_indication(view))
5496 wstandend(view->window);
5497 free(wline);
5498 wline = NULL;
5499 if (width < view->ncols - 1)
5500 waddch(view->window, '\n');
5501 if (--limit <= 0)
5502 return NULL;
5503 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
5504 0, 0);
5505 if (err)
5506 return err;
5507 waddwstr(view->window, wline);
5508 free(wline);
5509 wline = NULL;
5510 if (width < view->ncols - 1)
5511 waddch(view->window, '\n');
5512 if (--limit <= 0)
5513 return NULL;
5514 waddch(view->window, '\n');
5515 if (--limit <= 0)
5516 return NULL;
5518 if (s->first_displayed_entry == NULL) {
5519 te = got_object_tree_get_first_entry(s->tree);
5520 if (s->selected == 0) {
5521 if (view->focussed)
5522 wstandout(view->window);
5523 s->selected_entry = NULL;
5525 waddstr(view->window, " ..\n"); /* parent directory */
5526 if (s->selected == 0 && view->focussed)
5527 wstandend(view->window);
5528 s->ndisplayed++;
5529 if (--limit <= 0)
5530 return NULL;
5531 n = 1;
5532 } else {
5533 n = 0;
5534 te = s->first_displayed_entry;
5537 nentries = got_object_tree_get_nentries(s->tree);
5538 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
5539 char *line = NULL, *id_str = NULL, *link_target = NULL;
5540 const char *modestr = "";
5541 mode_t mode;
5543 te = got_object_tree_get_entry(s->tree, i);
5544 mode = got_tree_entry_get_mode(te);
5546 if (s->show_ids) {
5547 err = got_object_id_str(&id_str,
5548 got_tree_entry_get_id(te));
5549 if (err)
5550 return got_error_from_errno(
5551 "got_object_id_str");
5553 if (got_object_tree_entry_is_submodule(te))
5554 modestr = "$";
5555 else if (S_ISLNK(mode)) {
5556 int i;
5558 err = got_tree_entry_get_symlink_target(&link_target,
5559 te, s->repo);
5560 if (err) {
5561 free(id_str);
5562 return err;
5564 for (i = 0; i < strlen(link_target); i++) {
5565 if (!isprint((unsigned char)link_target[i]))
5566 link_target[i] = '?';
5568 modestr = "@";
5570 else if (S_ISDIR(mode))
5571 modestr = "/";
5572 else if (mode & S_IXUSR)
5573 modestr = "*";
5574 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
5575 got_tree_entry_get_name(te), modestr,
5576 link_target ? " -> ": "",
5577 link_target ? link_target : "") == -1) {
5578 free(id_str);
5579 free(link_target);
5580 return got_error_from_errno("asprintf");
5582 free(id_str);
5583 free(link_target);
5584 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
5585 0, 0);
5586 if (err) {
5587 free(line);
5588 break;
5590 if (n == s->selected) {
5591 if (view->focussed)
5592 wstandout(view->window);
5593 s->selected_entry = te;
5595 tc = match_color(&s->colors, line);
5596 if (tc)
5597 wattr_on(view->window,
5598 COLOR_PAIR(tc->colorpair), NULL);
5599 waddwstr(view->window, wline);
5600 if (tc)
5601 wattr_off(view->window,
5602 COLOR_PAIR(tc->colorpair), NULL);
5603 if (width < view->ncols - 1)
5604 waddch(view->window, '\n');
5605 if (n == s->selected && view->focussed)
5606 wstandend(view->window);
5607 free(line);
5608 free(wline);
5609 wline = NULL;
5610 n++;
5611 s->ndisplayed++;
5612 s->last_displayed_entry = te;
5613 if (--limit <= 0)
5614 break;
5617 return err;
5620 static void
5621 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
5623 struct got_tree_entry *te;
5624 int isroot = s->tree == s->root;
5625 int i = 0;
5627 if (s->first_displayed_entry == NULL)
5628 return;
5630 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
5631 while (i++ < maxscroll) {
5632 if (te == NULL) {
5633 if (!isroot)
5634 s->first_displayed_entry = NULL;
5635 break;
5637 s->first_displayed_entry = te;
5638 te = got_tree_entry_get_prev(s->tree, te);
5642 static void
5643 tree_scroll_down(struct tog_tree_view_state *s, int maxscroll)
5645 struct got_tree_entry *next, *last;
5646 int n = 0;
5648 if (s->first_displayed_entry)
5649 next = got_tree_entry_get_next(s->tree,
5650 s->first_displayed_entry);
5651 else
5652 next = got_object_tree_get_first_entry(s->tree);
5654 last = s->last_displayed_entry;
5655 while (next && last && n++ < maxscroll) {
5656 last = got_tree_entry_get_next(s->tree, last);
5657 if (last) {
5658 s->first_displayed_entry = next;
5659 next = got_tree_entry_get_next(s->tree, next);
5664 static const struct got_error *
5665 tree_entry_path(char **path, struct tog_parent_trees *parents,
5666 struct got_tree_entry *te)
5668 const struct got_error *err = NULL;
5669 struct tog_parent_tree *pt;
5670 size_t len = 2; /* for leading slash and NUL */
5672 TAILQ_FOREACH(pt, parents, entry)
5673 len += strlen(got_tree_entry_get_name(pt->selected_entry))
5674 + 1 /* slash */;
5675 if (te)
5676 len += strlen(got_tree_entry_get_name(te));
5678 *path = calloc(1, len);
5679 if (path == NULL)
5680 return got_error_from_errno("calloc");
5682 (*path)[0] = '/';
5683 pt = TAILQ_LAST(parents, tog_parent_trees);
5684 while (pt) {
5685 const char *name = got_tree_entry_get_name(pt->selected_entry);
5686 if (strlcat(*path, name, len) >= len) {
5687 err = got_error(GOT_ERR_NO_SPACE);
5688 goto done;
5690 if (strlcat(*path, "/", len) >= len) {
5691 err = got_error(GOT_ERR_NO_SPACE);
5692 goto done;
5694 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
5696 if (te) {
5697 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
5698 err = got_error(GOT_ERR_NO_SPACE);
5699 goto done;
5702 done:
5703 if (err) {
5704 free(*path);
5705 *path = NULL;
5707 return err;
5710 static const struct got_error *
5711 blame_tree_entry(struct tog_view **new_view, int begin_x,
5712 struct got_tree_entry *te, struct tog_parent_trees *parents,
5713 struct got_object_id *commit_id, struct got_repository *repo)
5715 const struct got_error *err = NULL;
5716 char *path;
5717 struct tog_view *blame_view;
5719 *new_view = NULL;
5721 err = tree_entry_path(&path, parents, te);
5722 if (err)
5723 return err;
5725 blame_view = view_open(0, 0, 0, begin_x, TOG_VIEW_BLAME);
5726 if (blame_view == NULL) {
5727 err = got_error_from_errno("view_open");
5728 goto done;
5731 err = open_blame_view(blame_view, path, commit_id, repo);
5732 if (err) {
5733 if (err->code == GOT_ERR_CANCELLED)
5734 err = NULL;
5735 view_close(blame_view);
5736 } else
5737 *new_view = blame_view;
5738 done:
5739 free(path);
5740 return err;
5743 static const struct got_error *
5744 log_selected_tree_entry(struct tog_view **new_view, int begin_x,
5745 struct tog_tree_view_state *s)
5747 struct tog_view *log_view;
5748 const struct got_error *err = NULL;
5749 char *path;
5751 *new_view = NULL;
5753 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
5754 if (log_view == NULL)
5755 return got_error_from_errno("view_open");
5757 err = tree_entry_path(&path, &s->parents, s->selected_entry);
5758 if (err)
5759 return err;
5761 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
5762 path, 0);
5763 if (err)
5764 view_close(log_view);
5765 else
5766 *new_view = log_view;
5767 free(path);
5768 return err;
5771 static const struct got_error *
5772 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
5773 const char *head_ref_name, struct got_repository *repo)
5775 const struct got_error *err = NULL;
5776 char *commit_id_str = NULL;
5777 struct tog_tree_view_state *s = &view->state.tree;
5778 struct got_commit_object *commit = NULL;
5780 TAILQ_INIT(&s->parents);
5781 STAILQ_INIT(&s->colors);
5783 s->commit_id = got_object_id_dup(commit_id);
5784 if (s->commit_id == NULL)
5785 return got_error_from_errno("got_object_id_dup");
5787 err = got_object_open_as_commit(&commit, repo, commit_id);
5788 if (err)
5789 goto done;
5792 * The root is opened here and will be closed when the view is closed.
5793 * Any visited subtrees and their path-wise parents are opened and
5794 * closed on demand.
5796 err = got_object_open_as_tree(&s->root, repo,
5797 got_object_commit_get_tree_id(commit));
5798 if (err)
5799 goto done;
5800 s->tree = s->root;
5802 err = got_object_id_str(&commit_id_str, commit_id);
5803 if (err != NULL)
5804 goto done;
5806 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
5807 err = got_error_from_errno("asprintf");
5808 goto done;
5811 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
5812 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
5813 if (head_ref_name) {
5814 s->head_ref_name = strdup(head_ref_name);
5815 if (s->head_ref_name == NULL) {
5816 err = got_error_from_errno("strdup");
5817 goto done;
5820 s->repo = repo;
5822 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5823 err = add_color(&s->colors, "\\$$",
5824 TOG_COLOR_TREE_SUBMODULE,
5825 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
5826 if (err)
5827 goto done;
5828 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
5829 get_color_value("TOG_COLOR_TREE_SYMLINK"));
5830 if (err)
5831 goto done;
5832 err = add_color(&s->colors, "/$",
5833 TOG_COLOR_TREE_DIRECTORY,
5834 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
5835 if (err)
5836 goto done;
5838 err = add_color(&s->colors, "\\*$",
5839 TOG_COLOR_TREE_EXECUTABLE,
5840 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
5841 if (err)
5842 goto done;
5844 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
5845 get_color_value("TOG_COLOR_COMMIT"));
5846 if (err)
5847 goto done;
5850 view->show = show_tree_view;
5851 view->input = input_tree_view;
5852 view->close = close_tree_view;
5853 view->search_start = search_start_tree_view;
5854 view->search_next = search_next_tree_view;
5855 done:
5856 free(commit_id_str);
5857 if (commit)
5858 got_object_commit_close(commit);
5859 if (err)
5860 close_tree_view(view);
5861 return err;
5864 static const struct got_error *
5865 close_tree_view(struct tog_view *view)
5867 struct tog_tree_view_state *s = &view->state.tree;
5869 free_colors(&s->colors);
5870 free(s->tree_label);
5871 s->tree_label = NULL;
5872 free(s->commit_id);
5873 s->commit_id = NULL;
5874 free(s->head_ref_name);
5875 s->head_ref_name = NULL;
5876 while (!TAILQ_EMPTY(&s->parents)) {
5877 struct tog_parent_tree *parent;
5878 parent = TAILQ_FIRST(&s->parents);
5879 TAILQ_REMOVE(&s->parents, parent, entry);
5880 if (parent->tree != s->root)
5881 got_object_tree_close(parent->tree);
5882 free(parent);
5885 if (s->tree != NULL && s->tree != s->root)
5886 got_object_tree_close(s->tree);
5887 if (s->root)
5888 got_object_tree_close(s->root);
5889 return NULL;
5892 static const struct got_error *
5893 search_start_tree_view(struct tog_view *view)
5895 struct tog_tree_view_state *s = &view->state.tree;
5897 s->matched_entry = NULL;
5898 return NULL;
5901 static int
5902 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
5904 regmatch_t regmatch;
5906 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
5907 0) == 0;
5910 static const struct got_error *
5911 search_next_tree_view(struct tog_view *view)
5913 struct tog_tree_view_state *s = &view->state.tree;
5914 struct got_tree_entry *te = NULL;
5916 if (!view->searching) {
5917 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5918 return NULL;
5921 if (s->matched_entry) {
5922 if (view->searching == TOG_SEARCH_FORWARD) {
5923 if (s->selected_entry)
5924 te = got_tree_entry_get_next(s->tree,
5925 s->selected_entry);
5926 else
5927 te = got_object_tree_get_first_entry(s->tree);
5928 } else {
5929 if (s->selected_entry == NULL)
5930 te = got_object_tree_get_last_entry(s->tree);
5931 else
5932 te = got_tree_entry_get_prev(s->tree,
5933 s->selected_entry);
5935 } else {
5936 if (s->selected_entry)
5937 te = s->selected_entry;
5938 else if (view->searching == TOG_SEARCH_FORWARD)
5939 te = got_object_tree_get_first_entry(s->tree);
5940 else
5941 te = got_object_tree_get_last_entry(s->tree);
5944 while (1) {
5945 if (te == NULL) {
5946 if (s->matched_entry == NULL) {
5947 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5948 return NULL;
5950 if (view->searching == TOG_SEARCH_FORWARD)
5951 te = got_object_tree_get_first_entry(s->tree);
5952 else
5953 te = got_object_tree_get_last_entry(s->tree);
5956 if (match_tree_entry(te, &view->regex)) {
5957 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5958 s->matched_entry = te;
5959 break;
5962 if (view->searching == TOG_SEARCH_FORWARD)
5963 te = got_tree_entry_get_next(s->tree, te);
5964 else
5965 te = got_tree_entry_get_prev(s->tree, te);
5968 if (s->matched_entry) {
5969 s->first_displayed_entry = s->matched_entry;
5970 s->selected = 0;
5973 return NULL;
5976 static const struct got_error *
5977 show_tree_view(struct tog_view *view)
5979 const struct got_error *err = NULL;
5980 struct tog_tree_view_state *s = &view->state.tree;
5981 char *parent_path;
5983 err = tree_entry_path(&parent_path, &s->parents, NULL);
5984 if (err)
5985 return err;
5987 err = draw_tree_entries(view, parent_path);
5988 free(parent_path);
5990 view_vborder(view);
5991 return err;
5994 static const struct got_error *
5995 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
5997 const struct got_error *err = NULL;
5998 struct tog_tree_view_state *s = &view->state.tree;
5999 struct tog_view *log_view, *ref_view;
6000 struct got_tree_entry *te;
6001 int begin_x = 0, n, nscroll = view->nlines - 3;
6003 switch (ch) {
6004 case 'i':
6005 s->show_ids = !s->show_ids;
6006 view->count = 0;
6007 break;
6008 case 'l':
6009 view->count = 0;
6010 if (!s->selected_entry)
6011 break;
6012 if (view_is_parent_view(view))
6013 begin_x = view_split_begin_x(view->begin_x);
6014 err = log_selected_tree_entry(&log_view, begin_x, s);
6015 view->focussed = 0;
6016 log_view->focussed = 1;
6017 if (view_is_parent_view(view)) {
6018 err = view_close_child(view);
6019 if (err)
6020 return err;
6021 err = view_set_child(view, log_view);
6022 if (err)
6023 return err;
6024 view->focus_child = 1;
6025 } else
6026 *new_view = log_view;
6027 break;
6028 case 'r':
6029 view->count = 0;
6030 if (view_is_parent_view(view))
6031 begin_x = view_split_begin_x(view->begin_x);
6032 ref_view = view_open(view->nlines, view->ncols,
6033 view->begin_y, begin_x, TOG_VIEW_REF);
6034 if (ref_view == NULL)
6035 return got_error_from_errno("view_open");
6036 err = open_ref_view(ref_view, s->repo);
6037 if (err) {
6038 view_close(ref_view);
6039 return err;
6041 view->focussed = 0;
6042 ref_view->focussed = 1;
6043 if (view_is_parent_view(view)) {
6044 err = view_close_child(view);
6045 if (err)
6046 return err;
6047 err = view_set_child(view, ref_view);
6048 if (err)
6049 return err;
6050 view->focus_child = 1;
6051 } else
6052 *new_view = ref_view;
6053 break;
6054 case 'g':
6055 case KEY_HOME:
6056 s->selected = 0;
6057 view->count = 0;
6058 if (s->tree == s->root)
6059 s->first_displayed_entry =
6060 got_object_tree_get_first_entry(s->tree);
6061 else
6062 s->first_displayed_entry = NULL;
6063 break;
6064 case 'G':
6065 case KEY_END:
6066 s->selected = 0;
6067 view->count = 0;
6068 te = got_object_tree_get_last_entry(s->tree);
6069 for (n = 0; n < view->nlines - 3; n++) {
6070 if (te == NULL) {
6071 if(s->tree != s->root) {
6072 s->first_displayed_entry = NULL;
6073 n++;
6075 break;
6077 s->first_displayed_entry = te;
6078 te = got_tree_entry_get_prev(s->tree, te);
6080 if (n > 0)
6081 s->selected = n - 1;
6082 break;
6083 case 'k':
6084 case KEY_UP:
6085 case CTRL('p'):
6086 if (s->selected > 0) {
6087 s->selected--;
6088 break;
6090 tree_scroll_up(s, 1);
6091 if (s->selected_entry == NULL ||
6092 (s->tree == s->root && s->selected_entry ==
6093 got_object_tree_get_first_entry(s->tree)))
6094 view->count = 0;
6095 break;
6096 case CTRL('u'):
6097 case 'u':
6098 nscroll /= 2;
6099 /* FALL THROUGH */
6100 case KEY_PPAGE:
6101 case CTRL('b'):
6102 case 'b':
6103 if (s->tree == s->root) {
6104 if (got_object_tree_get_first_entry(s->tree) ==
6105 s->first_displayed_entry)
6106 s->selected -= MIN(s->selected, nscroll);
6107 } else {
6108 if (s->first_displayed_entry == NULL)
6109 s->selected -= MIN(s->selected, nscroll);
6111 tree_scroll_up(s, MAX(0, nscroll));
6112 if (s->selected_entry == NULL ||
6113 (s->tree == s->root && s->selected_entry ==
6114 got_object_tree_get_first_entry(s->tree)))
6115 view->count = 0;
6116 break;
6117 case 'j':
6118 case KEY_DOWN:
6119 case CTRL('n'):
6120 if (s->selected < s->ndisplayed - 1) {
6121 s->selected++;
6122 break;
6124 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6125 == NULL) {
6126 /* can't scroll any further */
6127 view->count = 0;
6128 break;
6130 tree_scroll_down(s, 1);
6131 break;
6132 case CTRL('d'):
6133 case 'd':
6134 nscroll /= 2;
6135 /* FALL THROUGH */
6136 case KEY_NPAGE:
6137 case CTRL('f'):
6138 case 'f':
6139 case ' ':
6140 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6141 == NULL) {
6142 /* can't scroll any further; move cursor down */
6143 if (s->selected < s->ndisplayed - 1)
6144 s->selected += MIN(nscroll,
6145 s->ndisplayed - s->selected - 1);
6146 else
6147 view->count = 0;
6148 break;
6150 tree_scroll_down(s, nscroll);
6151 break;
6152 case KEY_ENTER:
6153 case '\r':
6154 case KEY_BACKSPACE:
6155 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6156 struct tog_parent_tree *parent;
6157 /* user selected '..' */
6158 if (s->tree == s->root) {
6159 view->count = 0;
6160 break;
6162 parent = TAILQ_FIRST(&s->parents);
6163 TAILQ_REMOVE(&s->parents, parent,
6164 entry);
6165 got_object_tree_close(s->tree);
6166 s->tree = parent->tree;
6167 s->first_displayed_entry =
6168 parent->first_displayed_entry;
6169 s->selected_entry =
6170 parent->selected_entry;
6171 s->selected = parent->selected;
6172 free(parent);
6173 } else if (S_ISDIR(got_tree_entry_get_mode(
6174 s->selected_entry))) {
6175 struct got_tree_object *subtree;
6176 view->count = 0;
6177 err = got_object_open_as_tree(&subtree, s->repo,
6178 got_tree_entry_get_id(s->selected_entry));
6179 if (err)
6180 break;
6181 err = tree_view_visit_subtree(s, subtree);
6182 if (err) {
6183 got_object_tree_close(subtree);
6184 break;
6186 } else if (S_ISREG(got_tree_entry_get_mode(
6187 s->selected_entry))) {
6188 struct tog_view *blame_view;
6189 int begin_x = view_is_parent_view(view) ?
6190 view_split_begin_x(view->begin_x) : 0;
6192 err = blame_tree_entry(&blame_view, begin_x,
6193 s->selected_entry, &s->parents,
6194 s->commit_id, s->repo);
6195 if (err)
6196 break;
6197 view->count = 0;
6198 view->focussed = 0;
6199 blame_view->focussed = 1;
6200 if (view_is_parent_view(view)) {
6201 err = view_close_child(view);
6202 if (err)
6203 return err;
6204 err = view_set_child(view, blame_view);
6205 if (err)
6206 return err;
6207 view->focus_child = 1;
6208 } else
6209 *new_view = blame_view;
6211 break;
6212 case KEY_RESIZE:
6213 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6214 s->selected = view->nlines - 4;
6215 view->count = 0;
6216 break;
6217 default:
6218 view->count = 0;
6219 break;
6222 return err;
6225 __dead static void
6226 usage_tree(void)
6228 endwin();
6229 fprintf(stderr,
6230 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6231 getprogname());
6232 exit(1);
6235 static const struct got_error *
6236 cmd_tree(int argc, char *argv[])
6238 const struct got_error *error;
6239 struct got_repository *repo = NULL;
6240 struct got_worktree *worktree = NULL;
6241 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6242 struct got_object_id *commit_id = NULL;
6243 struct got_commit_object *commit = NULL;
6244 const char *commit_id_arg = NULL;
6245 char *label = NULL;
6246 struct got_reference *ref = NULL;
6247 const char *head_ref_name = NULL;
6248 int ch;
6249 struct tog_view *view;
6250 int *pack_fds = NULL;
6252 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6253 switch (ch) {
6254 case 'c':
6255 commit_id_arg = optarg;
6256 break;
6257 case 'r':
6258 repo_path = realpath(optarg, NULL);
6259 if (repo_path == NULL)
6260 return got_error_from_errno2("realpath",
6261 optarg);
6262 break;
6263 default:
6264 usage_tree();
6265 /* NOTREACHED */
6269 argc -= optind;
6270 argv += optind;
6272 if (argc > 1)
6273 usage_tree();
6275 error = got_repo_pack_fds_open(&pack_fds);
6276 if (error != NULL)
6277 goto done;
6279 if (repo_path == NULL) {
6280 cwd = getcwd(NULL, 0);
6281 if (cwd == NULL)
6282 return got_error_from_errno("getcwd");
6283 error = got_worktree_open(&worktree, cwd);
6284 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6285 goto done;
6286 if (worktree)
6287 repo_path =
6288 strdup(got_worktree_get_repo_path(worktree));
6289 else
6290 repo_path = strdup(cwd);
6291 if (repo_path == NULL) {
6292 error = got_error_from_errno("strdup");
6293 goto done;
6297 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6298 if (error != NULL)
6299 goto done;
6301 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
6302 repo, worktree);
6303 if (error)
6304 goto done;
6306 init_curses();
6308 error = apply_unveil(got_repo_get_path(repo), NULL);
6309 if (error)
6310 goto done;
6312 error = tog_load_refs(repo, 0);
6313 if (error)
6314 goto done;
6316 if (commit_id_arg == NULL) {
6317 error = got_repo_match_object_id(&commit_id, &label,
6318 worktree ? got_worktree_get_head_ref_name(worktree) :
6319 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6320 if (error)
6321 goto done;
6322 head_ref_name = label;
6323 } else {
6324 error = got_ref_open(&ref, repo, commit_id_arg, 0);
6325 if (error == NULL)
6326 head_ref_name = got_ref_get_name(ref);
6327 else if (error->code != GOT_ERR_NOT_REF)
6328 goto done;
6329 error = got_repo_match_object_id(&commit_id, NULL,
6330 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6331 if (error)
6332 goto done;
6335 error = got_object_open_as_commit(&commit, repo, commit_id);
6336 if (error)
6337 goto done;
6339 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
6340 if (view == NULL) {
6341 error = got_error_from_errno("view_open");
6342 goto done;
6344 error = open_tree_view(view, commit_id, head_ref_name, repo);
6345 if (error)
6346 goto done;
6347 if (!got_path_is_root_dir(in_repo_path)) {
6348 error = tree_view_walk_path(&view->state.tree, commit,
6349 in_repo_path);
6350 if (error)
6351 goto done;
6354 if (worktree) {
6355 /* Release work tree lock. */
6356 got_worktree_close(worktree);
6357 worktree = NULL;
6359 error = view_loop(view);
6360 done:
6361 free(repo_path);
6362 free(cwd);
6363 free(commit_id);
6364 free(label);
6365 if (ref)
6366 got_ref_close(ref);
6367 if (repo) {
6368 const struct got_error *close_err = got_repo_close(repo);
6369 if (error == NULL)
6370 error = close_err;
6372 if (pack_fds) {
6373 const struct got_error *pack_err =
6374 got_repo_pack_fds_close(pack_fds);
6375 if (error == NULL)
6376 error = pack_err;
6378 tog_free_refs();
6379 return error;
6382 static const struct got_error *
6383 ref_view_load_refs(struct tog_ref_view_state *s)
6385 struct got_reflist_entry *sre;
6386 struct tog_reflist_entry *re;
6388 s->nrefs = 0;
6389 TAILQ_FOREACH(sre, &tog_refs, entry) {
6390 if (strncmp(got_ref_get_name(sre->ref),
6391 "refs/got/", 9) == 0 &&
6392 strncmp(got_ref_get_name(sre->ref),
6393 "refs/got/backup/", 16) != 0)
6394 continue;
6396 re = malloc(sizeof(*re));
6397 if (re == NULL)
6398 return got_error_from_errno("malloc");
6400 re->ref = got_ref_dup(sre->ref);
6401 if (re->ref == NULL)
6402 return got_error_from_errno("got_ref_dup");
6403 re->idx = s->nrefs++;
6404 TAILQ_INSERT_TAIL(&s->refs, re, entry);
6407 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6408 return NULL;
6411 static void
6412 ref_view_free_refs(struct tog_ref_view_state *s)
6414 struct tog_reflist_entry *re;
6416 while (!TAILQ_EMPTY(&s->refs)) {
6417 re = TAILQ_FIRST(&s->refs);
6418 TAILQ_REMOVE(&s->refs, re, entry);
6419 got_ref_close(re->ref);
6420 free(re);
6424 static const struct got_error *
6425 open_ref_view(struct tog_view *view, struct got_repository *repo)
6427 const struct got_error *err = NULL;
6428 struct tog_ref_view_state *s = &view->state.ref;
6430 s->selected_entry = 0;
6431 s->repo = repo;
6433 TAILQ_INIT(&s->refs);
6434 STAILQ_INIT(&s->colors);
6436 err = ref_view_load_refs(s);
6437 if (err)
6438 return err;
6440 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6441 err = add_color(&s->colors, "^refs/heads/",
6442 TOG_COLOR_REFS_HEADS,
6443 get_color_value("TOG_COLOR_REFS_HEADS"));
6444 if (err)
6445 goto done;
6447 err = add_color(&s->colors, "^refs/tags/",
6448 TOG_COLOR_REFS_TAGS,
6449 get_color_value("TOG_COLOR_REFS_TAGS"));
6450 if (err)
6451 goto done;
6453 err = add_color(&s->colors, "^refs/remotes/",
6454 TOG_COLOR_REFS_REMOTES,
6455 get_color_value("TOG_COLOR_REFS_REMOTES"));
6456 if (err)
6457 goto done;
6459 err = add_color(&s->colors, "^refs/got/backup/",
6460 TOG_COLOR_REFS_BACKUP,
6461 get_color_value("TOG_COLOR_REFS_BACKUP"));
6462 if (err)
6463 goto done;
6466 view->show = show_ref_view;
6467 view->input = input_ref_view;
6468 view->close = close_ref_view;
6469 view->search_start = search_start_ref_view;
6470 view->search_next = search_next_ref_view;
6471 done:
6472 if (err)
6473 free_colors(&s->colors);
6474 return err;
6477 static const struct got_error *
6478 close_ref_view(struct tog_view *view)
6480 struct tog_ref_view_state *s = &view->state.ref;
6482 ref_view_free_refs(s);
6483 free_colors(&s->colors);
6485 return NULL;
6488 static const struct got_error *
6489 resolve_reflist_entry(struct got_object_id **commit_id,
6490 struct tog_reflist_entry *re, struct got_repository *repo)
6492 const struct got_error *err = NULL;
6493 struct got_object_id *obj_id;
6494 struct got_tag_object *tag = NULL;
6495 int obj_type;
6497 *commit_id = NULL;
6499 err = got_ref_resolve(&obj_id, repo, re->ref);
6500 if (err)
6501 return err;
6503 err = got_object_get_type(&obj_type, repo, obj_id);
6504 if (err)
6505 goto done;
6507 switch (obj_type) {
6508 case GOT_OBJ_TYPE_COMMIT:
6509 *commit_id = obj_id;
6510 break;
6511 case GOT_OBJ_TYPE_TAG:
6512 err = got_object_open_as_tag(&tag, repo, obj_id);
6513 if (err)
6514 goto done;
6515 free(obj_id);
6516 err = got_object_get_type(&obj_type, repo,
6517 got_object_tag_get_object_id(tag));
6518 if (err)
6519 goto done;
6520 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
6521 err = got_error(GOT_ERR_OBJ_TYPE);
6522 goto done;
6524 *commit_id = got_object_id_dup(
6525 got_object_tag_get_object_id(tag));
6526 if (*commit_id == NULL) {
6527 err = got_error_from_errno("got_object_id_dup");
6528 goto done;
6530 break;
6531 default:
6532 err = got_error(GOT_ERR_OBJ_TYPE);
6533 break;
6536 done:
6537 if (tag)
6538 got_object_tag_close(tag);
6539 if (err) {
6540 free(*commit_id);
6541 *commit_id = NULL;
6543 return err;
6546 static const struct got_error *
6547 log_ref_entry(struct tog_view **new_view, int begin_x,
6548 struct tog_reflist_entry *re, struct got_repository *repo)
6550 struct tog_view *log_view;
6551 const struct got_error *err = NULL;
6552 struct got_object_id *commit_id = NULL;
6554 *new_view = NULL;
6556 err = resolve_reflist_entry(&commit_id, re, repo);
6557 if (err) {
6558 if (err->code != GOT_ERR_OBJ_TYPE)
6559 return err;
6560 else
6561 return NULL;
6564 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
6565 if (log_view == NULL) {
6566 err = got_error_from_errno("view_open");
6567 goto done;
6570 err = open_log_view(log_view, commit_id, repo,
6571 got_ref_get_name(re->ref), "", 0);
6572 done:
6573 if (err)
6574 view_close(log_view);
6575 else
6576 *new_view = log_view;
6577 free(commit_id);
6578 return err;
6581 static void
6582 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
6584 struct tog_reflist_entry *re;
6585 int i = 0;
6587 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
6588 return;
6590 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
6591 while (i++ < maxscroll) {
6592 if (re == NULL)
6593 break;
6594 s->first_displayed_entry = re;
6595 re = TAILQ_PREV(re, tog_reflist_head, entry);
6599 static void
6600 ref_scroll_down(struct tog_ref_view_state *s, int maxscroll)
6602 struct tog_reflist_entry *next, *last;
6603 int n = 0;
6605 if (s->first_displayed_entry)
6606 next = TAILQ_NEXT(s->first_displayed_entry, entry);
6607 else
6608 next = TAILQ_FIRST(&s->refs);
6610 last = s->last_displayed_entry;
6611 while (next && last && n++ < maxscroll) {
6612 last = TAILQ_NEXT(last, entry);
6613 if (last) {
6614 s->first_displayed_entry = next;
6615 next = TAILQ_NEXT(next, entry);
6620 static const struct got_error *
6621 search_start_ref_view(struct tog_view *view)
6623 struct tog_ref_view_state *s = &view->state.ref;
6625 s->matched_entry = NULL;
6626 return NULL;
6629 static int
6630 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
6632 regmatch_t regmatch;
6634 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
6635 0) == 0;
6638 static const struct got_error *
6639 search_next_ref_view(struct tog_view *view)
6641 struct tog_ref_view_state *s = &view->state.ref;
6642 struct tog_reflist_entry *re = NULL;
6644 if (!view->searching) {
6645 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6646 return NULL;
6649 if (s->matched_entry) {
6650 if (view->searching == TOG_SEARCH_FORWARD) {
6651 if (s->selected_entry)
6652 re = TAILQ_NEXT(s->selected_entry, entry);
6653 else
6654 re = TAILQ_PREV(s->selected_entry,
6655 tog_reflist_head, entry);
6656 } else {
6657 if (s->selected_entry == NULL)
6658 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6659 else
6660 re = TAILQ_PREV(s->selected_entry,
6661 tog_reflist_head, entry);
6663 } else {
6664 if (s->selected_entry)
6665 re = s->selected_entry;
6666 else if (view->searching == TOG_SEARCH_FORWARD)
6667 re = TAILQ_FIRST(&s->refs);
6668 else
6669 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6672 while (1) {
6673 if (re == NULL) {
6674 if (s->matched_entry == NULL) {
6675 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6676 return NULL;
6678 if (view->searching == TOG_SEARCH_FORWARD)
6679 re = TAILQ_FIRST(&s->refs);
6680 else
6681 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6684 if (match_reflist_entry(re, &view->regex)) {
6685 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6686 s->matched_entry = re;
6687 break;
6690 if (view->searching == TOG_SEARCH_FORWARD)
6691 re = TAILQ_NEXT(re, entry);
6692 else
6693 re = TAILQ_PREV(re, tog_reflist_head, entry);
6696 if (s->matched_entry) {
6697 s->first_displayed_entry = s->matched_entry;
6698 s->selected = 0;
6701 return NULL;
6704 static const struct got_error *
6705 show_ref_view(struct tog_view *view)
6707 const struct got_error *err = NULL;
6708 struct tog_ref_view_state *s = &view->state.ref;
6709 struct tog_reflist_entry *re;
6710 char *line = NULL;
6711 wchar_t *wline;
6712 struct tog_color *tc;
6713 int width, n;
6714 int limit = view->nlines;
6716 werase(view->window);
6718 s->ndisplayed = 0;
6720 if (limit == 0)
6721 return NULL;
6723 re = s->first_displayed_entry;
6725 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
6726 s->nrefs) == -1)
6727 return got_error_from_errno("asprintf");
6729 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6730 if (err) {
6731 free(line);
6732 return err;
6734 if (view_needs_focus_indication(view))
6735 wstandout(view->window);
6736 waddwstr(view->window, wline);
6737 if (view_needs_focus_indication(view))
6738 wstandend(view->window);
6739 free(wline);
6740 wline = NULL;
6741 free(line);
6742 line = NULL;
6743 if (width < view->ncols - 1)
6744 waddch(view->window, '\n');
6745 if (--limit <= 0)
6746 return NULL;
6748 n = 0;
6749 while (re && limit > 0) {
6750 char *line = NULL;
6751 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
6753 if (s->show_date) {
6754 struct got_commit_object *ci;
6755 struct got_tag_object *tag;
6756 struct got_object_id *id;
6757 struct tm tm;
6758 time_t t;
6760 err = got_ref_resolve(&id, s->repo, re->ref);
6761 if (err)
6762 return err;
6763 err = got_object_open_as_tag(&tag, s->repo, id);
6764 if (err) {
6765 if (err->code != GOT_ERR_OBJ_TYPE) {
6766 free(id);
6767 return err;
6769 err = got_object_open_as_commit(&ci, s->repo,
6770 id);
6771 if (err) {
6772 free(id);
6773 return err;
6775 t = got_object_commit_get_committer_time(ci);
6776 got_object_commit_close(ci);
6777 } else {
6778 t = got_object_tag_get_tagger_time(tag);
6779 got_object_tag_close(tag);
6781 free(id);
6782 if (gmtime_r(&t, &tm) == NULL)
6783 return got_error_from_errno("gmtime_r");
6784 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
6785 return got_error(GOT_ERR_NO_SPACE);
6787 if (got_ref_is_symbolic(re->ref)) {
6788 if (asprintf(&line, "%s%s -> %s", s->show_date ?
6789 ymd : "", got_ref_get_name(re->ref),
6790 got_ref_get_symref_target(re->ref)) == -1)
6791 return got_error_from_errno("asprintf");
6792 } else if (s->show_ids) {
6793 struct got_object_id *id;
6794 char *id_str;
6795 err = got_ref_resolve(&id, s->repo, re->ref);
6796 if (err)
6797 return err;
6798 err = got_object_id_str(&id_str, id);
6799 if (err) {
6800 free(id);
6801 return err;
6803 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
6804 got_ref_get_name(re->ref), id_str) == -1) {
6805 err = got_error_from_errno("asprintf");
6806 free(id);
6807 free(id_str);
6808 return err;
6810 free(id);
6811 free(id_str);
6812 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
6813 got_ref_get_name(re->ref)) == -1)
6814 return got_error_from_errno("asprintf");
6816 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6817 0, 0);
6818 if (err) {
6819 free(line);
6820 return err;
6822 if (n == s->selected) {
6823 if (view->focussed)
6824 wstandout(view->window);
6825 s->selected_entry = re;
6827 tc = match_color(&s->colors, got_ref_get_name(re->ref));
6828 if (tc)
6829 wattr_on(view->window,
6830 COLOR_PAIR(tc->colorpair), NULL);
6831 waddwstr(view->window, wline);
6832 if (tc)
6833 wattr_off(view->window,
6834 COLOR_PAIR(tc->colorpair), NULL);
6835 if (width < view->ncols - 1)
6836 waddch(view->window, '\n');
6837 if (n == s->selected && view->focussed)
6838 wstandend(view->window);
6839 free(line);
6840 free(wline);
6841 wline = NULL;
6842 n++;
6843 s->ndisplayed++;
6844 s->last_displayed_entry = re;
6846 limit--;
6847 re = TAILQ_NEXT(re, entry);
6850 view_vborder(view);
6851 return err;
6854 static const struct got_error *
6855 browse_ref_tree(struct tog_view **new_view, int begin_x,
6856 struct tog_reflist_entry *re, struct got_repository *repo)
6858 const struct got_error *err = NULL;
6859 struct got_object_id *commit_id = NULL;
6860 struct tog_view *tree_view;
6862 *new_view = NULL;
6864 err = resolve_reflist_entry(&commit_id, re, repo);
6865 if (err) {
6866 if (err->code != GOT_ERR_OBJ_TYPE)
6867 return err;
6868 else
6869 return NULL;
6873 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
6874 if (tree_view == NULL) {
6875 err = got_error_from_errno("view_open");
6876 goto done;
6879 err = open_tree_view(tree_view, commit_id,
6880 got_ref_get_name(re->ref), repo);
6881 if (err)
6882 goto done;
6884 *new_view = tree_view;
6885 done:
6886 free(commit_id);
6887 return err;
6889 static const struct got_error *
6890 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
6892 const struct got_error *err = NULL;
6893 struct tog_ref_view_state *s = &view->state.ref;
6894 struct tog_view *log_view, *tree_view;
6895 struct tog_reflist_entry *re;
6896 int begin_x = 0, n, nscroll = view->nlines - 1;
6898 switch (ch) {
6899 case 'i':
6900 s->show_ids = !s->show_ids;
6901 view->count = 0;
6902 break;
6903 case 'm':
6904 s->show_date = !s->show_date;
6905 view->count = 0;
6906 break;
6907 case 'o':
6908 s->sort_by_date = !s->sort_by_date;
6909 view->count = 0;
6910 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
6911 got_ref_cmp_by_commit_timestamp_descending :
6912 tog_ref_cmp_by_name, s->repo);
6913 if (err)
6914 break;
6915 got_reflist_object_id_map_free(tog_refs_idmap);
6916 err = got_reflist_object_id_map_create(&tog_refs_idmap,
6917 &tog_refs, s->repo);
6918 if (err)
6919 break;
6920 ref_view_free_refs(s);
6921 err = ref_view_load_refs(s);
6922 break;
6923 case KEY_ENTER:
6924 case '\r':
6925 view->count = 0;
6926 if (!s->selected_entry)
6927 break;
6928 if (view_is_parent_view(view))
6929 begin_x = view_split_begin_x(view->begin_x);
6930 err = log_ref_entry(&log_view, begin_x, s->selected_entry,
6931 s->repo);
6932 view->focussed = 0;
6933 log_view->focussed = 1;
6934 if (view_is_parent_view(view)) {
6935 err = view_close_child(view);
6936 if (err)
6937 return err;
6938 err = view_set_child(view, log_view);
6939 if (err)
6940 return err;
6941 view->focus_child = 1;
6942 } else
6943 *new_view = log_view;
6944 break;
6945 case 't':
6946 view->count = 0;
6947 if (!s->selected_entry)
6948 break;
6949 if (view_is_parent_view(view))
6950 begin_x = view_split_begin_x(view->begin_x);
6951 err = browse_ref_tree(&tree_view, begin_x, s->selected_entry,
6952 s->repo);
6953 if (err || tree_view == NULL)
6954 break;
6955 view->focussed = 0;
6956 tree_view->focussed = 1;
6957 if (view_is_parent_view(view)) {
6958 err = view_close_child(view);
6959 if (err)
6960 return err;
6961 err = view_set_child(view, tree_view);
6962 if (err)
6963 return err;
6964 view->focus_child = 1;
6965 } else
6966 *new_view = tree_view;
6967 break;
6968 case 'g':
6969 case KEY_HOME:
6970 s->selected = 0;
6971 view->count = 0;
6972 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6973 break;
6974 case 'G':
6975 case KEY_END:
6976 s->selected = 0;
6977 view->count = 0;
6978 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6979 for (n = 0; n < view->nlines - 1; n++) {
6980 if (re == NULL)
6981 break;
6982 s->first_displayed_entry = re;
6983 re = TAILQ_PREV(re, tog_reflist_head, entry);
6985 if (n > 0)
6986 s->selected = n - 1;
6987 break;
6988 case 'k':
6989 case KEY_UP:
6990 case CTRL('p'):
6991 if (s->selected > 0) {
6992 s->selected--;
6993 break;
6995 ref_scroll_up(s, 1);
6996 if (s->selected_entry == TAILQ_FIRST(&s->refs))
6997 view->count = 0;
6998 break;
6999 case CTRL('u'):
7000 case 'u':
7001 nscroll /= 2;
7002 /* FALL THROUGH */
7003 case KEY_PPAGE:
7004 case CTRL('b'):
7005 case 'b':
7006 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7007 s->selected -= MIN(nscroll, s->selected);
7008 ref_scroll_up(s, MAX(0, nscroll));
7009 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7010 view->count = 0;
7011 break;
7012 case 'j':
7013 case KEY_DOWN:
7014 case CTRL('n'):
7015 if (s->selected < s->ndisplayed - 1) {
7016 s->selected++;
7017 break;
7019 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7020 /* can't scroll any further */
7021 view->count = 0;
7022 break;
7024 ref_scroll_down(s, 1);
7025 break;
7026 case CTRL('d'):
7027 case 'd':
7028 nscroll /= 2;
7029 /* FALL THROUGH */
7030 case KEY_NPAGE:
7031 case CTRL('f'):
7032 case 'f':
7033 case ' ':
7034 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7035 /* can't scroll any further; move cursor down */
7036 if (s->selected < s->ndisplayed - 1)
7037 s->selected += MIN(nscroll,
7038 s->ndisplayed - s->selected - 1);
7039 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7040 s->selected += s->ndisplayed - s->selected - 1;
7041 view->count = 0;
7042 break;
7044 ref_scroll_down(s, nscroll);
7045 break;
7046 case CTRL('l'):
7047 view->count = 0;
7048 tog_free_refs();
7049 err = tog_load_refs(s->repo, s->sort_by_date);
7050 if (err)
7051 break;
7052 ref_view_free_refs(s);
7053 err = ref_view_load_refs(s);
7054 break;
7055 case KEY_RESIZE:
7056 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7057 s->selected = view->nlines - 2;
7058 break;
7059 default:
7060 view->count = 0;
7061 break;
7064 return err;
7067 __dead static void
7068 usage_ref(void)
7070 endwin();
7071 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7072 getprogname());
7073 exit(1);
7076 static const struct got_error *
7077 cmd_ref(int argc, char *argv[])
7079 const struct got_error *error;
7080 struct got_repository *repo = NULL;
7081 struct got_worktree *worktree = NULL;
7082 char *cwd = NULL, *repo_path = NULL;
7083 int ch;
7084 struct tog_view *view;
7085 int *pack_fds = NULL;
7087 while ((ch = getopt(argc, argv, "r:")) != -1) {
7088 switch (ch) {
7089 case 'r':
7090 repo_path = realpath(optarg, NULL);
7091 if (repo_path == NULL)
7092 return got_error_from_errno2("realpath",
7093 optarg);
7094 break;
7095 default:
7096 usage_ref();
7097 /* NOTREACHED */
7101 argc -= optind;
7102 argv += optind;
7104 if (argc > 1)
7105 usage_ref();
7107 error = got_repo_pack_fds_open(&pack_fds);
7108 if (error != NULL)
7109 goto done;
7111 if (repo_path == NULL) {
7112 cwd = getcwd(NULL, 0);
7113 if (cwd == NULL)
7114 return got_error_from_errno("getcwd");
7115 error = got_worktree_open(&worktree, cwd);
7116 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7117 goto done;
7118 if (worktree)
7119 repo_path =
7120 strdup(got_worktree_get_repo_path(worktree));
7121 else
7122 repo_path = strdup(cwd);
7123 if (repo_path == NULL) {
7124 error = got_error_from_errno("strdup");
7125 goto done;
7129 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7130 if (error != NULL)
7131 goto done;
7133 init_curses();
7135 error = apply_unveil(got_repo_get_path(repo), NULL);
7136 if (error)
7137 goto done;
7139 error = tog_load_refs(repo, 0);
7140 if (error)
7141 goto done;
7143 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7144 if (view == NULL) {
7145 error = got_error_from_errno("view_open");
7146 goto done;
7149 error = open_ref_view(view, repo);
7150 if (error)
7151 goto done;
7153 if (worktree) {
7154 /* Release work tree lock. */
7155 got_worktree_close(worktree);
7156 worktree = NULL;
7158 error = view_loop(view);
7159 done:
7160 free(repo_path);
7161 free(cwd);
7162 if (repo) {
7163 const struct got_error *close_err = got_repo_close(repo);
7164 if (close_err)
7165 error = close_err;
7167 if (pack_fds) {
7168 const struct got_error *pack_err =
7169 got_repo_pack_fds_close(pack_fds);
7170 if (error == NULL)
7171 error = pack_err;
7173 tog_free_refs();
7174 return error;
7177 static void
7178 list_commands(FILE *fp)
7180 size_t i;
7182 fprintf(fp, "commands:");
7183 for (i = 0; i < nitems(tog_commands); i++) {
7184 const struct tog_cmd *cmd = &tog_commands[i];
7185 fprintf(fp, " %s", cmd->name);
7187 fputc('\n', fp);
7190 __dead static void
7191 usage(int hflag, int status)
7193 FILE *fp = (status == 0) ? stdout : stderr;
7195 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
7196 getprogname());
7197 if (hflag) {
7198 fprintf(fp, "lazy usage: %s path\n", getprogname());
7199 list_commands(fp);
7201 exit(status);
7204 static char **
7205 make_argv(int argc, ...)
7207 va_list ap;
7208 char **argv;
7209 int i;
7211 va_start(ap, argc);
7213 argv = calloc(argc, sizeof(char *));
7214 if (argv == NULL)
7215 err(1, "calloc");
7216 for (i = 0; i < argc; i++) {
7217 argv[i] = strdup(va_arg(ap, char *));
7218 if (argv[i] == NULL)
7219 err(1, "strdup");
7222 va_end(ap);
7223 return argv;
7227 * Try to convert 'tog path' into a 'tog log path' command.
7228 * The user could simply have mistyped the command rather than knowingly
7229 * provided a path. So check whether argv[0] can in fact be resolved
7230 * to a path in the HEAD commit and print a special error if not.
7231 * This hack is for mpi@ <3
7233 static const struct got_error *
7234 tog_log_with_path(int argc, char *argv[])
7236 const struct got_error *error = NULL, *close_err;
7237 const struct tog_cmd *cmd = NULL;
7238 struct got_repository *repo = NULL;
7239 struct got_worktree *worktree = NULL;
7240 struct got_object_id *commit_id = NULL, *id = NULL;
7241 struct got_commit_object *commit = NULL;
7242 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7243 char *commit_id_str = NULL, **cmd_argv = NULL;
7244 int *pack_fds = NULL;
7246 cwd = getcwd(NULL, 0);
7247 if (cwd == NULL)
7248 return got_error_from_errno("getcwd");
7250 error = got_repo_pack_fds_open(&pack_fds);
7251 if (error != NULL)
7252 goto done;
7254 error = got_worktree_open(&worktree, cwd);
7255 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7256 goto done;
7258 if (worktree)
7259 repo_path = strdup(got_worktree_get_repo_path(worktree));
7260 else
7261 repo_path = strdup(cwd);
7262 if (repo_path == NULL) {
7263 error = got_error_from_errno("strdup");
7264 goto done;
7267 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7268 if (error != NULL)
7269 goto done;
7271 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7272 repo, worktree);
7273 if (error)
7274 goto done;
7276 error = tog_load_refs(repo, 0);
7277 if (error)
7278 goto done;
7279 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
7280 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
7281 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7282 if (error)
7283 goto done;
7285 if (worktree) {
7286 got_worktree_close(worktree);
7287 worktree = NULL;
7290 error = got_object_open_as_commit(&commit, repo, commit_id);
7291 if (error)
7292 goto done;
7294 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
7295 if (error) {
7296 if (error->code != GOT_ERR_NO_TREE_ENTRY)
7297 goto done;
7298 fprintf(stderr, "%s: '%s' is no known command or path\n",
7299 getprogname(), argv[0]);
7300 usage(1, 1);
7301 /* not reached */
7304 close_err = got_repo_close(repo);
7305 if (error == NULL)
7306 error = close_err;
7307 repo = NULL;
7309 error = got_object_id_str(&commit_id_str, commit_id);
7310 if (error)
7311 goto done;
7313 cmd = &tog_commands[0]; /* log */
7314 argc = 4;
7315 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
7316 error = cmd->cmd_main(argc, cmd_argv);
7317 done:
7318 if (repo) {
7319 close_err = got_repo_close(repo);
7320 if (error == NULL)
7321 error = close_err;
7323 if (commit)
7324 got_object_commit_close(commit);
7325 if (worktree)
7326 got_worktree_close(worktree);
7327 if (pack_fds) {
7328 const struct got_error *pack_err =
7329 got_repo_pack_fds_close(pack_fds);
7330 if (error == NULL)
7331 error = pack_err;
7333 free(id);
7334 free(commit_id_str);
7335 free(commit_id);
7336 free(cwd);
7337 free(repo_path);
7338 free(in_repo_path);
7339 if (cmd_argv) {
7340 int i;
7341 for (i = 0; i < argc; i++)
7342 free(cmd_argv[i]);
7343 free(cmd_argv);
7345 tog_free_refs();
7346 return error;
7349 int
7350 main(int argc, char *argv[])
7352 const struct got_error *error = NULL;
7353 const struct tog_cmd *cmd = NULL;
7354 int ch, hflag = 0, Vflag = 0;
7355 char **cmd_argv = NULL;
7356 static const struct option longopts[] = {
7357 { "version", no_argument, NULL, 'V' },
7358 { NULL, 0, NULL, 0}
7361 setlocale(LC_CTYPE, "");
7363 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
7364 switch (ch) {
7365 case 'h':
7366 hflag = 1;
7367 break;
7368 case 'V':
7369 Vflag = 1;
7370 break;
7371 default:
7372 usage(hflag, 1);
7373 /* NOTREACHED */
7377 argc -= optind;
7378 argv += optind;
7379 optind = 1;
7380 optreset = 1;
7382 if (Vflag) {
7383 got_version_print_str();
7384 return 0;
7387 #ifndef PROFILE
7388 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
7389 NULL) == -1)
7390 err(1, "pledge");
7391 #endif
7393 if (argc == 0) {
7394 if (hflag)
7395 usage(hflag, 0);
7396 /* Build an argument vector which runs a default command. */
7397 cmd = &tog_commands[0];
7398 argc = 1;
7399 cmd_argv = make_argv(argc, cmd->name);
7400 } else {
7401 size_t i;
7403 /* Did the user specify a command? */
7404 for (i = 0; i < nitems(tog_commands); i++) {
7405 if (strncmp(tog_commands[i].name, argv[0],
7406 strlen(argv[0])) == 0) {
7407 cmd = &tog_commands[i];
7408 break;
7413 if (cmd == NULL) {
7414 if (argc != 1)
7415 usage(0, 1);
7416 /* No command specified; try log with a path */
7417 error = tog_log_with_path(argc, argv);
7418 } else {
7419 if (hflag)
7420 cmd->cmd_usage();
7421 else
7422 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
7425 endwin();
7426 putchar('\n');
7427 if (cmd_argv) {
7428 int i;
7429 for (i = 0; i < argc; i++)
7430 free(cmd_argv[i]);
7431 free(cmd_argv);
7434 if (error && error->code != GOT_ERR_CANCELLED)
7435 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7436 return 0;