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 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 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 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 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]|(blob|file) [-+] |"
3986 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
3987 get_color_value("TOG_COLOR_DIFF_META"));
3988 if (err)
3989 goto done;
3991 err = add_color(&s->colors,
3992 "^(from|via): ", TOG_COLOR_AUTHOR,
3993 get_color_value("TOG_COLOR_AUTHOR"));
3994 if (err)
3995 goto done;
3997 err = add_color(&s->colors,
3998 "^date: ", TOG_COLOR_DATE,
3999 get_color_value("TOG_COLOR_DATE"));
4000 if (err)
4001 goto done;
4004 if (log_view && view_is_splitscreen(view))
4005 show_log_view(log_view); /* draw vborder */
4006 diff_view_indicate_progress(view);
4008 err = create_diff(s);
4010 view->show = show_diff_view;
4011 view->input = input_diff_view;
4012 view->close = close_diff_view;
4013 view->search_start = search_start_diff_view;
4014 view->search_next = search_next_diff_view;
4015 done:
4016 if (err)
4017 close_diff_view(view);
4018 return err;
4021 static const struct got_error *
4022 show_diff_view(struct tog_view *view)
4024 const struct got_error *err;
4025 struct tog_diff_view_state *s = &view->state.diff;
4026 char *id_str1 = NULL, *id_str2, *header;
4027 const char *label1, *label2;
4029 if (s->id1) {
4030 err = got_object_id_str(&id_str1, s->id1);
4031 if (err)
4032 return err;
4033 label1 = s->label1 ? : id_str1;
4034 } else
4035 label1 = "/dev/null";
4037 err = got_object_id_str(&id_str2, s->id2);
4038 if (err)
4039 return err;
4040 label2 = s->label2 ? : id_str2;
4042 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4043 err = got_error_from_errno("asprintf");
4044 free(id_str1);
4045 free(id_str2);
4046 return err;
4048 free(id_str1);
4049 free(id_str2);
4051 err = draw_file(view, header);
4052 free(header);
4053 return err;
4056 static const struct got_error *
4057 set_selected_commit(struct tog_diff_view_state *s,
4058 struct commit_queue_entry *entry)
4060 const struct got_error *err;
4061 const struct got_object_id_queue *parent_ids;
4062 struct got_commit_object *selected_commit;
4063 struct got_object_qid *pid;
4065 free(s->id2);
4066 s->id2 = got_object_id_dup(entry->id);
4067 if (s->id2 == NULL)
4068 return got_error_from_errno("got_object_id_dup");
4070 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4071 if (err)
4072 return err;
4073 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4074 free(s->id1);
4075 pid = STAILQ_FIRST(parent_ids);
4076 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4077 got_object_commit_close(selected_commit);
4078 return NULL;
4081 static const struct got_error *
4082 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4084 const struct got_error *err = NULL;
4085 struct tog_diff_view_state *s = &view->state.diff;
4086 struct tog_log_view_state *ls;
4087 struct commit_queue_entry *old_selected_entry;
4088 char *line = NULL;
4089 size_t linesize = 0;
4090 ssize_t linelen;
4091 int i, nscroll = view->nlines - 1;
4093 switch (ch) {
4094 case '0':
4095 view->x = 0;
4096 break;
4097 case '$':
4098 view->x = MAX(view->maxx - view->ncols / 3, 0);
4099 view->count = 0;
4100 break;
4101 case KEY_RIGHT:
4102 case 'l':
4103 if (view->x + view->ncols / 3 < view->maxx)
4104 view->x += 2; /* move two columns right */
4105 else
4106 view->count = 0;
4107 break;
4108 case KEY_LEFT:
4109 case 'h':
4110 view->x -= MIN(view->x, 2); /* move two columns back */
4111 if (view->x <= 0)
4112 view->count = 0;
4113 break;
4114 case 'a':
4115 case 'w':
4116 if (ch == 'a')
4117 s->force_text_diff = !s->force_text_diff;
4118 if (ch == 'w')
4119 s->ignore_whitespace = !s->ignore_whitespace;
4120 wclear(view->window);
4121 s->first_displayed_line = 1;
4122 s->last_displayed_line = view->nlines;
4123 s->matched_line = 0;
4124 diff_view_indicate_progress(view);
4125 err = create_diff(s);
4126 view->count = 0;
4127 break;
4128 case 'g':
4129 case KEY_HOME:
4130 s->first_displayed_line = 1;
4131 view->count = 0;
4132 break;
4133 case 'G':
4134 case KEY_END:
4135 view->count = 0;
4136 if (s->eof)
4137 break;
4139 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4140 s->eof = 1;
4141 break;
4142 case 'k':
4143 case KEY_UP:
4144 case CTRL('p'):
4145 if (s->first_displayed_line > 1)
4146 s->first_displayed_line--;
4147 else
4148 view->count = 0;
4149 break;
4150 case CTRL('u'):
4151 case 'u':
4152 nscroll /= 2;
4153 /* FALL THROUGH */
4154 case KEY_PPAGE:
4155 case CTRL('b'):
4156 case 'b':
4157 if (s->first_displayed_line == 1) {
4158 view->count = 0;
4159 break;
4161 i = 0;
4162 while (i++ < nscroll && s->first_displayed_line > 1)
4163 s->first_displayed_line--;
4164 break;
4165 case 'j':
4166 case KEY_DOWN:
4167 case CTRL('n'):
4168 if (!s->eof)
4169 s->first_displayed_line++;
4170 else
4171 view->count = 0;
4172 break;
4173 case CTRL('d'):
4174 case 'd':
4175 nscroll /= 2;
4176 /* FALL THROUGH */
4177 case KEY_NPAGE:
4178 case CTRL('f'):
4179 case 'f':
4180 case ' ':
4181 if (s->eof) {
4182 view->count = 0;
4183 break;
4185 i = 0;
4186 while (!s->eof && i++ < nscroll) {
4187 linelen = getline(&line, &linesize, s->f);
4188 s->first_displayed_line++;
4189 if (linelen == -1) {
4190 if (feof(s->f)) {
4191 s->eof = 1;
4192 } else
4193 err = got_ferror(s->f, GOT_ERR_IO);
4194 break;
4197 free(line);
4198 break;
4199 case '[':
4200 if (s->diff_context > 0) {
4201 s->diff_context--;
4202 s->matched_line = 0;
4203 diff_view_indicate_progress(view);
4204 err = create_diff(s);
4205 if (s->first_displayed_line + view->nlines - 1 >
4206 s->nlines) {
4207 s->first_displayed_line = 1;
4208 s->last_displayed_line = view->nlines;
4210 } else
4211 view->count = 0;
4212 break;
4213 case ']':
4214 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4215 s->diff_context++;
4216 s->matched_line = 0;
4217 diff_view_indicate_progress(view);
4218 err = create_diff(s);
4219 } else
4220 view->count = 0;
4221 break;
4222 case '<':
4223 case ',':
4224 if (s->log_view == NULL) {
4225 view->count = 0;
4226 break;
4228 ls = &s->log_view->state.log;
4229 old_selected_entry = ls->selected_entry;
4231 /* view->count handled in input_log_view() */
4232 err = input_log_view(NULL, s->log_view, KEY_UP);
4233 if (err)
4234 break;
4236 if (old_selected_entry == ls->selected_entry)
4237 break;
4239 err = set_selected_commit(s, ls->selected_entry);
4240 if (err)
4241 break;
4243 s->first_displayed_line = 1;
4244 s->last_displayed_line = view->nlines;
4245 s->matched_line = 0;
4246 view->x = 0;
4248 diff_view_indicate_progress(view);
4249 err = create_diff(s);
4250 break;
4251 case '>':
4252 case '.':
4253 if (s->log_view == NULL) {
4254 view->count = 0;
4255 break;
4257 ls = &s->log_view->state.log;
4258 old_selected_entry = ls->selected_entry;
4260 /* view->count handled in input_log_view() */
4261 err = input_log_view(NULL, s->log_view, KEY_DOWN);
4262 if (err)
4263 break;
4265 if (old_selected_entry == ls->selected_entry)
4266 break;
4268 err = set_selected_commit(s, ls->selected_entry);
4269 if (err)
4270 break;
4272 s->first_displayed_line = 1;
4273 s->last_displayed_line = view->nlines;
4274 s->matched_line = 0;
4275 view->x = 0;
4277 diff_view_indicate_progress(view);
4278 err = create_diff(s);
4279 break;
4280 default:
4281 view->count = 0;
4282 break;
4285 return err;
4288 static const struct got_error *
4289 cmd_diff(int argc, char *argv[])
4291 const struct got_error *error = NULL;
4292 struct got_repository *repo = NULL;
4293 struct got_worktree *worktree = NULL;
4294 struct got_object_id *id1 = NULL, *id2 = NULL;
4295 char *repo_path = NULL, *cwd = NULL;
4296 char *id_str1 = NULL, *id_str2 = NULL;
4297 char *label1 = NULL, *label2 = NULL;
4298 int diff_context = 3, ignore_whitespace = 0;
4299 int ch, force_text_diff = 0;
4300 const char *errstr;
4301 struct tog_view *view;
4302 int *pack_fds = NULL;
4304 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4305 switch (ch) {
4306 case 'a':
4307 force_text_diff = 1;
4308 break;
4309 case 'C':
4310 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4311 &errstr);
4312 if (errstr != NULL)
4313 errx(1, "number of context lines is %s: %s",
4314 errstr, errstr);
4315 break;
4316 case 'r':
4317 repo_path = realpath(optarg, NULL);
4318 if (repo_path == NULL)
4319 return got_error_from_errno2("realpath",
4320 optarg);
4321 got_path_strip_trailing_slashes(repo_path);
4322 break;
4323 case 'w':
4324 ignore_whitespace = 1;
4325 break;
4326 default:
4327 usage_diff();
4328 /* NOTREACHED */
4332 argc -= optind;
4333 argv += optind;
4335 if (argc == 0) {
4336 usage_diff(); /* TODO show local worktree changes */
4337 } else if (argc == 2) {
4338 id_str1 = argv[0];
4339 id_str2 = argv[1];
4340 } else
4341 usage_diff();
4343 error = got_repo_pack_fds_open(&pack_fds);
4344 if (error)
4345 goto done;
4347 if (repo_path == NULL) {
4348 cwd = getcwd(NULL, 0);
4349 if (cwd == NULL)
4350 return got_error_from_errno("getcwd");
4351 error = got_worktree_open(&worktree, cwd);
4352 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4353 goto done;
4354 if (worktree)
4355 repo_path =
4356 strdup(got_worktree_get_repo_path(worktree));
4357 else
4358 repo_path = strdup(cwd);
4359 if (repo_path == NULL) {
4360 error = got_error_from_errno("strdup");
4361 goto done;
4365 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4366 if (error)
4367 goto done;
4369 init_curses();
4371 error = apply_unveil(got_repo_get_path(repo), NULL);
4372 if (error)
4373 goto done;
4375 error = tog_load_refs(repo, 0);
4376 if (error)
4377 goto done;
4379 error = got_repo_match_object_id(&id1, &label1, id_str1,
4380 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4381 if (error)
4382 goto done;
4384 error = got_repo_match_object_id(&id2, &label2, id_str2,
4385 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4386 if (error)
4387 goto done;
4389 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4390 if (view == NULL) {
4391 error = got_error_from_errno("view_open");
4392 goto done;
4394 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4395 ignore_whitespace, force_text_diff, NULL, repo);
4396 if (error)
4397 goto done;
4398 error = view_loop(view);
4399 done:
4400 free(label1);
4401 free(label2);
4402 free(repo_path);
4403 free(cwd);
4404 if (repo) {
4405 const struct got_error *close_err = got_repo_close(repo);
4406 if (error == NULL)
4407 error = close_err;
4409 if (worktree)
4410 got_worktree_close(worktree);
4411 if (pack_fds) {
4412 const struct got_error *pack_err =
4413 got_repo_pack_fds_close(pack_fds);
4414 if (error == NULL)
4415 error = pack_err;
4417 tog_free_refs();
4418 return error;
4421 __dead static void
4422 usage_blame(void)
4424 endwin();
4425 fprintf(stderr,
4426 "usage: %s blame [-c commit] [-r repository-path] path\n",
4427 getprogname());
4428 exit(1);
4431 struct tog_blame_line {
4432 int annotated;
4433 struct got_object_id *id;
4436 static const struct got_error *
4437 draw_blame(struct tog_view *view)
4439 struct tog_blame_view_state *s = &view->state.blame;
4440 struct tog_blame *blame = &s->blame;
4441 regmatch_t *regmatch = &view->regmatch;
4442 const struct got_error *err;
4443 int lineno = 0, nprinted = 0;
4444 char *line = NULL;
4445 size_t linesize = 0;
4446 ssize_t linelen;
4447 wchar_t *wline;
4448 int width;
4449 struct tog_blame_line *blame_line;
4450 struct got_object_id *prev_id = NULL;
4451 char *id_str;
4452 struct tog_color *tc;
4454 err = got_object_id_str(&id_str, &s->blamed_commit->id);
4455 if (err)
4456 return err;
4458 rewind(blame->f);
4459 werase(view->window);
4461 if (asprintf(&line, "commit %s", id_str) == -1) {
4462 err = got_error_from_errno("asprintf");
4463 free(id_str);
4464 return err;
4467 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4468 free(line);
4469 line = NULL;
4470 if (err)
4471 return err;
4472 if (view_needs_focus_indication(view))
4473 wstandout(view->window);
4474 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4475 if (tc)
4476 wattr_on(view->window,
4477 COLOR_PAIR(tc->colorpair), NULL);
4478 waddwstr(view->window, wline);
4479 if (tc)
4480 wattr_off(view->window,
4481 COLOR_PAIR(tc->colorpair), NULL);
4482 if (view_needs_focus_indication(view))
4483 wstandend(view->window);
4484 free(wline);
4485 wline = NULL;
4486 if (width < view->ncols - 1)
4487 waddch(view->window, '\n');
4489 if (asprintf(&line, "[%d/%d] %s%s",
4490 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
4491 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
4492 free(id_str);
4493 return got_error_from_errno("asprintf");
4495 free(id_str);
4496 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4497 free(line);
4498 line = NULL;
4499 if (err)
4500 return err;
4501 waddwstr(view->window, wline);
4502 free(wline);
4503 wline = NULL;
4504 if (width < view->ncols - 1)
4505 waddch(view->window, '\n');
4507 s->eof = 0;
4508 view->maxx = 0;
4509 while (nprinted < view->nlines - 2) {
4510 linelen = getline(&line, &linesize, blame->f);
4511 if (linelen == -1) {
4512 if (feof(blame->f)) {
4513 s->eof = 1;
4514 break;
4516 free(line);
4517 return got_ferror(blame->f, GOT_ERR_IO);
4519 if (++lineno < s->first_displayed_line)
4520 continue;
4522 /* Set view->maxx based on full line length. */
4523 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
4524 if (err) {
4525 free(line);
4526 return err;
4528 free(wline);
4529 wline = NULL;
4530 view->maxx = MAX(view->maxx, width);
4532 if (view->focussed && nprinted == s->selected_line - 1)
4533 wstandout(view->window);
4535 if (blame->nlines > 0) {
4536 blame_line = &blame->lines[lineno - 1];
4537 if (blame_line->annotated && prev_id &&
4538 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
4539 !(view->focussed &&
4540 nprinted == s->selected_line - 1)) {
4541 waddstr(view->window, " ");
4542 } else if (blame_line->annotated) {
4543 char *id_str;
4544 err = got_object_id_str(&id_str,
4545 blame_line->id);
4546 if (err) {
4547 free(line);
4548 return err;
4550 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4551 if (tc)
4552 wattr_on(view->window,
4553 COLOR_PAIR(tc->colorpair), NULL);
4554 wprintw(view->window, "%.8s", id_str);
4555 if (tc)
4556 wattr_off(view->window,
4557 COLOR_PAIR(tc->colorpair), NULL);
4558 free(id_str);
4559 prev_id = blame_line->id;
4560 } else {
4561 waddstr(view->window, "........");
4562 prev_id = NULL;
4564 } else {
4565 waddstr(view->window, "........");
4566 prev_id = NULL;
4569 if (view->focussed && nprinted == s->selected_line - 1)
4570 wstandend(view->window);
4571 waddstr(view->window, " ");
4573 if (view->ncols <= 9) {
4574 width = 9;
4575 } else if (s->first_displayed_line + nprinted ==
4576 s->matched_line &&
4577 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4578 err = add_matched_line(&width, line, view->ncols - 9, 9,
4579 view->window, view->x, regmatch);
4580 if (err) {
4581 free(line);
4582 return err;
4584 width += 9;
4585 } else {
4586 int skip;
4587 err = format_line(&wline, &width, &skip, line,
4588 view->x, view->ncols - 9, 9, 1);
4589 if (err) {
4590 free(line);
4591 return err;
4593 waddwstr(view->window, &wline[skip]);
4594 width += 9;
4595 free(wline);
4596 wline = NULL;
4599 if (width <= view->ncols - 1)
4600 waddch(view->window, '\n');
4601 if (++nprinted == 1)
4602 s->first_displayed_line = lineno;
4604 free(line);
4605 s->last_displayed_line = lineno;
4607 view_vborder(view);
4609 return NULL;
4612 static const struct got_error *
4613 blame_cb(void *arg, int nlines, int lineno,
4614 struct got_commit_object *commit, struct got_object_id *id)
4616 const struct got_error *err = NULL;
4617 struct tog_blame_cb_args *a = arg;
4618 struct tog_blame_line *line;
4619 int errcode;
4621 if (nlines != a->nlines ||
4622 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4623 return got_error(GOT_ERR_RANGE);
4625 errcode = pthread_mutex_lock(&tog_mutex);
4626 if (errcode)
4627 return got_error_set_errno(errcode, "pthread_mutex_lock");
4629 if (*a->quit) { /* user has quit the blame view */
4630 err = got_error(GOT_ERR_ITER_COMPLETED);
4631 goto done;
4634 if (lineno == -1)
4635 goto done; /* no change in this commit */
4637 line = &a->lines[lineno - 1];
4638 if (line->annotated)
4639 goto done;
4641 line->id = got_object_id_dup(id);
4642 if (line->id == NULL) {
4643 err = got_error_from_errno("got_object_id_dup");
4644 goto done;
4646 line->annotated = 1;
4647 done:
4648 errcode = pthread_mutex_unlock(&tog_mutex);
4649 if (errcode)
4650 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4651 return err;
4654 static void *
4655 blame_thread(void *arg)
4657 const struct got_error *err, *close_err;
4658 struct tog_blame_thread_args *ta = arg;
4659 struct tog_blame_cb_args *a = ta->cb_args;
4660 int errcode;
4662 err = block_signals_used_by_main_thread();
4663 if (err)
4664 return (void *)err;
4666 err = got_blame(ta->path, a->commit_id, ta->repo,
4667 blame_cb, ta->cb_args, ta->cancel_cb, ta->cancel_arg);
4668 if (err && err->code == GOT_ERR_CANCELLED)
4669 err = NULL;
4671 errcode = pthread_mutex_lock(&tog_mutex);
4672 if (errcode)
4673 return (void *)got_error_set_errno(errcode,
4674 "pthread_mutex_lock");
4676 close_err = got_repo_close(ta->repo);
4677 if (err == NULL)
4678 err = close_err;
4679 ta->repo = NULL;
4680 *ta->complete = 1;
4682 errcode = pthread_mutex_unlock(&tog_mutex);
4683 if (errcode && err == NULL)
4684 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4686 return (void *)err;
4689 static struct got_object_id *
4690 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
4691 int first_displayed_line, int selected_line)
4693 struct tog_blame_line *line;
4695 if (nlines <= 0)
4696 return NULL;
4698 line = &lines[first_displayed_line - 1 + selected_line - 1];
4699 if (!line->annotated)
4700 return NULL;
4702 return line->id;
4705 static const struct got_error *
4706 stop_blame(struct tog_blame *blame)
4708 const struct got_error *err = NULL;
4709 int i;
4711 if (blame->thread) {
4712 int errcode;
4713 errcode = pthread_mutex_unlock(&tog_mutex);
4714 if (errcode)
4715 return got_error_set_errno(errcode,
4716 "pthread_mutex_unlock");
4717 errcode = pthread_join(blame->thread, (void **)&err);
4718 if (errcode)
4719 return got_error_set_errno(errcode, "pthread_join");
4720 errcode = pthread_mutex_lock(&tog_mutex);
4721 if (errcode)
4722 return got_error_set_errno(errcode,
4723 "pthread_mutex_lock");
4724 if (err && err->code == GOT_ERR_ITER_COMPLETED)
4725 err = NULL;
4726 blame->thread = 0; //NULL;
4728 if (blame->thread_args.repo) {
4729 const struct got_error *close_err;
4730 close_err = got_repo_close(blame->thread_args.repo);
4731 if (err == NULL)
4732 err = close_err;
4733 blame->thread_args.repo = NULL;
4735 if (blame->f) {
4736 if (fclose(blame->f) == EOF && err == NULL)
4737 err = got_error_from_errno("fclose");
4738 blame->f = NULL;
4740 if (blame->lines) {
4741 for (i = 0; i < blame->nlines; i++)
4742 free(blame->lines[i].id);
4743 free(blame->lines);
4744 blame->lines = NULL;
4746 free(blame->cb_args.commit_id);
4747 blame->cb_args.commit_id = NULL;
4748 if (blame->pack_fds) {
4749 const struct got_error *pack_err =
4750 got_repo_pack_fds_close(blame->pack_fds);
4751 if (err == NULL)
4752 err = pack_err;
4753 blame->pack_fds = NULL;
4755 return err;
4758 static const struct got_error *
4759 cancel_blame_view(void *arg)
4761 const struct got_error *err = NULL;
4762 int *done = arg;
4763 int errcode;
4765 errcode = pthread_mutex_lock(&tog_mutex);
4766 if (errcode)
4767 return got_error_set_errno(errcode,
4768 "pthread_mutex_unlock");
4770 if (*done)
4771 err = got_error(GOT_ERR_CANCELLED);
4773 errcode = pthread_mutex_unlock(&tog_mutex);
4774 if (errcode)
4775 return got_error_set_errno(errcode,
4776 "pthread_mutex_lock");
4778 return err;
4781 static const struct got_error *
4782 run_blame(struct tog_view *view)
4784 struct tog_blame_view_state *s = &view->state.blame;
4785 struct tog_blame *blame = &s->blame;
4786 const struct got_error *err = NULL;
4787 struct got_commit_object *commit = NULL;
4788 struct got_blob_object *blob = NULL;
4789 struct got_repository *thread_repo = NULL;
4790 struct got_object_id *obj_id = NULL;
4791 int obj_type;
4792 int *pack_fds = NULL;
4794 err = got_object_open_as_commit(&commit, s->repo,
4795 &s->blamed_commit->id);
4796 if (err)
4797 return err;
4799 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
4800 if (err)
4801 goto done;
4803 err = got_object_get_type(&obj_type, s->repo, obj_id);
4804 if (err)
4805 goto done;
4807 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4808 err = got_error(GOT_ERR_OBJ_TYPE);
4809 goto done;
4812 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192);
4813 if (err)
4814 goto done;
4815 blame->f = got_opentemp();
4816 if (blame->f == NULL) {
4817 err = got_error_from_errno("got_opentemp");
4818 goto done;
4820 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
4821 &blame->line_offsets, blame->f, blob);
4822 if (err)
4823 goto done;
4824 if (blame->nlines == 0) {
4825 s->blame_complete = 1;
4826 goto done;
4829 /* Don't include \n at EOF in the blame line count. */
4830 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
4831 blame->nlines--;
4833 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
4834 if (blame->lines == NULL) {
4835 err = got_error_from_errno("calloc");
4836 goto done;
4839 err = got_repo_pack_fds_open(&pack_fds);
4840 if (err)
4841 goto done;
4842 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
4843 pack_fds);
4844 if (err)
4845 goto done;
4847 blame->pack_fds = pack_fds;
4848 blame->cb_args.view = view;
4849 blame->cb_args.lines = blame->lines;
4850 blame->cb_args.nlines = blame->nlines;
4851 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
4852 if (blame->cb_args.commit_id == NULL) {
4853 err = got_error_from_errno("got_object_id_dup");
4854 goto done;
4856 blame->cb_args.quit = &s->done;
4858 blame->thread_args.path = s->path;
4859 blame->thread_args.repo = thread_repo;
4860 blame->thread_args.cb_args = &blame->cb_args;
4861 blame->thread_args.complete = &s->blame_complete;
4862 blame->thread_args.cancel_cb = cancel_blame_view;
4863 blame->thread_args.cancel_arg = &s->done;
4864 s->blame_complete = 0;
4866 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
4867 s->first_displayed_line = 1;
4868 s->last_displayed_line = view->nlines;
4869 s->selected_line = 1;
4871 s->matched_line = 0;
4873 done:
4874 if (commit)
4875 got_object_commit_close(commit);
4876 if (blob)
4877 got_object_blob_close(blob);
4878 free(obj_id);
4879 if (err)
4880 stop_blame(blame);
4881 return err;
4884 static const struct got_error *
4885 open_blame_view(struct tog_view *view, char *path,
4886 struct got_object_id *commit_id, struct got_repository *repo)
4888 const struct got_error *err = NULL;
4889 struct tog_blame_view_state *s = &view->state.blame;
4891 STAILQ_INIT(&s->blamed_commits);
4893 s->path = strdup(path);
4894 if (s->path == NULL)
4895 return got_error_from_errno("strdup");
4897 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
4898 if (err) {
4899 free(s->path);
4900 return err;
4903 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
4904 s->first_displayed_line = 1;
4905 s->last_displayed_line = view->nlines;
4906 s->selected_line = 1;
4907 s->blame_complete = 0;
4908 s->repo = repo;
4909 s->commit_id = commit_id;
4910 memset(&s->blame, 0, sizeof(s->blame));
4912 STAILQ_INIT(&s->colors);
4913 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4914 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
4915 get_color_value("TOG_COLOR_COMMIT"));
4916 if (err)
4917 return err;
4920 view->show = show_blame_view;
4921 view->input = input_blame_view;
4922 view->close = close_blame_view;
4923 view->search_start = search_start_blame_view;
4924 view->search_next = search_next_blame_view;
4926 return run_blame(view);
4929 static const struct got_error *
4930 close_blame_view(struct tog_view *view)
4932 const struct got_error *err = NULL;
4933 struct tog_blame_view_state *s = &view->state.blame;
4935 if (s->blame.thread)
4936 err = stop_blame(&s->blame);
4938 while (!STAILQ_EMPTY(&s->blamed_commits)) {
4939 struct got_object_qid *blamed_commit;
4940 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
4941 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
4942 got_object_qid_free(blamed_commit);
4945 free(s->path);
4946 free_colors(&s->colors);
4947 return err;
4950 static const struct got_error *
4951 search_start_blame_view(struct tog_view *view)
4953 struct tog_blame_view_state *s = &view->state.blame;
4955 s->matched_line = 0;
4956 return NULL;
4959 static const struct got_error *
4960 search_next_blame_view(struct tog_view *view)
4962 struct tog_blame_view_state *s = &view->state.blame;
4963 const struct got_error *err = NULL;
4964 int lineno;
4965 char *line = NULL;
4966 size_t linesize = 0;
4967 ssize_t linelen;
4969 if (!view->searching) {
4970 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4971 return NULL;
4974 if (s->matched_line) {
4975 if (view->searching == TOG_SEARCH_FORWARD)
4976 lineno = s->matched_line + 1;
4977 else
4978 lineno = s->matched_line - 1;
4979 } else
4980 lineno = s->first_displayed_line - 1 + s->selected_line;
4982 while (1) {
4983 off_t offset;
4985 if (lineno <= 0 || lineno > s->blame.nlines) {
4986 if (s->matched_line == 0) {
4987 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4988 break;
4991 if (view->searching == TOG_SEARCH_FORWARD)
4992 lineno = 1;
4993 else
4994 lineno = s->blame.nlines;
4997 offset = s->blame.line_offsets[lineno - 1];
4998 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
4999 free(line);
5000 return got_error_from_errno("fseeko");
5002 linelen = getline(&line, &linesize, s->blame.f);
5003 if (linelen != -1) {
5004 char *exstr;
5005 err = expand_tab(&exstr, line);
5006 if (err)
5007 break;
5008 if (match_line(exstr, &view->regex, 1,
5009 &view->regmatch)) {
5010 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5011 s->matched_line = lineno;
5012 free(exstr);
5013 break;
5015 free(exstr);
5017 if (view->searching == TOG_SEARCH_FORWARD)
5018 lineno++;
5019 else
5020 lineno--;
5022 free(line);
5024 if (s->matched_line) {
5025 s->first_displayed_line = s->matched_line;
5026 s->selected_line = 1;
5029 return err;
5032 static const struct got_error *
5033 show_blame_view(struct tog_view *view)
5035 const struct got_error *err = NULL;
5036 struct tog_blame_view_state *s = &view->state.blame;
5037 int errcode;
5039 if (s->blame.thread == 0 && !s->blame_complete) {
5040 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5041 &s->blame.thread_args);
5042 if (errcode)
5043 return got_error_set_errno(errcode, "pthread_create");
5045 halfdelay(1); /* fast refresh while annotating */
5048 if (s->blame_complete)
5049 halfdelay(10); /* disable fast refresh */
5051 err = draw_blame(view);
5053 view_vborder(view);
5054 return err;
5057 static const struct got_error *
5058 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5060 const struct got_error *err = NULL, *thread_err = NULL;
5061 struct tog_view *diff_view;
5062 struct tog_blame_view_state *s = &view->state.blame;
5063 int begin_x = 0, nscroll = view->nlines - 2;
5065 switch (ch) {
5066 case '0':
5067 view->x = 0;
5068 break;
5069 case '$':
5070 view->x = MAX(view->maxx - view->ncols / 3, 0);
5071 view->count = 0;
5072 break;
5073 case KEY_RIGHT:
5074 case 'l':
5075 if (view->x + view->ncols / 3 < view->maxx)
5076 view->x += 2; /* move two columns right */
5077 else
5078 view->count = 0;
5079 break;
5080 case KEY_LEFT:
5081 case 'h':
5082 view->x -= MIN(view->x, 2); /* move two columns back */
5083 if (view->x <= 0)
5084 view->count = 0;
5085 break;
5086 case 'q':
5087 s->done = 1;
5088 break;
5089 case 'g':
5090 case KEY_HOME:
5091 s->selected_line = 1;
5092 s->first_displayed_line = 1;
5093 view->count = 0;
5094 break;
5095 case 'G':
5096 case KEY_END:
5097 if (s->blame.nlines < view->nlines - 2) {
5098 s->selected_line = s->blame.nlines;
5099 s->first_displayed_line = 1;
5100 } else {
5101 s->selected_line = view->nlines - 2;
5102 s->first_displayed_line = s->blame.nlines -
5103 (view->nlines - 3);
5105 view->count = 0;
5106 break;
5107 case 'k':
5108 case KEY_UP:
5109 case CTRL('p'):
5110 if (s->selected_line > 1)
5111 s->selected_line--;
5112 else if (s->selected_line == 1 &&
5113 s->first_displayed_line > 1)
5114 s->first_displayed_line--;
5115 else
5116 view->count = 0;
5117 break;
5118 case CTRL('u'):
5119 case 'u':
5120 nscroll /= 2;
5121 /* FALL THROUGH */
5122 case KEY_PPAGE:
5123 case CTRL('b'):
5124 case 'b':
5125 if (s->first_displayed_line == 1) {
5126 if (view->count > 1)
5127 nscroll += nscroll;
5128 s->selected_line = MAX(1, s->selected_line - nscroll);
5129 view->count = 0;
5130 break;
5132 if (s->first_displayed_line > nscroll)
5133 s->first_displayed_line -= nscroll;
5134 else
5135 s->first_displayed_line = 1;
5136 break;
5137 case 'j':
5138 case KEY_DOWN:
5139 case CTRL('n'):
5140 if (s->selected_line < view->nlines - 2 &&
5141 s->first_displayed_line +
5142 s->selected_line <= s->blame.nlines)
5143 s->selected_line++;
5144 else if (s->last_displayed_line <
5145 s->blame.nlines)
5146 s->first_displayed_line++;
5147 else
5148 view->count = 0;
5149 break;
5150 case 'c':
5151 case 'p': {
5152 struct got_object_id *id = NULL;
5154 view->count = 0;
5155 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5156 s->first_displayed_line, s->selected_line);
5157 if (id == NULL)
5158 break;
5159 if (ch == 'p') {
5160 struct got_commit_object *commit, *pcommit;
5161 struct got_object_qid *pid;
5162 struct got_object_id *blob_id = NULL;
5163 int obj_type;
5164 err = got_object_open_as_commit(&commit,
5165 s->repo, id);
5166 if (err)
5167 break;
5168 pid = STAILQ_FIRST(
5169 got_object_commit_get_parent_ids(commit));
5170 if (pid == NULL) {
5171 got_object_commit_close(commit);
5172 break;
5174 /* Check if path history ends here. */
5175 err = got_object_open_as_commit(&pcommit,
5176 s->repo, &pid->id);
5177 if (err)
5178 break;
5179 err = got_object_id_by_path(&blob_id, s->repo,
5180 pcommit, s->path);
5181 got_object_commit_close(pcommit);
5182 if (err) {
5183 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5184 err = NULL;
5185 got_object_commit_close(commit);
5186 break;
5188 err = got_object_get_type(&obj_type, s->repo,
5189 blob_id);
5190 free(blob_id);
5191 /* Can't blame non-blob type objects. */
5192 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5193 got_object_commit_close(commit);
5194 break;
5196 err = got_object_qid_alloc(&s->blamed_commit,
5197 &pid->id);
5198 got_object_commit_close(commit);
5199 } else {
5200 if (got_object_id_cmp(id,
5201 &s->blamed_commit->id) == 0)
5202 break;
5203 err = got_object_qid_alloc(&s->blamed_commit,
5204 id);
5206 if (err)
5207 break;
5208 s->done = 1;
5209 thread_err = stop_blame(&s->blame);
5210 s->done = 0;
5211 if (thread_err)
5212 break;
5213 STAILQ_INSERT_HEAD(&s->blamed_commits,
5214 s->blamed_commit, entry);
5215 err = run_blame(view);
5216 if (err)
5217 break;
5218 break;
5220 case 'C': {
5221 struct got_object_qid *first;
5223 view->count = 0;
5224 first = STAILQ_FIRST(&s->blamed_commits);
5225 if (!got_object_id_cmp(&first->id, s->commit_id))
5226 break;
5227 s->done = 1;
5228 thread_err = stop_blame(&s->blame);
5229 s->done = 0;
5230 if (thread_err)
5231 break;
5232 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5233 got_object_qid_free(s->blamed_commit);
5234 s->blamed_commit =
5235 STAILQ_FIRST(&s->blamed_commits);
5236 err = run_blame(view);
5237 if (err)
5238 break;
5239 break;
5241 case KEY_ENTER:
5242 case '\r': {
5243 struct got_object_id *id = NULL;
5244 struct got_object_qid *pid;
5245 struct got_commit_object *commit = NULL;
5247 view->count = 0;
5248 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5249 s->first_displayed_line, s->selected_line);
5250 if (id == NULL)
5251 break;
5252 err = got_object_open_as_commit(&commit, s->repo, id);
5253 if (err)
5254 break;
5255 pid = STAILQ_FIRST(
5256 got_object_commit_get_parent_ids(commit));
5257 if (view_is_parent_view(view))
5258 begin_x = view_split_begin_x(view->begin_x);
5259 diff_view = view_open(0, 0, 0, begin_x, TOG_VIEW_DIFF);
5260 if (diff_view == NULL) {
5261 got_object_commit_close(commit);
5262 err = got_error_from_errno("view_open");
5263 break;
5265 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5266 id, NULL, NULL, 3, 0, 0, NULL, s->repo);
5267 got_object_commit_close(commit);
5268 if (err) {
5269 view_close(diff_view);
5270 break;
5272 view->focussed = 0;
5273 diff_view->focussed = 1;
5274 if (view_is_parent_view(view)) {
5275 err = view_close_child(view);
5276 if (err)
5277 break;
5278 err = view_set_child(view, diff_view);
5279 if (err)
5280 break;
5281 view->focus_child = 1;
5282 } else
5283 *new_view = diff_view;
5284 if (err)
5285 break;
5286 break;
5288 case CTRL('d'):
5289 case 'd':
5290 nscroll /= 2;
5291 /* FALL THROUGH */
5292 case KEY_NPAGE:
5293 case CTRL('f'):
5294 case 'f':
5295 case ' ':
5296 if (s->last_displayed_line >= s->blame.nlines &&
5297 s->selected_line >= MIN(s->blame.nlines,
5298 view->nlines - 2)) {
5299 view->count = 0;
5300 break;
5302 if (s->last_displayed_line >= s->blame.nlines &&
5303 s->selected_line < view->nlines - 2) {
5304 s->selected_line +=
5305 MIN(nscroll, s->last_displayed_line -
5306 s->first_displayed_line - s->selected_line + 1);
5308 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5309 s->first_displayed_line += nscroll;
5310 else
5311 s->first_displayed_line =
5312 s->blame.nlines - (view->nlines - 3);
5313 break;
5314 case KEY_RESIZE:
5315 if (s->selected_line > view->nlines - 2) {
5316 s->selected_line = MIN(s->blame.nlines,
5317 view->nlines - 2);
5319 break;
5320 default:
5321 view->count = 0;
5322 break;
5324 return thread_err ? thread_err : err;
5327 static const struct got_error *
5328 cmd_blame(int argc, char *argv[])
5330 const struct got_error *error;
5331 struct got_repository *repo = NULL;
5332 struct got_worktree *worktree = NULL;
5333 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5334 char *link_target = NULL;
5335 struct got_object_id *commit_id = NULL;
5336 struct got_commit_object *commit = NULL;
5337 char *commit_id_str = NULL;
5338 int ch;
5339 struct tog_view *view;
5340 int *pack_fds = NULL;
5342 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5343 switch (ch) {
5344 case 'c':
5345 commit_id_str = optarg;
5346 break;
5347 case 'r':
5348 repo_path = realpath(optarg, NULL);
5349 if (repo_path == NULL)
5350 return got_error_from_errno2("realpath",
5351 optarg);
5352 break;
5353 default:
5354 usage_blame();
5355 /* NOTREACHED */
5359 argc -= optind;
5360 argv += optind;
5362 if (argc != 1)
5363 usage_blame();
5365 error = got_repo_pack_fds_open(&pack_fds);
5366 if (error != NULL)
5367 goto done;
5369 if (repo_path == NULL) {
5370 cwd = getcwd(NULL, 0);
5371 if (cwd == NULL)
5372 return got_error_from_errno("getcwd");
5373 error = got_worktree_open(&worktree, cwd);
5374 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5375 goto done;
5376 if (worktree)
5377 repo_path =
5378 strdup(got_worktree_get_repo_path(worktree));
5379 else
5380 repo_path = strdup(cwd);
5381 if (repo_path == NULL) {
5382 error = got_error_from_errno("strdup");
5383 goto done;
5387 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5388 if (error != NULL)
5389 goto done;
5391 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
5392 worktree);
5393 if (error)
5394 goto done;
5396 init_curses();
5398 error = apply_unveil(got_repo_get_path(repo), NULL);
5399 if (error)
5400 goto done;
5402 error = tog_load_refs(repo, 0);
5403 if (error)
5404 goto done;
5406 if (commit_id_str == NULL) {
5407 struct got_reference *head_ref;
5408 error = got_ref_open(&head_ref, repo, worktree ?
5409 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5410 if (error != NULL)
5411 goto done;
5412 error = got_ref_resolve(&commit_id, repo, head_ref);
5413 got_ref_close(head_ref);
5414 } else {
5415 error = got_repo_match_object_id(&commit_id, NULL,
5416 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
5418 if (error != NULL)
5419 goto done;
5421 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
5422 if (view == NULL) {
5423 error = got_error_from_errno("view_open");
5424 goto done;
5427 error = got_object_open_as_commit(&commit, repo, commit_id);
5428 if (error)
5429 goto done;
5431 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5432 commit, repo);
5433 if (error)
5434 goto done;
5436 error = open_blame_view(view, link_target ? link_target : in_repo_path,
5437 commit_id, repo);
5438 if (error)
5439 goto done;
5440 if (worktree) {
5441 /* Release work tree lock. */
5442 got_worktree_close(worktree);
5443 worktree = NULL;
5445 error = view_loop(view);
5446 done:
5447 free(repo_path);
5448 free(in_repo_path);
5449 free(link_target);
5450 free(cwd);
5451 free(commit_id);
5452 if (commit)
5453 got_object_commit_close(commit);
5454 if (worktree)
5455 got_worktree_close(worktree);
5456 if (repo) {
5457 const struct got_error *close_err = got_repo_close(repo);
5458 if (error == NULL)
5459 error = close_err;
5461 if (pack_fds) {
5462 const struct got_error *pack_err =
5463 got_repo_pack_fds_close(pack_fds);
5464 if (error == NULL)
5465 error = pack_err;
5467 tog_free_refs();
5468 return error;
5471 static const struct got_error *
5472 draw_tree_entries(struct tog_view *view, const char *parent_path)
5474 struct tog_tree_view_state *s = &view->state.tree;
5475 const struct got_error *err = NULL;
5476 struct got_tree_entry *te;
5477 wchar_t *wline;
5478 struct tog_color *tc;
5479 int width, n, i, nentries;
5480 int limit = view->nlines;
5482 s->ndisplayed = 0;
5484 werase(view->window);
5486 if (limit == 0)
5487 return NULL;
5489 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
5490 0, 0);
5491 if (err)
5492 return err;
5493 if (view_needs_focus_indication(view))
5494 wstandout(view->window);
5495 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5496 if (tc)
5497 wattr_on(view->window,
5498 COLOR_PAIR(tc->colorpair), NULL);
5499 waddwstr(view->window, wline);
5500 if (tc)
5501 wattr_off(view->window,
5502 COLOR_PAIR(tc->colorpair), NULL);
5503 if (view_needs_focus_indication(view))
5504 wstandend(view->window);
5505 free(wline);
5506 wline = NULL;
5507 if (width < view->ncols - 1)
5508 waddch(view->window, '\n');
5509 if (--limit <= 0)
5510 return NULL;
5511 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
5512 0, 0);
5513 if (err)
5514 return err;
5515 waddwstr(view->window, wline);
5516 free(wline);
5517 wline = NULL;
5518 if (width < view->ncols - 1)
5519 waddch(view->window, '\n');
5520 if (--limit <= 0)
5521 return NULL;
5522 waddch(view->window, '\n');
5523 if (--limit <= 0)
5524 return NULL;
5526 if (s->first_displayed_entry == NULL) {
5527 te = got_object_tree_get_first_entry(s->tree);
5528 if (s->selected == 0) {
5529 if (view->focussed)
5530 wstandout(view->window);
5531 s->selected_entry = NULL;
5533 waddstr(view->window, " ..\n"); /* parent directory */
5534 if (s->selected == 0 && view->focussed)
5535 wstandend(view->window);
5536 s->ndisplayed++;
5537 if (--limit <= 0)
5538 return NULL;
5539 n = 1;
5540 } else {
5541 n = 0;
5542 te = s->first_displayed_entry;
5545 nentries = got_object_tree_get_nentries(s->tree);
5546 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
5547 char *line = NULL, *id_str = NULL, *link_target = NULL;
5548 const char *modestr = "";
5549 mode_t mode;
5551 te = got_object_tree_get_entry(s->tree, i);
5552 mode = got_tree_entry_get_mode(te);
5554 if (s->show_ids) {
5555 err = got_object_id_str(&id_str,
5556 got_tree_entry_get_id(te));
5557 if (err)
5558 return got_error_from_errno(
5559 "got_object_id_str");
5561 if (got_object_tree_entry_is_submodule(te))
5562 modestr = "$";
5563 else if (S_ISLNK(mode)) {
5564 int i;
5566 err = got_tree_entry_get_symlink_target(&link_target,
5567 te, s->repo);
5568 if (err) {
5569 free(id_str);
5570 return err;
5572 for (i = 0; i < strlen(link_target); i++) {
5573 if (!isprint((unsigned char)link_target[i]))
5574 link_target[i] = '?';
5576 modestr = "@";
5578 else if (S_ISDIR(mode))
5579 modestr = "/";
5580 else if (mode & S_IXUSR)
5581 modestr = "*";
5582 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
5583 got_tree_entry_get_name(te), modestr,
5584 link_target ? " -> ": "",
5585 link_target ? link_target : "") == -1) {
5586 free(id_str);
5587 free(link_target);
5588 return got_error_from_errno("asprintf");
5590 free(id_str);
5591 free(link_target);
5592 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
5593 0, 0);
5594 if (err) {
5595 free(line);
5596 break;
5598 if (n == s->selected) {
5599 if (view->focussed)
5600 wstandout(view->window);
5601 s->selected_entry = te;
5603 tc = match_color(&s->colors, line);
5604 if (tc)
5605 wattr_on(view->window,
5606 COLOR_PAIR(tc->colorpair), NULL);
5607 waddwstr(view->window, wline);
5608 if (tc)
5609 wattr_off(view->window,
5610 COLOR_PAIR(tc->colorpair), NULL);
5611 if (width < view->ncols - 1)
5612 waddch(view->window, '\n');
5613 if (n == s->selected && view->focussed)
5614 wstandend(view->window);
5615 free(line);
5616 free(wline);
5617 wline = NULL;
5618 n++;
5619 s->ndisplayed++;
5620 s->last_displayed_entry = te;
5621 if (--limit <= 0)
5622 break;
5625 return err;
5628 static void
5629 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
5631 struct got_tree_entry *te;
5632 int isroot = s->tree == s->root;
5633 int i = 0;
5635 if (s->first_displayed_entry == NULL)
5636 return;
5638 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
5639 while (i++ < maxscroll) {
5640 if (te == NULL) {
5641 if (!isroot)
5642 s->first_displayed_entry = NULL;
5643 break;
5645 s->first_displayed_entry = te;
5646 te = got_tree_entry_get_prev(s->tree, te);
5650 static void
5651 tree_scroll_down(struct tog_tree_view_state *s, int maxscroll)
5653 struct got_tree_entry *next, *last;
5654 int n = 0;
5656 if (s->first_displayed_entry)
5657 next = got_tree_entry_get_next(s->tree,
5658 s->first_displayed_entry);
5659 else
5660 next = got_object_tree_get_first_entry(s->tree);
5662 last = s->last_displayed_entry;
5663 while (next && last && n++ < maxscroll) {
5664 last = got_tree_entry_get_next(s->tree, last);
5665 if (last) {
5666 s->first_displayed_entry = next;
5667 next = got_tree_entry_get_next(s->tree, next);
5672 static const struct got_error *
5673 tree_entry_path(char **path, struct tog_parent_trees *parents,
5674 struct got_tree_entry *te)
5676 const struct got_error *err = NULL;
5677 struct tog_parent_tree *pt;
5678 size_t len = 2; /* for leading slash and NUL */
5680 TAILQ_FOREACH(pt, parents, entry)
5681 len += strlen(got_tree_entry_get_name(pt->selected_entry))
5682 + 1 /* slash */;
5683 if (te)
5684 len += strlen(got_tree_entry_get_name(te));
5686 *path = calloc(1, len);
5687 if (path == NULL)
5688 return got_error_from_errno("calloc");
5690 (*path)[0] = '/';
5691 pt = TAILQ_LAST(parents, tog_parent_trees);
5692 while (pt) {
5693 const char *name = got_tree_entry_get_name(pt->selected_entry);
5694 if (strlcat(*path, name, len) >= len) {
5695 err = got_error(GOT_ERR_NO_SPACE);
5696 goto done;
5698 if (strlcat(*path, "/", len) >= len) {
5699 err = got_error(GOT_ERR_NO_SPACE);
5700 goto done;
5702 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
5704 if (te) {
5705 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
5706 err = got_error(GOT_ERR_NO_SPACE);
5707 goto done;
5710 done:
5711 if (err) {
5712 free(*path);
5713 *path = NULL;
5715 return err;
5718 static const struct got_error *
5719 blame_tree_entry(struct tog_view **new_view, int begin_x,
5720 struct got_tree_entry *te, struct tog_parent_trees *parents,
5721 struct got_object_id *commit_id, struct got_repository *repo)
5723 const struct got_error *err = NULL;
5724 char *path;
5725 struct tog_view *blame_view;
5727 *new_view = NULL;
5729 err = tree_entry_path(&path, parents, te);
5730 if (err)
5731 return err;
5733 blame_view = view_open(0, 0, 0, begin_x, TOG_VIEW_BLAME);
5734 if (blame_view == NULL) {
5735 err = got_error_from_errno("view_open");
5736 goto done;
5739 err = open_blame_view(blame_view, path, commit_id, repo);
5740 if (err) {
5741 if (err->code == GOT_ERR_CANCELLED)
5742 err = NULL;
5743 view_close(blame_view);
5744 } else
5745 *new_view = blame_view;
5746 done:
5747 free(path);
5748 return err;
5751 static const struct got_error *
5752 log_selected_tree_entry(struct tog_view **new_view, int begin_x,
5753 struct tog_tree_view_state *s)
5755 struct tog_view *log_view;
5756 const struct got_error *err = NULL;
5757 char *path;
5759 *new_view = NULL;
5761 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
5762 if (log_view == NULL)
5763 return got_error_from_errno("view_open");
5765 err = tree_entry_path(&path, &s->parents, s->selected_entry);
5766 if (err)
5767 return err;
5769 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
5770 path, 0);
5771 if (err)
5772 view_close(log_view);
5773 else
5774 *new_view = log_view;
5775 free(path);
5776 return err;
5779 static const struct got_error *
5780 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
5781 const char *head_ref_name, struct got_repository *repo)
5783 const struct got_error *err = NULL;
5784 char *commit_id_str = NULL;
5785 struct tog_tree_view_state *s = &view->state.tree;
5786 struct got_commit_object *commit = NULL;
5788 TAILQ_INIT(&s->parents);
5789 STAILQ_INIT(&s->colors);
5791 s->commit_id = got_object_id_dup(commit_id);
5792 if (s->commit_id == NULL)
5793 return got_error_from_errno("got_object_id_dup");
5795 err = got_object_open_as_commit(&commit, repo, commit_id);
5796 if (err)
5797 goto done;
5800 * The root is opened here and will be closed when the view is closed.
5801 * Any visited subtrees and their path-wise parents are opened and
5802 * closed on demand.
5804 err = got_object_open_as_tree(&s->root, repo,
5805 got_object_commit_get_tree_id(commit));
5806 if (err)
5807 goto done;
5808 s->tree = s->root;
5810 err = got_object_id_str(&commit_id_str, commit_id);
5811 if (err != NULL)
5812 goto done;
5814 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
5815 err = got_error_from_errno("asprintf");
5816 goto done;
5819 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
5820 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
5821 if (head_ref_name) {
5822 s->head_ref_name = strdup(head_ref_name);
5823 if (s->head_ref_name == NULL) {
5824 err = got_error_from_errno("strdup");
5825 goto done;
5828 s->repo = repo;
5830 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5831 err = add_color(&s->colors, "\\$$",
5832 TOG_COLOR_TREE_SUBMODULE,
5833 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
5834 if (err)
5835 goto done;
5836 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
5837 get_color_value("TOG_COLOR_TREE_SYMLINK"));
5838 if (err)
5839 goto done;
5840 err = add_color(&s->colors, "/$",
5841 TOG_COLOR_TREE_DIRECTORY,
5842 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
5843 if (err)
5844 goto done;
5846 err = add_color(&s->colors, "\\*$",
5847 TOG_COLOR_TREE_EXECUTABLE,
5848 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
5849 if (err)
5850 goto done;
5852 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
5853 get_color_value("TOG_COLOR_COMMIT"));
5854 if (err)
5855 goto done;
5858 view->show = show_tree_view;
5859 view->input = input_tree_view;
5860 view->close = close_tree_view;
5861 view->search_start = search_start_tree_view;
5862 view->search_next = search_next_tree_view;
5863 done:
5864 free(commit_id_str);
5865 if (commit)
5866 got_object_commit_close(commit);
5867 if (err)
5868 close_tree_view(view);
5869 return err;
5872 static const struct got_error *
5873 close_tree_view(struct tog_view *view)
5875 struct tog_tree_view_state *s = &view->state.tree;
5877 free_colors(&s->colors);
5878 free(s->tree_label);
5879 s->tree_label = NULL;
5880 free(s->commit_id);
5881 s->commit_id = NULL;
5882 free(s->head_ref_name);
5883 s->head_ref_name = NULL;
5884 while (!TAILQ_EMPTY(&s->parents)) {
5885 struct tog_parent_tree *parent;
5886 parent = TAILQ_FIRST(&s->parents);
5887 TAILQ_REMOVE(&s->parents, parent, entry);
5888 if (parent->tree != s->root)
5889 got_object_tree_close(parent->tree);
5890 free(parent);
5893 if (s->tree != NULL && s->tree != s->root)
5894 got_object_tree_close(s->tree);
5895 if (s->root)
5896 got_object_tree_close(s->root);
5897 return NULL;
5900 static const struct got_error *
5901 search_start_tree_view(struct tog_view *view)
5903 struct tog_tree_view_state *s = &view->state.tree;
5905 s->matched_entry = NULL;
5906 return NULL;
5909 static int
5910 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
5912 regmatch_t regmatch;
5914 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
5915 0) == 0;
5918 static const struct got_error *
5919 search_next_tree_view(struct tog_view *view)
5921 struct tog_tree_view_state *s = &view->state.tree;
5922 struct got_tree_entry *te = NULL;
5924 if (!view->searching) {
5925 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5926 return NULL;
5929 if (s->matched_entry) {
5930 if (view->searching == TOG_SEARCH_FORWARD) {
5931 if (s->selected_entry)
5932 te = got_tree_entry_get_next(s->tree,
5933 s->selected_entry);
5934 else
5935 te = got_object_tree_get_first_entry(s->tree);
5936 } else {
5937 if (s->selected_entry == NULL)
5938 te = got_object_tree_get_last_entry(s->tree);
5939 else
5940 te = got_tree_entry_get_prev(s->tree,
5941 s->selected_entry);
5943 } else {
5944 if (s->selected_entry)
5945 te = s->selected_entry;
5946 else if (view->searching == TOG_SEARCH_FORWARD)
5947 te = got_object_tree_get_first_entry(s->tree);
5948 else
5949 te = got_object_tree_get_last_entry(s->tree);
5952 while (1) {
5953 if (te == NULL) {
5954 if (s->matched_entry == NULL) {
5955 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5956 return NULL;
5958 if (view->searching == TOG_SEARCH_FORWARD)
5959 te = got_object_tree_get_first_entry(s->tree);
5960 else
5961 te = got_object_tree_get_last_entry(s->tree);
5964 if (match_tree_entry(te, &view->regex)) {
5965 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5966 s->matched_entry = te;
5967 break;
5970 if (view->searching == TOG_SEARCH_FORWARD)
5971 te = got_tree_entry_get_next(s->tree, te);
5972 else
5973 te = got_tree_entry_get_prev(s->tree, te);
5976 if (s->matched_entry) {
5977 s->first_displayed_entry = s->matched_entry;
5978 s->selected = 0;
5981 return NULL;
5984 static const struct got_error *
5985 show_tree_view(struct tog_view *view)
5987 const struct got_error *err = NULL;
5988 struct tog_tree_view_state *s = &view->state.tree;
5989 char *parent_path;
5991 err = tree_entry_path(&parent_path, &s->parents, NULL);
5992 if (err)
5993 return err;
5995 err = draw_tree_entries(view, parent_path);
5996 free(parent_path);
5998 view_vborder(view);
5999 return err;
6002 static const struct got_error *
6003 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6005 const struct got_error *err = NULL;
6006 struct tog_tree_view_state *s = &view->state.tree;
6007 struct tog_view *log_view, *ref_view;
6008 struct got_tree_entry *te;
6009 int begin_x = 0, n, nscroll = view->nlines - 3;
6011 switch (ch) {
6012 case 'i':
6013 s->show_ids = !s->show_ids;
6014 view->count = 0;
6015 break;
6016 case 'l':
6017 view->count = 0;
6018 if (!s->selected_entry)
6019 break;
6020 if (view_is_parent_view(view))
6021 begin_x = view_split_begin_x(view->begin_x);
6022 err = log_selected_tree_entry(&log_view, begin_x, s);
6023 view->focussed = 0;
6024 log_view->focussed = 1;
6025 if (view_is_parent_view(view)) {
6026 err = view_close_child(view);
6027 if (err)
6028 return err;
6029 err = view_set_child(view, log_view);
6030 if (err)
6031 return err;
6032 view->focus_child = 1;
6033 } else
6034 *new_view = log_view;
6035 break;
6036 case 'r':
6037 view->count = 0;
6038 if (view_is_parent_view(view))
6039 begin_x = view_split_begin_x(view->begin_x);
6040 ref_view = view_open(view->nlines, view->ncols,
6041 view->begin_y, begin_x, TOG_VIEW_REF);
6042 if (ref_view == NULL)
6043 return got_error_from_errno("view_open");
6044 err = open_ref_view(ref_view, s->repo);
6045 if (err) {
6046 view_close(ref_view);
6047 return err;
6049 view->focussed = 0;
6050 ref_view->focussed = 1;
6051 if (view_is_parent_view(view)) {
6052 err = view_close_child(view);
6053 if (err)
6054 return err;
6055 err = view_set_child(view, ref_view);
6056 if (err)
6057 return err;
6058 view->focus_child = 1;
6059 } else
6060 *new_view = ref_view;
6061 break;
6062 case 'g':
6063 case KEY_HOME:
6064 s->selected = 0;
6065 view->count = 0;
6066 if (s->tree == s->root)
6067 s->first_displayed_entry =
6068 got_object_tree_get_first_entry(s->tree);
6069 else
6070 s->first_displayed_entry = NULL;
6071 break;
6072 case 'G':
6073 case KEY_END:
6074 s->selected = 0;
6075 view->count = 0;
6076 te = got_object_tree_get_last_entry(s->tree);
6077 for (n = 0; n < view->nlines - 3; n++) {
6078 if (te == NULL) {
6079 if(s->tree != s->root) {
6080 s->first_displayed_entry = NULL;
6081 n++;
6083 break;
6085 s->first_displayed_entry = te;
6086 te = got_tree_entry_get_prev(s->tree, te);
6088 if (n > 0)
6089 s->selected = n - 1;
6090 break;
6091 case 'k':
6092 case KEY_UP:
6093 case CTRL('p'):
6094 if (s->selected > 0) {
6095 s->selected--;
6096 break;
6098 tree_scroll_up(s, 1);
6099 if (s->selected_entry == NULL ||
6100 (s->tree == s->root && s->selected_entry ==
6101 got_object_tree_get_first_entry(s->tree)))
6102 view->count = 0;
6103 break;
6104 case CTRL('u'):
6105 case 'u':
6106 nscroll /= 2;
6107 /* FALL THROUGH */
6108 case KEY_PPAGE:
6109 case CTRL('b'):
6110 case 'b':
6111 if (s->tree == s->root) {
6112 if (got_object_tree_get_first_entry(s->tree) ==
6113 s->first_displayed_entry)
6114 s->selected -= MIN(s->selected, nscroll);
6115 } else {
6116 if (s->first_displayed_entry == NULL)
6117 s->selected -= MIN(s->selected, nscroll);
6119 tree_scroll_up(s, MAX(0, nscroll));
6120 if (s->selected_entry == NULL ||
6121 (s->tree == s->root && s->selected_entry ==
6122 got_object_tree_get_first_entry(s->tree)))
6123 view->count = 0;
6124 break;
6125 case 'j':
6126 case KEY_DOWN:
6127 case CTRL('n'):
6128 if (s->selected < s->ndisplayed - 1) {
6129 s->selected++;
6130 break;
6132 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6133 == NULL) {
6134 /* can't scroll any further */
6135 view->count = 0;
6136 break;
6138 tree_scroll_down(s, 1);
6139 break;
6140 case CTRL('d'):
6141 case 'd':
6142 nscroll /= 2;
6143 /* FALL THROUGH */
6144 case KEY_NPAGE:
6145 case CTRL('f'):
6146 case 'f':
6147 case ' ':
6148 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6149 == NULL) {
6150 /* can't scroll any further; move cursor down */
6151 if (s->selected < s->ndisplayed - 1)
6152 s->selected += MIN(nscroll,
6153 s->ndisplayed - s->selected - 1);
6154 else
6155 view->count = 0;
6156 break;
6158 tree_scroll_down(s, nscroll);
6159 break;
6160 case KEY_ENTER:
6161 case '\r':
6162 case KEY_BACKSPACE:
6163 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6164 struct tog_parent_tree *parent;
6165 /* user selected '..' */
6166 if (s->tree == s->root) {
6167 view->count = 0;
6168 break;
6170 parent = TAILQ_FIRST(&s->parents);
6171 TAILQ_REMOVE(&s->parents, parent,
6172 entry);
6173 got_object_tree_close(s->tree);
6174 s->tree = parent->tree;
6175 s->first_displayed_entry =
6176 parent->first_displayed_entry;
6177 s->selected_entry =
6178 parent->selected_entry;
6179 s->selected = parent->selected;
6180 free(parent);
6181 } else if (S_ISDIR(got_tree_entry_get_mode(
6182 s->selected_entry))) {
6183 struct got_tree_object *subtree;
6184 view->count = 0;
6185 err = got_object_open_as_tree(&subtree, s->repo,
6186 got_tree_entry_get_id(s->selected_entry));
6187 if (err)
6188 break;
6189 err = tree_view_visit_subtree(s, subtree);
6190 if (err) {
6191 got_object_tree_close(subtree);
6192 break;
6194 } else if (S_ISREG(got_tree_entry_get_mode(
6195 s->selected_entry))) {
6196 struct tog_view *blame_view;
6197 int begin_x = view_is_parent_view(view) ?
6198 view_split_begin_x(view->begin_x) : 0;
6200 err = blame_tree_entry(&blame_view, begin_x,
6201 s->selected_entry, &s->parents,
6202 s->commit_id, s->repo);
6203 if (err)
6204 break;
6205 view->count = 0;
6206 view->focussed = 0;
6207 blame_view->focussed = 1;
6208 if (view_is_parent_view(view)) {
6209 err = view_close_child(view);
6210 if (err)
6211 return err;
6212 err = view_set_child(view, blame_view);
6213 if (err)
6214 return err;
6215 view->focus_child = 1;
6216 } else
6217 *new_view = blame_view;
6219 break;
6220 case KEY_RESIZE:
6221 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6222 s->selected = view->nlines - 4;
6223 view->count = 0;
6224 break;
6225 default:
6226 view->count = 0;
6227 break;
6230 return err;
6233 __dead static void
6234 usage_tree(void)
6236 endwin();
6237 fprintf(stderr,
6238 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6239 getprogname());
6240 exit(1);
6243 static const struct got_error *
6244 cmd_tree(int argc, char *argv[])
6246 const struct got_error *error;
6247 struct got_repository *repo = NULL;
6248 struct got_worktree *worktree = NULL;
6249 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6250 struct got_object_id *commit_id = NULL;
6251 struct got_commit_object *commit = NULL;
6252 const char *commit_id_arg = NULL;
6253 char *label = NULL;
6254 struct got_reference *ref = NULL;
6255 const char *head_ref_name = NULL;
6256 int ch;
6257 struct tog_view *view;
6258 int *pack_fds = NULL;
6260 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6261 switch (ch) {
6262 case 'c':
6263 commit_id_arg = optarg;
6264 break;
6265 case 'r':
6266 repo_path = realpath(optarg, NULL);
6267 if (repo_path == NULL)
6268 return got_error_from_errno2("realpath",
6269 optarg);
6270 break;
6271 default:
6272 usage_tree();
6273 /* NOTREACHED */
6277 argc -= optind;
6278 argv += optind;
6280 if (argc > 1)
6281 usage_tree();
6283 error = got_repo_pack_fds_open(&pack_fds);
6284 if (error != NULL)
6285 goto done;
6287 if (repo_path == NULL) {
6288 cwd = getcwd(NULL, 0);
6289 if (cwd == NULL)
6290 return got_error_from_errno("getcwd");
6291 error = got_worktree_open(&worktree, cwd);
6292 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6293 goto done;
6294 if (worktree)
6295 repo_path =
6296 strdup(got_worktree_get_repo_path(worktree));
6297 else
6298 repo_path = strdup(cwd);
6299 if (repo_path == NULL) {
6300 error = got_error_from_errno("strdup");
6301 goto done;
6305 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6306 if (error != NULL)
6307 goto done;
6309 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
6310 repo, worktree);
6311 if (error)
6312 goto done;
6314 init_curses();
6316 error = apply_unveil(got_repo_get_path(repo), NULL);
6317 if (error)
6318 goto done;
6320 error = tog_load_refs(repo, 0);
6321 if (error)
6322 goto done;
6324 if (commit_id_arg == NULL) {
6325 error = got_repo_match_object_id(&commit_id, &label,
6326 worktree ? got_worktree_get_head_ref_name(worktree) :
6327 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6328 if (error)
6329 goto done;
6330 head_ref_name = label;
6331 } else {
6332 error = got_ref_open(&ref, repo, commit_id_arg, 0);
6333 if (error == NULL)
6334 head_ref_name = got_ref_get_name(ref);
6335 else if (error->code != GOT_ERR_NOT_REF)
6336 goto done;
6337 error = got_repo_match_object_id(&commit_id, NULL,
6338 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6339 if (error)
6340 goto done;
6343 error = got_object_open_as_commit(&commit, repo, commit_id);
6344 if (error)
6345 goto done;
6347 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
6348 if (view == NULL) {
6349 error = got_error_from_errno("view_open");
6350 goto done;
6352 error = open_tree_view(view, commit_id, head_ref_name, repo);
6353 if (error)
6354 goto done;
6355 if (!got_path_is_root_dir(in_repo_path)) {
6356 error = tree_view_walk_path(&view->state.tree, commit,
6357 in_repo_path);
6358 if (error)
6359 goto done;
6362 if (worktree) {
6363 /* Release work tree lock. */
6364 got_worktree_close(worktree);
6365 worktree = NULL;
6367 error = view_loop(view);
6368 done:
6369 free(repo_path);
6370 free(cwd);
6371 free(commit_id);
6372 free(label);
6373 if (ref)
6374 got_ref_close(ref);
6375 if (repo) {
6376 const struct got_error *close_err = got_repo_close(repo);
6377 if (error == NULL)
6378 error = close_err;
6380 if (pack_fds) {
6381 const struct got_error *pack_err =
6382 got_repo_pack_fds_close(pack_fds);
6383 if (error == NULL)
6384 error = pack_err;
6386 tog_free_refs();
6387 return error;
6390 static const struct got_error *
6391 ref_view_load_refs(struct tog_ref_view_state *s)
6393 struct got_reflist_entry *sre;
6394 struct tog_reflist_entry *re;
6396 s->nrefs = 0;
6397 TAILQ_FOREACH(sre, &tog_refs, entry) {
6398 if (strncmp(got_ref_get_name(sre->ref),
6399 "refs/got/", 9) == 0 &&
6400 strncmp(got_ref_get_name(sre->ref),
6401 "refs/got/backup/", 16) != 0)
6402 continue;
6404 re = malloc(sizeof(*re));
6405 if (re == NULL)
6406 return got_error_from_errno("malloc");
6408 re->ref = got_ref_dup(sre->ref);
6409 if (re->ref == NULL)
6410 return got_error_from_errno("got_ref_dup");
6411 re->idx = s->nrefs++;
6412 TAILQ_INSERT_TAIL(&s->refs, re, entry);
6415 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6416 return NULL;
6419 void
6420 ref_view_free_refs(struct tog_ref_view_state *s)
6422 struct tog_reflist_entry *re;
6424 while (!TAILQ_EMPTY(&s->refs)) {
6425 re = TAILQ_FIRST(&s->refs);
6426 TAILQ_REMOVE(&s->refs, re, entry);
6427 got_ref_close(re->ref);
6428 free(re);
6432 static const struct got_error *
6433 open_ref_view(struct tog_view *view, struct got_repository *repo)
6435 const struct got_error *err = NULL;
6436 struct tog_ref_view_state *s = &view->state.ref;
6438 s->selected_entry = 0;
6439 s->repo = repo;
6441 TAILQ_INIT(&s->refs);
6442 STAILQ_INIT(&s->colors);
6444 err = ref_view_load_refs(s);
6445 if (err)
6446 return err;
6448 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6449 err = add_color(&s->colors, "^refs/heads/",
6450 TOG_COLOR_REFS_HEADS,
6451 get_color_value("TOG_COLOR_REFS_HEADS"));
6452 if (err)
6453 goto done;
6455 err = add_color(&s->colors, "^refs/tags/",
6456 TOG_COLOR_REFS_TAGS,
6457 get_color_value("TOG_COLOR_REFS_TAGS"));
6458 if (err)
6459 goto done;
6461 err = add_color(&s->colors, "^refs/remotes/",
6462 TOG_COLOR_REFS_REMOTES,
6463 get_color_value("TOG_COLOR_REFS_REMOTES"));
6464 if (err)
6465 goto done;
6467 err = add_color(&s->colors, "^refs/got/backup/",
6468 TOG_COLOR_REFS_BACKUP,
6469 get_color_value("TOG_COLOR_REFS_BACKUP"));
6470 if (err)
6471 goto done;
6474 view->show = show_ref_view;
6475 view->input = input_ref_view;
6476 view->close = close_ref_view;
6477 view->search_start = search_start_ref_view;
6478 view->search_next = search_next_ref_view;
6479 done:
6480 if (err)
6481 free_colors(&s->colors);
6482 return err;
6485 static const struct got_error *
6486 close_ref_view(struct tog_view *view)
6488 struct tog_ref_view_state *s = &view->state.ref;
6490 ref_view_free_refs(s);
6491 free_colors(&s->colors);
6493 return NULL;
6496 static const struct got_error *
6497 resolve_reflist_entry(struct got_object_id **commit_id,
6498 struct tog_reflist_entry *re, struct got_repository *repo)
6500 const struct got_error *err = NULL;
6501 struct got_object_id *obj_id;
6502 struct got_tag_object *tag = NULL;
6503 int obj_type;
6505 *commit_id = NULL;
6507 err = got_ref_resolve(&obj_id, repo, re->ref);
6508 if (err)
6509 return err;
6511 err = got_object_get_type(&obj_type, repo, obj_id);
6512 if (err)
6513 goto done;
6515 switch (obj_type) {
6516 case GOT_OBJ_TYPE_COMMIT:
6517 *commit_id = obj_id;
6518 break;
6519 case GOT_OBJ_TYPE_TAG:
6520 err = got_object_open_as_tag(&tag, repo, obj_id);
6521 if (err)
6522 goto done;
6523 free(obj_id);
6524 err = got_object_get_type(&obj_type, repo,
6525 got_object_tag_get_object_id(tag));
6526 if (err)
6527 goto done;
6528 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
6529 err = got_error(GOT_ERR_OBJ_TYPE);
6530 goto done;
6532 *commit_id = got_object_id_dup(
6533 got_object_tag_get_object_id(tag));
6534 if (*commit_id == NULL) {
6535 err = got_error_from_errno("got_object_id_dup");
6536 goto done;
6538 break;
6539 default:
6540 err = got_error(GOT_ERR_OBJ_TYPE);
6541 break;
6544 done:
6545 if (tag)
6546 got_object_tag_close(tag);
6547 if (err) {
6548 free(*commit_id);
6549 *commit_id = NULL;
6551 return err;
6554 static const struct got_error *
6555 log_ref_entry(struct tog_view **new_view, int begin_x,
6556 struct tog_reflist_entry *re, struct got_repository *repo)
6558 struct tog_view *log_view;
6559 const struct got_error *err = NULL;
6560 struct got_object_id *commit_id = NULL;
6562 *new_view = NULL;
6564 err = resolve_reflist_entry(&commit_id, re, repo);
6565 if (err) {
6566 if (err->code != GOT_ERR_OBJ_TYPE)
6567 return err;
6568 else
6569 return NULL;
6572 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
6573 if (log_view == NULL) {
6574 err = got_error_from_errno("view_open");
6575 goto done;
6578 err = open_log_view(log_view, commit_id, repo,
6579 got_ref_get_name(re->ref), "", 0);
6580 done:
6581 if (err)
6582 view_close(log_view);
6583 else
6584 *new_view = log_view;
6585 free(commit_id);
6586 return err;
6589 static void
6590 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
6592 struct tog_reflist_entry *re;
6593 int i = 0;
6595 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
6596 return;
6598 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
6599 while (i++ < maxscroll) {
6600 if (re == NULL)
6601 break;
6602 s->first_displayed_entry = re;
6603 re = TAILQ_PREV(re, tog_reflist_head, entry);
6607 static void
6608 ref_scroll_down(struct tog_ref_view_state *s, int maxscroll)
6610 struct tog_reflist_entry *next, *last;
6611 int n = 0;
6613 if (s->first_displayed_entry)
6614 next = TAILQ_NEXT(s->first_displayed_entry, entry);
6615 else
6616 next = TAILQ_FIRST(&s->refs);
6618 last = s->last_displayed_entry;
6619 while (next && last && n++ < maxscroll) {
6620 last = TAILQ_NEXT(last, entry);
6621 if (last) {
6622 s->first_displayed_entry = next;
6623 next = TAILQ_NEXT(next, entry);
6628 static const struct got_error *
6629 search_start_ref_view(struct tog_view *view)
6631 struct tog_ref_view_state *s = &view->state.ref;
6633 s->matched_entry = NULL;
6634 return NULL;
6637 static int
6638 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
6640 regmatch_t regmatch;
6642 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
6643 0) == 0;
6646 static const struct got_error *
6647 search_next_ref_view(struct tog_view *view)
6649 struct tog_ref_view_state *s = &view->state.ref;
6650 struct tog_reflist_entry *re = NULL;
6652 if (!view->searching) {
6653 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6654 return NULL;
6657 if (s->matched_entry) {
6658 if (view->searching == TOG_SEARCH_FORWARD) {
6659 if (s->selected_entry)
6660 re = TAILQ_NEXT(s->selected_entry, entry);
6661 else
6662 re = TAILQ_PREV(s->selected_entry,
6663 tog_reflist_head, entry);
6664 } else {
6665 if (s->selected_entry == NULL)
6666 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6667 else
6668 re = TAILQ_PREV(s->selected_entry,
6669 tog_reflist_head, entry);
6671 } else {
6672 if (s->selected_entry)
6673 re = s->selected_entry;
6674 else if (view->searching == TOG_SEARCH_FORWARD)
6675 re = TAILQ_FIRST(&s->refs);
6676 else
6677 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6680 while (1) {
6681 if (re == NULL) {
6682 if (s->matched_entry == NULL) {
6683 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6684 return NULL;
6686 if (view->searching == TOG_SEARCH_FORWARD)
6687 re = TAILQ_FIRST(&s->refs);
6688 else
6689 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6692 if (match_reflist_entry(re, &view->regex)) {
6693 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6694 s->matched_entry = re;
6695 break;
6698 if (view->searching == TOG_SEARCH_FORWARD)
6699 re = TAILQ_NEXT(re, entry);
6700 else
6701 re = TAILQ_PREV(re, tog_reflist_head, entry);
6704 if (s->matched_entry) {
6705 s->first_displayed_entry = s->matched_entry;
6706 s->selected = 0;
6709 return NULL;
6712 static const struct got_error *
6713 show_ref_view(struct tog_view *view)
6715 const struct got_error *err = NULL;
6716 struct tog_ref_view_state *s = &view->state.ref;
6717 struct tog_reflist_entry *re;
6718 char *line = NULL;
6719 wchar_t *wline;
6720 struct tog_color *tc;
6721 int width, n;
6722 int limit = view->nlines;
6724 werase(view->window);
6726 s->ndisplayed = 0;
6728 if (limit == 0)
6729 return NULL;
6731 re = s->first_displayed_entry;
6733 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
6734 s->nrefs) == -1)
6735 return got_error_from_errno("asprintf");
6737 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6738 if (err) {
6739 free(line);
6740 return err;
6742 if (view_needs_focus_indication(view))
6743 wstandout(view->window);
6744 waddwstr(view->window, wline);
6745 if (view_needs_focus_indication(view))
6746 wstandend(view->window);
6747 free(wline);
6748 wline = NULL;
6749 free(line);
6750 line = NULL;
6751 if (width < view->ncols - 1)
6752 waddch(view->window, '\n');
6753 if (--limit <= 0)
6754 return NULL;
6756 n = 0;
6757 while (re && limit > 0) {
6758 char *line = NULL;
6759 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
6761 if (s->show_date) {
6762 struct got_commit_object *ci;
6763 struct got_tag_object *tag;
6764 struct got_object_id *id;
6765 struct tm tm;
6766 time_t t;
6768 err = got_ref_resolve(&id, s->repo, re->ref);
6769 if (err)
6770 return err;
6771 err = got_object_open_as_tag(&tag, s->repo, id);
6772 if (err) {
6773 if (err->code != GOT_ERR_OBJ_TYPE) {
6774 free(id);
6775 return err;
6777 err = got_object_open_as_commit(&ci, s->repo,
6778 id);
6779 if (err) {
6780 free(id);
6781 return err;
6783 t = got_object_commit_get_committer_time(ci);
6784 got_object_commit_close(ci);
6785 } else {
6786 t = got_object_tag_get_tagger_time(tag);
6787 got_object_tag_close(tag);
6789 free(id);
6790 if (gmtime_r(&t, &tm) == NULL)
6791 return got_error_from_errno("gmtime_r");
6792 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
6793 return got_error(GOT_ERR_NO_SPACE);
6795 if (got_ref_is_symbolic(re->ref)) {
6796 if (asprintf(&line, "%s%s -> %s", s->show_date ?
6797 ymd : "", got_ref_get_name(re->ref),
6798 got_ref_get_symref_target(re->ref)) == -1)
6799 return got_error_from_errno("asprintf");
6800 } else if (s->show_ids) {
6801 struct got_object_id *id;
6802 char *id_str;
6803 err = got_ref_resolve(&id, s->repo, re->ref);
6804 if (err)
6805 return err;
6806 err = got_object_id_str(&id_str, id);
6807 if (err) {
6808 free(id);
6809 return err;
6811 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
6812 got_ref_get_name(re->ref), id_str) == -1) {
6813 err = got_error_from_errno("asprintf");
6814 free(id);
6815 free(id_str);
6816 return err;
6818 free(id);
6819 free(id_str);
6820 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
6821 got_ref_get_name(re->ref)) == -1)
6822 return got_error_from_errno("asprintf");
6824 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6825 0, 0);
6826 if (err) {
6827 free(line);
6828 return err;
6830 if (n == s->selected) {
6831 if (view->focussed)
6832 wstandout(view->window);
6833 s->selected_entry = re;
6835 tc = match_color(&s->colors, got_ref_get_name(re->ref));
6836 if (tc)
6837 wattr_on(view->window,
6838 COLOR_PAIR(tc->colorpair), NULL);
6839 waddwstr(view->window, wline);
6840 if (tc)
6841 wattr_off(view->window,
6842 COLOR_PAIR(tc->colorpair), NULL);
6843 if (width < view->ncols - 1)
6844 waddch(view->window, '\n');
6845 if (n == s->selected && view->focussed)
6846 wstandend(view->window);
6847 free(line);
6848 free(wline);
6849 wline = NULL;
6850 n++;
6851 s->ndisplayed++;
6852 s->last_displayed_entry = re;
6854 limit--;
6855 re = TAILQ_NEXT(re, entry);
6858 view_vborder(view);
6859 return err;
6862 static const struct got_error *
6863 browse_ref_tree(struct tog_view **new_view, int begin_x,
6864 struct tog_reflist_entry *re, struct got_repository *repo)
6866 const struct got_error *err = NULL;
6867 struct got_object_id *commit_id = NULL;
6868 struct tog_view *tree_view;
6870 *new_view = NULL;
6872 err = resolve_reflist_entry(&commit_id, re, repo);
6873 if (err) {
6874 if (err->code != GOT_ERR_OBJ_TYPE)
6875 return err;
6876 else
6877 return NULL;
6881 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
6882 if (tree_view == NULL) {
6883 err = got_error_from_errno("view_open");
6884 goto done;
6887 err = open_tree_view(tree_view, commit_id,
6888 got_ref_get_name(re->ref), repo);
6889 if (err)
6890 goto done;
6892 *new_view = tree_view;
6893 done:
6894 free(commit_id);
6895 return err;
6897 static const struct got_error *
6898 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
6900 const struct got_error *err = NULL;
6901 struct tog_ref_view_state *s = &view->state.ref;
6902 struct tog_view *log_view, *tree_view;
6903 struct tog_reflist_entry *re;
6904 int begin_x = 0, n, nscroll = view->nlines - 1;
6906 switch (ch) {
6907 case 'i':
6908 s->show_ids = !s->show_ids;
6909 view->count = 0;
6910 break;
6911 case 'm':
6912 s->show_date = !s->show_date;
6913 view->count = 0;
6914 break;
6915 case 'o':
6916 s->sort_by_date = !s->sort_by_date;
6917 view->count = 0;
6918 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
6919 got_ref_cmp_by_commit_timestamp_descending :
6920 tog_ref_cmp_by_name, s->repo);
6921 if (err)
6922 break;
6923 got_reflist_object_id_map_free(tog_refs_idmap);
6924 err = got_reflist_object_id_map_create(&tog_refs_idmap,
6925 &tog_refs, s->repo);
6926 if (err)
6927 break;
6928 ref_view_free_refs(s);
6929 err = ref_view_load_refs(s);
6930 break;
6931 case KEY_ENTER:
6932 case '\r':
6933 view->count = 0;
6934 if (!s->selected_entry)
6935 break;
6936 if (view_is_parent_view(view))
6937 begin_x = view_split_begin_x(view->begin_x);
6938 err = log_ref_entry(&log_view, begin_x, s->selected_entry,
6939 s->repo);
6940 view->focussed = 0;
6941 log_view->focussed = 1;
6942 if (view_is_parent_view(view)) {
6943 err = view_close_child(view);
6944 if (err)
6945 return err;
6946 err = view_set_child(view, log_view);
6947 if (err)
6948 return err;
6949 view->focus_child = 1;
6950 } else
6951 *new_view = log_view;
6952 break;
6953 case 't':
6954 view->count = 0;
6955 if (!s->selected_entry)
6956 break;
6957 if (view_is_parent_view(view))
6958 begin_x = view_split_begin_x(view->begin_x);
6959 err = browse_ref_tree(&tree_view, begin_x, s->selected_entry,
6960 s->repo);
6961 if (err || tree_view == NULL)
6962 break;
6963 view->focussed = 0;
6964 tree_view->focussed = 1;
6965 if (view_is_parent_view(view)) {
6966 err = view_close_child(view);
6967 if (err)
6968 return err;
6969 err = view_set_child(view, tree_view);
6970 if (err)
6971 return err;
6972 view->focus_child = 1;
6973 } else
6974 *new_view = tree_view;
6975 break;
6976 case 'g':
6977 case KEY_HOME:
6978 s->selected = 0;
6979 view->count = 0;
6980 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6981 break;
6982 case 'G':
6983 case KEY_END:
6984 s->selected = 0;
6985 view->count = 0;
6986 re = TAILQ_LAST(&s->refs, tog_reflist_head);
6987 for (n = 0; n < view->nlines - 1; n++) {
6988 if (re == NULL)
6989 break;
6990 s->first_displayed_entry = re;
6991 re = TAILQ_PREV(re, tog_reflist_head, entry);
6993 if (n > 0)
6994 s->selected = n - 1;
6995 break;
6996 case 'k':
6997 case KEY_UP:
6998 case CTRL('p'):
6999 if (s->selected > 0) {
7000 s->selected--;
7001 break;
7003 ref_scroll_up(s, 1);
7004 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7005 view->count = 0;
7006 break;
7007 case CTRL('u'):
7008 case 'u':
7009 nscroll /= 2;
7010 /* FALL THROUGH */
7011 case KEY_PPAGE:
7012 case CTRL('b'):
7013 case 'b':
7014 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7015 s->selected -= MIN(nscroll, s->selected);
7016 ref_scroll_up(s, MAX(0, nscroll));
7017 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7018 view->count = 0;
7019 break;
7020 case 'j':
7021 case KEY_DOWN:
7022 case CTRL('n'):
7023 if (s->selected < s->ndisplayed - 1) {
7024 s->selected++;
7025 break;
7027 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7028 /* can't scroll any further */
7029 view->count = 0;
7030 break;
7032 ref_scroll_down(s, 1);
7033 break;
7034 case CTRL('d'):
7035 case 'd':
7036 nscroll /= 2;
7037 /* FALL THROUGH */
7038 case KEY_NPAGE:
7039 case CTRL('f'):
7040 case 'f':
7041 case ' ':
7042 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7043 /* can't scroll any further; move cursor down */
7044 if (s->selected < s->ndisplayed - 1)
7045 s->selected += MIN(nscroll,
7046 s->ndisplayed - s->selected - 1);
7047 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7048 s->selected += s->ndisplayed - s->selected - 1;
7049 view->count = 0;
7050 break;
7052 ref_scroll_down(s, nscroll);
7053 break;
7054 case CTRL('l'):
7055 view->count = 0;
7056 tog_free_refs();
7057 err = tog_load_refs(s->repo, s->sort_by_date);
7058 if (err)
7059 break;
7060 ref_view_free_refs(s);
7061 err = ref_view_load_refs(s);
7062 break;
7063 case KEY_RESIZE:
7064 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7065 s->selected = view->nlines - 2;
7066 break;
7067 default:
7068 view->count = 0;
7069 break;
7072 return err;
7075 __dead static void
7076 usage_ref(void)
7078 endwin();
7079 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7080 getprogname());
7081 exit(1);
7084 static const struct got_error *
7085 cmd_ref(int argc, char *argv[])
7087 const struct got_error *error;
7088 struct got_repository *repo = NULL;
7089 struct got_worktree *worktree = NULL;
7090 char *cwd = NULL, *repo_path = NULL;
7091 int ch;
7092 struct tog_view *view;
7093 int *pack_fds = NULL;
7095 while ((ch = getopt(argc, argv, "r:")) != -1) {
7096 switch (ch) {
7097 case 'r':
7098 repo_path = realpath(optarg, NULL);
7099 if (repo_path == NULL)
7100 return got_error_from_errno2("realpath",
7101 optarg);
7102 break;
7103 default:
7104 usage_ref();
7105 /* NOTREACHED */
7109 argc -= optind;
7110 argv += optind;
7112 if (argc > 1)
7113 usage_ref();
7115 error = got_repo_pack_fds_open(&pack_fds);
7116 if (error != NULL)
7117 goto done;
7119 if (repo_path == NULL) {
7120 cwd = getcwd(NULL, 0);
7121 if (cwd == NULL)
7122 return got_error_from_errno("getcwd");
7123 error = got_worktree_open(&worktree, cwd);
7124 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7125 goto done;
7126 if (worktree)
7127 repo_path =
7128 strdup(got_worktree_get_repo_path(worktree));
7129 else
7130 repo_path = strdup(cwd);
7131 if (repo_path == NULL) {
7132 error = got_error_from_errno("strdup");
7133 goto done;
7137 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7138 if (error != NULL)
7139 goto done;
7141 init_curses();
7143 error = apply_unveil(got_repo_get_path(repo), NULL);
7144 if (error)
7145 goto done;
7147 error = tog_load_refs(repo, 0);
7148 if (error)
7149 goto done;
7151 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7152 if (view == NULL) {
7153 error = got_error_from_errno("view_open");
7154 goto done;
7157 error = open_ref_view(view, repo);
7158 if (error)
7159 goto done;
7161 if (worktree) {
7162 /* Release work tree lock. */
7163 got_worktree_close(worktree);
7164 worktree = NULL;
7166 error = view_loop(view);
7167 done:
7168 free(repo_path);
7169 free(cwd);
7170 if (repo) {
7171 const struct got_error *close_err = got_repo_close(repo);
7172 if (close_err)
7173 error = close_err;
7175 if (pack_fds) {
7176 const struct got_error *pack_err =
7177 got_repo_pack_fds_close(pack_fds);
7178 if (error == NULL)
7179 error = pack_err;
7181 tog_free_refs();
7182 return error;
7185 static void
7186 list_commands(FILE *fp)
7188 size_t i;
7190 fprintf(fp, "commands:");
7191 for (i = 0; i < nitems(tog_commands); i++) {
7192 const struct tog_cmd *cmd = &tog_commands[i];
7193 fprintf(fp, " %s", cmd->name);
7195 fputc('\n', fp);
7198 __dead static void
7199 usage(int hflag, int status)
7201 FILE *fp = (status == 0) ? stdout : stderr;
7203 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
7204 getprogname());
7205 if (hflag) {
7206 fprintf(fp, "lazy usage: %s path\n", getprogname());
7207 list_commands(fp);
7209 exit(status);
7212 static char **
7213 make_argv(int argc, ...)
7215 va_list ap;
7216 char **argv;
7217 int i;
7219 va_start(ap, argc);
7221 argv = calloc(argc, sizeof(char *));
7222 if (argv == NULL)
7223 err(1, "calloc");
7224 for (i = 0; i < argc; i++) {
7225 argv[i] = strdup(va_arg(ap, char *));
7226 if (argv[i] == NULL)
7227 err(1, "strdup");
7230 va_end(ap);
7231 return argv;
7235 * Try to convert 'tog path' into a 'tog log path' command.
7236 * The user could simply have mistyped the command rather than knowingly
7237 * provided a path. So check whether argv[0] can in fact be resolved
7238 * to a path in the HEAD commit and print a special error if not.
7239 * This hack is for mpi@ <3
7241 static const struct got_error *
7242 tog_log_with_path(int argc, char *argv[])
7244 const struct got_error *error = NULL, *close_err;
7245 const struct tog_cmd *cmd = NULL;
7246 struct got_repository *repo = NULL;
7247 struct got_worktree *worktree = NULL;
7248 struct got_object_id *commit_id = NULL, *id = NULL;
7249 struct got_commit_object *commit = NULL;
7250 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7251 char *commit_id_str = NULL, **cmd_argv = NULL;
7252 int *pack_fds = NULL;
7254 cwd = getcwd(NULL, 0);
7255 if (cwd == NULL)
7256 return got_error_from_errno("getcwd");
7258 error = got_repo_pack_fds_open(&pack_fds);
7259 if (error != NULL)
7260 goto done;
7262 error = got_worktree_open(&worktree, cwd);
7263 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7264 goto done;
7266 if (worktree)
7267 repo_path = strdup(got_worktree_get_repo_path(worktree));
7268 else
7269 repo_path = strdup(cwd);
7270 if (repo_path == NULL) {
7271 error = got_error_from_errno("strdup");
7272 goto done;
7275 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7276 if (error != NULL)
7277 goto done;
7279 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7280 repo, worktree);
7281 if (error)
7282 goto done;
7284 error = tog_load_refs(repo, 0);
7285 if (error)
7286 goto done;
7287 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
7288 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
7289 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7290 if (error)
7291 goto done;
7293 if (worktree) {
7294 got_worktree_close(worktree);
7295 worktree = NULL;
7298 error = got_object_open_as_commit(&commit, repo, commit_id);
7299 if (error)
7300 goto done;
7302 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
7303 if (error) {
7304 if (error->code != GOT_ERR_NO_TREE_ENTRY)
7305 goto done;
7306 fprintf(stderr, "%s: '%s' is no known command or path\n",
7307 getprogname(), argv[0]);
7308 usage(1, 1);
7309 /* not reached */
7312 close_err = got_repo_close(repo);
7313 if (error == NULL)
7314 error = close_err;
7315 repo = NULL;
7317 error = got_object_id_str(&commit_id_str, commit_id);
7318 if (error)
7319 goto done;
7321 cmd = &tog_commands[0]; /* log */
7322 argc = 4;
7323 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
7324 error = cmd->cmd_main(argc, cmd_argv);
7325 done:
7326 if (repo) {
7327 close_err = got_repo_close(repo);
7328 if (error == NULL)
7329 error = close_err;
7331 if (commit)
7332 got_object_commit_close(commit);
7333 if (worktree)
7334 got_worktree_close(worktree);
7335 if (pack_fds) {
7336 const struct got_error *pack_err =
7337 got_repo_pack_fds_close(pack_fds);
7338 if (error == NULL)
7339 error = pack_err;
7341 free(id);
7342 free(commit_id_str);
7343 free(commit_id);
7344 free(cwd);
7345 free(repo_path);
7346 free(in_repo_path);
7347 if (cmd_argv) {
7348 int i;
7349 for (i = 0; i < argc; i++)
7350 free(cmd_argv[i]);
7351 free(cmd_argv);
7353 tog_free_refs();
7354 return error;
7357 int
7358 main(int argc, char *argv[])
7360 const struct got_error *error = NULL;
7361 const struct tog_cmd *cmd = NULL;
7362 int ch, hflag = 0, Vflag = 0;
7363 char **cmd_argv = NULL;
7364 static const struct option longopts[] = {
7365 { "version", no_argument, NULL, 'V' },
7366 { NULL, 0, NULL, 0}
7369 setlocale(LC_CTYPE, "");
7371 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
7372 switch (ch) {
7373 case 'h':
7374 hflag = 1;
7375 break;
7376 case 'V':
7377 Vflag = 1;
7378 break;
7379 default:
7380 usage(hflag, 1);
7381 /* NOTREACHED */
7385 argc -= optind;
7386 argv += optind;
7387 optind = 1;
7388 optreset = 1;
7390 if (Vflag) {
7391 got_version_print_str();
7392 return 0;
7395 #ifndef PROFILE
7396 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
7397 NULL) == -1)
7398 err(1, "pledge");
7399 #endif
7401 if (argc == 0) {
7402 if (hflag)
7403 usage(hflag, 0);
7404 /* Build an argument vector which runs a default command. */
7405 cmd = &tog_commands[0];
7406 argc = 1;
7407 cmd_argv = make_argv(argc, cmd->name);
7408 } else {
7409 size_t i;
7411 /* Did the user specify a command? */
7412 for (i = 0; i < nitems(tog_commands); i++) {
7413 if (strncmp(tog_commands[i].name, argv[0],
7414 strlen(argv[0])) == 0) {
7415 cmd = &tog_commands[i];
7416 break;
7421 if (cmd == NULL) {
7422 if (argc != 1)
7423 usage(0, 1);
7424 /* No command specified; try log with a path */
7425 error = tog_log_with_path(argc, argv);
7426 } else {
7427 if (hflag)
7428 cmd->cmd_usage();
7429 else
7430 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
7433 endwin();
7434 putchar('\n');
7435 if (cmd_argv) {
7436 int i;
7437 for (i = 0; i < argc; i++)
7438 free(cmd_argv[i]);
7439 free(cmd_argv);
7442 if (error && error->code != GOT_ERR_CANCELLED)
7443 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7444 return 0;