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/stat.h>
18 #include <sys/ioctl.h>
20 #include <ctype.h>
21 #include <errno.h>
22 #if defined(__FreeBSD__) || defined(__APPLE__)
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #endif
25 #include <curses.h>
26 #include <panel.h>
27 #include <locale.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_compat.h"
46 #include "got_version.h"
47 #include "got_error.h"
48 #include "got_object.h"
49 #include "got_reference.h"
50 #include "got_repository.h"
51 #include "got_diff.h"
52 #include "got_opentemp.h"
53 #include "got_utf8.h"
54 #include "got_cancel.h"
55 #include "got_commit_graph.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_path.h"
59 #include "got_worktree.h"
61 //#define update_panels() (0)
62 //#define doupdate() (0)
64 #ifndef MIN
65 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
66 #endif
68 #ifndef MAX
69 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
70 #endif
72 #ifndef CTRL
73 #define CTRL(x) ((x) & 0x1f)
74 #endif
76 #ifndef nitems
77 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
78 #endif
80 struct tog_cmd {
81 const char *name;
82 const struct got_error *(*cmd_main)(int, char *[]);
83 void (*cmd_usage)(void);
84 };
86 __dead static void usage(int, int);
87 __dead static void usage_log(void);
88 __dead static void usage_diff(void);
89 __dead static void usage_blame(void);
90 __dead static void usage_tree(void);
91 __dead static void usage_ref(void);
93 static const struct got_error* cmd_log(int, char *[]);
94 static const struct got_error* cmd_diff(int, char *[]);
95 static const struct got_error* cmd_blame(int, char *[]);
96 static const struct got_error* cmd_tree(int, char *[]);
97 static const struct got_error* cmd_ref(int, char *[]);
99 static const struct tog_cmd tog_commands[] = {
100 { "log", cmd_log, usage_log },
101 { "diff", cmd_diff, usage_diff },
102 { "blame", cmd_blame, usage_blame },
103 { "tree", cmd_tree, usage_tree },
104 { "ref", cmd_ref, usage_ref },
105 };
107 enum tog_view_type {
108 TOG_VIEW_DIFF,
109 TOG_VIEW_LOG,
110 TOG_VIEW_BLAME,
111 TOG_VIEW_TREE,
112 TOG_VIEW_REF,
113 };
115 #define TOG_EOF_STRING "(END)"
117 struct commit_queue_entry {
118 TAILQ_ENTRY(commit_queue_entry) entry;
119 struct got_object_id *id;
120 struct got_commit_object *commit;
121 int idx;
122 };
123 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
124 struct commit_queue {
125 int ncommits;
126 struct commit_queue_head head;
127 };
129 struct tog_color {
130 STAILQ_ENTRY(tog_color) entry;
131 regex_t regex;
132 short colorpair;
133 };
134 STAILQ_HEAD(tog_colors, tog_color);
136 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
137 static struct got_reflist_object_id_map *tog_refs_idmap;
139 static const struct got_error *
140 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
141 struct got_reference* re2)
143 const char *name1 = got_ref_get_name(re1);
144 const char *name2 = got_ref_get_name(re2);
145 int isbackup1, isbackup2;
147 /* Sort backup refs towards the bottom of the list. */
148 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
149 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
150 if (!isbackup1 && isbackup2) {
151 *cmp = -1;
152 return NULL;
153 } else if (isbackup1 && !isbackup2) {
154 *cmp = 1;
155 return NULL;
158 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
159 return NULL;
162 static const struct got_error *
163 tog_load_refs(struct got_repository *repo, int sort_by_date)
165 const struct got_error *err;
167 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
168 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
169 repo);
170 if (err)
171 return err;
173 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
174 repo);
177 static void
178 tog_free_refs(void)
180 if (tog_refs_idmap) {
181 got_reflist_object_id_map_free(tog_refs_idmap);
182 tog_refs_idmap = NULL;
184 got_ref_list_free(&tog_refs);
187 static const struct got_error *
188 add_color(struct tog_colors *colors, const char *pattern,
189 int idx, short color)
191 const struct got_error *err = NULL;
192 struct tog_color *tc;
193 int regerr = 0;
195 if (idx < 1 || idx > COLOR_PAIRS - 1)
196 return NULL;
198 init_pair(idx, color, -1);
200 tc = calloc(1, sizeof(*tc));
201 if (tc == NULL)
202 return got_error_from_errno("calloc");
203 regerr = regcomp(&tc->regex, pattern,
204 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
205 if (regerr) {
206 static char regerr_msg[512];
207 static char err_msg[512];
208 regerror(regerr, &tc->regex, regerr_msg,
209 sizeof(regerr_msg));
210 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
211 regerr_msg);
212 err = got_error_msg(GOT_ERR_REGEX, err_msg);
213 free(tc);
214 return err;
216 tc->colorpair = idx;
217 STAILQ_INSERT_HEAD(colors, tc, entry);
218 return NULL;
221 static void
222 free_colors(struct tog_colors *colors)
224 struct tog_color *tc;
226 while (!STAILQ_EMPTY(colors)) {
227 tc = STAILQ_FIRST(colors);
228 STAILQ_REMOVE_HEAD(colors, entry);
229 regfree(&tc->regex);
230 free(tc);
234 static struct tog_color *
235 get_color(struct tog_colors *colors, int colorpair)
237 struct tog_color *tc = NULL;
239 STAILQ_FOREACH(tc, colors, entry) {
240 if (tc->colorpair == colorpair)
241 return tc;
244 return NULL;
247 static int
248 default_color_value(const char *envvar)
250 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
251 return COLOR_MAGENTA;
252 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
253 return COLOR_CYAN;
254 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
255 return COLOR_YELLOW;
256 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
257 return COLOR_GREEN;
258 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
259 return COLOR_MAGENTA;
260 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
261 return COLOR_MAGENTA;
262 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
263 return COLOR_CYAN;
264 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
265 return COLOR_GREEN;
266 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
267 return COLOR_GREEN;
268 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
269 return COLOR_CYAN;
270 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
271 return COLOR_YELLOW;
272 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
273 return COLOR_GREEN;
274 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
275 return COLOR_MAGENTA;
276 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
277 return COLOR_YELLOW;
278 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
279 return COLOR_CYAN;
281 return -1;
284 static int
285 get_color_value(const char *envvar)
287 const char *val = getenv(envvar);
289 if (val == NULL)
290 return default_color_value(envvar);
292 if (strcasecmp(val, "black") == 0)
293 return COLOR_BLACK;
294 if (strcasecmp(val, "red") == 0)
295 return COLOR_RED;
296 if (strcasecmp(val, "green") == 0)
297 return COLOR_GREEN;
298 if (strcasecmp(val, "yellow") == 0)
299 return COLOR_YELLOW;
300 if (strcasecmp(val, "blue") == 0)
301 return COLOR_BLUE;
302 if (strcasecmp(val, "magenta") == 0)
303 return COLOR_MAGENTA;
304 if (strcasecmp(val, "cyan") == 0)
305 return COLOR_CYAN;
306 if (strcasecmp(val, "white") == 0)
307 return COLOR_WHITE;
308 if (strcasecmp(val, "default") == 0)
309 return -1;
311 return default_color_value(envvar);
315 struct tog_diff_view_state {
316 struct got_object_id *id1, *id2;
317 const char *label1, *label2;
318 FILE *f, *f1, *f2;
319 int first_displayed_line;
320 int last_displayed_line;
321 int eof;
322 int diff_context;
323 int ignore_whitespace;
324 int force_text_diff;
325 struct got_repository *repo;
326 struct tog_colors colors;
327 size_t nlines;
328 off_t *line_offsets;
329 int matched_line;
330 int selected_line;
332 /* passed from log view; may be NULL */
333 struct tog_view *log_view;
334 };
336 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
338 struct tog_log_thread_args {
339 pthread_cond_t need_commits;
340 pthread_cond_t commit_loaded;
341 int commits_needed;
342 int load_all;
343 struct got_commit_graph *graph;
344 struct commit_queue *commits;
345 const char *in_repo_path;
346 struct got_object_id *start_id;
347 struct got_repository *repo;
348 int *pack_fds;
349 int log_complete;
350 sig_atomic_t *quit;
351 struct commit_queue_entry **first_displayed_entry;
352 struct commit_queue_entry **selected_entry;
353 int *searching;
354 int *search_next_done;
355 regex_t *regex;
356 };
358 struct tog_log_view_state {
359 struct commit_queue commits;
360 struct commit_queue_entry *first_displayed_entry;
361 struct commit_queue_entry *last_displayed_entry;
362 struct commit_queue_entry *selected_entry;
363 int selected;
364 char *in_repo_path;
365 char *head_ref_name;
366 int log_branches;
367 struct got_repository *repo;
368 struct got_object_id *start_id;
369 sig_atomic_t quit;
370 pthread_t thread;
371 struct tog_log_thread_args thread_args;
372 struct commit_queue_entry *matched_entry;
373 struct commit_queue_entry *search_entry;
374 struct tog_colors colors;
375 };
377 #define TOG_COLOR_DIFF_MINUS 1
378 #define TOG_COLOR_DIFF_PLUS 2
379 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
380 #define TOG_COLOR_DIFF_META 4
381 #define TOG_COLOR_TREE_SUBMODULE 5
382 #define TOG_COLOR_TREE_SYMLINK 6
383 #define TOG_COLOR_TREE_DIRECTORY 7
384 #define TOG_COLOR_TREE_EXECUTABLE 8
385 #define TOG_COLOR_COMMIT 9
386 #define TOG_COLOR_AUTHOR 10
387 #define TOG_COLOR_DATE 11
388 #define TOG_COLOR_REFS_HEADS 12
389 #define TOG_COLOR_REFS_TAGS 13
390 #define TOG_COLOR_REFS_REMOTES 14
391 #define TOG_COLOR_REFS_BACKUP 15
393 struct tog_blame_cb_args {
394 struct tog_blame_line *lines; /* one per line */
395 int nlines;
397 struct tog_view *view;
398 struct got_object_id *commit_id;
399 int *quit;
400 };
402 struct tog_blame_thread_args {
403 const char *path;
404 struct got_repository *repo;
405 struct tog_blame_cb_args *cb_args;
406 int *complete;
407 got_cancel_cb cancel_cb;
408 void *cancel_arg;
409 };
411 struct tog_blame {
412 FILE *f;
413 off_t filesize;
414 struct tog_blame_line *lines;
415 int nlines;
416 off_t *line_offsets;
417 pthread_t thread;
418 struct tog_blame_thread_args thread_args;
419 struct tog_blame_cb_args cb_args;
420 const char *path;
421 int *pack_fds;
422 };
424 struct tog_blame_view_state {
425 int first_displayed_line;
426 int last_displayed_line;
427 int selected_line;
428 int blame_complete;
429 int eof;
430 int done;
431 struct got_object_id_queue blamed_commits;
432 struct got_object_qid *blamed_commit;
433 char *path;
434 struct got_repository *repo;
435 struct got_object_id *commit_id;
436 struct tog_blame blame;
437 int matched_line;
438 struct tog_colors colors;
439 };
441 struct tog_parent_tree {
442 TAILQ_ENTRY(tog_parent_tree) entry;
443 struct got_tree_object *tree;
444 struct got_tree_entry *first_displayed_entry;
445 struct got_tree_entry *selected_entry;
446 int selected;
447 };
449 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
451 struct tog_tree_view_state {
452 char *tree_label;
453 struct got_object_id *commit_id;/* commit which this tree belongs to */
454 struct got_tree_object *root; /* the commit's root tree entry */
455 struct got_tree_object *tree; /* currently displayed (sub-)tree */
456 struct got_tree_entry *first_displayed_entry;
457 struct got_tree_entry *last_displayed_entry;
458 struct got_tree_entry *selected_entry;
459 int ndisplayed, selected, show_ids;
460 struct tog_parent_trees parents; /* parent trees of current sub-tree */
461 char *head_ref_name;
462 struct got_repository *repo;
463 struct got_tree_entry *matched_entry;
464 struct tog_colors colors;
465 };
467 struct tog_reflist_entry {
468 TAILQ_ENTRY(tog_reflist_entry) entry;
469 struct got_reference *ref;
470 int idx;
471 };
473 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
475 struct tog_ref_view_state {
476 struct tog_reflist_head refs;
477 struct tog_reflist_entry *first_displayed_entry;
478 struct tog_reflist_entry *last_displayed_entry;
479 struct tog_reflist_entry *selected_entry;
480 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
481 struct got_repository *repo;
482 struct tog_reflist_entry *matched_entry;
483 struct tog_colors colors;
484 };
486 /*
487 * We implement two types of views: parent views and child views.
489 * The 'Tab' key switches focus between a parent view and its child view.
490 * Child views are shown side-by-side to their parent view, provided
491 * there is enough screen estate.
493 * When a new view is opened from within a parent view, this new view
494 * becomes a child view of the parent view, replacing any existing child.
496 * When a new view is opened from within a child view, this new view
497 * becomes a parent view which will obscure the views below until the
498 * user quits the new parent view by typing 'q'.
500 * This list of views contains parent views only.
501 * Child views are only pointed to by their parent view.
502 */
503 TAILQ_HEAD(tog_view_list_head, tog_view);
505 struct tog_view {
506 TAILQ_ENTRY(tog_view) entry;
507 WINDOW *window;
508 PANEL *panel;
509 int nlines, ncols, begin_y, begin_x;
510 int maxx, x; /* max column and current start column */
511 int lines, cols; /* copies of LINES and COLS */
512 int ch, count; /* current keymap and count prefix */
513 int focussed; /* Only set on one parent or child view at a time. */
514 int dying;
515 struct tog_view *parent;
516 struct tog_view *child;
518 /*
519 * This flag is initially set on parent views when a new child view
520 * is created. It gets toggled when the 'Tab' key switches focus
521 * between parent and child.
522 * The flag indicates whether focus should be passed on to our child
523 * view if this parent view gets picked for focus after another parent
524 * view was closed. This prevents child views from losing focus in such
525 * situations.
526 */
527 int focus_child;
529 /* type-specific state */
530 enum tog_view_type type;
531 union {
532 struct tog_diff_view_state diff;
533 struct tog_log_view_state log;
534 struct tog_blame_view_state blame;
535 struct tog_tree_view_state tree;
536 struct tog_ref_view_state ref;
537 } state;
539 const struct got_error *(*show)(struct tog_view *);
540 const struct got_error *(*input)(struct tog_view **,
541 struct tog_view *, int);
542 const struct got_error *(*close)(struct tog_view *);
544 const struct got_error *(*search_start)(struct tog_view *);
545 const struct got_error *(*search_next)(struct tog_view *);
546 int search_started;
547 int searching;
548 #define TOG_SEARCH_FORWARD 1
549 #define TOG_SEARCH_BACKWARD 2
550 int search_next_done;
551 #define TOG_SEARCH_HAVE_MORE 1
552 #define TOG_SEARCH_NO_MORE 2
553 #define TOG_SEARCH_HAVE_NONE 3
554 regex_t regex;
555 regmatch_t regmatch;
556 };
558 static const struct got_error *open_diff_view(struct tog_view *,
559 struct got_object_id *, struct got_object_id *,
560 const char *, const char *, int, int, int, struct tog_view *,
561 struct got_repository *);
562 static const struct got_error *show_diff_view(struct tog_view *);
563 static const struct got_error *input_diff_view(struct tog_view **,
564 struct tog_view *, int);
565 static const struct got_error* close_diff_view(struct tog_view *);
566 static const struct got_error *search_start_diff_view(struct tog_view *);
567 static const struct got_error *search_next_diff_view(struct tog_view *);
569 static const struct got_error *open_log_view(struct tog_view *,
570 struct got_object_id *, struct got_repository *,
571 const char *, const char *, int);
572 static const struct got_error * show_log_view(struct tog_view *);
573 static const struct got_error *input_log_view(struct tog_view **,
574 struct tog_view *, int);
575 static const struct got_error *close_log_view(struct tog_view *);
576 static const struct got_error *search_start_log_view(struct tog_view *);
577 static const struct got_error *search_next_log_view(struct tog_view *);
579 static const struct got_error *open_blame_view(struct tog_view *, char *,
580 struct got_object_id *, struct got_repository *);
581 static const struct got_error *show_blame_view(struct tog_view *);
582 static const struct got_error *input_blame_view(struct tog_view **,
583 struct tog_view *, int);
584 static const struct got_error *close_blame_view(struct tog_view *);
585 static const struct got_error *search_start_blame_view(struct tog_view *);
586 static const struct got_error *search_next_blame_view(struct tog_view *);
588 static const struct got_error *open_tree_view(struct tog_view *,
589 struct got_object_id *, const char *, struct got_repository *);
590 static const struct got_error *show_tree_view(struct tog_view *);
591 static const struct got_error *input_tree_view(struct tog_view **,
592 struct tog_view *, int);
593 static const struct got_error *close_tree_view(struct tog_view *);
594 static const struct got_error *search_start_tree_view(struct tog_view *);
595 static const struct got_error *search_next_tree_view(struct tog_view *);
597 static const struct got_error *open_ref_view(struct tog_view *,
598 struct got_repository *);
599 static const struct got_error *show_ref_view(struct tog_view *);
600 static const struct got_error *input_ref_view(struct tog_view **,
601 struct tog_view *, int);
602 static const struct got_error *close_ref_view(struct tog_view *);
603 static const struct got_error *search_start_ref_view(struct tog_view *);
604 static const struct got_error *search_next_ref_view(struct tog_view *);
606 static volatile sig_atomic_t tog_sigwinch_received;
607 static volatile sig_atomic_t tog_sigpipe_received;
608 static volatile sig_atomic_t tog_sigcont_received;
609 static volatile sig_atomic_t tog_sigint_received;
610 static volatile sig_atomic_t tog_sigterm_received;
612 static void
613 tog_sigwinch(int signo)
615 tog_sigwinch_received = 1;
618 static void
619 tog_sigpipe(int signo)
621 tog_sigpipe_received = 1;
624 static void
625 tog_sigcont(int signo)
627 tog_sigcont_received = 1;
630 static void
631 tog_sigint(int signo)
633 tog_sigint_received = 1;
636 static void
637 tog_sigterm(int signo)
639 tog_sigterm_received = 1;
642 static int
643 tog_fatal_signal_received(void)
645 return (tog_sigpipe_received ||
646 tog_sigint_received || tog_sigint_received);
650 static const struct got_error *
651 view_close(struct tog_view *view)
653 const struct got_error *err = NULL;
655 if (view->child) {
656 view_close(view->child);
657 view->child = NULL;
659 if (view->close)
660 err = view->close(view);
661 if (view->panel)
662 del_panel(view->panel);
663 if (view->window)
664 delwin(view->window);
665 free(view);
666 return err;
669 static struct tog_view *
670 view_open(int nlines, int ncols, int begin_y, int begin_x,
671 enum tog_view_type type)
673 struct tog_view *view = calloc(1, sizeof(*view));
675 if (view == NULL)
676 return NULL;
678 view->ch = 0;
679 view->count = 0;
680 view->type = type;
681 view->lines = LINES;
682 view->cols = COLS;
683 view->nlines = nlines ? nlines : LINES - begin_y;
684 view->ncols = ncols ? ncols : COLS - begin_x;
685 view->begin_y = begin_y;
686 view->begin_x = begin_x;
687 view->window = newwin(nlines, ncols, begin_y, begin_x);
688 if (view->window == NULL) {
689 view_close(view);
690 return NULL;
692 view->panel = new_panel(view->window);
693 if (view->panel == NULL ||
694 set_panel_userptr(view->panel, view) != OK) {
695 view_close(view);
696 return NULL;
699 keypad(view->window, TRUE);
700 return view;
703 static int
704 view_split_begin_x(int begin_x)
706 if (begin_x > 0 || COLS < 120)
707 return 0;
708 return (COLS - MAX(COLS / 2, 80));
711 static const struct got_error *view_resize(struct tog_view *);
713 static const struct got_error *
714 view_splitscreen(struct tog_view *view)
716 const struct got_error *err = NULL;
718 view->begin_y = 0;
719 view->begin_x = view_split_begin_x(0);
720 view->nlines = LINES;
721 view->ncols = COLS - view->begin_x;
722 view->lines = LINES;
723 view->cols = COLS;
724 err = view_resize(view);
725 if (err)
726 return err;
728 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
729 return got_error_from_errno("mvwin");
731 return NULL;
734 static const struct got_error *
735 view_fullscreen(struct tog_view *view)
737 const struct got_error *err = NULL;
739 view->begin_x = 0;
740 view->begin_y = 0;
741 view->nlines = LINES;
742 view->ncols = COLS;
743 view->lines = LINES;
744 view->cols = COLS;
745 err = view_resize(view);
746 if (err)
747 return err;
749 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
750 return got_error_from_errno("mvwin");
752 return NULL;
755 static int
756 view_is_parent_view(struct tog_view *view)
758 return view->parent == NULL;
761 static int
762 view_is_splitscreen(struct tog_view *view)
764 return view->begin_x > 0;
768 static const struct got_error *
769 view_resize(struct tog_view *view)
771 int nlines, ncols;
773 if (view->lines > LINES)
774 nlines = view->nlines - (view->lines - LINES);
775 else
776 nlines = view->nlines + (LINES - view->lines);
778 if (view->cols > COLS)
779 ncols = view->ncols - (view->cols - COLS);
780 else
781 ncols = view->ncols + (COLS - view->cols);
783 if (view->child && view_is_splitscreen(view->child)) {
784 view->child->begin_x = view_split_begin_x(view->begin_x);
785 if (view->child->begin_x == 0) {
786 ncols = COLS;
788 view_fullscreen(view->child);
789 if (view->child->focussed)
790 show_panel(view->child->panel);
791 else
792 show_panel(view->panel);
793 } else {
794 ncols = view->child->begin_x;
796 view_splitscreen(view->child);
797 show_panel(view->child->panel);
799 } else if (view->parent == NULL)
800 ncols = COLS;
802 if (wresize(view->window, nlines, ncols) == ERR)
803 return got_error_from_errno("wresize");
804 if (replace_panel(view->panel, view->window) == ERR)
805 return got_error_from_errno("replace_panel");
806 wclear(view->window);
808 view->nlines = nlines;
809 view->ncols = ncols;
810 view->lines = LINES;
811 view->cols = COLS;
813 return NULL;
816 static const struct got_error *
817 view_close_child(struct tog_view *view)
819 const struct got_error *err = NULL;
821 if (view->child == NULL)
822 return NULL;
824 err = view_close(view->child);
825 view->child = NULL;
826 return err;
829 static const struct got_error *
830 view_set_child(struct tog_view *view, struct tog_view *child)
832 view->child = child;
833 child->parent = view;
835 return view_resize(view);
838 static void
839 tog_resizeterm(void)
841 int cols, lines;
842 struct winsize size;
844 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
845 cols = 80; /* Default */
846 lines = 24;
847 } else {
848 cols = size.ws_col;
849 lines = size.ws_row;
851 resize_term(lines, cols);
854 static const struct got_error *
855 view_search_start(struct tog_view *view)
857 const struct got_error *err = NULL;
858 char pattern[1024];
859 int ret;
861 if (view->search_started) {
862 regfree(&view->regex);
863 view->searching = 0;
864 memset(&view->regmatch, 0, sizeof(view->regmatch));
866 view->search_started = 0;
868 if (view->nlines < 1)
869 return NULL;
871 mvwaddstr(view->window, view->begin_y + view->nlines - 1, 0, "/");
872 wclrtoeol(view->window);
874 nocbreak();
875 echo();
876 ret = wgetnstr(view->window, pattern, sizeof(pattern));
877 cbreak();
878 noecho();
879 if (ret == ERR)
880 return NULL;
882 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
883 err = view->search_start(view);
884 if (err) {
885 regfree(&view->regex);
886 return err;
888 view->search_started = 1;
889 view->searching = TOG_SEARCH_FORWARD;
890 view->search_next_done = 0;
891 view->search_next(view);
894 return NULL;
897 /*
898 * Compute view->count from numeric user input. User has five-tenths of a
899 * second to follow each numeric keypress with another number to form count.
900 * Return first non-numeric input or ERR and assign total to view->count.
901 * XXX Should we add support for user-defined timeout?
902 */
903 static int
904 get_compound_key(struct tog_view *view, int c)
906 int n = 0;
908 view->count = 0;
909 halfdelay(5); /* block for half a second */
911 do {
912 /*
913 * Don't overflow. Max valid request should be the greatest
914 * between the longest and total lines; cap at 10 million.
915 */
916 if (n >= 9999999)
917 n = 9999999;
918 else
919 n = n * 10 + (c - '0');
920 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
922 /* Massage excessive or inapplicable values at the input handler. */
923 view->count = n;
925 cbreak(); /* return to blocking */
926 return c;
929 static const struct got_error *
930 view_input(struct tog_view **new, int *done, struct tog_view *view,
931 struct tog_view_list_head *views)
933 const struct got_error *err = NULL;
934 struct tog_view *v;
935 int ch, errcode;
937 *new = NULL;
939 /* Clear "no matches" indicator. */
940 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
941 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
942 view->search_next_done = TOG_SEARCH_HAVE_MORE;
943 view->count = 0;
946 if (view->searching && !view->search_next_done) {
947 errcode = pthread_mutex_unlock(&tog_mutex);
948 if (errcode)
949 return got_error_set_errno(errcode,
950 "pthread_mutex_unlock");
951 sched_yield();
952 errcode = pthread_mutex_lock(&tog_mutex);
953 if (errcode)
954 return got_error_set_errno(errcode,
955 "pthread_mutex_lock");
956 view->search_next(view);
957 return NULL;
960 nodelay(stdscr, FALSE);
961 /* Allow threads to make progress while we are waiting for input. */
962 errcode = pthread_mutex_unlock(&tog_mutex);
963 if (errcode)
964 return got_error_set_errno(errcode, "pthread_mutex_unlock");
965 /* If we have an unfinished count, don't get a new key map. */
966 ch = view->ch;
967 if ((view->count && --view->count == 0) || !view->count) {
968 ch = wgetch(view->window);
969 if (ch >= '1' && ch <= '9')
970 view->ch = ch = get_compound_key(view, ch);
972 errcode = pthread_mutex_lock(&tog_mutex);
973 if (errcode)
974 return got_error_set_errno(errcode, "pthread_mutex_lock");
975 nodelay(stdscr, TRUE);
977 if (tog_sigwinch_received || tog_sigcont_received) {
978 tog_resizeterm();
979 tog_sigwinch_received = 0;
980 tog_sigcont_received = 0;
981 TAILQ_FOREACH(v, views, entry) {
982 err = view_resize(v);
983 if (err)
984 return err;
985 err = v->input(new, v, KEY_RESIZE);
986 if (err)
987 return err;
988 if (v->child) {
989 err = view_resize(v->child);
990 if (err)
991 return err;
992 err = v->child->input(new, v->child,
993 KEY_RESIZE);
994 if (err)
995 return err;
1000 switch (ch) {
1001 case '\t':
1002 view->count = 0;
1003 if (view->child) {
1004 view->focussed = 0;
1005 view->child->focussed = 1;
1006 view->focus_child = 1;
1007 } else if (view->parent) {
1008 view->focussed = 0;
1009 view->parent->focussed = 1;
1010 view->parent->focus_child = 0;
1011 if (!view_is_splitscreen(view))
1012 err = view_fullscreen(view->parent);
1014 break;
1015 case 'q':
1016 err = view->input(new, view, ch);
1017 view->dying = 1;
1018 break;
1019 case 'Q':
1020 *done = 1;
1021 break;
1022 case 'F':
1023 view->count = 0;
1024 if (view_is_parent_view(view)) {
1025 if (view->child == NULL)
1026 break;
1027 if (view_is_splitscreen(view->child)) {
1028 view->focussed = 0;
1029 view->child->focussed = 1;
1030 err = view_fullscreen(view->child);
1031 } else
1032 err = view_splitscreen(view->child);
1033 if (err)
1034 break;
1035 err = view->child->input(new, view->child,
1036 KEY_RESIZE);
1037 } else {
1038 if (view_is_splitscreen(view)) {
1039 view->parent->focussed = 0;
1040 view->focussed = 1;
1041 err = view_fullscreen(view);
1042 } else {
1043 err = view_splitscreen(view);
1044 if (!err)
1045 err = view_resize(view->parent);
1047 if (err)
1048 break;
1049 err = view->input(new, view, KEY_RESIZE);
1051 break;
1052 case KEY_RESIZE:
1053 break;
1054 case '/':
1055 view->count = 0;
1056 if (view->search_start)
1057 view_search_start(view);
1058 else
1059 err = view->input(new, view, ch);
1060 break;
1061 case 'N':
1062 case 'n':
1063 if (view->search_started && view->search_next) {
1064 view->searching = (ch == 'n' ?
1065 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1066 view->search_next_done = 0;
1067 view->search_next(view);
1068 } else
1069 err = view->input(new, view, ch);
1070 break;
1071 default:
1072 err = view->input(new, view, ch);
1073 break;
1076 return err;
1079 static void
1080 view_vborder(struct tog_view *view)
1082 PANEL *panel;
1083 const struct tog_view *view_above;
1085 if (view->parent)
1086 return view_vborder(view->parent);
1088 panel = panel_above(view->panel);
1089 if (panel == NULL)
1090 return;
1092 view_above = panel_userptr(panel);
1093 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
1094 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
1097 static int
1098 view_needs_focus_indication(struct tog_view *view)
1100 if (view_is_parent_view(view)) {
1101 if (view->child == NULL || view->child->focussed)
1102 return 0;
1103 if (!view_is_splitscreen(view->child))
1104 return 0;
1105 } else if (!view_is_splitscreen(view))
1106 return 0;
1108 return view->focussed;
1111 static const struct got_error *
1112 view_loop(struct tog_view *view)
1114 const struct got_error *err = NULL;
1115 struct tog_view_list_head views;
1116 struct tog_view *new_view;
1117 int fast_refresh = 10;
1118 int done = 0, errcode;
1120 errcode = pthread_mutex_lock(&tog_mutex);
1121 if (errcode)
1122 return got_error_set_errno(errcode, "pthread_mutex_lock");
1124 TAILQ_INIT(&views);
1125 TAILQ_INSERT_HEAD(&views, view, entry);
1127 view->focussed = 1;
1128 err = view->show(view);
1129 if (err)
1130 return err;
1131 update_panels();
1132 doupdate();
1133 while (!TAILQ_EMPTY(&views) && !done && !tog_fatal_signal_received()) {
1134 /* Refresh fast during initialization, then become slower. */
1135 if (fast_refresh && fast_refresh-- == 0)
1136 halfdelay(10); /* switch to once per second */
1138 err = view_input(&new_view, &done, view, &views);
1139 if (err)
1140 break;
1141 if (view->dying) {
1142 struct tog_view *v, *prev = NULL;
1144 if (view_is_parent_view(view))
1145 prev = TAILQ_PREV(view, tog_view_list_head,
1146 entry);
1147 else if (view->parent)
1148 prev = view->parent;
1150 if (view->parent) {
1151 view->parent->child = NULL;
1152 view->parent->focus_child = 0;
1154 err = view_resize(view->parent);
1155 if (err)
1156 break;
1157 } else
1158 TAILQ_REMOVE(&views, view, entry);
1160 err = view_close(view);
1161 if (err)
1162 goto done;
1164 view = NULL;
1165 TAILQ_FOREACH(v, &views, entry) {
1166 if (v->focussed)
1167 break;
1169 if (view == NULL && new_view == NULL) {
1170 /* No view has focus. Try to pick one. */
1171 if (prev)
1172 view = prev;
1173 else if (!TAILQ_EMPTY(&views)) {
1174 view = TAILQ_LAST(&views,
1175 tog_view_list_head);
1177 if (view) {
1178 if (view->focus_child) {
1179 view->child->focussed = 1;
1180 view = view->child;
1181 } else
1182 view->focussed = 1;
1186 if (new_view) {
1187 struct tog_view *v, *t;
1188 /* Only allow one parent view per type. */
1189 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1190 if (v->type != new_view->type)
1191 continue;
1192 TAILQ_REMOVE(&views, v, entry);
1193 err = view_close(v);
1194 if (err)
1195 goto done;
1196 break;
1198 TAILQ_INSERT_TAIL(&views, new_view, entry);
1199 view = new_view;
1201 if (view) {
1202 if (view_is_parent_view(view)) {
1203 if (view->child && view->child->focussed)
1204 view = view->child;
1205 } else {
1206 if (view->parent && view->parent->focussed)
1207 view = view->parent;
1209 show_panel(view->panel);
1210 if (view->child && view_is_splitscreen(view->child))
1211 show_panel(view->child->panel);
1212 if (view->parent && view_is_splitscreen(view)) {
1213 err = view->parent->show(view->parent);
1214 if (err)
1215 goto done;
1217 err = view->show(view);
1218 if (err)
1219 goto done;
1220 if (view->child) {
1221 err = view->child->show(view->child);
1222 if (err)
1223 goto done;
1225 update_panels();
1226 doupdate();
1229 done:
1230 while (!TAILQ_EMPTY(&views)) {
1231 view = TAILQ_FIRST(&views);
1232 TAILQ_REMOVE(&views, view, entry);
1233 view_close(view);
1236 errcode = pthread_mutex_unlock(&tog_mutex);
1237 if (errcode && err == NULL)
1238 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1240 return err;
1243 __dead static void
1244 usage_log(void)
1246 endwin();
1247 fprintf(stderr,
1248 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1249 getprogname());
1250 exit(1);
1253 /* Create newly allocated wide-character string equivalent to a byte string. */
1254 static const struct got_error *
1255 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1257 char *vis = NULL;
1258 const struct got_error *err = NULL;
1260 *ws = NULL;
1261 *wlen = mbstowcs(NULL, s, 0);
1262 if (*wlen == (size_t)-1) {
1263 int vislen;
1264 if (errno != EILSEQ)
1265 return got_error_from_errno("mbstowcs");
1267 /* byte string invalid in current encoding; try to "fix" it */
1268 err = got_mbsavis(&vis, &vislen, s);
1269 if (err)
1270 return err;
1271 *wlen = mbstowcs(NULL, vis, 0);
1272 if (*wlen == (size_t)-1) {
1273 err = got_error_from_errno("mbstowcs"); /* give up */
1274 goto done;
1278 *ws = calloc(*wlen + 1, sizeof(**ws));
1279 if (*ws == NULL) {
1280 err = got_error_from_errno("calloc");
1281 goto done;
1284 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1285 err = got_error_from_errno("mbstowcs");
1286 done:
1287 free(vis);
1288 if (err) {
1289 free(*ws);
1290 *ws = NULL;
1291 *wlen = 0;
1293 return err;
1296 static const struct got_error *
1297 expand_tab(char **ptr, const char *src)
1299 char *dst;
1300 size_t len, n, idx = 0, sz = 0;
1302 *ptr = NULL;
1303 n = len = strlen(src);
1304 dst = malloc(n + 1);
1305 if (dst == NULL)
1306 return got_error_from_errno("malloc");
1308 while (idx < len && src[idx]) {
1309 const char c = src[idx];
1311 if (c == '\t') {
1312 size_t nb = TABSIZE - sz % TABSIZE;
1313 char *p;
1315 p = realloc(dst, n + nb);
1316 if (p == NULL) {
1317 free(dst);
1318 return got_error_from_errno("realloc");
1321 dst = p;
1322 n += nb;
1323 memset(dst + sz, ' ', nb);
1324 sz += nb;
1325 } else
1326 dst[sz++] = src[idx];
1327 ++idx;
1330 dst[sz] = '\0';
1331 *ptr = dst;
1332 return NULL;
1336 * Advance at most n columns from wline starting at offset off.
1337 * Return the index to the first character after the span operation.
1338 * Return the combined column width of all spanned wide character in
1339 * *rcol.
1341 static int
1342 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1344 int width, i, cols = 0;
1346 if (n == 0) {
1347 *rcol = cols;
1348 return off;
1351 for (i = off; wline[i] != L'\0'; ++i) {
1352 if (wline[i] == L'\t')
1353 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1354 else
1355 width = wcwidth(wline[i]);
1357 if (width == -1) {
1358 width = 1;
1359 wline[i] = L'.';
1362 if (cols + width > n)
1363 break;
1364 cols += width;
1367 *rcol = cols;
1368 return i;
1372 * Format a line for display, ensuring that it won't overflow a width limit.
1373 * With scrolling, the width returned refers to the scrolled version of the
1374 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1376 static const struct got_error *
1377 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1378 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1380 const struct got_error *err = NULL;
1381 int cols;
1382 wchar_t *wline = NULL;
1383 char *exstr = NULL;
1384 size_t wlen;
1385 int i, scrollx;
1387 *wlinep = NULL;
1388 *widthp = 0;
1390 if (expand) {
1391 err = expand_tab(&exstr, line);
1392 if (err)
1393 return err;
1396 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1397 free(exstr);
1398 if (err)
1399 return err;
1401 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1403 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1404 wline[wlen - 1] = L'\0';
1405 wlen--;
1407 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1408 wline[wlen - 1] = L'\0';
1409 wlen--;
1412 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1413 wline[i] = L'\0';
1415 if (widthp)
1416 *widthp = cols;
1417 if (scrollxp)
1418 *scrollxp = scrollx;
1419 if (err)
1420 free(wline);
1421 else
1422 *wlinep = wline;
1423 return err;
1426 static const struct got_error*
1427 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1428 struct got_object_id *id, struct got_repository *repo)
1430 static const struct got_error *err = NULL;
1431 struct got_reflist_entry *re;
1432 char *s;
1433 const char *name;
1435 *refs_str = NULL;
1437 TAILQ_FOREACH(re, refs, entry) {
1438 struct got_tag_object *tag = NULL;
1439 struct got_object_id *ref_id;
1440 int cmp;
1442 name = got_ref_get_name(re->ref);
1443 if (strcmp(name, GOT_REF_HEAD) == 0)
1444 continue;
1445 if (strncmp(name, "refs/", 5) == 0)
1446 name += 5;
1447 if (strncmp(name, "got/", 4) == 0 &&
1448 strncmp(name, "got/backup/", 11) != 0)
1449 continue;
1450 if (strncmp(name, "heads/", 6) == 0)
1451 name += 6;
1452 if (strncmp(name, "remotes/", 8) == 0) {
1453 name += 8;
1454 s = strstr(name, "/" GOT_REF_HEAD);
1455 if (s != NULL && s[strlen(s)] == '\0')
1456 continue;
1458 err = got_ref_resolve(&ref_id, repo, re->ref);
1459 if (err)
1460 break;
1461 if (strncmp(name, "tags/", 5) == 0) {
1462 err = got_object_open_as_tag(&tag, repo, ref_id);
1463 if (err) {
1464 if (err->code != GOT_ERR_OBJ_TYPE) {
1465 free(ref_id);
1466 break;
1468 /* Ref points at something other than a tag. */
1469 err = NULL;
1470 tag = NULL;
1473 cmp = got_object_id_cmp(tag ?
1474 got_object_tag_get_object_id(tag) : ref_id, id);
1475 free(ref_id);
1476 if (tag)
1477 got_object_tag_close(tag);
1478 if (cmp != 0)
1479 continue;
1480 s = *refs_str;
1481 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1482 s ? ", " : "", name) == -1) {
1483 err = got_error_from_errno("asprintf");
1484 free(s);
1485 *refs_str = NULL;
1486 break;
1488 free(s);
1491 return err;
1494 static const struct got_error *
1495 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1496 int col_tab_align)
1498 char *smallerthan;
1500 smallerthan = strchr(author, '<');
1501 if (smallerthan && smallerthan[1] != '\0')
1502 author = smallerthan + 1;
1503 author[strcspn(author, "@>")] = '\0';
1504 return format_line(wauthor, author_width, NULL, author, 0, limit,
1505 col_tab_align, 0);
1508 static const struct got_error *
1509 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1510 struct got_object_id *id, const size_t date_display_cols,
1511 int author_display_cols)
1513 struct tog_log_view_state *s = &view->state.log;
1514 const struct got_error *err = NULL;
1515 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1516 char *logmsg0 = NULL, *logmsg = NULL;
1517 char *author = NULL;
1518 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1519 int author_width, logmsg_width;
1520 char *newline, *line = NULL;
1521 int col, limit, scrollx;
1522 const int avail = view->ncols;
1523 struct tm tm;
1524 time_t committer_time;
1525 struct tog_color *tc;
1527 committer_time = got_object_commit_get_committer_time(commit);
1528 if (gmtime_r(&committer_time, &tm) == NULL)
1529 return got_error_from_errno("gmtime_r");
1530 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1531 return got_error(GOT_ERR_NO_SPACE);
1533 if (avail <= date_display_cols)
1534 limit = MIN(sizeof(datebuf) - 1, avail);
1535 else
1536 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1537 tc = get_color(&s->colors, TOG_COLOR_DATE);
1538 if (tc)
1539 wattr_on(view->window,
1540 COLOR_PAIR(tc->colorpair), NULL);
1541 waddnstr(view->window, datebuf, limit);
1542 if (tc)
1543 wattr_off(view->window,
1544 COLOR_PAIR(tc->colorpair), NULL);
1545 col = limit;
1546 if (col > avail)
1547 goto done;
1549 if (avail >= 120) {
1550 char *id_str;
1551 err = got_object_id_str(&id_str, id);
1552 if (err)
1553 goto done;
1554 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1555 if (tc)
1556 wattr_on(view->window,
1557 COLOR_PAIR(tc->colorpair), NULL);
1558 wprintw(view->window, "%.8s ", id_str);
1559 if (tc)
1560 wattr_off(view->window,
1561 COLOR_PAIR(tc->colorpair), NULL);
1562 free(id_str);
1563 col += 9;
1564 if (col > avail)
1565 goto done;
1568 author = strdup(got_object_commit_get_author(commit));
1569 if (author == NULL) {
1570 err = got_error_from_errno("strdup");
1571 goto done;
1573 err = format_author(&wauthor, &author_width, author, avail - col, col);
1574 if (err)
1575 goto done;
1576 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1577 if (tc)
1578 wattr_on(view->window,
1579 COLOR_PAIR(tc->colorpair), NULL);
1580 waddwstr(view->window, wauthor);
1581 if (tc)
1582 wattr_off(view->window,
1583 COLOR_PAIR(tc->colorpair), NULL);
1584 col += author_width;
1585 while (col < avail && author_width < author_display_cols + 2) {
1586 waddch(view->window, ' ');
1587 col++;
1588 author_width++;
1590 if (col > avail)
1591 goto done;
1593 err = got_object_commit_get_logmsg(&logmsg0, commit);
1594 if (err)
1595 goto done;
1596 logmsg = logmsg0;
1597 while (*logmsg == '\n')
1598 logmsg++;
1599 newline = strchr(logmsg, '\n');
1600 if (newline)
1601 *newline = '\0';
1602 limit = avail - col;
1603 if (view->child && view_is_splitscreen(view->child) && limit > 0)
1604 limit--; /* for the border */
1605 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
1606 limit, col, 1);
1607 if (err)
1608 goto done;
1609 waddwstr(view->window, &wlogmsg[scrollx]);
1610 col += MAX(logmsg_width, 0);
1611 while (col < avail) {
1612 waddch(view->window, ' ');
1613 col++;
1615 done:
1616 free(logmsg0);
1617 free(wlogmsg);
1618 free(author);
1619 free(wauthor);
1620 free(line);
1621 return err;
1624 static struct commit_queue_entry *
1625 alloc_commit_queue_entry(struct got_commit_object *commit,
1626 struct got_object_id *id)
1628 struct commit_queue_entry *entry;
1630 entry = calloc(1, sizeof(*entry));
1631 if (entry == NULL)
1632 return NULL;
1634 entry->id = id;
1635 entry->commit = commit;
1636 return entry;
1639 static void
1640 pop_commit(struct commit_queue *commits)
1642 struct commit_queue_entry *entry;
1644 entry = TAILQ_FIRST(&commits->head);
1645 TAILQ_REMOVE(&commits->head, entry, entry);
1646 got_object_commit_close(entry->commit);
1647 commits->ncommits--;
1648 /* Don't free entry->id! It is owned by the commit graph. */
1649 free(entry);
1652 static void
1653 free_commits(struct commit_queue *commits)
1655 while (!TAILQ_EMPTY(&commits->head))
1656 pop_commit(commits);
1659 static const struct got_error *
1660 match_commit(int *have_match, struct got_object_id *id,
1661 struct got_commit_object *commit, regex_t *regex)
1663 const struct got_error *err = NULL;
1664 regmatch_t regmatch;
1665 char *id_str = NULL, *logmsg = NULL;
1667 *have_match = 0;
1669 err = got_object_id_str(&id_str, id);
1670 if (err)
1671 return err;
1673 err = got_object_commit_get_logmsg(&logmsg, commit);
1674 if (err)
1675 goto done;
1677 if (regexec(regex, got_object_commit_get_author(commit), 1,
1678 &regmatch, 0) == 0 ||
1679 regexec(regex, got_object_commit_get_committer(commit), 1,
1680 &regmatch, 0) == 0 ||
1681 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
1682 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
1683 *have_match = 1;
1684 done:
1685 free(id_str);
1686 free(logmsg);
1687 return err;
1690 static const struct got_error *
1691 queue_commits(struct tog_log_thread_args *a)
1693 const struct got_error *err = NULL;
1696 * We keep all commits open throughout the lifetime of the log
1697 * view in order to avoid having to re-fetch commits from disk
1698 * while updating the display.
1700 do {
1701 struct got_object_id *id;
1702 struct got_commit_object *commit;
1703 struct commit_queue_entry *entry;
1704 int errcode;
1706 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
1707 NULL, NULL);
1708 if (err || id == NULL)
1709 break;
1711 err = got_object_open_as_commit(&commit, a->repo, id);
1712 if (err)
1713 break;
1714 entry = alloc_commit_queue_entry(commit, id);
1715 if (entry == NULL) {
1716 err = got_error_from_errno("alloc_commit_queue_entry");
1717 break;
1720 errcode = pthread_mutex_lock(&tog_mutex);
1721 if (errcode) {
1722 err = got_error_set_errno(errcode,
1723 "pthread_mutex_lock");
1724 break;
1727 entry->idx = a->commits->ncommits;
1728 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
1729 a->commits->ncommits++;
1731 if (*a->searching == TOG_SEARCH_FORWARD &&
1732 !*a->search_next_done) {
1733 int have_match;
1734 err = match_commit(&have_match, id, commit, a->regex);
1735 if (err)
1736 break;
1737 if (have_match)
1738 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
1741 errcode = pthread_mutex_unlock(&tog_mutex);
1742 if (errcode && err == NULL)
1743 err = got_error_set_errno(errcode,
1744 "pthread_mutex_unlock");
1745 if (err)
1746 break;
1747 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
1749 return err;
1752 static void
1753 select_commit(struct tog_log_view_state *s)
1755 struct commit_queue_entry *entry;
1756 int ncommits = 0;
1758 entry = s->first_displayed_entry;
1759 while (entry) {
1760 if (ncommits == s->selected) {
1761 s->selected_entry = entry;
1762 break;
1764 entry = TAILQ_NEXT(entry, entry);
1765 ncommits++;
1769 static const struct got_error *
1770 draw_commits(struct tog_view *view)
1772 const struct got_error *err = NULL;
1773 struct tog_log_view_state *s = &view->state.log;
1774 struct commit_queue_entry *entry = s->selected_entry;
1775 const int limit = view->nlines;
1776 int width;
1777 int ncommits, author_cols = 4;
1778 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
1779 char *refs_str = NULL;
1780 wchar_t *wline;
1781 struct tog_color *tc;
1782 static const size_t date_display_cols = 12;
1784 if (s->selected_entry &&
1785 !(view->searching && view->search_next_done == 0)) {
1786 struct got_reflist_head *refs;
1787 err = got_object_id_str(&id_str, s->selected_entry->id);
1788 if (err)
1789 return err;
1790 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
1791 s->selected_entry->id);
1792 if (refs) {
1793 err = build_refs_str(&refs_str, refs,
1794 s->selected_entry->id, s->repo);
1795 if (err)
1796 goto done;
1800 if (s->thread_args.commits_needed == 0)
1801 halfdelay(10); /* disable fast refresh */
1803 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
1804 if (asprintf(&ncommits_str, " [%d/%d] %s",
1805 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1806 (view->searching && !view->search_next_done) ?
1807 "searching..." : "loading...") == -1) {
1808 err = got_error_from_errno("asprintf");
1809 goto done;
1811 } else {
1812 const char *search_str = NULL;
1814 if (view->searching) {
1815 if (view->search_next_done == TOG_SEARCH_NO_MORE)
1816 search_str = "no more matches";
1817 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
1818 search_str = "no matches found";
1819 else if (!view->search_next_done)
1820 search_str = "searching...";
1823 if (asprintf(&ncommits_str, " [%d/%d] %s",
1824 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1825 search_str ? search_str :
1826 (refs_str ? refs_str : "")) == -1) {
1827 err = got_error_from_errno("asprintf");
1828 goto done;
1832 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
1833 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
1834 "........................................",
1835 s->in_repo_path, ncommits_str) == -1) {
1836 err = got_error_from_errno("asprintf");
1837 header = NULL;
1838 goto done;
1840 } else if (asprintf(&header, "commit %s%s",
1841 id_str ? id_str : "........................................",
1842 ncommits_str) == -1) {
1843 err = got_error_from_errno("asprintf");
1844 header = NULL;
1845 goto done;
1847 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
1848 if (err)
1849 goto done;
1851 werase(view->window);
1853 if (view_needs_focus_indication(view))
1854 wstandout(view->window);
1855 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1856 if (tc)
1857 wattr_on(view->window,
1858 COLOR_PAIR(tc->colorpair), NULL);
1859 waddwstr(view->window, wline);
1860 if (tc)
1861 wattr_off(view->window,
1862 COLOR_PAIR(tc->colorpair), NULL);
1863 while (width < view->ncols) {
1864 waddch(view->window, ' ');
1865 width++;
1867 if (view_needs_focus_indication(view))
1868 wstandend(view->window);
1869 free(wline);
1870 if (limit <= 1)
1871 goto done;
1873 /* Grow author column size if necessary, and set view->maxx. */
1874 entry = s->first_displayed_entry;
1875 ncommits = 0;
1876 view->maxx = 0;
1877 while (entry) {
1878 char *author, *eol, *msg, *msg0;
1879 wchar_t *wauthor, *wmsg;
1880 int width;
1881 if (ncommits >= limit - 1)
1882 break;
1883 author = strdup(got_object_commit_get_author(entry->commit));
1884 if (author == NULL) {
1885 err = got_error_from_errno("strdup");
1886 goto done;
1888 err = format_author(&wauthor, &width, author, COLS,
1889 date_display_cols);
1890 if (author_cols < width)
1891 author_cols = width;
1892 free(wauthor);
1893 free(author);
1894 err = got_object_commit_get_logmsg(&msg0, entry->commit);
1895 if (err)
1896 goto done;
1897 msg = msg0;
1898 while (*msg == '\n')
1899 ++msg;
1900 if ((eol = strchr(msg, '\n')))
1901 *eol = '\0';
1902 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
1903 date_display_cols + author_cols, 0);
1904 if (err)
1905 goto done;
1906 view->maxx = MAX(view->maxx, width);
1907 free(msg0);
1908 free(wmsg);
1909 ncommits++;
1910 entry = TAILQ_NEXT(entry, entry);
1913 entry = s->first_displayed_entry;
1914 s->last_displayed_entry = s->first_displayed_entry;
1915 ncommits = 0;
1916 while (entry) {
1917 if (ncommits >= limit - 1)
1918 break;
1919 if (ncommits == s->selected)
1920 wstandout(view->window);
1921 err = draw_commit(view, entry->commit, entry->id,
1922 date_display_cols, author_cols);
1923 if (ncommits == s->selected)
1924 wstandend(view->window);
1925 if (err)
1926 goto done;
1927 ncommits++;
1928 s->last_displayed_entry = entry;
1929 entry = TAILQ_NEXT(entry, entry);
1932 view_vborder(view);
1933 update_panels();
1934 doupdate();
1935 done:
1936 free(id_str);
1937 free(refs_str);
1938 free(ncommits_str);
1939 free(header);
1940 return err;
1943 static void
1944 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
1946 struct commit_queue_entry *entry;
1947 int nscrolled = 0;
1949 entry = TAILQ_FIRST(&s->commits.head);
1950 if (s->first_displayed_entry == entry)
1951 return;
1953 entry = s->first_displayed_entry;
1954 while (entry && nscrolled < maxscroll) {
1955 entry = TAILQ_PREV(entry, commit_queue_head, entry);
1956 if (entry) {
1957 s->first_displayed_entry = entry;
1958 nscrolled++;
1963 static const struct got_error *
1964 trigger_log_thread(struct tog_view *view, int wait)
1966 struct tog_log_thread_args *ta = &view->state.log.thread_args;
1967 int errcode;
1969 halfdelay(1); /* fast refresh while loading commits */
1971 while (ta->commits_needed > 0 || ta->load_all) {
1972 if (ta->log_complete)
1973 break;
1975 /* Wake the log thread. */
1976 errcode = pthread_cond_signal(&ta->need_commits);
1977 if (errcode)
1978 return got_error_set_errno(errcode,
1979 "pthread_cond_signal");
1982 * The mutex will be released while the view loop waits
1983 * in wgetch(), at which time the log thread will run.
1985 if (!wait)
1986 break;
1988 /* Display progress update in log view. */
1989 show_log_view(view);
1990 update_panels();
1991 doupdate();
1993 /* Wait right here while next commit is being loaded. */
1994 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
1995 if (errcode)
1996 return got_error_set_errno(errcode,
1997 "pthread_cond_wait");
1999 /* Display progress update in log view. */
2000 show_log_view(view);
2001 update_panels();
2002 doupdate();
2005 return NULL;
2008 static const struct got_error *
2009 log_scroll_down(struct tog_view *view, int maxscroll)
2011 struct tog_log_view_state *s = &view->state.log;
2012 const struct got_error *err = NULL;
2013 struct commit_queue_entry *pentry;
2014 int nscrolled = 0, ncommits_needed;
2016 if (s->last_displayed_entry == NULL)
2017 return NULL;
2019 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2020 if (s->commits.ncommits < ncommits_needed &&
2021 !s->thread_args.log_complete) {
2023 * Ask the log thread for required amount of commits.
2025 s->thread_args.commits_needed += maxscroll;
2026 err = trigger_log_thread(view, 1);
2027 if (err)
2028 return err;
2031 do {
2032 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2033 if (pentry == NULL)
2034 break;
2036 s->last_displayed_entry = pentry;
2038 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2039 if (pentry == NULL)
2040 break;
2041 s->first_displayed_entry = pentry;
2042 } while (++nscrolled < maxscroll);
2044 return err;
2047 static const struct got_error *
2048 open_diff_view_for_commit(struct tog_view **new_view, int begin_x,
2049 struct got_commit_object *commit, struct got_object_id *commit_id,
2050 struct tog_view *log_view, struct got_repository *repo)
2052 const struct got_error *err;
2053 struct got_object_qid *parent_id;
2054 struct tog_view *diff_view;
2056 diff_view = view_open(0, 0, 0, begin_x, TOG_VIEW_DIFF);
2057 if (diff_view == NULL)
2058 return got_error_from_errno("view_open");
2060 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2061 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2062 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2063 if (err == NULL)
2064 *new_view = diff_view;
2065 return err;
2068 static const struct got_error *
2069 tree_view_visit_subtree(struct tog_tree_view_state *s,
2070 struct got_tree_object *subtree)
2072 struct tog_parent_tree *parent;
2074 parent = calloc(1, sizeof(*parent));
2075 if (parent == NULL)
2076 return got_error_from_errno("calloc");
2078 parent->tree = s->tree;
2079 parent->first_displayed_entry = s->first_displayed_entry;
2080 parent->selected_entry = s->selected_entry;
2081 parent->selected = s->selected;
2082 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2083 s->tree = subtree;
2084 s->selected = 0;
2085 s->first_displayed_entry = NULL;
2086 return NULL;
2089 static const struct got_error *
2090 tree_view_walk_path(struct tog_tree_view_state *s,
2091 struct got_commit_object *commit, const char *path)
2093 const struct got_error *err = NULL;
2094 struct got_tree_object *tree = NULL;
2095 const char *p;
2096 char *slash, *subpath = NULL;
2098 /* Walk the path and open corresponding tree objects. */
2099 p = path;
2100 while (*p) {
2101 struct got_tree_entry *te;
2102 struct got_object_id *tree_id;
2103 char *te_name;
2105 while (p[0] == '/')
2106 p++;
2108 /* Ensure the correct subtree entry is selected. */
2109 slash = strchr(p, '/');
2110 if (slash == NULL)
2111 te_name = strdup(p);
2112 else
2113 te_name = strndup(p, slash - p);
2114 if (te_name == NULL) {
2115 err = got_error_from_errno("strndup");
2116 break;
2118 te = got_object_tree_find_entry(s->tree, te_name);
2119 if (te == NULL) {
2120 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2121 free(te_name);
2122 break;
2124 free(te_name);
2125 s->first_displayed_entry = s->selected_entry = te;
2127 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2128 break; /* jump to this file's entry */
2130 slash = strchr(p, '/');
2131 if (slash)
2132 subpath = strndup(path, slash - path);
2133 else
2134 subpath = strdup(path);
2135 if (subpath == NULL) {
2136 err = got_error_from_errno("strdup");
2137 break;
2140 err = got_object_id_by_path(&tree_id, s->repo, commit,
2141 subpath);
2142 if (err)
2143 break;
2145 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2146 free(tree_id);
2147 if (err)
2148 break;
2150 err = tree_view_visit_subtree(s, tree);
2151 if (err) {
2152 got_object_tree_close(tree);
2153 break;
2155 if (slash == NULL)
2156 break;
2157 free(subpath);
2158 subpath = NULL;
2159 p = slash;
2162 free(subpath);
2163 return err;
2166 static const struct got_error *
2167 browse_commit_tree(struct tog_view **new_view, int begin_x,
2168 struct commit_queue_entry *entry, const char *path,
2169 const char *head_ref_name, struct got_repository *repo)
2171 const struct got_error *err = NULL;
2172 struct tog_tree_view_state *s;
2173 struct tog_view *tree_view;
2175 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
2176 if (tree_view == NULL)
2177 return got_error_from_errno("view_open");
2179 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2180 if (err)
2181 return err;
2182 s = &tree_view->state.tree;
2184 *new_view = tree_view;
2186 if (got_path_is_root_dir(path))
2187 return NULL;
2189 return tree_view_walk_path(s, entry->commit, path);
2192 static const struct got_error *
2193 block_signals_used_by_main_thread(void)
2195 sigset_t sigset;
2196 int errcode;
2198 if (sigemptyset(&sigset) == -1)
2199 return got_error_from_errno("sigemptyset");
2201 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2202 if (sigaddset(&sigset, SIGWINCH) == -1)
2203 return got_error_from_errno("sigaddset");
2204 if (sigaddset(&sigset, SIGCONT) == -1)
2205 return got_error_from_errno("sigaddset");
2206 if (sigaddset(&sigset, SIGINT) == -1)
2207 return got_error_from_errno("sigaddset");
2208 if (sigaddset(&sigset, SIGTERM) == -1)
2209 return got_error_from_errno("sigaddset");
2211 /* ncurses handles SIGTSTP */
2212 if (sigaddset(&sigset, SIGTSTP) == -1)
2213 return got_error_from_errno("sigaddset");
2215 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2216 if (errcode)
2217 return got_error_set_errno(errcode, "pthread_sigmask");
2219 return NULL;
2222 static void *
2223 log_thread(void *arg)
2225 const struct got_error *err = NULL;
2226 int errcode = 0;
2227 struct tog_log_thread_args *a = arg;
2228 int done = 0;
2230 err = block_signals_used_by_main_thread();
2231 if (err)
2232 return (void *)err;
2234 while (!done && !err && !tog_fatal_signal_received()) {
2235 err = queue_commits(a);
2236 if (err) {
2237 if (err->code != GOT_ERR_ITER_COMPLETED)
2238 return (void *)err;
2239 err = NULL;
2240 done = 1;
2241 } else if (a->commits_needed > 0 && !a->load_all)
2242 a->commits_needed--;
2244 errcode = pthread_mutex_lock(&tog_mutex);
2245 if (errcode) {
2246 err = got_error_set_errno(errcode,
2247 "pthread_mutex_lock");
2248 break;
2249 } else if (*a->quit)
2250 done = 1;
2251 else if (*a->first_displayed_entry == NULL) {
2252 *a->first_displayed_entry =
2253 TAILQ_FIRST(&a->commits->head);
2254 *a->selected_entry = *a->first_displayed_entry;
2257 errcode = pthread_cond_signal(&a->commit_loaded);
2258 if (errcode) {
2259 err = got_error_set_errno(errcode,
2260 "pthread_cond_signal");
2261 pthread_mutex_unlock(&tog_mutex);
2262 break;
2265 if (done)
2266 a->commits_needed = 0;
2267 else {
2268 if (a->commits_needed == 0 && !a->load_all) {
2269 errcode = pthread_cond_wait(&a->need_commits,
2270 &tog_mutex);
2271 if (errcode)
2272 err = got_error_set_errno(errcode,
2273 "pthread_cond_wait");
2274 if (*a->quit)
2275 done = 1;
2279 errcode = pthread_mutex_unlock(&tog_mutex);
2280 if (errcode && err == NULL)
2281 err = got_error_set_errno(errcode,
2282 "pthread_mutex_unlock");
2284 a->log_complete = 1;
2285 return (void *)err;
2288 static const struct got_error *
2289 stop_log_thread(struct tog_log_view_state *s)
2291 const struct got_error *err = NULL;
2292 int errcode;
2294 if (s->thread) {
2295 s->quit = 1;
2296 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2297 if (errcode)
2298 return got_error_set_errno(errcode,
2299 "pthread_cond_signal");
2300 errcode = pthread_mutex_unlock(&tog_mutex);
2301 if (errcode)
2302 return got_error_set_errno(errcode,
2303 "pthread_mutex_unlock");
2304 errcode = pthread_join(s->thread, (void **)&err);
2305 if (errcode)
2306 return got_error_set_errno(errcode, "pthread_join");
2307 errcode = pthread_mutex_lock(&tog_mutex);
2308 if (errcode)
2309 return got_error_set_errno(errcode,
2310 "pthread_mutex_lock");
2311 s->thread = 0; //NULL;
2314 if (s->thread_args.repo) {
2315 err = got_repo_close(s->thread_args.repo);
2316 s->thread_args.repo = NULL;
2319 if (s->thread_args.pack_fds) {
2320 const struct got_error *pack_err =
2321 got_repo_pack_fds_close(s->thread_args.pack_fds);
2322 if (err == NULL)
2323 err = pack_err;
2324 s->thread_args.pack_fds = NULL;
2327 if (s->thread_args.graph) {
2328 got_commit_graph_close(s->thread_args.graph);
2329 s->thread_args.graph = NULL;
2332 return err;
2335 static const struct got_error *
2336 close_log_view(struct tog_view *view)
2338 const struct got_error *err = NULL;
2339 struct tog_log_view_state *s = &view->state.log;
2340 int errcode;
2342 err = stop_log_thread(s);
2344 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2345 if (errcode && err == NULL)
2346 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2348 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2349 if (errcode && err == NULL)
2350 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2352 free_commits(&s->commits);
2353 free(s->in_repo_path);
2354 s->in_repo_path = NULL;
2355 free(s->start_id);
2356 s->start_id = NULL;
2357 free(s->head_ref_name);
2358 s->head_ref_name = NULL;
2359 return err;
2362 static const struct got_error *
2363 search_start_log_view(struct tog_view *view)
2365 struct tog_log_view_state *s = &view->state.log;
2367 s->matched_entry = NULL;
2368 s->search_entry = NULL;
2369 return NULL;
2372 static const struct got_error *
2373 search_next_log_view(struct tog_view *view)
2375 const struct got_error *err = NULL;
2376 struct tog_log_view_state *s = &view->state.log;
2377 struct commit_queue_entry *entry;
2379 /* Display progress update in log view. */
2380 show_log_view(view);
2381 update_panels();
2382 doupdate();
2384 if (s->search_entry) {
2385 int errcode, ch;
2386 errcode = pthread_mutex_unlock(&tog_mutex);
2387 if (errcode)
2388 return got_error_set_errno(errcode,
2389 "pthread_mutex_unlock");
2390 ch = wgetch(view->window);
2391 errcode = pthread_mutex_lock(&tog_mutex);
2392 if (errcode)
2393 return got_error_set_errno(errcode,
2394 "pthread_mutex_lock");
2395 if (ch == KEY_BACKSPACE) {
2396 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2397 return NULL;
2399 if (view->searching == TOG_SEARCH_FORWARD)
2400 entry = TAILQ_NEXT(s->search_entry, entry);
2401 else
2402 entry = TAILQ_PREV(s->search_entry,
2403 commit_queue_head, entry);
2404 } else if (s->matched_entry) {
2405 int matched_idx = s->matched_entry->idx;
2406 int selected_idx = s->selected_entry->idx;
2409 * If the user has moved the cursor after we hit a match,
2410 * the position from where we should continue searching
2411 * might have changed.
2413 if (view->searching == TOG_SEARCH_FORWARD) {
2414 if (matched_idx > selected_idx)
2415 entry = TAILQ_NEXT(s->selected_entry, entry);
2416 else
2417 entry = TAILQ_NEXT(s->matched_entry, entry);
2418 } else {
2419 if (matched_idx < selected_idx)
2420 entry = TAILQ_PREV(s->selected_entry,
2421 commit_queue_head, entry);
2422 else
2423 entry = TAILQ_PREV(s->matched_entry,
2424 commit_queue_head, entry);
2426 } else {
2427 entry = s->selected_entry;
2430 while (1) {
2431 int have_match = 0;
2433 if (entry == NULL) {
2434 if (s->thread_args.log_complete ||
2435 view->searching == TOG_SEARCH_BACKWARD) {
2436 view->search_next_done =
2437 (s->matched_entry == NULL ?
2438 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2439 s->search_entry = NULL;
2440 return NULL;
2443 * Poke the log thread for more commits and return,
2444 * allowing the main loop to make progress. Search
2445 * will resume at s->search_entry once we come back.
2447 s->thread_args.commits_needed++;
2448 return trigger_log_thread(view, 0);
2451 err = match_commit(&have_match, entry->id, entry->commit,
2452 &view->regex);
2453 if (err)
2454 break;
2455 if (have_match) {
2456 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2457 s->matched_entry = entry;
2458 break;
2461 s->search_entry = entry;
2462 if (view->searching == TOG_SEARCH_FORWARD)
2463 entry = TAILQ_NEXT(entry, entry);
2464 else
2465 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2468 if (s->matched_entry) {
2469 int cur = s->selected_entry->idx;
2470 while (cur < s->matched_entry->idx) {
2471 err = input_log_view(NULL, view, KEY_DOWN);
2472 if (err)
2473 return err;
2474 cur++;
2476 while (cur > s->matched_entry->idx) {
2477 err = input_log_view(NULL, view, KEY_UP);
2478 if (err)
2479 return err;
2480 cur--;
2484 s->search_entry = NULL;
2486 return NULL;
2489 static const struct got_error *
2490 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2491 struct got_repository *repo, const char *head_ref_name,
2492 const char *in_repo_path, int log_branches)
2494 const struct got_error *err = NULL;
2495 struct tog_log_view_state *s = &view->state.log;
2496 struct got_repository *thread_repo = NULL;
2497 struct got_commit_graph *thread_graph = NULL;
2498 int errcode;
2500 if (in_repo_path != s->in_repo_path) {
2501 free(s->in_repo_path);
2502 s->in_repo_path = strdup(in_repo_path);
2503 if (s->in_repo_path == NULL)
2504 return got_error_from_errno("strdup");
2507 /* The commit queue only contains commits being displayed. */
2508 TAILQ_INIT(&s->commits.head);
2509 s->commits.ncommits = 0;
2511 s->repo = repo;
2512 if (head_ref_name) {
2513 s->head_ref_name = strdup(head_ref_name);
2514 if (s->head_ref_name == NULL) {
2515 err = got_error_from_errno("strdup");
2516 goto done;
2519 s->start_id = got_object_id_dup(start_id);
2520 if (s->start_id == NULL) {
2521 err = got_error_from_errno("got_object_id_dup");
2522 goto done;
2524 s->log_branches = log_branches;
2526 STAILQ_INIT(&s->colors);
2527 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2528 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2529 get_color_value("TOG_COLOR_COMMIT"));
2530 if (err)
2531 goto done;
2532 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2533 get_color_value("TOG_COLOR_AUTHOR"));
2534 if (err) {
2535 free_colors(&s->colors);
2536 goto done;
2538 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
2539 get_color_value("TOG_COLOR_DATE"));
2540 if (err) {
2541 free_colors(&s->colors);
2542 goto done;
2546 view->show = show_log_view;
2547 view->input = input_log_view;
2548 view->close = close_log_view;
2549 view->search_start = search_start_log_view;
2550 view->search_next = search_next_log_view;
2552 if (s->thread_args.pack_fds == NULL) {
2553 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2554 if (err)
2555 goto done;
2557 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
2558 s->thread_args.pack_fds);
2559 if (err)
2560 goto done;
2561 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
2562 !s->log_branches);
2563 if (err)
2564 goto done;
2565 err = got_commit_graph_iter_start(thread_graph, s->start_id,
2566 s->repo, NULL, NULL);
2567 if (err)
2568 goto done;
2570 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
2571 if (errcode) {
2572 err = got_error_set_errno(errcode, "pthread_cond_init");
2573 goto done;
2575 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
2576 if (errcode) {
2577 err = got_error_set_errno(errcode, "pthread_cond_init");
2578 goto done;
2581 s->thread_args.commits_needed = view->nlines;
2582 s->thread_args.graph = thread_graph;
2583 s->thread_args.commits = &s->commits;
2584 s->thread_args.in_repo_path = s->in_repo_path;
2585 s->thread_args.start_id = s->start_id;
2586 s->thread_args.repo = thread_repo;
2587 s->thread_args.log_complete = 0;
2588 s->thread_args.quit = &s->quit;
2589 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
2590 s->thread_args.selected_entry = &s->selected_entry;
2591 s->thread_args.searching = &view->searching;
2592 s->thread_args.search_next_done = &view->search_next_done;
2593 s->thread_args.regex = &view->regex;
2594 done:
2595 if (err)
2596 close_log_view(view);
2597 return err;
2600 static const struct got_error *
2601 show_log_view(struct tog_view *view)
2603 const struct got_error *err;
2604 struct tog_log_view_state *s = &view->state.log;
2606 if (s->thread == 0) { //NULL) {
2607 int errcode = pthread_create(&s->thread, NULL, log_thread,
2608 &s->thread_args);
2609 if (errcode)
2610 return got_error_set_errno(errcode, "pthread_create");
2611 if (s->thread_args.commits_needed > 0) {
2612 err = trigger_log_thread(view, 1);
2613 if (err)
2614 return err;
2618 return draw_commits(view);
2621 static const struct got_error *
2622 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
2624 const struct got_error *err = NULL;
2625 struct tog_log_view_state *s = &view->state.log;
2626 struct tog_view *diff_view = NULL, *tree_view = NULL;
2627 struct tog_view *ref_view = NULL;
2628 struct commit_queue_entry *entry;
2629 int begin_x = 0, n, nscroll = view->nlines - 1;
2631 if (s->thread_args.load_all) {
2632 if (ch == KEY_BACKSPACE)
2633 s->thread_args.load_all = 0;
2634 else if (s->thread_args.log_complete) {
2635 s->thread_args.load_all = 0;
2636 log_scroll_down(view, s->commits.ncommits);
2637 s->selected = MIN(view->nlines - 2,
2638 s->commits.ncommits - 1);
2639 select_commit(s);
2641 return NULL;
2644 switch (ch) {
2645 case 'q':
2646 s->quit = 1;
2647 break;
2648 case '0':
2649 view->x = 0;
2650 break;
2651 case '$':
2652 view->x = MAX(view->maxx - view->ncols / 2, 0);
2653 view->count = 0;
2654 break;
2655 case KEY_RIGHT:
2656 case 'l':
2657 if (view->x + view->ncols / 2 < view->maxx)
2658 view->x += 2; /* move two columns right */
2659 else
2660 view->count = 0;
2661 break;
2662 case KEY_LEFT:
2663 case 'h':
2664 view->x -= MIN(view->x, 2); /* move two columns back */
2665 if (view->x <= 0)
2666 view->count = 0;
2667 break;
2668 case 'k':
2669 case KEY_UP:
2670 case '<':
2671 case ',':
2672 case CTRL('p'):
2673 if (s->selected_entry->idx == 0)
2674 view->count = 0;
2675 if (s->first_displayed_entry == NULL)
2676 break;
2677 if (s->selected > 0)
2678 s->selected--;
2679 else
2680 log_scroll_up(s, 1);
2681 select_commit(s);
2682 break;
2683 case 'g':
2684 case KEY_HOME:
2685 s->selected = 0;
2686 s->first_displayed_entry = TAILQ_FIRST(&s->commits.head);
2687 select_commit(s);
2688 view->count = 0;
2689 break;
2690 case CTRL('u'):
2691 case 'u':
2692 nscroll /= 2;
2693 /* FALL THROUGH */
2694 case KEY_PPAGE:
2695 case CTRL('b'):
2696 case 'b':
2697 if (s->first_displayed_entry == NULL)
2698 break;
2699 if (TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
2700 s->selected = MAX(0, s->selected - nscroll - 1);
2701 else
2702 log_scroll_up(s, nscroll);
2703 select_commit(s);
2704 if (s->selected_entry->idx == 0)
2705 view->count = 0;
2706 break;
2707 case 'j':
2708 case KEY_DOWN:
2709 case '>':
2710 case '.':
2711 case CTRL('n'):
2712 if (s->first_displayed_entry == NULL)
2713 break;
2714 if (s->selected < MIN(view->nlines - 2,
2715 s->commits.ncommits - 1))
2716 s->selected++;
2717 else {
2718 err = log_scroll_down(view, 1);
2719 if (err)
2720 break;
2722 select_commit(s);
2723 if (s->thread_args.log_complete &&
2724 s->selected_entry->idx == s->commits.ncommits - 1)
2725 view->count = 0;
2726 break;
2727 case 'G':
2728 case KEY_END: {
2729 /* We don't know yet how many commits, so we're forced to
2730 * traverse them all. */
2731 view->count = 0;
2732 if (!s->thread_args.log_complete) {
2733 s->thread_args.load_all = 1;
2734 return trigger_log_thread(view, 0);
2737 s->selected = 0;
2738 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
2739 for (n = 0; n < view->nlines - 1; n++) {
2740 if (entry == NULL)
2741 break;
2742 s->first_displayed_entry = entry;
2743 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2745 if (n > 0)
2746 s->selected = n - 1;
2747 select_commit(s);
2748 break;
2750 case CTRL('d'):
2751 case 'd':
2752 nscroll /= 2;
2753 /* FALL THROUGH */
2754 case KEY_NPAGE:
2755 case CTRL('f'):
2756 case 'f':
2757 case ' ': {
2758 struct commit_queue_entry *first;
2759 first = s->first_displayed_entry;
2760 if (first == NULL) {
2761 view->count = 0;
2762 break;
2764 err = log_scroll_down(view, nscroll);
2765 if (err)
2766 break;
2767 if (first == s->first_displayed_entry &&
2768 s->selected < MIN(view->nlines - 2,
2769 s->commits.ncommits - 1)) {
2770 /* can't scroll further down */
2771 s->selected += MIN(s->last_displayed_entry->idx -
2772 s->selected_entry->idx, nscroll + 1);
2774 select_commit(s);
2775 if (s->thread_args.log_complete &&
2776 s->selected_entry->idx == s->commits.ncommits - 1)
2777 view->count = 0;
2778 break;
2780 case KEY_RESIZE:
2781 if (s->selected > view->nlines - 2)
2782 s->selected = view->nlines - 2;
2783 if (s->selected > s->commits.ncommits - 1)
2784 s->selected = s->commits.ncommits - 1;
2785 select_commit(s);
2786 if (s->commits.ncommits < view->nlines - 1 &&
2787 !s->thread_args.log_complete) {
2788 s->thread_args.commits_needed += (view->nlines - 1) -
2789 s->commits.ncommits;
2790 err = trigger_log_thread(view, 1);
2792 break;
2793 case KEY_ENTER:
2794 case '\r':
2795 view->count = 0;
2796 if (s->selected_entry == NULL)
2797 break;
2798 if (view_is_parent_view(view))
2799 begin_x = view_split_begin_x(view->begin_x);
2800 err = open_diff_view_for_commit(&diff_view, begin_x,
2801 s->selected_entry->commit, s->selected_entry->id,
2802 view, s->repo);
2803 if (err)
2804 break;
2805 view->focussed = 0;
2806 diff_view->focussed = 1;
2807 if (view_is_parent_view(view)) {
2808 err = view_close_child(view);
2809 if (err)
2810 return err;
2811 err = view_set_child(view, diff_view);
2812 if (err)
2813 return err;
2814 view->focus_child = 1;
2815 } else
2816 *new_view = diff_view;
2817 break;
2818 case 't':
2819 view->count = 0;
2820 if (s->selected_entry == NULL)
2821 break;
2822 if (view_is_parent_view(view))
2823 begin_x = view_split_begin_x(view->begin_x);
2824 err = browse_commit_tree(&tree_view, begin_x,
2825 s->selected_entry, s->in_repo_path, s->head_ref_name,
2826 s->repo);
2827 if (err)
2828 break;
2829 view->focussed = 0;
2830 tree_view->focussed = 1;
2831 if (view_is_parent_view(view)) {
2832 err = view_close_child(view);
2833 if (err)
2834 return err;
2835 err = view_set_child(view, tree_view);
2836 if (err)
2837 return err;
2838 view->focus_child = 1;
2839 } else
2840 *new_view = tree_view;
2841 break;
2842 case KEY_BACKSPACE:
2843 case CTRL('l'):
2844 case 'B':
2845 view->count = 0;
2846 if (ch == KEY_BACKSPACE &&
2847 got_path_is_root_dir(s->in_repo_path))
2848 break;
2849 err = stop_log_thread(s);
2850 if (err)
2851 return err;
2852 if (ch == KEY_BACKSPACE) {
2853 char *parent_path;
2854 err = got_path_dirname(&parent_path, s->in_repo_path);
2855 if (err)
2856 return err;
2857 free(s->in_repo_path);
2858 s->in_repo_path = parent_path;
2859 s->thread_args.in_repo_path = s->in_repo_path;
2860 } else if (ch == CTRL('l')) {
2861 struct got_object_id *start_id;
2862 err = got_repo_match_object_id(&start_id, NULL,
2863 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
2864 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
2865 if (err)
2866 return err;
2867 free(s->start_id);
2868 s->start_id = start_id;
2869 s->thread_args.start_id = s->start_id;
2870 } else /* 'B' */
2871 s->log_branches = !s->log_branches;
2873 if (s->thread_args.pack_fds == NULL) {
2874 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2875 if (err)
2876 return err;
2878 err = got_repo_open(&s->thread_args.repo,
2879 got_repo_get_path(s->repo), NULL,
2880 s->thread_args.pack_fds);
2881 if (err)
2882 return err;
2883 tog_free_refs();
2884 err = tog_load_refs(s->repo, 0);
2885 if (err)
2886 return err;
2887 err = got_commit_graph_open(&s->thread_args.graph,
2888 s->in_repo_path, !s->log_branches);
2889 if (err)
2890 return err;
2891 err = got_commit_graph_iter_start(s->thread_args.graph,
2892 s->start_id, s->repo, NULL, NULL);
2893 if (err)
2894 return err;
2895 free_commits(&s->commits);
2896 s->first_displayed_entry = NULL;
2897 s->last_displayed_entry = NULL;
2898 s->selected_entry = NULL;
2899 s->selected = 0;
2900 s->thread_args.log_complete = 0;
2901 s->quit = 0;
2902 s->thread_args.commits_needed = view->nlines;
2903 s->matched_entry = NULL;
2904 s->search_entry = NULL;
2905 break;
2906 case 'r':
2907 view->count = 0;
2908 if (view_is_parent_view(view))
2909 begin_x = view_split_begin_x(view->begin_x);
2910 ref_view = view_open(view->nlines, view->ncols,
2911 view->begin_y, begin_x, TOG_VIEW_REF);
2912 if (ref_view == NULL)
2913 return got_error_from_errno("view_open");
2914 err = open_ref_view(ref_view, s->repo);
2915 if (err) {
2916 view_close(ref_view);
2917 return err;
2919 view->focussed = 0;
2920 ref_view->focussed = 1;
2921 if (view_is_parent_view(view)) {
2922 err = view_close_child(view);
2923 if (err)
2924 return err;
2925 err = view_set_child(view, ref_view);
2926 if (err)
2927 return err;
2928 view->focus_child = 1;
2929 } else
2930 *new_view = ref_view;
2931 break;
2932 default:
2933 view->count = 0;
2934 break;
2937 return err;
2940 static const struct got_error *
2941 apply_unveil(const char *repo_path, const char *worktree_path)
2943 const struct got_error *error;
2945 #ifdef PROFILE
2946 if (unveil("gmon.out", "rwc") != 0)
2947 return got_error_from_errno2("unveil", "gmon.out");
2948 #endif
2949 if (repo_path && unveil(repo_path, "r") != 0)
2950 return got_error_from_errno2("unveil", repo_path);
2952 if (worktree_path && unveil(worktree_path, "rwc") != 0)
2953 return got_error_from_errno2("unveil", worktree_path);
2955 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
2956 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
2958 error = got_privsep_unveil_exec_helpers();
2959 if (error != NULL)
2960 return error;
2962 if (unveil(NULL, NULL) != 0)
2963 return got_error_from_errno("unveil");
2965 return NULL;
2968 static void
2969 init_curses(void)
2972 * Override default signal handlers before starting ncurses.
2973 * This should prevent ncurses from installing its own
2974 * broken cleanup() signal handler.
2976 signal(SIGWINCH, tog_sigwinch);
2977 signal(SIGPIPE, tog_sigpipe);
2978 signal(SIGCONT, tog_sigcont);
2979 signal(SIGINT, tog_sigint);
2980 signal(SIGTERM, tog_sigterm);
2982 initscr();
2983 cbreak();
2984 halfdelay(1); /* Do fast refresh while initial view is loading. */
2985 noecho();
2986 nonl();
2987 intrflush(stdscr, FALSE);
2988 keypad(stdscr, TRUE);
2989 curs_set(0);
2990 if (getenv("TOG_COLORS") != NULL) {
2991 start_color();
2992 use_default_colors();
2996 static const struct got_error *
2997 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
2998 struct got_repository *repo, struct got_worktree *worktree)
3000 const struct got_error *err = NULL;
3002 if (argc == 0) {
3003 *in_repo_path = strdup("/");
3004 if (*in_repo_path == NULL)
3005 return got_error_from_errno("strdup");
3006 return NULL;
3009 if (worktree) {
3010 const char *prefix = got_worktree_get_path_prefix(worktree);
3011 char *p;
3013 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3014 if (err)
3015 return err;
3016 if (asprintf(in_repo_path, "%s%s%s", prefix,
3017 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3018 p) == -1) {
3019 err = got_error_from_errno("asprintf");
3020 *in_repo_path = NULL;
3022 free(p);
3023 } else
3024 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3026 return err;
3029 static const struct got_error *
3030 cmd_log(int argc, char *argv[])
3032 const struct got_error *error;
3033 struct got_repository *repo = NULL;
3034 struct got_worktree *worktree = NULL;
3035 struct got_object_id *start_id = NULL;
3036 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3037 char *start_commit = NULL, *label = NULL;
3038 struct got_reference *ref = NULL;
3039 const char *head_ref_name = NULL;
3040 int ch, log_branches = 0;
3041 struct tog_view *view;
3042 int *pack_fds = NULL;
3044 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3045 switch (ch) {
3046 case 'b':
3047 log_branches = 1;
3048 break;
3049 case 'c':
3050 start_commit = optarg;
3051 break;
3052 case 'r':
3053 repo_path = realpath(optarg, NULL);
3054 if (repo_path == NULL)
3055 return got_error_from_errno2("realpath",
3056 optarg);
3057 break;
3058 default:
3059 usage_log();
3060 /* NOTREACHED */
3064 argc -= optind;
3065 argv += optind;
3067 if (argc > 1)
3068 usage_log();
3070 error = got_repo_pack_fds_open(&pack_fds);
3071 if (error != NULL)
3072 goto done;
3074 if (repo_path == NULL) {
3075 cwd = getcwd(NULL, 0);
3076 if (cwd == NULL)
3077 return got_error_from_errno("getcwd");
3078 error = got_worktree_open(&worktree, cwd);
3079 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3080 goto done;
3081 if (worktree)
3082 repo_path =
3083 strdup(got_worktree_get_repo_path(worktree));
3084 else
3085 repo_path = strdup(cwd);
3086 if (repo_path == NULL) {
3087 error = got_error_from_errno("strdup");
3088 goto done;
3092 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3093 if (error != NULL)
3094 goto done;
3096 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3097 repo, worktree);
3098 if (error)
3099 goto done;
3101 init_curses();
3103 error = apply_unveil(got_repo_get_path(repo),
3104 worktree ? got_worktree_get_root_path(worktree) : NULL);
3105 if (error)
3106 goto done;
3108 /* already loaded by tog_log_with_path()? */
3109 if (TAILQ_EMPTY(&tog_refs)) {
3110 error = tog_load_refs(repo, 0);
3111 if (error)
3112 goto done;
3115 if (start_commit == NULL) {
3116 error = got_repo_match_object_id(&start_id, &label,
3117 worktree ? got_worktree_get_head_ref_name(worktree) :
3118 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3119 if (error)
3120 goto done;
3121 head_ref_name = label;
3122 } else {
3123 error = got_ref_open(&ref, repo, start_commit, 0);
3124 if (error == NULL)
3125 head_ref_name = got_ref_get_name(ref);
3126 else if (error->code != GOT_ERR_NOT_REF)
3127 goto done;
3128 error = got_repo_match_object_id(&start_id, NULL,
3129 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3130 if (error)
3131 goto done;
3134 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3135 if (view == NULL) {
3136 error = got_error_from_errno("view_open");
3137 goto done;
3139 error = open_log_view(view, start_id, repo, head_ref_name,
3140 in_repo_path, log_branches);
3141 if (error)
3142 goto done;
3143 if (worktree) {
3144 /* Release work tree lock. */
3145 got_worktree_close(worktree);
3146 worktree = NULL;
3148 error = view_loop(view);
3149 done:
3150 free(in_repo_path);
3151 free(repo_path);
3152 free(cwd);
3153 free(start_id);
3154 free(label);
3155 if (ref)
3156 got_ref_close(ref);
3157 if (repo) {
3158 const struct got_error *close_err = got_repo_close(repo);
3159 if (error == NULL)
3160 error = close_err;
3162 if (worktree)
3163 got_worktree_close(worktree);
3164 if (pack_fds) {
3165 const struct got_error *pack_err =
3166 got_repo_pack_fds_close(pack_fds);
3167 if (error == NULL)
3168 error = pack_err;
3170 tog_free_refs();
3171 return error;
3174 __dead static void
3175 usage_diff(void)
3177 endwin();
3178 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3179 "[-w] object1 object2\n", getprogname());
3180 exit(1);
3183 static int
3184 match_line(const char *line, regex_t *regex, size_t nmatch,
3185 regmatch_t *regmatch)
3187 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3190 static struct tog_color *
3191 match_color(struct tog_colors *colors, const char *line)
3193 struct tog_color *tc = NULL;
3195 STAILQ_FOREACH(tc, colors, entry) {
3196 if (match_line(line, &tc->regex, 0, NULL))
3197 return tc;
3200 return NULL;
3203 static const struct got_error *
3204 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3205 WINDOW *window, int skipcol, regmatch_t *regmatch)
3207 const struct got_error *err = NULL;
3208 char *exstr = NULL;
3209 wchar_t *wline = NULL;
3210 int rme, rms, n, width, scrollx;
3211 int width0 = 0, width1 = 0, width2 = 0;
3212 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3214 *wtotal = 0;
3216 rms = regmatch->rm_so;
3217 rme = regmatch->rm_eo;
3219 err = expand_tab(&exstr, line);
3220 if (err)
3221 return err;
3223 /* Split the line into 3 segments, according to match offsets. */
3224 seg0 = strndup(exstr, rms);
3225 if (seg0 == NULL) {
3226 err = got_error_from_errno("strndup");
3227 goto done;
3229 seg1 = strndup(exstr + rms, rme - rms);
3230 if (seg1 == NULL) {
3231 err = got_error_from_errno("strndup");
3232 goto done;
3234 seg2 = strdup(exstr + rme);
3235 if (seg2 == NULL) {
3236 err = got_error_from_errno("strndup");
3237 goto done;
3240 /* draw up to matched token if we haven't scrolled past it */
3241 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3242 col_tab_align, 1);
3243 if (err)
3244 goto done;
3245 n = MAX(width0 - skipcol, 0);
3246 if (n) {
3247 free(wline);
3248 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3249 wlimit, col_tab_align, 1);
3250 if (err)
3251 goto done;
3252 waddwstr(window, &wline[scrollx]);
3253 wlimit -= width;
3254 *wtotal += width;
3257 if (wlimit > 0) {
3258 int i = 0, w = 0;
3259 size_t wlen;
3261 free(wline);
3262 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3263 col_tab_align, 1);
3264 if (err)
3265 goto done;
3266 wlen = wcslen(wline);
3267 while (i < wlen) {
3268 width = wcwidth(wline[i]);
3269 if (width == -1) {
3270 /* should not happen, tabs are expanded */
3271 err = got_error(GOT_ERR_RANGE);
3272 goto done;
3274 if (width0 + w + width > skipcol)
3275 break;
3276 w += width;
3277 i++;
3279 /* draw (visible part of) matched token (if scrolled into it) */
3280 if (width1 - w > 0) {
3281 wattron(window, A_STANDOUT);
3282 waddwstr(window, &wline[i]);
3283 wattroff(window, A_STANDOUT);
3284 wlimit -= (width1 - w);
3285 *wtotal += (width1 - w);
3289 if (wlimit > 0) { /* draw rest of line */
3290 free(wline);
3291 if (skipcol > width0 + width1) {
3292 err = format_line(&wline, &width2, &scrollx, seg2,
3293 skipcol - (width0 + width1), wlimit,
3294 col_tab_align, 1);
3295 if (err)
3296 goto done;
3297 waddwstr(window, &wline[scrollx]);
3298 } else {
3299 err = format_line(&wline, &width2, NULL, seg2, 0,
3300 wlimit, col_tab_align, 1);
3301 if (err)
3302 goto done;
3303 waddwstr(window, wline);
3305 *wtotal += width2;
3307 done:
3308 free(wline);
3309 free(exstr);
3310 free(seg0);
3311 free(seg1);
3312 free(seg2);
3313 return err;
3316 static const struct got_error *
3317 draw_file(struct tog_view *view, const char *header)
3319 struct tog_diff_view_state *s = &view->state.diff;
3320 regmatch_t *regmatch = &view->regmatch;
3321 const struct got_error *err;
3322 int nprinted = 0;
3323 char *line;
3324 size_t linesize = 0;
3325 ssize_t linelen;
3326 struct tog_color *tc;
3327 wchar_t *wline;
3328 int width;
3329 int max_lines = view->nlines;
3330 int nlines = s->nlines;
3331 off_t line_offset;
3333 line_offset = s->line_offsets[s->first_displayed_line - 1];
3334 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3335 return got_error_from_errno("fseek");
3337 werase(view->window);
3339 if (header) {
3340 if (asprintf(&line, "[%d/%d] %s",
3341 s->first_displayed_line - 1 + s->selected_line, nlines,
3342 header) == -1)
3343 return got_error_from_errno("asprintf");
3344 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3345 0, 0);
3346 free(line);
3347 if (err)
3348 return err;
3350 if (view_needs_focus_indication(view))
3351 wstandout(view->window);
3352 waddwstr(view->window, wline);
3353 free(wline);
3354 wline = NULL;
3355 if (view_needs_focus_indication(view))
3356 wstandend(view->window);
3357 if (width <= view->ncols - 1)
3358 waddch(view->window, '\n');
3360 if (max_lines <= 1)
3361 return NULL;
3362 max_lines--;
3365 s->eof = 0;
3366 view->maxx = 0;
3367 line = NULL;
3368 while (max_lines > 0 && nprinted < max_lines) {
3369 linelen = getline(&line, &linesize, s->f);
3370 if (linelen == -1) {
3371 if (feof(s->f)) {
3372 s->eof = 1;
3373 break;
3375 free(line);
3376 return got_ferror(s->f, GOT_ERR_IO);
3379 /* Set view->maxx based on full line length. */
3380 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3381 view->x ? 1 : 0);
3382 if (err) {
3383 free(line);
3384 return err;
3386 view->maxx = MAX(view->maxx, width);
3387 free(wline);
3388 wline = NULL;
3390 tc = match_color(&s->colors, line);
3391 if (tc)
3392 wattr_on(view->window,
3393 COLOR_PAIR(tc->colorpair), NULL);
3394 if (s->first_displayed_line + nprinted == s->matched_line &&
3395 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3396 err = add_matched_line(&width, line, view->ncols, 0,
3397 view->window, view->x, regmatch);
3398 if (err) {
3399 free(line);
3400 return err;
3402 } else {
3403 int skip;
3404 err = format_line(&wline, &width, &skip, line,
3405 view->x, view->ncols, 0, view->x ? 1 : 0);
3406 if (err) {
3407 free(line);
3408 return err;
3410 waddwstr(view->window, &wline[skip]);
3411 free(wline);
3412 wline = NULL;
3414 if (tc)
3415 wattr_off(view->window,
3416 COLOR_PAIR(tc->colorpair), NULL);
3417 if (width <= view->ncols - 1)
3418 waddch(view->window, '\n');
3419 nprinted++;
3421 free(line);
3422 if (nprinted >= 1)
3423 s->last_displayed_line = s->first_displayed_line +
3424 (nprinted - 1);
3425 else
3426 s->last_displayed_line = s->first_displayed_line;
3428 view_vborder(view);
3430 if (s->eof) {
3431 while (nprinted < view->nlines) {
3432 waddch(view->window, '\n');
3433 nprinted++;
3436 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3437 view->ncols, 0, 0);
3438 if (err) {
3439 return err;
3442 wstandout(view->window);
3443 waddwstr(view->window, wline);
3444 free(wline);
3445 wline = NULL;
3446 wstandend(view->window);
3449 return NULL;
3452 static char *
3453 get_datestr(time_t *time, char *datebuf)
3455 struct tm mytm, *tm;
3456 char *p, *s;
3458 tm = gmtime_r(time, &mytm);
3459 if (tm == NULL)
3460 return NULL;
3461 s = asctime_r(tm, datebuf);
3462 if (s == NULL)
3463 return NULL;
3464 p = strchr(s, '\n');
3465 if (p)
3466 *p = '\0';
3467 return s;
3470 static const struct got_error *
3471 get_changed_paths(struct got_pathlist_head *paths,
3472 struct got_commit_object *commit, struct got_repository *repo)
3474 const struct got_error *err = NULL;
3475 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3476 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3477 struct got_object_qid *qid;
3479 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3480 if (qid != NULL) {
3481 struct got_commit_object *pcommit;
3482 err = got_object_open_as_commit(&pcommit, repo,
3483 &qid->id);
3484 if (err)
3485 return err;
3487 tree_id1 = got_object_id_dup(
3488 got_object_commit_get_tree_id(pcommit));
3489 if (tree_id1 == NULL) {
3490 got_object_commit_close(pcommit);
3491 return got_error_from_errno("got_object_id_dup");
3493 got_object_commit_close(pcommit);
3497 if (tree_id1) {
3498 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3499 if (err)
3500 goto done;
3503 tree_id2 = got_object_commit_get_tree_id(commit);
3504 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3505 if (err)
3506 goto done;
3508 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
3509 got_diff_tree_collect_changed_paths, paths, 0);
3510 done:
3511 if (tree1)
3512 got_object_tree_close(tree1);
3513 if (tree2)
3514 got_object_tree_close(tree2);
3515 free(tree_id1);
3516 return err;
3519 static const struct got_error *
3520 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
3522 off_t *p;
3524 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
3525 if (p == NULL)
3526 return got_error_from_errno("reallocarray");
3527 *line_offsets = p;
3528 (*line_offsets)[*nlines] = off;
3529 (*nlines)++;
3530 return NULL;
3533 static const struct got_error *
3534 write_commit_info(off_t **line_offsets, size_t *nlines,
3535 struct got_object_id *commit_id, struct got_reflist_head *refs,
3536 struct got_repository *repo, FILE *outfile)
3538 const struct got_error *err = NULL;
3539 char datebuf[26], *datestr;
3540 struct got_commit_object *commit;
3541 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
3542 time_t committer_time;
3543 const char *author, *committer;
3544 char *refs_str = NULL;
3545 struct got_pathlist_head changed_paths;
3546 struct got_pathlist_entry *pe;
3547 off_t outoff = 0;
3548 int n;
3550 TAILQ_INIT(&changed_paths);
3552 if (refs) {
3553 err = build_refs_str(&refs_str, refs, commit_id, repo);
3554 if (err)
3555 return err;
3558 err = got_object_open_as_commit(&commit, repo, commit_id);
3559 if (err)
3560 return err;
3562 err = got_object_id_str(&id_str, commit_id);
3563 if (err) {
3564 err = got_error_from_errno("got_object_id_str");
3565 goto done;
3568 err = add_line_offset(line_offsets, nlines, 0);
3569 if (err)
3570 goto done;
3572 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3573 refs_str ? refs_str : "", refs_str ? ")" : "");
3574 if (n < 0) {
3575 err = got_error_from_errno("fprintf");
3576 goto done;
3578 outoff += n;
3579 err = add_line_offset(line_offsets, nlines, outoff);
3580 if (err)
3581 goto done;
3583 n = fprintf(outfile, "from: %s\n",
3584 got_object_commit_get_author(commit));
3585 if (n < 0) {
3586 err = got_error_from_errno("fprintf");
3587 goto done;
3589 outoff += n;
3590 err = add_line_offset(line_offsets, nlines, outoff);
3591 if (err)
3592 goto done;
3594 committer_time = got_object_commit_get_committer_time(commit);
3595 datestr = get_datestr(&committer_time, datebuf);
3596 if (datestr) {
3597 n = fprintf(outfile, "date: %s UTC\n", datestr);
3598 if (n < 0) {
3599 err = got_error_from_errno("fprintf");
3600 goto done;
3602 outoff += n;
3603 err = add_line_offset(line_offsets, nlines, outoff);
3604 if (err)
3605 goto done;
3607 author = got_object_commit_get_author(commit);
3608 committer = got_object_commit_get_committer(commit);
3609 if (strcmp(author, committer) != 0) {
3610 n = fprintf(outfile, "via: %s\n", committer);
3611 if (n < 0) {
3612 err = got_error_from_errno("fprintf");
3613 goto done;
3615 outoff += n;
3616 err = add_line_offset(line_offsets, nlines, outoff);
3617 if (err)
3618 goto done;
3620 if (got_object_commit_get_nparents(commit) > 1) {
3621 const struct got_object_id_queue *parent_ids;
3622 struct got_object_qid *qid;
3623 int pn = 1;
3624 parent_ids = got_object_commit_get_parent_ids(commit);
3625 STAILQ_FOREACH(qid, parent_ids, entry) {
3626 err = got_object_id_str(&id_str, &qid->id);
3627 if (err)
3628 goto done;
3629 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
3630 if (n < 0) {
3631 err = got_error_from_errno("fprintf");
3632 goto done;
3634 outoff += n;
3635 err = add_line_offset(line_offsets, nlines, outoff);
3636 if (err)
3637 goto done;
3638 free(id_str);
3639 id_str = NULL;
3643 err = got_object_commit_get_logmsg(&logmsg, commit);
3644 if (err)
3645 goto done;
3646 s = logmsg;
3647 while ((line = strsep(&s, "\n")) != NULL) {
3648 n = fprintf(outfile, "%s\n", line);
3649 if (n < 0) {
3650 err = got_error_from_errno("fprintf");
3651 goto done;
3653 outoff += n;
3654 err = add_line_offset(line_offsets, nlines, outoff);
3655 if (err)
3656 goto done;
3659 err = get_changed_paths(&changed_paths, commit, repo);
3660 if (err)
3661 goto done;
3662 TAILQ_FOREACH(pe, &changed_paths, entry) {
3663 struct got_diff_changed_path *cp = pe->data;
3664 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
3665 if (n < 0) {
3666 err = got_error_from_errno("fprintf");
3667 goto done;
3669 outoff += n;
3670 err = add_line_offset(line_offsets, nlines, outoff);
3671 if (err)
3672 goto done;
3673 free((char *)pe->path);
3674 free(pe->data);
3677 fputc('\n', outfile);
3678 outoff++;
3679 err = add_line_offset(line_offsets, nlines, outoff);
3680 done:
3681 got_pathlist_free(&changed_paths);
3682 free(id_str);
3683 free(logmsg);
3684 free(refs_str);
3685 got_object_commit_close(commit);
3686 if (err) {
3687 free(*line_offsets);
3688 *line_offsets = NULL;
3689 *nlines = 0;
3691 return err;
3694 static const struct got_error *
3695 create_diff(struct tog_diff_view_state *s)
3697 const struct got_error *err = NULL;
3698 FILE *f = NULL;
3699 int obj_type;
3701 free(s->line_offsets);
3702 s->line_offsets = malloc(sizeof(off_t));
3703 if (s->line_offsets == NULL)
3704 return got_error_from_errno("malloc");
3705 s->nlines = 0;
3707 f = got_opentemp();
3708 if (f == NULL) {
3709 err = got_error_from_errno("got_opentemp");
3710 goto done;
3712 if (s->f && fclose(s->f) == EOF) {
3713 err = got_error_from_errno("fclose");
3714 goto done;
3716 s->f = f;
3718 if (s->id1)
3719 err = got_object_get_type(&obj_type, s->repo, s->id1);
3720 else
3721 err = got_object_get_type(&obj_type, s->repo, s->id2);
3722 if (err)
3723 goto done;
3725 switch (obj_type) {
3726 case GOT_OBJ_TYPE_BLOB:
3727 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
3728 s->f1, s->f2, s->id1, s->id2, s->label1, s->label2,
3729 s->diff_context, s->ignore_whitespace, s->force_text_diff,
3730 s->repo, s->f);
3731 break;
3732 case GOT_OBJ_TYPE_TREE:
3733 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
3734 s->f1, s->f2, s->id1, s->id2, NULL, "", "", s->diff_context,
3735 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
3736 break;
3737 case GOT_OBJ_TYPE_COMMIT: {
3738 const struct got_object_id_queue *parent_ids;
3739 struct got_object_qid *pid;
3740 struct got_commit_object *commit2;
3741 struct got_reflist_head *refs;
3743 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
3744 if (err)
3745 goto done;
3746 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
3747 /* Show commit info if we're diffing to a parent/root commit. */
3748 if (s->id1 == NULL) {
3749 err = write_commit_info(&s->line_offsets, &s->nlines,
3750 s->id2, refs, s->repo, s->f);
3751 if (err)
3752 goto done;
3753 } else {
3754 parent_ids = got_object_commit_get_parent_ids(commit2);
3755 STAILQ_FOREACH(pid, parent_ids, entry) {
3756 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
3757 err = write_commit_info(
3758 &s->line_offsets, &s->nlines,
3759 s->id2, refs, s->repo, s->f);
3760 if (err)
3761 goto done;
3762 break;
3766 got_object_commit_close(commit2);
3768 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
3769 s->f1, s->f2, s->id1, s->id2, NULL, s->diff_context,
3770 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
3771 break;
3773 default:
3774 err = got_error(GOT_ERR_OBJ_TYPE);
3775 break;
3777 if (err)
3778 goto done;
3779 done:
3780 if (s->f && fflush(s->f) != 0 && err == NULL)
3781 err = got_error_from_errno("fflush");
3782 return err;
3785 static void
3786 diff_view_indicate_progress(struct tog_view *view)
3788 mvwaddstr(view->window, 0, 0, "diffing...");
3789 update_panels();
3790 doupdate();
3793 static const struct got_error *
3794 search_start_diff_view(struct tog_view *view)
3796 struct tog_diff_view_state *s = &view->state.diff;
3798 s->matched_line = 0;
3799 return NULL;
3802 static const struct got_error *
3803 search_next_diff_view(struct tog_view *view)
3805 struct tog_diff_view_state *s = &view->state.diff;
3806 const struct got_error *err = NULL;
3807 int lineno;
3808 char *line = NULL;
3809 size_t linesize = 0;
3810 ssize_t linelen;
3812 if (!view->searching) {
3813 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3814 return NULL;
3817 if (s->matched_line) {
3818 if (view->searching == TOG_SEARCH_FORWARD)
3819 lineno = s->matched_line + 1;
3820 else
3821 lineno = s->matched_line - 1;
3822 } else
3823 lineno = s->first_displayed_line;
3825 while (1) {
3826 off_t offset;
3828 if (lineno <= 0 || lineno > s->nlines) {
3829 if (s->matched_line == 0) {
3830 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3831 break;
3834 if (view->searching == TOG_SEARCH_FORWARD)
3835 lineno = 1;
3836 else
3837 lineno = s->nlines;
3840 offset = s->line_offsets[lineno - 1];
3841 if (fseeko(s->f, offset, SEEK_SET) != 0) {
3842 free(line);
3843 return got_error_from_errno("fseeko");
3845 linelen = getline(&line, &linesize, s->f);
3846 if (linelen != -1) {
3847 char *exstr;
3848 err = expand_tab(&exstr, line);
3849 if (err)
3850 break;
3851 if (match_line(exstr, &view->regex, 1,
3852 &view->regmatch)) {
3853 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3854 s->matched_line = lineno;
3855 free(exstr);
3856 break;
3858 free(exstr);
3860 if (view->searching == TOG_SEARCH_FORWARD)
3861 lineno++;
3862 else
3863 lineno--;
3865 free(line);
3867 if (s->matched_line) {
3868 s->first_displayed_line = s->matched_line;
3869 s->selected_line = 1;
3872 return err;
3875 static const struct got_error *
3876 close_diff_view(struct tog_view *view)
3878 const struct got_error *err = NULL;
3879 struct tog_diff_view_state *s = &view->state.diff;
3881 free(s->id1);
3882 s->id1 = NULL;
3883 free(s->id2);
3884 s->id2 = NULL;
3885 if (s->f && fclose(s->f) == EOF)
3886 err = got_error_from_errno("fclose");
3887 s->f = NULL;
3888 if (s->f1 && fclose(s->f1) == EOF)
3889 err = got_error_from_errno("fclose");
3890 s->f1 = NULL;
3891 if (s->f2 && fclose(s->f2) == EOF)
3892 err = got_error_from_errno("fclose");
3893 s->f2 = NULL;
3894 free_colors(&s->colors);
3895 free(s->line_offsets);
3896 s->line_offsets = NULL;
3897 s->nlines = 0;
3898 return err;
3901 static const struct got_error *
3902 open_diff_view(struct tog_view *view, struct got_object_id *id1,
3903 struct got_object_id *id2, const char *label1, const char *label2,
3904 int diff_context, int ignore_whitespace, int force_text_diff,
3905 struct tog_view *log_view, struct got_repository *repo)
3907 const struct got_error *err;
3908 struct tog_diff_view_state *s = &view->state.diff;
3910 memset(s, 0, sizeof(*s));
3912 if (id1 != NULL && id2 != NULL) {
3913 int type1, type2;
3914 err = got_object_get_type(&type1, repo, id1);
3915 if (err)
3916 return err;
3917 err = got_object_get_type(&type2, repo, id2);
3918 if (err)
3919 return err;
3921 if (type1 != type2)
3922 return got_error(GOT_ERR_OBJ_TYPE);
3924 s->first_displayed_line = 1;
3925 s->last_displayed_line = view->nlines;
3926 s->selected_line = 1;
3927 s->repo = repo;
3928 s->id1 = id1;
3929 s->id2 = id2;
3930 s->label1 = label1;
3931 s->label2 = label2;
3933 if (id1) {
3934 s->id1 = got_object_id_dup(id1);
3935 if (s->id1 == NULL)
3936 return got_error_from_errno("got_object_id_dup");
3937 } else
3938 s->id1 = NULL;
3940 s->id2 = got_object_id_dup(id2);
3941 if (s->id2 == NULL) {
3942 err = got_error_from_errno("got_object_id_dup");
3943 goto done;
3946 s->f1 = got_opentemp();
3947 if (s->f1 == NULL) {
3948 err = got_error_from_errno("got_opentemp");
3949 goto done;
3952 s->f2 = got_opentemp();
3953 if (s->f2 == NULL) {
3954 err = got_error_from_errno("got_opentemp");
3955 goto done;
3958 s->first_displayed_line = 1;
3959 s->last_displayed_line = view->nlines;
3960 s->diff_context = diff_context;
3961 s->ignore_whitespace = ignore_whitespace;
3962 s->force_text_diff = force_text_diff;
3963 s->log_view = log_view;
3964 s->repo = repo;
3966 STAILQ_INIT(&s->colors);
3967 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3968 err = add_color(&s->colors,
3969 "^-", TOG_COLOR_DIFF_MINUS,
3970 get_color_value("TOG_COLOR_DIFF_MINUS"));
3971 if (err)
3972 goto done;
3973 err = add_color(&s->colors, "^\\+",
3974 TOG_COLOR_DIFF_PLUS,
3975 get_color_value("TOG_COLOR_DIFF_PLUS"));
3976 if (err)
3977 goto done;
3978 err = add_color(&s->colors,
3979 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
3980 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
3981 if (err)
3982 goto done;
3984 err = add_color(&s->colors,
3985 "^(commit [0-9a-f]|parent [0-9]|"
3986 "(blob|file|tree|commit) [-+] |"
3987 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
3988 get_color_value("TOG_COLOR_DIFF_META"));
3989 if (err)
3990 goto done;
3992 err = add_color(&s->colors,
3993 "^(from|via): ", TOG_COLOR_AUTHOR,
3994 get_color_value("TOG_COLOR_AUTHOR"));
3995 if (err)
3996 goto done;
3998 err = add_color(&s->colors,
3999 "^date: ", TOG_COLOR_DATE,
4000 get_color_value("TOG_COLOR_DATE"));
4001 if (err)
4002 goto done;
4005 if (log_view && view_is_splitscreen(view))
4006 show_log_view(log_view); /* draw vborder */
4007 diff_view_indicate_progress(view);
4009 err = create_diff(s);
4011 view->show = show_diff_view;
4012 view->input = input_diff_view;
4013 view->close = close_diff_view;
4014 view->search_start = search_start_diff_view;
4015 view->search_next = search_next_diff_view;
4016 done:
4017 if (err)
4018 close_diff_view(view);
4019 return err;
4022 static const struct got_error *
4023 show_diff_view(struct tog_view *view)
4025 const struct got_error *err;
4026 struct tog_diff_view_state *s = &view->state.diff;
4027 char *id_str1 = NULL, *id_str2, *header;
4028 const char *label1, *label2;
4030 if (s->id1) {
4031 err = got_object_id_str(&id_str1, s->id1);
4032 if (err)
4033 return err;
4034 label1 = s->label1 ? : id_str1;
4035 } else
4036 label1 = "/dev/null";
4038 err = got_object_id_str(&id_str2, s->id2);
4039 if (err)
4040 return err;
4041 label2 = s->label2 ? : id_str2;
4043 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4044 err = got_error_from_errno("asprintf");
4045 free(id_str1);
4046 free(id_str2);
4047 return err;
4049 free(id_str1);
4050 free(id_str2);
4052 err = draw_file(view, header);
4053 free(header);
4054 return err;
4057 static const struct got_error *
4058 set_selected_commit(struct tog_diff_view_state *s,
4059 struct commit_queue_entry *entry)
4061 const struct got_error *err;
4062 const struct got_object_id_queue *parent_ids;
4063 struct got_commit_object *selected_commit;
4064 struct got_object_qid *pid;
4066 free(s->id2);
4067 s->id2 = got_object_id_dup(entry->id);
4068 if (s->id2 == NULL)
4069 return got_error_from_errno("got_object_id_dup");
4071 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4072 if (err)
4073 return err;
4074 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4075 free(s->id1);
4076 pid = STAILQ_FIRST(parent_ids);
4077 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4078 got_object_commit_close(selected_commit);
4079 return NULL;
4082 static const struct got_error *
4083 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4085 const struct got_error *err = NULL;
4086 struct tog_diff_view_state *s = &view->state.diff;
4087 struct tog_log_view_state *ls;
4088 struct commit_queue_entry *old_selected_entry;
4089 char *line = NULL;
4090 size_t linesize = 0;
4091 ssize_t linelen;
4092 int i, nscroll = view->nlines - 1;
4094 switch (ch) {
4095 case '0':
4096 view->x = 0;
4097 break;
4098 case '$':
4099 view->x = MAX(view->maxx - view->ncols / 3, 0);
4100 view->count = 0;
4101 break;
4102 case KEY_RIGHT:
4103 case 'l':
4104 if (view->x + view->ncols / 3 < view->maxx)
4105 view->x += 2; /* move two columns right */
4106 else
4107 view->count = 0;
4108 break;
4109 case KEY_LEFT:
4110 case 'h':
4111 view->x -= MIN(view->x, 2); /* move two columns back */
4112 if (view->x <= 0)
4113 view->count = 0;
4114 break;
4115 case 'a':
4116 case 'w':
4117 if (ch == 'a')
4118 s->force_text_diff = !s->force_text_diff;
4119 if (ch == 'w')
4120 s->ignore_whitespace = !s->ignore_whitespace;
4121 wclear(view->window);
4122 s->first_displayed_line = 1;
4123 s->last_displayed_line = view->nlines;
4124 s->matched_line = 0;
4125 diff_view_indicate_progress(view);
4126 err = create_diff(s);
4127 view->count = 0;
4128 break;
4129 case 'g':
4130 case KEY_HOME:
4131 s->first_displayed_line = 1;
4132 view->count = 0;
4133 break;
4134 case 'G':
4135 case KEY_END:
4136 view->count = 0;
4137 if (s->eof)
4138 break;
4140 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4141 s->eof = 1;
4142 break;
4143 case 'k':
4144 case KEY_UP:
4145 case CTRL('p'):
4146 if (s->first_displayed_line > 1)
4147 s->first_displayed_line--;
4148 else
4149 view->count = 0;
4150 break;
4151 case CTRL('u'):
4152 case 'u':
4153 nscroll /= 2;
4154 /* FALL THROUGH */
4155 case KEY_PPAGE:
4156 case CTRL('b'):
4157 case 'b':
4158 if (s->first_displayed_line == 1) {
4159 view->count = 0;
4160 break;
4162 i = 0;
4163 while (i++ < nscroll && s->first_displayed_line > 1)
4164 s->first_displayed_line--;
4165 break;
4166 case 'j':
4167 case KEY_DOWN:
4168 case CTRL('n'):
4169 if (!s->eof)
4170 s->first_displayed_line++;
4171 else
4172 view->count = 0;
4173 break;
4174 case CTRL('d'):
4175 case 'd':
4176 nscroll /= 2;
4177 /* FALL THROUGH */
4178 case KEY_NPAGE:
4179 case CTRL('f'):
4180 case 'f':
4181 case ' ':
4182 if (s->eof) {
4183 view->count = 0;
4184 break;
4186 i = 0;
4187 while (!s->eof && i++ < nscroll) {
4188 linelen = getline(&line, &linesize, s->f);
4189 s->first_displayed_line++;
4190 if (linelen == -1) {
4191 if (feof(s->f)) {
4192 s->eof = 1;
4193 } else
4194 err = got_ferror(s->f, GOT_ERR_IO);
4195 break;
4198 free(line);
4199 break;
4200 case '[':
4201 if (s->diff_context > 0) {
4202 s->diff_context--;
4203 s->matched_line = 0;
4204 diff_view_indicate_progress(view);
4205 err = create_diff(s);
4206 if (s->first_displayed_line + view->nlines - 1 >
4207 s->nlines) {
4208 s->first_displayed_line = 1;
4209 s->last_displayed_line = view->nlines;
4211 } else
4212 view->count = 0;
4213 break;
4214 case ']':
4215 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4216 s->diff_context++;
4217 s->matched_line = 0;
4218 diff_view_indicate_progress(view);
4219 err = create_diff(s);
4220 } else
4221 view->count = 0;
4222 break;
4223 case '<':
4224 case ',':
4225 if (s->log_view == NULL) {
4226 view->count = 0;
4227 break;
4229 ls = &s->log_view->state.log;
4230 old_selected_entry = ls->selected_entry;
4232 /* view->count handled in input_log_view() */
4233 err = input_log_view(NULL, s->log_view, KEY_UP);
4234 if (err)
4235 break;
4237 if (old_selected_entry == ls->selected_entry)
4238 break;
4240 err = set_selected_commit(s, ls->selected_entry);
4241 if (err)
4242 break;
4244 s->first_displayed_line = 1;
4245 s->last_displayed_line = view->nlines;
4246 s->matched_line = 0;
4247 view->x = 0;
4249 diff_view_indicate_progress(view);
4250 err = create_diff(s);
4251 break;
4252 case '>':
4253 case '.':
4254 if (s->log_view == NULL) {
4255 view->count = 0;
4256 break;
4258 ls = &s->log_view->state.log;
4259 old_selected_entry = ls->selected_entry;
4261 /* view->count handled in input_log_view() */
4262 err = input_log_view(NULL, s->log_view, KEY_DOWN);
4263 if (err)
4264 break;
4266 if (old_selected_entry == ls->selected_entry)
4267 break;
4269 err = set_selected_commit(s, ls->selected_entry);
4270 if (err)
4271 break;
4273 s->first_displayed_line = 1;
4274 s->last_displayed_line = view->nlines;
4275 s->matched_line = 0;
4276 view->x = 0;
4278 diff_view_indicate_progress(view);
4279 err = create_diff(s);
4280 break;
4281 default:
4282 view->count = 0;
4283 break;
4286 return err;
4289 static const struct got_error *
4290 cmd_diff(int argc, char *argv[])
4292 const struct got_error *error = NULL;
4293 struct got_repository *repo = NULL;
4294 struct got_worktree *worktree = NULL;
4295 struct got_object_id *id1 = NULL, *id2 = NULL;
4296 char *repo_path = NULL, *cwd = NULL;
4297 char *id_str1 = NULL, *id_str2 = NULL;
4298 char *label1 = NULL, *label2 = NULL;
4299 int diff_context = 3, ignore_whitespace = 0;
4300 int ch, force_text_diff = 0;
4301 const char *errstr;
4302 struct tog_view *view;
4303 int *pack_fds = NULL;
4305 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4306 switch (ch) {
4307 case 'a':
4308 force_text_diff = 1;
4309 break;
4310 case 'C':
4311 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4312 &errstr);
4313 if (errstr != NULL)
4314 errx(1, "number of context lines is %s: %s",
4315 errstr, errstr);
4316 break;
4317 case 'r':
4318 repo_path = realpath(optarg, NULL);
4319 if (repo_path == NULL)
4320 return got_error_from_errno2("realpath",
4321 optarg);
4322 got_path_strip_trailing_slashes(repo_path);
4323 break;
4324 case 'w':
4325 ignore_whitespace = 1;
4326 break;
4327 default:
4328 usage_diff();
4329 /* NOTREACHED */
4333 argc -= optind;
4334 argv += optind;
4336 if (argc == 0) {
4337 usage_diff(); /* TODO show local worktree changes */
4338 } else if (argc == 2) {
4339 id_str1 = argv[0];
4340 id_str2 = argv[1];
4341 } else
4342 usage_diff();
4344 error = got_repo_pack_fds_open(&pack_fds);
4345 if (error)
4346 goto done;
4348 if (repo_path == NULL) {
4349 cwd = getcwd(NULL, 0);
4350 if (cwd == NULL)
4351 return got_error_from_errno("getcwd");
4352 error = got_worktree_open(&worktree, cwd);
4353 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4354 goto done;
4355 if (worktree)
4356 repo_path =
4357 strdup(got_worktree_get_repo_path(worktree));
4358 else
4359 repo_path = strdup(cwd);
4360 if (repo_path == NULL) {
4361 error = got_error_from_errno("strdup");
4362 goto done;
4366 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4367 if (error)
4368 goto done;
4370 init_curses();
4372 error = apply_unveil(got_repo_get_path(repo), NULL);
4373 if (error)
4374 goto done;
4376 error = tog_load_refs(repo, 0);
4377 if (error)
4378 goto done;
4380 error = got_repo_match_object_id(&id1, &label1, id_str1,
4381 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4382 if (error)
4383 goto done;
4385 error = got_repo_match_object_id(&id2, &label2, id_str2,
4386 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4387 if (error)
4388 goto done;
4390 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4391 if (view == NULL) {
4392 error = got_error_from_errno("view_open");
4393 goto done;
4395 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4396 ignore_whitespace, force_text_diff, NULL, repo);
4397 if (error)
4398 goto done;
4399 error = view_loop(view);
4400 done:
4401 free(label1);
4402 free(label2);
4403 free(repo_path);
4404 free(cwd);
4405 if (repo) {
4406 const struct got_error *close_err = got_repo_close(repo);
4407 if (error == NULL)
4408 error = close_err;
4410 if (worktree)
4411 got_worktree_close(worktree);
4412 if (pack_fds) {
4413 const struct got_error *pack_err =
4414 got_repo_pack_fds_close(pack_fds);
4415 if (error == NULL)
4416 error = pack_err;
4418 tog_free_refs();
4419 return error;
4422 __dead static void
4423 usage_blame(void)
4425 endwin();
4426 fprintf(stderr,
4427 "usage: %s blame [-c commit] [-r repository-path] path\n",
4428 getprogname());
4429 exit(1);
4432 struct tog_blame_line {
4433 int annotated;
4434 struct got_object_id *id;
4437 static const struct got_error *
4438 draw_blame(struct tog_view *view)
4440 struct tog_blame_view_state *s = &view->state.blame;
4441 struct tog_blame *blame = &s->blame;
4442 regmatch_t *regmatch = &view->regmatch;
4443 const struct got_error *err;
4444 int lineno = 0, nprinted = 0;
4445 char *line = NULL;
4446 size_t linesize = 0;
4447 ssize_t linelen;
4448 wchar_t *wline;
4449 int width;
4450 struct tog_blame_line *blame_line;
4451 struct got_object_id *prev_id = NULL;
4452 char *id_str;
4453 struct tog_color *tc;
4455 err = got_object_id_str(&id_str, &s->blamed_commit->id);
4456 if (err)
4457 return err;
4459 rewind(blame->f);
4460 werase(view->window);
4462 if (asprintf(&line, "commit %s", id_str) == -1) {
4463 err = got_error_from_errno("asprintf");
4464 free(id_str);
4465 return err;
4468 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4469 free(line);
4470 line = NULL;
4471 if (err)
4472 return err;
4473 if (view_needs_focus_indication(view))
4474 wstandout(view->window);
4475 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4476 if (tc)
4477 wattr_on(view->window,
4478 COLOR_PAIR(tc->colorpair), NULL);
4479 waddwstr(view->window, wline);
4480 if (tc)
4481 wattr_off(view->window,
4482 COLOR_PAIR(tc->colorpair), NULL);
4483 if (view_needs_focus_indication(view))
4484 wstandend(view->window);
4485 free(wline);
4486 wline = NULL;
4487 if (width < view->ncols - 1)
4488 waddch(view->window, '\n');
4490 if (asprintf(&line, "[%d/%d] %s%s",
4491 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
4492 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
4493 free(id_str);
4494 return got_error_from_errno("asprintf");
4496 free(id_str);
4497 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4498 free(line);
4499 line = NULL;
4500 if (err)
4501 return err;
4502 waddwstr(view->window, wline);
4503 free(wline);
4504 wline = NULL;
4505 if (width < view->ncols - 1)
4506 waddch(view->window, '\n');
4508 s->eof = 0;
4509 view->maxx = 0;
4510 while (nprinted < view->nlines - 2) {
4511 linelen = getline(&line, &linesize, blame->f);
4512 if (linelen == -1) {
4513 if (feof(blame->f)) {
4514 s->eof = 1;
4515 break;
4517 free(line);
4518 return got_ferror(blame->f, GOT_ERR_IO);
4520 if (++lineno < s->first_displayed_line)
4521 continue;
4523 /* Set view->maxx based on full line length. */
4524 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
4525 if (err) {
4526 free(line);
4527 return err;
4529 free(wline);
4530 wline = NULL;
4531 view->maxx = MAX(view->maxx, width);
4533 if (view->focussed && nprinted == s->selected_line - 1)
4534 wstandout(view->window);
4536 if (blame->nlines > 0) {
4537 blame_line = &blame->lines[lineno - 1];
4538 if (blame_line->annotated && prev_id &&
4539 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
4540 !(view->focussed &&
4541 nprinted == s->selected_line - 1)) {
4542 waddstr(view->window, " ");
4543 } else if (blame_line->annotated) {
4544 char *id_str;
4545 err = got_object_id_str(&id_str,
4546 blame_line->id);
4547 if (err) {
4548 free(line);
4549 return err;
4551 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4552 if (tc)
4553 wattr_on(view->window,
4554 COLOR_PAIR(tc->colorpair), NULL);
4555 wprintw(view->window, "%.8s", id_str);
4556 if (tc)
4557 wattr_off(view->window,
4558 COLOR_PAIR(tc->colorpair), NULL);
4559 free(id_str);
4560 prev_id = blame_line->id;
4561 } else {
4562 waddstr(view->window, "........");
4563 prev_id = NULL;
4565 } else {
4566 waddstr(view->window, "........");
4567 prev_id = NULL;
4570 if (view->focussed && nprinted == s->selected_line - 1)
4571 wstandend(view->window);
4572 waddstr(view->window, " ");
4574 if (view->ncols <= 9) {
4575 width = 9;
4576 } else if (s->first_displayed_line + nprinted ==
4577 s->matched_line &&
4578 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4579 err = add_matched_line(&width, line, view->ncols - 9, 9,
4580 view->window, view->x, regmatch);
4581 if (err) {
4582 free(line);
4583 return err;
4585 width += 9;
4586 } else {
4587 int skip;
4588 err = format_line(&wline, &width, &skip, line,
4589 view->x, view->ncols - 9, 9, 1);
4590 if (err) {
4591 free(line);
4592 return err;
4594 waddwstr(view->window, &wline[skip]);
4595 width += 9;
4596 free(wline);
4597 wline = NULL;
4600 if (width <= view->ncols - 1)
4601 waddch(view->window, '\n');
4602 if (++nprinted == 1)
4603 s->first_displayed_line = lineno;
4605 free(line);
4606 s->last_displayed_line = lineno;
4608 view_vborder(view);
4610 return NULL;
4613 static const struct got_error *
4614 blame_cb(void *arg, int nlines, int lineno,
4615 struct got_commit_object *commit, struct got_object_id *id)
4617 const struct got_error *err = NULL;
4618 struct tog_blame_cb_args *a = arg;
4619 struct tog_blame_line *line;
4620 int errcode;
4622 if (nlines != a->nlines ||
4623 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4624 return got_error(GOT_ERR_RANGE);
4626 errcode = pthread_mutex_lock(&tog_mutex);
4627 if (errcode)
4628 return got_error_set_errno(errcode, "pthread_mutex_lock");
4630 if (*a->quit) { /* user has quit the blame view */
4631 err = got_error(GOT_ERR_ITER_COMPLETED);
4632 goto done;
4635 if (lineno == -1)
4636 goto done; /* no change in this commit */
4638 line = &a->lines[lineno - 1];
4639 if (line->annotated)
4640 goto done;
4642 line->id = got_object_id_dup(id);
4643 if (line->id == NULL) {
4644 err = got_error_from_errno("got_object_id_dup");
4645 goto done;
4647 line->annotated = 1;
4648 done:
4649 errcode = pthread_mutex_unlock(&tog_mutex);
4650 if (errcode)
4651 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4652 return err;
4655 static void *
4656 blame_thread(void *arg)
4658 const struct got_error *err, *close_err;
4659 struct tog_blame_thread_args *ta = arg;
4660 struct tog_blame_cb_args *a = ta->cb_args;
4661 int errcode;
4663 err = block_signals_used_by_main_thread();
4664 if (err)
4665 return (void *)err;
4667 err = got_blame(ta->path, a->commit_id, ta->repo,
4668 blame_cb, ta->cb_args, ta->cancel_cb, ta->cancel_arg);
4669 if (err && err->code == GOT_ERR_CANCELLED)
4670 err = NULL;
4672 errcode = pthread_mutex_lock(&tog_mutex);
4673 if (errcode)
4674 return (void *)got_error_set_errno(errcode,
4675 "pthread_mutex_lock");
4677 close_err = got_repo_close(ta->repo);
4678 if (err == NULL)
4679 err = close_err;
4680 ta->repo = NULL;
4681 *ta->complete = 1;
4683 errcode = pthread_mutex_unlock(&tog_mutex);
4684 if (errcode && err == NULL)
4685 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4687 return (void *)err;
4690 static struct got_object_id *
4691 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
4692 int first_displayed_line, int selected_line)
4694 struct tog_blame_line *line;
4696 if (nlines <= 0)
4697 return NULL;
4699 line = &lines[first_displayed_line - 1 + selected_line - 1];
4700 if (!line->annotated)
4701 return NULL;
4703 return line->id;
4706 static const struct got_error *
4707 stop_blame(struct tog_blame *blame)
4709 const struct got_error *err = NULL;
4710 int i;
4712 if (blame->thread) {
4713 int errcode;
4714 errcode = pthread_mutex_unlock(&tog_mutex);
4715 if (errcode)
4716 return got_error_set_errno(errcode,
4717 "pthread_mutex_unlock");
4718 errcode = pthread_join(blame->thread, (void **)&err);
4719 if (errcode)
4720 return got_error_set_errno(errcode, "pthread_join");
4721 errcode = pthread_mutex_lock(&tog_mutex);
4722 if (errcode)
4723 return got_error_set_errno(errcode,
4724 "pthread_mutex_lock");
4725 if (err && err->code == GOT_ERR_ITER_COMPLETED)
4726 err = NULL;
4727 blame->thread = 0; //NULL;
4729 if (blame->thread_args.repo) {
4730 const struct got_error *close_err;
4731 close_err = got_repo_close(blame->thread_args.repo);
4732 if (err == NULL)
4733 err = close_err;
4734 blame->thread_args.repo = NULL;
4736 if (blame->f) {
4737 if (fclose(blame->f) == EOF && err == NULL)
4738 err = got_error_from_errno("fclose");
4739 blame->f = NULL;
4741 if (blame->lines) {
4742 for (i = 0; i < blame->nlines; i++)
4743 free(blame->lines[i].id);
4744 free(blame->lines);
4745 blame->lines = NULL;
4747 free(blame->cb_args.commit_id);
4748 blame->cb_args.commit_id = NULL;
4749 if (blame->pack_fds) {
4750 const struct got_error *pack_err =
4751 got_repo_pack_fds_close(blame->pack_fds);
4752 if (err == NULL)
4753 err = pack_err;
4754 blame->pack_fds = NULL;
4756 return err;
4759 static const struct got_error *
4760 cancel_blame_view(void *arg)
4762 const struct got_error *err = NULL;
4763 int *done = arg;
4764 int errcode;
4766 errcode = pthread_mutex_lock(&tog_mutex);
4767 if (errcode)
4768 return got_error_set_errno(errcode,
4769 "pthread_mutex_unlock");
4771 if (*done)
4772 err = got_error(GOT_ERR_CANCELLED);
4774 errcode = pthread_mutex_unlock(&tog_mutex);
4775 if (errcode)
4776 return got_error_set_errno(errcode,
4777 "pthread_mutex_lock");
4779 return err;
4782 static const struct got_error *
4783 run_blame(struct tog_view *view)
4785 struct tog_blame_view_state *s = &view->state.blame;
4786 struct tog_blame *blame = &s->blame;
4787 const struct got_error *err = NULL;
4788 struct got_commit_object *commit = NULL;
4789 struct got_blob_object *blob = NULL;
4790 struct got_repository *thread_repo = NULL;
4791 struct got_object_id *obj_id = NULL;
4792 int obj_type;
4793 int *pack_fds = NULL;
4795 err = got_object_open_as_commit(&commit, s->repo,
4796 &s->blamed_commit->id);
4797 if (err)
4798 return err;
4800 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
4801 if (err)
4802 goto done;
4804 err = got_object_get_type(&obj_type, s->repo, obj_id);
4805 if (err)
4806 goto done;
4808 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4809 err = got_error(GOT_ERR_OBJ_TYPE);
4810 goto done;
4813 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192);
4814 if (err)
4815 goto done;
4816 blame->f = got_opentemp();
4817 if (blame->f == NULL) {
4818 err = got_error_from_errno("got_opentemp");
4819 goto done;
4821 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
4822 &blame->line_offsets, blame->f, blob);
4823 if (err)
4824 goto done;
4825 if (blame->nlines == 0) {
4826 s->blame_complete = 1;
4827 goto done;
4830 /* Don't include \n at EOF in the blame line count. */
4831 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
4832 blame->nlines--;
4834 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
4835 if (blame->lines == NULL) {
4836 err = got_error_from_errno("calloc");
4837 goto done;
4840 err = got_repo_pack_fds_open(&pack_fds);
4841 if (err)
4842 goto done;
4843 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
4844 pack_fds);
4845 if (err)
4846 goto done;
4848 blame->pack_fds = pack_fds;
4849 blame->cb_args.view = view;
4850 blame->cb_args.lines = blame->lines;
4851 blame->cb_args.nlines = blame->nlines;
4852 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
4853 if (blame->cb_args.commit_id == NULL) {
4854 err = got_error_from_errno("got_object_id_dup");
4855 goto done;
4857 blame->cb_args.quit = &s->done;
4859 blame->thread_args.path = s->path;
4860 blame->thread_args.repo = thread_repo;
4861 blame->thread_args.cb_args = &blame->cb_args;
4862 blame->thread_args.complete = &s->blame_complete;
4863 blame->thread_args.cancel_cb = cancel_blame_view;
4864 blame->thread_args.cancel_arg = &s->done;
4865 s->blame_complete = 0;
4867 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
4868 s->first_displayed_line = 1;
4869 s->last_displayed_line = view->nlines;
4870 s->selected_line = 1;
4872 s->matched_line = 0;
4874 done:
4875 if (commit)
4876 got_object_commit_close(commit);
4877 if (blob)
4878 got_object_blob_close(blob);
4879 free(obj_id);
4880 if (err)
4881 stop_blame(blame);
4882 return err;
4885 static const struct got_error *
4886 open_blame_view(struct tog_view *view, char *path,
4887 struct got_object_id *commit_id, struct got_repository *repo)
4889 const struct got_error *err = NULL;
4890 struct tog_blame_view_state *s = &view->state.blame;
4892 STAILQ_INIT(&s->blamed_commits);
4894 s->path = strdup(path);
4895 if (s->path == NULL)
4896 return got_error_from_errno("strdup");
4898 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
4899 if (err) {
4900 free(s->path);
4901 return err;
4904 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
4905 s->first_displayed_line = 1;
4906 s->last_displayed_line = view->nlines;
4907 s->selected_line = 1;
4908 s->blame_complete = 0;
4909 s->repo = repo;
4910 s->commit_id = commit_id;
4911 memset(&s->blame, 0, sizeof(s->blame));
4913 STAILQ_INIT(&s->colors);
4914 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4915 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
4916 get_color_value("TOG_COLOR_COMMIT"));
4917 if (err)
4918 return err;
4921 view->show = show_blame_view;
4922 view->input = input_blame_view;
4923 view->close = close_blame_view;
4924 view->search_start = search_start_blame_view;
4925 view->search_next = search_next_blame_view;
4927 return run_blame(view);
4930 static const struct got_error *
4931 close_blame_view(struct tog_view *view)
4933 const struct got_error *err = NULL;
4934 struct tog_blame_view_state *s = &view->state.blame;
4936 if (s->blame.thread)
4937 err = stop_blame(&s->blame);
4939 while (!STAILQ_EMPTY(&s->blamed_commits)) {
4940 struct got_object_qid *blamed_commit;
4941 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
4942 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
4943 got_object_qid_free(blamed_commit);
4946 free(s->path);
4947 free_colors(&s->colors);
4948 return err;
4951 static const struct got_error *
4952 search_start_blame_view(struct tog_view *view)
4954 struct tog_blame_view_state *s = &view->state.blame;
4956 s->matched_line = 0;
4957 return NULL;
4960 static const struct got_error *
4961 search_next_blame_view(struct tog_view *view)
4963 struct tog_blame_view_state *s = &view->state.blame;
4964 const struct got_error *err = NULL;
4965 int lineno;
4966 char *line = NULL;
4967 size_t linesize = 0;
4968 ssize_t linelen;
4970 if (!view->searching) {
4971 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4972 return NULL;
4975 if (s->matched_line) {
4976 if (view->searching == TOG_SEARCH_FORWARD)
4977 lineno = s->matched_line + 1;
4978 else
4979 lineno = s->matched_line - 1;
4980 } else
4981 lineno = s->first_displayed_line - 1 + s->selected_line;
4983 while (1) {
4984 off_t offset;
4986 if (lineno <= 0 || lineno > s->blame.nlines) {
4987 if (s->matched_line == 0) {
4988 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4989 break;
4992 if (view->searching == TOG_SEARCH_FORWARD)
4993 lineno = 1;
4994 else
4995 lineno = s->blame.nlines;
4998 offset = s->blame.line_offsets[lineno - 1];
4999 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5000 free(line);
5001 return got_error_from_errno("fseeko");
5003 linelen = getline(&line, &linesize, s->blame.f);
5004 if (linelen != -1) {
5005 char *exstr;
5006 err = expand_tab(&exstr, line);
5007 if (err)
5008 break;
5009 if (match_line(exstr, &view->regex, 1,
5010 &view->regmatch)) {
5011 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5012 s->matched_line = lineno;
5013 free(exstr);
5014 break;
5016 free(exstr);
5018 if (view->searching == TOG_SEARCH_FORWARD)
5019 lineno++;
5020 else
5021 lineno--;
5023 free(line);
5025 if (s->matched_line) {
5026 s->first_displayed_line = s->matched_line;
5027 s->selected_line = 1;
5030 return err;
5033 static const struct got_error *
5034 show_blame_view(struct tog_view *view)
5036 const struct got_error *err = NULL;
5037 struct tog_blame_view_state *s = &view->state.blame;
5038 int errcode;
5040 if (s->blame.thread == 0 && !s->blame_complete) {
5041 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5042 &s->blame.thread_args);
5043 if (errcode)
5044 return got_error_set_errno(errcode, "pthread_create");
5046 halfdelay(1); /* fast refresh while annotating */
5049 if (s->blame_complete)
5050 halfdelay(10); /* disable fast refresh */
5052 err = draw_blame(view);
5054 view_vborder(view);
5055 return err;
5058 static const struct got_error *
5059 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5061 const struct got_error *err = NULL, *thread_err = NULL;
5062 struct tog_view *diff_view;
5063 struct tog_blame_view_state *s = &view->state.blame;
5064 int begin_x = 0, nscroll = view->nlines - 2;
5066 switch (ch) {
5067 case '0':
5068 view->x = 0;
5069 break;
5070 case '$':
5071 view->x = MAX(view->maxx - view->ncols / 3, 0);
5072 view->count = 0;
5073 break;
5074 case KEY_RIGHT:
5075 case 'l':
5076 if (view->x + view->ncols / 3 < view->maxx)
5077 view->x += 2; /* move two columns right */
5078 else
5079 view->count = 0;
5080 break;
5081 case KEY_LEFT:
5082 case 'h':
5083 view->x -= MIN(view->x, 2); /* move two columns back */
5084 if (view->x <= 0)
5085 view->count = 0;
5086 break;
5087 case 'q':
5088 s->done = 1;
5089 break;
5090 case 'g':
5091 case KEY_HOME:
5092 s->selected_line = 1;
5093 s->first_displayed_line = 1;
5094 view->count = 0;
5095 break;
5096 case 'G':
5097 case KEY_END:
5098 if (s->blame.nlines < view->nlines - 2) {
5099 s->selected_line = s->blame.nlines;
5100 s->first_displayed_line = 1;
5101 } else {
5102 s->selected_line = view->nlines - 2;
5103 s->first_displayed_line = s->blame.nlines -
5104 (view->nlines - 3);
5106 view->count = 0;
5107 break;
5108 case 'k':
5109 case KEY_UP:
5110 case CTRL('p'):
5111 if (s->selected_line > 1)
5112 s->selected_line--;
5113 else if (s->selected_line == 1 &&
5114 s->first_displayed_line > 1)
5115 s->first_displayed_line--;
5116 else
5117 view->count = 0;
5118 break;
5119 case CTRL('u'):
5120 case 'u':
5121 nscroll /= 2;
5122 /* FALL THROUGH */
5123 case KEY_PPAGE:
5124 case CTRL('b'):
5125 case 'b':
5126 if (s->first_displayed_line == 1) {
5127 if (view->count > 1)
5128 nscroll += nscroll;
5129 s->selected_line = MAX(1, s->selected_line - nscroll);
5130 view->count = 0;
5131 break;
5133 if (s->first_displayed_line > nscroll)
5134 s->first_displayed_line -= nscroll;
5135 else
5136 s->first_displayed_line = 1;
5137 break;
5138 case 'j':
5139 case KEY_DOWN:
5140 case CTRL('n'):
5141 if (s->selected_line < view->nlines - 2 &&
5142 s->first_displayed_line +
5143 s->selected_line <= s->blame.nlines)
5144 s->selected_line++;
5145 else if (s->last_displayed_line <
5146 s->blame.nlines)
5147 s->first_displayed_line++;
5148 else
5149 view->count = 0;
5150 break;
5151 case 'c':
5152 case 'p': {
5153 struct got_object_id *id = NULL;
5155 view->count = 0;
5156 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5157 s->first_displayed_line, s->selected_line);
5158 if (id == NULL)
5159 break;
5160 if (ch == 'p') {
5161 struct got_commit_object *commit, *pcommit;
5162 struct got_object_qid *pid;
5163 struct got_object_id *blob_id = NULL;
5164 int obj_type;
5165 err = got_object_open_as_commit(&commit,
5166 s->repo, id);
5167 if (err)
5168 break;
5169 pid = STAILQ_FIRST(
5170 got_object_commit_get_parent_ids(commit));
5171 if (pid == NULL) {
5172 got_object_commit_close(commit);
5173 break;
5175 /* Check if path history ends here. */
5176 err = got_object_open_as_commit(&pcommit,
5177 s->repo, &pid->id);
5178 if (err)
5179 break;
5180 err = got_object_id_by_path(&blob_id, s->repo,
5181 pcommit, s->path);
5182 got_object_commit_close(pcommit);
5183 if (err) {
5184 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5185 err = NULL;
5186 got_object_commit_close(commit);
5187 break;
5189 err = got_object_get_type(&obj_type, s->repo,
5190 blob_id);
5191 free(blob_id);
5192 /* Can't blame non-blob type objects. */
5193 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5194 got_object_commit_close(commit);
5195 break;
5197 err = got_object_qid_alloc(&s->blamed_commit,
5198 &pid->id);
5199 got_object_commit_close(commit);
5200 } else {
5201 if (got_object_id_cmp(id,
5202 &s->blamed_commit->id) == 0)
5203 break;
5204 err = got_object_qid_alloc(&s->blamed_commit,
5205 id);
5207 if (err)
5208 break;
5209 s->done = 1;
5210 thread_err = stop_blame(&s->blame);
5211 s->done = 0;
5212 if (thread_err)
5213 break;
5214 STAILQ_INSERT_HEAD(&s->blamed_commits,
5215 s->blamed_commit, entry);
5216 err = run_blame(view);
5217 if (err)
5218 break;
5219 break;
5221 case 'C': {
5222 struct got_object_qid *first;
5224 view->count = 0;
5225 first = STAILQ_FIRST(&s->blamed_commits);
5226 if (!got_object_id_cmp(&first->id, s->commit_id))
5227 break;
5228 s->done = 1;
5229 thread_err = stop_blame(&s->blame);
5230 s->done = 0;
5231 if (thread_err)
5232 break;
5233 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5234 got_object_qid_free(s->blamed_commit);
5235 s->blamed_commit =
5236 STAILQ_FIRST(&s->blamed_commits);
5237 err = run_blame(view);
5238 if (err)
5239 break;
5240 break;
5242 case KEY_ENTER:
5243 case '\r': {
5244 struct got_object_id *id = NULL;
5245 struct got_object_qid *pid;
5246 struct got_commit_object *commit = NULL;
5248 view->count = 0;
5249 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5250 s->first_displayed_line, s->selected_line);
5251 if (id == NULL)
5252 break;
5253 err = got_object_open_as_commit(&commit, s->repo, id);
5254 if (err)
5255 break;
5256 pid = STAILQ_FIRST(
5257 got_object_commit_get_parent_ids(commit));
5258 if (view_is_parent_view(view))
5259 begin_x = view_split_begin_x(view->begin_x);
5260 diff_view = view_open(0, 0, 0, begin_x, TOG_VIEW_DIFF);
5261 if (diff_view == NULL) {
5262 got_object_commit_close(commit);
5263 err = got_error_from_errno("view_open");
5264 break;
5266 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5267 id, NULL, NULL, 3, 0, 0, NULL, s->repo);
5268 got_object_commit_close(commit);
5269 if (err) {
5270 view_close(diff_view);
5271 break;
5273 view->focussed = 0;
5274 diff_view->focussed = 1;
5275 if (view_is_parent_view(view)) {
5276 err = view_close_child(view);
5277 if (err)
5278 break;
5279 err = view_set_child(view, diff_view);
5280 if (err)
5281 break;
5282 view->focus_child = 1;
5283 } else
5284 *new_view = diff_view;
5285 if (err)
5286 break;
5287 break;
5289 case CTRL('d'):
5290 case 'd':
5291 nscroll /= 2;
5292 /* FALL THROUGH */
5293 case KEY_NPAGE:
5294 case CTRL('f'):
5295 case 'f':
5296 case ' ':
5297 if (s->last_displayed_line >= s->blame.nlines &&
5298 s->selected_line >= MIN(s->blame.nlines,
5299 view->nlines - 2)) {
5300 view->count = 0;
5301 break;
5303 if (s->last_displayed_line >= s->blame.nlines &&
5304 s->selected_line < view->nlines - 2) {
5305 s->selected_line +=
5306 MIN(nscroll, s->last_displayed_line -
5307 s->first_displayed_line - s->selected_line + 1);
5309 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5310 s->first_displayed_line += nscroll;
5311 else
5312 s->first_displayed_line =
5313 s->blame.nlines - (view->nlines - 3);
5314 break;
5315 case KEY_RESIZE:
5316 if (s->selected_line > view->nlines - 2) {
5317 s->selected_line = MIN(s->blame.nlines,
5318 view->nlines - 2);
5320 break;
5321 default:
5322 view->count = 0;
5323 break;
5325 return thread_err ? thread_err : err;
5328 static const struct got_error *
5329 cmd_blame(int argc, char *argv[])
5331 const struct got_error *error;
5332 struct got_repository *repo = NULL;
5333 struct got_worktree *worktree = NULL;
5334 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5335 char *link_target = NULL;
5336 struct got_object_id *commit_id = NULL;
5337 struct got_commit_object *commit = NULL;
5338 char *commit_id_str = NULL;
5339 int ch;
5340 struct tog_view *view;
5341 int *pack_fds = NULL;
5343 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5344 switch (ch) {
5345 case 'c':
5346 commit_id_str = optarg;
5347 break;
5348 case 'r':
5349 repo_path = realpath(optarg, NULL);
5350 if (repo_path == NULL)
5351 return got_error_from_errno2("realpath",
5352 optarg);
5353 break;
5354 default:
5355 usage_blame();
5356 /* NOTREACHED */
5360 argc -= optind;
5361 argv += optind;
5363 if (argc != 1)
5364 usage_blame();
5366 error = got_repo_pack_fds_open(&pack_fds);
5367 if (error != NULL)
5368 goto done;
5370 if (repo_path == NULL) {
5371 cwd = getcwd(NULL, 0);
5372 if (cwd == NULL)
5373 return got_error_from_errno("getcwd");
5374 error = got_worktree_open(&worktree, cwd);
5375 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5376 goto done;
5377 if (worktree)
5378 repo_path =
5379 strdup(got_worktree_get_repo_path(worktree));
5380 else
5381 repo_path = strdup(cwd);
5382 if (repo_path == NULL) {
5383 error = got_error_from_errno("strdup");
5384 goto done;
5388 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5389 if (error != NULL)
5390 goto done;
5392 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
5393 worktree);
5394 if (error)
5395 goto done;
5397 init_curses();
5399 error = apply_unveil(got_repo_get_path(repo), NULL);
5400 if (error)
5401 goto done;
5403 error = tog_load_refs(repo, 0);
5404 if (error)
5405 goto done;
5407 if (commit_id_str == NULL) {
5408 struct got_reference *head_ref;
5409 error = got_ref_open(&head_ref, repo, worktree ?
5410 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5411 if (error != NULL)
5412 goto done;
5413 error = got_ref_resolve(&commit_id, repo, head_ref);
5414 got_ref_close(head_ref);
5415 } else {
5416 error = got_repo_match_object_id(&commit_id, NULL,
5417 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
5419 if (error != NULL)
5420 goto done;
5422 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
5423 if (view == NULL) {
5424 error = got_error_from_errno("view_open");
5425 goto done;
5428 error = got_object_open_as_commit(&commit, repo, commit_id);
5429 if (error)
5430 goto done;
5432 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5433 commit, repo);
5434 if (error)
5435 goto done;
5437 error = open_blame_view(view, link_target ? link_target : in_repo_path,
5438 commit_id, repo);
5439 if (error)
5440 goto done;
5441 if (worktree) {
5442 /* Release work tree lock. */
5443 got_worktree_close(worktree);
5444 worktree = NULL;
5446 error = view_loop(view);
5447 done:
5448 free(repo_path);
5449 free(in_repo_path);
5450 free(link_target);
5451 free(cwd);
5452 free(commit_id);
5453 if (commit)
5454 got_object_commit_close(commit);
5455 if (worktree)
5456 got_worktree_close(worktree);
5457 if (repo) {
5458 const struct got_error *close_err = got_repo_close(repo);
5459 if (error == NULL)
5460 error = close_err;
5462 if (pack_fds) {
5463 const struct got_error *pack_err =
5464 got_repo_pack_fds_close(pack_fds);
5465 if (error == NULL)
5466 error = pack_err;
5468 tog_free_refs();
5469 return error;
5472 static const struct got_error *
5473 draw_tree_entries(struct tog_view *view, const char *parent_path)
5475 struct tog_tree_view_state *s = &view->state.tree;
5476 const struct got_error *err = NULL;
5477 struct got_tree_entry *te;
5478 wchar_t *wline;
5479 struct tog_color *tc;
5480 int width, n, i, nentries;
5481 int limit = view->nlines;
5483 s->ndisplayed = 0;
5485 werase(view->window);
5487 if (limit == 0)
5488 return NULL;
5490 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
5491 0, 0);
5492 if (err)
5493 return err;
5494 if (view_needs_focus_indication(view))
5495 wstandout(view->window);
5496 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5497 if (tc)
5498 wattr_on(view->window,
5499 COLOR_PAIR(tc->colorpair), NULL);
5500 waddwstr(view->window, wline);
5501 if (tc)
5502 wattr_off(view->window,
5503 COLOR_PAIR(tc->colorpair), NULL);
5504 if (view_needs_focus_indication(view))
5505 wstandend(view->window);
5506 free(wline);
5507 wline = NULL;
5508 if (width < view->ncols - 1)
5509 waddch(view->window, '\n');
5510 if (--limit <= 0)
5511 return NULL;
5512 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
5513 0, 0);
5514 if (err)
5515 return err;
5516 waddwstr(view->window, wline);
5517 free(wline);
5518 wline = NULL;
5519 if (width < view->ncols - 1)
5520 waddch(view->window, '\n');
5521 if (--limit <= 0)
5522 return NULL;
5523 waddch(view->window, '\n');
5524 if (--limit <= 0)
5525 return NULL;
5527 if (s->first_displayed_entry == NULL) {
5528 te = got_object_tree_get_first_entry(s->tree);
5529 if (s->selected == 0) {
5530 if (view->focussed)
5531 wstandout(view->window);
5532 s->selected_entry = NULL;
5534 waddstr(view->window, " ..\n"); /* parent directory */
5535 if (s->selected == 0 && view->focussed)
5536 wstandend(view->window);
5537 s->ndisplayed++;
5538 if (--limit <= 0)
5539 return NULL;
5540 n = 1;
5541 } else {
5542 n = 0;
5543 te = s->first_displayed_entry;
5546 nentries = got_object_tree_get_nentries(s->tree);
5547 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
5548 char *line = NULL, *id_str = NULL, *link_target = NULL;
5549 const char *modestr = "";
5550 mode_t mode;
5552 te = got_object_tree_get_entry(s->tree, i);
5553 mode = got_tree_entry_get_mode(te);
5555 if (s->show_ids) {
5556 err = got_object_id_str(&id_str,
5557 got_tree_entry_get_id(te));
5558 if (err)
5559 return got_error_from_errno(
5560 "got_object_id_str");
5562 if (got_object_tree_entry_is_submodule(te))
5563 modestr = "$";
5564 else if (S_ISLNK(mode)) {
5565 int i;
5567 err = got_tree_entry_get_symlink_target(&link_target,
5568 te, s->repo);
5569 if (err) {
5570 free(id_str);
5571 return err;
5573 for (i = 0; i < strlen(link_target); i++) {
5574 if (!isprint((unsigned char)link_target[i]))
5575 link_target[i] = '?';
5577 modestr = "@";
5579 else if (S_ISDIR(mode))
5580 modestr = "/";
5581 else if (mode & S_IXUSR)
5582 modestr = "*";
5583 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
5584 got_tree_entry_get_name(te), modestr,
5585 link_target ? " -> ": "",
5586 link_target ? link_target : "") == -1) {
5587 free(id_str);
5588 free(link_target);
5589 return got_error_from_errno("asprintf");
5591 free(id_str);
5592 free(link_target);
5593 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
5594 0, 0);
5595 if (err) {
5596 free(line);
5597 break;
5599 if (n == s->selected) {
5600 if (view->focussed)
5601 wstandout(view->window);
5602 s->selected_entry = te;
5604 tc = match_color(&s->colors, line);
5605 if (tc)
5606 wattr_on(view->window,
5607 COLOR_PAIR(tc->colorpair), NULL);
5608 waddwstr(view->window, wline);
5609 if (tc)
5610 wattr_off(view->window,
5611 COLOR_PAIR(tc->colorpair), NULL);
5612 if (width < view->ncols - 1)
5613 waddch(view->window, '\n');
5614 if (n == s->selected && view->focussed)
5615 wstandend(view->window);
5616 free(line);
5617 free(wline);
5618 wline = NULL;
5619 n++;
5620 s->ndisplayed++;
5621 s->last_displayed_entry = te;
5622 if (--limit <= 0)
5623 break;
5626 return err;
5629 static void
5630 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
5632 struct got_tree_entry *te;
5633 int isroot = s->tree == s->root;
5634 int i = 0;
5636 if (s->first_displayed_entry == NULL)
5637 return;
5639 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
5640 while (i++ < maxscroll) {
5641 if (te == NULL) {
5642 if (!isroot)
5643 s->first_displayed_entry = NULL;
5644 break;
5646 s->first_displayed_entry = te;
5647 te = got_tree_entry_get_prev(s->tree, te);
5651 static void
5652 tree_scroll_down(struct tog_tree_view_state *s, int maxscroll)
5654 struct got_tree_entry *next, *last;
5655 int n = 0;
5657 if (s->first_displayed_entry)
5658 next = got_tree_entry_get_next(s->tree,
5659 s->first_displayed_entry);
5660 else
5661 next = got_object_tree_get_first_entry(s->tree);
5663 last = s->last_displayed_entry;
5664 while (next && last && n++ < maxscroll) {
5665 last = got_tree_entry_get_next(s->tree, last);
5666 if (last) {
5667 s->first_displayed_entry = next;
5668 next = got_tree_entry_get_next(s->tree, next);
5673 static const struct got_error *
5674 tree_entry_path(char **path, struct tog_parent_trees *parents,
5675 struct got_tree_entry *te)
5677 const struct got_error *err = NULL;
5678 struct tog_parent_tree *pt;
5679 size_t len = 2; /* for leading slash and NUL */
5681 TAILQ_FOREACH(pt, parents, entry)
5682 len += strlen(got_tree_entry_get_name(pt->selected_entry))
5683 + 1 /* slash */;
5684 if (te)
5685 len += strlen(got_tree_entry_get_name(te));
5687 *path = calloc(1, len);
5688 if (path == NULL)
5689 return got_error_from_errno("calloc");
5691 (*path)[0] = '/';
5692 pt = TAILQ_LAST(parents, tog_parent_trees);
5693 while (pt) {
5694 const char *name = got_tree_entry_get_name(pt->selected_entry);
5695 if (strlcat(*path, name, len) >= len) {
5696 err = got_error(GOT_ERR_NO_SPACE);
5697 goto done;
5699 if (strlcat(*path, "/", len) >= len) {
5700 err = got_error(GOT_ERR_NO_SPACE);
5701 goto done;
5703 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
5705 if (te) {
5706 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
5707 err = got_error(GOT_ERR_NO_SPACE);
5708 goto done;
5711 done:
5712 if (err) {
5713 free(*path);
5714 *path = NULL;
5716 return err;
5719 static const struct got_error *
5720 blame_tree_entry(struct tog_view **new_view, int begin_x,
5721 struct got_tree_entry *te, struct tog_parent_trees *parents,
5722 struct got_object_id *commit_id, struct got_repository *repo)
5724 const struct got_error *err = NULL;
5725 char *path;
5726 struct tog_view *blame_view;
5728 *new_view = NULL;
5730 err = tree_entry_path(&path, parents, te);
5731 if (err)
5732 return err;
5734 blame_view = view_open(0, 0, 0, begin_x, TOG_VIEW_BLAME);
5735 if (blame_view == NULL) {
5736 err = got_error_from_errno("view_open");
5737 goto done;
5740 err = open_blame_view(blame_view, path, commit_id, repo);
5741 if (err) {
5742 if (err->code == GOT_ERR_CANCELLED)
5743 err = NULL;
5744 view_close(blame_view);
5745 } else
5746 *new_view = blame_view;
5747 done:
5748 free(path);
5749 return err;
5752 static const struct got_error *
5753 log_selected_tree_entry(struct tog_view **new_view, int begin_x,
5754 struct tog_tree_view_state *s)
5756 struct tog_view *log_view;
5757 const struct got_error *err = NULL;
5758 char *path;
5760 *new_view = NULL;
5762 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
5763 if (log_view == NULL)
5764 return got_error_from_errno("view_open");
5766 err = tree_entry_path(&path, &s->parents, s->selected_entry);
5767 if (err)
5768 return err;
5770 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
5771 path, 0);
5772 if (err)
5773 view_close(log_view);
5774 else
5775 *new_view = log_view;
5776 free(path);
5777 return err;
5780 static const struct got_error *
5781 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
5782 const char *head_ref_name, struct got_repository *repo)
5784 const struct got_error *err = NULL;
5785 char *commit_id_str = NULL;
5786 struct tog_tree_view_state *s = &view->state.tree;
5787 struct got_commit_object *commit = NULL;
5789 TAILQ_INIT(&s->parents);
5790 STAILQ_INIT(&s->colors);
5792 s->commit_id = got_object_id_dup(commit_id);
5793 if (s->commit_id == NULL)
5794 return got_error_from_errno("got_object_id_dup");
5796 err = got_object_open_as_commit(&commit, repo, commit_id);
5797 if (err)
5798 goto done;
5801 * The root is opened here and will be closed when the view is closed.
5802 * Any visited subtrees and their path-wise parents are opened and
5803 * closed on demand.
5805 err = got_object_open_as_tree(&s->root, repo,
5806 got_object_commit_get_tree_id(commit));
5807 if (err)
5808 goto done;
5809 s->tree = s->root;
5811 err = got_object_id_str(&commit_id_str, commit_id);
5812 if (err != NULL)
5813 goto done;
5815 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
5816 err = got_error_from_errno("asprintf");
5817 goto done;
5820 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
5821 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
5822 if (head_ref_name) {
5823 s->head_ref_name = strdup(head_ref_name);
5824 if (s->head_ref_name == NULL) {
5825 err = got_error_from_errno("strdup");
5826 goto done;
5829 s->repo = repo;
5831 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5832 err = add_color(&s->colors, "\\$$",
5833 TOG_COLOR_TREE_SUBMODULE,
5834 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
5835 if (err)
5836 goto done;
5837 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
5838 get_color_value("TOG_COLOR_TREE_SYMLINK"));
5839 if (err)
5840 goto done;
5841 err = add_color(&s->colors, "/$",
5842 TOG_COLOR_TREE_DIRECTORY,
5843 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
5844 if (err)
5845 goto done;
5847 err = add_color(&s->colors, "\\*$",
5848 TOG_COLOR_TREE_EXECUTABLE,
5849 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
5850 if (err)
5851 goto done;
5853 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
5854 get_color_value("TOG_COLOR_COMMIT"));
5855 if (err)
5856 goto done;
5859 view->show = show_tree_view;
5860 view->input = input_tree_view;
5861 view->close = close_tree_view;
5862 view->search_start = search_start_tree_view;
5863 view->search_next = search_next_tree_view;
5864 done:
5865 free(commit_id_str);
5866 if (commit)
5867 got_object_commit_close(commit);
5868 if (err)
5869 close_tree_view(view);
5870 return err;
5873 static const struct got_error *
5874 close_tree_view(struct tog_view *view)
5876 struct tog_tree_view_state *s = &view->state.tree;
5878 free_colors(&s->colors);
5879 free(s->tree_label);
5880 s->tree_label = NULL;
5881 free(s->commit_id);
5882 s->commit_id = NULL;
5883 free(s->head_ref_name);
5884 s->head_ref_name = NULL;
5885 while (!TAILQ_EMPTY(&s->parents)) {
5886 struct tog_parent_tree *parent;
5887 parent = TAILQ_FIRST(&s->parents);
5888 TAILQ_REMOVE(&s->parents, parent, entry);
5889 if (parent->tree != s->root)
5890 got_object_tree_close(parent->tree);
5891 free(parent);
5894 if (s->tree != NULL && s->tree != s->root)
5895 got_object_tree_close(s->tree);
5896 if (s->root)
5897 got_object_tree_close(s->root);
5898 return NULL;
5901 static const struct got_error *
5902 search_start_tree_view(struct tog_view *view)
5904 struct tog_tree_view_state *s = &view->state.tree;
5906 s->matched_entry = NULL;
5907 return NULL;
5910 static int
5911 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
5913 regmatch_t regmatch;
5915 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
5916 0) == 0;
5919 static const struct got_error *
5920 search_next_tree_view(struct tog_view *view)
5922 struct tog_tree_view_state *s = &view->state.tree;
5923 struct got_tree_entry *te = NULL;
5925 if (!view->searching) {
5926 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5927 return NULL;
5930 if (s->matched_entry) {
5931 if (view->searching == TOG_SEARCH_FORWARD) {
5932 if (s->selected_entry)
5933 te = got_tree_entry_get_next(s->tree,
5934 s->selected_entry);
5935 else
5936 te = got_object_tree_get_first_entry(s->tree);
5937 } else {
5938 if (s->selected_entry == NULL)
5939 te = got_object_tree_get_last_entry(s->tree);
5940 else
5941 te = got_tree_entry_get_prev(s->tree,
5942 s->selected_entry);
5944 } else {
5945 if (s->selected_entry)
5946 te = s->selected_entry;
5947 else if (view->searching == TOG_SEARCH_FORWARD)
5948 te = got_object_tree_get_first_entry(s->tree);
5949 else
5950 te = got_object_tree_get_last_entry(s->tree);
5953 while (1) {
5954 if (te == NULL) {
5955 if (s->matched_entry == NULL) {
5956 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5957 return NULL;
5959 if (view->searching == TOG_SEARCH_FORWARD)
5960 te = got_object_tree_get_first_entry(s->tree);
5961 else
5962 te = got_object_tree_get_last_entry(s->tree);
5965 if (match_tree_entry(te, &view->regex)) {
5966 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5967 s->matched_entry = te;
5968 break;
5971 if (view->searching == TOG_SEARCH_FORWARD)
5972 te = got_tree_entry_get_next(s->tree, te);
5973 else
5974 te = got_tree_entry_get_prev(s->tree, te);
5977 if (s->matched_entry) {
5978 s->first_displayed_entry = s->matched_entry;
5979 s->selected = 0;
5982 return NULL;
5985 static const struct got_error *
5986 show_tree_view(struct tog_view *view)
5988 const struct got_error *err = NULL;
5989 struct tog_tree_view_state *s = &view->state.tree;
5990 char *parent_path;
5992 err = tree_entry_path(&parent_path, &s->parents, NULL);
5993 if (err)
5994 return err;
5996 err = draw_tree_entries(view, parent_path);
5997 free(parent_path);
5999 view_vborder(view);
6000 return err;
6003 static const struct got_error *
6004 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6006 const struct got_error *err = NULL;
6007 struct tog_tree_view_state *s = &view->state.tree;
6008 struct tog_view *log_view, *ref_view;
6009 struct got_tree_entry *te;
6010 int begin_x = 0, n, nscroll = view->nlines - 3;
6012 switch (ch) {
6013 case 'i':
6014 s->show_ids = !s->show_ids;
6015 view->count = 0;
6016 break;
6017 case 'l':
6018 view->count = 0;
6019 if (!s->selected_entry)
6020 break;
6021 if (view_is_parent_view(view))
6022 begin_x = view_split_begin_x(view->begin_x);
6023 err = log_selected_tree_entry(&log_view, begin_x, s);
6024 view->focussed = 0;
6025 log_view->focussed = 1;
6026 if (view_is_parent_view(view)) {
6027 err = view_close_child(view);
6028 if (err)
6029 return err;
6030 err = view_set_child(view, log_view);
6031 if (err)
6032 return err;
6033 view->focus_child = 1;
6034 } else
6035 *new_view = log_view;
6036 break;
6037 case 'r':
6038 view->count = 0;
6039 if (view_is_parent_view(view))
6040 begin_x = view_split_begin_x(view->begin_x);
6041 ref_view = view_open(view->nlines, view->ncols,
6042 view->begin_y, begin_x, TOG_VIEW_REF);
6043 if (ref_view == NULL)
6044 return got_error_from_errno("view_open");
6045 err = open_ref_view(ref_view, s->repo);
6046 if (err) {
6047 view_close(ref_view);
6048 return err;
6050 view->focussed = 0;
6051 ref_view->focussed = 1;
6052 if (view_is_parent_view(view)) {
6053 err = view_close_child(view);
6054 if (err)
6055 return err;
6056 err = view_set_child(view, ref_view);
6057 if (err)
6058 return err;
6059 view->focus_child = 1;
6060 } else
6061 *new_view = ref_view;
6062 break;
6063 case 'g':
6064 case KEY_HOME:
6065 s->selected = 0;
6066 view->count = 0;
6067 if (s->tree == s->root)
6068 s->first_displayed_entry =
6069 got_object_tree_get_first_entry(s->tree);
6070 else
6071 s->first_displayed_entry = NULL;
6072 break;
6073 case 'G':
6074 case KEY_END:
6075 s->selected = 0;
6076 view->count = 0;
6077 te = got_object_tree_get_last_entry(s->tree);
6078 for (n = 0; n < view->nlines - 3; n++) {
6079 if (te == NULL) {
6080 if(s->tree != s->root) {
6081 s->first_displayed_entry = NULL;
6082 n++;
6084 break;
6086 s->first_displayed_entry = te;
6087 te = got_tree_entry_get_prev(s->tree, te);
6089 if (n > 0)
6090 s->selected = n - 1;
6091 break;
6092 case 'k':
6093 case KEY_UP:
6094 case CTRL('p'):
6095 if (s->selected > 0) {
6096 s->selected--;
6097 break;
6099 tree_scroll_up(s, 1);
6100 if (s->selected_entry == NULL ||
6101 (s->tree == s->root && s->selected_entry ==
6102 got_object_tree_get_first_entry(s->tree)))
6103 view->count = 0;
6104 break;
6105 case CTRL('u'):
6106 case 'u':
6107 nscroll /= 2;
6108 /* FALL THROUGH */
6109 case KEY_PPAGE:
6110 case CTRL('b'):
6111 case 'b':
6112 if (s->tree == s->root) {
6113 if (got_object_tree_get_first_entry(s->tree) ==
6114 s->first_displayed_entry)
6115 s->selected -= MIN(s->selected, nscroll);
6116 } else {
6117 if (s->first_displayed_entry == NULL)
6118 s->selected -= MIN(s->selected, nscroll);
6120 tree_scroll_up(s, MAX(0, nscroll));
6121 if (s->selected_entry == NULL ||
6122 (s->tree == s->root && s->selected_entry ==
6123 got_object_tree_get_first_entry(s->tree)))
6124 view->count = 0;
6125 break;
6126 case 'j':
6127 case KEY_DOWN:
6128 case CTRL('n'):
6129 if (s->selected < s->ndisplayed - 1) {
6130 s->selected++;
6131 break;
6133 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6134 == NULL) {
6135 /* can't scroll any further */
6136 view->count = 0;
6137 break;
6139 tree_scroll_down(s, 1);
6140 break;
6141 case CTRL('d'):
6142 case 'd':
6143 nscroll /= 2;
6144 /* FALL THROUGH */
6145 case KEY_NPAGE:
6146 case CTRL('f'):
6147 case 'f':
6148 case ' ':
6149 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6150 == NULL) {
6151 /* can't scroll any further; move cursor down */
6152 if (s->selected < s->ndisplayed - 1)
6153 s->selected += MIN(nscroll,
6154 s->ndisplayed - s->selected - 1);
6155 else
6156 view->count = 0;
6157 break;
6159 tree_scroll_down(s, nscroll);
6160 break;
6161 case KEY_ENTER:
6162 case '\r':
6163 case KEY_BACKSPACE:
6164 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6165 struct tog_parent_tree *parent;
6166 /* user selected '..' */
6167 if (s->tree == s->root) {
6168 view->count = 0;
6169 break;
6171 parent = TAILQ_FIRST(&s->parents);
6172 TAILQ_REMOVE(&s->parents, parent,
6173 entry);
6174 got_object_tree_close(s->tree);
6175 s->tree = parent->tree;
6176 s->first_displayed_entry =
6177 parent->first_displayed_entry;
6178 s->selected_entry =
6179 parent->selected_entry;
6180 s->selected = parent->selected;
6181 free(parent);
6182 } else if (S_ISDIR(got_tree_entry_get_mode(
6183 s->selected_entry))) {
6184 struct got_tree_object *subtree;
6185 view->count = 0;
6186 err = got_object_open_as_tree(&subtree, s->repo,
6187 got_tree_entry_get_id(s->selected_entry));
6188 if (err)
6189 break;
6190 err = tree_view_visit_subtree(s, subtree);
6191 if (err) {
6192 got_object_tree_close(subtree);
6193 break;
6195 } else if (S_ISREG(got_tree_entry_get_mode(
6196 s->selected_entry))) {
6197 struct tog_view *blame_view;
6198 int begin_x = view_is_parent_view(view) ?
6199 view_split_begin_x(view->begin_x) : 0;
6201 err = blame_tree_entry(&blame_view, begin_x,
6202 s->selected_entry, &s->parents,
6203 s->commit_id, s->repo);
6204 if (err)
6205 break;
6206 view->count = 0;
6207 view->focussed = 0;
6208 blame_view->focussed = 1;
6209 if (view_is_parent_view(view)) {
6210 err = view_close_child(view);
6211 if (err)
6212 return err;
6213 err = view_set_child(view, blame_view);
6214 if (err)
6215 return err;
6216 view->focus_child = 1;
6217 } else
6218 *new_view = blame_view;
6220 break;
6221 case KEY_RESIZE:
6222 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6223 s->selected = view->nlines - 4;
6224 view->count = 0;
6225 break;
6226 default:
6227 view->count = 0;
6228 break;
6231 return err;
6234 __dead static void
6235 usage_tree(void)
6237 endwin();
6238 fprintf(stderr,
6239 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6240 getprogname());
6241 exit(1);
6244 static const struct got_error *
6245 cmd_tree(int argc, char *argv[])
6247 const struct got_error *error;
6248 struct got_repository *repo = NULL;
6249 struct got_worktree *worktree = NULL;
6250 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6251 struct got_object_id *commit_id = NULL;
6252 struct got_commit_object *commit = NULL;
6253 const char *commit_id_arg = NULL;
6254 char *label = NULL;
6255 struct got_reference *ref = NULL;
6256 const char *head_ref_name = NULL;
6257 int ch;
6258 struct tog_view *view;
6259 int *pack_fds = NULL;
6261 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6262 switch (ch) {
6263 case 'c':
6264 commit_id_arg = optarg;
6265 break;
6266 case 'r':
6267 repo_path = realpath(optarg, NULL);
6268 if (repo_path == NULL)
6269 return got_error_from_errno2("realpath",
6270 optarg);
6271 break;
6272 default:
6273 usage_tree();
6274 /* NOTREACHED */
6278 argc -= optind;
6279 argv += optind;
6281 if (argc > 1)
6282 usage_tree();
6284 error = got_repo_pack_fds_open(&pack_fds);
6285 if (error != NULL)
6286 goto done;
6288 if (repo_path == NULL) {
6289 cwd = getcwd(NULL, 0);
6290 if (cwd == NULL)
6291 return got_error_from_errno("getcwd");
6292 error = got_worktree_open(&worktree, cwd);
6293 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6294 goto done;
6295 if (worktree)
6296 repo_path =
6297 strdup(got_worktree_get_repo_path(worktree));
6298 else
6299 repo_path = strdup(cwd);
6300 if (repo_path == NULL) {
6301 error = got_error_from_errno("strdup");
6302 goto done;
6306 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6307 if (error != NULL)
6308 goto done;
6310 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
6311 repo, worktree);
6312 if (error)
6313 goto done;
6315 init_curses();
6317 error = apply_unveil(got_repo_get_path(repo), NULL);
6318 if (error)
6319 goto done;
6321 error = tog_load_refs(repo, 0);
6322 if (error)
6323 goto done;
6325 if (commit_id_arg == NULL) {
6326 error = got_repo_match_object_id(&commit_id, &label,
6327 worktree ? got_worktree_get_head_ref_name(worktree) :
6328 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6329 if (error)
6330 goto done;
6331 head_ref_name = label;
6332 } else {
6333 error = got_ref_open(&ref, repo, commit_id_arg, 0);
6334 if (error == NULL)
6335 head_ref_name = got_ref_get_name(ref);
6336 else if (error->code != GOT_ERR_NOT_REF)
6337 goto done;
6338 error = got_repo_match_object_id(&commit_id, NULL,
6339 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6340 if (error)
6341 goto done;
6344 error = got_object_open_as_commit(&commit, repo, commit_id);
6345 if (error)
6346 goto done;
6348 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
6349 if (view == NULL) {
6350 error = got_error_from_errno("view_open");
6351 goto done;
6353 error = open_tree_view(view, commit_id, head_ref_name, repo);
6354 if (error)
6355 goto done;
6356 if (!got_path_is_root_dir(in_repo_path)) {
6357 error = tree_view_walk_path(&view->state.tree, commit,
6358 in_repo_path);
6359 if (error)
6360 goto done;
6363 if (worktree) {
6364 /* Release work tree lock. */
6365 got_worktree_close(worktree);
6366 worktree = NULL;
6368 error = view_loop(view);
6369 done:
6370 free(repo_path);
6371 free(cwd);
6372 free(commit_id);
6373 free(label);
6374 if (ref)
6375 got_ref_close(ref);
6376 if (repo) {
6377 const struct got_error *close_err = got_repo_close(repo);
6378 if (error == NULL)
6379 error = close_err;
6381 if (pack_fds) {
6382 const struct got_error *pack_err =
6383 got_repo_pack_fds_close(pack_fds);
6384 if (error == NULL)
6385 error = pack_err;
6387 tog_free_refs();
6388 return error;
6391 static const struct got_error *
6392 ref_view_load_refs(struct tog_ref_view_state *s)
6394 struct got_reflist_entry *sre;
6395 struct tog_reflist_entry *re;
6397 s->nrefs = 0;
6398 TAILQ_FOREACH(sre, &tog_refs, entry) {
6399 if (strncmp(got_ref_get_name(sre->ref),
6400 "refs/got/", 9) == 0 &&
6401 strncmp(got_ref_get_name(sre->ref),
6402 "refs/got/backup/", 16) != 0)
6403 continue;
6405 re = malloc(sizeof(*re));
6406 if (re == NULL)
6407 return got_error_from_errno("malloc");
6409 re->ref = got_ref_dup(sre->ref);
6410 if (re->ref == NULL)
6411 return got_error_from_errno("got_ref_dup");
6412 re->idx = s->nrefs++;
6413 TAILQ_INSERT_TAIL(&s->refs, re, entry);
6416 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6417 return NULL;
6420 static void
6421 ref_view_free_refs(struct tog_ref_view_state *s)
6423 struct tog_reflist_entry *re;
6425 while (!TAILQ_EMPTY(&s->refs)) {
6426 re = TAILQ_FIRST(&s->refs);
6427 TAILQ_REMOVE(&s->refs, re, entry);
6428 got_ref_close(re->ref);
6429 free(re);
6433 static const struct got_error *
6434 open_ref_view(struct tog_view *view, struct got_repository *repo)
6436 const struct got_error *err = NULL;
6437 struct tog_ref_view_state *s = &view->state.ref;
6439 s->selected_entry = 0;
6440 s->repo = repo;
6442 TAILQ_INIT(&s->refs);
6443 STAILQ_INIT(&s->colors);
6445 err = ref_view_load_refs(s);
6446 if (err)
6447 return err;
6449 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6450 err = add_color(&s->colors, "^refs/heads/",
6451 TOG_COLOR_REFS_HEADS,
6452 get_color_value("TOG_COLOR_REFS_HEADS"));
6453 if (err)
6454 goto done;
6456 err = add_color(&s->colors, "^refs/tags/",
6457 TOG_COLOR_REFS_TAGS,
6458 get_color_value("TOG_COLOR_REFS_TAGS"));
6459 if (err)
6460 goto done;
6462 err = add_color(&s->colors, "^refs/remotes/",
6463 TOG_COLOR_REFS_REMOTES,
6464 get_color_value("TOG_COLOR_REFS_REMOTES"));
6465 if (err)
6466 goto done;
6468 err = add_color(&s->colors, "^refs/got/backup/",
6469 TOG_COLOR_REFS_BACKUP,
6470 get_color_value("TOG_COLOR_REFS_BACKUP"));
6471 if (err)
6472 goto done;
6475 view->show = show_ref_view;
6476 view->input = input_ref_view;
6477 view->close = close_ref_view;
6478 view->search_start = search_start_ref_view;
6479 view->search_next = search_next_ref_view;
6480 done:
6481 if (err)
6482 free_colors(&s->colors);
6483 return err;
6486 static const struct got_error *
6487 close_ref_view(struct tog_view *view)
6489 struct tog_ref_view_state *s = &view->state.ref;
6491 ref_view_free_refs(s);
6492 free_colors(&s->colors);
6494 return NULL;
6497 static const struct got_error *
6498 resolve_reflist_entry(struct got_object_id **commit_id,
6499 struct tog_reflist_entry *re, struct got_repository *repo)
6501 const struct got_error *err = NULL;
6502 struct got_object_id *obj_id;
6503 struct got_tag_object *tag = NULL;
6504 int obj_type;
6506 *commit_id = NULL;
6508 err = got_ref_resolve(&obj_id, repo, re->ref);
6509 if (err)
6510 return err;
6512 err = got_object_get_type(&obj_type, repo, obj_id);
6513 if (err)
6514 goto done;
6516 switch (obj_type) {
6517 case GOT_OBJ_TYPE_COMMIT:
6518 *commit_id = obj_id;
6519 break;
6520 case GOT_OBJ_TYPE_TAG:
6521 err = got_object_open_as_tag(&tag, repo, obj_id);
6522 if (err)
6523 goto done;
6524 free(obj_id);
6525 err = got_object_get_type(&obj_type, repo,
6526 got_object_tag_get_object_id(tag));
6527 if (err)
6528 goto done;
6529 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
6530 err = got_error(GOT_ERR_OBJ_TYPE);
6531 goto done;
6533 *commit_id = got_object_id_dup(
6534 got_object_tag_get_object_id(tag));
6535 if (*commit_id == NULL) {
6536 err = got_error_from_errno("got_object_id_dup");
6537 goto done;
6539 break;
6540 default:
6541 err = got_error(GOT_ERR_OBJ_TYPE);
6542 break;
6545 done:
6546 if (tag)
6547 got_object_tag_close(tag);
6548 if (err) {
6549 free(*commit_id);
6550 *commit_id = NULL;
6552 return err;
6555 static const struct got_error *
6556 log_ref_entry(struct tog_view **new_view, int begin_x,
6557 struct tog_reflist_entry *re, struct got_repository *repo)
6559 struct tog_view *log_view;
6560 const struct got_error *err = NULL;
6561 struct got_object_id *commit_id = NULL;
6563 *new_view = NULL;
6565 err = resolve_reflist_entry(&commit_id, re, repo);
6566 if (err) {
6567 if (err->code != GOT_ERR_OBJ_TYPE)
6568 return err;
6569 else
6570 return NULL;
6573 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
6574 if (log_view == NULL) {
6575 err = got_error_from_errno("view_open");
6576 goto done;
6579 err = open_log_view(log_view, commit_id, repo,
6580 got_ref_get_name(re->ref), "", 0);
6581 done:
6582 if (err)
6583 view_close(log_view);
6584 else
6585 *new_view = log_view;
6586 free(commit_id);
6587 return err;
6590 static void
6591 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
6593 struct tog_reflist_entry *re;
6594 int i = 0;
6596 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
6597 return;
6599 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
6600 while (i++ < maxscroll) {
6601 if (re == NULL)
6602 break;
6603 s->first_displayed_entry = re;
6604 re = TAILQ_PREV(re, tog_reflist_head, entry);
6608 static void
6609 ref_scroll_down(struct tog_ref_view_state *s, int maxscroll)
6611 struct tog_reflist_entry *next, *last;
6612 int n = 0;
6614 if (s->first_displayed_entry)
6615 next = TAILQ_NEXT(s->first_displayed_entry, entry);
6616 else
6617 next = TAILQ_FIRST(&s->refs);
6619 last = s->last_displayed_entry;
6620 while (next && last && n++ < maxscroll) {
6621 last = TAILQ_NEXT(last, entry);
6622 if (last) {
6623 s->first_displayed_entry = next;
6624 next = TAILQ_NEXT(next, entry);
6629 static const struct got_error *
6630 search_start_ref_view(struct tog_view *view)
6632 struct tog_ref_view_state *s = &view->state.ref;
6634 s->matched_entry = NULL;
6635 return NULL;
6638 static int
6639 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
6641 regmatch_t regmatch;
6643 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
6644 0) == 0;
6647 static const struct got_error *
6648 search_next_ref_view(struct tog_view *view)
6650 struct tog_ref_view_state *s = &view->state.ref;
6651 struct tog_reflist_entry *re = NULL;
6653 if (!view->searching) {
6654 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6655 return NULL;
6658 if (s->matched_entry) {
6659 if (view->searching == TOG_SEARCH_FORWARD) {
6660 if (s->selected_entry)
6661 re = TAILQ_NEXT(s->selected_entry, entry);
6662 else
6663 re = TAILQ_PREV(s->selected_entry,
6664 tog_reflist_head, entry);
6665 } else {
6666 if (s->selected_entry == NULL)
6667 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6668 else
6669 re = TAILQ_PREV(s->selected_entry,
6670 tog_reflist_head, entry);
6672 } else {
6673 if (s->selected_entry)
6674 re = s->selected_entry;
6675 else if (view->searching == TOG_SEARCH_FORWARD)
6676 re = TAILQ_FIRST(&s->refs);
6677 else
6678 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6681 while (1) {
6682 if (re == NULL) {
6683 if (s->matched_entry == NULL) {
6684 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6685 return NULL;
6687 if (view->searching == TOG_SEARCH_FORWARD)
6688 re = TAILQ_FIRST(&s->refs);
6689 else
6690 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6693 if (match_reflist_entry(re, &view->regex)) {
6694 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6695 s->matched_entry = re;
6696 break;
6699 if (view->searching == TOG_SEARCH_FORWARD)
6700 re = TAILQ_NEXT(re, entry);
6701 else
6702 re = TAILQ_PREV(re, tog_reflist_head, entry);
6705 if (s->matched_entry) {
6706 s->first_displayed_entry = s->matched_entry;
6707 s->selected = 0;
6710 return NULL;
6713 static const struct got_error *
6714 show_ref_view(struct tog_view *view)
6716 const struct got_error *err = NULL;
6717 struct tog_ref_view_state *s = &view->state.ref;
6718 struct tog_reflist_entry *re;
6719 char *line = NULL;
6720 wchar_t *wline;
6721 struct tog_color *tc;
6722 int width, n;
6723 int limit = view->nlines;
6725 werase(view->window);
6727 s->ndisplayed = 0;
6729 if (limit == 0)
6730 return NULL;
6732 re = s->first_displayed_entry;
6734 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
6735 s->nrefs) == -1)
6736 return got_error_from_errno("asprintf");
6738 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6739 if (err) {
6740 free(line);
6741 return err;
6743 if (view_needs_focus_indication(view))
6744 wstandout(view->window);
6745 waddwstr(view->window, wline);
6746 if (view_needs_focus_indication(view))
6747 wstandend(view->window);
6748 free(wline);
6749 wline = NULL;
6750 free(line);
6751 line = NULL;
6752 if (width < view->ncols - 1)
6753 waddch(view->window, '\n');
6754 if (--limit <= 0)
6755 return NULL;
6757 n = 0;
6758 while (re && limit > 0) {
6759 char *line = NULL;
6760 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
6762 if (s->show_date) {
6763 struct got_commit_object *ci;
6764 struct got_tag_object *tag;
6765 struct got_object_id *id;
6766 struct tm tm;
6767 time_t t;
6769 err = got_ref_resolve(&id, s->repo, re->ref);
6770 if (err)
6771 return err;
6772 err = got_object_open_as_tag(&tag, s->repo, id);
6773 if (err) {
6774 if (err->code != GOT_ERR_OBJ_TYPE) {
6775 free(id);
6776 return err;
6778 err = got_object_open_as_commit(&ci, s->repo,
6779 id);
6780 if (err) {
6781 free(id);
6782 return err;
6784 t = got_object_commit_get_committer_time(ci);
6785 got_object_commit_close(ci);
6786 } else {
6787 t = got_object_tag_get_tagger_time(tag);
6788 got_object_tag_close(tag);
6790 free(id);
6791 if (gmtime_r(&t, &tm) == NULL)
6792 return got_error_from_errno("gmtime_r");
6793 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
6794 return got_error(GOT_ERR_NO_SPACE);
6796 if (got_ref_is_symbolic(re->ref)) {
6797 if (asprintf(&line, "%s%s -> %s", s->show_date ?
6798 ymd : "", got_ref_get_name(re->ref),
6799 got_ref_get_symref_target(re->ref)) == -1)
6800 return got_error_from_errno("asprintf");
6801 } else if (s->show_ids) {
6802 struct got_object_id *id;
6803 char *id_str;
6804 err = got_ref_resolve(&id, s->repo, re->ref);
6805 if (err)
6806 return err;
6807 err = got_object_id_str(&id_str, id);
6808 if (err) {
6809 free(id);
6810 return err;
6812 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
6813 got_ref_get_name(re->ref), id_str) == -1) {
6814 err = got_error_from_errno("asprintf");
6815 free(id);
6816 free(id_str);
6817 return err;
6819 free(id);
6820 free(id_str);
6821 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
6822 got_ref_get_name(re->ref)) == -1)
6823 return got_error_from_errno("asprintf");
6825 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6826 0, 0);
6827 if (err) {
6828 free(line);
6829 return err;
6831 if (n == s->selected) {
6832 if (view->focussed)
6833 wstandout(view->window);
6834 s->selected_entry = re;
6836 tc = match_color(&s->colors, got_ref_get_name(re->ref));
6837 if (tc)
6838 wattr_on(view->window,
6839 COLOR_PAIR(tc->colorpair), NULL);
6840 waddwstr(view->window, wline);
6841 if (tc)
6842 wattr_off(view->window,
6843 COLOR_PAIR(tc->colorpair), NULL);
6844 if (width < view->ncols - 1)
6845 waddch(view->window, '\n');
6846 if (n == s->selected && view->focussed)
6847 wstandend(view->window);
6848 free(line);
6849 free(wline);
6850 wline = NULL;
6851 n++;
6852 s->ndisplayed++;
6853 s->last_displayed_entry = re;
6855 limit--;
6856 re = TAILQ_NEXT(re, entry);
6859 view_vborder(view);
6860 return err;
6863 static const struct got_error *
6864 browse_ref_tree(struct tog_view **new_view, int begin_x,
6865 struct tog_reflist_entry *re, struct got_repository *repo)
6867 const struct got_error *err = NULL;
6868 struct got_object_id *commit_id = NULL;
6869 struct tog_view *tree_view;
6871 *new_view = NULL;
6873 err = resolve_reflist_entry(&commit_id, re, repo);
6874 if (err) {
6875 if (err->code != GOT_ERR_OBJ_TYPE)
6876 return err;
6877 else
6878 return NULL;
6882 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
6883 if (tree_view == NULL) {
6884 err = got_error_from_errno("view_open");
6885 goto done;
6888 err = open_tree_view(tree_view, commit_id,
6889 got_ref_get_name(re->ref), repo);
6890 if (err)
6891 goto done;
6893 *new_view = tree_view;
6894 done:
6895 free(commit_id);
6896 return err;
6898 static const struct got_error *
6899 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
6901 const struct got_error *err = NULL;
6902 struct tog_ref_view_state *s = &view->state.ref;
6903 struct tog_view *log_view, *tree_view;
6904 struct tog_reflist_entry *re;
6905 int begin_x = 0, n, nscroll = view->nlines - 1;
6907 switch (ch) {
6908 case 'i':
6909 s->show_ids = !s->show_ids;
6910 view->count = 0;
6911 break;
6912 case 'm':
6913 s->show_date = !s->show_date;
6914 view->count = 0;
6915 break;
6916 case 'o':
6917 s->sort_by_date = !s->sort_by_date;
6918 view->count = 0;
6919 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
6920 got_ref_cmp_by_commit_timestamp_descending :
6921 tog_ref_cmp_by_name, s->repo);
6922 if (err)
6923 break;
6924 got_reflist_object_id_map_free(tog_refs_idmap);
6925 err = got_reflist_object_id_map_create(&tog_refs_idmap,
6926 &tog_refs, s->repo);
6927 if (err)
6928 break;
6929 ref_view_free_refs(s);
6930 err = ref_view_load_refs(s);
6931 break;
6932 case KEY_ENTER:
6933 case '\r':
6934 view->count = 0;
6935 if (!s->selected_entry)
6936 break;
6937 if (view_is_parent_view(view))
6938 begin_x = view_split_begin_x(view->begin_x);
6939 err = log_ref_entry(&log_view, begin_x, s->selected_entry,
6940 s->repo);
6941 view->focussed = 0;
6942 log_view->focussed = 1;
6943 if (view_is_parent_view(view)) {
6944 err = view_close_child(view);
6945 if (err)
6946 return err;
6947 err = view_set_child(view, log_view);
6948 if (err)
6949 return err;
6950 view->focus_child = 1;
6951 } else
6952 *new_view = log_view;
6953 break;
6954 case 't':
6955 view->count = 0;
6956 if (!s->selected_entry)
6957 break;
6958 if (view_is_parent_view(view))
6959 begin_x = view_split_begin_x(view->begin_x);
6960 err = browse_ref_tree(&tree_view, begin_x, s->selected_entry,
6961 s->repo);
6962 if (err || tree_view == NULL)
6963 break;
6964 view->focussed = 0;
6965 tree_view->focussed = 1;
6966 if (view_is_parent_view(view)) {
6967 err = view_close_child(view);
6968 if (err)
6969 return err;
6970 err = view_set_child(view, tree_view);
6971 if (err)
6972 return err;
6973 view->focus_child = 1;
6974 } else
6975 *new_view = tree_view;
6976 break;
6977 case 'g':
6978 case KEY_HOME:
6979 s->selected = 0;
6980 view->count = 0;
6981 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6982 break;
6983 case 'G':
6984 case KEY_END:
6985 s->selected = 0;
6986 view->count = 0;
6987 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6988 for (n = 0; n < view->nlines - 1; n++) {
6989 if (re == NULL)
6990 break;
6991 s->first_displayed_entry = re;
6992 re = TAILQ_PREV(re, tog_reflist_head, entry);
6994 if (n > 0)
6995 s->selected = n - 1;
6996 break;
6997 case 'k':
6998 case KEY_UP:
6999 case CTRL('p'):
7000 if (s->selected > 0) {
7001 s->selected--;
7002 break;
7004 ref_scroll_up(s, 1);
7005 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7006 view->count = 0;
7007 break;
7008 case CTRL('u'):
7009 case 'u':
7010 nscroll /= 2;
7011 /* FALL THROUGH */
7012 case KEY_PPAGE:
7013 case CTRL('b'):
7014 case 'b':
7015 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7016 s->selected -= MIN(nscroll, s->selected);
7017 ref_scroll_up(s, MAX(0, nscroll));
7018 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7019 view->count = 0;
7020 break;
7021 case 'j':
7022 case KEY_DOWN:
7023 case CTRL('n'):
7024 if (s->selected < s->ndisplayed - 1) {
7025 s->selected++;
7026 break;
7028 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7029 /* can't scroll any further */
7030 view->count = 0;
7031 break;
7033 ref_scroll_down(s, 1);
7034 break;
7035 case CTRL('d'):
7036 case 'd':
7037 nscroll /= 2;
7038 /* FALL THROUGH */
7039 case KEY_NPAGE:
7040 case CTRL('f'):
7041 case 'f':
7042 case ' ':
7043 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7044 /* can't scroll any further; move cursor down */
7045 if (s->selected < s->ndisplayed - 1)
7046 s->selected += MIN(nscroll,
7047 s->ndisplayed - s->selected - 1);
7048 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7049 s->selected += s->ndisplayed - s->selected - 1;
7050 view->count = 0;
7051 break;
7053 ref_scroll_down(s, nscroll);
7054 break;
7055 case CTRL('l'):
7056 view->count = 0;
7057 tog_free_refs();
7058 err = tog_load_refs(s->repo, s->sort_by_date);
7059 if (err)
7060 break;
7061 ref_view_free_refs(s);
7062 err = ref_view_load_refs(s);
7063 break;
7064 case KEY_RESIZE:
7065 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7066 s->selected = view->nlines - 2;
7067 break;
7068 default:
7069 view->count = 0;
7070 break;
7073 return err;
7076 __dead static void
7077 usage_ref(void)
7079 endwin();
7080 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7081 getprogname());
7082 exit(1);
7085 static const struct got_error *
7086 cmd_ref(int argc, char *argv[])
7088 const struct got_error *error;
7089 struct got_repository *repo = NULL;
7090 struct got_worktree *worktree = NULL;
7091 char *cwd = NULL, *repo_path = NULL;
7092 int ch;
7093 struct tog_view *view;
7094 int *pack_fds = NULL;
7096 while ((ch = getopt(argc, argv, "r:")) != -1) {
7097 switch (ch) {
7098 case 'r':
7099 repo_path = realpath(optarg, NULL);
7100 if (repo_path == NULL)
7101 return got_error_from_errno2("realpath",
7102 optarg);
7103 break;
7104 default:
7105 usage_ref();
7106 /* NOTREACHED */
7110 argc -= optind;
7111 argv += optind;
7113 if (argc > 1)
7114 usage_ref();
7116 error = got_repo_pack_fds_open(&pack_fds);
7117 if (error != NULL)
7118 goto done;
7120 if (repo_path == NULL) {
7121 cwd = getcwd(NULL, 0);
7122 if (cwd == NULL)
7123 return got_error_from_errno("getcwd");
7124 error = got_worktree_open(&worktree, cwd);
7125 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7126 goto done;
7127 if (worktree)
7128 repo_path =
7129 strdup(got_worktree_get_repo_path(worktree));
7130 else
7131 repo_path = strdup(cwd);
7132 if (repo_path == NULL) {
7133 error = got_error_from_errno("strdup");
7134 goto done;
7138 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7139 if (error != NULL)
7140 goto done;
7142 init_curses();
7144 error = apply_unveil(got_repo_get_path(repo), NULL);
7145 if (error)
7146 goto done;
7148 error = tog_load_refs(repo, 0);
7149 if (error)
7150 goto done;
7152 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7153 if (view == NULL) {
7154 error = got_error_from_errno("view_open");
7155 goto done;
7158 error = open_ref_view(view, repo);
7159 if (error)
7160 goto done;
7162 if (worktree) {
7163 /* Release work tree lock. */
7164 got_worktree_close(worktree);
7165 worktree = NULL;
7167 error = view_loop(view);
7168 done:
7169 free(repo_path);
7170 free(cwd);
7171 if (repo) {
7172 const struct got_error *close_err = got_repo_close(repo);
7173 if (close_err)
7174 error = close_err;
7176 if (pack_fds) {
7177 const struct got_error *pack_err =
7178 got_repo_pack_fds_close(pack_fds);
7179 if (error == NULL)
7180 error = pack_err;
7182 tog_free_refs();
7183 return error;
7186 static void
7187 list_commands(FILE *fp)
7189 size_t i;
7191 fprintf(fp, "commands:");
7192 for (i = 0; i < nitems(tog_commands); i++) {
7193 const struct tog_cmd *cmd = &tog_commands[i];
7194 fprintf(fp, " %s", cmd->name);
7196 fputc('\n', fp);
7199 __dead static void
7200 usage(int hflag, int status)
7202 FILE *fp = (status == 0) ? stdout : stderr;
7204 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
7205 getprogname());
7206 if (hflag) {
7207 fprintf(fp, "lazy usage: %s path\n", getprogname());
7208 list_commands(fp);
7210 exit(status);
7213 static char **
7214 make_argv(int argc, ...)
7216 va_list ap;
7217 char **argv;
7218 int i;
7220 va_start(ap, argc);
7222 argv = calloc(argc, sizeof(char *));
7223 if (argv == NULL)
7224 err(1, "calloc");
7225 for (i = 0; i < argc; i++) {
7226 argv[i] = strdup(va_arg(ap, char *));
7227 if (argv[i] == NULL)
7228 err(1, "strdup");
7231 va_end(ap);
7232 return argv;
7236 * Try to convert 'tog path' into a 'tog log path' command.
7237 * The user could simply have mistyped the command rather than knowingly
7238 * provided a path. So check whether argv[0] can in fact be resolved
7239 * to a path in the HEAD commit and print a special error if not.
7240 * This hack is for mpi@ <3
7242 static const struct got_error *
7243 tog_log_with_path(int argc, char *argv[])
7245 const struct got_error *error = NULL, *close_err;
7246 const struct tog_cmd *cmd = NULL;
7247 struct got_repository *repo = NULL;
7248 struct got_worktree *worktree = NULL;
7249 struct got_object_id *commit_id = NULL, *id = NULL;
7250 struct got_commit_object *commit = NULL;
7251 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7252 char *commit_id_str = NULL, **cmd_argv = NULL;
7253 int *pack_fds = NULL;
7255 cwd = getcwd(NULL, 0);
7256 if (cwd == NULL)
7257 return got_error_from_errno("getcwd");
7259 error = got_repo_pack_fds_open(&pack_fds);
7260 if (error != NULL)
7261 goto done;
7263 error = got_worktree_open(&worktree, cwd);
7264 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7265 goto done;
7267 if (worktree)
7268 repo_path = strdup(got_worktree_get_repo_path(worktree));
7269 else
7270 repo_path = strdup(cwd);
7271 if (repo_path == NULL) {
7272 error = got_error_from_errno("strdup");
7273 goto done;
7276 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7277 if (error != NULL)
7278 goto done;
7280 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7281 repo, worktree);
7282 if (error)
7283 goto done;
7285 error = tog_load_refs(repo, 0);
7286 if (error)
7287 goto done;
7288 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
7289 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
7290 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7291 if (error)
7292 goto done;
7294 if (worktree) {
7295 got_worktree_close(worktree);
7296 worktree = NULL;
7299 error = got_object_open_as_commit(&commit, repo, commit_id);
7300 if (error)
7301 goto done;
7303 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
7304 if (error) {
7305 if (error->code != GOT_ERR_NO_TREE_ENTRY)
7306 goto done;
7307 fprintf(stderr, "%s: '%s' is no known command or path\n",
7308 getprogname(), argv[0]);
7309 usage(1, 1);
7310 /* not reached */
7313 close_err = got_repo_close(repo);
7314 if (error == NULL)
7315 error = close_err;
7316 repo = NULL;
7318 error = got_object_id_str(&commit_id_str, commit_id);
7319 if (error)
7320 goto done;
7322 cmd = &tog_commands[0]; /* log */
7323 argc = 4;
7324 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
7325 error = cmd->cmd_main(argc, cmd_argv);
7326 done:
7327 if (repo) {
7328 close_err = got_repo_close(repo);
7329 if (error == NULL)
7330 error = close_err;
7332 if (commit)
7333 got_object_commit_close(commit);
7334 if (worktree)
7335 got_worktree_close(worktree);
7336 if (pack_fds) {
7337 const struct got_error *pack_err =
7338 got_repo_pack_fds_close(pack_fds);
7339 if (error == NULL)
7340 error = pack_err;
7342 free(id);
7343 free(commit_id_str);
7344 free(commit_id);
7345 free(cwd);
7346 free(repo_path);
7347 free(in_repo_path);
7348 if (cmd_argv) {
7349 int i;
7350 for (i = 0; i < argc; i++)
7351 free(cmd_argv[i]);
7352 free(cmd_argv);
7354 tog_free_refs();
7355 return error;
7358 int
7359 main(int argc, char *argv[])
7361 const struct got_error *error = NULL;
7362 const struct tog_cmd *cmd = NULL;
7363 int ch, hflag = 0, Vflag = 0;
7364 char **cmd_argv = NULL;
7365 static const struct option longopts[] = {
7366 { "version", no_argument, NULL, 'V' },
7367 { NULL, 0, NULL, 0}
7370 setlocale(LC_CTYPE, "");
7372 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
7373 switch (ch) {
7374 case 'h':
7375 hflag = 1;
7376 break;
7377 case 'V':
7378 Vflag = 1;
7379 break;
7380 default:
7381 usage(hflag, 1);
7382 /* NOTREACHED */
7386 argc -= optind;
7387 argv += optind;
7388 optind = 1;
7389 optreset = 1;
7391 if (Vflag) {
7392 got_version_print_str();
7393 return 0;
7396 #ifndef PROFILE
7397 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
7398 NULL) == -1)
7399 err(1, "pledge");
7400 #endif
7402 if (argc == 0) {
7403 if (hflag)
7404 usage(hflag, 0);
7405 /* Build an argument vector which runs a default command. */
7406 cmd = &tog_commands[0];
7407 argc = 1;
7408 cmd_argv = make_argv(argc, cmd->name);
7409 } else {
7410 size_t i;
7412 /* Did the user specify a command? */
7413 for (i = 0; i < nitems(tog_commands); i++) {
7414 if (strncmp(tog_commands[i].name, argv[0],
7415 strlen(argv[0])) == 0) {
7416 cmd = &tog_commands[i];
7417 break;
7422 if (cmd == NULL) {
7423 if (argc != 1)
7424 usage(0, 1);
7425 /* No command specified; try log with a path */
7426 error = tog_log_with_path(argc, argv);
7427 } else {
7428 if (hflag)
7429 cmd->cmd_usage();
7430 else
7431 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
7434 endwin();
7435 putchar('\n');
7436 if (cmd_argv) {
7437 int i;
7438 for (i = 0; i < argc; i++)
7439 free(cmd_argv[i]);
7440 free(cmd_argv);
7443 if (error && error->code != GOT_ERR_CANCELLED)
7444 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7445 return 0;