Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <getopt.h>
33 #include <string.h>
34 #include <err.h>
35 #include <unistd.h>
36 #include <limits.h>
37 #include <wchar.h>
38 #include <time.h>
39 #include <pthread.h>
40 #include <libgen.h>
41 #include <regex.h>
42 #include <sched.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_diff.h"
50 #include "got_opentemp.h"
51 #include "got_utf8.h"
52 #include "got_cancel.h"
53 #include "got_commit_graph.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_path.h"
57 #include "got_worktree.h"
59 #ifndef MIN
60 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
61 #endif
63 #ifndef MAX
64 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
65 #endif
67 #define CTRL(x) ((x) & 0x1f)
69 #ifndef nitems
70 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
71 #endif
73 struct tog_cmd {
74 const char *name;
75 const struct got_error *(*cmd_main)(int, char *[]);
76 void (*cmd_usage)(void);
77 };
79 __dead static void usage(int, int);
80 __dead static void usage_log(void);
81 __dead static void usage_diff(void);
82 __dead static void usage_blame(void);
83 __dead static void usage_tree(void);
84 __dead static void usage_ref(void);
86 static const struct got_error* cmd_log(int, char *[]);
87 static const struct got_error* cmd_diff(int, char *[]);
88 static const struct got_error* cmd_blame(int, char *[]);
89 static const struct got_error* cmd_tree(int, char *[]);
90 static const struct got_error* cmd_ref(int, char *[]);
92 static const struct tog_cmd tog_commands[] = {
93 { "log", cmd_log, usage_log },
94 { "diff", cmd_diff, usage_diff },
95 { "blame", cmd_blame, usage_blame },
96 { "tree", cmd_tree, usage_tree },
97 { "ref", cmd_ref, usage_ref },
98 };
100 enum tog_view_type {
101 TOG_VIEW_DIFF,
102 TOG_VIEW_LOG,
103 TOG_VIEW_BLAME,
104 TOG_VIEW_TREE,
105 TOG_VIEW_REF,
106 TOG_VIEW_HELP
107 };
109 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
110 enum tog_keymap_type {
111 TOG_KEYMAP_KEYS = -2,
112 TOG_KEYMAP_GLOBAL,
113 TOG_KEYMAP_DIFF,
114 TOG_KEYMAP_LOG,
115 TOG_KEYMAP_BLAME,
116 TOG_KEYMAP_TREE,
117 TOG_KEYMAP_REF,
118 TOG_KEYMAP_HELP
119 };
121 enum tog_view_mode {
122 TOG_VIEW_SPLIT_NONE,
123 TOG_VIEW_SPLIT_VERT,
124 TOG_VIEW_SPLIT_HRZN
125 };
127 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
129 #define TOG_EOF_STRING "(END)"
131 struct commit_queue_entry {
132 TAILQ_ENTRY(commit_queue_entry) entry;
133 struct got_object_id *id;
134 struct got_commit_object *commit;
135 int idx;
136 };
137 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
138 struct commit_queue {
139 int ncommits;
140 struct commit_queue_head head;
141 };
143 struct tog_color {
144 STAILQ_ENTRY(tog_color) entry;
145 regex_t regex;
146 short colorpair;
147 };
148 STAILQ_HEAD(tog_colors, tog_color);
150 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
151 static struct got_reflist_object_id_map *tog_refs_idmap;
152 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
154 static const struct got_error *
155 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
156 struct got_reference* re2)
158 const char *name1 = got_ref_get_name(re1);
159 const char *name2 = got_ref_get_name(re2);
160 int isbackup1, isbackup2;
162 /* Sort backup refs towards the bottom of the list. */
163 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
164 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
165 if (!isbackup1 && isbackup2) {
166 *cmp = -1;
167 return NULL;
168 } else if (isbackup1 && !isbackup2) {
169 *cmp = 1;
170 return NULL;
173 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
174 return NULL;
177 static const struct got_error *
178 tog_load_refs(struct got_repository *repo, int sort_by_date)
180 const struct got_error *err;
182 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
183 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
184 repo);
185 if (err)
186 return err;
188 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
189 repo);
192 static void
193 tog_free_refs(void)
195 if (tog_refs_idmap) {
196 got_reflist_object_id_map_free(tog_refs_idmap);
197 tog_refs_idmap = NULL;
199 got_ref_list_free(&tog_refs);
202 static const struct got_error *
203 add_color(struct tog_colors *colors, const char *pattern,
204 int idx, short color)
206 const struct got_error *err = NULL;
207 struct tog_color *tc;
208 int regerr = 0;
210 if (idx < 1 || idx > COLOR_PAIRS - 1)
211 return NULL;
213 init_pair(idx, color, -1);
215 tc = calloc(1, sizeof(*tc));
216 if (tc == NULL)
217 return got_error_from_errno("calloc");
218 regerr = regcomp(&tc->regex, pattern,
219 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
220 if (regerr) {
221 static char regerr_msg[512];
222 static char err_msg[512];
223 regerror(regerr, &tc->regex, regerr_msg,
224 sizeof(regerr_msg));
225 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
226 regerr_msg);
227 err = got_error_msg(GOT_ERR_REGEX, err_msg);
228 free(tc);
229 return err;
231 tc->colorpair = idx;
232 STAILQ_INSERT_HEAD(colors, tc, entry);
233 return NULL;
236 static void
237 free_colors(struct tog_colors *colors)
239 struct tog_color *tc;
241 while (!STAILQ_EMPTY(colors)) {
242 tc = STAILQ_FIRST(colors);
243 STAILQ_REMOVE_HEAD(colors, entry);
244 regfree(&tc->regex);
245 free(tc);
249 static struct tog_color *
250 get_color(struct tog_colors *colors, int colorpair)
252 struct tog_color *tc = NULL;
254 STAILQ_FOREACH(tc, colors, entry) {
255 if (tc->colorpair == colorpair)
256 return tc;
259 return NULL;
262 static int
263 default_color_value(const char *envvar)
265 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
266 return COLOR_MAGENTA;
267 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
268 return COLOR_CYAN;
269 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
270 return COLOR_YELLOW;
271 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
272 return COLOR_GREEN;
273 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
274 return COLOR_MAGENTA;
275 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
276 return COLOR_MAGENTA;
277 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
278 return COLOR_CYAN;
279 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
280 return COLOR_GREEN;
281 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
282 return COLOR_GREEN;
283 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
284 return COLOR_CYAN;
285 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
286 return COLOR_YELLOW;
287 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
288 return COLOR_GREEN;
289 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
290 return COLOR_MAGENTA;
291 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
292 return COLOR_YELLOW;
293 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
294 return COLOR_CYAN;
296 return -1;
299 static int
300 get_color_value(const char *envvar)
302 const char *val = getenv(envvar);
304 if (val == NULL)
305 return default_color_value(envvar);
307 if (strcasecmp(val, "black") == 0)
308 return COLOR_BLACK;
309 if (strcasecmp(val, "red") == 0)
310 return COLOR_RED;
311 if (strcasecmp(val, "green") == 0)
312 return COLOR_GREEN;
313 if (strcasecmp(val, "yellow") == 0)
314 return COLOR_YELLOW;
315 if (strcasecmp(val, "blue") == 0)
316 return COLOR_BLUE;
317 if (strcasecmp(val, "magenta") == 0)
318 return COLOR_MAGENTA;
319 if (strcasecmp(val, "cyan") == 0)
320 return COLOR_CYAN;
321 if (strcasecmp(val, "white") == 0)
322 return COLOR_WHITE;
323 if (strcasecmp(val, "default") == 0)
324 return -1;
326 return default_color_value(envvar);
329 struct tog_diff_view_state {
330 struct got_object_id *id1, *id2;
331 const char *label1, *label2;
332 FILE *f, *f1, *f2;
333 int fd1, fd2;
334 int lineno;
335 int first_displayed_line;
336 int last_displayed_line;
337 int eof;
338 int diff_context;
339 int ignore_whitespace;
340 int force_text_diff;
341 struct got_repository *repo;
342 struct got_diff_line *lines;
343 size_t nlines;
344 int matched_line;
345 int selected_line;
347 /* passed from log or blame view; may be NULL */
348 struct tog_view *parent_view;
349 };
351 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
352 static volatile sig_atomic_t tog_thread_error;
354 struct tog_log_thread_args {
355 pthread_cond_t need_commits;
356 pthread_cond_t commit_loaded;
357 int commits_needed;
358 int load_all;
359 struct got_commit_graph *graph;
360 struct commit_queue *real_commits;
361 const char *in_repo_path;
362 struct got_object_id *start_id;
363 struct got_repository *repo;
364 int *pack_fds;
365 int log_complete;
366 sig_atomic_t *quit;
367 struct commit_queue_entry **first_displayed_entry;
368 struct commit_queue_entry **selected_entry;
369 int *searching;
370 int *search_next_done;
371 regex_t *regex;
372 int *limiting;
373 int limit_match;
374 regex_t *limit_regex;
375 struct commit_queue *limit_commits;
376 };
378 struct tog_log_view_state {
379 struct commit_queue *commits;
380 struct commit_queue_entry *first_displayed_entry;
381 struct commit_queue_entry *last_displayed_entry;
382 struct commit_queue_entry *selected_entry;
383 struct commit_queue real_commits;
384 int selected;
385 char *in_repo_path;
386 char *head_ref_name;
387 int log_branches;
388 struct got_repository *repo;
389 struct got_object_id *start_id;
390 sig_atomic_t quit;
391 pthread_t thread;
392 struct tog_log_thread_args thread_args;
393 struct commit_queue_entry *matched_entry;
394 struct commit_queue_entry *search_entry;
395 struct tog_colors colors;
396 int use_committer;
397 int limit_view;
398 regex_t limit_regex;
399 struct commit_queue limit_commits;
400 };
402 #define TOG_COLOR_DIFF_MINUS 1
403 #define TOG_COLOR_DIFF_PLUS 2
404 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
405 #define TOG_COLOR_DIFF_META 4
406 #define TOG_COLOR_TREE_SUBMODULE 5
407 #define TOG_COLOR_TREE_SYMLINK 6
408 #define TOG_COLOR_TREE_DIRECTORY 7
409 #define TOG_COLOR_TREE_EXECUTABLE 8
410 #define TOG_COLOR_COMMIT 9
411 #define TOG_COLOR_AUTHOR 10
412 #define TOG_COLOR_DATE 11
413 #define TOG_COLOR_REFS_HEADS 12
414 #define TOG_COLOR_REFS_TAGS 13
415 #define TOG_COLOR_REFS_REMOTES 14
416 #define TOG_COLOR_REFS_BACKUP 15
418 struct tog_blame_cb_args {
419 struct tog_blame_line *lines; /* one per line */
420 int nlines;
422 struct tog_view *view;
423 struct got_object_id *commit_id;
424 int *quit;
425 };
427 struct tog_blame_thread_args {
428 const char *path;
429 struct got_repository *repo;
430 struct tog_blame_cb_args *cb_args;
431 int *complete;
432 got_cancel_cb cancel_cb;
433 void *cancel_arg;
434 };
436 struct tog_blame {
437 FILE *f;
438 off_t filesize;
439 struct tog_blame_line *lines;
440 int nlines;
441 off_t *line_offsets;
442 pthread_t thread;
443 struct tog_blame_thread_args thread_args;
444 struct tog_blame_cb_args cb_args;
445 const char *path;
446 int *pack_fds;
447 };
449 struct tog_blame_view_state {
450 int first_displayed_line;
451 int last_displayed_line;
452 int selected_line;
453 int last_diffed_line;
454 int blame_complete;
455 int eof;
456 int done;
457 struct got_object_id_queue blamed_commits;
458 struct got_object_qid *blamed_commit;
459 char *path;
460 struct got_repository *repo;
461 struct got_object_id *commit_id;
462 struct got_object_id *id_to_log;
463 struct tog_blame blame;
464 int matched_line;
465 struct tog_colors colors;
466 };
468 struct tog_parent_tree {
469 TAILQ_ENTRY(tog_parent_tree) entry;
470 struct got_tree_object *tree;
471 struct got_tree_entry *first_displayed_entry;
472 struct got_tree_entry *selected_entry;
473 int selected;
474 };
476 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
478 struct tog_tree_view_state {
479 char *tree_label;
480 struct got_object_id *commit_id;/* commit which this tree belongs to */
481 struct got_tree_object *root; /* the commit's root tree entry */
482 struct got_tree_object *tree; /* currently displayed (sub-)tree */
483 struct got_tree_entry *first_displayed_entry;
484 struct got_tree_entry *last_displayed_entry;
485 struct got_tree_entry *selected_entry;
486 int ndisplayed, selected, show_ids;
487 struct tog_parent_trees parents; /* parent trees of current sub-tree */
488 char *head_ref_name;
489 struct got_repository *repo;
490 struct got_tree_entry *matched_entry;
491 struct tog_colors colors;
492 };
494 struct tog_reflist_entry {
495 TAILQ_ENTRY(tog_reflist_entry) entry;
496 struct got_reference *ref;
497 int idx;
498 };
500 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
502 struct tog_ref_view_state {
503 struct tog_reflist_head refs;
504 struct tog_reflist_entry *first_displayed_entry;
505 struct tog_reflist_entry *last_displayed_entry;
506 struct tog_reflist_entry *selected_entry;
507 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
508 struct got_repository *repo;
509 struct tog_reflist_entry *matched_entry;
510 struct tog_colors colors;
511 };
513 struct tog_help_view_state {
514 FILE *f;
515 off_t *line_offsets;
516 size_t nlines;
517 int lineno;
518 int first_displayed_line;
519 int last_displayed_line;
520 int eof;
521 int matched_line;
522 int selected_line;
523 int all;
524 enum tog_keymap_type type;
525 };
527 #define GENERATE_HELP \
528 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
529 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
530 KEY_("k C-p Up", "Move cursor or page up one line"), \
531 KEY_("j C-n Down", "Move cursor or page down one line"), \
532 KEY_("C-b b PgUp", "Scroll the view up one page"), \
533 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
534 KEY_("C-u u", "Scroll the view up one half page"), \
535 KEY_("C-d d", "Scroll the view down one half page"), \
536 KEY_("g Home", "Go to line N (default: first line)"), \
537 KEY_("G End", "Go to line N (default: last line)"), \
538 KEY_("l Right", "Scroll the view right"), \
539 KEY_("h Left", "Scroll the view left"), \
540 KEY_("$", "Scroll view to the rightmost position"), \
541 KEY_("0", "Scroll view to the leftmost position"), \
542 KEY_("-", "Decrease size of the focussed split"), \
543 KEY_("+", "Increase size of the focussed split"), \
544 KEY_("Tab", "Switch focus between views"), \
545 KEY_("F", "Toggle fullscreen mode"), \
546 KEY_("/", "Open prompt to enter search term"), \
547 KEY_("n", "Find next line/token matching the current search term"), \
548 KEY_("N", "Find previous line/token matching the current search term"),\
549 KEY_("q", "Quit the focussed view; Quit help screen"), \
550 KEY_("Q", "Quit tog"), \
552 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
553 KEY_("< ,", "Move cursor up one commit"), \
554 KEY_("> .", "Move cursor down one commit"), \
555 KEY_("Enter", "Open diff view of the selected commit"), \
556 KEY_("B", "Reload the log view and toggle display of merged commits"), \
557 KEY_("R", "Open ref view of all repository references"), \
558 KEY_("T", "Display tree view of the repository from the selected" \
559 " commit"), \
560 KEY_("@", "Toggle between displaying author and committer name"), \
561 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
562 KEY_("C-g Backspace", "Cancel current search or log operation"), \
563 KEY_("C-l", "Reload the log view with new commits in the repository"), \
565 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
566 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
567 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
568 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
569 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
570 " data"), \
571 KEY_("(", "Go to the previous file in the diff"), \
572 KEY_(")", "Go to the next file in the diff"), \
573 KEY_("{", "Go to the previous hunk in the diff"), \
574 KEY_("}", "Go to the next hunk in the diff"), \
575 KEY_("[", "Decrease the number of context lines"), \
576 KEY_("]", "Increase the number of context lines"), \
577 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
579 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
580 KEY_("Enter", "Display diff view of the selected line's commit"), \
581 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
582 KEY_("L", "Open log view for the currently selected annotated line"), \
583 KEY_("C", "Reload view with the previously blamed commit"), \
584 KEY_("c", "Reload view with the version of the file found in the" \
585 " selected line's commit"), \
586 KEY_("p", "Reload view with the version of the file found in the" \
587 " selected line's parent commit"), \
589 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
590 KEY_("Enter", "Enter selected directory or open blame view of the" \
591 " selected file"), \
592 KEY_("L", "Open log view for the selected entry"), \
593 KEY_("R", "Open ref view of all repository references"), \
594 KEY_("i", "Show object IDs for all tree entries"), \
595 KEY_("Backspace", "Return to the parent directory"), \
597 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
598 KEY_("Enter", "Display log view of the selected reference"), \
599 KEY_("T", "Display tree view of the selected reference"), \
600 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
601 KEY_("m", "Toggle display of last modified date for each reference"), \
602 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
603 KEY_("C-l", "Reload view with all repository references")
605 struct tog_key_map {
606 const char *keys;
607 const char *info;
608 enum tog_keymap_type type;
609 };
611 /*
612 * We implement two types of views: parent views and child views.
614 * The 'Tab' key switches focus between a parent view and its child view.
615 * Child views are shown side-by-side to their parent view, provided
616 * there is enough screen estate.
618 * When a new view is opened from within a parent view, this new view
619 * becomes a child view of the parent view, replacing any existing child.
621 * When a new view is opened from within a child view, this new view
622 * becomes a parent view which will obscure the views below until the
623 * user quits the new parent view by typing 'q'.
625 * This list of views contains parent views only.
626 * Child views are only pointed to by their parent view.
627 */
628 TAILQ_HEAD(tog_view_list_head, tog_view);
630 struct tog_view {
631 TAILQ_ENTRY(tog_view) entry;
632 WINDOW *window;
633 PANEL *panel;
634 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
635 int resized_y, resized_x; /* begin_y/x based on user resizing */
636 int maxx, x; /* max column and current start column */
637 int lines, cols; /* copies of LINES and COLS */
638 int nscrolled, offset; /* lines scrolled and hsplit line offset */
639 int gline, hiline; /* navigate to and highlight this nG line */
640 int ch, count; /* current keymap and count prefix */
641 int resized; /* set when in a resize event */
642 int focussed; /* Only set on one parent or child view at a time. */
643 int dying;
644 struct tog_view *parent;
645 struct tog_view *child;
647 /*
648 * This flag is initially set on parent views when a new child view
649 * is created. It gets toggled when the 'Tab' key switches focus
650 * between parent and child.
651 * The flag indicates whether focus should be passed on to our child
652 * view if this parent view gets picked for focus after another parent
653 * view was closed. This prevents child views from losing focus in such
654 * situations.
655 */
656 int focus_child;
658 enum tog_view_mode mode;
659 /* type-specific state */
660 enum tog_view_type type;
661 union {
662 struct tog_diff_view_state diff;
663 struct tog_log_view_state log;
664 struct tog_blame_view_state blame;
665 struct tog_tree_view_state tree;
666 struct tog_ref_view_state ref;
667 struct tog_help_view_state help;
668 } state;
670 const struct got_error *(*show)(struct tog_view *);
671 const struct got_error *(*input)(struct tog_view **,
672 struct tog_view *, int);
673 const struct got_error *(*reset)(struct tog_view *);
674 const struct got_error *(*resize)(struct tog_view *, int);
675 const struct got_error *(*close)(struct tog_view *);
677 const struct got_error *(*search_start)(struct tog_view *);
678 const struct got_error *(*search_next)(struct tog_view *);
679 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
680 int **, int **, int **, int **);
681 int search_started;
682 int searching;
683 #define TOG_SEARCH_FORWARD 1
684 #define TOG_SEARCH_BACKWARD 2
685 int search_next_done;
686 #define TOG_SEARCH_HAVE_MORE 1
687 #define TOG_SEARCH_NO_MORE 2
688 #define TOG_SEARCH_HAVE_NONE 3
689 regex_t regex;
690 regmatch_t regmatch;
691 };
693 static const struct got_error *open_diff_view(struct tog_view *,
694 struct got_object_id *, struct got_object_id *,
695 const char *, const char *, int, int, int, struct tog_view *,
696 struct got_repository *);
697 static const struct got_error *show_diff_view(struct tog_view *);
698 static const struct got_error *input_diff_view(struct tog_view **,
699 struct tog_view *, int);
700 static const struct got_error *reset_diff_view(struct tog_view *);
701 static const struct got_error* close_diff_view(struct tog_view *);
702 static const struct got_error *search_start_diff_view(struct tog_view *);
703 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
704 size_t *, int **, int **, int **, int **);
705 static const struct got_error *search_next_view_match(struct tog_view *);
707 static const struct got_error *open_log_view(struct tog_view *,
708 struct got_object_id *, struct got_repository *,
709 const char *, const char *, int);
710 static const struct got_error * show_log_view(struct tog_view *);
711 static const struct got_error *input_log_view(struct tog_view **,
712 struct tog_view *, int);
713 static const struct got_error *resize_log_view(struct tog_view *, int);
714 static const struct got_error *close_log_view(struct tog_view *);
715 static const struct got_error *search_start_log_view(struct tog_view *);
716 static const struct got_error *search_next_log_view(struct tog_view *);
718 static const struct got_error *open_blame_view(struct tog_view *, char *,
719 struct got_object_id *, struct got_repository *);
720 static const struct got_error *show_blame_view(struct tog_view *);
721 static const struct got_error *input_blame_view(struct tog_view **,
722 struct tog_view *, int);
723 static const struct got_error *reset_blame_view(struct tog_view *);
724 static const struct got_error *close_blame_view(struct tog_view *);
725 static const struct got_error *search_start_blame_view(struct tog_view *);
726 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
727 size_t *, int **, int **, int **, int **);
729 static const struct got_error *open_tree_view(struct tog_view *,
730 struct got_object_id *, const char *, struct got_repository *);
731 static const struct got_error *show_tree_view(struct tog_view *);
732 static const struct got_error *input_tree_view(struct tog_view **,
733 struct tog_view *, int);
734 static const struct got_error *close_tree_view(struct tog_view *);
735 static const struct got_error *search_start_tree_view(struct tog_view *);
736 static const struct got_error *search_next_tree_view(struct tog_view *);
738 static const struct got_error *open_ref_view(struct tog_view *,
739 struct got_repository *);
740 static const struct got_error *show_ref_view(struct tog_view *);
741 static const struct got_error *input_ref_view(struct tog_view **,
742 struct tog_view *, int);
743 static const struct got_error *close_ref_view(struct tog_view *);
744 static const struct got_error *search_start_ref_view(struct tog_view *);
745 static const struct got_error *search_next_ref_view(struct tog_view *);
747 static const struct got_error *open_help_view(struct tog_view *,
748 struct tog_view *);
749 static const struct got_error *show_help_view(struct tog_view *);
750 static const struct got_error *input_help_view(struct tog_view **,
751 struct tog_view *, int);
752 static const struct got_error *reset_help_view(struct tog_view *);
753 static const struct got_error* close_help_view(struct tog_view *);
754 static const struct got_error *search_start_help_view(struct tog_view *);
755 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
756 size_t *, int **, int **, int **, int **);
758 static volatile sig_atomic_t tog_sigwinch_received;
759 static volatile sig_atomic_t tog_sigpipe_received;
760 static volatile sig_atomic_t tog_sigcont_received;
761 static volatile sig_atomic_t tog_sigint_received;
762 static volatile sig_atomic_t tog_sigterm_received;
764 static void
765 tog_sigwinch(int signo)
767 tog_sigwinch_received = 1;
770 static void
771 tog_sigpipe(int signo)
773 tog_sigpipe_received = 1;
776 static void
777 tog_sigcont(int signo)
779 tog_sigcont_received = 1;
782 static void
783 tog_sigint(int signo)
785 tog_sigint_received = 1;
788 static void
789 tog_sigterm(int signo)
791 tog_sigterm_received = 1;
794 static int
795 tog_fatal_signal_received(void)
797 return (tog_sigpipe_received ||
798 tog_sigint_received || tog_sigterm_received);
801 static const struct got_error *
802 view_close(struct tog_view *view)
804 const struct got_error *err = NULL, *child_err = NULL;
806 if (view->child) {
807 child_err = view_close(view->child);
808 view->child = NULL;
810 if (view->close)
811 err = view->close(view);
812 if (view->panel)
813 del_panel(view->panel);
814 if (view->window)
815 delwin(view->window);
816 free(view);
817 return err ? err : child_err;
820 static struct tog_view *
821 view_open(int nlines, int ncols, int begin_y, int begin_x,
822 enum tog_view_type type)
824 struct tog_view *view = calloc(1, sizeof(*view));
826 if (view == NULL)
827 return NULL;
829 view->type = type;
830 view->lines = LINES;
831 view->cols = COLS;
832 view->nlines = nlines ? nlines : LINES - begin_y;
833 view->ncols = ncols ? ncols : COLS - begin_x;
834 view->begin_y = begin_y;
835 view->begin_x = begin_x;
836 view->window = newwin(nlines, ncols, begin_y, begin_x);
837 if (view->window == NULL) {
838 view_close(view);
839 return NULL;
841 view->panel = new_panel(view->window);
842 if (view->panel == NULL ||
843 set_panel_userptr(view->panel, view) != OK) {
844 view_close(view);
845 return NULL;
848 keypad(view->window, TRUE);
849 return view;
852 static int
853 view_split_begin_x(int begin_x)
855 if (begin_x > 0 || COLS < 120)
856 return 0;
857 return (COLS - MAX(COLS / 2, 80));
860 /* XXX Stub till we decide what to do. */
861 static int
862 view_split_begin_y(int lines)
864 return lines * HSPLIT_SCALE;
867 static const struct got_error *view_resize(struct tog_view *);
869 static const struct got_error *
870 view_splitscreen(struct tog_view *view)
872 const struct got_error *err = NULL;
874 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
875 if (view->resized_y && view->resized_y < view->lines)
876 view->begin_y = view->resized_y;
877 else
878 view->begin_y = view_split_begin_y(view->nlines);
879 view->begin_x = 0;
880 } else if (!view->resized) {
881 if (view->resized_x && view->resized_x < view->cols - 1 &&
882 view->cols > 119)
883 view->begin_x = view->resized_x;
884 else
885 view->begin_x = view_split_begin_x(0);
886 view->begin_y = 0;
888 view->nlines = LINES - view->begin_y;
889 view->ncols = COLS - view->begin_x;
890 view->lines = LINES;
891 view->cols = COLS;
892 err = view_resize(view);
893 if (err)
894 return err;
896 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
897 view->parent->nlines = view->begin_y;
899 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
900 return got_error_from_errno("mvwin");
902 return NULL;
905 static const struct got_error *
906 view_fullscreen(struct tog_view *view)
908 const struct got_error *err = NULL;
910 view->begin_x = 0;
911 view->begin_y = view->resized ? view->begin_y : 0;
912 view->nlines = view->resized ? view->nlines : LINES;
913 view->ncols = COLS;
914 view->lines = LINES;
915 view->cols = COLS;
916 err = view_resize(view);
917 if (err)
918 return err;
920 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
921 return got_error_from_errno("mvwin");
923 return NULL;
926 static int
927 view_is_parent_view(struct tog_view *view)
929 return view->parent == NULL;
932 static int
933 view_is_splitscreen(struct tog_view *view)
935 return view->begin_x > 0 || view->begin_y > 0;
938 static int
939 view_is_fullscreen(struct tog_view *view)
941 return view->nlines == LINES && view->ncols == COLS;
944 static int
945 view_is_hsplit_top(struct tog_view *view)
947 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
948 view_is_splitscreen(view->child);
951 static void
952 view_border(struct tog_view *view)
954 PANEL *panel;
955 const struct tog_view *view_above;
957 if (view->parent)
958 return view_border(view->parent);
960 panel = panel_above(view->panel);
961 if (panel == NULL)
962 return;
964 view_above = panel_userptr(panel);
965 if (view->mode == TOG_VIEW_SPLIT_HRZN)
966 mvwhline(view->window, view_above->begin_y - 1,
967 view->begin_x, got_locale_is_utf8() ?
968 ACS_HLINE : '-', view->ncols);
969 else
970 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
971 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
974 static const struct got_error *view_init_hsplit(struct tog_view *, int);
975 static const struct got_error *request_log_commits(struct tog_view *);
976 static const struct got_error *offset_selection_down(struct tog_view *);
977 static void offset_selection_up(struct tog_view *);
978 static void view_get_split(struct tog_view *, int *, int *);
980 static const struct got_error *
981 view_resize(struct tog_view *view)
983 const struct got_error *err = NULL;
984 int dif, nlines, ncols;
986 dif = LINES - view->lines; /* line difference */
988 if (view->lines > LINES)
989 nlines = view->nlines - (view->lines - LINES);
990 else
991 nlines = view->nlines + (LINES - view->lines);
992 if (view->cols > COLS)
993 ncols = view->ncols - (view->cols - COLS);
994 else
995 ncols = view->ncols + (COLS - view->cols);
997 if (view->child) {
998 int hs = view->child->begin_y;
1000 if (!view_is_fullscreen(view))
1001 view->child->begin_x = view_split_begin_x(view->begin_x);
1002 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1003 view->child->begin_x == 0) {
1004 ncols = COLS;
1006 view_fullscreen(view->child);
1007 if (view->child->focussed)
1008 show_panel(view->child->panel);
1009 else
1010 show_panel(view->panel);
1011 } else {
1012 ncols = view->child->begin_x;
1014 view_splitscreen(view->child);
1015 show_panel(view->child->panel);
1018 * XXX This is ugly and needs to be moved into the above
1019 * logic but "works" for now and my attempts at moving it
1020 * break either 'tab' or 'F' key maps in horizontal splits.
1022 if (hs) {
1023 err = view_splitscreen(view->child);
1024 if (err)
1025 return err;
1026 if (dif < 0) { /* top split decreased */
1027 err = offset_selection_down(view);
1028 if (err)
1029 return err;
1031 view_border(view);
1032 update_panels();
1033 doupdate();
1034 show_panel(view->child->panel);
1035 nlines = view->nlines;
1037 } else if (view->parent == NULL)
1038 ncols = COLS;
1040 if (view->resize && dif > 0) {
1041 err = view->resize(view, dif);
1042 if (err)
1043 return err;
1046 if (wresize(view->window, nlines, ncols) == ERR)
1047 return got_error_from_errno("wresize");
1048 if (replace_panel(view->panel, view->window) == ERR)
1049 return got_error_from_errno("replace_panel");
1050 wclear(view->window);
1052 view->nlines = nlines;
1053 view->ncols = ncols;
1054 view->lines = LINES;
1055 view->cols = COLS;
1057 return NULL;
1060 static const struct got_error *
1061 resize_log_view(struct tog_view *view, int increase)
1063 struct tog_log_view_state *s = &view->state.log;
1064 const struct got_error *err = NULL;
1065 int n = 0;
1067 if (s->selected_entry)
1068 n = s->selected_entry->idx + view->lines - s->selected;
1071 * Request commits to account for the increased
1072 * height so we have enough to populate the view.
1074 if (s->commits->ncommits < n) {
1075 view->nscrolled = n - s->commits->ncommits + increase + 1;
1076 err = request_log_commits(view);
1079 return err;
1082 static void
1083 view_adjust_offset(struct tog_view *view, int n)
1085 if (n == 0)
1086 return;
1088 if (view->parent && view->parent->offset) {
1089 if (view->parent->offset + n >= 0)
1090 view->parent->offset += n;
1091 else
1092 view->parent->offset = 0;
1093 } else if (view->offset) {
1094 if (view->offset - n >= 0)
1095 view->offset -= n;
1096 else
1097 view->offset = 0;
1101 static const struct got_error *
1102 view_resize_split(struct tog_view *view, int resize)
1104 const struct got_error *err = NULL;
1105 struct tog_view *v = NULL;
1107 if (view->parent)
1108 v = view->parent;
1109 else
1110 v = view;
1112 if (!v->child || !view_is_splitscreen(v->child))
1113 return NULL;
1115 v->resized = v->child->resized = resize; /* lock for resize event */
1117 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1118 if (v->child->resized_y)
1119 v->child->begin_y = v->child->resized_y;
1120 if (view->parent)
1121 v->child->begin_y -= resize;
1122 else
1123 v->child->begin_y += resize;
1124 if (v->child->begin_y < 3) {
1125 view->count = 0;
1126 v->child->begin_y = 3;
1127 } else if (v->child->begin_y > LINES - 1) {
1128 view->count = 0;
1129 v->child->begin_y = LINES - 1;
1131 v->ncols = COLS;
1132 v->child->ncols = COLS;
1133 view_adjust_offset(view, resize);
1134 err = view_init_hsplit(v, v->child->begin_y);
1135 if (err)
1136 return err;
1137 v->child->resized_y = v->child->begin_y;
1138 } else {
1139 if (v->child->resized_x)
1140 v->child->begin_x = v->child->resized_x;
1141 if (view->parent)
1142 v->child->begin_x -= resize;
1143 else
1144 v->child->begin_x += resize;
1145 if (v->child->begin_x < 11) {
1146 view->count = 0;
1147 v->child->begin_x = 11;
1148 } else if (v->child->begin_x > COLS - 1) {
1149 view->count = 0;
1150 v->child->begin_x = COLS - 1;
1152 v->child->resized_x = v->child->begin_x;
1155 v->child->mode = v->mode;
1156 v->child->nlines = v->lines - v->child->begin_y;
1157 v->child->ncols = v->cols - v->child->begin_x;
1158 v->focus_child = 1;
1160 err = view_fullscreen(v);
1161 if (err)
1162 return err;
1163 err = view_splitscreen(v->child);
1164 if (err)
1165 return err;
1167 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1168 err = offset_selection_down(v->child);
1169 if (err)
1170 return err;
1173 if (v->resize)
1174 err = v->resize(v, 0);
1175 else if (v->child->resize)
1176 err = v->child->resize(v->child, 0);
1178 v->resized = v->child->resized = 0;
1180 return err;
1183 static void
1184 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1186 struct tog_view *v = src->child ? src->child : src;
1188 dst->resized_x = v->resized_x;
1189 dst->resized_y = v->resized_y;
1192 static const struct got_error *
1193 view_close_child(struct tog_view *view)
1195 const struct got_error *err = NULL;
1197 if (view->child == NULL)
1198 return NULL;
1200 err = view_close(view->child);
1201 view->child = NULL;
1202 return err;
1205 static const struct got_error *
1206 view_set_child(struct tog_view *view, struct tog_view *child)
1208 const struct got_error *err = NULL;
1210 view->child = child;
1211 child->parent = view;
1213 err = view_resize(view);
1214 if (err)
1215 return err;
1217 if (view->child->resized_x || view->child->resized_y)
1218 err = view_resize_split(view, 0);
1220 return err;
1223 static const struct got_error *view_dispatch_request(struct tog_view **,
1224 struct tog_view *, enum tog_view_type, int, int);
1226 static const struct got_error *
1227 view_request_new(struct tog_view **requested, struct tog_view *view,
1228 enum tog_view_type request)
1230 struct tog_view *new_view = NULL;
1231 const struct got_error *err;
1232 int y = 0, x = 0;
1234 *requested = NULL;
1236 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1237 view_get_split(view, &y, &x);
1239 err = view_dispatch_request(&new_view, view, request, y, x);
1240 if (err)
1241 return err;
1243 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1244 request != TOG_VIEW_HELP) {
1245 err = view_init_hsplit(view, y);
1246 if (err)
1247 return err;
1250 view->focussed = 0;
1251 new_view->focussed = 1;
1252 new_view->mode = view->mode;
1253 new_view->nlines = request == TOG_VIEW_HELP ?
1254 view->lines : view->lines - y;
1256 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1257 view_transfer_size(new_view, view);
1258 err = view_close_child(view);
1259 if (err)
1260 return err;
1261 err = view_set_child(view, new_view);
1262 if (err)
1263 return err;
1264 view->focus_child = 1;
1265 } else
1266 *requested = new_view;
1268 return NULL;
1271 static void
1272 tog_resizeterm(void)
1274 int cols, lines;
1275 struct winsize size;
1277 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1278 cols = 80; /* Default */
1279 lines = 24;
1280 } else {
1281 cols = size.ws_col;
1282 lines = size.ws_row;
1284 resize_term(lines, cols);
1287 static const struct got_error *
1288 view_search_start(struct tog_view *view)
1290 const struct got_error *err = NULL;
1291 struct tog_view *v = view;
1292 char pattern[1024];
1293 int ret;
1295 if (view->search_started) {
1296 regfree(&view->regex);
1297 view->searching = 0;
1298 memset(&view->regmatch, 0, sizeof(view->regmatch));
1300 view->search_started = 0;
1302 if (view->nlines < 1)
1303 return NULL;
1305 if (view_is_hsplit_top(view))
1306 v = view->child;
1308 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1309 wclrtoeol(v->window);
1311 nodelay(view->window, FALSE); /* block for search term input */
1312 nocbreak();
1313 echo();
1314 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1315 wrefresh(v->window);
1316 cbreak();
1317 noecho();
1318 nodelay(view->window, TRUE);
1319 if (ret == ERR)
1320 return NULL;
1322 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1323 err = view->search_start(view);
1324 if (err) {
1325 regfree(&view->regex);
1326 return err;
1328 view->search_started = 1;
1329 view->searching = TOG_SEARCH_FORWARD;
1330 view->search_next_done = 0;
1331 view->search_next(view);
1334 return NULL;
1337 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1338 static const struct got_error *
1339 switch_split(struct tog_view *view)
1341 const struct got_error *err = NULL;
1342 struct tog_view *v = NULL;
1344 if (view->parent)
1345 v = view->parent;
1346 else
1347 v = view;
1349 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1350 v->mode = TOG_VIEW_SPLIT_VERT;
1351 else
1352 v->mode = TOG_VIEW_SPLIT_HRZN;
1354 if (!v->child)
1355 return NULL;
1356 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1357 v->mode = TOG_VIEW_SPLIT_NONE;
1359 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1360 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1361 v->child->begin_y = v->child->resized_y;
1362 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1363 v->child->begin_x = v->child->resized_x;
1366 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1367 v->ncols = COLS;
1368 v->child->ncols = COLS;
1369 v->child->nscrolled = LINES - v->child->nlines;
1371 err = view_init_hsplit(v, v->child->begin_y);
1372 if (err)
1373 return err;
1375 v->child->mode = v->mode;
1376 v->child->nlines = v->lines - v->child->begin_y;
1377 v->focus_child = 1;
1379 err = view_fullscreen(v);
1380 if (err)
1381 return err;
1382 err = view_splitscreen(v->child);
1383 if (err)
1384 return err;
1386 if (v->mode == TOG_VIEW_SPLIT_NONE)
1387 v->mode = TOG_VIEW_SPLIT_VERT;
1388 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1389 err = offset_selection_down(v);
1390 if (err)
1391 return err;
1392 err = offset_selection_down(v->child);
1393 if (err)
1394 return err;
1395 } else {
1396 offset_selection_up(v);
1397 offset_selection_up(v->child);
1399 if (v->resize)
1400 err = v->resize(v, 0);
1401 else if (v->child->resize)
1402 err = v->child->resize(v->child, 0);
1404 return err;
1408 * Compute view->count from numeric input. Assign total to view->count and
1409 * return first non-numeric key entered.
1411 static int
1412 get_compound_key(struct tog_view *view, int c)
1414 struct tog_view *v = view;
1415 int x, n = 0;
1417 if (view_is_hsplit_top(view))
1418 v = view->child;
1419 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1420 v = view->parent;
1422 view->count = 0;
1423 cbreak(); /* block for input */
1424 nodelay(view->window, FALSE);
1425 wmove(v->window, v->nlines - 1, 0);
1426 wclrtoeol(v->window);
1427 waddch(v->window, ':');
1429 do {
1430 x = getcurx(v->window);
1431 if (x != ERR && x < view->ncols) {
1432 waddch(v->window, c);
1433 wrefresh(v->window);
1437 * Don't overflow. Max valid request should be the greatest
1438 * between the longest and total lines; cap at 10 million.
1440 if (n >= 9999999)
1441 n = 9999999;
1442 else
1443 n = n * 10 + (c - '0');
1444 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1446 if (c == 'G' || c == 'g') { /* nG key map */
1447 view->gline = view->hiline = n;
1448 n = 0;
1449 c = 0;
1452 /* Massage excessive or inapplicable values at the input handler. */
1453 view->count = n;
1455 return c;
1458 static const struct got_error *
1459 view_input(struct tog_view **new, int *done, struct tog_view *view,
1460 struct tog_view_list_head *views)
1462 const struct got_error *err = NULL;
1463 struct tog_view *v;
1464 int ch, errcode;
1466 *new = NULL;
1468 /* Clear "no matches" indicator. */
1469 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1470 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1471 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1472 view->count = 0;
1475 if (view->searching && !view->search_next_done) {
1476 errcode = pthread_mutex_unlock(&tog_mutex);
1477 if (errcode)
1478 return got_error_set_errno(errcode,
1479 "pthread_mutex_unlock");
1480 sched_yield();
1481 errcode = pthread_mutex_lock(&tog_mutex);
1482 if (errcode)
1483 return got_error_set_errno(errcode,
1484 "pthread_mutex_lock");
1485 view->search_next(view);
1486 return NULL;
1489 /* Allow threads to make progress while we are waiting for input. */
1490 errcode = pthread_mutex_unlock(&tog_mutex);
1491 if (errcode)
1492 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1493 /* If we have an unfinished count, let C-g or backspace abort. */
1494 if (view->count && --view->count) {
1495 cbreak();
1496 nodelay(view->window, TRUE);
1497 ch = wgetch(view->window);
1498 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1499 view->count = 0;
1500 else
1501 ch = view->ch;
1502 } else {
1503 ch = wgetch(view->window);
1504 if (ch >= '1' && ch <= '9')
1505 view->ch = ch = get_compound_key(view, ch);
1507 if (view->hiline && ch != ERR && ch != 0)
1508 view->hiline = 0; /* key pressed, clear line highlight */
1509 nodelay(view->window, TRUE);
1510 errcode = pthread_mutex_lock(&tog_mutex);
1511 if (errcode)
1512 return got_error_set_errno(errcode, "pthread_mutex_lock");
1514 if (tog_sigwinch_received || tog_sigcont_received) {
1515 tog_resizeterm();
1516 tog_sigwinch_received = 0;
1517 tog_sigcont_received = 0;
1518 TAILQ_FOREACH(v, views, entry) {
1519 err = view_resize(v);
1520 if (err)
1521 return err;
1522 err = v->input(new, v, KEY_RESIZE);
1523 if (err)
1524 return err;
1525 if (v->child) {
1526 err = view_resize(v->child);
1527 if (err)
1528 return err;
1529 err = v->child->input(new, v->child,
1530 KEY_RESIZE);
1531 if (err)
1532 return err;
1533 if (v->child->resized_x || v->child->resized_y) {
1534 err = view_resize_split(v, 0);
1535 if (err)
1536 return err;
1542 switch (ch) {
1543 case '?':
1544 case 'H':
1545 case KEY_F(1):
1546 if (view->type == TOG_VIEW_HELP)
1547 err = view->reset(view);
1548 else
1549 err = view_request_new(new, view, TOG_VIEW_HELP);
1550 break;
1551 case '\t':
1552 view->count = 0;
1553 if (view->child) {
1554 view->focussed = 0;
1555 view->child->focussed = 1;
1556 view->focus_child = 1;
1557 } else if (view->parent) {
1558 view->focussed = 0;
1559 view->parent->focussed = 1;
1560 view->parent->focus_child = 0;
1561 if (!view_is_splitscreen(view)) {
1562 if (view->parent->resize) {
1563 err = view->parent->resize(view->parent,
1564 0);
1565 if (err)
1566 return err;
1568 offset_selection_up(view->parent);
1569 err = view_fullscreen(view->parent);
1570 if (err)
1571 return err;
1574 break;
1575 case 'q':
1576 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1577 if (view->parent->resize) {
1578 /* might need more commits to fill fullscreen */
1579 err = view->parent->resize(view->parent, 0);
1580 if (err)
1581 break;
1583 offset_selection_up(view->parent);
1585 err = view->input(new, view, ch);
1586 view->dying = 1;
1587 break;
1588 case 'Q':
1589 *done = 1;
1590 break;
1591 case 'F':
1592 view->count = 0;
1593 if (view_is_parent_view(view)) {
1594 if (view->child == NULL)
1595 break;
1596 if (view_is_splitscreen(view->child)) {
1597 view->focussed = 0;
1598 view->child->focussed = 1;
1599 err = view_fullscreen(view->child);
1600 } else {
1601 err = view_splitscreen(view->child);
1602 if (!err)
1603 err = view_resize_split(view, 0);
1605 if (err)
1606 break;
1607 err = view->child->input(new, view->child,
1608 KEY_RESIZE);
1609 } else {
1610 if (view_is_splitscreen(view)) {
1611 view->parent->focussed = 0;
1612 view->focussed = 1;
1613 err = view_fullscreen(view);
1614 } else {
1615 err = view_splitscreen(view);
1616 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1617 err = view_resize(view->parent);
1618 if (!err)
1619 err = view_resize_split(view, 0);
1621 if (err)
1622 break;
1623 err = view->input(new, view, KEY_RESIZE);
1625 if (err)
1626 break;
1627 if (view->resize) {
1628 err = view->resize(view, 0);
1629 if (err)
1630 break;
1632 if (view->parent)
1633 err = offset_selection_down(view->parent);
1634 if (!err)
1635 err = offset_selection_down(view);
1636 break;
1637 case 'S':
1638 view->count = 0;
1639 err = switch_split(view);
1640 break;
1641 case '-':
1642 err = view_resize_split(view, -1);
1643 break;
1644 case '+':
1645 err = view_resize_split(view, 1);
1646 break;
1647 case KEY_RESIZE:
1648 break;
1649 case '/':
1650 view->count = 0;
1651 if (view->search_start)
1652 view_search_start(view);
1653 else
1654 err = view->input(new, view, ch);
1655 break;
1656 case 'N':
1657 case 'n':
1658 if (view->search_started && view->search_next) {
1659 view->searching = (ch == 'n' ?
1660 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1661 view->search_next_done = 0;
1662 view->search_next(view);
1663 } else
1664 err = view->input(new, view, ch);
1665 break;
1666 case 'A':
1667 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1668 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1669 else
1670 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1671 TAILQ_FOREACH(v, views, entry) {
1672 if (v->reset) {
1673 err = v->reset(v);
1674 if (err)
1675 return err;
1677 if (v->child && v->child->reset) {
1678 err = v->child->reset(v->child);
1679 if (err)
1680 return err;
1683 break;
1684 default:
1685 err = view->input(new, view, ch);
1686 break;
1689 return err;
1692 static int
1693 view_needs_focus_indication(struct tog_view *view)
1695 if (view_is_parent_view(view)) {
1696 if (view->child == NULL || view->child->focussed)
1697 return 0;
1698 if (!view_is_splitscreen(view->child))
1699 return 0;
1700 } else if (!view_is_splitscreen(view))
1701 return 0;
1703 return view->focussed;
1706 static const struct got_error *
1707 view_loop(struct tog_view *view)
1709 const struct got_error *err = NULL;
1710 struct tog_view_list_head views;
1711 struct tog_view *new_view;
1712 char *mode;
1713 int fast_refresh = 10;
1714 int done = 0, errcode;
1716 mode = getenv("TOG_VIEW_SPLIT_MODE");
1717 if (!mode || !(*mode == 'h' || *mode == 'H'))
1718 view->mode = TOG_VIEW_SPLIT_VERT;
1719 else
1720 view->mode = TOG_VIEW_SPLIT_HRZN;
1722 errcode = pthread_mutex_lock(&tog_mutex);
1723 if (errcode)
1724 return got_error_set_errno(errcode, "pthread_mutex_lock");
1726 TAILQ_INIT(&views);
1727 TAILQ_INSERT_HEAD(&views, view, entry);
1729 view->focussed = 1;
1730 err = view->show(view);
1731 if (err)
1732 return err;
1733 update_panels();
1734 doupdate();
1735 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1736 !tog_fatal_signal_received()) {
1737 /* Refresh fast during initialization, then become slower. */
1738 if (fast_refresh && fast_refresh-- == 0)
1739 halfdelay(10); /* switch to once per second */
1741 err = view_input(&new_view, &done, view, &views);
1742 if (err)
1743 break;
1744 if (view->dying) {
1745 struct tog_view *v, *prev = NULL;
1747 if (view_is_parent_view(view))
1748 prev = TAILQ_PREV(view, tog_view_list_head,
1749 entry);
1750 else if (view->parent)
1751 prev = view->parent;
1753 if (view->parent) {
1754 view->parent->child = NULL;
1755 view->parent->focus_child = 0;
1756 /* Restore fullscreen line height. */
1757 view->parent->nlines = view->parent->lines;
1758 err = view_resize(view->parent);
1759 if (err)
1760 break;
1761 /* Make resized splits persist. */
1762 view_transfer_size(view->parent, view);
1763 } else
1764 TAILQ_REMOVE(&views, view, entry);
1766 err = view_close(view);
1767 if (err)
1768 goto done;
1770 view = NULL;
1771 TAILQ_FOREACH(v, &views, entry) {
1772 if (v->focussed)
1773 break;
1775 if (view == NULL && new_view == NULL) {
1776 /* No view has focus. Try to pick one. */
1777 if (prev)
1778 view = prev;
1779 else if (!TAILQ_EMPTY(&views)) {
1780 view = TAILQ_LAST(&views,
1781 tog_view_list_head);
1783 if (view) {
1784 if (view->focus_child) {
1785 view->child->focussed = 1;
1786 view = view->child;
1787 } else
1788 view->focussed = 1;
1792 if (new_view) {
1793 struct tog_view *v, *t;
1794 /* Only allow one parent view per type. */
1795 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1796 if (v->type != new_view->type)
1797 continue;
1798 TAILQ_REMOVE(&views, v, entry);
1799 err = view_close(v);
1800 if (err)
1801 goto done;
1802 break;
1804 TAILQ_INSERT_TAIL(&views, new_view, entry);
1805 view = new_view;
1807 if (view) {
1808 if (view_is_parent_view(view)) {
1809 if (view->child && view->child->focussed)
1810 view = view->child;
1811 } else {
1812 if (view->parent && view->parent->focussed)
1813 view = view->parent;
1815 show_panel(view->panel);
1816 if (view->child && view_is_splitscreen(view->child))
1817 show_panel(view->child->panel);
1818 if (view->parent && view_is_splitscreen(view)) {
1819 err = view->parent->show(view->parent);
1820 if (err)
1821 goto done;
1823 err = view->show(view);
1824 if (err)
1825 goto done;
1826 if (view->child) {
1827 err = view->child->show(view->child);
1828 if (err)
1829 goto done;
1831 update_panels();
1832 doupdate();
1835 done:
1836 while (!TAILQ_EMPTY(&views)) {
1837 const struct got_error *close_err;
1838 view = TAILQ_FIRST(&views);
1839 TAILQ_REMOVE(&views, view, entry);
1840 close_err = view_close(view);
1841 if (close_err && err == NULL)
1842 err = close_err;
1845 errcode = pthread_mutex_unlock(&tog_mutex);
1846 if (errcode && err == NULL)
1847 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1849 return err;
1852 __dead static void
1853 usage_log(void)
1855 endwin();
1856 fprintf(stderr,
1857 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1858 getprogname());
1859 exit(1);
1862 /* Create newly allocated wide-character string equivalent to a byte string. */
1863 static const struct got_error *
1864 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1866 char *vis = NULL;
1867 const struct got_error *err = NULL;
1869 *ws = NULL;
1870 *wlen = mbstowcs(NULL, s, 0);
1871 if (*wlen == (size_t)-1) {
1872 int vislen;
1873 if (errno != EILSEQ)
1874 return got_error_from_errno("mbstowcs");
1876 /* byte string invalid in current encoding; try to "fix" it */
1877 err = got_mbsavis(&vis, &vislen, s);
1878 if (err)
1879 return err;
1880 *wlen = mbstowcs(NULL, vis, 0);
1881 if (*wlen == (size_t)-1) {
1882 err = got_error_from_errno("mbstowcs"); /* give up */
1883 goto done;
1887 *ws = calloc(*wlen + 1, sizeof(**ws));
1888 if (*ws == NULL) {
1889 err = got_error_from_errno("calloc");
1890 goto done;
1893 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1894 err = got_error_from_errno("mbstowcs");
1895 done:
1896 free(vis);
1897 if (err) {
1898 free(*ws);
1899 *ws = NULL;
1900 *wlen = 0;
1902 return err;
1905 static const struct got_error *
1906 expand_tab(char **ptr, const char *src)
1908 char *dst;
1909 size_t len, n, idx = 0, sz = 0;
1911 *ptr = NULL;
1912 n = len = strlen(src);
1913 dst = malloc(n + 1);
1914 if (dst == NULL)
1915 return got_error_from_errno("malloc");
1917 while (idx < len && src[idx]) {
1918 const char c = src[idx];
1920 if (c == '\t') {
1921 size_t nb = TABSIZE - sz % TABSIZE;
1922 char *p;
1924 p = realloc(dst, n + nb);
1925 if (p == NULL) {
1926 free(dst);
1927 return got_error_from_errno("realloc");
1930 dst = p;
1931 n += nb;
1932 memset(dst + sz, ' ', nb);
1933 sz += nb;
1934 } else
1935 dst[sz++] = src[idx];
1936 ++idx;
1939 dst[sz] = '\0';
1940 *ptr = dst;
1941 return NULL;
1945 * Advance at most n columns from wline starting at offset off.
1946 * Return the index to the first character after the span operation.
1947 * Return the combined column width of all spanned wide character in
1948 * *rcol.
1950 static int
1951 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1953 int width, i, cols = 0;
1955 if (n == 0) {
1956 *rcol = cols;
1957 return off;
1960 for (i = off; wline[i] != L'\0'; ++i) {
1961 if (wline[i] == L'\t')
1962 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1963 else
1964 width = wcwidth(wline[i]);
1966 if (width == -1) {
1967 width = 1;
1968 wline[i] = L'.';
1971 if (cols + width > n)
1972 break;
1973 cols += width;
1976 *rcol = cols;
1977 return i;
1981 * Format a line for display, ensuring that it won't overflow a width limit.
1982 * With scrolling, the width returned refers to the scrolled version of the
1983 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1985 static const struct got_error *
1986 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1987 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1989 const struct got_error *err = NULL;
1990 int cols;
1991 wchar_t *wline = NULL;
1992 char *exstr = NULL;
1993 size_t wlen;
1994 int i, scrollx;
1996 *wlinep = NULL;
1997 *widthp = 0;
1999 if (expand) {
2000 err = expand_tab(&exstr, line);
2001 if (err)
2002 return err;
2005 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2006 free(exstr);
2007 if (err)
2008 return err;
2010 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2012 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2013 wline[wlen - 1] = L'\0';
2014 wlen--;
2016 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2017 wline[wlen - 1] = L'\0';
2018 wlen--;
2021 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2022 wline[i] = L'\0';
2024 if (widthp)
2025 *widthp = cols;
2026 if (scrollxp)
2027 *scrollxp = scrollx;
2028 if (err)
2029 free(wline);
2030 else
2031 *wlinep = wline;
2032 return err;
2035 static const struct got_error*
2036 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2037 struct got_object_id *id, struct got_repository *repo)
2039 static const struct got_error *err = NULL;
2040 struct got_reflist_entry *re;
2041 char *s;
2042 const char *name;
2044 *refs_str = NULL;
2046 TAILQ_FOREACH(re, refs, entry) {
2047 struct got_tag_object *tag = NULL;
2048 struct got_object_id *ref_id;
2049 int cmp;
2051 name = got_ref_get_name(re->ref);
2052 if (strcmp(name, GOT_REF_HEAD) == 0)
2053 continue;
2054 if (strncmp(name, "refs/", 5) == 0)
2055 name += 5;
2056 if (strncmp(name, "got/", 4) == 0 &&
2057 strncmp(name, "got/backup/", 11) != 0)
2058 continue;
2059 if (strncmp(name, "heads/", 6) == 0)
2060 name += 6;
2061 if (strncmp(name, "remotes/", 8) == 0) {
2062 name += 8;
2063 s = strstr(name, "/" GOT_REF_HEAD);
2064 if (s != NULL && s[strlen(s)] == '\0')
2065 continue;
2067 err = got_ref_resolve(&ref_id, repo, re->ref);
2068 if (err)
2069 break;
2070 if (strncmp(name, "tags/", 5) == 0) {
2071 err = got_object_open_as_tag(&tag, repo, ref_id);
2072 if (err) {
2073 if (err->code != GOT_ERR_OBJ_TYPE) {
2074 free(ref_id);
2075 break;
2077 /* Ref points at something other than a tag. */
2078 err = NULL;
2079 tag = NULL;
2082 cmp = got_object_id_cmp(tag ?
2083 got_object_tag_get_object_id(tag) : ref_id, id);
2084 free(ref_id);
2085 if (tag)
2086 got_object_tag_close(tag);
2087 if (cmp != 0)
2088 continue;
2089 s = *refs_str;
2090 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2091 s ? ", " : "", name) == -1) {
2092 err = got_error_from_errno("asprintf");
2093 free(s);
2094 *refs_str = NULL;
2095 break;
2097 free(s);
2100 return err;
2103 static const struct got_error *
2104 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2105 int col_tab_align)
2107 char *smallerthan;
2109 smallerthan = strchr(author, '<');
2110 if (smallerthan && smallerthan[1] != '\0')
2111 author = smallerthan + 1;
2112 author[strcspn(author, "@>")] = '\0';
2113 return format_line(wauthor, author_width, NULL, author, 0, limit,
2114 col_tab_align, 0);
2117 static const struct got_error *
2118 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2119 struct got_object_id *id, const size_t date_display_cols,
2120 int author_display_cols)
2122 struct tog_log_view_state *s = &view->state.log;
2123 const struct got_error *err = NULL;
2124 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2125 char *logmsg0 = NULL, *logmsg = NULL;
2126 char *author = NULL;
2127 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2128 int author_width, logmsg_width;
2129 char *newline, *line = NULL;
2130 int col, limit, scrollx;
2131 const int avail = view->ncols;
2132 struct tm tm;
2133 time_t committer_time;
2134 struct tog_color *tc;
2136 committer_time = got_object_commit_get_committer_time(commit);
2137 if (gmtime_r(&committer_time, &tm) == NULL)
2138 return got_error_from_errno("gmtime_r");
2139 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2140 return got_error(GOT_ERR_NO_SPACE);
2142 if (avail <= date_display_cols)
2143 limit = MIN(sizeof(datebuf) - 1, avail);
2144 else
2145 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2146 tc = get_color(&s->colors, TOG_COLOR_DATE);
2147 if (tc)
2148 wattr_on(view->window,
2149 COLOR_PAIR(tc->colorpair), NULL);
2150 waddnstr(view->window, datebuf, limit);
2151 if (tc)
2152 wattr_off(view->window,
2153 COLOR_PAIR(tc->colorpair), NULL);
2154 col = limit;
2155 if (col > avail)
2156 goto done;
2158 if (avail >= 120) {
2159 char *id_str;
2160 err = got_object_id_str(&id_str, id);
2161 if (err)
2162 goto done;
2163 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2164 if (tc)
2165 wattr_on(view->window,
2166 COLOR_PAIR(tc->colorpair), NULL);
2167 wprintw(view->window, "%.8s ", id_str);
2168 if (tc)
2169 wattr_off(view->window,
2170 COLOR_PAIR(tc->colorpair), NULL);
2171 free(id_str);
2172 col += 9;
2173 if (col > avail)
2174 goto done;
2177 if (s->use_committer)
2178 author = strdup(got_object_commit_get_committer(commit));
2179 else
2180 author = strdup(got_object_commit_get_author(commit));
2181 if (author == NULL) {
2182 err = got_error_from_errno("strdup");
2183 goto done;
2185 err = format_author(&wauthor, &author_width, author, avail - col, col);
2186 if (err)
2187 goto done;
2188 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2189 if (tc)
2190 wattr_on(view->window,
2191 COLOR_PAIR(tc->colorpair), NULL);
2192 waddwstr(view->window, wauthor);
2193 col += author_width;
2194 while (col < avail && author_width < author_display_cols + 2) {
2195 waddch(view->window, ' ');
2196 col++;
2197 author_width++;
2199 if (tc)
2200 wattr_off(view->window,
2201 COLOR_PAIR(tc->colorpair), NULL);
2202 if (col > avail)
2203 goto done;
2205 err = got_object_commit_get_logmsg(&logmsg0, commit);
2206 if (err)
2207 goto done;
2208 logmsg = logmsg0;
2209 while (*logmsg == '\n')
2210 logmsg++;
2211 newline = strchr(logmsg, '\n');
2212 if (newline)
2213 *newline = '\0';
2214 limit = avail - col;
2215 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2216 limit--; /* for the border */
2217 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2218 limit, col, 1);
2219 if (err)
2220 goto done;
2221 waddwstr(view->window, &wlogmsg[scrollx]);
2222 col += MAX(logmsg_width, 0);
2223 while (col < avail) {
2224 waddch(view->window, ' ');
2225 col++;
2227 done:
2228 free(logmsg0);
2229 free(wlogmsg);
2230 free(author);
2231 free(wauthor);
2232 free(line);
2233 return err;
2236 static struct commit_queue_entry *
2237 alloc_commit_queue_entry(struct got_commit_object *commit,
2238 struct got_object_id *id)
2240 struct commit_queue_entry *entry;
2241 struct got_object_id *dup;
2243 entry = calloc(1, sizeof(*entry));
2244 if (entry == NULL)
2245 return NULL;
2247 dup = got_object_id_dup(id);
2248 if (dup == NULL) {
2249 free(entry);
2250 return NULL;
2253 entry->id = dup;
2254 entry->commit = commit;
2255 return entry;
2258 static void
2259 pop_commit(struct commit_queue *commits)
2261 struct commit_queue_entry *entry;
2263 entry = TAILQ_FIRST(&commits->head);
2264 TAILQ_REMOVE(&commits->head, entry, entry);
2265 got_object_commit_close(entry->commit);
2266 commits->ncommits--;
2267 free(entry->id);
2268 free(entry);
2271 static void
2272 free_commits(struct commit_queue *commits)
2274 while (!TAILQ_EMPTY(&commits->head))
2275 pop_commit(commits);
2278 static const struct got_error *
2279 match_commit(int *have_match, struct got_object_id *id,
2280 struct got_commit_object *commit, regex_t *regex)
2282 const struct got_error *err = NULL;
2283 regmatch_t regmatch;
2284 char *id_str = NULL, *logmsg = NULL;
2286 *have_match = 0;
2288 err = got_object_id_str(&id_str, id);
2289 if (err)
2290 return err;
2292 err = got_object_commit_get_logmsg(&logmsg, commit);
2293 if (err)
2294 goto done;
2296 if (regexec(regex, got_object_commit_get_author(commit), 1,
2297 &regmatch, 0) == 0 ||
2298 regexec(regex, got_object_commit_get_committer(commit), 1,
2299 &regmatch, 0) == 0 ||
2300 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2301 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2302 *have_match = 1;
2303 done:
2304 free(id_str);
2305 free(logmsg);
2306 return err;
2309 static const struct got_error *
2310 queue_commits(struct tog_log_thread_args *a)
2312 const struct got_error *err = NULL;
2315 * We keep all commits open throughout the lifetime of the log
2316 * view in order to avoid having to re-fetch commits from disk
2317 * while updating the display.
2319 do {
2320 struct got_object_id id;
2321 struct got_commit_object *commit;
2322 struct commit_queue_entry *entry;
2323 int limit_match = 0;
2324 int errcode;
2326 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2327 NULL, NULL);
2328 if (err)
2329 break;
2331 err = got_object_open_as_commit(&commit, a->repo, &id);
2332 if (err)
2333 break;
2334 entry = alloc_commit_queue_entry(commit, &id);
2335 if (entry == NULL) {
2336 err = got_error_from_errno("alloc_commit_queue_entry");
2337 break;
2340 errcode = pthread_mutex_lock(&tog_mutex);
2341 if (errcode) {
2342 err = got_error_set_errno(errcode,
2343 "pthread_mutex_lock");
2344 break;
2347 entry->idx = a->real_commits->ncommits;
2348 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2349 a->real_commits->ncommits++;
2351 if (*a->limiting) {
2352 err = match_commit(&limit_match, &id, commit,
2353 a->limit_regex);
2354 if (err)
2355 break;
2357 if (limit_match) {
2358 struct commit_queue_entry *matched;
2360 matched = alloc_commit_queue_entry(
2361 entry->commit, entry->id);
2362 if (matched == NULL) {
2363 err = got_error_from_errno(
2364 "alloc_commit_queue_entry");
2365 break;
2367 matched->commit = entry->commit;
2368 got_object_commit_retain(entry->commit);
2370 matched->idx = a->limit_commits->ncommits;
2371 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2372 matched, entry);
2373 a->limit_commits->ncommits++;
2377 * This is how we signal log_thread() that we
2378 * have found a match, and that it should be
2379 * counted as a new entry for the view.
2381 a->limit_match = limit_match;
2384 if (*a->searching == TOG_SEARCH_FORWARD &&
2385 !*a->search_next_done) {
2386 int have_match;
2387 err = match_commit(&have_match, &id, commit, a->regex);
2388 if (err)
2389 break;
2391 if (*a->limiting) {
2392 if (limit_match && have_match)
2393 *a->search_next_done =
2394 TOG_SEARCH_HAVE_MORE;
2395 } else if (have_match)
2396 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2399 errcode = pthread_mutex_unlock(&tog_mutex);
2400 if (errcode && err == NULL)
2401 err = got_error_set_errno(errcode,
2402 "pthread_mutex_unlock");
2403 if (err)
2404 break;
2405 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2407 return err;
2410 static void
2411 select_commit(struct tog_log_view_state *s)
2413 struct commit_queue_entry *entry;
2414 int ncommits = 0;
2416 entry = s->first_displayed_entry;
2417 while (entry) {
2418 if (ncommits == s->selected) {
2419 s->selected_entry = entry;
2420 break;
2422 entry = TAILQ_NEXT(entry, entry);
2423 ncommits++;
2427 static const struct got_error *
2428 draw_commits(struct tog_view *view)
2430 const struct got_error *err = NULL;
2431 struct tog_log_view_state *s = &view->state.log;
2432 struct commit_queue_entry *entry = s->selected_entry;
2433 int limit = view->nlines;
2434 int width;
2435 int ncommits, author_cols = 4;
2436 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2437 char *refs_str = NULL;
2438 wchar_t *wline;
2439 struct tog_color *tc;
2440 static const size_t date_display_cols = 12;
2442 if (view_is_hsplit_top(view))
2443 --limit; /* account for border */
2445 if (s->selected_entry &&
2446 !(view->searching && view->search_next_done == 0)) {
2447 struct got_reflist_head *refs;
2448 err = got_object_id_str(&id_str, s->selected_entry->id);
2449 if (err)
2450 return err;
2451 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2452 s->selected_entry->id);
2453 if (refs) {
2454 err = build_refs_str(&refs_str, refs,
2455 s->selected_entry->id, s->repo);
2456 if (err)
2457 goto done;
2461 if (s->thread_args.commits_needed == 0)
2462 halfdelay(10); /* disable fast refresh */
2464 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2465 if (asprintf(&ncommits_str, " [%d/%d] %s",
2466 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2467 (view->searching && !view->search_next_done) ?
2468 "searching..." : "loading...") == -1) {
2469 err = got_error_from_errno("asprintf");
2470 goto done;
2472 } else {
2473 const char *search_str = NULL;
2474 const char *limit_str = NULL;
2476 if (view->searching) {
2477 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2478 search_str = "no more matches";
2479 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2480 search_str = "no matches found";
2481 else if (!view->search_next_done)
2482 search_str = "searching...";
2485 if (s->limit_view && s->commits->ncommits == 0)
2486 limit_str = "no matches found";
2488 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2489 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2490 search_str ? search_str : (refs_str ? refs_str : ""),
2491 limit_str ? limit_str : "") == -1) {
2492 err = got_error_from_errno("asprintf");
2493 goto done;
2497 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2498 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2499 "........................................",
2500 s->in_repo_path, ncommits_str) == -1) {
2501 err = got_error_from_errno("asprintf");
2502 header = NULL;
2503 goto done;
2505 } else if (asprintf(&header, "commit %s%s",
2506 id_str ? id_str : "........................................",
2507 ncommits_str) == -1) {
2508 err = got_error_from_errno("asprintf");
2509 header = NULL;
2510 goto done;
2512 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2513 if (err)
2514 goto done;
2516 werase(view->window);
2518 if (view_needs_focus_indication(view))
2519 wstandout(view->window);
2520 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2521 if (tc)
2522 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2523 waddwstr(view->window, wline);
2524 while (width < view->ncols) {
2525 waddch(view->window, ' ');
2526 width++;
2528 if (tc)
2529 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2530 if (view_needs_focus_indication(view))
2531 wstandend(view->window);
2532 free(wline);
2533 if (limit <= 1)
2534 goto done;
2536 /* Grow author column size if necessary, and set view->maxx. */
2537 entry = s->first_displayed_entry;
2538 ncommits = 0;
2539 view->maxx = 0;
2540 while (entry) {
2541 struct got_commit_object *c = entry->commit;
2542 char *author, *eol, *msg, *msg0;
2543 wchar_t *wauthor, *wmsg;
2544 int width;
2545 if (ncommits >= limit - 1)
2546 break;
2547 if (s->use_committer)
2548 author = strdup(got_object_commit_get_committer(c));
2549 else
2550 author = strdup(got_object_commit_get_author(c));
2551 if (author == NULL) {
2552 err = got_error_from_errno("strdup");
2553 goto done;
2555 err = format_author(&wauthor, &width, author, COLS,
2556 date_display_cols);
2557 if (author_cols < width)
2558 author_cols = width;
2559 free(wauthor);
2560 free(author);
2561 if (err)
2562 goto done;
2563 err = got_object_commit_get_logmsg(&msg0, c);
2564 if (err)
2565 goto done;
2566 msg = msg0;
2567 while (*msg == '\n')
2568 ++msg;
2569 if ((eol = strchr(msg, '\n')))
2570 *eol = '\0';
2571 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2572 date_display_cols + author_cols, 0);
2573 if (err)
2574 goto done;
2575 view->maxx = MAX(view->maxx, width);
2576 free(msg0);
2577 free(wmsg);
2578 ncommits++;
2579 entry = TAILQ_NEXT(entry, entry);
2582 entry = s->first_displayed_entry;
2583 s->last_displayed_entry = s->first_displayed_entry;
2584 ncommits = 0;
2585 while (entry) {
2586 if (ncommits >= limit - 1)
2587 break;
2588 if (ncommits == s->selected)
2589 wstandout(view->window);
2590 err = draw_commit(view, entry->commit, entry->id,
2591 date_display_cols, author_cols);
2592 if (ncommits == s->selected)
2593 wstandend(view->window);
2594 if (err)
2595 goto done;
2596 ncommits++;
2597 s->last_displayed_entry = entry;
2598 entry = TAILQ_NEXT(entry, entry);
2601 view_border(view);
2602 done:
2603 free(id_str);
2604 free(refs_str);
2605 free(ncommits_str);
2606 free(header);
2607 return err;
2610 static void
2611 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2613 struct commit_queue_entry *entry;
2614 int nscrolled = 0;
2616 entry = TAILQ_FIRST(&s->commits->head);
2617 if (s->first_displayed_entry == entry)
2618 return;
2620 entry = s->first_displayed_entry;
2621 while (entry && nscrolled < maxscroll) {
2622 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2623 if (entry) {
2624 s->first_displayed_entry = entry;
2625 nscrolled++;
2630 static const struct got_error *
2631 trigger_log_thread(struct tog_view *view, int wait)
2633 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2634 int errcode;
2636 halfdelay(1); /* fast refresh while loading commits */
2638 while (!ta->log_complete && !tog_thread_error &&
2639 (ta->commits_needed > 0 || ta->load_all)) {
2640 /* Wake the log thread. */
2641 errcode = pthread_cond_signal(&ta->need_commits);
2642 if (errcode)
2643 return got_error_set_errno(errcode,
2644 "pthread_cond_signal");
2647 * The mutex will be released while the view loop waits
2648 * in wgetch(), at which time the log thread will run.
2650 if (!wait)
2651 break;
2653 /* Display progress update in log view. */
2654 show_log_view(view);
2655 update_panels();
2656 doupdate();
2658 /* Wait right here while next commit is being loaded. */
2659 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2660 if (errcode)
2661 return got_error_set_errno(errcode,
2662 "pthread_cond_wait");
2664 /* Display progress update in log view. */
2665 show_log_view(view);
2666 update_panels();
2667 doupdate();
2670 return NULL;
2673 static const struct got_error *
2674 request_log_commits(struct tog_view *view)
2676 struct tog_log_view_state *state = &view->state.log;
2677 const struct got_error *err = NULL;
2679 if (state->thread_args.log_complete)
2680 return NULL;
2682 state->thread_args.commits_needed += view->nscrolled;
2683 err = trigger_log_thread(view, 1);
2684 view->nscrolled = 0;
2686 return err;
2689 static const struct got_error *
2690 log_scroll_down(struct tog_view *view, int maxscroll)
2692 struct tog_log_view_state *s = &view->state.log;
2693 const struct got_error *err = NULL;
2694 struct commit_queue_entry *pentry;
2695 int nscrolled = 0, ncommits_needed;
2697 if (s->last_displayed_entry == NULL)
2698 return NULL;
2700 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2701 if (s->commits->ncommits < ncommits_needed &&
2702 !s->thread_args.log_complete) {
2704 * Ask the log thread for required amount of commits.
2706 s->thread_args.commits_needed +=
2707 ncommits_needed - s->commits->ncommits;
2708 err = trigger_log_thread(view, 1);
2709 if (err)
2710 return err;
2713 do {
2714 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2715 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2716 break;
2718 s->last_displayed_entry = pentry ?
2719 pentry : s->last_displayed_entry;;
2721 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2722 if (pentry == NULL)
2723 break;
2724 s->first_displayed_entry = pentry;
2725 } while (++nscrolled < maxscroll);
2727 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2728 view->nscrolled += nscrolled;
2729 else
2730 view->nscrolled = 0;
2732 return err;
2735 static const struct got_error *
2736 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2737 struct got_commit_object *commit, struct got_object_id *commit_id,
2738 struct tog_view *log_view, struct got_repository *repo)
2740 const struct got_error *err;
2741 struct got_object_qid *parent_id;
2742 struct tog_view *diff_view;
2744 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2745 if (diff_view == NULL)
2746 return got_error_from_errno("view_open");
2748 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2749 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2750 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2751 if (err == NULL)
2752 *new_view = diff_view;
2753 return err;
2756 static const struct got_error *
2757 tree_view_visit_subtree(struct tog_tree_view_state *s,
2758 struct got_tree_object *subtree)
2760 struct tog_parent_tree *parent;
2762 parent = calloc(1, sizeof(*parent));
2763 if (parent == NULL)
2764 return got_error_from_errno("calloc");
2766 parent->tree = s->tree;
2767 parent->first_displayed_entry = s->first_displayed_entry;
2768 parent->selected_entry = s->selected_entry;
2769 parent->selected = s->selected;
2770 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2771 s->tree = subtree;
2772 s->selected = 0;
2773 s->first_displayed_entry = NULL;
2774 return NULL;
2777 static const struct got_error *
2778 tree_view_walk_path(struct tog_tree_view_state *s,
2779 struct got_commit_object *commit, const char *path)
2781 const struct got_error *err = NULL;
2782 struct got_tree_object *tree = NULL;
2783 const char *p;
2784 char *slash, *subpath = NULL;
2786 /* Walk the path and open corresponding tree objects. */
2787 p = path;
2788 while (*p) {
2789 struct got_tree_entry *te;
2790 struct got_object_id *tree_id;
2791 char *te_name;
2793 while (p[0] == '/')
2794 p++;
2796 /* Ensure the correct subtree entry is selected. */
2797 slash = strchr(p, '/');
2798 if (slash == NULL)
2799 te_name = strdup(p);
2800 else
2801 te_name = strndup(p, slash - p);
2802 if (te_name == NULL) {
2803 err = got_error_from_errno("strndup");
2804 break;
2806 te = got_object_tree_find_entry(s->tree, te_name);
2807 if (te == NULL) {
2808 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2809 free(te_name);
2810 break;
2812 free(te_name);
2813 s->first_displayed_entry = s->selected_entry = te;
2815 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2816 break; /* jump to this file's entry */
2818 slash = strchr(p, '/');
2819 if (slash)
2820 subpath = strndup(path, slash - path);
2821 else
2822 subpath = strdup(path);
2823 if (subpath == NULL) {
2824 err = got_error_from_errno("strdup");
2825 break;
2828 err = got_object_id_by_path(&tree_id, s->repo, commit,
2829 subpath);
2830 if (err)
2831 break;
2833 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2834 free(tree_id);
2835 if (err)
2836 break;
2838 err = tree_view_visit_subtree(s, tree);
2839 if (err) {
2840 got_object_tree_close(tree);
2841 break;
2843 if (slash == NULL)
2844 break;
2845 free(subpath);
2846 subpath = NULL;
2847 p = slash;
2850 free(subpath);
2851 return err;
2854 static const struct got_error *
2855 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2856 struct commit_queue_entry *entry, const char *path,
2857 const char *head_ref_name, struct got_repository *repo)
2859 const struct got_error *err = NULL;
2860 struct tog_tree_view_state *s;
2861 struct tog_view *tree_view;
2863 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2864 if (tree_view == NULL)
2865 return got_error_from_errno("view_open");
2867 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2868 if (err)
2869 return err;
2870 s = &tree_view->state.tree;
2872 *new_view = tree_view;
2874 if (got_path_is_root_dir(path))
2875 return NULL;
2877 return tree_view_walk_path(s, entry->commit, path);
2880 static const struct got_error *
2881 block_signals_used_by_main_thread(void)
2883 sigset_t sigset;
2884 int errcode;
2886 if (sigemptyset(&sigset) == -1)
2887 return got_error_from_errno("sigemptyset");
2889 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2890 if (sigaddset(&sigset, SIGWINCH) == -1)
2891 return got_error_from_errno("sigaddset");
2892 if (sigaddset(&sigset, SIGCONT) == -1)
2893 return got_error_from_errno("sigaddset");
2894 if (sigaddset(&sigset, SIGINT) == -1)
2895 return got_error_from_errno("sigaddset");
2896 if (sigaddset(&sigset, SIGTERM) == -1)
2897 return got_error_from_errno("sigaddset");
2899 /* ncurses handles SIGTSTP */
2900 if (sigaddset(&sigset, SIGTSTP) == -1)
2901 return got_error_from_errno("sigaddset");
2903 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2904 if (errcode)
2905 return got_error_set_errno(errcode, "pthread_sigmask");
2907 return NULL;
2910 static void *
2911 log_thread(void *arg)
2913 const struct got_error *err = NULL;
2914 int errcode = 0;
2915 struct tog_log_thread_args *a = arg;
2916 int done = 0;
2919 * Sync startup with main thread such that we begin our
2920 * work once view_input() has released the mutex.
2922 errcode = pthread_mutex_lock(&tog_mutex);
2923 if (errcode) {
2924 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2925 return (void *)err;
2928 err = block_signals_used_by_main_thread();
2929 if (err) {
2930 pthread_mutex_unlock(&tog_mutex);
2931 goto done;
2934 while (!done && !err && !tog_fatal_signal_received()) {
2935 errcode = pthread_mutex_unlock(&tog_mutex);
2936 if (errcode) {
2937 err = got_error_set_errno(errcode,
2938 "pthread_mutex_unlock");
2939 goto done;
2941 err = queue_commits(a);
2942 if (err) {
2943 if (err->code != GOT_ERR_ITER_COMPLETED)
2944 goto done;
2945 err = NULL;
2946 done = 1;
2947 } else if (a->commits_needed > 0 && !a->load_all) {
2948 if (*a->limiting) {
2949 if (a->limit_match)
2950 a->commits_needed--;
2951 } else
2952 a->commits_needed--;
2955 errcode = pthread_mutex_lock(&tog_mutex);
2956 if (errcode) {
2957 err = got_error_set_errno(errcode,
2958 "pthread_mutex_lock");
2959 goto done;
2960 } else if (*a->quit)
2961 done = 1;
2962 else if (*a->limiting && *a->first_displayed_entry == NULL) {
2963 *a->first_displayed_entry =
2964 TAILQ_FIRST(&a->limit_commits->head);
2965 *a->selected_entry = *a->first_displayed_entry;
2966 } else if (*a->first_displayed_entry == NULL) {
2967 *a->first_displayed_entry =
2968 TAILQ_FIRST(&a->real_commits->head);
2969 *a->selected_entry = *a->first_displayed_entry;
2972 errcode = pthread_cond_signal(&a->commit_loaded);
2973 if (errcode) {
2974 err = got_error_set_errno(errcode,
2975 "pthread_cond_signal");
2976 pthread_mutex_unlock(&tog_mutex);
2977 goto done;
2980 if (done)
2981 a->commits_needed = 0;
2982 else {
2983 if (a->commits_needed == 0 && !a->load_all) {
2984 errcode = pthread_cond_wait(&a->need_commits,
2985 &tog_mutex);
2986 if (errcode) {
2987 err = got_error_set_errno(errcode,
2988 "pthread_cond_wait");
2989 pthread_mutex_unlock(&tog_mutex);
2990 goto done;
2992 if (*a->quit)
2993 done = 1;
2997 a->log_complete = 1;
2998 errcode = pthread_mutex_unlock(&tog_mutex);
2999 if (errcode)
3000 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3001 done:
3002 if (err) {
3003 tog_thread_error = 1;
3004 pthread_cond_signal(&a->commit_loaded);
3006 return (void *)err;
3009 static const struct got_error *
3010 stop_log_thread(struct tog_log_view_state *s)
3012 const struct got_error *err = NULL, *thread_err = NULL;
3013 int errcode;
3015 if (s->thread) {
3016 s->quit = 1;
3017 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3018 if (errcode)
3019 return got_error_set_errno(errcode,
3020 "pthread_cond_signal");
3021 errcode = pthread_mutex_unlock(&tog_mutex);
3022 if (errcode)
3023 return got_error_set_errno(errcode,
3024 "pthread_mutex_unlock");
3025 errcode = pthread_join(s->thread, (void **)&thread_err);
3026 if (errcode)
3027 return got_error_set_errno(errcode, "pthread_join");
3028 errcode = pthread_mutex_lock(&tog_mutex);
3029 if (errcode)
3030 return got_error_set_errno(errcode,
3031 "pthread_mutex_lock");
3032 s->thread = NULL;
3035 if (s->thread_args.repo) {
3036 err = got_repo_close(s->thread_args.repo);
3037 s->thread_args.repo = NULL;
3040 if (s->thread_args.pack_fds) {
3041 const struct got_error *pack_err =
3042 got_repo_pack_fds_close(s->thread_args.pack_fds);
3043 if (err == NULL)
3044 err = pack_err;
3045 s->thread_args.pack_fds = NULL;
3048 if (s->thread_args.graph) {
3049 got_commit_graph_close(s->thread_args.graph);
3050 s->thread_args.graph = NULL;
3053 return err ? err : thread_err;
3056 static const struct got_error *
3057 close_log_view(struct tog_view *view)
3059 const struct got_error *err = NULL;
3060 struct tog_log_view_state *s = &view->state.log;
3061 int errcode;
3063 err = stop_log_thread(s);
3065 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3066 if (errcode && err == NULL)
3067 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3069 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3070 if (errcode && err == NULL)
3071 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3073 free_commits(&s->limit_commits);
3074 free_commits(&s->real_commits);
3075 free(s->in_repo_path);
3076 s->in_repo_path = NULL;
3077 free(s->start_id);
3078 s->start_id = NULL;
3079 free(s->head_ref_name);
3080 s->head_ref_name = NULL;
3081 return err;
3085 * We use two queues to implement the limit feature: first consists of
3086 * commits matching the current limit_regex; second is the real queue
3087 * of all known commits (real_commits). When the user starts limiting,
3088 * we swap queues such that all movement and displaying functionality
3089 * works with very slight change.
3091 static const struct got_error *
3092 limit_log_view(struct tog_view *view)
3094 struct tog_log_view_state *s = &view->state.log;
3095 struct commit_queue_entry *entry;
3096 struct tog_view *v = view;
3097 const struct got_error *err = NULL;
3098 char pattern[1024];
3099 int ret;
3101 if (view_is_hsplit_top(view))
3102 v = view->child;
3103 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3104 v = view->parent;
3106 /* Get the pattern */
3107 wmove(v->window, v->nlines - 1, 0);
3108 wclrtoeol(v->window);
3109 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3110 nodelay(v->window, FALSE);
3111 nocbreak();
3112 echo();
3113 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3114 cbreak();
3115 noecho();
3116 nodelay(v->window, TRUE);
3117 if (ret == ERR)
3118 return NULL;
3120 if (*pattern == '\0') {
3122 * Safety measure for the situation where the user
3123 * resets limit without previously limiting anything.
3125 if (!s->limit_view)
3126 return NULL;
3129 * User could have pressed Ctrl+L, which refreshed the
3130 * commit queues, it means we can't save previously
3131 * (before limit took place) displayed entries,
3132 * because they would point to already free'ed memory,
3133 * so we are forced to always select first entry of
3134 * the queue.
3136 s->commits = &s->real_commits;
3137 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3138 s->selected_entry = s->first_displayed_entry;
3139 s->selected = 0;
3140 s->limit_view = 0;
3142 return NULL;
3145 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3146 return NULL;
3148 s->limit_view = 1;
3150 /* Clear the screen while loading limit view */
3151 s->first_displayed_entry = NULL;
3152 s->last_displayed_entry = NULL;
3153 s->selected_entry = NULL;
3154 s->commits = &s->limit_commits;
3156 /* Prepare limit queue for new search */
3157 free_commits(&s->limit_commits);
3158 s->limit_commits.ncommits = 0;
3160 /* First process commits, which are in queue already */
3161 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3162 int have_match = 0;
3164 err = match_commit(&have_match, entry->id,
3165 entry->commit, &s->limit_regex);
3166 if (err)
3167 return err;
3169 if (have_match) {
3170 struct commit_queue_entry *matched;
3172 matched = alloc_commit_queue_entry(entry->commit,
3173 entry->id);
3174 if (matched == NULL) {
3175 err = got_error_from_errno(
3176 "alloc_commit_queue_entry");
3177 break;
3179 matched->commit = entry->commit;
3180 got_object_commit_retain(entry->commit);
3182 matched->idx = s->limit_commits.ncommits;
3183 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3184 matched, entry);
3185 s->limit_commits.ncommits++;
3189 /* Second process all the commits, until we fill the screen */
3190 if (s->limit_commits.ncommits < view->nlines - 1 &&
3191 !s->thread_args.log_complete) {
3192 s->thread_args.commits_needed +=
3193 view->nlines - s->limit_commits.ncommits - 1;
3194 err = trigger_log_thread(view, 1);
3195 if (err)
3196 return err;
3199 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3200 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3201 s->selected = 0;
3203 return NULL;
3206 static const struct got_error *
3207 search_start_log_view(struct tog_view *view)
3209 struct tog_log_view_state *s = &view->state.log;
3211 s->matched_entry = NULL;
3212 s->search_entry = NULL;
3213 return NULL;
3216 static const struct got_error *
3217 search_next_log_view(struct tog_view *view)
3219 const struct got_error *err = NULL;
3220 struct tog_log_view_state *s = &view->state.log;
3221 struct commit_queue_entry *entry;
3223 /* Display progress update in log view. */
3224 show_log_view(view);
3225 update_panels();
3226 doupdate();
3228 if (s->search_entry) {
3229 int errcode, ch;
3230 errcode = pthread_mutex_unlock(&tog_mutex);
3231 if (errcode)
3232 return got_error_set_errno(errcode,
3233 "pthread_mutex_unlock");
3234 ch = wgetch(view->window);
3235 errcode = pthread_mutex_lock(&tog_mutex);
3236 if (errcode)
3237 return got_error_set_errno(errcode,
3238 "pthread_mutex_lock");
3239 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3240 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3241 return NULL;
3243 if (view->searching == TOG_SEARCH_FORWARD)
3244 entry = TAILQ_NEXT(s->search_entry, entry);
3245 else
3246 entry = TAILQ_PREV(s->search_entry,
3247 commit_queue_head, entry);
3248 } else if (s->matched_entry) {
3250 * If the user has moved the cursor after we hit a match,
3251 * the position from where we should continue searching
3252 * might have changed.
3254 if (view->searching == TOG_SEARCH_FORWARD)
3255 entry = TAILQ_NEXT(s->selected_entry, entry);
3256 else
3257 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3258 entry);
3259 } else {
3260 entry = s->selected_entry;
3263 while (1) {
3264 int have_match = 0;
3266 if (entry == NULL) {
3267 if (s->thread_args.log_complete ||
3268 view->searching == TOG_SEARCH_BACKWARD) {
3269 view->search_next_done =
3270 (s->matched_entry == NULL ?
3271 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3272 s->search_entry = NULL;
3273 return NULL;
3276 * Poke the log thread for more commits and return,
3277 * allowing the main loop to make progress. Search
3278 * will resume at s->search_entry once we come back.
3280 s->thread_args.commits_needed++;
3281 return trigger_log_thread(view, 0);
3284 err = match_commit(&have_match, entry->id, entry->commit,
3285 &view->regex);
3286 if (err)
3287 break;
3288 if (have_match) {
3289 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3290 s->matched_entry = entry;
3291 break;
3294 s->search_entry = entry;
3295 if (view->searching == TOG_SEARCH_FORWARD)
3296 entry = TAILQ_NEXT(entry, entry);
3297 else
3298 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3301 if (s->matched_entry) {
3302 int cur = s->selected_entry->idx;
3303 while (cur < s->matched_entry->idx) {
3304 err = input_log_view(NULL, view, KEY_DOWN);
3305 if (err)
3306 return err;
3307 cur++;
3309 while (cur > s->matched_entry->idx) {
3310 err = input_log_view(NULL, view, KEY_UP);
3311 if (err)
3312 return err;
3313 cur--;
3317 s->search_entry = NULL;
3319 return NULL;
3322 static const struct got_error *
3323 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3324 struct got_repository *repo, const char *head_ref_name,
3325 const char *in_repo_path, int log_branches)
3327 const struct got_error *err = NULL;
3328 struct tog_log_view_state *s = &view->state.log;
3329 struct got_repository *thread_repo = NULL;
3330 struct got_commit_graph *thread_graph = NULL;
3331 int errcode;
3333 if (in_repo_path != s->in_repo_path) {
3334 free(s->in_repo_path);
3335 s->in_repo_path = strdup(in_repo_path);
3336 if (s->in_repo_path == NULL)
3337 return got_error_from_errno("strdup");
3340 /* The commit queue only contains commits being displayed. */
3341 TAILQ_INIT(&s->real_commits.head);
3342 s->real_commits.ncommits = 0;
3343 s->commits = &s->real_commits;
3345 TAILQ_INIT(&s->limit_commits.head);
3346 s->limit_view = 0;
3347 s->limit_commits.ncommits = 0;
3349 s->repo = repo;
3350 if (head_ref_name) {
3351 s->head_ref_name = strdup(head_ref_name);
3352 if (s->head_ref_name == NULL) {
3353 err = got_error_from_errno("strdup");
3354 goto done;
3357 s->start_id = got_object_id_dup(start_id);
3358 if (s->start_id == NULL) {
3359 err = got_error_from_errno("got_object_id_dup");
3360 goto done;
3362 s->log_branches = log_branches;
3364 STAILQ_INIT(&s->colors);
3365 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3366 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3367 get_color_value("TOG_COLOR_COMMIT"));
3368 if (err)
3369 goto done;
3370 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3371 get_color_value("TOG_COLOR_AUTHOR"));
3372 if (err) {
3373 free_colors(&s->colors);
3374 goto done;
3376 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3377 get_color_value("TOG_COLOR_DATE"));
3378 if (err) {
3379 free_colors(&s->colors);
3380 goto done;
3384 view->show = show_log_view;
3385 view->input = input_log_view;
3386 view->resize = resize_log_view;
3387 view->close = close_log_view;
3388 view->search_start = search_start_log_view;
3389 view->search_next = search_next_log_view;
3391 if (s->thread_args.pack_fds == NULL) {
3392 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3393 if (err)
3394 goto done;
3396 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3397 s->thread_args.pack_fds);
3398 if (err)
3399 goto done;
3400 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3401 !s->log_branches);
3402 if (err)
3403 goto done;
3404 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3405 s->repo, NULL, NULL);
3406 if (err)
3407 goto done;
3409 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3410 if (errcode) {
3411 err = got_error_set_errno(errcode, "pthread_cond_init");
3412 goto done;
3414 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3415 if (errcode) {
3416 err = got_error_set_errno(errcode, "pthread_cond_init");
3417 goto done;
3420 s->thread_args.commits_needed = view->nlines;
3421 s->thread_args.graph = thread_graph;
3422 s->thread_args.real_commits = &s->real_commits;
3423 s->thread_args.limit_commits = &s->limit_commits;
3424 s->thread_args.in_repo_path = s->in_repo_path;
3425 s->thread_args.start_id = s->start_id;
3426 s->thread_args.repo = thread_repo;
3427 s->thread_args.log_complete = 0;
3428 s->thread_args.quit = &s->quit;
3429 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3430 s->thread_args.selected_entry = &s->selected_entry;
3431 s->thread_args.searching = &view->searching;
3432 s->thread_args.search_next_done = &view->search_next_done;
3433 s->thread_args.regex = &view->regex;
3434 s->thread_args.limiting = &s->limit_view;
3435 s->thread_args.limit_regex = &s->limit_regex;
3436 s->thread_args.limit_commits = &s->limit_commits;
3437 done:
3438 if (err)
3439 close_log_view(view);
3440 return err;
3443 static const struct got_error *
3444 show_log_view(struct tog_view *view)
3446 const struct got_error *err;
3447 struct tog_log_view_state *s = &view->state.log;
3449 if (s->thread == NULL) {
3450 int errcode = pthread_create(&s->thread, NULL, log_thread,
3451 &s->thread_args);
3452 if (errcode)
3453 return got_error_set_errno(errcode, "pthread_create");
3454 if (s->thread_args.commits_needed > 0) {
3455 err = trigger_log_thread(view, 1);
3456 if (err)
3457 return err;
3461 return draw_commits(view);
3464 static void
3465 log_move_cursor_up(struct tog_view *view, int page, int home)
3467 struct tog_log_view_state *s = &view->state.log;
3469 if (s->first_displayed_entry == NULL)
3470 return;
3471 if (s->selected_entry->idx == 0)
3472 view->count = 0;
3474 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3475 || home)
3476 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3478 if (!page && !home && s->selected > 0)
3479 --s->selected;
3480 else
3481 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3483 select_commit(s);
3484 return;
3487 static const struct got_error *
3488 log_move_cursor_down(struct tog_view *view, int page)
3490 struct tog_log_view_state *s = &view->state.log;
3491 const struct got_error *err = NULL;
3492 int eos = view->nlines - 2;
3494 if (s->first_displayed_entry == NULL)
3495 return NULL;
3497 if (s->thread_args.log_complete &&
3498 s->selected_entry->idx >= s->commits->ncommits - 1)
3499 return NULL;
3501 if (view_is_hsplit_top(view))
3502 --eos; /* border consumes the last line */
3504 if (!page) {
3505 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3506 ++s->selected;
3507 else
3508 err = log_scroll_down(view, 1);
3509 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3510 struct commit_queue_entry *entry;
3511 int n;
3513 s->selected = 0;
3514 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3515 s->last_displayed_entry = entry;
3516 for (n = 0; n <= eos; n++) {
3517 if (entry == NULL)
3518 break;
3519 s->first_displayed_entry = entry;
3520 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3522 if (n > 0)
3523 s->selected = n - 1;
3524 } else {
3525 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3526 s->thread_args.log_complete)
3527 s->selected += MIN(page,
3528 s->commits->ncommits - s->selected_entry->idx - 1);
3529 else
3530 err = log_scroll_down(view, page);
3532 if (err)
3533 return err;
3536 * We might necessarily overshoot in horizontal
3537 * splits; if so, select the last displayed commit.
3539 if (s->first_displayed_entry && s->last_displayed_entry) {
3540 s->selected = MIN(s->selected,
3541 s->last_displayed_entry->idx -
3542 s->first_displayed_entry->idx);
3545 select_commit(s);
3547 if (s->thread_args.log_complete &&
3548 s->selected_entry->idx == s->commits->ncommits - 1)
3549 view->count = 0;
3551 return NULL;
3554 static void
3555 view_get_split(struct tog_view *view, int *y, int *x)
3557 *x = 0;
3558 *y = 0;
3560 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3561 if (view->child && view->child->resized_y)
3562 *y = view->child->resized_y;
3563 else if (view->resized_y)
3564 *y = view->resized_y;
3565 else
3566 *y = view_split_begin_y(view->lines);
3567 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3568 if (view->child && view->child->resized_x)
3569 *x = view->child->resized_x;
3570 else if (view->resized_x)
3571 *x = view->resized_x;
3572 else
3573 *x = view_split_begin_x(view->begin_x);
3577 /* Split view horizontally at y and offset view->state->selected line. */
3578 static const struct got_error *
3579 view_init_hsplit(struct tog_view *view, int y)
3581 const struct got_error *err = NULL;
3583 view->nlines = y;
3584 view->ncols = COLS;
3585 err = view_resize(view);
3586 if (err)
3587 return err;
3589 err = offset_selection_down(view);
3591 return err;
3594 static const struct got_error *
3595 log_goto_line(struct tog_view *view, int nlines)
3597 const struct got_error *err = NULL;
3598 struct tog_log_view_state *s = &view->state.log;
3599 int g, idx = s->selected_entry->idx;
3601 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3602 return NULL;
3604 g = view->gline;
3605 view->gline = 0;
3607 if (g >= s->first_displayed_entry->idx + 1 &&
3608 g <= s->last_displayed_entry->idx + 1 &&
3609 g - s->first_displayed_entry->idx - 1 < nlines) {
3610 s->selected = g - s->first_displayed_entry->idx - 1;
3611 select_commit(s);
3612 return NULL;
3615 if (idx + 1 < g) {
3616 err = log_move_cursor_down(view, g - idx - 1);
3617 if (!err && g > s->selected_entry->idx + 1)
3618 err = log_move_cursor_down(view,
3619 g - s->first_displayed_entry->idx - 1);
3620 if (err)
3621 return err;
3622 } else if (idx + 1 > g)
3623 log_move_cursor_up(view, idx - g + 1, 0);
3625 if (g < nlines && s->first_displayed_entry->idx == 0)
3626 s->selected = g - 1;
3628 select_commit(s);
3629 return NULL;
3633 static const struct got_error *
3634 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3636 const struct got_error *err = NULL;
3637 struct tog_log_view_state *s = &view->state.log;
3638 int eos, nscroll;
3640 if (s->thread_args.load_all) {
3641 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3642 s->thread_args.load_all = 0;
3643 else if (s->thread_args.log_complete) {
3644 err = log_move_cursor_down(view, s->commits->ncommits);
3645 s->thread_args.load_all = 0;
3647 if (err)
3648 return err;
3651 eos = nscroll = view->nlines - 1;
3652 if (view_is_hsplit_top(view))
3653 --eos; /* border */
3655 if (view->gline)
3656 return log_goto_line(view, eos);
3658 switch (ch) {
3659 case '&':
3660 err = limit_log_view(view);
3661 break;
3662 case 'q':
3663 s->quit = 1;
3664 break;
3665 case '0':
3666 view->x = 0;
3667 break;
3668 case '$':
3669 view->x = MAX(view->maxx - view->ncols / 2, 0);
3670 view->count = 0;
3671 break;
3672 case KEY_RIGHT:
3673 case 'l':
3674 if (view->x + view->ncols / 2 < view->maxx)
3675 view->x += 2; /* move two columns right */
3676 else
3677 view->count = 0;
3678 break;
3679 case KEY_LEFT:
3680 case 'h':
3681 view->x -= MIN(view->x, 2); /* move two columns back */
3682 if (view->x <= 0)
3683 view->count = 0;
3684 break;
3685 case 'k':
3686 case KEY_UP:
3687 case '<':
3688 case ',':
3689 case CTRL('p'):
3690 log_move_cursor_up(view, 0, 0);
3691 break;
3692 case 'g':
3693 case KEY_HOME:
3694 log_move_cursor_up(view, 0, 1);
3695 view->count = 0;
3696 break;
3697 case CTRL('u'):
3698 case 'u':
3699 nscroll /= 2;
3700 /* FALL THROUGH */
3701 case KEY_PPAGE:
3702 case CTRL('b'):
3703 case 'b':
3704 log_move_cursor_up(view, nscroll, 0);
3705 break;
3706 case 'j':
3707 case KEY_DOWN:
3708 case '>':
3709 case '.':
3710 case CTRL('n'):
3711 err = log_move_cursor_down(view, 0);
3712 break;
3713 case '@':
3714 s->use_committer = !s->use_committer;
3715 break;
3716 case 'G':
3717 case KEY_END: {
3718 /* We don't know yet how many commits, so we're forced to
3719 * traverse them all. */
3720 view->count = 0;
3721 s->thread_args.load_all = 1;
3722 if (!s->thread_args.log_complete)
3723 return trigger_log_thread(view, 0);
3724 err = log_move_cursor_down(view, s->commits->ncommits);
3725 s->thread_args.load_all = 0;
3726 break;
3728 case CTRL('d'):
3729 case 'd':
3730 nscroll /= 2;
3731 /* FALL THROUGH */
3732 case KEY_NPAGE:
3733 case CTRL('f'):
3734 case 'f':
3735 case ' ':
3736 err = log_move_cursor_down(view, nscroll);
3737 break;
3738 case KEY_RESIZE:
3739 if (s->selected > view->nlines - 2)
3740 s->selected = view->nlines - 2;
3741 if (s->selected > s->commits->ncommits - 1)
3742 s->selected = s->commits->ncommits - 1;
3743 select_commit(s);
3744 if (s->commits->ncommits < view->nlines - 1 &&
3745 !s->thread_args.log_complete) {
3746 s->thread_args.commits_needed += (view->nlines - 1) -
3747 s->commits->ncommits;
3748 err = trigger_log_thread(view, 1);
3750 break;
3751 case KEY_ENTER:
3752 case '\r':
3753 view->count = 0;
3754 if (s->selected_entry == NULL)
3755 break;
3756 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3757 break;
3758 case 'T':
3759 view->count = 0;
3760 if (s->selected_entry == NULL)
3761 break;
3762 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3763 break;
3764 case KEY_BACKSPACE:
3765 case CTRL('l'):
3766 case 'B':
3767 view->count = 0;
3768 if (ch == KEY_BACKSPACE &&
3769 got_path_is_root_dir(s->in_repo_path))
3770 break;
3771 err = stop_log_thread(s);
3772 if (err)
3773 return err;
3774 if (ch == KEY_BACKSPACE) {
3775 char *parent_path;
3776 err = got_path_dirname(&parent_path, s->in_repo_path);
3777 if (err)
3778 return err;
3779 free(s->in_repo_path);
3780 s->in_repo_path = parent_path;
3781 s->thread_args.in_repo_path = s->in_repo_path;
3782 } else if (ch == CTRL('l')) {
3783 struct got_object_id *start_id;
3784 err = got_repo_match_object_id(&start_id, NULL,
3785 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3786 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3787 if (err)
3788 return err;
3789 free(s->start_id);
3790 s->start_id = start_id;
3791 s->thread_args.start_id = s->start_id;
3792 } else /* 'B' */
3793 s->log_branches = !s->log_branches;
3795 if (s->thread_args.pack_fds == NULL) {
3796 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3797 if (err)
3798 return err;
3800 err = got_repo_open(&s->thread_args.repo,
3801 got_repo_get_path(s->repo), NULL,
3802 s->thread_args.pack_fds);
3803 if (err)
3804 return err;
3805 tog_free_refs();
3806 err = tog_load_refs(s->repo, 0);
3807 if (err)
3808 return err;
3809 err = got_commit_graph_open(&s->thread_args.graph,
3810 s->in_repo_path, !s->log_branches);
3811 if (err)
3812 return err;
3813 err = got_commit_graph_iter_start(s->thread_args.graph,
3814 s->start_id, s->repo, NULL, NULL);
3815 if (err)
3816 return err;
3817 free_commits(&s->real_commits);
3818 free_commits(&s->limit_commits);
3819 s->first_displayed_entry = NULL;
3820 s->last_displayed_entry = NULL;
3821 s->selected_entry = NULL;
3822 s->selected = 0;
3823 s->thread_args.log_complete = 0;
3824 s->quit = 0;
3825 s->thread_args.commits_needed = view->lines;
3826 s->matched_entry = NULL;
3827 s->search_entry = NULL;
3828 view->offset = 0;
3829 break;
3830 case 'R':
3831 view->count = 0;
3832 err = view_request_new(new_view, view, TOG_VIEW_REF);
3833 break;
3834 default:
3835 view->count = 0;
3836 break;
3839 return err;
3842 static const struct got_error *
3843 apply_unveil(const char *repo_path, const char *worktree_path)
3845 const struct got_error *error;
3847 #ifdef PROFILE
3848 if (unveil("gmon.out", "rwc") != 0)
3849 return got_error_from_errno2("unveil", "gmon.out");
3850 #endif
3851 if (repo_path && unveil(repo_path, "r") != 0)
3852 return got_error_from_errno2("unveil", repo_path);
3854 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3855 return got_error_from_errno2("unveil", worktree_path);
3857 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3858 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3860 error = got_privsep_unveil_exec_helpers();
3861 if (error != NULL)
3862 return error;
3864 if (unveil(NULL, NULL) != 0)
3865 return got_error_from_errno("unveil");
3867 return NULL;
3870 static void
3871 init_curses(void)
3874 * Override default signal handlers before starting ncurses.
3875 * This should prevent ncurses from installing its own
3876 * broken cleanup() signal handler.
3878 signal(SIGWINCH, tog_sigwinch);
3879 signal(SIGPIPE, tog_sigpipe);
3880 signal(SIGCONT, tog_sigcont);
3881 signal(SIGINT, tog_sigint);
3882 signal(SIGTERM, tog_sigterm);
3884 initscr();
3885 cbreak();
3886 halfdelay(1); /* Do fast refresh while initial view is loading. */
3887 noecho();
3888 nonl();
3889 intrflush(stdscr, FALSE);
3890 keypad(stdscr, TRUE);
3891 curs_set(0);
3892 if (getenv("TOG_COLORS") != NULL) {
3893 start_color();
3894 use_default_colors();
3898 static const struct got_error *
3899 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3900 struct got_repository *repo, struct got_worktree *worktree)
3902 const struct got_error *err = NULL;
3904 if (argc == 0) {
3905 *in_repo_path = strdup("/");
3906 if (*in_repo_path == NULL)
3907 return got_error_from_errno("strdup");
3908 return NULL;
3911 if (worktree) {
3912 const char *prefix = got_worktree_get_path_prefix(worktree);
3913 char *p;
3915 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3916 if (err)
3917 return err;
3918 if (asprintf(in_repo_path, "%s%s%s", prefix,
3919 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3920 p) == -1) {
3921 err = got_error_from_errno("asprintf");
3922 *in_repo_path = NULL;
3924 free(p);
3925 } else
3926 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3928 return err;
3931 static const struct got_error *
3932 cmd_log(int argc, char *argv[])
3934 const struct got_error *error;
3935 struct got_repository *repo = NULL;
3936 struct got_worktree *worktree = NULL;
3937 struct got_object_id *start_id = NULL;
3938 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3939 char *start_commit = NULL, *label = NULL;
3940 struct got_reference *ref = NULL;
3941 const char *head_ref_name = NULL;
3942 int ch, log_branches = 0;
3943 struct tog_view *view;
3944 int *pack_fds = NULL;
3946 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3947 switch (ch) {
3948 case 'b':
3949 log_branches = 1;
3950 break;
3951 case 'c':
3952 start_commit = optarg;
3953 break;
3954 case 'r':
3955 repo_path = realpath(optarg, NULL);
3956 if (repo_path == NULL)
3957 return got_error_from_errno2("realpath",
3958 optarg);
3959 break;
3960 default:
3961 usage_log();
3962 /* NOTREACHED */
3966 argc -= optind;
3967 argv += optind;
3969 if (argc > 1)
3970 usage_log();
3972 error = got_repo_pack_fds_open(&pack_fds);
3973 if (error != NULL)
3974 goto done;
3976 if (repo_path == NULL) {
3977 cwd = getcwd(NULL, 0);
3978 if (cwd == NULL)
3979 return got_error_from_errno("getcwd");
3980 error = got_worktree_open(&worktree, cwd);
3981 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3982 goto done;
3983 if (worktree)
3984 repo_path =
3985 strdup(got_worktree_get_repo_path(worktree));
3986 else
3987 repo_path = strdup(cwd);
3988 if (repo_path == NULL) {
3989 error = got_error_from_errno("strdup");
3990 goto done;
3994 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3995 if (error != NULL)
3996 goto done;
3998 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3999 repo, worktree);
4000 if (error)
4001 goto done;
4003 init_curses();
4005 error = apply_unveil(got_repo_get_path(repo),
4006 worktree ? got_worktree_get_root_path(worktree) : NULL);
4007 if (error)
4008 goto done;
4010 /* already loaded by tog_log_with_path()? */
4011 if (TAILQ_EMPTY(&tog_refs)) {
4012 error = tog_load_refs(repo, 0);
4013 if (error)
4014 goto done;
4017 if (start_commit == NULL) {
4018 error = got_repo_match_object_id(&start_id, &label,
4019 worktree ? got_worktree_get_head_ref_name(worktree) :
4020 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4021 if (error)
4022 goto done;
4023 head_ref_name = label;
4024 } else {
4025 error = got_ref_open(&ref, repo, start_commit, 0);
4026 if (error == NULL)
4027 head_ref_name = got_ref_get_name(ref);
4028 else if (error->code != GOT_ERR_NOT_REF)
4029 goto done;
4030 error = got_repo_match_object_id(&start_id, NULL,
4031 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4032 if (error)
4033 goto done;
4036 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4037 if (view == NULL) {
4038 error = got_error_from_errno("view_open");
4039 goto done;
4041 error = open_log_view(view, start_id, repo, head_ref_name,
4042 in_repo_path, log_branches);
4043 if (error)
4044 goto done;
4045 if (worktree) {
4046 /* Release work tree lock. */
4047 got_worktree_close(worktree);
4048 worktree = NULL;
4050 error = view_loop(view);
4051 done:
4052 free(in_repo_path);
4053 free(repo_path);
4054 free(cwd);
4055 free(start_id);
4056 free(label);
4057 if (ref)
4058 got_ref_close(ref);
4059 if (repo) {
4060 const struct got_error *close_err = got_repo_close(repo);
4061 if (error == NULL)
4062 error = close_err;
4064 if (worktree)
4065 got_worktree_close(worktree);
4066 if (pack_fds) {
4067 const struct got_error *pack_err =
4068 got_repo_pack_fds_close(pack_fds);
4069 if (error == NULL)
4070 error = pack_err;
4072 tog_free_refs();
4073 return error;
4076 __dead static void
4077 usage_diff(void)
4079 endwin();
4080 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4081 "object1 object2\n", getprogname());
4082 exit(1);
4085 static int
4086 match_line(const char *line, regex_t *regex, size_t nmatch,
4087 regmatch_t *regmatch)
4089 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4092 static struct tog_color *
4093 match_color(struct tog_colors *colors, const char *line)
4095 struct tog_color *tc = NULL;
4097 STAILQ_FOREACH(tc, colors, entry) {
4098 if (match_line(line, &tc->regex, 0, NULL))
4099 return tc;
4102 return NULL;
4105 static const struct got_error *
4106 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4107 WINDOW *window, int skipcol, regmatch_t *regmatch)
4109 const struct got_error *err = NULL;
4110 char *exstr = NULL;
4111 wchar_t *wline = NULL;
4112 int rme, rms, n, width, scrollx;
4113 int width0 = 0, width1 = 0, width2 = 0;
4114 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4116 *wtotal = 0;
4118 rms = regmatch->rm_so;
4119 rme = regmatch->rm_eo;
4121 err = expand_tab(&exstr, line);
4122 if (err)
4123 return err;
4125 /* Split the line into 3 segments, according to match offsets. */
4126 seg0 = strndup(exstr, rms);
4127 if (seg0 == NULL) {
4128 err = got_error_from_errno("strndup");
4129 goto done;
4131 seg1 = strndup(exstr + rms, rme - rms);
4132 if (seg1 == NULL) {
4133 err = got_error_from_errno("strndup");
4134 goto done;
4136 seg2 = strdup(exstr + rme);
4137 if (seg2 == NULL) {
4138 err = got_error_from_errno("strndup");
4139 goto done;
4142 /* draw up to matched token if we haven't scrolled past it */
4143 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4144 col_tab_align, 1);
4145 if (err)
4146 goto done;
4147 n = MAX(width0 - skipcol, 0);
4148 if (n) {
4149 free(wline);
4150 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4151 wlimit, col_tab_align, 1);
4152 if (err)
4153 goto done;
4154 waddwstr(window, &wline[scrollx]);
4155 wlimit -= width;
4156 *wtotal += width;
4159 if (wlimit > 0) {
4160 int i = 0, w = 0;
4161 size_t wlen;
4163 free(wline);
4164 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4165 col_tab_align, 1);
4166 if (err)
4167 goto done;
4168 wlen = wcslen(wline);
4169 while (i < wlen) {
4170 width = wcwidth(wline[i]);
4171 if (width == -1) {
4172 /* should not happen, tabs are expanded */
4173 err = got_error(GOT_ERR_RANGE);
4174 goto done;
4176 if (width0 + w + width > skipcol)
4177 break;
4178 w += width;
4179 i++;
4181 /* draw (visible part of) matched token (if scrolled into it) */
4182 if (width1 - w > 0) {
4183 wattron(window, A_STANDOUT);
4184 waddwstr(window, &wline[i]);
4185 wattroff(window, A_STANDOUT);
4186 wlimit -= (width1 - w);
4187 *wtotal += (width1 - w);
4191 if (wlimit > 0) { /* draw rest of line */
4192 free(wline);
4193 if (skipcol > width0 + width1) {
4194 err = format_line(&wline, &width2, &scrollx, seg2,
4195 skipcol - (width0 + width1), wlimit,
4196 col_tab_align, 1);
4197 if (err)
4198 goto done;
4199 waddwstr(window, &wline[scrollx]);
4200 } else {
4201 err = format_line(&wline, &width2, NULL, seg2, 0,
4202 wlimit, col_tab_align, 1);
4203 if (err)
4204 goto done;
4205 waddwstr(window, wline);
4207 *wtotal += width2;
4209 done:
4210 free(wline);
4211 free(exstr);
4212 free(seg0);
4213 free(seg1);
4214 free(seg2);
4215 return err;
4218 static int
4219 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4221 FILE *f = NULL;
4222 int *eof, *first, *selected;
4224 if (view->type == TOG_VIEW_DIFF) {
4225 struct tog_diff_view_state *s = &view->state.diff;
4227 first = &s->first_displayed_line;
4228 selected = first;
4229 eof = &s->eof;
4230 f = s->f;
4231 } else if (view->type == TOG_VIEW_HELP) {
4232 struct tog_help_view_state *s = &view->state.help;
4234 first = &s->first_displayed_line;
4235 selected = first;
4236 eof = &s->eof;
4237 f = s->f;
4238 } else if (view->type == TOG_VIEW_BLAME) {
4239 struct tog_blame_view_state *s = &view->state.blame;
4241 first = &s->first_displayed_line;
4242 selected = &s->selected_line;
4243 eof = &s->eof;
4244 f = s->blame.f;
4245 } else
4246 return 0;
4248 /* Center gline in the middle of the page like vi(1). */
4249 if (*lineno < view->gline - (view->nlines - 3) / 2)
4250 return 0;
4251 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4252 rewind(f);
4253 *eof = 0;
4254 *first = 1;
4255 *lineno = 0;
4256 *nprinted = 0;
4257 return 0;
4260 *selected = view->gline <= (view->nlines - 3) / 2 ?
4261 view->gline : (view->nlines - 3) / 2 + 1;
4262 view->gline = 0;
4264 return 1;
4267 static const struct got_error *
4268 draw_file(struct tog_view *view, const char *header)
4270 struct tog_diff_view_state *s = &view->state.diff;
4271 regmatch_t *regmatch = &view->regmatch;
4272 const struct got_error *err;
4273 int nprinted = 0;
4274 char *line;
4275 size_t linesize = 0;
4276 ssize_t linelen;
4277 wchar_t *wline;
4278 int width;
4279 int max_lines = view->nlines;
4280 int nlines = s->nlines;
4281 off_t line_offset;
4283 s->lineno = s->first_displayed_line - 1;
4284 line_offset = s->lines[s->first_displayed_line - 1].offset;
4285 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4286 return got_error_from_errno("fseek");
4288 werase(view->window);
4290 if (view->gline > s->nlines - 1)
4291 view->gline = s->nlines - 1;
4293 if (header) {
4294 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4295 1 : view->gline - (view->nlines - 3) / 2 :
4296 s->lineno + s->selected_line;
4298 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4299 return got_error_from_errno("asprintf");
4300 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4301 0, 0);
4302 free(line);
4303 if (err)
4304 return err;
4306 if (view_needs_focus_indication(view))
4307 wstandout(view->window);
4308 waddwstr(view->window, wline);
4309 free(wline);
4310 wline = NULL;
4311 while (width++ < view->ncols)
4312 waddch(view->window, ' ');
4313 if (view_needs_focus_indication(view))
4314 wstandend(view->window);
4316 if (max_lines <= 1)
4317 return NULL;
4318 max_lines--;
4321 s->eof = 0;
4322 view->maxx = 0;
4323 line = NULL;
4324 while (max_lines > 0 && nprinted < max_lines) {
4325 enum got_diff_line_type linetype;
4326 attr_t attr = 0;
4328 linelen = getline(&line, &linesize, s->f);
4329 if (linelen == -1) {
4330 if (feof(s->f)) {
4331 s->eof = 1;
4332 break;
4334 free(line);
4335 return got_ferror(s->f, GOT_ERR_IO);
4338 if (++s->lineno < s->first_displayed_line)
4339 continue;
4340 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4341 continue;
4342 if (s->lineno == view->hiline)
4343 attr = A_STANDOUT;
4345 /* Set view->maxx based on full line length. */
4346 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4347 view->x ? 1 : 0);
4348 if (err) {
4349 free(line);
4350 return err;
4352 view->maxx = MAX(view->maxx, width);
4353 free(wline);
4354 wline = NULL;
4356 linetype = s->lines[s->lineno].type;
4357 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4358 linetype < GOT_DIFF_LINE_CONTEXT)
4359 attr |= COLOR_PAIR(linetype);
4360 if (attr)
4361 wattron(view->window, attr);
4362 if (s->first_displayed_line + nprinted == s->matched_line &&
4363 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4364 err = add_matched_line(&width, line, view->ncols, 0,
4365 view->window, view->x, regmatch);
4366 if (err) {
4367 free(line);
4368 return err;
4370 } else {
4371 int skip;
4372 err = format_line(&wline, &width, &skip, line,
4373 view->x, view->ncols, 0, view->x ? 1 : 0);
4374 if (err) {
4375 free(line);
4376 return err;
4378 waddwstr(view->window, &wline[skip]);
4379 free(wline);
4380 wline = NULL;
4382 if (s->lineno == view->hiline) {
4383 /* highlight full gline length */
4384 while (width++ < view->ncols)
4385 waddch(view->window, ' ');
4386 } else {
4387 if (width <= view->ncols - 1)
4388 waddch(view->window, '\n');
4390 if (attr)
4391 wattroff(view->window, attr);
4392 if (++nprinted == 1)
4393 s->first_displayed_line = s->lineno;
4395 free(line);
4396 if (nprinted >= 1)
4397 s->last_displayed_line = s->first_displayed_line +
4398 (nprinted - 1);
4399 else
4400 s->last_displayed_line = s->first_displayed_line;
4402 view_border(view);
4404 if (s->eof) {
4405 while (nprinted < view->nlines) {
4406 waddch(view->window, '\n');
4407 nprinted++;
4410 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4411 view->ncols, 0, 0);
4412 if (err) {
4413 return err;
4416 wstandout(view->window);
4417 waddwstr(view->window, wline);
4418 free(wline);
4419 wline = NULL;
4420 wstandend(view->window);
4423 return NULL;
4426 static char *
4427 get_datestr(time_t *time, char *datebuf)
4429 struct tm mytm, *tm;
4430 char *p, *s;
4432 tm = gmtime_r(time, &mytm);
4433 if (tm == NULL)
4434 return NULL;
4435 s = asctime_r(tm, datebuf);
4436 if (s == NULL)
4437 return NULL;
4438 p = strchr(s, '\n');
4439 if (p)
4440 *p = '\0';
4441 return s;
4444 static const struct got_error *
4445 get_changed_paths(struct got_pathlist_head *paths,
4446 struct got_commit_object *commit, struct got_repository *repo)
4448 const struct got_error *err = NULL;
4449 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4450 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4451 struct got_object_qid *qid;
4453 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4454 if (qid != NULL) {
4455 struct got_commit_object *pcommit;
4456 err = got_object_open_as_commit(&pcommit, repo,
4457 &qid->id);
4458 if (err)
4459 return err;
4461 tree_id1 = got_object_id_dup(
4462 got_object_commit_get_tree_id(pcommit));
4463 if (tree_id1 == NULL) {
4464 got_object_commit_close(pcommit);
4465 return got_error_from_errno("got_object_id_dup");
4467 got_object_commit_close(pcommit);
4471 if (tree_id1) {
4472 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4473 if (err)
4474 goto done;
4477 tree_id2 = got_object_commit_get_tree_id(commit);
4478 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4479 if (err)
4480 goto done;
4482 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4483 got_diff_tree_collect_changed_paths, paths, 0);
4484 done:
4485 if (tree1)
4486 got_object_tree_close(tree1);
4487 if (tree2)
4488 got_object_tree_close(tree2);
4489 free(tree_id1);
4490 return err;
4493 static const struct got_error *
4494 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4495 off_t off, uint8_t type)
4497 struct got_diff_line *p;
4499 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4500 if (p == NULL)
4501 return got_error_from_errno("reallocarray");
4502 *lines = p;
4503 (*lines)[*nlines].offset = off;
4504 (*lines)[*nlines].type = type;
4505 (*nlines)++;
4507 return NULL;
4510 static const struct got_error *
4511 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4512 struct got_object_id *commit_id, struct got_reflist_head *refs,
4513 struct got_repository *repo, FILE *outfile)
4515 const struct got_error *err = NULL;
4516 char datebuf[26], *datestr;
4517 struct got_commit_object *commit;
4518 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4519 time_t committer_time;
4520 const char *author, *committer;
4521 char *refs_str = NULL;
4522 struct got_pathlist_head changed_paths;
4523 struct got_pathlist_entry *pe;
4524 off_t outoff = 0;
4525 int n;
4527 TAILQ_INIT(&changed_paths);
4529 if (refs) {
4530 err = build_refs_str(&refs_str, refs, commit_id, repo);
4531 if (err)
4532 return err;
4535 err = got_object_open_as_commit(&commit, repo, commit_id);
4536 if (err)
4537 return err;
4539 err = got_object_id_str(&id_str, commit_id);
4540 if (err) {
4541 err = got_error_from_errno("got_object_id_str");
4542 goto done;
4545 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4546 if (err)
4547 goto done;
4549 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4550 refs_str ? refs_str : "", refs_str ? ")" : "");
4551 if (n < 0) {
4552 err = got_error_from_errno("fprintf");
4553 goto done;
4555 outoff += n;
4556 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4557 if (err)
4558 goto done;
4560 n = fprintf(outfile, "from: %s\n",
4561 got_object_commit_get_author(commit));
4562 if (n < 0) {
4563 err = got_error_from_errno("fprintf");
4564 goto done;
4566 outoff += n;
4567 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4568 if (err)
4569 goto done;
4571 committer_time = got_object_commit_get_committer_time(commit);
4572 datestr = get_datestr(&committer_time, datebuf);
4573 if (datestr) {
4574 n = fprintf(outfile, "date: %s UTC\n", datestr);
4575 if (n < 0) {
4576 err = got_error_from_errno("fprintf");
4577 goto done;
4579 outoff += n;
4580 err = add_line_metadata(lines, nlines, outoff,
4581 GOT_DIFF_LINE_DATE);
4582 if (err)
4583 goto done;
4585 author = got_object_commit_get_author(commit);
4586 committer = got_object_commit_get_committer(commit);
4587 if (strcmp(author, committer) != 0) {
4588 n = fprintf(outfile, "via: %s\n", committer);
4589 if (n < 0) {
4590 err = got_error_from_errno("fprintf");
4591 goto done;
4593 outoff += n;
4594 err = add_line_metadata(lines, nlines, outoff,
4595 GOT_DIFF_LINE_AUTHOR);
4596 if (err)
4597 goto done;
4599 if (got_object_commit_get_nparents(commit) > 1) {
4600 const struct got_object_id_queue *parent_ids;
4601 struct got_object_qid *qid;
4602 int pn = 1;
4603 parent_ids = got_object_commit_get_parent_ids(commit);
4604 STAILQ_FOREACH(qid, parent_ids, entry) {
4605 err = got_object_id_str(&id_str, &qid->id);
4606 if (err)
4607 goto done;
4608 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4609 if (n < 0) {
4610 err = got_error_from_errno("fprintf");
4611 goto done;
4613 outoff += n;
4614 err = add_line_metadata(lines, nlines, outoff,
4615 GOT_DIFF_LINE_META);
4616 if (err)
4617 goto done;
4618 free(id_str);
4619 id_str = NULL;
4623 err = got_object_commit_get_logmsg(&logmsg, commit);
4624 if (err)
4625 goto done;
4626 s = logmsg;
4627 while ((line = strsep(&s, "\n")) != NULL) {
4628 n = fprintf(outfile, "%s\n", line);
4629 if (n < 0) {
4630 err = got_error_from_errno("fprintf");
4631 goto done;
4633 outoff += n;
4634 err = add_line_metadata(lines, nlines, outoff,
4635 GOT_DIFF_LINE_LOGMSG);
4636 if (err)
4637 goto done;
4640 err = get_changed_paths(&changed_paths, commit, repo);
4641 if (err)
4642 goto done;
4643 TAILQ_FOREACH(pe, &changed_paths, entry) {
4644 struct got_diff_changed_path *cp = pe->data;
4645 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4646 if (n < 0) {
4647 err = got_error_from_errno("fprintf");
4648 goto done;
4650 outoff += n;
4651 err = add_line_metadata(lines, nlines, outoff,
4652 GOT_DIFF_LINE_CHANGES);
4653 if (err)
4654 goto done;
4655 free((char *)pe->path);
4656 free(pe->data);
4659 fputc('\n', outfile);
4660 outoff++;
4661 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4662 done:
4663 got_pathlist_free(&changed_paths);
4664 free(id_str);
4665 free(logmsg);
4666 free(refs_str);
4667 got_object_commit_close(commit);
4668 if (err) {
4669 free(*lines);
4670 *lines = NULL;
4671 *nlines = 0;
4673 return err;
4676 static const struct got_error *
4677 create_diff(struct tog_diff_view_state *s)
4679 const struct got_error *err = NULL;
4680 FILE *f = NULL;
4681 int obj_type;
4683 free(s->lines);
4684 s->lines = malloc(sizeof(*s->lines));
4685 if (s->lines == NULL)
4686 return got_error_from_errno("malloc");
4687 s->nlines = 0;
4689 f = got_opentemp();
4690 if (f == NULL) {
4691 err = got_error_from_errno("got_opentemp");
4692 goto done;
4694 if (s->f && fclose(s->f) == EOF) {
4695 err = got_error_from_errno("fclose");
4696 goto done;
4698 s->f = f;
4700 if (s->id1)
4701 err = got_object_get_type(&obj_type, s->repo, s->id1);
4702 else
4703 err = got_object_get_type(&obj_type, s->repo, s->id2);
4704 if (err)
4705 goto done;
4707 switch (obj_type) {
4708 case GOT_OBJ_TYPE_BLOB:
4709 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4710 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4711 s->label1, s->label2, tog_diff_algo, s->diff_context,
4712 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4713 break;
4714 case GOT_OBJ_TYPE_TREE:
4715 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4716 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4717 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4718 s->force_text_diff, s->repo, s->f);
4719 break;
4720 case GOT_OBJ_TYPE_COMMIT: {
4721 const struct got_object_id_queue *parent_ids;
4722 struct got_object_qid *pid;
4723 struct got_commit_object *commit2;
4724 struct got_reflist_head *refs;
4726 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4727 if (err)
4728 goto done;
4729 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4730 /* Show commit info if we're diffing to a parent/root commit. */
4731 if (s->id1 == NULL) {
4732 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4733 refs, s->repo, s->f);
4734 if (err)
4735 goto done;
4736 } else {
4737 parent_ids = got_object_commit_get_parent_ids(commit2);
4738 STAILQ_FOREACH(pid, parent_ids, entry) {
4739 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4740 err = write_commit_info(&s->lines,
4741 &s->nlines, s->id2, refs, s->repo,
4742 s->f);
4743 if (err)
4744 goto done;
4745 break;
4749 got_object_commit_close(commit2);
4751 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4752 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4753 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4754 s->force_text_diff, s->repo, s->f);
4755 break;
4757 default:
4758 err = got_error(GOT_ERR_OBJ_TYPE);
4759 break;
4761 done:
4762 if (s->f && fflush(s->f) != 0 && err == NULL)
4763 err = got_error_from_errno("fflush");
4764 return err;
4767 static void
4768 diff_view_indicate_progress(struct tog_view *view)
4770 mvwaddstr(view->window, 0, 0, "diffing...");
4771 update_panels();
4772 doupdate();
4775 static const struct got_error *
4776 search_start_diff_view(struct tog_view *view)
4778 struct tog_diff_view_state *s = &view->state.diff;
4780 s->matched_line = 0;
4781 return NULL;
4784 static void
4785 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4786 size_t *nlines, int **first, int **last, int **match, int **selected)
4788 struct tog_diff_view_state *s = &view->state.diff;
4790 *f = s->f;
4791 *nlines = s->nlines;
4792 *line_offsets = NULL;
4793 *match = &s->matched_line;
4794 *first = &s->first_displayed_line;
4795 *last = &s->last_displayed_line;
4796 *selected = &s->selected_line;
4799 static const struct got_error *
4800 search_next_view_match(struct tog_view *view)
4802 const struct got_error *err = NULL;
4803 FILE *f;
4804 int lineno;
4805 char *line = NULL;
4806 size_t linesize = 0;
4807 ssize_t linelen;
4808 off_t *line_offsets;
4809 size_t nlines = 0;
4810 int *first, *last, *match, *selected;
4812 if (!view->search_setup)
4813 return got_error_msg(GOT_ERR_NOT_IMPL,
4814 "view search not supported");
4815 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4816 &match, &selected);
4818 if (!view->searching) {
4819 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4820 return NULL;
4823 if (*match) {
4824 if (view->searching == TOG_SEARCH_FORWARD)
4825 lineno = *match + 1;
4826 else
4827 lineno = *match - 1;
4828 } else
4829 lineno = *first - 1 + *selected;
4831 while (1) {
4832 off_t offset;
4834 if (lineno <= 0 || lineno > nlines) {
4835 if (*match == 0) {
4836 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4837 break;
4840 if (view->searching == TOG_SEARCH_FORWARD)
4841 lineno = 1;
4842 else
4843 lineno = nlines;
4846 offset = view->type == TOG_VIEW_DIFF ?
4847 view->state.diff.lines[lineno - 1].offset :
4848 line_offsets[lineno - 1];
4849 if (fseeko(f, offset, SEEK_SET) != 0) {
4850 free(line);
4851 return got_error_from_errno("fseeko");
4853 linelen = getline(&line, &linesize, f);
4854 if (linelen != -1) {
4855 char *exstr;
4856 err = expand_tab(&exstr, line);
4857 if (err)
4858 break;
4859 if (match_line(exstr, &view->regex, 1,
4860 &view->regmatch)) {
4861 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4862 *match = lineno;
4863 free(exstr);
4864 break;
4866 free(exstr);
4868 if (view->searching == TOG_SEARCH_FORWARD)
4869 lineno++;
4870 else
4871 lineno--;
4873 free(line);
4875 if (*match) {
4876 *first = *match;
4877 *selected = 1;
4880 return err;
4883 static const struct got_error *
4884 close_diff_view(struct tog_view *view)
4886 const struct got_error *err = NULL;
4887 struct tog_diff_view_state *s = &view->state.diff;
4889 free(s->id1);
4890 s->id1 = NULL;
4891 free(s->id2);
4892 s->id2 = NULL;
4893 if (s->f && fclose(s->f) == EOF)
4894 err = got_error_from_errno("fclose");
4895 s->f = NULL;
4896 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4897 err = got_error_from_errno("fclose");
4898 s->f1 = NULL;
4899 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4900 err = got_error_from_errno("fclose");
4901 s->f2 = NULL;
4902 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4903 err = got_error_from_errno("close");
4904 s->fd1 = -1;
4905 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4906 err = got_error_from_errno("close");
4907 s->fd2 = -1;
4908 free(s->lines);
4909 s->lines = NULL;
4910 s->nlines = 0;
4911 return err;
4914 static const struct got_error *
4915 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4916 struct got_object_id *id2, const char *label1, const char *label2,
4917 int diff_context, int ignore_whitespace, int force_text_diff,
4918 struct tog_view *parent_view, struct got_repository *repo)
4920 const struct got_error *err;
4921 struct tog_diff_view_state *s = &view->state.diff;
4923 memset(s, 0, sizeof(*s));
4924 s->fd1 = -1;
4925 s->fd2 = -1;
4927 if (id1 != NULL && id2 != NULL) {
4928 int type1, type2;
4929 err = got_object_get_type(&type1, repo, id1);
4930 if (err)
4931 return err;
4932 err = got_object_get_type(&type2, repo, id2);
4933 if (err)
4934 return err;
4936 if (type1 != type2)
4937 return got_error(GOT_ERR_OBJ_TYPE);
4939 s->first_displayed_line = 1;
4940 s->last_displayed_line = view->nlines;
4941 s->selected_line = 1;
4942 s->repo = repo;
4943 s->id1 = id1;
4944 s->id2 = id2;
4945 s->label1 = label1;
4946 s->label2 = label2;
4948 if (id1) {
4949 s->id1 = got_object_id_dup(id1);
4950 if (s->id1 == NULL)
4951 return got_error_from_errno("got_object_id_dup");
4952 } else
4953 s->id1 = NULL;
4955 s->id2 = got_object_id_dup(id2);
4956 if (s->id2 == NULL) {
4957 err = got_error_from_errno("got_object_id_dup");
4958 goto done;
4961 s->f1 = got_opentemp();
4962 if (s->f1 == NULL) {
4963 err = got_error_from_errno("got_opentemp");
4964 goto done;
4967 s->f2 = got_opentemp();
4968 if (s->f2 == NULL) {
4969 err = got_error_from_errno("got_opentemp");
4970 goto done;
4973 s->fd1 = got_opentempfd();
4974 if (s->fd1 == -1) {
4975 err = got_error_from_errno("got_opentempfd");
4976 goto done;
4979 s->fd2 = got_opentempfd();
4980 if (s->fd2 == -1) {
4981 err = got_error_from_errno("got_opentempfd");
4982 goto done;
4985 s->first_displayed_line = 1;
4986 s->last_displayed_line = view->nlines;
4987 s->diff_context = diff_context;
4988 s->ignore_whitespace = ignore_whitespace;
4989 s->force_text_diff = force_text_diff;
4990 s->parent_view = parent_view;
4991 s->repo = repo;
4993 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4994 int rc;
4996 rc = init_pair(GOT_DIFF_LINE_MINUS,
4997 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
4998 if (rc != ERR)
4999 rc = init_pair(GOT_DIFF_LINE_PLUS,
5000 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5001 if (rc != ERR)
5002 rc = init_pair(GOT_DIFF_LINE_HUNK,
5003 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5004 if (rc != ERR)
5005 rc = init_pair(GOT_DIFF_LINE_META,
5006 get_color_value("TOG_COLOR_DIFF_META"), -1);
5007 if (rc != ERR)
5008 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5009 get_color_value("TOG_COLOR_DIFF_META"), -1);
5010 if (rc != ERR)
5011 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5012 get_color_value("TOG_COLOR_DIFF_META"), -1);
5013 if (rc != ERR)
5014 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5015 get_color_value("TOG_COLOR_DIFF_META"), -1);
5016 if (rc != ERR)
5017 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5018 get_color_value("TOG_COLOR_AUTHOR"), -1);
5019 if (rc != ERR)
5020 rc = init_pair(GOT_DIFF_LINE_DATE,
5021 get_color_value("TOG_COLOR_DATE"), -1);
5022 if (rc == ERR) {
5023 err = got_error(GOT_ERR_RANGE);
5024 goto done;
5028 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5029 view_is_splitscreen(view))
5030 show_log_view(parent_view); /* draw border */
5031 diff_view_indicate_progress(view);
5033 err = create_diff(s);
5035 view->show = show_diff_view;
5036 view->input = input_diff_view;
5037 view->reset = reset_diff_view;
5038 view->close = close_diff_view;
5039 view->search_start = search_start_diff_view;
5040 view->search_setup = search_setup_diff_view;
5041 view->search_next = search_next_view_match;
5042 done:
5043 if (err)
5044 close_diff_view(view);
5045 return err;
5048 static const struct got_error *
5049 show_diff_view(struct tog_view *view)
5051 const struct got_error *err;
5052 struct tog_diff_view_state *s = &view->state.diff;
5053 char *id_str1 = NULL, *id_str2, *header;
5054 const char *label1, *label2;
5056 if (s->id1) {
5057 err = got_object_id_str(&id_str1, s->id1);
5058 if (err)
5059 return err;
5060 label1 = s->label1 ? s->label1 : id_str1;
5061 } else
5062 label1 = "/dev/null";
5064 err = got_object_id_str(&id_str2, s->id2);
5065 if (err)
5066 return err;
5067 label2 = s->label2 ? s->label2 : id_str2;
5069 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5070 err = got_error_from_errno("asprintf");
5071 free(id_str1);
5072 free(id_str2);
5073 return err;
5075 free(id_str1);
5076 free(id_str2);
5078 err = draw_file(view, header);
5079 free(header);
5080 return err;
5083 static const struct got_error *
5084 set_selected_commit(struct tog_diff_view_state *s,
5085 struct commit_queue_entry *entry)
5087 const struct got_error *err;
5088 const struct got_object_id_queue *parent_ids;
5089 struct got_commit_object *selected_commit;
5090 struct got_object_qid *pid;
5092 free(s->id2);
5093 s->id2 = got_object_id_dup(entry->id);
5094 if (s->id2 == NULL)
5095 return got_error_from_errno("got_object_id_dup");
5097 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5098 if (err)
5099 return err;
5100 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5101 free(s->id1);
5102 pid = STAILQ_FIRST(parent_ids);
5103 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5104 got_object_commit_close(selected_commit);
5105 return NULL;
5108 static const struct got_error *
5109 reset_diff_view(struct tog_view *view)
5111 struct tog_diff_view_state *s = &view->state.diff;
5113 view->count = 0;
5114 wclear(view->window);
5115 s->first_displayed_line = 1;
5116 s->last_displayed_line = view->nlines;
5117 s->matched_line = 0;
5118 diff_view_indicate_progress(view);
5119 return create_diff(s);
5122 static void
5123 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5125 int start, i;
5127 i = start = s->first_displayed_line - 1;
5129 while (s->lines[i].type != type) {
5130 if (i == 0)
5131 i = s->nlines - 1;
5132 if (--i == start)
5133 return; /* do nothing, requested type not in file */
5136 s->selected_line = 1;
5137 s->first_displayed_line = i;
5140 static void
5141 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5143 int start, i;
5145 i = start = s->first_displayed_line + 1;
5147 while (s->lines[i].type != type) {
5148 if (i == s->nlines - 1)
5149 i = 0;
5150 if (++i == start)
5151 return; /* do nothing, requested type not in file */
5154 s->selected_line = 1;
5155 s->first_displayed_line = i;
5158 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5159 int, int, int);
5160 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5161 int, int);
5163 static const struct got_error *
5164 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5166 const struct got_error *err = NULL;
5167 struct tog_diff_view_state *s = &view->state.diff;
5168 struct tog_log_view_state *ls;
5169 struct commit_queue_entry *old_selected_entry;
5170 char *line = NULL;
5171 size_t linesize = 0;
5172 ssize_t linelen;
5173 int i, nscroll = view->nlines - 1, up = 0;
5175 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5177 switch (ch) {
5178 case '0':
5179 view->x = 0;
5180 break;
5181 case '$':
5182 view->x = MAX(view->maxx - view->ncols / 3, 0);
5183 view->count = 0;
5184 break;
5185 case KEY_RIGHT:
5186 case 'l':
5187 if (view->x + view->ncols / 3 < view->maxx)
5188 view->x += 2; /* move two columns right */
5189 else
5190 view->count = 0;
5191 break;
5192 case KEY_LEFT:
5193 case 'h':
5194 view->x -= MIN(view->x, 2); /* move two columns back */
5195 if (view->x <= 0)
5196 view->count = 0;
5197 break;
5198 case 'a':
5199 case 'w':
5200 if (ch == 'a')
5201 s->force_text_diff = !s->force_text_diff;
5202 if (ch == 'w')
5203 s->ignore_whitespace = !s->ignore_whitespace;
5204 err = reset_diff_view(view);
5205 break;
5206 case 'g':
5207 case KEY_HOME:
5208 s->first_displayed_line = 1;
5209 view->count = 0;
5210 break;
5211 case 'G':
5212 case KEY_END:
5213 view->count = 0;
5214 if (s->eof)
5215 break;
5217 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5218 s->eof = 1;
5219 break;
5220 case 'k':
5221 case KEY_UP:
5222 case CTRL('p'):
5223 if (s->first_displayed_line > 1)
5224 s->first_displayed_line--;
5225 else
5226 view->count = 0;
5227 break;
5228 case CTRL('u'):
5229 case 'u':
5230 nscroll /= 2;
5231 /* FALL THROUGH */
5232 case KEY_PPAGE:
5233 case CTRL('b'):
5234 case 'b':
5235 if (s->first_displayed_line == 1) {
5236 view->count = 0;
5237 break;
5239 i = 0;
5240 while (i++ < nscroll && s->first_displayed_line > 1)
5241 s->first_displayed_line--;
5242 break;
5243 case 'j':
5244 case KEY_DOWN:
5245 case CTRL('n'):
5246 if (!s->eof)
5247 s->first_displayed_line++;
5248 else
5249 view->count = 0;
5250 break;
5251 case CTRL('d'):
5252 case 'd':
5253 nscroll /= 2;
5254 /* FALL THROUGH */
5255 case KEY_NPAGE:
5256 case CTRL('f'):
5257 case 'f':
5258 case ' ':
5259 if (s->eof) {
5260 view->count = 0;
5261 break;
5263 i = 0;
5264 while (!s->eof && i++ < nscroll) {
5265 linelen = getline(&line, &linesize, s->f);
5266 s->first_displayed_line++;
5267 if (linelen == -1) {
5268 if (feof(s->f)) {
5269 s->eof = 1;
5270 } else
5271 err = got_ferror(s->f, GOT_ERR_IO);
5272 break;
5275 free(line);
5276 break;
5277 case '(':
5278 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5279 break;
5280 case ')':
5281 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5282 break;
5283 case '{':
5284 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5285 break;
5286 case '}':
5287 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5288 break;
5289 case '[':
5290 if (s->diff_context > 0) {
5291 s->diff_context--;
5292 s->matched_line = 0;
5293 diff_view_indicate_progress(view);
5294 err = create_diff(s);
5295 if (s->first_displayed_line + view->nlines - 1 >
5296 s->nlines) {
5297 s->first_displayed_line = 1;
5298 s->last_displayed_line = view->nlines;
5300 } else
5301 view->count = 0;
5302 break;
5303 case ']':
5304 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5305 s->diff_context++;
5306 s->matched_line = 0;
5307 diff_view_indicate_progress(view);
5308 err = create_diff(s);
5309 } else
5310 view->count = 0;
5311 break;
5312 case '<':
5313 case ',':
5314 case 'K':
5315 up = 1;
5316 /* FALL THROUGH */
5317 case '>':
5318 case '.':
5319 case 'J':
5320 if (s->parent_view == NULL) {
5321 view->count = 0;
5322 break;
5324 s->parent_view->count = view->count;
5326 if (s->parent_view->type == TOG_VIEW_LOG) {
5327 ls = &s->parent_view->state.log;
5328 old_selected_entry = ls->selected_entry;
5330 err = input_log_view(NULL, s->parent_view,
5331 up ? KEY_UP : KEY_DOWN);
5332 if (err)
5333 break;
5334 view->count = s->parent_view->count;
5336 if (old_selected_entry == ls->selected_entry)
5337 break;
5339 err = set_selected_commit(s, ls->selected_entry);
5340 if (err)
5341 break;
5342 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5343 struct tog_blame_view_state *bs;
5344 struct got_object_id *id, *prev_id;
5346 bs = &s->parent_view->state.blame;
5347 prev_id = get_annotation_for_line(bs->blame.lines,
5348 bs->blame.nlines, bs->last_diffed_line);
5350 err = input_blame_view(&view, s->parent_view,
5351 up ? KEY_UP : KEY_DOWN);
5352 if (err)
5353 break;
5354 view->count = s->parent_view->count;
5356 if (prev_id == NULL)
5357 break;
5358 id = get_selected_commit_id(bs->blame.lines,
5359 bs->blame.nlines, bs->first_displayed_line,
5360 bs->selected_line);
5361 if (id == NULL)
5362 break;
5364 if (!got_object_id_cmp(prev_id, id))
5365 break;
5367 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5368 if (err)
5369 break;
5371 s->first_displayed_line = 1;
5372 s->last_displayed_line = view->nlines;
5373 s->matched_line = 0;
5374 view->x = 0;
5376 diff_view_indicate_progress(view);
5377 err = create_diff(s);
5378 break;
5379 default:
5380 view->count = 0;
5381 break;
5384 return err;
5387 static const struct got_error *
5388 cmd_diff(int argc, char *argv[])
5390 const struct got_error *error = NULL;
5391 struct got_repository *repo = NULL;
5392 struct got_worktree *worktree = NULL;
5393 struct got_object_id *id1 = NULL, *id2 = NULL;
5394 char *repo_path = NULL, *cwd = NULL;
5395 char *id_str1 = NULL, *id_str2 = NULL;
5396 char *label1 = NULL, *label2 = NULL;
5397 int diff_context = 3, ignore_whitespace = 0;
5398 int ch, force_text_diff = 0;
5399 const char *errstr;
5400 struct tog_view *view;
5401 int *pack_fds = NULL;
5403 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5404 switch (ch) {
5405 case 'a':
5406 force_text_diff = 1;
5407 break;
5408 case 'C':
5409 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5410 &errstr);
5411 if (errstr != NULL)
5412 errx(1, "number of context lines is %s: %s",
5413 errstr, errstr);
5414 break;
5415 case 'r':
5416 repo_path = realpath(optarg, NULL);
5417 if (repo_path == NULL)
5418 return got_error_from_errno2("realpath",
5419 optarg);
5420 got_path_strip_trailing_slashes(repo_path);
5421 break;
5422 case 'w':
5423 ignore_whitespace = 1;
5424 break;
5425 default:
5426 usage_diff();
5427 /* NOTREACHED */
5431 argc -= optind;
5432 argv += optind;
5434 if (argc == 0) {
5435 usage_diff(); /* TODO show local worktree changes */
5436 } else if (argc == 2) {
5437 id_str1 = argv[0];
5438 id_str2 = argv[1];
5439 } else
5440 usage_diff();
5442 error = got_repo_pack_fds_open(&pack_fds);
5443 if (error)
5444 goto done;
5446 if (repo_path == NULL) {
5447 cwd = getcwd(NULL, 0);
5448 if (cwd == NULL)
5449 return got_error_from_errno("getcwd");
5450 error = got_worktree_open(&worktree, cwd);
5451 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5452 goto done;
5453 if (worktree)
5454 repo_path =
5455 strdup(got_worktree_get_repo_path(worktree));
5456 else
5457 repo_path = strdup(cwd);
5458 if (repo_path == NULL) {
5459 error = got_error_from_errno("strdup");
5460 goto done;
5464 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5465 if (error)
5466 goto done;
5468 init_curses();
5470 error = apply_unveil(got_repo_get_path(repo), NULL);
5471 if (error)
5472 goto done;
5474 error = tog_load_refs(repo, 0);
5475 if (error)
5476 goto done;
5478 error = got_repo_match_object_id(&id1, &label1, id_str1,
5479 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5480 if (error)
5481 goto done;
5483 error = got_repo_match_object_id(&id2, &label2, id_str2,
5484 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5485 if (error)
5486 goto done;
5488 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5489 if (view == NULL) {
5490 error = got_error_from_errno("view_open");
5491 goto done;
5493 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5494 ignore_whitespace, force_text_diff, NULL, repo);
5495 if (error)
5496 goto done;
5497 error = view_loop(view);
5498 done:
5499 free(label1);
5500 free(label2);
5501 free(repo_path);
5502 free(cwd);
5503 if (repo) {
5504 const struct got_error *close_err = got_repo_close(repo);
5505 if (error == NULL)
5506 error = close_err;
5508 if (worktree)
5509 got_worktree_close(worktree);
5510 if (pack_fds) {
5511 const struct got_error *pack_err =
5512 got_repo_pack_fds_close(pack_fds);
5513 if (error == NULL)
5514 error = pack_err;
5516 tog_free_refs();
5517 return error;
5520 __dead static void
5521 usage_blame(void)
5523 endwin();
5524 fprintf(stderr,
5525 "usage: %s blame [-c commit] [-r repository-path] path\n",
5526 getprogname());
5527 exit(1);
5530 struct tog_blame_line {
5531 int annotated;
5532 struct got_object_id *id;
5535 static const struct got_error *
5536 draw_blame(struct tog_view *view)
5538 struct tog_blame_view_state *s = &view->state.blame;
5539 struct tog_blame *blame = &s->blame;
5540 regmatch_t *regmatch = &view->regmatch;
5541 const struct got_error *err;
5542 int lineno = 0, nprinted = 0;
5543 char *line = NULL;
5544 size_t linesize = 0;
5545 ssize_t linelen;
5546 wchar_t *wline;
5547 int width;
5548 struct tog_blame_line *blame_line;
5549 struct got_object_id *prev_id = NULL;
5550 char *id_str;
5551 struct tog_color *tc;
5553 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5554 if (err)
5555 return err;
5557 rewind(blame->f);
5558 werase(view->window);
5560 if (asprintf(&line, "commit %s", id_str) == -1) {
5561 err = got_error_from_errno("asprintf");
5562 free(id_str);
5563 return err;
5566 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5567 free(line);
5568 line = NULL;
5569 if (err)
5570 return err;
5571 if (view_needs_focus_indication(view))
5572 wstandout(view->window);
5573 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5574 if (tc)
5575 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5576 waddwstr(view->window, wline);
5577 while (width++ < view->ncols)
5578 waddch(view->window, ' ');
5579 if (tc)
5580 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5581 if (view_needs_focus_indication(view))
5582 wstandend(view->window);
5583 free(wline);
5584 wline = NULL;
5586 if (view->gline > blame->nlines)
5587 view->gline = blame->nlines;
5589 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5590 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5591 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5592 free(id_str);
5593 return got_error_from_errno("asprintf");
5595 free(id_str);
5596 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5597 free(line);
5598 line = NULL;
5599 if (err)
5600 return err;
5601 waddwstr(view->window, wline);
5602 free(wline);
5603 wline = NULL;
5604 if (width < view->ncols - 1)
5605 waddch(view->window, '\n');
5607 s->eof = 0;
5608 view->maxx = 0;
5609 while (nprinted < view->nlines - 2) {
5610 linelen = getline(&line, &linesize, blame->f);
5611 if (linelen == -1) {
5612 if (feof(blame->f)) {
5613 s->eof = 1;
5614 break;
5616 free(line);
5617 return got_ferror(blame->f, GOT_ERR_IO);
5619 if (++lineno < s->first_displayed_line)
5620 continue;
5621 if (view->gline && !gotoline(view, &lineno, &nprinted))
5622 continue;
5624 /* Set view->maxx based on full line length. */
5625 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5626 if (err) {
5627 free(line);
5628 return err;
5630 free(wline);
5631 wline = NULL;
5632 view->maxx = MAX(view->maxx, width);
5634 if (nprinted == s->selected_line - 1)
5635 wstandout(view->window);
5637 if (blame->nlines > 0) {
5638 blame_line = &blame->lines[lineno - 1];
5639 if (blame_line->annotated && prev_id &&
5640 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5641 !(nprinted == s->selected_line - 1)) {
5642 waddstr(view->window, " ");
5643 } else if (blame_line->annotated) {
5644 char *id_str;
5645 err = got_object_id_str(&id_str,
5646 blame_line->id);
5647 if (err) {
5648 free(line);
5649 return err;
5651 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5652 if (tc)
5653 wattr_on(view->window,
5654 COLOR_PAIR(tc->colorpair), NULL);
5655 wprintw(view->window, "%.8s", id_str);
5656 if (tc)
5657 wattr_off(view->window,
5658 COLOR_PAIR(tc->colorpair), NULL);
5659 free(id_str);
5660 prev_id = blame_line->id;
5661 } else {
5662 waddstr(view->window, "........");
5663 prev_id = NULL;
5665 } else {
5666 waddstr(view->window, "........");
5667 prev_id = NULL;
5670 if (nprinted == s->selected_line - 1)
5671 wstandend(view->window);
5672 waddstr(view->window, " ");
5674 if (view->ncols <= 9) {
5675 width = 9;
5676 } else if (s->first_displayed_line + nprinted ==
5677 s->matched_line &&
5678 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5679 err = add_matched_line(&width, line, view->ncols - 9, 9,
5680 view->window, view->x, regmatch);
5681 if (err) {
5682 free(line);
5683 return err;
5685 width += 9;
5686 } else {
5687 int skip;
5688 err = format_line(&wline, &width, &skip, line,
5689 view->x, view->ncols - 9, 9, 1);
5690 if (err) {
5691 free(line);
5692 return err;
5694 waddwstr(view->window, &wline[skip]);
5695 width += 9;
5696 free(wline);
5697 wline = NULL;
5700 if (width <= view->ncols - 1)
5701 waddch(view->window, '\n');
5702 if (++nprinted == 1)
5703 s->first_displayed_line = lineno;
5705 free(line);
5706 s->last_displayed_line = lineno;
5708 view_border(view);
5710 return NULL;
5713 static const struct got_error *
5714 blame_cb(void *arg, int nlines, int lineno,
5715 struct got_commit_object *commit, struct got_object_id *id)
5717 const struct got_error *err = NULL;
5718 struct tog_blame_cb_args *a = arg;
5719 struct tog_blame_line *line;
5720 int errcode;
5722 if (nlines != a->nlines ||
5723 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5724 return got_error(GOT_ERR_RANGE);
5726 errcode = pthread_mutex_lock(&tog_mutex);
5727 if (errcode)
5728 return got_error_set_errno(errcode, "pthread_mutex_lock");
5730 if (*a->quit) { /* user has quit the blame view */
5731 err = got_error(GOT_ERR_ITER_COMPLETED);
5732 goto done;
5735 if (lineno == -1)
5736 goto done; /* no change in this commit */
5738 line = &a->lines[lineno - 1];
5739 if (line->annotated)
5740 goto done;
5742 line->id = got_object_id_dup(id);
5743 if (line->id == NULL) {
5744 err = got_error_from_errno("got_object_id_dup");
5745 goto done;
5747 line->annotated = 1;
5748 done:
5749 errcode = pthread_mutex_unlock(&tog_mutex);
5750 if (errcode)
5751 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5752 return err;
5755 static void *
5756 blame_thread(void *arg)
5758 const struct got_error *err, *close_err;
5759 struct tog_blame_thread_args *ta = arg;
5760 struct tog_blame_cb_args *a = ta->cb_args;
5761 int errcode, fd1 = -1, fd2 = -1;
5762 FILE *f1 = NULL, *f2 = NULL;
5764 fd1 = got_opentempfd();
5765 if (fd1 == -1)
5766 return (void *)got_error_from_errno("got_opentempfd");
5768 fd2 = got_opentempfd();
5769 if (fd2 == -1) {
5770 err = got_error_from_errno("got_opentempfd");
5771 goto done;
5774 f1 = got_opentemp();
5775 if (f1 == NULL) {
5776 err = (void *)got_error_from_errno("got_opentemp");
5777 goto done;
5779 f2 = got_opentemp();
5780 if (f2 == NULL) {
5781 err = (void *)got_error_from_errno("got_opentemp");
5782 goto done;
5785 err = block_signals_used_by_main_thread();
5786 if (err)
5787 goto done;
5789 err = got_blame(ta->path, a->commit_id, ta->repo,
5790 tog_diff_algo, blame_cb, ta->cb_args,
5791 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5792 if (err && err->code == GOT_ERR_CANCELLED)
5793 err = NULL;
5795 errcode = pthread_mutex_lock(&tog_mutex);
5796 if (errcode) {
5797 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5798 goto done;
5801 close_err = got_repo_close(ta->repo);
5802 if (err == NULL)
5803 err = close_err;
5804 ta->repo = NULL;
5805 *ta->complete = 1;
5807 errcode = pthread_mutex_unlock(&tog_mutex);
5808 if (errcode && err == NULL)
5809 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5811 done:
5812 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5813 err = got_error_from_errno("close");
5814 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5815 err = got_error_from_errno("close");
5816 if (f1 && fclose(f1) == EOF && err == NULL)
5817 err = got_error_from_errno("fclose");
5818 if (f2 && fclose(f2) == EOF && err == NULL)
5819 err = got_error_from_errno("fclose");
5821 return (void *)err;
5824 static struct got_object_id *
5825 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5826 int first_displayed_line, int selected_line)
5828 struct tog_blame_line *line;
5830 if (nlines <= 0)
5831 return NULL;
5833 line = &lines[first_displayed_line - 1 + selected_line - 1];
5834 if (!line->annotated)
5835 return NULL;
5837 return line->id;
5840 static struct got_object_id *
5841 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5842 int lineno)
5844 struct tog_blame_line *line;
5846 if (nlines <= 0 || lineno >= nlines)
5847 return NULL;
5849 line = &lines[lineno - 1];
5850 if (!line->annotated)
5851 return NULL;
5853 return line->id;
5856 static const struct got_error *
5857 stop_blame(struct tog_blame *blame)
5859 const struct got_error *err = NULL;
5860 int i;
5862 if (blame->thread) {
5863 int errcode;
5864 errcode = pthread_mutex_unlock(&tog_mutex);
5865 if (errcode)
5866 return got_error_set_errno(errcode,
5867 "pthread_mutex_unlock");
5868 errcode = pthread_join(blame->thread, (void **)&err);
5869 if (errcode)
5870 return got_error_set_errno(errcode, "pthread_join");
5871 errcode = pthread_mutex_lock(&tog_mutex);
5872 if (errcode)
5873 return got_error_set_errno(errcode,
5874 "pthread_mutex_lock");
5875 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5876 err = NULL;
5877 blame->thread = NULL;
5879 if (blame->thread_args.repo) {
5880 const struct got_error *close_err;
5881 close_err = got_repo_close(blame->thread_args.repo);
5882 if (err == NULL)
5883 err = close_err;
5884 blame->thread_args.repo = NULL;
5886 if (blame->f) {
5887 if (fclose(blame->f) == EOF && err == NULL)
5888 err = got_error_from_errno("fclose");
5889 blame->f = NULL;
5891 if (blame->lines) {
5892 for (i = 0; i < blame->nlines; i++)
5893 free(blame->lines[i].id);
5894 free(blame->lines);
5895 blame->lines = NULL;
5897 free(blame->cb_args.commit_id);
5898 blame->cb_args.commit_id = NULL;
5899 if (blame->pack_fds) {
5900 const struct got_error *pack_err =
5901 got_repo_pack_fds_close(blame->pack_fds);
5902 if (err == NULL)
5903 err = pack_err;
5904 blame->pack_fds = NULL;
5906 return err;
5909 static const struct got_error *
5910 cancel_blame_view(void *arg)
5912 const struct got_error *err = NULL;
5913 int *done = arg;
5914 int errcode;
5916 errcode = pthread_mutex_lock(&tog_mutex);
5917 if (errcode)
5918 return got_error_set_errno(errcode,
5919 "pthread_mutex_unlock");
5921 if (*done)
5922 err = got_error(GOT_ERR_CANCELLED);
5924 errcode = pthread_mutex_unlock(&tog_mutex);
5925 if (errcode)
5926 return got_error_set_errno(errcode,
5927 "pthread_mutex_lock");
5929 return err;
5932 static const struct got_error *
5933 run_blame(struct tog_view *view)
5935 struct tog_blame_view_state *s = &view->state.blame;
5936 struct tog_blame *blame = &s->blame;
5937 const struct got_error *err = NULL;
5938 struct got_commit_object *commit = NULL;
5939 struct got_blob_object *blob = NULL;
5940 struct got_repository *thread_repo = NULL;
5941 struct got_object_id *obj_id = NULL;
5942 int obj_type, fd = -1;
5943 int *pack_fds = NULL;
5945 err = got_object_open_as_commit(&commit, s->repo,
5946 &s->blamed_commit->id);
5947 if (err)
5948 return err;
5950 fd = got_opentempfd();
5951 if (fd == -1) {
5952 err = got_error_from_errno("got_opentempfd");
5953 goto done;
5956 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5957 if (err)
5958 goto done;
5960 err = got_object_get_type(&obj_type, s->repo, obj_id);
5961 if (err)
5962 goto done;
5964 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5965 err = got_error(GOT_ERR_OBJ_TYPE);
5966 goto done;
5969 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5970 if (err)
5971 goto done;
5972 blame->f = got_opentemp();
5973 if (blame->f == NULL) {
5974 err = got_error_from_errno("got_opentemp");
5975 goto done;
5977 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5978 &blame->line_offsets, blame->f, blob);
5979 if (err)
5980 goto done;
5981 if (blame->nlines == 0) {
5982 s->blame_complete = 1;
5983 goto done;
5986 /* Don't include \n at EOF in the blame line count. */
5987 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5988 blame->nlines--;
5990 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5991 if (blame->lines == NULL) {
5992 err = got_error_from_errno("calloc");
5993 goto done;
5996 err = got_repo_pack_fds_open(&pack_fds);
5997 if (err)
5998 goto done;
5999 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6000 pack_fds);
6001 if (err)
6002 goto done;
6004 blame->pack_fds = pack_fds;
6005 blame->cb_args.view = view;
6006 blame->cb_args.lines = blame->lines;
6007 blame->cb_args.nlines = blame->nlines;
6008 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6009 if (blame->cb_args.commit_id == NULL) {
6010 err = got_error_from_errno("got_object_id_dup");
6011 goto done;
6013 blame->cb_args.quit = &s->done;
6015 blame->thread_args.path = s->path;
6016 blame->thread_args.repo = thread_repo;
6017 blame->thread_args.cb_args = &blame->cb_args;
6018 blame->thread_args.complete = &s->blame_complete;
6019 blame->thread_args.cancel_cb = cancel_blame_view;
6020 blame->thread_args.cancel_arg = &s->done;
6021 s->blame_complete = 0;
6023 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6024 s->first_displayed_line = 1;
6025 s->last_displayed_line = view->nlines;
6026 s->selected_line = 1;
6028 s->matched_line = 0;
6030 done:
6031 if (commit)
6032 got_object_commit_close(commit);
6033 if (fd != -1 && close(fd) == -1 && err == NULL)
6034 err = got_error_from_errno("close");
6035 if (blob)
6036 got_object_blob_close(blob);
6037 free(obj_id);
6038 if (err)
6039 stop_blame(blame);
6040 return err;
6043 static const struct got_error *
6044 open_blame_view(struct tog_view *view, char *path,
6045 struct got_object_id *commit_id, struct got_repository *repo)
6047 const struct got_error *err = NULL;
6048 struct tog_blame_view_state *s = &view->state.blame;
6050 STAILQ_INIT(&s->blamed_commits);
6052 s->path = strdup(path);
6053 if (s->path == NULL)
6054 return got_error_from_errno("strdup");
6056 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6057 if (err) {
6058 free(s->path);
6059 return err;
6062 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6063 s->first_displayed_line = 1;
6064 s->last_displayed_line = view->nlines;
6065 s->selected_line = 1;
6066 s->blame_complete = 0;
6067 s->repo = repo;
6068 s->commit_id = commit_id;
6069 memset(&s->blame, 0, sizeof(s->blame));
6071 STAILQ_INIT(&s->colors);
6072 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6073 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6074 get_color_value("TOG_COLOR_COMMIT"));
6075 if (err)
6076 return err;
6079 view->show = show_blame_view;
6080 view->input = input_blame_view;
6081 view->reset = reset_blame_view;
6082 view->close = close_blame_view;
6083 view->search_start = search_start_blame_view;
6084 view->search_setup = search_setup_blame_view;
6085 view->search_next = search_next_view_match;
6087 return run_blame(view);
6090 static const struct got_error *
6091 close_blame_view(struct tog_view *view)
6093 const struct got_error *err = NULL;
6094 struct tog_blame_view_state *s = &view->state.blame;
6096 if (s->blame.thread)
6097 err = stop_blame(&s->blame);
6099 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6100 struct got_object_qid *blamed_commit;
6101 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6102 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6103 got_object_qid_free(blamed_commit);
6106 free(s->path);
6107 free_colors(&s->colors);
6108 return err;
6111 static const struct got_error *
6112 search_start_blame_view(struct tog_view *view)
6114 struct tog_blame_view_state *s = &view->state.blame;
6116 s->matched_line = 0;
6117 return NULL;
6120 static void
6121 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6122 size_t *nlines, int **first, int **last, int **match, int **selected)
6124 struct tog_blame_view_state *s = &view->state.blame;
6126 *f = s->blame.f;
6127 *nlines = s->blame.nlines;
6128 *line_offsets = s->blame.line_offsets;
6129 *match = &s->matched_line;
6130 *first = &s->first_displayed_line;
6131 *last = &s->last_displayed_line;
6132 *selected = &s->selected_line;
6135 static const struct got_error *
6136 show_blame_view(struct tog_view *view)
6138 const struct got_error *err = NULL;
6139 struct tog_blame_view_state *s = &view->state.blame;
6140 int errcode;
6142 if (s->blame.thread == NULL && !s->blame_complete) {
6143 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6144 &s->blame.thread_args);
6145 if (errcode)
6146 return got_error_set_errno(errcode, "pthread_create");
6148 halfdelay(1); /* fast refresh while annotating */
6151 if (s->blame_complete)
6152 halfdelay(10); /* disable fast refresh */
6154 err = draw_blame(view);
6156 view_border(view);
6157 return err;
6160 static const struct got_error *
6161 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6162 struct got_repository *repo, struct got_object_id *id)
6164 struct tog_view *log_view;
6165 const struct got_error *err = NULL;
6167 *new_view = NULL;
6169 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6170 if (log_view == NULL)
6171 return got_error_from_errno("view_open");
6173 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6174 if (err)
6175 view_close(log_view);
6176 else
6177 *new_view = log_view;
6179 return err;
6182 static const struct got_error *
6183 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6185 const struct got_error *err = NULL, *thread_err = NULL;
6186 struct tog_view *diff_view;
6187 struct tog_blame_view_state *s = &view->state.blame;
6188 int eos, nscroll, begin_y = 0, begin_x = 0;
6190 eos = nscroll = view->nlines - 2;
6191 if (view_is_hsplit_top(view))
6192 --eos; /* border */
6194 switch (ch) {
6195 case '0':
6196 view->x = 0;
6197 break;
6198 case '$':
6199 view->x = MAX(view->maxx - view->ncols / 3, 0);
6200 view->count = 0;
6201 break;
6202 case KEY_RIGHT:
6203 case 'l':
6204 if (view->x + view->ncols / 3 < view->maxx)
6205 view->x += 2; /* move two columns right */
6206 else
6207 view->count = 0;
6208 break;
6209 case KEY_LEFT:
6210 case 'h':
6211 view->x -= MIN(view->x, 2); /* move two columns back */
6212 if (view->x <= 0)
6213 view->count = 0;
6214 break;
6215 case 'q':
6216 s->done = 1;
6217 break;
6218 case 'g':
6219 case KEY_HOME:
6220 s->selected_line = 1;
6221 s->first_displayed_line = 1;
6222 view->count = 0;
6223 break;
6224 case 'G':
6225 case KEY_END:
6226 if (s->blame.nlines < eos) {
6227 s->selected_line = s->blame.nlines;
6228 s->first_displayed_line = 1;
6229 } else {
6230 s->selected_line = eos;
6231 s->first_displayed_line = s->blame.nlines - (eos - 1);
6233 view->count = 0;
6234 break;
6235 case 'k':
6236 case KEY_UP:
6237 case CTRL('p'):
6238 if (s->selected_line > 1)
6239 s->selected_line--;
6240 else if (s->selected_line == 1 &&
6241 s->first_displayed_line > 1)
6242 s->first_displayed_line--;
6243 else
6244 view->count = 0;
6245 break;
6246 case CTRL('u'):
6247 case 'u':
6248 nscroll /= 2;
6249 /* FALL THROUGH */
6250 case KEY_PPAGE:
6251 case CTRL('b'):
6252 case 'b':
6253 if (s->first_displayed_line == 1) {
6254 if (view->count > 1)
6255 nscroll += nscroll;
6256 s->selected_line = MAX(1, s->selected_line - nscroll);
6257 view->count = 0;
6258 break;
6260 if (s->first_displayed_line > nscroll)
6261 s->first_displayed_line -= nscroll;
6262 else
6263 s->first_displayed_line = 1;
6264 break;
6265 case 'j':
6266 case KEY_DOWN:
6267 case CTRL('n'):
6268 if (s->selected_line < eos && s->first_displayed_line +
6269 s->selected_line <= s->blame.nlines)
6270 s->selected_line++;
6271 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6272 s->first_displayed_line++;
6273 else
6274 view->count = 0;
6275 break;
6276 case 'c':
6277 case 'p': {
6278 struct got_object_id *id = NULL;
6280 view->count = 0;
6281 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6282 s->first_displayed_line, s->selected_line);
6283 if (id == NULL)
6284 break;
6285 if (ch == 'p') {
6286 struct got_commit_object *commit, *pcommit;
6287 struct got_object_qid *pid;
6288 struct got_object_id *blob_id = NULL;
6289 int obj_type;
6290 err = got_object_open_as_commit(&commit,
6291 s->repo, id);
6292 if (err)
6293 break;
6294 pid = STAILQ_FIRST(
6295 got_object_commit_get_parent_ids(commit));
6296 if (pid == NULL) {
6297 got_object_commit_close(commit);
6298 break;
6300 /* Check if path history ends here. */
6301 err = got_object_open_as_commit(&pcommit,
6302 s->repo, &pid->id);
6303 if (err)
6304 break;
6305 err = got_object_id_by_path(&blob_id, s->repo,
6306 pcommit, s->path);
6307 got_object_commit_close(pcommit);
6308 if (err) {
6309 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6310 err = NULL;
6311 got_object_commit_close(commit);
6312 break;
6314 err = got_object_get_type(&obj_type, s->repo,
6315 blob_id);
6316 free(blob_id);
6317 /* Can't blame non-blob type objects. */
6318 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6319 got_object_commit_close(commit);
6320 break;
6322 err = got_object_qid_alloc(&s->blamed_commit,
6323 &pid->id);
6324 got_object_commit_close(commit);
6325 } else {
6326 if (got_object_id_cmp(id,
6327 &s->blamed_commit->id) == 0)
6328 break;
6329 err = got_object_qid_alloc(&s->blamed_commit,
6330 id);
6332 if (err)
6333 break;
6334 s->done = 1;
6335 thread_err = stop_blame(&s->blame);
6336 s->done = 0;
6337 if (thread_err)
6338 break;
6339 STAILQ_INSERT_HEAD(&s->blamed_commits,
6340 s->blamed_commit, entry);
6341 err = run_blame(view);
6342 if (err)
6343 break;
6344 break;
6346 case 'C': {
6347 struct got_object_qid *first;
6349 view->count = 0;
6350 first = STAILQ_FIRST(&s->blamed_commits);
6351 if (!got_object_id_cmp(&first->id, s->commit_id))
6352 break;
6353 s->done = 1;
6354 thread_err = stop_blame(&s->blame);
6355 s->done = 0;
6356 if (thread_err)
6357 break;
6358 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6359 got_object_qid_free(s->blamed_commit);
6360 s->blamed_commit =
6361 STAILQ_FIRST(&s->blamed_commits);
6362 err = run_blame(view);
6363 if (err)
6364 break;
6365 break;
6367 case 'L':
6368 view->count = 0;
6369 s->id_to_log = get_selected_commit_id(s->blame.lines,
6370 s->blame.nlines, s->first_displayed_line, s->selected_line);
6371 if (s->id_to_log)
6372 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6373 break;
6374 case KEY_ENTER:
6375 case '\r': {
6376 struct got_object_id *id = NULL;
6377 struct got_object_qid *pid;
6378 struct got_commit_object *commit = NULL;
6380 view->count = 0;
6381 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6382 s->first_displayed_line, s->selected_line);
6383 if (id == NULL)
6384 break;
6385 err = got_object_open_as_commit(&commit, s->repo, id);
6386 if (err)
6387 break;
6388 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6389 if (*new_view) {
6390 /* traversed from diff view, release diff resources */
6391 err = close_diff_view(*new_view);
6392 if (err)
6393 break;
6394 diff_view = *new_view;
6395 } else {
6396 if (view_is_parent_view(view))
6397 view_get_split(view, &begin_y, &begin_x);
6399 diff_view = view_open(0, 0, begin_y, begin_x,
6400 TOG_VIEW_DIFF);
6401 if (diff_view == NULL) {
6402 got_object_commit_close(commit);
6403 err = got_error_from_errno("view_open");
6404 break;
6407 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6408 id, NULL, NULL, 3, 0, 0, view, s->repo);
6409 got_object_commit_close(commit);
6410 if (err) {
6411 view_close(diff_view);
6412 break;
6414 s->last_diffed_line = s->first_displayed_line - 1 +
6415 s->selected_line;
6416 if (*new_view)
6417 break; /* still open from active diff view */
6418 if (view_is_parent_view(view) &&
6419 view->mode == TOG_VIEW_SPLIT_HRZN) {
6420 err = view_init_hsplit(view, begin_y);
6421 if (err)
6422 break;
6425 view->focussed = 0;
6426 diff_view->focussed = 1;
6427 diff_view->mode = view->mode;
6428 diff_view->nlines = view->lines - begin_y;
6429 if (view_is_parent_view(view)) {
6430 view_transfer_size(diff_view, view);
6431 err = view_close_child(view);
6432 if (err)
6433 break;
6434 err = view_set_child(view, diff_view);
6435 if (err)
6436 break;
6437 view->focus_child = 1;
6438 } else
6439 *new_view = diff_view;
6440 if (err)
6441 break;
6442 break;
6444 case CTRL('d'):
6445 case 'd':
6446 nscroll /= 2;
6447 /* FALL THROUGH */
6448 case KEY_NPAGE:
6449 case CTRL('f'):
6450 case 'f':
6451 case ' ':
6452 if (s->last_displayed_line >= s->blame.nlines &&
6453 s->selected_line >= MIN(s->blame.nlines,
6454 view->nlines - 2)) {
6455 view->count = 0;
6456 break;
6458 if (s->last_displayed_line >= s->blame.nlines &&
6459 s->selected_line < view->nlines - 2) {
6460 s->selected_line +=
6461 MIN(nscroll, s->last_displayed_line -
6462 s->first_displayed_line - s->selected_line + 1);
6464 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6465 s->first_displayed_line += nscroll;
6466 else
6467 s->first_displayed_line =
6468 s->blame.nlines - (view->nlines - 3);
6469 break;
6470 case KEY_RESIZE:
6471 if (s->selected_line > view->nlines - 2) {
6472 s->selected_line = MIN(s->blame.nlines,
6473 view->nlines - 2);
6475 break;
6476 default:
6477 view->count = 0;
6478 break;
6480 return thread_err ? thread_err : err;
6483 static const struct got_error *
6484 reset_blame_view(struct tog_view *view)
6486 const struct got_error *err;
6487 struct tog_blame_view_state *s = &view->state.blame;
6489 view->count = 0;
6490 s->done = 1;
6491 err = stop_blame(&s->blame);
6492 s->done = 0;
6493 if (err)
6494 return err;
6495 return run_blame(view);
6498 static const struct got_error *
6499 cmd_blame(int argc, char *argv[])
6501 const struct got_error *error;
6502 struct got_repository *repo = NULL;
6503 struct got_worktree *worktree = NULL;
6504 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6505 char *link_target = NULL;
6506 struct got_object_id *commit_id = NULL;
6507 struct got_commit_object *commit = NULL;
6508 char *commit_id_str = NULL;
6509 int ch;
6510 struct tog_view *view;
6511 int *pack_fds = NULL;
6513 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6514 switch (ch) {
6515 case 'c':
6516 commit_id_str = optarg;
6517 break;
6518 case 'r':
6519 repo_path = realpath(optarg, NULL);
6520 if (repo_path == NULL)
6521 return got_error_from_errno2("realpath",
6522 optarg);
6523 break;
6524 default:
6525 usage_blame();
6526 /* NOTREACHED */
6530 argc -= optind;
6531 argv += optind;
6533 if (argc != 1)
6534 usage_blame();
6536 error = got_repo_pack_fds_open(&pack_fds);
6537 if (error != NULL)
6538 goto done;
6540 if (repo_path == NULL) {
6541 cwd = getcwd(NULL, 0);
6542 if (cwd == NULL)
6543 return got_error_from_errno("getcwd");
6544 error = got_worktree_open(&worktree, cwd);
6545 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6546 goto done;
6547 if (worktree)
6548 repo_path =
6549 strdup(got_worktree_get_repo_path(worktree));
6550 else
6551 repo_path = strdup(cwd);
6552 if (repo_path == NULL) {
6553 error = got_error_from_errno("strdup");
6554 goto done;
6558 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6559 if (error != NULL)
6560 goto done;
6562 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6563 worktree);
6564 if (error)
6565 goto done;
6567 init_curses();
6569 error = apply_unveil(got_repo_get_path(repo), NULL);
6570 if (error)
6571 goto done;
6573 error = tog_load_refs(repo, 0);
6574 if (error)
6575 goto done;
6577 if (commit_id_str == NULL) {
6578 struct got_reference *head_ref;
6579 error = got_ref_open(&head_ref, repo, worktree ?
6580 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6581 if (error != NULL)
6582 goto done;
6583 error = got_ref_resolve(&commit_id, repo, head_ref);
6584 got_ref_close(head_ref);
6585 } else {
6586 error = got_repo_match_object_id(&commit_id, NULL,
6587 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6589 if (error != NULL)
6590 goto done;
6592 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6593 if (view == NULL) {
6594 error = got_error_from_errno("view_open");
6595 goto done;
6598 error = got_object_open_as_commit(&commit, repo, commit_id);
6599 if (error)
6600 goto done;
6602 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6603 commit, repo);
6604 if (error)
6605 goto done;
6607 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6608 commit_id, repo);
6609 if (error)
6610 goto done;
6611 if (worktree) {
6612 /* Release work tree lock. */
6613 got_worktree_close(worktree);
6614 worktree = NULL;
6616 error = view_loop(view);
6617 done:
6618 free(repo_path);
6619 free(in_repo_path);
6620 free(link_target);
6621 free(cwd);
6622 free(commit_id);
6623 if (commit)
6624 got_object_commit_close(commit);
6625 if (worktree)
6626 got_worktree_close(worktree);
6627 if (repo) {
6628 const struct got_error *close_err = got_repo_close(repo);
6629 if (error == NULL)
6630 error = close_err;
6632 if (pack_fds) {
6633 const struct got_error *pack_err =
6634 got_repo_pack_fds_close(pack_fds);
6635 if (error == NULL)
6636 error = pack_err;
6638 tog_free_refs();
6639 return error;
6642 static const struct got_error *
6643 draw_tree_entries(struct tog_view *view, const char *parent_path)
6645 struct tog_tree_view_state *s = &view->state.tree;
6646 const struct got_error *err = NULL;
6647 struct got_tree_entry *te;
6648 wchar_t *wline;
6649 char *index = NULL;
6650 struct tog_color *tc;
6651 int width, n, nentries, i = 1;
6652 int limit = view->nlines;
6654 s->ndisplayed = 0;
6655 if (view_is_hsplit_top(view))
6656 --limit; /* border */
6658 werase(view->window);
6660 if (limit == 0)
6661 return NULL;
6663 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6664 0, 0);
6665 if (err)
6666 return err;
6667 if (view_needs_focus_indication(view))
6668 wstandout(view->window);
6669 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6670 if (tc)
6671 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6672 waddwstr(view->window, wline);
6673 free(wline);
6674 wline = NULL;
6675 while (width++ < view->ncols)
6676 waddch(view->window, ' ');
6677 if (tc)
6678 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6679 if (view_needs_focus_indication(view))
6680 wstandend(view->window);
6681 if (--limit <= 0)
6682 return NULL;
6684 i += s->selected;
6685 if (s->first_displayed_entry) {
6686 i += got_tree_entry_get_index(s->first_displayed_entry);
6687 if (s->tree != s->root)
6688 ++i; /* account for ".." entry */
6690 nentries = got_object_tree_get_nentries(s->tree);
6691 if (asprintf(&index, "[%d/%d] %s",
6692 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6693 return got_error_from_errno("asprintf");
6694 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6695 free(index);
6696 if (err)
6697 return err;
6698 waddwstr(view->window, wline);
6699 free(wline);
6700 wline = NULL;
6701 if (width < view->ncols - 1)
6702 waddch(view->window, '\n');
6703 if (--limit <= 0)
6704 return NULL;
6705 waddch(view->window, '\n');
6706 if (--limit <= 0)
6707 return NULL;
6709 if (s->first_displayed_entry == NULL) {
6710 te = got_object_tree_get_first_entry(s->tree);
6711 if (s->selected == 0) {
6712 if (view->focussed)
6713 wstandout(view->window);
6714 s->selected_entry = NULL;
6716 waddstr(view->window, " ..\n"); /* parent directory */
6717 if (s->selected == 0 && view->focussed)
6718 wstandend(view->window);
6719 s->ndisplayed++;
6720 if (--limit <= 0)
6721 return NULL;
6722 n = 1;
6723 } else {
6724 n = 0;
6725 te = s->first_displayed_entry;
6728 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6729 char *line = NULL, *id_str = NULL, *link_target = NULL;
6730 const char *modestr = "";
6731 mode_t mode;
6733 te = got_object_tree_get_entry(s->tree, i);
6734 mode = got_tree_entry_get_mode(te);
6736 if (s->show_ids) {
6737 err = got_object_id_str(&id_str,
6738 got_tree_entry_get_id(te));
6739 if (err)
6740 return got_error_from_errno(
6741 "got_object_id_str");
6743 if (got_object_tree_entry_is_submodule(te))
6744 modestr = "$";
6745 else if (S_ISLNK(mode)) {
6746 int i;
6748 err = got_tree_entry_get_symlink_target(&link_target,
6749 te, s->repo);
6750 if (err) {
6751 free(id_str);
6752 return err;
6754 for (i = 0; i < strlen(link_target); i++) {
6755 if (!isprint((unsigned char)link_target[i]))
6756 link_target[i] = '?';
6758 modestr = "@";
6760 else if (S_ISDIR(mode))
6761 modestr = "/";
6762 else if (mode & S_IXUSR)
6763 modestr = "*";
6764 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6765 got_tree_entry_get_name(te), modestr,
6766 link_target ? " -> ": "",
6767 link_target ? link_target : "") == -1) {
6768 free(id_str);
6769 free(link_target);
6770 return got_error_from_errno("asprintf");
6772 free(id_str);
6773 free(link_target);
6774 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6775 0, 0);
6776 if (err) {
6777 free(line);
6778 break;
6780 if (n == s->selected) {
6781 if (view->focussed)
6782 wstandout(view->window);
6783 s->selected_entry = te;
6785 tc = match_color(&s->colors, line);
6786 if (tc)
6787 wattr_on(view->window,
6788 COLOR_PAIR(tc->colorpair), NULL);
6789 waddwstr(view->window, wline);
6790 if (tc)
6791 wattr_off(view->window,
6792 COLOR_PAIR(tc->colorpair), NULL);
6793 if (width < view->ncols - 1)
6794 waddch(view->window, '\n');
6795 if (n == s->selected && view->focussed)
6796 wstandend(view->window);
6797 free(line);
6798 free(wline);
6799 wline = NULL;
6800 n++;
6801 s->ndisplayed++;
6802 s->last_displayed_entry = te;
6803 if (--limit <= 0)
6804 break;
6807 return err;
6810 static void
6811 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6813 struct got_tree_entry *te;
6814 int isroot = s->tree == s->root;
6815 int i = 0;
6817 if (s->first_displayed_entry == NULL)
6818 return;
6820 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6821 while (i++ < maxscroll) {
6822 if (te == NULL) {
6823 if (!isroot)
6824 s->first_displayed_entry = NULL;
6825 break;
6827 s->first_displayed_entry = te;
6828 te = got_tree_entry_get_prev(s->tree, te);
6832 static const struct got_error *
6833 tree_scroll_down(struct tog_view *view, int maxscroll)
6835 struct tog_tree_view_state *s = &view->state.tree;
6836 struct got_tree_entry *next, *last;
6837 int n = 0;
6839 if (s->first_displayed_entry)
6840 next = got_tree_entry_get_next(s->tree,
6841 s->first_displayed_entry);
6842 else
6843 next = got_object_tree_get_first_entry(s->tree);
6845 last = s->last_displayed_entry;
6846 while (next && n++ < maxscroll) {
6847 if (last) {
6848 s->last_displayed_entry = last;
6849 last = got_tree_entry_get_next(s->tree, last);
6851 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6852 s->first_displayed_entry = next;
6853 next = got_tree_entry_get_next(s->tree, next);
6857 return NULL;
6860 static const struct got_error *
6861 tree_entry_path(char **path, struct tog_parent_trees *parents,
6862 struct got_tree_entry *te)
6864 const struct got_error *err = NULL;
6865 struct tog_parent_tree *pt;
6866 size_t len = 2; /* for leading slash and NUL */
6868 TAILQ_FOREACH(pt, parents, entry)
6869 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6870 + 1 /* slash */;
6871 if (te)
6872 len += strlen(got_tree_entry_get_name(te));
6874 *path = calloc(1, len);
6875 if (path == NULL)
6876 return got_error_from_errno("calloc");
6878 (*path)[0] = '/';
6879 pt = TAILQ_LAST(parents, tog_parent_trees);
6880 while (pt) {
6881 const char *name = got_tree_entry_get_name(pt->selected_entry);
6882 if (strlcat(*path, name, len) >= len) {
6883 err = got_error(GOT_ERR_NO_SPACE);
6884 goto done;
6886 if (strlcat(*path, "/", len) >= len) {
6887 err = got_error(GOT_ERR_NO_SPACE);
6888 goto done;
6890 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6892 if (te) {
6893 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6894 err = got_error(GOT_ERR_NO_SPACE);
6895 goto done;
6898 done:
6899 if (err) {
6900 free(*path);
6901 *path = NULL;
6903 return err;
6906 static const struct got_error *
6907 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6908 struct got_tree_entry *te, struct tog_parent_trees *parents,
6909 struct got_object_id *commit_id, struct got_repository *repo)
6911 const struct got_error *err = NULL;
6912 char *path;
6913 struct tog_view *blame_view;
6915 *new_view = NULL;
6917 err = tree_entry_path(&path, parents, te);
6918 if (err)
6919 return err;
6921 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6922 if (blame_view == NULL) {
6923 err = got_error_from_errno("view_open");
6924 goto done;
6927 err = open_blame_view(blame_view, path, commit_id, repo);
6928 if (err) {
6929 if (err->code == GOT_ERR_CANCELLED)
6930 err = NULL;
6931 view_close(blame_view);
6932 } else
6933 *new_view = blame_view;
6934 done:
6935 free(path);
6936 return err;
6939 static const struct got_error *
6940 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6941 struct tog_tree_view_state *s)
6943 struct tog_view *log_view;
6944 const struct got_error *err = NULL;
6945 char *path;
6947 *new_view = NULL;
6949 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6950 if (log_view == NULL)
6951 return got_error_from_errno("view_open");
6953 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6954 if (err)
6955 return err;
6957 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6958 path, 0);
6959 if (err)
6960 view_close(log_view);
6961 else
6962 *new_view = log_view;
6963 free(path);
6964 return err;
6967 static const struct got_error *
6968 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6969 const char *head_ref_name, struct got_repository *repo)
6971 const struct got_error *err = NULL;
6972 char *commit_id_str = NULL;
6973 struct tog_tree_view_state *s = &view->state.tree;
6974 struct got_commit_object *commit = NULL;
6976 TAILQ_INIT(&s->parents);
6977 STAILQ_INIT(&s->colors);
6979 s->commit_id = got_object_id_dup(commit_id);
6980 if (s->commit_id == NULL)
6981 return got_error_from_errno("got_object_id_dup");
6983 err = got_object_open_as_commit(&commit, repo, commit_id);
6984 if (err)
6985 goto done;
6988 * The root is opened here and will be closed when the view is closed.
6989 * Any visited subtrees and their path-wise parents are opened and
6990 * closed on demand.
6992 err = got_object_open_as_tree(&s->root, repo,
6993 got_object_commit_get_tree_id(commit));
6994 if (err)
6995 goto done;
6996 s->tree = s->root;
6998 err = got_object_id_str(&commit_id_str, commit_id);
6999 if (err != NULL)
7000 goto done;
7002 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7003 err = got_error_from_errno("asprintf");
7004 goto done;
7007 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7008 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7009 if (head_ref_name) {
7010 s->head_ref_name = strdup(head_ref_name);
7011 if (s->head_ref_name == NULL) {
7012 err = got_error_from_errno("strdup");
7013 goto done;
7016 s->repo = repo;
7018 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7019 err = add_color(&s->colors, "\\$$",
7020 TOG_COLOR_TREE_SUBMODULE,
7021 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7022 if (err)
7023 goto done;
7024 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7025 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7026 if (err)
7027 goto done;
7028 err = add_color(&s->colors, "/$",
7029 TOG_COLOR_TREE_DIRECTORY,
7030 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7031 if (err)
7032 goto done;
7034 err = add_color(&s->colors, "\\*$",
7035 TOG_COLOR_TREE_EXECUTABLE,
7036 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7037 if (err)
7038 goto done;
7040 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7041 get_color_value("TOG_COLOR_COMMIT"));
7042 if (err)
7043 goto done;
7046 view->show = show_tree_view;
7047 view->input = input_tree_view;
7048 view->close = close_tree_view;
7049 view->search_start = search_start_tree_view;
7050 view->search_next = search_next_tree_view;
7051 done:
7052 free(commit_id_str);
7053 if (commit)
7054 got_object_commit_close(commit);
7055 if (err)
7056 close_tree_view(view);
7057 return err;
7060 static const struct got_error *
7061 close_tree_view(struct tog_view *view)
7063 struct tog_tree_view_state *s = &view->state.tree;
7065 free_colors(&s->colors);
7066 free(s->tree_label);
7067 s->tree_label = NULL;
7068 free(s->commit_id);
7069 s->commit_id = NULL;
7070 free(s->head_ref_name);
7071 s->head_ref_name = NULL;
7072 while (!TAILQ_EMPTY(&s->parents)) {
7073 struct tog_parent_tree *parent;
7074 parent = TAILQ_FIRST(&s->parents);
7075 TAILQ_REMOVE(&s->parents, parent, entry);
7076 if (parent->tree != s->root)
7077 got_object_tree_close(parent->tree);
7078 free(parent);
7081 if (s->tree != NULL && s->tree != s->root)
7082 got_object_tree_close(s->tree);
7083 if (s->root)
7084 got_object_tree_close(s->root);
7085 return NULL;
7088 static const struct got_error *
7089 search_start_tree_view(struct tog_view *view)
7091 struct tog_tree_view_state *s = &view->state.tree;
7093 s->matched_entry = NULL;
7094 return NULL;
7097 static int
7098 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7100 regmatch_t regmatch;
7102 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7103 0) == 0;
7106 static const struct got_error *
7107 search_next_tree_view(struct tog_view *view)
7109 struct tog_tree_view_state *s = &view->state.tree;
7110 struct got_tree_entry *te = NULL;
7112 if (!view->searching) {
7113 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7114 return NULL;
7117 if (s->matched_entry) {
7118 if (view->searching == TOG_SEARCH_FORWARD) {
7119 if (s->selected_entry)
7120 te = got_tree_entry_get_next(s->tree,
7121 s->selected_entry);
7122 else
7123 te = got_object_tree_get_first_entry(s->tree);
7124 } else {
7125 if (s->selected_entry == NULL)
7126 te = got_object_tree_get_last_entry(s->tree);
7127 else
7128 te = got_tree_entry_get_prev(s->tree,
7129 s->selected_entry);
7131 } else {
7132 if (s->selected_entry)
7133 te = s->selected_entry;
7134 else if (view->searching == TOG_SEARCH_FORWARD)
7135 te = got_object_tree_get_first_entry(s->tree);
7136 else
7137 te = got_object_tree_get_last_entry(s->tree);
7140 while (1) {
7141 if (te == NULL) {
7142 if (s->matched_entry == NULL) {
7143 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7144 return NULL;
7146 if (view->searching == TOG_SEARCH_FORWARD)
7147 te = got_object_tree_get_first_entry(s->tree);
7148 else
7149 te = got_object_tree_get_last_entry(s->tree);
7152 if (match_tree_entry(te, &view->regex)) {
7153 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7154 s->matched_entry = te;
7155 break;
7158 if (view->searching == TOG_SEARCH_FORWARD)
7159 te = got_tree_entry_get_next(s->tree, te);
7160 else
7161 te = got_tree_entry_get_prev(s->tree, te);
7164 if (s->matched_entry) {
7165 s->first_displayed_entry = s->matched_entry;
7166 s->selected = 0;
7169 return NULL;
7172 static const struct got_error *
7173 show_tree_view(struct tog_view *view)
7175 const struct got_error *err = NULL;
7176 struct tog_tree_view_state *s = &view->state.tree;
7177 char *parent_path;
7179 err = tree_entry_path(&parent_path, &s->parents, NULL);
7180 if (err)
7181 return err;
7183 err = draw_tree_entries(view, parent_path);
7184 free(parent_path);
7186 view_border(view);
7187 return err;
7190 static const struct got_error *
7191 tree_goto_line(struct tog_view *view, int nlines)
7193 const struct got_error *err = NULL;
7194 struct tog_tree_view_state *s = &view->state.tree;
7195 struct got_tree_entry **fte, **lte, **ste;
7196 int g, last, first = 1, i = 1;
7197 int root = s->tree == s->root;
7198 int off = root ? 1 : 2;
7200 g = view->gline;
7201 view->gline = 0;
7203 if (g == 0)
7204 g = 1;
7205 else if (g > got_object_tree_get_nentries(s->tree))
7206 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7208 fte = &s->first_displayed_entry;
7209 lte = &s->last_displayed_entry;
7210 ste = &s->selected_entry;
7212 if (*fte != NULL) {
7213 first = got_tree_entry_get_index(*fte);
7214 first += off; /* account for ".." */
7216 last = got_tree_entry_get_index(*lte);
7217 last += off;
7219 if (g >= first && g <= last && g - first < nlines) {
7220 s->selected = g - first;
7221 return NULL; /* gline is on the current page */
7224 if (*ste != NULL) {
7225 i = got_tree_entry_get_index(*ste);
7226 i += off;
7229 if (i < g) {
7230 err = tree_scroll_down(view, g - i);
7231 if (err)
7232 return err;
7233 if (got_tree_entry_get_index(*lte) >=
7234 got_object_tree_get_nentries(s->tree) - 1 &&
7235 first + s->selected < g &&
7236 s->selected < s->ndisplayed - 1) {
7237 first = got_tree_entry_get_index(*fte);
7238 first += off;
7239 s->selected = g - first;
7241 } else if (i > g)
7242 tree_scroll_up(s, i - g);
7244 if (g < nlines &&
7245 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7246 s->selected = g - 1;
7248 return NULL;
7251 static const struct got_error *
7252 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7254 const struct got_error *err = NULL;
7255 struct tog_tree_view_state *s = &view->state.tree;
7256 struct got_tree_entry *te;
7257 int n, nscroll = view->nlines - 3;
7259 if (view->gline)
7260 return tree_goto_line(view, nscroll);
7262 switch (ch) {
7263 case 'i':
7264 s->show_ids = !s->show_ids;
7265 view->count = 0;
7266 break;
7267 case 'L':
7268 view->count = 0;
7269 if (!s->selected_entry)
7270 break;
7271 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7272 break;
7273 case 'R':
7274 view->count = 0;
7275 err = view_request_new(new_view, view, TOG_VIEW_REF);
7276 break;
7277 case 'g':
7278 case KEY_HOME:
7279 s->selected = 0;
7280 view->count = 0;
7281 if (s->tree == s->root)
7282 s->first_displayed_entry =
7283 got_object_tree_get_first_entry(s->tree);
7284 else
7285 s->first_displayed_entry = NULL;
7286 break;
7287 case 'G':
7288 case KEY_END: {
7289 int eos = view->nlines - 3;
7291 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7292 --eos; /* border */
7293 s->selected = 0;
7294 view->count = 0;
7295 te = got_object_tree_get_last_entry(s->tree);
7296 for (n = 0; n < eos; n++) {
7297 if (te == NULL) {
7298 if (s->tree != s->root) {
7299 s->first_displayed_entry = NULL;
7300 n++;
7302 break;
7304 s->first_displayed_entry = te;
7305 te = got_tree_entry_get_prev(s->tree, te);
7307 if (n > 0)
7308 s->selected = n - 1;
7309 break;
7311 case 'k':
7312 case KEY_UP:
7313 case CTRL('p'):
7314 if (s->selected > 0) {
7315 s->selected--;
7316 break;
7318 tree_scroll_up(s, 1);
7319 if (s->selected_entry == NULL ||
7320 (s->tree == s->root && s->selected_entry ==
7321 got_object_tree_get_first_entry(s->tree)))
7322 view->count = 0;
7323 break;
7324 case CTRL('u'):
7325 case 'u':
7326 nscroll /= 2;
7327 /* FALL THROUGH */
7328 case KEY_PPAGE:
7329 case CTRL('b'):
7330 case 'b':
7331 if (s->tree == s->root) {
7332 if (got_object_tree_get_first_entry(s->tree) ==
7333 s->first_displayed_entry)
7334 s->selected -= MIN(s->selected, nscroll);
7335 } else {
7336 if (s->first_displayed_entry == NULL)
7337 s->selected -= MIN(s->selected, nscroll);
7339 tree_scroll_up(s, MAX(0, nscroll));
7340 if (s->selected_entry == NULL ||
7341 (s->tree == s->root && s->selected_entry ==
7342 got_object_tree_get_first_entry(s->tree)))
7343 view->count = 0;
7344 break;
7345 case 'j':
7346 case KEY_DOWN:
7347 case CTRL('n'):
7348 if (s->selected < s->ndisplayed - 1) {
7349 s->selected++;
7350 break;
7352 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7353 == NULL) {
7354 /* can't scroll any further */
7355 view->count = 0;
7356 break;
7358 tree_scroll_down(view, 1);
7359 break;
7360 case CTRL('d'):
7361 case 'd':
7362 nscroll /= 2;
7363 /* FALL THROUGH */
7364 case KEY_NPAGE:
7365 case CTRL('f'):
7366 case 'f':
7367 case ' ':
7368 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7369 == NULL) {
7370 /* can't scroll any further; move cursor down */
7371 if (s->selected < s->ndisplayed - 1)
7372 s->selected += MIN(nscroll,
7373 s->ndisplayed - s->selected - 1);
7374 else
7375 view->count = 0;
7376 break;
7378 tree_scroll_down(view, nscroll);
7379 break;
7380 case KEY_ENTER:
7381 case '\r':
7382 case KEY_BACKSPACE:
7383 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7384 struct tog_parent_tree *parent;
7385 /* user selected '..' */
7386 if (s->tree == s->root) {
7387 view->count = 0;
7388 break;
7390 parent = TAILQ_FIRST(&s->parents);
7391 TAILQ_REMOVE(&s->parents, parent,
7392 entry);
7393 got_object_tree_close(s->tree);
7394 s->tree = parent->tree;
7395 s->first_displayed_entry =
7396 parent->first_displayed_entry;
7397 s->selected_entry =
7398 parent->selected_entry;
7399 s->selected = parent->selected;
7400 if (s->selected > view->nlines - 3) {
7401 err = offset_selection_down(view);
7402 if (err)
7403 break;
7405 free(parent);
7406 } else if (S_ISDIR(got_tree_entry_get_mode(
7407 s->selected_entry))) {
7408 struct got_tree_object *subtree;
7409 view->count = 0;
7410 err = got_object_open_as_tree(&subtree, s->repo,
7411 got_tree_entry_get_id(s->selected_entry));
7412 if (err)
7413 break;
7414 err = tree_view_visit_subtree(s, subtree);
7415 if (err) {
7416 got_object_tree_close(subtree);
7417 break;
7419 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7420 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7421 break;
7422 case KEY_RESIZE:
7423 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7424 s->selected = view->nlines - 4;
7425 view->count = 0;
7426 break;
7427 default:
7428 view->count = 0;
7429 break;
7432 return err;
7435 __dead static void
7436 usage_tree(void)
7438 endwin();
7439 fprintf(stderr,
7440 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7441 getprogname());
7442 exit(1);
7445 static const struct got_error *
7446 cmd_tree(int argc, char *argv[])
7448 const struct got_error *error;
7449 struct got_repository *repo = NULL;
7450 struct got_worktree *worktree = NULL;
7451 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7452 struct got_object_id *commit_id = NULL;
7453 struct got_commit_object *commit = NULL;
7454 const char *commit_id_arg = NULL;
7455 char *label = NULL;
7456 struct got_reference *ref = NULL;
7457 const char *head_ref_name = NULL;
7458 int ch;
7459 struct tog_view *view;
7460 int *pack_fds = NULL;
7462 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7463 switch (ch) {
7464 case 'c':
7465 commit_id_arg = optarg;
7466 break;
7467 case 'r':
7468 repo_path = realpath(optarg, NULL);
7469 if (repo_path == NULL)
7470 return got_error_from_errno2("realpath",
7471 optarg);
7472 break;
7473 default:
7474 usage_tree();
7475 /* NOTREACHED */
7479 argc -= optind;
7480 argv += optind;
7482 if (argc > 1)
7483 usage_tree();
7485 error = got_repo_pack_fds_open(&pack_fds);
7486 if (error != NULL)
7487 goto done;
7489 if (repo_path == NULL) {
7490 cwd = getcwd(NULL, 0);
7491 if (cwd == NULL)
7492 return got_error_from_errno("getcwd");
7493 error = got_worktree_open(&worktree, cwd);
7494 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7495 goto done;
7496 if (worktree)
7497 repo_path =
7498 strdup(got_worktree_get_repo_path(worktree));
7499 else
7500 repo_path = strdup(cwd);
7501 if (repo_path == NULL) {
7502 error = got_error_from_errno("strdup");
7503 goto done;
7507 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7508 if (error != NULL)
7509 goto done;
7511 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7512 repo, worktree);
7513 if (error)
7514 goto done;
7516 init_curses();
7518 error = apply_unveil(got_repo_get_path(repo), NULL);
7519 if (error)
7520 goto done;
7522 error = tog_load_refs(repo, 0);
7523 if (error)
7524 goto done;
7526 if (commit_id_arg == NULL) {
7527 error = got_repo_match_object_id(&commit_id, &label,
7528 worktree ? got_worktree_get_head_ref_name(worktree) :
7529 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7530 if (error)
7531 goto done;
7532 head_ref_name = label;
7533 } else {
7534 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7535 if (error == NULL)
7536 head_ref_name = got_ref_get_name(ref);
7537 else if (error->code != GOT_ERR_NOT_REF)
7538 goto done;
7539 error = got_repo_match_object_id(&commit_id, NULL,
7540 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7541 if (error)
7542 goto done;
7545 error = got_object_open_as_commit(&commit, repo, commit_id);
7546 if (error)
7547 goto done;
7549 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7550 if (view == NULL) {
7551 error = got_error_from_errno("view_open");
7552 goto done;
7554 error = open_tree_view(view, commit_id, head_ref_name, repo);
7555 if (error)
7556 goto done;
7557 if (!got_path_is_root_dir(in_repo_path)) {
7558 error = tree_view_walk_path(&view->state.tree, commit,
7559 in_repo_path);
7560 if (error)
7561 goto done;
7564 if (worktree) {
7565 /* Release work tree lock. */
7566 got_worktree_close(worktree);
7567 worktree = NULL;
7569 error = view_loop(view);
7570 done:
7571 free(repo_path);
7572 free(cwd);
7573 free(commit_id);
7574 free(label);
7575 if (ref)
7576 got_ref_close(ref);
7577 if (repo) {
7578 const struct got_error *close_err = got_repo_close(repo);
7579 if (error == NULL)
7580 error = close_err;
7582 if (pack_fds) {
7583 const struct got_error *pack_err =
7584 got_repo_pack_fds_close(pack_fds);
7585 if (error == NULL)
7586 error = pack_err;
7588 tog_free_refs();
7589 return error;
7592 static const struct got_error *
7593 ref_view_load_refs(struct tog_ref_view_state *s)
7595 struct got_reflist_entry *sre;
7596 struct tog_reflist_entry *re;
7598 s->nrefs = 0;
7599 TAILQ_FOREACH(sre, &tog_refs, entry) {
7600 if (strncmp(got_ref_get_name(sre->ref),
7601 "refs/got/", 9) == 0 &&
7602 strncmp(got_ref_get_name(sre->ref),
7603 "refs/got/backup/", 16) != 0)
7604 continue;
7606 re = malloc(sizeof(*re));
7607 if (re == NULL)
7608 return got_error_from_errno("malloc");
7610 re->ref = got_ref_dup(sre->ref);
7611 if (re->ref == NULL)
7612 return got_error_from_errno("got_ref_dup");
7613 re->idx = s->nrefs++;
7614 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7617 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7618 return NULL;
7621 static void
7622 ref_view_free_refs(struct tog_ref_view_state *s)
7624 struct tog_reflist_entry *re;
7626 while (!TAILQ_EMPTY(&s->refs)) {
7627 re = TAILQ_FIRST(&s->refs);
7628 TAILQ_REMOVE(&s->refs, re, entry);
7629 got_ref_close(re->ref);
7630 free(re);
7634 static const struct got_error *
7635 open_ref_view(struct tog_view *view, struct got_repository *repo)
7637 const struct got_error *err = NULL;
7638 struct tog_ref_view_state *s = &view->state.ref;
7640 s->selected_entry = 0;
7641 s->repo = repo;
7643 TAILQ_INIT(&s->refs);
7644 STAILQ_INIT(&s->colors);
7646 err = ref_view_load_refs(s);
7647 if (err)
7648 return err;
7650 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7651 err = add_color(&s->colors, "^refs/heads/",
7652 TOG_COLOR_REFS_HEADS,
7653 get_color_value("TOG_COLOR_REFS_HEADS"));
7654 if (err)
7655 goto done;
7657 err = add_color(&s->colors, "^refs/tags/",
7658 TOG_COLOR_REFS_TAGS,
7659 get_color_value("TOG_COLOR_REFS_TAGS"));
7660 if (err)
7661 goto done;
7663 err = add_color(&s->colors, "^refs/remotes/",
7664 TOG_COLOR_REFS_REMOTES,
7665 get_color_value("TOG_COLOR_REFS_REMOTES"));
7666 if (err)
7667 goto done;
7669 err = add_color(&s->colors, "^refs/got/backup/",
7670 TOG_COLOR_REFS_BACKUP,
7671 get_color_value("TOG_COLOR_REFS_BACKUP"));
7672 if (err)
7673 goto done;
7676 view->show = show_ref_view;
7677 view->input = input_ref_view;
7678 view->close = close_ref_view;
7679 view->search_start = search_start_ref_view;
7680 view->search_next = search_next_ref_view;
7681 done:
7682 if (err)
7683 free_colors(&s->colors);
7684 return err;
7687 static const struct got_error *
7688 close_ref_view(struct tog_view *view)
7690 struct tog_ref_view_state *s = &view->state.ref;
7692 ref_view_free_refs(s);
7693 free_colors(&s->colors);
7695 return NULL;
7698 static const struct got_error *
7699 resolve_reflist_entry(struct got_object_id **commit_id,
7700 struct tog_reflist_entry *re, struct got_repository *repo)
7702 const struct got_error *err = NULL;
7703 struct got_object_id *obj_id;
7704 struct got_tag_object *tag = NULL;
7705 int obj_type;
7707 *commit_id = NULL;
7709 err = got_ref_resolve(&obj_id, repo, re->ref);
7710 if (err)
7711 return err;
7713 err = got_object_get_type(&obj_type, repo, obj_id);
7714 if (err)
7715 goto done;
7717 switch (obj_type) {
7718 case GOT_OBJ_TYPE_COMMIT:
7719 *commit_id = obj_id;
7720 break;
7721 case GOT_OBJ_TYPE_TAG:
7722 err = got_object_open_as_tag(&tag, repo, obj_id);
7723 if (err)
7724 goto done;
7725 free(obj_id);
7726 err = got_object_get_type(&obj_type, repo,
7727 got_object_tag_get_object_id(tag));
7728 if (err)
7729 goto done;
7730 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7731 err = got_error(GOT_ERR_OBJ_TYPE);
7732 goto done;
7734 *commit_id = got_object_id_dup(
7735 got_object_tag_get_object_id(tag));
7736 if (*commit_id == NULL) {
7737 err = got_error_from_errno("got_object_id_dup");
7738 goto done;
7740 break;
7741 default:
7742 err = got_error(GOT_ERR_OBJ_TYPE);
7743 break;
7746 done:
7747 if (tag)
7748 got_object_tag_close(tag);
7749 if (err) {
7750 free(*commit_id);
7751 *commit_id = NULL;
7753 return err;
7756 static const struct got_error *
7757 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7758 struct tog_reflist_entry *re, struct got_repository *repo)
7760 struct tog_view *log_view;
7761 const struct got_error *err = NULL;
7762 struct got_object_id *commit_id = NULL;
7764 *new_view = NULL;
7766 err = resolve_reflist_entry(&commit_id, re, repo);
7767 if (err) {
7768 if (err->code != GOT_ERR_OBJ_TYPE)
7769 return err;
7770 else
7771 return NULL;
7774 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7775 if (log_view == NULL) {
7776 err = got_error_from_errno("view_open");
7777 goto done;
7780 err = open_log_view(log_view, commit_id, repo,
7781 got_ref_get_name(re->ref), "", 0);
7782 done:
7783 if (err)
7784 view_close(log_view);
7785 else
7786 *new_view = log_view;
7787 free(commit_id);
7788 return err;
7791 static void
7792 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7794 struct tog_reflist_entry *re;
7795 int i = 0;
7797 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7798 return;
7800 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7801 while (i++ < maxscroll) {
7802 if (re == NULL)
7803 break;
7804 s->first_displayed_entry = re;
7805 re = TAILQ_PREV(re, tog_reflist_head, entry);
7809 static const struct got_error *
7810 ref_scroll_down(struct tog_view *view, int maxscroll)
7812 struct tog_ref_view_state *s = &view->state.ref;
7813 struct tog_reflist_entry *next, *last;
7814 int n = 0;
7816 if (s->first_displayed_entry)
7817 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7818 else
7819 next = TAILQ_FIRST(&s->refs);
7821 last = s->last_displayed_entry;
7822 while (next && n++ < maxscroll) {
7823 if (last) {
7824 s->last_displayed_entry = last;
7825 last = TAILQ_NEXT(last, entry);
7827 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7828 s->first_displayed_entry = next;
7829 next = TAILQ_NEXT(next, entry);
7833 return NULL;
7836 static const struct got_error *
7837 search_start_ref_view(struct tog_view *view)
7839 struct tog_ref_view_state *s = &view->state.ref;
7841 s->matched_entry = NULL;
7842 return NULL;
7845 static int
7846 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7848 regmatch_t regmatch;
7850 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7851 0) == 0;
7854 static const struct got_error *
7855 search_next_ref_view(struct tog_view *view)
7857 struct tog_ref_view_state *s = &view->state.ref;
7858 struct tog_reflist_entry *re = NULL;
7860 if (!view->searching) {
7861 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7862 return NULL;
7865 if (s->matched_entry) {
7866 if (view->searching == TOG_SEARCH_FORWARD) {
7867 if (s->selected_entry)
7868 re = TAILQ_NEXT(s->selected_entry, entry);
7869 else
7870 re = TAILQ_PREV(s->selected_entry,
7871 tog_reflist_head, entry);
7872 } else {
7873 if (s->selected_entry == NULL)
7874 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7875 else
7876 re = TAILQ_PREV(s->selected_entry,
7877 tog_reflist_head, entry);
7879 } else {
7880 if (s->selected_entry)
7881 re = s->selected_entry;
7882 else if (view->searching == TOG_SEARCH_FORWARD)
7883 re = TAILQ_FIRST(&s->refs);
7884 else
7885 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7888 while (1) {
7889 if (re == NULL) {
7890 if (s->matched_entry == NULL) {
7891 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7892 return NULL;
7894 if (view->searching == TOG_SEARCH_FORWARD)
7895 re = TAILQ_FIRST(&s->refs);
7896 else
7897 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7900 if (match_reflist_entry(re, &view->regex)) {
7901 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7902 s->matched_entry = re;
7903 break;
7906 if (view->searching == TOG_SEARCH_FORWARD)
7907 re = TAILQ_NEXT(re, entry);
7908 else
7909 re = TAILQ_PREV(re, tog_reflist_head, entry);
7912 if (s->matched_entry) {
7913 s->first_displayed_entry = s->matched_entry;
7914 s->selected = 0;
7917 return NULL;
7920 static const struct got_error *
7921 show_ref_view(struct tog_view *view)
7923 const struct got_error *err = NULL;
7924 struct tog_ref_view_state *s = &view->state.ref;
7925 struct tog_reflist_entry *re;
7926 char *line = NULL;
7927 wchar_t *wline;
7928 struct tog_color *tc;
7929 int width, n;
7930 int limit = view->nlines;
7932 werase(view->window);
7934 s->ndisplayed = 0;
7935 if (view_is_hsplit_top(view))
7936 --limit; /* border */
7938 if (limit == 0)
7939 return NULL;
7941 re = s->first_displayed_entry;
7943 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7944 s->nrefs) == -1)
7945 return got_error_from_errno("asprintf");
7947 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7948 if (err) {
7949 free(line);
7950 return err;
7952 if (view_needs_focus_indication(view))
7953 wstandout(view->window);
7954 waddwstr(view->window, wline);
7955 while (width++ < view->ncols)
7956 waddch(view->window, ' ');
7957 if (view_needs_focus_indication(view))
7958 wstandend(view->window);
7959 free(wline);
7960 wline = NULL;
7961 free(line);
7962 line = NULL;
7963 if (--limit <= 0)
7964 return NULL;
7966 n = 0;
7967 while (re && limit > 0) {
7968 char *line = NULL;
7969 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7971 if (s->show_date) {
7972 struct got_commit_object *ci;
7973 struct got_tag_object *tag;
7974 struct got_object_id *id;
7975 struct tm tm;
7976 time_t t;
7978 err = got_ref_resolve(&id, s->repo, re->ref);
7979 if (err)
7980 return err;
7981 err = got_object_open_as_tag(&tag, s->repo, id);
7982 if (err) {
7983 if (err->code != GOT_ERR_OBJ_TYPE) {
7984 free(id);
7985 return err;
7987 err = got_object_open_as_commit(&ci, s->repo,
7988 id);
7989 if (err) {
7990 free(id);
7991 return err;
7993 t = got_object_commit_get_committer_time(ci);
7994 got_object_commit_close(ci);
7995 } else {
7996 t = got_object_tag_get_tagger_time(tag);
7997 got_object_tag_close(tag);
7999 free(id);
8000 if (gmtime_r(&t, &tm) == NULL)
8001 return got_error_from_errno("gmtime_r");
8002 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8003 return got_error(GOT_ERR_NO_SPACE);
8005 if (got_ref_is_symbolic(re->ref)) {
8006 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8007 ymd : "", got_ref_get_name(re->ref),
8008 got_ref_get_symref_target(re->ref)) == -1)
8009 return got_error_from_errno("asprintf");
8010 } else if (s->show_ids) {
8011 struct got_object_id *id;
8012 char *id_str;
8013 err = got_ref_resolve(&id, s->repo, re->ref);
8014 if (err)
8015 return err;
8016 err = got_object_id_str(&id_str, id);
8017 if (err) {
8018 free(id);
8019 return err;
8021 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8022 got_ref_get_name(re->ref), id_str) == -1) {
8023 err = got_error_from_errno("asprintf");
8024 free(id);
8025 free(id_str);
8026 return err;
8028 free(id);
8029 free(id_str);
8030 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8031 got_ref_get_name(re->ref)) == -1)
8032 return got_error_from_errno("asprintf");
8034 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
8035 0, 0);
8036 if (err) {
8037 free(line);
8038 return err;
8040 if (n == s->selected) {
8041 if (view->focussed)
8042 wstandout(view->window);
8043 s->selected_entry = re;
8045 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8046 if (tc)
8047 wattr_on(view->window,
8048 COLOR_PAIR(tc->colorpair), NULL);
8049 waddwstr(view->window, wline);
8050 if (tc)
8051 wattr_off(view->window,
8052 COLOR_PAIR(tc->colorpair), NULL);
8053 if (width < view->ncols - 1)
8054 waddch(view->window, '\n');
8055 if (n == s->selected && view->focussed)
8056 wstandend(view->window);
8057 free(line);
8058 free(wline);
8059 wline = NULL;
8060 n++;
8061 s->ndisplayed++;
8062 s->last_displayed_entry = re;
8064 limit--;
8065 re = TAILQ_NEXT(re, entry);
8068 view_border(view);
8069 return err;
8072 static const struct got_error *
8073 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8074 struct tog_reflist_entry *re, struct got_repository *repo)
8076 const struct got_error *err = NULL;
8077 struct got_object_id *commit_id = NULL;
8078 struct tog_view *tree_view;
8080 *new_view = NULL;
8082 err = resolve_reflist_entry(&commit_id, re, repo);
8083 if (err) {
8084 if (err->code != GOT_ERR_OBJ_TYPE)
8085 return err;
8086 else
8087 return NULL;
8091 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8092 if (tree_view == NULL) {
8093 err = got_error_from_errno("view_open");
8094 goto done;
8097 err = open_tree_view(tree_view, commit_id,
8098 got_ref_get_name(re->ref), repo);
8099 if (err)
8100 goto done;
8102 *new_view = tree_view;
8103 done:
8104 free(commit_id);
8105 return err;
8108 static const struct got_error *
8109 ref_goto_line(struct tog_view *view, int nlines)
8111 const struct got_error *err = NULL;
8112 struct tog_ref_view_state *s = &view->state.ref;
8113 int g, idx = s->selected_entry->idx;
8115 g = view->gline;
8116 view->gline = 0;
8118 if (g == 0)
8119 g = 1;
8120 else if (g > s->nrefs)
8121 g = s->nrefs;
8123 if (g >= s->first_displayed_entry->idx + 1 &&
8124 g <= s->last_displayed_entry->idx + 1 &&
8125 g - s->first_displayed_entry->idx - 1 < nlines) {
8126 s->selected = g - s->first_displayed_entry->idx - 1;
8127 return NULL;
8130 if (idx + 1 < g) {
8131 err = ref_scroll_down(view, g - idx - 1);
8132 if (err)
8133 return err;
8134 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8135 s->first_displayed_entry->idx + s->selected < g &&
8136 s->selected < s->ndisplayed - 1)
8137 s->selected = g - s->first_displayed_entry->idx - 1;
8138 } else if (idx + 1 > g)
8139 ref_scroll_up(s, idx - g + 1);
8141 if (g < nlines && s->first_displayed_entry->idx == 0)
8142 s->selected = g - 1;
8144 return NULL;
8148 static const struct got_error *
8149 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8151 const struct got_error *err = NULL;
8152 struct tog_ref_view_state *s = &view->state.ref;
8153 struct tog_reflist_entry *re;
8154 int n, nscroll = view->nlines - 1;
8156 if (view->gline)
8157 return ref_goto_line(view, nscroll);
8159 switch (ch) {
8160 case 'i':
8161 s->show_ids = !s->show_ids;
8162 view->count = 0;
8163 break;
8164 case 'm':
8165 s->show_date = !s->show_date;
8166 view->count = 0;
8167 break;
8168 case 'o':
8169 s->sort_by_date = !s->sort_by_date;
8170 view->count = 0;
8171 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8172 got_ref_cmp_by_commit_timestamp_descending :
8173 tog_ref_cmp_by_name, s->repo);
8174 if (err)
8175 break;
8176 got_reflist_object_id_map_free(tog_refs_idmap);
8177 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8178 &tog_refs, s->repo);
8179 if (err)
8180 break;
8181 ref_view_free_refs(s);
8182 err = ref_view_load_refs(s);
8183 break;
8184 case KEY_ENTER:
8185 case '\r':
8186 view->count = 0;
8187 if (!s->selected_entry)
8188 break;
8189 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8190 break;
8191 case 'T':
8192 view->count = 0;
8193 if (!s->selected_entry)
8194 break;
8195 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8196 break;
8197 case 'g':
8198 case KEY_HOME:
8199 s->selected = 0;
8200 view->count = 0;
8201 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8202 break;
8203 case 'G':
8204 case KEY_END: {
8205 int eos = view->nlines - 1;
8207 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8208 --eos; /* border */
8209 s->selected = 0;
8210 view->count = 0;
8211 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8212 for (n = 0; n < eos; n++) {
8213 if (re == NULL)
8214 break;
8215 s->first_displayed_entry = re;
8216 re = TAILQ_PREV(re, tog_reflist_head, entry);
8218 if (n > 0)
8219 s->selected = n - 1;
8220 break;
8222 case 'k':
8223 case KEY_UP:
8224 case CTRL('p'):
8225 if (s->selected > 0) {
8226 s->selected--;
8227 break;
8229 ref_scroll_up(s, 1);
8230 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8231 view->count = 0;
8232 break;
8233 case CTRL('u'):
8234 case 'u':
8235 nscroll /= 2;
8236 /* FALL THROUGH */
8237 case KEY_PPAGE:
8238 case CTRL('b'):
8239 case 'b':
8240 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8241 s->selected -= MIN(nscroll, s->selected);
8242 ref_scroll_up(s, MAX(0, nscroll));
8243 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8244 view->count = 0;
8245 break;
8246 case 'j':
8247 case KEY_DOWN:
8248 case CTRL('n'):
8249 if (s->selected < s->ndisplayed - 1) {
8250 s->selected++;
8251 break;
8253 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8254 /* can't scroll any further */
8255 view->count = 0;
8256 break;
8258 ref_scroll_down(view, 1);
8259 break;
8260 case CTRL('d'):
8261 case 'd':
8262 nscroll /= 2;
8263 /* FALL THROUGH */
8264 case KEY_NPAGE:
8265 case CTRL('f'):
8266 case 'f':
8267 case ' ':
8268 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8269 /* can't scroll any further; move cursor down */
8270 if (s->selected < s->ndisplayed - 1)
8271 s->selected += MIN(nscroll,
8272 s->ndisplayed - s->selected - 1);
8273 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8274 s->selected += s->ndisplayed - s->selected - 1;
8275 view->count = 0;
8276 break;
8278 ref_scroll_down(view, nscroll);
8279 break;
8280 case CTRL('l'):
8281 view->count = 0;
8282 tog_free_refs();
8283 err = tog_load_refs(s->repo, s->sort_by_date);
8284 if (err)
8285 break;
8286 ref_view_free_refs(s);
8287 err = ref_view_load_refs(s);
8288 break;
8289 case KEY_RESIZE:
8290 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8291 s->selected = view->nlines - 2;
8292 break;
8293 default:
8294 view->count = 0;
8295 break;
8298 return err;
8301 __dead static void
8302 usage_ref(void)
8304 endwin();
8305 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8306 getprogname());
8307 exit(1);
8310 static const struct got_error *
8311 cmd_ref(int argc, char *argv[])
8313 const struct got_error *error;
8314 struct got_repository *repo = NULL;
8315 struct got_worktree *worktree = NULL;
8316 char *cwd = NULL, *repo_path = NULL;
8317 int ch;
8318 struct tog_view *view;
8319 int *pack_fds = NULL;
8321 while ((ch = getopt(argc, argv, "r:")) != -1) {
8322 switch (ch) {
8323 case 'r':
8324 repo_path = realpath(optarg, NULL);
8325 if (repo_path == NULL)
8326 return got_error_from_errno2("realpath",
8327 optarg);
8328 break;
8329 default:
8330 usage_ref();
8331 /* NOTREACHED */
8335 argc -= optind;
8336 argv += optind;
8338 if (argc > 1)
8339 usage_ref();
8341 error = got_repo_pack_fds_open(&pack_fds);
8342 if (error != NULL)
8343 goto done;
8345 if (repo_path == NULL) {
8346 cwd = getcwd(NULL, 0);
8347 if (cwd == NULL)
8348 return got_error_from_errno("getcwd");
8349 error = got_worktree_open(&worktree, cwd);
8350 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8351 goto done;
8352 if (worktree)
8353 repo_path =
8354 strdup(got_worktree_get_repo_path(worktree));
8355 else
8356 repo_path = strdup(cwd);
8357 if (repo_path == NULL) {
8358 error = got_error_from_errno("strdup");
8359 goto done;
8363 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8364 if (error != NULL)
8365 goto done;
8367 init_curses();
8369 error = apply_unveil(got_repo_get_path(repo), NULL);
8370 if (error)
8371 goto done;
8373 error = tog_load_refs(repo, 0);
8374 if (error)
8375 goto done;
8377 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8378 if (view == NULL) {
8379 error = got_error_from_errno("view_open");
8380 goto done;
8383 error = open_ref_view(view, repo);
8384 if (error)
8385 goto done;
8387 if (worktree) {
8388 /* Release work tree lock. */
8389 got_worktree_close(worktree);
8390 worktree = NULL;
8392 error = view_loop(view);
8393 done:
8394 free(repo_path);
8395 free(cwd);
8396 if (repo) {
8397 const struct got_error *close_err = got_repo_close(repo);
8398 if (close_err)
8399 error = close_err;
8401 if (pack_fds) {
8402 const struct got_error *pack_err =
8403 got_repo_pack_fds_close(pack_fds);
8404 if (error == NULL)
8405 error = pack_err;
8407 tog_free_refs();
8408 return error;
8411 static const struct got_error*
8412 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8413 const char *str)
8415 size_t len;
8417 if (win == NULL)
8418 win = stdscr;
8420 len = strlen(str);
8421 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8423 if (focus)
8424 wstandout(win);
8425 if (mvwprintw(win, y, x, "%s", str) == ERR)
8426 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8427 if (focus)
8428 wstandend(win);
8430 return NULL;
8433 static const struct got_error *
8434 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8436 off_t *p;
8438 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8439 if (p == NULL) {
8440 free(*line_offsets);
8441 *line_offsets = NULL;
8442 return got_error_from_errno("reallocarray");
8445 *line_offsets = p;
8446 (*line_offsets)[*nlines] = off;
8447 ++(*nlines);
8448 return NULL;
8451 static const struct got_error *
8452 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8454 *ret = 0;
8456 for (;n > 0; --n, ++km) {
8457 char *t0, *t, *k;
8458 size_t len = 1;
8460 if (km->keys == NULL)
8461 continue;
8463 t = t0 = strdup(km->keys);
8464 if (t0 == NULL)
8465 return got_error_from_errno("strdup");
8467 len += strlen(t);
8468 while ((k = strsep(&t, " ")) != NULL)
8469 len += strlen(k) > 1 ? 2 : 0;
8470 free(t0);
8471 *ret = MAX(*ret, len);
8474 return NULL;
8478 * Write keymap section headers, keys, and key info in km to f.
8479 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8480 * wrap control and symbolic keys in guillemets, else use <>.
8482 static const struct got_error *
8483 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8485 int n, len = width;
8487 if (km->keys) {
8488 static const char *u8_glyph[] = {
8489 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8490 "\xe2\x80\xba" /* U+203A (utf8 >) */
8492 char *t0, *t, *k;
8493 int cs, s, first = 1;
8495 cs = got_locale_is_utf8();
8497 t = t0 = strdup(km->keys);
8498 if (t0 == NULL)
8499 return got_error_from_errno("strdup");
8501 len = strlen(km->keys);
8502 while ((k = strsep(&t, " ")) != NULL) {
8503 s = strlen(k) > 1; /* control or symbolic key */
8504 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8505 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8506 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8507 if (n < 0) {
8508 free(t0);
8509 return got_error_from_errno("fprintf");
8511 first = 0;
8512 len += s ? 2 : 0;
8513 *off += n;
8515 free(t0);
8517 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8518 if (n < 0)
8519 return got_error_from_errno("fprintf");
8520 *off += n;
8522 return NULL;
8525 static const struct got_error *
8526 format_help(struct tog_help_view_state *s)
8528 const struct got_error *err = NULL;
8529 off_t off = 0;
8530 int i, max, n, show = s->all;
8531 static const struct tog_key_map km[] = {
8532 #define KEYMAP_(info, type) { NULL, (info), type }
8533 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8534 GENERATE_HELP
8535 #undef KEYMAP_
8536 #undef KEY_
8539 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8540 if (err)
8541 return err;
8543 n = nitems(km);
8544 err = max_key_str(&max, km, n);
8545 if (err)
8546 return err;
8548 for (i = 0; i < n; ++i) {
8549 if (km[i].keys == NULL) {
8550 show = s->all;
8551 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8552 km[i].type == s->type || s->all)
8553 show = 1;
8555 if (show) {
8556 err = format_help_line(&off, s->f, &km[i], max);
8557 if (err)
8558 return err;
8559 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8560 if (err)
8561 return err;
8564 fputc('\n', s->f);
8565 ++off;
8566 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8567 return err;
8570 static const struct got_error *
8571 create_help(struct tog_help_view_state *s)
8573 FILE *f;
8574 const struct got_error *err;
8576 free(s->line_offsets);
8577 s->line_offsets = NULL;
8578 s->nlines = 0;
8580 f = got_opentemp();
8581 if (f == NULL)
8582 return got_error_from_errno("got_opentemp");
8583 s->f = f;
8585 err = format_help(s);
8586 if (err)
8587 return err;
8589 if (s->f && fflush(s->f) != 0)
8590 return got_error_from_errno("fflush");
8592 return NULL;
8595 static const struct got_error *
8596 search_start_help_view(struct tog_view *view)
8598 view->state.help.matched_line = 0;
8599 return NULL;
8602 static void
8603 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8604 size_t *nlines, int **first, int **last, int **match, int **selected)
8606 struct tog_help_view_state *s = &view->state.help;
8608 *f = s->f;
8609 *nlines = s->nlines;
8610 *line_offsets = s->line_offsets;
8611 *match = &s->matched_line;
8612 *first = &s->first_displayed_line;
8613 *last = &s->last_displayed_line;
8614 *selected = &s->selected_line;
8617 static const struct got_error *
8618 show_help_view(struct tog_view *view)
8620 struct tog_help_view_state *s = &view->state.help;
8621 const struct got_error *err;
8622 regmatch_t *regmatch = &view->regmatch;
8623 wchar_t *wline;
8624 char *line;
8625 ssize_t linelen;
8626 size_t linesz = 0;
8627 int width, nprinted = 0, rc = 0;
8628 int eos = view->nlines;
8630 if (view_is_hsplit_top(view))
8631 --eos; /* account for border */
8633 s->lineno = 0;
8634 rewind(s->f);
8635 werase(view->window);
8637 if (view->gline > s->nlines - 1)
8638 view->gline = s->nlines - 1;
8640 err = win_draw_center(view->window, 0, 0, view->ncols,
8641 view_needs_focus_indication(view),
8642 "tog help (press q to return to tog)");
8643 if (err)
8644 return err;
8645 if (eos <= 1)
8646 return NULL;
8647 waddstr(view->window, "\n\n");
8648 eos -= 2;
8650 s->eof = 0;
8651 view->maxx = 0;
8652 line = NULL;
8653 while (eos > 0 && nprinted < eos) {
8654 attr_t attr = 0;
8656 linelen = getline(&line, &linesz, s->f);
8657 if (linelen == -1) {
8658 if (!feof(s->f)) {
8659 free(line);
8660 return got_ferror(s->f, GOT_ERR_IO);
8662 s->eof = 1;
8663 break;
8665 if (++s->lineno < s->first_displayed_line)
8666 continue;
8667 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8668 continue;
8669 if (s->lineno == view->hiline)
8670 attr = A_STANDOUT;
8672 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8673 view->x ? 1 : 0);
8674 if (err) {
8675 free(line);
8676 return err;
8678 view->maxx = MAX(view->maxx, width);
8679 free(wline);
8680 wline = NULL;
8682 if (attr)
8683 wattron(view->window, attr);
8684 if (s->first_displayed_line + nprinted == s->matched_line &&
8685 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8686 err = add_matched_line(&width, line, view->ncols - 1, 0,
8687 view->window, view->x, regmatch);
8688 if (err) {
8689 free(line);
8690 return err;
8692 } else {
8693 int skip;
8695 err = format_line(&wline, &width, &skip, line,
8696 view->x, view->ncols - 1, 0, view->x ? 1 : 0);
8697 if (err) {
8698 free(line);
8699 return err;
8701 rc = waddwstr(view->window, &wline[skip]);
8702 free(wline);
8703 wline = NULL;
8704 if (rc == ERR)
8705 return got_error_msg(GOT_ERR_IO, "waddwstr");
8707 if (s->lineno == view->hiline) {
8708 while (width++ < view->ncols)
8709 waddch(view->window, ' ');
8710 } else {
8711 if (width <= view->ncols)
8712 waddch(view->window, '\n');
8714 if (attr)
8715 wattroff(view->window, attr);
8716 if (++nprinted == 1)
8717 s->first_displayed_line = s->lineno;
8719 free(line);
8720 if (nprinted > 0)
8721 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8722 else
8723 s->last_displayed_line = s->first_displayed_line;
8725 view_border(view);
8727 if (s->eof) {
8728 rc = waddnstr(view->window,
8729 "See the tog(1) manual page for full documentation",
8730 view->ncols - 1);
8731 if (rc == ERR)
8732 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8733 } else {
8734 wmove(view->window, view->nlines - 1, 0);
8735 wclrtoeol(view->window);
8736 wstandout(view->window);
8737 rc = waddnstr(view->window, "scroll down for more...",
8738 view->ncols - 1);
8739 if (rc == ERR)
8740 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8741 if (getcurx(view->window) < view->ncols - 6) {
8742 rc = wprintw(view->window, "[%.0f%%]",
8743 100.00 * s->last_displayed_line / s->nlines);
8744 if (rc == ERR)
8745 return got_error_msg(GOT_ERR_IO, "wprintw");
8747 wstandend(view->window);
8750 return NULL;
8753 static const struct got_error *
8754 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8756 struct tog_help_view_state *s = &view->state.help;
8757 const struct got_error *err = NULL;
8758 char *line = NULL;
8759 ssize_t linelen;
8760 size_t linesz = 0;
8761 int eos, nscroll;
8763 eos = nscroll = view->nlines;
8764 if (view_is_hsplit_top(view))
8765 --eos; /* border */
8767 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8769 switch (ch) {
8770 case '0':
8771 view->x = 0;
8772 break;
8773 case '$':
8774 view->x = MAX(view->maxx - view->ncols / 3, 0);
8775 view->count = 0;
8776 break;
8777 case KEY_RIGHT:
8778 case 'l':
8779 if (view->x + view->ncols / 3 < view->maxx)
8780 view->x += 2;
8781 else
8782 view->count = 0;
8783 break;
8784 case KEY_LEFT:
8785 case 'h':
8786 view->x -= MIN(view->x, 2);
8787 if (view->x <= 0)
8788 view->count = 0;
8789 break;
8790 case 'g':
8791 case KEY_HOME:
8792 s->first_displayed_line = 1;
8793 view->count = 0;
8794 break;
8795 case 'G':
8796 case KEY_END:
8797 view->count = 0;
8798 if (s->eof)
8799 break;
8800 s->first_displayed_line = (s->nlines - eos) + 3;
8801 s->eof = 1;
8802 break;
8803 case 'k':
8804 case KEY_UP:
8805 if (s->first_displayed_line > 1)
8806 --s->first_displayed_line;
8807 else
8808 view->count = 0;
8809 break;
8810 case CTRL('u'):
8811 case 'u':
8812 nscroll /= 2;
8813 /* FALL THROUGH */
8814 case KEY_PPAGE:
8815 case CTRL('b'):
8816 case 'b':
8817 if (s->first_displayed_line == 1) {
8818 view->count = 0;
8819 break;
8821 while (--nscroll > 0 && s->first_displayed_line > 1)
8822 s->first_displayed_line--;
8823 break;
8824 case 'j':
8825 case KEY_DOWN:
8826 case CTRL('n'):
8827 if (!s->eof)
8828 ++s->first_displayed_line;
8829 else
8830 view->count = 0;
8831 break;
8832 case CTRL('d'):
8833 case 'd':
8834 nscroll /= 2;
8835 /* FALL THROUGH */
8836 case KEY_NPAGE:
8837 case CTRL('f'):
8838 case 'f':
8839 case ' ':
8840 if (s->eof) {
8841 view->count = 0;
8842 break;
8844 while (!s->eof && --nscroll > 0) {
8845 linelen = getline(&line, &linesz, s->f);
8846 s->first_displayed_line++;
8847 if (linelen == -1) {
8848 if (feof(s->f))
8849 s->eof = 1;
8850 else
8851 err = got_ferror(s->f, GOT_ERR_IO);
8852 break;
8855 free(line);
8856 break;
8857 default:
8858 view->count = 0;
8859 break;
8862 return err;
8865 static const struct got_error *
8866 close_help_view(struct tog_view *view)
8868 struct tog_help_view_state *s = &view->state.help;
8870 free(s->line_offsets);
8871 s->line_offsets = NULL;
8872 if (fclose(s->f) == EOF)
8873 return got_error_from_errno("fclose");
8875 return NULL;
8878 static const struct got_error *
8879 reset_help_view(struct tog_view *view)
8881 struct tog_help_view_state *s = &view->state.help;
8884 if (s->f && fclose(s->f) == EOF)
8885 return got_error_from_errno("fclose");
8887 wclear(view->window);
8888 view->count = 0;
8889 view->x = 0;
8890 s->all = !s->all;
8891 s->first_displayed_line = 1;
8892 s->last_displayed_line = view->nlines;
8893 s->matched_line = 0;
8895 return create_help(s);
8898 static const struct got_error *
8899 open_help_view(struct tog_view *view, struct tog_view *parent)
8901 const struct got_error *err = NULL;
8902 struct tog_help_view_state *s = &view->state.help;
8904 s->type = (enum tog_keymap_type)parent->type;
8905 s->first_displayed_line = 1;
8906 s->last_displayed_line = view->nlines;
8907 s->selected_line = 1;
8909 view->show = show_help_view;
8910 view->input = input_help_view;
8911 view->reset = reset_help_view;
8912 view->close = close_help_view;
8913 view->search_start = search_start_help_view;
8914 view->search_setup = search_setup_help_view;
8915 view->search_next = search_next_view_match;
8917 err = create_help(s);
8918 return err;
8921 static const struct got_error *
8922 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8923 enum tog_view_type request, int y, int x)
8925 const struct got_error *err = NULL;
8927 *new_view = NULL;
8929 switch (request) {
8930 case TOG_VIEW_DIFF:
8931 if (view->type == TOG_VIEW_LOG) {
8932 struct tog_log_view_state *s = &view->state.log;
8934 err = open_diff_view_for_commit(new_view, y, x,
8935 s->selected_entry->commit, s->selected_entry->id,
8936 view, s->repo);
8937 } else
8938 return got_error_msg(GOT_ERR_NOT_IMPL,
8939 "parent/child view pair not supported");
8940 break;
8941 case TOG_VIEW_BLAME:
8942 if (view->type == TOG_VIEW_TREE) {
8943 struct tog_tree_view_state *s = &view->state.tree;
8945 err = blame_tree_entry(new_view, y, x,
8946 s->selected_entry, &s->parents, s->commit_id,
8947 s->repo);
8948 } else
8949 return got_error_msg(GOT_ERR_NOT_IMPL,
8950 "parent/child view pair not supported");
8951 break;
8952 case TOG_VIEW_LOG:
8953 if (view->type == TOG_VIEW_BLAME)
8954 err = log_annotated_line(new_view, y, x,
8955 view->state.blame.repo, view->state.blame.id_to_log);
8956 else if (view->type == TOG_VIEW_TREE)
8957 err = log_selected_tree_entry(new_view, y, x,
8958 &view->state.tree);
8959 else if (view->type == TOG_VIEW_REF)
8960 err = log_ref_entry(new_view, y, x,
8961 view->state.ref.selected_entry,
8962 view->state.ref.repo);
8963 else
8964 return got_error_msg(GOT_ERR_NOT_IMPL,
8965 "parent/child view pair not supported");
8966 break;
8967 case TOG_VIEW_TREE:
8968 if (view->type == TOG_VIEW_LOG)
8969 err = browse_commit_tree(new_view, y, x,
8970 view->state.log.selected_entry,
8971 view->state.log.in_repo_path,
8972 view->state.log.head_ref_name,
8973 view->state.log.repo);
8974 else if (view->type == TOG_VIEW_REF)
8975 err = browse_ref_tree(new_view, y, x,
8976 view->state.ref.selected_entry,
8977 view->state.ref.repo);
8978 else
8979 return got_error_msg(GOT_ERR_NOT_IMPL,
8980 "parent/child view pair not supported");
8981 break;
8982 case TOG_VIEW_REF:
8983 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8984 if (*new_view == NULL)
8985 return got_error_from_errno("view_open");
8986 if (view->type == TOG_VIEW_LOG)
8987 err = open_ref_view(*new_view, view->state.log.repo);
8988 else if (view->type == TOG_VIEW_TREE)
8989 err = open_ref_view(*new_view, view->state.tree.repo);
8990 else
8991 err = got_error_msg(GOT_ERR_NOT_IMPL,
8992 "parent/child view pair not supported");
8993 if (err)
8994 view_close(*new_view);
8995 break;
8996 case TOG_VIEW_HELP:
8997 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
8998 if (*new_view == NULL)
8999 return got_error_from_errno("view_open");
9000 err = open_help_view(*new_view, view);
9001 if (err)
9002 view_close(*new_view);
9003 break;
9004 default:
9005 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9008 return err;
9012 * If view was scrolled down to move the selected line into view when opening a
9013 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9015 static void
9016 offset_selection_up(struct tog_view *view)
9018 switch (view->type) {
9019 case TOG_VIEW_BLAME: {
9020 struct tog_blame_view_state *s = &view->state.blame;
9021 if (s->first_displayed_line == 1) {
9022 s->selected_line = MAX(s->selected_line - view->offset,
9023 1);
9024 break;
9026 if (s->first_displayed_line > view->offset)
9027 s->first_displayed_line -= view->offset;
9028 else
9029 s->first_displayed_line = 1;
9030 s->selected_line += view->offset;
9031 break;
9033 case TOG_VIEW_LOG:
9034 log_scroll_up(&view->state.log, view->offset);
9035 view->state.log.selected += view->offset;
9036 break;
9037 case TOG_VIEW_REF:
9038 ref_scroll_up(&view->state.ref, view->offset);
9039 view->state.ref.selected += view->offset;
9040 break;
9041 case TOG_VIEW_TREE:
9042 tree_scroll_up(&view->state.tree, view->offset);
9043 view->state.tree.selected += view->offset;
9044 break;
9045 default:
9046 break;
9049 view->offset = 0;
9053 * If the selected line is in the section of screen covered by the bottom split,
9054 * scroll down offset lines to move it into view and index its new position.
9056 static const struct got_error *
9057 offset_selection_down(struct tog_view *view)
9059 const struct got_error *err = NULL;
9060 const struct got_error *(*scrolld)(struct tog_view *, int);
9061 int *selected = NULL;
9062 int header, offset;
9064 switch (view->type) {
9065 case TOG_VIEW_BLAME: {
9066 struct tog_blame_view_state *s = &view->state.blame;
9067 header = 3;
9068 scrolld = NULL;
9069 if (s->selected_line > view->nlines - header) {
9070 offset = abs(view->nlines - s->selected_line - header);
9071 s->first_displayed_line += offset;
9072 s->selected_line -= offset;
9073 view->offset = offset;
9075 break;
9077 case TOG_VIEW_LOG: {
9078 struct tog_log_view_state *s = &view->state.log;
9079 scrolld = &log_scroll_down;
9080 header = view_is_parent_view(view) ? 3 : 2;
9081 selected = &s->selected;
9082 break;
9084 case TOG_VIEW_REF: {
9085 struct tog_ref_view_state *s = &view->state.ref;
9086 scrolld = &ref_scroll_down;
9087 header = 3;
9088 selected = &s->selected;
9089 break;
9091 case TOG_VIEW_TREE: {
9092 struct tog_tree_view_state *s = &view->state.tree;
9093 scrolld = &tree_scroll_down;
9094 header = 5;
9095 selected = &s->selected;
9096 break;
9098 default:
9099 selected = NULL;
9100 scrolld = NULL;
9101 header = 0;
9102 break;
9105 if (selected && *selected > view->nlines - header) {
9106 offset = abs(view->nlines - *selected - header);
9107 view->offset = offset;
9108 if (scrolld && offset) {
9109 err = scrolld(view, offset);
9110 *selected -= offset;
9114 return err;
9117 static void
9118 list_commands(FILE *fp)
9120 size_t i;
9122 fprintf(fp, "commands:");
9123 for (i = 0; i < nitems(tog_commands); i++) {
9124 const struct tog_cmd *cmd = &tog_commands[i];
9125 fprintf(fp, " %s", cmd->name);
9127 fputc('\n', fp);
9130 __dead static void
9131 usage(int hflag, int status)
9133 FILE *fp = (status == 0) ? stdout : stderr;
9135 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9136 getprogname());
9137 if (hflag) {
9138 fprintf(fp, "lazy usage: %s path\n", getprogname());
9139 list_commands(fp);
9141 exit(status);
9144 static char **
9145 make_argv(int argc, ...)
9147 va_list ap;
9148 char **argv;
9149 int i;
9151 va_start(ap, argc);
9153 argv = calloc(argc, sizeof(char *));
9154 if (argv == NULL)
9155 err(1, "calloc");
9156 for (i = 0; i < argc; i++) {
9157 argv[i] = strdup(va_arg(ap, char *));
9158 if (argv[i] == NULL)
9159 err(1, "strdup");
9162 va_end(ap);
9163 return argv;
9167 * Try to convert 'tog path' into a 'tog log path' command.
9168 * The user could simply have mistyped the command rather than knowingly
9169 * provided a path. So check whether argv[0] can in fact be resolved
9170 * to a path in the HEAD commit and print a special error if not.
9171 * This hack is for mpi@ <3
9173 static const struct got_error *
9174 tog_log_with_path(int argc, char *argv[])
9176 const struct got_error *error = NULL, *close_err;
9177 const struct tog_cmd *cmd = NULL;
9178 struct got_repository *repo = NULL;
9179 struct got_worktree *worktree = NULL;
9180 struct got_object_id *commit_id = NULL, *id = NULL;
9181 struct got_commit_object *commit = NULL;
9182 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9183 char *commit_id_str = NULL, **cmd_argv = NULL;
9184 int *pack_fds = NULL;
9186 cwd = getcwd(NULL, 0);
9187 if (cwd == NULL)
9188 return got_error_from_errno("getcwd");
9190 error = got_repo_pack_fds_open(&pack_fds);
9191 if (error != NULL)
9192 goto done;
9194 error = got_worktree_open(&worktree, cwd);
9195 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9196 goto done;
9198 if (worktree)
9199 repo_path = strdup(got_worktree_get_repo_path(worktree));
9200 else
9201 repo_path = strdup(cwd);
9202 if (repo_path == NULL) {
9203 error = got_error_from_errno("strdup");
9204 goto done;
9207 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9208 if (error != NULL)
9209 goto done;
9211 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9212 repo, worktree);
9213 if (error)
9214 goto done;
9216 error = tog_load_refs(repo, 0);
9217 if (error)
9218 goto done;
9219 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9220 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9221 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9222 if (error)
9223 goto done;
9225 if (worktree) {
9226 got_worktree_close(worktree);
9227 worktree = NULL;
9230 error = got_object_open_as_commit(&commit, repo, commit_id);
9231 if (error)
9232 goto done;
9234 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9235 if (error) {
9236 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9237 goto done;
9238 fprintf(stderr, "%s: '%s' is no known command or path\n",
9239 getprogname(), argv[0]);
9240 usage(1, 1);
9241 /* not reached */
9244 error = got_object_id_str(&commit_id_str, commit_id);
9245 if (error)
9246 goto done;
9248 cmd = &tog_commands[0]; /* log */
9249 argc = 4;
9250 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9251 error = cmd->cmd_main(argc, cmd_argv);
9252 done:
9253 if (repo) {
9254 close_err = got_repo_close(repo);
9255 if (error == NULL)
9256 error = close_err;
9258 if (commit)
9259 got_object_commit_close(commit);
9260 if (worktree)
9261 got_worktree_close(worktree);
9262 if (pack_fds) {
9263 const struct got_error *pack_err =
9264 got_repo_pack_fds_close(pack_fds);
9265 if (error == NULL)
9266 error = pack_err;
9268 free(id);
9269 free(commit_id_str);
9270 free(commit_id);
9271 free(cwd);
9272 free(repo_path);
9273 free(in_repo_path);
9274 if (cmd_argv) {
9275 int i;
9276 for (i = 0; i < argc; i++)
9277 free(cmd_argv[i]);
9278 free(cmd_argv);
9280 tog_free_refs();
9281 return error;
9284 int
9285 main(int argc, char *argv[])
9287 const struct got_error *error = NULL;
9288 const struct tog_cmd *cmd = NULL;
9289 int ch, hflag = 0, Vflag = 0;
9290 char **cmd_argv = NULL;
9291 static const struct option longopts[] = {
9292 { "version", no_argument, NULL, 'V' },
9293 { NULL, 0, NULL, 0}
9295 char *diff_algo_str = NULL;
9297 if (!isatty(STDIN_FILENO))
9298 errx(1, "standard input is not a tty");
9300 setlocale(LC_CTYPE, "");
9302 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9303 switch (ch) {
9304 case 'h':
9305 hflag = 1;
9306 break;
9307 case 'V':
9308 Vflag = 1;
9309 break;
9310 default:
9311 usage(hflag, 1);
9312 /* NOTREACHED */
9316 argc -= optind;
9317 argv += optind;
9318 optind = 1;
9319 optreset = 1;
9321 if (Vflag) {
9322 got_version_print_str();
9323 return 0;
9326 #ifndef PROFILE
9327 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9328 NULL) == -1)
9329 err(1, "pledge");
9330 #endif
9332 if (argc == 0) {
9333 if (hflag)
9334 usage(hflag, 0);
9335 /* Build an argument vector which runs a default command. */
9336 cmd = &tog_commands[0];
9337 argc = 1;
9338 cmd_argv = make_argv(argc, cmd->name);
9339 } else {
9340 size_t i;
9342 /* Did the user specify a command? */
9343 for (i = 0; i < nitems(tog_commands); i++) {
9344 if (strncmp(tog_commands[i].name, argv[0],
9345 strlen(argv[0])) == 0) {
9346 cmd = &tog_commands[i];
9347 break;
9352 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9353 if (diff_algo_str) {
9354 if (strcasecmp(diff_algo_str, "patience") == 0)
9355 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9356 if (strcasecmp(diff_algo_str, "myers") == 0)
9357 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9360 if (cmd == NULL) {
9361 if (argc != 1)
9362 usage(0, 1);
9363 /* No command specified; try log with a path */
9364 error = tog_log_with_path(argc, argv);
9365 } else {
9366 if (hflag)
9367 cmd->cmd_usage();
9368 else
9369 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9372 endwin();
9373 putchar('\n');
9374 if (cmd_argv) {
9375 int i;
9376 for (i = 0; i < argc; i++)
9377 free(cmd_argv[i]);
9378 free(cmd_argv);
9381 if (error && error->code != GOT_ERR_CANCELLED &&
9382 error->code != GOT_ERR_EOF &&
9383 error->code != GOT_ERR_PRIVSEP_EXIT &&
9384 error->code != GOT_ERR_PRIVSEP_PIPE &&
9385 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9386 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9387 return 0;