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 #if defined(__FreeBSD__) || defined(__APPLE__)
24 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
25 #endif
26 #include <curses.h>
27 #include <panel.h>
28 #include <locale.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_compat.h"
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 };
113 enum tog_view_mode {
114 TOG_VIEW_SPLIT_NONE,
115 TOG_VIEW_SPLIT_VERT,
116 TOG_VIEW_SPLIT_HRZN
117 };
119 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
121 #define TOG_EOF_STRING "(END)"
123 struct commit_queue_entry {
124 TAILQ_ENTRY(commit_queue_entry) entry;
125 struct got_object_id *id;
126 struct got_commit_object *commit;
127 int idx;
128 };
129 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
130 struct commit_queue {
131 int ncommits;
132 struct commit_queue_head head;
133 };
135 struct tog_color {
136 STAILQ_ENTRY(tog_color) entry;
137 regex_t regex;
138 short colorpair;
139 };
140 STAILQ_HEAD(tog_colors, tog_color);
142 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
143 static struct got_reflist_object_id_map *tog_refs_idmap;
144 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
146 static const struct got_error *
147 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
148 struct got_reference* re2)
150 const char *name1 = got_ref_get_name(re1);
151 const char *name2 = got_ref_get_name(re2);
152 int isbackup1, isbackup2;
154 /* Sort backup refs towards the bottom of the list. */
155 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
156 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
157 if (!isbackup1 && isbackup2) {
158 *cmp = -1;
159 return NULL;
160 } else if (isbackup1 && !isbackup2) {
161 *cmp = 1;
162 return NULL;
165 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
166 return NULL;
169 static const struct got_error *
170 tog_load_refs(struct got_repository *repo, int sort_by_date)
172 const struct got_error *err;
174 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
175 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
176 repo);
177 if (err)
178 return err;
180 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
181 repo);
184 static void
185 tog_free_refs(void)
187 if (tog_refs_idmap) {
188 got_reflist_object_id_map_free(tog_refs_idmap);
189 tog_refs_idmap = NULL;
191 got_ref_list_free(&tog_refs);
194 static const struct got_error *
195 add_color(struct tog_colors *colors, const char *pattern,
196 int idx, short color)
198 const struct got_error *err = NULL;
199 struct tog_color *tc;
200 int regerr = 0;
202 if (idx < 1 || idx > COLOR_PAIRS - 1)
203 return NULL;
205 init_pair(idx, color, -1);
207 tc = calloc(1, sizeof(*tc));
208 if (tc == NULL)
209 return got_error_from_errno("calloc");
210 regerr = regcomp(&tc->regex, pattern,
211 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
212 if (regerr) {
213 static char regerr_msg[512];
214 static char err_msg[512];
215 regerror(regerr, &tc->regex, regerr_msg,
216 sizeof(regerr_msg));
217 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
218 regerr_msg);
219 err = got_error_msg(GOT_ERR_REGEX, err_msg);
220 free(tc);
221 return err;
223 tc->colorpair = idx;
224 STAILQ_INSERT_HEAD(colors, tc, entry);
225 return NULL;
228 static void
229 free_colors(struct tog_colors *colors)
231 struct tog_color *tc;
233 while (!STAILQ_EMPTY(colors)) {
234 tc = STAILQ_FIRST(colors);
235 STAILQ_REMOVE_HEAD(colors, entry);
236 regfree(&tc->regex);
237 free(tc);
241 static struct tog_color *
242 get_color(struct tog_colors *colors, int colorpair)
244 struct tog_color *tc = NULL;
246 STAILQ_FOREACH(tc, colors, entry) {
247 if (tc->colorpair == colorpair)
248 return tc;
251 return NULL;
254 static int
255 default_color_value(const char *envvar)
257 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
258 return COLOR_MAGENTA;
259 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
260 return COLOR_CYAN;
261 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
262 return COLOR_YELLOW;
263 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
264 return COLOR_GREEN;
265 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
266 return COLOR_MAGENTA;
267 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
268 return COLOR_MAGENTA;
269 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
270 return COLOR_CYAN;
271 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
272 return COLOR_GREEN;
273 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
274 return COLOR_GREEN;
275 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
276 return COLOR_CYAN;
277 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
278 return COLOR_YELLOW;
279 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
280 return COLOR_GREEN;
281 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
282 return COLOR_MAGENTA;
283 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
284 return COLOR_YELLOW;
285 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
286 return COLOR_CYAN;
288 return -1;
291 static int
292 get_color_value(const char *envvar)
294 const char *val = getenv(envvar);
296 if (val == NULL)
297 return default_color_value(envvar);
299 if (strcasecmp(val, "black") == 0)
300 return COLOR_BLACK;
301 if (strcasecmp(val, "red") == 0)
302 return COLOR_RED;
303 if (strcasecmp(val, "green") == 0)
304 return COLOR_GREEN;
305 if (strcasecmp(val, "yellow") == 0)
306 return COLOR_YELLOW;
307 if (strcasecmp(val, "blue") == 0)
308 return COLOR_BLUE;
309 if (strcasecmp(val, "magenta") == 0)
310 return COLOR_MAGENTA;
311 if (strcasecmp(val, "cyan") == 0)
312 return COLOR_CYAN;
313 if (strcasecmp(val, "white") == 0)
314 return COLOR_WHITE;
315 if (strcasecmp(val, "default") == 0)
316 return -1;
318 return default_color_value(envvar);
321 struct tog_diff_view_state {
322 struct got_object_id *id1, *id2;
323 const char *label1, *label2;
324 FILE *f, *f1, *f2;
325 int fd1, fd2;
326 int lineno;
327 int first_displayed_line;
328 int last_displayed_line;
329 int eof;
330 int diff_context;
331 int ignore_whitespace;
332 int force_text_diff;
333 struct got_repository *repo;
334 struct got_diff_line *lines;
335 size_t nlines;
336 int matched_line;
337 int selected_line;
339 /* passed from log or blame view; may be NULL */
340 struct tog_view *parent_view;
341 };
343 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
344 static volatile sig_atomic_t tog_thread_error;
346 struct tog_log_thread_args {
347 pthread_cond_t need_commits;
348 pthread_cond_t commit_loaded;
349 int commits_needed;
350 int load_all;
351 struct got_commit_graph *graph;
352 struct commit_queue *real_commits;
353 const char *in_repo_path;
354 struct got_object_id *start_id;
355 struct got_repository *repo;
356 int *pack_fds;
357 int log_complete;
358 sig_atomic_t *quit;
359 struct commit_queue_entry **first_displayed_entry;
360 struct commit_queue_entry **selected_entry;
361 int *searching;
362 int *search_next_done;
363 regex_t *regex;
364 int *limiting;
365 int limit_match;
366 regex_t *limit_regex;
367 struct commit_queue *limit_commits;
368 };
370 struct tog_log_view_state {
371 struct commit_queue *commits;
372 struct commit_queue_entry *first_displayed_entry;
373 struct commit_queue_entry *last_displayed_entry;
374 struct commit_queue_entry *selected_entry;
375 struct commit_queue real_commits;
376 int selected;
377 char *in_repo_path;
378 char *head_ref_name;
379 int log_branches;
380 struct got_repository *repo;
381 struct got_object_id *start_id;
382 sig_atomic_t quit;
383 pthread_t thread;
384 struct tog_log_thread_args thread_args;
385 struct commit_queue_entry *matched_entry;
386 struct commit_queue_entry *search_entry;
387 struct tog_colors colors;
388 int use_committer;
389 int limit_view;
390 regex_t limit_regex;
391 struct commit_queue limit_commits;
392 };
394 #define TOG_COLOR_DIFF_MINUS 1
395 #define TOG_COLOR_DIFF_PLUS 2
396 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
397 #define TOG_COLOR_DIFF_META 4
398 #define TOG_COLOR_TREE_SUBMODULE 5
399 #define TOG_COLOR_TREE_SYMLINK 6
400 #define TOG_COLOR_TREE_DIRECTORY 7
401 #define TOG_COLOR_TREE_EXECUTABLE 8
402 #define TOG_COLOR_COMMIT 9
403 #define TOG_COLOR_AUTHOR 10
404 #define TOG_COLOR_DATE 11
405 #define TOG_COLOR_REFS_HEADS 12
406 #define TOG_COLOR_REFS_TAGS 13
407 #define TOG_COLOR_REFS_REMOTES 14
408 #define TOG_COLOR_REFS_BACKUP 15
410 struct tog_blame_cb_args {
411 struct tog_blame_line *lines; /* one per line */
412 int nlines;
414 struct tog_view *view;
415 struct got_object_id *commit_id;
416 int *quit;
417 };
419 struct tog_blame_thread_args {
420 const char *path;
421 struct got_repository *repo;
422 struct tog_blame_cb_args *cb_args;
423 int *complete;
424 got_cancel_cb cancel_cb;
425 void *cancel_arg;
426 };
428 struct tog_blame {
429 FILE *f;
430 off_t filesize;
431 struct tog_blame_line *lines;
432 int nlines;
433 off_t *line_offsets;
434 pthread_t thread;
435 struct tog_blame_thread_args thread_args;
436 struct tog_blame_cb_args cb_args;
437 const char *path;
438 int *pack_fds;
439 };
441 struct tog_blame_view_state {
442 int first_displayed_line;
443 int last_displayed_line;
444 int selected_line;
445 int last_diffed_line;
446 int blame_complete;
447 int eof;
448 int done;
449 struct got_object_id_queue blamed_commits;
450 struct got_object_qid *blamed_commit;
451 char *path;
452 struct got_repository *repo;
453 struct got_object_id *commit_id;
454 struct got_object_id *id_to_log;
455 struct tog_blame blame;
456 int matched_line;
457 struct tog_colors colors;
458 };
460 struct tog_parent_tree {
461 TAILQ_ENTRY(tog_parent_tree) entry;
462 struct got_tree_object *tree;
463 struct got_tree_entry *first_displayed_entry;
464 struct got_tree_entry *selected_entry;
465 int selected;
466 };
468 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
470 struct tog_tree_view_state {
471 char *tree_label;
472 struct got_object_id *commit_id;/* commit which this tree belongs to */
473 struct got_tree_object *root; /* the commit's root tree entry */
474 struct got_tree_object *tree; /* currently displayed (sub-)tree */
475 struct got_tree_entry *first_displayed_entry;
476 struct got_tree_entry *last_displayed_entry;
477 struct got_tree_entry *selected_entry;
478 int ndisplayed, selected, show_ids;
479 struct tog_parent_trees parents; /* parent trees of current sub-tree */
480 char *head_ref_name;
481 struct got_repository *repo;
482 struct got_tree_entry *matched_entry;
483 struct tog_colors colors;
484 };
486 struct tog_reflist_entry {
487 TAILQ_ENTRY(tog_reflist_entry) entry;
488 struct got_reference *ref;
489 int idx;
490 };
492 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
494 struct tog_ref_view_state {
495 struct tog_reflist_head refs;
496 struct tog_reflist_entry *first_displayed_entry;
497 struct tog_reflist_entry *last_displayed_entry;
498 struct tog_reflist_entry *selected_entry;
499 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
500 struct got_repository *repo;
501 struct tog_reflist_entry *matched_entry;
502 struct tog_colors colors;
503 };
505 /*
506 * We implement two types of views: parent views and child views.
508 * The 'Tab' key switches focus between a parent view and its child view.
509 * Child views are shown side-by-side to their parent view, provided
510 * there is enough screen estate.
512 * When a new view is opened from within a parent view, this new view
513 * becomes a child view of the parent view, replacing any existing child.
515 * When a new view is opened from within a child view, this new view
516 * becomes a parent view which will obscure the views below until the
517 * user quits the new parent view by typing 'q'.
519 * This list of views contains parent views only.
520 * Child views are only pointed to by their parent view.
521 */
522 TAILQ_HEAD(tog_view_list_head, tog_view);
524 struct tog_view {
525 TAILQ_ENTRY(tog_view) entry;
526 WINDOW *window;
527 PANEL *panel;
528 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
529 int resized_y, resized_x; /* begin_y/x based on user resizing */
530 int maxx, x; /* max column and current start column */
531 int lines, cols; /* copies of LINES and COLS */
532 int nscrolled, offset; /* lines scrolled and hsplit line offset */
533 int gline, hiline; /* navigate to and highlight this nG line */
534 int ch, count; /* current keymap and count prefix */
535 int resized; /* set when in a resize event */
536 int focussed; /* Only set on one parent or child view at a time. */
537 int dying;
538 struct tog_view *parent;
539 struct tog_view *child;
541 /*
542 * This flag is initially set on parent views when a new child view
543 * is created. It gets toggled when the 'Tab' key switches focus
544 * between parent and child.
545 * The flag indicates whether focus should be passed on to our child
546 * view if this parent view gets picked for focus after another parent
547 * view was closed. This prevents child views from losing focus in such
548 * situations.
549 */
550 int focus_child;
552 enum tog_view_mode mode;
553 /* type-specific state */
554 enum tog_view_type type;
555 union {
556 struct tog_diff_view_state diff;
557 struct tog_log_view_state log;
558 struct tog_blame_view_state blame;
559 struct tog_tree_view_state tree;
560 struct tog_ref_view_state ref;
561 } state;
563 const struct got_error *(*show)(struct tog_view *);
564 const struct got_error *(*input)(struct tog_view **,
565 struct tog_view *, int);
566 const struct got_error *(*reset)(struct tog_view *);
567 const struct got_error *(*resize)(struct tog_view *, int);
568 const struct got_error *(*close)(struct tog_view *);
570 const struct got_error *(*search_start)(struct tog_view *);
571 const struct got_error *(*search_next)(struct tog_view *);
572 int search_started;
573 int searching;
574 #define TOG_SEARCH_FORWARD 1
575 #define TOG_SEARCH_BACKWARD 2
576 int search_next_done;
577 #define TOG_SEARCH_HAVE_MORE 1
578 #define TOG_SEARCH_NO_MORE 2
579 #define TOG_SEARCH_HAVE_NONE 3
580 regex_t regex;
581 regmatch_t regmatch;
582 };
584 static const struct got_error *open_diff_view(struct tog_view *,
585 struct got_object_id *, struct got_object_id *,
586 const char *, const char *, int, int, int, struct tog_view *,
587 struct got_repository *);
588 static const struct got_error *show_diff_view(struct tog_view *);
589 static const struct got_error *input_diff_view(struct tog_view **,
590 struct tog_view *, int);
591 static const struct got_error *reset_diff_view(struct tog_view *);
592 static const struct got_error* close_diff_view(struct tog_view *);
593 static const struct got_error *search_start_diff_view(struct tog_view *);
594 static const struct got_error *search_next_diff_view(struct tog_view *);
596 static const struct got_error *open_log_view(struct tog_view *,
597 struct got_object_id *, struct got_repository *,
598 const char *, const char *, int);
599 static const struct got_error * show_log_view(struct tog_view *);
600 static const struct got_error *input_log_view(struct tog_view **,
601 struct tog_view *, int);
602 static const struct got_error *resize_log_view(struct tog_view *, int);
603 static const struct got_error *close_log_view(struct tog_view *);
604 static const struct got_error *search_start_log_view(struct tog_view *);
605 static const struct got_error *search_next_log_view(struct tog_view *);
607 static const struct got_error *open_blame_view(struct tog_view *, char *,
608 struct got_object_id *, struct got_repository *);
609 static const struct got_error *show_blame_view(struct tog_view *);
610 static const struct got_error *input_blame_view(struct tog_view **,
611 struct tog_view *, int);
612 static const struct got_error *reset_blame_view(struct tog_view *);
613 static const struct got_error *close_blame_view(struct tog_view *);
614 static const struct got_error *search_start_blame_view(struct tog_view *);
615 static const struct got_error *search_next_blame_view(struct tog_view *);
617 static const struct got_error *open_tree_view(struct tog_view *,
618 struct got_object_id *, const char *, struct got_repository *);
619 static const struct got_error *show_tree_view(struct tog_view *);
620 static const struct got_error *input_tree_view(struct tog_view **,
621 struct tog_view *, int);
622 static const struct got_error *close_tree_view(struct tog_view *);
623 static const struct got_error *search_start_tree_view(struct tog_view *);
624 static const struct got_error *search_next_tree_view(struct tog_view *);
626 static const struct got_error *open_ref_view(struct tog_view *,
627 struct got_repository *);
628 static const struct got_error *show_ref_view(struct tog_view *);
629 static const struct got_error *input_ref_view(struct tog_view **,
630 struct tog_view *, int);
631 static const struct got_error *close_ref_view(struct tog_view *);
632 static const struct got_error *search_start_ref_view(struct tog_view *);
633 static const struct got_error *search_next_ref_view(struct tog_view *);
635 static volatile sig_atomic_t tog_sigwinch_received;
636 static volatile sig_atomic_t tog_sigpipe_received;
637 static volatile sig_atomic_t tog_sigcont_received;
638 static volatile sig_atomic_t tog_sigint_received;
639 static volatile sig_atomic_t tog_sigterm_received;
641 static void
642 tog_sigwinch(int signo)
644 tog_sigwinch_received = 1;
647 static void
648 tog_sigpipe(int signo)
650 tog_sigpipe_received = 1;
653 static void
654 tog_sigcont(int signo)
656 tog_sigcont_received = 1;
659 static void
660 tog_sigint(int signo)
662 tog_sigint_received = 1;
665 static void
666 tog_sigterm(int signo)
668 tog_sigterm_received = 1;
671 static int
672 tog_fatal_signal_received(void)
674 return (tog_sigpipe_received ||
675 tog_sigint_received || tog_sigint_received);
678 static const struct got_error *
679 view_close(struct tog_view *view)
681 const struct got_error *err = NULL, *child_err = NULL;
683 if (view->child) {
684 child_err = view_close(view->child);
685 view->child = NULL;
687 if (view->close)
688 err = view->close(view);
689 if (view->panel)
690 del_panel(view->panel);
691 if (view->window)
692 delwin(view->window);
693 free(view);
694 return err ? err : child_err;
697 static struct tog_view *
698 view_open(int nlines, int ncols, int begin_y, int begin_x,
699 enum tog_view_type type)
701 struct tog_view *view = calloc(1, sizeof(*view));
703 if (view == NULL)
704 return NULL;
706 view->type = type;
707 view->lines = LINES;
708 view->cols = COLS;
709 view->nlines = nlines ? nlines : LINES - begin_y;
710 view->ncols = ncols ? ncols : COLS - begin_x;
711 view->begin_y = begin_y;
712 view->begin_x = begin_x;
713 view->window = newwin(nlines, ncols, begin_y, begin_x);
714 if (view->window == NULL) {
715 view_close(view);
716 return NULL;
718 view->panel = new_panel(view->window);
719 if (view->panel == NULL ||
720 set_panel_userptr(view->panel, view) != OK) {
721 view_close(view);
722 return NULL;
725 keypad(view->window, TRUE);
726 return view;
729 static int
730 view_split_begin_x(int begin_x)
732 if (begin_x > 0 || COLS < 120)
733 return 0;
734 return (COLS - MAX(COLS / 2, 80));
737 /* XXX Stub till we decide what to do. */
738 static int
739 view_split_begin_y(int lines)
741 return lines * HSPLIT_SCALE;
744 static const struct got_error *view_resize(struct tog_view *);
746 static const struct got_error *
747 view_splitscreen(struct tog_view *view)
749 const struct got_error *err = NULL;
751 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
752 if (view->resized_y && view->resized_y < view->lines)
753 view->begin_y = view->resized_y;
754 else
755 view->begin_y = view_split_begin_y(view->nlines);
756 view->begin_x = 0;
757 } else if (!view->resized) {
758 if (view->resized_x && view->resized_x < view->cols - 1 &&
759 view->cols > 119)
760 view->begin_x = view->resized_x;
761 else
762 view->begin_x = view_split_begin_x(0);
763 view->begin_y = 0;
765 view->nlines = LINES - view->begin_y;
766 view->ncols = COLS - view->begin_x;
767 view->lines = LINES;
768 view->cols = COLS;
769 err = view_resize(view);
770 if (err)
771 return err;
773 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
774 view->parent->nlines = view->begin_y;
776 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
777 return got_error_from_errno("mvwin");
779 return NULL;
782 static const struct got_error *
783 view_fullscreen(struct tog_view *view)
785 const struct got_error *err = NULL;
787 view->begin_x = 0;
788 view->begin_y = view->resized ? view->begin_y : 0;
789 view->nlines = view->resized ? view->nlines : LINES;
790 view->ncols = COLS;
791 view->lines = LINES;
792 view->cols = COLS;
793 err = view_resize(view);
794 if (err)
795 return err;
797 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
798 return got_error_from_errno("mvwin");
800 return NULL;
803 static int
804 view_is_parent_view(struct tog_view *view)
806 return view->parent == NULL;
809 static int
810 view_is_splitscreen(struct tog_view *view)
812 return view->begin_x > 0 || view->begin_y > 0;
815 static int
816 view_is_fullscreen(struct tog_view *view)
818 return view->nlines == LINES && view->ncols == COLS;
821 static int
822 view_is_hsplit_top(struct tog_view *view)
824 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
825 view_is_splitscreen(view->child);
828 static void
829 view_border(struct tog_view *view)
831 PANEL *panel;
832 const struct tog_view *view_above;
834 if (view->parent)
835 return view_border(view->parent);
837 panel = panel_above(view->panel);
838 if (panel == NULL)
839 return;
841 view_above = panel_userptr(panel);
842 if (view->mode == TOG_VIEW_SPLIT_HRZN)
843 mvwhline(view->window, view_above->begin_y - 1,
844 view->begin_x, got_locale_is_utf8() ?
845 ACS_HLINE : '-', view->ncols);
846 else
847 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
848 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
851 static const struct got_error *view_init_hsplit(struct tog_view *, int);
852 static const struct got_error *request_log_commits(struct tog_view *);
853 static const struct got_error *offset_selection_down(struct tog_view *);
854 static void offset_selection_up(struct tog_view *);
855 static void view_get_split(struct tog_view *, int *, int *);
857 static const struct got_error *
858 view_resize(struct tog_view *view)
860 const struct got_error *err = NULL;
861 int dif, nlines, ncols;
863 dif = LINES - view->lines; /* line difference */
865 if (view->lines > LINES)
866 nlines = view->nlines - (view->lines - LINES);
867 else
868 nlines = view->nlines + (LINES - view->lines);
869 if (view->cols > COLS)
870 ncols = view->ncols - (view->cols - COLS);
871 else
872 ncols = view->ncols + (COLS - view->cols);
874 if (view->child) {
875 int hs = view->child->begin_y;
877 if (!view_is_fullscreen(view))
878 view->child->begin_x = view_split_begin_x(view->begin_x);
879 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
880 view->child->begin_x == 0) {
881 ncols = COLS;
883 view_fullscreen(view->child);
884 if (view->child->focussed)
885 show_panel(view->child->panel);
886 else
887 show_panel(view->panel);
888 } else {
889 ncols = view->child->begin_x;
891 view_splitscreen(view->child);
892 show_panel(view->child->panel);
894 /*
895 * XXX This is ugly and needs to be moved into the above
896 * logic but "works" for now and my attempts at moving it
897 * break either 'tab' or 'F' key maps in horizontal splits.
898 */
899 if (hs) {
900 err = view_splitscreen(view->child);
901 if (err)
902 return err;
903 if (dif < 0) { /* top split decreased */
904 err = offset_selection_down(view);
905 if (err)
906 return err;
908 view_border(view);
909 update_panels();
910 doupdate();
911 show_panel(view->child->panel);
912 nlines = view->nlines;
914 } else if (view->parent == NULL)
915 ncols = COLS;
917 if (view->resize && dif > 0) {
918 err = view->resize(view, dif);
919 if (err)
920 return err;
923 if (wresize(view->window, nlines, ncols) == ERR)
924 return got_error_from_errno("wresize");
925 if (replace_panel(view->panel, view->window) == ERR)
926 return got_error_from_errno("replace_panel");
927 wclear(view->window);
929 view->nlines = nlines;
930 view->ncols = ncols;
931 view->lines = LINES;
932 view->cols = COLS;
934 return NULL;
937 static const struct got_error *
938 resize_log_view(struct tog_view *view, int increase)
940 struct tog_log_view_state *s = &view->state.log;
941 const struct got_error *err = NULL;
942 int n = 0;
944 if (s->selected_entry)
945 n = s->selected_entry->idx + view->lines - s->selected;
947 /*
948 * Request commits to account for the increased
949 * height so we have enough to populate the view.
950 */
951 if (s->commits->ncommits < n) {
952 view->nscrolled = n - s->commits->ncommits + increase + 1;
953 err = request_log_commits(view);
956 return err;
959 static void
960 view_adjust_offset(struct tog_view *view, int n)
962 if (n == 0)
963 return;
965 if (view->parent && view->parent->offset) {
966 if (view->parent->offset + n >= 0)
967 view->parent->offset += n;
968 else
969 view->parent->offset = 0;
970 } else if (view->offset) {
971 if (view->offset - n >= 0)
972 view->offset -= n;
973 else
974 view->offset = 0;
978 static const struct got_error *
979 view_resize_split(struct tog_view *view, int resize)
981 const struct got_error *err = NULL;
982 struct tog_view *v = NULL;
984 if (view->parent)
985 v = view->parent;
986 else
987 v = view;
989 if (!v->child || !view_is_splitscreen(v->child))
990 return NULL;
992 v->resized = v->child->resized = resize; /* lock for resize event */
994 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
995 if (v->child->resized_y)
996 v->child->begin_y = v->child->resized_y;
997 if (view->parent)
998 v->child->begin_y -= resize;
999 else
1000 v->child->begin_y += resize;
1001 if (v->child->begin_y < 3) {
1002 view->count = 0;
1003 v->child->begin_y = 3;
1004 } else if (v->child->begin_y > LINES - 1) {
1005 view->count = 0;
1006 v->child->begin_y = LINES - 1;
1008 v->ncols = COLS;
1009 v->child->ncols = COLS;
1010 view_adjust_offset(view, resize);
1011 err = view_init_hsplit(v, v->child->begin_y);
1012 if (err)
1013 return err;
1014 v->child->resized_y = v->child->begin_y;
1015 } else {
1016 if (v->child->resized_x)
1017 v->child->begin_x = v->child->resized_x;
1018 if (view->parent)
1019 v->child->begin_x -= resize;
1020 else
1021 v->child->begin_x += resize;
1022 if (v->child->begin_x < 11) {
1023 view->count = 0;
1024 v->child->begin_x = 11;
1025 } else if (v->child->begin_x > COLS - 1) {
1026 view->count = 0;
1027 v->child->begin_x = COLS - 1;
1029 v->child->resized_x = v->child->begin_x;
1032 v->child->mode = v->mode;
1033 v->child->nlines = v->lines - v->child->begin_y;
1034 v->child->ncols = v->cols - v->child->begin_x;
1035 v->focus_child = 1;
1037 err = view_fullscreen(v);
1038 if (err)
1039 return err;
1040 err = view_splitscreen(v->child);
1041 if (err)
1042 return err;
1044 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1045 err = offset_selection_down(v->child);
1046 if (err)
1047 return err;
1050 if (v->resize)
1051 err = v->resize(v, 0);
1052 else if (v->child->resize)
1053 err = v->child->resize(v->child, 0);
1055 v->resized = v->child->resized = 0;
1057 return err;
1060 static void
1061 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1063 struct tog_view *v = src->child ? src->child : src;
1065 dst->resized_x = v->resized_x;
1066 dst->resized_y = v->resized_y;
1069 static const struct got_error *
1070 view_close_child(struct tog_view *view)
1072 const struct got_error *err = NULL;
1074 if (view->child == NULL)
1075 return NULL;
1077 err = view_close(view->child);
1078 view->child = NULL;
1079 return err;
1082 static const struct got_error *
1083 view_set_child(struct tog_view *view, struct tog_view *child)
1085 const struct got_error *err = NULL;
1087 view->child = child;
1088 child->parent = view;
1090 err = view_resize(view);
1091 if (err)
1092 return err;
1094 if (view->child->resized_x || view->child->resized_y)
1095 err = view_resize_split(view, 0);
1097 return err;
1100 static const struct got_error *view_dispatch_request(struct tog_view **,
1101 struct tog_view *, enum tog_view_type, int, int);
1103 static const struct got_error *
1104 view_request_new(struct tog_view **requested, struct tog_view *view,
1105 enum tog_view_type request)
1107 struct tog_view *new_view = NULL;
1108 const struct got_error *err;
1109 int y = 0, x = 0;
1111 *requested = NULL;
1113 if (view_is_parent_view(view))
1114 view_get_split(view, &y, &x);
1116 err = view_dispatch_request(&new_view, view, request, y, x);
1117 if (err)
1118 return err;
1120 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN) {
1121 err = view_init_hsplit(view, y);
1122 if (err)
1123 return err;
1126 view->focussed = 0;
1127 new_view->focussed = 1;
1128 new_view->mode = view->mode;
1129 new_view->nlines = view->lines - y;
1131 if (view_is_parent_view(view)) {
1132 view_transfer_size(new_view, view);
1133 err = view_close_child(view);
1134 if (err)
1135 return err;
1136 err = view_set_child(view, new_view);
1137 if (err)
1138 return err;
1139 view->focus_child = 1;
1140 } else
1141 *requested = new_view;
1143 return NULL;
1146 static void
1147 tog_resizeterm(void)
1149 int cols, lines;
1150 struct winsize size;
1152 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1153 cols = 80; /* Default */
1154 lines = 24;
1155 } else {
1156 cols = size.ws_col;
1157 lines = size.ws_row;
1159 resize_term(lines, cols);
1162 static const struct got_error *
1163 view_search_start(struct tog_view *view)
1165 const struct got_error *err = NULL;
1166 struct tog_view *v = view;
1167 char pattern[1024];
1168 int ret;
1170 if (view->search_started) {
1171 regfree(&view->regex);
1172 view->searching = 0;
1173 memset(&view->regmatch, 0, sizeof(view->regmatch));
1175 view->search_started = 0;
1177 if (view->nlines < 1)
1178 return NULL;
1180 if (view_is_hsplit_top(view))
1181 v = view->child;
1183 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1184 wclrtoeol(v->window);
1186 nodelay(view->window, FALSE); /* block for search term input */
1187 nocbreak();
1188 echo();
1189 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1190 wrefresh(v->window);
1191 cbreak();
1192 noecho();
1193 nodelay(view->window, TRUE);
1194 if (ret == ERR)
1195 return NULL;
1197 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1198 err = view->search_start(view);
1199 if (err) {
1200 regfree(&view->regex);
1201 return err;
1203 view->search_started = 1;
1204 view->searching = TOG_SEARCH_FORWARD;
1205 view->search_next_done = 0;
1206 view->search_next(view);
1209 return NULL;
1212 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1213 static const struct got_error *
1214 switch_split(struct tog_view *view)
1216 const struct got_error *err = NULL;
1217 struct tog_view *v = NULL;
1219 if (view->parent)
1220 v = view->parent;
1221 else
1222 v = view;
1224 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1225 v->mode = TOG_VIEW_SPLIT_VERT;
1226 else
1227 v->mode = TOG_VIEW_SPLIT_HRZN;
1229 if (!v->child)
1230 return NULL;
1231 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1232 v->mode = TOG_VIEW_SPLIT_NONE;
1234 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1235 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1236 v->child->begin_y = v->child->resized_y;
1237 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1238 v->child->begin_x = v->child->resized_x;
1241 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1242 v->ncols = COLS;
1243 v->child->ncols = COLS;
1244 v->child->nscrolled = LINES - v->child->nlines;
1246 err = view_init_hsplit(v, v->child->begin_y);
1247 if (err)
1248 return err;
1250 v->child->mode = v->mode;
1251 v->child->nlines = v->lines - v->child->begin_y;
1252 v->focus_child = 1;
1254 err = view_fullscreen(v);
1255 if (err)
1256 return err;
1257 err = view_splitscreen(v->child);
1258 if (err)
1259 return err;
1261 if (v->mode == TOG_VIEW_SPLIT_NONE)
1262 v->mode = TOG_VIEW_SPLIT_VERT;
1263 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1264 err = offset_selection_down(v);
1265 if (err)
1266 return err;
1267 err = offset_selection_down(v->child);
1268 if (err)
1269 return err;
1270 } else {
1271 offset_selection_up(v);
1272 offset_selection_up(v->child);
1274 if (v->resize)
1275 err = v->resize(v, 0);
1276 else if (v->child->resize)
1277 err = v->child->resize(v->child, 0);
1279 return err;
1283 * Compute view->count from numeric input. Assign total to view->count and
1284 * return first non-numeric key entered.
1286 static int
1287 get_compound_key(struct tog_view *view, int c)
1289 struct tog_view *v = view;
1290 int x, n = 0;
1292 if (view_is_hsplit_top(view))
1293 v = view->child;
1294 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1295 v = view->parent;
1297 view->count = 0;
1298 cbreak(); /* block for input */
1299 nodelay(view->window, FALSE);
1300 wmove(v->window, v->nlines - 1, 0);
1301 wclrtoeol(v->window);
1302 waddch(v->window, ':');
1304 do {
1305 x = getcurx(v->window);
1306 if (x != ERR && x < view->ncols) {
1307 waddch(v->window, c);
1308 wrefresh(v->window);
1312 * Don't overflow. Max valid request should be the greatest
1313 * between the longest and total lines; cap at 10 million.
1315 if (n >= 9999999)
1316 n = 9999999;
1317 else
1318 n = n * 10 + (c - '0');
1319 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1321 if (c == 'G' || c == 'g') { /* nG key map */
1322 view->gline = view->hiline = n;
1323 n = 0;
1324 c = 0;
1327 /* Massage excessive or inapplicable values at the input handler. */
1328 view->count = n;
1330 return c;
1333 static const struct got_error *
1334 view_input(struct tog_view **new, int *done, struct tog_view *view,
1335 struct tog_view_list_head *views)
1337 const struct got_error *err = NULL;
1338 struct tog_view *v;
1339 int ch, errcode;
1341 *new = NULL;
1343 /* Clear "no matches" indicator. */
1344 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1345 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1346 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1347 view->count = 0;
1350 if (view->searching && !view->search_next_done) {
1351 errcode = pthread_mutex_unlock(&tog_mutex);
1352 if (errcode)
1353 return got_error_set_errno(errcode,
1354 "pthread_mutex_unlock");
1355 sched_yield();
1356 errcode = pthread_mutex_lock(&tog_mutex);
1357 if (errcode)
1358 return got_error_set_errno(errcode,
1359 "pthread_mutex_lock");
1360 view->search_next(view);
1361 return NULL;
1364 /* Allow threads to make progress while we are waiting for input. */
1365 errcode = pthread_mutex_unlock(&tog_mutex);
1366 if (errcode)
1367 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1368 /* If we have an unfinished count, let C-g or backspace abort. */
1369 if (view->count && --view->count) {
1370 cbreak();
1371 nodelay(view->window, TRUE);
1372 ch = wgetch(view->window);
1373 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1374 view->count = 0;
1375 else
1376 ch = view->ch;
1377 } else {
1378 ch = wgetch(view->window);
1379 if (ch >= '1' && ch <= '9')
1380 view->ch = ch = get_compound_key(view, ch);
1382 if (view->hiline && ch != ERR && ch != 0)
1383 view->hiline = 0; /* key pressed, clear line highlight */
1384 nodelay(view->window, TRUE);
1385 errcode = pthread_mutex_lock(&tog_mutex);
1386 if (errcode)
1387 return got_error_set_errno(errcode, "pthread_mutex_lock");
1389 if (tog_sigwinch_received || tog_sigcont_received) {
1390 tog_resizeterm();
1391 tog_sigwinch_received = 0;
1392 tog_sigcont_received = 0;
1393 TAILQ_FOREACH(v, views, entry) {
1394 err = view_resize(v);
1395 if (err)
1396 return err;
1397 err = v->input(new, v, KEY_RESIZE);
1398 if (err)
1399 return err;
1400 if (v->child) {
1401 err = view_resize(v->child);
1402 if (err)
1403 return err;
1404 err = v->child->input(new, v->child,
1405 KEY_RESIZE);
1406 if (err)
1407 return err;
1408 if (v->child->resized_x || v->child->resized_y) {
1409 err = view_resize_split(v, 0);
1410 if (err)
1411 return err;
1417 switch (ch) {
1418 case '\t':
1419 view->count = 0;
1420 if (view->child) {
1421 view->focussed = 0;
1422 view->child->focussed = 1;
1423 view->focus_child = 1;
1424 } else if (view->parent) {
1425 view->focussed = 0;
1426 view->parent->focussed = 1;
1427 view->parent->focus_child = 0;
1428 if (!view_is_splitscreen(view)) {
1429 if (view->parent->resize) {
1430 err = view->parent->resize(view->parent,
1431 0);
1432 if (err)
1433 return err;
1435 offset_selection_up(view->parent);
1436 err = view_fullscreen(view->parent);
1437 if (err)
1438 return err;
1441 break;
1442 case 'q':
1443 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1444 if (view->parent->resize) {
1445 /* might need more commits to fill fullscreen */
1446 err = view->parent->resize(view->parent, 0);
1447 if (err)
1448 break;
1450 offset_selection_up(view->parent);
1452 err = view->input(new, view, ch);
1453 view->dying = 1;
1454 break;
1455 case 'Q':
1456 *done = 1;
1457 break;
1458 case 'F':
1459 view->count = 0;
1460 if (view_is_parent_view(view)) {
1461 if (view->child == NULL)
1462 break;
1463 if (view_is_splitscreen(view->child)) {
1464 view->focussed = 0;
1465 view->child->focussed = 1;
1466 err = view_fullscreen(view->child);
1467 } else {
1468 err = view_splitscreen(view->child);
1469 if (!err)
1470 err = view_resize_split(view, 0);
1472 if (err)
1473 break;
1474 err = view->child->input(new, view->child,
1475 KEY_RESIZE);
1476 } else {
1477 if (view_is_splitscreen(view)) {
1478 view->parent->focussed = 0;
1479 view->focussed = 1;
1480 err = view_fullscreen(view);
1481 } else {
1482 err = view_splitscreen(view);
1483 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1484 err = view_resize(view->parent);
1485 if (!err)
1486 err = view_resize_split(view, 0);
1488 if (err)
1489 break;
1490 err = view->input(new, view, KEY_RESIZE);
1492 if (err)
1493 break;
1494 if (view->resize) {
1495 err = view->resize(view, 0);
1496 if (err)
1497 break;
1499 if (view->parent)
1500 err = offset_selection_down(view->parent);
1501 if (!err)
1502 err = offset_selection_down(view);
1503 break;
1504 case 'S':
1505 view->count = 0;
1506 err = switch_split(view);
1507 break;
1508 case '-':
1509 err = view_resize_split(view, -1);
1510 break;
1511 case '+':
1512 err = view_resize_split(view, 1);
1513 break;
1514 case KEY_RESIZE:
1515 break;
1516 case '/':
1517 view->count = 0;
1518 if (view->search_start)
1519 view_search_start(view);
1520 else
1521 err = view->input(new, view, ch);
1522 break;
1523 case 'N':
1524 case 'n':
1525 if (view->search_started && view->search_next) {
1526 view->searching = (ch == 'n' ?
1527 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1528 view->search_next_done = 0;
1529 view->search_next(view);
1530 } else
1531 err = view->input(new, view, ch);
1532 break;
1533 case 'A':
1534 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1535 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1536 else
1537 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1538 TAILQ_FOREACH(v, views, entry) {
1539 if (v->reset) {
1540 err = v->reset(v);
1541 if (err)
1542 return err;
1544 if (v->child && v->child->reset) {
1545 err = v->child->reset(v->child);
1546 if (err)
1547 return err;
1550 break;
1551 default:
1552 err = view->input(new, view, ch);
1553 break;
1556 return err;
1559 static int
1560 view_needs_focus_indication(struct tog_view *view)
1562 if (view_is_parent_view(view)) {
1563 if (view->child == NULL || view->child->focussed)
1564 return 0;
1565 if (!view_is_splitscreen(view->child))
1566 return 0;
1567 } else if (!view_is_splitscreen(view))
1568 return 0;
1570 return view->focussed;
1573 static const struct got_error *
1574 view_loop(struct tog_view *view)
1576 const struct got_error *err = NULL;
1577 struct tog_view_list_head views;
1578 struct tog_view *new_view;
1579 char *mode;
1580 int fast_refresh = 10;
1581 int done = 0, errcode;
1583 mode = getenv("TOG_VIEW_SPLIT_MODE");
1584 if (!mode || !(*mode == 'h' || *mode == 'H'))
1585 view->mode = TOG_VIEW_SPLIT_VERT;
1586 else
1587 view->mode = TOG_VIEW_SPLIT_HRZN;
1589 errcode = pthread_mutex_lock(&tog_mutex);
1590 if (errcode)
1591 return got_error_set_errno(errcode, "pthread_mutex_lock");
1593 TAILQ_INIT(&views);
1594 TAILQ_INSERT_HEAD(&views, view, entry);
1596 view->focussed = 1;
1597 err = view->show(view);
1598 if (err)
1599 return err;
1600 update_panels();
1601 doupdate();
1602 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1603 !tog_fatal_signal_received()) {
1604 /* Refresh fast during initialization, then become slower. */
1605 if (fast_refresh && fast_refresh-- == 0)
1606 halfdelay(10); /* switch to once per second */
1608 err = view_input(&new_view, &done, view, &views);
1609 if (err)
1610 break;
1611 if (view->dying) {
1612 struct tog_view *v, *prev = NULL;
1614 if (view_is_parent_view(view))
1615 prev = TAILQ_PREV(view, tog_view_list_head,
1616 entry);
1617 else if (view->parent)
1618 prev = view->parent;
1620 if (view->parent) {
1621 view->parent->child = NULL;
1622 view->parent->focus_child = 0;
1623 /* Restore fullscreen line height. */
1624 view->parent->nlines = view->parent->lines;
1625 err = view_resize(view->parent);
1626 if (err)
1627 break;
1628 /* Make resized splits persist. */
1629 view_transfer_size(view->parent, view);
1630 } else
1631 TAILQ_REMOVE(&views, view, entry);
1633 err = view_close(view);
1634 if (err)
1635 goto done;
1637 view = NULL;
1638 TAILQ_FOREACH(v, &views, entry) {
1639 if (v->focussed)
1640 break;
1642 if (view == NULL && new_view == NULL) {
1643 /* No view has focus. Try to pick one. */
1644 if (prev)
1645 view = prev;
1646 else if (!TAILQ_EMPTY(&views)) {
1647 view = TAILQ_LAST(&views,
1648 tog_view_list_head);
1650 if (view) {
1651 if (view->focus_child) {
1652 view->child->focussed = 1;
1653 view = view->child;
1654 } else
1655 view->focussed = 1;
1659 if (new_view) {
1660 struct tog_view *v, *t;
1661 /* Only allow one parent view per type. */
1662 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1663 if (v->type != new_view->type)
1664 continue;
1665 TAILQ_REMOVE(&views, v, entry);
1666 err = view_close(v);
1667 if (err)
1668 goto done;
1669 break;
1671 TAILQ_INSERT_TAIL(&views, new_view, entry);
1672 view = new_view;
1674 if (view) {
1675 if (view_is_parent_view(view)) {
1676 if (view->child && view->child->focussed)
1677 view = view->child;
1678 } else {
1679 if (view->parent && view->parent->focussed)
1680 view = view->parent;
1682 show_panel(view->panel);
1683 if (view->child && view_is_splitscreen(view->child))
1684 show_panel(view->child->panel);
1685 if (view->parent && view_is_splitscreen(view)) {
1686 err = view->parent->show(view->parent);
1687 if (err)
1688 goto done;
1690 err = view->show(view);
1691 if (err)
1692 goto done;
1693 if (view->child) {
1694 err = view->child->show(view->child);
1695 if (err)
1696 goto done;
1698 update_panels();
1699 doupdate();
1702 done:
1703 while (!TAILQ_EMPTY(&views)) {
1704 const struct got_error *close_err;
1705 view = TAILQ_FIRST(&views);
1706 TAILQ_REMOVE(&views, view, entry);
1707 close_err = view_close(view);
1708 if (close_err && err == NULL)
1709 err = close_err;
1712 errcode = pthread_mutex_unlock(&tog_mutex);
1713 if (errcode && err == NULL)
1714 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1716 return err;
1719 __dead static void
1720 usage_log(void)
1722 endwin();
1723 fprintf(stderr,
1724 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1725 getprogname());
1726 exit(1);
1729 /* Create newly allocated wide-character string equivalent to a byte string. */
1730 static const struct got_error *
1731 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1733 char *vis = NULL;
1734 const struct got_error *err = NULL;
1736 *ws = NULL;
1737 *wlen = mbstowcs(NULL, s, 0);
1738 if (*wlen == (size_t)-1) {
1739 int vislen;
1740 if (errno != EILSEQ)
1741 return got_error_from_errno("mbstowcs");
1743 /* byte string invalid in current encoding; try to "fix" it */
1744 err = got_mbsavis(&vis, &vislen, s);
1745 if (err)
1746 return err;
1747 *wlen = mbstowcs(NULL, vis, 0);
1748 if (*wlen == (size_t)-1) {
1749 err = got_error_from_errno("mbstowcs"); /* give up */
1750 goto done;
1754 *ws = calloc(*wlen + 1, sizeof(**ws));
1755 if (*ws == NULL) {
1756 err = got_error_from_errno("calloc");
1757 goto done;
1760 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1761 err = got_error_from_errno("mbstowcs");
1762 done:
1763 free(vis);
1764 if (err) {
1765 free(*ws);
1766 *ws = NULL;
1767 *wlen = 0;
1769 return err;
1772 static const struct got_error *
1773 expand_tab(char **ptr, const char *src)
1775 char *dst;
1776 size_t len, n, idx = 0, sz = 0;
1778 *ptr = NULL;
1779 n = len = strlen(src);
1780 dst = malloc(n + 1);
1781 if (dst == NULL)
1782 return got_error_from_errno("malloc");
1784 while (idx < len && src[idx]) {
1785 const char c = src[idx];
1787 if (c == '\t') {
1788 size_t nb = TABSIZE - sz % TABSIZE;
1789 char *p;
1791 p = realloc(dst, n + nb);
1792 if (p == NULL) {
1793 free(dst);
1794 return got_error_from_errno("realloc");
1797 dst = p;
1798 n += nb;
1799 memset(dst + sz, ' ', nb);
1800 sz += nb;
1801 } else
1802 dst[sz++] = src[idx];
1803 ++idx;
1806 dst[sz] = '\0';
1807 *ptr = dst;
1808 return NULL;
1812 * Advance at most n columns from wline starting at offset off.
1813 * Return the index to the first character after the span operation.
1814 * Return the combined column width of all spanned wide character in
1815 * *rcol.
1817 static int
1818 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1820 int width, i, cols = 0;
1822 if (n == 0) {
1823 *rcol = cols;
1824 return off;
1827 for (i = off; wline[i] != L'\0'; ++i) {
1828 if (wline[i] == L'\t')
1829 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1830 else
1831 width = wcwidth(wline[i]);
1833 if (width == -1) {
1834 width = 1;
1835 wline[i] = L'.';
1838 if (cols + width > n)
1839 break;
1840 cols += width;
1843 *rcol = cols;
1844 return i;
1848 * Format a line for display, ensuring that it won't overflow a width limit.
1849 * With scrolling, the width returned refers to the scrolled version of the
1850 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1852 static const struct got_error *
1853 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1854 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1856 const struct got_error *err = NULL;
1857 int cols;
1858 wchar_t *wline = NULL;
1859 char *exstr = NULL;
1860 size_t wlen;
1861 int i, scrollx;
1863 *wlinep = NULL;
1864 *widthp = 0;
1866 if (expand) {
1867 err = expand_tab(&exstr, line);
1868 if (err)
1869 return err;
1872 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1873 free(exstr);
1874 if (err)
1875 return err;
1877 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1879 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1880 wline[wlen - 1] = L'\0';
1881 wlen--;
1883 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1884 wline[wlen - 1] = L'\0';
1885 wlen--;
1888 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1889 wline[i] = L'\0';
1891 if (widthp)
1892 *widthp = cols;
1893 if (scrollxp)
1894 *scrollxp = scrollx;
1895 if (err)
1896 free(wline);
1897 else
1898 *wlinep = wline;
1899 return err;
1902 static const struct got_error*
1903 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1904 struct got_object_id *id, struct got_repository *repo)
1906 static const struct got_error *err = NULL;
1907 struct got_reflist_entry *re;
1908 char *s;
1909 const char *name;
1911 *refs_str = NULL;
1913 TAILQ_FOREACH(re, refs, entry) {
1914 struct got_tag_object *tag = NULL;
1915 struct got_object_id *ref_id;
1916 int cmp;
1918 name = got_ref_get_name(re->ref);
1919 if (strcmp(name, GOT_REF_HEAD) == 0)
1920 continue;
1921 if (strncmp(name, "refs/", 5) == 0)
1922 name += 5;
1923 if (strncmp(name, "got/", 4) == 0 &&
1924 strncmp(name, "got/backup/", 11) != 0)
1925 continue;
1926 if (strncmp(name, "heads/", 6) == 0)
1927 name += 6;
1928 if (strncmp(name, "remotes/", 8) == 0) {
1929 name += 8;
1930 s = strstr(name, "/" GOT_REF_HEAD);
1931 if (s != NULL && s[strlen(s)] == '\0')
1932 continue;
1934 err = got_ref_resolve(&ref_id, repo, re->ref);
1935 if (err)
1936 break;
1937 if (strncmp(name, "tags/", 5) == 0) {
1938 err = got_object_open_as_tag(&tag, repo, ref_id);
1939 if (err) {
1940 if (err->code != GOT_ERR_OBJ_TYPE) {
1941 free(ref_id);
1942 break;
1944 /* Ref points at something other than a tag. */
1945 err = NULL;
1946 tag = NULL;
1949 cmp = got_object_id_cmp(tag ?
1950 got_object_tag_get_object_id(tag) : ref_id, id);
1951 free(ref_id);
1952 if (tag)
1953 got_object_tag_close(tag);
1954 if (cmp != 0)
1955 continue;
1956 s = *refs_str;
1957 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1958 s ? ", " : "", name) == -1) {
1959 err = got_error_from_errno("asprintf");
1960 free(s);
1961 *refs_str = NULL;
1962 break;
1964 free(s);
1967 return err;
1970 static const struct got_error *
1971 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1972 int col_tab_align)
1974 char *smallerthan;
1976 smallerthan = strchr(author, '<');
1977 if (smallerthan && smallerthan[1] != '\0')
1978 author = smallerthan + 1;
1979 author[strcspn(author, "@>")] = '\0';
1980 return format_line(wauthor, author_width, NULL, author, 0, limit,
1981 col_tab_align, 0);
1984 static const struct got_error *
1985 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1986 struct got_object_id *id, const size_t date_display_cols,
1987 int author_display_cols)
1989 struct tog_log_view_state *s = &view->state.log;
1990 const struct got_error *err = NULL;
1991 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1992 char *logmsg0 = NULL, *logmsg = NULL;
1993 char *author = NULL;
1994 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1995 int author_width, logmsg_width;
1996 char *newline, *line = NULL;
1997 int col, limit, scrollx;
1998 const int avail = view->ncols;
1999 struct tm tm;
2000 time_t committer_time;
2001 struct tog_color *tc;
2003 committer_time = got_object_commit_get_committer_time(commit);
2004 if (gmtime_r(&committer_time, &tm) == NULL)
2005 return got_error_from_errno("gmtime_r");
2006 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2007 return got_error(GOT_ERR_NO_SPACE);
2009 if (avail <= date_display_cols)
2010 limit = MIN(sizeof(datebuf) - 1, avail);
2011 else
2012 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2013 tc = get_color(&s->colors, TOG_COLOR_DATE);
2014 if (tc)
2015 wattr_on(view->window,
2016 COLOR_PAIR(tc->colorpair), NULL);
2017 waddnstr(view->window, datebuf, limit);
2018 if (tc)
2019 wattr_off(view->window,
2020 COLOR_PAIR(tc->colorpair), NULL);
2021 col = limit;
2022 if (col > avail)
2023 goto done;
2025 if (avail >= 120) {
2026 char *id_str;
2027 err = got_object_id_str(&id_str, id);
2028 if (err)
2029 goto done;
2030 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2031 if (tc)
2032 wattr_on(view->window,
2033 COLOR_PAIR(tc->colorpair), NULL);
2034 wprintw(view->window, "%.8s ", id_str);
2035 if (tc)
2036 wattr_off(view->window,
2037 COLOR_PAIR(tc->colorpair), NULL);
2038 free(id_str);
2039 col += 9;
2040 if (col > avail)
2041 goto done;
2044 if (s->use_committer)
2045 author = strdup(got_object_commit_get_committer(commit));
2046 else
2047 author = strdup(got_object_commit_get_author(commit));
2048 if (author == NULL) {
2049 err = got_error_from_errno("strdup");
2050 goto done;
2052 err = format_author(&wauthor, &author_width, author, avail - col, col);
2053 if (err)
2054 goto done;
2055 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2056 if (tc)
2057 wattr_on(view->window,
2058 COLOR_PAIR(tc->colorpair), NULL);
2059 waddwstr(view->window, wauthor);
2060 col += author_width;
2061 while (col < avail && author_width < author_display_cols + 2) {
2062 waddch(view->window, ' ');
2063 col++;
2064 author_width++;
2066 if (tc)
2067 wattr_off(view->window,
2068 COLOR_PAIR(tc->colorpair), NULL);
2069 if (col > avail)
2070 goto done;
2072 err = got_object_commit_get_logmsg(&logmsg0, commit);
2073 if (err)
2074 goto done;
2075 logmsg = logmsg0;
2076 while (*logmsg == '\n')
2077 logmsg++;
2078 newline = strchr(logmsg, '\n');
2079 if (newline)
2080 *newline = '\0';
2081 limit = avail - col;
2082 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2083 limit--; /* for the border */
2084 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2085 limit, col, 1);
2086 if (err)
2087 goto done;
2088 waddwstr(view->window, &wlogmsg[scrollx]);
2089 col += MAX(logmsg_width, 0);
2090 while (col < avail) {
2091 waddch(view->window, ' ');
2092 col++;
2094 done:
2095 free(logmsg0);
2096 free(wlogmsg);
2097 free(author);
2098 free(wauthor);
2099 free(line);
2100 return err;
2103 static struct commit_queue_entry *
2104 alloc_commit_queue_entry(struct got_commit_object *commit,
2105 struct got_object_id *id)
2107 struct commit_queue_entry *entry;
2108 struct got_object_id *dup;
2110 entry = calloc(1, sizeof(*entry));
2111 if (entry == NULL)
2112 return NULL;
2114 dup = got_object_id_dup(id);
2115 if (dup == NULL) {
2116 free(entry);
2117 return NULL;
2120 entry->id = dup;
2121 entry->commit = commit;
2122 return entry;
2125 static void
2126 pop_commit(struct commit_queue *commits)
2128 struct commit_queue_entry *entry;
2130 entry = TAILQ_FIRST(&commits->head);
2131 TAILQ_REMOVE(&commits->head, entry, entry);
2132 got_object_commit_close(entry->commit);
2133 commits->ncommits--;
2134 free(entry->id);
2135 free(entry);
2138 static void
2139 free_commits(struct commit_queue *commits)
2141 while (!TAILQ_EMPTY(&commits->head))
2142 pop_commit(commits);
2145 static const struct got_error *
2146 match_commit(int *have_match, struct got_object_id *id,
2147 struct got_commit_object *commit, regex_t *regex)
2149 const struct got_error *err = NULL;
2150 regmatch_t regmatch;
2151 char *id_str = NULL, *logmsg = NULL;
2153 *have_match = 0;
2155 err = got_object_id_str(&id_str, id);
2156 if (err)
2157 return err;
2159 err = got_object_commit_get_logmsg(&logmsg, commit);
2160 if (err)
2161 goto done;
2163 if (regexec(regex, got_object_commit_get_author(commit), 1,
2164 &regmatch, 0) == 0 ||
2165 regexec(regex, got_object_commit_get_committer(commit), 1,
2166 &regmatch, 0) == 0 ||
2167 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2168 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2169 *have_match = 1;
2170 done:
2171 free(id_str);
2172 free(logmsg);
2173 return err;
2176 static const struct got_error *
2177 queue_commits(struct tog_log_thread_args *a)
2179 const struct got_error *err = NULL;
2182 * We keep all commits open throughout the lifetime of the log
2183 * view in order to avoid having to re-fetch commits from disk
2184 * while updating the display.
2186 do {
2187 struct got_object_id id;
2188 struct got_commit_object *commit;
2189 struct commit_queue_entry *entry;
2190 int limit_match = 0;
2191 int errcode;
2193 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2194 NULL, NULL);
2195 if (err)
2196 break;
2198 err = got_object_open_as_commit(&commit, a->repo, &id);
2199 if (err)
2200 break;
2201 entry = alloc_commit_queue_entry(commit, &id);
2202 if (entry == NULL) {
2203 err = got_error_from_errno("alloc_commit_queue_entry");
2204 break;
2207 errcode = pthread_mutex_lock(&tog_mutex);
2208 if (errcode) {
2209 err = got_error_set_errno(errcode,
2210 "pthread_mutex_lock");
2211 break;
2214 entry->idx = a->real_commits->ncommits;
2215 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2216 a->real_commits->ncommits++;
2218 if (*a->limiting) {
2219 err = match_commit(&limit_match, &id, commit,
2220 a->limit_regex);
2221 if (err)
2222 break;
2224 if (limit_match) {
2225 struct commit_queue_entry *matched;
2227 matched = alloc_commit_queue_entry(
2228 entry->commit, entry->id);
2229 if (matched == NULL) {
2230 err = got_error_from_errno(
2231 "alloc_commit_queue_entry");
2232 break;
2235 err = got_object_commit_dup(&matched->commit,
2236 entry->commit);
2237 if (err)
2238 break;
2240 matched->idx = a->limit_commits->ncommits;
2241 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2242 matched, entry);
2243 a->limit_commits->ncommits++;
2247 * This is how we signal log_thread() that we
2248 * have found a match, and that it should be
2249 * counted as a new entry for the view.
2251 a->limit_match = limit_match;
2254 if (*a->searching == TOG_SEARCH_FORWARD &&
2255 !*a->search_next_done) {
2256 int have_match;
2257 err = match_commit(&have_match, &id, commit, a->regex);
2258 if (err)
2259 break;
2261 if (*a->limiting) {
2262 if (limit_match && have_match)
2263 *a->search_next_done =
2264 TOG_SEARCH_HAVE_MORE;
2265 } else if (have_match)
2266 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2269 errcode = pthread_mutex_unlock(&tog_mutex);
2270 if (errcode && err == NULL)
2271 err = got_error_set_errno(errcode,
2272 "pthread_mutex_unlock");
2273 if (err)
2274 break;
2275 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2277 return err;
2280 static void
2281 select_commit(struct tog_log_view_state *s)
2283 struct commit_queue_entry *entry;
2284 int ncommits = 0;
2286 entry = s->first_displayed_entry;
2287 while (entry) {
2288 if (ncommits == s->selected) {
2289 s->selected_entry = entry;
2290 break;
2292 entry = TAILQ_NEXT(entry, entry);
2293 ncommits++;
2297 static const struct got_error *
2298 draw_commits(struct tog_view *view)
2300 const struct got_error *err = NULL;
2301 struct tog_log_view_state *s = &view->state.log;
2302 struct commit_queue_entry *entry = s->selected_entry;
2303 int limit = view->nlines;
2304 int width;
2305 int ncommits, author_cols = 4;
2306 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2307 char *refs_str = NULL;
2308 wchar_t *wline;
2309 struct tog_color *tc;
2310 static const size_t date_display_cols = 12;
2312 if (view_is_hsplit_top(view))
2313 --limit; /* account for border */
2315 if (s->selected_entry &&
2316 !(view->searching && view->search_next_done == 0)) {
2317 struct got_reflist_head *refs;
2318 err = got_object_id_str(&id_str, s->selected_entry->id);
2319 if (err)
2320 return err;
2321 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2322 s->selected_entry->id);
2323 if (refs) {
2324 err = build_refs_str(&refs_str, refs,
2325 s->selected_entry->id, s->repo);
2326 if (err)
2327 goto done;
2331 if (s->thread_args.commits_needed == 0)
2332 halfdelay(10); /* disable fast refresh */
2334 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2335 if (asprintf(&ncommits_str, " [%d/%d] %s",
2336 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2337 (view->searching && !view->search_next_done) ?
2338 "searching..." : "loading...") == -1) {
2339 err = got_error_from_errno("asprintf");
2340 goto done;
2342 } else {
2343 const char *search_str = NULL;
2344 const char *limit_str = NULL;
2346 if (view->searching) {
2347 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2348 search_str = "no more matches";
2349 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2350 search_str = "no matches found";
2351 else if (!view->search_next_done)
2352 search_str = "searching...";
2355 if (s->limit_view && s->commits->ncommits == 0)
2356 limit_str = "no matches found";
2358 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2359 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2360 search_str ? search_str : (refs_str ? refs_str : ""),
2361 limit_str ? limit_str : "") == -1) {
2362 err = got_error_from_errno("asprintf");
2363 goto done;
2367 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2368 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2369 "........................................",
2370 s->in_repo_path, ncommits_str) == -1) {
2371 err = got_error_from_errno("asprintf");
2372 header = NULL;
2373 goto done;
2375 } else if (asprintf(&header, "commit %s%s",
2376 id_str ? id_str : "........................................",
2377 ncommits_str) == -1) {
2378 err = got_error_from_errno("asprintf");
2379 header = NULL;
2380 goto done;
2382 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2383 if (err)
2384 goto done;
2386 werase(view->window);
2388 if (view_needs_focus_indication(view))
2389 wstandout(view->window);
2390 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2391 if (tc)
2392 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2393 waddwstr(view->window, wline);
2394 while (width < view->ncols) {
2395 waddch(view->window, ' ');
2396 width++;
2398 if (tc)
2399 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2400 if (view_needs_focus_indication(view))
2401 wstandend(view->window);
2402 free(wline);
2403 if (limit <= 1)
2404 goto done;
2406 /* Grow author column size if necessary, and set view->maxx. */
2407 entry = s->first_displayed_entry;
2408 ncommits = 0;
2409 view->maxx = 0;
2410 while (entry) {
2411 struct got_commit_object *c = entry->commit;
2412 char *author, *eol, *msg, *msg0;
2413 wchar_t *wauthor, *wmsg;
2414 int width;
2415 if (ncommits >= limit - 1)
2416 break;
2417 if (s->use_committer)
2418 author = strdup(got_object_commit_get_committer(c));
2419 else
2420 author = strdup(got_object_commit_get_author(c));
2421 if (author == NULL) {
2422 err = got_error_from_errno("strdup");
2423 goto done;
2425 err = format_author(&wauthor, &width, author, COLS,
2426 date_display_cols);
2427 if (author_cols < width)
2428 author_cols = width;
2429 free(wauthor);
2430 free(author);
2431 if (err)
2432 goto done;
2433 err = got_object_commit_get_logmsg(&msg0, c);
2434 if (err)
2435 goto done;
2436 msg = msg0;
2437 while (*msg == '\n')
2438 ++msg;
2439 if ((eol = strchr(msg, '\n')))
2440 *eol = '\0';
2441 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2442 date_display_cols + author_cols, 0);
2443 if (err)
2444 goto done;
2445 view->maxx = MAX(view->maxx, width);
2446 free(msg0);
2447 free(wmsg);
2448 ncommits++;
2449 entry = TAILQ_NEXT(entry, entry);
2452 entry = s->first_displayed_entry;
2453 s->last_displayed_entry = s->first_displayed_entry;
2454 ncommits = 0;
2455 while (entry) {
2456 if (ncommits >= limit - 1)
2457 break;
2458 if (ncommits == s->selected)
2459 wstandout(view->window);
2460 err = draw_commit(view, entry->commit, entry->id,
2461 date_display_cols, author_cols);
2462 if (ncommits == s->selected)
2463 wstandend(view->window);
2464 if (err)
2465 goto done;
2466 ncommits++;
2467 s->last_displayed_entry = entry;
2468 entry = TAILQ_NEXT(entry, entry);
2471 view_border(view);
2472 done:
2473 free(id_str);
2474 free(refs_str);
2475 free(ncommits_str);
2476 free(header);
2477 return err;
2480 static void
2481 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2483 struct commit_queue_entry *entry;
2484 int nscrolled = 0;
2486 entry = TAILQ_FIRST(&s->commits->head);
2487 if (s->first_displayed_entry == entry)
2488 return;
2490 entry = s->first_displayed_entry;
2491 while (entry && nscrolled < maxscroll) {
2492 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2493 if (entry) {
2494 s->first_displayed_entry = entry;
2495 nscrolled++;
2500 static const struct got_error *
2501 trigger_log_thread(struct tog_view *view, int wait)
2503 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2504 int errcode;
2506 halfdelay(1); /* fast refresh while loading commits */
2508 while (!ta->log_complete && !tog_thread_error &&
2509 (ta->commits_needed > 0 || ta->load_all)) {
2510 /* Wake the log thread. */
2511 errcode = pthread_cond_signal(&ta->need_commits);
2512 if (errcode)
2513 return got_error_set_errno(errcode,
2514 "pthread_cond_signal");
2517 * The mutex will be released while the view loop waits
2518 * in wgetch(), at which time the log thread will run.
2520 if (!wait)
2521 break;
2523 /* Display progress update in log view. */
2524 show_log_view(view);
2525 update_panels();
2526 doupdate();
2528 /* Wait right here while next commit is being loaded. */
2529 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2530 if (errcode)
2531 return got_error_set_errno(errcode,
2532 "pthread_cond_wait");
2534 /* Display progress update in log view. */
2535 show_log_view(view);
2536 update_panels();
2537 doupdate();
2540 return NULL;
2543 static const struct got_error *
2544 request_log_commits(struct tog_view *view)
2546 struct tog_log_view_state *state = &view->state.log;
2547 const struct got_error *err = NULL;
2549 if (state->thread_args.log_complete)
2550 return NULL;
2552 state->thread_args.commits_needed += view->nscrolled;
2553 err = trigger_log_thread(view, 1);
2554 view->nscrolled = 0;
2556 return err;
2559 static const struct got_error *
2560 log_scroll_down(struct tog_view *view, int maxscroll)
2562 struct tog_log_view_state *s = &view->state.log;
2563 const struct got_error *err = NULL;
2564 struct commit_queue_entry *pentry;
2565 int nscrolled = 0, ncommits_needed;
2567 if (s->last_displayed_entry == NULL)
2568 return NULL;
2570 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2571 if (s->commits->ncommits < ncommits_needed &&
2572 !s->thread_args.log_complete) {
2574 * Ask the log thread for required amount of commits.
2576 s->thread_args.commits_needed +=
2577 ncommits_needed - s->commits->ncommits;
2578 err = trigger_log_thread(view, 1);
2579 if (err)
2580 return err;
2583 do {
2584 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2585 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2586 break;
2588 s->last_displayed_entry = pentry ?
2589 pentry : s->last_displayed_entry;;
2591 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2592 if (pentry == NULL)
2593 break;
2594 s->first_displayed_entry = pentry;
2595 } while (++nscrolled < maxscroll);
2597 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2598 view->nscrolled += nscrolled;
2599 else
2600 view->nscrolled = 0;
2602 return err;
2605 static const struct got_error *
2606 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2607 struct got_commit_object *commit, struct got_object_id *commit_id,
2608 struct tog_view *log_view, struct got_repository *repo)
2610 const struct got_error *err;
2611 struct got_object_qid *parent_id;
2612 struct tog_view *diff_view;
2614 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2615 if (diff_view == NULL)
2616 return got_error_from_errno("view_open");
2618 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2619 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2620 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2621 if (err == NULL)
2622 *new_view = diff_view;
2623 return err;
2626 static const struct got_error *
2627 tree_view_visit_subtree(struct tog_tree_view_state *s,
2628 struct got_tree_object *subtree)
2630 struct tog_parent_tree *parent;
2632 parent = calloc(1, sizeof(*parent));
2633 if (parent == NULL)
2634 return got_error_from_errno("calloc");
2636 parent->tree = s->tree;
2637 parent->first_displayed_entry = s->first_displayed_entry;
2638 parent->selected_entry = s->selected_entry;
2639 parent->selected = s->selected;
2640 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2641 s->tree = subtree;
2642 s->selected = 0;
2643 s->first_displayed_entry = NULL;
2644 return NULL;
2647 static const struct got_error *
2648 tree_view_walk_path(struct tog_tree_view_state *s,
2649 struct got_commit_object *commit, const char *path)
2651 const struct got_error *err = NULL;
2652 struct got_tree_object *tree = NULL;
2653 const char *p;
2654 char *slash, *subpath = NULL;
2656 /* Walk the path and open corresponding tree objects. */
2657 p = path;
2658 while (*p) {
2659 struct got_tree_entry *te;
2660 struct got_object_id *tree_id;
2661 char *te_name;
2663 while (p[0] == '/')
2664 p++;
2666 /* Ensure the correct subtree entry is selected. */
2667 slash = strchr(p, '/');
2668 if (slash == NULL)
2669 te_name = strdup(p);
2670 else
2671 te_name = strndup(p, slash - p);
2672 if (te_name == NULL) {
2673 err = got_error_from_errno("strndup");
2674 break;
2676 te = got_object_tree_find_entry(s->tree, te_name);
2677 if (te == NULL) {
2678 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2679 free(te_name);
2680 break;
2682 free(te_name);
2683 s->first_displayed_entry = s->selected_entry = te;
2685 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2686 break; /* jump to this file's entry */
2688 slash = strchr(p, '/');
2689 if (slash)
2690 subpath = strndup(path, slash - path);
2691 else
2692 subpath = strdup(path);
2693 if (subpath == NULL) {
2694 err = got_error_from_errno("strdup");
2695 break;
2698 err = got_object_id_by_path(&tree_id, s->repo, commit,
2699 subpath);
2700 if (err)
2701 break;
2703 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2704 free(tree_id);
2705 if (err)
2706 break;
2708 err = tree_view_visit_subtree(s, tree);
2709 if (err) {
2710 got_object_tree_close(tree);
2711 break;
2713 if (slash == NULL)
2714 break;
2715 free(subpath);
2716 subpath = NULL;
2717 p = slash;
2720 free(subpath);
2721 return err;
2724 static const struct got_error *
2725 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2726 struct commit_queue_entry *entry, const char *path,
2727 const char *head_ref_name, struct got_repository *repo)
2729 const struct got_error *err = NULL;
2730 struct tog_tree_view_state *s;
2731 struct tog_view *tree_view;
2733 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2734 if (tree_view == NULL)
2735 return got_error_from_errno("view_open");
2737 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2738 if (err)
2739 return err;
2740 s = &tree_view->state.tree;
2742 *new_view = tree_view;
2744 if (got_path_is_root_dir(path))
2745 return NULL;
2747 return tree_view_walk_path(s, entry->commit, path);
2750 static const struct got_error *
2751 block_signals_used_by_main_thread(void)
2753 sigset_t sigset;
2754 int errcode;
2756 if (sigemptyset(&sigset) == -1)
2757 return got_error_from_errno("sigemptyset");
2759 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2760 if (sigaddset(&sigset, SIGWINCH) == -1)
2761 return got_error_from_errno("sigaddset");
2762 if (sigaddset(&sigset, SIGCONT) == -1)
2763 return got_error_from_errno("sigaddset");
2764 if (sigaddset(&sigset, SIGINT) == -1)
2765 return got_error_from_errno("sigaddset");
2766 if (sigaddset(&sigset, SIGTERM) == -1)
2767 return got_error_from_errno("sigaddset");
2769 /* ncurses handles SIGTSTP */
2770 if (sigaddset(&sigset, SIGTSTP) == -1)
2771 return got_error_from_errno("sigaddset");
2773 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2774 if (errcode)
2775 return got_error_set_errno(errcode, "pthread_sigmask");
2777 return NULL;
2780 static void *
2781 log_thread(void *arg)
2783 const struct got_error *err = NULL;
2784 int errcode = 0;
2785 struct tog_log_thread_args *a = arg;
2786 int done = 0;
2789 * Sync startup with main thread such that we begin our
2790 * work once view_input() has released the mutex.
2792 errcode = pthread_mutex_lock(&tog_mutex);
2793 if (errcode) {
2794 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2795 return (void *)err;
2798 err = block_signals_used_by_main_thread();
2799 if (err) {
2800 pthread_mutex_unlock(&tog_mutex);
2801 goto done;
2804 while (!done && !err && !tog_fatal_signal_received()) {
2805 errcode = pthread_mutex_unlock(&tog_mutex);
2806 if (errcode) {
2807 err = got_error_set_errno(errcode,
2808 "pthread_mutex_unlock");
2809 goto done;
2811 err = queue_commits(a);
2812 if (err) {
2813 if (err->code != GOT_ERR_ITER_COMPLETED)
2814 goto done;
2815 err = NULL;
2816 done = 1;
2817 } else if (a->commits_needed > 0 && !a->load_all) {
2818 if (*a->limiting) {
2819 if (a->limit_match)
2820 a->commits_needed--;
2821 } else
2822 a->commits_needed--;
2825 errcode = pthread_mutex_lock(&tog_mutex);
2826 if (errcode) {
2827 err = got_error_set_errno(errcode,
2828 "pthread_mutex_lock");
2829 goto done;
2830 } else if (*a->quit)
2831 done = 1;
2832 else if (*a->limiting && *a->first_displayed_entry == NULL) {
2833 *a->first_displayed_entry =
2834 TAILQ_FIRST(&a->limit_commits->head);
2835 *a->selected_entry = *a->first_displayed_entry;
2836 } else if (*a->first_displayed_entry == NULL) {
2837 *a->first_displayed_entry =
2838 TAILQ_FIRST(&a->real_commits->head);
2839 *a->selected_entry = *a->first_displayed_entry;
2842 errcode = pthread_cond_signal(&a->commit_loaded);
2843 if (errcode) {
2844 err = got_error_set_errno(errcode,
2845 "pthread_cond_signal");
2846 pthread_mutex_unlock(&tog_mutex);
2847 goto done;
2850 if (done)
2851 a->commits_needed = 0;
2852 else {
2853 if (a->commits_needed == 0 && !a->load_all) {
2854 errcode = pthread_cond_wait(&a->need_commits,
2855 &tog_mutex);
2856 if (errcode) {
2857 err = got_error_set_errno(errcode,
2858 "pthread_cond_wait");
2859 pthread_mutex_unlock(&tog_mutex);
2860 goto done;
2862 if (*a->quit)
2863 done = 1;
2867 a->log_complete = 1;
2868 errcode = pthread_mutex_unlock(&tog_mutex);
2869 if (errcode)
2870 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2871 done:
2872 if (err) {
2873 tog_thread_error = 1;
2874 pthread_cond_signal(&a->commit_loaded);
2876 return (void *)err;
2879 static const struct got_error *
2880 stop_log_thread(struct tog_log_view_state *s)
2882 const struct got_error *err = NULL, *thread_err = NULL;
2883 int errcode;
2885 if (s->thread) {
2886 s->quit = 1;
2887 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2888 if (errcode)
2889 return got_error_set_errno(errcode,
2890 "pthread_cond_signal");
2891 errcode = pthread_mutex_unlock(&tog_mutex);
2892 if (errcode)
2893 return got_error_set_errno(errcode,
2894 "pthread_mutex_unlock");
2895 errcode = pthread_join(s->thread, (void **)&thread_err);
2896 if (errcode)
2897 return got_error_set_errno(errcode, "pthread_join");
2898 errcode = pthread_mutex_lock(&tog_mutex);
2899 if (errcode)
2900 return got_error_set_errno(errcode,
2901 "pthread_mutex_lock");
2902 s->thread = 0; //NULL;
2905 if (s->thread_args.repo) {
2906 err = got_repo_close(s->thread_args.repo);
2907 s->thread_args.repo = NULL;
2910 if (s->thread_args.pack_fds) {
2911 const struct got_error *pack_err =
2912 got_repo_pack_fds_close(s->thread_args.pack_fds);
2913 if (err == NULL)
2914 err = pack_err;
2915 s->thread_args.pack_fds = NULL;
2918 if (s->thread_args.graph) {
2919 got_commit_graph_close(s->thread_args.graph);
2920 s->thread_args.graph = NULL;
2923 return err ? err : thread_err;
2926 static const struct got_error *
2927 close_log_view(struct tog_view *view)
2929 const struct got_error *err = NULL;
2930 struct tog_log_view_state *s = &view->state.log;
2931 int errcode;
2933 err = stop_log_thread(s);
2935 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2936 if (errcode && err == NULL)
2937 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2939 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2940 if (errcode && err == NULL)
2941 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2943 free_commits(&s->limit_commits);
2944 free_commits(&s->real_commits);
2945 free(s->in_repo_path);
2946 s->in_repo_path = NULL;
2947 free(s->start_id);
2948 s->start_id = NULL;
2949 free(s->head_ref_name);
2950 s->head_ref_name = NULL;
2951 return err;
2955 * We use two queues to implement the limit feature: first consists of
2956 * commits matching the current limit_regex; second is the real queue
2957 * of all known commits (real_commits). When the user starts limiting,
2958 * we swap queues such that all movement and displaying functionality
2959 * works with very slight change.
2961 static const struct got_error *
2962 limit_log_view(struct tog_view *view)
2964 struct tog_log_view_state *s = &view->state.log;
2965 struct commit_queue_entry *entry;
2966 struct tog_view *v = view;
2967 const struct got_error *err = NULL;
2968 char pattern[1024];
2969 int ret;
2971 if (view_is_hsplit_top(view))
2972 v = view->child;
2973 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
2974 v = view->parent;
2976 /* Get the pattern */
2977 wmove(v->window, v->nlines - 1, 0);
2978 wclrtoeol(v->window);
2979 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
2980 nodelay(v->window, FALSE);
2981 nocbreak();
2982 echo();
2983 ret = wgetnstr(v->window, pattern, sizeof(pattern));
2984 cbreak();
2985 noecho();
2986 nodelay(v->window, TRUE);
2987 if (ret == ERR)
2988 return NULL;
2990 if (*pattern == '\0') {
2992 * Safety measure for the situation where the user
2993 * resets limit without previously limiting anything.
2995 if (!s->limit_view)
2996 return NULL;
2999 * User could have pressed Ctrl+L, which refreshed the
3000 * commit queues, it means we can't save previously
3001 * (before limit took place) displayed entries,
3002 * because they would point to already free'ed memory,
3003 * so we are forced to always select first entry of
3004 * the queue.
3006 s->commits = &s->real_commits;
3007 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3008 s->selected_entry = s->first_displayed_entry;
3009 s->selected = 0;
3010 s->limit_view = 0;
3012 return NULL;
3015 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3016 return NULL;
3018 s->limit_view = 1;
3020 /* Clear the screen while loading limit view */
3021 s->first_displayed_entry = NULL;
3022 s->last_displayed_entry = NULL;
3023 s->selected_entry = NULL;
3024 s->commits = &s->limit_commits;
3026 /* Prepare limit queue for new search */
3027 free_commits(&s->limit_commits);
3028 s->limit_commits.ncommits = 0;
3030 /* First process commits, which are in queue already */
3031 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3032 int have_match = 0;
3034 err = match_commit(&have_match, entry->id,
3035 entry->commit, &s->limit_regex);
3036 if (err)
3037 return err;
3039 if (have_match) {
3040 struct commit_queue_entry *matched;
3042 matched = alloc_commit_queue_entry(entry->commit,
3043 entry->id);
3044 if (matched == NULL) {
3045 err = got_error_from_errno(
3046 "alloc_commit_queue_entry");
3047 break;
3050 err = got_object_commit_dup(&matched->commit,
3051 entry->commit);
3052 if (err) {
3053 free(matched);
3054 return err;
3057 matched->idx = s->limit_commits.ncommits;
3058 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3059 matched, entry);
3060 s->limit_commits.ncommits++;
3064 /* Second process all the commits, until we fill the screen */
3065 if (s->limit_commits.ncommits < view->nlines - 1 &&
3066 !s->thread_args.log_complete) {
3067 s->thread_args.commits_needed +=
3068 view->nlines - s->limit_commits.ncommits - 1;
3069 err = trigger_log_thread(view, 1);
3070 if (err)
3071 return err;
3074 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3075 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3076 s->selected = 0;
3078 return NULL;
3081 static const struct got_error *
3082 search_start_log_view(struct tog_view *view)
3084 struct tog_log_view_state *s = &view->state.log;
3086 s->matched_entry = NULL;
3087 s->search_entry = NULL;
3088 return NULL;
3091 static const struct got_error *
3092 search_next_log_view(struct tog_view *view)
3094 const struct got_error *err = NULL;
3095 struct tog_log_view_state *s = &view->state.log;
3096 struct commit_queue_entry *entry;
3098 /* Display progress update in log view. */
3099 show_log_view(view);
3100 update_panels();
3101 doupdate();
3103 if (s->search_entry) {
3104 int errcode, ch;
3105 errcode = pthread_mutex_unlock(&tog_mutex);
3106 if (errcode)
3107 return got_error_set_errno(errcode,
3108 "pthread_mutex_unlock");
3109 ch = wgetch(view->window);
3110 errcode = pthread_mutex_lock(&tog_mutex);
3111 if (errcode)
3112 return got_error_set_errno(errcode,
3113 "pthread_mutex_lock");
3114 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3115 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3116 return NULL;
3118 if (view->searching == TOG_SEARCH_FORWARD)
3119 entry = TAILQ_NEXT(s->search_entry, entry);
3120 else
3121 entry = TAILQ_PREV(s->search_entry,
3122 commit_queue_head, entry);
3123 } else if (s->matched_entry) {
3124 int matched_idx = s->matched_entry->idx;
3125 int selected_idx = s->selected_entry->idx;
3128 * If the user has moved the cursor after we hit a match,
3129 * the position from where we should continue searching
3130 * might have changed.
3132 if (view->searching == TOG_SEARCH_FORWARD) {
3133 if (matched_idx > selected_idx)
3134 entry = TAILQ_NEXT(s->selected_entry, entry);
3135 else
3136 entry = TAILQ_NEXT(s->matched_entry, entry);
3137 } else {
3138 if (matched_idx < selected_idx)
3139 entry = TAILQ_PREV(s->selected_entry,
3140 commit_queue_head, entry);
3141 else
3142 entry = TAILQ_PREV(s->matched_entry,
3143 commit_queue_head, entry);
3145 } else {
3146 entry = s->selected_entry;
3149 while (1) {
3150 int have_match = 0;
3152 if (entry == NULL) {
3153 if (s->thread_args.log_complete ||
3154 view->searching == TOG_SEARCH_BACKWARD) {
3155 view->search_next_done =
3156 (s->matched_entry == NULL ?
3157 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3158 s->search_entry = NULL;
3159 return NULL;
3162 * Poke the log thread for more commits and return,
3163 * allowing the main loop to make progress. Search
3164 * will resume at s->search_entry once we come back.
3166 s->thread_args.commits_needed++;
3167 return trigger_log_thread(view, 0);
3170 err = match_commit(&have_match, entry->id, entry->commit,
3171 &view->regex);
3172 if (err)
3173 break;
3174 if (have_match) {
3175 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3176 s->matched_entry = entry;
3177 break;
3180 s->search_entry = entry;
3181 if (view->searching == TOG_SEARCH_FORWARD)
3182 entry = TAILQ_NEXT(entry, entry);
3183 else
3184 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3187 if (s->matched_entry) {
3188 int cur = s->selected_entry->idx;
3189 while (cur < s->matched_entry->idx) {
3190 err = input_log_view(NULL, view, KEY_DOWN);
3191 if (err)
3192 return err;
3193 cur++;
3195 while (cur > s->matched_entry->idx) {
3196 err = input_log_view(NULL, view, KEY_UP);
3197 if (err)
3198 return err;
3199 cur--;
3203 s->search_entry = NULL;
3205 return NULL;
3208 static const struct got_error *
3209 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3210 struct got_repository *repo, const char *head_ref_name,
3211 const char *in_repo_path, int log_branches)
3213 const struct got_error *err = NULL;
3214 struct tog_log_view_state *s = &view->state.log;
3215 struct got_repository *thread_repo = NULL;
3216 struct got_commit_graph *thread_graph = NULL;
3217 int errcode;
3219 if (in_repo_path != s->in_repo_path) {
3220 free(s->in_repo_path);
3221 s->in_repo_path = strdup(in_repo_path);
3222 if (s->in_repo_path == NULL)
3223 return got_error_from_errno("strdup");
3226 /* The commit queue only contains commits being displayed. */
3227 TAILQ_INIT(&s->real_commits.head);
3228 s->real_commits.ncommits = 0;
3229 s->commits = &s->real_commits;
3231 TAILQ_INIT(&s->limit_commits.head);
3232 s->limit_view = 0;
3233 s->limit_commits.ncommits = 0;
3235 s->repo = repo;
3236 if (head_ref_name) {
3237 s->head_ref_name = strdup(head_ref_name);
3238 if (s->head_ref_name == NULL) {
3239 err = got_error_from_errno("strdup");
3240 goto done;
3243 s->start_id = got_object_id_dup(start_id);
3244 if (s->start_id == NULL) {
3245 err = got_error_from_errno("got_object_id_dup");
3246 goto done;
3248 s->log_branches = log_branches;
3250 STAILQ_INIT(&s->colors);
3251 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3252 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3253 get_color_value("TOG_COLOR_COMMIT"));
3254 if (err)
3255 goto done;
3256 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3257 get_color_value("TOG_COLOR_AUTHOR"));
3258 if (err) {
3259 free_colors(&s->colors);
3260 goto done;
3262 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3263 get_color_value("TOG_COLOR_DATE"));
3264 if (err) {
3265 free_colors(&s->colors);
3266 goto done;
3270 view->show = show_log_view;
3271 view->input = input_log_view;
3272 view->resize = resize_log_view;
3273 view->close = close_log_view;
3274 view->search_start = search_start_log_view;
3275 view->search_next = search_next_log_view;
3277 if (s->thread_args.pack_fds == NULL) {
3278 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3279 if (err)
3280 goto done;
3282 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3283 s->thread_args.pack_fds);
3284 if (err)
3285 goto done;
3286 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3287 !s->log_branches);
3288 if (err)
3289 goto done;
3290 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3291 s->repo, NULL, NULL);
3292 if (err)
3293 goto done;
3295 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3296 if (errcode) {
3297 err = got_error_set_errno(errcode, "pthread_cond_init");
3298 goto done;
3300 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3301 if (errcode) {
3302 err = got_error_set_errno(errcode, "pthread_cond_init");
3303 goto done;
3306 s->thread_args.commits_needed = view->nlines;
3307 s->thread_args.graph = thread_graph;
3308 s->thread_args.real_commits = &s->real_commits;
3309 s->thread_args.limit_commits = &s->limit_commits;
3310 s->thread_args.in_repo_path = s->in_repo_path;
3311 s->thread_args.start_id = s->start_id;
3312 s->thread_args.repo = thread_repo;
3313 s->thread_args.log_complete = 0;
3314 s->thread_args.quit = &s->quit;
3315 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3316 s->thread_args.selected_entry = &s->selected_entry;
3317 s->thread_args.searching = &view->searching;
3318 s->thread_args.search_next_done = &view->search_next_done;
3319 s->thread_args.regex = &view->regex;
3320 s->thread_args.limiting = &s->limit_view;
3321 s->thread_args.limit_regex = &s->limit_regex;
3322 s->thread_args.limit_commits = &s->limit_commits;
3323 done:
3324 if (err)
3325 close_log_view(view);
3326 return err;
3329 static const struct got_error *
3330 show_log_view(struct tog_view *view)
3332 const struct got_error *err;
3333 struct tog_log_view_state *s = &view->state.log;
3335 if (s->thread == 0) { //NULL) {
3336 int errcode = pthread_create(&s->thread, NULL, log_thread,
3337 &s->thread_args);
3338 if (errcode)
3339 return got_error_set_errno(errcode, "pthread_create");
3340 if (s->thread_args.commits_needed > 0) {
3341 err = trigger_log_thread(view, 1);
3342 if (err)
3343 return err;
3347 return draw_commits(view);
3350 static void
3351 log_move_cursor_up(struct tog_view *view, int page, int home)
3353 struct tog_log_view_state *s = &view->state.log;
3355 if (s->first_displayed_entry == NULL)
3356 return;
3357 if (s->selected_entry->idx == 0)
3358 view->count = 0;
3360 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3361 || home)
3362 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3364 if (!page && !home && s->selected > 0)
3365 --s->selected;
3366 else
3367 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3369 select_commit(s);
3370 return;
3373 static const struct got_error *
3374 log_move_cursor_down(struct tog_view *view, int page)
3376 struct tog_log_view_state *s = &view->state.log;
3377 const struct got_error *err = NULL;
3378 int eos = view->nlines - 2;
3380 if (s->first_displayed_entry == NULL)
3381 return NULL;
3383 if (s->thread_args.log_complete &&
3384 s->selected_entry->idx >= s->commits->ncommits - 1)
3385 return NULL;
3387 if (view_is_hsplit_top(view))
3388 --eos; /* border consumes the last line */
3390 if (!page) {
3391 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3392 ++s->selected;
3393 else
3394 err = log_scroll_down(view, 1);
3395 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3396 struct commit_queue_entry *entry;
3397 int n;
3399 s->selected = 0;
3400 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3401 s->last_displayed_entry = entry;
3402 for (n = 0; n <= eos; n++) {
3403 if (entry == NULL)
3404 break;
3405 s->first_displayed_entry = entry;
3406 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3408 if (n > 0)
3409 s->selected = n - 1;
3410 } else {
3411 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3412 s->thread_args.log_complete)
3413 s->selected += MIN(page,
3414 s->commits->ncommits - s->selected_entry->idx - 1);
3415 else
3416 err = log_scroll_down(view, page);
3418 if (err)
3419 return err;
3422 * We might necessarily overshoot in horizontal
3423 * splits; if so, select the last displayed commit.
3425 if (s->first_displayed_entry && s->last_displayed_entry) {
3426 s->selected = MIN(s->selected,
3427 s->last_displayed_entry->idx -
3428 s->first_displayed_entry->idx);
3431 select_commit(s);
3433 if (s->thread_args.log_complete &&
3434 s->selected_entry->idx == s->commits->ncommits - 1)
3435 view->count = 0;
3437 return NULL;
3440 static void
3441 view_get_split(struct tog_view *view, int *y, int *x)
3443 *x = 0;
3444 *y = 0;
3446 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3447 if (view->child && view->child->resized_y)
3448 *y = view->child->resized_y;
3449 else if (view->resized_y)
3450 *y = view->resized_y;
3451 else
3452 *y = view_split_begin_y(view->lines);
3453 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3454 if (view->child && view->child->resized_x)
3455 *x = view->child->resized_x;
3456 else if (view->resized_x)
3457 *x = view->resized_x;
3458 else
3459 *x = view_split_begin_x(view->begin_x);
3463 /* Split view horizontally at y and offset view->state->selected line. */
3464 static const struct got_error *
3465 view_init_hsplit(struct tog_view *view, int y)
3467 const struct got_error *err = NULL;
3469 view->nlines = y;
3470 view->ncols = COLS;
3471 err = view_resize(view);
3472 if (err)
3473 return err;
3475 err = offset_selection_down(view);
3477 return err;
3480 static const struct got_error *
3481 log_goto_line(struct tog_view *view, int nlines)
3483 const struct got_error *err = NULL;
3484 struct tog_log_view_state *s = &view->state.log;
3485 int g, idx = s->selected_entry->idx;
3487 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3488 return NULL;
3490 g = view->gline;
3491 view->gline = 0;
3493 if (g >= s->first_displayed_entry->idx + 1 &&
3494 g <= s->last_displayed_entry->idx + 1 &&
3495 g - s->first_displayed_entry->idx - 1 < nlines) {
3496 s->selected = g - s->first_displayed_entry->idx - 1;
3497 select_commit(s);
3498 return NULL;
3501 if (idx + 1 < g) {
3502 err = log_move_cursor_down(view, g - idx - 1);
3503 if (!err && g > s->selected_entry->idx + 1)
3504 err = log_move_cursor_down(view,
3505 g - s->first_displayed_entry->idx - 1);
3506 if (err)
3507 return err;
3508 } else if (idx + 1 > g)
3509 log_move_cursor_up(view, idx - g + 1, 0);
3511 if (g < nlines && s->first_displayed_entry->idx == 0)
3512 s->selected = g - 1;
3514 select_commit(s);
3515 return NULL;
3519 static const struct got_error *
3520 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3522 const struct got_error *err = NULL;
3523 struct tog_log_view_state *s = &view->state.log;
3524 int eos, nscroll;
3526 if (s->thread_args.load_all) {
3527 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3528 s->thread_args.load_all = 0;
3529 else if (s->thread_args.log_complete) {
3530 err = log_move_cursor_down(view, s->commits->ncommits);
3531 s->thread_args.load_all = 0;
3533 if (err)
3534 return err;
3537 eos = nscroll = view->nlines - 1;
3538 if (view_is_hsplit_top(view))
3539 --eos; /* border */
3541 if (view->gline)
3542 return log_goto_line(view, eos);
3544 switch (ch) {
3545 case '&':
3546 err = limit_log_view(view);
3547 break;
3548 case 'q':
3549 s->quit = 1;
3550 break;
3551 case '0':
3552 view->x = 0;
3553 break;
3554 case '$':
3555 view->x = MAX(view->maxx - view->ncols / 2, 0);
3556 view->count = 0;
3557 break;
3558 case KEY_RIGHT:
3559 case 'l':
3560 if (view->x + view->ncols / 2 < view->maxx)
3561 view->x += 2; /* move two columns right */
3562 else
3563 view->count = 0;
3564 break;
3565 case KEY_LEFT:
3566 case 'h':
3567 view->x -= MIN(view->x, 2); /* move two columns back */
3568 if (view->x <= 0)
3569 view->count = 0;
3570 break;
3571 case 'k':
3572 case KEY_UP:
3573 case '<':
3574 case ',':
3575 case CTRL('p'):
3576 log_move_cursor_up(view, 0, 0);
3577 break;
3578 case 'g':
3579 case KEY_HOME:
3580 log_move_cursor_up(view, 0, 1);
3581 view->count = 0;
3582 break;
3583 case CTRL('u'):
3584 case 'u':
3585 nscroll /= 2;
3586 /* FALL THROUGH */
3587 case KEY_PPAGE:
3588 case CTRL('b'):
3589 case 'b':
3590 log_move_cursor_up(view, nscroll, 0);
3591 break;
3592 case 'j':
3593 case KEY_DOWN:
3594 case '>':
3595 case '.':
3596 case CTRL('n'):
3597 err = log_move_cursor_down(view, 0);
3598 break;
3599 case '@':
3600 s->use_committer = !s->use_committer;
3601 break;
3602 case 'G':
3603 case KEY_END: {
3604 /* We don't know yet how many commits, so we're forced to
3605 * traverse them all. */
3606 view->count = 0;
3607 s->thread_args.load_all = 1;
3608 if (!s->thread_args.log_complete)
3609 return trigger_log_thread(view, 0);
3610 err = log_move_cursor_down(view, s->commits->ncommits);
3611 s->thread_args.load_all = 0;
3612 break;
3614 case CTRL('d'):
3615 case 'd':
3616 nscroll /= 2;
3617 /* FALL THROUGH */
3618 case KEY_NPAGE:
3619 case CTRL('f'):
3620 case 'f':
3621 case ' ':
3622 err = log_move_cursor_down(view, nscroll);
3623 break;
3624 case KEY_RESIZE:
3625 if (s->selected > view->nlines - 2)
3626 s->selected = view->nlines - 2;
3627 if (s->selected > s->commits->ncommits - 1)
3628 s->selected = s->commits->ncommits - 1;
3629 select_commit(s);
3630 if (s->commits->ncommits < view->nlines - 1 &&
3631 !s->thread_args.log_complete) {
3632 s->thread_args.commits_needed += (view->nlines - 1) -
3633 s->commits->ncommits;
3634 err = trigger_log_thread(view, 1);
3636 break;
3637 case KEY_ENTER:
3638 case '\r':
3639 view->count = 0;
3640 if (s->selected_entry == NULL)
3641 break;
3642 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3643 break;
3644 case 'T':
3645 view->count = 0;
3646 if (s->selected_entry == NULL)
3647 break;
3648 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3649 break;
3650 case KEY_BACKSPACE:
3651 case CTRL('l'):
3652 case 'B':
3653 view->count = 0;
3654 if (ch == KEY_BACKSPACE &&
3655 got_path_is_root_dir(s->in_repo_path))
3656 break;
3657 err = stop_log_thread(s);
3658 if (err)
3659 return err;
3660 if (ch == KEY_BACKSPACE) {
3661 char *parent_path;
3662 err = got_path_dirname(&parent_path, s->in_repo_path);
3663 if (err)
3664 return err;
3665 free(s->in_repo_path);
3666 s->in_repo_path = parent_path;
3667 s->thread_args.in_repo_path = s->in_repo_path;
3668 } else if (ch == CTRL('l')) {
3669 struct got_object_id *start_id;
3670 err = got_repo_match_object_id(&start_id, NULL,
3671 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3672 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3673 if (err)
3674 return err;
3675 free(s->start_id);
3676 s->start_id = start_id;
3677 s->thread_args.start_id = s->start_id;
3678 } else /* 'B' */
3679 s->log_branches = !s->log_branches;
3681 if (s->thread_args.pack_fds == NULL) {
3682 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3683 if (err)
3684 return err;
3686 err = got_repo_open(&s->thread_args.repo,
3687 got_repo_get_path(s->repo), NULL,
3688 s->thread_args.pack_fds);
3689 if (err)
3690 return err;
3691 tog_free_refs();
3692 err = tog_load_refs(s->repo, 0);
3693 if (err)
3694 return err;
3695 err = got_commit_graph_open(&s->thread_args.graph,
3696 s->in_repo_path, !s->log_branches);
3697 if (err)
3698 return err;
3699 err = got_commit_graph_iter_start(s->thread_args.graph,
3700 s->start_id, s->repo, NULL, NULL);
3701 if (err)
3702 return err;
3703 free_commits(&s->real_commits);
3704 free_commits(&s->limit_commits);
3705 s->first_displayed_entry = NULL;
3706 s->last_displayed_entry = NULL;
3707 s->selected_entry = NULL;
3708 s->selected = 0;
3709 s->thread_args.log_complete = 0;
3710 s->quit = 0;
3711 s->thread_args.commits_needed = view->lines;
3712 s->matched_entry = NULL;
3713 s->search_entry = NULL;
3714 view->offset = 0;
3715 break;
3716 case 'R':
3717 view->count = 0;
3718 err = view_request_new(new_view, view, TOG_VIEW_REF);
3719 break;
3720 default:
3721 view->count = 0;
3722 break;
3725 return err;
3728 static const struct got_error *
3729 apply_unveil(const char *repo_path, const char *worktree_path)
3731 const struct got_error *error;
3733 #ifdef PROFILE
3734 if (unveil("gmon.out", "rwc") != 0)
3735 return got_error_from_errno2("unveil", "gmon.out");
3736 #endif
3737 if (repo_path && unveil(repo_path, "r") != 0)
3738 return got_error_from_errno2("unveil", repo_path);
3740 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3741 return got_error_from_errno2("unveil", worktree_path);
3743 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3744 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3746 error = got_privsep_unveil_exec_helpers();
3747 if (error != NULL)
3748 return error;
3750 if (unveil(NULL, NULL) != 0)
3751 return got_error_from_errno("unveil");
3753 return NULL;
3756 static void
3757 init_curses(void)
3760 * Override default signal handlers before starting ncurses.
3761 * This should prevent ncurses from installing its own
3762 * broken cleanup() signal handler.
3764 signal(SIGWINCH, tog_sigwinch);
3765 signal(SIGPIPE, tog_sigpipe);
3766 signal(SIGCONT, tog_sigcont);
3767 signal(SIGINT, tog_sigint);
3768 signal(SIGTERM, tog_sigterm);
3770 initscr();
3771 cbreak();
3772 halfdelay(1); /* Do fast refresh while initial view is loading. */
3773 noecho();
3774 nonl();
3775 intrflush(stdscr, FALSE);
3776 keypad(stdscr, TRUE);
3777 curs_set(0);
3778 if (getenv("TOG_COLORS") != NULL) {
3779 start_color();
3780 use_default_colors();
3784 static const struct got_error *
3785 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3786 struct got_repository *repo, struct got_worktree *worktree)
3788 const struct got_error *err = NULL;
3790 if (argc == 0) {
3791 *in_repo_path = strdup("/");
3792 if (*in_repo_path == NULL)
3793 return got_error_from_errno("strdup");
3794 return NULL;
3797 if (worktree) {
3798 const char *prefix = got_worktree_get_path_prefix(worktree);
3799 char *p;
3801 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3802 if (err)
3803 return err;
3804 if (asprintf(in_repo_path, "%s%s%s", prefix,
3805 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3806 p) == -1) {
3807 err = got_error_from_errno("asprintf");
3808 *in_repo_path = NULL;
3810 free(p);
3811 } else
3812 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3814 return err;
3817 static const struct got_error *
3818 cmd_log(int argc, char *argv[])
3820 const struct got_error *error;
3821 struct got_repository *repo = NULL;
3822 struct got_worktree *worktree = NULL;
3823 struct got_object_id *start_id = NULL;
3824 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3825 char *start_commit = NULL, *label = NULL;
3826 struct got_reference *ref = NULL;
3827 const char *head_ref_name = NULL;
3828 int ch, log_branches = 0;
3829 struct tog_view *view;
3830 int *pack_fds = NULL;
3832 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3833 switch (ch) {
3834 case 'b':
3835 log_branches = 1;
3836 break;
3837 case 'c':
3838 start_commit = optarg;
3839 break;
3840 case 'r':
3841 repo_path = realpath(optarg, NULL);
3842 if (repo_path == NULL)
3843 return got_error_from_errno2("realpath",
3844 optarg);
3845 break;
3846 default:
3847 usage_log();
3848 /* NOTREACHED */
3852 argc -= optind;
3853 argv += optind;
3855 if (argc > 1)
3856 usage_log();
3858 error = got_repo_pack_fds_open(&pack_fds);
3859 if (error != NULL)
3860 goto done;
3862 if (repo_path == NULL) {
3863 cwd = getcwd(NULL, 0);
3864 if (cwd == NULL)
3865 return got_error_from_errno("getcwd");
3866 error = got_worktree_open(&worktree, cwd);
3867 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3868 goto done;
3869 if (worktree)
3870 repo_path =
3871 strdup(got_worktree_get_repo_path(worktree));
3872 else
3873 repo_path = strdup(cwd);
3874 if (repo_path == NULL) {
3875 error = got_error_from_errno("strdup");
3876 goto done;
3880 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3881 if (error != NULL)
3882 goto done;
3884 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3885 repo, worktree);
3886 if (error)
3887 goto done;
3889 init_curses();
3891 error = apply_unveil(got_repo_get_path(repo),
3892 worktree ? got_worktree_get_root_path(worktree) : NULL);
3893 if (error)
3894 goto done;
3896 /* already loaded by tog_log_with_path()? */
3897 if (TAILQ_EMPTY(&tog_refs)) {
3898 error = tog_load_refs(repo, 0);
3899 if (error)
3900 goto done;
3903 if (start_commit == NULL) {
3904 error = got_repo_match_object_id(&start_id, &label,
3905 worktree ? got_worktree_get_head_ref_name(worktree) :
3906 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3907 if (error)
3908 goto done;
3909 head_ref_name = label;
3910 } else {
3911 error = got_ref_open(&ref, repo, start_commit, 0);
3912 if (error == NULL)
3913 head_ref_name = got_ref_get_name(ref);
3914 else if (error->code != GOT_ERR_NOT_REF)
3915 goto done;
3916 error = got_repo_match_object_id(&start_id, NULL,
3917 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3918 if (error)
3919 goto done;
3922 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3923 if (view == NULL) {
3924 error = got_error_from_errno("view_open");
3925 goto done;
3927 error = open_log_view(view, start_id, repo, head_ref_name,
3928 in_repo_path, log_branches);
3929 if (error)
3930 goto done;
3931 if (worktree) {
3932 /* Release work tree lock. */
3933 got_worktree_close(worktree);
3934 worktree = NULL;
3936 error = view_loop(view);
3937 done:
3938 free(in_repo_path);
3939 free(repo_path);
3940 free(cwd);
3941 free(start_id);
3942 free(label);
3943 if (ref)
3944 got_ref_close(ref);
3945 if (repo) {
3946 const struct got_error *close_err = got_repo_close(repo);
3947 if (error == NULL)
3948 error = close_err;
3950 if (worktree)
3951 got_worktree_close(worktree);
3952 if (pack_fds) {
3953 const struct got_error *pack_err =
3954 got_repo_pack_fds_close(pack_fds);
3955 if (error == NULL)
3956 error = pack_err;
3958 tog_free_refs();
3959 return error;
3962 __dead static void
3963 usage_diff(void)
3965 endwin();
3966 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
3967 "object1 object2\n", getprogname());
3968 exit(1);
3971 static int
3972 match_line(const char *line, regex_t *regex, size_t nmatch,
3973 regmatch_t *regmatch)
3975 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3978 static struct tog_color *
3979 match_color(struct tog_colors *colors, const char *line)
3981 struct tog_color *tc = NULL;
3983 STAILQ_FOREACH(tc, colors, entry) {
3984 if (match_line(line, &tc->regex, 0, NULL))
3985 return tc;
3988 return NULL;
3991 static const struct got_error *
3992 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3993 WINDOW *window, int skipcol, regmatch_t *regmatch)
3995 const struct got_error *err = NULL;
3996 char *exstr = NULL;
3997 wchar_t *wline = NULL;
3998 int rme, rms, n, width, scrollx;
3999 int width0 = 0, width1 = 0, width2 = 0;
4000 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4002 *wtotal = 0;
4004 rms = regmatch->rm_so;
4005 rme = regmatch->rm_eo;
4007 err = expand_tab(&exstr, line);
4008 if (err)
4009 return err;
4011 /* Split the line into 3 segments, according to match offsets. */
4012 seg0 = strndup(exstr, rms);
4013 if (seg0 == NULL) {
4014 err = got_error_from_errno("strndup");
4015 goto done;
4017 seg1 = strndup(exstr + rms, rme - rms);
4018 if (seg1 == NULL) {
4019 err = got_error_from_errno("strndup");
4020 goto done;
4022 seg2 = strdup(exstr + rme);
4023 if (seg2 == NULL) {
4024 err = got_error_from_errno("strndup");
4025 goto done;
4028 /* draw up to matched token if we haven't scrolled past it */
4029 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4030 col_tab_align, 1);
4031 if (err)
4032 goto done;
4033 n = MAX(width0 - skipcol, 0);
4034 if (n) {
4035 free(wline);
4036 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4037 wlimit, col_tab_align, 1);
4038 if (err)
4039 goto done;
4040 waddwstr(window, &wline[scrollx]);
4041 wlimit -= width;
4042 *wtotal += width;
4045 if (wlimit > 0) {
4046 int i = 0, w = 0;
4047 size_t wlen;
4049 free(wline);
4050 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4051 col_tab_align, 1);
4052 if (err)
4053 goto done;
4054 wlen = wcslen(wline);
4055 while (i < wlen) {
4056 width = wcwidth(wline[i]);
4057 if (width == -1) {
4058 /* should not happen, tabs are expanded */
4059 err = got_error(GOT_ERR_RANGE);
4060 goto done;
4062 if (width0 + w + width > skipcol)
4063 break;
4064 w += width;
4065 i++;
4067 /* draw (visible part of) matched token (if scrolled into it) */
4068 if (width1 - w > 0) {
4069 wattron(window, A_STANDOUT);
4070 waddwstr(window, &wline[i]);
4071 wattroff(window, A_STANDOUT);
4072 wlimit -= (width1 - w);
4073 *wtotal += (width1 - w);
4077 if (wlimit > 0) { /* draw rest of line */
4078 free(wline);
4079 if (skipcol > width0 + width1) {
4080 err = format_line(&wline, &width2, &scrollx, seg2,
4081 skipcol - (width0 + width1), wlimit,
4082 col_tab_align, 1);
4083 if (err)
4084 goto done;
4085 waddwstr(window, &wline[scrollx]);
4086 } else {
4087 err = format_line(&wline, &width2, NULL, seg2, 0,
4088 wlimit, col_tab_align, 1);
4089 if (err)
4090 goto done;
4091 waddwstr(window, wline);
4093 *wtotal += width2;
4095 done:
4096 free(wline);
4097 free(exstr);
4098 free(seg0);
4099 free(seg1);
4100 free(seg2);
4101 return err;
4104 static int
4105 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4107 FILE *f = NULL;
4108 int *eof, *first, *selected;
4110 if (view->type == TOG_VIEW_DIFF) {
4111 struct tog_diff_view_state *s = &view->state.diff;
4113 first = &s->first_displayed_line;
4114 selected = first;
4115 eof = &s->eof;
4116 f = s->f;
4117 } else if (view->type == TOG_VIEW_BLAME) {
4118 struct tog_blame_view_state *s = &view->state.blame;
4120 first = &s->first_displayed_line;
4121 selected = &s->selected_line;
4122 eof = &s->eof;
4123 f = s->blame.f;
4124 } else
4125 return 0;
4127 /* Center gline in the middle of the page like vi(1). */
4128 if (*lineno < view->gline - (view->nlines - 3) / 2)
4129 return 0;
4130 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4131 rewind(f);
4132 *eof = 0;
4133 *first = 1;
4134 *lineno = 0;
4135 *nprinted = 0;
4136 return 0;
4139 *selected = view->gline <= (view->nlines - 3) / 2 ?
4140 view->gline : (view->nlines - 3) / 2 + 1;
4141 view->gline = 0;
4143 return 1;
4146 static const struct got_error *
4147 draw_file(struct tog_view *view, const char *header)
4149 struct tog_diff_view_state *s = &view->state.diff;
4150 regmatch_t *regmatch = &view->regmatch;
4151 const struct got_error *err;
4152 int nprinted = 0;
4153 char *line;
4154 size_t linesize = 0;
4155 ssize_t linelen;
4156 wchar_t *wline;
4157 int width;
4158 int max_lines = view->nlines;
4159 int nlines = s->nlines;
4160 off_t line_offset;
4162 s->lineno = s->first_displayed_line - 1;
4163 line_offset = s->lines[s->first_displayed_line - 1].offset;
4164 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4165 return got_error_from_errno("fseek");
4167 werase(view->window);
4169 if (view->gline > s->nlines - 1)
4170 view->gline = s->nlines - 1;
4172 if (header) {
4173 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4174 1 : view->gline - (view->nlines - 3) / 2 :
4175 s->lineno + s->selected_line;
4177 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4178 return got_error_from_errno("asprintf");
4179 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4180 0, 0);
4181 free(line);
4182 if (err)
4183 return err;
4185 if (view_needs_focus_indication(view))
4186 wstandout(view->window);
4187 waddwstr(view->window, wline);
4188 free(wline);
4189 wline = NULL;
4190 while (width++ < view->ncols)
4191 waddch(view->window, ' ');
4192 if (view_needs_focus_indication(view))
4193 wstandend(view->window);
4195 if (max_lines <= 1)
4196 return NULL;
4197 max_lines--;
4200 s->eof = 0;
4201 view->maxx = 0;
4202 line = NULL;
4203 while (max_lines > 0 && nprinted < max_lines) {
4204 enum got_diff_line_type linetype;
4205 attr_t attr = 0;
4207 linelen = getline(&line, &linesize, s->f);
4208 if (linelen == -1) {
4209 if (feof(s->f)) {
4210 s->eof = 1;
4211 break;
4213 free(line);
4214 return got_ferror(s->f, GOT_ERR_IO);
4217 if (++s->lineno < s->first_displayed_line)
4218 continue;
4219 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4220 continue;
4221 if (s->lineno == view->hiline)
4222 attr = A_STANDOUT;
4224 /* Set view->maxx based on full line length. */
4225 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4226 view->x ? 1 : 0);
4227 if (err) {
4228 free(line);
4229 return err;
4231 view->maxx = MAX(view->maxx, width);
4232 free(wline);
4233 wline = NULL;
4235 linetype = s->lines[s->lineno].type;
4236 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4237 linetype < GOT_DIFF_LINE_CONTEXT)
4238 attr |= COLOR_PAIR(linetype);
4239 if (attr)
4240 wattron(view->window, attr);
4241 if (s->first_displayed_line + nprinted == s->matched_line &&
4242 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4243 err = add_matched_line(&width, line, view->ncols, 0,
4244 view->window, view->x, regmatch);
4245 if (err) {
4246 free(line);
4247 return err;
4249 } else {
4250 int skip;
4251 err = format_line(&wline, &width, &skip, line,
4252 view->x, view->ncols, 0, view->x ? 1 : 0);
4253 if (err) {
4254 free(line);
4255 return err;
4257 waddwstr(view->window, &wline[skip]);
4258 free(wline);
4259 wline = NULL;
4261 if (s->lineno == view->hiline) {
4262 /* highlight full gline length */
4263 while (width++ < view->ncols)
4264 waddch(view->window, ' ');
4265 } else {
4266 if (width <= view->ncols - 1)
4267 waddch(view->window, '\n');
4269 if (attr)
4270 wattroff(view->window, attr);
4271 if (++nprinted == 1)
4272 s->first_displayed_line = s->lineno;
4274 free(line);
4275 if (nprinted >= 1)
4276 s->last_displayed_line = s->first_displayed_line +
4277 (nprinted - 1);
4278 else
4279 s->last_displayed_line = s->first_displayed_line;
4281 view_border(view);
4283 if (s->eof) {
4284 while (nprinted < view->nlines) {
4285 waddch(view->window, '\n');
4286 nprinted++;
4289 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4290 view->ncols, 0, 0);
4291 if (err) {
4292 return err;
4295 wstandout(view->window);
4296 waddwstr(view->window, wline);
4297 free(wline);
4298 wline = NULL;
4299 wstandend(view->window);
4302 return NULL;
4305 static char *
4306 get_datestr(time_t *time, char *datebuf)
4308 struct tm mytm, *tm;
4309 char *p, *s;
4311 tm = gmtime_r(time, &mytm);
4312 if (tm == NULL)
4313 return NULL;
4314 s = asctime_r(tm, datebuf);
4315 if (s == NULL)
4316 return NULL;
4317 p = strchr(s, '\n');
4318 if (p)
4319 *p = '\0';
4320 return s;
4323 static const struct got_error *
4324 get_changed_paths(struct got_pathlist_head *paths,
4325 struct got_commit_object *commit, struct got_repository *repo)
4327 const struct got_error *err = NULL;
4328 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4329 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4330 struct got_object_qid *qid;
4332 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4333 if (qid != NULL) {
4334 struct got_commit_object *pcommit;
4335 err = got_object_open_as_commit(&pcommit, repo,
4336 &qid->id);
4337 if (err)
4338 return err;
4340 tree_id1 = got_object_id_dup(
4341 got_object_commit_get_tree_id(pcommit));
4342 if (tree_id1 == NULL) {
4343 got_object_commit_close(pcommit);
4344 return got_error_from_errno("got_object_id_dup");
4346 got_object_commit_close(pcommit);
4350 if (tree_id1) {
4351 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4352 if (err)
4353 goto done;
4356 tree_id2 = got_object_commit_get_tree_id(commit);
4357 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4358 if (err)
4359 goto done;
4361 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4362 got_diff_tree_collect_changed_paths, paths, 0);
4363 done:
4364 if (tree1)
4365 got_object_tree_close(tree1);
4366 if (tree2)
4367 got_object_tree_close(tree2);
4368 free(tree_id1);
4369 return err;
4372 static const struct got_error *
4373 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4374 off_t off, uint8_t type)
4376 struct got_diff_line *p;
4378 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4379 if (p == NULL)
4380 return got_error_from_errno("reallocarray");
4381 *lines = p;
4382 (*lines)[*nlines].offset = off;
4383 (*lines)[*nlines].type = type;
4384 (*nlines)++;
4386 return NULL;
4389 static const struct got_error *
4390 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4391 struct got_object_id *commit_id, struct got_reflist_head *refs,
4392 struct got_repository *repo, FILE *outfile)
4394 const struct got_error *err = NULL;
4395 char datebuf[26], *datestr;
4396 struct got_commit_object *commit;
4397 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4398 time_t committer_time;
4399 const char *author, *committer;
4400 char *refs_str = NULL;
4401 struct got_pathlist_head changed_paths;
4402 struct got_pathlist_entry *pe;
4403 off_t outoff = 0;
4404 int n;
4406 TAILQ_INIT(&changed_paths);
4408 if (refs) {
4409 err = build_refs_str(&refs_str, refs, commit_id, repo);
4410 if (err)
4411 return err;
4414 err = got_object_open_as_commit(&commit, repo, commit_id);
4415 if (err)
4416 return err;
4418 err = got_object_id_str(&id_str, commit_id);
4419 if (err) {
4420 err = got_error_from_errno("got_object_id_str");
4421 goto done;
4424 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4425 if (err)
4426 goto done;
4428 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4429 refs_str ? refs_str : "", refs_str ? ")" : "");
4430 if (n < 0) {
4431 err = got_error_from_errno("fprintf");
4432 goto done;
4434 outoff += n;
4435 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4436 if (err)
4437 goto done;
4439 n = fprintf(outfile, "from: %s\n",
4440 got_object_commit_get_author(commit));
4441 if (n < 0) {
4442 err = got_error_from_errno("fprintf");
4443 goto done;
4445 outoff += n;
4446 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4447 if (err)
4448 goto done;
4450 committer_time = got_object_commit_get_committer_time(commit);
4451 datestr = get_datestr(&committer_time, datebuf);
4452 if (datestr) {
4453 n = fprintf(outfile, "date: %s UTC\n", datestr);
4454 if (n < 0) {
4455 err = got_error_from_errno("fprintf");
4456 goto done;
4458 outoff += n;
4459 err = add_line_metadata(lines, nlines, outoff,
4460 GOT_DIFF_LINE_DATE);
4461 if (err)
4462 goto done;
4464 author = got_object_commit_get_author(commit);
4465 committer = got_object_commit_get_committer(commit);
4466 if (strcmp(author, committer) != 0) {
4467 n = fprintf(outfile, "via: %s\n", committer);
4468 if (n < 0) {
4469 err = got_error_from_errno("fprintf");
4470 goto done;
4472 outoff += n;
4473 err = add_line_metadata(lines, nlines, outoff,
4474 GOT_DIFF_LINE_AUTHOR);
4475 if (err)
4476 goto done;
4478 if (got_object_commit_get_nparents(commit) > 1) {
4479 const struct got_object_id_queue *parent_ids;
4480 struct got_object_qid *qid;
4481 int pn = 1;
4482 parent_ids = got_object_commit_get_parent_ids(commit);
4483 STAILQ_FOREACH(qid, parent_ids, entry) {
4484 err = got_object_id_str(&id_str, &qid->id);
4485 if (err)
4486 goto done;
4487 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4488 if (n < 0) {
4489 err = got_error_from_errno("fprintf");
4490 goto done;
4492 outoff += n;
4493 err = add_line_metadata(lines, nlines, outoff,
4494 GOT_DIFF_LINE_META);
4495 if (err)
4496 goto done;
4497 free(id_str);
4498 id_str = NULL;
4502 err = got_object_commit_get_logmsg(&logmsg, commit);
4503 if (err)
4504 goto done;
4505 s = logmsg;
4506 while ((line = strsep(&s, "\n")) != NULL) {
4507 n = fprintf(outfile, "%s\n", line);
4508 if (n < 0) {
4509 err = got_error_from_errno("fprintf");
4510 goto done;
4512 outoff += n;
4513 err = add_line_metadata(lines, nlines, outoff,
4514 GOT_DIFF_LINE_LOGMSG);
4515 if (err)
4516 goto done;
4519 err = get_changed_paths(&changed_paths, commit, repo);
4520 if (err)
4521 goto done;
4522 TAILQ_FOREACH(pe, &changed_paths, entry) {
4523 struct got_diff_changed_path *cp = pe->data;
4524 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4525 if (n < 0) {
4526 err = got_error_from_errno("fprintf");
4527 goto done;
4529 outoff += n;
4530 err = add_line_metadata(lines, nlines, outoff,
4531 GOT_DIFF_LINE_CHANGES);
4532 if (err)
4533 goto done;
4534 free((char *)pe->path);
4535 free(pe->data);
4538 fputc('\n', outfile);
4539 outoff++;
4540 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4541 done:
4542 got_pathlist_free(&changed_paths);
4543 free(id_str);
4544 free(logmsg);
4545 free(refs_str);
4546 got_object_commit_close(commit);
4547 if (err) {
4548 free(*lines);
4549 *lines = NULL;
4550 *nlines = 0;
4552 return err;
4555 static const struct got_error *
4556 create_diff(struct tog_diff_view_state *s)
4558 const struct got_error *err = NULL;
4559 FILE *f = NULL;
4560 int obj_type;
4562 free(s->lines);
4563 s->lines = malloc(sizeof(*s->lines));
4564 if (s->lines == NULL)
4565 return got_error_from_errno("malloc");
4566 s->nlines = 0;
4568 f = got_opentemp();
4569 if (f == NULL) {
4570 err = got_error_from_errno("got_opentemp");
4571 goto done;
4573 if (s->f && fclose(s->f) == EOF) {
4574 err = got_error_from_errno("fclose");
4575 goto done;
4577 s->f = f;
4579 if (s->id1)
4580 err = got_object_get_type(&obj_type, s->repo, s->id1);
4581 else
4582 err = got_object_get_type(&obj_type, s->repo, s->id2);
4583 if (err)
4584 goto done;
4586 switch (obj_type) {
4587 case GOT_OBJ_TYPE_BLOB:
4588 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4589 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4590 s->label1, s->label2, tog_diff_algo, s->diff_context,
4591 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4592 break;
4593 case GOT_OBJ_TYPE_TREE:
4594 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4595 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4596 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4597 s->force_text_diff, s->repo, s->f);
4598 break;
4599 case GOT_OBJ_TYPE_COMMIT: {
4600 const struct got_object_id_queue *parent_ids;
4601 struct got_object_qid *pid;
4602 struct got_commit_object *commit2;
4603 struct got_reflist_head *refs;
4605 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4606 if (err)
4607 goto done;
4608 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4609 /* Show commit info if we're diffing to a parent/root commit. */
4610 if (s->id1 == NULL) {
4611 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4612 refs, s->repo, s->f);
4613 if (err)
4614 goto done;
4615 } else {
4616 parent_ids = got_object_commit_get_parent_ids(commit2);
4617 STAILQ_FOREACH(pid, parent_ids, entry) {
4618 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4619 err = write_commit_info(&s->lines,
4620 &s->nlines, s->id2, refs, s->repo,
4621 s->f);
4622 if (err)
4623 goto done;
4624 break;
4628 got_object_commit_close(commit2);
4630 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4631 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4632 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4633 s->force_text_diff, s->repo, s->f);
4634 break;
4636 default:
4637 err = got_error(GOT_ERR_OBJ_TYPE);
4638 break;
4640 done:
4641 if (s->f && fflush(s->f) != 0 && err == NULL)
4642 err = got_error_from_errno("fflush");
4643 return err;
4646 static void
4647 diff_view_indicate_progress(struct tog_view *view)
4649 mvwaddstr(view->window, 0, 0, "diffing...");
4650 update_panels();
4651 doupdate();
4654 static const struct got_error *
4655 search_start_diff_view(struct tog_view *view)
4657 struct tog_diff_view_state *s = &view->state.diff;
4659 s->matched_line = 0;
4660 return NULL;
4663 static const struct got_error *
4664 search_next_diff_view(struct tog_view *view)
4666 struct tog_diff_view_state *s = &view->state.diff;
4667 const struct got_error *err = NULL;
4668 int lineno;
4669 char *line = NULL;
4670 size_t linesize = 0;
4671 ssize_t linelen;
4673 if (!view->searching) {
4674 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4675 return NULL;
4678 if (s->matched_line) {
4679 if (view->searching == TOG_SEARCH_FORWARD)
4680 lineno = s->matched_line + 1;
4681 else
4682 lineno = s->matched_line - 1;
4683 } else
4684 lineno = s->first_displayed_line;
4686 while (1) {
4687 off_t offset;
4689 if (lineno <= 0 || lineno > s->nlines) {
4690 if (s->matched_line == 0) {
4691 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4692 break;
4695 if (view->searching == TOG_SEARCH_FORWARD)
4696 lineno = 1;
4697 else
4698 lineno = s->nlines;
4701 offset = s->lines[lineno - 1].offset;
4702 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4703 free(line);
4704 return got_error_from_errno("fseeko");
4706 linelen = getline(&line, &linesize, s->f);
4707 if (linelen != -1) {
4708 char *exstr;
4709 err = expand_tab(&exstr, line);
4710 if (err)
4711 break;
4712 if (match_line(exstr, &view->regex, 1,
4713 &view->regmatch)) {
4714 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4715 s->matched_line = lineno;
4716 free(exstr);
4717 break;
4719 free(exstr);
4721 if (view->searching == TOG_SEARCH_FORWARD)
4722 lineno++;
4723 else
4724 lineno--;
4726 free(line);
4728 if (s->matched_line) {
4729 s->first_displayed_line = s->matched_line;
4730 s->selected_line = 1;
4733 return err;
4736 static const struct got_error *
4737 close_diff_view(struct tog_view *view)
4739 const struct got_error *err = NULL;
4740 struct tog_diff_view_state *s = &view->state.diff;
4742 free(s->id1);
4743 s->id1 = NULL;
4744 free(s->id2);
4745 s->id2 = NULL;
4746 if (s->f && fclose(s->f) == EOF)
4747 err = got_error_from_errno("fclose");
4748 s->f = NULL;
4749 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4750 err = got_error_from_errno("fclose");
4751 s->f1 = NULL;
4752 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4753 err = got_error_from_errno("fclose");
4754 s->f2 = NULL;
4755 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4756 err = got_error_from_errno("close");
4757 s->fd1 = -1;
4758 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4759 err = got_error_from_errno("close");
4760 s->fd2 = -1;
4761 free(s->lines);
4762 s->lines = NULL;
4763 s->nlines = 0;
4764 return err;
4767 static const struct got_error *
4768 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4769 struct got_object_id *id2, const char *label1, const char *label2,
4770 int diff_context, int ignore_whitespace, int force_text_diff,
4771 struct tog_view *parent_view, struct got_repository *repo)
4773 const struct got_error *err;
4774 struct tog_diff_view_state *s = &view->state.diff;
4776 memset(s, 0, sizeof(*s));
4777 s->fd1 = -1;
4778 s->fd2 = -1;
4780 if (id1 != NULL && id2 != NULL) {
4781 int type1, type2;
4782 err = got_object_get_type(&type1, repo, id1);
4783 if (err)
4784 return err;
4785 err = got_object_get_type(&type2, repo, id2);
4786 if (err)
4787 return err;
4789 if (type1 != type2)
4790 return got_error(GOT_ERR_OBJ_TYPE);
4792 s->first_displayed_line = 1;
4793 s->last_displayed_line = view->nlines;
4794 s->selected_line = 1;
4795 s->repo = repo;
4796 s->id1 = id1;
4797 s->id2 = id2;
4798 s->label1 = label1;
4799 s->label2 = label2;
4801 if (id1) {
4802 s->id1 = got_object_id_dup(id1);
4803 if (s->id1 == NULL)
4804 return got_error_from_errno("got_object_id_dup");
4805 } else
4806 s->id1 = NULL;
4808 s->id2 = got_object_id_dup(id2);
4809 if (s->id2 == NULL) {
4810 err = got_error_from_errno("got_object_id_dup");
4811 goto done;
4814 s->f1 = got_opentemp();
4815 if (s->f1 == NULL) {
4816 err = got_error_from_errno("got_opentemp");
4817 goto done;
4820 s->f2 = got_opentemp();
4821 if (s->f2 == NULL) {
4822 err = got_error_from_errno("got_opentemp");
4823 goto done;
4826 s->fd1 = got_opentempfd();
4827 if (s->fd1 == -1) {
4828 err = got_error_from_errno("got_opentempfd");
4829 goto done;
4832 s->fd2 = got_opentempfd();
4833 if (s->fd2 == -1) {
4834 err = got_error_from_errno("got_opentempfd");
4835 goto done;
4838 s->first_displayed_line = 1;
4839 s->last_displayed_line = view->nlines;
4840 s->diff_context = diff_context;
4841 s->ignore_whitespace = ignore_whitespace;
4842 s->force_text_diff = force_text_diff;
4843 s->parent_view = parent_view;
4844 s->repo = repo;
4846 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4847 int rc;
4849 rc = init_pair(GOT_DIFF_LINE_MINUS,
4850 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
4851 if (rc != ERR)
4852 rc = init_pair(GOT_DIFF_LINE_PLUS,
4853 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
4854 if (rc != ERR)
4855 rc = init_pair(GOT_DIFF_LINE_HUNK,
4856 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
4857 if (rc != ERR)
4858 rc = init_pair(GOT_DIFF_LINE_META,
4859 get_color_value("TOG_COLOR_DIFF_META"), -1);
4860 if (rc != ERR)
4861 rc = init_pair(GOT_DIFF_LINE_CHANGES,
4862 get_color_value("TOG_COLOR_DIFF_META"), -1);
4863 if (rc != ERR)
4864 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
4865 get_color_value("TOG_COLOR_DIFF_META"), -1);
4866 if (rc != ERR)
4867 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
4868 get_color_value("TOG_COLOR_DIFF_META"), -1);
4869 if (rc != ERR)
4870 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
4871 get_color_value("TOG_COLOR_AUTHOR"), -1);
4872 if (rc != ERR)
4873 rc = init_pair(GOT_DIFF_LINE_DATE,
4874 get_color_value("TOG_COLOR_DATE"), -1);
4875 if (rc == ERR) {
4876 err = got_error(GOT_ERR_RANGE);
4877 goto done;
4881 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4882 view_is_splitscreen(view))
4883 show_log_view(parent_view); /* draw border */
4884 diff_view_indicate_progress(view);
4886 err = create_diff(s);
4888 view->show = show_diff_view;
4889 view->input = input_diff_view;
4890 view->reset = reset_diff_view;
4891 view->close = close_diff_view;
4892 view->search_start = search_start_diff_view;
4893 view->search_next = search_next_diff_view;
4894 done:
4895 if (err)
4896 close_diff_view(view);
4897 return err;
4900 static const struct got_error *
4901 show_diff_view(struct tog_view *view)
4903 const struct got_error *err;
4904 struct tog_diff_view_state *s = &view->state.diff;
4905 char *id_str1 = NULL, *id_str2, *header;
4906 const char *label1, *label2;
4908 if (s->id1) {
4909 err = got_object_id_str(&id_str1, s->id1);
4910 if (err)
4911 return err;
4912 label1 = s->label1 ? s->label1 : id_str1;
4913 } else
4914 label1 = "/dev/null";
4916 err = got_object_id_str(&id_str2, s->id2);
4917 if (err)
4918 return err;
4919 label2 = s->label2 ? s->label2 : id_str2;
4921 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4922 err = got_error_from_errno("asprintf");
4923 free(id_str1);
4924 free(id_str2);
4925 return err;
4927 free(id_str1);
4928 free(id_str2);
4930 err = draw_file(view, header);
4931 free(header);
4932 return err;
4935 static const struct got_error *
4936 set_selected_commit(struct tog_diff_view_state *s,
4937 struct commit_queue_entry *entry)
4939 const struct got_error *err;
4940 const struct got_object_id_queue *parent_ids;
4941 struct got_commit_object *selected_commit;
4942 struct got_object_qid *pid;
4944 free(s->id2);
4945 s->id2 = got_object_id_dup(entry->id);
4946 if (s->id2 == NULL)
4947 return got_error_from_errno("got_object_id_dup");
4949 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4950 if (err)
4951 return err;
4952 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4953 free(s->id1);
4954 pid = STAILQ_FIRST(parent_ids);
4955 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4956 got_object_commit_close(selected_commit);
4957 return NULL;
4960 static const struct got_error *
4961 reset_diff_view(struct tog_view *view)
4963 struct tog_diff_view_state *s = &view->state.diff;
4965 view->count = 0;
4966 wclear(view->window);
4967 s->first_displayed_line = 1;
4968 s->last_displayed_line = view->nlines;
4969 s->matched_line = 0;
4970 diff_view_indicate_progress(view);
4971 return create_diff(s);
4974 static void
4975 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4977 int start, i;
4979 i = start = s->first_displayed_line - 1;
4981 while (s->lines[i].type != type) {
4982 if (i == 0)
4983 i = s->nlines - 1;
4984 if (--i == start)
4985 return; /* do nothing, requested type not in file */
4988 s->selected_line = 1;
4989 s->first_displayed_line = i;
4992 static void
4993 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4995 int start, i;
4997 i = start = s->first_displayed_line + 1;
4999 while (s->lines[i].type != type) {
5000 if (i == s->nlines - 1)
5001 i = 0;
5002 if (++i == start)
5003 return; /* do nothing, requested type not in file */
5006 s->selected_line = 1;
5007 s->first_displayed_line = i;
5010 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5011 int, int, int);
5012 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5013 int, int);
5015 static const struct got_error *
5016 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5018 const struct got_error *err = NULL;
5019 struct tog_diff_view_state *s = &view->state.diff;
5020 struct tog_log_view_state *ls;
5021 struct commit_queue_entry *old_selected_entry;
5022 char *line = NULL;
5023 size_t linesize = 0;
5024 ssize_t linelen;
5025 int i, nscroll = view->nlines - 1, up = 0;
5027 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5029 switch (ch) {
5030 case '0':
5031 view->x = 0;
5032 break;
5033 case '$':
5034 view->x = MAX(view->maxx - view->ncols / 3, 0);
5035 view->count = 0;
5036 break;
5037 case KEY_RIGHT:
5038 case 'l':
5039 if (view->x + view->ncols / 3 < view->maxx)
5040 view->x += 2; /* move two columns right */
5041 else
5042 view->count = 0;
5043 break;
5044 case KEY_LEFT:
5045 case 'h':
5046 view->x -= MIN(view->x, 2); /* move two columns back */
5047 if (view->x <= 0)
5048 view->count = 0;
5049 break;
5050 case 'a':
5051 case 'w':
5052 if (ch == 'a')
5053 s->force_text_diff = !s->force_text_diff;
5054 if (ch == 'w')
5055 s->ignore_whitespace = !s->ignore_whitespace;
5056 err = reset_diff_view(view);
5057 break;
5058 case 'g':
5059 case KEY_HOME:
5060 s->first_displayed_line = 1;
5061 view->count = 0;
5062 break;
5063 case 'G':
5064 case KEY_END:
5065 view->count = 0;
5066 if (s->eof)
5067 break;
5069 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5070 s->eof = 1;
5071 break;
5072 case 'k':
5073 case KEY_UP:
5074 case CTRL('p'):
5075 if (s->first_displayed_line > 1)
5076 s->first_displayed_line--;
5077 else
5078 view->count = 0;
5079 break;
5080 case CTRL('u'):
5081 case 'u':
5082 nscroll /= 2;
5083 /* FALL THROUGH */
5084 case KEY_PPAGE:
5085 case CTRL('b'):
5086 case 'b':
5087 if (s->first_displayed_line == 1) {
5088 view->count = 0;
5089 break;
5091 i = 0;
5092 while (i++ < nscroll && s->first_displayed_line > 1)
5093 s->first_displayed_line--;
5094 break;
5095 case 'j':
5096 case KEY_DOWN:
5097 case CTRL('n'):
5098 if (!s->eof)
5099 s->first_displayed_line++;
5100 else
5101 view->count = 0;
5102 break;
5103 case CTRL('d'):
5104 case 'd':
5105 nscroll /= 2;
5106 /* FALL THROUGH */
5107 case KEY_NPAGE:
5108 case CTRL('f'):
5109 case 'f':
5110 case ' ':
5111 if (s->eof) {
5112 view->count = 0;
5113 break;
5115 i = 0;
5116 while (!s->eof && i++ < nscroll) {
5117 linelen = getline(&line, &linesize, s->f);
5118 s->first_displayed_line++;
5119 if (linelen == -1) {
5120 if (feof(s->f)) {
5121 s->eof = 1;
5122 } else
5123 err = got_ferror(s->f, GOT_ERR_IO);
5124 break;
5127 free(line);
5128 break;
5129 case '(':
5130 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5131 break;
5132 case ')':
5133 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5134 break;
5135 case '{':
5136 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5137 break;
5138 case '}':
5139 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5140 break;
5141 case '[':
5142 if (s->diff_context > 0) {
5143 s->diff_context--;
5144 s->matched_line = 0;
5145 diff_view_indicate_progress(view);
5146 err = create_diff(s);
5147 if (s->first_displayed_line + view->nlines - 1 >
5148 s->nlines) {
5149 s->first_displayed_line = 1;
5150 s->last_displayed_line = view->nlines;
5152 } else
5153 view->count = 0;
5154 break;
5155 case ']':
5156 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5157 s->diff_context++;
5158 s->matched_line = 0;
5159 diff_view_indicate_progress(view);
5160 err = create_diff(s);
5161 } else
5162 view->count = 0;
5163 break;
5164 case '<':
5165 case ',':
5166 case 'K':
5167 up = 1;
5168 /* FALL THROUGH */
5169 case '>':
5170 case '.':
5171 case 'J':
5172 if (s->parent_view == NULL) {
5173 view->count = 0;
5174 break;
5176 s->parent_view->count = view->count;
5178 if (s->parent_view->type == TOG_VIEW_LOG) {
5179 ls = &s->parent_view->state.log;
5180 old_selected_entry = ls->selected_entry;
5182 err = input_log_view(NULL, s->parent_view,
5183 up ? KEY_UP : KEY_DOWN);
5184 if (err)
5185 break;
5186 view->count = s->parent_view->count;
5188 if (old_selected_entry == ls->selected_entry)
5189 break;
5191 err = set_selected_commit(s, ls->selected_entry);
5192 if (err)
5193 break;
5194 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5195 struct tog_blame_view_state *bs;
5196 struct got_object_id *id, *prev_id;
5198 bs = &s->parent_view->state.blame;
5199 prev_id = get_annotation_for_line(bs->blame.lines,
5200 bs->blame.nlines, bs->last_diffed_line);
5202 err = input_blame_view(&view, s->parent_view,
5203 up ? KEY_UP : KEY_DOWN);
5204 if (err)
5205 break;
5206 view->count = s->parent_view->count;
5208 if (prev_id == NULL)
5209 break;
5210 id = get_selected_commit_id(bs->blame.lines,
5211 bs->blame.nlines, bs->first_displayed_line,
5212 bs->selected_line);
5213 if (id == NULL)
5214 break;
5216 if (!got_object_id_cmp(prev_id, id))
5217 break;
5219 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5220 if (err)
5221 break;
5223 s->first_displayed_line = 1;
5224 s->last_displayed_line = view->nlines;
5225 s->matched_line = 0;
5226 view->x = 0;
5228 diff_view_indicate_progress(view);
5229 err = create_diff(s);
5230 break;
5231 default:
5232 view->count = 0;
5233 break;
5236 return err;
5239 static const struct got_error *
5240 cmd_diff(int argc, char *argv[])
5242 const struct got_error *error = NULL;
5243 struct got_repository *repo = NULL;
5244 struct got_worktree *worktree = NULL;
5245 struct got_object_id *id1 = NULL, *id2 = NULL;
5246 char *repo_path = NULL, *cwd = NULL;
5247 char *id_str1 = NULL, *id_str2 = NULL;
5248 char *label1 = NULL, *label2 = NULL;
5249 int diff_context = 3, ignore_whitespace = 0;
5250 int ch, force_text_diff = 0;
5251 const char *errstr;
5252 struct tog_view *view;
5253 int *pack_fds = NULL;
5255 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5256 switch (ch) {
5257 case 'a':
5258 force_text_diff = 1;
5259 break;
5260 case 'C':
5261 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5262 &errstr);
5263 if (errstr != NULL)
5264 errx(1, "number of context lines is %s: %s",
5265 errstr, errstr);
5266 break;
5267 case 'r':
5268 repo_path = realpath(optarg, NULL);
5269 if (repo_path == NULL)
5270 return got_error_from_errno2("realpath",
5271 optarg);
5272 got_path_strip_trailing_slashes(repo_path);
5273 break;
5274 case 'w':
5275 ignore_whitespace = 1;
5276 break;
5277 default:
5278 usage_diff();
5279 /* NOTREACHED */
5283 argc -= optind;
5284 argv += optind;
5286 if (argc == 0) {
5287 usage_diff(); /* TODO show local worktree changes */
5288 } else if (argc == 2) {
5289 id_str1 = argv[0];
5290 id_str2 = argv[1];
5291 } else
5292 usage_diff();
5294 error = got_repo_pack_fds_open(&pack_fds);
5295 if (error)
5296 goto done;
5298 if (repo_path == NULL) {
5299 cwd = getcwd(NULL, 0);
5300 if (cwd == NULL)
5301 return got_error_from_errno("getcwd");
5302 error = got_worktree_open(&worktree, cwd);
5303 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5304 goto done;
5305 if (worktree)
5306 repo_path =
5307 strdup(got_worktree_get_repo_path(worktree));
5308 else
5309 repo_path = strdup(cwd);
5310 if (repo_path == NULL) {
5311 error = got_error_from_errno("strdup");
5312 goto done;
5316 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5317 if (error)
5318 goto done;
5320 init_curses();
5322 error = apply_unveil(got_repo_get_path(repo), NULL);
5323 if (error)
5324 goto done;
5326 error = tog_load_refs(repo, 0);
5327 if (error)
5328 goto done;
5330 error = got_repo_match_object_id(&id1, &label1, id_str1,
5331 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5332 if (error)
5333 goto done;
5335 error = got_repo_match_object_id(&id2, &label2, id_str2,
5336 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5337 if (error)
5338 goto done;
5340 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5341 if (view == NULL) {
5342 error = got_error_from_errno("view_open");
5343 goto done;
5345 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5346 ignore_whitespace, force_text_diff, NULL, repo);
5347 if (error)
5348 goto done;
5349 error = view_loop(view);
5350 done:
5351 free(label1);
5352 free(label2);
5353 free(repo_path);
5354 free(cwd);
5355 if (repo) {
5356 const struct got_error *close_err = got_repo_close(repo);
5357 if (error == NULL)
5358 error = close_err;
5360 if (worktree)
5361 got_worktree_close(worktree);
5362 if (pack_fds) {
5363 const struct got_error *pack_err =
5364 got_repo_pack_fds_close(pack_fds);
5365 if (error == NULL)
5366 error = pack_err;
5368 tog_free_refs();
5369 return error;
5372 __dead static void
5373 usage_blame(void)
5375 endwin();
5376 fprintf(stderr,
5377 "usage: %s blame [-c commit] [-r repository-path] path\n",
5378 getprogname());
5379 exit(1);
5382 struct tog_blame_line {
5383 int annotated;
5384 struct got_object_id *id;
5387 static const struct got_error *
5388 draw_blame(struct tog_view *view)
5390 struct tog_blame_view_state *s = &view->state.blame;
5391 struct tog_blame *blame = &s->blame;
5392 regmatch_t *regmatch = &view->regmatch;
5393 const struct got_error *err;
5394 int lineno = 0, nprinted = 0;
5395 char *line = NULL;
5396 size_t linesize = 0;
5397 ssize_t linelen;
5398 wchar_t *wline;
5399 int width;
5400 struct tog_blame_line *blame_line;
5401 struct got_object_id *prev_id = NULL;
5402 char *id_str;
5403 struct tog_color *tc;
5405 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5406 if (err)
5407 return err;
5409 rewind(blame->f);
5410 werase(view->window);
5412 if (asprintf(&line, "commit %s", id_str) == -1) {
5413 err = got_error_from_errno("asprintf");
5414 free(id_str);
5415 return err;
5418 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5419 free(line);
5420 line = NULL;
5421 if (err)
5422 return err;
5423 if (view_needs_focus_indication(view))
5424 wstandout(view->window);
5425 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5426 if (tc)
5427 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5428 waddwstr(view->window, wline);
5429 while (width++ < view->ncols)
5430 waddch(view->window, ' ');
5431 if (tc)
5432 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5433 if (view_needs_focus_indication(view))
5434 wstandend(view->window);
5435 free(wline);
5436 wline = NULL;
5438 if (view->gline > blame->nlines)
5439 view->gline = blame->nlines;
5441 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5442 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5443 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5444 free(id_str);
5445 return got_error_from_errno("asprintf");
5447 free(id_str);
5448 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5449 free(line);
5450 line = NULL;
5451 if (err)
5452 return err;
5453 waddwstr(view->window, wline);
5454 free(wline);
5455 wline = NULL;
5456 if (width < view->ncols - 1)
5457 waddch(view->window, '\n');
5459 s->eof = 0;
5460 view->maxx = 0;
5461 while (nprinted < view->nlines - 2) {
5462 linelen = getline(&line, &linesize, blame->f);
5463 if (linelen == -1) {
5464 if (feof(blame->f)) {
5465 s->eof = 1;
5466 break;
5468 free(line);
5469 return got_ferror(blame->f, GOT_ERR_IO);
5471 if (++lineno < s->first_displayed_line)
5472 continue;
5473 if (view->gline && !gotoline(view, &lineno, &nprinted))
5474 continue;
5476 /* Set view->maxx based on full line length. */
5477 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5478 if (err) {
5479 free(line);
5480 return err;
5482 free(wline);
5483 wline = NULL;
5484 view->maxx = MAX(view->maxx, width);
5486 if (nprinted == s->selected_line - 1)
5487 wstandout(view->window);
5489 if (blame->nlines > 0) {
5490 blame_line = &blame->lines[lineno - 1];
5491 if (blame_line->annotated && prev_id &&
5492 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5493 !(nprinted == s->selected_line - 1)) {
5494 waddstr(view->window, " ");
5495 } else if (blame_line->annotated) {
5496 char *id_str;
5497 err = got_object_id_str(&id_str,
5498 blame_line->id);
5499 if (err) {
5500 free(line);
5501 return err;
5503 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5504 if (tc)
5505 wattr_on(view->window,
5506 COLOR_PAIR(tc->colorpair), NULL);
5507 wprintw(view->window, "%.8s", id_str);
5508 if (tc)
5509 wattr_off(view->window,
5510 COLOR_PAIR(tc->colorpair), NULL);
5511 free(id_str);
5512 prev_id = blame_line->id;
5513 } else {
5514 waddstr(view->window, "........");
5515 prev_id = NULL;
5517 } else {
5518 waddstr(view->window, "........");
5519 prev_id = NULL;
5522 if (nprinted == s->selected_line - 1)
5523 wstandend(view->window);
5524 waddstr(view->window, " ");
5526 if (view->ncols <= 9) {
5527 width = 9;
5528 } else if (s->first_displayed_line + nprinted ==
5529 s->matched_line &&
5530 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5531 err = add_matched_line(&width, line, view->ncols - 9, 9,
5532 view->window, view->x, regmatch);
5533 if (err) {
5534 free(line);
5535 return err;
5537 width += 9;
5538 } else {
5539 int skip;
5540 err = format_line(&wline, &width, &skip, line,
5541 view->x, view->ncols - 9, 9, 1);
5542 if (err) {
5543 free(line);
5544 return err;
5546 waddwstr(view->window, &wline[skip]);
5547 width += 9;
5548 free(wline);
5549 wline = NULL;
5552 if (width <= view->ncols - 1)
5553 waddch(view->window, '\n');
5554 if (++nprinted == 1)
5555 s->first_displayed_line = lineno;
5557 free(line);
5558 s->last_displayed_line = lineno;
5560 view_border(view);
5562 return NULL;
5565 static const struct got_error *
5566 blame_cb(void *arg, int nlines, int lineno,
5567 struct got_commit_object *commit, struct got_object_id *id)
5569 const struct got_error *err = NULL;
5570 struct tog_blame_cb_args *a = arg;
5571 struct tog_blame_line *line;
5572 int errcode;
5574 if (nlines != a->nlines ||
5575 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5576 return got_error(GOT_ERR_RANGE);
5578 errcode = pthread_mutex_lock(&tog_mutex);
5579 if (errcode)
5580 return got_error_set_errno(errcode, "pthread_mutex_lock");
5582 if (*a->quit) { /* user has quit the blame view */
5583 err = got_error(GOT_ERR_ITER_COMPLETED);
5584 goto done;
5587 if (lineno == -1)
5588 goto done; /* no change in this commit */
5590 line = &a->lines[lineno - 1];
5591 if (line->annotated)
5592 goto done;
5594 line->id = got_object_id_dup(id);
5595 if (line->id == NULL) {
5596 err = got_error_from_errno("got_object_id_dup");
5597 goto done;
5599 line->annotated = 1;
5600 done:
5601 errcode = pthread_mutex_unlock(&tog_mutex);
5602 if (errcode)
5603 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5604 return err;
5607 static void *
5608 blame_thread(void *arg)
5610 const struct got_error *err, *close_err;
5611 struct tog_blame_thread_args *ta = arg;
5612 struct tog_blame_cb_args *a = ta->cb_args;
5613 int errcode, fd1 = -1, fd2 = -1;
5614 FILE *f1 = NULL, *f2 = NULL;
5616 fd1 = got_opentempfd();
5617 if (fd1 == -1)
5618 return (void *)got_error_from_errno("got_opentempfd");
5620 fd2 = got_opentempfd();
5621 if (fd2 == -1) {
5622 err = got_error_from_errno("got_opentempfd");
5623 goto done;
5626 f1 = got_opentemp();
5627 if (f1 == NULL) {
5628 err = (void *)got_error_from_errno("got_opentemp");
5629 goto done;
5631 f2 = got_opentemp();
5632 if (f2 == NULL) {
5633 err = (void *)got_error_from_errno("got_opentemp");
5634 goto done;
5637 err = block_signals_used_by_main_thread();
5638 if (err)
5639 goto done;
5641 err = got_blame(ta->path, a->commit_id, ta->repo,
5642 tog_diff_algo, blame_cb, ta->cb_args,
5643 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5644 if (err && err->code == GOT_ERR_CANCELLED)
5645 err = NULL;
5647 errcode = pthread_mutex_lock(&tog_mutex);
5648 if (errcode) {
5649 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5650 goto done;
5653 close_err = got_repo_close(ta->repo);
5654 if (err == NULL)
5655 err = close_err;
5656 ta->repo = NULL;
5657 *ta->complete = 1;
5659 errcode = pthread_mutex_unlock(&tog_mutex);
5660 if (errcode && err == NULL)
5661 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5663 done:
5664 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5665 err = got_error_from_errno("close");
5666 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5667 err = got_error_from_errno("close");
5668 if (f1 && fclose(f1) == EOF && err == NULL)
5669 err = got_error_from_errno("fclose");
5670 if (f2 && fclose(f2) == EOF && err == NULL)
5671 err = got_error_from_errno("fclose");
5673 return (void *)err;
5676 static struct got_object_id *
5677 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5678 int first_displayed_line, int selected_line)
5680 struct tog_blame_line *line;
5682 if (nlines <= 0)
5683 return NULL;
5685 line = &lines[first_displayed_line - 1 + selected_line - 1];
5686 if (!line->annotated)
5687 return NULL;
5689 return line->id;
5692 static struct got_object_id *
5693 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5694 int lineno)
5696 struct tog_blame_line *line;
5698 if (nlines <= 0 || lineno >= nlines)
5699 return NULL;
5701 line = &lines[lineno - 1];
5702 if (!line->annotated)
5703 return NULL;
5705 return line->id;
5708 static const struct got_error *
5709 stop_blame(struct tog_blame *blame)
5711 const struct got_error *err = NULL;
5712 int i;
5714 if (blame->thread) {
5715 int errcode;
5716 errcode = pthread_mutex_unlock(&tog_mutex);
5717 if (errcode)
5718 return got_error_set_errno(errcode,
5719 "pthread_mutex_unlock");
5720 errcode = pthread_join(blame->thread, (void **)&err);
5721 if (errcode)
5722 return got_error_set_errno(errcode, "pthread_join");
5723 errcode = pthread_mutex_lock(&tog_mutex);
5724 if (errcode)
5725 return got_error_set_errno(errcode,
5726 "pthread_mutex_lock");
5727 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5728 err = NULL;
5729 blame->thread = 0; //NULL;
5731 if (blame->thread_args.repo) {
5732 const struct got_error *close_err;
5733 close_err = got_repo_close(blame->thread_args.repo);
5734 if (err == NULL)
5735 err = close_err;
5736 blame->thread_args.repo = NULL;
5738 if (blame->f) {
5739 if (fclose(blame->f) == EOF && err == NULL)
5740 err = got_error_from_errno("fclose");
5741 blame->f = NULL;
5743 if (blame->lines) {
5744 for (i = 0; i < blame->nlines; i++)
5745 free(blame->lines[i].id);
5746 free(blame->lines);
5747 blame->lines = NULL;
5749 free(blame->cb_args.commit_id);
5750 blame->cb_args.commit_id = NULL;
5751 if (blame->pack_fds) {
5752 const struct got_error *pack_err =
5753 got_repo_pack_fds_close(blame->pack_fds);
5754 if (err == NULL)
5755 err = pack_err;
5756 blame->pack_fds = NULL;
5758 return err;
5761 static const struct got_error *
5762 cancel_blame_view(void *arg)
5764 const struct got_error *err = NULL;
5765 int *done = arg;
5766 int errcode;
5768 errcode = pthread_mutex_lock(&tog_mutex);
5769 if (errcode)
5770 return got_error_set_errno(errcode,
5771 "pthread_mutex_unlock");
5773 if (*done)
5774 err = got_error(GOT_ERR_CANCELLED);
5776 errcode = pthread_mutex_unlock(&tog_mutex);
5777 if (errcode)
5778 return got_error_set_errno(errcode,
5779 "pthread_mutex_lock");
5781 return err;
5784 static const struct got_error *
5785 run_blame(struct tog_view *view)
5787 struct tog_blame_view_state *s = &view->state.blame;
5788 struct tog_blame *blame = &s->blame;
5789 const struct got_error *err = NULL;
5790 struct got_commit_object *commit = NULL;
5791 struct got_blob_object *blob = NULL;
5792 struct got_repository *thread_repo = NULL;
5793 struct got_object_id *obj_id = NULL;
5794 int obj_type, fd = -1;
5795 int *pack_fds = NULL;
5797 err = got_object_open_as_commit(&commit, s->repo,
5798 &s->blamed_commit->id);
5799 if (err)
5800 return err;
5802 fd = got_opentempfd();
5803 if (fd == -1) {
5804 err = got_error_from_errno("got_opentempfd");
5805 goto done;
5808 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5809 if (err)
5810 goto done;
5812 err = got_object_get_type(&obj_type, s->repo, obj_id);
5813 if (err)
5814 goto done;
5816 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5817 err = got_error(GOT_ERR_OBJ_TYPE);
5818 goto done;
5821 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5822 if (err)
5823 goto done;
5824 blame->f = got_opentemp();
5825 if (blame->f == NULL) {
5826 err = got_error_from_errno("got_opentemp");
5827 goto done;
5829 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5830 &blame->line_offsets, blame->f, blob);
5831 if (err)
5832 goto done;
5833 if (blame->nlines == 0) {
5834 s->blame_complete = 1;
5835 goto done;
5838 /* Don't include \n at EOF in the blame line count. */
5839 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5840 blame->nlines--;
5842 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5843 if (blame->lines == NULL) {
5844 err = got_error_from_errno("calloc");
5845 goto done;
5848 err = got_repo_pack_fds_open(&pack_fds);
5849 if (err)
5850 goto done;
5851 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5852 pack_fds);
5853 if (err)
5854 goto done;
5856 blame->pack_fds = pack_fds;
5857 blame->cb_args.view = view;
5858 blame->cb_args.lines = blame->lines;
5859 blame->cb_args.nlines = blame->nlines;
5860 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5861 if (blame->cb_args.commit_id == NULL) {
5862 err = got_error_from_errno("got_object_id_dup");
5863 goto done;
5865 blame->cb_args.quit = &s->done;
5867 blame->thread_args.path = s->path;
5868 blame->thread_args.repo = thread_repo;
5869 blame->thread_args.cb_args = &blame->cb_args;
5870 blame->thread_args.complete = &s->blame_complete;
5871 blame->thread_args.cancel_cb = cancel_blame_view;
5872 blame->thread_args.cancel_arg = &s->done;
5873 s->blame_complete = 0;
5875 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5876 s->first_displayed_line = 1;
5877 s->last_displayed_line = view->nlines;
5878 s->selected_line = 1;
5880 s->matched_line = 0;
5882 done:
5883 if (commit)
5884 got_object_commit_close(commit);
5885 if (fd != -1 && close(fd) == -1 && err == NULL)
5886 err = got_error_from_errno("close");
5887 if (blob)
5888 got_object_blob_close(blob);
5889 free(obj_id);
5890 if (err)
5891 stop_blame(blame);
5892 return err;
5895 static const struct got_error *
5896 open_blame_view(struct tog_view *view, char *path,
5897 struct got_object_id *commit_id, struct got_repository *repo)
5899 const struct got_error *err = NULL;
5900 struct tog_blame_view_state *s = &view->state.blame;
5902 STAILQ_INIT(&s->blamed_commits);
5904 s->path = strdup(path);
5905 if (s->path == NULL)
5906 return got_error_from_errno("strdup");
5908 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5909 if (err) {
5910 free(s->path);
5911 return err;
5914 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5915 s->first_displayed_line = 1;
5916 s->last_displayed_line = view->nlines;
5917 s->selected_line = 1;
5918 s->blame_complete = 0;
5919 s->repo = repo;
5920 s->commit_id = commit_id;
5921 memset(&s->blame, 0, sizeof(s->blame));
5923 STAILQ_INIT(&s->colors);
5924 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5925 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5926 get_color_value("TOG_COLOR_COMMIT"));
5927 if (err)
5928 return err;
5931 view->show = show_blame_view;
5932 view->input = input_blame_view;
5933 view->reset = reset_blame_view;
5934 view->close = close_blame_view;
5935 view->search_start = search_start_blame_view;
5936 view->search_next = search_next_blame_view;
5938 return run_blame(view);
5941 static const struct got_error *
5942 close_blame_view(struct tog_view *view)
5944 const struct got_error *err = NULL;
5945 struct tog_blame_view_state *s = &view->state.blame;
5947 if (s->blame.thread)
5948 err = stop_blame(&s->blame);
5950 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5951 struct got_object_qid *blamed_commit;
5952 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5953 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5954 got_object_qid_free(blamed_commit);
5957 free(s->path);
5958 free_colors(&s->colors);
5959 return err;
5962 static const struct got_error *
5963 search_start_blame_view(struct tog_view *view)
5965 struct tog_blame_view_state *s = &view->state.blame;
5967 s->matched_line = 0;
5968 return NULL;
5971 static const struct got_error *
5972 search_next_blame_view(struct tog_view *view)
5974 struct tog_blame_view_state *s = &view->state.blame;
5975 const struct got_error *err = NULL;
5976 int lineno;
5977 char *line = NULL;
5978 size_t linesize = 0;
5979 ssize_t linelen;
5981 if (!view->searching) {
5982 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5983 return NULL;
5986 if (s->matched_line) {
5987 if (view->searching == TOG_SEARCH_FORWARD)
5988 lineno = s->matched_line + 1;
5989 else
5990 lineno = s->matched_line - 1;
5991 } else
5992 lineno = s->first_displayed_line - 1 + s->selected_line;
5994 while (1) {
5995 off_t offset;
5997 if (lineno <= 0 || lineno > s->blame.nlines) {
5998 if (s->matched_line == 0) {
5999 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6000 break;
6003 if (view->searching == TOG_SEARCH_FORWARD)
6004 lineno = 1;
6005 else
6006 lineno = s->blame.nlines;
6009 offset = s->blame.line_offsets[lineno - 1];
6010 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
6011 free(line);
6012 return got_error_from_errno("fseeko");
6014 linelen = getline(&line, &linesize, s->blame.f);
6015 if (linelen != -1) {
6016 char *exstr;
6017 err = expand_tab(&exstr, line);
6018 if (err)
6019 break;
6020 if (match_line(exstr, &view->regex, 1,
6021 &view->regmatch)) {
6022 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6023 s->matched_line = lineno;
6024 free(exstr);
6025 break;
6027 free(exstr);
6029 if (view->searching == TOG_SEARCH_FORWARD)
6030 lineno++;
6031 else
6032 lineno--;
6034 free(line);
6036 if (s->matched_line) {
6037 s->first_displayed_line = s->matched_line;
6038 s->selected_line = 1;
6041 return err;
6044 static const struct got_error *
6045 show_blame_view(struct tog_view *view)
6047 const struct got_error *err = NULL;
6048 struct tog_blame_view_state *s = &view->state.blame;
6049 int errcode;
6051 if (s->blame.thread == 0 && !s->blame_complete) {
6052 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6053 &s->blame.thread_args);
6054 if (errcode)
6055 return got_error_set_errno(errcode, "pthread_create");
6057 halfdelay(1); /* fast refresh while annotating */
6060 if (s->blame_complete)
6061 halfdelay(10); /* disable fast refresh */
6063 err = draw_blame(view);
6065 view_border(view);
6066 return err;
6069 static const struct got_error *
6070 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6071 struct got_repository *repo, struct got_object_id *id)
6073 struct tog_view *log_view;
6074 const struct got_error *err = NULL;
6076 *new_view = NULL;
6078 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6079 if (log_view == NULL)
6080 return got_error_from_errno("view_open");
6082 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6083 if (err)
6084 view_close(log_view);
6085 else
6086 *new_view = log_view;
6088 return err;
6091 static const struct got_error *
6092 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6094 const struct got_error *err = NULL, *thread_err = NULL;
6095 struct tog_view *diff_view;
6096 struct tog_blame_view_state *s = &view->state.blame;
6097 int eos, nscroll, begin_y = 0, begin_x = 0;
6099 eos = nscroll = view->nlines - 2;
6100 if (view_is_hsplit_top(view))
6101 --eos; /* border */
6103 switch (ch) {
6104 case '0':
6105 view->x = 0;
6106 break;
6107 case '$':
6108 view->x = MAX(view->maxx - view->ncols / 3, 0);
6109 view->count = 0;
6110 break;
6111 case KEY_RIGHT:
6112 case 'l':
6113 if (view->x + view->ncols / 3 < view->maxx)
6114 view->x += 2; /* move two columns right */
6115 else
6116 view->count = 0;
6117 break;
6118 case KEY_LEFT:
6119 case 'h':
6120 view->x -= MIN(view->x, 2); /* move two columns back */
6121 if (view->x <= 0)
6122 view->count = 0;
6123 break;
6124 case 'q':
6125 s->done = 1;
6126 break;
6127 case 'g':
6128 case KEY_HOME:
6129 s->selected_line = 1;
6130 s->first_displayed_line = 1;
6131 view->count = 0;
6132 break;
6133 case 'G':
6134 case KEY_END:
6135 if (s->blame.nlines < eos) {
6136 s->selected_line = s->blame.nlines;
6137 s->first_displayed_line = 1;
6138 } else {
6139 s->selected_line = eos;
6140 s->first_displayed_line = s->blame.nlines - (eos - 1);
6142 view->count = 0;
6143 break;
6144 case 'k':
6145 case KEY_UP:
6146 case CTRL('p'):
6147 if (s->selected_line > 1)
6148 s->selected_line--;
6149 else if (s->selected_line == 1 &&
6150 s->first_displayed_line > 1)
6151 s->first_displayed_line--;
6152 else
6153 view->count = 0;
6154 break;
6155 case CTRL('u'):
6156 case 'u':
6157 nscroll /= 2;
6158 /* FALL THROUGH */
6159 case KEY_PPAGE:
6160 case CTRL('b'):
6161 case 'b':
6162 if (s->first_displayed_line == 1) {
6163 if (view->count > 1)
6164 nscroll += nscroll;
6165 s->selected_line = MAX(1, s->selected_line - nscroll);
6166 view->count = 0;
6167 break;
6169 if (s->first_displayed_line > nscroll)
6170 s->first_displayed_line -= nscroll;
6171 else
6172 s->first_displayed_line = 1;
6173 break;
6174 case 'j':
6175 case KEY_DOWN:
6176 case CTRL('n'):
6177 if (s->selected_line < eos && s->first_displayed_line +
6178 s->selected_line <= s->blame.nlines)
6179 s->selected_line++;
6180 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6181 s->first_displayed_line++;
6182 else
6183 view->count = 0;
6184 break;
6185 case 'c':
6186 case 'p': {
6187 struct got_object_id *id = NULL;
6189 view->count = 0;
6190 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6191 s->first_displayed_line, s->selected_line);
6192 if (id == NULL)
6193 break;
6194 if (ch == 'p') {
6195 struct got_commit_object *commit, *pcommit;
6196 struct got_object_qid *pid;
6197 struct got_object_id *blob_id = NULL;
6198 int obj_type;
6199 err = got_object_open_as_commit(&commit,
6200 s->repo, id);
6201 if (err)
6202 break;
6203 pid = STAILQ_FIRST(
6204 got_object_commit_get_parent_ids(commit));
6205 if (pid == NULL) {
6206 got_object_commit_close(commit);
6207 break;
6209 /* Check if path history ends here. */
6210 err = got_object_open_as_commit(&pcommit,
6211 s->repo, &pid->id);
6212 if (err)
6213 break;
6214 err = got_object_id_by_path(&blob_id, s->repo,
6215 pcommit, s->path);
6216 got_object_commit_close(pcommit);
6217 if (err) {
6218 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6219 err = NULL;
6220 got_object_commit_close(commit);
6221 break;
6223 err = got_object_get_type(&obj_type, s->repo,
6224 blob_id);
6225 free(blob_id);
6226 /* Can't blame non-blob type objects. */
6227 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6228 got_object_commit_close(commit);
6229 break;
6231 err = got_object_qid_alloc(&s->blamed_commit,
6232 &pid->id);
6233 got_object_commit_close(commit);
6234 } else {
6235 if (got_object_id_cmp(id,
6236 &s->blamed_commit->id) == 0)
6237 break;
6238 err = got_object_qid_alloc(&s->blamed_commit,
6239 id);
6241 if (err)
6242 break;
6243 s->done = 1;
6244 thread_err = stop_blame(&s->blame);
6245 s->done = 0;
6246 if (thread_err)
6247 break;
6248 STAILQ_INSERT_HEAD(&s->blamed_commits,
6249 s->blamed_commit, entry);
6250 err = run_blame(view);
6251 if (err)
6252 break;
6253 break;
6255 case 'C': {
6256 struct got_object_qid *first;
6258 view->count = 0;
6259 first = STAILQ_FIRST(&s->blamed_commits);
6260 if (!got_object_id_cmp(&first->id, s->commit_id))
6261 break;
6262 s->done = 1;
6263 thread_err = stop_blame(&s->blame);
6264 s->done = 0;
6265 if (thread_err)
6266 break;
6267 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6268 got_object_qid_free(s->blamed_commit);
6269 s->blamed_commit =
6270 STAILQ_FIRST(&s->blamed_commits);
6271 err = run_blame(view);
6272 if (err)
6273 break;
6274 break;
6276 case 'L':
6277 view->count = 0;
6278 s->id_to_log = get_selected_commit_id(s->blame.lines,
6279 s->blame.nlines, s->first_displayed_line, s->selected_line);
6280 if (s->id_to_log)
6281 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6282 break;
6283 case KEY_ENTER:
6284 case '\r': {
6285 struct got_object_id *id = NULL;
6286 struct got_object_qid *pid;
6287 struct got_commit_object *commit = NULL;
6289 view->count = 0;
6290 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6291 s->first_displayed_line, s->selected_line);
6292 if (id == NULL)
6293 break;
6294 err = got_object_open_as_commit(&commit, s->repo, id);
6295 if (err)
6296 break;
6297 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6298 if (*new_view) {
6299 /* traversed from diff view, release diff resources */
6300 err = close_diff_view(*new_view);
6301 if (err)
6302 break;
6303 diff_view = *new_view;
6304 } else {
6305 if (view_is_parent_view(view))
6306 view_get_split(view, &begin_y, &begin_x);
6308 diff_view = view_open(0, 0, begin_y, begin_x,
6309 TOG_VIEW_DIFF);
6310 if (diff_view == NULL) {
6311 got_object_commit_close(commit);
6312 err = got_error_from_errno("view_open");
6313 break;
6316 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6317 id, NULL, NULL, 3, 0, 0, view, s->repo);
6318 got_object_commit_close(commit);
6319 if (err) {
6320 view_close(diff_view);
6321 break;
6323 s->last_diffed_line = s->first_displayed_line - 1 +
6324 s->selected_line;
6325 if (*new_view)
6326 break; /* still open from active diff view */
6327 if (view_is_parent_view(view) &&
6328 view->mode == TOG_VIEW_SPLIT_HRZN) {
6329 err = view_init_hsplit(view, begin_y);
6330 if (err)
6331 break;
6334 view->focussed = 0;
6335 diff_view->focussed = 1;
6336 diff_view->mode = view->mode;
6337 diff_view->nlines = view->lines - begin_y;
6338 if (view_is_parent_view(view)) {
6339 view_transfer_size(diff_view, view);
6340 err = view_close_child(view);
6341 if (err)
6342 break;
6343 err = view_set_child(view, diff_view);
6344 if (err)
6345 break;
6346 view->focus_child = 1;
6347 } else
6348 *new_view = diff_view;
6349 if (err)
6350 break;
6351 break;
6353 case CTRL('d'):
6354 case 'd':
6355 nscroll /= 2;
6356 /* FALL THROUGH */
6357 case KEY_NPAGE:
6358 case CTRL('f'):
6359 case 'f':
6360 case ' ':
6361 if (s->last_displayed_line >= s->blame.nlines &&
6362 s->selected_line >= MIN(s->blame.nlines,
6363 view->nlines - 2)) {
6364 view->count = 0;
6365 break;
6367 if (s->last_displayed_line >= s->blame.nlines &&
6368 s->selected_line < view->nlines - 2) {
6369 s->selected_line +=
6370 MIN(nscroll, s->last_displayed_line -
6371 s->first_displayed_line - s->selected_line + 1);
6373 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6374 s->first_displayed_line += nscroll;
6375 else
6376 s->first_displayed_line =
6377 s->blame.nlines - (view->nlines - 3);
6378 break;
6379 case KEY_RESIZE:
6380 if (s->selected_line > view->nlines - 2) {
6381 s->selected_line = MIN(s->blame.nlines,
6382 view->nlines - 2);
6384 break;
6385 default:
6386 view->count = 0;
6387 break;
6389 return thread_err ? thread_err : err;
6392 static const struct got_error *
6393 reset_blame_view(struct tog_view *view)
6395 const struct got_error *err;
6396 struct tog_blame_view_state *s = &view->state.blame;
6398 view->count = 0;
6399 s->done = 1;
6400 err = stop_blame(&s->blame);
6401 s->done = 0;
6402 if (err)
6403 return err;
6404 return run_blame(view);
6407 static const struct got_error *
6408 cmd_blame(int argc, char *argv[])
6410 const struct got_error *error;
6411 struct got_repository *repo = NULL;
6412 struct got_worktree *worktree = NULL;
6413 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6414 char *link_target = NULL;
6415 struct got_object_id *commit_id = NULL;
6416 struct got_commit_object *commit = NULL;
6417 char *commit_id_str = NULL;
6418 int ch;
6419 struct tog_view *view;
6420 int *pack_fds = NULL;
6422 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6423 switch (ch) {
6424 case 'c':
6425 commit_id_str = optarg;
6426 break;
6427 case 'r':
6428 repo_path = realpath(optarg, NULL);
6429 if (repo_path == NULL)
6430 return got_error_from_errno2("realpath",
6431 optarg);
6432 break;
6433 default:
6434 usage_blame();
6435 /* NOTREACHED */
6439 argc -= optind;
6440 argv += optind;
6442 if (argc != 1)
6443 usage_blame();
6445 error = got_repo_pack_fds_open(&pack_fds);
6446 if (error != NULL)
6447 goto done;
6449 if (repo_path == NULL) {
6450 cwd = getcwd(NULL, 0);
6451 if (cwd == NULL)
6452 return got_error_from_errno("getcwd");
6453 error = got_worktree_open(&worktree, cwd);
6454 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6455 goto done;
6456 if (worktree)
6457 repo_path =
6458 strdup(got_worktree_get_repo_path(worktree));
6459 else
6460 repo_path = strdup(cwd);
6461 if (repo_path == NULL) {
6462 error = got_error_from_errno("strdup");
6463 goto done;
6467 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6468 if (error != NULL)
6469 goto done;
6471 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6472 worktree);
6473 if (error)
6474 goto done;
6476 init_curses();
6478 error = apply_unveil(got_repo_get_path(repo), NULL);
6479 if (error)
6480 goto done;
6482 error = tog_load_refs(repo, 0);
6483 if (error)
6484 goto done;
6486 if (commit_id_str == NULL) {
6487 struct got_reference *head_ref;
6488 error = got_ref_open(&head_ref, repo, worktree ?
6489 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6490 if (error != NULL)
6491 goto done;
6492 error = got_ref_resolve(&commit_id, repo, head_ref);
6493 got_ref_close(head_ref);
6494 } else {
6495 error = got_repo_match_object_id(&commit_id, NULL,
6496 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6498 if (error != NULL)
6499 goto done;
6501 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6502 if (view == NULL) {
6503 error = got_error_from_errno("view_open");
6504 goto done;
6507 error = got_object_open_as_commit(&commit, repo, commit_id);
6508 if (error)
6509 goto done;
6511 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6512 commit, repo);
6513 if (error)
6514 goto done;
6516 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6517 commit_id, repo);
6518 if (error)
6519 goto done;
6520 if (worktree) {
6521 /* Release work tree lock. */
6522 got_worktree_close(worktree);
6523 worktree = NULL;
6525 error = view_loop(view);
6526 done:
6527 free(repo_path);
6528 free(in_repo_path);
6529 free(link_target);
6530 free(cwd);
6531 free(commit_id);
6532 if (commit)
6533 got_object_commit_close(commit);
6534 if (worktree)
6535 got_worktree_close(worktree);
6536 if (repo) {
6537 const struct got_error *close_err = got_repo_close(repo);
6538 if (error == NULL)
6539 error = close_err;
6541 if (pack_fds) {
6542 const struct got_error *pack_err =
6543 got_repo_pack_fds_close(pack_fds);
6544 if (error == NULL)
6545 error = pack_err;
6547 tog_free_refs();
6548 return error;
6551 static const struct got_error *
6552 draw_tree_entries(struct tog_view *view, const char *parent_path)
6554 struct tog_tree_view_state *s = &view->state.tree;
6555 const struct got_error *err = NULL;
6556 struct got_tree_entry *te;
6557 wchar_t *wline;
6558 char *index = NULL;
6559 struct tog_color *tc;
6560 int width, n, nentries, i = 1;
6561 int limit = view->nlines;
6563 s->ndisplayed = 0;
6564 if (view_is_hsplit_top(view))
6565 --limit; /* border */
6567 werase(view->window);
6569 if (limit == 0)
6570 return NULL;
6572 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6573 0, 0);
6574 if (err)
6575 return err;
6576 if (view_needs_focus_indication(view))
6577 wstandout(view->window);
6578 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6579 if (tc)
6580 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6581 waddwstr(view->window, wline);
6582 free(wline);
6583 wline = NULL;
6584 while (width++ < view->ncols)
6585 waddch(view->window, ' ');
6586 if (tc)
6587 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6588 if (view_needs_focus_indication(view))
6589 wstandend(view->window);
6590 if (--limit <= 0)
6591 return NULL;
6593 i += s->selected;
6594 if (s->first_displayed_entry) {
6595 i += got_tree_entry_get_index(s->first_displayed_entry);
6596 if (s->tree != s->root)
6597 ++i; /* account for ".." entry */
6599 nentries = got_object_tree_get_nentries(s->tree);
6600 if (asprintf(&index, "[%d/%d] %s",
6601 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6602 return got_error_from_errno("asprintf");
6603 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6604 free(index);
6605 if (err)
6606 return err;
6607 waddwstr(view->window, wline);
6608 free(wline);
6609 wline = NULL;
6610 if (width < view->ncols - 1)
6611 waddch(view->window, '\n');
6612 if (--limit <= 0)
6613 return NULL;
6614 waddch(view->window, '\n');
6615 if (--limit <= 0)
6616 return NULL;
6618 if (s->first_displayed_entry == NULL) {
6619 te = got_object_tree_get_first_entry(s->tree);
6620 if (s->selected == 0) {
6621 if (view->focussed)
6622 wstandout(view->window);
6623 s->selected_entry = NULL;
6625 waddstr(view->window, " ..\n"); /* parent directory */
6626 if (s->selected == 0 && view->focussed)
6627 wstandend(view->window);
6628 s->ndisplayed++;
6629 if (--limit <= 0)
6630 return NULL;
6631 n = 1;
6632 } else {
6633 n = 0;
6634 te = s->first_displayed_entry;
6637 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6638 char *line = NULL, *id_str = NULL, *link_target = NULL;
6639 const char *modestr = "";
6640 mode_t mode;
6642 te = got_object_tree_get_entry(s->tree, i);
6643 mode = got_tree_entry_get_mode(te);
6645 if (s->show_ids) {
6646 err = got_object_id_str(&id_str,
6647 got_tree_entry_get_id(te));
6648 if (err)
6649 return got_error_from_errno(
6650 "got_object_id_str");
6652 if (got_object_tree_entry_is_submodule(te))
6653 modestr = "$";
6654 else if (S_ISLNK(mode)) {
6655 int i;
6657 err = got_tree_entry_get_symlink_target(&link_target,
6658 te, s->repo);
6659 if (err) {
6660 free(id_str);
6661 return err;
6663 for (i = 0; i < strlen(link_target); i++) {
6664 if (!isprint((unsigned char)link_target[i]))
6665 link_target[i] = '?';
6667 modestr = "@";
6669 else if (S_ISDIR(mode))
6670 modestr = "/";
6671 else if (mode & S_IXUSR)
6672 modestr = "*";
6673 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6674 got_tree_entry_get_name(te), modestr,
6675 link_target ? " -> ": "",
6676 link_target ? link_target : "") == -1) {
6677 free(id_str);
6678 free(link_target);
6679 return got_error_from_errno("asprintf");
6681 free(id_str);
6682 free(link_target);
6683 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6684 0, 0);
6685 if (err) {
6686 free(line);
6687 break;
6689 if (n == s->selected) {
6690 if (view->focussed)
6691 wstandout(view->window);
6692 s->selected_entry = te;
6694 tc = match_color(&s->colors, line);
6695 if (tc)
6696 wattr_on(view->window,
6697 COLOR_PAIR(tc->colorpair), NULL);
6698 waddwstr(view->window, wline);
6699 if (tc)
6700 wattr_off(view->window,
6701 COLOR_PAIR(tc->colorpair), NULL);
6702 if (width < view->ncols - 1)
6703 waddch(view->window, '\n');
6704 if (n == s->selected && view->focussed)
6705 wstandend(view->window);
6706 free(line);
6707 free(wline);
6708 wline = NULL;
6709 n++;
6710 s->ndisplayed++;
6711 s->last_displayed_entry = te;
6712 if (--limit <= 0)
6713 break;
6716 return err;
6719 static void
6720 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6722 struct got_tree_entry *te;
6723 int isroot = s->tree == s->root;
6724 int i = 0;
6726 if (s->first_displayed_entry == NULL)
6727 return;
6729 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6730 while (i++ < maxscroll) {
6731 if (te == NULL) {
6732 if (!isroot)
6733 s->first_displayed_entry = NULL;
6734 break;
6736 s->first_displayed_entry = te;
6737 te = got_tree_entry_get_prev(s->tree, te);
6741 static const struct got_error *
6742 tree_scroll_down(struct tog_view *view, int maxscroll)
6744 struct tog_tree_view_state *s = &view->state.tree;
6745 struct got_tree_entry *next, *last;
6746 int n = 0;
6748 if (s->first_displayed_entry)
6749 next = got_tree_entry_get_next(s->tree,
6750 s->first_displayed_entry);
6751 else
6752 next = got_object_tree_get_first_entry(s->tree);
6754 last = s->last_displayed_entry;
6755 while (next && n++ < maxscroll) {
6756 if (last) {
6757 s->last_displayed_entry = last;
6758 last = got_tree_entry_get_next(s->tree, last);
6760 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6761 s->first_displayed_entry = next;
6762 next = got_tree_entry_get_next(s->tree, next);
6766 return NULL;
6769 static const struct got_error *
6770 tree_entry_path(char **path, struct tog_parent_trees *parents,
6771 struct got_tree_entry *te)
6773 const struct got_error *err = NULL;
6774 struct tog_parent_tree *pt;
6775 size_t len = 2; /* for leading slash and NUL */
6777 TAILQ_FOREACH(pt, parents, entry)
6778 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6779 + 1 /* slash */;
6780 if (te)
6781 len += strlen(got_tree_entry_get_name(te));
6783 *path = calloc(1, len);
6784 if (path == NULL)
6785 return got_error_from_errno("calloc");
6787 (*path)[0] = '/';
6788 pt = TAILQ_LAST(parents, tog_parent_trees);
6789 while (pt) {
6790 const char *name = got_tree_entry_get_name(pt->selected_entry);
6791 if (strlcat(*path, name, len) >= len) {
6792 err = got_error(GOT_ERR_NO_SPACE);
6793 goto done;
6795 if (strlcat(*path, "/", len) >= len) {
6796 err = got_error(GOT_ERR_NO_SPACE);
6797 goto done;
6799 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6801 if (te) {
6802 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6803 err = got_error(GOT_ERR_NO_SPACE);
6804 goto done;
6807 done:
6808 if (err) {
6809 free(*path);
6810 *path = NULL;
6812 return err;
6815 static const struct got_error *
6816 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6817 struct got_tree_entry *te, struct tog_parent_trees *parents,
6818 struct got_object_id *commit_id, struct got_repository *repo)
6820 const struct got_error *err = NULL;
6821 char *path;
6822 struct tog_view *blame_view;
6824 *new_view = NULL;
6826 err = tree_entry_path(&path, parents, te);
6827 if (err)
6828 return err;
6830 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6831 if (blame_view == NULL) {
6832 err = got_error_from_errno("view_open");
6833 goto done;
6836 err = open_blame_view(blame_view, path, commit_id, repo);
6837 if (err) {
6838 if (err->code == GOT_ERR_CANCELLED)
6839 err = NULL;
6840 view_close(blame_view);
6841 } else
6842 *new_view = blame_view;
6843 done:
6844 free(path);
6845 return err;
6848 static const struct got_error *
6849 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6850 struct tog_tree_view_state *s)
6852 struct tog_view *log_view;
6853 const struct got_error *err = NULL;
6854 char *path;
6856 *new_view = NULL;
6858 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6859 if (log_view == NULL)
6860 return got_error_from_errno("view_open");
6862 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6863 if (err)
6864 return err;
6866 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6867 path, 0);
6868 if (err)
6869 view_close(log_view);
6870 else
6871 *new_view = log_view;
6872 free(path);
6873 return err;
6876 static const struct got_error *
6877 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6878 const char *head_ref_name, struct got_repository *repo)
6880 const struct got_error *err = NULL;
6881 char *commit_id_str = NULL;
6882 struct tog_tree_view_state *s = &view->state.tree;
6883 struct got_commit_object *commit = NULL;
6885 TAILQ_INIT(&s->parents);
6886 STAILQ_INIT(&s->colors);
6888 s->commit_id = got_object_id_dup(commit_id);
6889 if (s->commit_id == NULL)
6890 return got_error_from_errno("got_object_id_dup");
6892 err = got_object_open_as_commit(&commit, repo, commit_id);
6893 if (err)
6894 goto done;
6897 * The root is opened here and will be closed when the view is closed.
6898 * Any visited subtrees and their path-wise parents are opened and
6899 * closed on demand.
6901 err = got_object_open_as_tree(&s->root, repo,
6902 got_object_commit_get_tree_id(commit));
6903 if (err)
6904 goto done;
6905 s->tree = s->root;
6907 err = got_object_id_str(&commit_id_str, commit_id);
6908 if (err != NULL)
6909 goto done;
6911 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6912 err = got_error_from_errno("asprintf");
6913 goto done;
6916 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6917 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6918 if (head_ref_name) {
6919 s->head_ref_name = strdup(head_ref_name);
6920 if (s->head_ref_name == NULL) {
6921 err = got_error_from_errno("strdup");
6922 goto done;
6925 s->repo = repo;
6927 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6928 err = add_color(&s->colors, "\\$$",
6929 TOG_COLOR_TREE_SUBMODULE,
6930 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6931 if (err)
6932 goto done;
6933 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6934 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6935 if (err)
6936 goto done;
6937 err = add_color(&s->colors, "/$",
6938 TOG_COLOR_TREE_DIRECTORY,
6939 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6940 if (err)
6941 goto done;
6943 err = add_color(&s->colors, "\\*$",
6944 TOG_COLOR_TREE_EXECUTABLE,
6945 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6946 if (err)
6947 goto done;
6949 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6950 get_color_value("TOG_COLOR_COMMIT"));
6951 if (err)
6952 goto done;
6955 view->show = show_tree_view;
6956 view->input = input_tree_view;
6957 view->close = close_tree_view;
6958 view->search_start = search_start_tree_view;
6959 view->search_next = search_next_tree_view;
6960 done:
6961 free(commit_id_str);
6962 if (commit)
6963 got_object_commit_close(commit);
6964 if (err)
6965 close_tree_view(view);
6966 return err;
6969 static const struct got_error *
6970 close_tree_view(struct tog_view *view)
6972 struct tog_tree_view_state *s = &view->state.tree;
6974 free_colors(&s->colors);
6975 free(s->tree_label);
6976 s->tree_label = NULL;
6977 free(s->commit_id);
6978 s->commit_id = NULL;
6979 free(s->head_ref_name);
6980 s->head_ref_name = NULL;
6981 while (!TAILQ_EMPTY(&s->parents)) {
6982 struct tog_parent_tree *parent;
6983 parent = TAILQ_FIRST(&s->parents);
6984 TAILQ_REMOVE(&s->parents, parent, entry);
6985 if (parent->tree != s->root)
6986 got_object_tree_close(parent->tree);
6987 free(parent);
6990 if (s->tree != NULL && s->tree != s->root)
6991 got_object_tree_close(s->tree);
6992 if (s->root)
6993 got_object_tree_close(s->root);
6994 return NULL;
6997 static const struct got_error *
6998 search_start_tree_view(struct tog_view *view)
7000 struct tog_tree_view_state *s = &view->state.tree;
7002 s->matched_entry = NULL;
7003 return NULL;
7006 static int
7007 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7009 regmatch_t regmatch;
7011 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7012 0) == 0;
7015 static const struct got_error *
7016 search_next_tree_view(struct tog_view *view)
7018 struct tog_tree_view_state *s = &view->state.tree;
7019 struct got_tree_entry *te = NULL;
7021 if (!view->searching) {
7022 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7023 return NULL;
7026 if (s->matched_entry) {
7027 if (view->searching == TOG_SEARCH_FORWARD) {
7028 if (s->selected_entry)
7029 te = got_tree_entry_get_next(s->tree,
7030 s->selected_entry);
7031 else
7032 te = got_object_tree_get_first_entry(s->tree);
7033 } else {
7034 if (s->selected_entry == NULL)
7035 te = got_object_tree_get_last_entry(s->tree);
7036 else
7037 te = got_tree_entry_get_prev(s->tree,
7038 s->selected_entry);
7040 } else {
7041 if (s->selected_entry)
7042 te = s->selected_entry;
7043 else if (view->searching == TOG_SEARCH_FORWARD)
7044 te = got_object_tree_get_first_entry(s->tree);
7045 else
7046 te = got_object_tree_get_last_entry(s->tree);
7049 while (1) {
7050 if (te == NULL) {
7051 if (s->matched_entry == NULL) {
7052 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7053 return NULL;
7055 if (view->searching == TOG_SEARCH_FORWARD)
7056 te = got_object_tree_get_first_entry(s->tree);
7057 else
7058 te = got_object_tree_get_last_entry(s->tree);
7061 if (match_tree_entry(te, &view->regex)) {
7062 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7063 s->matched_entry = te;
7064 break;
7067 if (view->searching == TOG_SEARCH_FORWARD)
7068 te = got_tree_entry_get_next(s->tree, te);
7069 else
7070 te = got_tree_entry_get_prev(s->tree, te);
7073 if (s->matched_entry) {
7074 s->first_displayed_entry = s->matched_entry;
7075 s->selected = 0;
7078 return NULL;
7081 static const struct got_error *
7082 show_tree_view(struct tog_view *view)
7084 const struct got_error *err = NULL;
7085 struct tog_tree_view_state *s = &view->state.tree;
7086 char *parent_path;
7088 err = tree_entry_path(&parent_path, &s->parents, NULL);
7089 if (err)
7090 return err;
7092 err = draw_tree_entries(view, parent_path);
7093 free(parent_path);
7095 view_border(view);
7096 return err;
7099 static const struct got_error *
7100 tree_goto_line(struct tog_view *view, int nlines)
7102 const struct got_error *err = NULL;
7103 struct tog_tree_view_state *s = &view->state.tree;
7104 struct got_tree_entry **fte, **lte, **ste;
7105 int g, last, first = 1, i = 1;
7106 int root = s->tree == s->root;
7107 int off = root ? 1 : 2;
7109 g = view->gline;
7110 view->gline = 0;
7112 if (g == 0)
7113 g = 1;
7114 else if (g > got_object_tree_get_nentries(s->tree))
7115 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7117 fte = &s->first_displayed_entry;
7118 lte = &s->last_displayed_entry;
7119 ste = &s->selected_entry;
7121 if (*fte != NULL) {
7122 first = got_tree_entry_get_index(*fte);
7123 first += off; /* account for ".." */
7125 last = got_tree_entry_get_index(*lte);
7126 last += off;
7128 if (g >= first && g <= last && g - first < nlines) {
7129 s->selected = g - first;
7130 return NULL; /* gline is on the current page */
7133 if (*ste != NULL) {
7134 i = got_tree_entry_get_index(*ste);
7135 i += off;
7138 if (i < g) {
7139 err = tree_scroll_down(view, g - i);
7140 if (err)
7141 return err;
7142 if (got_tree_entry_get_index(*lte) >=
7143 got_object_tree_get_nentries(s->tree) - 1 &&
7144 first + s->selected < g &&
7145 s->selected < s->ndisplayed - 1) {
7146 first = got_tree_entry_get_index(*fte);
7147 first += off;
7148 s->selected = g - first;
7150 } else if (i > g)
7151 tree_scroll_up(s, i - g);
7153 if (g < nlines &&
7154 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7155 s->selected = g - 1;
7157 return NULL;
7160 static const struct got_error *
7161 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7163 const struct got_error *err = NULL;
7164 struct tog_tree_view_state *s = &view->state.tree;
7165 struct got_tree_entry *te;
7166 int n, nscroll = view->nlines - 3;
7168 if (view->gline)
7169 return tree_goto_line(view, nscroll);
7171 switch (ch) {
7172 case 'i':
7173 s->show_ids = !s->show_ids;
7174 view->count = 0;
7175 break;
7176 case 'L':
7177 view->count = 0;
7178 if (!s->selected_entry)
7179 break;
7180 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7181 break;
7182 case 'R':
7183 view->count = 0;
7184 err = view_request_new(new_view, view, TOG_VIEW_REF);
7185 break;
7186 case 'g':
7187 case KEY_HOME:
7188 s->selected = 0;
7189 view->count = 0;
7190 if (s->tree == s->root)
7191 s->first_displayed_entry =
7192 got_object_tree_get_first_entry(s->tree);
7193 else
7194 s->first_displayed_entry = NULL;
7195 break;
7196 case 'G':
7197 case KEY_END: {
7198 int eos = view->nlines - 3;
7200 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7201 --eos; /* border */
7202 s->selected = 0;
7203 view->count = 0;
7204 te = got_object_tree_get_last_entry(s->tree);
7205 for (n = 0; n < eos; n++) {
7206 if (te == NULL) {
7207 if (s->tree != s->root) {
7208 s->first_displayed_entry = NULL;
7209 n++;
7211 break;
7213 s->first_displayed_entry = te;
7214 te = got_tree_entry_get_prev(s->tree, te);
7216 if (n > 0)
7217 s->selected = n - 1;
7218 break;
7220 case 'k':
7221 case KEY_UP:
7222 case CTRL('p'):
7223 if (s->selected > 0) {
7224 s->selected--;
7225 break;
7227 tree_scroll_up(s, 1);
7228 if (s->selected_entry == NULL ||
7229 (s->tree == s->root && s->selected_entry ==
7230 got_object_tree_get_first_entry(s->tree)))
7231 view->count = 0;
7232 break;
7233 case CTRL('u'):
7234 case 'u':
7235 nscroll /= 2;
7236 /* FALL THROUGH */
7237 case KEY_PPAGE:
7238 case CTRL('b'):
7239 case 'b':
7240 if (s->tree == s->root) {
7241 if (got_object_tree_get_first_entry(s->tree) ==
7242 s->first_displayed_entry)
7243 s->selected -= MIN(s->selected, nscroll);
7244 } else {
7245 if (s->first_displayed_entry == NULL)
7246 s->selected -= MIN(s->selected, nscroll);
7248 tree_scroll_up(s, MAX(0, nscroll));
7249 if (s->selected_entry == NULL ||
7250 (s->tree == s->root && s->selected_entry ==
7251 got_object_tree_get_first_entry(s->tree)))
7252 view->count = 0;
7253 break;
7254 case 'j':
7255 case KEY_DOWN:
7256 case CTRL('n'):
7257 if (s->selected < s->ndisplayed - 1) {
7258 s->selected++;
7259 break;
7261 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7262 == NULL) {
7263 /* can't scroll any further */
7264 view->count = 0;
7265 break;
7267 tree_scroll_down(view, 1);
7268 break;
7269 case CTRL('d'):
7270 case 'd':
7271 nscroll /= 2;
7272 /* FALL THROUGH */
7273 case KEY_NPAGE:
7274 case CTRL('f'):
7275 case 'f':
7276 case ' ':
7277 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7278 == NULL) {
7279 /* can't scroll any further; move cursor down */
7280 if (s->selected < s->ndisplayed - 1)
7281 s->selected += MIN(nscroll,
7282 s->ndisplayed - s->selected - 1);
7283 else
7284 view->count = 0;
7285 break;
7287 tree_scroll_down(view, nscroll);
7288 break;
7289 case KEY_ENTER:
7290 case '\r':
7291 case KEY_BACKSPACE:
7292 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7293 struct tog_parent_tree *parent;
7294 /* user selected '..' */
7295 if (s->tree == s->root) {
7296 view->count = 0;
7297 break;
7299 parent = TAILQ_FIRST(&s->parents);
7300 TAILQ_REMOVE(&s->parents, parent,
7301 entry);
7302 got_object_tree_close(s->tree);
7303 s->tree = parent->tree;
7304 s->first_displayed_entry =
7305 parent->first_displayed_entry;
7306 s->selected_entry =
7307 parent->selected_entry;
7308 s->selected = parent->selected;
7309 if (s->selected > view->nlines - 3) {
7310 err = offset_selection_down(view);
7311 if (err)
7312 break;
7314 free(parent);
7315 } else if (S_ISDIR(got_tree_entry_get_mode(
7316 s->selected_entry))) {
7317 struct got_tree_object *subtree;
7318 view->count = 0;
7319 err = got_object_open_as_tree(&subtree, s->repo,
7320 got_tree_entry_get_id(s->selected_entry));
7321 if (err)
7322 break;
7323 err = tree_view_visit_subtree(s, subtree);
7324 if (err) {
7325 got_object_tree_close(subtree);
7326 break;
7328 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7329 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7330 break;
7331 case KEY_RESIZE:
7332 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7333 s->selected = view->nlines - 4;
7334 view->count = 0;
7335 break;
7336 default:
7337 view->count = 0;
7338 break;
7341 return err;
7344 __dead static void
7345 usage_tree(void)
7347 endwin();
7348 fprintf(stderr,
7349 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7350 getprogname());
7351 exit(1);
7354 static const struct got_error *
7355 cmd_tree(int argc, char *argv[])
7357 const struct got_error *error;
7358 struct got_repository *repo = NULL;
7359 struct got_worktree *worktree = NULL;
7360 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7361 struct got_object_id *commit_id = NULL;
7362 struct got_commit_object *commit = NULL;
7363 const char *commit_id_arg = NULL;
7364 char *label = NULL;
7365 struct got_reference *ref = NULL;
7366 const char *head_ref_name = NULL;
7367 int ch;
7368 struct tog_view *view;
7369 int *pack_fds = NULL;
7371 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7372 switch (ch) {
7373 case 'c':
7374 commit_id_arg = optarg;
7375 break;
7376 case 'r':
7377 repo_path = realpath(optarg, NULL);
7378 if (repo_path == NULL)
7379 return got_error_from_errno2("realpath",
7380 optarg);
7381 break;
7382 default:
7383 usage_tree();
7384 /* NOTREACHED */
7388 argc -= optind;
7389 argv += optind;
7391 if (argc > 1)
7392 usage_tree();
7394 error = got_repo_pack_fds_open(&pack_fds);
7395 if (error != NULL)
7396 goto done;
7398 if (repo_path == NULL) {
7399 cwd = getcwd(NULL, 0);
7400 if (cwd == NULL)
7401 return got_error_from_errno("getcwd");
7402 error = got_worktree_open(&worktree, cwd);
7403 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7404 goto done;
7405 if (worktree)
7406 repo_path =
7407 strdup(got_worktree_get_repo_path(worktree));
7408 else
7409 repo_path = strdup(cwd);
7410 if (repo_path == NULL) {
7411 error = got_error_from_errno("strdup");
7412 goto done;
7416 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7417 if (error != NULL)
7418 goto done;
7420 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7421 repo, worktree);
7422 if (error)
7423 goto done;
7425 init_curses();
7427 error = apply_unveil(got_repo_get_path(repo), NULL);
7428 if (error)
7429 goto done;
7431 error = tog_load_refs(repo, 0);
7432 if (error)
7433 goto done;
7435 if (commit_id_arg == NULL) {
7436 error = got_repo_match_object_id(&commit_id, &label,
7437 worktree ? got_worktree_get_head_ref_name(worktree) :
7438 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7439 if (error)
7440 goto done;
7441 head_ref_name = label;
7442 } else {
7443 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7444 if (error == NULL)
7445 head_ref_name = got_ref_get_name(ref);
7446 else if (error->code != GOT_ERR_NOT_REF)
7447 goto done;
7448 error = got_repo_match_object_id(&commit_id, NULL,
7449 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7450 if (error)
7451 goto done;
7454 error = got_object_open_as_commit(&commit, repo, commit_id);
7455 if (error)
7456 goto done;
7458 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7459 if (view == NULL) {
7460 error = got_error_from_errno("view_open");
7461 goto done;
7463 error = open_tree_view(view, commit_id, head_ref_name, repo);
7464 if (error)
7465 goto done;
7466 if (!got_path_is_root_dir(in_repo_path)) {
7467 error = tree_view_walk_path(&view->state.tree, commit,
7468 in_repo_path);
7469 if (error)
7470 goto done;
7473 if (worktree) {
7474 /* Release work tree lock. */
7475 got_worktree_close(worktree);
7476 worktree = NULL;
7478 error = view_loop(view);
7479 done:
7480 free(repo_path);
7481 free(cwd);
7482 free(commit_id);
7483 free(label);
7484 if (ref)
7485 got_ref_close(ref);
7486 if (repo) {
7487 const struct got_error *close_err = got_repo_close(repo);
7488 if (error == NULL)
7489 error = close_err;
7491 if (pack_fds) {
7492 const struct got_error *pack_err =
7493 got_repo_pack_fds_close(pack_fds);
7494 if (error == NULL)
7495 error = pack_err;
7497 tog_free_refs();
7498 return error;
7501 static const struct got_error *
7502 ref_view_load_refs(struct tog_ref_view_state *s)
7504 struct got_reflist_entry *sre;
7505 struct tog_reflist_entry *re;
7507 s->nrefs = 0;
7508 TAILQ_FOREACH(sre, &tog_refs, entry) {
7509 if (strncmp(got_ref_get_name(sre->ref),
7510 "refs/got/", 9) == 0 &&
7511 strncmp(got_ref_get_name(sre->ref),
7512 "refs/got/backup/", 16) != 0)
7513 continue;
7515 re = malloc(sizeof(*re));
7516 if (re == NULL)
7517 return got_error_from_errno("malloc");
7519 re->ref = got_ref_dup(sre->ref);
7520 if (re->ref == NULL)
7521 return got_error_from_errno("got_ref_dup");
7522 re->idx = s->nrefs++;
7523 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7526 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7527 return NULL;
7530 static void
7531 ref_view_free_refs(struct tog_ref_view_state *s)
7533 struct tog_reflist_entry *re;
7535 while (!TAILQ_EMPTY(&s->refs)) {
7536 re = TAILQ_FIRST(&s->refs);
7537 TAILQ_REMOVE(&s->refs, re, entry);
7538 got_ref_close(re->ref);
7539 free(re);
7543 static const struct got_error *
7544 open_ref_view(struct tog_view *view, struct got_repository *repo)
7546 const struct got_error *err = NULL;
7547 struct tog_ref_view_state *s = &view->state.ref;
7549 s->selected_entry = 0;
7550 s->repo = repo;
7552 TAILQ_INIT(&s->refs);
7553 STAILQ_INIT(&s->colors);
7555 err = ref_view_load_refs(s);
7556 if (err)
7557 return err;
7559 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7560 err = add_color(&s->colors, "^refs/heads/",
7561 TOG_COLOR_REFS_HEADS,
7562 get_color_value("TOG_COLOR_REFS_HEADS"));
7563 if (err)
7564 goto done;
7566 err = add_color(&s->colors, "^refs/tags/",
7567 TOG_COLOR_REFS_TAGS,
7568 get_color_value("TOG_COLOR_REFS_TAGS"));
7569 if (err)
7570 goto done;
7572 err = add_color(&s->colors, "^refs/remotes/",
7573 TOG_COLOR_REFS_REMOTES,
7574 get_color_value("TOG_COLOR_REFS_REMOTES"));
7575 if (err)
7576 goto done;
7578 err = add_color(&s->colors, "^refs/got/backup/",
7579 TOG_COLOR_REFS_BACKUP,
7580 get_color_value("TOG_COLOR_REFS_BACKUP"));
7581 if (err)
7582 goto done;
7585 view->show = show_ref_view;
7586 view->input = input_ref_view;
7587 view->close = close_ref_view;
7588 view->search_start = search_start_ref_view;
7589 view->search_next = search_next_ref_view;
7590 done:
7591 if (err)
7592 free_colors(&s->colors);
7593 return err;
7596 static const struct got_error *
7597 close_ref_view(struct tog_view *view)
7599 struct tog_ref_view_state *s = &view->state.ref;
7601 ref_view_free_refs(s);
7602 free_colors(&s->colors);
7604 return NULL;
7607 static const struct got_error *
7608 resolve_reflist_entry(struct got_object_id **commit_id,
7609 struct tog_reflist_entry *re, struct got_repository *repo)
7611 const struct got_error *err = NULL;
7612 struct got_object_id *obj_id;
7613 struct got_tag_object *tag = NULL;
7614 int obj_type;
7616 *commit_id = NULL;
7618 err = got_ref_resolve(&obj_id, repo, re->ref);
7619 if (err)
7620 return err;
7622 err = got_object_get_type(&obj_type, repo, obj_id);
7623 if (err)
7624 goto done;
7626 switch (obj_type) {
7627 case GOT_OBJ_TYPE_COMMIT:
7628 *commit_id = obj_id;
7629 break;
7630 case GOT_OBJ_TYPE_TAG:
7631 err = got_object_open_as_tag(&tag, repo, obj_id);
7632 if (err)
7633 goto done;
7634 free(obj_id);
7635 err = got_object_get_type(&obj_type, repo,
7636 got_object_tag_get_object_id(tag));
7637 if (err)
7638 goto done;
7639 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7640 err = got_error(GOT_ERR_OBJ_TYPE);
7641 goto done;
7643 *commit_id = got_object_id_dup(
7644 got_object_tag_get_object_id(tag));
7645 if (*commit_id == NULL) {
7646 err = got_error_from_errno("got_object_id_dup");
7647 goto done;
7649 break;
7650 default:
7651 err = got_error(GOT_ERR_OBJ_TYPE);
7652 break;
7655 done:
7656 if (tag)
7657 got_object_tag_close(tag);
7658 if (err) {
7659 free(*commit_id);
7660 *commit_id = NULL;
7662 return err;
7665 static const struct got_error *
7666 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7667 struct tog_reflist_entry *re, struct got_repository *repo)
7669 struct tog_view *log_view;
7670 const struct got_error *err = NULL;
7671 struct got_object_id *commit_id = NULL;
7673 *new_view = NULL;
7675 err = resolve_reflist_entry(&commit_id, re, repo);
7676 if (err) {
7677 if (err->code != GOT_ERR_OBJ_TYPE)
7678 return err;
7679 else
7680 return NULL;
7683 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7684 if (log_view == NULL) {
7685 err = got_error_from_errno("view_open");
7686 goto done;
7689 err = open_log_view(log_view, commit_id, repo,
7690 got_ref_get_name(re->ref), "", 0);
7691 done:
7692 if (err)
7693 view_close(log_view);
7694 else
7695 *new_view = log_view;
7696 free(commit_id);
7697 return err;
7700 static void
7701 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7703 struct tog_reflist_entry *re;
7704 int i = 0;
7706 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7707 return;
7709 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7710 while (i++ < maxscroll) {
7711 if (re == NULL)
7712 break;
7713 s->first_displayed_entry = re;
7714 re = TAILQ_PREV(re, tog_reflist_head, entry);
7718 static const struct got_error *
7719 ref_scroll_down(struct tog_view *view, int maxscroll)
7721 struct tog_ref_view_state *s = &view->state.ref;
7722 struct tog_reflist_entry *next, *last;
7723 int n = 0;
7725 if (s->first_displayed_entry)
7726 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7727 else
7728 next = TAILQ_FIRST(&s->refs);
7730 last = s->last_displayed_entry;
7731 while (next && n++ < maxscroll) {
7732 if (last) {
7733 s->last_displayed_entry = last;
7734 last = TAILQ_NEXT(last, entry);
7736 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7737 s->first_displayed_entry = next;
7738 next = TAILQ_NEXT(next, entry);
7742 return NULL;
7745 static const struct got_error *
7746 search_start_ref_view(struct tog_view *view)
7748 struct tog_ref_view_state *s = &view->state.ref;
7750 s->matched_entry = NULL;
7751 return NULL;
7754 static int
7755 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7757 regmatch_t regmatch;
7759 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7760 0) == 0;
7763 static const struct got_error *
7764 search_next_ref_view(struct tog_view *view)
7766 struct tog_ref_view_state *s = &view->state.ref;
7767 struct tog_reflist_entry *re = NULL;
7769 if (!view->searching) {
7770 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7771 return NULL;
7774 if (s->matched_entry) {
7775 if (view->searching == TOG_SEARCH_FORWARD) {
7776 if (s->selected_entry)
7777 re = TAILQ_NEXT(s->selected_entry, entry);
7778 else
7779 re = TAILQ_PREV(s->selected_entry,
7780 tog_reflist_head, entry);
7781 } else {
7782 if (s->selected_entry == NULL)
7783 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7784 else
7785 re = TAILQ_PREV(s->selected_entry,
7786 tog_reflist_head, entry);
7788 } else {
7789 if (s->selected_entry)
7790 re = s->selected_entry;
7791 else if (view->searching == TOG_SEARCH_FORWARD)
7792 re = TAILQ_FIRST(&s->refs);
7793 else
7794 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7797 while (1) {
7798 if (re == NULL) {
7799 if (s->matched_entry == NULL) {
7800 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7801 return NULL;
7803 if (view->searching == TOG_SEARCH_FORWARD)
7804 re = TAILQ_FIRST(&s->refs);
7805 else
7806 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7809 if (match_reflist_entry(re, &view->regex)) {
7810 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7811 s->matched_entry = re;
7812 break;
7815 if (view->searching == TOG_SEARCH_FORWARD)
7816 re = TAILQ_NEXT(re, entry);
7817 else
7818 re = TAILQ_PREV(re, tog_reflist_head, entry);
7821 if (s->matched_entry) {
7822 s->first_displayed_entry = s->matched_entry;
7823 s->selected = 0;
7826 return NULL;
7829 static const struct got_error *
7830 show_ref_view(struct tog_view *view)
7832 const struct got_error *err = NULL;
7833 struct tog_ref_view_state *s = &view->state.ref;
7834 struct tog_reflist_entry *re;
7835 char *line = NULL;
7836 wchar_t *wline;
7837 struct tog_color *tc;
7838 int width, n;
7839 int limit = view->nlines;
7841 werase(view->window);
7843 s->ndisplayed = 0;
7844 if (view_is_hsplit_top(view))
7845 --limit; /* border */
7847 if (limit == 0)
7848 return NULL;
7850 re = s->first_displayed_entry;
7852 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7853 s->nrefs) == -1)
7854 return got_error_from_errno("asprintf");
7856 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7857 if (err) {
7858 free(line);
7859 return err;
7861 if (view_needs_focus_indication(view))
7862 wstandout(view->window);
7863 waddwstr(view->window, wline);
7864 while (width++ < view->ncols)
7865 waddch(view->window, ' ');
7866 if (view_needs_focus_indication(view))
7867 wstandend(view->window);
7868 free(wline);
7869 wline = NULL;
7870 free(line);
7871 line = NULL;
7872 if (--limit <= 0)
7873 return NULL;
7875 n = 0;
7876 while (re && limit > 0) {
7877 char *line = NULL;
7878 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7880 if (s->show_date) {
7881 struct got_commit_object *ci;
7882 struct got_tag_object *tag;
7883 struct got_object_id *id;
7884 struct tm tm;
7885 time_t t;
7887 err = got_ref_resolve(&id, s->repo, re->ref);
7888 if (err)
7889 return err;
7890 err = got_object_open_as_tag(&tag, s->repo, id);
7891 if (err) {
7892 if (err->code != GOT_ERR_OBJ_TYPE) {
7893 free(id);
7894 return err;
7896 err = got_object_open_as_commit(&ci, s->repo,
7897 id);
7898 if (err) {
7899 free(id);
7900 return err;
7902 t = got_object_commit_get_committer_time(ci);
7903 got_object_commit_close(ci);
7904 } else {
7905 t = got_object_tag_get_tagger_time(tag);
7906 got_object_tag_close(tag);
7908 free(id);
7909 if (gmtime_r(&t, &tm) == NULL)
7910 return got_error_from_errno("gmtime_r");
7911 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7912 return got_error(GOT_ERR_NO_SPACE);
7914 if (got_ref_is_symbolic(re->ref)) {
7915 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7916 ymd : "", got_ref_get_name(re->ref),
7917 got_ref_get_symref_target(re->ref)) == -1)
7918 return got_error_from_errno("asprintf");
7919 } else if (s->show_ids) {
7920 struct got_object_id *id;
7921 char *id_str;
7922 err = got_ref_resolve(&id, s->repo, re->ref);
7923 if (err)
7924 return err;
7925 err = got_object_id_str(&id_str, id);
7926 if (err) {
7927 free(id);
7928 return err;
7930 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7931 got_ref_get_name(re->ref), id_str) == -1) {
7932 err = got_error_from_errno("asprintf");
7933 free(id);
7934 free(id_str);
7935 return err;
7937 free(id);
7938 free(id_str);
7939 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7940 got_ref_get_name(re->ref)) == -1)
7941 return got_error_from_errno("asprintf");
7943 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7944 0, 0);
7945 if (err) {
7946 free(line);
7947 return err;
7949 if (n == s->selected) {
7950 if (view->focussed)
7951 wstandout(view->window);
7952 s->selected_entry = re;
7954 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7955 if (tc)
7956 wattr_on(view->window,
7957 COLOR_PAIR(tc->colorpair), NULL);
7958 waddwstr(view->window, wline);
7959 if (tc)
7960 wattr_off(view->window,
7961 COLOR_PAIR(tc->colorpair), NULL);
7962 if (width < view->ncols - 1)
7963 waddch(view->window, '\n');
7964 if (n == s->selected && view->focussed)
7965 wstandend(view->window);
7966 free(line);
7967 free(wline);
7968 wline = NULL;
7969 n++;
7970 s->ndisplayed++;
7971 s->last_displayed_entry = re;
7973 limit--;
7974 re = TAILQ_NEXT(re, entry);
7977 view_border(view);
7978 return err;
7981 static const struct got_error *
7982 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7983 struct tog_reflist_entry *re, struct got_repository *repo)
7985 const struct got_error *err = NULL;
7986 struct got_object_id *commit_id = NULL;
7987 struct tog_view *tree_view;
7989 *new_view = NULL;
7991 err = resolve_reflist_entry(&commit_id, re, repo);
7992 if (err) {
7993 if (err->code != GOT_ERR_OBJ_TYPE)
7994 return err;
7995 else
7996 return NULL;
8000 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8001 if (tree_view == NULL) {
8002 err = got_error_from_errno("view_open");
8003 goto done;
8006 err = open_tree_view(tree_view, commit_id,
8007 got_ref_get_name(re->ref), repo);
8008 if (err)
8009 goto done;
8011 *new_view = tree_view;
8012 done:
8013 free(commit_id);
8014 return err;
8017 static const struct got_error *
8018 ref_goto_line(struct tog_view *view, int nlines)
8020 const struct got_error *err = NULL;
8021 struct tog_ref_view_state *s = &view->state.ref;
8022 int g, idx = s->selected_entry->idx;
8024 g = view->gline;
8025 view->gline = 0;
8027 if (g == 0)
8028 g = 1;
8029 else if (g > s->nrefs)
8030 g = s->nrefs;
8032 if (g >= s->first_displayed_entry->idx + 1 &&
8033 g <= s->last_displayed_entry->idx + 1 &&
8034 g - s->first_displayed_entry->idx - 1 < nlines) {
8035 s->selected = g - s->first_displayed_entry->idx - 1;
8036 return NULL;
8039 if (idx + 1 < g) {
8040 err = ref_scroll_down(view, g - idx - 1);
8041 if (err)
8042 return err;
8043 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8044 s->first_displayed_entry->idx + s->selected < g &&
8045 s->selected < s->ndisplayed - 1)
8046 s->selected = g - s->first_displayed_entry->idx - 1;
8047 } else if (idx + 1 > g)
8048 ref_scroll_up(s, idx - g + 1);
8050 if (g < nlines && s->first_displayed_entry->idx == 0)
8051 s->selected = g - 1;
8053 return NULL;
8057 static const struct got_error *
8058 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8060 const struct got_error *err = NULL;
8061 struct tog_ref_view_state *s = &view->state.ref;
8062 struct tog_reflist_entry *re;
8063 int n, nscroll = view->nlines - 1;
8065 if (view->gline)
8066 return ref_goto_line(view, nscroll);
8068 switch (ch) {
8069 case 'i':
8070 s->show_ids = !s->show_ids;
8071 view->count = 0;
8072 break;
8073 case 'm':
8074 s->show_date = !s->show_date;
8075 view->count = 0;
8076 break;
8077 case 'o':
8078 s->sort_by_date = !s->sort_by_date;
8079 view->count = 0;
8080 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8081 got_ref_cmp_by_commit_timestamp_descending :
8082 tog_ref_cmp_by_name, s->repo);
8083 if (err)
8084 break;
8085 got_reflist_object_id_map_free(tog_refs_idmap);
8086 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8087 &tog_refs, s->repo);
8088 if (err)
8089 break;
8090 ref_view_free_refs(s);
8091 err = ref_view_load_refs(s);
8092 break;
8093 case KEY_ENTER:
8094 case '\r':
8095 view->count = 0;
8096 if (!s->selected_entry)
8097 break;
8098 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8099 break;
8100 case 'T':
8101 view->count = 0;
8102 if (!s->selected_entry)
8103 break;
8104 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8105 break;
8106 case 'g':
8107 case KEY_HOME:
8108 s->selected = 0;
8109 view->count = 0;
8110 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8111 break;
8112 case 'G':
8113 case KEY_END: {
8114 int eos = view->nlines - 1;
8116 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8117 --eos; /* border */
8118 s->selected = 0;
8119 view->count = 0;
8120 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8121 for (n = 0; n < eos; n++) {
8122 if (re == NULL)
8123 break;
8124 s->first_displayed_entry = re;
8125 re = TAILQ_PREV(re, tog_reflist_head, entry);
8127 if (n > 0)
8128 s->selected = n - 1;
8129 break;
8131 case 'k':
8132 case KEY_UP:
8133 case CTRL('p'):
8134 if (s->selected > 0) {
8135 s->selected--;
8136 break;
8138 ref_scroll_up(s, 1);
8139 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8140 view->count = 0;
8141 break;
8142 case CTRL('u'):
8143 case 'u':
8144 nscroll /= 2;
8145 /* FALL THROUGH */
8146 case KEY_PPAGE:
8147 case CTRL('b'):
8148 case 'b':
8149 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8150 s->selected -= MIN(nscroll, s->selected);
8151 ref_scroll_up(s, MAX(0, nscroll));
8152 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8153 view->count = 0;
8154 break;
8155 case 'j':
8156 case KEY_DOWN:
8157 case CTRL('n'):
8158 if (s->selected < s->ndisplayed - 1) {
8159 s->selected++;
8160 break;
8162 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8163 /* can't scroll any further */
8164 view->count = 0;
8165 break;
8167 ref_scroll_down(view, 1);
8168 break;
8169 case CTRL('d'):
8170 case 'd':
8171 nscroll /= 2;
8172 /* FALL THROUGH */
8173 case KEY_NPAGE:
8174 case CTRL('f'):
8175 case 'f':
8176 case ' ':
8177 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8178 /* can't scroll any further; move cursor down */
8179 if (s->selected < s->ndisplayed - 1)
8180 s->selected += MIN(nscroll,
8181 s->ndisplayed - s->selected - 1);
8182 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8183 s->selected += s->ndisplayed - s->selected - 1;
8184 view->count = 0;
8185 break;
8187 ref_scroll_down(view, nscroll);
8188 break;
8189 case CTRL('l'):
8190 view->count = 0;
8191 tog_free_refs();
8192 err = tog_load_refs(s->repo, s->sort_by_date);
8193 if (err)
8194 break;
8195 ref_view_free_refs(s);
8196 err = ref_view_load_refs(s);
8197 break;
8198 case KEY_RESIZE:
8199 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8200 s->selected = view->nlines - 2;
8201 break;
8202 default:
8203 view->count = 0;
8204 break;
8207 return err;
8210 __dead static void
8211 usage_ref(void)
8213 endwin();
8214 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8215 getprogname());
8216 exit(1);
8219 static const struct got_error *
8220 cmd_ref(int argc, char *argv[])
8222 const struct got_error *error;
8223 struct got_repository *repo = NULL;
8224 struct got_worktree *worktree = NULL;
8225 char *cwd = NULL, *repo_path = NULL;
8226 int ch;
8227 struct tog_view *view;
8228 int *pack_fds = NULL;
8230 while ((ch = getopt(argc, argv, "r:")) != -1) {
8231 switch (ch) {
8232 case 'r':
8233 repo_path = realpath(optarg, NULL);
8234 if (repo_path == NULL)
8235 return got_error_from_errno2("realpath",
8236 optarg);
8237 break;
8238 default:
8239 usage_ref();
8240 /* NOTREACHED */
8244 argc -= optind;
8245 argv += optind;
8247 if (argc > 1)
8248 usage_ref();
8250 error = got_repo_pack_fds_open(&pack_fds);
8251 if (error != NULL)
8252 goto done;
8254 if (repo_path == NULL) {
8255 cwd = getcwd(NULL, 0);
8256 if (cwd == NULL)
8257 return got_error_from_errno("getcwd");
8258 error = got_worktree_open(&worktree, cwd);
8259 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8260 goto done;
8261 if (worktree)
8262 repo_path =
8263 strdup(got_worktree_get_repo_path(worktree));
8264 else
8265 repo_path = strdup(cwd);
8266 if (repo_path == NULL) {
8267 error = got_error_from_errno("strdup");
8268 goto done;
8272 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8273 if (error != NULL)
8274 goto done;
8276 init_curses();
8278 error = apply_unveil(got_repo_get_path(repo), NULL);
8279 if (error)
8280 goto done;
8282 error = tog_load_refs(repo, 0);
8283 if (error)
8284 goto done;
8286 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8287 if (view == NULL) {
8288 error = got_error_from_errno("view_open");
8289 goto done;
8292 error = open_ref_view(view, repo);
8293 if (error)
8294 goto done;
8296 if (worktree) {
8297 /* Release work tree lock. */
8298 got_worktree_close(worktree);
8299 worktree = NULL;
8301 error = view_loop(view);
8302 done:
8303 free(repo_path);
8304 free(cwd);
8305 if (repo) {
8306 const struct got_error *close_err = got_repo_close(repo);
8307 if (close_err)
8308 error = close_err;
8310 if (pack_fds) {
8311 const struct got_error *pack_err =
8312 got_repo_pack_fds_close(pack_fds);
8313 if (error == NULL)
8314 error = pack_err;
8316 tog_free_refs();
8317 return error;
8320 static const struct got_error *
8321 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8322 enum tog_view_type request, int y, int x)
8324 const struct got_error *err = NULL;
8326 *new_view = NULL;
8328 switch (request) {
8329 case TOG_VIEW_DIFF:
8330 if (view->type == TOG_VIEW_LOG) {
8331 struct tog_log_view_state *s = &view->state.log;
8333 err = open_diff_view_for_commit(new_view, y, x,
8334 s->selected_entry->commit, s->selected_entry->id,
8335 view, s->repo);
8336 } else
8337 return got_error_msg(GOT_ERR_NOT_IMPL,
8338 "parent/child view pair not supported");
8339 break;
8340 case TOG_VIEW_BLAME:
8341 if (view->type == TOG_VIEW_TREE) {
8342 struct tog_tree_view_state *s = &view->state.tree;
8344 err = blame_tree_entry(new_view, y, x,
8345 s->selected_entry, &s->parents, s->commit_id,
8346 s->repo);
8347 } else
8348 return got_error_msg(GOT_ERR_NOT_IMPL,
8349 "parent/child view pair not supported");
8350 break;
8351 case TOG_VIEW_LOG:
8352 if (view->type == TOG_VIEW_BLAME)
8353 err = log_annotated_line(new_view, y, x,
8354 view->state.blame.repo, view->state.blame.id_to_log);
8355 else if (view->type == TOG_VIEW_TREE)
8356 err = log_selected_tree_entry(new_view, y, x,
8357 &view->state.tree);
8358 else if (view->type == TOG_VIEW_REF)
8359 err = log_ref_entry(new_view, y, x,
8360 view->state.ref.selected_entry,
8361 view->state.ref.repo);
8362 else
8363 return got_error_msg(GOT_ERR_NOT_IMPL,
8364 "parent/child view pair not supported");
8365 break;
8366 case TOG_VIEW_TREE:
8367 if (view->type == TOG_VIEW_LOG)
8368 err = browse_commit_tree(new_view, y, x,
8369 view->state.log.selected_entry,
8370 view->state.log.in_repo_path,
8371 view->state.log.head_ref_name,
8372 view->state.log.repo);
8373 else if (view->type == TOG_VIEW_REF)
8374 err = browse_ref_tree(new_view, y, x,
8375 view->state.ref.selected_entry,
8376 view->state.ref.repo);
8377 else
8378 return got_error_msg(GOT_ERR_NOT_IMPL,
8379 "parent/child view pair not supported");
8380 break;
8381 case TOG_VIEW_REF:
8382 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8383 if (*new_view == NULL)
8384 return got_error_from_errno("view_open");
8385 if (view->type == TOG_VIEW_LOG)
8386 err = open_ref_view(*new_view, view->state.log.repo);
8387 else if (view->type == TOG_VIEW_TREE)
8388 err = open_ref_view(*new_view, view->state.tree.repo);
8389 else
8390 err = got_error_msg(GOT_ERR_NOT_IMPL,
8391 "parent/child view pair not supported");
8392 if (err)
8393 view_close(*new_view);
8394 break;
8395 default:
8396 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
8399 return err;
8403 * If view was scrolled down to move the selected line into view when opening a
8404 * horizontal split, scroll back up when closing the split/toggling fullscreen.
8406 static void
8407 offset_selection_up(struct tog_view *view)
8409 switch (view->type) {
8410 case TOG_VIEW_BLAME: {
8411 struct tog_blame_view_state *s = &view->state.blame;
8412 if (s->first_displayed_line == 1) {
8413 s->selected_line = MAX(s->selected_line - view->offset,
8414 1);
8415 break;
8417 if (s->first_displayed_line > view->offset)
8418 s->first_displayed_line -= view->offset;
8419 else
8420 s->first_displayed_line = 1;
8421 s->selected_line += view->offset;
8422 break;
8424 case TOG_VIEW_LOG:
8425 log_scroll_up(&view->state.log, view->offset);
8426 view->state.log.selected += view->offset;
8427 break;
8428 case TOG_VIEW_REF:
8429 ref_scroll_up(&view->state.ref, view->offset);
8430 view->state.ref.selected += view->offset;
8431 break;
8432 case TOG_VIEW_TREE:
8433 tree_scroll_up(&view->state.tree, view->offset);
8434 view->state.tree.selected += view->offset;
8435 break;
8436 default:
8437 break;
8440 view->offset = 0;
8444 * If the selected line is in the section of screen covered by the bottom split,
8445 * scroll down offset lines to move it into view and index its new position.
8447 static const struct got_error *
8448 offset_selection_down(struct tog_view *view)
8450 const struct got_error *err = NULL;
8451 const struct got_error *(*scrolld)(struct tog_view *, int);
8452 int *selected = NULL;
8453 int header, offset;
8455 switch (view->type) {
8456 case TOG_VIEW_BLAME: {
8457 struct tog_blame_view_state *s = &view->state.blame;
8458 header = 3;
8459 scrolld = NULL;
8460 if (s->selected_line > view->nlines - header) {
8461 offset = abs(view->nlines - s->selected_line - header);
8462 s->first_displayed_line += offset;
8463 s->selected_line -= offset;
8464 view->offset = offset;
8466 break;
8468 case TOG_VIEW_LOG: {
8469 struct tog_log_view_state *s = &view->state.log;
8470 scrolld = &log_scroll_down;
8471 header = view_is_parent_view(view) ? 3 : 2;
8472 selected = &s->selected;
8473 break;
8475 case TOG_VIEW_REF: {
8476 struct tog_ref_view_state *s = &view->state.ref;
8477 scrolld = &ref_scroll_down;
8478 header = 3;
8479 selected = &s->selected;
8480 break;
8482 case TOG_VIEW_TREE: {
8483 struct tog_tree_view_state *s = &view->state.tree;
8484 scrolld = &tree_scroll_down;
8485 header = 5;
8486 selected = &s->selected;
8487 break;
8489 default:
8490 selected = NULL;
8491 scrolld = NULL;
8492 header = 0;
8493 break;
8496 if (selected && *selected > view->nlines - header) {
8497 offset = abs(view->nlines - *selected - header);
8498 view->offset = offset;
8499 if (scrolld && offset) {
8500 err = scrolld(view, offset);
8501 *selected -= offset;
8505 return err;
8508 static void
8509 list_commands(FILE *fp)
8511 size_t i;
8513 fprintf(fp, "commands:");
8514 for (i = 0; i < nitems(tog_commands); i++) {
8515 const struct tog_cmd *cmd = &tog_commands[i];
8516 fprintf(fp, " %s", cmd->name);
8518 fputc('\n', fp);
8521 __dead static void
8522 usage(int hflag, int status)
8524 FILE *fp = (status == 0) ? stdout : stderr;
8526 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8527 getprogname());
8528 if (hflag) {
8529 fprintf(fp, "lazy usage: %s path\n", getprogname());
8530 list_commands(fp);
8532 exit(status);
8535 static char **
8536 make_argv(int argc, ...)
8538 va_list ap;
8539 char **argv;
8540 int i;
8542 va_start(ap, argc);
8544 argv = calloc(argc, sizeof(char *));
8545 if (argv == NULL)
8546 err(1, "calloc");
8547 for (i = 0; i < argc; i++) {
8548 argv[i] = strdup(va_arg(ap, char *));
8549 if (argv[i] == NULL)
8550 err(1, "strdup");
8553 va_end(ap);
8554 return argv;
8558 * Try to convert 'tog path' into a 'tog log path' command.
8559 * The user could simply have mistyped the command rather than knowingly
8560 * provided a path. So check whether argv[0] can in fact be resolved
8561 * to a path in the HEAD commit and print a special error if not.
8562 * This hack is for mpi@ <3
8564 static const struct got_error *
8565 tog_log_with_path(int argc, char *argv[])
8567 const struct got_error *error = NULL, *close_err;
8568 const struct tog_cmd *cmd = NULL;
8569 struct got_repository *repo = NULL;
8570 struct got_worktree *worktree = NULL;
8571 struct got_object_id *commit_id = NULL, *id = NULL;
8572 struct got_commit_object *commit = NULL;
8573 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8574 char *commit_id_str = NULL, **cmd_argv = NULL;
8575 int *pack_fds = NULL;
8577 cwd = getcwd(NULL, 0);
8578 if (cwd == NULL)
8579 return got_error_from_errno("getcwd");
8581 error = got_repo_pack_fds_open(&pack_fds);
8582 if (error != NULL)
8583 goto done;
8585 error = got_worktree_open(&worktree, cwd);
8586 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8587 goto done;
8589 if (worktree)
8590 repo_path = strdup(got_worktree_get_repo_path(worktree));
8591 else
8592 repo_path = strdup(cwd);
8593 if (repo_path == NULL) {
8594 error = got_error_from_errno("strdup");
8595 goto done;
8598 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8599 if (error != NULL)
8600 goto done;
8602 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8603 repo, worktree);
8604 if (error)
8605 goto done;
8607 error = tog_load_refs(repo, 0);
8608 if (error)
8609 goto done;
8610 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8611 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8612 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8613 if (error)
8614 goto done;
8616 if (worktree) {
8617 got_worktree_close(worktree);
8618 worktree = NULL;
8621 error = got_object_open_as_commit(&commit, repo, commit_id);
8622 if (error)
8623 goto done;
8625 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8626 if (error) {
8627 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8628 goto done;
8629 fprintf(stderr, "%s: '%s' is no known command or path\n",
8630 getprogname(), argv[0]);
8631 usage(1, 1);
8632 /* not reached */
8635 error = got_object_id_str(&commit_id_str, commit_id);
8636 if (error)
8637 goto done;
8639 cmd = &tog_commands[0]; /* log */
8640 argc = 4;
8641 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8642 error = cmd->cmd_main(argc, cmd_argv);
8643 done:
8644 if (repo) {
8645 close_err = got_repo_close(repo);
8646 if (error == NULL)
8647 error = close_err;
8649 if (commit)
8650 got_object_commit_close(commit);
8651 if (worktree)
8652 got_worktree_close(worktree);
8653 if (pack_fds) {
8654 const struct got_error *pack_err =
8655 got_repo_pack_fds_close(pack_fds);
8656 if (error == NULL)
8657 error = pack_err;
8659 free(id);
8660 free(commit_id_str);
8661 free(commit_id);
8662 free(cwd);
8663 free(repo_path);
8664 free(in_repo_path);
8665 if (cmd_argv) {
8666 int i;
8667 for (i = 0; i < argc; i++)
8668 free(cmd_argv[i]);
8669 free(cmd_argv);
8671 tog_free_refs();
8672 return error;
8675 int
8676 main(int argc, char *argv[])
8678 const struct got_error *error = NULL;
8679 const struct tog_cmd *cmd = NULL;
8680 int ch, hflag = 0, Vflag = 0;
8681 char **cmd_argv = NULL;
8682 static const struct option longopts[] = {
8683 { "version", no_argument, NULL, 'V' },
8684 { NULL, 0, NULL, 0}
8686 char *diff_algo_str = NULL;
8688 if (!isatty(STDIN_FILENO))
8689 errx(1, "standard input is not a tty");
8691 setlocale(LC_CTYPE, "");
8693 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8694 switch (ch) {
8695 case 'h':
8696 hflag = 1;
8697 break;
8698 case 'V':
8699 Vflag = 1;
8700 break;
8701 default:
8702 usage(hflag, 1);
8703 /* NOTREACHED */
8707 argc -= optind;
8708 argv += optind;
8709 optind = 1;
8710 optreset = 1;
8712 if (Vflag) {
8713 got_version_print_str();
8714 return 0;
8717 #ifndef PROFILE
8718 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8719 NULL) == -1)
8720 err(1, "pledge");
8721 #endif
8723 if (argc == 0) {
8724 if (hflag)
8725 usage(hflag, 0);
8726 /* Build an argument vector which runs a default command. */
8727 cmd = &tog_commands[0];
8728 argc = 1;
8729 cmd_argv = make_argv(argc, cmd->name);
8730 } else {
8731 size_t i;
8733 /* Did the user specify a command? */
8734 for (i = 0; i < nitems(tog_commands); i++) {
8735 if (strncmp(tog_commands[i].name, argv[0],
8736 strlen(argv[0])) == 0) {
8737 cmd = &tog_commands[i];
8738 break;
8743 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8744 if (diff_algo_str) {
8745 if (strcasecmp(diff_algo_str, "patience") == 0)
8746 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8747 if (strcasecmp(diff_algo_str, "myers") == 0)
8748 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8751 if (cmd == NULL) {
8752 if (argc != 1)
8753 usage(0, 1);
8754 /* No command specified; try log with a path */
8755 error = tog_log_with_path(argc, argv);
8756 } else {
8757 if (hflag)
8758 cmd->cmd_usage();
8759 else
8760 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8763 endwin();
8764 putchar('\n');
8765 if (cmd_argv) {
8766 int i;
8767 for (i = 0; i < argc; i++)
8768 free(cmd_argv[i]);
8769 free(cmd_argv);
8772 if (error && error->code != GOT_ERR_CANCELLED)
8773 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8774 return 0;