Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <getopt.h>
33 #include <string.h>
34 #include <err.h>
35 #include <unistd.h>
36 #include <limits.h>
37 #include <wchar.h>
38 #include <time.h>
39 #include <pthread.h>
40 #include <libgen.h>
41 #include <regex.h>
42 #include <sched.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_diff.h"
50 #include "got_opentemp.h"
51 #include "got_utf8.h"
52 #include "got_cancel.h"
53 #include "got_commit_graph.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_path.h"
57 #include "got_worktree.h"
59 #ifndef MIN
60 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
61 #endif
63 #ifndef MAX
64 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
65 #endif
67 #define CTRL(x) ((x) & 0x1f)
69 #ifndef nitems
70 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
71 #endif
73 struct tog_cmd {
74 const char *name;
75 const struct got_error *(*cmd_main)(int, char *[]);
76 void (*cmd_usage)(void);
77 };
79 __dead static void usage(int, int);
80 __dead static void usage_log(void);
81 __dead static void usage_diff(void);
82 __dead static void usage_blame(void);
83 __dead static void usage_tree(void);
84 __dead static void usage_ref(void);
86 static const struct got_error* cmd_log(int, char *[]);
87 static const struct got_error* cmd_diff(int, char *[]);
88 static const struct got_error* cmd_blame(int, char *[]);
89 static const struct got_error* cmd_tree(int, char *[]);
90 static const struct got_error* cmd_ref(int, char *[]);
92 static const struct tog_cmd tog_commands[] = {
93 { "log", cmd_log, usage_log },
94 { "diff", cmd_diff, usage_diff },
95 { "blame", cmd_blame, usage_blame },
96 { "tree", cmd_tree, usage_tree },
97 { "ref", cmd_ref, usage_ref },
98 };
100 enum tog_view_type {
101 TOG_VIEW_DIFF,
102 TOG_VIEW_LOG,
103 TOG_VIEW_BLAME,
104 TOG_VIEW_TREE,
105 TOG_VIEW_REF,
106 };
108 enum tog_view_mode {
109 TOG_VIEW_SPLIT_NONE,
110 TOG_VIEW_SPLIT_VERT,
111 TOG_VIEW_SPLIT_HRZN
112 };
114 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
116 #define TOG_EOF_STRING "(END)"
118 struct commit_queue_entry {
119 TAILQ_ENTRY(commit_queue_entry) entry;
120 struct got_object_id *id;
121 struct got_commit_object *commit;
122 int idx;
123 };
124 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
125 struct commit_queue {
126 int ncommits;
127 struct commit_queue_head head;
128 };
130 struct tog_color {
131 STAILQ_ENTRY(tog_color) entry;
132 regex_t regex;
133 short colorpair;
134 };
135 STAILQ_HEAD(tog_colors, tog_color);
137 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
138 static struct got_reflist_object_id_map *tog_refs_idmap;
140 static const struct got_error *
141 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
142 struct got_reference* re2)
144 const char *name1 = got_ref_get_name(re1);
145 const char *name2 = got_ref_get_name(re2);
146 int isbackup1, isbackup2;
148 /* Sort backup refs towards the bottom of the list. */
149 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
150 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
151 if (!isbackup1 && isbackup2) {
152 *cmp = -1;
153 return NULL;
154 } else if (isbackup1 && !isbackup2) {
155 *cmp = 1;
156 return NULL;
159 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
160 return NULL;
163 static const struct got_error *
164 tog_load_refs(struct got_repository *repo, int sort_by_date)
166 const struct got_error *err;
168 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
169 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
170 repo);
171 if (err)
172 return err;
174 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
175 repo);
178 static void
179 tog_free_refs(void)
181 if (tog_refs_idmap) {
182 got_reflist_object_id_map_free(tog_refs_idmap);
183 tog_refs_idmap = NULL;
185 got_ref_list_free(&tog_refs);
188 static const struct got_error *
189 add_color(struct tog_colors *colors, const char *pattern,
190 int idx, short color)
192 const struct got_error *err = NULL;
193 struct tog_color *tc;
194 int regerr = 0;
196 if (idx < 1 || idx > COLOR_PAIRS - 1)
197 return NULL;
199 init_pair(idx, color, -1);
201 tc = calloc(1, sizeof(*tc));
202 if (tc == NULL)
203 return got_error_from_errno("calloc");
204 regerr = regcomp(&tc->regex, pattern,
205 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
206 if (regerr) {
207 static char regerr_msg[512];
208 static char err_msg[512];
209 regerror(regerr, &tc->regex, regerr_msg,
210 sizeof(regerr_msg));
211 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
212 regerr_msg);
213 err = got_error_msg(GOT_ERR_REGEX, err_msg);
214 free(tc);
215 return err;
217 tc->colorpair = idx;
218 STAILQ_INSERT_HEAD(colors, tc, entry);
219 return NULL;
222 static void
223 free_colors(struct tog_colors *colors)
225 struct tog_color *tc;
227 while (!STAILQ_EMPTY(colors)) {
228 tc = STAILQ_FIRST(colors);
229 STAILQ_REMOVE_HEAD(colors, entry);
230 regfree(&tc->regex);
231 free(tc);
235 static struct tog_color *
236 get_color(struct tog_colors *colors, int colorpair)
238 struct tog_color *tc = NULL;
240 STAILQ_FOREACH(tc, colors, entry) {
241 if (tc->colorpair == colorpair)
242 return tc;
245 return NULL;
248 static int
249 default_color_value(const char *envvar)
251 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
252 return COLOR_MAGENTA;
253 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
254 return COLOR_CYAN;
255 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
256 return COLOR_YELLOW;
257 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
258 return COLOR_GREEN;
259 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
260 return COLOR_MAGENTA;
261 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
262 return COLOR_MAGENTA;
263 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
264 return COLOR_CYAN;
265 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
266 return COLOR_GREEN;
267 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
268 return COLOR_GREEN;
269 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
270 return COLOR_CYAN;
271 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
272 return COLOR_YELLOW;
273 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
274 return COLOR_GREEN;
275 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
276 return COLOR_MAGENTA;
277 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
278 return COLOR_YELLOW;
279 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
280 return COLOR_CYAN;
282 return -1;
285 static int
286 get_color_value(const char *envvar)
288 const char *val = getenv(envvar);
290 if (val == NULL)
291 return default_color_value(envvar);
293 if (strcasecmp(val, "black") == 0)
294 return COLOR_BLACK;
295 if (strcasecmp(val, "red") == 0)
296 return COLOR_RED;
297 if (strcasecmp(val, "green") == 0)
298 return COLOR_GREEN;
299 if (strcasecmp(val, "yellow") == 0)
300 return COLOR_YELLOW;
301 if (strcasecmp(val, "blue") == 0)
302 return COLOR_BLUE;
303 if (strcasecmp(val, "magenta") == 0)
304 return COLOR_MAGENTA;
305 if (strcasecmp(val, "cyan") == 0)
306 return COLOR_CYAN;
307 if (strcasecmp(val, "white") == 0)
308 return COLOR_WHITE;
309 if (strcasecmp(val, "default") == 0)
310 return -1;
312 return default_color_value(envvar);
316 struct tog_diff_view_state {
317 struct got_object_id *id1, *id2;
318 const char *label1, *label2;
319 FILE *f, *f1, *f2;
320 int fd1, fd2;
321 int first_displayed_line;
322 int last_displayed_line;
323 int eof;
324 enum got_diff_algorithm diff_algo;
325 int diff_context;
326 int ignore_whitespace;
327 int force_text_diff;
328 struct got_repository *repo;
329 struct tog_colors colors;
330 size_t nlines;
331 off_t *line_offsets;
332 int matched_line;
333 int selected_line;
335 /* passed from log view; may be NULL */
336 struct tog_view *log_view;
337 };
339 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
341 struct tog_log_thread_args {
342 pthread_cond_t need_commits;
343 pthread_cond_t commit_loaded;
344 int commits_needed;
345 int load_all;
346 struct got_commit_graph *graph;
347 struct commit_queue *commits;
348 const char *in_repo_path;
349 struct got_object_id *start_id;
350 struct got_repository *repo;
351 int *pack_fds;
352 int log_complete;
353 sig_atomic_t *quit;
354 struct commit_queue_entry **first_displayed_entry;
355 struct commit_queue_entry **selected_entry;
356 int *searching;
357 int *search_next_done;
358 regex_t *regex;
359 };
361 struct tog_log_view_state {
362 struct commit_queue commits;
363 struct commit_queue_entry *first_displayed_entry;
364 struct commit_queue_entry *last_displayed_entry;
365 struct commit_queue_entry *selected_entry;
366 int selected;
367 char *in_repo_path;
368 char *head_ref_name;
369 int log_branches;
370 struct got_repository *repo;
371 struct got_object_id *start_id;
372 sig_atomic_t quit;
373 pthread_t thread;
374 struct tog_log_thread_args thread_args;
375 struct commit_queue_entry *matched_entry;
376 struct commit_queue_entry *search_entry;
377 struct tog_colors colors;
378 };
380 #define TOG_COLOR_DIFF_MINUS 1
381 #define TOG_COLOR_DIFF_PLUS 2
382 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
383 #define TOG_COLOR_DIFF_META 4
384 #define TOG_COLOR_TREE_SUBMODULE 5
385 #define TOG_COLOR_TREE_SYMLINK 6
386 #define TOG_COLOR_TREE_DIRECTORY 7
387 #define TOG_COLOR_TREE_EXECUTABLE 8
388 #define TOG_COLOR_COMMIT 9
389 #define TOG_COLOR_AUTHOR 10
390 #define TOG_COLOR_DATE 11
391 #define TOG_COLOR_REFS_HEADS 12
392 #define TOG_COLOR_REFS_TAGS 13
393 #define TOG_COLOR_REFS_REMOTES 14
394 #define TOG_COLOR_REFS_BACKUP 15
396 struct tog_blame_cb_args {
397 struct tog_blame_line *lines; /* one per line */
398 int nlines;
400 struct tog_view *view;
401 struct got_object_id *commit_id;
402 int *quit;
403 };
405 struct tog_blame_thread_args {
406 const char *path;
407 struct got_repository *repo;
408 struct tog_blame_cb_args *cb_args;
409 int *complete;
410 got_cancel_cb cancel_cb;
411 void *cancel_arg;
412 };
414 struct tog_blame {
415 FILE *f;
416 off_t filesize;
417 struct tog_blame_line *lines;
418 int nlines;
419 off_t *line_offsets;
420 pthread_t thread;
421 struct tog_blame_thread_args thread_args;
422 struct tog_blame_cb_args cb_args;
423 const char *path;
424 int *pack_fds;
425 };
427 struct tog_blame_view_state {
428 int first_displayed_line;
429 int last_displayed_line;
430 int selected_line;
431 int blame_complete;
432 int eof;
433 int done;
434 struct got_object_id_queue blamed_commits;
435 struct got_object_qid *blamed_commit;
436 char *path;
437 struct got_repository *repo;
438 struct got_object_id *commit_id;
439 struct tog_blame blame;
440 int matched_line;
441 struct tog_colors colors;
442 };
444 struct tog_parent_tree {
445 TAILQ_ENTRY(tog_parent_tree) entry;
446 struct got_tree_object *tree;
447 struct got_tree_entry *first_displayed_entry;
448 struct got_tree_entry *selected_entry;
449 int selected;
450 };
452 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
454 struct tog_tree_view_state {
455 char *tree_label;
456 struct got_object_id *commit_id;/* commit which this tree belongs to */
457 struct got_tree_object *root; /* the commit's root tree entry */
458 struct got_tree_object *tree; /* currently displayed (sub-)tree */
459 struct got_tree_entry *first_displayed_entry;
460 struct got_tree_entry *last_displayed_entry;
461 struct got_tree_entry *selected_entry;
462 int ndisplayed, selected, show_ids;
463 struct tog_parent_trees parents; /* parent trees of current sub-tree */
464 char *head_ref_name;
465 struct got_repository *repo;
466 struct got_tree_entry *matched_entry;
467 struct tog_colors colors;
468 };
470 struct tog_reflist_entry {
471 TAILQ_ENTRY(tog_reflist_entry) entry;
472 struct got_reference *ref;
473 int idx;
474 };
476 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
478 struct tog_ref_view_state {
479 struct tog_reflist_head refs;
480 struct tog_reflist_entry *first_displayed_entry;
481 struct tog_reflist_entry *last_displayed_entry;
482 struct tog_reflist_entry *selected_entry;
483 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
484 struct got_repository *repo;
485 struct tog_reflist_entry *matched_entry;
486 struct tog_colors colors;
487 };
489 /*
490 * We implement two types of views: parent views and child views.
492 * The 'Tab' key switches focus between a parent view and its child view.
493 * Child views are shown side-by-side to their parent view, provided
494 * there is enough screen estate.
496 * When a new view is opened from within a parent view, this new view
497 * becomes a child view of the parent view, replacing any existing child.
499 * When a new view is opened from within a child view, this new view
500 * becomes a parent view which will obscure the views below until the
501 * user quits the new parent view by typing 'q'.
503 * This list of views contains parent views only.
504 * Child views are only pointed to by their parent view.
505 */
506 TAILQ_HEAD(tog_view_list_head, tog_view);
508 struct tog_view {
509 TAILQ_ENTRY(tog_view) entry;
510 WINDOW *window;
511 PANEL *panel;
512 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
513 int maxx, x; /* max column and current start column */
514 int lines, cols; /* copies of LINES and COLS */
515 int nscrolled, offset; /* lines scrolled and hsplit line offset */
516 int ch, count; /* current keymap and count prefix */
517 int focussed; /* Only set on one parent or child view at a time. */
518 int dying;
519 struct tog_view *parent;
520 struct tog_view *child;
522 /*
523 * This flag is initially set on parent views when a new child view
524 * is created. It gets toggled when the 'Tab' key switches focus
525 * between parent and child.
526 * The flag indicates whether focus should be passed on to our child
527 * view if this parent view gets picked for focus after another parent
528 * view was closed. This prevents child views from losing focus in such
529 * situations.
530 */
531 int focus_child;
533 enum tog_view_mode mode;
534 /* type-specific state */
535 enum tog_view_type type;
536 union {
537 struct tog_diff_view_state diff;
538 struct tog_log_view_state log;
539 struct tog_blame_view_state blame;
540 struct tog_tree_view_state tree;
541 struct tog_ref_view_state ref;
542 } state;
544 const struct got_error *(*show)(struct tog_view *);
545 const struct got_error *(*input)(struct tog_view **,
546 struct tog_view *, int);
547 const struct got_error *(*close)(struct tog_view *);
549 const struct got_error *(*search_start)(struct tog_view *);
550 const struct got_error *(*search_next)(struct tog_view *);
551 int search_started;
552 int searching;
553 #define TOG_SEARCH_FORWARD 1
554 #define TOG_SEARCH_BACKWARD 2
555 int search_next_done;
556 #define TOG_SEARCH_HAVE_MORE 1
557 #define TOG_SEARCH_NO_MORE 2
558 #define TOG_SEARCH_HAVE_NONE 3
559 regex_t regex;
560 regmatch_t regmatch;
561 };
563 static const struct got_error *open_diff_view(struct tog_view *,
564 struct got_object_id *, struct got_object_id *,
565 const char *, const char *, int, int, int, struct tog_view *,
566 struct got_repository *);
567 static const struct got_error *show_diff_view(struct tog_view *);
568 static const struct got_error *input_diff_view(struct tog_view **,
569 struct tog_view *, int);
570 static const struct got_error* close_diff_view(struct tog_view *);
571 static const struct got_error *search_start_diff_view(struct tog_view *);
572 static const struct got_error *search_next_diff_view(struct tog_view *);
574 static const struct got_error *open_log_view(struct tog_view *,
575 struct got_object_id *, struct got_repository *,
576 const char *, const char *, int);
577 static const struct got_error * show_log_view(struct tog_view *);
578 static const struct got_error *input_log_view(struct tog_view **,
579 struct tog_view *, int);
580 static const struct got_error *close_log_view(struct tog_view *);
581 static const struct got_error *search_start_log_view(struct tog_view *);
582 static const struct got_error *search_next_log_view(struct tog_view *);
584 static const struct got_error *open_blame_view(struct tog_view *, char *,
585 struct got_object_id *, struct got_repository *);
586 static const struct got_error *show_blame_view(struct tog_view *);
587 static const struct got_error *input_blame_view(struct tog_view **,
588 struct tog_view *, int);
589 static const struct got_error *close_blame_view(struct tog_view *);
590 static const struct got_error *search_start_blame_view(struct tog_view *);
591 static const struct got_error *search_next_blame_view(struct tog_view *);
593 static const struct got_error *open_tree_view(struct tog_view *,
594 struct got_object_id *, const char *, struct got_repository *);
595 static const struct got_error *show_tree_view(struct tog_view *);
596 static const struct got_error *input_tree_view(struct tog_view **,
597 struct tog_view *, int);
598 static const struct got_error *close_tree_view(struct tog_view *);
599 static const struct got_error *search_start_tree_view(struct tog_view *);
600 static const struct got_error *search_next_tree_view(struct tog_view *);
602 static const struct got_error *open_ref_view(struct tog_view *,
603 struct got_repository *);
604 static const struct got_error *show_ref_view(struct tog_view *);
605 static const struct got_error *input_ref_view(struct tog_view **,
606 struct tog_view *, int);
607 static const struct got_error *close_ref_view(struct tog_view *);
608 static const struct got_error *search_start_ref_view(struct tog_view *);
609 static const struct got_error *search_next_ref_view(struct tog_view *);
611 static volatile sig_atomic_t tog_sigwinch_received;
612 static volatile sig_atomic_t tog_sigpipe_received;
613 static volatile sig_atomic_t tog_sigcont_received;
614 static volatile sig_atomic_t tog_sigint_received;
615 static volatile sig_atomic_t tog_sigterm_received;
617 static void
618 tog_sigwinch(int signo)
620 tog_sigwinch_received = 1;
623 static void
624 tog_sigpipe(int signo)
626 tog_sigpipe_received = 1;
629 static void
630 tog_sigcont(int signo)
632 tog_sigcont_received = 1;
635 static void
636 tog_sigint(int signo)
638 tog_sigint_received = 1;
641 static void
642 tog_sigterm(int signo)
644 tog_sigterm_received = 1;
647 static int
648 tog_fatal_signal_received(void)
650 return (tog_sigpipe_received ||
651 tog_sigint_received || tog_sigint_received);
655 static const struct got_error *
656 view_close(struct tog_view *view)
658 const struct got_error *err = NULL;
660 if (view->child) {
661 view_close(view->child);
662 view->child = NULL;
664 if (view->close)
665 err = view->close(view);
666 if (view->panel)
667 del_panel(view->panel);
668 if (view->window)
669 delwin(view->window);
670 free(view);
671 return err;
674 static struct tog_view *
675 view_open(int nlines, int ncols, int begin_y, int begin_x,
676 enum tog_view_type type)
678 struct tog_view *view = calloc(1, sizeof(*view));
680 if (view == NULL)
681 return NULL;
683 view->type = type;
684 view->lines = LINES;
685 view->cols = COLS;
686 view->nlines = nlines ? nlines : LINES - begin_y;
687 view->ncols = ncols ? ncols : COLS - begin_x;
688 view->begin_y = begin_y;
689 view->begin_x = begin_x;
690 view->window = newwin(nlines, ncols, begin_y, begin_x);
691 if (view->window == NULL) {
692 view_close(view);
693 return NULL;
695 view->panel = new_panel(view->window);
696 if (view->panel == NULL ||
697 set_panel_userptr(view->panel, view) != OK) {
698 view_close(view);
699 return NULL;
702 keypad(view->window, TRUE);
703 return view;
706 static int
707 view_split_begin_x(int begin_x)
709 if (begin_x > 0 || COLS < 120)
710 return 0;
711 return (COLS - MAX(COLS / 2, 80));
714 /* XXX Stub till we decide what to do. */
715 static int
716 view_split_begin_y(int lines)
718 return lines * HSPLIT_SCALE;
721 static const struct got_error *view_resize(struct tog_view *);
723 static const struct got_error *
724 view_splitscreen(struct tog_view *view)
726 const struct got_error *err = NULL;
728 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
729 view->begin_y = view_split_begin_y(view->nlines);
730 view->begin_x = 0;
731 } else {
732 view->begin_x = view_split_begin_x(0);
733 view->begin_y = 0;
735 view->nlines = LINES - view->begin_y;
736 view->ncols = COLS - view->begin_x;
737 view->lines = LINES;
738 view->cols = COLS;
739 err = view_resize(view);
740 if (err)
741 return err;
743 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
744 view->parent->nlines = view->begin_y;
746 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
747 return got_error_from_errno("mvwin");
749 return NULL;
752 static const struct got_error *
753 view_fullscreen(struct tog_view *view)
755 const struct got_error *err = NULL;
757 view->begin_x = 0;
758 view->begin_y = 0;
759 view->nlines = LINES;
760 view->ncols = COLS;
761 view->lines = LINES;
762 view->cols = COLS;
763 err = view_resize(view);
764 if (err)
765 return err;
767 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
768 return got_error_from_errno("mvwin");
770 return NULL;
773 static int
774 view_is_parent_view(struct tog_view *view)
776 return view->parent == NULL;
779 static int
780 view_is_splitscreen(struct tog_view *view)
782 return view->begin_x > 0 || view->begin_y > 0;
785 static int
786 view_is_fullscreen(struct tog_view *view)
788 return view->nlines == LINES && view->ncols == COLS;
791 static void
792 view_border(struct tog_view *view)
794 PANEL *panel;
795 const struct tog_view *view_above;
797 if (view->parent)
798 return view_border(view->parent);
800 panel = panel_above(view->panel);
801 if (panel == NULL)
802 return;
804 view_above = panel_userptr(panel);
805 if (view->mode == TOG_VIEW_SPLIT_HRZN)
806 mvwhline(view->window, view_above->begin_y - 1,
807 view->begin_x, got_locale_is_utf8() ?
808 ACS_HLINE : '-', view->ncols);
809 else
810 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
811 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
814 static const struct got_error *request_log_commits(struct tog_view *);
815 static const struct got_error *offset_selection_down(struct tog_view *);
816 static void offset_selection_up(struct tog_view *);
818 static const struct got_error *
819 view_resize(struct tog_view *view)
821 const struct got_error *err = NULL;
822 int dif, nlines, ncols;
824 dif = LINES - view->lines; /* line difference */
826 if (view->lines > LINES)
827 nlines = view->nlines - (view->lines - LINES);
828 else
829 nlines = view->nlines + (LINES - view->lines);
830 if (view->cols > COLS)
831 ncols = view->ncols - (view->cols - COLS);
832 else
833 ncols = view->ncols + (COLS - view->cols);
835 if (view->child) {
836 int hs = view->child->begin_y;
838 if (!view_is_fullscreen(view))
839 view->child->begin_x = view_split_begin_x(view->begin_x);
840 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
841 view->child->begin_x == 0) {
842 ncols = COLS;
844 view_fullscreen(view->child);
845 if (view->child->focussed)
846 show_panel(view->child->panel);
847 else
848 show_panel(view->panel);
849 } else {
850 ncols = view->child->begin_x;
852 view_splitscreen(view->child);
853 show_panel(view->child->panel);
855 /*
856 * Request commits if terminal height was increased in a log
857 * view so we have enough commits loaded to populate the view.
858 */
859 if (view->type == TOG_VIEW_LOG && dif > 0) {
860 struct tog_log_view_state *ts = &view->state.log;
862 if (ts->commits.ncommits < ts->selected_entry->idx +
863 view->lines - ts->selected) {
864 view->nscrolled = ts->selected_entry->idx +
865 view->lines - ts->selected -
866 ts->commits.ncommits + dif;
867 err = request_log_commits(view);
868 if (err)
869 return err;
873 /*
874 * XXX This is ugly and needs to be moved into the above
875 * logic but "works" for now and my attempts at moving it
876 * break either 'tab' or 'F' key maps in horizontal splits.
877 */
878 if (hs) {
879 err = view_splitscreen(view->child);
880 if (err)
881 return err;
882 if (dif < 0) { /* top split decreased */
883 err = offset_selection_down(view);
884 if (err)
885 return err;
887 view_border(view);
888 update_panels();
889 doupdate();
890 show_panel(view->child->panel);
891 nlines = view->nlines;
893 } else if (view->parent == NULL)
894 ncols = COLS;
896 if (wresize(view->window, nlines, ncols) == ERR)
897 return got_error_from_errno("wresize");
898 if (replace_panel(view->panel, view->window) == ERR)
899 return got_error_from_errno("replace_panel");
900 wclear(view->window);
902 view->nlines = nlines;
903 view->ncols = ncols;
904 view->lines = LINES;
905 view->cols = COLS;
907 return NULL;
910 static const struct got_error *
911 view_close_child(struct tog_view *view)
913 const struct got_error *err = NULL;
915 if (view->child == NULL)
916 return NULL;
918 err = view_close(view->child);
919 view->child = NULL;
920 return err;
923 static const struct got_error *
924 view_set_child(struct tog_view *view, struct tog_view *child)
926 view->child = child;
927 child->parent = view;
929 return view_resize(view);
932 static void
933 tog_resizeterm(void)
935 int cols, lines;
936 struct winsize size;
938 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
939 cols = 80; /* Default */
940 lines = 24;
941 } else {
942 cols = size.ws_col;
943 lines = size.ws_row;
945 resize_term(lines, cols);
948 static const struct got_error *
949 view_search_start(struct tog_view *view)
951 const struct got_error *err = NULL;
952 struct tog_view *v = view;
953 char pattern[1024];
954 int ret;
956 if (view->search_started) {
957 regfree(&view->regex);
958 view->searching = 0;
959 memset(&view->regmatch, 0, sizeof(view->regmatch));
961 view->search_started = 0;
963 if (view->nlines < 1)
964 return NULL;
966 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
967 view_is_splitscreen(view->child))
968 v = view->child;
970 mvwaddstr(v->window, v->nlines - 1, 0, "/");
971 wclrtoeol(v->window);
973 nocbreak();
974 echo();
975 ret = wgetnstr(v->window, pattern, sizeof(pattern));
976 wrefresh(v->window);
977 cbreak();
978 noecho();
979 if (ret == ERR)
980 return NULL;
982 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
983 err = view->search_start(view);
984 if (err) {
985 regfree(&view->regex);
986 return err;
988 view->search_started = 1;
989 view->searching = TOG_SEARCH_FORWARD;
990 view->search_next_done = 0;
991 view->search_next(view);
994 return NULL;
997 /*
998 * Compute view->count from numeric user input. User has five-tenths of a
999 * second to follow each numeric keypress with another number to form count.
1000 * Return first non-numeric input or ERR and assign total to view->count.
1001 * XXX Should we add support for user-defined timeout?
1003 static int
1004 get_compound_key(struct tog_view *view, int c)
1006 struct tog_view *v = view;
1007 int x, n = 0;
1009 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
1010 view_is_splitscreen(view->child))
1011 v = view->child;
1012 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1013 v = view->parent;
1015 view->count = 0;
1016 halfdelay(5); /* block for half a second */
1017 wattron(v->window, A_BOLD);
1018 wmove(v->window, v->nlines - 1, 0);
1019 wclrtoeol(v->window);
1020 waddch(v->window, ':');
1022 do {
1023 x = getcurx(v->window);
1024 if (x != ERR && x < view->ncols) {
1025 waddch(v->window, c);
1026 wrefresh(v->window);
1030 * Don't overflow. Max valid request should be the greatest
1031 * between the longest and total lines; cap at 10 million.
1033 if (n >= 9999999)
1034 n = 9999999;
1035 else
1036 n = n * 10 + (c - '0');
1037 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1039 /* Massage excessive or inapplicable values at the input handler. */
1040 view->count = n;
1042 wattroff(v->window, A_BOLD);
1043 cbreak(); /* return to blocking */
1044 return c;
1047 static const struct got_error *
1048 view_input(struct tog_view **new, int *done, struct tog_view *view,
1049 struct tog_view_list_head *views)
1051 const struct got_error *err = NULL;
1052 struct tog_view *v;
1053 int ch, errcode;
1055 *new = NULL;
1057 /* Clear "no matches" indicator. */
1058 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1059 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1060 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1061 view->count = 0;
1064 if (view->searching && !view->search_next_done) {
1065 errcode = pthread_mutex_unlock(&tog_mutex);
1066 if (errcode)
1067 return got_error_set_errno(errcode,
1068 "pthread_mutex_unlock");
1069 sched_yield();
1070 errcode = pthread_mutex_lock(&tog_mutex);
1071 if (errcode)
1072 return got_error_set_errno(errcode,
1073 "pthread_mutex_lock");
1074 view->search_next(view);
1075 return NULL;
1078 nodelay(stdscr, FALSE);
1079 /* Allow threads to make progress while we are waiting for input. */
1080 errcode = pthread_mutex_unlock(&tog_mutex);
1081 if (errcode)
1082 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1083 /* If we have an unfinished count, don't get a new key map. */
1084 ch = view->ch;
1085 if ((view->count && --view->count == 0) || !view->count) {
1086 ch = wgetch(view->window);
1087 if (ch >= '1' && ch <= '9')
1088 view->ch = ch = get_compound_key(view, ch);
1090 errcode = pthread_mutex_lock(&tog_mutex);
1091 if (errcode)
1092 return got_error_set_errno(errcode, "pthread_mutex_lock");
1093 nodelay(stdscr, TRUE);
1095 if (tog_sigwinch_received || tog_sigcont_received) {
1096 tog_resizeterm();
1097 tog_sigwinch_received = 0;
1098 tog_sigcont_received = 0;
1099 TAILQ_FOREACH(v, views, entry) {
1100 err = view_resize(v);
1101 if (err)
1102 return err;
1103 err = v->input(new, v, KEY_RESIZE);
1104 if (err)
1105 return err;
1106 if (v->child) {
1107 err = view_resize(v->child);
1108 if (err)
1109 return err;
1110 err = v->child->input(new, v->child,
1111 KEY_RESIZE);
1112 if (err)
1113 return err;
1118 switch (ch) {
1119 case '\t':
1120 view->count = 0;
1121 if (view->child) {
1122 view->focussed = 0;
1123 view->child->focussed = 1;
1124 view->focus_child = 1;
1125 } else if (view->parent) {
1126 view->focussed = 0;
1127 view->parent->focussed = 1;
1128 view->parent->focus_child = 0;
1129 if (!view_is_splitscreen(view)) {
1130 if (view->mode == TOG_VIEW_SPLIT_HRZN &&
1131 view->parent->type == TOG_VIEW_LOG) {
1132 err = request_log_commits(view->parent);
1133 if (err)
1134 return err;
1136 offset_selection_up(view->parent);
1137 err = view_fullscreen(view->parent);
1138 if (err)
1139 return err;
1142 break;
1143 case 'q':
1144 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1145 if (view->parent->type == TOG_VIEW_LOG) {
1146 /* might need more commits to fill fullscreen */
1147 err = request_log_commits(view->parent);
1148 if (err)
1149 break;
1151 offset_selection_up(view->parent);
1152 view->parent->mode = TOG_VIEW_SPLIT_NONE;
1154 err = view->input(new, view, ch);
1155 view->dying = 1;
1156 break;
1157 case 'Q':
1158 *done = 1;
1159 break;
1160 case 'F':
1161 view->count = 0;
1162 if (view_is_parent_view(view)) {
1163 if (view->child == NULL)
1164 break;
1165 if (view_is_splitscreen(view->child)) {
1166 view->focussed = 0;
1167 view->child->focussed = 1;
1168 err = view_fullscreen(view->child);
1169 } else
1170 err = view_splitscreen(view->child);
1171 if (err)
1172 break;
1173 err = view->child->input(new, view->child,
1174 KEY_RESIZE);
1175 } else {
1176 if (view_is_splitscreen(view)) {
1177 view->parent->focussed = 0;
1178 view->focussed = 1;
1179 err = view_fullscreen(view);
1180 } else {
1181 err = view_splitscreen(view);
1182 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1183 err = view_resize(view->parent);
1185 if (err)
1186 break;
1187 err = view->input(new, view, KEY_RESIZE);
1189 if (err)
1190 break;
1191 if (view->type == TOG_VIEW_LOG) {
1192 err = request_log_commits(view);
1193 if (err)
1194 break;
1196 if (view->parent)
1197 err = offset_selection_down(view->parent);
1198 if (!err)
1199 err = offset_selection_down(view);
1200 break;
1201 case KEY_RESIZE:
1202 break;
1203 case '/':
1204 view->count = 0;
1205 if (view->search_start)
1206 view_search_start(view);
1207 else
1208 err = view->input(new, view, ch);
1209 break;
1210 case 'N':
1211 case 'n':
1212 if (view->search_started && view->search_next) {
1213 view->searching = (ch == 'n' ?
1214 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1215 view->search_next_done = 0;
1216 view->search_next(view);
1217 } else
1218 err = view->input(new, view, ch);
1219 break;
1220 default:
1221 err = view->input(new, view, ch);
1222 break;
1225 return err;
1228 static int
1229 view_needs_focus_indication(struct tog_view *view)
1231 if (view_is_parent_view(view)) {
1232 if (view->child == NULL || view->child->focussed)
1233 return 0;
1234 if (!view_is_splitscreen(view->child))
1235 return 0;
1236 } else if (!view_is_splitscreen(view))
1237 return 0;
1239 return view->focussed;
1242 static const struct got_error *
1243 view_loop(struct tog_view *view)
1245 const struct got_error *err = NULL;
1246 struct tog_view_list_head views;
1247 struct tog_view *new_view;
1248 int fast_refresh = 10;
1249 int done = 0, errcode;
1251 errcode = pthread_mutex_lock(&tog_mutex);
1252 if (errcode)
1253 return got_error_set_errno(errcode, "pthread_mutex_lock");
1255 TAILQ_INIT(&views);
1256 TAILQ_INSERT_HEAD(&views, view, entry);
1258 view->focussed = 1;
1259 err = view->show(view);
1260 if (err)
1261 return err;
1262 update_panels();
1263 doupdate();
1264 while (!TAILQ_EMPTY(&views) && !done && !tog_fatal_signal_received()) {
1265 /* Refresh fast during initialization, then become slower. */
1266 if (fast_refresh && fast_refresh-- == 0)
1267 halfdelay(10); /* switch to once per second */
1269 err = view_input(&new_view, &done, view, &views);
1270 if (err)
1271 break;
1272 if (view->dying) {
1273 struct tog_view *v, *prev = NULL;
1275 if (view_is_parent_view(view))
1276 prev = TAILQ_PREV(view, tog_view_list_head,
1277 entry);
1278 else if (view->parent)
1279 prev = view->parent;
1281 if (view->parent) {
1282 view->parent->child = NULL;
1283 view->parent->focus_child = 0;
1284 /* Restore fullscreen line height. */
1285 view->parent->nlines = view->parent->lines;
1286 err = view_resize(view->parent);
1287 if (err)
1288 break;
1289 } else
1290 TAILQ_REMOVE(&views, view, entry);
1292 err = view_close(view);
1293 if (err)
1294 goto done;
1296 view = NULL;
1297 TAILQ_FOREACH(v, &views, entry) {
1298 if (v->focussed)
1299 break;
1301 if (view == NULL && new_view == NULL) {
1302 /* No view has focus. Try to pick one. */
1303 if (prev)
1304 view = prev;
1305 else if (!TAILQ_EMPTY(&views)) {
1306 view = TAILQ_LAST(&views,
1307 tog_view_list_head);
1309 if (view) {
1310 if (view->focus_child) {
1311 view->child->focussed = 1;
1312 view = view->child;
1313 } else
1314 view->focussed = 1;
1318 if (new_view) {
1319 struct tog_view *v, *t;
1320 /* Only allow one parent view per type. */
1321 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1322 if (v->type != new_view->type)
1323 continue;
1324 TAILQ_REMOVE(&views, v, entry);
1325 err = view_close(v);
1326 if (err)
1327 goto done;
1328 break;
1330 TAILQ_INSERT_TAIL(&views, new_view, entry);
1331 view = new_view;
1333 if (view) {
1334 if (view_is_parent_view(view)) {
1335 if (view->child && view->child->focussed)
1336 view = view->child;
1337 } else {
1338 if (view->parent && view->parent->focussed)
1339 view = view->parent;
1341 show_panel(view->panel);
1342 if (view->child && view_is_splitscreen(view->child))
1343 show_panel(view->child->panel);
1344 if (view->parent && view_is_splitscreen(view)) {
1345 err = view->parent->show(view->parent);
1346 if (err)
1347 goto done;
1349 err = view->show(view);
1350 if (err)
1351 goto done;
1352 if (view->child) {
1353 err = view->child->show(view->child);
1354 if (err)
1355 goto done;
1357 update_panels();
1358 doupdate();
1361 done:
1362 while (!TAILQ_EMPTY(&views)) {
1363 view = TAILQ_FIRST(&views);
1364 TAILQ_REMOVE(&views, view, entry);
1365 view_close(view);
1368 errcode = pthread_mutex_unlock(&tog_mutex);
1369 if (errcode && err == NULL)
1370 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1372 return err;
1375 __dead static void
1376 usage_log(void)
1378 endwin();
1379 fprintf(stderr,
1380 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1381 getprogname());
1382 exit(1);
1385 /* Create newly allocated wide-character string equivalent to a byte string. */
1386 static const struct got_error *
1387 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1389 char *vis = NULL;
1390 const struct got_error *err = NULL;
1392 *ws = NULL;
1393 *wlen = mbstowcs(NULL, s, 0);
1394 if (*wlen == (size_t)-1) {
1395 int vislen;
1396 if (errno != EILSEQ)
1397 return got_error_from_errno("mbstowcs");
1399 /* byte string invalid in current encoding; try to "fix" it */
1400 err = got_mbsavis(&vis, &vislen, s);
1401 if (err)
1402 return err;
1403 *wlen = mbstowcs(NULL, vis, 0);
1404 if (*wlen == (size_t)-1) {
1405 err = got_error_from_errno("mbstowcs"); /* give up */
1406 goto done;
1410 *ws = calloc(*wlen + 1, sizeof(**ws));
1411 if (*ws == NULL) {
1412 err = got_error_from_errno("calloc");
1413 goto done;
1416 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1417 err = got_error_from_errno("mbstowcs");
1418 done:
1419 free(vis);
1420 if (err) {
1421 free(*ws);
1422 *ws = NULL;
1423 *wlen = 0;
1425 return err;
1428 static const struct got_error *
1429 expand_tab(char **ptr, const char *src)
1431 char *dst;
1432 size_t len, n, idx = 0, sz = 0;
1434 *ptr = NULL;
1435 n = len = strlen(src);
1436 dst = malloc(n + 1);
1437 if (dst == NULL)
1438 return got_error_from_errno("malloc");
1440 while (idx < len && src[idx]) {
1441 const char c = src[idx];
1443 if (c == '\t') {
1444 size_t nb = TABSIZE - sz % TABSIZE;
1445 char *p;
1447 p = realloc(dst, n + nb);
1448 if (p == NULL) {
1449 free(dst);
1450 return got_error_from_errno("realloc");
1453 dst = p;
1454 n += nb;
1455 memset(dst + sz, ' ', nb);
1456 sz += nb;
1457 } else
1458 dst[sz++] = src[idx];
1459 ++idx;
1462 dst[sz] = '\0';
1463 *ptr = dst;
1464 return NULL;
1468 * Advance at most n columns from wline starting at offset off.
1469 * Return the index to the first character after the span operation.
1470 * Return the combined column width of all spanned wide character in
1471 * *rcol.
1473 static int
1474 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1476 int width, i, cols = 0;
1478 if (n == 0) {
1479 *rcol = cols;
1480 return off;
1483 for (i = off; wline[i] != L'\0'; ++i) {
1484 if (wline[i] == L'\t')
1485 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1486 else
1487 width = wcwidth(wline[i]);
1489 if (width == -1) {
1490 width = 1;
1491 wline[i] = L'.';
1494 if (cols + width > n)
1495 break;
1496 cols += width;
1499 *rcol = cols;
1500 return i;
1504 * Format a line for display, ensuring that it won't overflow a width limit.
1505 * With scrolling, the width returned refers to the scrolled version of the
1506 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1508 static const struct got_error *
1509 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1510 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1512 const struct got_error *err = NULL;
1513 int cols;
1514 wchar_t *wline = NULL;
1515 char *exstr = NULL;
1516 size_t wlen;
1517 int i, scrollx;
1519 *wlinep = NULL;
1520 *widthp = 0;
1522 if (expand) {
1523 err = expand_tab(&exstr, line);
1524 if (err)
1525 return err;
1528 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1529 free(exstr);
1530 if (err)
1531 return err;
1533 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1535 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1536 wline[wlen - 1] = L'\0';
1537 wlen--;
1539 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1540 wline[wlen - 1] = L'\0';
1541 wlen--;
1544 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1545 wline[i] = L'\0';
1547 if (widthp)
1548 *widthp = cols;
1549 if (scrollxp)
1550 *scrollxp = scrollx;
1551 if (err)
1552 free(wline);
1553 else
1554 *wlinep = wline;
1555 return err;
1558 static const struct got_error*
1559 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1560 struct got_object_id *id, struct got_repository *repo)
1562 static const struct got_error *err = NULL;
1563 struct got_reflist_entry *re;
1564 char *s;
1565 const char *name;
1567 *refs_str = NULL;
1569 TAILQ_FOREACH(re, refs, entry) {
1570 struct got_tag_object *tag = NULL;
1571 struct got_object_id *ref_id;
1572 int cmp;
1574 name = got_ref_get_name(re->ref);
1575 if (strcmp(name, GOT_REF_HEAD) == 0)
1576 continue;
1577 if (strncmp(name, "refs/", 5) == 0)
1578 name += 5;
1579 if (strncmp(name, "got/", 4) == 0 &&
1580 strncmp(name, "got/backup/", 11) != 0)
1581 continue;
1582 if (strncmp(name, "heads/", 6) == 0)
1583 name += 6;
1584 if (strncmp(name, "remotes/", 8) == 0) {
1585 name += 8;
1586 s = strstr(name, "/" GOT_REF_HEAD);
1587 if (s != NULL && s[strlen(s)] == '\0')
1588 continue;
1590 err = got_ref_resolve(&ref_id, repo, re->ref);
1591 if (err)
1592 break;
1593 if (strncmp(name, "tags/", 5) == 0) {
1594 err = got_object_open_as_tag(&tag, repo, ref_id);
1595 if (err) {
1596 if (err->code != GOT_ERR_OBJ_TYPE) {
1597 free(ref_id);
1598 break;
1600 /* Ref points at something other than a tag. */
1601 err = NULL;
1602 tag = NULL;
1605 cmp = got_object_id_cmp(tag ?
1606 got_object_tag_get_object_id(tag) : ref_id, id);
1607 free(ref_id);
1608 if (tag)
1609 got_object_tag_close(tag);
1610 if (cmp != 0)
1611 continue;
1612 s = *refs_str;
1613 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1614 s ? ", " : "", name) == -1) {
1615 err = got_error_from_errno("asprintf");
1616 free(s);
1617 *refs_str = NULL;
1618 break;
1620 free(s);
1623 return err;
1626 static const struct got_error *
1627 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1628 int col_tab_align)
1630 char *smallerthan;
1632 smallerthan = strchr(author, '<');
1633 if (smallerthan && smallerthan[1] != '\0')
1634 author = smallerthan + 1;
1635 author[strcspn(author, "@>")] = '\0';
1636 return format_line(wauthor, author_width, NULL, author, 0, limit,
1637 col_tab_align, 0);
1640 static const struct got_error *
1641 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1642 struct got_object_id *id, const size_t date_display_cols,
1643 int author_display_cols)
1645 struct tog_log_view_state *s = &view->state.log;
1646 const struct got_error *err = NULL;
1647 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1648 char *logmsg0 = NULL, *logmsg = NULL;
1649 char *author = NULL;
1650 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1651 int author_width, logmsg_width;
1652 char *newline, *line = NULL;
1653 int col, limit, scrollx;
1654 const int avail = view->ncols;
1655 struct tm tm;
1656 time_t committer_time;
1657 struct tog_color *tc;
1659 committer_time = got_object_commit_get_committer_time(commit);
1660 if (gmtime_r(&committer_time, &tm) == NULL)
1661 return got_error_from_errno("gmtime_r");
1662 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1663 return got_error(GOT_ERR_NO_SPACE);
1665 if (avail <= date_display_cols)
1666 limit = MIN(sizeof(datebuf) - 1, avail);
1667 else
1668 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
1669 tc = get_color(&s->colors, TOG_COLOR_DATE);
1670 if (tc)
1671 wattr_on(view->window,
1672 COLOR_PAIR(tc->colorpair), NULL);
1673 waddnstr(view->window, datebuf, limit);
1674 if (tc)
1675 wattr_off(view->window,
1676 COLOR_PAIR(tc->colorpair), NULL);
1677 col = limit;
1678 if (col > avail)
1679 goto done;
1681 if (avail >= 120) {
1682 char *id_str;
1683 err = got_object_id_str(&id_str, id);
1684 if (err)
1685 goto done;
1686 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1687 if (tc)
1688 wattr_on(view->window,
1689 COLOR_PAIR(tc->colorpair), NULL);
1690 wprintw(view->window, "%.8s ", id_str);
1691 if (tc)
1692 wattr_off(view->window,
1693 COLOR_PAIR(tc->colorpair), NULL);
1694 free(id_str);
1695 col += 9;
1696 if (col > avail)
1697 goto done;
1700 author = strdup(got_object_commit_get_author(commit));
1701 if (author == NULL) {
1702 err = got_error_from_errno("strdup");
1703 goto done;
1705 err = format_author(&wauthor, &author_width, author, avail - col, col);
1706 if (err)
1707 goto done;
1708 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
1709 if (tc)
1710 wattr_on(view->window,
1711 COLOR_PAIR(tc->colorpair), NULL);
1712 waddwstr(view->window, wauthor);
1713 if (tc)
1714 wattr_off(view->window,
1715 COLOR_PAIR(tc->colorpair), NULL);
1716 col += author_width;
1717 while (col < avail && author_width < author_display_cols + 2) {
1718 waddch(view->window, ' ');
1719 col++;
1720 author_width++;
1722 if (col > avail)
1723 goto done;
1725 err = got_object_commit_get_logmsg(&logmsg0, commit);
1726 if (err)
1727 goto done;
1728 logmsg = logmsg0;
1729 while (*logmsg == '\n')
1730 logmsg++;
1731 newline = strchr(logmsg, '\n');
1732 if (newline)
1733 *newline = '\0';
1734 limit = avail - col;
1735 if (view->child && view_is_splitscreen(view->child) && limit > 0)
1736 limit--; /* for the border */
1737 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
1738 limit, col, 1);
1739 if (err)
1740 goto done;
1741 waddwstr(view->window, &wlogmsg[scrollx]);
1742 col += MAX(logmsg_width, 0);
1743 while (col < avail) {
1744 waddch(view->window, ' ');
1745 col++;
1747 done:
1748 free(logmsg0);
1749 free(wlogmsg);
1750 free(author);
1751 free(wauthor);
1752 free(line);
1753 return err;
1756 static struct commit_queue_entry *
1757 alloc_commit_queue_entry(struct got_commit_object *commit,
1758 struct got_object_id *id)
1760 struct commit_queue_entry *entry;
1762 entry = calloc(1, sizeof(*entry));
1763 if (entry == NULL)
1764 return NULL;
1766 entry->id = id;
1767 entry->commit = commit;
1768 return entry;
1771 static void
1772 pop_commit(struct commit_queue *commits)
1774 struct commit_queue_entry *entry;
1776 entry = TAILQ_FIRST(&commits->head);
1777 TAILQ_REMOVE(&commits->head, entry, entry);
1778 got_object_commit_close(entry->commit);
1779 commits->ncommits--;
1780 /* Don't free entry->id! It is owned by the commit graph. */
1781 free(entry);
1784 static void
1785 free_commits(struct commit_queue *commits)
1787 while (!TAILQ_EMPTY(&commits->head))
1788 pop_commit(commits);
1791 static const struct got_error *
1792 match_commit(int *have_match, struct got_object_id *id,
1793 struct got_commit_object *commit, regex_t *regex)
1795 const struct got_error *err = NULL;
1796 regmatch_t regmatch;
1797 char *id_str = NULL, *logmsg = NULL;
1799 *have_match = 0;
1801 err = got_object_id_str(&id_str, id);
1802 if (err)
1803 return err;
1805 err = got_object_commit_get_logmsg(&logmsg, commit);
1806 if (err)
1807 goto done;
1809 if (regexec(regex, got_object_commit_get_author(commit), 1,
1810 &regmatch, 0) == 0 ||
1811 regexec(regex, got_object_commit_get_committer(commit), 1,
1812 &regmatch, 0) == 0 ||
1813 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
1814 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
1815 *have_match = 1;
1816 done:
1817 free(id_str);
1818 free(logmsg);
1819 return err;
1822 static const struct got_error *
1823 queue_commits(struct tog_log_thread_args *a)
1825 const struct got_error *err = NULL;
1828 * We keep all commits open throughout the lifetime of the log
1829 * view in order to avoid having to re-fetch commits from disk
1830 * while updating the display.
1832 do {
1833 struct got_object_id *id;
1834 struct got_commit_object *commit;
1835 struct commit_queue_entry *entry;
1836 int errcode;
1838 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
1839 NULL, NULL);
1840 if (err || id == NULL)
1841 break;
1843 err = got_object_open_as_commit(&commit, a->repo, id);
1844 if (err)
1845 break;
1846 entry = alloc_commit_queue_entry(commit, id);
1847 if (entry == NULL) {
1848 err = got_error_from_errno("alloc_commit_queue_entry");
1849 break;
1852 errcode = pthread_mutex_lock(&tog_mutex);
1853 if (errcode) {
1854 err = got_error_set_errno(errcode,
1855 "pthread_mutex_lock");
1856 break;
1859 entry->idx = a->commits->ncommits;
1860 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
1861 a->commits->ncommits++;
1863 if (*a->searching == TOG_SEARCH_FORWARD &&
1864 !*a->search_next_done) {
1865 int have_match;
1866 err = match_commit(&have_match, id, commit, a->regex);
1867 if (err)
1868 break;
1869 if (have_match)
1870 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
1873 errcode = pthread_mutex_unlock(&tog_mutex);
1874 if (errcode && err == NULL)
1875 err = got_error_set_errno(errcode,
1876 "pthread_mutex_unlock");
1877 if (err)
1878 break;
1879 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
1881 return err;
1884 static void
1885 select_commit(struct tog_log_view_state *s)
1887 struct commit_queue_entry *entry;
1888 int ncommits = 0;
1890 entry = s->first_displayed_entry;
1891 while (entry) {
1892 if (ncommits == s->selected) {
1893 s->selected_entry = entry;
1894 break;
1896 entry = TAILQ_NEXT(entry, entry);
1897 ncommits++;
1901 static const struct got_error *
1902 draw_commits(struct tog_view *view)
1904 const struct got_error *err = NULL;
1905 struct tog_log_view_state *s = &view->state.log;
1906 struct commit_queue_entry *entry = s->selected_entry;
1907 const int limit = view->nlines;
1908 int width;
1909 int ncommits, author_cols = 4;
1910 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
1911 char *refs_str = NULL;
1912 wchar_t *wline;
1913 struct tog_color *tc;
1914 static const size_t date_display_cols = 12;
1916 if (s->selected_entry &&
1917 !(view->searching && view->search_next_done == 0)) {
1918 struct got_reflist_head *refs;
1919 err = got_object_id_str(&id_str, s->selected_entry->id);
1920 if (err)
1921 return err;
1922 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
1923 s->selected_entry->id);
1924 if (refs) {
1925 err = build_refs_str(&refs_str, refs,
1926 s->selected_entry->id, s->repo);
1927 if (err)
1928 goto done;
1932 if (s->thread_args.commits_needed == 0)
1933 halfdelay(10); /* disable fast refresh */
1935 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
1936 if (asprintf(&ncommits_str, " [%d/%d] %s",
1937 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1938 (view->searching && !view->search_next_done) ?
1939 "searching..." : "loading...") == -1) {
1940 err = got_error_from_errno("asprintf");
1941 goto done;
1943 } else {
1944 const char *search_str = NULL;
1946 if (view->searching) {
1947 if (view->search_next_done == TOG_SEARCH_NO_MORE)
1948 search_str = "no more matches";
1949 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
1950 search_str = "no matches found";
1951 else if (!view->search_next_done)
1952 search_str = "searching...";
1955 if (asprintf(&ncommits_str, " [%d/%d] %s",
1956 entry ? entry->idx + 1 : 0, s->commits.ncommits,
1957 search_str ? search_str :
1958 (refs_str ? refs_str : "")) == -1) {
1959 err = got_error_from_errno("asprintf");
1960 goto done;
1964 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
1965 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
1966 "........................................",
1967 s->in_repo_path, ncommits_str) == -1) {
1968 err = got_error_from_errno("asprintf");
1969 header = NULL;
1970 goto done;
1972 } else if (asprintf(&header, "commit %s%s",
1973 id_str ? id_str : "........................................",
1974 ncommits_str) == -1) {
1975 err = got_error_from_errno("asprintf");
1976 header = NULL;
1977 goto done;
1979 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
1980 if (err)
1981 goto done;
1983 werase(view->window);
1985 if (view_needs_focus_indication(view))
1986 wstandout(view->window);
1987 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
1988 if (tc)
1989 wattr_on(view->window,
1990 COLOR_PAIR(tc->colorpair), NULL);
1991 waddwstr(view->window, wline);
1992 if (tc)
1993 wattr_off(view->window,
1994 COLOR_PAIR(tc->colorpair), NULL);
1995 while (width < view->ncols) {
1996 waddch(view->window, ' ');
1997 width++;
1999 if (view_needs_focus_indication(view))
2000 wstandend(view->window);
2001 free(wline);
2002 if (limit <= 1)
2003 goto done;
2005 /* Grow author column size if necessary, and set view->maxx. */
2006 entry = s->first_displayed_entry;
2007 ncommits = 0;
2008 view->maxx = 0;
2009 while (entry) {
2010 char *author, *eol, *msg, *msg0;
2011 wchar_t *wauthor, *wmsg;
2012 int width;
2013 if (ncommits >= limit - 1)
2014 break;
2015 author = strdup(got_object_commit_get_author(entry->commit));
2016 if (author == NULL) {
2017 err = got_error_from_errno("strdup");
2018 goto done;
2020 err = format_author(&wauthor, &width, author, COLS,
2021 date_display_cols);
2022 if (author_cols < width)
2023 author_cols = width;
2024 free(wauthor);
2025 free(author);
2026 err = got_object_commit_get_logmsg(&msg0, entry->commit);
2027 if (err)
2028 goto done;
2029 msg = msg0;
2030 while (*msg == '\n')
2031 ++msg;
2032 if ((eol = strchr(msg, '\n')))
2033 *eol = '\0';
2034 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2035 date_display_cols + author_cols, 0);
2036 if (err)
2037 goto done;
2038 view->maxx = MAX(view->maxx, width);
2039 free(msg0);
2040 free(wmsg);
2041 ncommits++;
2042 entry = TAILQ_NEXT(entry, entry);
2045 entry = s->first_displayed_entry;
2046 s->last_displayed_entry = s->first_displayed_entry;
2047 ncommits = 0;
2048 while (entry) {
2049 if (ncommits >= limit - 1)
2050 break;
2051 if (ncommits == s->selected)
2052 wstandout(view->window);
2053 err = draw_commit(view, entry->commit, entry->id,
2054 date_display_cols, author_cols);
2055 if (ncommits == s->selected)
2056 wstandend(view->window);
2057 if (err)
2058 goto done;
2059 ncommits++;
2060 s->last_displayed_entry = entry;
2061 entry = TAILQ_NEXT(entry, entry);
2064 view_border(view);
2065 done:
2066 free(id_str);
2067 free(refs_str);
2068 free(ncommits_str);
2069 free(header);
2070 return err;
2073 static void
2074 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2076 struct commit_queue_entry *entry;
2077 int nscrolled = 0;
2079 entry = TAILQ_FIRST(&s->commits.head);
2080 if (s->first_displayed_entry == entry)
2081 return;
2083 entry = s->first_displayed_entry;
2084 while (entry && nscrolled < maxscroll) {
2085 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2086 if (entry) {
2087 s->first_displayed_entry = entry;
2088 nscrolled++;
2093 static const struct got_error *
2094 trigger_log_thread(struct tog_view *view, int wait)
2096 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2097 int errcode;
2099 halfdelay(1); /* fast refresh while loading commits */
2101 while (ta->commits_needed > 0 || ta->load_all) {
2102 if (ta->log_complete)
2103 break;
2105 /* Wake the log thread. */
2106 errcode = pthread_cond_signal(&ta->need_commits);
2107 if (errcode)
2108 return got_error_set_errno(errcode,
2109 "pthread_cond_signal");
2112 * The mutex will be released while the view loop waits
2113 * in wgetch(), at which time the log thread will run.
2115 if (!wait)
2116 break;
2118 /* Display progress update in log view. */
2119 show_log_view(view);
2120 update_panels();
2121 doupdate();
2123 /* Wait right here while next commit is being loaded. */
2124 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2125 if (errcode)
2126 return got_error_set_errno(errcode,
2127 "pthread_cond_wait");
2129 /* Display progress update in log view. */
2130 show_log_view(view);
2131 update_panels();
2132 doupdate();
2135 return NULL;
2138 static const struct got_error *
2139 request_log_commits(struct tog_view *view)
2141 struct tog_log_view_state *state = &view->state.log;
2142 const struct got_error *err = NULL;
2144 state->thread_args.commits_needed = view->nscrolled;
2145 err = trigger_log_thread(view, 1);
2146 view->nscrolled = 0;
2148 return err;
2151 static const struct got_error *
2152 log_scroll_down(struct tog_view *view, int maxscroll)
2154 struct tog_log_view_state *s = &view->state.log;
2155 const struct got_error *err = NULL;
2156 struct commit_queue_entry *pentry;
2157 int nscrolled = 0, ncommits_needed;
2159 if (s->last_displayed_entry == NULL)
2160 return NULL;
2162 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2163 if (s->commits.ncommits < ncommits_needed &&
2164 !s->thread_args.log_complete) {
2166 * Ask the log thread for required amount of commits.
2168 s->thread_args.commits_needed += maxscroll;
2169 err = trigger_log_thread(view, 1);
2170 if (err)
2171 return err;
2174 do {
2175 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2176 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2177 break;
2179 s->last_displayed_entry = pentry ?
2180 pentry : s->last_displayed_entry;;
2182 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2183 if (pentry == NULL)
2184 break;
2185 s->first_displayed_entry = pentry;
2186 } while (++nscrolled < maxscroll);
2188 if (view->mode == TOG_VIEW_SPLIT_HRZN)
2189 view->nscrolled += nscrolled;
2190 else
2191 view->nscrolled = 0;
2193 return err;
2196 static const struct got_error *
2197 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2198 struct got_commit_object *commit, struct got_object_id *commit_id,
2199 struct tog_view *log_view, struct got_repository *repo)
2201 const struct got_error *err;
2202 struct got_object_qid *parent_id;
2203 struct tog_view *diff_view;
2205 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2206 if (diff_view == NULL)
2207 return got_error_from_errno("view_open");
2209 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2210 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2211 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2212 if (err == NULL)
2213 *new_view = diff_view;
2214 return err;
2217 static const struct got_error *
2218 tree_view_visit_subtree(struct tog_tree_view_state *s,
2219 struct got_tree_object *subtree)
2221 struct tog_parent_tree *parent;
2223 parent = calloc(1, sizeof(*parent));
2224 if (parent == NULL)
2225 return got_error_from_errno("calloc");
2227 parent->tree = s->tree;
2228 parent->first_displayed_entry = s->first_displayed_entry;
2229 parent->selected_entry = s->selected_entry;
2230 parent->selected = s->selected;
2231 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2232 s->tree = subtree;
2233 s->selected = 0;
2234 s->first_displayed_entry = NULL;
2235 return NULL;
2238 static const struct got_error *
2239 tree_view_walk_path(struct tog_tree_view_state *s,
2240 struct got_commit_object *commit, const char *path)
2242 const struct got_error *err = NULL;
2243 struct got_tree_object *tree = NULL;
2244 const char *p;
2245 char *slash, *subpath = NULL;
2247 /* Walk the path and open corresponding tree objects. */
2248 p = path;
2249 while (*p) {
2250 struct got_tree_entry *te;
2251 struct got_object_id *tree_id;
2252 char *te_name;
2254 while (p[0] == '/')
2255 p++;
2257 /* Ensure the correct subtree entry is selected. */
2258 slash = strchr(p, '/');
2259 if (slash == NULL)
2260 te_name = strdup(p);
2261 else
2262 te_name = strndup(p, slash - p);
2263 if (te_name == NULL) {
2264 err = got_error_from_errno("strndup");
2265 break;
2267 te = got_object_tree_find_entry(s->tree, te_name);
2268 if (te == NULL) {
2269 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2270 free(te_name);
2271 break;
2273 free(te_name);
2274 s->first_displayed_entry = s->selected_entry = te;
2276 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2277 break; /* jump to this file's entry */
2279 slash = strchr(p, '/');
2280 if (slash)
2281 subpath = strndup(path, slash - path);
2282 else
2283 subpath = strdup(path);
2284 if (subpath == NULL) {
2285 err = got_error_from_errno("strdup");
2286 break;
2289 err = got_object_id_by_path(&tree_id, s->repo, commit,
2290 subpath);
2291 if (err)
2292 break;
2294 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2295 free(tree_id);
2296 if (err)
2297 break;
2299 err = tree_view_visit_subtree(s, tree);
2300 if (err) {
2301 got_object_tree_close(tree);
2302 break;
2304 if (slash == NULL)
2305 break;
2306 free(subpath);
2307 subpath = NULL;
2308 p = slash;
2311 free(subpath);
2312 return err;
2315 static const struct got_error *
2316 browse_commit_tree(struct tog_view **new_view, int begin_x,
2317 struct commit_queue_entry *entry, const char *path,
2318 const char *head_ref_name, struct got_repository *repo)
2320 const struct got_error *err = NULL;
2321 struct tog_tree_view_state *s;
2322 struct tog_view *tree_view;
2324 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
2325 if (tree_view == NULL)
2326 return got_error_from_errno("view_open");
2328 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2329 if (err)
2330 return err;
2331 s = &tree_view->state.tree;
2333 *new_view = tree_view;
2335 if (got_path_is_root_dir(path))
2336 return NULL;
2338 return tree_view_walk_path(s, entry->commit, path);
2341 static const struct got_error *
2342 block_signals_used_by_main_thread(void)
2344 sigset_t sigset;
2345 int errcode;
2347 if (sigemptyset(&sigset) == -1)
2348 return got_error_from_errno("sigemptyset");
2350 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2351 if (sigaddset(&sigset, SIGWINCH) == -1)
2352 return got_error_from_errno("sigaddset");
2353 if (sigaddset(&sigset, SIGCONT) == -1)
2354 return got_error_from_errno("sigaddset");
2355 if (sigaddset(&sigset, SIGINT) == -1)
2356 return got_error_from_errno("sigaddset");
2357 if (sigaddset(&sigset, SIGTERM) == -1)
2358 return got_error_from_errno("sigaddset");
2360 /* ncurses handles SIGTSTP */
2361 if (sigaddset(&sigset, SIGTSTP) == -1)
2362 return got_error_from_errno("sigaddset");
2364 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2365 if (errcode)
2366 return got_error_set_errno(errcode, "pthread_sigmask");
2368 return NULL;
2371 static void *
2372 log_thread(void *arg)
2374 const struct got_error *err = NULL;
2375 int errcode = 0;
2376 struct tog_log_thread_args *a = arg;
2377 int done = 0;
2379 err = block_signals_used_by_main_thread();
2380 if (err)
2381 return (void *)err;
2383 while (!done && !err && !tog_fatal_signal_received()) {
2384 err = queue_commits(a);
2385 if (err) {
2386 if (err->code != GOT_ERR_ITER_COMPLETED)
2387 return (void *)err;
2388 err = NULL;
2389 done = 1;
2390 } else if (a->commits_needed > 0 && !a->load_all)
2391 a->commits_needed--;
2393 errcode = pthread_mutex_lock(&tog_mutex);
2394 if (errcode) {
2395 err = got_error_set_errno(errcode,
2396 "pthread_mutex_lock");
2397 break;
2398 } else if (*a->quit)
2399 done = 1;
2400 else if (*a->first_displayed_entry == NULL) {
2401 *a->first_displayed_entry =
2402 TAILQ_FIRST(&a->commits->head);
2403 *a->selected_entry = *a->first_displayed_entry;
2406 errcode = pthread_cond_signal(&a->commit_loaded);
2407 if (errcode) {
2408 err = got_error_set_errno(errcode,
2409 "pthread_cond_signal");
2410 pthread_mutex_unlock(&tog_mutex);
2411 break;
2414 if (done)
2415 a->commits_needed = 0;
2416 else {
2417 if (a->commits_needed == 0 && !a->load_all) {
2418 errcode = pthread_cond_wait(&a->need_commits,
2419 &tog_mutex);
2420 if (errcode)
2421 err = got_error_set_errno(errcode,
2422 "pthread_cond_wait");
2423 if (*a->quit)
2424 done = 1;
2428 errcode = pthread_mutex_unlock(&tog_mutex);
2429 if (errcode && err == NULL)
2430 err = got_error_set_errno(errcode,
2431 "pthread_mutex_unlock");
2433 a->log_complete = 1;
2434 return (void *)err;
2437 static const struct got_error *
2438 stop_log_thread(struct tog_log_view_state *s)
2440 const struct got_error *err = NULL;
2441 int errcode;
2443 if (s->thread) {
2444 s->quit = 1;
2445 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2446 if (errcode)
2447 return got_error_set_errno(errcode,
2448 "pthread_cond_signal");
2449 errcode = pthread_mutex_unlock(&tog_mutex);
2450 if (errcode)
2451 return got_error_set_errno(errcode,
2452 "pthread_mutex_unlock");
2453 errcode = pthread_join(s->thread, (void **)&err);
2454 if (errcode)
2455 return got_error_set_errno(errcode, "pthread_join");
2456 errcode = pthread_mutex_lock(&tog_mutex);
2457 if (errcode)
2458 return got_error_set_errno(errcode,
2459 "pthread_mutex_lock");
2460 s->thread = NULL;
2463 if (s->thread_args.repo) {
2464 err = got_repo_close(s->thread_args.repo);
2465 s->thread_args.repo = NULL;
2468 if (s->thread_args.pack_fds) {
2469 const struct got_error *pack_err =
2470 got_repo_pack_fds_close(s->thread_args.pack_fds);
2471 if (err == NULL)
2472 err = pack_err;
2473 s->thread_args.pack_fds = NULL;
2476 if (s->thread_args.graph) {
2477 got_commit_graph_close(s->thread_args.graph);
2478 s->thread_args.graph = NULL;
2481 return err;
2484 static const struct got_error *
2485 close_log_view(struct tog_view *view)
2487 const struct got_error *err = NULL;
2488 struct tog_log_view_state *s = &view->state.log;
2489 int errcode;
2491 err = stop_log_thread(s);
2493 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2494 if (errcode && err == NULL)
2495 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2497 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2498 if (errcode && err == NULL)
2499 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2501 free_commits(&s->commits);
2502 free(s->in_repo_path);
2503 s->in_repo_path = NULL;
2504 free(s->start_id);
2505 s->start_id = NULL;
2506 free(s->head_ref_name);
2507 s->head_ref_name = NULL;
2508 return err;
2511 static const struct got_error *
2512 search_start_log_view(struct tog_view *view)
2514 struct tog_log_view_state *s = &view->state.log;
2516 s->matched_entry = NULL;
2517 s->search_entry = NULL;
2518 return NULL;
2521 static const struct got_error *
2522 search_next_log_view(struct tog_view *view)
2524 const struct got_error *err = NULL;
2525 struct tog_log_view_state *s = &view->state.log;
2526 struct commit_queue_entry *entry;
2528 /* Display progress update in log view. */
2529 show_log_view(view);
2530 update_panels();
2531 doupdate();
2533 if (s->search_entry) {
2534 int errcode, ch;
2535 errcode = pthread_mutex_unlock(&tog_mutex);
2536 if (errcode)
2537 return got_error_set_errno(errcode,
2538 "pthread_mutex_unlock");
2539 ch = wgetch(view->window);
2540 errcode = pthread_mutex_lock(&tog_mutex);
2541 if (errcode)
2542 return got_error_set_errno(errcode,
2543 "pthread_mutex_lock");
2544 if (ch == KEY_BACKSPACE) {
2545 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2546 return NULL;
2548 if (view->searching == TOG_SEARCH_FORWARD)
2549 entry = TAILQ_NEXT(s->search_entry, entry);
2550 else
2551 entry = TAILQ_PREV(s->search_entry,
2552 commit_queue_head, entry);
2553 } else if (s->matched_entry) {
2554 int matched_idx = s->matched_entry->idx;
2555 int selected_idx = s->selected_entry->idx;
2558 * If the user has moved the cursor after we hit a match,
2559 * the position from where we should continue searching
2560 * might have changed.
2562 if (view->searching == TOG_SEARCH_FORWARD) {
2563 if (matched_idx > selected_idx)
2564 entry = TAILQ_NEXT(s->selected_entry, entry);
2565 else
2566 entry = TAILQ_NEXT(s->matched_entry, entry);
2567 } else {
2568 if (matched_idx < selected_idx)
2569 entry = TAILQ_PREV(s->selected_entry,
2570 commit_queue_head, entry);
2571 else
2572 entry = TAILQ_PREV(s->matched_entry,
2573 commit_queue_head, entry);
2575 } else {
2576 entry = s->selected_entry;
2579 while (1) {
2580 int have_match = 0;
2582 if (entry == NULL) {
2583 if (s->thread_args.log_complete ||
2584 view->searching == TOG_SEARCH_BACKWARD) {
2585 view->search_next_done =
2586 (s->matched_entry == NULL ?
2587 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2588 s->search_entry = NULL;
2589 return NULL;
2592 * Poke the log thread for more commits and return,
2593 * allowing the main loop to make progress. Search
2594 * will resume at s->search_entry once we come back.
2596 s->thread_args.commits_needed++;
2597 return trigger_log_thread(view, 0);
2600 err = match_commit(&have_match, entry->id, entry->commit,
2601 &view->regex);
2602 if (err)
2603 break;
2604 if (have_match) {
2605 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2606 s->matched_entry = entry;
2607 break;
2610 s->search_entry = entry;
2611 if (view->searching == TOG_SEARCH_FORWARD)
2612 entry = TAILQ_NEXT(entry, entry);
2613 else
2614 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2617 if (s->matched_entry) {
2618 int cur = s->selected_entry->idx;
2619 while (cur < s->matched_entry->idx) {
2620 err = input_log_view(NULL, view, KEY_DOWN);
2621 if (err)
2622 return err;
2623 cur++;
2625 while (cur > s->matched_entry->idx) {
2626 err = input_log_view(NULL, view, KEY_UP);
2627 if (err)
2628 return err;
2629 cur--;
2633 s->search_entry = NULL;
2635 return NULL;
2638 static const struct got_error *
2639 open_log_view(struct tog_view *view, struct got_object_id *start_id,
2640 struct got_repository *repo, const char *head_ref_name,
2641 const char *in_repo_path, int log_branches)
2643 const struct got_error *err = NULL;
2644 struct tog_log_view_state *s = &view->state.log;
2645 struct got_repository *thread_repo = NULL;
2646 struct got_commit_graph *thread_graph = NULL;
2647 int errcode;
2649 if (in_repo_path != s->in_repo_path) {
2650 free(s->in_repo_path);
2651 s->in_repo_path = strdup(in_repo_path);
2652 if (s->in_repo_path == NULL)
2653 return got_error_from_errno("strdup");
2656 /* The commit queue only contains commits being displayed. */
2657 TAILQ_INIT(&s->commits.head);
2658 s->commits.ncommits = 0;
2660 s->repo = repo;
2661 if (head_ref_name) {
2662 s->head_ref_name = strdup(head_ref_name);
2663 if (s->head_ref_name == NULL) {
2664 err = got_error_from_errno("strdup");
2665 goto done;
2668 s->start_id = got_object_id_dup(start_id);
2669 if (s->start_id == NULL) {
2670 err = got_error_from_errno("got_object_id_dup");
2671 goto done;
2673 s->log_branches = log_branches;
2675 STAILQ_INIT(&s->colors);
2676 if (has_colors() && getenv("TOG_COLORS") != NULL) {
2677 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
2678 get_color_value("TOG_COLOR_COMMIT"));
2679 if (err)
2680 goto done;
2681 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
2682 get_color_value("TOG_COLOR_AUTHOR"));
2683 if (err) {
2684 free_colors(&s->colors);
2685 goto done;
2687 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
2688 get_color_value("TOG_COLOR_DATE"));
2689 if (err) {
2690 free_colors(&s->colors);
2691 goto done;
2695 view->show = show_log_view;
2696 view->input = input_log_view;
2697 view->close = close_log_view;
2698 view->search_start = search_start_log_view;
2699 view->search_next = search_next_log_view;
2701 if (s->thread_args.pack_fds == NULL) {
2702 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
2703 if (err)
2704 goto done;
2706 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
2707 s->thread_args.pack_fds);
2708 if (err)
2709 goto done;
2710 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
2711 !s->log_branches);
2712 if (err)
2713 goto done;
2714 err = got_commit_graph_iter_start(thread_graph, s->start_id,
2715 s->repo, NULL, NULL);
2716 if (err)
2717 goto done;
2719 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
2720 if (errcode) {
2721 err = got_error_set_errno(errcode, "pthread_cond_init");
2722 goto done;
2724 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
2725 if (errcode) {
2726 err = got_error_set_errno(errcode, "pthread_cond_init");
2727 goto done;
2730 s->thread_args.commits_needed = view->nlines;
2731 s->thread_args.graph = thread_graph;
2732 s->thread_args.commits = &s->commits;
2733 s->thread_args.in_repo_path = s->in_repo_path;
2734 s->thread_args.start_id = s->start_id;
2735 s->thread_args.repo = thread_repo;
2736 s->thread_args.log_complete = 0;
2737 s->thread_args.quit = &s->quit;
2738 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
2739 s->thread_args.selected_entry = &s->selected_entry;
2740 s->thread_args.searching = &view->searching;
2741 s->thread_args.search_next_done = &view->search_next_done;
2742 s->thread_args.regex = &view->regex;
2743 done:
2744 if (err)
2745 close_log_view(view);
2746 return err;
2749 static const struct got_error *
2750 show_log_view(struct tog_view *view)
2752 const struct got_error *err;
2753 struct tog_log_view_state *s = &view->state.log;
2755 if (s->thread == NULL) {
2756 int errcode = pthread_create(&s->thread, NULL, log_thread,
2757 &s->thread_args);
2758 if (errcode)
2759 return got_error_set_errno(errcode, "pthread_create");
2760 if (s->thread_args.commits_needed > 0) {
2761 err = trigger_log_thread(view, 1);
2762 if (err)
2763 return err;
2767 return draw_commits(view);
2770 static void
2771 log_move_cursor_up(struct tog_view *view, int page, int home)
2773 struct tog_log_view_state *s = &view->state.log;
2775 if (s->selected_entry->idx == 0)
2776 view->count = 0;
2777 if (s->first_displayed_entry == NULL)
2778 return;
2780 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
2781 || home)
2782 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
2784 if (!page && !home && s->selected > 0)
2785 --s->selected;
2786 else
2787 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
2789 select_commit(s);
2790 return;
2793 static const struct got_error *
2794 log_move_cursor_down(struct tog_view *view, int page)
2796 struct tog_log_view_state *s = &view->state.log;
2797 struct commit_queue_entry *first;
2798 const struct got_error *err = NULL;
2800 first = s->first_displayed_entry;
2801 if (first == NULL) {
2802 view->count = 0;
2803 return NULL;
2806 if (s->thread_args.log_complete &&
2807 s->selected_entry->idx >= s->commits.ncommits - 1)
2808 return NULL;
2810 if (!page) {
2811 int eos = view->nlines - 2;
2813 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
2814 view_is_splitscreen(view->child))
2815 --eos; /* border consumes the last line */
2816 if (s->selected < MIN(eos, s->commits.ncommits - 1))
2817 ++s->selected;
2818 else
2819 err = log_scroll_down(view, 1);
2820 } else if (s->thread_args.load_all) {
2821 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
2822 s->selected += MIN(s->last_displayed_entry->idx -
2823 s->selected_entry->idx, page + 1);
2824 else
2825 err = log_scroll_down(view, MIN(page,
2826 s->commits.ncommits - s->selected_entry->idx - 1));
2827 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
2828 } else {
2829 err = log_scroll_down(view, page);
2830 if (err)
2831 return err;
2832 if (first == s->first_displayed_entry && s->selected <
2833 MIN(view->nlines - 2, s->commits.ncommits - 1)) {
2834 s->selected = MIN(s->commits.ncommits - 1, page);
2837 if (err)
2838 return err;
2841 * We might necessarily overshoot in horizontal
2842 * splits; if so, select the last displayed commit.
2844 s->selected = MIN(s->selected,
2845 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
2847 select_commit(s);
2849 if (s->thread_args.log_complete &&
2850 s->selected_entry->idx == s->commits.ncommits - 1)
2851 view->count = 0;
2853 return NULL;
2857 * Get splitscreen dimensions based on TOG_VIEW_SPLIT_MODE:
2858 * TOG_VIEW_SPLIT_VERT vertical split if COLS > 119 (default)
2859 * TOG_VIEW_SPLIT_HRZN horizontal split
2860 * Assign start column and line of the new split to *x and *y, respectively,
2861 * and assign view mode to view->mode.
2863 static void
2864 view_get_split(struct tog_view *view, int *y, int *x)
2866 char *mode;
2868 mode = getenv("TOG_VIEW_SPLIT_MODE");
2870 if (!mode || mode[0] != 'h') {
2871 view->mode = TOG_VIEW_SPLIT_VERT;
2872 *x = view_split_begin_x(view->begin_x);
2873 } else if (mode && mode[0] == 'h') {
2874 view->mode = TOG_VIEW_SPLIT_HRZN;
2875 *y = view_split_begin_y(view->lines);
2879 /* Split view horizontally at y and offset view->state->selected line. */
2880 static const struct got_error *
2881 view_init_hsplit(struct tog_view *view, int y)
2883 const struct got_error *err = NULL;
2885 view->nlines = y;
2886 err = view_resize(view);
2887 if (err)
2888 return err;
2890 err = offset_selection_down(view);
2892 return err;
2895 static const struct got_error *
2896 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
2898 const struct got_error *err = NULL;
2899 struct tog_log_view_state *s = &view->state.log;
2900 struct tog_view *diff_view = NULL, *tree_view = NULL;
2901 struct tog_view *ref_view = NULL;
2902 struct commit_queue_entry *entry;
2903 int begin_x = 0, begin_y = 0, eos, n, nscroll;
2905 if (s->thread_args.load_all) {
2906 if (ch == KEY_BACKSPACE)
2907 s->thread_args.load_all = 0;
2908 else if (s->thread_args.log_complete) {
2909 err = log_move_cursor_down(view, s->commits.ncommits);
2910 s->thread_args.load_all = 0;
2912 return err;
2915 eos = nscroll = view->nlines - 1;
2916 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
2917 view_is_splitscreen(view->child))
2918 --eos; /* border */
2921 switch (ch) {
2922 case 'q':
2923 s->quit = 1;
2924 break;
2925 case '0':
2926 view->x = 0;
2927 break;
2928 case '$':
2929 view->x = MAX(view->maxx - view->ncols / 2, 0);
2930 view->count = 0;
2931 break;
2932 case KEY_RIGHT:
2933 case 'l':
2934 if (view->x + view->ncols / 2 < view->maxx)
2935 view->x += 2; /* move two columns right */
2936 else
2937 view->count = 0;
2938 break;
2939 case KEY_LEFT:
2940 case 'h':
2941 view->x -= MIN(view->x, 2); /* move two columns back */
2942 if (view->x <= 0)
2943 view->count = 0;
2944 break;
2945 case 'k':
2946 case KEY_UP:
2947 case '<':
2948 case ',':
2949 case CTRL('p'):
2950 log_move_cursor_up(view, 0, 0);
2951 break;
2952 case 'g':
2953 case KEY_HOME:
2954 log_move_cursor_up(view, 0, 1);
2955 view->count = 0;
2956 break;
2957 case CTRL('u'):
2958 case 'u':
2959 nscroll /= 2;
2960 /* FALL THROUGH */
2961 case KEY_PPAGE:
2962 case CTRL('b'):
2963 case 'b':
2964 log_move_cursor_up(view, nscroll, 0);
2965 break;
2966 case 'j':
2967 case KEY_DOWN:
2968 case '>':
2969 case '.':
2970 case CTRL('n'):
2971 err = log_move_cursor_down(view, 0);
2972 break;
2973 case 'G':
2974 case KEY_END: {
2975 /* We don't know yet how many commits, so we're forced to
2976 * traverse them all. */
2977 view->count = 0;
2978 if (!s->thread_args.log_complete) {
2979 s->thread_args.load_all = 1;
2980 return trigger_log_thread(view, 0);
2983 s->selected = 0;
2984 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
2985 for (n = 0; n < eos; n++) {
2986 if (entry == NULL)
2987 break;
2988 s->first_displayed_entry = entry;
2989 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2991 if (n > 0)
2992 s->selected = n - 1;
2993 select_commit(s);
2994 break;
2996 case CTRL('d'):
2997 case 'd':
2998 nscroll /= 2;
2999 /* FALL THROUGH */
3000 case KEY_NPAGE:
3001 case CTRL('f'):
3002 case 'f':
3003 case ' ':
3004 err = log_move_cursor_down(view, nscroll);
3005 break;
3006 case KEY_RESIZE:
3007 if (s->selected > view->nlines - 2)
3008 s->selected = view->nlines - 2;
3009 if (s->selected > s->commits.ncommits - 1)
3010 s->selected = s->commits.ncommits - 1;
3011 select_commit(s);
3012 if (s->commits.ncommits < view->nlines - 1 &&
3013 !s->thread_args.log_complete) {
3014 s->thread_args.commits_needed += (view->nlines - 1) -
3015 s->commits.ncommits;
3016 err = trigger_log_thread(view, 1);
3018 break;
3019 case KEY_ENTER:
3020 case '\r': {
3021 view->count = 0;
3022 if (s->selected_entry == NULL)
3023 break;
3025 /* get dimensions--don't split till initialisation succeeds */
3026 if (view_is_parent_view(view))
3027 view_get_split(view, &begin_y, &begin_x);
3029 err = open_diff_view_for_commit(&diff_view, begin_y, begin_x,
3030 s->selected_entry->commit, s->selected_entry->id,
3031 view, s->repo);
3032 if (err)
3033 break;
3035 if (view->mode == TOG_VIEW_SPLIT_HRZN) { /* safe to split */
3036 err = view_init_hsplit(view, begin_y);
3037 if (err)
3038 break;
3041 view->focussed = 0;
3042 diff_view->focussed = 1;
3043 diff_view->mode = view->mode;
3044 diff_view->nlines = view->lines - begin_y;
3046 if (view_is_parent_view(view)) {
3047 err = view_close_child(view);
3048 if (err)
3049 return err;
3050 err = view_set_child(view, diff_view);
3051 if (err)
3052 return err;
3053 view->focus_child = 1;
3054 } else
3055 *new_view = diff_view;
3056 break;
3058 case 't':
3059 view->count = 0;
3060 if (s->selected_entry == NULL)
3061 break;
3062 if (view_is_parent_view(view))
3063 begin_x = view_split_begin_x(view->begin_x);
3064 err = browse_commit_tree(&tree_view, begin_x,
3065 s->selected_entry, s->in_repo_path, s->head_ref_name,
3066 s->repo);
3067 if (err)
3068 break;
3069 view->focussed = 0;
3070 tree_view->focussed = 1;
3071 if (view_is_parent_view(view)) {
3072 err = view_close_child(view);
3073 if (err)
3074 return err;
3075 err = view_set_child(view, tree_view);
3076 if (err)
3077 return err;
3078 view->focus_child = 1;
3079 } else
3080 *new_view = tree_view;
3081 break;
3082 case KEY_BACKSPACE:
3083 case CTRL('l'):
3084 case 'B':
3085 view->count = 0;
3086 if (ch == KEY_BACKSPACE &&
3087 got_path_is_root_dir(s->in_repo_path))
3088 break;
3089 err = stop_log_thread(s);
3090 if (err)
3091 return err;
3092 if (ch == KEY_BACKSPACE) {
3093 char *parent_path;
3094 err = got_path_dirname(&parent_path, s->in_repo_path);
3095 if (err)
3096 return err;
3097 free(s->in_repo_path);
3098 s->in_repo_path = parent_path;
3099 s->thread_args.in_repo_path = s->in_repo_path;
3100 } else if (ch == CTRL('l')) {
3101 struct got_object_id *start_id;
3102 err = got_repo_match_object_id(&start_id, NULL,
3103 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3104 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3105 if (err)
3106 return err;
3107 free(s->start_id);
3108 s->start_id = start_id;
3109 s->thread_args.start_id = s->start_id;
3110 } else /* 'B' */
3111 s->log_branches = !s->log_branches;
3113 if (s->thread_args.pack_fds == NULL) {
3114 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3115 if (err)
3116 return err;
3118 err = got_repo_open(&s->thread_args.repo,
3119 got_repo_get_path(s->repo), NULL,
3120 s->thread_args.pack_fds);
3121 if (err)
3122 return err;
3123 tog_free_refs();
3124 err = tog_load_refs(s->repo, 0);
3125 if (err)
3126 return err;
3127 err = got_commit_graph_open(&s->thread_args.graph,
3128 s->in_repo_path, !s->log_branches);
3129 if (err)
3130 return err;
3131 err = got_commit_graph_iter_start(s->thread_args.graph,
3132 s->start_id, s->repo, NULL, NULL);
3133 if (err)
3134 return err;
3135 free_commits(&s->commits);
3136 s->first_displayed_entry = NULL;
3137 s->last_displayed_entry = NULL;
3138 s->selected_entry = NULL;
3139 s->selected = 0;
3140 s->thread_args.log_complete = 0;
3141 s->quit = 0;
3142 s->thread_args.commits_needed = view->lines;
3143 s->matched_entry = NULL;
3144 s->search_entry = NULL;
3145 break;
3146 case 'r':
3147 view->count = 0;
3148 if (view_is_parent_view(view))
3149 begin_x = view_split_begin_x(view->begin_x);
3150 ref_view = view_open(view->nlines, view->ncols,
3151 view->begin_y, begin_x, TOG_VIEW_REF);
3152 if (ref_view == NULL)
3153 return got_error_from_errno("view_open");
3154 err = open_ref_view(ref_view, s->repo);
3155 if (err) {
3156 view_close(ref_view);
3157 return err;
3159 view->focussed = 0;
3160 ref_view->focussed = 1;
3161 if (view_is_parent_view(view)) {
3162 err = view_close_child(view);
3163 if (err)
3164 return err;
3165 err = view_set_child(view, ref_view);
3166 if (err)
3167 return err;
3168 view->focus_child = 1;
3169 } else
3170 *new_view = ref_view;
3171 break;
3172 default:
3173 view->count = 0;
3174 break;
3177 return err;
3180 static const struct got_error *
3181 apply_unveil(const char *repo_path, const char *worktree_path)
3183 const struct got_error *error;
3185 #ifdef PROFILE
3186 if (unveil("gmon.out", "rwc") != 0)
3187 return got_error_from_errno2("unveil", "gmon.out");
3188 #endif
3189 if (repo_path && unveil(repo_path, "r") != 0)
3190 return got_error_from_errno2("unveil", repo_path);
3192 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3193 return got_error_from_errno2("unveil", worktree_path);
3195 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3196 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3198 error = got_privsep_unveil_exec_helpers();
3199 if (error != NULL)
3200 return error;
3202 if (unveil(NULL, NULL) != 0)
3203 return got_error_from_errno("unveil");
3205 return NULL;
3208 static void
3209 init_curses(void)
3212 * Override default signal handlers before starting ncurses.
3213 * This should prevent ncurses from installing its own
3214 * broken cleanup() signal handler.
3216 signal(SIGWINCH, tog_sigwinch);
3217 signal(SIGPIPE, tog_sigpipe);
3218 signal(SIGCONT, tog_sigcont);
3219 signal(SIGINT, tog_sigint);
3220 signal(SIGTERM, tog_sigterm);
3222 initscr();
3223 cbreak();
3224 halfdelay(1); /* Do fast refresh while initial view is loading. */
3225 noecho();
3226 nonl();
3227 intrflush(stdscr, FALSE);
3228 keypad(stdscr, TRUE);
3229 curs_set(0);
3230 if (getenv("TOG_COLORS") != NULL) {
3231 start_color();
3232 use_default_colors();
3236 static const struct got_error *
3237 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3238 struct got_repository *repo, struct got_worktree *worktree)
3240 const struct got_error *err = NULL;
3242 if (argc == 0) {
3243 *in_repo_path = strdup("/");
3244 if (*in_repo_path == NULL)
3245 return got_error_from_errno("strdup");
3246 return NULL;
3249 if (worktree) {
3250 const char *prefix = got_worktree_get_path_prefix(worktree);
3251 char *p;
3253 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3254 if (err)
3255 return err;
3256 if (asprintf(in_repo_path, "%s%s%s", prefix,
3257 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3258 p) == -1) {
3259 err = got_error_from_errno("asprintf");
3260 *in_repo_path = NULL;
3262 free(p);
3263 } else
3264 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3266 return err;
3269 static const struct got_error *
3270 cmd_log(int argc, char *argv[])
3272 const struct got_error *error;
3273 struct got_repository *repo = NULL;
3274 struct got_worktree *worktree = NULL;
3275 struct got_object_id *start_id = NULL;
3276 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3277 char *start_commit = NULL, *label = NULL;
3278 struct got_reference *ref = NULL;
3279 const char *head_ref_name = NULL;
3280 int ch, log_branches = 0;
3281 struct tog_view *view;
3282 int *pack_fds = NULL;
3284 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3285 switch (ch) {
3286 case 'b':
3287 log_branches = 1;
3288 break;
3289 case 'c':
3290 start_commit = optarg;
3291 break;
3292 case 'r':
3293 repo_path = realpath(optarg, NULL);
3294 if (repo_path == NULL)
3295 return got_error_from_errno2("realpath",
3296 optarg);
3297 break;
3298 default:
3299 usage_log();
3300 /* NOTREACHED */
3304 argc -= optind;
3305 argv += optind;
3307 if (argc > 1)
3308 usage_log();
3310 error = got_repo_pack_fds_open(&pack_fds);
3311 if (error != NULL)
3312 goto done;
3314 if (repo_path == NULL) {
3315 cwd = getcwd(NULL, 0);
3316 if (cwd == NULL)
3317 return got_error_from_errno("getcwd");
3318 error = got_worktree_open(&worktree, cwd);
3319 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3320 goto done;
3321 if (worktree)
3322 repo_path =
3323 strdup(got_worktree_get_repo_path(worktree));
3324 else
3325 repo_path = strdup(cwd);
3326 if (repo_path == NULL) {
3327 error = got_error_from_errno("strdup");
3328 goto done;
3332 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3333 if (error != NULL)
3334 goto done;
3336 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3337 repo, worktree);
3338 if (error)
3339 goto done;
3341 init_curses();
3343 error = apply_unveil(got_repo_get_path(repo),
3344 worktree ? got_worktree_get_root_path(worktree) : NULL);
3345 if (error)
3346 goto done;
3348 /* already loaded by tog_log_with_path()? */
3349 if (TAILQ_EMPTY(&tog_refs)) {
3350 error = tog_load_refs(repo, 0);
3351 if (error)
3352 goto done;
3355 if (start_commit == NULL) {
3356 error = got_repo_match_object_id(&start_id, &label,
3357 worktree ? got_worktree_get_head_ref_name(worktree) :
3358 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3359 if (error)
3360 goto done;
3361 head_ref_name = label;
3362 } else {
3363 error = got_ref_open(&ref, repo, start_commit, 0);
3364 if (error == NULL)
3365 head_ref_name = got_ref_get_name(ref);
3366 else if (error->code != GOT_ERR_NOT_REF)
3367 goto done;
3368 error = got_repo_match_object_id(&start_id, NULL,
3369 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3370 if (error)
3371 goto done;
3374 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3375 if (view == NULL) {
3376 error = got_error_from_errno("view_open");
3377 goto done;
3379 error = open_log_view(view, start_id, repo, head_ref_name,
3380 in_repo_path, log_branches);
3381 if (error)
3382 goto done;
3383 if (worktree) {
3384 /* Release work tree lock. */
3385 got_worktree_close(worktree);
3386 worktree = NULL;
3388 error = view_loop(view);
3389 done:
3390 free(in_repo_path);
3391 free(repo_path);
3392 free(cwd);
3393 free(start_id);
3394 free(label);
3395 if (ref)
3396 got_ref_close(ref);
3397 if (repo) {
3398 const struct got_error *close_err = got_repo_close(repo);
3399 if (error == NULL)
3400 error = close_err;
3402 if (worktree)
3403 got_worktree_close(worktree);
3404 if (pack_fds) {
3405 const struct got_error *pack_err =
3406 got_repo_pack_fds_close(pack_fds);
3407 if (error == NULL)
3408 error = pack_err;
3410 tog_free_refs();
3411 return error;
3414 __dead static void
3415 usage_diff(void)
3417 endwin();
3418 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3419 "[-w] object1 object2\n", getprogname());
3420 exit(1);
3423 static int
3424 match_line(const char *line, regex_t *regex, size_t nmatch,
3425 regmatch_t *regmatch)
3427 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3430 static struct tog_color *
3431 match_color(struct tog_colors *colors, const char *line)
3433 struct tog_color *tc = NULL;
3435 STAILQ_FOREACH(tc, colors, entry) {
3436 if (match_line(line, &tc->regex, 0, NULL))
3437 return tc;
3440 return NULL;
3443 static const struct got_error *
3444 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3445 WINDOW *window, int skipcol, regmatch_t *regmatch)
3447 const struct got_error *err = NULL;
3448 char *exstr = NULL;
3449 wchar_t *wline = NULL;
3450 int rme, rms, n, width, scrollx;
3451 int width0 = 0, width1 = 0, width2 = 0;
3452 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3454 *wtotal = 0;
3456 rms = regmatch->rm_so;
3457 rme = regmatch->rm_eo;
3459 err = expand_tab(&exstr, line);
3460 if (err)
3461 return err;
3463 /* Split the line into 3 segments, according to match offsets. */
3464 seg0 = strndup(exstr, rms);
3465 if (seg0 == NULL) {
3466 err = got_error_from_errno("strndup");
3467 goto done;
3469 seg1 = strndup(exstr + rms, rme - rms);
3470 if (seg1 == NULL) {
3471 err = got_error_from_errno("strndup");
3472 goto done;
3474 seg2 = strdup(exstr + rme);
3475 if (seg2 == NULL) {
3476 err = got_error_from_errno("strndup");
3477 goto done;
3480 /* draw up to matched token if we haven't scrolled past it */
3481 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3482 col_tab_align, 1);
3483 if (err)
3484 goto done;
3485 n = MAX(width0 - skipcol, 0);
3486 if (n) {
3487 free(wline);
3488 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3489 wlimit, col_tab_align, 1);
3490 if (err)
3491 goto done;
3492 waddwstr(window, &wline[scrollx]);
3493 wlimit -= width;
3494 *wtotal += width;
3497 if (wlimit > 0) {
3498 int i = 0, w = 0;
3499 size_t wlen;
3501 free(wline);
3502 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3503 col_tab_align, 1);
3504 if (err)
3505 goto done;
3506 wlen = wcslen(wline);
3507 while (i < wlen) {
3508 width = wcwidth(wline[i]);
3509 if (width == -1) {
3510 /* should not happen, tabs are expanded */
3511 err = got_error(GOT_ERR_RANGE);
3512 goto done;
3514 if (width0 + w + width > skipcol)
3515 break;
3516 w += width;
3517 i++;
3519 /* draw (visible part of) matched token (if scrolled into it) */
3520 if (width1 - w > 0) {
3521 wattron(window, A_STANDOUT);
3522 waddwstr(window, &wline[i]);
3523 wattroff(window, A_STANDOUT);
3524 wlimit -= (width1 - w);
3525 *wtotal += (width1 - w);
3529 if (wlimit > 0) { /* draw rest of line */
3530 free(wline);
3531 if (skipcol > width0 + width1) {
3532 err = format_line(&wline, &width2, &scrollx, seg2,
3533 skipcol - (width0 + width1), wlimit,
3534 col_tab_align, 1);
3535 if (err)
3536 goto done;
3537 waddwstr(window, &wline[scrollx]);
3538 } else {
3539 err = format_line(&wline, &width2, NULL, seg2, 0,
3540 wlimit, col_tab_align, 1);
3541 if (err)
3542 goto done;
3543 waddwstr(window, wline);
3545 *wtotal += width2;
3547 done:
3548 free(wline);
3549 free(exstr);
3550 free(seg0);
3551 free(seg1);
3552 free(seg2);
3553 return err;
3556 static const struct got_error *
3557 draw_file(struct tog_view *view, const char *header)
3559 struct tog_diff_view_state *s = &view->state.diff;
3560 regmatch_t *regmatch = &view->regmatch;
3561 const struct got_error *err;
3562 int nprinted = 0;
3563 char *line;
3564 size_t linesize = 0;
3565 ssize_t linelen;
3566 struct tog_color *tc;
3567 wchar_t *wline;
3568 int width;
3569 int max_lines = view->nlines;
3570 int nlines = s->nlines;
3571 off_t line_offset;
3573 line_offset = s->line_offsets[s->first_displayed_line - 1];
3574 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3575 return got_error_from_errno("fseek");
3577 werase(view->window);
3579 if (header) {
3580 if (asprintf(&line, "[%d/%d] %s",
3581 s->first_displayed_line - 1 + s->selected_line, nlines,
3582 header) == -1)
3583 return got_error_from_errno("asprintf");
3584 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3585 0, 0);
3586 free(line);
3587 if (err)
3588 return err;
3590 if (view_needs_focus_indication(view))
3591 wstandout(view->window);
3592 waddwstr(view->window, wline);
3593 free(wline);
3594 wline = NULL;
3595 if (view_needs_focus_indication(view))
3596 wstandend(view->window);
3597 if (width <= view->ncols - 1)
3598 waddch(view->window, '\n');
3600 if (max_lines <= 1)
3601 return NULL;
3602 max_lines--;
3605 s->eof = 0;
3606 view->maxx = 0;
3607 line = NULL;
3608 while (max_lines > 0 && nprinted < max_lines) {
3609 linelen = getline(&line, &linesize, s->f);
3610 if (linelen == -1) {
3611 if (feof(s->f)) {
3612 s->eof = 1;
3613 break;
3615 free(line);
3616 return got_ferror(s->f, GOT_ERR_IO);
3619 /* Set view->maxx based on full line length. */
3620 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
3621 view->x ? 1 : 0);
3622 if (err) {
3623 free(line);
3624 return err;
3626 view->maxx = MAX(view->maxx, width);
3627 free(wline);
3628 wline = NULL;
3630 tc = match_color(&s->colors, line);
3631 if (tc)
3632 wattr_on(view->window,
3633 COLOR_PAIR(tc->colorpair), NULL);
3634 if (s->first_displayed_line + nprinted == s->matched_line &&
3635 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
3636 err = add_matched_line(&width, line, view->ncols, 0,
3637 view->window, view->x, regmatch);
3638 if (err) {
3639 free(line);
3640 return err;
3642 } else {
3643 int skip;
3644 err = format_line(&wline, &width, &skip, line,
3645 view->x, view->ncols, 0, view->x ? 1 : 0);
3646 if (err) {
3647 free(line);
3648 return err;
3650 waddwstr(view->window, &wline[skip]);
3651 free(wline);
3652 wline = NULL;
3654 if (tc)
3655 wattr_off(view->window,
3656 COLOR_PAIR(tc->colorpair), NULL);
3657 if (width <= view->ncols - 1)
3658 waddch(view->window, '\n');
3659 nprinted++;
3661 free(line);
3662 if (nprinted >= 1)
3663 s->last_displayed_line = s->first_displayed_line +
3664 (nprinted - 1);
3665 else
3666 s->last_displayed_line = s->first_displayed_line;
3668 view_border(view);
3670 if (s->eof) {
3671 while (nprinted < view->nlines) {
3672 waddch(view->window, '\n');
3673 nprinted++;
3676 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
3677 view->ncols, 0, 0);
3678 if (err) {
3679 return err;
3682 wstandout(view->window);
3683 waddwstr(view->window, wline);
3684 free(wline);
3685 wline = NULL;
3686 wstandend(view->window);
3689 return NULL;
3692 static char *
3693 get_datestr(time_t *time, char *datebuf)
3695 struct tm mytm, *tm;
3696 char *p, *s;
3698 tm = gmtime_r(time, &mytm);
3699 if (tm == NULL)
3700 return NULL;
3701 s = asctime_r(tm, datebuf);
3702 if (s == NULL)
3703 return NULL;
3704 p = strchr(s, '\n');
3705 if (p)
3706 *p = '\0';
3707 return s;
3710 static const struct got_error *
3711 get_changed_paths(struct got_pathlist_head *paths,
3712 struct got_commit_object *commit, struct got_repository *repo)
3714 const struct got_error *err = NULL;
3715 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3716 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3717 struct got_object_qid *qid;
3719 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3720 if (qid != NULL) {
3721 struct got_commit_object *pcommit;
3722 err = got_object_open_as_commit(&pcommit, repo,
3723 &qid->id);
3724 if (err)
3725 return err;
3727 tree_id1 = got_object_id_dup(
3728 got_object_commit_get_tree_id(pcommit));
3729 if (tree_id1 == NULL) {
3730 got_object_commit_close(pcommit);
3731 return got_error_from_errno("got_object_id_dup");
3733 got_object_commit_close(pcommit);
3737 if (tree_id1) {
3738 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3739 if (err)
3740 goto done;
3743 tree_id2 = got_object_commit_get_tree_id(commit);
3744 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3745 if (err)
3746 goto done;
3748 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3749 got_diff_tree_collect_changed_paths, paths, 0);
3750 done:
3751 if (tree1)
3752 got_object_tree_close(tree1);
3753 if (tree2)
3754 got_object_tree_close(tree2);
3755 free(tree_id1);
3756 return err;
3759 static const struct got_error *
3760 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
3762 off_t *p;
3764 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
3765 if (p == NULL)
3766 return got_error_from_errno("reallocarray");
3767 *line_offsets = p;
3768 (*line_offsets)[*nlines] = off;
3769 (*nlines)++;
3770 return NULL;
3773 static const struct got_error *
3774 write_commit_info(off_t **line_offsets, size_t *nlines,
3775 struct got_object_id *commit_id, struct got_reflist_head *refs,
3776 struct got_repository *repo, FILE *outfile)
3778 const struct got_error *err = NULL;
3779 char datebuf[26], *datestr;
3780 struct got_commit_object *commit;
3781 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
3782 time_t committer_time;
3783 const char *author, *committer;
3784 char *refs_str = NULL;
3785 struct got_pathlist_head changed_paths;
3786 struct got_pathlist_entry *pe;
3787 off_t outoff = 0;
3788 int n;
3790 TAILQ_INIT(&changed_paths);
3792 if (refs) {
3793 err = build_refs_str(&refs_str, refs, commit_id, repo);
3794 if (err)
3795 return err;
3798 err = got_object_open_as_commit(&commit, repo, commit_id);
3799 if (err)
3800 return err;
3802 err = got_object_id_str(&id_str, commit_id);
3803 if (err) {
3804 err = got_error_from_errno("got_object_id_str");
3805 goto done;
3808 err = add_line_offset(line_offsets, nlines, 0);
3809 if (err)
3810 goto done;
3812 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3813 refs_str ? refs_str : "", refs_str ? ")" : "");
3814 if (n < 0) {
3815 err = got_error_from_errno("fprintf");
3816 goto done;
3818 outoff += n;
3819 err = add_line_offset(line_offsets, nlines, outoff);
3820 if (err)
3821 goto done;
3823 n = fprintf(outfile, "from: %s\n",
3824 got_object_commit_get_author(commit));
3825 if (n < 0) {
3826 err = got_error_from_errno("fprintf");
3827 goto done;
3829 outoff += n;
3830 err = add_line_offset(line_offsets, nlines, outoff);
3831 if (err)
3832 goto done;
3834 committer_time = got_object_commit_get_committer_time(commit);
3835 datestr = get_datestr(&committer_time, datebuf);
3836 if (datestr) {
3837 n = fprintf(outfile, "date: %s UTC\n", datestr);
3838 if (n < 0) {
3839 err = got_error_from_errno("fprintf");
3840 goto done;
3842 outoff += n;
3843 err = add_line_offset(line_offsets, nlines, outoff);
3844 if (err)
3845 goto done;
3847 author = got_object_commit_get_author(commit);
3848 committer = got_object_commit_get_committer(commit);
3849 if (strcmp(author, committer) != 0) {
3850 n = fprintf(outfile, "via: %s\n", committer);
3851 if (n < 0) {
3852 err = got_error_from_errno("fprintf");
3853 goto done;
3855 outoff += n;
3856 err = add_line_offset(line_offsets, nlines, outoff);
3857 if (err)
3858 goto done;
3860 if (got_object_commit_get_nparents(commit) > 1) {
3861 const struct got_object_id_queue *parent_ids;
3862 struct got_object_qid *qid;
3863 int pn = 1;
3864 parent_ids = got_object_commit_get_parent_ids(commit);
3865 STAILQ_FOREACH(qid, parent_ids, entry) {
3866 err = got_object_id_str(&id_str, &qid->id);
3867 if (err)
3868 goto done;
3869 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
3870 if (n < 0) {
3871 err = got_error_from_errno("fprintf");
3872 goto done;
3874 outoff += n;
3875 err = add_line_offset(line_offsets, nlines, outoff);
3876 if (err)
3877 goto done;
3878 free(id_str);
3879 id_str = NULL;
3883 err = got_object_commit_get_logmsg(&logmsg, commit);
3884 if (err)
3885 goto done;
3886 s = logmsg;
3887 while ((line = strsep(&s, "\n")) != NULL) {
3888 n = fprintf(outfile, "%s\n", line);
3889 if (n < 0) {
3890 err = got_error_from_errno("fprintf");
3891 goto done;
3893 outoff += n;
3894 err = add_line_offset(line_offsets, nlines, outoff);
3895 if (err)
3896 goto done;
3899 err = get_changed_paths(&changed_paths, commit, repo);
3900 if (err)
3901 goto done;
3902 TAILQ_FOREACH(pe, &changed_paths, entry) {
3903 struct got_diff_changed_path *cp = pe->data;
3904 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
3905 if (n < 0) {
3906 err = got_error_from_errno("fprintf");
3907 goto done;
3909 outoff += n;
3910 err = add_line_offset(line_offsets, nlines, outoff);
3911 if (err)
3912 goto done;
3913 free((char *)pe->path);
3914 free(pe->data);
3917 fputc('\n', outfile);
3918 outoff++;
3919 err = add_line_offset(line_offsets, nlines, outoff);
3920 done:
3921 got_pathlist_free(&changed_paths);
3922 free(id_str);
3923 free(logmsg);
3924 free(refs_str);
3925 got_object_commit_close(commit);
3926 if (err) {
3927 free(*line_offsets);
3928 *line_offsets = NULL;
3929 *nlines = 0;
3931 return err;
3934 static const struct got_error *
3935 create_diff(struct tog_diff_view_state *s)
3937 const struct got_error *err = NULL;
3938 FILE *f = NULL;
3939 int obj_type;
3941 free(s->line_offsets);
3942 s->line_offsets = malloc(sizeof(off_t));
3943 if (s->line_offsets == NULL)
3944 return got_error_from_errno("malloc");
3945 s->nlines = 0;
3947 f = got_opentemp();
3948 if (f == NULL) {
3949 err = got_error_from_errno("got_opentemp");
3950 goto done;
3952 if (s->f && fclose(s->f) == EOF) {
3953 err = got_error_from_errno("fclose");
3954 goto done;
3956 s->f = f;
3958 if (s->id1)
3959 err = got_object_get_type(&obj_type, s->repo, s->id1);
3960 else
3961 err = got_object_get_type(&obj_type, s->repo, s->id2);
3962 if (err)
3963 goto done;
3965 switch (obj_type) {
3966 case GOT_OBJ_TYPE_BLOB:
3967 err = got_diff_objects_as_blobs(&s->line_offsets, &s->nlines,
3968 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
3969 s->label1, s->label2, s->diff_algo, s->diff_context,
3970 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
3971 break;
3972 case GOT_OBJ_TYPE_TREE:
3973 err = got_diff_objects_as_trees(&s->line_offsets, &s->nlines,
3974 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
3975 s->diff_algo, s->diff_context, s->ignore_whitespace,
3976 s->force_text_diff, s->repo, s->f);
3977 break;
3978 case GOT_OBJ_TYPE_COMMIT: {
3979 const struct got_object_id_queue *parent_ids;
3980 struct got_object_qid *pid;
3981 struct got_commit_object *commit2;
3982 struct got_reflist_head *refs;
3984 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
3985 if (err)
3986 goto done;
3987 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
3988 /* Show commit info if we're diffing to a parent/root commit. */
3989 if (s->id1 == NULL) {
3990 err = write_commit_info(&s->line_offsets, &s->nlines,
3991 s->id2, refs, s->repo, s->f);
3992 if (err)
3993 goto done;
3994 } else {
3995 parent_ids = got_object_commit_get_parent_ids(commit2);
3996 STAILQ_FOREACH(pid, parent_ids, entry) {
3997 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
3998 err = write_commit_info(
3999 &s->line_offsets, &s->nlines,
4000 s->id2, refs, s->repo, s->f);
4001 if (err)
4002 goto done;
4003 break;
4007 got_object_commit_close(commit2);
4009 err = got_diff_objects_as_commits(&s->line_offsets, &s->nlines,
4010 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4011 s->diff_algo, s->diff_context, s->ignore_whitespace,
4012 s->force_text_diff, s->repo, s->f);
4013 break;
4015 default:
4016 err = got_error(GOT_ERR_OBJ_TYPE);
4017 break;
4019 if (err)
4020 goto done;
4021 done:
4022 if (s->f && fflush(s->f) != 0 && err == NULL)
4023 err = got_error_from_errno("fflush");
4024 return err;
4027 static void
4028 diff_view_indicate_progress(struct tog_view *view)
4030 mvwaddstr(view->window, 0, 0, "diffing...");
4031 update_panels();
4032 doupdate();
4035 static const struct got_error *
4036 search_start_diff_view(struct tog_view *view)
4038 struct tog_diff_view_state *s = &view->state.diff;
4040 s->matched_line = 0;
4041 return NULL;
4044 static const struct got_error *
4045 search_next_diff_view(struct tog_view *view)
4047 struct tog_diff_view_state *s = &view->state.diff;
4048 const struct got_error *err = NULL;
4049 int lineno;
4050 char *line = NULL;
4051 size_t linesize = 0;
4052 ssize_t linelen;
4054 if (!view->searching) {
4055 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4056 return NULL;
4059 if (s->matched_line) {
4060 if (view->searching == TOG_SEARCH_FORWARD)
4061 lineno = s->matched_line + 1;
4062 else
4063 lineno = s->matched_line - 1;
4064 } else
4065 lineno = s->first_displayed_line;
4067 while (1) {
4068 off_t offset;
4070 if (lineno <= 0 || lineno > s->nlines) {
4071 if (s->matched_line == 0) {
4072 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4073 break;
4076 if (view->searching == TOG_SEARCH_FORWARD)
4077 lineno = 1;
4078 else
4079 lineno = s->nlines;
4082 offset = s->line_offsets[lineno - 1];
4083 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4084 free(line);
4085 return got_error_from_errno("fseeko");
4087 linelen = getline(&line, &linesize, s->f);
4088 if (linelen != -1) {
4089 char *exstr;
4090 err = expand_tab(&exstr, line);
4091 if (err)
4092 break;
4093 if (match_line(exstr, &view->regex, 1,
4094 &view->regmatch)) {
4095 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4096 s->matched_line = lineno;
4097 free(exstr);
4098 break;
4100 free(exstr);
4102 if (view->searching == TOG_SEARCH_FORWARD)
4103 lineno++;
4104 else
4105 lineno--;
4107 free(line);
4109 if (s->matched_line) {
4110 s->first_displayed_line = s->matched_line;
4111 s->selected_line = 1;
4114 return err;
4117 static const struct got_error *
4118 close_diff_view(struct tog_view *view)
4120 const struct got_error *err = NULL;
4121 struct tog_diff_view_state *s = &view->state.diff;
4123 free(s->id1);
4124 s->id1 = NULL;
4125 free(s->id2);
4126 s->id2 = NULL;
4127 if (s->f && fclose(s->f) == EOF)
4128 err = got_error_from_errno("fclose");
4129 s->f = NULL;
4130 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4131 err = got_error_from_errno("fclose");
4132 s->f1 = NULL;
4133 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4134 err = got_error_from_errno("fclose");
4135 s->f2 = NULL;
4136 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4137 err = got_error_from_errno("close");
4138 s->fd1 = -1;
4139 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4140 err = got_error_from_errno("close");
4141 s->fd2 = -1;
4142 free_colors(&s->colors);
4143 free(s->line_offsets);
4144 s->line_offsets = NULL;
4145 s->nlines = 0;
4146 return err;
4149 static const struct got_error *
4150 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4151 struct got_object_id *id2, const char *label1, const char *label2,
4152 int diff_context, int ignore_whitespace, int force_text_diff,
4153 struct tog_view *log_view, struct got_repository *repo)
4155 const struct got_error *err;
4156 struct tog_diff_view_state *s = &view->state.diff;
4158 memset(s, 0, sizeof(*s));
4159 s->fd1 = -1;
4160 s->fd2 = -1;
4162 if (id1 != NULL && id2 != NULL) {
4163 int type1, type2;
4164 err = got_object_get_type(&type1, repo, id1);
4165 if (err)
4166 return err;
4167 err = got_object_get_type(&type2, repo, id2);
4168 if (err)
4169 return err;
4171 if (type1 != type2)
4172 return got_error(GOT_ERR_OBJ_TYPE);
4174 s->first_displayed_line = 1;
4175 s->last_displayed_line = view->nlines;
4176 s->selected_line = 1;
4177 s->repo = repo;
4178 s->id1 = id1;
4179 s->id2 = id2;
4180 s->label1 = label1;
4181 s->label2 = label2;
4183 if (id1) {
4184 s->id1 = got_object_id_dup(id1);
4185 if (s->id1 == NULL)
4186 return got_error_from_errno("got_object_id_dup");
4187 } else
4188 s->id1 = NULL;
4190 s->id2 = got_object_id_dup(id2);
4191 if (s->id2 == NULL) {
4192 err = got_error_from_errno("got_object_id_dup");
4193 goto done;
4196 s->f1 = got_opentemp();
4197 if (s->f1 == NULL) {
4198 err = got_error_from_errno("got_opentemp");
4199 goto done;
4202 s->f2 = got_opentemp();
4203 if (s->f2 == NULL) {
4204 err = got_error_from_errno("got_opentemp");
4205 goto done;
4208 s->fd1 = got_opentempfd();
4209 if (s->fd1 == -1) {
4210 err = got_error_from_errno("got_opentempfd");
4211 goto done;
4214 s->fd2 = got_opentempfd();
4215 if (s->fd2 == -1) {
4216 err = got_error_from_errno("got_opentempfd");
4217 goto done;
4220 s->first_displayed_line = 1;
4221 s->last_displayed_line = view->nlines;
4222 s->diff_algo = GOT_DIFF_ALGORITHM_MYERS;
4223 s->diff_context = diff_context;
4224 s->ignore_whitespace = ignore_whitespace;
4225 s->force_text_diff = force_text_diff;
4226 s->log_view = log_view;
4227 s->repo = repo;
4229 STAILQ_INIT(&s->colors);
4230 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4231 err = add_color(&s->colors,
4232 "^-", TOG_COLOR_DIFF_MINUS,
4233 get_color_value("TOG_COLOR_DIFF_MINUS"));
4234 if (err)
4235 goto done;
4236 err = add_color(&s->colors, "^\\+",
4237 TOG_COLOR_DIFF_PLUS,
4238 get_color_value("TOG_COLOR_DIFF_PLUS"));
4239 if (err)
4240 goto done;
4241 err = add_color(&s->colors,
4242 "^@@", TOG_COLOR_DIFF_CHUNK_HEADER,
4243 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"));
4244 if (err)
4245 goto done;
4247 err = add_color(&s->colors,
4248 "^(commit [0-9a-f]|parent [0-9]|"
4249 "(blob|file|tree|commit) [-+] |"
4250 "[MDmA] [^ ])", TOG_COLOR_DIFF_META,
4251 get_color_value("TOG_COLOR_DIFF_META"));
4252 if (err)
4253 goto done;
4255 err = add_color(&s->colors,
4256 "^(from|via): ", TOG_COLOR_AUTHOR,
4257 get_color_value("TOG_COLOR_AUTHOR"));
4258 if (err)
4259 goto done;
4261 err = add_color(&s->colors,
4262 "^date: ", TOG_COLOR_DATE,
4263 get_color_value("TOG_COLOR_DATE"));
4264 if (err)
4265 goto done;
4268 if (log_view && view_is_splitscreen(view))
4269 show_log_view(log_view); /* draw vborder */
4270 diff_view_indicate_progress(view);
4272 err = create_diff(s);
4274 view->show = show_diff_view;
4275 view->input = input_diff_view;
4276 view->close = close_diff_view;
4277 view->search_start = search_start_diff_view;
4278 view->search_next = search_next_diff_view;
4279 done:
4280 if (err)
4281 close_diff_view(view);
4282 return err;
4285 static const struct got_error *
4286 show_diff_view(struct tog_view *view)
4288 const struct got_error *err;
4289 struct tog_diff_view_state *s = &view->state.diff;
4290 char *id_str1 = NULL, *id_str2, *header;
4291 const char *label1, *label2;
4293 if (s->id1) {
4294 err = got_object_id_str(&id_str1, s->id1);
4295 if (err)
4296 return err;
4297 label1 = s->label1 ? : id_str1;
4298 } else
4299 label1 = "/dev/null";
4301 err = got_object_id_str(&id_str2, s->id2);
4302 if (err)
4303 return err;
4304 label2 = s->label2 ? : id_str2;
4306 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4307 err = got_error_from_errno("asprintf");
4308 free(id_str1);
4309 free(id_str2);
4310 return err;
4312 free(id_str1);
4313 free(id_str2);
4315 err = draw_file(view, header);
4316 free(header);
4317 return err;
4320 static const struct got_error *
4321 set_selected_commit(struct tog_diff_view_state *s,
4322 struct commit_queue_entry *entry)
4324 const struct got_error *err;
4325 const struct got_object_id_queue *parent_ids;
4326 struct got_commit_object *selected_commit;
4327 struct got_object_qid *pid;
4329 free(s->id2);
4330 s->id2 = got_object_id_dup(entry->id);
4331 if (s->id2 == NULL)
4332 return got_error_from_errno("got_object_id_dup");
4334 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4335 if (err)
4336 return err;
4337 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4338 free(s->id1);
4339 pid = STAILQ_FIRST(parent_ids);
4340 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4341 got_object_commit_close(selected_commit);
4342 return NULL;
4345 static const struct got_error *
4346 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4348 const struct got_error *err = NULL;
4349 struct tog_diff_view_state *s = &view->state.diff;
4350 struct tog_log_view_state *ls;
4351 struct commit_queue_entry *old_selected_entry;
4352 char *line = NULL;
4353 size_t linesize = 0;
4354 ssize_t linelen;
4355 int i, nscroll = view->nlines - 1;
4357 switch (ch) {
4358 case '0':
4359 view->x = 0;
4360 break;
4361 case '$':
4362 view->x = MAX(view->maxx - view->ncols / 3, 0);
4363 view->count = 0;
4364 break;
4365 case KEY_RIGHT:
4366 case 'l':
4367 if (view->x + view->ncols / 3 < view->maxx)
4368 view->x += 2; /* move two columns right */
4369 else
4370 view->count = 0;
4371 break;
4372 case KEY_LEFT:
4373 case 'h':
4374 view->x -= MIN(view->x, 2); /* move two columns back */
4375 if (view->x <= 0)
4376 view->count = 0;
4377 break;
4378 case 'a':
4379 case 'w':
4380 if (ch == 'a')
4381 s->force_text_diff = !s->force_text_diff;
4382 if (ch == 'w')
4383 s->ignore_whitespace = !s->ignore_whitespace;
4384 wclear(view->window);
4385 s->first_displayed_line = 1;
4386 s->last_displayed_line = view->nlines;
4387 s->matched_line = 0;
4388 diff_view_indicate_progress(view);
4389 err = create_diff(s);
4390 view->count = 0;
4391 break;
4392 case 'g':
4393 case KEY_HOME:
4394 s->first_displayed_line = 1;
4395 view->count = 0;
4396 break;
4397 case 'G':
4398 case KEY_END:
4399 view->count = 0;
4400 if (s->eof)
4401 break;
4403 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4404 s->eof = 1;
4405 break;
4406 case 'k':
4407 case KEY_UP:
4408 case CTRL('p'):
4409 if (s->first_displayed_line > 1)
4410 s->first_displayed_line--;
4411 else
4412 view->count = 0;
4413 break;
4414 case CTRL('u'):
4415 case 'u':
4416 nscroll /= 2;
4417 /* FALL THROUGH */
4418 case KEY_PPAGE:
4419 case CTRL('b'):
4420 case 'b':
4421 if (s->first_displayed_line == 1) {
4422 view->count = 0;
4423 break;
4425 i = 0;
4426 while (i++ < nscroll && s->first_displayed_line > 1)
4427 s->first_displayed_line--;
4428 break;
4429 case 'j':
4430 case KEY_DOWN:
4431 case CTRL('n'):
4432 if (!s->eof)
4433 s->first_displayed_line++;
4434 else
4435 view->count = 0;
4436 break;
4437 case CTRL('d'):
4438 case 'd':
4439 nscroll /= 2;
4440 /* FALL THROUGH */
4441 case KEY_NPAGE:
4442 case CTRL('f'):
4443 case 'f':
4444 case ' ':
4445 if (s->eof) {
4446 view->count = 0;
4447 break;
4449 i = 0;
4450 while (!s->eof && i++ < nscroll) {
4451 linelen = getline(&line, &linesize, s->f);
4452 s->first_displayed_line++;
4453 if (linelen == -1) {
4454 if (feof(s->f)) {
4455 s->eof = 1;
4456 } else
4457 err = got_ferror(s->f, GOT_ERR_IO);
4458 break;
4461 free(line);
4462 break;
4463 case '[':
4464 if (s->diff_context > 0) {
4465 s->diff_context--;
4466 s->matched_line = 0;
4467 diff_view_indicate_progress(view);
4468 err = create_diff(s);
4469 if (s->first_displayed_line + view->nlines - 1 >
4470 s->nlines) {
4471 s->first_displayed_line = 1;
4472 s->last_displayed_line = view->nlines;
4474 } else
4475 view->count = 0;
4476 break;
4477 case ']':
4478 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4479 s->diff_context++;
4480 s->matched_line = 0;
4481 diff_view_indicate_progress(view);
4482 err = create_diff(s);
4483 } else
4484 view->count = 0;
4485 break;
4486 case '<':
4487 case ',':
4488 if (s->log_view == NULL) {
4489 view->count = 0;
4490 break;
4492 ls = &s->log_view->state.log;
4493 old_selected_entry = ls->selected_entry;
4495 /* view->count handled in input_log_view() */
4496 err = input_log_view(NULL, s->log_view, KEY_UP);
4497 if (err)
4498 break;
4500 if (old_selected_entry == ls->selected_entry)
4501 break;
4503 err = set_selected_commit(s, ls->selected_entry);
4504 if (err)
4505 break;
4507 s->first_displayed_line = 1;
4508 s->last_displayed_line = view->nlines;
4509 s->matched_line = 0;
4510 view->x = 0;
4512 diff_view_indicate_progress(view);
4513 err = create_diff(s);
4514 break;
4515 case '>':
4516 case '.':
4517 if (s->log_view == NULL) {
4518 view->count = 0;
4519 break;
4521 ls = &s->log_view->state.log;
4522 old_selected_entry = ls->selected_entry;
4524 /* view->count handled in input_log_view() */
4525 err = input_log_view(NULL, s->log_view, KEY_DOWN);
4526 if (err)
4527 break;
4529 if (old_selected_entry == ls->selected_entry)
4530 break;
4532 err = set_selected_commit(s, ls->selected_entry);
4533 if (err)
4534 break;
4536 s->first_displayed_line = 1;
4537 s->last_displayed_line = view->nlines;
4538 s->matched_line = 0;
4539 view->x = 0;
4541 diff_view_indicate_progress(view);
4542 err = create_diff(s);
4543 break;
4544 default:
4545 view->count = 0;
4546 break;
4549 return err;
4552 static const struct got_error *
4553 cmd_diff(int argc, char *argv[])
4555 const struct got_error *error = NULL;
4556 struct got_repository *repo = NULL;
4557 struct got_worktree *worktree = NULL;
4558 struct got_object_id *id1 = NULL, *id2 = NULL;
4559 char *repo_path = NULL, *cwd = NULL;
4560 char *id_str1 = NULL, *id_str2 = NULL;
4561 char *label1 = NULL, *label2 = NULL;
4562 int diff_context = 3, ignore_whitespace = 0;
4563 int ch, force_text_diff = 0;
4564 const char *errstr;
4565 struct tog_view *view;
4566 int *pack_fds = NULL;
4568 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
4569 switch (ch) {
4570 case 'a':
4571 force_text_diff = 1;
4572 break;
4573 case 'C':
4574 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4575 &errstr);
4576 if (errstr != NULL)
4577 errx(1, "number of context lines is %s: %s",
4578 errstr, errstr);
4579 break;
4580 case 'r':
4581 repo_path = realpath(optarg, NULL);
4582 if (repo_path == NULL)
4583 return got_error_from_errno2("realpath",
4584 optarg);
4585 got_path_strip_trailing_slashes(repo_path);
4586 break;
4587 case 'w':
4588 ignore_whitespace = 1;
4589 break;
4590 default:
4591 usage_diff();
4592 /* NOTREACHED */
4596 argc -= optind;
4597 argv += optind;
4599 if (argc == 0) {
4600 usage_diff(); /* TODO show local worktree changes */
4601 } else if (argc == 2) {
4602 id_str1 = argv[0];
4603 id_str2 = argv[1];
4604 } else
4605 usage_diff();
4607 error = got_repo_pack_fds_open(&pack_fds);
4608 if (error)
4609 goto done;
4611 if (repo_path == NULL) {
4612 cwd = getcwd(NULL, 0);
4613 if (cwd == NULL)
4614 return got_error_from_errno("getcwd");
4615 error = got_worktree_open(&worktree, cwd);
4616 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4617 goto done;
4618 if (worktree)
4619 repo_path =
4620 strdup(got_worktree_get_repo_path(worktree));
4621 else
4622 repo_path = strdup(cwd);
4623 if (repo_path == NULL) {
4624 error = got_error_from_errno("strdup");
4625 goto done;
4629 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4630 if (error)
4631 goto done;
4633 init_curses();
4635 error = apply_unveil(got_repo_get_path(repo), NULL);
4636 if (error)
4637 goto done;
4639 error = tog_load_refs(repo, 0);
4640 if (error)
4641 goto done;
4643 error = got_repo_match_object_id(&id1, &label1, id_str1,
4644 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4645 if (error)
4646 goto done;
4648 error = got_repo_match_object_id(&id2, &label2, id_str2,
4649 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
4650 if (error)
4651 goto done;
4653 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
4654 if (view == NULL) {
4655 error = got_error_from_errno("view_open");
4656 goto done;
4658 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
4659 ignore_whitespace, force_text_diff, NULL, repo);
4660 if (error)
4661 goto done;
4662 error = view_loop(view);
4663 done:
4664 free(label1);
4665 free(label2);
4666 free(repo_path);
4667 free(cwd);
4668 if (repo) {
4669 const struct got_error *close_err = got_repo_close(repo);
4670 if (error == NULL)
4671 error = close_err;
4673 if (worktree)
4674 got_worktree_close(worktree);
4675 if (pack_fds) {
4676 const struct got_error *pack_err =
4677 got_repo_pack_fds_close(pack_fds);
4678 if (error == NULL)
4679 error = pack_err;
4681 tog_free_refs();
4682 return error;
4685 __dead static void
4686 usage_blame(void)
4688 endwin();
4689 fprintf(stderr,
4690 "usage: %s blame [-c commit] [-r repository-path] path\n",
4691 getprogname());
4692 exit(1);
4695 struct tog_blame_line {
4696 int annotated;
4697 struct got_object_id *id;
4700 static const struct got_error *
4701 draw_blame(struct tog_view *view)
4703 struct tog_blame_view_state *s = &view->state.blame;
4704 struct tog_blame *blame = &s->blame;
4705 regmatch_t *regmatch = &view->regmatch;
4706 const struct got_error *err;
4707 int lineno = 0, nprinted = 0;
4708 char *line = NULL;
4709 size_t linesize = 0;
4710 ssize_t linelen;
4711 wchar_t *wline;
4712 int width;
4713 struct tog_blame_line *blame_line;
4714 struct got_object_id *prev_id = NULL;
4715 char *id_str;
4716 struct tog_color *tc;
4718 err = got_object_id_str(&id_str, &s->blamed_commit->id);
4719 if (err)
4720 return err;
4722 rewind(blame->f);
4723 werase(view->window);
4725 if (asprintf(&line, "commit %s", id_str) == -1) {
4726 err = got_error_from_errno("asprintf");
4727 free(id_str);
4728 return err;
4731 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4732 free(line);
4733 line = NULL;
4734 if (err)
4735 return err;
4736 if (view_needs_focus_indication(view))
4737 wstandout(view->window);
4738 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4739 if (tc)
4740 wattr_on(view->window,
4741 COLOR_PAIR(tc->colorpair), NULL);
4742 waddwstr(view->window, wline);
4743 if (tc)
4744 wattr_off(view->window,
4745 COLOR_PAIR(tc->colorpair), NULL);
4746 if (view_needs_focus_indication(view))
4747 wstandend(view->window);
4748 free(wline);
4749 wline = NULL;
4750 if (width < view->ncols - 1)
4751 waddch(view->window, '\n');
4753 if (asprintf(&line, "[%d/%d] %s%s",
4754 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
4755 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
4756 free(id_str);
4757 return got_error_from_errno("asprintf");
4759 free(id_str);
4760 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
4761 free(line);
4762 line = NULL;
4763 if (err)
4764 return err;
4765 waddwstr(view->window, wline);
4766 free(wline);
4767 wline = NULL;
4768 if (width < view->ncols - 1)
4769 waddch(view->window, '\n');
4771 s->eof = 0;
4772 view->maxx = 0;
4773 while (nprinted < view->nlines - 2) {
4774 linelen = getline(&line, &linesize, blame->f);
4775 if (linelen == -1) {
4776 if (feof(blame->f)) {
4777 s->eof = 1;
4778 break;
4780 free(line);
4781 return got_ferror(blame->f, GOT_ERR_IO);
4783 if (++lineno < s->first_displayed_line)
4784 continue;
4786 /* Set view->maxx based on full line length. */
4787 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
4788 if (err) {
4789 free(line);
4790 return err;
4792 free(wline);
4793 wline = NULL;
4794 view->maxx = MAX(view->maxx, width);
4796 if (view->focussed && nprinted == s->selected_line - 1)
4797 wstandout(view->window);
4799 if (blame->nlines > 0) {
4800 blame_line = &blame->lines[lineno - 1];
4801 if (blame_line->annotated && prev_id &&
4802 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
4803 !(view->focussed &&
4804 nprinted == s->selected_line - 1)) {
4805 waddstr(view->window, " ");
4806 } else if (blame_line->annotated) {
4807 char *id_str;
4808 err = got_object_id_str(&id_str,
4809 blame_line->id);
4810 if (err) {
4811 free(line);
4812 return err;
4814 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
4815 if (tc)
4816 wattr_on(view->window,
4817 COLOR_PAIR(tc->colorpair), NULL);
4818 wprintw(view->window, "%.8s", id_str);
4819 if (tc)
4820 wattr_off(view->window,
4821 COLOR_PAIR(tc->colorpair), NULL);
4822 free(id_str);
4823 prev_id = blame_line->id;
4824 } else {
4825 waddstr(view->window, "........");
4826 prev_id = NULL;
4828 } else {
4829 waddstr(view->window, "........");
4830 prev_id = NULL;
4833 if (view->focussed && nprinted == s->selected_line - 1)
4834 wstandend(view->window);
4835 waddstr(view->window, " ");
4837 if (view->ncols <= 9) {
4838 width = 9;
4839 } else if (s->first_displayed_line + nprinted ==
4840 s->matched_line &&
4841 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4842 err = add_matched_line(&width, line, view->ncols - 9, 9,
4843 view->window, view->x, regmatch);
4844 if (err) {
4845 free(line);
4846 return err;
4848 width += 9;
4849 } else {
4850 int skip;
4851 err = format_line(&wline, &width, &skip, line,
4852 view->x, view->ncols - 9, 9, 1);
4853 if (err) {
4854 free(line);
4855 return err;
4857 waddwstr(view->window, &wline[skip]);
4858 width += 9;
4859 free(wline);
4860 wline = NULL;
4863 if (width <= view->ncols - 1)
4864 waddch(view->window, '\n');
4865 if (++nprinted == 1)
4866 s->first_displayed_line = lineno;
4868 free(line);
4869 s->last_displayed_line = lineno;
4871 view_border(view);
4873 return NULL;
4876 static const struct got_error *
4877 blame_cb(void *arg, int nlines, int lineno,
4878 struct got_commit_object *commit, struct got_object_id *id)
4880 const struct got_error *err = NULL;
4881 struct tog_blame_cb_args *a = arg;
4882 struct tog_blame_line *line;
4883 int errcode;
4885 if (nlines != a->nlines ||
4886 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4887 return got_error(GOT_ERR_RANGE);
4889 errcode = pthread_mutex_lock(&tog_mutex);
4890 if (errcode)
4891 return got_error_set_errno(errcode, "pthread_mutex_lock");
4893 if (*a->quit) { /* user has quit the blame view */
4894 err = got_error(GOT_ERR_ITER_COMPLETED);
4895 goto done;
4898 if (lineno == -1)
4899 goto done; /* no change in this commit */
4901 line = &a->lines[lineno - 1];
4902 if (line->annotated)
4903 goto done;
4905 line->id = got_object_id_dup(id);
4906 if (line->id == NULL) {
4907 err = got_error_from_errno("got_object_id_dup");
4908 goto done;
4910 line->annotated = 1;
4911 done:
4912 errcode = pthread_mutex_unlock(&tog_mutex);
4913 if (errcode)
4914 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4915 return err;
4918 static void *
4919 blame_thread(void *arg)
4921 const struct got_error *err, *close_err;
4922 struct tog_blame_thread_args *ta = arg;
4923 struct tog_blame_cb_args *a = ta->cb_args;
4924 int errcode, fd1 = -1, fd2 = -1;
4925 FILE *f1 = NULL, *f2 = NULL;
4927 fd1 = got_opentempfd();
4928 if (fd1 == -1)
4929 return (void *)got_error_from_errno("got_opentempfd");
4931 fd2 = got_opentempfd();
4932 if (fd2 == -1) {
4933 err = got_error_from_errno("got_opentempfd");
4934 goto done;
4937 f1 = got_opentemp();
4938 if (f1 == NULL) {
4939 err = (void *)got_error_from_errno("got_opentemp");
4940 goto done;
4942 f2 = got_opentemp();
4943 if (f2 == NULL) {
4944 err = (void *)got_error_from_errno("got_opentemp");
4945 goto done;
4948 err = block_signals_used_by_main_thread();
4949 if (err)
4950 goto done;
4952 err = got_blame(ta->path, a->commit_id, ta->repo,
4953 GOT_DIFF_ALGORITHM_MYERS, blame_cb, ta->cb_args,
4954 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
4955 if (err && err->code == GOT_ERR_CANCELLED)
4956 err = NULL;
4958 errcode = pthread_mutex_lock(&tog_mutex);
4959 if (errcode) {
4960 err = got_error_set_errno(errcode, "pthread_mutex_lock");
4961 goto done;
4964 close_err = got_repo_close(ta->repo);
4965 if (err == NULL)
4966 err = close_err;
4967 ta->repo = NULL;
4968 *ta->complete = 1;
4970 errcode = pthread_mutex_unlock(&tog_mutex);
4971 if (errcode && err == NULL)
4972 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
4974 done:
4975 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4976 err = got_error_from_errno("close");
4977 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4978 err = got_error_from_errno("close");
4979 if (f1 && fclose(f1) == EOF && err == NULL)
4980 err = got_error_from_errno("fclose");
4981 if (f2 && fclose(f2) == EOF && err == NULL)
4982 err = got_error_from_errno("fclose");
4984 return (void *)err;
4987 static struct got_object_id *
4988 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
4989 int first_displayed_line, int selected_line)
4991 struct tog_blame_line *line;
4993 if (nlines <= 0)
4994 return NULL;
4996 line = &lines[first_displayed_line - 1 + selected_line - 1];
4997 if (!line->annotated)
4998 return NULL;
5000 return line->id;
5003 static const struct got_error *
5004 stop_blame(struct tog_blame *blame)
5006 const struct got_error *err = NULL;
5007 int i;
5009 if (blame->thread) {
5010 int errcode;
5011 errcode = pthread_mutex_unlock(&tog_mutex);
5012 if (errcode)
5013 return got_error_set_errno(errcode,
5014 "pthread_mutex_unlock");
5015 errcode = pthread_join(blame->thread, (void **)&err);
5016 if (errcode)
5017 return got_error_set_errno(errcode, "pthread_join");
5018 errcode = pthread_mutex_lock(&tog_mutex);
5019 if (errcode)
5020 return got_error_set_errno(errcode,
5021 "pthread_mutex_lock");
5022 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5023 err = NULL;
5024 blame->thread = NULL;
5026 if (blame->thread_args.repo) {
5027 const struct got_error *close_err;
5028 close_err = got_repo_close(blame->thread_args.repo);
5029 if (err == NULL)
5030 err = close_err;
5031 blame->thread_args.repo = NULL;
5033 if (blame->f) {
5034 if (fclose(blame->f) == EOF && err == NULL)
5035 err = got_error_from_errno("fclose");
5036 blame->f = NULL;
5038 if (blame->lines) {
5039 for (i = 0; i < blame->nlines; i++)
5040 free(blame->lines[i].id);
5041 free(blame->lines);
5042 blame->lines = NULL;
5044 free(blame->cb_args.commit_id);
5045 blame->cb_args.commit_id = NULL;
5046 if (blame->pack_fds) {
5047 const struct got_error *pack_err =
5048 got_repo_pack_fds_close(blame->pack_fds);
5049 if (err == NULL)
5050 err = pack_err;
5051 blame->pack_fds = NULL;
5053 return err;
5056 static const struct got_error *
5057 cancel_blame_view(void *arg)
5059 const struct got_error *err = NULL;
5060 int *done = arg;
5061 int errcode;
5063 errcode = pthread_mutex_lock(&tog_mutex);
5064 if (errcode)
5065 return got_error_set_errno(errcode,
5066 "pthread_mutex_unlock");
5068 if (*done)
5069 err = got_error(GOT_ERR_CANCELLED);
5071 errcode = pthread_mutex_unlock(&tog_mutex);
5072 if (errcode)
5073 return got_error_set_errno(errcode,
5074 "pthread_mutex_lock");
5076 return err;
5079 static const struct got_error *
5080 run_blame(struct tog_view *view)
5082 struct tog_blame_view_state *s = &view->state.blame;
5083 struct tog_blame *blame = &s->blame;
5084 const struct got_error *err = NULL;
5085 struct got_commit_object *commit = NULL;
5086 struct got_blob_object *blob = NULL;
5087 struct got_repository *thread_repo = NULL;
5088 struct got_object_id *obj_id = NULL;
5089 int obj_type, fd = -1;
5090 int *pack_fds = NULL;
5092 err = got_object_open_as_commit(&commit, s->repo,
5093 &s->blamed_commit->id);
5094 if (err)
5095 return err;
5097 fd = got_opentempfd();
5098 if (fd == -1) {
5099 err = got_error_from_errno("got_opentempfd");
5100 goto done;
5103 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5104 if (err)
5105 goto done;
5107 err = got_object_get_type(&obj_type, s->repo, obj_id);
5108 if (err)
5109 goto done;
5111 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5112 err = got_error(GOT_ERR_OBJ_TYPE);
5113 goto done;
5116 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5117 if (err)
5118 goto done;
5119 blame->f = got_opentemp();
5120 if (blame->f == NULL) {
5121 err = got_error_from_errno("got_opentemp");
5122 goto done;
5124 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5125 &blame->line_offsets, blame->f, blob);
5126 if (err)
5127 goto done;
5128 if (blame->nlines == 0) {
5129 s->blame_complete = 1;
5130 goto done;
5133 /* Don't include \n at EOF in the blame line count. */
5134 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5135 blame->nlines--;
5137 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5138 if (blame->lines == NULL) {
5139 err = got_error_from_errno("calloc");
5140 goto done;
5143 err = got_repo_pack_fds_open(&pack_fds);
5144 if (err)
5145 goto done;
5146 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5147 pack_fds);
5148 if (err)
5149 goto done;
5151 blame->pack_fds = pack_fds;
5152 blame->cb_args.view = view;
5153 blame->cb_args.lines = blame->lines;
5154 blame->cb_args.nlines = blame->nlines;
5155 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5156 if (blame->cb_args.commit_id == NULL) {
5157 err = got_error_from_errno("got_object_id_dup");
5158 goto done;
5160 blame->cb_args.quit = &s->done;
5162 blame->thread_args.path = s->path;
5163 blame->thread_args.repo = thread_repo;
5164 blame->thread_args.cb_args = &blame->cb_args;
5165 blame->thread_args.complete = &s->blame_complete;
5166 blame->thread_args.cancel_cb = cancel_blame_view;
5167 blame->thread_args.cancel_arg = &s->done;
5168 s->blame_complete = 0;
5170 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5171 s->first_displayed_line = 1;
5172 s->last_displayed_line = view->nlines;
5173 s->selected_line = 1;
5175 s->matched_line = 0;
5177 done:
5178 if (commit)
5179 got_object_commit_close(commit);
5180 if (fd != -1 && close(fd) == -1 && err == NULL)
5181 err = got_error_from_errno("close");
5182 if (blob)
5183 got_object_blob_close(blob);
5184 free(obj_id);
5185 if (err)
5186 stop_blame(blame);
5187 return err;
5190 static const struct got_error *
5191 open_blame_view(struct tog_view *view, char *path,
5192 struct got_object_id *commit_id, struct got_repository *repo)
5194 const struct got_error *err = NULL;
5195 struct tog_blame_view_state *s = &view->state.blame;
5197 STAILQ_INIT(&s->blamed_commits);
5199 s->path = strdup(path);
5200 if (s->path == NULL)
5201 return got_error_from_errno("strdup");
5203 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5204 if (err) {
5205 free(s->path);
5206 return err;
5209 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5210 s->first_displayed_line = 1;
5211 s->last_displayed_line = view->nlines;
5212 s->selected_line = 1;
5213 s->blame_complete = 0;
5214 s->repo = repo;
5215 s->commit_id = commit_id;
5216 memset(&s->blame, 0, sizeof(s->blame));
5218 STAILQ_INIT(&s->colors);
5219 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5220 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5221 get_color_value("TOG_COLOR_COMMIT"));
5222 if (err)
5223 return err;
5226 view->show = show_blame_view;
5227 view->input = input_blame_view;
5228 view->close = close_blame_view;
5229 view->search_start = search_start_blame_view;
5230 view->search_next = search_next_blame_view;
5232 return run_blame(view);
5235 static const struct got_error *
5236 close_blame_view(struct tog_view *view)
5238 const struct got_error *err = NULL;
5239 struct tog_blame_view_state *s = &view->state.blame;
5241 if (s->blame.thread)
5242 err = stop_blame(&s->blame);
5244 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5245 struct got_object_qid *blamed_commit;
5246 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5247 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5248 got_object_qid_free(blamed_commit);
5251 free(s->path);
5252 free_colors(&s->colors);
5253 return err;
5256 static const struct got_error *
5257 search_start_blame_view(struct tog_view *view)
5259 struct tog_blame_view_state *s = &view->state.blame;
5261 s->matched_line = 0;
5262 return NULL;
5265 static const struct got_error *
5266 search_next_blame_view(struct tog_view *view)
5268 struct tog_blame_view_state *s = &view->state.blame;
5269 const struct got_error *err = NULL;
5270 int lineno;
5271 char *line = NULL;
5272 size_t linesize = 0;
5273 ssize_t linelen;
5275 if (!view->searching) {
5276 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5277 return NULL;
5280 if (s->matched_line) {
5281 if (view->searching == TOG_SEARCH_FORWARD)
5282 lineno = s->matched_line + 1;
5283 else
5284 lineno = s->matched_line - 1;
5285 } else
5286 lineno = s->first_displayed_line - 1 + s->selected_line;
5288 while (1) {
5289 off_t offset;
5291 if (lineno <= 0 || lineno > s->blame.nlines) {
5292 if (s->matched_line == 0) {
5293 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5294 break;
5297 if (view->searching == TOG_SEARCH_FORWARD)
5298 lineno = 1;
5299 else
5300 lineno = s->blame.nlines;
5303 offset = s->blame.line_offsets[lineno - 1];
5304 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5305 free(line);
5306 return got_error_from_errno("fseeko");
5308 linelen = getline(&line, &linesize, s->blame.f);
5309 if (linelen != -1) {
5310 char *exstr;
5311 err = expand_tab(&exstr, line);
5312 if (err)
5313 break;
5314 if (match_line(exstr, &view->regex, 1,
5315 &view->regmatch)) {
5316 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5317 s->matched_line = lineno;
5318 free(exstr);
5319 break;
5321 free(exstr);
5323 if (view->searching == TOG_SEARCH_FORWARD)
5324 lineno++;
5325 else
5326 lineno--;
5328 free(line);
5330 if (s->matched_line) {
5331 s->first_displayed_line = s->matched_line;
5332 s->selected_line = 1;
5335 return err;
5338 static const struct got_error *
5339 show_blame_view(struct tog_view *view)
5341 const struct got_error *err = NULL;
5342 struct tog_blame_view_state *s = &view->state.blame;
5343 int errcode;
5345 if (s->blame.thread == NULL && !s->blame_complete) {
5346 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5347 &s->blame.thread_args);
5348 if (errcode)
5349 return got_error_set_errno(errcode, "pthread_create");
5351 halfdelay(1); /* fast refresh while annotating */
5354 if (s->blame_complete)
5355 halfdelay(10); /* disable fast refresh */
5357 err = draw_blame(view);
5359 view_border(view);
5360 return err;
5363 static const struct got_error *
5364 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5366 const struct got_error *err = NULL, *thread_err = NULL;
5367 struct tog_view *diff_view;
5368 struct tog_blame_view_state *s = &view->state.blame;
5369 int eos, nscroll, begin_y = 0, begin_x = 0;
5371 eos = nscroll = view->nlines - 2;
5372 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
5373 view_is_splitscreen(view->child))
5374 --eos; /* border */
5376 switch (ch) {
5377 case '0':
5378 view->x = 0;
5379 break;
5380 case '$':
5381 view->x = MAX(view->maxx - view->ncols / 3, 0);
5382 view->count = 0;
5383 break;
5384 case KEY_RIGHT:
5385 case 'l':
5386 if (view->x + view->ncols / 3 < view->maxx)
5387 view->x += 2; /* move two columns right */
5388 else
5389 view->count = 0;
5390 break;
5391 case KEY_LEFT:
5392 case 'h':
5393 view->x -= MIN(view->x, 2); /* move two columns back */
5394 if (view->x <= 0)
5395 view->count = 0;
5396 break;
5397 case 'q':
5398 s->done = 1;
5399 break;
5400 case 'g':
5401 case KEY_HOME:
5402 s->selected_line = 1;
5403 s->first_displayed_line = 1;
5404 view->count = 0;
5405 break;
5406 case 'G':
5407 case KEY_END:
5408 if (s->blame.nlines < eos) {
5409 s->selected_line = s->blame.nlines;
5410 s->first_displayed_line = 1;
5411 } else {
5412 s->selected_line = eos;
5413 s->first_displayed_line = s->blame.nlines - (eos - 1);
5415 view->count = 0;
5416 break;
5417 case 'k':
5418 case KEY_UP:
5419 case CTRL('p'):
5420 if (s->selected_line > 1)
5421 s->selected_line--;
5422 else if (s->selected_line == 1 &&
5423 s->first_displayed_line > 1)
5424 s->first_displayed_line--;
5425 else
5426 view->count = 0;
5427 break;
5428 case CTRL('u'):
5429 case 'u':
5430 nscroll /= 2;
5431 /* FALL THROUGH */
5432 case KEY_PPAGE:
5433 case CTRL('b'):
5434 case 'b':
5435 if (s->first_displayed_line == 1) {
5436 if (view->count > 1)
5437 nscroll += nscroll;
5438 s->selected_line = MAX(1, s->selected_line - nscroll);
5439 view->count = 0;
5440 break;
5442 if (s->first_displayed_line > nscroll)
5443 s->first_displayed_line -= nscroll;
5444 else
5445 s->first_displayed_line = 1;
5446 break;
5447 case 'j':
5448 case KEY_DOWN:
5449 case CTRL('n'):
5450 if (s->selected_line < eos && s->first_displayed_line +
5451 s->selected_line <= s->blame.nlines)
5452 s->selected_line++;
5453 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5454 s->first_displayed_line++;
5455 else
5456 view->count = 0;
5457 break;
5458 case 'c':
5459 case 'p': {
5460 struct got_object_id *id = NULL;
5462 view->count = 0;
5463 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5464 s->first_displayed_line, s->selected_line);
5465 if (id == NULL)
5466 break;
5467 if (ch == 'p') {
5468 struct got_commit_object *commit, *pcommit;
5469 struct got_object_qid *pid;
5470 struct got_object_id *blob_id = NULL;
5471 int obj_type;
5472 err = got_object_open_as_commit(&commit,
5473 s->repo, id);
5474 if (err)
5475 break;
5476 pid = STAILQ_FIRST(
5477 got_object_commit_get_parent_ids(commit));
5478 if (pid == NULL) {
5479 got_object_commit_close(commit);
5480 break;
5482 /* Check if path history ends here. */
5483 err = got_object_open_as_commit(&pcommit,
5484 s->repo, &pid->id);
5485 if (err)
5486 break;
5487 err = got_object_id_by_path(&blob_id, s->repo,
5488 pcommit, s->path);
5489 got_object_commit_close(pcommit);
5490 if (err) {
5491 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5492 err = NULL;
5493 got_object_commit_close(commit);
5494 break;
5496 err = got_object_get_type(&obj_type, s->repo,
5497 blob_id);
5498 free(blob_id);
5499 /* Can't blame non-blob type objects. */
5500 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5501 got_object_commit_close(commit);
5502 break;
5504 err = got_object_qid_alloc(&s->blamed_commit,
5505 &pid->id);
5506 got_object_commit_close(commit);
5507 } else {
5508 if (got_object_id_cmp(id,
5509 &s->blamed_commit->id) == 0)
5510 break;
5511 err = got_object_qid_alloc(&s->blamed_commit,
5512 id);
5514 if (err)
5515 break;
5516 s->done = 1;
5517 thread_err = stop_blame(&s->blame);
5518 s->done = 0;
5519 if (thread_err)
5520 break;
5521 STAILQ_INSERT_HEAD(&s->blamed_commits,
5522 s->blamed_commit, entry);
5523 err = run_blame(view);
5524 if (err)
5525 break;
5526 break;
5528 case 'C': {
5529 struct got_object_qid *first;
5531 view->count = 0;
5532 first = STAILQ_FIRST(&s->blamed_commits);
5533 if (!got_object_id_cmp(&first->id, s->commit_id))
5534 break;
5535 s->done = 1;
5536 thread_err = stop_blame(&s->blame);
5537 s->done = 0;
5538 if (thread_err)
5539 break;
5540 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5541 got_object_qid_free(s->blamed_commit);
5542 s->blamed_commit =
5543 STAILQ_FIRST(&s->blamed_commits);
5544 err = run_blame(view);
5545 if (err)
5546 break;
5547 break;
5549 case KEY_ENTER:
5550 case '\r': {
5551 struct got_object_id *id = NULL;
5552 struct got_object_qid *pid;
5553 struct got_commit_object *commit = NULL;
5555 view->count = 0;
5556 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5557 s->first_displayed_line, s->selected_line);
5558 if (id == NULL)
5559 break;
5560 err = got_object_open_as_commit(&commit, s->repo, id);
5561 if (err)
5562 break;
5563 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
5564 if (view_is_parent_view(view))
5565 view_get_split(view, &begin_y, &begin_x);
5567 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
5568 if (diff_view == NULL) {
5569 got_object_commit_close(commit);
5570 err = got_error_from_errno("view_open");
5571 break;
5573 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
5574 id, NULL, NULL, 3, 0, 0, NULL, s->repo);
5575 got_object_commit_close(commit);
5576 if (err) {
5577 view_close(diff_view);
5578 break;
5580 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
5581 err = view_init_hsplit(view, begin_y);
5582 if (err)
5583 break;
5586 view->focussed = 0;
5587 diff_view->focussed = 1;
5588 diff_view->mode = view->mode;
5589 diff_view->nlines = view->lines - begin_y;
5590 if (view_is_parent_view(view)) {
5591 err = view_close_child(view);
5592 if (err)
5593 break;
5594 err = view_set_child(view, diff_view);
5595 if (err)
5596 break;
5597 view->focus_child = 1;
5598 } else
5599 *new_view = diff_view;
5600 if (err)
5601 break;
5602 break;
5604 case CTRL('d'):
5605 case 'd':
5606 nscroll /= 2;
5607 /* FALL THROUGH */
5608 case KEY_NPAGE:
5609 case CTRL('f'):
5610 case 'f':
5611 case ' ':
5612 if (s->last_displayed_line >= s->blame.nlines &&
5613 s->selected_line >= MIN(s->blame.nlines,
5614 view->nlines - 2)) {
5615 view->count = 0;
5616 break;
5618 if (s->last_displayed_line >= s->blame.nlines &&
5619 s->selected_line < view->nlines - 2) {
5620 s->selected_line +=
5621 MIN(nscroll, s->last_displayed_line -
5622 s->first_displayed_line - s->selected_line + 1);
5624 if (s->last_displayed_line + nscroll <= s->blame.nlines)
5625 s->first_displayed_line += nscroll;
5626 else
5627 s->first_displayed_line =
5628 s->blame.nlines - (view->nlines - 3);
5629 break;
5630 case KEY_RESIZE:
5631 if (s->selected_line > view->nlines - 2) {
5632 s->selected_line = MIN(s->blame.nlines,
5633 view->nlines - 2);
5635 break;
5636 default:
5637 view->count = 0;
5638 break;
5640 return thread_err ? thread_err : err;
5643 static const struct got_error *
5644 cmd_blame(int argc, char *argv[])
5646 const struct got_error *error;
5647 struct got_repository *repo = NULL;
5648 struct got_worktree *worktree = NULL;
5649 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5650 char *link_target = NULL;
5651 struct got_object_id *commit_id = NULL;
5652 struct got_commit_object *commit = NULL;
5653 char *commit_id_str = NULL;
5654 int ch;
5655 struct tog_view *view;
5656 int *pack_fds = NULL;
5658 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5659 switch (ch) {
5660 case 'c':
5661 commit_id_str = optarg;
5662 break;
5663 case 'r':
5664 repo_path = realpath(optarg, NULL);
5665 if (repo_path == NULL)
5666 return got_error_from_errno2("realpath",
5667 optarg);
5668 break;
5669 default:
5670 usage_blame();
5671 /* NOTREACHED */
5675 argc -= optind;
5676 argv += optind;
5678 if (argc != 1)
5679 usage_blame();
5681 error = got_repo_pack_fds_open(&pack_fds);
5682 if (error != NULL)
5683 goto done;
5685 if (repo_path == NULL) {
5686 cwd = getcwd(NULL, 0);
5687 if (cwd == NULL)
5688 return got_error_from_errno("getcwd");
5689 error = got_worktree_open(&worktree, cwd);
5690 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5691 goto done;
5692 if (worktree)
5693 repo_path =
5694 strdup(got_worktree_get_repo_path(worktree));
5695 else
5696 repo_path = strdup(cwd);
5697 if (repo_path == NULL) {
5698 error = got_error_from_errno("strdup");
5699 goto done;
5703 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5704 if (error != NULL)
5705 goto done;
5707 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
5708 worktree);
5709 if (error)
5710 goto done;
5712 init_curses();
5714 error = apply_unveil(got_repo_get_path(repo), NULL);
5715 if (error)
5716 goto done;
5718 error = tog_load_refs(repo, 0);
5719 if (error)
5720 goto done;
5722 if (commit_id_str == NULL) {
5723 struct got_reference *head_ref;
5724 error = got_ref_open(&head_ref, repo, worktree ?
5725 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5726 if (error != NULL)
5727 goto done;
5728 error = got_ref_resolve(&commit_id, repo, head_ref);
5729 got_ref_close(head_ref);
5730 } else {
5731 error = got_repo_match_object_id(&commit_id, NULL,
5732 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
5734 if (error != NULL)
5735 goto done;
5737 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
5738 if (view == NULL) {
5739 error = got_error_from_errno("view_open");
5740 goto done;
5743 error = got_object_open_as_commit(&commit, repo, commit_id);
5744 if (error)
5745 goto done;
5747 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5748 commit, repo);
5749 if (error)
5750 goto done;
5752 error = open_blame_view(view, link_target ? link_target : in_repo_path,
5753 commit_id, repo);
5754 if (error)
5755 goto done;
5756 if (worktree) {
5757 /* Release work tree lock. */
5758 got_worktree_close(worktree);
5759 worktree = NULL;
5761 error = view_loop(view);
5762 done:
5763 free(repo_path);
5764 free(in_repo_path);
5765 free(link_target);
5766 free(cwd);
5767 free(commit_id);
5768 if (commit)
5769 got_object_commit_close(commit);
5770 if (worktree)
5771 got_worktree_close(worktree);
5772 if (repo) {
5773 const struct got_error *close_err = got_repo_close(repo);
5774 if (error == NULL)
5775 error = close_err;
5777 if (pack_fds) {
5778 const struct got_error *pack_err =
5779 got_repo_pack_fds_close(pack_fds);
5780 if (error == NULL)
5781 error = pack_err;
5783 tog_free_refs();
5784 return error;
5787 static const struct got_error *
5788 draw_tree_entries(struct tog_view *view, const char *parent_path)
5790 struct tog_tree_view_state *s = &view->state.tree;
5791 const struct got_error *err = NULL;
5792 struct got_tree_entry *te;
5793 wchar_t *wline;
5794 struct tog_color *tc;
5795 int width, n, i, nentries;
5796 int limit = view->nlines;
5798 s->ndisplayed = 0;
5799 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
5800 view_is_splitscreen(view->child))
5801 --limit; /* border */
5803 werase(view->window);
5805 if (limit == 0)
5806 return NULL;
5808 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
5809 0, 0);
5810 if (err)
5811 return err;
5812 if (view_needs_focus_indication(view))
5813 wstandout(view->window);
5814 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5815 if (tc)
5816 wattr_on(view->window,
5817 COLOR_PAIR(tc->colorpair), NULL);
5818 waddwstr(view->window, wline);
5819 if (tc)
5820 wattr_off(view->window,
5821 COLOR_PAIR(tc->colorpair), NULL);
5822 if (view_needs_focus_indication(view))
5823 wstandend(view->window);
5824 free(wline);
5825 wline = NULL;
5826 if (width < view->ncols - 1)
5827 waddch(view->window, '\n');
5828 if (--limit <= 0)
5829 return NULL;
5830 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
5831 0, 0);
5832 if (err)
5833 return err;
5834 waddwstr(view->window, wline);
5835 free(wline);
5836 wline = NULL;
5837 if (width < view->ncols - 1)
5838 waddch(view->window, '\n');
5839 if (--limit <= 0)
5840 return NULL;
5841 waddch(view->window, '\n');
5842 if (--limit <= 0)
5843 return NULL;
5845 if (s->first_displayed_entry == NULL) {
5846 te = got_object_tree_get_first_entry(s->tree);
5847 if (s->selected == 0) {
5848 if (view->focussed)
5849 wstandout(view->window);
5850 s->selected_entry = NULL;
5852 waddstr(view->window, " ..\n"); /* parent directory */
5853 if (s->selected == 0 && view->focussed)
5854 wstandend(view->window);
5855 s->ndisplayed++;
5856 if (--limit <= 0)
5857 return NULL;
5858 n = 1;
5859 } else {
5860 n = 0;
5861 te = s->first_displayed_entry;
5864 nentries = got_object_tree_get_nentries(s->tree);
5865 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
5866 char *line = NULL, *id_str = NULL, *link_target = NULL;
5867 const char *modestr = "";
5868 mode_t mode;
5870 te = got_object_tree_get_entry(s->tree, i);
5871 mode = got_tree_entry_get_mode(te);
5873 if (s->show_ids) {
5874 err = got_object_id_str(&id_str,
5875 got_tree_entry_get_id(te));
5876 if (err)
5877 return got_error_from_errno(
5878 "got_object_id_str");
5880 if (got_object_tree_entry_is_submodule(te))
5881 modestr = "$";
5882 else if (S_ISLNK(mode)) {
5883 int i;
5885 err = got_tree_entry_get_symlink_target(&link_target,
5886 te, s->repo);
5887 if (err) {
5888 free(id_str);
5889 return err;
5891 for (i = 0; i < strlen(link_target); i++) {
5892 if (!isprint((unsigned char)link_target[i]))
5893 link_target[i] = '?';
5895 modestr = "@";
5897 else if (S_ISDIR(mode))
5898 modestr = "/";
5899 else if (mode & S_IXUSR)
5900 modestr = "*";
5901 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
5902 got_tree_entry_get_name(te), modestr,
5903 link_target ? " -> ": "",
5904 link_target ? link_target : "") == -1) {
5905 free(id_str);
5906 free(link_target);
5907 return got_error_from_errno("asprintf");
5909 free(id_str);
5910 free(link_target);
5911 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
5912 0, 0);
5913 if (err) {
5914 free(line);
5915 break;
5917 if (n == s->selected) {
5918 if (view->focussed)
5919 wstandout(view->window);
5920 s->selected_entry = te;
5922 tc = match_color(&s->colors, line);
5923 if (tc)
5924 wattr_on(view->window,
5925 COLOR_PAIR(tc->colorpair), NULL);
5926 waddwstr(view->window, wline);
5927 if (tc)
5928 wattr_off(view->window,
5929 COLOR_PAIR(tc->colorpair), NULL);
5930 if (width < view->ncols - 1)
5931 waddch(view->window, '\n');
5932 if (n == s->selected && view->focussed)
5933 wstandend(view->window);
5934 free(line);
5935 free(wline);
5936 wline = NULL;
5937 n++;
5938 s->ndisplayed++;
5939 s->last_displayed_entry = te;
5940 if (--limit <= 0)
5941 break;
5944 return err;
5947 static void
5948 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
5950 struct got_tree_entry *te;
5951 int isroot = s->tree == s->root;
5952 int i = 0;
5954 if (s->first_displayed_entry == NULL)
5955 return;
5957 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
5958 while (i++ < maxscroll) {
5959 if (te == NULL) {
5960 if (!isroot)
5961 s->first_displayed_entry = NULL;
5962 break;
5964 s->first_displayed_entry = te;
5965 te = got_tree_entry_get_prev(s->tree, te);
5969 static const struct got_error *
5970 tree_scroll_down(struct tog_view *view, int maxscroll)
5972 struct tog_tree_view_state *s = &view->state.tree;
5973 struct got_tree_entry *next, *last;
5974 int n = 0;
5976 if (s->first_displayed_entry)
5977 next = got_tree_entry_get_next(s->tree,
5978 s->first_displayed_entry);
5979 else
5980 next = got_object_tree_get_first_entry(s->tree);
5982 last = s->last_displayed_entry;
5983 while (next && n++ < maxscroll) {
5984 if (last)
5985 last = got_tree_entry_get_next(s->tree, last);
5986 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
5987 s->first_displayed_entry = next;
5988 next = got_tree_entry_get_next(s->tree, next);
5992 return NULL;
5995 static const struct got_error *
5996 tree_entry_path(char **path, struct tog_parent_trees *parents,
5997 struct got_tree_entry *te)
5999 const struct got_error *err = NULL;
6000 struct tog_parent_tree *pt;
6001 size_t len = 2; /* for leading slash and NUL */
6003 TAILQ_FOREACH(pt, parents, entry)
6004 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6005 + 1 /* slash */;
6006 if (te)
6007 len += strlen(got_tree_entry_get_name(te));
6009 *path = calloc(1, len);
6010 if (path == NULL)
6011 return got_error_from_errno("calloc");
6013 (*path)[0] = '/';
6014 pt = TAILQ_LAST(parents, tog_parent_trees);
6015 while (pt) {
6016 const char *name = got_tree_entry_get_name(pt->selected_entry);
6017 if (strlcat(*path, name, len) >= len) {
6018 err = got_error(GOT_ERR_NO_SPACE);
6019 goto done;
6021 if (strlcat(*path, "/", len) >= len) {
6022 err = got_error(GOT_ERR_NO_SPACE);
6023 goto done;
6025 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6027 if (te) {
6028 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6029 err = got_error(GOT_ERR_NO_SPACE);
6030 goto done;
6033 done:
6034 if (err) {
6035 free(*path);
6036 *path = NULL;
6038 return err;
6041 static const struct got_error *
6042 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6043 struct got_tree_entry *te, struct tog_parent_trees *parents,
6044 struct got_object_id *commit_id, struct got_repository *repo)
6046 const struct got_error *err = NULL;
6047 char *path;
6048 struct tog_view *blame_view;
6050 *new_view = NULL;
6052 err = tree_entry_path(&path, parents, te);
6053 if (err)
6054 return err;
6056 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6057 if (blame_view == NULL) {
6058 err = got_error_from_errno("view_open");
6059 goto done;
6062 err = open_blame_view(blame_view, path, commit_id, repo);
6063 if (err) {
6064 if (err->code == GOT_ERR_CANCELLED)
6065 err = NULL;
6066 view_close(blame_view);
6067 } else
6068 *new_view = blame_view;
6069 done:
6070 free(path);
6071 return err;
6074 static const struct got_error *
6075 log_selected_tree_entry(struct tog_view **new_view, int begin_x,
6076 struct tog_tree_view_state *s)
6078 struct tog_view *log_view;
6079 const struct got_error *err = NULL;
6080 char *path;
6082 *new_view = NULL;
6084 log_view = view_open(0, 0, 0, begin_x, TOG_VIEW_LOG);
6085 if (log_view == NULL)
6086 return got_error_from_errno("view_open");
6088 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6089 if (err)
6090 return err;
6092 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6093 path, 0);
6094 if (err)
6095 view_close(log_view);
6096 else
6097 *new_view = log_view;
6098 free(path);
6099 return err;
6102 static const struct got_error *
6103 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6104 const char *head_ref_name, struct got_repository *repo)
6106 const struct got_error *err = NULL;
6107 char *commit_id_str = NULL;
6108 struct tog_tree_view_state *s = &view->state.tree;
6109 struct got_commit_object *commit = NULL;
6111 TAILQ_INIT(&s->parents);
6112 STAILQ_INIT(&s->colors);
6114 s->commit_id = got_object_id_dup(commit_id);
6115 if (s->commit_id == NULL)
6116 return got_error_from_errno("got_object_id_dup");
6118 err = got_object_open_as_commit(&commit, repo, commit_id);
6119 if (err)
6120 goto done;
6123 * The root is opened here and will be closed when the view is closed.
6124 * Any visited subtrees and their path-wise parents are opened and
6125 * closed on demand.
6127 err = got_object_open_as_tree(&s->root, repo,
6128 got_object_commit_get_tree_id(commit));
6129 if (err)
6130 goto done;
6131 s->tree = s->root;
6133 err = got_object_id_str(&commit_id_str, commit_id);
6134 if (err != NULL)
6135 goto done;
6137 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6138 err = got_error_from_errno("asprintf");
6139 goto done;
6142 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6143 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6144 if (head_ref_name) {
6145 s->head_ref_name = strdup(head_ref_name);
6146 if (s->head_ref_name == NULL) {
6147 err = got_error_from_errno("strdup");
6148 goto done;
6151 s->repo = repo;
6153 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6154 err = add_color(&s->colors, "\\$$",
6155 TOG_COLOR_TREE_SUBMODULE,
6156 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6157 if (err)
6158 goto done;
6159 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6160 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6161 if (err)
6162 goto done;
6163 err = add_color(&s->colors, "/$",
6164 TOG_COLOR_TREE_DIRECTORY,
6165 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6166 if (err)
6167 goto done;
6169 err = add_color(&s->colors, "\\*$",
6170 TOG_COLOR_TREE_EXECUTABLE,
6171 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6172 if (err)
6173 goto done;
6175 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6176 get_color_value("TOG_COLOR_COMMIT"));
6177 if (err)
6178 goto done;
6181 view->show = show_tree_view;
6182 view->input = input_tree_view;
6183 view->close = close_tree_view;
6184 view->search_start = search_start_tree_view;
6185 view->search_next = search_next_tree_view;
6186 done:
6187 free(commit_id_str);
6188 if (commit)
6189 got_object_commit_close(commit);
6190 if (err)
6191 close_tree_view(view);
6192 return err;
6195 static const struct got_error *
6196 close_tree_view(struct tog_view *view)
6198 struct tog_tree_view_state *s = &view->state.tree;
6200 free_colors(&s->colors);
6201 free(s->tree_label);
6202 s->tree_label = NULL;
6203 free(s->commit_id);
6204 s->commit_id = NULL;
6205 free(s->head_ref_name);
6206 s->head_ref_name = NULL;
6207 while (!TAILQ_EMPTY(&s->parents)) {
6208 struct tog_parent_tree *parent;
6209 parent = TAILQ_FIRST(&s->parents);
6210 TAILQ_REMOVE(&s->parents, parent, entry);
6211 if (parent->tree != s->root)
6212 got_object_tree_close(parent->tree);
6213 free(parent);
6216 if (s->tree != NULL && s->tree != s->root)
6217 got_object_tree_close(s->tree);
6218 if (s->root)
6219 got_object_tree_close(s->root);
6220 return NULL;
6223 static const struct got_error *
6224 search_start_tree_view(struct tog_view *view)
6226 struct tog_tree_view_state *s = &view->state.tree;
6228 s->matched_entry = NULL;
6229 return NULL;
6232 static int
6233 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6235 regmatch_t regmatch;
6237 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6238 0) == 0;
6241 static const struct got_error *
6242 search_next_tree_view(struct tog_view *view)
6244 struct tog_tree_view_state *s = &view->state.tree;
6245 struct got_tree_entry *te = NULL;
6247 if (!view->searching) {
6248 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6249 return NULL;
6252 if (s->matched_entry) {
6253 if (view->searching == TOG_SEARCH_FORWARD) {
6254 if (s->selected_entry)
6255 te = got_tree_entry_get_next(s->tree,
6256 s->selected_entry);
6257 else
6258 te = got_object_tree_get_first_entry(s->tree);
6259 } else {
6260 if (s->selected_entry == NULL)
6261 te = got_object_tree_get_last_entry(s->tree);
6262 else
6263 te = got_tree_entry_get_prev(s->tree,
6264 s->selected_entry);
6266 } else {
6267 if (s->selected_entry)
6268 te = s->selected_entry;
6269 else if (view->searching == TOG_SEARCH_FORWARD)
6270 te = got_object_tree_get_first_entry(s->tree);
6271 else
6272 te = got_object_tree_get_last_entry(s->tree);
6275 while (1) {
6276 if (te == NULL) {
6277 if (s->matched_entry == NULL) {
6278 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6279 return NULL;
6281 if (view->searching == TOG_SEARCH_FORWARD)
6282 te = got_object_tree_get_first_entry(s->tree);
6283 else
6284 te = got_object_tree_get_last_entry(s->tree);
6287 if (match_tree_entry(te, &view->regex)) {
6288 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6289 s->matched_entry = te;
6290 break;
6293 if (view->searching == TOG_SEARCH_FORWARD)
6294 te = got_tree_entry_get_next(s->tree, te);
6295 else
6296 te = got_tree_entry_get_prev(s->tree, te);
6299 if (s->matched_entry) {
6300 s->first_displayed_entry = s->matched_entry;
6301 s->selected = 0;
6304 return NULL;
6307 static const struct got_error *
6308 show_tree_view(struct tog_view *view)
6310 const struct got_error *err = NULL;
6311 struct tog_tree_view_state *s = &view->state.tree;
6312 char *parent_path;
6314 err = tree_entry_path(&parent_path, &s->parents, NULL);
6315 if (err)
6316 return err;
6318 err = draw_tree_entries(view, parent_path);
6319 free(parent_path);
6321 view_border(view);
6322 return err;
6325 static const struct got_error *
6326 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6328 const struct got_error *err = NULL;
6329 struct tog_tree_view_state *s = &view->state.tree;
6330 struct tog_view *log_view, *ref_view;
6331 struct got_tree_entry *te;
6332 int begin_x = 0, n, nscroll = view->nlines - 3;
6334 switch (ch) {
6335 case 'i':
6336 s->show_ids = !s->show_ids;
6337 view->count = 0;
6338 break;
6339 case 'l':
6340 view->count = 0;
6341 if (!s->selected_entry)
6342 break;
6343 if (view_is_parent_view(view))
6344 begin_x = view_split_begin_x(view->begin_x);
6345 err = log_selected_tree_entry(&log_view, begin_x, s);
6346 view->focussed = 0;
6347 log_view->focussed = 1;
6348 if (view_is_parent_view(view)) {
6349 err = view_close_child(view);
6350 if (err)
6351 return err;
6352 err = view_set_child(view, log_view);
6353 if (err)
6354 return err;
6355 view->focus_child = 1;
6356 } else
6357 *new_view = log_view;
6358 break;
6359 case 'r':
6360 view->count = 0;
6361 if (view_is_parent_view(view))
6362 begin_x = view_split_begin_x(view->begin_x);
6363 ref_view = view_open(view->nlines, view->ncols,
6364 view->begin_y, begin_x, TOG_VIEW_REF);
6365 if (ref_view == NULL)
6366 return got_error_from_errno("view_open");
6367 err = open_ref_view(ref_view, s->repo);
6368 if (err) {
6369 view_close(ref_view);
6370 return err;
6372 view->focussed = 0;
6373 ref_view->focussed = 1;
6374 if (view_is_parent_view(view)) {
6375 err = view_close_child(view);
6376 if (err)
6377 return err;
6378 err = view_set_child(view, ref_view);
6379 if (err)
6380 return err;
6381 view->focus_child = 1;
6382 } else
6383 *new_view = ref_view;
6384 break;
6385 case 'g':
6386 case KEY_HOME:
6387 s->selected = 0;
6388 view->count = 0;
6389 if (s->tree == s->root)
6390 s->first_displayed_entry =
6391 got_object_tree_get_first_entry(s->tree);
6392 else
6393 s->first_displayed_entry = NULL;
6394 break;
6395 case 'G':
6396 case KEY_END: {
6397 int eos = view->nlines - 3;
6399 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6400 --eos; /* border */
6401 s->selected = 0;
6402 view->count = 0;
6403 te = got_object_tree_get_last_entry(s->tree);
6404 for (n = 0; n < eos; n++) {
6405 if (te == NULL) {
6406 if(s->tree != s->root) {
6407 s->first_displayed_entry = NULL;
6408 n++;
6410 break;
6412 s->first_displayed_entry = te;
6413 te = got_tree_entry_get_prev(s->tree, te);
6415 if (n > 0)
6416 s->selected = n - 1;
6417 break;
6419 case 'k':
6420 case KEY_UP:
6421 case CTRL('p'):
6422 if (s->selected > 0) {
6423 s->selected--;
6424 break;
6426 tree_scroll_up(s, 1);
6427 if (s->selected_entry == NULL ||
6428 (s->tree == s->root && s->selected_entry ==
6429 got_object_tree_get_first_entry(s->tree)))
6430 view->count = 0;
6431 break;
6432 case CTRL('u'):
6433 case 'u':
6434 nscroll /= 2;
6435 /* FALL THROUGH */
6436 case KEY_PPAGE:
6437 case CTRL('b'):
6438 case 'b':
6439 if (s->tree == s->root) {
6440 if (got_object_tree_get_first_entry(s->tree) ==
6441 s->first_displayed_entry)
6442 s->selected -= MIN(s->selected, nscroll);
6443 } else {
6444 if (s->first_displayed_entry == NULL)
6445 s->selected -= MIN(s->selected, nscroll);
6447 tree_scroll_up(s, MAX(0, nscroll));
6448 if (s->selected_entry == NULL ||
6449 (s->tree == s->root && s->selected_entry ==
6450 got_object_tree_get_first_entry(s->tree)))
6451 view->count = 0;
6452 break;
6453 case 'j':
6454 case KEY_DOWN:
6455 case CTRL('n'):
6456 if (s->selected < s->ndisplayed - 1) {
6457 s->selected++;
6458 break;
6460 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6461 == NULL) {
6462 /* can't scroll any further */
6463 view->count = 0;
6464 break;
6466 tree_scroll_down(view, 1);
6467 break;
6468 case CTRL('d'):
6469 case 'd':
6470 nscroll /= 2;
6471 /* FALL THROUGH */
6472 case KEY_NPAGE:
6473 case CTRL('f'):
6474 case 'f':
6475 case ' ':
6476 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
6477 == NULL) {
6478 /* can't scroll any further; move cursor down */
6479 if (s->selected < s->ndisplayed - 1)
6480 s->selected += MIN(nscroll,
6481 s->ndisplayed - s->selected - 1);
6482 else
6483 view->count = 0;
6484 break;
6486 tree_scroll_down(view, nscroll);
6487 break;
6488 case KEY_ENTER:
6489 case '\r':
6490 case KEY_BACKSPACE:
6491 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
6492 struct tog_parent_tree *parent;
6493 /* user selected '..' */
6494 if (s->tree == s->root) {
6495 view->count = 0;
6496 break;
6498 parent = TAILQ_FIRST(&s->parents);
6499 TAILQ_REMOVE(&s->parents, parent,
6500 entry);
6501 got_object_tree_close(s->tree);
6502 s->tree = parent->tree;
6503 s->first_displayed_entry =
6504 parent->first_displayed_entry;
6505 s->selected_entry =
6506 parent->selected_entry;
6507 s->selected = parent->selected;
6508 if (s->selected > view->nlines - 3) {
6509 err = offset_selection_down(view);
6510 if (err)
6511 break;
6513 free(parent);
6514 } else if (S_ISDIR(got_tree_entry_get_mode(
6515 s->selected_entry))) {
6516 struct got_tree_object *subtree;
6517 view->count = 0;
6518 err = got_object_open_as_tree(&subtree, s->repo,
6519 got_tree_entry_get_id(s->selected_entry));
6520 if (err)
6521 break;
6522 err = tree_view_visit_subtree(s, subtree);
6523 if (err) {
6524 got_object_tree_close(subtree);
6525 break;
6527 } else if (S_ISREG(got_tree_entry_get_mode(
6528 s->selected_entry))) {
6529 struct tog_view *blame_view;
6530 int begin_x = 0, begin_y = 0;
6532 if (view_is_parent_view(view))
6533 view_get_split(view, &begin_y, &begin_x);
6535 err = blame_tree_entry(&blame_view, begin_y, begin_x,
6536 s->selected_entry, &s->parents,
6537 s->commit_id, s->repo);
6538 if (err)
6539 break;
6541 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
6542 err = view_init_hsplit(view, begin_y);
6543 if (err)
6544 break;
6547 view->count = 0;
6548 view->focussed = 0;
6549 blame_view->focussed = 1;
6550 blame_view->mode = view->mode;
6551 blame_view->nlines = view->lines - begin_y;
6552 if (view_is_parent_view(view)) {
6553 err = view_close_child(view);
6554 if (err)
6555 return err;
6556 err = view_set_child(view, blame_view);
6557 if (err)
6558 return err;
6559 view->focus_child = 1;
6560 } else
6561 *new_view = blame_view;
6563 break;
6564 case KEY_RESIZE:
6565 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
6566 s->selected = view->nlines - 4;
6567 view->count = 0;
6568 break;
6569 default:
6570 view->count = 0;
6571 break;
6574 return err;
6577 __dead static void
6578 usage_tree(void)
6580 endwin();
6581 fprintf(stderr,
6582 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
6583 getprogname());
6584 exit(1);
6587 static const struct got_error *
6588 cmd_tree(int argc, char *argv[])
6590 const struct got_error *error;
6591 struct got_repository *repo = NULL;
6592 struct got_worktree *worktree = NULL;
6593 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6594 struct got_object_id *commit_id = NULL;
6595 struct got_commit_object *commit = NULL;
6596 const char *commit_id_arg = NULL;
6597 char *label = NULL;
6598 struct got_reference *ref = NULL;
6599 const char *head_ref_name = NULL;
6600 int ch;
6601 struct tog_view *view;
6602 int *pack_fds = NULL;
6604 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6605 switch (ch) {
6606 case 'c':
6607 commit_id_arg = optarg;
6608 break;
6609 case 'r':
6610 repo_path = realpath(optarg, NULL);
6611 if (repo_path == NULL)
6612 return got_error_from_errno2("realpath",
6613 optarg);
6614 break;
6615 default:
6616 usage_tree();
6617 /* NOTREACHED */
6621 argc -= optind;
6622 argv += optind;
6624 if (argc > 1)
6625 usage_tree();
6627 error = got_repo_pack_fds_open(&pack_fds);
6628 if (error != NULL)
6629 goto done;
6631 if (repo_path == NULL) {
6632 cwd = getcwd(NULL, 0);
6633 if (cwd == NULL)
6634 return got_error_from_errno("getcwd");
6635 error = got_worktree_open(&worktree, cwd);
6636 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6637 goto done;
6638 if (worktree)
6639 repo_path =
6640 strdup(got_worktree_get_repo_path(worktree));
6641 else
6642 repo_path = strdup(cwd);
6643 if (repo_path == NULL) {
6644 error = got_error_from_errno("strdup");
6645 goto done;
6649 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6650 if (error != NULL)
6651 goto done;
6653 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
6654 repo, worktree);
6655 if (error)
6656 goto done;
6658 init_curses();
6660 error = apply_unveil(got_repo_get_path(repo), NULL);
6661 if (error)
6662 goto done;
6664 error = tog_load_refs(repo, 0);
6665 if (error)
6666 goto done;
6668 if (commit_id_arg == NULL) {
6669 error = got_repo_match_object_id(&commit_id, &label,
6670 worktree ? got_worktree_get_head_ref_name(worktree) :
6671 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6672 if (error)
6673 goto done;
6674 head_ref_name = label;
6675 } else {
6676 error = got_ref_open(&ref, repo, commit_id_arg, 0);
6677 if (error == NULL)
6678 head_ref_name = got_ref_get_name(ref);
6679 else if (error->code != GOT_ERR_NOT_REF)
6680 goto done;
6681 error = got_repo_match_object_id(&commit_id, NULL,
6682 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6683 if (error)
6684 goto done;
6687 error = got_object_open_as_commit(&commit, repo, commit_id);
6688 if (error)
6689 goto done;
6691 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
6692 if (view == NULL) {
6693 error = got_error_from_errno("view_open");
6694 goto done;
6696 error = open_tree_view(view, commit_id, head_ref_name, repo);
6697 if (error)
6698 goto done;
6699 if (!got_path_is_root_dir(in_repo_path)) {
6700 error = tree_view_walk_path(&view->state.tree, commit,
6701 in_repo_path);
6702 if (error)
6703 goto done;
6706 if (worktree) {
6707 /* Release work tree lock. */
6708 got_worktree_close(worktree);
6709 worktree = NULL;
6711 error = view_loop(view);
6712 done:
6713 free(repo_path);
6714 free(cwd);
6715 free(commit_id);
6716 free(label);
6717 if (ref)
6718 got_ref_close(ref);
6719 if (repo) {
6720 const struct got_error *close_err = got_repo_close(repo);
6721 if (error == NULL)
6722 error = close_err;
6724 if (pack_fds) {
6725 const struct got_error *pack_err =
6726 got_repo_pack_fds_close(pack_fds);
6727 if (error == NULL)
6728 error = pack_err;
6730 tog_free_refs();
6731 return error;
6734 static const struct got_error *
6735 ref_view_load_refs(struct tog_ref_view_state *s)
6737 struct got_reflist_entry *sre;
6738 struct tog_reflist_entry *re;
6740 s->nrefs = 0;
6741 TAILQ_FOREACH(sre, &tog_refs, entry) {
6742 if (strncmp(got_ref_get_name(sre->ref),
6743 "refs/got/", 9) == 0 &&
6744 strncmp(got_ref_get_name(sre->ref),
6745 "refs/got/backup/", 16) != 0)
6746 continue;
6748 re = malloc(sizeof(*re));
6749 if (re == NULL)
6750 return got_error_from_errno("malloc");
6752 re->ref = got_ref_dup(sre->ref);
6753 if (re->ref == NULL)
6754 return got_error_from_errno("got_ref_dup");
6755 re->idx = s->nrefs++;
6756 TAILQ_INSERT_TAIL(&s->refs, re, entry);
6759 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
6760 return NULL;
6763 static void
6764 ref_view_free_refs(struct tog_ref_view_state *s)
6766 struct tog_reflist_entry *re;
6768 while (!TAILQ_EMPTY(&s->refs)) {
6769 re = TAILQ_FIRST(&s->refs);
6770 TAILQ_REMOVE(&s->refs, re, entry);
6771 got_ref_close(re->ref);
6772 free(re);
6776 static const struct got_error *
6777 open_ref_view(struct tog_view *view, struct got_repository *repo)
6779 const struct got_error *err = NULL;
6780 struct tog_ref_view_state *s = &view->state.ref;
6782 s->selected_entry = 0;
6783 s->repo = repo;
6785 TAILQ_INIT(&s->refs);
6786 STAILQ_INIT(&s->colors);
6788 err = ref_view_load_refs(s);
6789 if (err)
6790 return err;
6792 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6793 err = add_color(&s->colors, "^refs/heads/",
6794 TOG_COLOR_REFS_HEADS,
6795 get_color_value("TOG_COLOR_REFS_HEADS"));
6796 if (err)
6797 goto done;
6799 err = add_color(&s->colors, "^refs/tags/",
6800 TOG_COLOR_REFS_TAGS,
6801 get_color_value("TOG_COLOR_REFS_TAGS"));
6802 if (err)
6803 goto done;
6805 err = add_color(&s->colors, "^refs/remotes/",
6806 TOG_COLOR_REFS_REMOTES,
6807 get_color_value("TOG_COLOR_REFS_REMOTES"));
6808 if (err)
6809 goto done;
6811 err = add_color(&s->colors, "^refs/got/backup/",
6812 TOG_COLOR_REFS_BACKUP,
6813 get_color_value("TOG_COLOR_REFS_BACKUP"));
6814 if (err)
6815 goto done;
6818 view->show = show_ref_view;
6819 view->input = input_ref_view;
6820 view->close = close_ref_view;
6821 view->search_start = search_start_ref_view;
6822 view->search_next = search_next_ref_view;
6823 done:
6824 if (err)
6825 free_colors(&s->colors);
6826 return err;
6829 static const struct got_error *
6830 close_ref_view(struct tog_view *view)
6832 struct tog_ref_view_state *s = &view->state.ref;
6834 ref_view_free_refs(s);
6835 free_colors(&s->colors);
6837 return NULL;
6840 static const struct got_error *
6841 resolve_reflist_entry(struct got_object_id **commit_id,
6842 struct tog_reflist_entry *re, struct got_repository *repo)
6844 const struct got_error *err = NULL;
6845 struct got_object_id *obj_id;
6846 struct got_tag_object *tag = NULL;
6847 int obj_type;
6849 *commit_id = NULL;
6851 err = got_ref_resolve(&obj_id, repo, re->ref);
6852 if (err)
6853 return err;
6855 err = got_object_get_type(&obj_type, repo, obj_id);
6856 if (err)
6857 goto done;
6859 switch (obj_type) {
6860 case GOT_OBJ_TYPE_COMMIT:
6861 *commit_id = obj_id;
6862 break;
6863 case GOT_OBJ_TYPE_TAG:
6864 err = got_object_open_as_tag(&tag, repo, obj_id);
6865 if (err)
6866 goto done;
6867 free(obj_id);
6868 err = got_object_get_type(&obj_type, repo,
6869 got_object_tag_get_object_id(tag));
6870 if (err)
6871 goto done;
6872 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
6873 err = got_error(GOT_ERR_OBJ_TYPE);
6874 goto done;
6876 *commit_id = got_object_id_dup(
6877 got_object_tag_get_object_id(tag));
6878 if (*commit_id == NULL) {
6879 err = got_error_from_errno("got_object_id_dup");
6880 goto done;
6882 break;
6883 default:
6884 err = got_error(GOT_ERR_OBJ_TYPE);
6885 break;
6888 done:
6889 if (tag)
6890 got_object_tag_close(tag);
6891 if (err) {
6892 free(*commit_id);
6893 *commit_id = NULL;
6895 return err;
6898 static const struct got_error *
6899 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
6900 struct tog_reflist_entry *re, struct got_repository *repo)
6902 struct tog_view *log_view;
6903 const struct got_error *err = NULL;
6904 struct got_object_id *commit_id = NULL;
6906 *new_view = NULL;
6908 err = resolve_reflist_entry(&commit_id, re, repo);
6909 if (err) {
6910 if (err->code != GOT_ERR_OBJ_TYPE)
6911 return err;
6912 else
6913 return NULL;
6916 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6917 if (log_view == NULL) {
6918 err = got_error_from_errno("view_open");
6919 goto done;
6922 err = open_log_view(log_view, commit_id, repo,
6923 got_ref_get_name(re->ref), "", 0);
6924 done:
6925 if (err)
6926 view_close(log_view);
6927 else
6928 *new_view = log_view;
6929 free(commit_id);
6930 return err;
6933 static void
6934 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
6936 struct tog_reflist_entry *re;
6937 int i = 0;
6939 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
6940 return;
6942 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
6943 while (i++ < maxscroll) {
6944 if (re == NULL)
6945 break;
6946 s->first_displayed_entry = re;
6947 re = TAILQ_PREV(re, tog_reflist_head, entry);
6951 static const struct got_error *
6952 ref_scroll_down(struct tog_view *view, int maxscroll)
6954 struct tog_ref_view_state *s = &view->state.ref;
6955 struct tog_reflist_entry *next, *last;
6956 int n = 0;
6958 if (s->first_displayed_entry)
6959 next = TAILQ_NEXT(s->first_displayed_entry, entry);
6960 else
6961 next = TAILQ_FIRST(&s->refs);
6963 last = s->last_displayed_entry;
6964 while (next && n++ < maxscroll) {
6965 if (last)
6966 last = TAILQ_NEXT(last, entry);
6967 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
6968 s->first_displayed_entry = next;
6969 next = TAILQ_NEXT(next, entry);
6973 return NULL;
6976 static const struct got_error *
6977 search_start_ref_view(struct tog_view *view)
6979 struct tog_ref_view_state *s = &view->state.ref;
6981 s->matched_entry = NULL;
6982 return NULL;
6985 static int
6986 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
6988 regmatch_t regmatch;
6990 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
6991 0) == 0;
6994 static const struct got_error *
6995 search_next_ref_view(struct tog_view *view)
6997 struct tog_ref_view_state *s = &view->state.ref;
6998 struct tog_reflist_entry *re = NULL;
7000 if (!view->searching) {
7001 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7002 return NULL;
7005 if (s->matched_entry) {
7006 if (view->searching == TOG_SEARCH_FORWARD) {
7007 if (s->selected_entry)
7008 re = TAILQ_NEXT(s->selected_entry, entry);
7009 else
7010 re = TAILQ_PREV(s->selected_entry,
7011 tog_reflist_head, entry);
7012 } else {
7013 if (s->selected_entry == NULL)
7014 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7015 else
7016 re = TAILQ_PREV(s->selected_entry,
7017 tog_reflist_head, entry);
7019 } else {
7020 if (s->selected_entry)
7021 re = s->selected_entry;
7022 else if (view->searching == TOG_SEARCH_FORWARD)
7023 re = TAILQ_FIRST(&s->refs);
7024 else
7025 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7028 while (1) {
7029 if (re == NULL) {
7030 if (s->matched_entry == NULL) {
7031 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7032 return NULL;
7034 if (view->searching == TOG_SEARCH_FORWARD)
7035 re = TAILQ_FIRST(&s->refs);
7036 else
7037 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7040 if (match_reflist_entry(re, &view->regex)) {
7041 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7042 s->matched_entry = re;
7043 break;
7046 if (view->searching == TOG_SEARCH_FORWARD)
7047 re = TAILQ_NEXT(re, entry);
7048 else
7049 re = TAILQ_PREV(re, tog_reflist_head, entry);
7052 if (s->matched_entry) {
7053 s->first_displayed_entry = s->matched_entry;
7054 s->selected = 0;
7057 return NULL;
7060 static const struct got_error *
7061 show_ref_view(struct tog_view *view)
7063 const struct got_error *err = NULL;
7064 struct tog_ref_view_state *s = &view->state.ref;
7065 struct tog_reflist_entry *re;
7066 char *line = NULL;
7067 wchar_t *wline;
7068 struct tog_color *tc;
7069 int width, n;
7070 int limit = view->nlines;
7072 werase(view->window);
7074 s->ndisplayed = 0;
7075 if (view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
7076 view_is_splitscreen(view->child))
7077 --limit; /* border */
7079 if (limit == 0)
7080 return NULL;
7082 re = s->first_displayed_entry;
7084 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7085 s->nrefs) == -1)
7086 return got_error_from_errno("asprintf");
7088 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7089 if (err) {
7090 free(line);
7091 return err;
7093 if (view_needs_focus_indication(view))
7094 wstandout(view->window);
7095 waddwstr(view->window, wline);
7096 if (view_needs_focus_indication(view))
7097 wstandend(view->window);
7098 free(wline);
7099 wline = NULL;
7100 free(line);
7101 line = NULL;
7102 if (width < view->ncols - 1)
7103 waddch(view->window, '\n');
7104 if (--limit <= 0)
7105 return NULL;
7107 n = 0;
7108 while (re && limit > 0) {
7109 char *line = NULL;
7110 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7112 if (s->show_date) {
7113 struct got_commit_object *ci;
7114 struct got_tag_object *tag;
7115 struct got_object_id *id;
7116 struct tm tm;
7117 time_t t;
7119 err = got_ref_resolve(&id, s->repo, re->ref);
7120 if (err)
7121 return err;
7122 err = got_object_open_as_tag(&tag, s->repo, id);
7123 if (err) {
7124 if (err->code != GOT_ERR_OBJ_TYPE) {
7125 free(id);
7126 return err;
7128 err = got_object_open_as_commit(&ci, s->repo,
7129 id);
7130 if (err) {
7131 free(id);
7132 return err;
7134 t = got_object_commit_get_committer_time(ci);
7135 got_object_commit_close(ci);
7136 } else {
7137 t = got_object_tag_get_tagger_time(tag);
7138 got_object_tag_close(tag);
7140 free(id);
7141 if (gmtime_r(&t, &tm) == NULL)
7142 return got_error_from_errno("gmtime_r");
7143 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7144 return got_error(GOT_ERR_NO_SPACE);
7146 if (got_ref_is_symbolic(re->ref)) {
7147 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7148 ymd : "", got_ref_get_name(re->ref),
7149 got_ref_get_symref_target(re->ref)) == -1)
7150 return got_error_from_errno("asprintf");
7151 } else if (s->show_ids) {
7152 struct got_object_id *id;
7153 char *id_str;
7154 err = got_ref_resolve(&id, s->repo, re->ref);
7155 if (err)
7156 return err;
7157 err = got_object_id_str(&id_str, id);
7158 if (err) {
7159 free(id);
7160 return err;
7162 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7163 got_ref_get_name(re->ref), id_str) == -1) {
7164 err = got_error_from_errno("asprintf");
7165 free(id);
7166 free(id_str);
7167 return err;
7169 free(id);
7170 free(id_str);
7171 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7172 got_ref_get_name(re->ref)) == -1)
7173 return got_error_from_errno("asprintf");
7175 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7176 0, 0);
7177 if (err) {
7178 free(line);
7179 return err;
7181 if (n == s->selected) {
7182 if (view->focussed)
7183 wstandout(view->window);
7184 s->selected_entry = re;
7186 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7187 if (tc)
7188 wattr_on(view->window,
7189 COLOR_PAIR(tc->colorpair), NULL);
7190 waddwstr(view->window, wline);
7191 if (tc)
7192 wattr_off(view->window,
7193 COLOR_PAIR(tc->colorpair), NULL);
7194 if (width < view->ncols - 1)
7195 waddch(view->window, '\n');
7196 if (n == s->selected && view->focussed)
7197 wstandend(view->window);
7198 free(line);
7199 free(wline);
7200 wline = NULL;
7201 n++;
7202 s->ndisplayed++;
7203 s->last_displayed_entry = re;
7205 limit--;
7206 re = TAILQ_NEXT(re, entry);
7209 view_border(view);
7210 return err;
7213 static const struct got_error *
7214 browse_ref_tree(struct tog_view **new_view, int begin_x,
7215 struct tog_reflist_entry *re, struct got_repository *repo)
7217 const struct got_error *err = NULL;
7218 struct got_object_id *commit_id = NULL;
7219 struct tog_view *tree_view;
7221 *new_view = NULL;
7223 err = resolve_reflist_entry(&commit_id, re, repo);
7224 if (err) {
7225 if (err->code != GOT_ERR_OBJ_TYPE)
7226 return err;
7227 else
7228 return NULL;
7232 tree_view = view_open(0, 0, 0, begin_x, TOG_VIEW_TREE);
7233 if (tree_view == NULL) {
7234 err = got_error_from_errno("view_open");
7235 goto done;
7238 err = open_tree_view(tree_view, commit_id,
7239 got_ref_get_name(re->ref), repo);
7240 if (err)
7241 goto done;
7243 *new_view = tree_view;
7244 done:
7245 free(commit_id);
7246 return err;
7248 static const struct got_error *
7249 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7251 const struct got_error *err = NULL;
7252 struct tog_ref_view_state *s = &view->state.ref;
7253 struct tog_view *log_view, *tree_view;
7254 struct tog_reflist_entry *re;
7255 int begin_y = 0, begin_x = 0, n, nscroll = view->nlines - 1;
7257 switch (ch) {
7258 case 'i':
7259 s->show_ids = !s->show_ids;
7260 view->count = 0;
7261 break;
7262 case 'm':
7263 s->show_date = !s->show_date;
7264 view->count = 0;
7265 break;
7266 case 'o':
7267 s->sort_by_date = !s->sort_by_date;
7268 view->count = 0;
7269 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7270 got_ref_cmp_by_commit_timestamp_descending :
7271 tog_ref_cmp_by_name, s->repo);
7272 if (err)
7273 break;
7274 got_reflist_object_id_map_free(tog_refs_idmap);
7275 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7276 &tog_refs, s->repo);
7277 if (err)
7278 break;
7279 ref_view_free_refs(s);
7280 err = ref_view_load_refs(s);
7281 break;
7282 case KEY_ENTER:
7283 case '\r':
7284 view->count = 0;
7285 if (!s->selected_entry)
7286 break;
7287 if (view_is_parent_view(view))
7288 view_get_split(view, &begin_y, &begin_x);
7290 err = log_ref_entry(&log_view, begin_y, begin_x,
7291 s->selected_entry, s->repo);
7292 if (err)
7293 break;
7295 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
7296 err = view_init_hsplit(view, begin_y);
7297 if (err)
7298 break;
7301 view->focussed = 0;
7302 log_view->focussed = 1;
7303 log_view->mode = view->mode;
7304 log_view->nlines = view->lines - begin_y;
7305 if (view_is_parent_view(view)) {
7306 err = view_close_child(view);
7307 if (err)
7308 return err;
7309 err = view_set_child(view, log_view);
7310 if (err)
7311 return err;
7312 view->focus_child = 1;
7313 } else
7314 *new_view = log_view;
7315 break;
7316 case 't':
7317 view->count = 0;
7318 if (!s->selected_entry)
7319 break;
7320 if (view_is_parent_view(view))
7321 begin_x = view_split_begin_x(view->begin_x);
7322 err = browse_ref_tree(&tree_view, begin_x, s->selected_entry,
7323 s->repo);
7324 if (err || tree_view == NULL)
7325 break;
7326 view->focussed = 0;
7327 tree_view->focussed = 1;
7328 if (view_is_parent_view(view)) {
7329 err = view_close_child(view);
7330 if (err)
7331 return err;
7332 err = view_set_child(view, tree_view);
7333 if (err)
7334 return err;
7335 view->focus_child = 1;
7336 } else
7337 *new_view = tree_view;
7338 break;
7339 case 'g':
7340 case KEY_HOME:
7341 s->selected = 0;
7342 view->count = 0;
7343 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7344 break;
7345 case 'G':
7346 case KEY_END: {
7347 int eos = view->nlines - 1;
7349 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7350 --eos; /* border */
7351 s->selected = 0;
7352 view->count = 0;
7353 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7354 for (n = 0; n < eos; n++) {
7355 if (re == NULL)
7356 break;
7357 s->first_displayed_entry = re;
7358 re = TAILQ_PREV(re, tog_reflist_head, entry);
7360 if (n > 0)
7361 s->selected = n - 1;
7362 break;
7364 case 'k':
7365 case KEY_UP:
7366 case CTRL('p'):
7367 if (s->selected > 0) {
7368 s->selected--;
7369 break;
7371 ref_scroll_up(s, 1);
7372 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7373 view->count = 0;
7374 break;
7375 case CTRL('u'):
7376 case 'u':
7377 nscroll /= 2;
7378 /* FALL THROUGH */
7379 case KEY_PPAGE:
7380 case CTRL('b'):
7381 case 'b':
7382 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7383 s->selected -= MIN(nscroll, s->selected);
7384 ref_scroll_up(s, MAX(0, nscroll));
7385 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7386 view->count = 0;
7387 break;
7388 case 'j':
7389 case KEY_DOWN:
7390 case CTRL('n'):
7391 if (s->selected < s->ndisplayed - 1) {
7392 s->selected++;
7393 break;
7395 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7396 /* can't scroll any further */
7397 view->count = 0;
7398 break;
7400 ref_scroll_down(view, 1);
7401 break;
7402 case CTRL('d'):
7403 case 'd':
7404 nscroll /= 2;
7405 /* FALL THROUGH */
7406 case KEY_NPAGE:
7407 case CTRL('f'):
7408 case 'f':
7409 case ' ':
7410 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7411 /* can't scroll any further; move cursor down */
7412 if (s->selected < s->ndisplayed - 1)
7413 s->selected += MIN(nscroll,
7414 s->ndisplayed - s->selected - 1);
7415 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7416 s->selected += s->ndisplayed - s->selected - 1;
7417 view->count = 0;
7418 break;
7420 ref_scroll_down(view, nscroll);
7421 break;
7422 case CTRL('l'):
7423 view->count = 0;
7424 tog_free_refs();
7425 err = tog_load_refs(s->repo, s->sort_by_date);
7426 if (err)
7427 break;
7428 ref_view_free_refs(s);
7429 err = ref_view_load_refs(s);
7430 break;
7431 case KEY_RESIZE:
7432 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7433 s->selected = view->nlines - 2;
7434 break;
7435 default:
7436 view->count = 0;
7437 break;
7440 return err;
7443 __dead static void
7444 usage_ref(void)
7446 endwin();
7447 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7448 getprogname());
7449 exit(1);
7452 static const struct got_error *
7453 cmd_ref(int argc, char *argv[])
7455 const struct got_error *error;
7456 struct got_repository *repo = NULL;
7457 struct got_worktree *worktree = NULL;
7458 char *cwd = NULL, *repo_path = NULL;
7459 int ch;
7460 struct tog_view *view;
7461 int *pack_fds = NULL;
7463 while ((ch = getopt(argc, argv, "r:")) != -1) {
7464 switch (ch) {
7465 case 'r':
7466 repo_path = realpath(optarg, NULL);
7467 if (repo_path == NULL)
7468 return got_error_from_errno2("realpath",
7469 optarg);
7470 break;
7471 default:
7472 usage_ref();
7473 /* NOTREACHED */
7477 argc -= optind;
7478 argv += optind;
7480 if (argc > 1)
7481 usage_ref();
7483 error = got_repo_pack_fds_open(&pack_fds);
7484 if (error != NULL)
7485 goto done;
7487 if (repo_path == NULL) {
7488 cwd = getcwd(NULL, 0);
7489 if (cwd == NULL)
7490 return got_error_from_errno("getcwd");
7491 error = got_worktree_open(&worktree, cwd);
7492 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7493 goto done;
7494 if (worktree)
7495 repo_path =
7496 strdup(got_worktree_get_repo_path(worktree));
7497 else
7498 repo_path = strdup(cwd);
7499 if (repo_path == NULL) {
7500 error = got_error_from_errno("strdup");
7501 goto done;
7505 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7506 if (error != NULL)
7507 goto done;
7509 init_curses();
7511 error = apply_unveil(got_repo_get_path(repo), NULL);
7512 if (error)
7513 goto done;
7515 error = tog_load_refs(repo, 0);
7516 if (error)
7517 goto done;
7519 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
7520 if (view == NULL) {
7521 error = got_error_from_errno("view_open");
7522 goto done;
7525 error = open_ref_view(view, repo);
7526 if (error)
7527 goto done;
7529 if (worktree) {
7530 /* Release work tree lock. */
7531 got_worktree_close(worktree);
7532 worktree = NULL;
7534 error = view_loop(view);
7535 done:
7536 free(repo_path);
7537 free(cwd);
7538 if (repo) {
7539 const struct got_error *close_err = got_repo_close(repo);
7540 if (close_err)
7541 error = close_err;
7543 if (pack_fds) {
7544 const struct got_error *pack_err =
7545 got_repo_pack_fds_close(pack_fds);
7546 if (error == NULL)
7547 error = pack_err;
7549 tog_free_refs();
7550 return error;
7554 * If view was scrolled down to move the selected line into view when opening a
7555 * horizontal split, scroll back up when closing the split/toggling fullscreen.
7557 static void
7558 offset_selection_up(struct tog_view *view)
7560 switch (view->type) {
7561 case TOG_VIEW_BLAME: {
7562 struct tog_blame_view_state *s = &view->state.blame;
7563 if (s->first_displayed_line == 1) {
7564 s->selected_line = MAX(s->selected_line - view->offset,
7565 1);
7566 break;
7568 if (s->first_displayed_line > view->offset)
7569 s->first_displayed_line -= view->offset;
7570 else
7571 s->first_displayed_line = 1;
7572 s->selected_line += view->offset;
7573 break;
7575 case TOG_VIEW_LOG:
7576 log_scroll_up(&view->state.log, view->offset);
7577 view->state.log.selected += view->offset;
7578 break;
7579 case TOG_VIEW_REF:
7580 ref_scroll_up(&view->state.ref, view->offset);
7581 view->state.ref.selected += view->offset;
7582 break;
7583 case TOG_VIEW_TREE:
7584 tree_scroll_up(&view->state.tree, view->offset);
7585 view->state.tree.selected += view->offset;
7586 break;
7587 default:
7588 break;
7591 view->offset = 0;
7595 * If the selected line is in the section of screen covered by the bottom split,
7596 * scroll down offset lines to move it into view and index its new position.
7598 static const struct got_error *
7599 offset_selection_down(struct tog_view *view)
7601 const struct got_error *err = NULL;
7602 const struct got_error *(*scrolld)(struct tog_view *, int);
7603 int *selected = NULL;
7604 int header, offset;
7606 switch (view->type) {
7607 case TOG_VIEW_BLAME: {
7608 struct tog_blame_view_state *s = &view->state.blame;
7609 header = 3;
7610 scrolld = NULL;
7611 if (s->selected_line > view->nlines - header) {
7612 offset = abs(view->nlines - s->selected_line - header);
7613 s->first_displayed_line += offset;
7614 s->selected_line -= offset;
7615 view->offset = offset;
7617 break;
7619 case TOG_VIEW_LOG: {
7620 struct tog_log_view_state *s = &view->state.log;
7621 scrolld = &log_scroll_down;
7622 header = 3;
7623 selected = &s->selected;
7624 break;
7626 case TOG_VIEW_REF: {
7627 struct tog_ref_view_state *s = &view->state.ref;
7628 scrolld = &ref_scroll_down;
7629 header = 3;
7630 selected = &s->selected;
7631 break;
7633 case TOG_VIEW_TREE: {
7634 struct tog_tree_view_state *s = &view->state.tree;
7635 scrolld = &tree_scroll_down;
7636 header = 5;
7637 selected = &s->selected;
7638 break;
7640 default:
7641 selected = NULL;
7642 scrolld = NULL;
7643 header = 0;
7644 break;
7647 if (selected && *selected > view->nlines - header) {
7648 offset = abs(view->nlines - *selected - header);
7649 view->offset = offset;
7650 if (scrolld && offset) {
7651 err = scrolld(view, offset);
7652 *selected -= offset;
7656 return err;
7659 static void
7660 list_commands(FILE *fp)
7662 size_t i;
7664 fprintf(fp, "commands:");
7665 for (i = 0; i < nitems(tog_commands); i++) {
7666 const struct tog_cmd *cmd = &tog_commands[i];
7667 fprintf(fp, " %s", cmd->name);
7669 fputc('\n', fp);
7672 __dead static void
7673 usage(int hflag, int status)
7675 FILE *fp = (status == 0) ? stdout : stderr;
7677 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
7678 getprogname());
7679 if (hflag) {
7680 fprintf(fp, "lazy usage: %s path\n", getprogname());
7681 list_commands(fp);
7683 exit(status);
7686 static char **
7687 make_argv(int argc, ...)
7689 va_list ap;
7690 char **argv;
7691 int i;
7693 va_start(ap, argc);
7695 argv = calloc(argc, sizeof(char *));
7696 if (argv == NULL)
7697 err(1, "calloc");
7698 for (i = 0; i < argc; i++) {
7699 argv[i] = strdup(va_arg(ap, char *));
7700 if (argv[i] == NULL)
7701 err(1, "strdup");
7704 va_end(ap);
7705 return argv;
7709 * Try to convert 'tog path' into a 'tog log path' command.
7710 * The user could simply have mistyped the command rather than knowingly
7711 * provided a path. So check whether argv[0] can in fact be resolved
7712 * to a path in the HEAD commit and print a special error if not.
7713 * This hack is for mpi@ <3
7715 static const struct got_error *
7716 tog_log_with_path(int argc, char *argv[])
7718 const struct got_error *error = NULL, *close_err;
7719 const struct tog_cmd *cmd = NULL;
7720 struct got_repository *repo = NULL;
7721 struct got_worktree *worktree = NULL;
7722 struct got_object_id *commit_id = NULL, *id = NULL;
7723 struct got_commit_object *commit = NULL;
7724 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7725 char *commit_id_str = NULL, **cmd_argv = NULL;
7726 int *pack_fds = NULL;
7728 cwd = getcwd(NULL, 0);
7729 if (cwd == NULL)
7730 return got_error_from_errno("getcwd");
7732 error = got_repo_pack_fds_open(&pack_fds);
7733 if (error != NULL)
7734 goto done;
7736 error = got_worktree_open(&worktree, cwd);
7737 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7738 goto done;
7740 if (worktree)
7741 repo_path = strdup(got_worktree_get_repo_path(worktree));
7742 else
7743 repo_path = strdup(cwd);
7744 if (repo_path == NULL) {
7745 error = got_error_from_errno("strdup");
7746 goto done;
7749 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7750 if (error != NULL)
7751 goto done;
7753 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7754 repo, worktree);
7755 if (error)
7756 goto done;
7758 error = tog_load_refs(repo, 0);
7759 if (error)
7760 goto done;
7761 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
7762 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
7763 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7764 if (error)
7765 goto done;
7767 if (worktree) {
7768 got_worktree_close(worktree);
7769 worktree = NULL;
7772 error = got_object_open_as_commit(&commit, repo, commit_id);
7773 if (error)
7774 goto done;
7776 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
7777 if (error) {
7778 if (error->code != GOT_ERR_NO_TREE_ENTRY)
7779 goto done;
7780 fprintf(stderr, "%s: '%s' is no known command or path\n",
7781 getprogname(), argv[0]);
7782 usage(1, 1);
7783 /* not reached */
7786 close_err = got_repo_close(repo);
7787 if (error == NULL)
7788 error = close_err;
7789 repo = NULL;
7791 error = got_object_id_str(&commit_id_str, commit_id);
7792 if (error)
7793 goto done;
7795 cmd = &tog_commands[0]; /* log */
7796 argc = 4;
7797 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
7798 error = cmd->cmd_main(argc, cmd_argv);
7799 done:
7800 if (repo) {
7801 close_err = got_repo_close(repo);
7802 if (error == NULL)
7803 error = close_err;
7805 if (commit)
7806 got_object_commit_close(commit);
7807 if (worktree)
7808 got_worktree_close(worktree);
7809 if (pack_fds) {
7810 const struct got_error *pack_err =
7811 got_repo_pack_fds_close(pack_fds);
7812 if (error == NULL)
7813 error = pack_err;
7815 free(id);
7816 free(commit_id_str);
7817 free(commit_id);
7818 free(cwd);
7819 free(repo_path);
7820 free(in_repo_path);
7821 if (cmd_argv) {
7822 int i;
7823 for (i = 0; i < argc; i++)
7824 free(cmd_argv[i]);
7825 free(cmd_argv);
7827 tog_free_refs();
7828 return error;
7831 int
7832 main(int argc, char *argv[])
7834 const struct got_error *error = NULL;
7835 const struct tog_cmd *cmd = NULL;
7836 int ch, hflag = 0, Vflag = 0;
7837 char **cmd_argv = NULL;
7838 static const struct option longopts[] = {
7839 { "version", no_argument, NULL, 'V' },
7840 { NULL, 0, NULL, 0}
7843 setlocale(LC_CTYPE, "");
7845 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
7846 switch (ch) {
7847 case 'h':
7848 hflag = 1;
7849 break;
7850 case 'V':
7851 Vflag = 1;
7852 break;
7853 default:
7854 usage(hflag, 1);
7855 /* NOTREACHED */
7859 argc -= optind;
7860 argv += optind;
7861 optind = 1;
7862 optreset = 1;
7864 if (Vflag) {
7865 got_version_print_str();
7866 return 0;
7869 #ifndef PROFILE
7870 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
7871 NULL) == -1)
7872 err(1, "pledge");
7873 #endif
7875 if (argc == 0) {
7876 if (hflag)
7877 usage(hflag, 0);
7878 /* Build an argument vector which runs a default command. */
7879 cmd = &tog_commands[0];
7880 argc = 1;
7881 cmd_argv = make_argv(argc, cmd->name);
7882 } else {
7883 size_t i;
7885 /* Did the user specify a command? */
7886 for (i = 0; i < nitems(tog_commands); i++) {
7887 if (strncmp(tog_commands[i].name, argv[0],
7888 strlen(argv[0])) == 0) {
7889 cmd = &tog_commands[i];
7890 break;
7895 if (cmd == NULL) {
7896 if (argc != 1)
7897 usage(0, 1);
7898 /* No command specified; try log with a path */
7899 error = tog_log_with_path(argc, argv);
7900 } else {
7901 if (hflag)
7902 cmd->cmd_usage();
7903 else
7904 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
7907 endwin();
7908 putchar('\n');
7909 if (cmd_argv) {
7910 int i;
7911 for (i = 0; i < argc; i++)
7912 free(cmd_argv[i]);
7913 free(cmd_argv);
7916 if (error && error->code != GOT_ERR_CANCELLED)
7917 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7918 return 0;