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"), \
550 KEY_("Q", "Quit tog"), \
552 KEYMAP_("Log", 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", 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", 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", 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", 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_sigint_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))
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 err = view_init_hsplit(view, y);
1245 if (err)
1246 return err;
1249 view->focussed = 0;
1250 new_view->focussed = 1;
1251 new_view->mode = view->mode;
1252 new_view->nlines = view->lines - y;
1254 if (view_is_parent_view(view)) {
1255 view_transfer_size(new_view, view);
1256 err = view_close_child(view);
1257 if (err)
1258 return err;
1259 err = view_set_child(view, new_view);
1260 if (err)
1261 return err;
1262 view->focus_child = 1;
1263 } else
1264 *requested = new_view;
1266 return NULL;
1269 static void
1270 tog_resizeterm(void)
1272 int cols, lines;
1273 struct winsize size;
1275 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1276 cols = 80; /* Default */
1277 lines = 24;
1278 } else {
1279 cols = size.ws_col;
1280 lines = size.ws_row;
1282 resize_term(lines, cols);
1285 static const struct got_error *
1286 view_search_start(struct tog_view *view)
1288 const struct got_error *err = NULL;
1289 struct tog_view *v = view;
1290 char pattern[1024];
1291 int ret;
1293 if (view->search_started) {
1294 regfree(&view->regex);
1295 view->searching = 0;
1296 memset(&view->regmatch, 0, sizeof(view->regmatch));
1298 view->search_started = 0;
1300 if (view->nlines < 1)
1301 return NULL;
1303 if (view_is_hsplit_top(view))
1304 v = view->child;
1306 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1307 wclrtoeol(v->window);
1309 nodelay(view->window, FALSE); /* block for search term input */
1310 nocbreak();
1311 echo();
1312 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1313 wrefresh(v->window);
1314 cbreak();
1315 noecho();
1316 nodelay(view->window, TRUE);
1317 if (ret == ERR)
1318 return NULL;
1320 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1321 err = view->search_start(view);
1322 if (err) {
1323 regfree(&view->regex);
1324 return err;
1326 view->search_started = 1;
1327 view->searching = TOG_SEARCH_FORWARD;
1328 view->search_next_done = 0;
1329 view->search_next(view);
1332 return NULL;
1335 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1336 static const struct got_error *
1337 switch_split(struct tog_view *view)
1339 const struct got_error *err = NULL;
1340 struct tog_view *v = NULL;
1342 if (view->parent)
1343 v = view->parent;
1344 else
1345 v = view;
1347 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1348 v->mode = TOG_VIEW_SPLIT_VERT;
1349 else
1350 v->mode = TOG_VIEW_SPLIT_HRZN;
1352 if (!v->child)
1353 return NULL;
1354 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1355 v->mode = TOG_VIEW_SPLIT_NONE;
1357 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1358 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1359 v->child->begin_y = v->child->resized_y;
1360 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1361 v->child->begin_x = v->child->resized_x;
1364 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1365 v->ncols = COLS;
1366 v->child->ncols = COLS;
1367 v->child->nscrolled = LINES - v->child->nlines;
1369 err = view_init_hsplit(v, v->child->begin_y);
1370 if (err)
1371 return err;
1373 v->child->mode = v->mode;
1374 v->child->nlines = v->lines - v->child->begin_y;
1375 v->focus_child = 1;
1377 err = view_fullscreen(v);
1378 if (err)
1379 return err;
1380 err = view_splitscreen(v->child);
1381 if (err)
1382 return err;
1384 if (v->mode == TOG_VIEW_SPLIT_NONE)
1385 v->mode = TOG_VIEW_SPLIT_VERT;
1386 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1387 err = offset_selection_down(v);
1388 if (err)
1389 return err;
1390 err = offset_selection_down(v->child);
1391 if (err)
1392 return err;
1393 } else {
1394 offset_selection_up(v);
1395 offset_selection_up(v->child);
1397 if (v->resize)
1398 err = v->resize(v, 0);
1399 else if (v->child->resize)
1400 err = v->child->resize(v->child, 0);
1402 return err;
1406 * Compute view->count from numeric input. Assign total to view->count and
1407 * return first non-numeric key entered.
1409 static int
1410 get_compound_key(struct tog_view *view, int c)
1412 struct tog_view *v = view;
1413 int x, n = 0;
1415 if (view_is_hsplit_top(view))
1416 v = view->child;
1417 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1418 v = view->parent;
1420 view->count = 0;
1421 cbreak(); /* block for input */
1422 nodelay(view->window, FALSE);
1423 wmove(v->window, v->nlines - 1, 0);
1424 wclrtoeol(v->window);
1425 waddch(v->window, ':');
1427 do {
1428 x = getcurx(v->window);
1429 if (x != ERR && x < view->ncols) {
1430 waddch(v->window, c);
1431 wrefresh(v->window);
1435 * Don't overflow. Max valid request should be the greatest
1436 * between the longest and total lines; cap at 10 million.
1438 if (n >= 9999999)
1439 n = 9999999;
1440 else
1441 n = n * 10 + (c - '0');
1442 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1444 if (c == 'G' || c == 'g') { /* nG key map */
1445 view->gline = view->hiline = n;
1446 n = 0;
1447 c = 0;
1450 /* Massage excessive or inapplicable values at the input handler. */
1451 view->count = n;
1453 return c;
1456 static const struct got_error *
1457 view_input(struct tog_view **new, int *done, struct tog_view *view,
1458 struct tog_view_list_head *views)
1460 const struct got_error *err = NULL;
1461 struct tog_view *v;
1462 int ch, errcode;
1464 *new = NULL;
1466 /* Clear "no matches" indicator. */
1467 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1468 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1469 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1470 view->count = 0;
1473 if (view->searching && !view->search_next_done) {
1474 errcode = pthread_mutex_unlock(&tog_mutex);
1475 if (errcode)
1476 return got_error_set_errno(errcode,
1477 "pthread_mutex_unlock");
1478 sched_yield();
1479 errcode = pthread_mutex_lock(&tog_mutex);
1480 if (errcode)
1481 return got_error_set_errno(errcode,
1482 "pthread_mutex_lock");
1483 view->search_next(view);
1484 return NULL;
1487 /* Allow threads to make progress while we are waiting for input. */
1488 errcode = pthread_mutex_unlock(&tog_mutex);
1489 if (errcode)
1490 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1491 /* If we have an unfinished count, let C-g or backspace abort. */
1492 if (view->count && --view->count) {
1493 cbreak();
1494 nodelay(view->window, TRUE);
1495 ch = wgetch(view->window);
1496 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1497 view->count = 0;
1498 else
1499 ch = view->ch;
1500 } else {
1501 ch = wgetch(view->window);
1502 if (ch >= '1' && ch <= '9')
1503 view->ch = ch = get_compound_key(view, ch);
1505 if (view->hiline && ch != ERR && ch != 0)
1506 view->hiline = 0; /* key pressed, clear line highlight */
1507 nodelay(view->window, TRUE);
1508 errcode = pthread_mutex_lock(&tog_mutex);
1509 if (errcode)
1510 return got_error_set_errno(errcode, "pthread_mutex_lock");
1512 if (tog_sigwinch_received || tog_sigcont_received) {
1513 tog_resizeterm();
1514 tog_sigwinch_received = 0;
1515 tog_sigcont_received = 0;
1516 TAILQ_FOREACH(v, views, entry) {
1517 err = view_resize(v);
1518 if (err)
1519 return err;
1520 err = v->input(new, v, KEY_RESIZE);
1521 if (err)
1522 return err;
1523 if (v->child) {
1524 err = view_resize(v->child);
1525 if (err)
1526 return err;
1527 err = v->child->input(new, v->child,
1528 KEY_RESIZE);
1529 if (err)
1530 return err;
1531 if (v->child->resized_x || v->child->resized_y) {
1532 err = view_resize_split(v, 0);
1533 if (err)
1534 return err;
1540 switch (ch) {
1541 case '?':
1542 case 'H':
1543 case KEY_F(1):
1544 if (view->type == TOG_VIEW_HELP)
1545 err = view->reset(view);
1546 else
1547 err = view_request_new(new, view, TOG_VIEW_HELP);
1548 break;
1549 case '\t':
1550 view->count = 0;
1551 if (view->child) {
1552 view->focussed = 0;
1553 view->child->focussed = 1;
1554 view->focus_child = 1;
1555 } else if (view->parent) {
1556 view->focussed = 0;
1557 view->parent->focussed = 1;
1558 view->parent->focus_child = 0;
1559 if (!view_is_splitscreen(view)) {
1560 if (view->parent->resize) {
1561 err = view->parent->resize(view->parent,
1562 0);
1563 if (err)
1564 return err;
1566 offset_selection_up(view->parent);
1567 err = view_fullscreen(view->parent);
1568 if (err)
1569 return err;
1572 break;
1573 case 'q':
1574 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1575 if (view->parent->resize) {
1576 /* might need more commits to fill fullscreen */
1577 err = view->parent->resize(view->parent, 0);
1578 if (err)
1579 break;
1581 offset_selection_up(view->parent);
1583 err = view->input(new, view, ch);
1584 view->dying = 1;
1585 break;
1586 case 'Q':
1587 *done = 1;
1588 break;
1589 case 'F':
1590 view->count = 0;
1591 if (view_is_parent_view(view)) {
1592 if (view->child == NULL)
1593 break;
1594 if (view_is_splitscreen(view->child)) {
1595 view->focussed = 0;
1596 view->child->focussed = 1;
1597 err = view_fullscreen(view->child);
1598 } else {
1599 err = view_splitscreen(view->child);
1600 if (!err)
1601 err = view_resize_split(view, 0);
1603 if (err)
1604 break;
1605 err = view->child->input(new, view->child,
1606 KEY_RESIZE);
1607 } else {
1608 if (view_is_splitscreen(view)) {
1609 view->parent->focussed = 0;
1610 view->focussed = 1;
1611 err = view_fullscreen(view);
1612 } else {
1613 err = view_splitscreen(view);
1614 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1615 err = view_resize(view->parent);
1616 if (!err)
1617 err = view_resize_split(view, 0);
1619 if (err)
1620 break;
1621 err = view->input(new, view, KEY_RESIZE);
1623 if (err)
1624 break;
1625 if (view->resize) {
1626 err = view->resize(view, 0);
1627 if (err)
1628 break;
1630 if (view->parent)
1631 err = offset_selection_down(view->parent);
1632 if (!err)
1633 err = offset_selection_down(view);
1634 break;
1635 case 'S':
1636 view->count = 0;
1637 err = switch_split(view);
1638 break;
1639 case '-':
1640 err = view_resize_split(view, -1);
1641 break;
1642 case '+':
1643 err = view_resize_split(view, 1);
1644 break;
1645 case KEY_RESIZE:
1646 break;
1647 case '/':
1648 view->count = 0;
1649 if (view->search_start)
1650 view_search_start(view);
1651 else
1652 err = view->input(new, view, ch);
1653 break;
1654 case 'N':
1655 case 'n':
1656 if (view->search_started && view->search_next) {
1657 view->searching = (ch == 'n' ?
1658 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1659 view->search_next_done = 0;
1660 view->search_next(view);
1661 } else
1662 err = view->input(new, view, ch);
1663 break;
1664 case 'A':
1665 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1666 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1667 else
1668 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1669 TAILQ_FOREACH(v, views, entry) {
1670 if (v->reset) {
1671 err = v->reset(v);
1672 if (err)
1673 return err;
1675 if (v->child && v->child->reset) {
1676 err = v->child->reset(v->child);
1677 if (err)
1678 return err;
1681 break;
1682 default:
1683 err = view->input(new, view, ch);
1684 break;
1687 return err;
1690 static int
1691 view_needs_focus_indication(struct tog_view *view)
1693 if (view_is_parent_view(view)) {
1694 if (view->child == NULL || view->child->focussed)
1695 return 0;
1696 if (!view_is_splitscreen(view->child))
1697 return 0;
1698 } else if (!view_is_splitscreen(view))
1699 return 0;
1701 return view->focussed;
1704 static const struct got_error *
1705 view_loop(struct tog_view *view)
1707 const struct got_error *err = NULL;
1708 struct tog_view_list_head views;
1709 struct tog_view *new_view;
1710 char *mode;
1711 int fast_refresh = 10;
1712 int done = 0, errcode;
1714 mode = getenv("TOG_VIEW_SPLIT_MODE");
1715 if (!mode || !(*mode == 'h' || *mode == 'H'))
1716 view->mode = TOG_VIEW_SPLIT_VERT;
1717 else
1718 view->mode = TOG_VIEW_SPLIT_HRZN;
1720 errcode = pthread_mutex_lock(&tog_mutex);
1721 if (errcode)
1722 return got_error_set_errno(errcode, "pthread_mutex_lock");
1724 TAILQ_INIT(&views);
1725 TAILQ_INSERT_HEAD(&views, view, entry);
1727 view->focussed = 1;
1728 err = view->show(view);
1729 if (err)
1730 return err;
1731 update_panels();
1732 doupdate();
1733 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1734 !tog_fatal_signal_received()) {
1735 /* Refresh fast during initialization, then become slower. */
1736 if (fast_refresh && fast_refresh-- == 0)
1737 halfdelay(10); /* switch to once per second */
1739 err = view_input(&new_view, &done, view, &views);
1740 if (err)
1741 break;
1742 if (view->dying) {
1743 struct tog_view *v, *prev = NULL;
1745 if (view_is_parent_view(view))
1746 prev = TAILQ_PREV(view, tog_view_list_head,
1747 entry);
1748 else if (view->parent)
1749 prev = view->parent;
1751 if (view->parent) {
1752 view->parent->child = NULL;
1753 view->parent->focus_child = 0;
1754 /* Restore fullscreen line height. */
1755 view->parent->nlines = view->parent->lines;
1756 err = view_resize(view->parent);
1757 if (err)
1758 break;
1759 /* Make resized splits persist. */
1760 view_transfer_size(view->parent, view);
1761 } else
1762 TAILQ_REMOVE(&views, view, entry);
1764 err = view_close(view);
1765 if (err)
1766 goto done;
1768 view = NULL;
1769 TAILQ_FOREACH(v, &views, entry) {
1770 if (v->focussed)
1771 break;
1773 if (view == NULL && new_view == NULL) {
1774 /* No view has focus. Try to pick one. */
1775 if (prev)
1776 view = prev;
1777 else if (!TAILQ_EMPTY(&views)) {
1778 view = TAILQ_LAST(&views,
1779 tog_view_list_head);
1781 if (view) {
1782 if (view->focus_child) {
1783 view->child->focussed = 1;
1784 view = view->child;
1785 } else
1786 view->focussed = 1;
1790 if (new_view) {
1791 struct tog_view *v, *t;
1792 /* Only allow one parent view per type. */
1793 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1794 if (v->type != new_view->type)
1795 continue;
1796 TAILQ_REMOVE(&views, v, entry);
1797 err = view_close(v);
1798 if (err)
1799 goto done;
1800 break;
1802 TAILQ_INSERT_TAIL(&views, new_view, entry);
1803 view = new_view;
1805 if (view) {
1806 if (view_is_parent_view(view)) {
1807 if (view->child && view->child->focussed)
1808 view = view->child;
1809 } else {
1810 if (view->parent && view->parent->focussed)
1811 view = view->parent;
1813 show_panel(view->panel);
1814 if (view->child && view_is_splitscreen(view->child))
1815 show_panel(view->child->panel);
1816 if (view->parent && view_is_splitscreen(view)) {
1817 err = view->parent->show(view->parent);
1818 if (err)
1819 goto done;
1821 err = view->show(view);
1822 if (err)
1823 goto done;
1824 if (view->child) {
1825 err = view->child->show(view->child);
1826 if (err)
1827 goto done;
1829 update_panels();
1830 doupdate();
1833 done:
1834 while (!TAILQ_EMPTY(&views)) {
1835 const struct got_error *close_err;
1836 view = TAILQ_FIRST(&views);
1837 TAILQ_REMOVE(&views, view, entry);
1838 close_err = view_close(view);
1839 if (close_err && err == NULL)
1840 err = close_err;
1843 errcode = pthread_mutex_unlock(&tog_mutex);
1844 if (errcode && err == NULL)
1845 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1847 return err;
1850 __dead static void
1851 usage_log(void)
1853 endwin();
1854 fprintf(stderr,
1855 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1856 getprogname());
1857 exit(1);
1860 /* Create newly allocated wide-character string equivalent to a byte string. */
1861 static const struct got_error *
1862 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1864 char *vis = NULL;
1865 const struct got_error *err = NULL;
1867 *ws = NULL;
1868 *wlen = mbstowcs(NULL, s, 0);
1869 if (*wlen == (size_t)-1) {
1870 int vislen;
1871 if (errno != EILSEQ)
1872 return got_error_from_errno("mbstowcs");
1874 /* byte string invalid in current encoding; try to "fix" it */
1875 err = got_mbsavis(&vis, &vislen, s);
1876 if (err)
1877 return err;
1878 *wlen = mbstowcs(NULL, vis, 0);
1879 if (*wlen == (size_t)-1) {
1880 err = got_error_from_errno("mbstowcs"); /* give up */
1881 goto done;
1885 *ws = calloc(*wlen + 1, sizeof(**ws));
1886 if (*ws == NULL) {
1887 err = got_error_from_errno("calloc");
1888 goto done;
1891 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1892 err = got_error_from_errno("mbstowcs");
1893 done:
1894 free(vis);
1895 if (err) {
1896 free(*ws);
1897 *ws = NULL;
1898 *wlen = 0;
1900 return err;
1903 static const struct got_error *
1904 expand_tab(char **ptr, const char *src)
1906 char *dst;
1907 size_t len, n, idx = 0, sz = 0;
1909 *ptr = NULL;
1910 n = len = strlen(src);
1911 dst = malloc(n + 1);
1912 if (dst == NULL)
1913 return got_error_from_errno("malloc");
1915 while (idx < len && src[idx]) {
1916 const char c = src[idx];
1918 if (c == '\t') {
1919 size_t nb = TABSIZE - sz % TABSIZE;
1920 char *p;
1922 p = realloc(dst, n + nb);
1923 if (p == NULL) {
1924 free(dst);
1925 return got_error_from_errno("realloc");
1928 dst = p;
1929 n += nb;
1930 memset(dst + sz, ' ', nb);
1931 sz += nb;
1932 } else
1933 dst[sz++] = src[idx];
1934 ++idx;
1937 dst[sz] = '\0';
1938 *ptr = dst;
1939 return NULL;
1943 * Advance at most n columns from wline starting at offset off.
1944 * Return the index to the first character after the span operation.
1945 * Return the combined column width of all spanned wide character in
1946 * *rcol.
1948 static int
1949 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1951 int width, i, cols = 0;
1953 if (n == 0) {
1954 *rcol = cols;
1955 return off;
1958 for (i = off; wline[i] != L'\0'; ++i) {
1959 if (wline[i] == L'\t')
1960 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1961 else
1962 width = wcwidth(wline[i]);
1964 if (width == -1) {
1965 width = 1;
1966 wline[i] = L'.';
1969 if (cols + width > n)
1970 break;
1971 cols += width;
1974 *rcol = cols;
1975 return i;
1979 * Format a line for display, ensuring that it won't overflow a width limit.
1980 * With scrolling, the width returned refers to the scrolled version of the
1981 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1983 static const struct got_error *
1984 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1985 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1987 const struct got_error *err = NULL;
1988 int cols;
1989 wchar_t *wline = NULL;
1990 char *exstr = NULL;
1991 size_t wlen;
1992 int i, scrollx;
1994 *wlinep = NULL;
1995 *widthp = 0;
1997 if (expand) {
1998 err = expand_tab(&exstr, line);
1999 if (err)
2000 return err;
2003 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2004 free(exstr);
2005 if (err)
2006 return err;
2008 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2010 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2011 wline[wlen - 1] = L'\0';
2012 wlen--;
2014 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2015 wline[wlen - 1] = L'\0';
2016 wlen--;
2019 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2020 wline[i] = L'\0';
2022 if (widthp)
2023 *widthp = cols;
2024 if (scrollxp)
2025 *scrollxp = scrollx;
2026 if (err)
2027 free(wline);
2028 else
2029 *wlinep = wline;
2030 return err;
2033 static const struct got_error*
2034 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2035 struct got_object_id *id, struct got_repository *repo)
2037 static const struct got_error *err = NULL;
2038 struct got_reflist_entry *re;
2039 char *s;
2040 const char *name;
2042 *refs_str = NULL;
2044 TAILQ_FOREACH(re, refs, entry) {
2045 struct got_tag_object *tag = NULL;
2046 struct got_object_id *ref_id;
2047 int cmp;
2049 name = got_ref_get_name(re->ref);
2050 if (strcmp(name, GOT_REF_HEAD) == 0)
2051 continue;
2052 if (strncmp(name, "refs/", 5) == 0)
2053 name += 5;
2054 if (strncmp(name, "got/", 4) == 0 &&
2055 strncmp(name, "got/backup/", 11) != 0)
2056 continue;
2057 if (strncmp(name, "heads/", 6) == 0)
2058 name += 6;
2059 if (strncmp(name, "remotes/", 8) == 0) {
2060 name += 8;
2061 s = strstr(name, "/" GOT_REF_HEAD);
2062 if (s != NULL && s[strlen(s)] == '\0')
2063 continue;
2065 err = got_ref_resolve(&ref_id, repo, re->ref);
2066 if (err)
2067 break;
2068 if (strncmp(name, "tags/", 5) == 0) {
2069 err = got_object_open_as_tag(&tag, repo, ref_id);
2070 if (err) {
2071 if (err->code != GOT_ERR_OBJ_TYPE) {
2072 free(ref_id);
2073 break;
2075 /* Ref points at something other than a tag. */
2076 err = NULL;
2077 tag = NULL;
2080 cmp = got_object_id_cmp(tag ?
2081 got_object_tag_get_object_id(tag) : ref_id, id);
2082 free(ref_id);
2083 if (tag)
2084 got_object_tag_close(tag);
2085 if (cmp != 0)
2086 continue;
2087 s = *refs_str;
2088 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2089 s ? ", " : "", name) == -1) {
2090 err = got_error_from_errno("asprintf");
2091 free(s);
2092 *refs_str = NULL;
2093 break;
2095 free(s);
2098 return err;
2101 static const struct got_error *
2102 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2103 int col_tab_align)
2105 char *smallerthan;
2107 smallerthan = strchr(author, '<');
2108 if (smallerthan && smallerthan[1] != '\0')
2109 author = smallerthan + 1;
2110 author[strcspn(author, "@>")] = '\0';
2111 return format_line(wauthor, author_width, NULL, author, 0, limit,
2112 col_tab_align, 0);
2115 static const struct got_error *
2116 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2117 struct got_object_id *id, const size_t date_display_cols,
2118 int author_display_cols)
2120 struct tog_log_view_state *s = &view->state.log;
2121 const struct got_error *err = NULL;
2122 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2123 char *logmsg0 = NULL, *logmsg = NULL;
2124 char *author = NULL;
2125 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2126 int author_width, logmsg_width;
2127 char *newline, *line = NULL;
2128 int col, limit, scrollx;
2129 const int avail = view->ncols;
2130 struct tm tm;
2131 time_t committer_time;
2132 struct tog_color *tc;
2134 committer_time = got_object_commit_get_committer_time(commit);
2135 if (gmtime_r(&committer_time, &tm) == NULL)
2136 return got_error_from_errno("gmtime_r");
2137 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2138 return got_error(GOT_ERR_NO_SPACE);
2140 if (avail <= date_display_cols)
2141 limit = MIN(sizeof(datebuf) - 1, avail);
2142 else
2143 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2144 tc = get_color(&s->colors, TOG_COLOR_DATE);
2145 if (tc)
2146 wattr_on(view->window,
2147 COLOR_PAIR(tc->colorpair), NULL);
2148 waddnstr(view->window, datebuf, limit);
2149 if (tc)
2150 wattr_off(view->window,
2151 COLOR_PAIR(tc->colorpair), NULL);
2152 col = limit;
2153 if (col > avail)
2154 goto done;
2156 if (avail >= 120) {
2157 char *id_str;
2158 err = got_object_id_str(&id_str, id);
2159 if (err)
2160 goto done;
2161 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2162 if (tc)
2163 wattr_on(view->window,
2164 COLOR_PAIR(tc->colorpair), NULL);
2165 wprintw(view->window, "%.8s ", id_str);
2166 if (tc)
2167 wattr_off(view->window,
2168 COLOR_PAIR(tc->colorpair), NULL);
2169 free(id_str);
2170 col += 9;
2171 if (col > avail)
2172 goto done;
2175 if (s->use_committer)
2176 author = strdup(got_object_commit_get_committer(commit));
2177 else
2178 author = strdup(got_object_commit_get_author(commit));
2179 if (author == NULL) {
2180 err = got_error_from_errno("strdup");
2181 goto done;
2183 err = format_author(&wauthor, &author_width, author, avail - col, col);
2184 if (err)
2185 goto done;
2186 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2187 if (tc)
2188 wattr_on(view->window,
2189 COLOR_PAIR(tc->colorpair), NULL);
2190 waddwstr(view->window, wauthor);
2191 col += author_width;
2192 while (col < avail && author_width < author_display_cols + 2) {
2193 waddch(view->window, ' ');
2194 col++;
2195 author_width++;
2197 if (tc)
2198 wattr_off(view->window,
2199 COLOR_PAIR(tc->colorpair), NULL);
2200 if (col > avail)
2201 goto done;
2203 err = got_object_commit_get_logmsg(&logmsg0, commit);
2204 if (err)
2205 goto done;
2206 logmsg = logmsg0;
2207 while (*logmsg == '\n')
2208 logmsg++;
2209 newline = strchr(logmsg, '\n');
2210 if (newline)
2211 *newline = '\0';
2212 limit = avail - col;
2213 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2214 limit--; /* for the border */
2215 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2216 limit, col, 1);
2217 if (err)
2218 goto done;
2219 waddwstr(view->window, &wlogmsg[scrollx]);
2220 col += MAX(logmsg_width, 0);
2221 while (col < avail) {
2222 waddch(view->window, ' ');
2223 col++;
2225 done:
2226 free(logmsg0);
2227 free(wlogmsg);
2228 free(author);
2229 free(wauthor);
2230 free(line);
2231 return err;
2234 static struct commit_queue_entry *
2235 alloc_commit_queue_entry(struct got_commit_object *commit,
2236 struct got_object_id *id)
2238 struct commit_queue_entry *entry;
2239 struct got_object_id *dup;
2241 entry = calloc(1, sizeof(*entry));
2242 if (entry == NULL)
2243 return NULL;
2245 dup = got_object_id_dup(id);
2246 if (dup == NULL) {
2247 free(entry);
2248 return NULL;
2251 entry->id = dup;
2252 entry->commit = commit;
2253 return entry;
2256 static void
2257 pop_commit(struct commit_queue *commits)
2259 struct commit_queue_entry *entry;
2261 entry = TAILQ_FIRST(&commits->head);
2262 TAILQ_REMOVE(&commits->head, entry, entry);
2263 got_object_commit_close(entry->commit);
2264 commits->ncommits--;
2265 free(entry->id);
2266 free(entry);
2269 static void
2270 free_commits(struct commit_queue *commits)
2272 while (!TAILQ_EMPTY(&commits->head))
2273 pop_commit(commits);
2276 static const struct got_error *
2277 match_commit(int *have_match, struct got_object_id *id,
2278 struct got_commit_object *commit, regex_t *regex)
2280 const struct got_error *err = NULL;
2281 regmatch_t regmatch;
2282 char *id_str = NULL, *logmsg = NULL;
2284 *have_match = 0;
2286 err = got_object_id_str(&id_str, id);
2287 if (err)
2288 return err;
2290 err = got_object_commit_get_logmsg(&logmsg, commit);
2291 if (err)
2292 goto done;
2294 if (regexec(regex, got_object_commit_get_author(commit), 1,
2295 &regmatch, 0) == 0 ||
2296 regexec(regex, got_object_commit_get_committer(commit), 1,
2297 &regmatch, 0) == 0 ||
2298 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2299 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2300 *have_match = 1;
2301 done:
2302 free(id_str);
2303 free(logmsg);
2304 return err;
2307 static const struct got_error *
2308 queue_commits(struct tog_log_thread_args *a)
2310 const struct got_error *err = NULL;
2313 * We keep all commits open throughout the lifetime of the log
2314 * view in order to avoid having to re-fetch commits from disk
2315 * while updating the display.
2317 do {
2318 struct got_object_id id;
2319 struct got_commit_object *commit;
2320 struct commit_queue_entry *entry;
2321 int limit_match = 0;
2322 int errcode;
2324 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2325 NULL, NULL);
2326 if (err)
2327 break;
2329 err = got_object_open_as_commit(&commit, a->repo, &id);
2330 if (err)
2331 break;
2332 entry = alloc_commit_queue_entry(commit, &id);
2333 if (entry == NULL) {
2334 err = got_error_from_errno("alloc_commit_queue_entry");
2335 break;
2338 errcode = pthread_mutex_lock(&tog_mutex);
2339 if (errcode) {
2340 err = got_error_set_errno(errcode,
2341 "pthread_mutex_lock");
2342 break;
2345 entry->idx = a->real_commits->ncommits;
2346 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2347 a->real_commits->ncommits++;
2349 if (*a->limiting) {
2350 err = match_commit(&limit_match, &id, commit,
2351 a->limit_regex);
2352 if (err)
2353 break;
2355 if (limit_match) {
2356 struct commit_queue_entry *matched;
2358 matched = alloc_commit_queue_entry(
2359 entry->commit, entry->id);
2360 if (matched == NULL) {
2361 err = got_error_from_errno(
2362 "alloc_commit_queue_entry");
2363 break;
2366 err = got_object_commit_dup(&matched->commit,
2367 entry->commit);
2368 if (err)
2369 break;
2371 matched->idx = a->limit_commits->ncommits;
2372 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2373 matched, entry);
2374 a->limit_commits->ncommits++;
2378 * This is how we signal log_thread() that we
2379 * have found a match, and that it should be
2380 * counted as a new entry for the view.
2382 a->limit_match = limit_match;
2385 if (*a->searching == TOG_SEARCH_FORWARD &&
2386 !*a->search_next_done) {
2387 int have_match;
2388 err = match_commit(&have_match, &id, commit, a->regex);
2389 if (err)
2390 break;
2392 if (*a->limiting) {
2393 if (limit_match && have_match)
2394 *a->search_next_done =
2395 TOG_SEARCH_HAVE_MORE;
2396 } else if (have_match)
2397 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2400 errcode = pthread_mutex_unlock(&tog_mutex);
2401 if (errcode && err == NULL)
2402 err = got_error_set_errno(errcode,
2403 "pthread_mutex_unlock");
2404 if (err)
2405 break;
2406 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2408 return err;
2411 static void
2412 select_commit(struct tog_log_view_state *s)
2414 struct commit_queue_entry *entry;
2415 int ncommits = 0;
2417 entry = s->first_displayed_entry;
2418 while (entry) {
2419 if (ncommits == s->selected) {
2420 s->selected_entry = entry;
2421 break;
2423 entry = TAILQ_NEXT(entry, entry);
2424 ncommits++;
2428 static const struct got_error *
2429 draw_commits(struct tog_view *view)
2431 const struct got_error *err = NULL;
2432 struct tog_log_view_state *s = &view->state.log;
2433 struct commit_queue_entry *entry = s->selected_entry;
2434 int limit = view->nlines;
2435 int width;
2436 int ncommits, author_cols = 4;
2437 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2438 char *refs_str = NULL;
2439 wchar_t *wline;
2440 struct tog_color *tc;
2441 static const size_t date_display_cols = 12;
2443 if (view_is_hsplit_top(view))
2444 --limit; /* account for border */
2446 if (s->selected_entry &&
2447 !(view->searching && view->search_next_done == 0)) {
2448 struct got_reflist_head *refs;
2449 err = got_object_id_str(&id_str, s->selected_entry->id);
2450 if (err)
2451 return err;
2452 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2453 s->selected_entry->id);
2454 if (refs) {
2455 err = build_refs_str(&refs_str, refs,
2456 s->selected_entry->id, s->repo);
2457 if (err)
2458 goto done;
2462 if (s->thread_args.commits_needed == 0)
2463 halfdelay(10); /* disable fast refresh */
2465 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2466 if (asprintf(&ncommits_str, " [%d/%d] %s",
2467 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2468 (view->searching && !view->search_next_done) ?
2469 "searching..." : "loading...") == -1) {
2470 err = got_error_from_errno("asprintf");
2471 goto done;
2473 } else {
2474 const char *search_str = NULL;
2475 const char *limit_str = NULL;
2477 if (view->searching) {
2478 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2479 search_str = "no more matches";
2480 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2481 search_str = "no matches found";
2482 else if (!view->search_next_done)
2483 search_str = "searching...";
2486 if (s->limit_view && s->commits->ncommits == 0)
2487 limit_str = "no matches found";
2489 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2490 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2491 search_str ? search_str : (refs_str ? refs_str : ""),
2492 limit_str ? limit_str : "") == -1) {
2493 err = got_error_from_errno("asprintf");
2494 goto done;
2498 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2499 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2500 "........................................",
2501 s->in_repo_path, ncommits_str) == -1) {
2502 err = got_error_from_errno("asprintf");
2503 header = NULL;
2504 goto done;
2506 } else if (asprintf(&header, "commit %s%s",
2507 id_str ? id_str : "........................................",
2508 ncommits_str) == -1) {
2509 err = got_error_from_errno("asprintf");
2510 header = NULL;
2511 goto done;
2513 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2514 if (err)
2515 goto done;
2517 werase(view->window);
2519 if (view_needs_focus_indication(view))
2520 wstandout(view->window);
2521 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2522 if (tc)
2523 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2524 waddwstr(view->window, wline);
2525 while (width < view->ncols) {
2526 waddch(view->window, ' ');
2527 width++;
2529 if (tc)
2530 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2531 if (view_needs_focus_indication(view))
2532 wstandend(view->window);
2533 free(wline);
2534 if (limit <= 1)
2535 goto done;
2537 /* Grow author column size if necessary, and set view->maxx. */
2538 entry = s->first_displayed_entry;
2539 ncommits = 0;
2540 view->maxx = 0;
2541 while (entry) {
2542 struct got_commit_object *c = entry->commit;
2543 char *author, *eol, *msg, *msg0;
2544 wchar_t *wauthor, *wmsg;
2545 int width;
2546 if (ncommits >= limit - 1)
2547 break;
2548 if (s->use_committer)
2549 author = strdup(got_object_commit_get_committer(c));
2550 else
2551 author = strdup(got_object_commit_get_author(c));
2552 if (author == NULL) {
2553 err = got_error_from_errno("strdup");
2554 goto done;
2556 err = format_author(&wauthor, &width, author, COLS,
2557 date_display_cols);
2558 if (author_cols < width)
2559 author_cols = width;
2560 free(wauthor);
2561 free(author);
2562 if (err)
2563 goto done;
2564 err = got_object_commit_get_logmsg(&msg0, c);
2565 if (err)
2566 goto done;
2567 msg = msg0;
2568 while (*msg == '\n')
2569 ++msg;
2570 if ((eol = strchr(msg, '\n')))
2571 *eol = '\0';
2572 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2573 date_display_cols + author_cols, 0);
2574 if (err)
2575 goto done;
2576 view->maxx = MAX(view->maxx, width);
2577 free(msg0);
2578 free(wmsg);
2579 ncommits++;
2580 entry = TAILQ_NEXT(entry, entry);
2583 entry = s->first_displayed_entry;
2584 s->last_displayed_entry = s->first_displayed_entry;
2585 ncommits = 0;
2586 while (entry) {
2587 if (ncommits >= limit - 1)
2588 break;
2589 if (ncommits == s->selected)
2590 wstandout(view->window);
2591 err = draw_commit(view, entry->commit, entry->id,
2592 date_display_cols, author_cols);
2593 if (ncommits == s->selected)
2594 wstandend(view->window);
2595 if (err)
2596 goto done;
2597 ncommits++;
2598 s->last_displayed_entry = entry;
2599 entry = TAILQ_NEXT(entry, entry);
2602 view_border(view);
2603 done:
2604 free(id_str);
2605 free(refs_str);
2606 free(ncommits_str);
2607 free(header);
2608 return err;
2611 static void
2612 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2614 struct commit_queue_entry *entry;
2615 int nscrolled = 0;
2617 entry = TAILQ_FIRST(&s->commits->head);
2618 if (s->first_displayed_entry == entry)
2619 return;
2621 entry = s->first_displayed_entry;
2622 while (entry && nscrolled < maxscroll) {
2623 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2624 if (entry) {
2625 s->first_displayed_entry = entry;
2626 nscrolled++;
2631 static const struct got_error *
2632 trigger_log_thread(struct tog_view *view, int wait)
2634 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2635 int errcode;
2637 halfdelay(1); /* fast refresh while loading commits */
2639 while (!ta->log_complete && !tog_thread_error &&
2640 (ta->commits_needed > 0 || ta->load_all)) {
2641 /* Wake the log thread. */
2642 errcode = pthread_cond_signal(&ta->need_commits);
2643 if (errcode)
2644 return got_error_set_errno(errcode,
2645 "pthread_cond_signal");
2648 * The mutex will be released while the view loop waits
2649 * in wgetch(), at which time the log thread will run.
2651 if (!wait)
2652 break;
2654 /* Display progress update in log view. */
2655 show_log_view(view);
2656 update_panels();
2657 doupdate();
2659 /* Wait right here while next commit is being loaded. */
2660 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2661 if (errcode)
2662 return got_error_set_errno(errcode,
2663 "pthread_cond_wait");
2665 /* Display progress update in log view. */
2666 show_log_view(view);
2667 update_panels();
2668 doupdate();
2671 return NULL;
2674 static const struct got_error *
2675 request_log_commits(struct tog_view *view)
2677 struct tog_log_view_state *state = &view->state.log;
2678 const struct got_error *err = NULL;
2680 if (state->thread_args.log_complete)
2681 return NULL;
2683 state->thread_args.commits_needed += view->nscrolled;
2684 err = trigger_log_thread(view, 1);
2685 view->nscrolled = 0;
2687 return err;
2690 static const struct got_error *
2691 log_scroll_down(struct tog_view *view, int maxscroll)
2693 struct tog_log_view_state *s = &view->state.log;
2694 const struct got_error *err = NULL;
2695 struct commit_queue_entry *pentry;
2696 int nscrolled = 0, ncommits_needed;
2698 if (s->last_displayed_entry == NULL)
2699 return NULL;
2701 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2702 if (s->commits->ncommits < ncommits_needed &&
2703 !s->thread_args.log_complete) {
2705 * Ask the log thread for required amount of commits.
2707 s->thread_args.commits_needed +=
2708 ncommits_needed - s->commits->ncommits;
2709 err = trigger_log_thread(view, 1);
2710 if (err)
2711 return err;
2714 do {
2715 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2716 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2717 break;
2719 s->last_displayed_entry = pentry ?
2720 pentry : s->last_displayed_entry;;
2722 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2723 if (pentry == NULL)
2724 break;
2725 s->first_displayed_entry = pentry;
2726 } while (++nscrolled < maxscroll);
2728 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2729 view->nscrolled += nscrolled;
2730 else
2731 view->nscrolled = 0;
2733 return err;
2736 static const struct got_error *
2737 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2738 struct got_commit_object *commit, struct got_object_id *commit_id,
2739 struct tog_view *log_view, struct got_repository *repo)
2741 const struct got_error *err;
2742 struct got_object_qid *parent_id;
2743 struct tog_view *diff_view;
2745 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2746 if (diff_view == NULL)
2747 return got_error_from_errno("view_open");
2749 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2750 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2751 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2752 if (err == NULL)
2753 *new_view = diff_view;
2754 return err;
2757 static const struct got_error *
2758 tree_view_visit_subtree(struct tog_tree_view_state *s,
2759 struct got_tree_object *subtree)
2761 struct tog_parent_tree *parent;
2763 parent = calloc(1, sizeof(*parent));
2764 if (parent == NULL)
2765 return got_error_from_errno("calloc");
2767 parent->tree = s->tree;
2768 parent->first_displayed_entry = s->first_displayed_entry;
2769 parent->selected_entry = s->selected_entry;
2770 parent->selected = s->selected;
2771 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2772 s->tree = subtree;
2773 s->selected = 0;
2774 s->first_displayed_entry = NULL;
2775 return NULL;
2778 static const struct got_error *
2779 tree_view_walk_path(struct tog_tree_view_state *s,
2780 struct got_commit_object *commit, const char *path)
2782 const struct got_error *err = NULL;
2783 struct got_tree_object *tree = NULL;
2784 const char *p;
2785 char *slash, *subpath = NULL;
2787 /* Walk the path and open corresponding tree objects. */
2788 p = path;
2789 while (*p) {
2790 struct got_tree_entry *te;
2791 struct got_object_id *tree_id;
2792 char *te_name;
2794 while (p[0] == '/')
2795 p++;
2797 /* Ensure the correct subtree entry is selected. */
2798 slash = strchr(p, '/');
2799 if (slash == NULL)
2800 te_name = strdup(p);
2801 else
2802 te_name = strndup(p, slash - p);
2803 if (te_name == NULL) {
2804 err = got_error_from_errno("strndup");
2805 break;
2807 te = got_object_tree_find_entry(s->tree, te_name);
2808 if (te == NULL) {
2809 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2810 free(te_name);
2811 break;
2813 free(te_name);
2814 s->first_displayed_entry = s->selected_entry = te;
2816 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2817 break; /* jump to this file's entry */
2819 slash = strchr(p, '/');
2820 if (slash)
2821 subpath = strndup(path, slash - path);
2822 else
2823 subpath = strdup(path);
2824 if (subpath == NULL) {
2825 err = got_error_from_errno("strdup");
2826 break;
2829 err = got_object_id_by_path(&tree_id, s->repo, commit,
2830 subpath);
2831 if (err)
2832 break;
2834 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2835 free(tree_id);
2836 if (err)
2837 break;
2839 err = tree_view_visit_subtree(s, tree);
2840 if (err) {
2841 got_object_tree_close(tree);
2842 break;
2844 if (slash == NULL)
2845 break;
2846 free(subpath);
2847 subpath = NULL;
2848 p = slash;
2851 free(subpath);
2852 return err;
2855 static const struct got_error *
2856 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2857 struct commit_queue_entry *entry, const char *path,
2858 const char *head_ref_name, struct got_repository *repo)
2860 const struct got_error *err = NULL;
2861 struct tog_tree_view_state *s;
2862 struct tog_view *tree_view;
2864 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2865 if (tree_view == NULL)
2866 return got_error_from_errno("view_open");
2868 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2869 if (err)
2870 return err;
2871 s = &tree_view->state.tree;
2873 *new_view = tree_view;
2875 if (got_path_is_root_dir(path))
2876 return NULL;
2878 return tree_view_walk_path(s, entry->commit, path);
2881 static const struct got_error *
2882 block_signals_used_by_main_thread(void)
2884 sigset_t sigset;
2885 int errcode;
2887 if (sigemptyset(&sigset) == -1)
2888 return got_error_from_errno("sigemptyset");
2890 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2891 if (sigaddset(&sigset, SIGWINCH) == -1)
2892 return got_error_from_errno("sigaddset");
2893 if (sigaddset(&sigset, SIGCONT) == -1)
2894 return got_error_from_errno("sigaddset");
2895 if (sigaddset(&sigset, SIGINT) == -1)
2896 return got_error_from_errno("sigaddset");
2897 if (sigaddset(&sigset, SIGTERM) == -1)
2898 return got_error_from_errno("sigaddset");
2900 /* ncurses handles SIGTSTP */
2901 if (sigaddset(&sigset, SIGTSTP) == -1)
2902 return got_error_from_errno("sigaddset");
2904 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2905 if (errcode)
2906 return got_error_set_errno(errcode, "pthread_sigmask");
2908 return NULL;
2911 static void *
2912 log_thread(void *arg)
2914 const struct got_error *err = NULL;
2915 int errcode = 0;
2916 struct tog_log_thread_args *a = arg;
2917 int done = 0;
2920 * Sync startup with main thread such that we begin our
2921 * work once view_input() has released the mutex.
2923 errcode = pthread_mutex_lock(&tog_mutex);
2924 if (errcode) {
2925 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2926 return (void *)err;
2929 err = block_signals_used_by_main_thread();
2930 if (err) {
2931 pthread_mutex_unlock(&tog_mutex);
2932 goto done;
2935 while (!done && !err && !tog_fatal_signal_received()) {
2936 errcode = pthread_mutex_unlock(&tog_mutex);
2937 if (errcode) {
2938 err = got_error_set_errno(errcode,
2939 "pthread_mutex_unlock");
2940 goto done;
2942 err = queue_commits(a);
2943 if (err) {
2944 if (err->code != GOT_ERR_ITER_COMPLETED)
2945 goto done;
2946 err = NULL;
2947 done = 1;
2948 } else if (a->commits_needed > 0 && !a->load_all) {
2949 if (*a->limiting) {
2950 if (a->limit_match)
2951 a->commits_needed--;
2952 } else
2953 a->commits_needed--;
2956 errcode = pthread_mutex_lock(&tog_mutex);
2957 if (errcode) {
2958 err = got_error_set_errno(errcode,
2959 "pthread_mutex_lock");
2960 goto done;
2961 } else if (*a->quit)
2962 done = 1;
2963 else if (*a->limiting && *a->first_displayed_entry == NULL) {
2964 *a->first_displayed_entry =
2965 TAILQ_FIRST(&a->limit_commits->head);
2966 *a->selected_entry = *a->first_displayed_entry;
2967 } else if (*a->first_displayed_entry == NULL) {
2968 *a->first_displayed_entry =
2969 TAILQ_FIRST(&a->real_commits->head);
2970 *a->selected_entry = *a->first_displayed_entry;
2973 errcode = pthread_cond_signal(&a->commit_loaded);
2974 if (errcode) {
2975 err = got_error_set_errno(errcode,
2976 "pthread_cond_signal");
2977 pthread_mutex_unlock(&tog_mutex);
2978 goto done;
2981 if (done)
2982 a->commits_needed = 0;
2983 else {
2984 if (a->commits_needed == 0 && !a->load_all) {
2985 errcode = pthread_cond_wait(&a->need_commits,
2986 &tog_mutex);
2987 if (errcode) {
2988 err = got_error_set_errno(errcode,
2989 "pthread_cond_wait");
2990 pthread_mutex_unlock(&tog_mutex);
2991 goto done;
2993 if (*a->quit)
2994 done = 1;
2998 a->log_complete = 1;
2999 errcode = pthread_mutex_unlock(&tog_mutex);
3000 if (errcode)
3001 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3002 done:
3003 if (err) {
3004 tog_thread_error = 1;
3005 pthread_cond_signal(&a->commit_loaded);
3007 return (void *)err;
3010 static const struct got_error *
3011 stop_log_thread(struct tog_log_view_state *s)
3013 const struct got_error *err = NULL, *thread_err = NULL;
3014 int errcode;
3016 if (s->thread) {
3017 s->quit = 1;
3018 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3019 if (errcode)
3020 return got_error_set_errno(errcode,
3021 "pthread_cond_signal");
3022 errcode = pthread_mutex_unlock(&tog_mutex);
3023 if (errcode)
3024 return got_error_set_errno(errcode,
3025 "pthread_mutex_unlock");
3026 errcode = pthread_join(s->thread, (void **)&thread_err);
3027 if (errcode)
3028 return got_error_set_errno(errcode, "pthread_join");
3029 errcode = pthread_mutex_lock(&tog_mutex);
3030 if (errcode)
3031 return got_error_set_errno(errcode,
3032 "pthread_mutex_lock");
3033 s->thread = NULL;
3036 if (s->thread_args.repo) {
3037 err = got_repo_close(s->thread_args.repo);
3038 s->thread_args.repo = NULL;
3041 if (s->thread_args.pack_fds) {
3042 const struct got_error *pack_err =
3043 got_repo_pack_fds_close(s->thread_args.pack_fds);
3044 if (err == NULL)
3045 err = pack_err;
3046 s->thread_args.pack_fds = NULL;
3049 if (s->thread_args.graph) {
3050 got_commit_graph_close(s->thread_args.graph);
3051 s->thread_args.graph = NULL;
3054 return err ? err : thread_err;
3057 static const struct got_error *
3058 close_log_view(struct tog_view *view)
3060 const struct got_error *err = NULL;
3061 struct tog_log_view_state *s = &view->state.log;
3062 int errcode;
3064 err = stop_log_thread(s);
3066 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3067 if (errcode && err == NULL)
3068 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3070 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3071 if (errcode && err == NULL)
3072 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3074 free_commits(&s->limit_commits);
3075 free_commits(&s->real_commits);
3076 free(s->in_repo_path);
3077 s->in_repo_path = NULL;
3078 free(s->start_id);
3079 s->start_id = NULL;
3080 free(s->head_ref_name);
3081 s->head_ref_name = NULL;
3082 return err;
3086 * We use two queues to implement the limit feature: first consists of
3087 * commits matching the current limit_regex; second is the real queue
3088 * of all known commits (real_commits). When the user starts limiting,
3089 * we swap queues such that all movement and displaying functionality
3090 * works with very slight change.
3092 static const struct got_error *
3093 limit_log_view(struct tog_view *view)
3095 struct tog_log_view_state *s = &view->state.log;
3096 struct commit_queue_entry *entry;
3097 struct tog_view *v = view;
3098 const struct got_error *err = NULL;
3099 char pattern[1024];
3100 int ret;
3102 if (view_is_hsplit_top(view))
3103 v = view->child;
3104 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3105 v = view->parent;
3107 /* Get the pattern */
3108 wmove(v->window, v->nlines - 1, 0);
3109 wclrtoeol(v->window);
3110 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3111 nodelay(v->window, FALSE);
3112 nocbreak();
3113 echo();
3114 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3115 cbreak();
3116 noecho();
3117 nodelay(v->window, TRUE);
3118 if (ret == ERR)
3119 return NULL;
3121 if (*pattern == '\0') {
3123 * Safety measure for the situation where the user
3124 * resets limit without previously limiting anything.
3126 if (!s->limit_view)
3127 return NULL;
3130 * User could have pressed Ctrl+L, which refreshed the
3131 * commit queues, it means we can't save previously
3132 * (before limit took place) displayed entries,
3133 * because they would point to already free'ed memory,
3134 * so we are forced to always select first entry of
3135 * the queue.
3137 s->commits = &s->real_commits;
3138 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3139 s->selected_entry = s->first_displayed_entry;
3140 s->selected = 0;
3141 s->limit_view = 0;
3143 return NULL;
3146 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3147 return NULL;
3149 s->limit_view = 1;
3151 /* Clear the screen while loading limit view */
3152 s->first_displayed_entry = NULL;
3153 s->last_displayed_entry = NULL;
3154 s->selected_entry = NULL;
3155 s->commits = &s->limit_commits;
3157 /* Prepare limit queue for new search */
3158 free_commits(&s->limit_commits);
3159 s->limit_commits.ncommits = 0;
3161 /* First process commits, which are in queue already */
3162 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3163 int have_match = 0;
3165 err = match_commit(&have_match, entry->id,
3166 entry->commit, &s->limit_regex);
3167 if (err)
3168 return err;
3170 if (have_match) {
3171 struct commit_queue_entry *matched;
3173 matched = alloc_commit_queue_entry(entry->commit,
3174 entry->id);
3175 if (matched == NULL) {
3176 err = got_error_from_errno(
3177 "alloc_commit_queue_entry");
3178 break;
3181 err = got_object_commit_dup(&matched->commit,
3182 entry->commit);
3183 if (err) {
3184 free(matched);
3185 return err;
3188 matched->idx = s->limit_commits.ncommits;
3189 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3190 matched, entry);
3191 s->limit_commits.ncommits++;
3195 /* Second process all the commits, until we fill the screen */
3196 if (s->limit_commits.ncommits < view->nlines - 1 &&
3197 !s->thread_args.log_complete) {
3198 s->thread_args.commits_needed +=
3199 view->nlines - s->limit_commits.ncommits - 1;
3200 err = trigger_log_thread(view, 1);
3201 if (err)
3202 return err;
3205 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3206 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3207 s->selected = 0;
3209 return NULL;
3212 static const struct got_error *
3213 search_start_log_view(struct tog_view *view)
3215 struct tog_log_view_state *s = &view->state.log;
3217 s->matched_entry = NULL;
3218 s->search_entry = NULL;
3219 return NULL;
3222 static const struct got_error *
3223 search_next_log_view(struct tog_view *view)
3225 const struct got_error *err = NULL;
3226 struct tog_log_view_state *s = &view->state.log;
3227 struct commit_queue_entry *entry;
3229 /* Display progress update in log view. */
3230 show_log_view(view);
3231 update_panels();
3232 doupdate();
3234 if (s->search_entry) {
3235 int errcode, ch;
3236 errcode = pthread_mutex_unlock(&tog_mutex);
3237 if (errcode)
3238 return got_error_set_errno(errcode,
3239 "pthread_mutex_unlock");
3240 ch = wgetch(view->window);
3241 errcode = pthread_mutex_lock(&tog_mutex);
3242 if (errcode)
3243 return got_error_set_errno(errcode,
3244 "pthread_mutex_lock");
3245 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3246 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3247 return NULL;
3249 if (view->searching == TOG_SEARCH_FORWARD)
3250 entry = TAILQ_NEXT(s->search_entry, entry);
3251 else
3252 entry = TAILQ_PREV(s->search_entry,
3253 commit_queue_head, entry);
3254 } else if (s->matched_entry) {
3256 * If the user has moved the cursor after we hit a match,
3257 * the position from where we should continue searching
3258 * might have changed.
3260 if (view->searching == TOG_SEARCH_FORWARD)
3261 entry = TAILQ_NEXT(s->selected_entry, entry);
3262 else
3263 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3264 entry);
3265 } else {
3266 entry = s->selected_entry;
3269 while (1) {
3270 int have_match = 0;
3272 if (entry == NULL) {
3273 if (s->thread_args.log_complete ||
3274 view->searching == TOG_SEARCH_BACKWARD) {
3275 view->search_next_done =
3276 (s->matched_entry == NULL ?
3277 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3278 s->search_entry = NULL;
3279 return NULL;
3282 * Poke the log thread for more commits and return,
3283 * allowing the main loop to make progress. Search
3284 * will resume at s->search_entry once we come back.
3286 s->thread_args.commits_needed++;
3287 return trigger_log_thread(view, 0);
3290 err = match_commit(&have_match, entry->id, entry->commit,
3291 &view->regex);
3292 if (err)
3293 break;
3294 if (have_match) {
3295 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3296 s->matched_entry = entry;
3297 break;
3300 s->search_entry = entry;
3301 if (view->searching == TOG_SEARCH_FORWARD)
3302 entry = TAILQ_NEXT(entry, entry);
3303 else
3304 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3307 if (s->matched_entry) {
3308 int cur = s->selected_entry->idx;
3309 while (cur < s->matched_entry->idx) {
3310 err = input_log_view(NULL, view, KEY_DOWN);
3311 if (err)
3312 return err;
3313 cur++;
3315 while (cur > s->matched_entry->idx) {
3316 err = input_log_view(NULL, view, KEY_UP);
3317 if (err)
3318 return err;
3319 cur--;
3323 s->search_entry = NULL;
3325 return NULL;
3328 static const struct got_error *
3329 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3330 struct got_repository *repo, const char *head_ref_name,
3331 const char *in_repo_path, int log_branches)
3333 const struct got_error *err = NULL;
3334 struct tog_log_view_state *s = &view->state.log;
3335 struct got_repository *thread_repo = NULL;
3336 struct got_commit_graph *thread_graph = NULL;
3337 int errcode;
3339 if (in_repo_path != s->in_repo_path) {
3340 free(s->in_repo_path);
3341 s->in_repo_path = strdup(in_repo_path);
3342 if (s->in_repo_path == NULL)
3343 return got_error_from_errno("strdup");
3346 /* The commit queue only contains commits being displayed. */
3347 TAILQ_INIT(&s->real_commits.head);
3348 s->real_commits.ncommits = 0;
3349 s->commits = &s->real_commits;
3351 TAILQ_INIT(&s->limit_commits.head);
3352 s->limit_view = 0;
3353 s->limit_commits.ncommits = 0;
3355 s->repo = repo;
3356 if (head_ref_name) {
3357 s->head_ref_name = strdup(head_ref_name);
3358 if (s->head_ref_name == NULL) {
3359 err = got_error_from_errno("strdup");
3360 goto done;
3363 s->start_id = got_object_id_dup(start_id);
3364 if (s->start_id == NULL) {
3365 err = got_error_from_errno("got_object_id_dup");
3366 goto done;
3368 s->log_branches = log_branches;
3370 STAILQ_INIT(&s->colors);
3371 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3372 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3373 get_color_value("TOG_COLOR_COMMIT"));
3374 if (err)
3375 goto done;
3376 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3377 get_color_value("TOG_COLOR_AUTHOR"));
3378 if (err) {
3379 free_colors(&s->colors);
3380 goto done;
3382 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3383 get_color_value("TOG_COLOR_DATE"));
3384 if (err) {
3385 free_colors(&s->colors);
3386 goto done;
3390 view->show = show_log_view;
3391 view->input = input_log_view;
3392 view->resize = resize_log_view;
3393 view->close = close_log_view;
3394 view->search_start = search_start_log_view;
3395 view->search_next = search_next_log_view;
3397 if (s->thread_args.pack_fds == NULL) {
3398 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3399 if (err)
3400 goto done;
3402 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3403 s->thread_args.pack_fds);
3404 if (err)
3405 goto done;
3406 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3407 !s->log_branches);
3408 if (err)
3409 goto done;
3410 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3411 s->repo, NULL, NULL);
3412 if (err)
3413 goto done;
3415 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3416 if (errcode) {
3417 err = got_error_set_errno(errcode, "pthread_cond_init");
3418 goto done;
3420 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3421 if (errcode) {
3422 err = got_error_set_errno(errcode, "pthread_cond_init");
3423 goto done;
3426 s->thread_args.commits_needed = view->nlines;
3427 s->thread_args.graph = thread_graph;
3428 s->thread_args.real_commits = &s->real_commits;
3429 s->thread_args.limit_commits = &s->limit_commits;
3430 s->thread_args.in_repo_path = s->in_repo_path;
3431 s->thread_args.start_id = s->start_id;
3432 s->thread_args.repo = thread_repo;
3433 s->thread_args.log_complete = 0;
3434 s->thread_args.quit = &s->quit;
3435 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3436 s->thread_args.selected_entry = &s->selected_entry;
3437 s->thread_args.searching = &view->searching;
3438 s->thread_args.search_next_done = &view->search_next_done;
3439 s->thread_args.regex = &view->regex;
3440 s->thread_args.limiting = &s->limit_view;
3441 s->thread_args.limit_regex = &s->limit_regex;
3442 s->thread_args.limit_commits = &s->limit_commits;
3443 done:
3444 if (err)
3445 close_log_view(view);
3446 return err;
3449 static const struct got_error *
3450 show_log_view(struct tog_view *view)
3452 const struct got_error *err;
3453 struct tog_log_view_state *s = &view->state.log;
3455 if (s->thread == NULL) {
3456 int errcode = pthread_create(&s->thread, NULL, log_thread,
3457 &s->thread_args);
3458 if (errcode)
3459 return got_error_set_errno(errcode, "pthread_create");
3460 if (s->thread_args.commits_needed > 0) {
3461 err = trigger_log_thread(view, 1);
3462 if (err)
3463 return err;
3467 return draw_commits(view);
3470 static void
3471 log_move_cursor_up(struct tog_view *view, int page, int home)
3473 struct tog_log_view_state *s = &view->state.log;
3475 if (s->first_displayed_entry == NULL)
3476 return;
3477 if (s->selected_entry->idx == 0)
3478 view->count = 0;
3480 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3481 || home)
3482 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3484 if (!page && !home && s->selected > 0)
3485 --s->selected;
3486 else
3487 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3489 select_commit(s);
3490 return;
3493 static const struct got_error *
3494 log_move_cursor_down(struct tog_view *view, int page)
3496 struct tog_log_view_state *s = &view->state.log;
3497 const struct got_error *err = NULL;
3498 int eos = view->nlines - 2;
3500 if (s->first_displayed_entry == NULL)
3501 return NULL;
3503 if (s->thread_args.log_complete &&
3504 s->selected_entry->idx >= s->commits->ncommits - 1)
3505 return NULL;
3507 if (view_is_hsplit_top(view))
3508 --eos; /* border consumes the last line */
3510 if (!page) {
3511 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3512 ++s->selected;
3513 else
3514 err = log_scroll_down(view, 1);
3515 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3516 struct commit_queue_entry *entry;
3517 int n;
3519 s->selected = 0;
3520 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3521 s->last_displayed_entry = entry;
3522 for (n = 0; n <= eos; n++) {
3523 if (entry == NULL)
3524 break;
3525 s->first_displayed_entry = entry;
3526 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3528 if (n > 0)
3529 s->selected = n - 1;
3530 } else {
3531 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3532 s->thread_args.log_complete)
3533 s->selected += MIN(page,
3534 s->commits->ncommits - s->selected_entry->idx - 1);
3535 else
3536 err = log_scroll_down(view, page);
3538 if (err)
3539 return err;
3542 * We might necessarily overshoot in horizontal
3543 * splits; if so, select the last displayed commit.
3545 if (s->first_displayed_entry && s->last_displayed_entry) {
3546 s->selected = MIN(s->selected,
3547 s->last_displayed_entry->idx -
3548 s->first_displayed_entry->idx);
3551 select_commit(s);
3553 if (s->thread_args.log_complete &&
3554 s->selected_entry->idx == s->commits->ncommits - 1)
3555 view->count = 0;
3557 return NULL;
3560 static void
3561 view_get_split(struct tog_view *view, int *y, int *x)
3563 *x = 0;
3564 *y = 0;
3566 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3567 if (view->child && view->child->resized_y)
3568 *y = view->child->resized_y;
3569 else if (view->resized_y)
3570 *y = view->resized_y;
3571 else
3572 *y = view_split_begin_y(view->lines);
3573 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3574 if (view->child && view->child->resized_x)
3575 *x = view->child->resized_x;
3576 else if (view->resized_x)
3577 *x = view->resized_x;
3578 else
3579 *x = view_split_begin_x(view->begin_x);
3583 /* Split view horizontally at y and offset view->state->selected line. */
3584 static const struct got_error *
3585 view_init_hsplit(struct tog_view *view, int y)
3587 const struct got_error *err = NULL;
3589 view->nlines = y;
3590 view->ncols = COLS;
3591 err = view_resize(view);
3592 if (err)
3593 return err;
3595 err = offset_selection_down(view);
3597 return err;
3600 static const struct got_error *
3601 log_goto_line(struct tog_view *view, int nlines)
3603 const struct got_error *err = NULL;
3604 struct tog_log_view_state *s = &view->state.log;
3605 int g, idx = s->selected_entry->idx;
3607 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3608 return NULL;
3610 g = view->gline;
3611 view->gline = 0;
3613 if (g >= s->first_displayed_entry->idx + 1 &&
3614 g <= s->last_displayed_entry->idx + 1 &&
3615 g - s->first_displayed_entry->idx - 1 < nlines) {
3616 s->selected = g - s->first_displayed_entry->idx - 1;
3617 select_commit(s);
3618 return NULL;
3621 if (idx + 1 < g) {
3622 err = log_move_cursor_down(view, g - idx - 1);
3623 if (!err && g > s->selected_entry->idx + 1)
3624 err = log_move_cursor_down(view,
3625 g - s->first_displayed_entry->idx - 1);
3626 if (err)
3627 return err;
3628 } else if (idx + 1 > g)
3629 log_move_cursor_up(view, idx - g + 1, 0);
3631 if (g < nlines && s->first_displayed_entry->idx == 0)
3632 s->selected = g - 1;
3634 select_commit(s);
3635 return NULL;
3639 static const struct got_error *
3640 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3642 const struct got_error *err = NULL;
3643 struct tog_log_view_state *s = &view->state.log;
3644 int eos, nscroll;
3646 if (s->thread_args.load_all) {
3647 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3648 s->thread_args.load_all = 0;
3649 else if (s->thread_args.log_complete) {
3650 err = log_move_cursor_down(view, s->commits->ncommits);
3651 s->thread_args.load_all = 0;
3653 if (err)
3654 return err;
3657 eos = nscroll = view->nlines - 1;
3658 if (view_is_hsplit_top(view))
3659 --eos; /* border */
3661 if (view->gline)
3662 return log_goto_line(view, eos);
3664 switch (ch) {
3665 case '&':
3666 err = limit_log_view(view);
3667 break;
3668 case 'q':
3669 s->quit = 1;
3670 break;
3671 case '0':
3672 view->x = 0;
3673 break;
3674 case '$':
3675 view->x = MAX(view->maxx - view->ncols / 2, 0);
3676 view->count = 0;
3677 break;
3678 case KEY_RIGHT:
3679 case 'l':
3680 if (view->x + view->ncols / 2 < view->maxx)
3681 view->x += 2; /* move two columns right */
3682 else
3683 view->count = 0;
3684 break;
3685 case KEY_LEFT:
3686 case 'h':
3687 view->x -= MIN(view->x, 2); /* move two columns back */
3688 if (view->x <= 0)
3689 view->count = 0;
3690 break;
3691 case 'k':
3692 case KEY_UP:
3693 case '<':
3694 case ',':
3695 case CTRL('p'):
3696 log_move_cursor_up(view, 0, 0);
3697 break;
3698 case 'g':
3699 case KEY_HOME:
3700 log_move_cursor_up(view, 0, 1);
3701 view->count = 0;
3702 break;
3703 case CTRL('u'):
3704 case 'u':
3705 nscroll /= 2;
3706 /* FALL THROUGH */
3707 case KEY_PPAGE:
3708 case CTRL('b'):
3709 case 'b':
3710 log_move_cursor_up(view, nscroll, 0);
3711 break;
3712 case 'j':
3713 case KEY_DOWN:
3714 case '>':
3715 case '.':
3716 case CTRL('n'):
3717 err = log_move_cursor_down(view, 0);
3718 break;
3719 case '@':
3720 s->use_committer = !s->use_committer;
3721 break;
3722 case 'G':
3723 case KEY_END: {
3724 /* We don't know yet how many commits, so we're forced to
3725 * traverse them all. */
3726 view->count = 0;
3727 s->thread_args.load_all = 1;
3728 if (!s->thread_args.log_complete)
3729 return trigger_log_thread(view, 0);
3730 err = log_move_cursor_down(view, s->commits->ncommits);
3731 s->thread_args.load_all = 0;
3732 break;
3734 case CTRL('d'):
3735 case 'd':
3736 nscroll /= 2;
3737 /* FALL THROUGH */
3738 case KEY_NPAGE:
3739 case CTRL('f'):
3740 case 'f':
3741 case ' ':
3742 err = log_move_cursor_down(view, nscroll);
3743 break;
3744 case KEY_RESIZE:
3745 if (s->selected > view->nlines - 2)
3746 s->selected = view->nlines - 2;
3747 if (s->selected > s->commits->ncommits - 1)
3748 s->selected = s->commits->ncommits - 1;
3749 select_commit(s);
3750 if (s->commits->ncommits < view->nlines - 1 &&
3751 !s->thread_args.log_complete) {
3752 s->thread_args.commits_needed += (view->nlines - 1) -
3753 s->commits->ncommits;
3754 err = trigger_log_thread(view, 1);
3756 break;
3757 case KEY_ENTER:
3758 case '\r':
3759 view->count = 0;
3760 if (s->selected_entry == NULL)
3761 break;
3762 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3763 break;
3764 case 'T':
3765 view->count = 0;
3766 if (s->selected_entry == NULL)
3767 break;
3768 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3769 break;
3770 case KEY_BACKSPACE:
3771 case CTRL('l'):
3772 case 'B':
3773 view->count = 0;
3774 if (ch == KEY_BACKSPACE &&
3775 got_path_is_root_dir(s->in_repo_path))
3776 break;
3777 err = stop_log_thread(s);
3778 if (err)
3779 return err;
3780 if (ch == KEY_BACKSPACE) {
3781 char *parent_path;
3782 err = got_path_dirname(&parent_path, s->in_repo_path);
3783 if (err)
3784 return err;
3785 free(s->in_repo_path);
3786 s->in_repo_path = parent_path;
3787 s->thread_args.in_repo_path = s->in_repo_path;
3788 } else if (ch == CTRL('l')) {
3789 struct got_object_id *start_id;
3790 err = got_repo_match_object_id(&start_id, NULL,
3791 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3792 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3793 if (err)
3794 return err;
3795 free(s->start_id);
3796 s->start_id = start_id;
3797 s->thread_args.start_id = s->start_id;
3798 } else /* 'B' */
3799 s->log_branches = !s->log_branches;
3801 if (s->thread_args.pack_fds == NULL) {
3802 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3803 if (err)
3804 return err;
3806 err = got_repo_open(&s->thread_args.repo,
3807 got_repo_get_path(s->repo), NULL,
3808 s->thread_args.pack_fds);
3809 if (err)
3810 return err;
3811 tog_free_refs();
3812 err = tog_load_refs(s->repo, 0);
3813 if (err)
3814 return err;
3815 err = got_commit_graph_open(&s->thread_args.graph,
3816 s->in_repo_path, !s->log_branches);
3817 if (err)
3818 return err;
3819 err = got_commit_graph_iter_start(s->thread_args.graph,
3820 s->start_id, s->repo, NULL, NULL);
3821 if (err)
3822 return err;
3823 free_commits(&s->real_commits);
3824 free_commits(&s->limit_commits);
3825 s->first_displayed_entry = NULL;
3826 s->last_displayed_entry = NULL;
3827 s->selected_entry = NULL;
3828 s->selected = 0;
3829 s->thread_args.log_complete = 0;
3830 s->quit = 0;
3831 s->thread_args.commits_needed = view->lines;
3832 s->matched_entry = NULL;
3833 s->search_entry = NULL;
3834 view->offset = 0;
3835 break;
3836 case 'R':
3837 view->count = 0;
3838 err = view_request_new(new_view, view, TOG_VIEW_REF);
3839 break;
3840 default:
3841 view->count = 0;
3842 break;
3845 return err;
3848 static const struct got_error *
3849 apply_unveil(const char *repo_path, const char *worktree_path)
3851 const struct got_error *error;
3853 #ifdef PROFILE
3854 if (unveil("gmon.out", "rwc") != 0)
3855 return got_error_from_errno2("unveil", "gmon.out");
3856 #endif
3857 if (repo_path && unveil(repo_path, "r") != 0)
3858 return got_error_from_errno2("unveil", repo_path);
3860 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3861 return got_error_from_errno2("unveil", worktree_path);
3863 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3864 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3866 error = got_privsep_unveil_exec_helpers();
3867 if (error != NULL)
3868 return error;
3870 if (unveil(NULL, NULL) != 0)
3871 return got_error_from_errno("unveil");
3873 return NULL;
3876 static void
3877 init_curses(void)
3880 * Override default signal handlers before starting ncurses.
3881 * This should prevent ncurses from installing its own
3882 * broken cleanup() signal handler.
3884 signal(SIGWINCH, tog_sigwinch);
3885 signal(SIGPIPE, tog_sigpipe);
3886 signal(SIGCONT, tog_sigcont);
3887 signal(SIGINT, tog_sigint);
3888 signal(SIGTERM, tog_sigterm);
3890 initscr();
3891 cbreak();
3892 halfdelay(1); /* Do fast refresh while initial view is loading. */
3893 noecho();
3894 nonl();
3895 intrflush(stdscr, FALSE);
3896 keypad(stdscr, TRUE);
3897 curs_set(0);
3898 if (getenv("TOG_COLORS") != NULL) {
3899 start_color();
3900 use_default_colors();
3904 static const struct got_error *
3905 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3906 struct got_repository *repo, struct got_worktree *worktree)
3908 const struct got_error *err = NULL;
3910 if (argc == 0) {
3911 *in_repo_path = strdup("/");
3912 if (*in_repo_path == NULL)
3913 return got_error_from_errno("strdup");
3914 return NULL;
3917 if (worktree) {
3918 const char *prefix = got_worktree_get_path_prefix(worktree);
3919 char *p;
3921 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3922 if (err)
3923 return err;
3924 if (asprintf(in_repo_path, "%s%s%s", prefix,
3925 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3926 p) == -1) {
3927 err = got_error_from_errno("asprintf");
3928 *in_repo_path = NULL;
3930 free(p);
3931 } else
3932 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3934 return err;
3937 static const struct got_error *
3938 cmd_log(int argc, char *argv[])
3940 const struct got_error *error;
3941 struct got_repository *repo = NULL;
3942 struct got_worktree *worktree = NULL;
3943 struct got_object_id *start_id = NULL;
3944 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3945 char *start_commit = NULL, *label = NULL;
3946 struct got_reference *ref = NULL;
3947 const char *head_ref_name = NULL;
3948 int ch, log_branches = 0;
3949 struct tog_view *view;
3950 int *pack_fds = NULL;
3952 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3953 switch (ch) {
3954 case 'b':
3955 log_branches = 1;
3956 break;
3957 case 'c':
3958 start_commit = optarg;
3959 break;
3960 case 'r':
3961 repo_path = realpath(optarg, NULL);
3962 if (repo_path == NULL)
3963 return got_error_from_errno2("realpath",
3964 optarg);
3965 break;
3966 default:
3967 usage_log();
3968 /* NOTREACHED */
3972 argc -= optind;
3973 argv += optind;
3975 if (argc > 1)
3976 usage_log();
3978 error = got_repo_pack_fds_open(&pack_fds);
3979 if (error != NULL)
3980 goto done;
3982 if (repo_path == NULL) {
3983 cwd = getcwd(NULL, 0);
3984 if (cwd == NULL)
3985 return got_error_from_errno("getcwd");
3986 error = got_worktree_open(&worktree, cwd);
3987 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3988 goto done;
3989 if (worktree)
3990 repo_path =
3991 strdup(got_worktree_get_repo_path(worktree));
3992 else
3993 repo_path = strdup(cwd);
3994 if (repo_path == NULL) {
3995 error = got_error_from_errno("strdup");
3996 goto done;
4000 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4001 if (error != NULL)
4002 goto done;
4004 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4005 repo, worktree);
4006 if (error)
4007 goto done;
4009 init_curses();
4011 error = apply_unveil(got_repo_get_path(repo),
4012 worktree ? got_worktree_get_root_path(worktree) : NULL);
4013 if (error)
4014 goto done;
4016 /* already loaded by tog_log_with_path()? */
4017 if (TAILQ_EMPTY(&tog_refs)) {
4018 error = tog_load_refs(repo, 0);
4019 if (error)
4020 goto done;
4023 if (start_commit == NULL) {
4024 error = got_repo_match_object_id(&start_id, &label,
4025 worktree ? got_worktree_get_head_ref_name(worktree) :
4026 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4027 if (error)
4028 goto done;
4029 head_ref_name = label;
4030 } else {
4031 error = got_ref_open(&ref, repo, start_commit, 0);
4032 if (error == NULL)
4033 head_ref_name = got_ref_get_name(ref);
4034 else if (error->code != GOT_ERR_NOT_REF)
4035 goto done;
4036 error = got_repo_match_object_id(&start_id, NULL,
4037 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4038 if (error)
4039 goto done;
4042 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4043 if (view == NULL) {
4044 error = got_error_from_errno("view_open");
4045 goto done;
4047 error = open_log_view(view, start_id, repo, head_ref_name,
4048 in_repo_path, log_branches);
4049 if (error)
4050 goto done;
4051 if (worktree) {
4052 /* Release work tree lock. */
4053 got_worktree_close(worktree);
4054 worktree = NULL;
4056 error = view_loop(view);
4057 done:
4058 free(in_repo_path);
4059 free(repo_path);
4060 free(cwd);
4061 free(start_id);
4062 free(label);
4063 if (ref)
4064 got_ref_close(ref);
4065 if (repo) {
4066 const struct got_error *close_err = got_repo_close(repo);
4067 if (error == NULL)
4068 error = close_err;
4070 if (worktree)
4071 got_worktree_close(worktree);
4072 if (pack_fds) {
4073 const struct got_error *pack_err =
4074 got_repo_pack_fds_close(pack_fds);
4075 if (error == NULL)
4076 error = pack_err;
4078 tog_free_refs();
4079 return error;
4082 __dead static void
4083 usage_diff(void)
4085 endwin();
4086 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4087 "object1 object2\n", getprogname());
4088 exit(1);
4091 static int
4092 match_line(const char *line, regex_t *regex, size_t nmatch,
4093 regmatch_t *regmatch)
4095 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4098 static struct tog_color *
4099 match_color(struct tog_colors *colors, const char *line)
4101 struct tog_color *tc = NULL;
4103 STAILQ_FOREACH(tc, colors, entry) {
4104 if (match_line(line, &tc->regex, 0, NULL))
4105 return tc;
4108 return NULL;
4111 static const struct got_error *
4112 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4113 WINDOW *window, int skipcol, regmatch_t *regmatch)
4115 const struct got_error *err = NULL;
4116 char *exstr = NULL;
4117 wchar_t *wline = NULL;
4118 int rme, rms, n, width, scrollx;
4119 int width0 = 0, width1 = 0, width2 = 0;
4120 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4122 *wtotal = 0;
4124 rms = regmatch->rm_so;
4125 rme = regmatch->rm_eo;
4127 err = expand_tab(&exstr, line);
4128 if (err)
4129 return err;
4131 /* Split the line into 3 segments, according to match offsets. */
4132 seg0 = strndup(exstr, rms);
4133 if (seg0 == NULL) {
4134 err = got_error_from_errno("strndup");
4135 goto done;
4137 seg1 = strndup(exstr + rms, rme - rms);
4138 if (seg1 == NULL) {
4139 err = got_error_from_errno("strndup");
4140 goto done;
4142 seg2 = strdup(exstr + rme);
4143 if (seg2 == NULL) {
4144 err = got_error_from_errno("strndup");
4145 goto done;
4148 /* draw up to matched token if we haven't scrolled past it */
4149 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4150 col_tab_align, 1);
4151 if (err)
4152 goto done;
4153 n = MAX(width0 - skipcol, 0);
4154 if (n) {
4155 free(wline);
4156 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4157 wlimit, col_tab_align, 1);
4158 if (err)
4159 goto done;
4160 waddwstr(window, &wline[scrollx]);
4161 wlimit -= width;
4162 *wtotal += width;
4165 if (wlimit > 0) {
4166 int i = 0, w = 0;
4167 size_t wlen;
4169 free(wline);
4170 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4171 col_tab_align, 1);
4172 if (err)
4173 goto done;
4174 wlen = wcslen(wline);
4175 while (i < wlen) {
4176 width = wcwidth(wline[i]);
4177 if (width == -1) {
4178 /* should not happen, tabs are expanded */
4179 err = got_error(GOT_ERR_RANGE);
4180 goto done;
4182 if (width0 + w + width > skipcol)
4183 break;
4184 w += width;
4185 i++;
4187 /* draw (visible part of) matched token (if scrolled into it) */
4188 if (width1 - w > 0) {
4189 wattron(window, A_STANDOUT);
4190 waddwstr(window, &wline[i]);
4191 wattroff(window, A_STANDOUT);
4192 wlimit -= (width1 - w);
4193 *wtotal += (width1 - w);
4197 if (wlimit > 0) { /* draw rest of line */
4198 free(wline);
4199 if (skipcol > width0 + width1) {
4200 err = format_line(&wline, &width2, &scrollx, seg2,
4201 skipcol - (width0 + width1), wlimit,
4202 col_tab_align, 1);
4203 if (err)
4204 goto done;
4205 waddwstr(window, &wline[scrollx]);
4206 } else {
4207 err = format_line(&wline, &width2, NULL, seg2, 0,
4208 wlimit, col_tab_align, 1);
4209 if (err)
4210 goto done;
4211 waddwstr(window, wline);
4213 *wtotal += width2;
4215 done:
4216 free(wline);
4217 free(exstr);
4218 free(seg0);
4219 free(seg1);
4220 free(seg2);
4221 return err;
4224 static int
4225 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4227 FILE *f = NULL;
4228 int *eof, *first, *selected;
4230 if (view->type == TOG_VIEW_DIFF) {
4231 struct tog_diff_view_state *s = &view->state.diff;
4233 first = &s->first_displayed_line;
4234 selected = first;
4235 eof = &s->eof;
4236 f = s->f;
4237 } else if (view->type == TOG_VIEW_HELP) {
4238 struct tog_help_view_state *s = &view->state.help;
4240 first = &s->first_displayed_line;
4241 selected = first;
4242 eof = &s->eof;
4243 f = s->f;
4244 } else if (view->type == TOG_VIEW_BLAME) {
4245 struct tog_blame_view_state *s = &view->state.blame;
4247 first = &s->first_displayed_line;
4248 selected = &s->selected_line;
4249 eof = &s->eof;
4250 f = s->blame.f;
4251 } else
4252 return 0;
4254 /* Center gline in the middle of the page like vi(1). */
4255 if (*lineno < view->gline - (view->nlines - 3) / 2)
4256 return 0;
4257 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4258 rewind(f);
4259 *eof = 0;
4260 *first = 1;
4261 *lineno = 0;
4262 *nprinted = 0;
4263 return 0;
4266 *selected = view->gline <= (view->nlines - 3) / 2 ?
4267 view->gline : (view->nlines - 3) / 2 + 1;
4268 view->gline = 0;
4270 return 1;
4273 static const struct got_error *
4274 draw_file(struct tog_view *view, const char *header)
4276 struct tog_diff_view_state *s = &view->state.diff;
4277 regmatch_t *regmatch = &view->regmatch;
4278 const struct got_error *err;
4279 int nprinted = 0;
4280 char *line;
4281 size_t linesize = 0;
4282 ssize_t linelen;
4283 wchar_t *wline;
4284 int width;
4285 int max_lines = view->nlines;
4286 int nlines = s->nlines;
4287 off_t line_offset;
4289 s->lineno = s->first_displayed_line - 1;
4290 line_offset = s->lines[s->first_displayed_line - 1].offset;
4291 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4292 return got_error_from_errno("fseek");
4294 werase(view->window);
4296 if (view->gline > s->nlines - 1)
4297 view->gline = s->nlines - 1;
4299 if (header) {
4300 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4301 1 : view->gline - (view->nlines - 3) / 2 :
4302 s->lineno + s->selected_line;
4304 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4305 return got_error_from_errno("asprintf");
4306 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4307 0, 0);
4308 free(line);
4309 if (err)
4310 return err;
4312 if (view_needs_focus_indication(view))
4313 wstandout(view->window);
4314 waddwstr(view->window, wline);
4315 free(wline);
4316 wline = NULL;
4317 while (width++ < view->ncols)
4318 waddch(view->window, ' ');
4319 if (view_needs_focus_indication(view))
4320 wstandend(view->window);
4322 if (max_lines <= 1)
4323 return NULL;
4324 max_lines--;
4327 s->eof = 0;
4328 view->maxx = 0;
4329 line = NULL;
4330 while (max_lines > 0 && nprinted < max_lines) {
4331 enum got_diff_line_type linetype;
4332 attr_t attr = 0;
4334 linelen = getline(&line, &linesize, s->f);
4335 if (linelen == -1) {
4336 if (feof(s->f)) {
4337 s->eof = 1;
4338 break;
4340 free(line);
4341 return got_ferror(s->f, GOT_ERR_IO);
4344 if (++s->lineno < s->first_displayed_line)
4345 continue;
4346 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4347 continue;
4348 if (s->lineno == view->hiline)
4349 attr = A_STANDOUT;
4351 /* Set view->maxx based on full line length. */
4352 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4353 view->x ? 1 : 0);
4354 if (err) {
4355 free(line);
4356 return err;
4358 view->maxx = MAX(view->maxx, width);
4359 free(wline);
4360 wline = NULL;
4362 linetype = s->lines[s->lineno].type;
4363 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4364 linetype < GOT_DIFF_LINE_CONTEXT)
4365 attr |= COLOR_PAIR(linetype);
4366 if (attr)
4367 wattron(view->window, attr);
4368 if (s->first_displayed_line + nprinted == s->matched_line &&
4369 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4370 err = add_matched_line(&width, line, view->ncols, 0,
4371 view->window, view->x, regmatch);
4372 if (err) {
4373 free(line);
4374 return err;
4376 } else {
4377 int skip;
4378 err = format_line(&wline, &width, &skip, line,
4379 view->x, view->ncols, 0, view->x ? 1 : 0);
4380 if (err) {
4381 free(line);
4382 return err;
4384 waddwstr(view->window, &wline[skip]);
4385 free(wline);
4386 wline = NULL;
4388 if (s->lineno == view->hiline) {
4389 /* highlight full gline length */
4390 while (width++ < view->ncols)
4391 waddch(view->window, ' ');
4392 } else {
4393 if (width <= view->ncols - 1)
4394 waddch(view->window, '\n');
4396 if (attr)
4397 wattroff(view->window, attr);
4398 if (++nprinted == 1)
4399 s->first_displayed_line = s->lineno;
4401 free(line);
4402 if (nprinted >= 1)
4403 s->last_displayed_line = s->first_displayed_line +
4404 (nprinted - 1);
4405 else
4406 s->last_displayed_line = s->first_displayed_line;
4408 view_border(view);
4410 if (s->eof) {
4411 while (nprinted < view->nlines) {
4412 waddch(view->window, '\n');
4413 nprinted++;
4416 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4417 view->ncols, 0, 0);
4418 if (err) {
4419 return err;
4422 wstandout(view->window);
4423 waddwstr(view->window, wline);
4424 free(wline);
4425 wline = NULL;
4426 wstandend(view->window);
4429 return NULL;
4432 static char *
4433 get_datestr(time_t *time, char *datebuf)
4435 struct tm mytm, *tm;
4436 char *p, *s;
4438 tm = gmtime_r(time, &mytm);
4439 if (tm == NULL)
4440 return NULL;
4441 s = asctime_r(tm, datebuf);
4442 if (s == NULL)
4443 return NULL;
4444 p = strchr(s, '\n');
4445 if (p)
4446 *p = '\0';
4447 return s;
4450 static const struct got_error *
4451 get_changed_paths(struct got_pathlist_head *paths,
4452 struct got_commit_object *commit, struct got_repository *repo)
4454 const struct got_error *err = NULL;
4455 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4456 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4457 struct got_object_qid *qid;
4459 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4460 if (qid != NULL) {
4461 struct got_commit_object *pcommit;
4462 err = got_object_open_as_commit(&pcommit, repo,
4463 &qid->id);
4464 if (err)
4465 return err;
4467 tree_id1 = got_object_id_dup(
4468 got_object_commit_get_tree_id(pcommit));
4469 if (tree_id1 == NULL) {
4470 got_object_commit_close(pcommit);
4471 return got_error_from_errno("got_object_id_dup");
4473 got_object_commit_close(pcommit);
4477 if (tree_id1) {
4478 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4479 if (err)
4480 goto done;
4483 tree_id2 = got_object_commit_get_tree_id(commit);
4484 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4485 if (err)
4486 goto done;
4488 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4489 got_diff_tree_collect_changed_paths, paths, 0);
4490 done:
4491 if (tree1)
4492 got_object_tree_close(tree1);
4493 if (tree2)
4494 got_object_tree_close(tree2);
4495 free(tree_id1);
4496 return err;
4499 static const struct got_error *
4500 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4501 off_t off, uint8_t type)
4503 struct got_diff_line *p;
4505 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4506 if (p == NULL)
4507 return got_error_from_errno("reallocarray");
4508 *lines = p;
4509 (*lines)[*nlines].offset = off;
4510 (*lines)[*nlines].type = type;
4511 (*nlines)++;
4513 return NULL;
4516 static const struct got_error *
4517 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4518 struct got_object_id *commit_id, struct got_reflist_head *refs,
4519 struct got_repository *repo, FILE *outfile)
4521 const struct got_error *err = NULL;
4522 char datebuf[26], *datestr;
4523 struct got_commit_object *commit;
4524 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4525 time_t committer_time;
4526 const char *author, *committer;
4527 char *refs_str = NULL;
4528 struct got_pathlist_head changed_paths;
4529 struct got_pathlist_entry *pe;
4530 off_t outoff = 0;
4531 int n;
4533 TAILQ_INIT(&changed_paths);
4535 if (refs) {
4536 err = build_refs_str(&refs_str, refs, commit_id, repo);
4537 if (err)
4538 return err;
4541 err = got_object_open_as_commit(&commit, repo, commit_id);
4542 if (err)
4543 return err;
4545 err = got_object_id_str(&id_str, commit_id);
4546 if (err) {
4547 err = got_error_from_errno("got_object_id_str");
4548 goto done;
4551 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4552 if (err)
4553 goto done;
4555 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4556 refs_str ? refs_str : "", refs_str ? ")" : "");
4557 if (n < 0) {
4558 err = got_error_from_errno("fprintf");
4559 goto done;
4561 outoff += n;
4562 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4563 if (err)
4564 goto done;
4566 n = fprintf(outfile, "from: %s\n",
4567 got_object_commit_get_author(commit));
4568 if (n < 0) {
4569 err = got_error_from_errno("fprintf");
4570 goto done;
4572 outoff += n;
4573 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4574 if (err)
4575 goto done;
4577 committer_time = got_object_commit_get_committer_time(commit);
4578 datestr = get_datestr(&committer_time, datebuf);
4579 if (datestr) {
4580 n = fprintf(outfile, "date: %s UTC\n", datestr);
4581 if (n < 0) {
4582 err = got_error_from_errno("fprintf");
4583 goto done;
4585 outoff += n;
4586 err = add_line_metadata(lines, nlines, outoff,
4587 GOT_DIFF_LINE_DATE);
4588 if (err)
4589 goto done;
4591 author = got_object_commit_get_author(commit);
4592 committer = got_object_commit_get_committer(commit);
4593 if (strcmp(author, committer) != 0) {
4594 n = fprintf(outfile, "via: %s\n", committer);
4595 if (n < 0) {
4596 err = got_error_from_errno("fprintf");
4597 goto done;
4599 outoff += n;
4600 err = add_line_metadata(lines, nlines, outoff,
4601 GOT_DIFF_LINE_AUTHOR);
4602 if (err)
4603 goto done;
4605 if (got_object_commit_get_nparents(commit) > 1) {
4606 const struct got_object_id_queue *parent_ids;
4607 struct got_object_qid *qid;
4608 int pn = 1;
4609 parent_ids = got_object_commit_get_parent_ids(commit);
4610 STAILQ_FOREACH(qid, parent_ids, entry) {
4611 err = got_object_id_str(&id_str, &qid->id);
4612 if (err)
4613 goto done;
4614 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4615 if (n < 0) {
4616 err = got_error_from_errno("fprintf");
4617 goto done;
4619 outoff += n;
4620 err = add_line_metadata(lines, nlines, outoff,
4621 GOT_DIFF_LINE_META);
4622 if (err)
4623 goto done;
4624 free(id_str);
4625 id_str = NULL;
4629 err = got_object_commit_get_logmsg(&logmsg, commit);
4630 if (err)
4631 goto done;
4632 s = logmsg;
4633 while ((line = strsep(&s, "\n")) != NULL) {
4634 n = fprintf(outfile, "%s\n", line);
4635 if (n < 0) {
4636 err = got_error_from_errno("fprintf");
4637 goto done;
4639 outoff += n;
4640 err = add_line_metadata(lines, nlines, outoff,
4641 GOT_DIFF_LINE_LOGMSG);
4642 if (err)
4643 goto done;
4646 err = get_changed_paths(&changed_paths, commit, repo);
4647 if (err)
4648 goto done;
4649 TAILQ_FOREACH(pe, &changed_paths, entry) {
4650 struct got_diff_changed_path *cp = pe->data;
4651 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4652 if (n < 0) {
4653 err = got_error_from_errno("fprintf");
4654 goto done;
4656 outoff += n;
4657 err = add_line_metadata(lines, nlines, outoff,
4658 GOT_DIFF_LINE_CHANGES);
4659 if (err)
4660 goto done;
4661 free((char *)pe->path);
4662 free(pe->data);
4665 fputc('\n', outfile);
4666 outoff++;
4667 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4668 done:
4669 got_pathlist_free(&changed_paths);
4670 free(id_str);
4671 free(logmsg);
4672 free(refs_str);
4673 got_object_commit_close(commit);
4674 if (err) {
4675 free(*lines);
4676 *lines = NULL;
4677 *nlines = 0;
4679 return err;
4682 static const struct got_error *
4683 create_diff(struct tog_diff_view_state *s)
4685 const struct got_error *err = NULL;
4686 FILE *f = NULL;
4687 int obj_type;
4689 free(s->lines);
4690 s->lines = malloc(sizeof(*s->lines));
4691 if (s->lines == NULL)
4692 return got_error_from_errno("malloc");
4693 s->nlines = 0;
4695 f = got_opentemp();
4696 if (f == NULL) {
4697 err = got_error_from_errno("got_opentemp");
4698 goto done;
4700 if (s->f && fclose(s->f) == EOF) {
4701 err = got_error_from_errno("fclose");
4702 goto done;
4704 s->f = f;
4706 if (s->id1)
4707 err = got_object_get_type(&obj_type, s->repo, s->id1);
4708 else
4709 err = got_object_get_type(&obj_type, s->repo, s->id2);
4710 if (err)
4711 goto done;
4713 switch (obj_type) {
4714 case GOT_OBJ_TYPE_BLOB:
4715 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4716 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4717 s->label1, s->label2, tog_diff_algo, s->diff_context,
4718 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4719 break;
4720 case GOT_OBJ_TYPE_TREE:
4721 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4722 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4723 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4724 s->force_text_diff, s->repo, s->f);
4725 break;
4726 case GOT_OBJ_TYPE_COMMIT: {
4727 const struct got_object_id_queue *parent_ids;
4728 struct got_object_qid *pid;
4729 struct got_commit_object *commit2;
4730 struct got_reflist_head *refs;
4732 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4733 if (err)
4734 goto done;
4735 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4736 /* Show commit info if we're diffing to a parent/root commit. */
4737 if (s->id1 == NULL) {
4738 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4739 refs, s->repo, s->f);
4740 if (err)
4741 goto done;
4742 } else {
4743 parent_ids = got_object_commit_get_parent_ids(commit2);
4744 STAILQ_FOREACH(pid, parent_ids, entry) {
4745 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4746 err = write_commit_info(&s->lines,
4747 &s->nlines, s->id2, refs, s->repo,
4748 s->f);
4749 if (err)
4750 goto done;
4751 break;
4755 got_object_commit_close(commit2);
4757 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4758 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4759 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4760 s->force_text_diff, s->repo, s->f);
4761 break;
4763 default:
4764 err = got_error(GOT_ERR_OBJ_TYPE);
4765 break;
4767 done:
4768 if (s->f && fflush(s->f) != 0 && err == NULL)
4769 err = got_error_from_errno("fflush");
4770 return err;
4773 static void
4774 diff_view_indicate_progress(struct tog_view *view)
4776 mvwaddstr(view->window, 0, 0, "diffing...");
4777 update_panels();
4778 doupdate();
4781 static const struct got_error *
4782 search_start_diff_view(struct tog_view *view)
4784 struct tog_diff_view_state *s = &view->state.diff;
4786 s->matched_line = 0;
4787 return NULL;
4790 static void
4791 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4792 size_t *nlines, int **first, int **last, int **match, int **selected)
4794 struct tog_diff_view_state *s = &view->state.diff;
4796 *f = s->f;
4797 *nlines = s->nlines;
4798 *line_offsets = NULL;
4799 *match = &s->matched_line;
4800 *first = &s->first_displayed_line;
4801 *last = &s->last_displayed_line;
4802 *selected = &s->selected_line;
4805 static const struct got_error *
4806 search_next_view_match(struct tog_view *view)
4808 const struct got_error *err = NULL;
4809 FILE *f;
4810 int lineno;
4811 char *line = NULL;
4812 size_t linesize = 0;
4813 ssize_t linelen;
4814 off_t *line_offsets;
4815 size_t nlines = 0;
4816 int *first, *last, *match, *selected;
4818 if (!view->search_setup)
4819 return got_error_msg(GOT_ERR_NOT_IMPL,
4820 "view search not supported");
4821 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4822 &match, &selected);
4824 if (!view->searching) {
4825 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4826 return NULL;
4829 if (*match) {
4830 if (view->searching == TOG_SEARCH_FORWARD)
4831 lineno = *match + 1;
4832 else
4833 lineno = *match - 1;
4834 } else
4835 lineno = *first - 1 + *selected;
4837 while (1) {
4838 off_t offset;
4840 if (lineno <= 0 || lineno > nlines) {
4841 if (*match == 0) {
4842 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4843 break;
4846 if (view->searching == TOG_SEARCH_FORWARD)
4847 lineno = 1;
4848 else
4849 lineno = nlines;
4852 offset = view->type == TOG_VIEW_DIFF ?
4853 view->state.diff.lines[lineno - 1].offset :
4854 line_offsets[lineno - 1];
4855 if (fseeko(f, offset, SEEK_SET) != 0) {
4856 free(line);
4857 return got_error_from_errno("fseeko");
4859 linelen = getline(&line, &linesize, f);
4860 if (linelen != -1) {
4861 char *exstr;
4862 err = expand_tab(&exstr, line);
4863 if (err)
4864 break;
4865 if (match_line(exstr, &view->regex, 1,
4866 &view->regmatch)) {
4867 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4868 *match = lineno;
4869 free(exstr);
4870 break;
4872 free(exstr);
4874 if (view->searching == TOG_SEARCH_FORWARD)
4875 lineno++;
4876 else
4877 lineno--;
4879 free(line);
4881 if (*match) {
4882 *first = *match;
4883 *selected = 1;
4886 return err;
4889 static const struct got_error *
4890 close_diff_view(struct tog_view *view)
4892 const struct got_error *err = NULL;
4893 struct tog_diff_view_state *s = &view->state.diff;
4895 free(s->id1);
4896 s->id1 = NULL;
4897 free(s->id2);
4898 s->id2 = NULL;
4899 if (s->f && fclose(s->f) == EOF)
4900 err = got_error_from_errno("fclose");
4901 s->f = NULL;
4902 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4903 err = got_error_from_errno("fclose");
4904 s->f1 = NULL;
4905 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4906 err = got_error_from_errno("fclose");
4907 s->f2 = NULL;
4908 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4909 err = got_error_from_errno("close");
4910 s->fd1 = -1;
4911 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4912 err = got_error_from_errno("close");
4913 s->fd2 = -1;
4914 free(s->lines);
4915 s->lines = NULL;
4916 s->nlines = 0;
4917 return err;
4920 static const struct got_error *
4921 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4922 struct got_object_id *id2, const char *label1, const char *label2,
4923 int diff_context, int ignore_whitespace, int force_text_diff,
4924 struct tog_view *parent_view, struct got_repository *repo)
4926 const struct got_error *err;
4927 struct tog_diff_view_state *s = &view->state.diff;
4929 memset(s, 0, sizeof(*s));
4930 s->fd1 = -1;
4931 s->fd2 = -1;
4933 if (id1 != NULL && id2 != NULL) {
4934 int type1, type2;
4935 err = got_object_get_type(&type1, repo, id1);
4936 if (err)
4937 return err;
4938 err = got_object_get_type(&type2, repo, id2);
4939 if (err)
4940 return err;
4942 if (type1 != type2)
4943 return got_error(GOT_ERR_OBJ_TYPE);
4945 s->first_displayed_line = 1;
4946 s->last_displayed_line = view->nlines;
4947 s->selected_line = 1;
4948 s->repo = repo;
4949 s->id1 = id1;
4950 s->id2 = id2;
4951 s->label1 = label1;
4952 s->label2 = label2;
4954 if (id1) {
4955 s->id1 = got_object_id_dup(id1);
4956 if (s->id1 == NULL)
4957 return got_error_from_errno("got_object_id_dup");
4958 } else
4959 s->id1 = NULL;
4961 s->id2 = got_object_id_dup(id2);
4962 if (s->id2 == NULL) {
4963 err = got_error_from_errno("got_object_id_dup");
4964 goto done;
4967 s->f1 = got_opentemp();
4968 if (s->f1 == NULL) {
4969 err = got_error_from_errno("got_opentemp");
4970 goto done;
4973 s->f2 = got_opentemp();
4974 if (s->f2 == NULL) {
4975 err = got_error_from_errno("got_opentemp");
4976 goto done;
4979 s->fd1 = got_opentempfd();
4980 if (s->fd1 == -1) {
4981 err = got_error_from_errno("got_opentempfd");
4982 goto done;
4985 s->fd2 = got_opentempfd();
4986 if (s->fd2 == -1) {
4987 err = got_error_from_errno("got_opentempfd");
4988 goto done;
4991 s->first_displayed_line = 1;
4992 s->last_displayed_line = view->nlines;
4993 s->diff_context = diff_context;
4994 s->ignore_whitespace = ignore_whitespace;
4995 s->force_text_diff = force_text_diff;
4996 s->parent_view = parent_view;
4997 s->repo = repo;
4999 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5000 int rc;
5002 rc = init_pair(GOT_DIFF_LINE_MINUS,
5003 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5004 if (rc != ERR)
5005 rc = init_pair(GOT_DIFF_LINE_PLUS,
5006 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5007 if (rc != ERR)
5008 rc = init_pair(GOT_DIFF_LINE_HUNK,
5009 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5010 if (rc != ERR)
5011 rc = init_pair(GOT_DIFF_LINE_META,
5012 get_color_value("TOG_COLOR_DIFF_META"), -1);
5013 if (rc != ERR)
5014 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5015 get_color_value("TOG_COLOR_DIFF_META"), -1);
5016 if (rc != ERR)
5017 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5018 get_color_value("TOG_COLOR_DIFF_META"), -1);
5019 if (rc != ERR)
5020 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5021 get_color_value("TOG_COLOR_DIFF_META"), -1);
5022 if (rc != ERR)
5023 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5024 get_color_value("TOG_COLOR_AUTHOR"), -1);
5025 if (rc != ERR)
5026 rc = init_pair(GOT_DIFF_LINE_DATE,
5027 get_color_value("TOG_COLOR_DATE"), -1);
5028 if (rc == ERR) {
5029 err = got_error(GOT_ERR_RANGE);
5030 goto done;
5034 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5035 view_is_splitscreen(view))
5036 show_log_view(parent_view); /* draw border */
5037 diff_view_indicate_progress(view);
5039 err = create_diff(s);
5041 view->show = show_diff_view;
5042 view->input = input_diff_view;
5043 view->reset = reset_diff_view;
5044 view->close = close_diff_view;
5045 view->search_start = search_start_diff_view;
5046 view->search_setup = search_setup_diff_view;
5047 view->search_next = search_next_view_match;
5048 done:
5049 if (err)
5050 close_diff_view(view);
5051 return err;
5054 static const struct got_error *
5055 show_diff_view(struct tog_view *view)
5057 const struct got_error *err;
5058 struct tog_diff_view_state *s = &view->state.diff;
5059 char *id_str1 = NULL, *id_str2, *header;
5060 const char *label1, *label2;
5062 if (s->id1) {
5063 err = got_object_id_str(&id_str1, s->id1);
5064 if (err)
5065 return err;
5066 label1 = s->label1 ? s->label1 : id_str1;
5067 } else
5068 label1 = "/dev/null";
5070 err = got_object_id_str(&id_str2, s->id2);
5071 if (err)
5072 return err;
5073 label2 = s->label2 ? s->label2 : id_str2;
5075 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5076 err = got_error_from_errno("asprintf");
5077 free(id_str1);
5078 free(id_str2);
5079 return err;
5081 free(id_str1);
5082 free(id_str2);
5084 err = draw_file(view, header);
5085 free(header);
5086 return err;
5089 static const struct got_error *
5090 set_selected_commit(struct tog_diff_view_state *s,
5091 struct commit_queue_entry *entry)
5093 const struct got_error *err;
5094 const struct got_object_id_queue *parent_ids;
5095 struct got_commit_object *selected_commit;
5096 struct got_object_qid *pid;
5098 free(s->id2);
5099 s->id2 = got_object_id_dup(entry->id);
5100 if (s->id2 == NULL)
5101 return got_error_from_errno("got_object_id_dup");
5103 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5104 if (err)
5105 return err;
5106 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5107 free(s->id1);
5108 pid = STAILQ_FIRST(parent_ids);
5109 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5110 got_object_commit_close(selected_commit);
5111 return NULL;
5114 static const struct got_error *
5115 reset_diff_view(struct tog_view *view)
5117 struct tog_diff_view_state *s = &view->state.diff;
5119 view->count = 0;
5120 wclear(view->window);
5121 s->first_displayed_line = 1;
5122 s->last_displayed_line = view->nlines;
5123 s->matched_line = 0;
5124 diff_view_indicate_progress(view);
5125 return create_diff(s);
5128 static void
5129 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5131 int start, i;
5133 i = start = s->first_displayed_line - 1;
5135 while (s->lines[i].type != type) {
5136 if (i == 0)
5137 i = s->nlines - 1;
5138 if (--i == start)
5139 return; /* do nothing, requested type not in file */
5142 s->selected_line = 1;
5143 s->first_displayed_line = i;
5146 static void
5147 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5149 int start, i;
5151 i = start = s->first_displayed_line + 1;
5153 while (s->lines[i].type != type) {
5154 if (i == s->nlines - 1)
5155 i = 0;
5156 if (++i == start)
5157 return; /* do nothing, requested type not in file */
5160 s->selected_line = 1;
5161 s->first_displayed_line = i;
5164 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5165 int, int, int);
5166 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5167 int, int);
5169 static const struct got_error *
5170 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5172 const struct got_error *err = NULL;
5173 struct tog_diff_view_state *s = &view->state.diff;
5174 struct tog_log_view_state *ls;
5175 struct commit_queue_entry *old_selected_entry;
5176 char *line = NULL;
5177 size_t linesize = 0;
5178 ssize_t linelen;
5179 int i, nscroll = view->nlines - 1, up = 0;
5181 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5183 switch (ch) {
5184 case '0':
5185 view->x = 0;
5186 break;
5187 case '$':
5188 view->x = MAX(view->maxx - view->ncols / 3, 0);
5189 view->count = 0;
5190 break;
5191 case KEY_RIGHT:
5192 case 'l':
5193 if (view->x + view->ncols / 3 < view->maxx)
5194 view->x += 2; /* move two columns right */
5195 else
5196 view->count = 0;
5197 break;
5198 case KEY_LEFT:
5199 case 'h':
5200 view->x -= MIN(view->x, 2); /* move two columns back */
5201 if (view->x <= 0)
5202 view->count = 0;
5203 break;
5204 case 'a':
5205 case 'w':
5206 if (ch == 'a')
5207 s->force_text_diff = !s->force_text_diff;
5208 if (ch == 'w')
5209 s->ignore_whitespace = !s->ignore_whitespace;
5210 err = reset_diff_view(view);
5211 break;
5212 case 'g':
5213 case KEY_HOME:
5214 s->first_displayed_line = 1;
5215 view->count = 0;
5216 break;
5217 case 'G':
5218 case KEY_END:
5219 view->count = 0;
5220 if (s->eof)
5221 break;
5223 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5224 s->eof = 1;
5225 break;
5226 case 'k':
5227 case KEY_UP:
5228 case CTRL('p'):
5229 if (s->first_displayed_line > 1)
5230 s->first_displayed_line--;
5231 else
5232 view->count = 0;
5233 break;
5234 case CTRL('u'):
5235 case 'u':
5236 nscroll /= 2;
5237 /* FALL THROUGH */
5238 case KEY_PPAGE:
5239 case CTRL('b'):
5240 case 'b':
5241 if (s->first_displayed_line == 1) {
5242 view->count = 0;
5243 break;
5245 i = 0;
5246 while (i++ < nscroll && s->first_displayed_line > 1)
5247 s->first_displayed_line--;
5248 break;
5249 case 'j':
5250 case KEY_DOWN:
5251 case CTRL('n'):
5252 if (!s->eof)
5253 s->first_displayed_line++;
5254 else
5255 view->count = 0;
5256 break;
5257 case CTRL('d'):
5258 case 'd':
5259 nscroll /= 2;
5260 /* FALL THROUGH */
5261 case KEY_NPAGE:
5262 case CTRL('f'):
5263 case 'f':
5264 case ' ':
5265 if (s->eof) {
5266 view->count = 0;
5267 break;
5269 i = 0;
5270 while (!s->eof && i++ < nscroll) {
5271 linelen = getline(&line, &linesize, s->f);
5272 s->first_displayed_line++;
5273 if (linelen == -1) {
5274 if (feof(s->f)) {
5275 s->eof = 1;
5276 } else
5277 err = got_ferror(s->f, GOT_ERR_IO);
5278 break;
5281 free(line);
5282 break;
5283 case '(':
5284 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5285 break;
5286 case ')':
5287 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5288 break;
5289 case '{':
5290 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5291 break;
5292 case '}':
5293 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5294 break;
5295 case '[':
5296 if (s->diff_context > 0) {
5297 s->diff_context--;
5298 s->matched_line = 0;
5299 diff_view_indicate_progress(view);
5300 err = create_diff(s);
5301 if (s->first_displayed_line + view->nlines - 1 >
5302 s->nlines) {
5303 s->first_displayed_line = 1;
5304 s->last_displayed_line = view->nlines;
5306 } else
5307 view->count = 0;
5308 break;
5309 case ']':
5310 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5311 s->diff_context++;
5312 s->matched_line = 0;
5313 diff_view_indicate_progress(view);
5314 err = create_diff(s);
5315 } else
5316 view->count = 0;
5317 break;
5318 case '<':
5319 case ',':
5320 case 'K':
5321 up = 1;
5322 /* FALL THROUGH */
5323 case '>':
5324 case '.':
5325 case 'J':
5326 if (s->parent_view == NULL) {
5327 view->count = 0;
5328 break;
5330 s->parent_view->count = view->count;
5332 if (s->parent_view->type == TOG_VIEW_LOG) {
5333 ls = &s->parent_view->state.log;
5334 old_selected_entry = ls->selected_entry;
5336 err = input_log_view(NULL, s->parent_view,
5337 up ? KEY_UP : KEY_DOWN);
5338 if (err)
5339 break;
5340 view->count = s->parent_view->count;
5342 if (old_selected_entry == ls->selected_entry)
5343 break;
5345 err = set_selected_commit(s, ls->selected_entry);
5346 if (err)
5347 break;
5348 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5349 struct tog_blame_view_state *bs;
5350 struct got_object_id *id, *prev_id;
5352 bs = &s->parent_view->state.blame;
5353 prev_id = get_annotation_for_line(bs->blame.lines,
5354 bs->blame.nlines, bs->last_diffed_line);
5356 err = input_blame_view(&view, s->parent_view,
5357 up ? KEY_UP : KEY_DOWN);
5358 if (err)
5359 break;
5360 view->count = s->parent_view->count;
5362 if (prev_id == NULL)
5363 break;
5364 id = get_selected_commit_id(bs->blame.lines,
5365 bs->blame.nlines, bs->first_displayed_line,
5366 bs->selected_line);
5367 if (id == NULL)
5368 break;
5370 if (!got_object_id_cmp(prev_id, id))
5371 break;
5373 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5374 if (err)
5375 break;
5377 s->first_displayed_line = 1;
5378 s->last_displayed_line = view->nlines;
5379 s->matched_line = 0;
5380 view->x = 0;
5382 diff_view_indicate_progress(view);
5383 err = create_diff(s);
5384 break;
5385 default:
5386 view->count = 0;
5387 break;
5390 return err;
5393 static const struct got_error *
5394 cmd_diff(int argc, char *argv[])
5396 const struct got_error *error = NULL;
5397 struct got_repository *repo = NULL;
5398 struct got_worktree *worktree = NULL;
5399 struct got_object_id *id1 = NULL, *id2 = NULL;
5400 char *repo_path = NULL, *cwd = NULL;
5401 char *id_str1 = NULL, *id_str2 = NULL;
5402 char *label1 = NULL, *label2 = NULL;
5403 int diff_context = 3, ignore_whitespace = 0;
5404 int ch, force_text_diff = 0;
5405 const char *errstr;
5406 struct tog_view *view;
5407 int *pack_fds = NULL;
5409 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5410 switch (ch) {
5411 case 'a':
5412 force_text_diff = 1;
5413 break;
5414 case 'C':
5415 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5416 &errstr);
5417 if (errstr != NULL)
5418 errx(1, "number of context lines is %s: %s",
5419 errstr, errstr);
5420 break;
5421 case 'r':
5422 repo_path = realpath(optarg, NULL);
5423 if (repo_path == NULL)
5424 return got_error_from_errno2("realpath",
5425 optarg);
5426 got_path_strip_trailing_slashes(repo_path);
5427 break;
5428 case 'w':
5429 ignore_whitespace = 1;
5430 break;
5431 default:
5432 usage_diff();
5433 /* NOTREACHED */
5437 argc -= optind;
5438 argv += optind;
5440 if (argc == 0) {
5441 usage_diff(); /* TODO show local worktree changes */
5442 } else if (argc == 2) {
5443 id_str1 = argv[0];
5444 id_str2 = argv[1];
5445 } else
5446 usage_diff();
5448 error = got_repo_pack_fds_open(&pack_fds);
5449 if (error)
5450 goto done;
5452 if (repo_path == NULL) {
5453 cwd = getcwd(NULL, 0);
5454 if (cwd == NULL)
5455 return got_error_from_errno("getcwd");
5456 error = got_worktree_open(&worktree, cwd);
5457 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5458 goto done;
5459 if (worktree)
5460 repo_path =
5461 strdup(got_worktree_get_repo_path(worktree));
5462 else
5463 repo_path = strdup(cwd);
5464 if (repo_path == NULL) {
5465 error = got_error_from_errno("strdup");
5466 goto done;
5470 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5471 if (error)
5472 goto done;
5474 init_curses();
5476 error = apply_unveil(got_repo_get_path(repo), NULL);
5477 if (error)
5478 goto done;
5480 error = tog_load_refs(repo, 0);
5481 if (error)
5482 goto done;
5484 error = got_repo_match_object_id(&id1, &label1, id_str1,
5485 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5486 if (error)
5487 goto done;
5489 error = got_repo_match_object_id(&id2, &label2, id_str2,
5490 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5491 if (error)
5492 goto done;
5494 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5495 if (view == NULL) {
5496 error = got_error_from_errno("view_open");
5497 goto done;
5499 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5500 ignore_whitespace, force_text_diff, NULL, repo);
5501 if (error)
5502 goto done;
5503 error = view_loop(view);
5504 done:
5505 free(label1);
5506 free(label2);
5507 free(repo_path);
5508 free(cwd);
5509 if (repo) {
5510 const struct got_error *close_err = got_repo_close(repo);
5511 if (error == NULL)
5512 error = close_err;
5514 if (worktree)
5515 got_worktree_close(worktree);
5516 if (pack_fds) {
5517 const struct got_error *pack_err =
5518 got_repo_pack_fds_close(pack_fds);
5519 if (error == NULL)
5520 error = pack_err;
5522 tog_free_refs();
5523 return error;
5526 __dead static void
5527 usage_blame(void)
5529 endwin();
5530 fprintf(stderr,
5531 "usage: %s blame [-c commit] [-r repository-path] path\n",
5532 getprogname());
5533 exit(1);
5536 struct tog_blame_line {
5537 int annotated;
5538 struct got_object_id *id;
5541 static const struct got_error *
5542 draw_blame(struct tog_view *view)
5544 struct tog_blame_view_state *s = &view->state.blame;
5545 struct tog_blame *blame = &s->blame;
5546 regmatch_t *regmatch = &view->regmatch;
5547 const struct got_error *err;
5548 int lineno = 0, nprinted = 0;
5549 char *line = NULL;
5550 size_t linesize = 0;
5551 ssize_t linelen;
5552 wchar_t *wline;
5553 int width;
5554 struct tog_blame_line *blame_line;
5555 struct got_object_id *prev_id = NULL;
5556 char *id_str;
5557 struct tog_color *tc;
5559 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5560 if (err)
5561 return err;
5563 rewind(blame->f);
5564 werase(view->window);
5566 if (asprintf(&line, "commit %s", id_str) == -1) {
5567 err = got_error_from_errno("asprintf");
5568 free(id_str);
5569 return err;
5572 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5573 free(line);
5574 line = NULL;
5575 if (err)
5576 return err;
5577 if (view_needs_focus_indication(view))
5578 wstandout(view->window);
5579 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5580 if (tc)
5581 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5582 waddwstr(view->window, wline);
5583 while (width++ < view->ncols)
5584 waddch(view->window, ' ');
5585 if (tc)
5586 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5587 if (view_needs_focus_indication(view))
5588 wstandend(view->window);
5589 free(wline);
5590 wline = NULL;
5592 if (view->gline > blame->nlines)
5593 view->gline = blame->nlines;
5595 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5596 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5597 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5598 free(id_str);
5599 return got_error_from_errno("asprintf");
5601 free(id_str);
5602 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5603 free(line);
5604 line = NULL;
5605 if (err)
5606 return err;
5607 waddwstr(view->window, wline);
5608 free(wline);
5609 wline = NULL;
5610 if (width < view->ncols - 1)
5611 waddch(view->window, '\n');
5613 s->eof = 0;
5614 view->maxx = 0;
5615 while (nprinted < view->nlines - 2) {
5616 linelen = getline(&line, &linesize, blame->f);
5617 if (linelen == -1) {
5618 if (feof(blame->f)) {
5619 s->eof = 1;
5620 break;
5622 free(line);
5623 return got_ferror(blame->f, GOT_ERR_IO);
5625 if (++lineno < s->first_displayed_line)
5626 continue;
5627 if (view->gline && !gotoline(view, &lineno, &nprinted))
5628 continue;
5630 /* Set view->maxx based on full line length. */
5631 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5632 if (err) {
5633 free(line);
5634 return err;
5636 free(wline);
5637 wline = NULL;
5638 view->maxx = MAX(view->maxx, width);
5640 if (nprinted == s->selected_line - 1)
5641 wstandout(view->window);
5643 if (blame->nlines > 0) {
5644 blame_line = &blame->lines[lineno - 1];
5645 if (blame_line->annotated && prev_id &&
5646 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5647 !(nprinted == s->selected_line - 1)) {
5648 waddstr(view->window, " ");
5649 } else if (blame_line->annotated) {
5650 char *id_str;
5651 err = got_object_id_str(&id_str,
5652 blame_line->id);
5653 if (err) {
5654 free(line);
5655 return err;
5657 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5658 if (tc)
5659 wattr_on(view->window,
5660 COLOR_PAIR(tc->colorpair), NULL);
5661 wprintw(view->window, "%.8s", id_str);
5662 if (tc)
5663 wattr_off(view->window,
5664 COLOR_PAIR(tc->colorpair), NULL);
5665 free(id_str);
5666 prev_id = blame_line->id;
5667 } else {
5668 waddstr(view->window, "........");
5669 prev_id = NULL;
5671 } else {
5672 waddstr(view->window, "........");
5673 prev_id = NULL;
5676 if (nprinted == s->selected_line - 1)
5677 wstandend(view->window);
5678 waddstr(view->window, " ");
5680 if (view->ncols <= 9) {
5681 width = 9;
5682 } else if (s->first_displayed_line + nprinted ==
5683 s->matched_line &&
5684 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5685 err = add_matched_line(&width, line, view->ncols - 9, 9,
5686 view->window, view->x, regmatch);
5687 if (err) {
5688 free(line);
5689 return err;
5691 width += 9;
5692 } else {
5693 int skip;
5694 err = format_line(&wline, &width, &skip, line,
5695 view->x, view->ncols - 9, 9, 1);
5696 if (err) {
5697 free(line);
5698 return err;
5700 waddwstr(view->window, &wline[skip]);
5701 width += 9;
5702 free(wline);
5703 wline = NULL;
5706 if (width <= view->ncols - 1)
5707 waddch(view->window, '\n');
5708 if (++nprinted == 1)
5709 s->first_displayed_line = lineno;
5711 free(line);
5712 s->last_displayed_line = lineno;
5714 view_border(view);
5716 return NULL;
5719 static const struct got_error *
5720 blame_cb(void *arg, int nlines, int lineno,
5721 struct got_commit_object *commit, struct got_object_id *id)
5723 const struct got_error *err = NULL;
5724 struct tog_blame_cb_args *a = arg;
5725 struct tog_blame_line *line;
5726 int errcode;
5728 if (nlines != a->nlines ||
5729 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5730 return got_error(GOT_ERR_RANGE);
5732 errcode = pthread_mutex_lock(&tog_mutex);
5733 if (errcode)
5734 return got_error_set_errno(errcode, "pthread_mutex_lock");
5736 if (*a->quit) { /* user has quit the blame view */
5737 err = got_error(GOT_ERR_ITER_COMPLETED);
5738 goto done;
5741 if (lineno == -1)
5742 goto done; /* no change in this commit */
5744 line = &a->lines[lineno - 1];
5745 if (line->annotated)
5746 goto done;
5748 line->id = got_object_id_dup(id);
5749 if (line->id == NULL) {
5750 err = got_error_from_errno("got_object_id_dup");
5751 goto done;
5753 line->annotated = 1;
5754 done:
5755 errcode = pthread_mutex_unlock(&tog_mutex);
5756 if (errcode)
5757 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5758 return err;
5761 static void *
5762 blame_thread(void *arg)
5764 const struct got_error *err, *close_err;
5765 struct tog_blame_thread_args *ta = arg;
5766 struct tog_blame_cb_args *a = ta->cb_args;
5767 int errcode, fd1 = -1, fd2 = -1;
5768 FILE *f1 = NULL, *f2 = NULL;
5770 fd1 = got_opentempfd();
5771 if (fd1 == -1)
5772 return (void *)got_error_from_errno("got_opentempfd");
5774 fd2 = got_opentempfd();
5775 if (fd2 == -1) {
5776 err = got_error_from_errno("got_opentempfd");
5777 goto done;
5780 f1 = got_opentemp();
5781 if (f1 == NULL) {
5782 err = (void *)got_error_from_errno("got_opentemp");
5783 goto done;
5785 f2 = got_opentemp();
5786 if (f2 == NULL) {
5787 err = (void *)got_error_from_errno("got_opentemp");
5788 goto done;
5791 err = block_signals_used_by_main_thread();
5792 if (err)
5793 goto done;
5795 err = got_blame(ta->path, a->commit_id, ta->repo,
5796 tog_diff_algo, blame_cb, ta->cb_args,
5797 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5798 if (err && err->code == GOT_ERR_CANCELLED)
5799 err = NULL;
5801 errcode = pthread_mutex_lock(&tog_mutex);
5802 if (errcode) {
5803 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5804 goto done;
5807 close_err = got_repo_close(ta->repo);
5808 if (err == NULL)
5809 err = close_err;
5810 ta->repo = NULL;
5811 *ta->complete = 1;
5813 errcode = pthread_mutex_unlock(&tog_mutex);
5814 if (errcode && err == NULL)
5815 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5817 done:
5818 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5819 err = got_error_from_errno("close");
5820 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5821 err = got_error_from_errno("close");
5822 if (f1 && fclose(f1) == EOF && err == NULL)
5823 err = got_error_from_errno("fclose");
5824 if (f2 && fclose(f2) == EOF && err == NULL)
5825 err = got_error_from_errno("fclose");
5827 return (void *)err;
5830 static struct got_object_id *
5831 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5832 int first_displayed_line, int selected_line)
5834 struct tog_blame_line *line;
5836 if (nlines <= 0)
5837 return NULL;
5839 line = &lines[first_displayed_line - 1 + selected_line - 1];
5840 if (!line->annotated)
5841 return NULL;
5843 return line->id;
5846 static struct got_object_id *
5847 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5848 int lineno)
5850 struct tog_blame_line *line;
5852 if (nlines <= 0 || lineno >= nlines)
5853 return NULL;
5855 line = &lines[lineno - 1];
5856 if (!line->annotated)
5857 return NULL;
5859 return line->id;
5862 static const struct got_error *
5863 stop_blame(struct tog_blame *blame)
5865 const struct got_error *err = NULL;
5866 int i;
5868 if (blame->thread) {
5869 int errcode;
5870 errcode = pthread_mutex_unlock(&tog_mutex);
5871 if (errcode)
5872 return got_error_set_errno(errcode,
5873 "pthread_mutex_unlock");
5874 errcode = pthread_join(blame->thread, (void **)&err);
5875 if (errcode)
5876 return got_error_set_errno(errcode, "pthread_join");
5877 errcode = pthread_mutex_lock(&tog_mutex);
5878 if (errcode)
5879 return got_error_set_errno(errcode,
5880 "pthread_mutex_lock");
5881 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5882 err = NULL;
5883 blame->thread = NULL;
5885 if (blame->thread_args.repo) {
5886 const struct got_error *close_err;
5887 close_err = got_repo_close(blame->thread_args.repo);
5888 if (err == NULL)
5889 err = close_err;
5890 blame->thread_args.repo = NULL;
5892 if (blame->f) {
5893 if (fclose(blame->f) == EOF && err == NULL)
5894 err = got_error_from_errno("fclose");
5895 blame->f = NULL;
5897 if (blame->lines) {
5898 for (i = 0; i < blame->nlines; i++)
5899 free(blame->lines[i].id);
5900 free(blame->lines);
5901 blame->lines = NULL;
5903 free(blame->cb_args.commit_id);
5904 blame->cb_args.commit_id = NULL;
5905 if (blame->pack_fds) {
5906 const struct got_error *pack_err =
5907 got_repo_pack_fds_close(blame->pack_fds);
5908 if (err == NULL)
5909 err = pack_err;
5910 blame->pack_fds = NULL;
5912 return err;
5915 static const struct got_error *
5916 cancel_blame_view(void *arg)
5918 const struct got_error *err = NULL;
5919 int *done = arg;
5920 int errcode;
5922 errcode = pthread_mutex_lock(&tog_mutex);
5923 if (errcode)
5924 return got_error_set_errno(errcode,
5925 "pthread_mutex_unlock");
5927 if (*done)
5928 err = got_error(GOT_ERR_CANCELLED);
5930 errcode = pthread_mutex_unlock(&tog_mutex);
5931 if (errcode)
5932 return got_error_set_errno(errcode,
5933 "pthread_mutex_lock");
5935 return err;
5938 static const struct got_error *
5939 run_blame(struct tog_view *view)
5941 struct tog_blame_view_state *s = &view->state.blame;
5942 struct tog_blame *blame = &s->blame;
5943 const struct got_error *err = NULL;
5944 struct got_commit_object *commit = NULL;
5945 struct got_blob_object *blob = NULL;
5946 struct got_repository *thread_repo = NULL;
5947 struct got_object_id *obj_id = NULL;
5948 int obj_type, fd = -1;
5949 int *pack_fds = NULL;
5951 err = got_object_open_as_commit(&commit, s->repo,
5952 &s->blamed_commit->id);
5953 if (err)
5954 return err;
5956 fd = got_opentempfd();
5957 if (fd == -1) {
5958 err = got_error_from_errno("got_opentempfd");
5959 goto done;
5962 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5963 if (err)
5964 goto done;
5966 err = got_object_get_type(&obj_type, s->repo, obj_id);
5967 if (err)
5968 goto done;
5970 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5971 err = got_error(GOT_ERR_OBJ_TYPE);
5972 goto done;
5975 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5976 if (err)
5977 goto done;
5978 blame->f = got_opentemp();
5979 if (blame->f == NULL) {
5980 err = got_error_from_errno("got_opentemp");
5981 goto done;
5983 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5984 &blame->line_offsets, blame->f, blob);
5985 if (err)
5986 goto done;
5987 if (blame->nlines == 0) {
5988 s->blame_complete = 1;
5989 goto done;
5992 /* Don't include \n at EOF in the blame line count. */
5993 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5994 blame->nlines--;
5996 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5997 if (blame->lines == NULL) {
5998 err = got_error_from_errno("calloc");
5999 goto done;
6002 err = got_repo_pack_fds_open(&pack_fds);
6003 if (err)
6004 goto done;
6005 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6006 pack_fds);
6007 if (err)
6008 goto done;
6010 blame->pack_fds = pack_fds;
6011 blame->cb_args.view = view;
6012 blame->cb_args.lines = blame->lines;
6013 blame->cb_args.nlines = blame->nlines;
6014 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6015 if (blame->cb_args.commit_id == NULL) {
6016 err = got_error_from_errno("got_object_id_dup");
6017 goto done;
6019 blame->cb_args.quit = &s->done;
6021 blame->thread_args.path = s->path;
6022 blame->thread_args.repo = thread_repo;
6023 blame->thread_args.cb_args = &blame->cb_args;
6024 blame->thread_args.complete = &s->blame_complete;
6025 blame->thread_args.cancel_cb = cancel_blame_view;
6026 blame->thread_args.cancel_arg = &s->done;
6027 s->blame_complete = 0;
6029 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6030 s->first_displayed_line = 1;
6031 s->last_displayed_line = view->nlines;
6032 s->selected_line = 1;
6034 s->matched_line = 0;
6036 done:
6037 if (commit)
6038 got_object_commit_close(commit);
6039 if (fd != -1 && close(fd) == -1 && err == NULL)
6040 err = got_error_from_errno("close");
6041 if (blob)
6042 got_object_blob_close(blob);
6043 free(obj_id);
6044 if (err)
6045 stop_blame(blame);
6046 return err;
6049 static const struct got_error *
6050 open_blame_view(struct tog_view *view, char *path,
6051 struct got_object_id *commit_id, struct got_repository *repo)
6053 const struct got_error *err = NULL;
6054 struct tog_blame_view_state *s = &view->state.blame;
6056 STAILQ_INIT(&s->blamed_commits);
6058 s->path = strdup(path);
6059 if (s->path == NULL)
6060 return got_error_from_errno("strdup");
6062 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6063 if (err) {
6064 free(s->path);
6065 return err;
6068 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6069 s->first_displayed_line = 1;
6070 s->last_displayed_line = view->nlines;
6071 s->selected_line = 1;
6072 s->blame_complete = 0;
6073 s->repo = repo;
6074 s->commit_id = commit_id;
6075 memset(&s->blame, 0, sizeof(s->blame));
6077 STAILQ_INIT(&s->colors);
6078 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6079 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6080 get_color_value("TOG_COLOR_COMMIT"));
6081 if (err)
6082 return err;
6085 view->show = show_blame_view;
6086 view->input = input_blame_view;
6087 view->reset = reset_blame_view;
6088 view->close = close_blame_view;
6089 view->search_start = search_start_blame_view;
6090 view->search_setup = search_setup_blame_view;
6091 view->search_next = search_next_view_match;
6093 return run_blame(view);
6096 static const struct got_error *
6097 close_blame_view(struct tog_view *view)
6099 const struct got_error *err = NULL;
6100 struct tog_blame_view_state *s = &view->state.blame;
6102 if (s->blame.thread)
6103 err = stop_blame(&s->blame);
6105 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6106 struct got_object_qid *blamed_commit;
6107 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6108 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6109 got_object_qid_free(blamed_commit);
6112 free(s->path);
6113 free_colors(&s->colors);
6114 return err;
6117 static const struct got_error *
6118 search_start_blame_view(struct tog_view *view)
6120 struct tog_blame_view_state *s = &view->state.blame;
6122 s->matched_line = 0;
6123 return NULL;
6126 static void
6127 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6128 size_t *nlines, int **first, int **last, int **match, int **selected)
6130 struct tog_blame_view_state *s = &view->state.blame;
6132 *f = s->blame.f;
6133 *nlines = s->blame.nlines;
6134 *line_offsets = s->blame.line_offsets;
6135 *match = &s->matched_line;
6136 *first = &s->first_displayed_line;
6137 *last = &s->last_displayed_line;
6138 *selected = &s->selected_line;
6141 static const struct got_error *
6142 show_blame_view(struct tog_view *view)
6144 const struct got_error *err = NULL;
6145 struct tog_blame_view_state *s = &view->state.blame;
6146 int errcode;
6148 if (s->blame.thread == NULL && !s->blame_complete) {
6149 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6150 &s->blame.thread_args);
6151 if (errcode)
6152 return got_error_set_errno(errcode, "pthread_create");
6154 halfdelay(1); /* fast refresh while annotating */
6157 if (s->blame_complete)
6158 halfdelay(10); /* disable fast refresh */
6160 err = draw_blame(view);
6162 view_border(view);
6163 return err;
6166 static const struct got_error *
6167 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6168 struct got_repository *repo, struct got_object_id *id)
6170 struct tog_view *log_view;
6171 const struct got_error *err = NULL;
6173 *new_view = NULL;
6175 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6176 if (log_view == NULL)
6177 return got_error_from_errno("view_open");
6179 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6180 if (err)
6181 view_close(log_view);
6182 else
6183 *new_view = log_view;
6185 return err;
6188 static const struct got_error *
6189 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6191 const struct got_error *err = NULL, *thread_err = NULL;
6192 struct tog_view *diff_view;
6193 struct tog_blame_view_state *s = &view->state.blame;
6194 int eos, nscroll, begin_y = 0, begin_x = 0;
6196 eos = nscroll = view->nlines - 2;
6197 if (view_is_hsplit_top(view))
6198 --eos; /* border */
6200 switch (ch) {
6201 case '0':
6202 view->x = 0;
6203 break;
6204 case '$':
6205 view->x = MAX(view->maxx - view->ncols / 3, 0);
6206 view->count = 0;
6207 break;
6208 case KEY_RIGHT:
6209 case 'l':
6210 if (view->x + view->ncols / 3 < view->maxx)
6211 view->x += 2; /* move two columns right */
6212 else
6213 view->count = 0;
6214 break;
6215 case KEY_LEFT:
6216 case 'h':
6217 view->x -= MIN(view->x, 2); /* move two columns back */
6218 if (view->x <= 0)
6219 view->count = 0;
6220 break;
6221 case 'q':
6222 s->done = 1;
6223 break;
6224 case 'g':
6225 case KEY_HOME:
6226 s->selected_line = 1;
6227 s->first_displayed_line = 1;
6228 view->count = 0;
6229 break;
6230 case 'G':
6231 case KEY_END:
6232 if (s->blame.nlines < eos) {
6233 s->selected_line = s->blame.nlines;
6234 s->first_displayed_line = 1;
6235 } else {
6236 s->selected_line = eos;
6237 s->first_displayed_line = s->blame.nlines - (eos - 1);
6239 view->count = 0;
6240 break;
6241 case 'k':
6242 case KEY_UP:
6243 case CTRL('p'):
6244 if (s->selected_line > 1)
6245 s->selected_line--;
6246 else if (s->selected_line == 1 &&
6247 s->first_displayed_line > 1)
6248 s->first_displayed_line--;
6249 else
6250 view->count = 0;
6251 break;
6252 case CTRL('u'):
6253 case 'u':
6254 nscroll /= 2;
6255 /* FALL THROUGH */
6256 case KEY_PPAGE:
6257 case CTRL('b'):
6258 case 'b':
6259 if (s->first_displayed_line == 1) {
6260 if (view->count > 1)
6261 nscroll += nscroll;
6262 s->selected_line = MAX(1, s->selected_line - nscroll);
6263 view->count = 0;
6264 break;
6266 if (s->first_displayed_line > nscroll)
6267 s->first_displayed_line -= nscroll;
6268 else
6269 s->first_displayed_line = 1;
6270 break;
6271 case 'j':
6272 case KEY_DOWN:
6273 case CTRL('n'):
6274 if (s->selected_line < eos && s->first_displayed_line +
6275 s->selected_line <= s->blame.nlines)
6276 s->selected_line++;
6277 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6278 s->first_displayed_line++;
6279 else
6280 view->count = 0;
6281 break;
6282 case 'c':
6283 case 'p': {
6284 struct got_object_id *id = NULL;
6286 view->count = 0;
6287 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6288 s->first_displayed_line, s->selected_line);
6289 if (id == NULL)
6290 break;
6291 if (ch == 'p') {
6292 struct got_commit_object *commit, *pcommit;
6293 struct got_object_qid *pid;
6294 struct got_object_id *blob_id = NULL;
6295 int obj_type;
6296 err = got_object_open_as_commit(&commit,
6297 s->repo, id);
6298 if (err)
6299 break;
6300 pid = STAILQ_FIRST(
6301 got_object_commit_get_parent_ids(commit));
6302 if (pid == NULL) {
6303 got_object_commit_close(commit);
6304 break;
6306 /* Check if path history ends here. */
6307 err = got_object_open_as_commit(&pcommit,
6308 s->repo, &pid->id);
6309 if (err)
6310 break;
6311 err = got_object_id_by_path(&blob_id, s->repo,
6312 pcommit, s->path);
6313 got_object_commit_close(pcommit);
6314 if (err) {
6315 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6316 err = NULL;
6317 got_object_commit_close(commit);
6318 break;
6320 err = got_object_get_type(&obj_type, s->repo,
6321 blob_id);
6322 free(blob_id);
6323 /* Can't blame non-blob type objects. */
6324 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6325 got_object_commit_close(commit);
6326 break;
6328 err = got_object_qid_alloc(&s->blamed_commit,
6329 &pid->id);
6330 got_object_commit_close(commit);
6331 } else {
6332 if (got_object_id_cmp(id,
6333 &s->blamed_commit->id) == 0)
6334 break;
6335 err = got_object_qid_alloc(&s->blamed_commit,
6336 id);
6338 if (err)
6339 break;
6340 s->done = 1;
6341 thread_err = stop_blame(&s->blame);
6342 s->done = 0;
6343 if (thread_err)
6344 break;
6345 STAILQ_INSERT_HEAD(&s->blamed_commits,
6346 s->blamed_commit, entry);
6347 err = run_blame(view);
6348 if (err)
6349 break;
6350 break;
6352 case 'C': {
6353 struct got_object_qid *first;
6355 view->count = 0;
6356 first = STAILQ_FIRST(&s->blamed_commits);
6357 if (!got_object_id_cmp(&first->id, s->commit_id))
6358 break;
6359 s->done = 1;
6360 thread_err = stop_blame(&s->blame);
6361 s->done = 0;
6362 if (thread_err)
6363 break;
6364 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6365 got_object_qid_free(s->blamed_commit);
6366 s->blamed_commit =
6367 STAILQ_FIRST(&s->blamed_commits);
6368 err = run_blame(view);
6369 if (err)
6370 break;
6371 break;
6373 case 'L':
6374 view->count = 0;
6375 s->id_to_log = get_selected_commit_id(s->blame.lines,
6376 s->blame.nlines, s->first_displayed_line, s->selected_line);
6377 if (s->id_to_log)
6378 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6379 break;
6380 case KEY_ENTER:
6381 case '\r': {
6382 struct got_object_id *id = NULL;
6383 struct got_object_qid *pid;
6384 struct got_commit_object *commit = NULL;
6386 view->count = 0;
6387 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6388 s->first_displayed_line, s->selected_line);
6389 if (id == NULL)
6390 break;
6391 err = got_object_open_as_commit(&commit, s->repo, id);
6392 if (err)
6393 break;
6394 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6395 if (*new_view) {
6396 /* traversed from diff view, release diff resources */
6397 err = close_diff_view(*new_view);
6398 if (err)
6399 break;
6400 diff_view = *new_view;
6401 } else {
6402 if (view_is_parent_view(view))
6403 view_get_split(view, &begin_y, &begin_x);
6405 diff_view = view_open(0, 0, begin_y, begin_x,
6406 TOG_VIEW_DIFF);
6407 if (diff_view == NULL) {
6408 got_object_commit_close(commit);
6409 err = got_error_from_errno("view_open");
6410 break;
6413 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6414 id, NULL, NULL, 3, 0, 0, view, s->repo);
6415 got_object_commit_close(commit);
6416 if (err) {
6417 view_close(diff_view);
6418 break;
6420 s->last_diffed_line = s->first_displayed_line - 1 +
6421 s->selected_line;
6422 if (*new_view)
6423 break; /* still open from active diff view */
6424 if (view_is_parent_view(view) &&
6425 view->mode == TOG_VIEW_SPLIT_HRZN) {
6426 err = view_init_hsplit(view, begin_y);
6427 if (err)
6428 break;
6431 view->focussed = 0;
6432 diff_view->focussed = 1;
6433 diff_view->mode = view->mode;
6434 diff_view->nlines = view->lines - begin_y;
6435 if (view_is_parent_view(view)) {
6436 view_transfer_size(diff_view, view);
6437 err = view_close_child(view);
6438 if (err)
6439 break;
6440 err = view_set_child(view, diff_view);
6441 if (err)
6442 break;
6443 view->focus_child = 1;
6444 } else
6445 *new_view = diff_view;
6446 if (err)
6447 break;
6448 break;
6450 case CTRL('d'):
6451 case 'd':
6452 nscroll /= 2;
6453 /* FALL THROUGH */
6454 case KEY_NPAGE:
6455 case CTRL('f'):
6456 case 'f':
6457 case ' ':
6458 if (s->last_displayed_line >= s->blame.nlines &&
6459 s->selected_line >= MIN(s->blame.nlines,
6460 view->nlines - 2)) {
6461 view->count = 0;
6462 break;
6464 if (s->last_displayed_line >= s->blame.nlines &&
6465 s->selected_line < view->nlines - 2) {
6466 s->selected_line +=
6467 MIN(nscroll, s->last_displayed_line -
6468 s->first_displayed_line - s->selected_line + 1);
6470 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6471 s->first_displayed_line += nscroll;
6472 else
6473 s->first_displayed_line =
6474 s->blame.nlines - (view->nlines - 3);
6475 break;
6476 case KEY_RESIZE:
6477 if (s->selected_line > view->nlines - 2) {
6478 s->selected_line = MIN(s->blame.nlines,
6479 view->nlines - 2);
6481 break;
6482 default:
6483 view->count = 0;
6484 break;
6486 return thread_err ? thread_err : err;
6489 static const struct got_error *
6490 reset_blame_view(struct tog_view *view)
6492 const struct got_error *err;
6493 struct tog_blame_view_state *s = &view->state.blame;
6495 view->count = 0;
6496 s->done = 1;
6497 err = stop_blame(&s->blame);
6498 s->done = 0;
6499 if (err)
6500 return err;
6501 return run_blame(view);
6504 static const struct got_error *
6505 cmd_blame(int argc, char *argv[])
6507 const struct got_error *error;
6508 struct got_repository *repo = NULL;
6509 struct got_worktree *worktree = NULL;
6510 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6511 char *link_target = NULL;
6512 struct got_object_id *commit_id = NULL;
6513 struct got_commit_object *commit = NULL;
6514 char *commit_id_str = NULL;
6515 int ch;
6516 struct tog_view *view;
6517 int *pack_fds = NULL;
6519 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6520 switch (ch) {
6521 case 'c':
6522 commit_id_str = optarg;
6523 break;
6524 case 'r':
6525 repo_path = realpath(optarg, NULL);
6526 if (repo_path == NULL)
6527 return got_error_from_errno2("realpath",
6528 optarg);
6529 break;
6530 default:
6531 usage_blame();
6532 /* NOTREACHED */
6536 argc -= optind;
6537 argv += optind;
6539 if (argc != 1)
6540 usage_blame();
6542 error = got_repo_pack_fds_open(&pack_fds);
6543 if (error != NULL)
6544 goto done;
6546 if (repo_path == NULL) {
6547 cwd = getcwd(NULL, 0);
6548 if (cwd == NULL)
6549 return got_error_from_errno("getcwd");
6550 error = got_worktree_open(&worktree, cwd);
6551 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6552 goto done;
6553 if (worktree)
6554 repo_path =
6555 strdup(got_worktree_get_repo_path(worktree));
6556 else
6557 repo_path = strdup(cwd);
6558 if (repo_path == NULL) {
6559 error = got_error_from_errno("strdup");
6560 goto done;
6564 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6565 if (error != NULL)
6566 goto done;
6568 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6569 worktree);
6570 if (error)
6571 goto done;
6573 init_curses();
6575 error = apply_unveil(got_repo_get_path(repo), NULL);
6576 if (error)
6577 goto done;
6579 error = tog_load_refs(repo, 0);
6580 if (error)
6581 goto done;
6583 if (commit_id_str == NULL) {
6584 struct got_reference *head_ref;
6585 error = got_ref_open(&head_ref, repo, worktree ?
6586 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6587 if (error != NULL)
6588 goto done;
6589 error = got_ref_resolve(&commit_id, repo, head_ref);
6590 got_ref_close(head_ref);
6591 } else {
6592 error = got_repo_match_object_id(&commit_id, NULL,
6593 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6595 if (error != NULL)
6596 goto done;
6598 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6599 if (view == NULL) {
6600 error = got_error_from_errno("view_open");
6601 goto done;
6604 error = got_object_open_as_commit(&commit, repo, commit_id);
6605 if (error)
6606 goto done;
6608 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6609 commit, repo);
6610 if (error)
6611 goto done;
6613 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6614 commit_id, repo);
6615 if (error)
6616 goto done;
6617 if (worktree) {
6618 /* Release work tree lock. */
6619 got_worktree_close(worktree);
6620 worktree = NULL;
6622 error = view_loop(view);
6623 done:
6624 free(repo_path);
6625 free(in_repo_path);
6626 free(link_target);
6627 free(cwd);
6628 free(commit_id);
6629 if (commit)
6630 got_object_commit_close(commit);
6631 if (worktree)
6632 got_worktree_close(worktree);
6633 if (repo) {
6634 const struct got_error *close_err = got_repo_close(repo);
6635 if (error == NULL)
6636 error = close_err;
6638 if (pack_fds) {
6639 const struct got_error *pack_err =
6640 got_repo_pack_fds_close(pack_fds);
6641 if (error == NULL)
6642 error = pack_err;
6644 tog_free_refs();
6645 return error;
6648 static const struct got_error *
6649 draw_tree_entries(struct tog_view *view, const char *parent_path)
6651 struct tog_tree_view_state *s = &view->state.tree;
6652 const struct got_error *err = NULL;
6653 struct got_tree_entry *te;
6654 wchar_t *wline;
6655 char *index = NULL;
6656 struct tog_color *tc;
6657 int width, n, nentries, i = 1;
6658 int limit = view->nlines;
6660 s->ndisplayed = 0;
6661 if (view_is_hsplit_top(view))
6662 --limit; /* border */
6664 werase(view->window);
6666 if (limit == 0)
6667 return NULL;
6669 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6670 0, 0);
6671 if (err)
6672 return err;
6673 if (view_needs_focus_indication(view))
6674 wstandout(view->window);
6675 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6676 if (tc)
6677 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6678 waddwstr(view->window, wline);
6679 free(wline);
6680 wline = NULL;
6681 while (width++ < view->ncols)
6682 waddch(view->window, ' ');
6683 if (tc)
6684 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6685 if (view_needs_focus_indication(view))
6686 wstandend(view->window);
6687 if (--limit <= 0)
6688 return NULL;
6690 i += s->selected;
6691 if (s->first_displayed_entry) {
6692 i += got_tree_entry_get_index(s->first_displayed_entry);
6693 if (s->tree != s->root)
6694 ++i; /* account for ".." entry */
6696 nentries = got_object_tree_get_nentries(s->tree);
6697 if (asprintf(&index, "[%d/%d] %s",
6698 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6699 return got_error_from_errno("asprintf");
6700 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6701 free(index);
6702 if (err)
6703 return err;
6704 waddwstr(view->window, wline);
6705 free(wline);
6706 wline = NULL;
6707 if (width < view->ncols - 1)
6708 waddch(view->window, '\n');
6709 if (--limit <= 0)
6710 return NULL;
6711 waddch(view->window, '\n');
6712 if (--limit <= 0)
6713 return NULL;
6715 if (s->first_displayed_entry == NULL) {
6716 te = got_object_tree_get_first_entry(s->tree);
6717 if (s->selected == 0) {
6718 if (view->focussed)
6719 wstandout(view->window);
6720 s->selected_entry = NULL;
6722 waddstr(view->window, " ..\n"); /* parent directory */
6723 if (s->selected == 0 && view->focussed)
6724 wstandend(view->window);
6725 s->ndisplayed++;
6726 if (--limit <= 0)
6727 return NULL;
6728 n = 1;
6729 } else {
6730 n = 0;
6731 te = s->first_displayed_entry;
6734 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6735 char *line = NULL, *id_str = NULL, *link_target = NULL;
6736 const char *modestr = "";
6737 mode_t mode;
6739 te = got_object_tree_get_entry(s->tree, i);
6740 mode = got_tree_entry_get_mode(te);
6742 if (s->show_ids) {
6743 err = got_object_id_str(&id_str,
6744 got_tree_entry_get_id(te));
6745 if (err)
6746 return got_error_from_errno(
6747 "got_object_id_str");
6749 if (got_object_tree_entry_is_submodule(te))
6750 modestr = "$";
6751 else if (S_ISLNK(mode)) {
6752 int i;
6754 err = got_tree_entry_get_symlink_target(&link_target,
6755 te, s->repo);
6756 if (err) {
6757 free(id_str);
6758 return err;
6760 for (i = 0; i < strlen(link_target); i++) {
6761 if (!isprint((unsigned char)link_target[i]))
6762 link_target[i] = '?';
6764 modestr = "@";
6766 else if (S_ISDIR(mode))
6767 modestr = "/";
6768 else if (mode & S_IXUSR)
6769 modestr = "*";
6770 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6771 got_tree_entry_get_name(te), modestr,
6772 link_target ? " -> ": "",
6773 link_target ? link_target : "") == -1) {
6774 free(id_str);
6775 free(link_target);
6776 return got_error_from_errno("asprintf");
6778 free(id_str);
6779 free(link_target);
6780 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6781 0, 0);
6782 if (err) {
6783 free(line);
6784 break;
6786 if (n == s->selected) {
6787 if (view->focussed)
6788 wstandout(view->window);
6789 s->selected_entry = te;
6791 tc = match_color(&s->colors, line);
6792 if (tc)
6793 wattr_on(view->window,
6794 COLOR_PAIR(tc->colorpair), NULL);
6795 waddwstr(view->window, wline);
6796 if (tc)
6797 wattr_off(view->window,
6798 COLOR_PAIR(tc->colorpair), NULL);
6799 if (width < view->ncols - 1)
6800 waddch(view->window, '\n');
6801 if (n == s->selected && view->focussed)
6802 wstandend(view->window);
6803 free(line);
6804 free(wline);
6805 wline = NULL;
6806 n++;
6807 s->ndisplayed++;
6808 s->last_displayed_entry = te;
6809 if (--limit <= 0)
6810 break;
6813 return err;
6816 static void
6817 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6819 struct got_tree_entry *te;
6820 int isroot = s->tree == s->root;
6821 int i = 0;
6823 if (s->first_displayed_entry == NULL)
6824 return;
6826 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6827 while (i++ < maxscroll) {
6828 if (te == NULL) {
6829 if (!isroot)
6830 s->first_displayed_entry = NULL;
6831 break;
6833 s->first_displayed_entry = te;
6834 te = got_tree_entry_get_prev(s->tree, te);
6838 static const struct got_error *
6839 tree_scroll_down(struct tog_view *view, int maxscroll)
6841 struct tog_tree_view_state *s = &view->state.tree;
6842 struct got_tree_entry *next, *last;
6843 int n = 0;
6845 if (s->first_displayed_entry)
6846 next = got_tree_entry_get_next(s->tree,
6847 s->first_displayed_entry);
6848 else
6849 next = got_object_tree_get_first_entry(s->tree);
6851 last = s->last_displayed_entry;
6852 while (next && n++ < maxscroll) {
6853 if (last) {
6854 s->last_displayed_entry = last;
6855 last = got_tree_entry_get_next(s->tree, last);
6857 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6858 s->first_displayed_entry = next;
6859 next = got_tree_entry_get_next(s->tree, next);
6863 return NULL;
6866 static const struct got_error *
6867 tree_entry_path(char **path, struct tog_parent_trees *parents,
6868 struct got_tree_entry *te)
6870 const struct got_error *err = NULL;
6871 struct tog_parent_tree *pt;
6872 size_t len = 2; /* for leading slash and NUL */
6874 TAILQ_FOREACH(pt, parents, entry)
6875 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6876 + 1 /* slash */;
6877 if (te)
6878 len += strlen(got_tree_entry_get_name(te));
6880 *path = calloc(1, len);
6881 if (path == NULL)
6882 return got_error_from_errno("calloc");
6884 (*path)[0] = '/';
6885 pt = TAILQ_LAST(parents, tog_parent_trees);
6886 while (pt) {
6887 const char *name = got_tree_entry_get_name(pt->selected_entry);
6888 if (strlcat(*path, name, len) >= len) {
6889 err = got_error(GOT_ERR_NO_SPACE);
6890 goto done;
6892 if (strlcat(*path, "/", len) >= len) {
6893 err = got_error(GOT_ERR_NO_SPACE);
6894 goto done;
6896 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6898 if (te) {
6899 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6900 err = got_error(GOT_ERR_NO_SPACE);
6901 goto done;
6904 done:
6905 if (err) {
6906 free(*path);
6907 *path = NULL;
6909 return err;
6912 static const struct got_error *
6913 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6914 struct got_tree_entry *te, struct tog_parent_trees *parents,
6915 struct got_object_id *commit_id, struct got_repository *repo)
6917 const struct got_error *err = NULL;
6918 char *path;
6919 struct tog_view *blame_view;
6921 *new_view = NULL;
6923 err = tree_entry_path(&path, parents, te);
6924 if (err)
6925 return err;
6927 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6928 if (blame_view == NULL) {
6929 err = got_error_from_errno("view_open");
6930 goto done;
6933 err = open_blame_view(blame_view, path, commit_id, repo);
6934 if (err) {
6935 if (err->code == GOT_ERR_CANCELLED)
6936 err = NULL;
6937 view_close(blame_view);
6938 } else
6939 *new_view = blame_view;
6940 done:
6941 free(path);
6942 return err;
6945 static const struct got_error *
6946 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6947 struct tog_tree_view_state *s)
6949 struct tog_view *log_view;
6950 const struct got_error *err = NULL;
6951 char *path;
6953 *new_view = NULL;
6955 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6956 if (log_view == NULL)
6957 return got_error_from_errno("view_open");
6959 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6960 if (err)
6961 return err;
6963 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6964 path, 0);
6965 if (err)
6966 view_close(log_view);
6967 else
6968 *new_view = log_view;
6969 free(path);
6970 return err;
6973 static const struct got_error *
6974 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6975 const char *head_ref_name, struct got_repository *repo)
6977 const struct got_error *err = NULL;
6978 char *commit_id_str = NULL;
6979 struct tog_tree_view_state *s = &view->state.tree;
6980 struct got_commit_object *commit = NULL;
6982 TAILQ_INIT(&s->parents);
6983 STAILQ_INIT(&s->colors);
6985 s->commit_id = got_object_id_dup(commit_id);
6986 if (s->commit_id == NULL)
6987 return got_error_from_errno("got_object_id_dup");
6989 err = got_object_open_as_commit(&commit, repo, commit_id);
6990 if (err)
6991 goto done;
6994 * The root is opened here and will be closed when the view is closed.
6995 * Any visited subtrees and their path-wise parents are opened and
6996 * closed on demand.
6998 err = got_object_open_as_tree(&s->root, repo,
6999 got_object_commit_get_tree_id(commit));
7000 if (err)
7001 goto done;
7002 s->tree = s->root;
7004 err = got_object_id_str(&commit_id_str, commit_id);
7005 if (err != NULL)
7006 goto done;
7008 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7009 err = got_error_from_errno("asprintf");
7010 goto done;
7013 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7014 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7015 if (head_ref_name) {
7016 s->head_ref_name = strdup(head_ref_name);
7017 if (s->head_ref_name == NULL) {
7018 err = got_error_from_errno("strdup");
7019 goto done;
7022 s->repo = repo;
7024 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7025 err = add_color(&s->colors, "\\$$",
7026 TOG_COLOR_TREE_SUBMODULE,
7027 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7028 if (err)
7029 goto done;
7030 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7031 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7032 if (err)
7033 goto done;
7034 err = add_color(&s->colors, "/$",
7035 TOG_COLOR_TREE_DIRECTORY,
7036 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7037 if (err)
7038 goto done;
7040 err = add_color(&s->colors, "\\*$",
7041 TOG_COLOR_TREE_EXECUTABLE,
7042 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7043 if (err)
7044 goto done;
7046 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7047 get_color_value("TOG_COLOR_COMMIT"));
7048 if (err)
7049 goto done;
7052 view->show = show_tree_view;
7053 view->input = input_tree_view;
7054 view->close = close_tree_view;
7055 view->search_start = search_start_tree_view;
7056 view->search_next = search_next_tree_view;
7057 done:
7058 free(commit_id_str);
7059 if (commit)
7060 got_object_commit_close(commit);
7061 if (err)
7062 close_tree_view(view);
7063 return err;
7066 static const struct got_error *
7067 close_tree_view(struct tog_view *view)
7069 struct tog_tree_view_state *s = &view->state.tree;
7071 free_colors(&s->colors);
7072 free(s->tree_label);
7073 s->tree_label = NULL;
7074 free(s->commit_id);
7075 s->commit_id = NULL;
7076 free(s->head_ref_name);
7077 s->head_ref_name = NULL;
7078 while (!TAILQ_EMPTY(&s->parents)) {
7079 struct tog_parent_tree *parent;
7080 parent = TAILQ_FIRST(&s->parents);
7081 TAILQ_REMOVE(&s->parents, parent, entry);
7082 if (parent->tree != s->root)
7083 got_object_tree_close(parent->tree);
7084 free(parent);
7087 if (s->tree != NULL && s->tree != s->root)
7088 got_object_tree_close(s->tree);
7089 if (s->root)
7090 got_object_tree_close(s->root);
7091 return NULL;
7094 static const struct got_error *
7095 search_start_tree_view(struct tog_view *view)
7097 struct tog_tree_view_state *s = &view->state.tree;
7099 s->matched_entry = NULL;
7100 return NULL;
7103 static int
7104 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7106 regmatch_t regmatch;
7108 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7109 0) == 0;
7112 static const struct got_error *
7113 search_next_tree_view(struct tog_view *view)
7115 struct tog_tree_view_state *s = &view->state.tree;
7116 struct got_tree_entry *te = NULL;
7118 if (!view->searching) {
7119 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7120 return NULL;
7123 if (s->matched_entry) {
7124 if (view->searching == TOG_SEARCH_FORWARD) {
7125 if (s->selected_entry)
7126 te = got_tree_entry_get_next(s->tree,
7127 s->selected_entry);
7128 else
7129 te = got_object_tree_get_first_entry(s->tree);
7130 } else {
7131 if (s->selected_entry == NULL)
7132 te = got_object_tree_get_last_entry(s->tree);
7133 else
7134 te = got_tree_entry_get_prev(s->tree,
7135 s->selected_entry);
7137 } else {
7138 if (s->selected_entry)
7139 te = s->selected_entry;
7140 else if (view->searching == TOG_SEARCH_FORWARD)
7141 te = got_object_tree_get_first_entry(s->tree);
7142 else
7143 te = got_object_tree_get_last_entry(s->tree);
7146 while (1) {
7147 if (te == NULL) {
7148 if (s->matched_entry == NULL) {
7149 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7150 return NULL;
7152 if (view->searching == TOG_SEARCH_FORWARD)
7153 te = got_object_tree_get_first_entry(s->tree);
7154 else
7155 te = got_object_tree_get_last_entry(s->tree);
7158 if (match_tree_entry(te, &view->regex)) {
7159 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7160 s->matched_entry = te;
7161 break;
7164 if (view->searching == TOG_SEARCH_FORWARD)
7165 te = got_tree_entry_get_next(s->tree, te);
7166 else
7167 te = got_tree_entry_get_prev(s->tree, te);
7170 if (s->matched_entry) {
7171 s->first_displayed_entry = s->matched_entry;
7172 s->selected = 0;
7175 return NULL;
7178 static const struct got_error *
7179 show_tree_view(struct tog_view *view)
7181 const struct got_error *err = NULL;
7182 struct tog_tree_view_state *s = &view->state.tree;
7183 char *parent_path;
7185 err = tree_entry_path(&parent_path, &s->parents, NULL);
7186 if (err)
7187 return err;
7189 err = draw_tree_entries(view, parent_path);
7190 free(parent_path);
7192 view_border(view);
7193 return err;
7196 static const struct got_error *
7197 tree_goto_line(struct tog_view *view, int nlines)
7199 const struct got_error *err = NULL;
7200 struct tog_tree_view_state *s = &view->state.tree;
7201 struct got_tree_entry **fte, **lte, **ste;
7202 int g, last, first = 1, i = 1;
7203 int root = s->tree == s->root;
7204 int off = root ? 1 : 2;
7206 g = view->gline;
7207 view->gline = 0;
7209 if (g == 0)
7210 g = 1;
7211 else if (g > got_object_tree_get_nentries(s->tree))
7212 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7214 fte = &s->first_displayed_entry;
7215 lte = &s->last_displayed_entry;
7216 ste = &s->selected_entry;
7218 if (*fte != NULL) {
7219 first = got_tree_entry_get_index(*fte);
7220 first += off; /* account for ".." */
7222 last = got_tree_entry_get_index(*lte);
7223 last += off;
7225 if (g >= first && g <= last && g - first < nlines) {
7226 s->selected = g - first;
7227 return NULL; /* gline is on the current page */
7230 if (*ste != NULL) {
7231 i = got_tree_entry_get_index(*ste);
7232 i += off;
7235 if (i < g) {
7236 err = tree_scroll_down(view, g - i);
7237 if (err)
7238 return err;
7239 if (got_tree_entry_get_index(*lte) >=
7240 got_object_tree_get_nentries(s->tree) - 1 &&
7241 first + s->selected < g &&
7242 s->selected < s->ndisplayed - 1) {
7243 first = got_tree_entry_get_index(*fte);
7244 first += off;
7245 s->selected = g - first;
7247 } else if (i > g)
7248 tree_scroll_up(s, i - g);
7250 if (g < nlines &&
7251 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7252 s->selected = g - 1;
7254 return NULL;
7257 static const struct got_error *
7258 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7260 const struct got_error *err = NULL;
7261 struct tog_tree_view_state *s = &view->state.tree;
7262 struct got_tree_entry *te;
7263 int n, nscroll = view->nlines - 3;
7265 if (view->gline)
7266 return tree_goto_line(view, nscroll);
7268 switch (ch) {
7269 case 'i':
7270 s->show_ids = !s->show_ids;
7271 view->count = 0;
7272 break;
7273 case 'L':
7274 view->count = 0;
7275 if (!s->selected_entry)
7276 break;
7277 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7278 break;
7279 case 'R':
7280 view->count = 0;
7281 err = view_request_new(new_view, view, TOG_VIEW_REF);
7282 break;
7283 case 'g':
7284 case KEY_HOME:
7285 s->selected = 0;
7286 view->count = 0;
7287 if (s->tree == s->root)
7288 s->first_displayed_entry =
7289 got_object_tree_get_first_entry(s->tree);
7290 else
7291 s->first_displayed_entry = NULL;
7292 break;
7293 case 'G':
7294 case KEY_END: {
7295 int eos = view->nlines - 3;
7297 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7298 --eos; /* border */
7299 s->selected = 0;
7300 view->count = 0;
7301 te = got_object_tree_get_last_entry(s->tree);
7302 for (n = 0; n < eos; n++) {
7303 if (te == NULL) {
7304 if (s->tree != s->root) {
7305 s->first_displayed_entry = NULL;
7306 n++;
7308 break;
7310 s->first_displayed_entry = te;
7311 te = got_tree_entry_get_prev(s->tree, te);
7313 if (n > 0)
7314 s->selected = n - 1;
7315 break;
7317 case 'k':
7318 case KEY_UP:
7319 case CTRL('p'):
7320 if (s->selected > 0) {
7321 s->selected--;
7322 break;
7324 tree_scroll_up(s, 1);
7325 if (s->selected_entry == NULL ||
7326 (s->tree == s->root && s->selected_entry ==
7327 got_object_tree_get_first_entry(s->tree)))
7328 view->count = 0;
7329 break;
7330 case CTRL('u'):
7331 case 'u':
7332 nscroll /= 2;
7333 /* FALL THROUGH */
7334 case KEY_PPAGE:
7335 case CTRL('b'):
7336 case 'b':
7337 if (s->tree == s->root) {
7338 if (got_object_tree_get_first_entry(s->tree) ==
7339 s->first_displayed_entry)
7340 s->selected -= MIN(s->selected, nscroll);
7341 } else {
7342 if (s->first_displayed_entry == NULL)
7343 s->selected -= MIN(s->selected, nscroll);
7345 tree_scroll_up(s, MAX(0, nscroll));
7346 if (s->selected_entry == NULL ||
7347 (s->tree == s->root && s->selected_entry ==
7348 got_object_tree_get_first_entry(s->tree)))
7349 view->count = 0;
7350 break;
7351 case 'j':
7352 case KEY_DOWN:
7353 case CTRL('n'):
7354 if (s->selected < s->ndisplayed - 1) {
7355 s->selected++;
7356 break;
7358 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7359 == NULL) {
7360 /* can't scroll any further */
7361 view->count = 0;
7362 break;
7364 tree_scroll_down(view, 1);
7365 break;
7366 case CTRL('d'):
7367 case 'd':
7368 nscroll /= 2;
7369 /* FALL THROUGH */
7370 case KEY_NPAGE:
7371 case CTRL('f'):
7372 case 'f':
7373 case ' ':
7374 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7375 == NULL) {
7376 /* can't scroll any further; move cursor down */
7377 if (s->selected < s->ndisplayed - 1)
7378 s->selected += MIN(nscroll,
7379 s->ndisplayed - s->selected - 1);
7380 else
7381 view->count = 0;
7382 break;
7384 tree_scroll_down(view, nscroll);
7385 break;
7386 case KEY_ENTER:
7387 case '\r':
7388 case KEY_BACKSPACE:
7389 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7390 struct tog_parent_tree *parent;
7391 /* user selected '..' */
7392 if (s->tree == s->root) {
7393 view->count = 0;
7394 break;
7396 parent = TAILQ_FIRST(&s->parents);
7397 TAILQ_REMOVE(&s->parents, parent,
7398 entry);
7399 got_object_tree_close(s->tree);
7400 s->tree = parent->tree;
7401 s->first_displayed_entry =
7402 parent->first_displayed_entry;
7403 s->selected_entry =
7404 parent->selected_entry;
7405 s->selected = parent->selected;
7406 if (s->selected > view->nlines - 3) {
7407 err = offset_selection_down(view);
7408 if (err)
7409 break;
7411 free(parent);
7412 } else if (S_ISDIR(got_tree_entry_get_mode(
7413 s->selected_entry))) {
7414 struct got_tree_object *subtree;
7415 view->count = 0;
7416 err = got_object_open_as_tree(&subtree, s->repo,
7417 got_tree_entry_get_id(s->selected_entry));
7418 if (err)
7419 break;
7420 err = tree_view_visit_subtree(s, subtree);
7421 if (err) {
7422 got_object_tree_close(subtree);
7423 break;
7425 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7426 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7427 break;
7428 case KEY_RESIZE:
7429 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7430 s->selected = view->nlines - 4;
7431 view->count = 0;
7432 break;
7433 default:
7434 view->count = 0;
7435 break;
7438 return err;
7441 __dead static void
7442 usage_tree(void)
7444 endwin();
7445 fprintf(stderr,
7446 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7447 getprogname());
7448 exit(1);
7451 static const struct got_error *
7452 cmd_tree(int argc, char *argv[])
7454 const struct got_error *error;
7455 struct got_repository *repo = NULL;
7456 struct got_worktree *worktree = NULL;
7457 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7458 struct got_object_id *commit_id = NULL;
7459 struct got_commit_object *commit = NULL;
7460 const char *commit_id_arg = NULL;
7461 char *label = NULL;
7462 struct got_reference *ref = NULL;
7463 const char *head_ref_name = NULL;
7464 int ch;
7465 struct tog_view *view;
7466 int *pack_fds = NULL;
7468 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7469 switch (ch) {
7470 case 'c':
7471 commit_id_arg = optarg;
7472 break;
7473 case 'r':
7474 repo_path = realpath(optarg, NULL);
7475 if (repo_path == NULL)
7476 return got_error_from_errno2("realpath",
7477 optarg);
7478 break;
7479 default:
7480 usage_tree();
7481 /* NOTREACHED */
7485 argc -= optind;
7486 argv += optind;
7488 if (argc > 1)
7489 usage_tree();
7491 error = got_repo_pack_fds_open(&pack_fds);
7492 if (error != NULL)
7493 goto done;
7495 if (repo_path == NULL) {
7496 cwd = getcwd(NULL, 0);
7497 if (cwd == NULL)
7498 return got_error_from_errno("getcwd");
7499 error = got_worktree_open(&worktree, cwd);
7500 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7501 goto done;
7502 if (worktree)
7503 repo_path =
7504 strdup(got_worktree_get_repo_path(worktree));
7505 else
7506 repo_path = strdup(cwd);
7507 if (repo_path == NULL) {
7508 error = got_error_from_errno("strdup");
7509 goto done;
7513 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7514 if (error != NULL)
7515 goto done;
7517 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7518 repo, worktree);
7519 if (error)
7520 goto done;
7522 init_curses();
7524 error = apply_unveil(got_repo_get_path(repo), NULL);
7525 if (error)
7526 goto done;
7528 error = tog_load_refs(repo, 0);
7529 if (error)
7530 goto done;
7532 if (commit_id_arg == NULL) {
7533 error = got_repo_match_object_id(&commit_id, &label,
7534 worktree ? got_worktree_get_head_ref_name(worktree) :
7535 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7536 if (error)
7537 goto done;
7538 head_ref_name = label;
7539 } else {
7540 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7541 if (error == NULL)
7542 head_ref_name = got_ref_get_name(ref);
7543 else if (error->code != GOT_ERR_NOT_REF)
7544 goto done;
7545 error = got_repo_match_object_id(&commit_id, NULL,
7546 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7547 if (error)
7548 goto done;
7551 error = got_object_open_as_commit(&commit, repo, commit_id);
7552 if (error)
7553 goto done;
7555 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7556 if (view == NULL) {
7557 error = got_error_from_errno("view_open");
7558 goto done;
7560 error = open_tree_view(view, commit_id, head_ref_name, repo);
7561 if (error)
7562 goto done;
7563 if (!got_path_is_root_dir(in_repo_path)) {
7564 error = tree_view_walk_path(&view->state.tree, commit,
7565 in_repo_path);
7566 if (error)
7567 goto done;
7570 if (worktree) {
7571 /* Release work tree lock. */
7572 got_worktree_close(worktree);
7573 worktree = NULL;
7575 error = view_loop(view);
7576 done:
7577 free(repo_path);
7578 free(cwd);
7579 free(commit_id);
7580 free(label);
7581 if (ref)
7582 got_ref_close(ref);
7583 if (repo) {
7584 const struct got_error *close_err = got_repo_close(repo);
7585 if (error == NULL)
7586 error = close_err;
7588 if (pack_fds) {
7589 const struct got_error *pack_err =
7590 got_repo_pack_fds_close(pack_fds);
7591 if (error == NULL)
7592 error = pack_err;
7594 tog_free_refs();
7595 return error;
7598 static const struct got_error *
7599 ref_view_load_refs(struct tog_ref_view_state *s)
7601 struct got_reflist_entry *sre;
7602 struct tog_reflist_entry *re;
7604 s->nrefs = 0;
7605 TAILQ_FOREACH(sre, &tog_refs, entry) {
7606 if (strncmp(got_ref_get_name(sre->ref),
7607 "refs/got/", 9) == 0 &&
7608 strncmp(got_ref_get_name(sre->ref),
7609 "refs/got/backup/", 16) != 0)
7610 continue;
7612 re = malloc(sizeof(*re));
7613 if (re == NULL)
7614 return got_error_from_errno("malloc");
7616 re->ref = got_ref_dup(sre->ref);
7617 if (re->ref == NULL)
7618 return got_error_from_errno("got_ref_dup");
7619 re->idx = s->nrefs++;
7620 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7623 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7624 return NULL;
7627 static void
7628 ref_view_free_refs(struct tog_ref_view_state *s)
7630 struct tog_reflist_entry *re;
7632 while (!TAILQ_EMPTY(&s->refs)) {
7633 re = TAILQ_FIRST(&s->refs);
7634 TAILQ_REMOVE(&s->refs, re, entry);
7635 got_ref_close(re->ref);
7636 free(re);
7640 static const struct got_error *
7641 open_ref_view(struct tog_view *view, struct got_repository *repo)
7643 const struct got_error *err = NULL;
7644 struct tog_ref_view_state *s = &view->state.ref;
7646 s->selected_entry = 0;
7647 s->repo = repo;
7649 TAILQ_INIT(&s->refs);
7650 STAILQ_INIT(&s->colors);
7652 err = ref_view_load_refs(s);
7653 if (err)
7654 return err;
7656 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7657 err = add_color(&s->colors, "^refs/heads/",
7658 TOG_COLOR_REFS_HEADS,
7659 get_color_value("TOG_COLOR_REFS_HEADS"));
7660 if (err)
7661 goto done;
7663 err = add_color(&s->colors, "^refs/tags/",
7664 TOG_COLOR_REFS_TAGS,
7665 get_color_value("TOG_COLOR_REFS_TAGS"));
7666 if (err)
7667 goto done;
7669 err = add_color(&s->colors, "^refs/remotes/",
7670 TOG_COLOR_REFS_REMOTES,
7671 get_color_value("TOG_COLOR_REFS_REMOTES"));
7672 if (err)
7673 goto done;
7675 err = add_color(&s->colors, "^refs/got/backup/",
7676 TOG_COLOR_REFS_BACKUP,
7677 get_color_value("TOG_COLOR_REFS_BACKUP"));
7678 if (err)
7679 goto done;
7682 view->show = show_ref_view;
7683 view->input = input_ref_view;
7684 view->close = close_ref_view;
7685 view->search_start = search_start_ref_view;
7686 view->search_next = search_next_ref_view;
7687 done:
7688 if (err)
7689 free_colors(&s->colors);
7690 return err;
7693 static const struct got_error *
7694 close_ref_view(struct tog_view *view)
7696 struct tog_ref_view_state *s = &view->state.ref;
7698 ref_view_free_refs(s);
7699 free_colors(&s->colors);
7701 return NULL;
7704 static const struct got_error *
7705 resolve_reflist_entry(struct got_object_id **commit_id,
7706 struct tog_reflist_entry *re, struct got_repository *repo)
7708 const struct got_error *err = NULL;
7709 struct got_object_id *obj_id;
7710 struct got_tag_object *tag = NULL;
7711 int obj_type;
7713 *commit_id = NULL;
7715 err = got_ref_resolve(&obj_id, repo, re->ref);
7716 if (err)
7717 return err;
7719 err = got_object_get_type(&obj_type, repo, obj_id);
7720 if (err)
7721 goto done;
7723 switch (obj_type) {
7724 case GOT_OBJ_TYPE_COMMIT:
7725 *commit_id = obj_id;
7726 break;
7727 case GOT_OBJ_TYPE_TAG:
7728 err = got_object_open_as_tag(&tag, repo, obj_id);
7729 if (err)
7730 goto done;
7731 free(obj_id);
7732 err = got_object_get_type(&obj_type, repo,
7733 got_object_tag_get_object_id(tag));
7734 if (err)
7735 goto done;
7736 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7737 err = got_error(GOT_ERR_OBJ_TYPE);
7738 goto done;
7740 *commit_id = got_object_id_dup(
7741 got_object_tag_get_object_id(tag));
7742 if (*commit_id == NULL) {
7743 err = got_error_from_errno("got_object_id_dup");
7744 goto done;
7746 break;
7747 default:
7748 err = got_error(GOT_ERR_OBJ_TYPE);
7749 break;
7752 done:
7753 if (tag)
7754 got_object_tag_close(tag);
7755 if (err) {
7756 free(*commit_id);
7757 *commit_id = NULL;
7759 return err;
7762 static const struct got_error *
7763 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7764 struct tog_reflist_entry *re, struct got_repository *repo)
7766 struct tog_view *log_view;
7767 const struct got_error *err = NULL;
7768 struct got_object_id *commit_id = NULL;
7770 *new_view = NULL;
7772 err = resolve_reflist_entry(&commit_id, re, repo);
7773 if (err) {
7774 if (err->code != GOT_ERR_OBJ_TYPE)
7775 return err;
7776 else
7777 return NULL;
7780 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7781 if (log_view == NULL) {
7782 err = got_error_from_errno("view_open");
7783 goto done;
7786 err = open_log_view(log_view, commit_id, repo,
7787 got_ref_get_name(re->ref), "", 0);
7788 done:
7789 if (err)
7790 view_close(log_view);
7791 else
7792 *new_view = log_view;
7793 free(commit_id);
7794 return err;
7797 static void
7798 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7800 struct tog_reflist_entry *re;
7801 int i = 0;
7803 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7804 return;
7806 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7807 while (i++ < maxscroll) {
7808 if (re == NULL)
7809 break;
7810 s->first_displayed_entry = re;
7811 re = TAILQ_PREV(re, tog_reflist_head, entry);
7815 static const struct got_error *
7816 ref_scroll_down(struct tog_view *view, int maxscroll)
7818 struct tog_ref_view_state *s = &view->state.ref;
7819 struct tog_reflist_entry *next, *last;
7820 int n = 0;
7822 if (s->first_displayed_entry)
7823 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7824 else
7825 next = TAILQ_FIRST(&s->refs);
7827 last = s->last_displayed_entry;
7828 while (next && n++ < maxscroll) {
7829 if (last) {
7830 s->last_displayed_entry = last;
7831 last = TAILQ_NEXT(last, entry);
7833 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7834 s->first_displayed_entry = next;
7835 next = TAILQ_NEXT(next, entry);
7839 return NULL;
7842 static const struct got_error *
7843 search_start_ref_view(struct tog_view *view)
7845 struct tog_ref_view_state *s = &view->state.ref;
7847 s->matched_entry = NULL;
7848 return NULL;
7851 static int
7852 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7854 regmatch_t regmatch;
7856 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7857 0) == 0;
7860 static const struct got_error *
7861 search_next_ref_view(struct tog_view *view)
7863 struct tog_ref_view_state *s = &view->state.ref;
7864 struct tog_reflist_entry *re = NULL;
7866 if (!view->searching) {
7867 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7868 return NULL;
7871 if (s->matched_entry) {
7872 if (view->searching == TOG_SEARCH_FORWARD) {
7873 if (s->selected_entry)
7874 re = TAILQ_NEXT(s->selected_entry, entry);
7875 else
7876 re = TAILQ_PREV(s->selected_entry,
7877 tog_reflist_head, entry);
7878 } else {
7879 if (s->selected_entry == NULL)
7880 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7881 else
7882 re = TAILQ_PREV(s->selected_entry,
7883 tog_reflist_head, entry);
7885 } else {
7886 if (s->selected_entry)
7887 re = s->selected_entry;
7888 else if (view->searching == TOG_SEARCH_FORWARD)
7889 re = TAILQ_FIRST(&s->refs);
7890 else
7891 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7894 while (1) {
7895 if (re == NULL) {
7896 if (s->matched_entry == NULL) {
7897 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7898 return NULL;
7900 if (view->searching == TOG_SEARCH_FORWARD)
7901 re = TAILQ_FIRST(&s->refs);
7902 else
7903 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7906 if (match_reflist_entry(re, &view->regex)) {
7907 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7908 s->matched_entry = re;
7909 break;
7912 if (view->searching == TOG_SEARCH_FORWARD)
7913 re = TAILQ_NEXT(re, entry);
7914 else
7915 re = TAILQ_PREV(re, tog_reflist_head, entry);
7918 if (s->matched_entry) {
7919 s->first_displayed_entry = s->matched_entry;
7920 s->selected = 0;
7923 return NULL;
7926 static const struct got_error *
7927 show_ref_view(struct tog_view *view)
7929 const struct got_error *err = NULL;
7930 struct tog_ref_view_state *s = &view->state.ref;
7931 struct tog_reflist_entry *re;
7932 char *line = NULL;
7933 wchar_t *wline;
7934 struct tog_color *tc;
7935 int width, n;
7936 int limit = view->nlines;
7938 werase(view->window);
7940 s->ndisplayed = 0;
7941 if (view_is_hsplit_top(view))
7942 --limit; /* border */
7944 if (limit == 0)
7945 return NULL;
7947 re = s->first_displayed_entry;
7949 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7950 s->nrefs) == -1)
7951 return got_error_from_errno("asprintf");
7953 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7954 if (err) {
7955 free(line);
7956 return err;
7958 if (view_needs_focus_indication(view))
7959 wstandout(view->window);
7960 waddwstr(view->window, wline);
7961 while (width++ < view->ncols)
7962 waddch(view->window, ' ');
7963 if (view_needs_focus_indication(view))
7964 wstandend(view->window);
7965 free(wline);
7966 wline = NULL;
7967 free(line);
7968 line = NULL;
7969 if (--limit <= 0)
7970 return NULL;
7972 n = 0;
7973 while (re && limit > 0) {
7974 char *line = NULL;
7975 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7977 if (s->show_date) {
7978 struct got_commit_object *ci;
7979 struct got_tag_object *tag;
7980 struct got_object_id *id;
7981 struct tm tm;
7982 time_t t;
7984 err = got_ref_resolve(&id, s->repo, re->ref);
7985 if (err)
7986 return err;
7987 err = got_object_open_as_tag(&tag, s->repo, id);
7988 if (err) {
7989 if (err->code != GOT_ERR_OBJ_TYPE) {
7990 free(id);
7991 return err;
7993 err = got_object_open_as_commit(&ci, s->repo,
7994 id);
7995 if (err) {
7996 free(id);
7997 return err;
7999 t = got_object_commit_get_committer_time(ci);
8000 got_object_commit_close(ci);
8001 } else {
8002 t = got_object_tag_get_tagger_time(tag);
8003 got_object_tag_close(tag);
8005 free(id);
8006 if (gmtime_r(&t, &tm) == NULL)
8007 return got_error_from_errno("gmtime_r");
8008 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8009 return got_error(GOT_ERR_NO_SPACE);
8011 if (got_ref_is_symbolic(re->ref)) {
8012 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8013 ymd : "", got_ref_get_name(re->ref),
8014 got_ref_get_symref_target(re->ref)) == -1)
8015 return got_error_from_errno("asprintf");
8016 } else if (s->show_ids) {
8017 struct got_object_id *id;
8018 char *id_str;
8019 err = got_ref_resolve(&id, s->repo, re->ref);
8020 if (err)
8021 return err;
8022 err = got_object_id_str(&id_str, id);
8023 if (err) {
8024 free(id);
8025 return err;
8027 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8028 got_ref_get_name(re->ref), id_str) == -1) {
8029 err = got_error_from_errno("asprintf");
8030 free(id);
8031 free(id_str);
8032 return err;
8034 free(id);
8035 free(id_str);
8036 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8037 got_ref_get_name(re->ref)) == -1)
8038 return got_error_from_errno("asprintf");
8040 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
8041 0, 0);
8042 if (err) {
8043 free(line);
8044 return err;
8046 if (n == s->selected) {
8047 if (view->focussed)
8048 wstandout(view->window);
8049 s->selected_entry = re;
8051 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8052 if (tc)
8053 wattr_on(view->window,
8054 COLOR_PAIR(tc->colorpair), NULL);
8055 waddwstr(view->window, wline);
8056 if (tc)
8057 wattr_off(view->window,
8058 COLOR_PAIR(tc->colorpair), NULL);
8059 if (width < view->ncols - 1)
8060 waddch(view->window, '\n');
8061 if (n == s->selected && view->focussed)
8062 wstandend(view->window);
8063 free(line);
8064 free(wline);
8065 wline = NULL;
8066 n++;
8067 s->ndisplayed++;
8068 s->last_displayed_entry = re;
8070 limit--;
8071 re = TAILQ_NEXT(re, entry);
8074 view_border(view);
8075 return err;
8078 static const struct got_error *
8079 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8080 struct tog_reflist_entry *re, struct got_repository *repo)
8082 const struct got_error *err = NULL;
8083 struct got_object_id *commit_id = NULL;
8084 struct tog_view *tree_view;
8086 *new_view = NULL;
8088 err = resolve_reflist_entry(&commit_id, re, repo);
8089 if (err) {
8090 if (err->code != GOT_ERR_OBJ_TYPE)
8091 return err;
8092 else
8093 return NULL;
8097 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8098 if (tree_view == NULL) {
8099 err = got_error_from_errno("view_open");
8100 goto done;
8103 err = open_tree_view(tree_view, commit_id,
8104 got_ref_get_name(re->ref), repo);
8105 if (err)
8106 goto done;
8108 *new_view = tree_view;
8109 done:
8110 free(commit_id);
8111 return err;
8114 static const struct got_error *
8115 ref_goto_line(struct tog_view *view, int nlines)
8117 const struct got_error *err = NULL;
8118 struct tog_ref_view_state *s = &view->state.ref;
8119 int g, idx = s->selected_entry->idx;
8121 g = view->gline;
8122 view->gline = 0;
8124 if (g == 0)
8125 g = 1;
8126 else if (g > s->nrefs)
8127 g = s->nrefs;
8129 if (g >= s->first_displayed_entry->idx + 1 &&
8130 g <= s->last_displayed_entry->idx + 1 &&
8131 g - s->first_displayed_entry->idx - 1 < nlines) {
8132 s->selected = g - s->first_displayed_entry->idx - 1;
8133 return NULL;
8136 if (idx + 1 < g) {
8137 err = ref_scroll_down(view, g - idx - 1);
8138 if (err)
8139 return err;
8140 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8141 s->first_displayed_entry->idx + s->selected < g &&
8142 s->selected < s->ndisplayed - 1)
8143 s->selected = g - s->first_displayed_entry->idx - 1;
8144 } else if (idx + 1 > g)
8145 ref_scroll_up(s, idx - g + 1);
8147 if (g < nlines && s->first_displayed_entry->idx == 0)
8148 s->selected = g - 1;
8150 return NULL;
8154 static const struct got_error *
8155 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8157 const struct got_error *err = NULL;
8158 struct tog_ref_view_state *s = &view->state.ref;
8159 struct tog_reflist_entry *re;
8160 int n, nscroll = view->nlines - 1;
8162 if (view->gline)
8163 return ref_goto_line(view, nscroll);
8165 switch (ch) {
8166 case 'i':
8167 s->show_ids = !s->show_ids;
8168 view->count = 0;
8169 break;
8170 case 'm':
8171 s->show_date = !s->show_date;
8172 view->count = 0;
8173 break;
8174 case 'o':
8175 s->sort_by_date = !s->sort_by_date;
8176 view->count = 0;
8177 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8178 got_ref_cmp_by_commit_timestamp_descending :
8179 tog_ref_cmp_by_name, s->repo);
8180 if (err)
8181 break;
8182 got_reflist_object_id_map_free(tog_refs_idmap);
8183 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8184 &tog_refs, s->repo);
8185 if (err)
8186 break;
8187 ref_view_free_refs(s);
8188 err = ref_view_load_refs(s);
8189 break;
8190 case KEY_ENTER:
8191 case '\r':
8192 view->count = 0;
8193 if (!s->selected_entry)
8194 break;
8195 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8196 break;
8197 case 'T':
8198 view->count = 0;
8199 if (!s->selected_entry)
8200 break;
8201 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8202 break;
8203 case 'g':
8204 case KEY_HOME:
8205 s->selected = 0;
8206 view->count = 0;
8207 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8208 break;
8209 case 'G':
8210 case KEY_END: {
8211 int eos = view->nlines - 1;
8213 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8214 --eos; /* border */
8215 s->selected = 0;
8216 view->count = 0;
8217 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8218 for (n = 0; n < eos; n++) {
8219 if (re == NULL)
8220 break;
8221 s->first_displayed_entry = re;
8222 re = TAILQ_PREV(re, tog_reflist_head, entry);
8224 if (n > 0)
8225 s->selected = n - 1;
8226 break;
8228 case 'k':
8229 case KEY_UP:
8230 case CTRL('p'):
8231 if (s->selected > 0) {
8232 s->selected--;
8233 break;
8235 ref_scroll_up(s, 1);
8236 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8237 view->count = 0;
8238 break;
8239 case CTRL('u'):
8240 case 'u':
8241 nscroll /= 2;
8242 /* FALL THROUGH */
8243 case KEY_PPAGE:
8244 case CTRL('b'):
8245 case 'b':
8246 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8247 s->selected -= MIN(nscroll, s->selected);
8248 ref_scroll_up(s, MAX(0, nscroll));
8249 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8250 view->count = 0;
8251 break;
8252 case 'j':
8253 case KEY_DOWN:
8254 case CTRL('n'):
8255 if (s->selected < s->ndisplayed - 1) {
8256 s->selected++;
8257 break;
8259 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8260 /* can't scroll any further */
8261 view->count = 0;
8262 break;
8264 ref_scroll_down(view, 1);
8265 break;
8266 case CTRL('d'):
8267 case 'd':
8268 nscroll /= 2;
8269 /* FALL THROUGH */
8270 case KEY_NPAGE:
8271 case CTRL('f'):
8272 case 'f':
8273 case ' ':
8274 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8275 /* can't scroll any further; move cursor down */
8276 if (s->selected < s->ndisplayed - 1)
8277 s->selected += MIN(nscroll,
8278 s->ndisplayed - s->selected - 1);
8279 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8280 s->selected += s->ndisplayed - s->selected - 1;
8281 view->count = 0;
8282 break;
8284 ref_scroll_down(view, nscroll);
8285 break;
8286 case CTRL('l'):
8287 view->count = 0;
8288 tog_free_refs();
8289 err = tog_load_refs(s->repo, s->sort_by_date);
8290 if (err)
8291 break;
8292 ref_view_free_refs(s);
8293 err = ref_view_load_refs(s);
8294 break;
8295 case KEY_RESIZE:
8296 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8297 s->selected = view->nlines - 2;
8298 break;
8299 default:
8300 view->count = 0;
8301 break;
8304 return err;
8307 __dead static void
8308 usage_ref(void)
8310 endwin();
8311 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8312 getprogname());
8313 exit(1);
8316 static const struct got_error *
8317 cmd_ref(int argc, char *argv[])
8319 const struct got_error *error;
8320 struct got_repository *repo = NULL;
8321 struct got_worktree *worktree = NULL;
8322 char *cwd = NULL, *repo_path = NULL;
8323 int ch;
8324 struct tog_view *view;
8325 int *pack_fds = NULL;
8327 while ((ch = getopt(argc, argv, "r:")) != -1) {
8328 switch (ch) {
8329 case 'r':
8330 repo_path = realpath(optarg, NULL);
8331 if (repo_path == NULL)
8332 return got_error_from_errno2("realpath",
8333 optarg);
8334 break;
8335 default:
8336 usage_ref();
8337 /* NOTREACHED */
8341 argc -= optind;
8342 argv += optind;
8344 if (argc > 1)
8345 usage_ref();
8347 error = got_repo_pack_fds_open(&pack_fds);
8348 if (error != NULL)
8349 goto done;
8351 if (repo_path == NULL) {
8352 cwd = getcwd(NULL, 0);
8353 if (cwd == NULL)
8354 return got_error_from_errno("getcwd");
8355 error = got_worktree_open(&worktree, cwd);
8356 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8357 goto done;
8358 if (worktree)
8359 repo_path =
8360 strdup(got_worktree_get_repo_path(worktree));
8361 else
8362 repo_path = strdup(cwd);
8363 if (repo_path == NULL) {
8364 error = got_error_from_errno("strdup");
8365 goto done;
8369 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8370 if (error != NULL)
8371 goto done;
8373 init_curses();
8375 error = apply_unveil(got_repo_get_path(repo), NULL);
8376 if (error)
8377 goto done;
8379 error = tog_load_refs(repo, 0);
8380 if (error)
8381 goto done;
8383 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8384 if (view == NULL) {
8385 error = got_error_from_errno("view_open");
8386 goto done;
8389 error = open_ref_view(view, repo);
8390 if (error)
8391 goto done;
8393 if (worktree) {
8394 /* Release work tree lock. */
8395 got_worktree_close(worktree);
8396 worktree = NULL;
8398 error = view_loop(view);
8399 done:
8400 free(repo_path);
8401 free(cwd);
8402 if (repo) {
8403 const struct got_error *close_err = got_repo_close(repo);
8404 if (close_err)
8405 error = close_err;
8407 if (pack_fds) {
8408 const struct got_error *pack_err =
8409 got_repo_pack_fds_close(pack_fds);
8410 if (error == NULL)
8411 error = pack_err;
8413 tog_free_refs();
8414 return error;
8417 static const struct got_error*
8418 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8419 const char *str)
8421 size_t len;
8423 if (win == NULL)
8424 win = stdscr;
8426 len = strlen(str);
8427 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8429 if (focus)
8430 wstandout(win);
8431 if (mvwprintw(win, y, x, "%s", str) == ERR)
8432 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8433 if (focus)
8434 wstandend(win);
8436 return NULL;
8439 static const struct got_error *
8440 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8442 off_t *p;
8444 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8445 if (p == NULL) {
8446 free(*line_offsets);
8447 *line_offsets = NULL;
8448 return got_error_from_errno("reallocarray");
8451 *line_offsets = p;
8452 (*line_offsets)[*nlines] = off;
8453 ++(*nlines);
8454 return NULL;
8457 static const struct got_error *
8458 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8460 *ret = 0;
8462 for (;n > 0; --n, ++km) {
8463 char *t0, *t, *k;
8464 size_t len = 1;
8466 if (km->keys == NULL)
8467 continue;
8469 t = t0 = strdup(km->keys);
8470 if (t0 == NULL)
8471 return got_error_from_errno("strdup");
8473 len += strlen(t);
8474 while ((k = strsep(&t, " ")) != NULL)
8475 len += strlen(k) > 1 ? 2 : 0;
8476 free(t0);
8477 *ret = MAX(*ret, len);
8480 return NULL;
8484 * Write keymap section headers, keys, and key info in km to f.
8485 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8486 * wrap control and symbolic keys in guillemets, else use <>.
8488 static const struct got_error *
8489 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8491 int n, len = width;
8493 if (km->keys) {
8494 static const char *u8_glyph[] = {
8495 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8496 "\xe2\x80\xba" /* U+203A (utf8 >) */
8498 char *t0, *t, *k;
8499 int cs, s, first = 1;
8501 cs = got_locale_is_utf8();
8503 t = t0 = strdup(km->keys);
8504 if (t0 == NULL)
8505 return got_error_from_errno("strdup");
8507 len = strlen(km->keys);
8508 while ((k = strsep(&t, " ")) != NULL) {
8509 s = strlen(k) > 1; /* control or symbolic key */
8510 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8511 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8512 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8513 if (n < 0) {
8514 free(t0);
8515 return got_error_from_errno("fprintf");
8517 first = 0;
8518 len += s ? 2 : 0;
8519 *off += n;
8521 free(t0);
8523 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8524 if (n < 0)
8525 return got_error_from_errno("fprintf");
8526 *off += n;
8528 return NULL;
8531 static const struct got_error *
8532 format_help(struct tog_help_view_state *s)
8534 const struct got_error *err = NULL;
8535 off_t off = 0;
8536 int i, max, n, show = s->all;
8537 static const struct tog_key_map km[] = {
8538 #define KEYMAP_(info, type) { NULL, (info), type }
8539 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8540 GENERATE_HELP
8541 #undef KEYMAP_
8542 #undef KEY_
8545 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8546 if (err)
8547 return err;
8549 n = nitems(km);
8550 err = max_key_str(&max, km, n);
8551 if (err)
8552 return err;
8554 for (i = 0; i < n; ++i) {
8555 if (km[i].keys == NULL) {
8556 show = s->all;
8557 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8558 km[i].type == s->type || s->all)
8559 show = 1;
8561 if (show) {
8562 err = format_help_line(&off, s->f, &km[i], max);
8563 if (err)
8564 return err;
8565 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8566 if (err)
8567 return err;
8570 fputc('\n', s->f);
8571 ++off;
8572 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8573 return err;
8576 static const struct got_error *
8577 create_help(struct tog_help_view_state *s)
8579 FILE *f;
8580 const struct got_error *err;
8582 free(s->line_offsets);
8583 s->line_offsets = NULL;
8584 s->nlines = 0;
8586 f = got_opentemp();
8587 if (f == NULL)
8588 return got_error_from_errno("got_opentemp");
8589 s->f = f;
8591 err = format_help(s);
8592 if (err)
8593 return err;
8595 if (s->f && fflush(s->f) != 0)
8596 return got_error_from_errno("fflush");
8598 return NULL;
8601 static const struct got_error *
8602 search_start_help_view(struct tog_view *view)
8604 view->state.help.matched_line = 0;
8605 return NULL;
8608 static void
8609 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8610 size_t *nlines, int **first, int **last, int **match, int **selected)
8612 struct tog_help_view_state *s = &view->state.help;
8614 *f = s->f;
8615 *nlines = s->nlines;
8616 *line_offsets = s->line_offsets;
8617 *match = &s->matched_line;
8618 *first = &s->first_displayed_line;
8619 *last = &s->last_displayed_line;
8620 *selected = &s->selected_line;
8623 static const struct got_error *
8624 show_help_view(struct tog_view *view)
8626 struct tog_help_view_state *s = &view->state.help;
8627 const struct got_error *err;
8628 regmatch_t *regmatch = &view->regmatch;
8629 wchar_t *wline;
8630 char *line;
8631 ssize_t linelen;
8632 size_t linesz = 0;
8633 int width, nprinted = 0, rc = 0;
8634 int eos = view->nlines;
8636 if (view_is_hsplit_top(view))
8637 --eos; /* account for border */
8639 s->lineno = 0;
8640 rewind(s->f);
8641 werase(view->window);
8643 if (view->gline > s->nlines - 1)
8644 view->gline = s->nlines - 1;
8646 err = win_draw_center(view->window, 0, 0, view->ncols,
8647 view_needs_focus_indication(view), "tog help");
8648 if (err)
8649 return err;
8650 if (eos <= 1)
8651 return NULL;
8652 waddstr(view->window, "\n\n");
8653 eos -= 2;
8655 s->eof = 0;
8656 view->maxx = 0;
8657 line = NULL;
8658 while (eos > 0 && nprinted < eos) {
8659 attr_t attr = 0;
8661 linelen = getline(&line, &linesz, s->f);
8662 if (linelen == -1) {
8663 if (!feof(s->f)) {
8664 free(line);
8665 return got_ferror(s->f, GOT_ERR_IO);
8667 s->eof = 1;
8668 break;
8670 if (++s->lineno < s->first_displayed_line)
8671 continue;
8672 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8673 continue;
8674 if (s->lineno == view->hiline)
8675 attr = A_STANDOUT;
8677 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8678 view->x ? 1 : 0);
8679 if (err) {
8680 free(line);
8681 return err;
8683 view->maxx = MAX(view->maxx, width);
8684 free(wline);
8685 wline = NULL;
8687 if (attr)
8688 wattron(view->window, attr);
8689 if (s->first_displayed_line + nprinted == s->matched_line &&
8690 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8691 err = add_matched_line(&width, line, view->ncols - 1, 0,
8692 view->window, view->x, regmatch);
8693 if (err) {
8694 free(line);
8695 return err;
8697 } else {
8698 int skip;
8700 err = format_line(&wline, &width, &skip, line,
8701 view->x, view->ncols - 1, 0, view->x ? 1 : 0);
8702 if (err) {
8703 free(line);
8704 return err;
8706 rc = waddwstr(view->window, &wline[skip]);
8707 free(wline);
8708 wline = NULL;
8709 if (rc == ERR)
8710 return got_error_msg(GOT_ERR_IO, "waddwstr");
8712 if (s->lineno == view->hiline) {
8713 while (width++ < view->ncols)
8714 waddch(view->window, ' ');
8715 } else {
8716 if (width <= view->ncols)
8717 waddch(view->window, '\n');
8719 if (attr)
8720 wattroff(view->window, attr);
8721 if (++nprinted == 1)
8722 s->first_displayed_line = s->lineno;
8724 free(line);
8725 if (nprinted > 0)
8726 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8727 else
8728 s->last_displayed_line = s->first_displayed_line;
8730 view_border(view);
8732 if (s->eof) {
8733 rc = waddnstr(view->window,
8734 "See the tog(1) manual page for full documentation",
8735 view->ncols - 1);
8736 if (rc == ERR)
8737 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8738 } else {
8739 wmove(view->window, view->nlines - 1, 0);
8740 wclrtoeol(view->window);
8741 wstandout(view->window);
8742 rc = waddnstr(view->window, "scroll down for more...",
8743 view->ncols - 1);
8744 if (rc == ERR)
8745 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8746 if (getcurx(view->window) < view->ncols - 6) {
8747 rc = wprintw(view->window, "[%.0f%%]",
8748 100.00 * s->last_displayed_line / s->nlines);
8749 if (rc == ERR)
8750 return got_error_msg(GOT_ERR_IO, "wprintw");
8752 wstandend(view->window);
8755 return NULL;
8758 static const struct got_error *
8759 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8761 struct tog_help_view_state *s = &view->state.help;
8762 const struct got_error *err = NULL;
8763 char *line = NULL;
8764 ssize_t linelen;
8765 size_t linesz = 0;
8766 int eos, nscroll;
8768 eos = nscroll = view->nlines;
8769 if (view_is_hsplit_top(view))
8770 --eos; /* border */
8772 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8774 switch (ch) {
8775 case '0':
8776 view->x = 0;
8777 break;
8778 case '$':
8779 view->x = MAX(view->maxx - view->ncols / 3, 0);
8780 view->count = 0;
8781 break;
8782 case KEY_RIGHT:
8783 case 'l':
8784 if (view->x + view->ncols / 3 < view->maxx)
8785 view->x += 2;
8786 else
8787 view->count = 0;
8788 break;
8789 case KEY_LEFT:
8790 case 'h':
8791 view->x -= MIN(view->x, 2);
8792 if (view->x <= 0)
8793 view->count = 0;
8794 break;
8795 case 'g':
8796 case KEY_HOME:
8797 s->first_displayed_line = 1;
8798 view->count = 0;
8799 break;
8800 case 'G':
8801 case KEY_END:
8802 view->count = 0;
8803 if (s->eof)
8804 break;
8805 s->first_displayed_line = (s->nlines - eos) + 3;
8806 s->eof = 1;
8807 break;
8808 case 'k':
8809 case KEY_UP:
8810 if (s->first_displayed_line > 1)
8811 --s->first_displayed_line;
8812 else
8813 view->count = 0;
8814 break;
8815 case CTRL('u'):
8816 case 'u':
8817 nscroll /= 2;
8818 /* FALL THROUGH */
8819 case KEY_PPAGE:
8820 case CTRL('b'):
8821 case 'b':
8822 if (s->first_displayed_line == 1) {
8823 view->count = 0;
8824 break;
8826 while (--nscroll > 0 && s->first_displayed_line > 1)
8827 s->first_displayed_line--;
8828 break;
8829 case 'j':
8830 case KEY_DOWN:
8831 case CTRL('n'):
8832 if (!s->eof)
8833 ++s->first_displayed_line;
8834 else
8835 view->count = 0;
8836 break;
8837 case CTRL('d'):
8838 case 'd':
8839 nscroll /= 2;
8840 /* FALL THROUGH */
8841 case KEY_NPAGE:
8842 case CTRL('f'):
8843 case 'f':
8844 case ' ':
8845 if (s->eof) {
8846 view->count = 0;
8847 break;
8849 while (!s->eof && --nscroll > 0) {
8850 linelen = getline(&line, &linesz, s->f);
8851 s->first_displayed_line++;
8852 if (linelen == -1) {
8853 if (feof(s->f))
8854 s->eof = 1;
8855 else
8856 err = got_ferror(s->f, GOT_ERR_IO);
8857 break;
8860 free(line);
8861 break;
8862 default:
8863 view->count = 0;
8864 break;
8867 return err;
8870 static const struct got_error *
8871 close_help_view(struct tog_view *view)
8873 struct tog_help_view_state *s = &view->state.help;
8875 free(s->line_offsets);
8876 s->line_offsets = NULL;
8877 if (fclose(s->f) == EOF)
8878 return got_error_from_errno("fclose");
8880 return NULL;
8883 static const struct got_error *
8884 reset_help_view(struct tog_view *view)
8886 struct tog_help_view_state *s = &view->state.help;
8889 if (s->f && fclose(s->f) == EOF)
8890 return got_error_from_errno("fclose");
8892 wclear(view->window);
8893 view->count = 0;
8894 view->x = 0;
8895 s->all = !s->all;
8896 s->first_displayed_line = 1;
8897 s->last_displayed_line = view->nlines;
8898 s->matched_line = 0;
8900 return create_help(s);
8903 static const struct got_error *
8904 open_help_view(struct tog_view *view, struct tog_view *parent)
8906 const struct got_error *err = NULL;
8907 struct tog_help_view_state *s = &view->state.help;
8909 s->type = (enum tog_keymap_type)parent->type;
8910 s->first_displayed_line = 1;
8911 s->last_displayed_line = view->nlines;
8912 s->selected_line = 1;
8914 view->show = show_help_view;
8915 view->input = input_help_view;
8916 view->reset = reset_help_view;
8917 view->close = close_help_view;
8918 view->search_start = search_start_help_view;
8919 view->search_setup = search_setup_help_view;
8920 view->search_next = search_next_view_match;
8922 err = create_help(s);
8923 return err;
8926 static const struct got_error *
8927 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8928 enum tog_view_type request, int y, int x)
8930 const struct got_error *err = NULL;
8932 *new_view = NULL;
8934 switch (request) {
8935 case TOG_VIEW_DIFF:
8936 if (view->type == TOG_VIEW_LOG) {
8937 struct tog_log_view_state *s = &view->state.log;
8939 err = open_diff_view_for_commit(new_view, y, x,
8940 s->selected_entry->commit, s->selected_entry->id,
8941 view, s->repo);
8942 } else
8943 return got_error_msg(GOT_ERR_NOT_IMPL,
8944 "parent/child view pair not supported");
8945 break;
8946 case TOG_VIEW_BLAME:
8947 if (view->type == TOG_VIEW_TREE) {
8948 struct tog_tree_view_state *s = &view->state.tree;
8950 err = blame_tree_entry(new_view, y, x,
8951 s->selected_entry, &s->parents, s->commit_id,
8952 s->repo);
8953 } else
8954 return got_error_msg(GOT_ERR_NOT_IMPL,
8955 "parent/child view pair not supported");
8956 break;
8957 case TOG_VIEW_LOG:
8958 if (view->type == TOG_VIEW_BLAME)
8959 err = log_annotated_line(new_view, y, x,
8960 view->state.blame.repo, view->state.blame.id_to_log);
8961 else if (view->type == TOG_VIEW_TREE)
8962 err = log_selected_tree_entry(new_view, y, x,
8963 &view->state.tree);
8964 else if (view->type == TOG_VIEW_REF)
8965 err = log_ref_entry(new_view, y, x,
8966 view->state.ref.selected_entry,
8967 view->state.ref.repo);
8968 else
8969 return got_error_msg(GOT_ERR_NOT_IMPL,
8970 "parent/child view pair not supported");
8971 break;
8972 case TOG_VIEW_TREE:
8973 if (view->type == TOG_VIEW_LOG)
8974 err = browse_commit_tree(new_view, y, x,
8975 view->state.log.selected_entry,
8976 view->state.log.in_repo_path,
8977 view->state.log.head_ref_name,
8978 view->state.log.repo);
8979 else if (view->type == TOG_VIEW_REF)
8980 err = browse_ref_tree(new_view, y, x,
8981 view->state.ref.selected_entry,
8982 view->state.ref.repo);
8983 else
8984 return got_error_msg(GOT_ERR_NOT_IMPL,
8985 "parent/child view pair not supported");
8986 break;
8987 case TOG_VIEW_REF:
8988 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8989 if (*new_view == NULL)
8990 return got_error_from_errno("view_open");
8991 if (view->type == TOG_VIEW_LOG)
8992 err = open_ref_view(*new_view, view->state.log.repo);
8993 else if (view->type == TOG_VIEW_TREE)
8994 err = open_ref_view(*new_view, view->state.tree.repo);
8995 else
8996 err = got_error_msg(GOT_ERR_NOT_IMPL,
8997 "parent/child view pair not supported");
8998 if (err)
8999 view_close(*new_view);
9000 break;
9001 case TOG_VIEW_HELP:
9002 *new_view = view_open(0, 0, y, x, TOG_VIEW_HELP);
9003 if (*new_view == NULL)
9004 return got_error_from_errno("view_open");
9005 err = open_help_view(*new_view, view);
9006 if (err)
9007 view_close(*new_view);
9008 break;
9009 default:
9010 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9013 return err;
9017 * If view was scrolled down to move the selected line into view when opening a
9018 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9020 static void
9021 offset_selection_up(struct tog_view *view)
9023 switch (view->type) {
9024 case TOG_VIEW_BLAME: {
9025 struct tog_blame_view_state *s = &view->state.blame;
9026 if (s->first_displayed_line == 1) {
9027 s->selected_line = MAX(s->selected_line - view->offset,
9028 1);
9029 break;
9031 if (s->first_displayed_line > view->offset)
9032 s->first_displayed_line -= view->offset;
9033 else
9034 s->first_displayed_line = 1;
9035 s->selected_line += view->offset;
9036 break;
9038 case TOG_VIEW_LOG:
9039 log_scroll_up(&view->state.log, view->offset);
9040 view->state.log.selected += view->offset;
9041 break;
9042 case TOG_VIEW_REF:
9043 ref_scroll_up(&view->state.ref, view->offset);
9044 view->state.ref.selected += view->offset;
9045 break;
9046 case TOG_VIEW_TREE:
9047 tree_scroll_up(&view->state.tree, view->offset);
9048 view->state.tree.selected += view->offset;
9049 break;
9050 default:
9051 break;
9054 view->offset = 0;
9058 * If the selected line is in the section of screen covered by the bottom split,
9059 * scroll down offset lines to move it into view and index its new position.
9061 static const struct got_error *
9062 offset_selection_down(struct tog_view *view)
9064 const struct got_error *err = NULL;
9065 const struct got_error *(*scrolld)(struct tog_view *, int);
9066 int *selected = NULL;
9067 int header, offset;
9069 switch (view->type) {
9070 case TOG_VIEW_BLAME: {
9071 struct tog_blame_view_state *s = &view->state.blame;
9072 header = 3;
9073 scrolld = NULL;
9074 if (s->selected_line > view->nlines - header) {
9075 offset = abs(view->nlines - s->selected_line - header);
9076 s->first_displayed_line += offset;
9077 s->selected_line -= offset;
9078 view->offset = offset;
9080 break;
9082 case TOG_VIEW_LOG: {
9083 struct tog_log_view_state *s = &view->state.log;
9084 scrolld = &log_scroll_down;
9085 header = view_is_parent_view(view) ? 3 : 2;
9086 selected = &s->selected;
9087 break;
9089 case TOG_VIEW_REF: {
9090 struct tog_ref_view_state *s = &view->state.ref;
9091 scrolld = &ref_scroll_down;
9092 header = 3;
9093 selected = &s->selected;
9094 break;
9096 case TOG_VIEW_TREE: {
9097 struct tog_tree_view_state *s = &view->state.tree;
9098 scrolld = &tree_scroll_down;
9099 header = 5;
9100 selected = &s->selected;
9101 break;
9103 default:
9104 selected = NULL;
9105 scrolld = NULL;
9106 header = 0;
9107 break;
9110 if (selected && *selected > view->nlines - header) {
9111 offset = abs(view->nlines - *selected - header);
9112 view->offset = offset;
9113 if (scrolld && offset) {
9114 err = scrolld(view, offset);
9115 *selected -= offset;
9119 return err;
9122 static void
9123 list_commands(FILE *fp)
9125 size_t i;
9127 fprintf(fp, "commands:");
9128 for (i = 0; i < nitems(tog_commands); i++) {
9129 const struct tog_cmd *cmd = &tog_commands[i];
9130 fprintf(fp, " %s", cmd->name);
9132 fputc('\n', fp);
9135 __dead static void
9136 usage(int hflag, int status)
9138 FILE *fp = (status == 0) ? stdout : stderr;
9140 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
9141 getprogname());
9142 if (hflag) {
9143 fprintf(fp, "lazy usage: %s path\n", getprogname());
9144 list_commands(fp);
9146 exit(status);
9149 static char **
9150 make_argv(int argc, ...)
9152 va_list ap;
9153 char **argv;
9154 int i;
9156 va_start(ap, argc);
9158 argv = calloc(argc, sizeof(char *));
9159 if (argv == NULL)
9160 err(1, "calloc");
9161 for (i = 0; i < argc; i++) {
9162 argv[i] = strdup(va_arg(ap, char *));
9163 if (argv[i] == NULL)
9164 err(1, "strdup");
9167 va_end(ap);
9168 return argv;
9172 * Try to convert 'tog path' into a 'tog log path' command.
9173 * The user could simply have mistyped the command rather than knowingly
9174 * provided a path. So check whether argv[0] can in fact be resolved
9175 * to a path in the HEAD commit and print a special error if not.
9176 * This hack is for mpi@ <3
9178 static const struct got_error *
9179 tog_log_with_path(int argc, char *argv[])
9181 const struct got_error *error = NULL, *close_err;
9182 const struct tog_cmd *cmd = NULL;
9183 struct got_repository *repo = NULL;
9184 struct got_worktree *worktree = NULL;
9185 struct got_object_id *commit_id = NULL, *id = NULL;
9186 struct got_commit_object *commit = NULL;
9187 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9188 char *commit_id_str = NULL, **cmd_argv = NULL;
9189 int *pack_fds = NULL;
9191 cwd = getcwd(NULL, 0);
9192 if (cwd == NULL)
9193 return got_error_from_errno("getcwd");
9195 error = got_repo_pack_fds_open(&pack_fds);
9196 if (error != NULL)
9197 goto done;
9199 error = got_worktree_open(&worktree, cwd);
9200 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9201 goto done;
9203 if (worktree)
9204 repo_path = strdup(got_worktree_get_repo_path(worktree));
9205 else
9206 repo_path = strdup(cwd);
9207 if (repo_path == NULL) {
9208 error = got_error_from_errno("strdup");
9209 goto done;
9212 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9213 if (error != NULL)
9214 goto done;
9216 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9217 repo, worktree);
9218 if (error)
9219 goto done;
9221 error = tog_load_refs(repo, 0);
9222 if (error)
9223 goto done;
9224 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9225 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9226 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9227 if (error)
9228 goto done;
9230 if (worktree) {
9231 got_worktree_close(worktree);
9232 worktree = NULL;
9235 error = got_object_open_as_commit(&commit, repo, commit_id);
9236 if (error)
9237 goto done;
9239 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9240 if (error) {
9241 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9242 goto done;
9243 fprintf(stderr, "%s: '%s' is no known command or path\n",
9244 getprogname(), argv[0]);
9245 usage(1, 1);
9246 /* not reached */
9249 error = got_object_id_str(&commit_id_str, commit_id);
9250 if (error)
9251 goto done;
9253 cmd = &tog_commands[0]; /* log */
9254 argc = 4;
9255 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9256 error = cmd->cmd_main(argc, cmd_argv);
9257 done:
9258 if (repo) {
9259 close_err = got_repo_close(repo);
9260 if (error == NULL)
9261 error = close_err;
9263 if (commit)
9264 got_object_commit_close(commit);
9265 if (worktree)
9266 got_worktree_close(worktree);
9267 if (pack_fds) {
9268 const struct got_error *pack_err =
9269 got_repo_pack_fds_close(pack_fds);
9270 if (error == NULL)
9271 error = pack_err;
9273 free(id);
9274 free(commit_id_str);
9275 free(commit_id);
9276 free(cwd);
9277 free(repo_path);
9278 free(in_repo_path);
9279 if (cmd_argv) {
9280 int i;
9281 for (i = 0; i < argc; i++)
9282 free(cmd_argv[i]);
9283 free(cmd_argv);
9285 tog_free_refs();
9286 return error;
9289 int
9290 main(int argc, char *argv[])
9292 const struct got_error *error = NULL;
9293 const struct tog_cmd *cmd = NULL;
9294 int ch, hflag = 0, Vflag = 0;
9295 char **cmd_argv = NULL;
9296 static const struct option longopts[] = {
9297 { "version", no_argument, NULL, 'V' },
9298 { NULL, 0, NULL, 0}
9300 char *diff_algo_str = NULL;
9302 if (!isatty(STDIN_FILENO))
9303 errx(1, "standard input is not a tty");
9305 setlocale(LC_CTYPE, "");
9307 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9308 switch (ch) {
9309 case 'h':
9310 hflag = 1;
9311 break;
9312 case 'V':
9313 Vflag = 1;
9314 break;
9315 default:
9316 usage(hflag, 1);
9317 /* NOTREACHED */
9321 argc -= optind;
9322 argv += optind;
9323 optind = 1;
9324 optreset = 1;
9326 if (Vflag) {
9327 got_version_print_str();
9328 return 0;
9331 #ifndef PROFILE
9332 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9333 NULL) == -1)
9334 err(1, "pledge");
9335 #endif
9337 if (argc == 0) {
9338 if (hflag)
9339 usage(hflag, 0);
9340 /* Build an argument vector which runs a default command. */
9341 cmd = &tog_commands[0];
9342 argc = 1;
9343 cmd_argv = make_argv(argc, cmd->name);
9344 } else {
9345 size_t i;
9347 /* Did the user specify a command? */
9348 for (i = 0; i < nitems(tog_commands); i++) {
9349 if (strncmp(tog_commands[i].name, argv[0],
9350 strlen(argv[0])) == 0) {
9351 cmd = &tog_commands[i];
9352 break;
9357 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9358 if (diff_algo_str) {
9359 if (strcasecmp(diff_algo_str, "patience") == 0)
9360 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9361 if (strcasecmp(diff_algo_str, "myers") == 0)
9362 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9365 if (cmd == NULL) {
9366 if (argc != 1)
9367 usage(0, 1);
9368 /* No command specified; try log with a path */
9369 error = tog_log_with_path(argc, argv);
9370 } else {
9371 if (hflag)
9372 cmd->cmd_usage();
9373 else
9374 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9377 endwin();
9378 putchar('\n');
9379 if (cmd_argv) {
9380 int i;
9381 for (i = 0; i < argc; i++)
9382 free(cmd_argv[i]);
9383 free(cmd_argv);
9386 if (error && error->code != GOT_ERR_CANCELLED)
9387 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9388 return 0;