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 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 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 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 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]|(blob|file) [-+] |"
3977 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
3978 get_color_value("TOG_COLOR_DIFF_META"));
3979 if (err)
3980 goto done;
3982 err = add_color(&s->colors,
3983 "^(from|via): ", TOG_COLOR_AUTHOR,
3984 get_color_value("TOG_COLOR_AUTHOR"));
3985 if (err)
3986 goto done;
3988 err = add_color(&s->colors,
3989 "^date: ", TOG_COLOR_DATE,
3990 get_color_value("TOG_COLOR_DATE"));
3991 if (err)
3992 goto done;
3995 if (log_view && view_is_splitscreen(view))
3996 show_log_view(log_view); /* draw vborder */
3997 diff_view_indicate_progress(view);
3999 err = create_diff(s);
4001 view->show = show_diff_view;
4002 view->input = input_diff_view;
4003 view->close = close_diff_view;
4004 view->search_start = search_start_diff_view;
4005 view->search_next = search_next_diff_view;
4006 done:
4007 if (err)
4008 close_diff_view(view);
4009 return err;
4012 static const struct got_error *
4013 show_diff_view(struct tog_view *view)
4015 const struct got_error *err;
4016 struct tog_diff_view_state *s = &view->state.diff;
4017 char *id_str1 = NULL, *id_str2, *header;
4018 const char *label1, *label2;
4020 if (s->id1) {
4021 err = got_object_id_str(&id_str1, s->id1);
4022 if (err)
4023 return err;
4024 label1 = s->label1 ? : id_str1;
4025 } else
4026 label1 = "/dev/null";
4028 err = got_object_id_str(&id_str2, s->id2);
4029 if (err)
4030 return err;
4031 label2 = s->label2 ? : id_str2;
4033 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4034 err = got_error_from_errno("asprintf");
4035 free(id_str1);
4036 free(id_str2);
4037 return err;
4039 free(id_str1);
4040 free(id_str2);
4042 err = draw_file(view, header);
4043 free(header);
4044 return err;
4047 static const struct got_error *
4048 set_selected_commit(struct tog_diff_view_state *s,
4049 struct commit_queue_entry *entry)
4051 const struct got_error *err;
4052 const struct got_object_id_queue *parent_ids;
4053 struct got_commit_object *selected_commit;
4054 struct got_object_qid *pid;
4056 free(s->id2);
4057 s->id2 = got_object_id_dup(entry->id);
4058 if (s->id2 == NULL)
4059 return got_error_from_errno("got_object_id_dup");
4061 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4062 if (err)
4063 return err;
4064 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4065 free(s->id1);
4066 pid = STAILQ_FIRST(parent_ids);
4067 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4068 got_object_commit_close(selected_commit);
4069 return NULL;
4072 static const struct got_error *
4073 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4075 const struct got_error *err = NULL;
4076 struct tog_diff_view_state *s = &view->state.diff;
4077 struct tog_log_view_state *ls;
4078 struct commit_queue_entry *old_selected_entry;
4079 char *line = NULL;
4080 size_t linesize = 0;
4081 ssize_t linelen;
4082 int i, nscroll = view->nlines - 1;
4084 switch (ch) {
4085 case '0':
4086 view->x = 0;
4087 break;
4088 case '$':
4089 view->x = MAX(view->maxx - view->ncols / 3, 0);
4090 view->count = 0;
4091 break;
4092 case KEY_RIGHT:
4093 case 'l':
4094 if (view->x + view->ncols / 3 < view->maxx)
4095 view->x += 2; /* move two columns right */
4096 else
4097 view->count = 0;
4098 break;
4099 case KEY_LEFT:
4100 case 'h':
4101 view->x -= MIN(view->x, 2); /* move two columns back */
4102 if (view->x <= 0)
4103 view->count = 0;
4104 break;
4105 case 'a':
4106 case 'w':
4107 if (ch == 'a')
4108 s->force_text_diff = !s->force_text_diff;
4109 if (ch == 'w')
4110 s->ignore_whitespace = !s->ignore_whitespace;
4111 wclear(view->window);
4112 s->first_displayed_line = 1;
4113 s->last_displayed_line = view->nlines;
4114 s->matched_line = 0;
4115 diff_view_indicate_progress(view);
4116 err = create_diff(s);
4117 view->count = 0;
4118 break;
4119 case 'g':
4120 case KEY_HOME:
4121 s->first_displayed_line = 1;
4122 view->count = 0;
4123 break;
4124 case 'G':
4125 case KEY_END:
4126 view->count = 0;
4127 if (s->eof)
4128 break;
4130 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4131 s->eof = 1;
4132 break;
4133 case 'k':
4134 case KEY_UP:
4135 case CTRL('p'):
4136 if (s->first_displayed_line > 1)
4137 s->first_displayed_line--;
4138 else
4139 view->count = 0;
4140 break;
4141 case CTRL('u'):
4142 case 'u':
4143 nscroll /= 2;
4144 /* FALL THROUGH */
4145 case KEY_PPAGE:
4146 case CTRL('b'):
4147 case 'b':
4148 if (s->first_displayed_line == 1) {
4149 view->count = 0;
4150 break;
4152 i = 0;
4153 while (i++ < nscroll && s->first_displayed_line > 1)
4154 s->first_displayed_line--;
4155 break;
4156 case 'j':
4157 case KEY_DOWN:
4158 case CTRL('n'):
4159 if (!s->eof)
4160 s->first_displayed_line++;
4161 else
4162 view->count = 0;
4163 break;
4164 case CTRL('d'):
4165 case 'd':
4166 nscroll /= 2;
4167 /* FALL THROUGH */
4168 case KEY_NPAGE:
4169 case CTRL('f'):
4170 case 'f':
4171 case ' ':
4172 if (s->eof) {
4173 view->count = 0;
4174 break;
4176 i = 0;
4177 while (!s->eof && i++ < nscroll) {
4178 linelen = getline(&line, &linesize, s->f);
4179 s->first_displayed_line++;
4180 if (linelen == -1) {
4181 if (feof(s->f)) {
4182 s->eof = 1;
4183 } else
4184 err = got_ferror(s->f, GOT_ERR_IO);
4185 break;
4188 free(line);
4189 break;
4190 case '[':
4191 if (s->diff_context > 0) {
4192 s->diff_context--;
4193 s->matched_line = 0;
4194 diff_view_indicate_progress(view);
4195 err = create_diff(s);
4196 if (s->first_displayed_line + view->nlines - 1 >
4197 s->nlines) {
4198 s->first_displayed_line = 1;
4199 s->last_displayed_line = view->nlines;
4201 } else
4202 view->count = 0;
4203 break;
4204 case ']':
4205 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4206 s->diff_context++;
4207 s->matched_line = 0;
4208 diff_view_indicate_progress(view);
4209 err = create_diff(s);
4210 } else
4211 view->count = 0;
4212 break;
4213 case '<':
4214 case ',':
4215 if (s->log_view == NULL) {
4216 view->count = 0;
4217 break;
4219 ls = &s->log_view->state.log;
4220 old_selected_entry = ls->selected_entry;
4222 /* view->count handled in input_log_view() */
4223 err = input_log_view(NULL, s->log_view, KEY_UP);
4224 if (err)
4225 break;
4227 if (old_selected_entry == ls->selected_entry)
4228 break;
4230 err = set_selected_commit(s, ls->selected_entry);
4231 if (err)
4232 break;
4234 s->first_displayed_line = 1;
4235 s->last_displayed_line = view->nlines;
4236 s->matched_line = 0;
4237 view->x = 0;
4239 diff_view_indicate_progress(view);
4240 err = create_diff(s);
4241 break;
4242 case '>':
4243 case '.':
4244 if (s->log_view == NULL) {
4245 view->count = 0;
4246 break;
4248 ls = &s->log_view->state.log;
4249 old_selected_entry = ls->selected_entry;
4251 /* view->count handled in input_log_view() */
4252 err = input_log_view(NULL, s->log_view, KEY_DOWN);
4253 if (err)
4254 break;
4256 if (old_selected_entry == ls->selected_entry)
4257 break;
4259 err = set_selected_commit(s, ls->selected_entry);
4260 if (err)
4261 break;
4263 s->first_displayed_line = 1;
4264 s->last_displayed_line = view->nlines;
4265 s->matched_line = 0;
4266 view->x = 0;
4268 diff_view_indicate_progress(view);
4269 err = create_diff(s);
4270 break;
4271 default:
4272 view->count = 0;
4273 break;
4276 return err;
4279 static const struct got_error *
4280 cmd_diff(int argc, char *argv[])
4282 const struct got_error *error = NULL;
4283 struct got_repository *repo = NULL;
4284 struct got_worktree *worktree = NULL;
4285 struct got_object_id *id1 = NULL, *id2 = NULL;
4286 char *repo_path = NULL, *cwd = NULL;
4287 char *id_str1 = NULL, *id_str2 = NULL;
4288 char *label1 = NULL, *label2 = NULL;
4289 int diff_context = 3, ignore_whitespace = 0;
4290 int ch, force_text_diff = 0;
4291 const char *errstr;
4292 struct tog_view *view;
4293 int *pack_fds = NULL;
4295 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4296 switch (ch) {
4297 case 'a':
4298 force_text_diff = 1;
4299 break;
4300 case 'C':
4301 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4302 &errstr);
4303 if (errstr != NULL)
4304 errx(1, "number of context lines is %s: %s",
4305 errstr, errstr);
4306 break;
4307 case 'r':
4308 repo_path = realpath(optarg, NULL);
4309 if (repo_path == NULL)
4310 return got_error_from_errno2("realpath",
4311 optarg);
4312 got_path_strip_trailing_slashes(repo_path);
4313 break;
4314 case 'w':
4315 ignore_whitespace = 1;
4316 break;
4317 default:
4318 usage_diff();
4319 /* NOTREACHED */
4323 argc -= optind;
4324 argv += optind;
4326 if (argc == 0) {
4327 usage_diff(); /* TODO show local worktree changes */
4328 } else if (argc == 2) {
4329 id_str1 = argv[0];
4330 id_str2 = argv[1];
4331 } else
4332 usage_diff();
4334 error = got_repo_pack_fds_open(&pack_fds);
4335 if (error)
4336 goto done;
4338 if (repo_path == NULL) {
4339 cwd = getcwd(NULL, 0);
4340 if (cwd == NULL)
4341 return got_error_from_errno("getcwd");
4342 error = got_worktree_open(&worktree, cwd);
4343 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4344 goto done;
4345 if (worktree)
4346 repo_path =
4347 strdup(got_worktree_get_repo_path(worktree));
4348 else
4349 repo_path = strdup(cwd);
4350 if (repo_path == NULL) {
4351 error = got_error_from_errno("strdup");
4352 goto done;
4356 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4357 if (error)
4358 goto done;
4360 init_curses();
4362 error = apply_unveil(got_repo_get_path(repo), NULL);
4363 if (error)
4364 goto done;
4366 error = tog_load_refs(repo, 0);
4367 if (error)
4368 goto done;
4370 error = got_repo_match_object_id(&id1, &label1, id_str1,
4371 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4372 if (error)
4373 goto done;
4375 error = got_repo_match_object_id(&id2, &label2, id_str2,
4376 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4377 if (error)
4378 goto done;
4380 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4381 if (view == NULL) {
4382 error = got_error_from_errno("view_open");
4383 goto done;
4385 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4386 ignore_whitespace, force_text_diff, NULL, repo);
4387 if (error)
4388 goto done;
4389 error = view_loop(view);
4390 done:
4391 free(label1);
4392 free(label2);
4393 free(repo_path);
4394 free(cwd);
4395 if (repo) {
4396 const struct got_error *close_err = got_repo_close(repo);
4397 if (error == NULL)
4398 error = close_err;
4400 if (worktree)
4401 got_worktree_close(worktree);
4402 if (pack_fds) {
4403 const struct got_error *pack_err =
4404 got_repo_pack_fds_close(pack_fds);
4405 if (error == NULL)
4406 error = pack_err;
4408 tog_free_refs();
4409 return error;
4412 __dead static void
4413 usage_blame(void)
4415 endwin();
4416 fprintf(stderr,
4417 "usage: %s blame [-c commit] [-r repository-path] path\n",
4418 getprogname());
4419 exit(1);
4422 struct tog_blame_line {
4423 int annotated;
4424 struct got_object_id *id;
4427 static const struct got_error *
4428 draw_blame(struct tog_view *view)
4430 struct tog_blame_view_state *s = &view->state.blame;
4431 struct tog_blame *blame = &s->blame;
4432 regmatch_t *regmatch = &view->regmatch;
4433 const struct got_error *err;
4434 int lineno = 0, nprinted = 0;
4435 char *line = NULL;
4436 size_t linesize = 0;
4437 ssize_t linelen;
4438 wchar_t *wline;
4439 int width;
4440 struct tog_blame_line *blame_line;
4441 struct got_object_id *prev_id = NULL;
4442 char *id_str;
4443 struct tog_color *tc;
4445 err = got_object_id_str(&id_str, &s->blamed_commit->id);
4446 if (err)
4447 return err;
4449 rewind(blame->f);
4450 werase(view->window);
4452 if (asprintf(&line, "commit %s", id_str) == -1) {
4453 err = got_error_from_errno("asprintf");
4454 free(id_str);
4455 return err;
4458 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4459 free(line);
4460 line = NULL;
4461 if (err)
4462 return err;
4463 if (view_needs_focus_indication(view))
4464 wstandout(view->window);
4465 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4466 if (tc)
4467 wattr_on(view->window,
4468 COLOR_PAIR(tc->colorpair), NULL);
4469 waddwstr(view->window, wline);
4470 if (tc)
4471 wattr_off(view->window,
4472 COLOR_PAIR(tc->colorpair), NULL);
4473 if (view_needs_focus_indication(view))
4474 wstandend(view->window);
4475 free(wline);
4476 wline = NULL;
4477 if (width < view->ncols - 1)
4478 waddch(view->window, '\n');
4480 if (asprintf(&line, "[%d/%d] %s%s",
4481 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
4482 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
4483 free(id_str);
4484 return got_error_from_errno("asprintf");
4486 free(id_str);
4487 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4488 free(line);
4489 line = NULL;
4490 if (err)
4491 return err;
4492 waddwstr(view->window, wline);
4493 free(wline);
4494 wline = NULL;
4495 if (width < view->ncols - 1)
4496 waddch(view->window, '\n');
4498 s->eof = 0;
4499 view->maxx = 0;
4500 while (nprinted < view->nlines - 2) {
4501 linelen = getline(&line, &linesize, blame->f);
4502 if (linelen == -1) {
4503 if (feof(blame->f)) {
4504 s->eof = 1;
4505 break;
4507 free(line);
4508 return got_ferror(blame->f, GOT_ERR_IO);
4510 if (++lineno < s->first_displayed_line)
4511 continue;
4513 /* Set view->maxx based on full line length. */
4514 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
4515 if (err) {
4516 free(line);
4517 return err;
4519 free(wline);
4520 wline = NULL;
4521 view->maxx = MAX(view->maxx, width);
4523 if (view->focussed && nprinted == s->selected_line - 1)
4524 wstandout(view->window);
4526 if (blame->nlines > 0) {
4527 blame_line = &blame->lines[lineno - 1];
4528 if (blame_line->annotated && prev_id &&
4529 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
4530 !(view->focussed &&
4531 nprinted == s->selected_line - 1)) {
4532 waddstr(view->window, " ");
4533 } else if (blame_line->annotated) {
4534 char *id_str;
4535 err = got_object_id_str(&id_str,
4536 blame_line->id);
4537 if (err) {
4538 free(line);
4539 return err;
4541 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4542 if (tc)
4543 wattr_on(view->window,
4544 COLOR_PAIR(tc->colorpair), NULL);
4545 wprintw(view->window, "%.8s", id_str);
4546 if (tc)
4547 wattr_off(view->window,
4548 COLOR_PAIR(tc->colorpair), NULL);
4549 free(id_str);
4550 prev_id = blame_line->id;
4551 } else {
4552 waddstr(view->window, "........");
4553 prev_id = NULL;
4555 } else {
4556 waddstr(view->window, "........");
4557 prev_id = NULL;
4560 if (view->focussed && nprinted == s->selected_line - 1)
4561 wstandend(view->window);
4562 waddstr(view->window, " ");
4564 if (view->ncols <= 9) {
4565 width = 9;
4566 } else if (s->first_displayed_line + nprinted ==
4567 s->matched_line &&
4568 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4569 err = add_matched_line(&width, line, view->ncols - 9, 9,
4570 view->window, view->x, regmatch);
4571 if (err) {
4572 free(line);
4573 return err;
4575 width += 9;
4576 } else {
4577 int skip;
4578 err = format_line(&wline, &width, &skip, line,
4579 view->x, view->ncols - 9, 9, 1);
4580 if (err) {
4581 free(line);
4582 return err;
4584 waddwstr(view->window, &wline[skip]);
4585 width += 9;
4586 free(wline);
4587 wline = NULL;
4590 if (width <= view->ncols - 1)
4591 waddch(view->window, '\n');
4592 if (++nprinted == 1)
4593 s->first_displayed_line = lineno;
4595 free(line);
4596 s->last_displayed_line = lineno;
4598 view_vborder(view);
4600 return NULL;
4603 static const struct got_error *
4604 blame_cb(void *arg, int nlines, int lineno,
4605 struct got_commit_object *commit, struct got_object_id *id)
4607 const struct got_error *err = NULL;
4608 struct tog_blame_cb_args *a = arg;
4609 struct tog_blame_line *line;
4610 int errcode;
4612 if (nlines != a->nlines ||
4613 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4614 return got_error(GOT_ERR_RANGE);
4616 errcode = pthread_mutex_lock(&tog_mutex);
4617 if (errcode)
4618 return got_error_set_errno(errcode, "pthread_mutex_lock");
4620 if (*a->quit) { /* user has quit the blame view */
4621 err = got_error(GOT_ERR_ITER_COMPLETED);
4622 goto done;
4625 if (lineno == -1)
4626 goto done; /* no change in this commit */
4628 line = &a->lines[lineno - 1];
4629 if (line->annotated)
4630 goto done;
4632 line->id = got_object_id_dup(id);
4633 if (line->id == NULL) {
4634 err = got_error_from_errno("got_object_id_dup");
4635 goto done;
4637 line->annotated = 1;
4638 done:
4639 errcode = pthread_mutex_unlock(&tog_mutex);
4640 if (errcode)
4641 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4642 return err;
4645 static void *
4646 blame_thread(void *arg)
4648 const struct got_error *err, *close_err;
4649 struct tog_blame_thread_args *ta = arg;
4650 struct tog_blame_cb_args *a = ta->cb_args;
4651 int errcode;
4653 err = block_signals_used_by_main_thread();
4654 if (err)
4655 return (void *)err;
4657 err = got_blame(ta->path, a->commit_id, ta->repo,
4658 blame_cb, ta->cb_args, ta->cancel_cb, ta->cancel_arg);
4659 if (err && err->code == GOT_ERR_CANCELLED)
4660 err = NULL;
4662 errcode = pthread_mutex_lock(&tog_mutex);
4663 if (errcode)
4664 return (void *)got_error_set_errno(errcode,
4665 "pthread_mutex_lock");
4667 close_err = got_repo_close(ta->repo);
4668 if (err == NULL)
4669 err = close_err;
4670 ta->repo = NULL;
4671 *ta->complete = 1;
4673 errcode = pthread_mutex_unlock(&tog_mutex);
4674 if (errcode && err == NULL)
4675 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4677 return (void *)err;
4680 static struct got_object_id *
4681 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
4682 int first_displayed_line, int selected_line)
4684 struct tog_blame_line *line;
4686 if (nlines <= 0)
4687 return NULL;
4689 line = &lines[first_displayed_line - 1 + selected_line - 1];
4690 if (!line->annotated)
4691 return NULL;
4693 return line->id;
4696 static const struct got_error *
4697 stop_blame(struct tog_blame *blame)
4699 const struct got_error *err = NULL;
4700 int i;
4702 if (blame->thread) {
4703 int errcode;
4704 errcode = pthread_mutex_unlock(&tog_mutex);
4705 if (errcode)
4706 return got_error_set_errno(errcode,
4707 "pthread_mutex_unlock");
4708 errcode = pthread_join(blame->thread, (void **)&err);
4709 if (errcode)
4710 return got_error_set_errno(errcode, "pthread_join");
4711 errcode = pthread_mutex_lock(&tog_mutex);
4712 if (errcode)
4713 return got_error_set_errno(errcode,
4714 "pthread_mutex_lock");
4715 if (err && err->code == GOT_ERR_ITER_COMPLETED)
4716 err = NULL;
4717 blame->thread = NULL;
4719 if (blame->thread_args.repo) {
4720 const struct got_error *close_err;
4721 close_err = got_repo_close(blame->thread_args.repo);
4722 if (err == NULL)
4723 err = close_err;
4724 blame->thread_args.repo = NULL;
4726 if (blame->f) {
4727 if (fclose(blame->f) == EOF && err == NULL)
4728 err = got_error_from_errno("fclose");
4729 blame->f = NULL;
4731 if (blame->lines) {
4732 for (i = 0; i < blame->nlines; i++)
4733 free(blame->lines[i].id);
4734 free(blame->lines);
4735 blame->lines = NULL;
4737 free(blame->cb_args.commit_id);
4738 blame->cb_args.commit_id = NULL;
4739 if (blame->pack_fds) {
4740 const struct got_error *pack_err =
4741 got_repo_pack_fds_close(blame->pack_fds);
4742 if (err == NULL)
4743 err = pack_err;
4744 blame->pack_fds = NULL;
4746 return err;
4749 static const struct got_error *
4750 cancel_blame_view(void *arg)
4752 const struct got_error *err = NULL;
4753 int *done = arg;
4754 int errcode;
4756 errcode = pthread_mutex_lock(&tog_mutex);
4757 if (errcode)
4758 return got_error_set_errno(errcode,
4759 "pthread_mutex_unlock");
4761 if (*done)
4762 err = got_error(GOT_ERR_CANCELLED);
4764 errcode = pthread_mutex_unlock(&tog_mutex);
4765 if (errcode)
4766 return got_error_set_errno(errcode,
4767 "pthread_mutex_lock");
4769 return err;
4772 static const struct got_error *
4773 run_blame(struct tog_view *view)
4775 struct tog_blame_view_state *s = &view->state.blame;
4776 struct tog_blame *blame = &s->blame;
4777 const struct got_error *err = NULL;
4778 struct got_commit_object *commit = NULL;
4779 struct got_blob_object *blob = NULL;
4780 struct got_repository *thread_repo = NULL;
4781 struct got_object_id *obj_id = NULL;
4782 int obj_type;
4783 int *pack_fds = NULL;
4785 err = got_object_open_as_commit(&commit, s->repo,
4786 &s->blamed_commit->id);
4787 if (err)
4788 return err;
4790 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
4791 if (err)
4792 goto done;
4794 err = got_object_get_type(&obj_type, s->repo, obj_id);
4795 if (err)
4796 goto done;
4798 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4799 err = got_error(GOT_ERR_OBJ_TYPE);
4800 goto done;
4803 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192);
4804 if (err)
4805 goto done;
4806 blame->f = got_opentemp();
4807 if (blame->f == NULL) {
4808 err = got_error_from_errno("got_opentemp");
4809 goto done;
4811 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
4812 &blame->line_offsets, blame->f, blob);
4813 if (err)
4814 goto done;
4815 if (blame->nlines == 0) {
4816 s->blame_complete = 1;
4817 goto done;
4820 /* Don't include \n at EOF in the blame line count. */
4821 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
4822 blame->nlines--;
4824 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
4825 if (blame->lines == NULL) {
4826 err = got_error_from_errno("calloc");
4827 goto done;
4830 err = got_repo_pack_fds_open(&pack_fds);
4831 if (err)
4832 goto done;
4833 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
4834 pack_fds);
4835 if (err)
4836 goto done;
4838 blame->pack_fds = pack_fds;
4839 blame->cb_args.view = view;
4840 blame->cb_args.lines = blame->lines;
4841 blame->cb_args.nlines = blame->nlines;
4842 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
4843 if (blame->cb_args.commit_id == NULL) {
4844 err = got_error_from_errno("got_object_id_dup");
4845 goto done;
4847 blame->cb_args.quit = &s->done;
4849 blame->thread_args.path = s->path;
4850 blame->thread_args.repo = thread_repo;
4851 blame->thread_args.cb_args = &blame->cb_args;
4852 blame->thread_args.complete = &s->blame_complete;
4853 blame->thread_args.cancel_cb = cancel_blame_view;
4854 blame->thread_args.cancel_arg = &s->done;
4855 s->blame_complete = 0;
4857 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
4858 s->first_displayed_line = 1;
4859 s->last_displayed_line = view->nlines;
4860 s->selected_line = 1;
4862 s->matched_line = 0;
4864 done:
4865 if (commit)
4866 got_object_commit_close(commit);
4867 if (blob)
4868 got_object_blob_close(blob);
4869 free(obj_id);
4870 if (err)
4871 stop_blame(blame);
4872 return err;
4875 static const struct got_error *
4876 open_blame_view(struct tog_view *view, char *path,
4877 struct got_object_id *commit_id, struct got_repository *repo)
4879 const struct got_error *err = NULL;
4880 struct tog_blame_view_state *s = &view->state.blame;
4882 STAILQ_INIT(&s->blamed_commits);
4884 s->path = strdup(path);
4885 if (s->path == NULL)
4886 return got_error_from_errno("strdup");
4888 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
4889 if (err) {
4890 free(s->path);
4891 return err;
4894 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
4895 s->first_displayed_line = 1;
4896 s->last_displayed_line = view->nlines;
4897 s->selected_line = 1;
4898 s->blame_complete = 0;
4899 s->repo = repo;
4900 s->commit_id = commit_id;
4901 memset(&s->blame, 0, sizeof(s->blame));
4903 STAILQ_INIT(&s->colors);
4904 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4905 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
4906 get_color_value("TOG_COLOR_COMMIT"));
4907 if (err)
4908 return err;
4911 view->show = show_blame_view;
4912 view->input = input_blame_view;
4913 view->close = close_blame_view;
4914 view->search_start = search_start_blame_view;
4915 view->search_next = search_next_blame_view;
4917 return run_blame(view);
4920 static const struct got_error *
4921 close_blame_view(struct tog_view *view)
4923 const struct got_error *err = NULL;
4924 struct tog_blame_view_state *s = &view->state.blame;
4926 if (s->blame.thread)
4927 err = stop_blame(&s->blame);
4929 while (!STAILQ_EMPTY(&s->blamed_commits)) {
4930 struct got_object_qid *blamed_commit;
4931 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
4932 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
4933 got_object_qid_free(blamed_commit);
4936 free(s->path);
4937 free_colors(&s->colors);
4938 return err;
4941 static const struct got_error *
4942 search_start_blame_view(struct tog_view *view)
4944 struct tog_blame_view_state *s = &view->state.blame;
4946 s->matched_line = 0;
4947 return NULL;
4950 static const struct got_error *
4951 search_next_blame_view(struct tog_view *view)
4953 struct tog_blame_view_state *s = &view->state.blame;
4954 const struct got_error *err = NULL;
4955 int lineno;
4956 char *line = NULL;
4957 size_t linesize = 0;
4958 ssize_t linelen;
4960 if (!view->searching) {
4961 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4962 return NULL;
4965 if (s->matched_line) {
4966 if (view->searching == TOG_SEARCH_FORWARD)
4967 lineno = s->matched_line + 1;
4968 else
4969 lineno = s->matched_line - 1;
4970 } else
4971 lineno = s->first_displayed_line - 1 + s->selected_line;
4973 while (1) {
4974 off_t offset;
4976 if (lineno <= 0 || lineno > s->blame.nlines) {
4977 if (s->matched_line == 0) {
4978 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4979 break;
4982 if (view->searching == TOG_SEARCH_FORWARD)
4983 lineno = 1;
4984 else
4985 lineno = s->blame.nlines;
4988 offset = s->blame.line_offsets[lineno - 1];
4989 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
4990 free(line);
4991 return got_error_from_errno("fseeko");
4993 linelen = getline(&line, &linesize, s->blame.f);
4994 if (linelen != -1) {
4995 char *exstr;
4996 err = expand_tab(&exstr, line);
4997 if (err)
4998 break;
4999 if (match_line(exstr, &view->regex, 1,
5000 &view->regmatch)) {
5001 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5002 s->matched_line = lineno;
5003 free(exstr);
5004 break;
5006 free(exstr);
5008 if (view->searching == TOG_SEARCH_FORWARD)
5009 lineno++;
5010 else
5011 lineno--;
5013 free(line);
5015 if (s->matched_line) {
5016 s->first_displayed_line = s->matched_line;
5017 s->selected_line = 1;
5020 return err;
5023 static const struct got_error *
5024 show_blame_view(struct tog_view *view)
5026 const struct got_error *err = NULL;
5027 struct tog_blame_view_state *s = &view->state.blame;
5028 int errcode;
5030 if (s->blame.thread == NULL && !s->blame_complete) {
5031 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5032 &s->blame.thread_args);
5033 if (errcode)
5034 return got_error_set_errno(errcode, "pthread_create");
5036 halfdelay(1); /* fast refresh while annotating */
5039 if (s->blame_complete)
5040 halfdelay(10); /* disable fast refresh */
5042 err = draw_blame(view);
5044 view_vborder(view);
5045 return err;
5048 static const struct got_error *
5049 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5051 const struct got_error *err = NULL, *thread_err = NULL;
5052 struct tog_view *diff_view;
5053 struct tog_blame_view_state *s = &view->state.blame;
5054 int begin_x = 0, nscroll = view->nlines - 2;
5056 switch (ch) {
5057 case '0':
5058 view->x = 0;
5059 break;
5060 case '$':
5061 view->x = MAX(view->maxx - view->ncols / 3, 0);
5062 view->count = 0;
5063 break;
5064 case KEY_RIGHT:
5065 case 'l':
5066 if (view->x + view->ncols / 3 < view->maxx)
5067 view->x += 2; /* move two columns right */
5068 else
5069 view->count = 0;
5070 break;
5071 case KEY_LEFT:
5072 case 'h':
5073 view->x -= MIN(view->x, 2); /* move two columns back */
5074 if (view->x <= 0)
5075 view->count = 0;
5076 break;
5077 case 'q':
5078 s->done = 1;
5079 break;
5080 case 'g':
5081 case KEY_HOME:
5082 s->selected_line = 1;
5083 s->first_displayed_line = 1;
5084 view->count = 0;
5085 break;
5086 case 'G':
5087 case KEY_END:
5088 if (s->blame.nlines < view->nlines - 2) {
5089 s->selected_line = s->blame.nlines;
5090 s->first_displayed_line = 1;
5091 } else {
5092 s->selected_line = view->nlines - 2;
5093 s->first_displayed_line = s->blame.nlines -
5094 (view->nlines - 3);
5096 view->count = 0;
5097 break;
5098 case 'k':
5099 case KEY_UP:
5100 case CTRL('p'):
5101 if (s->selected_line > 1)
5102 s->selected_line--;
5103 else if (s->selected_line == 1 &&
5104 s->first_displayed_line > 1)
5105 s->first_displayed_line--;
5106 else
5107 view->count = 0;
5108 break;
5109 case CTRL('u'):
5110 case 'u':
5111 nscroll /= 2;
5112 /* FALL THROUGH */
5113 case KEY_PPAGE:
5114 case CTRL('b'):
5115 case 'b':
5116 if (s->first_displayed_line == 1) {
5117 if (view->count > 1)
5118 nscroll += nscroll;
5119 s->selected_line = MAX(1, s->selected_line - nscroll);
5120 view->count = 0;
5121 break;
5123 if (s->first_displayed_line > nscroll)
5124 s->first_displayed_line -= nscroll;
5125 else
5126 s->first_displayed_line = 1;
5127 break;
5128 case 'j':
5129 case KEY_DOWN:
5130 case CTRL('n'):
5131 if (s->selected_line < view->nlines - 2 &&
5132 s->first_displayed_line +
5133 s->selected_line <= s->blame.nlines)
5134 s->selected_line++;
5135 else if (s->last_displayed_line <
5136 s->blame.nlines)
5137 s->first_displayed_line++;
5138 else
5139 view->count = 0;
5140 break;
5141 case 'c':
5142 case 'p': {
5143 struct got_object_id *id = NULL;
5145 view->count = 0;
5146 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5147 s->first_displayed_line, s->selected_line);
5148 if (id == NULL)
5149 break;
5150 if (ch == 'p') {
5151 struct got_commit_object *commit, *pcommit;
5152 struct got_object_qid *pid;
5153 struct got_object_id *blob_id = NULL;
5154 int obj_type;
5155 err = got_object_open_as_commit(&commit,
5156 s->repo, id);
5157 if (err)
5158 break;
5159 pid = STAILQ_FIRST(
5160 got_object_commit_get_parent_ids(commit));
5161 if (pid == NULL) {
5162 got_object_commit_close(commit);
5163 break;
5165 /* Check if path history ends here. */
5166 err = got_object_open_as_commit(&pcommit,
5167 s->repo, &pid->id);
5168 if (err)
5169 break;
5170 err = got_object_id_by_path(&blob_id, s->repo,
5171 pcommit, s->path);
5172 got_object_commit_close(pcommit);
5173 if (err) {
5174 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5175 err = NULL;
5176 got_object_commit_close(commit);
5177 break;
5179 err = got_object_get_type(&obj_type, s->repo,
5180 blob_id);
5181 free(blob_id);
5182 /* Can't blame non-blob type objects. */
5183 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5184 got_object_commit_close(commit);
5185 break;
5187 err = got_object_qid_alloc(&s->blamed_commit,
5188 &pid->id);
5189 got_object_commit_close(commit);
5190 } else {
5191 if (got_object_id_cmp(id,
5192 &s->blamed_commit->id) == 0)
5193 break;
5194 err = got_object_qid_alloc(&s->blamed_commit,
5195 id);
5197 if (err)
5198 break;
5199 s->done = 1;
5200 thread_err = stop_blame(&s->blame);
5201 s->done = 0;
5202 if (thread_err)
5203 break;
5204 STAILQ_INSERT_HEAD(&s->blamed_commits,
5205 s->blamed_commit, entry);
5206 err = run_blame(view);
5207 if (err)
5208 break;
5209 break;
5211 case 'C': {
5212 struct got_object_qid *first;
5214 view->count = 0;
5215 first = STAILQ_FIRST(&s->blamed_commits);
5216 if (!got_object_id_cmp(&first->id, s->commit_id))
5217 break;
5218 s->done = 1;
5219 thread_err = stop_blame(&s->blame);
5220 s->done = 0;
5221 if (thread_err)
5222 break;
5223 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5224 got_object_qid_free(s->blamed_commit);
5225 s->blamed_commit =
5226 STAILQ_FIRST(&s->blamed_commits);
5227 err = run_blame(view);
5228 if (err)
5229 break;
5230 break;
5232 case KEY_ENTER:
5233 case '\r': {
5234 struct got_object_id *id = NULL;
5235 struct got_object_qid *pid;
5236 struct got_commit_object *commit = NULL;
5238 view->count = 0;
5239 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5240 s->first_displayed_line, s->selected_line);
5241 if (id == NULL)
5242 break;
5243 err = got_object_open_as_commit(&commit, s->repo, id);
5244 if (err)
5245 break;
5246 pid = STAILQ_FIRST(
5247 got_object_commit_get_parent_ids(commit));
5248 if (view_is_parent_view(view))
5249 begin_x = view_split_begin_x(view->begin_x);
5250 diff_view = view_open(0, 0, 0, begin_x, TOG_VIEW_DIFF);
5251 if (diff_view == NULL) {
5252 got_object_commit_close(commit);
5253 err = got_error_from_errno("view_open");
5254 break;
5256 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5257 id, NULL, NULL, 3, 0, 0, NULL, s->repo);
5258 got_object_commit_close(commit);
5259 if (err) {
5260 view_close(diff_view);
5261 break;
5263 view->focussed = 0;
5264 diff_view->focussed = 1;
5265 if (view_is_parent_view(view)) {
5266 err = view_close_child(view);
5267 if (err)
5268 break;
5269 err = view_set_child(view, diff_view);
5270 if (err)
5271 break;
5272 view->focus_child = 1;
5273 } else
5274 *new_view = diff_view;
5275 if (err)
5276 break;
5277 break;
5279 case CTRL('d'):
5280 case 'd':
5281 nscroll /= 2;
5282 /* FALL THROUGH */
5283 case KEY_NPAGE:
5284 case CTRL('f'):
5285 case 'f':
5286 case ' ':
5287 if (s->last_displayed_line >= s->blame.nlines &&
5288 s->selected_line >= MIN(s->blame.nlines,
5289 view->nlines - 2)) {
5290 view->count = 0;
5291 break;
5293 if (s->last_displayed_line >= s->blame.nlines &&
5294 s->selected_line < view->nlines - 2) {
5295 s->selected_line +=
5296 MIN(nscroll, s->last_displayed_line -
5297 s->first_displayed_line - s->selected_line + 1);
5299 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5300 s->first_displayed_line += nscroll;
5301 else
5302 s->first_displayed_line =
5303 s->blame.nlines - (view->nlines - 3);
5304 break;
5305 case KEY_RESIZE:
5306 if (s->selected_line > view->nlines - 2) {
5307 s->selected_line = MIN(s->blame.nlines,
5308 view->nlines - 2);
5310 break;
5311 default:
5312 view->count = 0;
5313 break;
5315 return thread_err ? thread_err : err;
5318 static const struct got_error *
5319 cmd_blame(int argc, char *argv[])
5321 const struct got_error *error;
5322 struct got_repository *repo = NULL;
5323 struct got_worktree *worktree = NULL;
5324 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5325 char *link_target = NULL;
5326 struct got_object_id *commit_id = NULL;
5327 struct got_commit_object *commit = NULL;
5328 char *commit_id_str = NULL;
5329 int ch;
5330 struct tog_view *view;
5331 int *pack_fds = NULL;
5333 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5334 switch (ch) {
5335 case 'c':
5336 commit_id_str = optarg;
5337 break;
5338 case 'r':
5339 repo_path = realpath(optarg, NULL);
5340 if (repo_path == NULL)
5341 return got_error_from_errno2("realpath",
5342 optarg);
5343 break;
5344 default:
5345 usage_blame();
5346 /* NOTREACHED */
5350 argc -= optind;
5351 argv += optind;
5353 if (argc != 1)
5354 usage_blame();
5356 error = got_repo_pack_fds_open(&pack_fds);
5357 if (error != NULL)
5358 goto done;
5360 if (repo_path == NULL) {
5361 cwd = getcwd(NULL, 0);
5362 if (cwd == NULL)
5363 return got_error_from_errno("getcwd");
5364 error = got_worktree_open(&worktree, cwd);
5365 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5366 goto done;
5367 if (worktree)
5368 repo_path =
5369 strdup(got_worktree_get_repo_path(worktree));
5370 else
5371 repo_path = strdup(cwd);
5372 if (repo_path == NULL) {
5373 error = got_error_from_errno("strdup");
5374 goto done;
5378 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5379 if (error != NULL)
5380 goto done;
5382 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
5383 worktree);
5384 if (error)
5385 goto done;
5387 init_curses();
5389 error = apply_unveil(got_repo_get_path(repo), NULL);
5390 if (error)
5391 goto done;
5393 error = tog_load_refs(repo, 0);
5394 if (error)
5395 goto done;
5397 if (commit_id_str == NULL) {
5398 struct got_reference *head_ref;
5399 error = got_ref_open(&head_ref, repo, worktree ?
5400 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5401 if (error != NULL)
5402 goto done;
5403 error = got_ref_resolve(&commit_id, repo, head_ref);
5404 got_ref_close(head_ref);
5405 } else {
5406 error = got_repo_match_object_id(&commit_id, NULL,
5407 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
5409 if (error != NULL)
5410 goto done;
5412 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
5413 if (view == NULL) {
5414 error = got_error_from_errno("view_open");
5415 goto done;
5418 error = got_object_open_as_commit(&commit, repo, commit_id);
5419 if (error)
5420 goto done;
5422 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5423 commit, repo);
5424 if (error)
5425 goto done;
5427 error = open_blame_view(view, link_target ? link_target : in_repo_path,
5428 commit_id, repo);
5429 if (error)
5430 goto done;
5431 if (worktree) {
5432 /* Release work tree lock. */
5433 got_worktree_close(worktree);
5434 worktree = NULL;
5436 error = view_loop(view);
5437 done:
5438 free(repo_path);
5439 free(in_repo_path);
5440 free(link_target);
5441 free(cwd);
5442 free(commit_id);
5443 if (commit)
5444 got_object_commit_close(commit);
5445 if (worktree)
5446 got_worktree_close(worktree);
5447 if (repo) {
5448 const struct got_error *close_err = got_repo_close(repo);
5449 if (error == NULL)
5450 error = close_err;
5452 if (pack_fds) {
5453 const struct got_error *pack_err =
5454 got_repo_pack_fds_close(pack_fds);
5455 if (error == NULL)
5456 error = pack_err;
5458 tog_free_refs();
5459 return error;
5462 static const struct got_error *
5463 draw_tree_entries(struct tog_view *view, const char *parent_path)
5465 struct tog_tree_view_state *s = &view->state.tree;
5466 const struct got_error *err = NULL;
5467 struct got_tree_entry *te;
5468 wchar_t *wline;
5469 struct tog_color *tc;
5470 int width, n, i, nentries;
5471 int limit = view->nlines;
5473 s->ndisplayed = 0;
5475 werase(view->window);
5477 if (limit == 0)
5478 return NULL;
5480 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
5481 0, 0);
5482 if (err)
5483 return err;
5484 if (view_needs_focus_indication(view))
5485 wstandout(view->window);
5486 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5487 if (tc)
5488 wattr_on(view->window,
5489 COLOR_PAIR(tc->colorpair), NULL);
5490 waddwstr(view->window, wline);
5491 if (tc)
5492 wattr_off(view->window,
5493 COLOR_PAIR(tc->colorpair), NULL);
5494 if (view_needs_focus_indication(view))
5495 wstandend(view->window);
5496 free(wline);
5497 wline = NULL;
5498 if (width < view->ncols - 1)
5499 waddch(view->window, '\n');
5500 if (--limit <= 0)
5501 return NULL;
5502 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
5503 0, 0);
5504 if (err)
5505 return err;
5506 waddwstr(view->window, wline);
5507 free(wline);
5508 wline = NULL;
5509 if (width < view->ncols - 1)
5510 waddch(view->window, '\n');
5511 if (--limit <= 0)
5512 return NULL;
5513 waddch(view->window, '\n');
5514 if (--limit <= 0)
5515 return NULL;
5517 if (s->first_displayed_entry == NULL) {
5518 te = got_object_tree_get_first_entry(s->tree);
5519 if (s->selected == 0) {
5520 if (view->focussed)
5521 wstandout(view->window);
5522 s->selected_entry = NULL;
5524 waddstr(view->window, " ..\n"); /* parent directory */
5525 if (s->selected == 0 && view->focussed)
5526 wstandend(view->window);
5527 s->ndisplayed++;
5528 if (--limit <= 0)
5529 return NULL;
5530 n = 1;
5531 } else {
5532 n = 0;
5533 te = s->first_displayed_entry;
5536 nentries = got_object_tree_get_nentries(s->tree);
5537 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
5538 char *line = NULL, *id_str = NULL, *link_target = NULL;
5539 const char *modestr = "";
5540 mode_t mode;
5542 te = got_object_tree_get_entry(s->tree, i);
5543 mode = got_tree_entry_get_mode(te);
5545 if (s->show_ids) {
5546 err = got_object_id_str(&id_str,
5547 got_tree_entry_get_id(te));
5548 if (err)
5549 return got_error_from_errno(
5550 "got_object_id_str");
5552 if (got_object_tree_entry_is_submodule(te))
5553 modestr = "$";
5554 else if (S_ISLNK(mode)) {
5555 int i;
5557 err = got_tree_entry_get_symlink_target(&link_target,
5558 te, s->repo);
5559 if (err) {
5560 free(id_str);
5561 return err;
5563 for (i = 0; i < strlen(link_target); i++) {
5564 if (!isprint((unsigned char)link_target[i]))
5565 link_target[i] = '?';
5567 modestr = "@";
5569 else if (S_ISDIR(mode))
5570 modestr = "/";
5571 else if (mode & S_IXUSR)
5572 modestr = "*";
5573 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
5574 got_tree_entry_get_name(te), modestr,
5575 link_target ? " -> ": "",
5576 link_target ? link_target : "") == -1) {
5577 free(id_str);
5578 free(link_target);
5579 return got_error_from_errno("asprintf");
5581 free(id_str);
5582 free(link_target);
5583 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
5584 0, 0);
5585 if (err) {
5586 free(line);
5587 break;
5589 if (n == s->selected) {
5590 if (view->focussed)
5591 wstandout(view->window);
5592 s->selected_entry = te;
5594 tc = match_color(&s->colors, line);
5595 if (tc)
5596 wattr_on(view->window,
5597 COLOR_PAIR(tc->colorpair), NULL);
5598 waddwstr(view->window, wline);
5599 if (tc)
5600 wattr_off(view->window,
5601 COLOR_PAIR(tc->colorpair), NULL);
5602 if (width < view->ncols - 1)
5603 waddch(view->window, '\n');
5604 if (n == s->selected && view->focussed)
5605 wstandend(view->window);
5606 free(line);
5607 free(wline);
5608 wline = NULL;
5609 n++;
5610 s->ndisplayed++;
5611 s->last_displayed_entry = te;
5612 if (--limit <= 0)
5613 break;
5616 return err;
5619 static void
5620 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
5622 struct got_tree_entry *te;
5623 int isroot = s->tree == s->root;
5624 int i = 0;
5626 if (s->first_displayed_entry == NULL)
5627 return;
5629 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
5630 while (i++ < maxscroll) {
5631 if (te == NULL) {
5632 if (!isroot)
5633 s->first_displayed_entry = NULL;
5634 break;
5636 s->first_displayed_entry = te;
5637 te = got_tree_entry_get_prev(s->tree, te);
5641 static void
5642 tree_scroll_down(struct tog_tree_view_state *s, int maxscroll)
5644 struct got_tree_entry *next, *last;
5645 int n = 0;
5647 if (s->first_displayed_entry)
5648 next = got_tree_entry_get_next(s->tree,
5649 s->first_displayed_entry);
5650 else
5651 next = got_object_tree_get_first_entry(s->tree);
5653 last = s->last_displayed_entry;
5654 while (next && last && n++ < maxscroll) {
5655 last = got_tree_entry_get_next(s->tree, last);
5656 if (last) {
5657 s->first_displayed_entry = next;
5658 next = got_tree_entry_get_next(s->tree, next);
5663 static const struct got_error *
5664 tree_entry_path(char **path, struct tog_parent_trees *parents,
5665 struct got_tree_entry *te)
5667 const struct got_error *err = NULL;
5668 struct tog_parent_tree *pt;
5669 size_t len = 2; /* for leading slash and NUL */
5671 TAILQ_FOREACH(pt, parents, entry)
5672 len += strlen(got_tree_entry_get_name(pt->selected_entry))
5673 + 1 /* slash */;
5674 if (te)
5675 len += strlen(got_tree_entry_get_name(te));
5677 *path = calloc(1, len);
5678 if (path == NULL)
5679 return got_error_from_errno("calloc");
5681 (*path)[0] = '/';
5682 pt = TAILQ_LAST(parents, tog_parent_trees);
5683 while (pt) {
5684 const char *name = got_tree_entry_get_name(pt->selected_entry);
5685 if (strlcat(*path, name, len) >= len) {
5686 err = got_error(GOT_ERR_NO_SPACE);
5687 goto done;
5689 if (strlcat(*path, "/", len) >= len) {
5690 err = got_error(GOT_ERR_NO_SPACE);
5691 goto done;
5693 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
5695 if (te) {
5696 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
5697 err = got_error(GOT_ERR_NO_SPACE);
5698 goto done;
5701 done:
5702 if (err) {
5703 free(*path);
5704 *path = NULL;
5706 return err;
5709 static const struct got_error *
5710 blame_tree_entry(struct tog_view **new_view, int begin_x,
5711 struct got_tree_entry *te, struct tog_parent_trees *parents,
5712 struct got_object_id *commit_id, struct got_repository *repo)
5714 const struct got_error *err = NULL;
5715 char *path;
5716 struct tog_view *blame_view;
5718 *new_view = NULL;
5720 err = tree_entry_path(&path, parents, te);
5721 if (err)
5722 return err;
5724 blame_view = view_open(0, 0, 0, begin_x, TOG_VIEW_BLAME);
5725 if (blame_view == NULL) {
5726 err = got_error_from_errno("view_open");
5727 goto done;
5730 err = open_blame_view(blame_view, path, commit_id, repo);
5731 if (err) {
5732 if (err->code == GOT_ERR_CANCELLED)
5733 err = NULL;
5734 view_close(blame_view);
5735 } else
5736 *new_view = blame_view;
5737 done:
5738 free(path);
5739 return err;
5742 static const struct got_error *
5743 log_selected_tree_entry(struct tog_view **new_view, int begin_x,
5744 struct tog_tree_view_state *s)
5746 struct tog_view *log_view;
5747 const struct got_error *err = NULL;
5748 char *path;
5750 *new_view = NULL;
5752 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
5753 if (log_view == NULL)
5754 return got_error_from_errno("view_open");
5756 err = tree_entry_path(&path, &s->parents, s->selected_entry);
5757 if (err)
5758 return err;
5760 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
5761 path, 0);
5762 if (err)
5763 view_close(log_view);
5764 else
5765 *new_view = log_view;
5766 free(path);
5767 return err;
5770 static const struct got_error *
5771 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
5772 const char *head_ref_name, struct got_repository *repo)
5774 const struct got_error *err = NULL;
5775 char *commit_id_str = NULL;
5776 struct tog_tree_view_state *s = &view->state.tree;
5777 struct got_commit_object *commit = NULL;
5779 TAILQ_INIT(&s->parents);
5780 STAILQ_INIT(&s->colors);
5782 s->commit_id = got_object_id_dup(commit_id);
5783 if (s->commit_id == NULL)
5784 return got_error_from_errno("got_object_id_dup");
5786 err = got_object_open_as_commit(&commit, repo, commit_id);
5787 if (err)
5788 goto done;
5791 * The root is opened here and will be closed when the view is closed.
5792 * Any visited subtrees and their path-wise parents are opened and
5793 * closed on demand.
5795 err = got_object_open_as_tree(&s->root, repo,
5796 got_object_commit_get_tree_id(commit));
5797 if (err)
5798 goto done;
5799 s->tree = s->root;
5801 err = got_object_id_str(&commit_id_str, commit_id);
5802 if (err != NULL)
5803 goto done;
5805 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
5806 err = got_error_from_errno("asprintf");
5807 goto done;
5810 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
5811 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
5812 if (head_ref_name) {
5813 s->head_ref_name = strdup(head_ref_name);
5814 if (s->head_ref_name == NULL) {
5815 err = got_error_from_errno("strdup");
5816 goto done;
5819 s->repo = repo;
5821 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5822 err = add_color(&s->colors, "\\$$",
5823 TOG_COLOR_TREE_SUBMODULE,
5824 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
5825 if (err)
5826 goto done;
5827 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
5828 get_color_value("TOG_COLOR_TREE_SYMLINK"));
5829 if (err)
5830 goto done;
5831 err = add_color(&s->colors, "/$",
5832 TOG_COLOR_TREE_DIRECTORY,
5833 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
5834 if (err)
5835 goto done;
5837 err = add_color(&s->colors, "\\*$",
5838 TOG_COLOR_TREE_EXECUTABLE,
5839 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
5840 if (err)
5841 goto done;
5843 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
5844 get_color_value("TOG_COLOR_COMMIT"));
5845 if (err)
5846 goto done;
5849 view->show = show_tree_view;
5850 view->input = input_tree_view;
5851 view->close = close_tree_view;
5852 view->search_start = search_start_tree_view;
5853 view->search_next = search_next_tree_view;
5854 done:
5855 free(commit_id_str);
5856 if (commit)
5857 got_object_commit_close(commit);
5858 if (err)
5859 close_tree_view(view);
5860 return err;
5863 static const struct got_error *
5864 close_tree_view(struct tog_view *view)
5866 struct tog_tree_view_state *s = &view->state.tree;
5868 free_colors(&s->colors);
5869 free(s->tree_label);
5870 s->tree_label = NULL;
5871 free(s->commit_id);
5872 s->commit_id = NULL;
5873 free(s->head_ref_name);
5874 s->head_ref_name = NULL;
5875 while (!TAILQ_EMPTY(&s->parents)) {
5876 struct tog_parent_tree *parent;
5877 parent = TAILQ_FIRST(&s->parents);
5878 TAILQ_REMOVE(&s->parents, parent, entry);
5879 if (parent->tree != s->root)
5880 got_object_tree_close(parent->tree);
5881 free(parent);
5884 if (s->tree != NULL && s->tree != s->root)
5885 got_object_tree_close(s->tree);
5886 if (s->root)
5887 got_object_tree_close(s->root);
5888 return NULL;
5891 static const struct got_error *
5892 search_start_tree_view(struct tog_view *view)
5894 struct tog_tree_view_state *s = &view->state.tree;
5896 s->matched_entry = NULL;
5897 return NULL;
5900 static int
5901 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
5903 regmatch_t regmatch;
5905 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
5906 0) == 0;
5909 static const struct got_error *
5910 search_next_tree_view(struct tog_view *view)
5912 struct tog_tree_view_state *s = &view->state.tree;
5913 struct got_tree_entry *te = NULL;
5915 if (!view->searching) {
5916 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5917 return NULL;
5920 if (s->matched_entry) {
5921 if (view->searching == TOG_SEARCH_FORWARD) {
5922 if (s->selected_entry)
5923 te = got_tree_entry_get_next(s->tree,
5924 s->selected_entry);
5925 else
5926 te = got_object_tree_get_first_entry(s->tree);
5927 } else {
5928 if (s->selected_entry == NULL)
5929 te = got_object_tree_get_last_entry(s->tree);
5930 else
5931 te = got_tree_entry_get_prev(s->tree,
5932 s->selected_entry);
5934 } else {
5935 if (s->selected_entry)
5936 te = s->selected_entry;
5937 else if (view->searching == TOG_SEARCH_FORWARD)
5938 te = got_object_tree_get_first_entry(s->tree);
5939 else
5940 te = got_object_tree_get_last_entry(s->tree);
5943 while (1) {
5944 if (te == NULL) {
5945 if (s->matched_entry == NULL) {
5946 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5947 return NULL;
5949 if (view->searching == TOG_SEARCH_FORWARD)
5950 te = got_object_tree_get_first_entry(s->tree);
5951 else
5952 te = got_object_tree_get_last_entry(s->tree);
5955 if (match_tree_entry(te, &view->regex)) {
5956 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5957 s->matched_entry = te;
5958 break;
5961 if (view->searching == TOG_SEARCH_FORWARD)
5962 te = got_tree_entry_get_next(s->tree, te);
5963 else
5964 te = got_tree_entry_get_prev(s->tree, te);
5967 if (s->matched_entry) {
5968 s->first_displayed_entry = s->matched_entry;
5969 s->selected = 0;
5972 return NULL;
5975 static const struct got_error *
5976 show_tree_view(struct tog_view *view)
5978 const struct got_error *err = NULL;
5979 struct tog_tree_view_state *s = &view->state.tree;
5980 char *parent_path;
5982 err = tree_entry_path(&parent_path, &s->parents, NULL);
5983 if (err)
5984 return err;
5986 err = draw_tree_entries(view, parent_path);
5987 free(parent_path);
5989 view_vborder(view);
5990 return err;
5993 static const struct got_error *
5994 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
5996 const struct got_error *err = NULL;
5997 struct tog_tree_view_state *s = &view->state.tree;
5998 struct tog_view *log_view, *ref_view;
5999 struct got_tree_entry *te;
6000 int begin_x = 0, n, nscroll = view->nlines - 3;
6002 switch (ch) {
6003 case 'i':
6004 s->show_ids = !s->show_ids;
6005 view->count = 0;
6006 break;
6007 case 'l':
6008 view->count = 0;
6009 if (!s->selected_entry)
6010 break;
6011 if (view_is_parent_view(view))
6012 begin_x = view_split_begin_x(view->begin_x);
6013 err = log_selected_tree_entry(&log_view, begin_x, s);
6014 view->focussed = 0;
6015 log_view->focussed = 1;
6016 if (view_is_parent_view(view)) {
6017 err = view_close_child(view);
6018 if (err)
6019 return err;
6020 err = view_set_child(view, log_view);
6021 if (err)
6022 return err;
6023 view->focus_child = 1;
6024 } else
6025 *new_view = log_view;
6026 break;
6027 case 'r':
6028 view->count = 0;
6029 if (view_is_parent_view(view))
6030 begin_x = view_split_begin_x(view->begin_x);
6031 ref_view = view_open(view->nlines, view->ncols,
6032 view->begin_y, begin_x, TOG_VIEW_REF);
6033 if (ref_view == NULL)
6034 return got_error_from_errno("view_open");
6035 err = open_ref_view(ref_view, s->repo);
6036 if (err) {
6037 view_close(ref_view);
6038 return err;
6040 view->focussed = 0;
6041 ref_view->focussed = 1;
6042 if (view_is_parent_view(view)) {
6043 err = view_close_child(view);
6044 if (err)
6045 return err;
6046 err = view_set_child(view, ref_view);
6047 if (err)
6048 return err;
6049 view->focus_child = 1;
6050 } else
6051 *new_view = ref_view;
6052 break;
6053 case 'g':
6054 case KEY_HOME:
6055 s->selected = 0;
6056 view->count = 0;
6057 if (s->tree == s->root)
6058 s->first_displayed_entry =
6059 got_object_tree_get_first_entry(s->tree);
6060 else
6061 s->first_displayed_entry = NULL;
6062 break;
6063 case 'G':
6064 case KEY_END:
6065 s->selected = 0;
6066 view->count = 0;
6067 te = got_object_tree_get_last_entry(s->tree);
6068 for (n = 0; n < view->nlines - 3; n++) {
6069 if (te == NULL) {
6070 if(s->tree != s->root) {
6071 s->first_displayed_entry = NULL;
6072 n++;
6074 break;
6076 s->first_displayed_entry = te;
6077 te = got_tree_entry_get_prev(s->tree, te);
6079 if (n > 0)
6080 s->selected = n - 1;
6081 break;
6082 case 'k':
6083 case KEY_UP:
6084 case CTRL('p'):
6085 if (s->selected > 0) {
6086 s->selected--;
6087 break;
6089 tree_scroll_up(s, 1);
6090 if (s->selected_entry == NULL ||
6091 (s->tree == s->root && s->selected_entry ==
6092 got_object_tree_get_first_entry(s->tree)))
6093 view->count = 0;
6094 break;
6095 case CTRL('u'):
6096 case 'u':
6097 nscroll /= 2;
6098 /* FALL THROUGH */
6099 case KEY_PPAGE:
6100 case CTRL('b'):
6101 case 'b':
6102 if (s->tree == s->root) {
6103 if (got_object_tree_get_first_entry(s->tree) ==
6104 s->first_displayed_entry)
6105 s->selected -= MIN(s->selected, nscroll);
6106 } else {
6107 if (s->first_displayed_entry == NULL)
6108 s->selected -= MIN(s->selected, nscroll);
6110 tree_scroll_up(s, MAX(0, nscroll));
6111 if (s->selected_entry == NULL ||
6112 (s->tree == s->root && s->selected_entry ==
6113 got_object_tree_get_first_entry(s->tree)))
6114 view->count = 0;
6115 break;
6116 case 'j':
6117 case KEY_DOWN:
6118 case CTRL('n'):
6119 if (s->selected < s->ndisplayed - 1) {
6120 s->selected++;
6121 break;
6123 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6124 == NULL) {
6125 /* can't scroll any further */
6126 view->count = 0;
6127 break;
6129 tree_scroll_down(s, 1);
6130 break;
6131 case CTRL('d'):
6132 case 'd':
6133 nscroll /= 2;
6134 /* FALL THROUGH */
6135 case KEY_NPAGE:
6136 case CTRL('f'):
6137 case 'f':
6138 case ' ':
6139 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6140 == NULL) {
6141 /* can't scroll any further; move cursor down */
6142 if (s->selected < s->ndisplayed - 1)
6143 s->selected += MIN(nscroll,
6144 s->ndisplayed - s->selected - 1);
6145 else
6146 view->count = 0;
6147 break;
6149 tree_scroll_down(s, nscroll);
6150 break;
6151 case KEY_ENTER:
6152 case '\r':
6153 case KEY_BACKSPACE:
6154 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6155 struct tog_parent_tree *parent;
6156 /* user selected '..' */
6157 if (s->tree == s->root) {
6158 view->count = 0;
6159 break;
6161 parent = TAILQ_FIRST(&s->parents);
6162 TAILQ_REMOVE(&s->parents, parent,
6163 entry);
6164 got_object_tree_close(s->tree);
6165 s->tree = parent->tree;
6166 s->first_displayed_entry =
6167 parent->first_displayed_entry;
6168 s->selected_entry =
6169 parent->selected_entry;
6170 s->selected = parent->selected;
6171 free(parent);
6172 } else if (S_ISDIR(got_tree_entry_get_mode(
6173 s->selected_entry))) {
6174 struct got_tree_object *subtree;
6175 view->count = 0;
6176 err = got_object_open_as_tree(&subtree, s->repo,
6177 got_tree_entry_get_id(s->selected_entry));
6178 if (err)
6179 break;
6180 err = tree_view_visit_subtree(s, subtree);
6181 if (err) {
6182 got_object_tree_close(subtree);
6183 break;
6185 } else if (S_ISREG(got_tree_entry_get_mode(
6186 s->selected_entry))) {
6187 struct tog_view *blame_view;
6188 int begin_x = view_is_parent_view(view) ?
6189 view_split_begin_x(view->begin_x) : 0;
6191 err = blame_tree_entry(&blame_view, begin_x,
6192 s->selected_entry, &s->parents,
6193 s->commit_id, s->repo);
6194 if (err)
6195 break;
6196 view->count = 0;
6197 view->focussed = 0;
6198 blame_view->focussed = 1;
6199 if (view_is_parent_view(view)) {
6200 err = view_close_child(view);
6201 if (err)
6202 return err;
6203 err = view_set_child(view, blame_view);
6204 if (err)
6205 return err;
6206 view->focus_child = 1;
6207 } else
6208 *new_view = blame_view;
6210 break;
6211 case KEY_RESIZE:
6212 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6213 s->selected = view->nlines - 4;
6214 view->count = 0;
6215 break;
6216 default:
6217 view->count = 0;
6218 break;
6221 return err;
6224 __dead static void
6225 usage_tree(void)
6227 endwin();
6228 fprintf(stderr,
6229 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6230 getprogname());
6231 exit(1);
6234 static const struct got_error *
6235 cmd_tree(int argc, char *argv[])
6237 const struct got_error *error;
6238 struct got_repository *repo = NULL;
6239 struct got_worktree *worktree = NULL;
6240 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6241 struct got_object_id *commit_id = NULL;
6242 struct got_commit_object *commit = NULL;
6243 const char *commit_id_arg = NULL;
6244 char *label = NULL;
6245 struct got_reference *ref = NULL;
6246 const char *head_ref_name = NULL;
6247 int ch;
6248 struct tog_view *view;
6249 int *pack_fds = NULL;
6251 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6252 switch (ch) {
6253 case 'c':
6254 commit_id_arg = optarg;
6255 break;
6256 case 'r':
6257 repo_path = realpath(optarg, NULL);
6258 if (repo_path == NULL)
6259 return got_error_from_errno2("realpath",
6260 optarg);
6261 break;
6262 default:
6263 usage_tree();
6264 /* NOTREACHED */
6268 argc -= optind;
6269 argv += optind;
6271 if (argc > 1)
6272 usage_tree();
6274 error = got_repo_pack_fds_open(&pack_fds);
6275 if (error != NULL)
6276 goto done;
6278 if (repo_path == NULL) {
6279 cwd = getcwd(NULL, 0);
6280 if (cwd == NULL)
6281 return got_error_from_errno("getcwd");
6282 error = got_worktree_open(&worktree, cwd);
6283 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6284 goto done;
6285 if (worktree)
6286 repo_path =
6287 strdup(got_worktree_get_repo_path(worktree));
6288 else
6289 repo_path = strdup(cwd);
6290 if (repo_path == NULL) {
6291 error = got_error_from_errno("strdup");
6292 goto done;
6296 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6297 if (error != NULL)
6298 goto done;
6300 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
6301 repo, worktree);
6302 if (error)
6303 goto done;
6305 init_curses();
6307 error = apply_unveil(got_repo_get_path(repo), NULL);
6308 if (error)
6309 goto done;
6311 error = tog_load_refs(repo, 0);
6312 if (error)
6313 goto done;
6315 if (commit_id_arg == NULL) {
6316 error = got_repo_match_object_id(&commit_id, &label,
6317 worktree ? got_worktree_get_head_ref_name(worktree) :
6318 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6319 if (error)
6320 goto done;
6321 head_ref_name = label;
6322 } else {
6323 error = got_ref_open(&ref, repo, commit_id_arg, 0);
6324 if (error == NULL)
6325 head_ref_name = got_ref_get_name(ref);
6326 else if (error->code != GOT_ERR_NOT_REF)
6327 goto done;
6328 error = got_repo_match_object_id(&commit_id, NULL,
6329 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6330 if (error)
6331 goto done;
6334 error = got_object_open_as_commit(&commit, repo, commit_id);
6335 if (error)
6336 goto done;
6338 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
6339 if (view == NULL) {
6340 error = got_error_from_errno("view_open");
6341 goto done;
6343 error = open_tree_view(view, commit_id, head_ref_name, repo);
6344 if (error)
6345 goto done;
6346 if (!got_path_is_root_dir(in_repo_path)) {
6347 error = tree_view_walk_path(&view->state.tree, commit,
6348 in_repo_path);
6349 if (error)
6350 goto done;
6353 if (worktree) {
6354 /* Release work tree lock. */
6355 got_worktree_close(worktree);
6356 worktree = NULL;
6358 error = view_loop(view);
6359 done:
6360 free(repo_path);
6361 free(cwd);
6362 free(commit_id);
6363 free(label);
6364 if (ref)
6365 got_ref_close(ref);
6366 if (repo) {
6367 const struct got_error *close_err = got_repo_close(repo);
6368 if (error == NULL)
6369 error = close_err;
6371 if (pack_fds) {
6372 const struct got_error *pack_err =
6373 got_repo_pack_fds_close(pack_fds);
6374 if (error == NULL)
6375 error = pack_err;
6377 tog_free_refs();
6378 return error;
6381 static const struct got_error *
6382 ref_view_load_refs(struct tog_ref_view_state *s)
6384 struct got_reflist_entry *sre;
6385 struct tog_reflist_entry *re;
6387 s->nrefs = 0;
6388 TAILQ_FOREACH(sre, &tog_refs, entry) {
6389 if (strncmp(got_ref_get_name(sre->ref),
6390 "refs/got/", 9) == 0 &&
6391 strncmp(got_ref_get_name(sre->ref),
6392 "refs/got/backup/", 16) != 0)
6393 continue;
6395 re = malloc(sizeof(*re));
6396 if (re == NULL)
6397 return got_error_from_errno("malloc");
6399 re->ref = got_ref_dup(sre->ref);
6400 if (re->ref == NULL)
6401 return got_error_from_errno("got_ref_dup");
6402 re->idx = s->nrefs++;
6403 TAILQ_INSERT_TAIL(&s->refs, re, entry);
6406 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6407 return NULL;
6410 void
6411 ref_view_free_refs(struct tog_ref_view_state *s)
6413 struct tog_reflist_entry *re;
6415 while (!TAILQ_EMPTY(&s->refs)) {
6416 re = TAILQ_FIRST(&s->refs);
6417 TAILQ_REMOVE(&s->refs, re, entry);
6418 got_ref_close(re->ref);
6419 free(re);
6423 static const struct got_error *
6424 open_ref_view(struct tog_view *view, struct got_repository *repo)
6426 const struct got_error *err = NULL;
6427 struct tog_ref_view_state *s = &view->state.ref;
6429 s->selected_entry = 0;
6430 s->repo = repo;
6432 TAILQ_INIT(&s->refs);
6433 STAILQ_INIT(&s->colors);
6435 err = ref_view_load_refs(s);
6436 if (err)
6437 return err;
6439 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6440 err = add_color(&s->colors, "^refs/heads/",
6441 TOG_COLOR_REFS_HEADS,
6442 get_color_value("TOG_COLOR_REFS_HEADS"));
6443 if (err)
6444 goto done;
6446 err = add_color(&s->colors, "^refs/tags/",
6447 TOG_COLOR_REFS_TAGS,
6448 get_color_value("TOG_COLOR_REFS_TAGS"));
6449 if (err)
6450 goto done;
6452 err = add_color(&s->colors, "^refs/remotes/",
6453 TOG_COLOR_REFS_REMOTES,
6454 get_color_value("TOG_COLOR_REFS_REMOTES"));
6455 if (err)
6456 goto done;
6458 err = add_color(&s->colors, "^refs/got/backup/",
6459 TOG_COLOR_REFS_BACKUP,
6460 get_color_value("TOG_COLOR_REFS_BACKUP"));
6461 if (err)
6462 goto done;
6465 view->show = show_ref_view;
6466 view->input = input_ref_view;
6467 view->close = close_ref_view;
6468 view->search_start = search_start_ref_view;
6469 view->search_next = search_next_ref_view;
6470 done:
6471 if (err)
6472 free_colors(&s->colors);
6473 return err;
6476 static const struct got_error *
6477 close_ref_view(struct tog_view *view)
6479 struct tog_ref_view_state *s = &view->state.ref;
6481 ref_view_free_refs(s);
6482 free_colors(&s->colors);
6484 return NULL;
6487 static const struct got_error *
6488 resolve_reflist_entry(struct got_object_id **commit_id,
6489 struct tog_reflist_entry *re, struct got_repository *repo)
6491 const struct got_error *err = NULL;
6492 struct got_object_id *obj_id;
6493 struct got_tag_object *tag = NULL;
6494 int obj_type;
6496 *commit_id = NULL;
6498 err = got_ref_resolve(&obj_id, repo, re->ref);
6499 if (err)
6500 return err;
6502 err = got_object_get_type(&obj_type, repo, obj_id);
6503 if (err)
6504 goto done;
6506 switch (obj_type) {
6507 case GOT_OBJ_TYPE_COMMIT:
6508 *commit_id = obj_id;
6509 break;
6510 case GOT_OBJ_TYPE_TAG:
6511 err = got_object_open_as_tag(&tag, repo, obj_id);
6512 if (err)
6513 goto done;
6514 free(obj_id);
6515 err = got_object_get_type(&obj_type, repo,
6516 got_object_tag_get_object_id(tag));
6517 if (err)
6518 goto done;
6519 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
6520 err = got_error(GOT_ERR_OBJ_TYPE);
6521 goto done;
6523 *commit_id = got_object_id_dup(
6524 got_object_tag_get_object_id(tag));
6525 if (*commit_id == NULL) {
6526 err = got_error_from_errno("got_object_id_dup");
6527 goto done;
6529 break;
6530 default:
6531 err = got_error(GOT_ERR_OBJ_TYPE);
6532 break;
6535 done:
6536 if (tag)
6537 got_object_tag_close(tag);
6538 if (err) {
6539 free(*commit_id);
6540 *commit_id = NULL;
6542 return err;
6545 static const struct got_error *
6546 log_ref_entry(struct tog_view **new_view, int begin_x,
6547 struct tog_reflist_entry *re, struct got_repository *repo)
6549 struct tog_view *log_view;
6550 const struct got_error *err = NULL;
6551 struct got_object_id *commit_id = NULL;
6553 *new_view = NULL;
6555 err = resolve_reflist_entry(&commit_id, re, repo);
6556 if (err) {
6557 if (err->code != GOT_ERR_OBJ_TYPE)
6558 return err;
6559 else
6560 return NULL;
6563 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
6564 if (log_view == NULL) {
6565 err = got_error_from_errno("view_open");
6566 goto done;
6569 err = open_log_view(log_view, commit_id, repo,
6570 got_ref_get_name(re->ref), "", 0);
6571 done:
6572 if (err)
6573 view_close(log_view);
6574 else
6575 *new_view = log_view;
6576 free(commit_id);
6577 return err;
6580 static void
6581 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
6583 struct tog_reflist_entry *re;
6584 int i = 0;
6586 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
6587 return;
6589 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
6590 while (i++ < maxscroll) {
6591 if (re == NULL)
6592 break;
6593 s->first_displayed_entry = re;
6594 re = TAILQ_PREV(re, tog_reflist_head, entry);
6598 static void
6599 ref_scroll_down(struct tog_ref_view_state *s, int maxscroll)
6601 struct tog_reflist_entry *next, *last;
6602 int n = 0;
6604 if (s->first_displayed_entry)
6605 next = TAILQ_NEXT(s->first_displayed_entry, entry);
6606 else
6607 next = TAILQ_FIRST(&s->refs);
6609 last = s->last_displayed_entry;
6610 while (next && last && n++ < maxscroll) {
6611 last = TAILQ_NEXT(last, entry);
6612 if (last) {
6613 s->first_displayed_entry = next;
6614 next = TAILQ_NEXT(next, entry);
6619 static const struct got_error *
6620 search_start_ref_view(struct tog_view *view)
6622 struct tog_ref_view_state *s = &view->state.ref;
6624 s->matched_entry = NULL;
6625 return NULL;
6628 static int
6629 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
6631 regmatch_t regmatch;
6633 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
6634 0) == 0;
6637 static const struct got_error *
6638 search_next_ref_view(struct tog_view *view)
6640 struct tog_ref_view_state *s = &view->state.ref;
6641 struct tog_reflist_entry *re = NULL;
6643 if (!view->searching) {
6644 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6645 return NULL;
6648 if (s->matched_entry) {
6649 if (view->searching == TOG_SEARCH_FORWARD) {
6650 if (s->selected_entry)
6651 re = TAILQ_NEXT(s->selected_entry, entry);
6652 else
6653 re = TAILQ_PREV(s->selected_entry,
6654 tog_reflist_head, entry);
6655 } else {
6656 if (s->selected_entry == NULL)
6657 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6658 else
6659 re = TAILQ_PREV(s->selected_entry,
6660 tog_reflist_head, entry);
6662 } else {
6663 if (s->selected_entry)
6664 re = s->selected_entry;
6665 else if (view->searching == TOG_SEARCH_FORWARD)
6666 re = TAILQ_FIRST(&s->refs);
6667 else
6668 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6671 while (1) {
6672 if (re == NULL) {
6673 if (s->matched_entry == NULL) {
6674 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6675 return NULL;
6677 if (view->searching == TOG_SEARCH_FORWARD)
6678 re = TAILQ_FIRST(&s->refs);
6679 else
6680 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6683 if (match_reflist_entry(re, &view->regex)) {
6684 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6685 s->matched_entry = re;
6686 break;
6689 if (view->searching == TOG_SEARCH_FORWARD)
6690 re = TAILQ_NEXT(re, entry);
6691 else
6692 re = TAILQ_PREV(re, tog_reflist_head, entry);
6695 if (s->matched_entry) {
6696 s->first_displayed_entry = s->matched_entry;
6697 s->selected = 0;
6700 return NULL;
6703 static const struct got_error *
6704 show_ref_view(struct tog_view *view)
6706 const struct got_error *err = NULL;
6707 struct tog_ref_view_state *s = &view->state.ref;
6708 struct tog_reflist_entry *re;
6709 char *line = NULL;
6710 wchar_t *wline;
6711 struct tog_color *tc;
6712 int width, n;
6713 int limit = view->nlines;
6715 werase(view->window);
6717 s->ndisplayed = 0;
6719 if (limit == 0)
6720 return NULL;
6722 re = s->first_displayed_entry;
6724 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
6725 s->nrefs) == -1)
6726 return got_error_from_errno("asprintf");
6728 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6729 if (err) {
6730 free(line);
6731 return err;
6733 if (view_needs_focus_indication(view))
6734 wstandout(view->window);
6735 waddwstr(view->window, wline);
6736 if (view_needs_focus_indication(view))
6737 wstandend(view->window);
6738 free(wline);
6739 wline = NULL;
6740 free(line);
6741 line = NULL;
6742 if (width < view->ncols - 1)
6743 waddch(view->window, '\n');
6744 if (--limit <= 0)
6745 return NULL;
6747 n = 0;
6748 while (re && limit > 0) {
6749 char *line = NULL;
6750 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
6752 if (s->show_date) {
6753 struct got_commit_object *ci;
6754 struct got_tag_object *tag;
6755 struct got_object_id *id;
6756 struct tm tm;
6757 time_t t;
6759 err = got_ref_resolve(&id, s->repo, re->ref);
6760 if (err)
6761 return err;
6762 err = got_object_open_as_tag(&tag, s->repo, id);
6763 if (err) {
6764 if (err->code != GOT_ERR_OBJ_TYPE) {
6765 free(id);
6766 return err;
6768 err = got_object_open_as_commit(&ci, s->repo,
6769 id);
6770 if (err) {
6771 free(id);
6772 return err;
6774 t = got_object_commit_get_committer_time(ci);
6775 got_object_commit_close(ci);
6776 } else {
6777 t = got_object_tag_get_tagger_time(tag);
6778 got_object_tag_close(tag);
6780 free(id);
6781 if (gmtime_r(&t, &tm) == NULL)
6782 return got_error_from_errno("gmtime_r");
6783 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
6784 return got_error(GOT_ERR_NO_SPACE);
6786 if (got_ref_is_symbolic(re->ref)) {
6787 if (asprintf(&line, "%s%s -> %s", s->show_date ?
6788 ymd : "", got_ref_get_name(re->ref),
6789 got_ref_get_symref_target(re->ref)) == -1)
6790 return got_error_from_errno("asprintf");
6791 } else if (s->show_ids) {
6792 struct got_object_id *id;
6793 char *id_str;
6794 err = got_ref_resolve(&id, s->repo, re->ref);
6795 if (err)
6796 return err;
6797 err = got_object_id_str(&id_str, id);
6798 if (err) {
6799 free(id);
6800 return err;
6802 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
6803 got_ref_get_name(re->ref), id_str) == -1) {
6804 err = got_error_from_errno("asprintf");
6805 free(id);
6806 free(id_str);
6807 return err;
6809 free(id);
6810 free(id_str);
6811 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
6812 got_ref_get_name(re->ref)) == -1)
6813 return got_error_from_errno("asprintf");
6815 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6816 0, 0);
6817 if (err) {
6818 free(line);
6819 return err;
6821 if (n == s->selected) {
6822 if (view->focussed)
6823 wstandout(view->window);
6824 s->selected_entry = re;
6826 tc = match_color(&s->colors, got_ref_get_name(re->ref));
6827 if (tc)
6828 wattr_on(view->window,
6829 COLOR_PAIR(tc->colorpair), NULL);
6830 waddwstr(view->window, wline);
6831 if (tc)
6832 wattr_off(view->window,
6833 COLOR_PAIR(tc->colorpair), NULL);
6834 if (width < view->ncols - 1)
6835 waddch(view->window, '\n');
6836 if (n == s->selected && view->focussed)
6837 wstandend(view->window);
6838 free(line);
6839 free(wline);
6840 wline = NULL;
6841 n++;
6842 s->ndisplayed++;
6843 s->last_displayed_entry = re;
6845 limit--;
6846 re = TAILQ_NEXT(re, entry);
6849 view_vborder(view);
6850 return err;
6853 static const struct got_error *
6854 browse_ref_tree(struct tog_view **new_view, int begin_x,
6855 struct tog_reflist_entry *re, struct got_repository *repo)
6857 const struct got_error *err = NULL;
6858 struct got_object_id *commit_id = NULL;
6859 struct tog_view *tree_view;
6861 *new_view = NULL;
6863 err = resolve_reflist_entry(&commit_id, re, repo);
6864 if (err) {
6865 if (err->code != GOT_ERR_OBJ_TYPE)
6866 return err;
6867 else
6868 return NULL;
6872 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
6873 if (tree_view == NULL) {
6874 err = got_error_from_errno("view_open");
6875 goto done;
6878 err = open_tree_view(tree_view, commit_id,
6879 got_ref_get_name(re->ref), repo);
6880 if (err)
6881 goto done;
6883 *new_view = tree_view;
6884 done:
6885 free(commit_id);
6886 return err;
6888 static const struct got_error *
6889 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
6891 const struct got_error *err = NULL;
6892 struct tog_ref_view_state *s = &view->state.ref;
6893 struct tog_view *log_view, *tree_view;
6894 struct tog_reflist_entry *re;
6895 int begin_x = 0, n, nscroll = view->nlines - 1;
6897 switch (ch) {
6898 case 'i':
6899 s->show_ids = !s->show_ids;
6900 view->count = 0;
6901 break;
6902 case 'm':
6903 s->show_date = !s->show_date;
6904 view->count = 0;
6905 break;
6906 case 'o':
6907 s->sort_by_date = !s->sort_by_date;
6908 view->count = 0;
6909 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
6910 got_ref_cmp_by_commit_timestamp_descending :
6911 tog_ref_cmp_by_name, s->repo);
6912 if (err)
6913 break;
6914 got_reflist_object_id_map_free(tog_refs_idmap);
6915 err = got_reflist_object_id_map_create(&tog_refs_idmap,
6916 &tog_refs, s->repo);
6917 if (err)
6918 break;
6919 ref_view_free_refs(s);
6920 err = ref_view_load_refs(s);
6921 break;
6922 case KEY_ENTER:
6923 case '\r':
6924 view->count = 0;
6925 if (!s->selected_entry)
6926 break;
6927 if (view_is_parent_view(view))
6928 begin_x = view_split_begin_x(view->begin_x);
6929 err = log_ref_entry(&log_view, begin_x, s->selected_entry,
6930 s->repo);
6931 view->focussed = 0;
6932 log_view->focussed = 1;
6933 if (view_is_parent_view(view)) {
6934 err = view_close_child(view);
6935 if (err)
6936 return err;
6937 err = view_set_child(view, log_view);
6938 if (err)
6939 return err;
6940 view->focus_child = 1;
6941 } else
6942 *new_view = log_view;
6943 break;
6944 case 't':
6945 view->count = 0;
6946 if (!s->selected_entry)
6947 break;
6948 if (view_is_parent_view(view))
6949 begin_x = view_split_begin_x(view->begin_x);
6950 err = browse_ref_tree(&tree_view, begin_x, s->selected_entry,
6951 s->repo);
6952 if (err || tree_view == NULL)
6953 break;
6954 view->focussed = 0;
6955 tree_view->focussed = 1;
6956 if (view_is_parent_view(view)) {
6957 err = view_close_child(view);
6958 if (err)
6959 return err;
6960 err = view_set_child(view, tree_view);
6961 if (err)
6962 return err;
6963 view->focus_child = 1;
6964 } else
6965 *new_view = tree_view;
6966 break;
6967 case 'g':
6968 case KEY_HOME:
6969 s->selected = 0;
6970 view->count = 0;
6971 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6972 break;
6973 case 'G':
6974 case KEY_END:
6975 s->selected = 0;
6976 view->count = 0;
6977 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6978 for (n = 0; n < view->nlines - 1; n++) {
6979 if (re == NULL)
6980 break;
6981 s->first_displayed_entry = re;
6982 re = TAILQ_PREV(re, tog_reflist_head, entry);
6984 if (n > 0)
6985 s->selected = n - 1;
6986 break;
6987 case 'k':
6988 case KEY_UP:
6989 case CTRL('p'):
6990 if (s->selected > 0) {
6991 s->selected--;
6992 break;
6994 ref_scroll_up(s, 1);
6995 if (s->selected_entry == TAILQ_FIRST(&s->refs))
6996 view->count = 0;
6997 break;
6998 case CTRL('u'):
6999 case 'u':
7000 nscroll /= 2;
7001 /* FALL THROUGH */
7002 case KEY_PPAGE:
7003 case CTRL('b'):
7004 case 'b':
7005 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7006 s->selected -= MIN(nscroll, s->selected);
7007 ref_scroll_up(s, MAX(0, nscroll));
7008 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7009 view->count = 0;
7010 break;
7011 case 'j':
7012 case KEY_DOWN:
7013 case CTRL('n'):
7014 if (s->selected < s->ndisplayed - 1) {
7015 s->selected++;
7016 break;
7018 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7019 /* can't scroll any further */
7020 view->count = 0;
7021 break;
7023 ref_scroll_down(s, 1);
7024 break;
7025 case CTRL('d'):
7026 case 'd':
7027 nscroll /= 2;
7028 /* FALL THROUGH */
7029 case KEY_NPAGE:
7030 case CTRL('f'):
7031 case 'f':
7032 case ' ':
7033 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7034 /* can't scroll any further; move cursor down */
7035 if (s->selected < s->ndisplayed - 1)
7036 s->selected += MIN(nscroll,
7037 s->ndisplayed - s->selected - 1);
7038 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7039 s->selected += s->ndisplayed - s->selected - 1;
7040 view->count = 0;
7041 break;
7043 ref_scroll_down(s, nscroll);
7044 break;
7045 case CTRL('l'):
7046 view->count = 0;
7047 tog_free_refs();
7048 err = tog_load_refs(s->repo, s->sort_by_date);
7049 if (err)
7050 break;
7051 ref_view_free_refs(s);
7052 err = ref_view_load_refs(s);
7053 break;
7054 case KEY_RESIZE:
7055 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7056 s->selected = view->nlines - 2;
7057 break;
7058 default:
7059 view->count = 0;
7060 break;
7063 return err;
7066 __dead static void
7067 usage_ref(void)
7069 endwin();
7070 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7071 getprogname());
7072 exit(1);
7075 static const struct got_error *
7076 cmd_ref(int argc, char *argv[])
7078 const struct got_error *error;
7079 struct got_repository *repo = NULL;
7080 struct got_worktree *worktree = NULL;
7081 char *cwd = NULL, *repo_path = NULL;
7082 int ch;
7083 struct tog_view *view;
7084 int *pack_fds = NULL;
7086 while ((ch = getopt(argc, argv, "r:")) != -1) {
7087 switch (ch) {
7088 case 'r':
7089 repo_path = realpath(optarg, NULL);
7090 if (repo_path == NULL)
7091 return got_error_from_errno2("realpath",
7092 optarg);
7093 break;
7094 default:
7095 usage_ref();
7096 /* NOTREACHED */
7100 argc -= optind;
7101 argv += optind;
7103 if (argc > 1)
7104 usage_ref();
7106 error = got_repo_pack_fds_open(&pack_fds);
7107 if (error != NULL)
7108 goto done;
7110 if (repo_path == NULL) {
7111 cwd = getcwd(NULL, 0);
7112 if (cwd == NULL)
7113 return got_error_from_errno("getcwd");
7114 error = got_worktree_open(&worktree, cwd);
7115 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7116 goto done;
7117 if (worktree)
7118 repo_path =
7119 strdup(got_worktree_get_repo_path(worktree));
7120 else
7121 repo_path = strdup(cwd);
7122 if (repo_path == NULL) {
7123 error = got_error_from_errno("strdup");
7124 goto done;
7128 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7129 if (error != NULL)
7130 goto done;
7132 init_curses();
7134 error = apply_unveil(got_repo_get_path(repo), NULL);
7135 if (error)
7136 goto done;
7138 error = tog_load_refs(repo, 0);
7139 if (error)
7140 goto done;
7142 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7143 if (view == NULL) {
7144 error = got_error_from_errno("view_open");
7145 goto done;
7148 error = open_ref_view(view, repo);
7149 if (error)
7150 goto done;
7152 if (worktree) {
7153 /* Release work tree lock. */
7154 got_worktree_close(worktree);
7155 worktree = NULL;
7157 error = view_loop(view);
7158 done:
7159 free(repo_path);
7160 free(cwd);
7161 if (repo) {
7162 const struct got_error *close_err = got_repo_close(repo);
7163 if (close_err)
7164 error = close_err;
7166 if (pack_fds) {
7167 const struct got_error *pack_err =
7168 got_repo_pack_fds_close(pack_fds);
7169 if (error == NULL)
7170 error = pack_err;
7172 tog_free_refs();
7173 return error;
7176 static void
7177 list_commands(FILE *fp)
7179 size_t i;
7181 fprintf(fp, "commands:");
7182 for (i = 0; i < nitems(tog_commands); i++) {
7183 const struct tog_cmd *cmd = &tog_commands[i];
7184 fprintf(fp, " %s", cmd->name);
7186 fputc('\n', fp);
7189 __dead static void
7190 usage(int hflag, int status)
7192 FILE *fp = (status == 0) ? stdout : stderr;
7194 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
7195 getprogname());
7196 if (hflag) {
7197 fprintf(fp, "lazy usage: %s path\n", getprogname());
7198 list_commands(fp);
7200 exit(status);
7203 static char **
7204 make_argv(int argc, ...)
7206 va_list ap;
7207 char **argv;
7208 int i;
7210 va_start(ap, argc);
7212 argv = calloc(argc, sizeof(char *));
7213 if (argv == NULL)
7214 err(1, "calloc");
7215 for (i = 0; i < argc; i++) {
7216 argv[i] = strdup(va_arg(ap, char *));
7217 if (argv[i] == NULL)
7218 err(1, "strdup");
7221 va_end(ap);
7222 return argv;
7226 * Try to convert 'tog path' into a 'tog log path' command.
7227 * The user could simply have mistyped the command rather than knowingly
7228 * provided a path. So check whether argv[0] can in fact be resolved
7229 * to a path in the HEAD commit and print a special error if not.
7230 * This hack is for mpi@ <3
7232 static const struct got_error *
7233 tog_log_with_path(int argc, char *argv[])
7235 const struct got_error *error = NULL, *close_err;
7236 const struct tog_cmd *cmd = NULL;
7237 struct got_repository *repo = NULL;
7238 struct got_worktree *worktree = NULL;
7239 struct got_object_id *commit_id = NULL, *id = NULL;
7240 struct got_commit_object *commit = NULL;
7241 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7242 char *commit_id_str = NULL, **cmd_argv = NULL;
7243 int *pack_fds = NULL;
7245 cwd = getcwd(NULL, 0);
7246 if (cwd == NULL)
7247 return got_error_from_errno("getcwd");
7249 error = got_repo_pack_fds_open(&pack_fds);
7250 if (error != NULL)
7251 goto done;
7253 error = got_worktree_open(&worktree, cwd);
7254 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7255 goto done;
7257 if (worktree)
7258 repo_path = strdup(got_worktree_get_repo_path(worktree));
7259 else
7260 repo_path = strdup(cwd);
7261 if (repo_path == NULL) {
7262 error = got_error_from_errno("strdup");
7263 goto done;
7266 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7267 if (error != NULL)
7268 goto done;
7270 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7271 repo, worktree);
7272 if (error)
7273 goto done;
7275 error = tog_load_refs(repo, 0);
7276 if (error)
7277 goto done;
7278 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
7279 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
7280 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7281 if (error)
7282 goto done;
7284 if (worktree) {
7285 got_worktree_close(worktree);
7286 worktree = NULL;
7289 error = got_object_open_as_commit(&commit, repo, commit_id);
7290 if (error)
7291 goto done;
7293 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
7294 if (error) {
7295 if (error->code != GOT_ERR_NO_TREE_ENTRY)
7296 goto done;
7297 fprintf(stderr, "%s: '%s' is no known command or path\n",
7298 getprogname(), argv[0]);
7299 usage(1, 1);
7300 /* not reached */
7303 close_err = got_repo_close(repo);
7304 if (error == NULL)
7305 error = close_err;
7306 repo = NULL;
7308 error = got_object_id_str(&commit_id_str, commit_id);
7309 if (error)
7310 goto done;
7312 cmd = &tog_commands[0]; /* log */
7313 argc = 4;
7314 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
7315 error = cmd->cmd_main(argc, cmd_argv);
7316 done:
7317 if (repo) {
7318 close_err = got_repo_close(repo);
7319 if (error == NULL)
7320 error = close_err;
7322 if (commit)
7323 got_object_commit_close(commit);
7324 if (worktree)
7325 got_worktree_close(worktree);
7326 if (pack_fds) {
7327 const struct got_error *pack_err =
7328 got_repo_pack_fds_close(pack_fds);
7329 if (error == NULL)
7330 error = pack_err;
7332 free(id);
7333 free(commit_id_str);
7334 free(commit_id);
7335 free(cwd);
7336 free(repo_path);
7337 free(in_repo_path);
7338 if (cmd_argv) {
7339 int i;
7340 for (i = 0; i < argc; i++)
7341 free(cmd_argv[i]);
7342 free(cmd_argv);
7344 tog_free_refs();
7345 return error;
7348 int
7349 main(int argc, char *argv[])
7351 const struct got_error *error = NULL;
7352 const struct tog_cmd *cmd = NULL;
7353 int ch, hflag = 0, Vflag = 0;
7354 char **cmd_argv = NULL;
7355 static const struct option longopts[] = {
7356 { "version", no_argument, NULL, 'V' },
7357 { NULL, 0, NULL, 0}
7360 setlocale(LC_CTYPE, "");
7362 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
7363 switch (ch) {
7364 case 'h':
7365 hflag = 1;
7366 break;
7367 case 'V':
7368 Vflag = 1;
7369 break;
7370 default:
7371 usage(hflag, 1);
7372 /* NOTREACHED */
7376 argc -= optind;
7377 argv += optind;
7378 optind = 1;
7379 optreset = 1;
7381 if (Vflag) {
7382 got_version_print_str();
7383 return 0;
7386 #ifndef PROFILE
7387 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
7388 NULL) == -1)
7389 err(1, "pledge");
7390 #endif
7392 if (argc == 0) {
7393 if (hflag)
7394 usage(hflag, 0);
7395 /* Build an argument vector which runs a default command. */
7396 cmd = &tog_commands[0];
7397 argc = 1;
7398 cmd_argv = make_argv(argc, cmd->name);
7399 } else {
7400 size_t i;
7402 /* Did the user specify a command? */
7403 for (i = 0; i < nitems(tog_commands); i++) {
7404 if (strncmp(tog_commands[i].name, argv[0],
7405 strlen(argv[0])) == 0) {
7406 cmd = &tog_commands[i];
7407 break;
7412 if (cmd == NULL) {
7413 if (argc != 1)
7414 usage(0, 1);
7415 /* No command specified; try log with a path */
7416 error = tog_log_with_path(argc, argv);
7417 } else {
7418 if (hflag)
7419 cmd->cmd_usage();
7420 else
7421 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
7424 endwin();
7425 putchar('\n');
7426 if (cmd_argv) {
7427 int i;
7428 for (i = 0; i < argc; i++)
7429 free(cmd_argv[i]);
7430 free(cmd_argv);
7433 if (error && error->code != GOT_ERR_CANCELLED)
7434 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7435 return 0;