Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <getopt.h>
33 #include <string.h>
34 #include <err.h>
35 #include <unistd.h>
36 #include <limits.h>
37 #include <wchar.h>
38 #include <time.h>
39 #include <pthread.h>
40 #include <libgen.h>
41 #include <regex.h>
42 #include <sched.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_diff.h"
50 #include "got_opentemp.h"
51 #include "got_utf8.h"
52 #include "got_cancel.h"
53 #include "got_commit_graph.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_path.h"
57 #include "got_worktree.h"
59 #ifndef MIN
60 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
61 #endif
63 #ifndef MAX
64 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
65 #endif
67 #define CTRL(x) ((x) & 0x1f)
69 #ifndef nitems
70 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
71 #endif
73 struct tog_cmd {
74 const char *name;
75 const struct got_error *(*cmd_main)(int, char *[]);
76 void (*cmd_usage)(void);
77 };
79 __dead static void usage(int, int);
80 __dead static void usage_log(void);
81 __dead static void usage_diff(void);
82 __dead static void usage_blame(void);
83 __dead static void usage_tree(void);
84 __dead static void usage_ref(void);
86 static const struct got_error* cmd_log(int, char *[]);
87 static const struct got_error* cmd_diff(int, char *[]);
88 static const struct got_error* cmd_blame(int, char *[]);
89 static const struct got_error* cmd_tree(int, char *[]);
90 static const struct got_error* cmd_ref(int, char *[]);
92 static const struct tog_cmd tog_commands[] = {
93 { "log", cmd_log, usage_log },
94 { "diff", cmd_diff, usage_diff },
95 { "blame", cmd_blame, usage_blame },
96 { "tree", cmd_tree, usage_tree },
97 { "ref", cmd_ref, usage_ref },
98 };
100 enum tog_view_type {
101 TOG_VIEW_DIFF,
102 TOG_VIEW_LOG,
103 TOG_VIEW_BLAME,
104 TOG_VIEW_TREE,
105 TOG_VIEW_REF,
106 TOG_VIEW_HELP
107 };
109 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
110 enum tog_keymap_type {
111 TOG_KEYMAP_KEYS = -2,
112 TOG_KEYMAP_GLOBAL,
113 TOG_KEYMAP_DIFF,
114 TOG_KEYMAP_LOG,
115 TOG_KEYMAP_BLAME,
116 TOG_KEYMAP_TREE,
117 TOG_KEYMAP_REF,
118 TOG_KEYMAP_HELP
119 };
121 enum tog_view_mode {
122 TOG_VIEW_SPLIT_NONE,
123 TOG_VIEW_SPLIT_VERT,
124 TOG_VIEW_SPLIT_HRZN
125 };
127 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
129 #define TOG_EOF_STRING "(END)"
131 struct commit_queue_entry {
132 TAILQ_ENTRY(commit_queue_entry) entry;
133 struct got_object_id *id;
134 struct got_commit_object *commit;
135 int idx;
136 };
137 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
138 struct commit_queue {
139 int ncommits;
140 struct commit_queue_head head;
141 };
143 struct tog_color {
144 STAILQ_ENTRY(tog_color) entry;
145 regex_t regex;
146 short colorpair;
147 };
148 STAILQ_HEAD(tog_colors, tog_color);
150 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
151 static struct got_reflist_object_id_map *tog_refs_idmap;
152 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
154 static const struct got_error *
155 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
156 struct got_reference* re2)
158 const char *name1 = got_ref_get_name(re1);
159 const char *name2 = got_ref_get_name(re2);
160 int isbackup1, isbackup2;
162 /* Sort backup refs towards the bottom of the list. */
163 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
164 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
165 if (!isbackup1 && isbackup2) {
166 *cmp = -1;
167 return NULL;
168 } else if (isbackup1 && !isbackup2) {
169 *cmp = 1;
170 return NULL;
173 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
174 return NULL;
177 static const struct got_error *
178 tog_load_refs(struct got_repository *repo, int sort_by_date)
180 const struct got_error *err;
182 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
183 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
184 repo);
185 if (err)
186 return err;
188 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
189 repo);
192 static void
193 tog_free_refs(void)
195 if (tog_refs_idmap) {
196 got_reflist_object_id_map_free(tog_refs_idmap);
197 tog_refs_idmap = NULL;
199 got_ref_list_free(&tog_refs);
202 static const struct got_error *
203 add_color(struct tog_colors *colors, const char *pattern,
204 int idx, short color)
206 const struct got_error *err = NULL;
207 struct tog_color *tc;
208 int regerr = 0;
210 if (idx < 1 || idx > COLOR_PAIRS - 1)
211 return NULL;
213 init_pair(idx, color, -1);
215 tc = calloc(1, sizeof(*tc));
216 if (tc == NULL)
217 return got_error_from_errno("calloc");
218 regerr = regcomp(&tc->regex, pattern,
219 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
220 if (regerr) {
221 static char regerr_msg[512];
222 static char err_msg[512];
223 regerror(regerr, &tc->regex, regerr_msg,
224 sizeof(regerr_msg));
225 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
226 regerr_msg);
227 err = got_error_msg(GOT_ERR_REGEX, err_msg);
228 free(tc);
229 return err;
231 tc->colorpair = idx;
232 STAILQ_INSERT_HEAD(colors, tc, entry);
233 return NULL;
236 static void
237 free_colors(struct tog_colors *colors)
239 struct tog_color *tc;
241 while (!STAILQ_EMPTY(colors)) {
242 tc = STAILQ_FIRST(colors);
243 STAILQ_REMOVE_HEAD(colors, entry);
244 regfree(&tc->regex);
245 free(tc);
249 static struct tog_color *
250 get_color(struct tog_colors *colors, int colorpair)
252 struct tog_color *tc = NULL;
254 STAILQ_FOREACH(tc, colors, entry) {
255 if (tc->colorpair == colorpair)
256 return tc;
259 return NULL;
262 static int
263 default_color_value(const char *envvar)
265 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
266 return COLOR_MAGENTA;
267 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
268 return COLOR_CYAN;
269 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
270 return COLOR_YELLOW;
271 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
272 return COLOR_GREEN;
273 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
274 return COLOR_MAGENTA;
275 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
276 return COLOR_MAGENTA;
277 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
278 return COLOR_CYAN;
279 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
280 return COLOR_GREEN;
281 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
282 return COLOR_GREEN;
283 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
284 return COLOR_CYAN;
285 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
286 return COLOR_YELLOW;
287 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
288 return COLOR_GREEN;
289 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
290 return COLOR_MAGENTA;
291 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
292 return COLOR_YELLOW;
293 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
294 return COLOR_CYAN;
296 return -1;
299 static int
300 get_color_value(const char *envvar)
302 const char *val = getenv(envvar);
304 if (val == NULL)
305 return default_color_value(envvar);
307 if (strcasecmp(val, "black") == 0)
308 return COLOR_BLACK;
309 if (strcasecmp(val, "red") == 0)
310 return COLOR_RED;
311 if (strcasecmp(val, "green") == 0)
312 return COLOR_GREEN;
313 if (strcasecmp(val, "yellow") == 0)
314 return COLOR_YELLOW;
315 if (strcasecmp(val, "blue") == 0)
316 return COLOR_BLUE;
317 if (strcasecmp(val, "magenta") == 0)
318 return COLOR_MAGENTA;
319 if (strcasecmp(val, "cyan") == 0)
320 return COLOR_CYAN;
321 if (strcasecmp(val, "white") == 0)
322 return COLOR_WHITE;
323 if (strcasecmp(val, "default") == 0)
324 return -1;
326 return default_color_value(envvar);
329 struct tog_diff_view_state {
330 struct got_object_id *id1, *id2;
331 const char *label1, *label2;
332 FILE *f, *f1, *f2;
333 int fd1, fd2;
334 int lineno;
335 int first_displayed_line;
336 int last_displayed_line;
337 int eof;
338 int diff_context;
339 int ignore_whitespace;
340 int force_text_diff;
341 struct got_repository *repo;
342 struct got_diff_line *lines;
343 size_t nlines;
344 int matched_line;
345 int selected_line;
347 /* passed from log or blame view; may be NULL */
348 struct tog_view *parent_view;
349 };
351 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
352 static volatile sig_atomic_t tog_thread_error;
354 struct tog_log_thread_args {
355 pthread_cond_t need_commits;
356 pthread_cond_t commit_loaded;
357 int commits_needed;
358 int load_all;
359 struct got_commit_graph *graph;
360 struct commit_queue *real_commits;
361 const char *in_repo_path;
362 struct got_object_id *start_id;
363 struct got_repository *repo;
364 int *pack_fds;
365 int log_complete;
366 sig_atomic_t *quit;
367 struct commit_queue_entry **first_displayed_entry;
368 struct commit_queue_entry **selected_entry;
369 int *searching;
370 int *search_next_done;
371 regex_t *regex;
372 int *limiting;
373 int limit_match;
374 regex_t *limit_regex;
375 struct commit_queue *limit_commits;
376 };
378 struct tog_log_view_state {
379 struct commit_queue *commits;
380 struct commit_queue_entry *first_displayed_entry;
381 struct commit_queue_entry *last_displayed_entry;
382 struct commit_queue_entry *selected_entry;
383 struct commit_queue real_commits;
384 int selected;
385 char *in_repo_path;
386 char *head_ref_name;
387 int log_branches;
388 struct got_repository *repo;
389 struct got_object_id *start_id;
390 sig_atomic_t quit;
391 pthread_t thread;
392 struct tog_log_thread_args thread_args;
393 struct commit_queue_entry *matched_entry;
394 struct commit_queue_entry *search_entry;
395 struct tog_colors colors;
396 int use_committer;
397 int limit_view;
398 regex_t limit_regex;
399 struct commit_queue limit_commits;
400 };
402 #define TOG_COLOR_DIFF_MINUS 1
403 #define TOG_COLOR_DIFF_PLUS 2
404 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
405 #define TOG_COLOR_DIFF_META 4
406 #define TOG_COLOR_TREE_SUBMODULE 5
407 #define TOG_COLOR_TREE_SYMLINK 6
408 #define TOG_COLOR_TREE_DIRECTORY 7
409 #define TOG_COLOR_TREE_EXECUTABLE 8
410 #define TOG_COLOR_COMMIT 9
411 #define TOG_COLOR_AUTHOR 10
412 #define TOG_COLOR_DATE 11
413 #define TOG_COLOR_REFS_HEADS 12
414 #define TOG_COLOR_REFS_TAGS 13
415 #define TOG_COLOR_REFS_REMOTES 14
416 #define TOG_COLOR_REFS_BACKUP 15
418 struct tog_blame_cb_args {
419 struct tog_blame_line *lines; /* one per line */
420 int nlines;
422 struct tog_view *view;
423 struct got_object_id *commit_id;
424 int *quit;
425 };
427 struct tog_blame_thread_args {
428 const char *path;
429 struct got_repository *repo;
430 struct tog_blame_cb_args *cb_args;
431 int *complete;
432 got_cancel_cb cancel_cb;
433 void *cancel_arg;
434 };
436 struct tog_blame {
437 FILE *f;
438 off_t filesize;
439 struct tog_blame_line *lines;
440 int nlines;
441 off_t *line_offsets;
442 pthread_t thread;
443 struct tog_blame_thread_args thread_args;
444 struct tog_blame_cb_args cb_args;
445 const char *path;
446 int *pack_fds;
447 };
449 struct tog_blame_view_state {
450 int first_displayed_line;
451 int last_displayed_line;
452 int selected_line;
453 int last_diffed_line;
454 int blame_complete;
455 int eof;
456 int done;
457 struct got_object_id_queue blamed_commits;
458 struct got_object_qid *blamed_commit;
459 char *path;
460 struct got_repository *repo;
461 struct got_object_id *commit_id;
462 struct got_object_id *id_to_log;
463 struct tog_blame blame;
464 int matched_line;
465 struct tog_colors colors;
466 };
468 struct tog_parent_tree {
469 TAILQ_ENTRY(tog_parent_tree) entry;
470 struct got_tree_object *tree;
471 struct got_tree_entry *first_displayed_entry;
472 struct got_tree_entry *selected_entry;
473 int selected;
474 };
476 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
478 struct tog_tree_view_state {
479 char *tree_label;
480 struct got_object_id *commit_id;/* commit which this tree belongs to */
481 struct got_tree_object *root; /* the commit's root tree entry */
482 struct got_tree_object *tree; /* currently displayed (sub-)tree */
483 struct got_tree_entry *first_displayed_entry;
484 struct got_tree_entry *last_displayed_entry;
485 struct got_tree_entry *selected_entry;
486 int ndisplayed, selected, show_ids;
487 struct tog_parent_trees parents; /* parent trees of current sub-tree */
488 char *head_ref_name;
489 struct got_repository *repo;
490 struct got_tree_entry *matched_entry;
491 struct tog_colors colors;
492 };
494 struct tog_reflist_entry {
495 TAILQ_ENTRY(tog_reflist_entry) entry;
496 struct got_reference *ref;
497 int idx;
498 };
500 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
502 struct tog_ref_view_state {
503 struct tog_reflist_head refs;
504 struct tog_reflist_entry *first_displayed_entry;
505 struct tog_reflist_entry *last_displayed_entry;
506 struct tog_reflist_entry *selected_entry;
507 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
508 struct got_repository *repo;
509 struct tog_reflist_entry *matched_entry;
510 struct tog_colors colors;
511 };
513 struct tog_help_view_state {
514 FILE *f;
515 off_t *line_offsets;
516 size_t nlines;
517 int lineno;
518 int first_displayed_line;
519 int last_displayed_line;
520 int eof;
521 int matched_line;
522 int selected_line;
523 int all;
524 enum tog_keymap_type type;
525 };
527 #define GENERATE_HELP \
528 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
529 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
530 KEY_("k C-p Up", "Move cursor or page up one line"), \
531 KEY_("j C-n Down", "Move cursor or page down one line"), \
532 KEY_("C-b b PgUp", "Scroll the view up one page"), \
533 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
534 KEY_("C-u u", "Scroll the view up one half page"), \
535 KEY_("C-d d", "Scroll the view down one half page"), \
536 KEY_("g Home", "Go to line N (default: first line)"), \
537 KEY_("G End", "Go to line N (default: last line)"), \
538 KEY_("l Right", "Scroll the view right"), \
539 KEY_("h Left", "Scroll the view left"), \
540 KEY_("$", "Scroll view to the rightmost position"), \
541 KEY_("0", "Scroll view to the leftmost position"), \
542 KEY_("-", "Decrease size of the focussed split"), \
543 KEY_("+", "Increase size of the focussed split"), \
544 KEY_("Tab", "Switch focus between views"), \
545 KEY_("F", "Toggle fullscreen mode"), \
546 KEY_("/", "Open prompt to enter search term"), \
547 KEY_("n", "Find next line/token matching the current search term"), \
548 KEY_("N", "Find previous line/token matching the current search term"),\
549 KEY_("q", "Quit the focussed view; Quit help screen"), \
550 KEY_("Q", "Quit tog"), \
552 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
553 KEY_("< ,", "Move cursor up one commit"), \
554 KEY_("> .", "Move cursor down one commit"), \
555 KEY_("Enter", "Open diff view of the selected commit"), \
556 KEY_("B", "Reload the log view and toggle display of merged commits"), \
557 KEY_("R", "Open ref view of all repository references"), \
558 KEY_("T", "Display tree view of the repository from the selected" \
559 " commit"), \
560 KEY_("@", "Toggle between displaying author and committer name"), \
561 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
562 KEY_("C-g Backspace", "Cancel current search or log operation"), \
563 KEY_("C-l", "Reload the log view with new commits in the repository"), \
565 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
566 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
567 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
568 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
569 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
570 " data"), \
571 KEY_("(", "Go to the previous file in the diff"), \
572 KEY_(")", "Go to the next file in the diff"), \
573 KEY_("{", "Go to the previous hunk in the diff"), \
574 KEY_("}", "Go to the next hunk in the diff"), \
575 KEY_("[", "Decrease the number of context lines"), \
576 KEY_("]", "Increase the number of context lines"), \
577 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
579 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
580 KEY_("Enter", "Display diff view of the selected line's commit"), \
581 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
582 KEY_("L", "Open log view for the currently selected annotated line"), \
583 KEY_("C", "Reload view with the previously blamed commit"), \
584 KEY_("c", "Reload view with the version of the file found in the" \
585 " selected line's commit"), \
586 KEY_("p", "Reload view with the version of the file found in the" \
587 " selected line's parent commit"), \
589 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
590 KEY_("Enter", "Enter selected directory or open blame view of the" \
591 " selected file"), \
592 KEY_("L", "Open log view for the selected entry"), \
593 KEY_("R", "Open ref view of all repository references"), \
594 KEY_("i", "Show object IDs for all tree entries"), \
595 KEY_("Backspace", "Return to the parent directory"), \
597 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
598 KEY_("Enter", "Display log view of the selected reference"), \
599 KEY_("T", "Display tree view of the selected reference"), \
600 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
601 KEY_("m", "Toggle display of last modified date for each reference"), \
602 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
603 KEY_("C-l", "Reload view with all repository references")
605 struct tog_key_map {
606 const char *keys;
607 const char *info;
608 enum tog_keymap_type type;
609 };
611 /*
612 * We implement two types of views: parent views and child views.
614 * The 'Tab' key switches focus between a parent view and its child view.
615 * Child views are shown side-by-side to their parent view, provided
616 * there is enough screen estate.
618 * When a new view is opened from within a parent view, this new view
619 * becomes a child view of the parent view, replacing any existing child.
621 * When a new view is opened from within a child view, this new view
622 * becomes a parent view which will obscure the views below until the
623 * user quits the new parent view by typing 'q'.
625 * This list of views contains parent views only.
626 * Child views are only pointed to by their parent view.
627 */
628 TAILQ_HEAD(tog_view_list_head, tog_view);
630 struct tog_view {
631 TAILQ_ENTRY(tog_view) entry;
632 WINDOW *window;
633 PANEL *panel;
634 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
635 int resized_y, resized_x; /* begin_y/x based on user resizing */
636 int maxx, x; /* max column and current start column */
637 int lines, cols; /* copies of LINES and COLS */
638 int nscrolled, offset; /* lines scrolled and hsplit line offset */
639 int gline, hiline; /* navigate to and highlight this nG line */
640 int ch, count; /* current keymap and count prefix */
641 int resized; /* set when in a resize event */
642 int focussed; /* Only set on one parent or child view at a time. */
643 int dying;
644 struct tog_view *parent;
645 struct tog_view *child;
647 /*
648 * This flag is initially set on parent views when a new child view
649 * is created. It gets toggled when the 'Tab' key switches focus
650 * between parent and child.
651 * The flag indicates whether focus should be passed on to our child
652 * view if this parent view gets picked for focus after another parent
653 * view was closed. This prevents child views from losing focus in such
654 * situations.
655 */
656 int focus_child;
658 enum tog_view_mode mode;
659 /* type-specific state */
660 enum tog_view_type type;
661 union {
662 struct tog_diff_view_state diff;
663 struct tog_log_view_state log;
664 struct tog_blame_view_state blame;
665 struct tog_tree_view_state tree;
666 struct tog_ref_view_state ref;
667 struct tog_help_view_state help;
668 } state;
670 const struct got_error *(*show)(struct tog_view *);
671 const struct got_error *(*input)(struct tog_view **,
672 struct tog_view *, int);
673 const struct got_error *(*reset)(struct tog_view *);
674 const struct got_error *(*resize)(struct tog_view *, int);
675 const struct got_error *(*close)(struct tog_view *);
677 const struct got_error *(*search_start)(struct tog_view *);
678 const struct got_error *(*search_next)(struct tog_view *);
679 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
680 int **, int **, int **, int **);
681 int search_started;
682 int searching;
683 #define TOG_SEARCH_FORWARD 1
684 #define TOG_SEARCH_BACKWARD 2
685 int search_next_done;
686 #define TOG_SEARCH_HAVE_MORE 1
687 #define TOG_SEARCH_NO_MORE 2
688 #define TOG_SEARCH_HAVE_NONE 3
689 regex_t regex;
690 regmatch_t regmatch;
691 };
693 static const struct got_error *open_diff_view(struct tog_view *,
694 struct got_object_id *, struct got_object_id *,
695 const char *, const char *, int, int, int, struct tog_view *,
696 struct got_repository *);
697 static const struct got_error *show_diff_view(struct tog_view *);
698 static const struct got_error *input_diff_view(struct tog_view **,
699 struct tog_view *, int);
700 static const struct got_error *reset_diff_view(struct tog_view *);
701 static const struct got_error* close_diff_view(struct tog_view *);
702 static const struct got_error *search_start_diff_view(struct tog_view *);
703 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
704 size_t *, int **, int **, int **, int **);
705 static const struct got_error *search_next_view_match(struct tog_view *);
707 static const struct got_error *open_log_view(struct tog_view *,
708 struct got_object_id *, struct got_repository *,
709 const char *, const char *, int);
710 static const struct got_error * show_log_view(struct tog_view *);
711 static const struct got_error *input_log_view(struct tog_view **,
712 struct tog_view *, int);
713 static const struct got_error *resize_log_view(struct tog_view *, int);
714 static const struct got_error *close_log_view(struct tog_view *);
715 static const struct got_error *search_start_log_view(struct tog_view *);
716 static const struct got_error *search_next_log_view(struct tog_view *);
718 static const struct got_error *open_blame_view(struct tog_view *, char *,
719 struct got_object_id *, struct got_repository *);
720 static const struct got_error *show_blame_view(struct tog_view *);
721 static const struct got_error *input_blame_view(struct tog_view **,
722 struct tog_view *, int);
723 static const struct got_error *reset_blame_view(struct tog_view *);
724 static const struct got_error *close_blame_view(struct tog_view *);
725 static const struct got_error *search_start_blame_view(struct tog_view *);
726 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
727 size_t *, int **, int **, int **, int **);
729 static const struct got_error *open_tree_view(struct tog_view *,
730 struct got_object_id *, const char *, struct got_repository *);
731 static const struct got_error *show_tree_view(struct tog_view *);
732 static const struct got_error *input_tree_view(struct tog_view **,
733 struct tog_view *, int);
734 static const struct got_error *close_tree_view(struct tog_view *);
735 static const struct got_error *search_start_tree_view(struct tog_view *);
736 static const struct got_error *search_next_tree_view(struct tog_view *);
738 static const struct got_error *open_ref_view(struct tog_view *,
739 struct got_repository *);
740 static const struct got_error *show_ref_view(struct tog_view *);
741 static const struct got_error *input_ref_view(struct tog_view **,
742 struct tog_view *, int);
743 static const struct got_error *close_ref_view(struct tog_view *);
744 static const struct got_error *search_start_ref_view(struct tog_view *);
745 static const struct got_error *search_next_ref_view(struct tog_view *);
747 static const struct got_error *open_help_view(struct tog_view *,
748 struct tog_view *);
749 static const struct got_error *show_help_view(struct tog_view *);
750 static const struct got_error *input_help_view(struct tog_view **,
751 struct tog_view *, int);
752 static const struct got_error *reset_help_view(struct tog_view *);
753 static const struct got_error* close_help_view(struct tog_view *);
754 static const struct got_error *search_start_help_view(struct tog_view *);
755 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
756 size_t *, int **, int **, int **, int **);
758 static volatile sig_atomic_t tog_sigwinch_received;
759 static volatile sig_atomic_t tog_sigpipe_received;
760 static volatile sig_atomic_t tog_sigcont_received;
761 static volatile sig_atomic_t tog_sigint_received;
762 static volatile sig_atomic_t tog_sigterm_received;
764 static void
765 tog_sigwinch(int signo)
767 tog_sigwinch_received = 1;
770 static void
771 tog_sigpipe(int signo)
773 tog_sigpipe_received = 1;
776 static void
777 tog_sigcont(int signo)
779 tog_sigcont_received = 1;
782 static void
783 tog_sigint(int signo)
785 tog_sigint_received = 1;
788 static void
789 tog_sigterm(int signo)
791 tog_sigterm_received = 1;
794 static int
795 tog_fatal_signal_received(void)
797 return (tog_sigpipe_received ||
798 tog_sigint_received || tog_sigterm_received);
801 static const struct got_error *
802 view_close(struct tog_view *view)
804 const struct got_error *err = NULL, *child_err = NULL;
806 if (view->child) {
807 child_err = view_close(view->child);
808 view->child = NULL;
810 if (view->close)
811 err = view->close(view);
812 if (view->panel)
813 del_panel(view->panel);
814 if (view->window)
815 delwin(view->window);
816 free(view);
817 return err ? err : child_err;
820 static struct tog_view *
821 view_open(int nlines, int ncols, int begin_y, int begin_x,
822 enum tog_view_type type)
824 struct tog_view *view = calloc(1, sizeof(*view));
826 if (view == NULL)
827 return NULL;
829 view->type = type;
830 view->lines = LINES;
831 view->cols = COLS;
832 view->nlines = nlines ? nlines : LINES - begin_y;
833 view->ncols = ncols ? ncols : COLS - begin_x;
834 view->begin_y = begin_y;
835 view->begin_x = begin_x;
836 view->window = newwin(nlines, ncols, begin_y, begin_x);
837 if (view->window == NULL) {
838 view_close(view);
839 return NULL;
841 view->panel = new_panel(view->window);
842 if (view->panel == NULL ||
843 set_panel_userptr(view->panel, view) != OK) {
844 view_close(view);
845 return NULL;
848 keypad(view->window, TRUE);
849 return view;
852 static int
853 view_split_begin_x(int begin_x)
855 if (begin_x > 0 || COLS < 120)
856 return 0;
857 return (COLS - MAX(COLS / 2, 80));
860 /* XXX Stub till we decide what to do. */
861 static int
862 view_split_begin_y(int lines)
864 return lines * HSPLIT_SCALE;
867 static const struct got_error *view_resize(struct tog_view *);
869 static const struct got_error *
870 view_splitscreen(struct tog_view *view)
872 const struct got_error *err = NULL;
874 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
875 if (view->resized_y && view->resized_y < view->lines)
876 view->begin_y = view->resized_y;
877 else
878 view->begin_y = view_split_begin_y(view->nlines);
879 view->begin_x = 0;
880 } else if (!view->resized) {
881 if (view->resized_x && view->resized_x < view->cols - 1 &&
882 view->cols > 119)
883 view->begin_x = view->resized_x;
884 else
885 view->begin_x = view_split_begin_x(0);
886 view->begin_y = 0;
888 view->nlines = LINES - view->begin_y;
889 view->ncols = COLS - view->begin_x;
890 view->lines = LINES;
891 view->cols = COLS;
892 err = view_resize(view);
893 if (err)
894 return err;
896 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
897 view->parent->nlines = view->begin_y;
899 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
900 return got_error_from_errno("mvwin");
902 return NULL;
905 static const struct got_error *
906 view_fullscreen(struct tog_view *view)
908 const struct got_error *err = NULL;
910 view->begin_x = 0;
911 view->begin_y = view->resized ? view->begin_y : 0;
912 view->nlines = view->resized ? view->nlines : LINES;
913 view->ncols = COLS;
914 view->lines = LINES;
915 view->cols = COLS;
916 err = view_resize(view);
917 if (err)
918 return err;
920 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
921 return got_error_from_errno("mvwin");
923 return NULL;
926 static int
927 view_is_parent_view(struct tog_view *view)
929 return view->parent == NULL;
932 static int
933 view_is_splitscreen(struct tog_view *view)
935 return view->begin_x > 0 || view->begin_y > 0;
938 static int
939 view_is_fullscreen(struct tog_view *view)
941 return view->nlines == LINES && view->ncols == COLS;
944 static int
945 view_is_hsplit_top(struct tog_view *view)
947 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
948 view_is_splitscreen(view->child);
951 static void
952 view_border(struct tog_view *view)
954 PANEL *panel;
955 const struct tog_view *view_above;
957 if (view->parent)
958 return view_border(view->parent);
960 panel = panel_above(view->panel);
961 if (panel == NULL)
962 return;
964 view_above = panel_userptr(panel);
965 if (view->mode == TOG_VIEW_SPLIT_HRZN)
966 mvwhline(view->window, view_above->begin_y - 1,
967 view->begin_x, got_locale_is_utf8() ?
968 ACS_HLINE : '-', view->ncols);
969 else
970 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
971 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
974 static const struct got_error *view_init_hsplit(struct tog_view *, int);
975 static const struct got_error *request_log_commits(struct tog_view *);
976 static const struct got_error *offset_selection_down(struct tog_view *);
977 static void offset_selection_up(struct tog_view *);
978 static void view_get_split(struct tog_view *, int *, int *);
980 static const struct got_error *
981 view_resize(struct tog_view *view)
983 const struct got_error *err = NULL;
984 int dif, nlines, ncols;
986 dif = LINES - view->lines; /* line difference */
988 if (view->lines > LINES)
989 nlines = view->nlines - (view->lines - LINES);
990 else
991 nlines = view->nlines + (LINES - view->lines);
992 if (view->cols > COLS)
993 ncols = view->ncols - (view->cols - COLS);
994 else
995 ncols = view->ncols + (COLS - view->cols);
997 if (view->child) {
998 int hs = view->child->begin_y;
1000 if (!view_is_fullscreen(view))
1001 view->child->begin_x = view_split_begin_x(view->begin_x);
1002 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1003 view->child->begin_x == 0) {
1004 ncols = COLS;
1006 view_fullscreen(view->child);
1007 if (view->child->focussed)
1008 show_panel(view->child->panel);
1009 else
1010 show_panel(view->panel);
1011 } else {
1012 ncols = view->child->begin_x;
1014 view_splitscreen(view->child);
1015 show_panel(view->child->panel);
1018 * XXX This is ugly and needs to be moved into the above
1019 * logic but "works" for now and my attempts at moving it
1020 * break either 'tab' or 'F' key maps in horizontal splits.
1022 if (hs) {
1023 err = view_splitscreen(view->child);
1024 if (err)
1025 return err;
1026 if (dif < 0) { /* top split decreased */
1027 err = offset_selection_down(view);
1028 if (err)
1029 return err;
1031 view_border(view);
1032 update_panels();
1033 doupdate();
1034 show_panel(view->child->panel);
1035 nlines = view->nlines;
1037 } else if (view->parent == NULL)
1038 ncols = COLS;
1040 if (view->resize && dif > 0) {
1041 err = view->resize(view, dif);
1042 if (err)
1043 return err;
1046 if (wresize(view->window, nlines, ncols) == ERR)
1047 return got_error_from_errno("wresize");
1048 if (replace_panel(view->panel, view->window) == ERR)
1049 return got_error_from_errno("replace_panel");
1050 wclear(view->window);
1052 view->nlines = nlines;
1053 view->ncols = ncols;
1054 view->lines = LINES;
1055 view->cols = COLS;
1057 return NULL;
1060 static const struct got_error *
1061 resize_log_view(struct tog_view *view, int increase)
1063 struct tog_log_view_state *s = &view->state.log;
1064 const struct got_error *err = NULL;
1065 int n = 0;
1067 if (s->selected_entry)
1068 n = s->selected_entry->idx + view->lines - s->selected;
1071 * Request commits to account for the increased
1072 * height so we have enough to populate the view.
1074 if (s->commits->ncommits < n) {
1075 view->nscrolled = n - s->commits->ncommits + increase + 1;
1076 err = request_log_commits(view);
1079 return err;
1082 static void
1083 view_adjust_offset(struct tog_view *view, int n)
1085 if (n == 0)
1086 return;
1088 if (view->parent && view->parent->offset) {
1089 if (view->parent->offset + n >= 0)
1090 view->parent->offset += n;
1091 else
1092 view->parent->offset = 0;
1093 } else if (view->offset) {
1094 if (view->offset - n >= 0)
1095 view->offset -= n;
1096 else
1097 view->offset = 0;
1101 static const struct got_error *
1102 view_resize_split(struct tog_view *view, int resize)
1104 const struct got_error *err = NULL;
1105 struct tog_view *v = NULL;
1107 if (view->parent)
1108 v = view->parent;
1109 else
1110 v = view;
1112 if (!v->child || !view_is_splitscreen(v->child))
1113 return NULL;
1115 v->resized = v->child->resized = resize; /* lock for resize event */
1117 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1118 if (v->child->resized_y)
1119 v->child->begin_y = v->child->resized_y;
1120 if (view->parent)
1121 v->child->begin_y -= resize;
1122 else
1123 v->child->begin_y += resize;
1124 if (v->child->begin_y < 3) {
1125 view->count = 0;
1126 v->child->begin_y = 3;
1127 } else if (v->child->begin_y > LINES - 1) {
1128 view->count = 0;
1129 v->child->begin_y = LINES - 1;
1131 v->ncols = COLS;
1132 v->child->ncols = COLS;
1133 view_adjust_offset(view, resize);
1134 err = view_init_hsplit(v, v->child->begin_y);
1135 if (err)
1136 return err;
1137 v->child->resized_y = v->child->begin_y;
1138 } else {
1139 if (v->child->resized_x)
1140 v->child->begin_x = v->child->resized_x;
1141 if (view->parent)
1142 v->child->begin_x -= resize;
1143 else
1144 v->child->begin_x += resize;
1145 if (v->child->begin_x < 11) {
1146 view->count = 0;
1147 v->child->begin_x = 11;
1148 } else if (v->child->begin_x > COLS - 1) {
1149 view->count = 0;
1150 v->child->begin_x = COLS - 1;
1152 v->child->resized_x = v->child->begin_x;
1155 v->child->mode = v->mode;
1156 v->child->nlines = v->lines - v->child->begin_y;
1157 v->child->ncols = v->cols - v->child->begin_x;
1158 v->focus_child = 1;
1160 err = view_fullscreen(v);
1161 if (err)
1162 return err;
1163 err = view_splitscreen(v->child);
1164 if (err)
1165 return err;
1167 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1168 err = offset_selection_down(v->child);
1169 if (err)
1170 return err;
1173 if (v->resize)
1174 err = v->resize(v, 0);
1175 else if (v->child->resize)
1176 err = v->child->resize(v->child, 0);
1178 v->resized = v->child->resized = 0;
1180 return err;
1183 static void
1184 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1186 struct tog_view *v = src->child ? src->child : src;
1188 dst->resized_x = v->resized_x;
1189 dst->resized_y = v->resized_y;
1192 static const struct got_error *
1193 view_close_child(struct tog_view *view)
1195 const struct got_error *err = NULL;
1197 if (view->child == NULL)
1198 return NULL;
1200 err = view_close(view->child);
1201 view->child = NULL;
1202 return err;
1205 static const struct got_error *
1206 view_set_child(struct tog_view *view, struct tog_view *child)
1208 const struct got_error *err = NULL;
1210 view->child = child;
1211 child->parent = view;
1213 err = view_resize(view);
1214 if (err)
1215 return err;
1217 if (view->child->resized_x || view->child->resized_y)
1218 err = view_resize_split(view, 0);
1220 return err;
1223 static const struct got_error *view_dispatch_request(struct tog_view **,
1224 struct tog_view *, enum tog_view_type, int, int);
1226 static const struct got_error *
1227 view_request_new(struct tog_view **requested, struct tog_view *view,
1228 enum tog_view_type request)
1230 struct tog_view *new_view = NULL;
1231 const struct got_error *err;
1232 int y = 0, x = 0;
1234 *requested = NULL;
1236 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1237 view_get_split(view, &y, &x);
1239 err = view_dispatch_request(&new_view, view, request, y, x);
1240 if (err)
1241 return err;
1243 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1244 request != TOG_VIEW_HELP) {
1245 err = view_init_hsplit(view, y);
1246 if (err)
1247 return err;
1250 view->focussed = 0;
1251 new_view->focussed = 1;
1252 new_view->mode = view->mode;
1253 new_view->nlines = request == TOG_VIEW_HELP ?
1254 view->lines : view->lines - y;
1256 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1257 view_transfer_size(new_view, view);
1258 err = view_close_child(view);
1259 if (err)
1260 return err;
1261 err = view_set_child(view, new_view);
1262 if (err)
1263 return err;
1264 view->focus_child = 1;
1265 } else
1266 *requested = new_view;
1268 return NULL;
1271 static void
1272 tog_resizeterm(void)
1274 int cols, lines;
1275 struct winsize size;
1277 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1278 cols = 80; /* Default */
1279 lines = 24;
1280 } else {
1281 cols = size.ws_col;
1282 lines = size.ws_row;
1284 resize_term(lines, cols);
1287 static const struct got_error *
1288 view_search_start(struct tog_view *view)
1290 const struct got_error *err = NULL;
1291 struct tog_view *v = view;
1292 char pattern[1024];
1293 int ret;
1295 if (view->search_started) {
1296 regfree(&view->regex);
1297 view->searching = 0;
1298 memset(&view->regmatch, 0, sizeof(view->regmatch));
1300 view->search_started = 0;
1302 if (view->nlines < 1)
1303 return NULL;
1305 if (view_is_hsplit_top(view))
1306 v = view->child;
1307 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1308 v = view->parent;
1310 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1311 wclrtoeol(v->window);
1313 nodelay(v->window, FALSE); /* block for search term input */
1314 nocbreak();
1315 echo();
1316 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1317 wrefresh(v->window);
1318 cbreak();
1319 noecho();
1320 nodelay(v->window, TRUE);
1321 if (ret == ERR)
1322 return NULL;
1324 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1325 err = view->search_start(view);
1326 if (err) {
1327 regfree(&view->regex);
1328 return err;
1330 view->search_started = 1;
1331 view->searching = TOG_SEARCH_FORWARD;
1332 view->search_next_done = 0;
1333 view->search_next(view);
1336 return NULL;
1339 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1340 static const struct got_error *
1341 switch_split(struct tog_view *view)
1343 const struct got_error *err = NULL;
1344 struct tog_view *v = NULL;
1346 if (view->parent)
1347 v = view->parent;
1348 else
1349 v = view;
1351 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1352 v->mode = TOG_VIEW_SPLIT_VERT;
1353 else
1354 v->mode = TOG_VIEW_SPLIT_HRZN;
1356 if (!v->child)
1357 return NULL;
1358 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1359 v->mode = TOG_VIEW_SPLIT_NONE;
1361 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1362 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1363 v->child->begin_y = v->child->resized_y;
1364 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1365 v->child->begin_x = v->child->resized_x;
1368 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1369 v->ncols = COLS;
1370 v->child->ncols = COLS;
1371 v->child->nscrolled = LINES - v->child->nlines;
1373 err = view_init_hsplit(v, v->child->begin_y);
1374 if (err)
1375 return err;
1377 v->child->mode = v->mode;
1378 v->child->nlines = v->lines - v->child->begin_y;
1379 v->focus_child = 1;
1381 err = view_fullscreen(v);
1382 if (err)
1383 return err;
1384 err = view_splitscreen(v->child);
1385 if (err)
1386 return err;
1388 if (v->mode == TOG_VIEW_SPLIT_NONE)
1389 v->mode = TOG_VIEW_SPLIT_VERT;
1390 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1391 err = offset_selection_down(v);
1392 if (err)
1393 return err;
1394 err = offset_selection_down(v->child);
1395 if (err)
1396 return err;
1397 } else {
1398 offset_selection_up(v);
1399 offset_selection_up(v->child);
1401 if (v->resize)
1402 err = v->resize(v, 0);
1403 else if (v->child->resize)
1404 err = v->child->resize(v->child, 0);
1406 return err;
1410 * Compute view->count from numeric input. Assign total to view->count and
1411 * return first non-numeric key entered.
1413 static int
1414 get_compound_key(struct tog_view *view, int c)
1416 struct tog_view *v = view;
1417 int x, n = 0;
1419 if (view_is_hsplit_top(view))
1420 v = view->child;
1421 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1422 v = view->parent;
1424 view->count = 0;
1425 cbreak(); /* block for input */
1426 nodelay(view->window, FALSE);
1427 wmove(v->window, v->nlines - 1, 0);
1428 wclrtoeol(v->window);
1429 waddch(v->window, ':');
1431 do {
1432 x = getcurx(v->window);
1433 if (x != ERR && x < view->ncols) {
1434 waddch(v->window, c);
1435 wrefresh(v->window);
1439 * Don't overflow. Max valid request should be the greatest
1440 * between the longest and total lines; cap at 10 million.
1442 if (n >= 9999999)
1443 n = 9999999;
1444 else
1445 n = n * 10 + (c - '0');
1446 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1448 if (c == 'G' || c == 'g') { /* nG key map */
1449 view->gline = view->hiline = n;
1450 n = 0;
1451 c = 0;
1454 /* Massage excessive or inapplicable values at the input handler. */
1455 view->count = n;
1457 return c;
1460 static const struct got_error *
1461 view_input(struct tog_view **new, int *done, struct tog_view *view,
1462 struct tog_view_list_head *views)
1464 const struct got_error *err = NULL;
1465 struct tog_view *v;
1466 int ch, errcode;
1468 *new = NULL;
1470 /* Clear "no matches" indicator. */
1471 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1472 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1473 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1474 view->count = 0;
1477 if (view->searching && !view->search_next_done) {
1478 errcode = pthread_mutex_unlock(&tog_mutex);
1479 if (errcode)
1480 return got_error_set_errno(errcode,
1481 "pthread_mutex_unlock");
1482 sched_yield();
1483 errcode = pthread_mutex_lock(&tog_mutex);
1484 if (errcode)
1485 return got_error_set_errno(errcode,
1486 "pthread_mutex_lock");
1487 view->search_next(view);
1488 return NULL;
1491 /* Allow threads to make progress while we are waiting for input. */
1492 errcode = pthread_mutex_unlock(&tog_mutex);
1493 if (errcode)
1494 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1495 /* If we have an unfinished count, let C-g or backspace abort. */
1496 if (view->count && --view->count) {
1497 cbreak();
1498 nodelay(view->window, TRUE);
1499 ch = wgetch(view->window);
1500 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1501 view->count = 0;
1502 else
1503 ch = view->ch;
1504 } else {
1505 ch = wgetch(view->window);
1506 if (ch >= '1' && ch <= '9')
1507 view->ch = ch = get_compound_key(view, ch);
1509 if (view->hiline && ch != ERR && ch != 0)
1510 view->hiline = 0; /* key pressed, clear line highlight */
1511 nodelay(view->window, TRUE);
1512 errcode = pthread_mutex_lock(&tog_mutex);
1513 if (errcode)
1514 return got_error_set_errno(errcode, "pthread_mutex_lock");
1516 if (tog_sigwinch_received || tog_sigcont_received) {
1517 tog_resizeterm();
1518 tog_sigwinch_received = 0;
1519 tog_sigcont_received = 0;
1520 TAILQ_FOREACH(v, views, entry) {
1521 err = view_resize(v);
1522 if (err)
1523 return err;
1524 err = v->input(new, v, KEY_RESIZE);
1525 if (err)
1526 return err;
1527 if (v->child) {
1528 err = view_resize(v->child);
1529 if (err)
1530 return err;
1531 err = v->child->input(new, v->child,
1532 KEY_RESIZE);
1533 if (err)
1534 return err;
1535 if (v->child->resized_x || v->child->resized_y) {
1536 err = view_resize_split(v, 0);
1537 if (err)
1538 return err;
1544 switch (ch) {
1545 case '?':
1546 case 'H':
1547 case KEY_F(1):
1548 if (view->type == TOG_VIEW_HELP)
1549 err = view->reset(view);
1550 else
1551 err = view_request_new(new, view, TOG_VIEW_HELP);
1552 break;
1553 case '\t':
1554 view->count = 0;
1555 if (view->child) {
1556 view->focussed = 0;
1557 view->child->focussed = 1;
1558 view->focus_child = 1;
1559 } else if (view->parent) {
1560 view->focussed = 0;
1561 view->parent->focussed = 1;
1562 view->parent->focus_child = 0;
1563 if (!view_is_splitscreen(view)) {
1564 if (view->parent->resize) {
1565 err = view->parent->resize(view->parent,
1566 0);
1567 if (err)
1568 return err;
1570 offset_selection_up(view->parent);
1571 err = view_fullscreen(view->parent);
1572 if (err)
1573 return err;
1576 break;
1577 case 'q':
1578 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1579 if (view->parent->resize) {
1580 /* might need more commits to fill fullscreen */
1581 err = view->parent->resize(view->parent, 0);
1582 if (err)
1583 break;
1585 offset_selection_up(view->parent);
1587 err = view->input(new, view, ch);
1588 view->dying = 1;
1589 break;
1590 case 'Q':
1591 *done = 1;
1592 break;
1593 case 'F':
1594 view->count = 0;
1595 if (view_is_parent_view(view)) {
1596 if (view->child == NULL)
1597 break;
1598 if (view_is_splitscreen(view->child)) {
1599 view->focussed = 0;
1600 view->child->focussed = 1;
1601 err = view_fullscreen(view->child);
1602 } else {
1603 err = view_splitscreen(view->child);
1604 if (!err)
1605 err = view_resize_split(view, 0);
1607 if (err)
1608 break;
1609 err = view->child->input(new, view->child,
1610 KEY_RESIZE);
1611 } else {
1612 if (view_is_splitscreen(view)) {
1613 view->parent->focussed = 0;
1614 view->focussed = 1;
1615 err = view_fullscreen(view);
1616 } else {
1617 err = view_splitscreen(view);
1618 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1619 err = view_resize(view->parent);
1620 if (!err)
1621 err = view_resize_split(view, 0);
1623 if (err)
1624 break;
1625 err = view->input(new, view, KEY_RESIZE);
1627 if (err)
1628 break;
1629 if (view->resize) {
1630 err = view->resize(view, 0);
1631 if (err)
1632 break;
1634 if (view->parent)
1635 err = offset_selection_down(view->parent);
1636 if (!err)
1637 err = offset_selection_down(view);
1638 break;
1639 case 'S':
1640 view->count = 0;
1641 err = switch_split(view);
1642 break;
1643 case '-':
1644 err = view_resize_split(view, -1);
1645 break;
1646 case '+':
1647 err = view_resize_split(view, 1);
1648 break;
1649 case KEY_RESIZE:
1650 break;
1651 case '/':
1652 view->count = 0;
1653 if (view->search_start)
1654 view_search_start(view);
1655 else
1656 err = view->input(new, view, ch);
1657 break;
1658 case 'N':
1659 case 'n':
1660 if (view->search_started && view->search_next) {
1661 view->searching = (ch == 'n' ?
1662 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1663 view->search_next_done = 0;
1664 view->search_next(view);
1665 } else
1666 err = view->input(new, view, ch);
1667 break;
1668 case 'A':
1669 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1670 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1671 else
1672 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1673 TAILQ_FOREACH(v, views, entry) {
1674 if (v->reset) {
1675 err = v->reset(v);
1676 if (err)
1677 return err;
1679 if (v->child && v->child->reset) {
1680 err = v->child->reset(v->child);
1681 if (err)
1682 return err;
1685 break;
1686 default:
1687 err = view->input(new, view, ch);
1688 break;
1691 return err;
1694 static int
1695 view_needs_focus_indication(struct tog_view *view)
1697 if (view_is_parent_view(view)) {
1698 if (view->child == NULL || view->child->focussed)
1699 return 0;
1700 if (!view_is_splitscreen(view->child))
1701 return 0;
1702 } else if (!view_is_splitscreen(view))
1703 return 0;
1705 return view->focussed;
1708 static const struct got_error *
1709 view_loop(struct tog_view *view)
1711 const struct got_error *err = NULL;
1712 struct tog_view_list_head views;
1713 struct tog_view *new_view;
1714 char *mode;
1715 int fast_refresh = 10;
1716 int done = 0, errcode;
1718 mode = getenv("TOG_VIEW_SPLIT_MODE");
1719 if (!mode || !(*mode == 'h' || *mode == 'H'))
1720 view->mode = TOG_VIEW_SPLIT_VERT;
1721 else
1722 view->mode = TOG_VIEW_SPLIT_HRZN;
1724 errcode = pthread_mutex_lock(&tog_mutex);
1725 if (errcode)
1726 return got_error_set_errno(errcode, "pthread_mutex_lock");
1728 TAILQ_INIT(&views);
1729 TAILQ_INSERT_HEAD(&views, view, entry);
1731 view->focussed = 1;
1732 err = view->show(view);
1733 if (err)
1734 return err;
1735 update_panels();
1736 doupdate();
1737 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1738 !tog_fatal_signal_received()) {
1739 /* Refresh fast during initialization, then become slower. */
1740 if (fast_refresh && fast_refresh-- == 0)
1741 halfdelay(10); /* switch to once per second */
1743 err = view_input(&new_view, &done, view, &views);
1744 if (err)
1745 break;
1746 if (view->dying) {
1747 struct tog_view *v, *prev = NULL;
1749 if (view_is_parent_view(view))
1750 prev = TAILQ_PREV(view, tog_view_list_head,
1751 entry);
1752 else if (view->parent)
1753 prev = view->parent;
1755 if (view->parent) {
1756 view->parent->child = NULL;
1757 view->parent->focus_child = 0;
1758 /* Restore fullscreen line height. */
1759 view->parent->nlines = view->parent->lines;
1760 err = view_resize(view->parent);
1761 if (err)
1762 break;
1763 /* Make resized splits persist. */
1764 view_transfer_size(view->parent, view);
1765 } else
1766 TAILQ_REMOVE(&views, view, entry);
1768 err = view_close(view);
1769 if (err)
1770 goto done;
1772 view = NULL;
1773 TAILQ_FOREACH(v, &views, entry) {
1774 if (v->focussed)
1775 break;
1777 if (view == NULL && new_view == NULL) {
1778 /* No view has focus. Try to pick one. */
1779 if (prev)
1780 view = prev;
1781 else if (!TAILQ_EMPTY(&views)) {
1782 view = TAILQ_LAST(&views,
1783 tog_view_list_head);
1785 if (view) {
1786 if (view->focus_child) {
1787 view->child->focussed = 1;
1788 view = view->child;
1789 } else
1790 view->focussed = 1;
1794 if (new_view) {
1795 struct tog_view *v, *t;
1796 /* Only allow one parent view per type. */
1797 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1798 if (v->type != new_view->type)
1799 continue;
1800 TAILQ_REMOVE(&views, v, entry);
1801 err = view_close(v);
1802 if (err)
1803 goto done;
1804 break;
1806 TAILQ_INSERT_TAIL(&views, new_view, entry);
1807 view = new_view;
1809 if (view) {
1810 if (view_is_parent_view(view)) {
1811 if (view->child && view->child->focussed)
1812 view = view->child;
1813 } else {
1814 if (view->parent && view->parent->focussed)
1815 view = view->parent;
1817 show_panel(view->panel);
1818 if (view->child && view_is_splitscreen(view->child))
1819 show_panel(view->child->panel);
1820 if (view->parent && view_is_splitscreen(view)) {
1821 err = view->parent->show(view->parent);
1822 if (err)
1823 goto done;
1825 err = view->show(view);
1826 if (err)
1827 goto done;
1828 if (view->child) {
1829 err = view->child->show(view->child);
1830 if (err)
1831 goto done;
1833 update_panels();
1834 doupdate();
1837 done:
1838 while (!TAILQ_EMPTY(&views)) {
1839 const struct got_error *close_err;
1840 view = TAILQ_FIRST(&views);
1841 TAILQ_REMOVE(&views, view, entry);
1842 close_err = view_close(view);
1843 if (close_err && err == NULL)
1844 err = close_err;
1847 errcode = pthread_mutex_unlock(&tog_mutex);
1848 if (errcode && err == NULL)
1849 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1851 return err;
1854 __dead static void
1855 usage_log(void)
1857 endwin();
1858 fprintf(stderr,
1859 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1860 getprogname());
1861 exit(1);
1864 /* Create newly allocated wide-character string equivalent to a byte string. */
1865 static const struct got_error *
1866 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1868 char *vis = NULL;
1869 const struct got_error *err = NULL;
1871 *ws = NULL;
1872 *wlen = mbstowcs(NULL, s, 0);
1873 if (*wlen == (size_t)-1) {
1874 int vislen;
1875 if (errno != EILSEQ)
1876 return got_error_from_errno("mbstowcs");
1878 /* byte string invalid in current encoding; try to "fix" it */
1879 err = got_mbsavis(&vis, &vislen, s);
1880 if (err)
1881 return err;
1882 *wlen = mbstowcs(NULL, vis, 0);
1883 if (*wlen == (size_t)-1) {
1884 err = got_error_from_errno("mbstowcs"); /* give up */
1885 goto done;
1889 *ws = calloc(*wlen + 1, sizeof(**ws));
1890 if (*ws == NULL) {
1891 err = got_error_from_errno("calloc");
1892 goto done;
1895 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1896 err = got_error_from_errno("mbstowcs");
1897 done:
1898 free(vis);
1899 if (err) {
1900 free(*ws);
1901 *ws = NULL;
1902 *wlen = 0;
1904 return err;
1907 static const struct got_error *
1908 expand_tab(char **ptr, const char *src)
1910 char *dst;
1911 size_t len, n, idx = 0, sz = 0;
1913 *ptr = NULL;
1914 n = len = strlen(src);
1915 dst = malloc(n + 1);
1916 if (dst == NULL)
1917 return got_error_from_errno("malloc");
1919 while (idx < len && src[idx]) {
1920 const char c = src[idx];
1922 if (c == '\t') {
1923 size_t nb = TABSIZE - sz % TABSIZE;
1924 char *p;
1926 p = realloc(dst, n + nb);
1927 if (p == NULL) {
1928 free(dst);
1929 return got_error_from_errno("realloc");
1932 dst = p;
1933 n += nb;
1934 memset(dst + sz, ' ', nb);
1935 sz += nb;
1936 } else
1937 dst[sz++] = src[idx];
1938 ++idx;
1941 dst[sz] = '\0';
1942 *ptr = dst;
1943 return NULL;
1947 * Advance at most n columns from wline starting at offset off.
1948 * Return the index to the first character after the span operation.
1949 * Return the combined column width of all spanned wide character in
1950 * *rcol.
1952 static int
1953 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1955 int width, i, cols = 0;
1957 if (n == 0) {
1958 *rcol = cols;
1959 return off;
1962 for (i = off; wline[i] != L'\0'; ++i) {
1963 if (wline[i] == L'\t')
1964 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1965 else
1966 width = wcwidth(wline[i]);
1968 if (width == -1) {
1969 width = 1;
1970 wline[i] = L'.';
1973 if (cols + width > n)
1974 break;
1975 cols += width;
1978 *rcol = cols;
1979 return i;
1983 * Format a line for display, ensuring that it won't overflow a width limit.
1984 * With scrolling, the width returned refers to the scrolled version of the
1985 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1987 static const struct got_error *
1988 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1989 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1991 const struct got_error *err = NULL;
1992 int cols;
1993 wchar_t *wline = NULL;
1994 char *exstr = NULL;
1995 size_t wlen;
1996 int i, scrollx;
1998 *wlinep = NULL;
1999 *widthp = 0;
2001 if (expand) {
2002 err = expand_tab(&exstr, line);
2003 if (err)
2004 return err;
2007 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2008 free(exstr);
2009 if (err)
2010 return err;
2012 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2014 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2015 wline[wlen - 1] = L'\0';
2016 wlen--;
2018 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2019 wline[wlen - 1] = L'\0';
2020 wlen--;
2023 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2024 wline[i] = L'\0';
2026 if (widthp)
2027 *widthp = cols;
2028 if (scrollxp)
2029 *scrollxp = scrollx;
2030 if (err)
2031 free(wline);
2032 else
2033 *wlinep = wline;
2034 return err;
2037 static const struct got_error*
2038 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2039 struct got_object_id *id, struct got_repository *repo)
2041 static const struct got_error *err = NULL;
2042 struct got_reflist_entry *re;
2043 char *s;
2044 const char *name;
2046 *refs_str = NULL;
2048 TAILQ_FOREACH(re, refs, entry) {
2049 struct got_tag_object *tag = NULL;
2050 struct got_object_id *ref_id;
2051 int cmp;
2053 name = got_ref_get_name(re->ref);
2054 if (strcmp(name, GOT_REF_HEAD) == 0)
2055 continue;
2056 if (strncmp(name, "refs/", 5) == 0)
2057 name += 5;
2058 if (strncmp(name, "got/", 4) == 0 &&
2059 strncmp(name, "got/backup/", 11) != 0)
2060 continue;
2061 if (strncmp(name, "heads/", 6) == 0)
2062 name += 6;
2063 if (strncmp(name, "remotes/", 8) == 0) {
2064 name += 8;
2065 s = strstr(name, "/" GOT_REF_HEAD);
2066 if (s != NULL && s[strlen(s)] == '\0')
2067 continue;
2069 err = got_ref_resolve(&ref_id, repo, re->ref);
2070 if (err)
2071 break;
2072 if (strncmp(name, "tags/", 5) == 0) {
2073 err = got_object_open_as_tag(&tag, repo, ref_id);
2074 if (err) {
2075 if (err->code != GOT_ERR_OBJ_TYPE) {
2076 free(ref_id);
2077 break;
2079 /* Ref points at something other than a tag. */
2080 err = NULL;
2081 tag = NULL;
2084 cmp = got_object_id_cmp(tag ?
2085 got_object_tag_get_object_id(tag) : ref_id, id);
2086 free(ref_id);
2087 if (tag)
2088 got_object_tag_close(tag);
2089 if (cmp != 0)
2090 continue;
2091 s = *refs_str;
2092 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2093 s ? ", " : "", name) == -1) {
2094 err = got_error_from_errno("asprintf");
2095 free(s);
2096 *refs_str = NULL;
2097 break;
2099 free(s);
2102 return err;
2105 static const struct got_error *
2106 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2107 int col_tab_align)
2109 char *smallerthan;
2111 smallerthan = strchr(author, '<');
2112 if (smallerthan && smallerthan[1] != '\0')
2113 author = smallerthan + 1;
2114 author[strcspn(author, "@>")] = '\0';
2115 return format_line(wauthor, author_width, NULL, author, 0, limit,
2116 col_tab_align, 0);
2119 static const struct got_error *
2120 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2121 struct got_object_id *id, const size_t date_display_cols,
2122 int author_display_cols)
2124 struct tog_log_view_state *s = &view->state.log;
2125 const struct got_error *err = NULL;
2126 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2127 char *logmsg0 = NULL, *logmsg = NULL;
2128 char *author = NULL;
2129 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2130 int author_width, logmsg_width;
2131 char *newline, *line = NULL;
2132 int col, limit, scrollx;
2133 const int avail = view->ncols;
2134 struct tm tm;
2135 time_t committer_time;
2136 struct tog_color *tc;
2138 committer_time = got_object_commit_get_committer_time(commit);
2139 if (gmtime_r(&committer_time, &tm) == NULL)
2140 return got_error_from_errno("gmtime_r");
2141 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2142 return got_error(GOT_ERR_NO_SPACE);
2144 if (avail <= date_display_cols)
2145 limit = MIN(sizeof(datebuf) - 1, avail);
2146 else
2147 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2148 tc = get_color(&s->colors, TOG_COLOR_DATE);
2149 if (tc)
2150 wattr_on(view->window,
2151 COLOR_PAIR(tc->colorpair), NULL);
2152 waddnstr(view->window, datebuf, limit);
2153 if (tc)
2154 wattr_off(view->window,
2155 COLOR_PAIR(tc->colorpair), NULL);
2156 col = limit;
2157 if (col > avail)
2158 goto done;
2160 if (avail >= 120) {
2161 char *id_str;
2162 err = got_object_id_str(&id_str, id);
2163 if (err)
2164 goto done;
2165 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2166 if (tc)
2167 wattr_on(view->window,
2168 COLOR_PAIR(tc->colorpair), NULL);
2169 wprintw(view->window, "%.8s ", id_str);
2170 if (tc)
2171 wattr_off(view->window,
2172 COLOR_PAIR(tc->colorpair), NULL);
2173 free(id_str);
2174 col += 9;
2175 if (col > avail)
2176 goto done;
2179 if (s->use_committer)
2180 author = strdup(got_object_commit_get_committer(commit));
2181 else
2182 author = strdup(got_object_commit_get_author(commit));
2183 if (author == NULL) {
2184 err = got_error_from_errno("strdup");
2185 goto done;
2187 err = format_author(&wauthor, &author_width, author, avail - col, col);
2188 if (err)
2189 goto done;
2190 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2191 if (tc)
2192 wattr_on(view->window,
2193 COLOR_PAIR(tc->colorpair), NULL);
2194 waddwstr(view->window, wauthor);
2195 col += author_width;
2196 while (col < avail && author_width < author_display_cols + 2) {
2197 waddch(view->window, ' ');
2198 col++;
2199 author_width++;
2201 if (tc)
2202 wattr_off(view->window,
2203 COLOR_PAIR(tc->colorpair), NULL);
2204 if (col > avail)
2205 goto done;
2207 err = got_object_commit_get_logmsg(&logmsg0, commit);
2208 if (err)
2209 goto done;
2210 logmsg = logmsg0;
2211 while (*logmsg == '\n')
2212 logmsg++;
2213 newline = strchr(logmsg, '\n');
2214 if (newline)
2215 *newline = '\0';
2216 limit = avail - col;
2217 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2218 limit--; /* for the border */
2219 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2220 limit, col, 1);
2221 if (err)
2222 goto done;
2223 waddwstr(view->window, &wlogmsg[scrollx]);
2224 col += MAX(logmsg_width, 0);
2225 while (col < avail) {
2226 waddch(view->window, ' ');
2227 col++;
2229 done:
2230 free(logmsg0);
2231 free(wlogmsg);
2232 free(author);
2233 free(wauthor);
2234 free(line);
2235 return err;
2238 static struct commit_queue_entry *
2239 alloc_commit_queue_entry(struct got_commit_object *commit,
2240 struct got_object_id *id)
2242 struct commit_queue_entry *entry;
2243 struct got_object_id *dup;
2245 entry = calloc(1, sizeof(*entry));
2246 if (entry == NULL)
2247 return NULL;
2249 dup = got_object_id_dup(id);
2250 if (dup == NULL) {
2251 free(entry);
2252 return NULL;
2255 entry->id = dup;
2256 entry->commit = commit;
2257 return entry;
2260 static void
2261 pop_commit(struct commit_queue *commits)
2263 struct commit_queue_entry *entry;
2265 entry = TAILQ_FIRST(&commits->head);
2266 TAILQ_REMOVE(&commits->head, entry, entry);
2267 got_object_commit_close(entry->commit);
2268 commits->ncommits--;
2269 free(entry->id);
2270 free(entry);
2273 static void
2274 free_commits(struct commit_queue *commits)
2276 while (!TAILQ_EMPTY(&commits->head))
2277 pop_commit(commits);
2280 static const struct got_error *
2281 match_commit(int *have_match, struct got_object_id *id,
2282 struct got_commit_object *commit, regex_t *regex)
2284 const struct got_error *err = NULL;
2285 regmatch_t regmatch;
2286 char *id_str = NULL, *logmsg = NULL;
2288 *have_match = 0;
2290 err = got_object_id_str(&id_str, id);
2291 if (err)
2292 return err;
2294 err = got_object_commit_get_logmsg(&logmsg, commit);
2295 if (err)
2296 goto done;
2298 if (regexec(regex, got_object_commit_get_author(commit), 1,
2299 &regmatch, 0) == 0 ||
2300 regexec(regex, got_object_commit_get_committer(commit), 1,
2301 &regmatch, 0) == 0 ||
2302 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2303 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2304 *have_match = 1;
2305 done:
2306 free(id_str);
2307 free(logmsg);
2308 return err;
2311 static const struct got_error *
2312 queue_commits(struct tog_log_thread_args *a)
2314 const struct got_error *err = NULL;
2317 * We keep all commits open throughout the lifetime of the log
2318 * view in order to avoid having to re-fetch commits from disk
2319 * while updating the display.
2321 do {
2322 struct got_object_id id;
2323 struct got_commit_object *commit;
2324 struct commit_queue_entry *entry;
2325 int limit_match = 0;
2326 int errcode;
2328 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2329 NULL, NULL);
2330 if (err)
2331 break;
2333 err = got_object_open_as_commit(&commit, a->repo, &id);
2334 if (err)
2335 break;
2336 entry = alloc_commit_queue_entry(commit, &id);
2337 if (entry == NULL) {
2338 err = got_error_from_errno("alloc_commit_queue_entry");
2339 break;
2342 errcode = pthread_mutex_lock(&tog_mutex);
2343 if (errcode) {
2344 err = got_error_set_errno(errcode,
2345 "pthread_mutex_lock");
2346 break;
2349 entry->idx = a->real_commits->ncommits;
2350 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2351 a->real_commits->ncommits++;
2353 if (*a->limiting) {
2354 err = match_commit(&limit_match, &id, commit,
2355 a->limit_regex);
2356 if (err)
2357 break;
2359 if (limit_match) {
2360 struct commit_queue_entry *matched;
2362 matched = alloc_commit_queue_entry(
2363 entry->commit, entry->id);
2364 if (matched == NULL) {
2365 err = got_error_from_errno(
2366 "alloc_commit_queue_entry");
2367 break;
2369 matched->commit = entry->commit;
2370 got_object_commit_retain(entry->commit);
2372 matched->idx = a->limit_commits->ncommits;
2373 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2374 matched, entry);
2375 a->limit_commits->ncommits++;
2379 * This is how we signal log_thread() that we
2380 * have found a match, and that it should be
2381 * counted as a new entry for the view.
2383 a->limit_match = limit_match;
2386 if (*a->searching == TOG_SEARCH_FORWARD &&
2387 !*a->search_next_done) {
2388 int have_match;
2389 err = match_commit(&have_match, &id, commit, a->regex);
2390 if (err)
2391 break;
2393 if (*a->limiting) {
2394 if (limit_match && have_match)
2395 *a->search_next_done =
2396 TOG_SEARCH_HAVE_MORE;
2397 } else if (have_match)
2398 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2401 errcode = pthread_mutex_unlock(&tog_mutex);
2402 if (errcode && err == NULL)
2403 err = got_error_set_errno(errcode,
2404 "pthread_mutex_unlock");
2405 if (err)
2406 break;
2407 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2409 return err;
2412 static void
2413 select_commit(struct tog_log_view_state *s)
2415 struct commit_queue_entry *entry;
2416 int ncommits = 0;
2418 entry = s->first_displayed_entry;
2419 while (entry) {
2420 if (ncommits == s->selected) {
2421 s->selected_entry = entry;
2422 break;
2424 entry = TAILQ_NEXT(entry, entry);
2425 ncommits++;
2429 static const struct got_error *
2430 draw_commits(struct tog_view *view)
2432 const struct got_error *err = NULL;
2433 struct tog_log_view_state *s = &view->state.log;
2434 struct commit_queue_entry *entry = s->selected_entry;
2435 int limit = view->nlines;
2436 int width;
2437 int ncommits, author_cols = 4;
2438 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2439 char *refs_str = NULL;
2440 wchar_t *wline;
2441 struct tog_color *tc;
2442 static const size_t date_display_cols = 12;
2444 if (view_is_hsplit_top(view))
2445 --limit; /* account for border */
2447 if (s->selected_entry &&
2448 !(view->searching && view->search_next_done == 0)) {
2449 struct got_reflist_head *refs;
2450 err = got_object_id_str(&id_str, s->selected_entry->id);
2451 if (err)
2452 return err;
2453 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2454 s->selected_entry->id);
2455 if (refs) {
2456 err = build_refs_str(&refs_str, refs,
2457 s->selected_entry->id, s->repo);
2458 if (err)
2459 goto done;
2463 if (s->thread_args.commits_needed == 0)
2464 halfdelay(10); /* disable fast refresh */
2466 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2467 if (asprintf(&ncommits_str, " [%d/%d] %s",
2468 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2469 (view->searching && !view->search_next_done) ?
2470 "searching..." : "loading...") == -1) {
2471 err = got_error_from_errno("asprintf");
2472 goto done;
2474 } else {
2475 const char *search_str = NULL;
2476 const char *limit_str = NULL;
2478 if (view->searching) {
2479 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2480 search_str = "no more matches";
2481 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2482 search_str = "no matches found";
2483 else if (!view->search_next_done)
2484 search_str = "searching...";
2487 if (s->limit_view && s->commits->ncommits == 0)
2488 limit_str = "no matches found";
2490 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2491 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2492 search_str ? search_str : (refs_str ? refs_str : ""),
2493 limit_str ? limit_str : "") == -1) {
2494 err = got_error_from_errno("asprintf");
2495 goto done;
2499 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2500 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2501 "........................................",
2502 s->in_repo_path, ncommits_str) == -1) {
2503 err = got_error_from_errno("asprintf");
2504 header = NULL;
2505 goto done;
2507 } else if (asprintf(&header, "commit %s%s",
2508 id_str ? id_str : "........................................",
2509 ncommits_str) == -1) {
2510 err = got_error_from_errno("asprintf");
2511 header = NULL;
2512 goto done;
2514 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2515 if (err)
2516 goto done;
2518 werase(view->window);
2520 if (view_needs_focus_indication(view))
2521 wstandout(view->window);
2522 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2523 if (tc)
2524 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2525 waddwstr(view->window, wline);
2526 while (width < view->ncols) {
2527 waddch(view->window, ' ');
2528 width++;
2530 if (tc)
2531 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2532 if (view_needs_focus_indication(view))
2533 wstandend(view->window);
2534 free(wline);
2535 if (limit <= 1)
2536 goto done;
2538 /* Grow author column size if necessary, and set view->maxx. */
2539 entry = s->first_displayed_entry;
2540 ncommits = 0;
2541 view->maxx = 0;
2542 while (entry) {
2543 struct got_commit_object *c = entry->commit;
2544 char *author, *eol, *msg, *msg0;
2545 wchar_t *wauthor, *wmsg;
2546 int width;
2547 if (ncommits >= limit - 1)
2548 break;
2549 if (s->use_committer)
2550 author = strdup(got_object_commit_get_committer(c));
2551 else
2552 author = strdup(got_object_commit_get_author(c));
2553 if (author == NULL) {
2554 err = got_error_from_errno("strdup");
2555 goto done;
2557 err = format_author(&wauthor, &width, author, COLS,
2558 date_display_cols);
2559 if (author_cols < width)
2560 author_cols = width;
2561 free(wauthor);
2562 free(author);
2563 if (err)
2564 goto done;
2565 err = got_object_commit_get_logmsg(&msg0, c);
2566 if (err)
2567 goto done;
2568 msg = msg0;
2569 while (*msg == '\n')
2570 ++msg;
2571 if ((eol = strchr(msg, '\n')))
2572 *eol = '\0';
2573 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2574 date_display_cols + author_cols, 0);
2575 if (err)
2576 goto done;
2577 view->maxx = MAX(view->maxx, width);
2578 free(msg0);
2579 free(wmsg);
2580 ncommits++;
2581 entry = TAILQ_NEXT(entry, entry);
2584 entry = s->first_displayed_entry;
2585 s->last_displayed_entry = s->first_displayed_entry;
2586 ncommits = 0;
2587 while (entry) {
2588 if (ncommits >= limit - 1)
2589 break;
2590 if (ncommits == s->selected)
2591 wstandout(view->window);
2592 err = draw_commit(view, entry->commit, entry->id,
2593 date_display_cols, author_cols);
2594 if (ncommits == s->selected)
2595 wstandend(view->window);
2596 if (err)
2597 goto done;
2598 ncommits++;
2599 s->last_displayed_entry = entry;
2600 entry = TAILQ_NEXT(entry, entry);
2603 view_border(view);
2604 done:
2605 free(id_str);
2606 free(refs_str);
2607 free(ncommits_str);
2608 free(header);
2609 return err;
2612 static void
2613 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2615 struct commit_queue_entry *entry;
2616 int nscrolled = 0;
2618 entry = TAILQ_FIRST(&s->commits->head);
2619 if (s->first_displayed_entry == entry)
2620 return;
2622 entry = s->first_displayed_entry;
2623 while (entry && nscrolled < maxscroll) {
2624 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2625 if (entry) {
2626 s->first_displayed_entry = entry;
2627 nscrolled++;
2632 static const struct got_error *
2633 trigger_log_thread(struct tog_view *view, int wait)
2635 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2636 int errcode;
2638 halfdelay(1); /* fast refresh while loading commits */
2640 while (!ta->log_complete && !tog_thread_error &&
2641 (ta->commits_needed > 0 || ta->load_all)) {
2642 /* Wake the log thread. */
2643 errcode = pthread_cond_signal(&ta->need_commits);
2644 if (errcode)
2645 return got_error_set_errno(errcode,
2646 "pthread_cond_signal");
2649 * The mutex will be released while the view loop waits
2650 * in wgetch(), at which time the log thread will run.
2652 if (!wait)
2653 break;
2655 /* Display progress update in log view. */
2656 show_log_view(view);
2657 update_panels();
2658 doupdate();
2660 /* Wait right here while next commit is being loaded. */
2661 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2662 if (errcode)
2663 return got_error_set_errno(errcode,
2664 "pthread_cond_wait");
2666 /* Display progress update in log view. */
2667 show_log_view(view);
2668 update_panels();
2669 doupdate();
2672 return NULL;
2675 static const struct got_error *
2676 request_log_commits(struct tog_view *view)
2678 struct tog_log_view_state *state = &view->state.log;
2679 const struct got_error *err = NULL;
2681 if (state->thread_args.log_complete)
2682 return NULL;
2684 state->thread_args.commits_needed += view->nscrolled;
2685 err = trigger_log_thread(view, 1);
2686 view->nscrolled = 0;
2688 return err;
2691 static const struct got_error *
2692 log_scroll_down(struct tog_view *view, int maxscroll)
2694 struct tog_log_view_state *s = &view->state.log;
2695 const struct got_error *err = NULL;
2696 struct commit_queue_entry *pentry;
2697 int nscrolled = 0, ncommits_needed;
2699 if (s->last_displayed_entry == NULL)
2700 return NULL;
2702 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2703 if (s->commits->ncommits < ncommits_needed &&
2704 !s->thread_args.log_complete) {
2706 * Ask the log thread for required amount of commits.
2708 s->thread_args.commits_needed +=
2709 ncommits_needed - s->commits->ncommits;
2710 err = trigger_log_thread(view, 1);
2711 if (err)
2712 return err;
2715 do {
2716 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2717 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2718 break;
2720 s->last_displayed_entry = pentry ?
2721 pentry : s->last_displayed_entry;;
2723 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2724 if (pentry == NULL)
2725 break;
2726 s->first_displayed_entry = pentry;
2727 } while (++nscrolled < maxscroll);
2729 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2730 view->nscrolled += nscrolled;
2731 else
2732 view->nscrolled = 0;
2734 return err;
2737 static const struct got_error *
2738 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2739 struct got_commit_object *commit, struct got_object_id *commit_id,
2740 struct tog_view *log_view, struct got_repository *repo)
2742 const struct got_error *err;
2743 struct got_object_qid *parent_id;
2744 struct tog_view *diff_view;
2746 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2747 if (diff_view == NULL)
2748 return got_error_from_errno("view_open");
2750 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2751 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2752 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2753 if (err == NULL)
2754 *new_view = diff_view;
2755 return err;
2758 static const struct got_error *
2759 tree_view_visit_subtree(struct tog_tree_view_state *s,
2760 struct got_tree_object *subtree)
2762 struct tog_parent_tree *parent;
2764 parent = calloc(1, sizeof(*parent));
2765 if (parent == NULL)
2766 return got_error_from_errno("calloc");
2768 parent->tree = s->tree;
2769 parent->first_displayed_entry = s->first_displayed_entry;
2770 parent->selected_entry = s->selected_entry;
2771 parent->selected = s->selected;
2772 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2773 s->tree = subtree;
2774 s->selected = 0;
2775 s->first_displayed_entry = NULL;
2776 return NULL;
2779 static const struct got_error *
2780 tree_view_walk_path(struct tog_tree_view_state *s,
2781 struct got_commit_object *commit, const char *path)
2783 const struct got_error *err = NULL;
2784 struct got_tree_object *tree = NULL;
2785 const char *p;
2786 char *slash, *subpath = NULL;
2788 /* Walk the path and open corresponding tree objects. */
2789 p = path;
2790 while (*p) {
2791 struct got_tree_entry *te;
2792 struct got_object_id *tree_id;
2793 char *te_name;
2795 while (p[0] == '/')
2796 p++;
2798 /* Ensure the correct subtree entry is selected. */
2799 slash = strchr(p, '/');
2800 if (slash == NULL)
2801 te_name = strdup(p);
2802 else
2803 te_name = strndup(p, slash - p);
2804 if (te_name == NULL) {
2805 err = got_error_from_errno("strndup");
2806 break;
2808 te = got_object_tree_find_entry(s->tree, te_name);
2809 if (te == NULL) {
2810 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2811 free(te_name);
2812 break;
2814 free(te_name);
2815 s->first_displayed_entry = s->selected_entry = te;
2817 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2818 break; /* jump to this file's entry */
2820 slash = strchr(p, '/');
2821 if (slash)
2822 subpath = strndup(path, slash - path);
2823 else
2824 subpath = strdup(path);
2825 if (subpath == NULL) {
2826 err = got_error_from_errno("strdup");
2827 break;
2830 err = got_object_id_by_path(&tree_id, s->repo, commit,
2831 subpath);
2832 if (err)
2833 break;
2835 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2836 free(tree_id);
2837 if (err)
2838 break;
2840 err = tree_view_visit_subtree(s, tree);
2841 if (err) {
2842 got_object_tree_close(tree);
2843 break;
2845 if (slash == NULL)
2846 break;
2847 free(subpath);
2848 subpath = NULL;
2849 p = slash;
2852 free(subpath);
2853 return err;
2856 static const struct got_error *
2857 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2858 struct commit_queue_entry *entry, const char *path,
2859 const char *head_ref_name, struct got_repository *repo)
2861 const struct got_error *err = NULL;
2862 struct tog_tree_view_state *s;
2863 struct tog_view *tree_view;
2865 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2866 if (tree_view == NULL)
2867 return got_error_from_errno("view_open");
2869 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2870 if (err)
2871 return err;
2872 s = &tree_view->state.tree;
2874 *new_view = tree_view;
2876 if (got_path_is_root_dir(path))
2877 return NULL;
2879 return tree_view_walk_path(s, entry->commit, path);
2882 static const struct got_error *
2883 block_signals_used_by_main_thread(void)
2885 sigset_t sigset;
2886 int errcode;
2888 if (sigemptyset(&sigset) == -1)
2889 return got_error_from_errno("sigemptyset");
2891 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2892 if (sigaddset(&sigset, SIGWINCH) == -1)
2893 return got_error_from_errno("sigaddset");
2894 if (sigaddset(&sigset, SIGCONT) == -1)
2895 return got_error_from_errno("sigaddset");
2896 if (sigaddset(&sigset, SIGINT) == -1)
2897 return got_error_from_errno("sigaddset");
2898 if (sigaddset(&sigset, SIGTERM) == -1)
2899 return got_error_from_errno("sigaddset");
2901 /* ncurses handles SIGTSTP */
2902 if (sigaddset(&sigset, SIGTSTP) == -1)
2903 return got_error_from_errno("sigaddset");
2905 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2906 if (errcode)
2907 return got_error_set_errno(errcode, "pthread_sigmask");
2909 return NULL;
2912 static void *
2913 log_thread(void *arg)
2915 const struct got_error *err = NULL;
2916 int errcode = 0;
2917 struct tog_log_thread_args *a = arg;
2918 int done = 0;
2921 * Sync startup with main thread such that we begin our
2922 * work once view_input() has released the mutex.
2924 errcode = pthread_mutex_lock(&tog_mutex);
2925 if (errcode) {
2926 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2927 return (void *)err;
2930 err = block_signals_used_by_main_thread();
2931 if (err) {
2932 pthread_mutex_unlock(&tog_mutex);
2933 goto done;
2936 while (!done && !err && !tog_fatal_signal_received()) {
2937 errcode = pthread_mutex_unlock(&tog_mutex);
2938 if (errcode) {
2939 err = got_error_set_errno(errcode,
2940 "pthread_mutex_unlock");
2941 goto done;
2943 err = queue_commits(a);
2944 if (err) {
2945 if (err->code != GOT_ERR_ITER_COMPLETED)
2946 goto done;
2947 err = NULL;
2948 done = 1;
2949 } else if (a->commits_needed > 0 && !a->load_all) {
2950 if (*a->limiting) {
2951 if (a->limit_match)
2952 a->commits_needed--;
2953 } else
2954 a->commits_needed--;
2957 errcode = pthread_mutex_lock(&tog_mutex);
2958 if (errcode) {
2959 err = got_error_set_errno(errcode,
2960 "pthread_mutex_lock");
2961 goto done;
2962 } else if (*a->quit)
2963 done = 1;
2964 else if (*a->limiting && *a->first_displayed_entry == NULL) {
2965 *a->first_displayed_entry =
2966 TAILQ_FIRST(&a->limit_commits->head);
2967 *a->selected_entry = *a->first_displayed_entry;
2968 } else if (*a->first_displayed_entry == NULL) {
2969 *a->first_displayed_entry =
2970 TAILQ_FIRST(&a->real_commits->head);
2971 *a->selected_entry = *a->first_displayed_entry;
2974 errcode = pthread_cond_signal(&a->commit_loaded);
2975 if (errcode) {
2976 err = got_error_set_errno(errcode,
2977 "pthread_cond_signal");
2978 pthread_mutex_unlock(&tog_mutex);
2979 goto done;
2982 if (done)
2983 a->commits_needed = 0;
2984 else {
2985 if (a->commits_needed == 0 && !a->load_all) {
2986 errcode = pthread_cond_wait(&a->need_commits,
2987 &tog_mutex);
2988 if (errcode) {
2989 err = got_error_set_errno(errcode,
2990 "pthread_cond_wait");
2991 pthread_mutex_unlock(&tog_mutex);
2992 goto done;
2994 if (*a->quit)
2995 done = 1;
2999 a->log_complete = 1;
3000 errcode = pthread_mutex_unlock(&tog_mutex);
3001 if (errcode)
3002 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3003 done:
3004 if (err) {
3005 tog_thread_error = 1;
3006 pthread_cond_signal(&a->commit_loaded);
3008 return (void *)err;
3011 static const struct got_error *
3012 stop_log_thread(struct tog_log_view_state *s)
3014 const struct got_error *err = NULL, *thread_err = NULL;
3015 int errcode;
3017 if (s->thread) {
3018 s->quit = 1;
3019 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3020 if (errcode)
3021 return got_error_set_errno(errcode,
3022 "pthread_cond_signal");
3023 errcode = pthread_mutex_unlock(&tog_mutex);
3024 if (errcode)
3025 return got_error_set_errno(errcode,
3026 "pthread_mutex_unlock");
3027 errcode = pthread_join(s->thread, (void **)&thread_err);
3028 if (errcode)
3029 return got_error_set_errno(errcode, "pthread_join");
3030 errcode = pthread_mutex_lock(&tog_mutex);
3031 if (errcode)
3032 return got_error_set_errno(errcode,
3033 "pthread_mutex_lock");
3034 s->thread = NULL;
3037 if (s->thread_args.repo) {
3038 err = got_repo_close(s->thread_args.repo);
3039 s->thread_args.repo = NULL;
3042 if (s->thread_args.pack_fds) {
3043 const struct got_error *pack_err =
3044 got_repo_pack_fds_close(s->thread_args.pack_fds);
3045 if (err == NULL)
3046 err = pack_err;
3047 s->thread_args.pack_fds = NULL;
3050 if (s->thread_args.graph) {
3051 got_commit_graph_close(s->thread_args.graph);
3052 s->thread_args.graph = NULL;
3055 return err ? err : thread_err;
3058 static const struct got_error *
3059 close_log_view(struct tog_view *view)
3061 const struct got_error *err = NULL;
3062 struct tog_log_view_state *s = &view->state.log;
3063 int errcode;
3065 err = stop_log_thread(s);
3067 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3068 if (errcode && err == NULL)
3069 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3071 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3072 if (errcode && err == NULL)
3073 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3075 free_commits(&s->limit_commits);
3076 free_commits(&s->real_commits);
3077 free(s->in_repo_path);
3078 s->in_repo_path = NULL;
3079 free(s->start_id);
3080 s->start_id = NULL;
3081 free(s->head_ref_name);
3082 s->head_ref_name = NULL;
3083 return err;
3087 * We use two queues to implement the limit feature: first consists of
3088 * commits matching the current limit_regex; second is the real queue
3089 * of all known commits (real_commits). When the user starts limiting,
3090 * we swap queues such that all movement and displaying functionality
3091 * works with very slight change.
3093 static const struct got_error *
3094 limit_log_view(struct tog_view *view)
3096 struct tog_log_view_state *s = &view->state.log;
3097 struct commit_queue_entry *entry;
3098 struct tog_view *v = view;
3099 const struct got_error *err = NULL;
3100 char pattern[1024];
3101 int ret;
3103 if (view_is_hsplit_top(view))
3104 v = view->child;
3105 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3106 v = view->parent;
3108 /* Get the pattern */
3109 wmove(v->window, v->nlines - 1, 0);
3110 wclrtoeol(v->window);
3111 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3112 nodelay(v->window, FALSE);
3113 nocbreak();
3114 echo();
3115 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3116 cbreak();
3117 noecho();
3118 nodelay(v->window, TRUE);
3119 if (ret == ERR)
3120 return NULL;
3122 if (*pattern == '\0') {
3124 * Safety measure for the situation where the user
3125 * resets limit without previously limiting anything.
3127 if (!s->limit_view)
3128 return NULL;
3131 * User could have pressed Ctrl+L, which refreshed the
3132 * commit queues, it means we can't save previously
3133 * (before limit took place) displayed entries,
3134 * because they would point to already free'ed memory,
3135 * so we are forced to always select first entry of
3136 * the queue.
3138 s->commits = &s->real_commits;
3139 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3140 s->selected_entry = s->first_displayed_entry;
3141 s->selected = 0;
3142 s->limit_view = 0;
3144 return NULL;
3147 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3148 return NULL;
3150 s->limit_view = 1;
3152 /* Clear the screen while loading limit view */
3153 s->first_displayed_entry = NULL;
3154 s->last_displayed_entry = NULL;
3155 s->selected_entry = NULL;
3156 s->commits = &s->limit_commits;
3158 /* Prepare limit queue for new search */
3159 free_commits(&s->limit_commits);
3160 s->limit_commits.ncommits = 0;
3162 /* First process commits, which are in queue already */
3163 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3164 int have_match = 0;
3166 err = match_commit(&have_match, entry->id,
3167 entry->commit, &s->limit_regex);
3168 if (err)
3169 return err;
3171 if (have_match) {
3172 struct commit_queue_entry *matched;
3174 matched = alloc_commit_queue_entry(entry->commit,
3175 entry->id);
3176 if (matched == NULL) {
3177 err = got_error_from_errno(
3178 "alloc_commit_queue_entry");
3179 break;
3181 matched->commit = entry->commit;
3182 got_object_commit_retain(entry->commit);
3184 matched->idx = s->limit_commits.ncommits;
3185 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3186 matched, entry);
3187 s->limit_commits.ncommits++;
3191 /* Second process all the commits, until we fill the screen */
3192 if (s->limit_commits.ncommits < view->nlines - 1 &&
3193 !s->thread_args.log_complete) {
3194 s->thread_args.commits_needed +=
3195 view->nlines - s->limit_commits.ncommits - 1;
3196 err = trigger_log_thread(view, 1);
3197 if (err)
3198 return err;
3201 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3202 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3203 s->selected = 0;
3205 return NULL;
3208 static const struct got_error *
3209 search_start_log_view(struct tog_view *view)
3211 struct tog_log_view_state *s = &view->state.log;
3213 s->matched_entry = NULL;
3214 s->search_entry = NULL;
3215 return NULL;
3218 static const struct got_error *
3219 search_next_log_view(struct tog_view *view)
3221 const struct got_error *err = NULL;
3222 struct tog_log_view_state *s = &view->state.log;
3223 struct commit_queue_entry *entry;
3225 /* Display progress update in log view. */
3226 show_log_view(view);
3227 update_panels();
3228 doupdate();
3230 if (s->search_entry) {
3231 int errcode, ch;
3232 errcode = pthread_mutex_unlock(&tog_mutex);
3233 if (errcode)
3234 return got_error_set_errno(errcode,
3235 "pthread_mutex_unlock");
3236 ch = wgetch(view->window);
3237 errcode = pthread_mutex_lock(&tog_mutex);
3238 if (errcode)
3239 return got_error_set_errno(errcode,
3240 "pthread_mutex_lock");
3241 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3242 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3243 return NULL;
3245 if (view->searching == TOG_SEARCH_FORWARD)
3246 entry = TAILQ_NEXT(s->search_entry, entry);
3247 else
3248 entry = TAILQ_PREV(s->search_entry,
3249 commit_queue_head, entry);
3250 } else if (s->matched_entry) {
3252 * If the user has moved the cursor after we hit a match,
3253 * the position from where we should continue searching
3254 * might have changed.
3256 if (view->searching == TOG_SEARCH_FORWARD)
3257 entry = TAILQ_NEXT(s->selected_entry, entry);
3258 else
3259 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3260 entry);
3261 } else {
3262 entry = s->selected_entry;
3265 while (1) {
3266 int have_match = 0;
3268 if (entry == NULL) {
3269 if (s->thread_args.log_complete ||
3270 view->searching == TOG_SEARCH_BACKWARD) {
3271 view->search_next_done =
3272 (s->matched_entry == NULL ?
3273 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3274 s->search_entry = NULL;
3275 return NULL;
3278 * Poke the log thread for more commits and return,
3279 * allowing the main loop to make progress. Search
3280 * will resume at s->search_entry once we come back.
3282 s->thread_args.commits_needed++;
3283 return trigger_log_thread(view, 0);
3286 err = match_commit(&have_match, entry->id, entry->commit,
3287 &view->regex);
3288 if (err)
3289 break;
3290 if (have_match) {
3291 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3292 s->matched_entry = entry;
3293 break;
3296 s->search_entry = entry;
3297 if (view->searching == TOG_SEARCH_FORWARD)
3298 entry = TAILQ_NEXT(entry, entry);
3299 else
3300 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3303 if (s->matched_entry) {
3304 int cur = s->selected_entry->idx;
3305 while (cur < s->matched_entry->idx) {
3306 err = input_log_view(NULL, view, KEY_DOWN);
3307 if (err)
3308 return err;
3309 cur++;
3311 while (cur > s->matched_entry->idx) {
3312 err = input_log_view(NULL, view, KEY_UP);
3313 if (err)
3314 return err;
3315 cur--;
3319 s->search_entry = NULL;
3321 return NULL;
3324 static const struct got_error *
3325 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3326 struct got_repository *repo, const char *head_ref_name,
3327 const char *in_repo_path, int log_branches)
3329 const struct got_error *err = NULL;
3330 struct tog_log_view_state *s = &view->state.log;
3331 struct got_repository *thread_repo = NULL;
3332 struct got_commit_graph *thread_graph = NULL;
3333 int errcode;
3335 if (in_repo_path != s->in_repo_path) {
3336 free(s->in_repo_path);
3337 s->in_repo_path = strdup(in_repo_path);
3338 if (s->in_repo_path == NULL)
3339 return got_error_from_errno("strdup");
3342 /* The commit queue only contains commits being displayed. */
3343 TAILQ_INIT(&s->real_commits.head);
3344 s->real_commits.ncommits = 0;
3345 s->commits = &s->real_commits;
3347 TAILQ_INIT(&s->limit_commits.head);
3348 s->limit_view = 0;
3349 s->limit_commits.ncommits = 0;
3351 s->repo = repo;
3352 if (head_ref_name) {
3353 s->head_ref_name = strdup(head_ref_name);
3354 if (s->head_ref_name == NULL) {
3355 err = got_error_from_errno("strdup");
3356 goto done;
3359 s->start_id = got_object_id_dup(start_id);
3360 if (s->start_id == NULL) {
3361 err = got_error_from_errno("got_object_id_dup");
3362 goto done;
3364 s->log_branches = log_branches;
3365 s->use_committer = 1;
3367 STAILQ_INIT(&s->colors);
3368 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3369 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3370 get_color_value("TOG_COLOR_COMMIT"));
3371 if (err)
3372 goto done;
3373 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3374 get_color_value("TOG_COLOR_AUTHOR"));
3375 if (err) {
3376 free_colors(&s->colors);
3377 goto done;
3379 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3380 get_color_value("TOG_COLOR_DATE"));
3381 if (err) {
3382 free_colors(&s->colors);
3383 goto done;
3387 view->show = show_log_view;
3388 view->input = input_log_view;
3389 view->resize = resize_log_view;
3390 view->close = close_log_view;
3391 view->search_start = search_start_log_view;
3392 view->search_next = search_next_log_view;
3394 if (s->thread_args.pack_fds == NULL) {
3395 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3396 if (err)
3397 goto done;
3399 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3400 s->thread_args.pack_fds);
3401 if (err)
3402 goto done;
3403 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3404 !s->log_branches);
3405 if (err)
3406 goto done;
3407 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3408 s->repo, NULL, NULL);
3409 if (err)
3410 goto done;
3412 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3413 if (errcode) {
3414 err = got_error_set_errno(errcode, "pthread_cond_init");
3415 goto done;
3417 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3418 if (errcode) {
3419 err = got_error_set_errno(errcode, "pthread_cond_init");
3420 goto done;
3423 s->thread_args.commits_needed = view->nlines;
3424 s->thread_args.graph = thread_graph;
3425 s->thread_args.real_commits = &s->real_commits;
3426 s->thread_args.limit_commits = &s->limit_commits;
3427 s->thread_args.in_repo_path = s->in_repo_path;
3428 s->thread_args.start_id = s->start_id;
3429 s->thread_args.repo = thread_repo;
3430 s->thread_args.log_complete = 0;
3431 s->thread_args.quit = &s->quit;
3432 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3433 s->thread_args.selected_entry = &s->selected_entry;
3434 s->thread_args.searching = &view->searching;
3435 s->thread_args.search_next_done = &view->search_next_done;
3436 s->thread_args.regex = &view->regex;
3437 s->thread_args.limiting = &s->limit_view;
3438 s->thread_args.limit_regex = &s->limit_regex;
3439 s->thread_args.limit_commits = &s->limit_commits;
3440 done:
3441 if (err)
3442 close_log_view(view);
3443 return err;
3446 static const struct got_error *
3447 show_log_view(struct tog_view *view)
3449 const struct got_error *err;
3450 struct tog_log_view_state *s = &view->state.log;
3452 if (s->thread == NULL) {
3453 int errcode = pthread_create(&s->thread, NULL, log_thread,
3454 &s->thread_args);
3455 if (errcode)
3456 return got_error_set_errno(errcode, "pthread_create");
3457 if (s->thread_args.commits_needed > 0) {
3458 err = trigger_log_thread(view, 1);
3459 if (err)
3460 return err;
3464 return draw_commits(view);
3467 static void
3468 log_move_cursor_up(struct tog_view *view, int page, int home)
3470 struct tog_log_view_state *s = &view->state.log;
3472 if (s->first_displayed_entry == NULL)
3473 return;
3474 if (s->selected_entry->idx == 0)
3475 view->count = 0;
3477 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3478 || home)
3479 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3481 if (!page && !home && s->selected > 0)
3482 --s->selected;
3483 else
3484 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3486 select_commit(s);
3487 return;
3490 static const struct got_error *
3491 log_move_cursor_down(struct tog_view *view, int page)
3493 struct tog_log_view_state *s = &view->state.log;
3494 const struct got_error *err = NULL;
3495 int eos = view->nlines - 2;
3497 if (s->first_displayed_entry == NULL)
3498 return NULL;
3500 if (s->thread_args.log_complete &&
3501 s->selected_entry->idx >= s->commits->ncommits - 1)
3502 return NULL;
3504 if (view_is_hsplit_top(view))
3505 --eos; /* border consumes the last line */
3507 if (!page) {
3508 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3509 ++s->selected;
3510 else
3511 err = log_scroll_down(view, 1);
3512 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3513 struct commit_queue_entry *entry;
3514 int n;
3516 s->selected = 0;
3517 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3518 s->last_displayed_entry = entry;
3519 for (n = 0; n <= eos; n++) {
3520 if (entry == NULL)
3521 break;
3522 s->first_displayed_entry = entry;
3523 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3525 if (n > 0)
3526 s->selected = n - 1;
3527 } else {
3528 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3529 s->thread_args.log_complete)
3530 s->selected += MIN(page,
3531 s->commits->ncommits - s->selected_entry->idx - 1);
3532 else
3533 err = log_scroll_down(view, page);
3535 if (err)
3536 return err;
3539 * We might necessarily overshoot in horizontal
3540 * splits; if so, select the last displayed commit.
3542 if (s->first_displayed_entry && s->last_displayed_entry) {
3543 s->selected = MIN(s->selected,
3544 s->last_displayed_entry->idx -
3545 s->first_displayed_entry->idx);
3548 select_commit(s);
3550 if (s->thread_args.log_complete &&
3551 s->selected_entry->idx == s->commits->ncommits - 1)
3552 view->count = 0;
3554 return NULL;
3557 static void
3558 view_get_split(struct tog_view *view, int *y, int *x)
3560 *x = 0;
3561 *y = 0;
3563 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3564 if (view->child && view->child->resized_y)
3565 *y = view->child->resized_y;
3566 else if (view->resized_y)
3567 *y = view->resized_y;
3568 else
3569 *y = view_split_begin_y(view->lines);
3570 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3571 if (view->child && view->child->resized_x)
3572 *x = view->child->resized_x;
3573 else if (view->resized_x)
3574 *x = view->resized_x;
3575 else
3576 *x = view_split_begin_x(view->begin_x);
3580 /* Split view horizontally at y and offset view->state->selected line. */
3581 static const struct got_error *
3582 view_init_hsplit(struct tog_view *view, int y)
3584 const struct got_error *err = NULL;
3586 view->nlines = y;
3587 view->ncols = COLS;
3588 err = view_resize(view);
3589 if (err)
3590 return err;
3592 err = offset_selection_down(view);
3594 return err;
3597 static const struct got_error *
3598 log_goto_line(struct tog_view *view, int nlines)
3600 const struct got_error *err = NULL;
3601 struct tog_log_view_state *s = &view->state.log;
3602 int g, idx = s->selected_entry->idx;
3604 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3605 return NULL;
3607 g = view->gline;
3608 view->gline = 0;
3610 if (g >= s->first_displayed_entry->idx + 1 &&
3611 g <= s->last_displayed_entry->idx + 1 &&
3612 g - s->first_displayed_entry->idx - 1 < nlines) {
3613 s->selected = g - s->first_displayed_entry->idx - 1;
3614 select_commit(s);
3615 return NULL;
3618 if (idx + 1 < g) {
3619 err = log_move_cursor_down(view, g - idx - 1);
3620 if (!err && g > s->selected_entry->idx + 1)
3621 err = log_move_cursor_down(view,
3622 g - s->first_displayed_entry->idx - 1);
3623 if (err)
3624 return err;
3625 } else if (idx + 1 > g)
3626 log_move_cursor_up(view, idx - g + 1, 0);
3628 if (g < nlines && s->first_displayed_entry->idx == 0)
3629 s->selected = g - 1;
3631 select_commit(s);
3632 return NULL;
3636 static const struct got_error *
3637 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3639 const struct got_error *err = NULL;
3640 struct tog_log_view_state *s = &view->state.log;
3641 int eos, nscroll;
3643 if (s->thread_args.load_all) {
3644 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3645 s->thread_args.load_all = 0;
3646 else if (s->thread_args.log_complete) {
3647 err = log_move_cursor_down(view, s->commits->ncommits);
3648 s->thread_args.load_all = 0;
3650 if (err)
3651 return err;
3654 eos = nscroll = view->nlines - 1;
3655 if (view_is_hsplit_top(view))
3656 --eos; /* border */
3658 if (view->gline)
3659 return log_goto_line(view, eos);
3661 switch (ch) {
3662 case '&':
3663 err = limit_log_view(view);
3664 break;
3665 case 'q':
3666 s->quit = 1;
3667 break;
3668 case '0':
3669 view->x = 0;
3670 break;
3671 case '$':
3672 view->x = MAX(view->maxx - view->ncols / 2, 0);
3673 view->count = 0;
3674 break;
3675 case KEY_RIGHT:
3676 case 'l':
3677 if (view->x + view->ncols / 2 < view->maxx)
3678 view->x += 2; /* move two columns right */
3679 else
3680 view->count = 0;
3681 break;
3682 case KEY_LEFT:
3683 case 'h':
3684 view->x -= MIN(view->x, 2); /* move two columns back */
3685 if (view->x <= 0)
3686 view->count = 0;
3687 break;
3688 case 'k':
3689 case KEY_UP:
3690 case '<':
3691 case ',':
3692 case CTRL('p'):
3693 log_move_cursor_up(view, 0, 0);
3694 break;
3695 case 'g':
3696 case KEY_HOME:
3697 log_move_cursor_up(view, 0, 1);
3698 view->count = 0;
3699 break;
3700 case CTRL('u'):
3701 case 'u':
3702 nscroll /= 2;
3703 /* FALL THROUGH */
3704 case KEY_PPAGE:
3705 case CTRL('b'):
3706 case 'b':
3707 log_move_cursor_up(view, nscroll, 0);
3708 break;
3709 case 'j':
3710 case KEY_DOWN:
3711 case '>':
3712 case '.':
3713 case CTRL('n'):
3714 err = log_move_cursor_down(view, 0);
3715 break;
3716 case '@':
3717 s->use_committer = !s->use_committer;
3718 break;
3719 case 'G':
3720 case KEY_END: {
3721 /* We don't know yet how many commits, so we're forced to
3722 * traverse them all. */
3723 view->count = 0;
3724 s->thread_args.load_all = 1;
3725 if (!s->thread_args.log_complete)
3726 return trigger_log_thread(view, 0);
3727 err = log_move_cursor_down(view, s->commits->ncommits);
3728 s->thread_args.load_all = 0;
3729 break;
3731 case CTRL('d'):
3732 case 'd':
3733 nscroll /= 2;
3734 /* FALL THROUGH */
3735 case KEY_NPAGE:
3736 case CTRL('f'):
3737 case 'f':
3738 case ' ':
3739 err = log_move_cursor_down(view, nscroll);
3740 break;
3741 case KEY_RESIZE:
3742 if (s->selected > view->nlines - 2)
3743 s->selected = view->nlines - 2;
3744 if (s->selected > s->commits->ncommits - 1)
3745 s->selected = s->commits->ncommits - 1;
3746 select_commit(s);
3747 if (s->commits->ncommits < view->nlines - 1 &&
3748 !s->thread_args.log_complete) {
3749 s->thread_args.commits_needed += (view->nlines - 1) -
3750 s->commits->ncommits;
3751 err = trigger_log_thread(view, 1);
3753 break;
3754 case KEY_ENTER:
3755 case '\r':
3756 view->count = 0;
3757 if (s->selected_entry == NULL)
3758 break;
3759 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3760 break;
3761 case 'T':
3762 view->count = 0;
3763 if (s->selected_entry == NULL)
3764 break;
3765 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3766 break;
3767 case KEY_BACKSPACE:
3768 case CTRL('l'):
3769 case 'B':
3770 view->count = 0;
3771 if (ch == KEY_BACKSPACE &&
3772 got_path_is_root_dir(s->in_repo_path))
3773 break;
3774 err = stop_log_thread(s);
3775 if (err)
3776 return err;
3777 if (ch == KEY_BACKSPACE) {
3778 char *parent_path;
3779 err = got_path_dirname(&parent_path, s->in_repo_path);
3780 if (err)
3781 return err;
3782 free(s->in_repo_path);
3783 s->in_repo_path = parent_path;
3784 s->thread_args.in_repo_path = s->in_repo_path;
3785 } else if (ch == CTRL('l')) {
3786 struct got_object_id *start_id;
3787 err = got_repo_match_object_id(&start_id, NULL,
3788 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3789 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3790 if (err) {
3791 if (s->head_ref_name == NULL ||
3792 err->code != GOT_ERR_NOT_REF)
3793 return err;
3794 /* Try to cope with deleted references. */
3795 free(s->head_ref_name);
3796 s->head_ref_name = NULL;
3797 err = got_repo_match_object_id(&start_id,
3798 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
3799 &tog_refs, s->repo);
3800 if (err)
3801 return err;
3803 free(s->start_id);
3804 s->start_id = start_id;
3805 s->thread_args.start_id = s->start_id;
3806 } else /* 'B' */
3807 s->log_branches = !s->log_branches;
3809 if (s->thread_args.pack_fds == NULL) {
3810 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3811 if (err)
3812 return err;
3814 err = got_repo_open(&s->thread_args.repo,
3815 got_repo_get_path(s->repo), NULL,
3816 s->thread_args.pack_fds);
3817 if (err)
3818 return err;
3819 tog_free_refs();
3820 err = tog_load_refs(s->repo, 0);
3821 if (err)
3822 return err;
3823 err = got_commit_graph_open(&s->thread_args.graph,
3824 s->in_repo_path, !s->log_branches);
3825 if (err)
3826 return err;
3827 err = got_commit_graph_iter_start(s->thread_args.graph,
3828 s->start_id, s->repo, NULL, NULL);
3829 if (err)
3830 return err;
3831 free_commits(&s->real_commits);
3832 free_commits(&s->limit_commits);
3833 s->first_displayed_entry = NULL;
3834 s->last_displayed_entry = NULL;
3835 s->selected_entry = NULL;
3836 s->selected = 0;
3837 s->thread_args.log_complete = 0;
3838 s->quit = 0;
3839 s->thread_args.commits_needed = view->lines;
3840 s->matched_entry = NULL;
3841 s->search_entry = NULL;
3842 view->offset = 0;
3843 break;
3844 case 'R':
3845 view->count = 0;
3846 err = view_request_new(new_view, view, TOG_VIEW_REF);
3847 break;
3848 default:
3849 view->count = 0;
3850 break;
3853 return err;
3856 static const struct got_error *
3857 apply_unveil(const char *repo_path, const char *worktree_path)
3859 const struct got_error *error;
3861 #ifdef PROFILE
3862 if (unveil("gmon.out", "rwc") != 0)
3863 return got_error_from_errno2("unveil", "gmon.out");
3864 #endif
3865 if (repo_path && unveil(repo_path, "r") != 0)
3866 return got_error_from_errno2("unveil", repo_path);
3868 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3869 return got_error_from_errno2("unveil", worktree_path);
3871 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3872 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3874 error = got_privsep_unveil_exec_helpers();
3875 if (error != NULL)
3876 return error;
3878 if (unveil(NULL, NULL) != 0)
3879 return got_error_from_errno("unveil");
3881 return NULL;
3884 static void
3885 init_curses(void)
3888 * Override default signal handlers before starting ncurses.
3889 * This should prevent ncurses from installing its own
3890 * broken cleanup() signal handler.
3892 signal(SIGWINCH, tog_sigwinch);
3893 signal(SIGPIPE, tog_sigpipe);
3894 signal(SIGCONT, tog_sigcont);
3895 signal(SIGINT, tog_sigint);
3896 signal(SIGTERM, tog_sigterm);
3898 initscr();
3899 cbreak();
3900 halfdelay(1); /* Do fast refresh while initial view is loading. */
3901 noecho();
3902 nonl();
3903 intrflush(stdscr, FALSE);
3904 keypad(stdscr, TRUE);
3905 curs_set(0);
3906 if (getenv("TOG_COLORS") != NULL) {
3907 start_color();
3908 use_default_colors();
3912 static const struct got_error *
3913 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3914 struct got_repository *repo, struct got_worktree *worktree)
3916 const struct got_error *err = NULL;
3918 if (argc == 0) {
3919 *in_repo_path = strdup("/");
3920 if (*in_repo_path == NULL)
3921 return got_error_from_errno("strdup");
3922 return NULL;
3925 if (worktree) {
3926 const char *prefix = got_worktree_get_path_prefix(worktree);
3927 char *p;
3929 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3930 if (err)
3931 return err;
3932 if (asprintf(in_repo_path, "%s%s%s", prefix,
3933 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3934 p) == -1) {
3935 err = got_error_from_errno("asprintf");
3936 *in_repo_path = NULL;
3938 free(p);
3939 } else
3940 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3942 return err;
3945 static const struct got_error *
3946 cmd_log(int argc, char *argv[])
3948 const struct got_error *error;
3949 struct got_repository *repo = NULL;
3950 struct got_worktree *worktree = NULL;
3951 struct got_object_id *start_id = NULL;
3952 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3953 char *start_commit = NULL, *label = NULL;
3954 struct got_reference *ref = NULL;
3955 const char *head_ref_name = NULL;
3956 int ch, log_branches = 0;
3957 struct tog_view *view;
3958 int *pack_fds = NULL;
3960 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3961 switch (ch) {
3962 case 'b':
3963 log_branches = 1;
3964 break;
3965 case 'c':
3966 start_commit = optarg;
3967 break;
3968 case 'r':
3969 repo_path = realpath(optarg, NULL);
3970 if (repo_path == NULL)
3971 return got_error_from_errno2("realpath",
3972 optarg);
3973 break;
3974 default:
3975 usage_log();
3976 /* NOTREACHED */
3980 argc -= optind;
3981 argv += optind;
3983 if (argc > 1)
3984 usage_log();
3986 error = got_repo_pack_fds_open(&pack_fds);
3987 if (error != NULL)
3988 goto done;
3990 if (repo_path == NULL) {
3991 cwd = getcwd(NULL, 0);
3992 if (cwd == NULL)
3993 return got_error_from_errno("getcwd");
3994 error = got_worktree_open(&worktree, cwd);
3995 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3996 goto done;
3997 if (worktree)
3998 repo_path =
3999 strdup(got_worktree_get_repo_path(worktree));
4000 else
4001 repo_path = strdup(cwd);
4002 if (repo_path == NULL) {
4003 error = got_error_from_errno("strdup");
4004 goto done;
4008 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4009 if (error != NULL)
4010 goto done;
4012 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4013 repo, worktree);
4014 if (error)
4015 goto done;
4017 init_curses();
4019 error = apply_unveil(got_repo_get_path(repo),
4020 worktree ? got_worktree_get_root_path(worktree) : NULL);
4021 if (error)
4022 goto done;
4024 /* already loaded by tog_log_with_path()? */
4025 if (TAILQ_EMPTY(&tog_refs)) {
4026 error = tog_load_refs(repo, 0);
4027 if (error)
4028 goto done;
4031 if (start_commit == NULL) {
4032 error = got_repo_match_object_id(&start_id, &label,
4033 worktree ? got_worktree_get_head_ref_name(worktree) :
4034 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4035 if (error)
4036 goto done;
4037 head_ref_name = label;
4038 } else {
4039 error = got_ref_open(&ref, repo, start_commit, 0);
4040 if (error == NULL)
4041 head_ref_name = got_ref_get_name(ref);
4042 else if (error->code != GOT_ERR_NOT_REF)
4043 goto done;
4044 error = got_repo_match_object_id(&start_id, NULL,
4045 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4046 if (error)
4047 goto done;
4050 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4051 if (view == NULL) {
4052 error = got_error_from_errno("view_open");
4053 goto done;
4055 error = open_log_view(view, start_id, repo, head_ref_name,
4056 in_repo_path, log_branches);
4057 if (error)
4058 goto done;
4059 if (worktree) {
4060 /* Release work tree lock. */
4061 got_worktree_close(worktree);
4062 worktree = NULL;
4064 error = view_loop(view);
4065 done:
4066 free(in_repo_path);
4067 free(repo_path);
4068 free(cwd);
4069 free(start_id);
4070 free(label);
4071 if (ref)
4072 got_ref_close(ref);
4073 if (repo) {
4074 const struct got_error *close_err = got_repo_close(repo);
4075 if (error == NULL)
4076 error = close_err;
4078 if (worktree)
4079 got_worktree_close(worktree);
4080 if (pack_fds) {
4081 const struct got_error *pack_err =
4082 got_repo_pack_fds_close(pack_fds);
4083 if (error == NULL)
4084 error = pack_err;
4086 tog_free_refs();
4087 return error;
4090 __dead static void
4091 usage_diff(void)
4093 endwin();
4094 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4095 "object1 object2\n", getprogname());
4096 exit(1);
4099 static int
4100 match_line(const char *line, regex_t *regex, size_t nmatch,
4101 regmatch_t *regmatch)
4103 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4106 static struct tog_color *
4107 match_color(struct tog_colors *colors, const char *line)
4109 struct tog_color *tc = NULL;
4111 STAILQ_FOREACH(tc, colors, entry) {
4112 if (match_line(line, &tc->regex, 0, NULL))
4113 return tc;
4116 return NULL;
4119 static const struct got_error *
4120 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4121 WINDOW *window, int skipcol, regmatch_t *regmatch)
4123 const struct got_error *err = NULL;
4124 char *exstr = NULL;
4125 wchar_t *wline = NULL;
4126 int rme, rms, n, width, scrollx;
4127 int width0 = 0, width1 = 0, width2 = 0;
4128 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4130 *wtotal = 0;
4132 rms = regmatch->rm_so;
4133 rme = regmatch->rm_eo;
4135 err = expand_tab(&exstr, line);
4136 if (err)
4137 return err;
4139 /* Split the line into 3 segments, according to match offsets. */
4140 seg0 = strndup(exstr, rms);
4141 if (seg0 == NULL) {
4142 err = got_error_from_errno("strndup");
4143 goto done;
4145 seg1 = strndup(exstr + rms, rme - rms);
4146 if (seg1 == NULL) {
4147 err = got_error_from_errno("strndup");
4148 goto done;
4150 seg2 = strdup(exstr + rme);
4151 if (seg2 == NULL) {
4152 err = got_error_from_errno("strndup");
4153 goto done;
4156 /* draw up to matched token if we haven't scrolled past it */
4157 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4158 col_tab_align, 1);
4159 if (err)
4160 goto done;
4161 n = MAX(width0 - skipcol, 0);
4162 if (n) {
4163 free(wline);
4164 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4165 wlimit, col_tab_align, 1);
4166 if (err)
4167 goto done;
4168 waddwstr(window, &wline[scrollx]);
4169 wlimit -= width;
4170 *wtotal += width;
4173 if (wlimit > 0) {
4174 int i = 0, w = 0;
4175 size_t wlen;
4177 free(wline);
4178 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4179 col_tab_align, 1);
4180 if (err)
4181 goto done;
4182 wlen = wcslen(wline);
4183 while (i < wlen) {
4184 width = wcwidth(wline[i]);
4185 if (width == -1) {
4186 /* should not happen, tabs are expanded */
4187 err = got_error(GOT_ERR_RANGE);
4188 goto done;
4190 if (width0 + w + width > skipcol)
4191 break;
4192 w += width;
4193 i++;
4195 /* draw (visible part of) matched token (if scrolled into it) */
4196 if (width1 - w > 0) {
4197 wattron(window, A_STANDOUT);
4198 waddwstr(window, &wline[i]);
4199 wattroff(window, A_STANDOUT);
4200 wlimit -= (width1 - w);
4201 *wtotal += (width1 - w);
4205 if (wlimit > 0) { /* draw rest of line */
4206 free(wline);
4207 if (skipcol > width0 + width1) {
4208 err = format_line(&wline, &width2, &scrollx, seg2,
4209 skipcol - (width0 + width1), wlimit,
4210 col_tab_align, 1);
4211 if (err)
4212 goto done;
4213 waddwstr(window, &wline[scrollx]);
4214 } else {
4215 err = format_line(&wline, &width2, NULL, seg2, 0,
4216 wlimit, col_tab_align, 1);
4217 if (err)
4218 goto done;
4219 waddwstr(window, wline);
4221 *wtotal += width2;
4223 done:
4224 free(wline);
4225 free(exstr);
4226 free(seg0);
4227 free(seg1);
4228 free(seg2);
4229 return err;
4232 static int
4233 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4235 FILE *f = NULL;
4236 int *eof, *first, *selected;
4238 if (view->type == TOG_VIEW_DIFF) {
4239 struct tog_diff_view_state *s = &view->state.diff;
4241 first = &s->first_displayed_line;
4242 selected = first;
4243 eof = &s->eof;
4244 f = s->f;
4245 } else if (view->type == TOG_VIEW_HELP) {
4246 struct tog_help_view_state *s = &view->state.help;
4248 first = &s->first_displayed_line;
4249 selected = first;
4250 eof = &s->eof;
4251 f = s->f;
4252 } else if (view->type == TOG_VIEW_BLAME) {
4253 struct tog_blame_view_state *s = &view->state.blame;
4255 first = &s->first_displayed_line;
4256 selected = &s->selected_line;
4257 eof = &s->eof;
4258 f = s->blame.f;
4259 } else
4260 return 0;
4262 /* Center gline in the middle of the page like vi(1). */
4263 if (*lineno < view->gline - (view->nlines - 3) / 2)
4264 return 0;
4265 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4266 rewind(f);
4267 *eof = 0;
4268 *first = 1;
4269 *lineno = 0;
4270 *nprinted = 0;
4271 return 0;
4274 *selected = view->gline <= (view->nlines - 3) / 2 ?
4275 view->gline : (view->nlines - 3) / 2 + 1;
4276 view->gline = 0;
4278 return 1;
4281 static const struct got_error *
4282 draw_file(struct tog_view *view, const char *header)
4284 struct tog_diff_view_state *s = &view->state.diff;
4285 regmatch_t *regmatch = &view->regmatch;
4286 const struct got_error *err;
4287 int nprinted = 0;
4288 char *line;
4289 size_t linesize = 0;
4290 ssize_t linelen;
4291 wchar_t *wline;
4292 int width;
4293 int max_lines = view->nlines;
4294 int nlines = s->nlines;
4295 off_t line_offset;
4297 s->lineno = s->first_displayed_line - 1;
4298 line_offset = s->lines[s->first_displayed_line - 1].offset;
4299 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4300 return got_error_from_errno("fseek");
4302 werase(view->window);
4304 if (view->gline > s->nlines - 1)
4305 view->gline = s->nlines - 1;
4307 if (header) {
4308 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4309 1 : view->gline - (view->nlines - 3) / 2 :
4310 s->lineno + s->selected_line;
4312 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4313 return got_error_from_errno("asprintf");
4314 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4315 0, 0);
4316 free(line);
4317 if (err)
4318 return err;
4320 if (view_needs_focus_indication(view))
4321 wstandout(view->window);
4322 waddwstr(view->window, wline);
4323 free(wline);
4324 wline = NULL;
4325 while (width++ < view->ncols)
4326 waddch(view->window, ' ');
4327 if (view_needs_focus_indication(view))
4328 wstandend(view->window);
4330 if (max_lines <= 1)
4331 return NULL;
4332 max_lines--;
4335 s->eof = 0;
4336 view->maxx = 0;
4337 line = NULL;
4338 while (max_lines > 0 && nprinted < max_lines) {
4339 enum got_diff_line_type linetype;
4340 attr_t attr = 0;
4342 linelen = getline(&line, &linesize, s->f);
4343 if (linelen == -1) {
4344 if (feof(s->f)) {
4345 s->eof = 1;
4346 break;
4348 free(line);
4349 return got_ferror(s->f, GOT_ERR_IO);
4352 if (++s->lineno < s->first_displayed_line)
4353 continue;
4354 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4355 continue;
4356 if (s->lineno == view->hiline)
4357 attr = A_STANDOUT;
4359 /* Set view->maxx based on full line length. */
4360 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4361 view->x ? 1 : 0);
4362 if (err) {
4363 free(line);
4364 return err;
4366 view->maxx = MAX(view->maxx, width);
4367 free(wline);
4368 wline = NULL;
4370 linetype = s->lines[s->lineno].type;
4371 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4372 linetype < GOT_DIFF_LINE_CONTEXT)
4373 attr |= COLOR_PAIR(linetype);
4374 if (attr)
4375 wattron(view->window, attr);
4376 if (s->first_displayed_line + nprinted == s->matched_line &&
4377 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4378 err = add_matched_line(&width, line, view->ncols, 0,
4379 view->window, view->x, regmatch);
4380 if (err) {
4381 free(line);
4382 return err;
4384 } else {
4385 int skip;
4386 err = format_line(&wline, &width, &skip, line,
4387 view->x, view->ncols, 0, view->x ? 1 : 0);
4388 if (err) {
4389 free(line);
4390 return err;
4392 waddwstr(view->window, &wline[skip]);
4393 free(wline);
4394 wline = NULL;
4396 if (s->lineno == view->hiline) {
4397 /* highlight full gline length */
4398 while (width++ < view->ncols)
4399 waddch(view->window, ' ');
4400 } else {
4401 if (width <= view->ncols - 1)
4402 waddch(view->window, '\n');
4404 if (attr)
4405 wattroff(view->window, attr);
4406 if (++nprinted == 1)
4407 s->first_displayed_line = s->lineno;
4409 free(line);
4410 if (nprinted >= 1)
4411 s->last_displayed_line = s->first_displayed_line +
4412 (nprinted - 1);
4413 else
4414 s->last_displayed_line = s->first_displayed_line;
4416 view_border(view);
4418 if (s->eof) {
4419 while (nprinted < view->nlines) {
4420 waddch(view->window, '\n');
4421 nprinted++;
4424 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4425 view->ncols, 0, 0);
4426 if (err) {
4427 return err;
4430 wstandout(view->window);
4431 waddwstr(view->window, wline);
4432 free(wline);
4433 wline = NULL;
4434 wstandend(view->window);
4437 return NULL;
4440 static char *
4441 get_datestr(time_t *time, char *datebuf)
4443 struct tm mytm, *tm;
4444 char *p, *s;
4446 tm = gmtime_r(time, &mytm);
4447 if (tm == NULL)
4448 return NULL;
4449 s = asctime_r(tm, datebuf);
4450 if (s == NULL)
4451 return NULL;
4452 p = strchr(s, '\n');
4453 if (p)
4454 *p = '\0';
4455 return s;
4458 static const struct got_error *
4459 get_changed_paths(struct got_pathlist_head *paths,
4460 struct got_commit_object *commit, struct got_repository *repo,
4461 struct got_diffstat_cb_arg *dsa)
4463 const struct got_error *err = NULL;
4464 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4465 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4466 struct got_object_qid *qid;
4467 FILE *f1 = NULL, *f2 = NULL;
4468 int fd1 = -1, fd2 = -1;
4470 f1 = got_opentemp();
4471 if (f1 == NULL) {
4472 err = got_error_from_errno("got_opentemp");
4473 goto done;
4475 f2 = got_opentemp();
4476 if (f2 == NULL) {
4477 err = got_error_from_errno("got_opentemp");
4478 goto done;
4481 fd1 = got_opentempfd();
4482 if (fd1 == -1) {
4483 err = got_error_from_errno("got_opentempfd");
4484 goto done;
4486 fd2 = got_opentempfd();
4487 if (fd2 == -1) {
4488 err = got_error_from_errno("got_opentempfd");
4489 goto done;
4492 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4493 if (qid != NULL) {
4494 struct got_commit_object *pcommit;
4495 err = got_object_open_as_commit(&pcommit, repo,
4496 &qid->id);
4497 if (err)
4498 return err;
4500 tree_id1 = got_object_id_dup(
4501 got_object_commit_get_tree_id(pcommit));
4502 if (tree_id1 == NULL) {
4503 got_object_commit_close(pcommit);
4504 return got_error_from_errno("got_object_id_dup");
4506 got_object_commit_close(pcommit);
4510 if (tree_id1) {
4511 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4512 if (err)
4513 goto done;
4516 tree_id2 = got_object_commit_get_tree_id(commit);
4517 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4518 if (err)
4519 goto done;
4521 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
4522 got_diff_tree_compute_diffstat, dsa, 1);
4523 done:
4524 if (tree1)
4525 got_object_tree_close(tree1);
4526 if (tree2)
4527 got_object_tree_close(tree2);
4528 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4529 err = got_error_from_errno("close");
4530 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4531 err = got_error_from_errno("close");
4532 if (f1 && fclose(f1) == EOF && err == NULL)
4533 err = got_error_from_errno("fclose");
4534 if (f2 && fclose(f2) == EOF && err == NULL)
4535 err = got_error_from_errno("fclose");
4536 free(tree_id1);
4537 return err;
4540 static const struct got_error *
4541 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4542 off_t off, uint8_t type)
4544 struct got_diff_line *p;
4546 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4547 if (p == NULL)
4548 return got_error_from_errno("reallocarray");
4549 *lines = p;
4550 (*lines)[*nlines].offset = off;
4551 (*lines)[*nlines].type = type;
4552 (*nlines)++;
4554 return NULL;
4557 static const struct got_error *
4558 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4559 struct got_object_id *commit_id, struct got_reflist_head *refs,
4560 struct got_repository *repo, int ignore_ws, int force_text_diff,
4561 FILE *outfile)
4563 const struct got_error *err = NULL;
4564 char datebuf[26], *datestr;
4565 struct got_commit_object *commit;
4566 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4567 time_t committer_time;
4568 const char *author, *committer;
4569 char *refs_str = NULL;
4570 struct got_pathlist_head changed_paths;
4571 struct got_pathlist_entry *pe;
4572 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0, &changed_paths,
4573 ignore_ws, force_text_diff, tog_diff_algo };
4574 off_t outoff = 0;
4575 int n;
4577 TAILQ_INIT(&changed_paths);
4579 if (refs) {
4580 err = build_refs_str(&refs_str, refs, commit_id, repo);
4581 if (err)
4582 return err;
4585 err = got_object_open_as_commit(&commit, repo, commit_id);
4586 if (err)
4587 return err;
4589 err = got_object_id_str(&id_str, commit_id);
4590 if (err) {
4591 err = got_error_from_errno("got_object_id_str");
4592 goto done;
4595 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4596 if (err)
4597 goto done;
4599 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4600 refs_str ? refs_str : "", refs_str ? ")" : "");
4601 if (n < 0) {
4602 err = got_error_from_errno("fprintf");
4603 goto done;
4605 outoff += n;
4606 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4607 if (err)
4608 goto done;
4610 n = fprintf(outfile, "from: %s\n",
4611 got_object_commit_get_author(commit));
4612 if (n < 0) {
4613 err = got_error_from_errno("fprintf");
4614 goto done;
4616 outoff += n;
4617 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4618 if (err)
4619 goto done;
4621 committer_time = got_object_commit_get_committer_time(commit);
4622 datestr = get_datestr(&committer_time, datebuf);
4623 if (datestr) {
4624 n = fprintf(outfile, "date: %s UTC\n", datestr);
4625 if (n < 0) {
4626 err = got_error_from_errno("fprintf");
4627 goto done;
4629 outoff += n;
4630 err = add_line_metadata(lines, nlines, outoff,
4631 GOT_DIFF_LINE_DATE);
4632 if (err)
4633 goto done;
4635 author = got_object_commit_get_author(commit);
4636 committer = got_object_commit_get_committer(commit);
4637 if (strcmp(author, committer) != 0) {
4638 n = fprintf(outfile, "via: %s\n", committer);
4639 if (n < 0) {
4640 err = got_error_from_errno("fprintf");
4641 goto done;
4643 outoff += n;
4644 err = add_line_metadata(lines, nlines, outoff,
4645 GOT_DIFF_LINE_AUTHOR);
4646 if (err)
4647 goto done;
4649 if (got_object_commit_get_nparents(commit) > 1) {
4650 const struct got_object_id_queue *parent_ids;
4651 struct got_object_qid *qid;
4652 int pn = 1;
4653 parent_ids = got_object_commit_get_parent_ids(commit);
4654 STAILQ_FOREACH(qid, parent_ids, entry) {
4655 err = got_object_id_str(&id_str, &qid->id);
4656 if (err)
4657 goto done;
4658 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4659 if (n < 0) {
4660 err = got_error_from_errno("fprintf");
4661 goto done;
4663 outoff += n;
4664 err = add_line_metadata(lines, nlines, outoff,
4665 GOT_DIFF_LINE_META);
4666 if (err)
4667 goto done;
4668 free(id_str);
4669 id_str = NULL;
4673 err = got_object_commit_get_logmsg(&logmsg, commit);
4674 if (err)
4675 goto done;
4676 s = logmsg;
4677 while ((line = strsep(&s, "\n")) != NULL) {
4678 n = fprintf(outfile, "%s\n", line);
4679 if (n < 0) {
4680 err = got_error_from_errno("fprintf");
4681 goto done;
4683 outoff += n;
4684 err = add_line_metadata(lines, nlines, outoff,
4685 GOT_DIFF_LINE_LOGMSG);
4686 if (err)
4687 goto done;
4690 err = get_changed_paths(&changed_paths, commit, repo, &dsa);
4691 if (err)
4692 goto done;
4694 TAILQ_FOREACH(pe, &changed_paths, entry) {
4695 struct got_diff_changed_path *cp = pe->data;
4696 int pad = dsa.max_path_len - pe->path_len + 1;
4698 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4699 pe->path, pad, ' ', dsa.add_cols + 1, cp->add,
4700 dsa.rm_cols + 1, cp->rm);
4701 if (n < 0) {
4702 err = got_error_from_errno("fprintf");
4703 goto done;
4705 outoff += n;
4706 err = add_line_metadata(lines, nlines, outoff,
4707 GOT_DIFF_LINE_CHANGES);
4708 if (err)
4709 goto done;
4710 free((char *)pe->path);
4711 free(pe->data);
4714 fputc('\n', outfile);
4715 outoff++;
4716 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4717 if (err)
4718 goto done;
4720 n = fprintf(outfile,
4721 "%d file%s changed, %d insertions(+), %d deletions(-)\n",
4722 dsa.nfiles, dsa.nfiles > 1 ? "s" : "", dsa.ins, dsa.del);
4723 if (n < 0) {
4724 err = got_error_from_errno("fprintf");
4725 goto done;
4727 outoff += n;
4728 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4729 if (err)
4730 goto done;
4732 fputc('\n', outfile);
4733 outoff++;
4734 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4735 done:
4736 got_pathlist_free(&changed_paths);
4737 free(id_str);
4738 free(logmsg);
4739 free(refs_str);
4740 got_object_commit_close(commit);
4741 if (err) {
4742 free(*lines);
4743 *lines = NULL;
4744 *nlines = 0;
4746 return err;
4749 static const struct got_error *
4750 create_diff(struct tog_diff_view_state *s)
4752 const struct got_error *err = NULL;
4753 FILE *f = NULL;
4754 int obj_type;
4756 free(s->lines);
4757 s->lines = malloc(sizeof(*s->lines));
4758 if (s->lines == NULL)
4759 return got_error_from_errno("malloc");
4760 s->nlines = 0;
4762 f = got_opentemp();
4763 if (f == NULL) {
4764 err = got_error_from_errno("got_opentemp");
4765 goto done;
4767 if (s->f && fclose(s->f) == EOF) {
4768 err = got_error_from_errno("fclose");
4769 goto done;
4771 s->f = f;
4773 if (s->id1)
4774 err = got_object_get_type(&obj_type, s->repo, s->id1);
4775 else
4776 err = got_object_get_type(&obj_type, s->repo, s->id2);
4777 if (err)
4778 goto done;
4780 switch (obj_type) {
4781 case GOT_OBJ_TYPE_BLOB:
4782 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4783 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4784 s->label1, s->label2, tog_diff_algo, s->diff_context,
4785 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4786 break;
4787 case GOT_OBJ_TYPE_TREE:
4788 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4789 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4790 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4791 s->force_text_diff, s->repo, s->f);
4792 break;
4793 case GOT_OBJ_TYPE_COMMIT: {
4794 const struct got_object_id_queue *parent_ids;
4795 struct got_object_qid *pid;
4796 struct got_commit_object *commit2;
4797 struct got_reflist_head *refs;
4799 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4800 if (err)
4801 goto done;
4802 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4803 /* Show commit info if we're diffing to a parent/root commit. */
4804 if (s->id1 == NULL) {
4805 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4806 refs, s->repo, s->ignore_whitespace,
4807 s->force_text_diff, s->f);
4808 if (err)
4809 goto done;
4810 } else {
4811 parent_ids = got_object_commit_get_parent_ids(commit2);
4812 STAILQ_FOREACH(pid, parent_ids, entry) {
4813 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4814 err = write_commit_info(&s->lines,
4815 &s->nlines, s->id2, refs, s->repo,
4816 s->ignore_whitespace,
4817 s->force_text_diff, s->f);
4818 if (err)
4819 goto done;
4820 break;
4824 got_object_commit_close(commit2);
4826 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4827 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4828 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4829 s->force_text_diff, s->repo, s->f);
4830 break;
4832 default:
4833 err = got_error(GOT_ERR_OBJ_TYPE);
4834 break;
4836 done:
4837 if (s->f && fflush(s->f) != 0 && err == NULL)
4838 err = got_error_from_errno("fflush");
4839 return err;
4842 static void
4843 diff_view_indicate_progress(struct tog_view *view)
4845 mvwaddstr(view->window, 0, 0, "diffing...");
4846 update_panels();
4847 doupdate();
4850 static const struct got_error *
4851 search_start_diff_view(struct tog_view *view)
4853 struct tog_diff_view_state *s = &view->state.diff;
4855 s->matched_line = 0;
4856 return NULL;
4859 static void
4860 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4861 size_t *nlines, int **first, int **last, int **match, int **selected)
4863 struct tog_diff_view_state *s = &view->state.diff;
4865 *f = s->f;
4866 *nlines = s->nlines;
4867 *line_offsets = NULL;
4868 *match = &s->matched_line;
4869 *first = &s->first_displayed_line;
4870 *last = &s->last_displayed_line;
4871 *selected = &s->selected_line;
4874 static const struct got_error *
4875 search_next_view_match(struct tog_view *view)
4877 const struct got_error *err = NULL;
4878 FILE *f;
4879 int lineno;
4880 char *line = NULL;
4881 size_t linesize = 0;
4882 ssize_t linelen;
4883 off_t *line_offsets;
4884 size_t nlines = 0;
4885 int *first, *last, *match, *selected;
4887 if (!view->search_setup)
4888 return got_error_msg(GOT_ERR_NOT_IMPL,
4889 "view search not supported");
4890 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4891 &match, &selected);
4893 if (!view->searching) {
4894 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4895 return NULL;
4898 if (*match) {
4899 if (view->searching == TOG_SEARCH_FORWARD)
4900 lineno = *match + 1;
4901 else
4902 lineno = *match - 1;
4903 } else
4904 lineno = *first - 1 + *selected;
4906 while (1) {
4907 off_t offset;
4909 if (lineno <= 0 || lineno > nlines) {
4910 if (*match == 0) {
4911 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4912 break;
4915 if (view->searching == TOG_SEARCH_FORWARD)
4916 lineno = 1;
4917 else
4918 lineno = nlines;
4921 offset = view->type == TOG_VIEW_DIFF ?
4922 view->state.diff.lines[lineno - 1].offset :
4923 line_offsets[lineno - 1];
4924 if (fseeko(f, offset, SEEK_SET) != 0) {
4925 free(line);
4926 return got_error_from_errno("fseeko");
4928 linelen = getline(&line, &linesize, f);
4929 if (linelen != -1) {
4930 char *exstr;
4931 err = expand_tab(&exstr, line);
4932 if (err)
4933 break;
4934 if (match_line(exstr, &view->regex, 1,
4935 &view->regmatch)) {
4936 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4937 *match = lineno;
4938 free(exstr);
4939 break;
4941 free(exstr);
4943 if (view->searching == TOG_SEARCH_FORWARD)
4944 lineno++;
4945 else
4946 lineno--;
4948 free(line);
4950 if (*match) {
4951 *first = *match;
4952 *selected = 1;
4955 return err;
4958 static const struct got_error *
4959 close_diff_view(struct tog_view *view)
4961 const struct got_error *err = NULL;
4962 struct tog_diff_view_state *s = &view->state.diff;
4964 free(s->id1);
4965 s->id1 = NULL;
4966 free(s->id2);
4967 s->id2 = NULL;
4968 if (s->f && fclose(s->f) == EOF)
4969 err = got_error_from_errno("fclose");
4970 s->f = NULL;
4971 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4972 err = got_error_from_errno("fclose");
4973 s->f1 = NULL;
4974 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4975 err = got_error_from_errno("fclose");
4976 s->f2 = NULL;
4977 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4978 err = got_error_from_errno("close");
4979 s->fd1 = -1;
4980 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4981 err = got_error_from_errno("close");
4982 s->fd2 = -1;
4983 free(s->lines);
4984 s->lines = NULL;
4985 s->nlines = 0;
4986 return err;
4989 static const struct got_error *
4990 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4991 struct got_object_id *id2, const char *label1, const char *label2,
4992 int diff_context, int ignore_whitespace, int force_text_diff,
4993 struct tog_view *parent_view, struct got_repository *repo)
4995 const struct got_error *err;
4996 struct tog_diff_view_state *s = &view->state.diff;
4998 memset(s, 0, sizeof(*s));
4999 s->fd1 = -1;
5000 s->fd2 = -1;
5002 if (id1 != NULL && id2 != NULL) {
5003 int type1, type2;
5004 err = got_object_get_type(&type1, repo, id1);
5005 if (err)
5006 return err;
5007 err = got_object_get_type(&type2, repo, id2);
5008 if (err)
5009 return err;
5011 if (type1 != type2)
5012 return got_error(GOT_ERR_OBJ_TYPE);
5014 s->first_displayed_line = 1;
5015 s->last_displayed_line = view->nlines;
5016 s->selected_line = 1;
5017 s->repo = repo;
5018 s->id1 = id1;
5019 s->id2 = id2;
5020 s->label1 = label1;
5021 s->label2 = label2;
5023 if (id1) {
5024 s->id1 = got_object_id_dup(id1);
5025 if (s->id1 == NULL)
5026 return got_error_from_errno("got_object_id_dup");
5027 } else
5028 s->id1 = NULL;
5030 s->id2 = got_object_id_dup(id2);
5031 if (s->id2 == NULL) {
5032 err = got_error_from_errno("got_object_id_dup");
5033 goto done;
5036 s->f1 = got_opentemp();
5037 if (s->f1 == NULL) {
5038 err = got_error_from_errno("got_opentemp");
5039 goto done;
5042 s->f2 = got_opentemp();
5043 if (s->f2 == NULL) {
5044 err = got_error_from_errno("got_opentemp");
5045 goto done;
5048 s->fd1 = got_opentempfd();
5049 if (s->fd1 == -1) {
5050 err = got_error_from_errno("got_opentempfd");
5051 goto done;
5054 s->fd2 = got_opentempfd();
5055 if (s->fd2 == -1) {
5056 err = got_error_from_errno("got_opentempfd");
5057 goto done;
5060 s->first_displayed_line = 1;
5061 s->last_displayed_line = view->nlines;
5062 s->diff_context = diff_context;
5063 s->ignore_whitespace = ignore_whitespace;
5064 s->force_text_diff = force_text_diff;
5065 s->parent_view = parent_view;
5066 s->repo = repo;
5068 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5069 int rc;
5071 rc = init_pair(GOT_DIFF_LINE_MINUS,
5072 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5073 if (rc != ERR)
5074 rc = init_pair(GOT_DIFF_LINE_PLUS,
5075 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5076 if (rc != ERR)
5077 rc = init_pair(GOT_DIFF_LINE_HUNK,
5078 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5079 if (rc != ERR)
5080 rc = init_pair(GOT_DIFF_LINE_META,
5081 get_color_value("TOG_COLOR_DIFF_META"), -1);
5082 if (rc != ERR)
5083 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5084 get_color_value("TOG_COLOR_DIFF_META"), -1);
5085 if (rc != ERR)
5086 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5087 get_color_value("TOG_COLOR_DIFF_META"), -1);
5088 if (rc != ERR)
5089 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5090 get_color_value("TOG_COLOR_DIFF_META"), -1);
5091 if (rc != ERR)
5092 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5093 get_color_value("TOG_COLOR_AUTHOR"), -1);
5094 if (rc != ERR)
5095 rc = init_pair(GOT_DIFF_LINE_DATE,
5096 get_color_value("TOG_COLOR_DATE"), -1);
5097 if (rc == ERR) {
5098 err = got_error(GOT_ERR_RANGE);
5099 goto done;
5103 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5104 view_is_splitscreen(view))
5105 show_log_view(parent_view); /* draw border */
5106 diff_view_indicate_progress(view);
5108 err = create_diff(s);
5110 view->show = show_diff_view;
5111 view->input = input_diff_view;
5112 view->reset = reset_diff_view;
5113 view->close = close_diff_view;
5114 view->search_start = search_start_diff_view;
5115 view->search_setup = search_setup_diff_view;
5116 view->search_next = search_next_view_match;
5117 done:
5118 if (err)
5119 close_diff_view(view);
5120 return err;
5123 static const struct got_error *
5124 show_diff_view(struct tog_view *view)
5126 const struct got_error *err;
5127 struct tog_diff_view_state *s = &view->state.diff;
5128 char *id_str1 = NULL, *id_str2, *header;
5129 const char *label1, *label2;
5131 if (s->id1) {
5132 err = got_object_id_str(&id_str1, s->id1);
5133 if (err)
5134 return err;
5135 label1 = s->label1 ? s->label1 : id_str1;
5136 } else
5137 label1 = "/dev/null";
5139 err = got_object_id_str(&id_str2, s->id2);
5140 if (err)
5141 return err;
5142 label2 = s->label2 ? s->label2 : id_str2;
5144 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5145 err = got_error_from_errno("asprintf");
5146 free(id_str1);
5147 free(id_str2);
5148 return err;
5150 free(id_str1);
5151 free(id_str2);
5153 err = draw_file(view, header);
5154 free(header);
5155 return err;
5158 static const struct got_error *
5159 set_selected_commit(struct tog_diff_view_state *s,
5160 struct commit_queue_entry *entry)
5162 const struct got_error *err;
5163 const struct got_object_id_queue *parent_ids;
5164 struct got_commit_object *selected_commit;
5165 struct got_object_qid *pid;
5167 free(s->id2);
5168 s->id2 = got_object_id_dup(entry->id);
5169 if (s->id2 == NULL)
5170 return got_error_from_errno("got_object_id_dup");
5172 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5173 if (err)
5174 return err;
5175 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5176 free(s->id1);
5177 pid = STAILQ_FIRST(parent_ids);
5178 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5179 got_object_commit_close(selected_commit);
5180 return NULL;
5183 static const struct got_error *
5184 reset_diff_view(struct tog_view *view)
5186 struct tog_diff_view_state *s = &view->state.diff;
5188 view->count = 0;
5189 wclear(view->window);
5190 s->first_displayed_line = 1;
5191 s->last_displayed_line = view->nlines;
5192 s->matched_line = 0;
5193 diff_view_indicate_progress(view);
5194 return create_diff(s);
5197 static void
5198 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5200 int start, i;
5202 i = start = s->first_displayed_line - 1;
5204 while (s->lines[i].type != type) {
5205 if (i == 0)
5206 i = s->nlines - 1;
5207 if (--i == start)
5208 return; /* do nothing, requested type not in file */
5211 s->selected_line = 1;
5212 s->first_displayed_line = i;
5215 static void
5216 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5218 int start, i;
5220 i = start = s->first_displayed_line + 1;
5222 while (s->lines[i].type != type) {
5223 if (i == s->nlines - 1)
5224 i = 0;
5225 if (++i == start)
5226 return; /* do nothing, requested type not in file */
5229 s->selected_line = 1;
5230 s->first_displayed_line = i;
5233 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5234 int, int, int);
5235 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5236 int, int);
5238 static const struct got_error *
5239 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5241 const struct got_error *err = NULL;
5242 struct tog_diff_view_state *s = &view->state.diff;
5243 struct tog_log_view_state *ls;
5244 struct commit_queue_entry *old_selected_entry;
5245 char *line = NULL;
5246 size_t linesize = 0;
5247 ssize_t linelen;
5248 int i, nscroll = view->nlines - 1, up = 0;
5250 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5252 switch (ch) {
5253 case '0':
5254 view->x = 0;
5255 break;
5256 case '$':
5257 view->x = MAX(view->maxx - view->ncols / 3, 0);
5258 view->count = 0;
5259 break;
5260 case KEY_RIGHT:
5261 case 'l':
5262 if (view->x + view->ncols / 3 < view->maxx)
5263 view->x += 2; /* move two columns right */
5264 else
5265 view->count = 0;
5266 break;
5267 case KEY_LEFT:
5268 case 'h':
5269 view->x -= MIN(view->x, 2); /* move two columns back */
5270 if (view->x <= 0)
5271 view->count = 0;
5272 break;
5273 case 'a':
5274 case 'w':
5275 if (ch == 'a')
5276 s->force_text_diff = !s->force_text_diff;
5277 else if (ch == 'w')
5278 s->ignore_whitespace = !s->ignore_whitespace;
5279 err = reset_diff_view(view);
5280 break;
5281 case 'g':
5282 case KEY_HOME:
5283 s->first_displayed_line = 1;
5284 view->count = 0;
5285 break;
5286 case 'G':
5287 case KEY_END:
5288 view->count = 0;
5289 if (s->eof)
5290 break;
5292 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5293 s->eof = 1;
5294 break;
5295 case 'k':
5296 case KEY_UP:
5297 case CTRL('p'):
5298 if (s->first_displayed_line > 1)
5299 s->first_displayed_line--;
5300 else
5301 view->count = 0;
5302 break;
5303 case CTRL('u'):
5304 case 'u':
5305 nscroll /= 2;
5306 /* FALL THROUGH */
5307 case KEY_PPAGE:
5308 case CTRL('b'):
5309 case 'b':
5310 if (s->first_displayed_line == 1) {
5311 view->count = 0;
5312 break;
5314 i = 0;
5315 while (i++ < nscroll && s->first_displayed_line > 1)
5316 s->first_displayed_line--;
5317 break;
5318 case 'j':
5319 case KEY_DOWN:
5320 case CTRL('n'):
5321 if (!s->eof)
5322 s->first_displayed_line++;
5323 else
5324 view->count = 0;
5325 break;
5326 case CTRL('d'):
5327 case 'd':
5328 nscroll /= 2;
5329 /* FALL THROUGH */
5330 case KEY_NPAGE:
5331 case CTRL('f'):
5332 case 'f':
5333 case ' ':
5334 if (s->eof) {
5335 view->count = 0;
5336 break;
5338 i = 0;
5339 while (!s->eof && i++ < nscroll) {
5340 linelen = getline(&line, &linesize, s->f);
5341 s->first_displayed_line++;
5342 if (linelen == -1) {
5343 if (feof(s->f)) {
5344 s->eof = 1;
5345 } else
5346 err = got_ferror(s->f, GOT_ERR_IO);
5347 break;
5350 free(line);
5351 break;
5352 case '(':
5353 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5354 break;
5355 case ')':
5356 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5357 break;
5358 case '{':
5359 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5360 break;
5361 case '}':
5362 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5363 break;
5364 case '[':
5365 if (s->diff_context > 0) {
5366 s->diff_context--;
5367 s->matched_line = 0;
5368 diff_view_indicate_progress(view);
5369 err = create_diff(s);
5370 if (s->first_displayed_line + view->nlines - 1 >
5371 s->nlines) {
5372 s->first_displayed_line = 1;
5373 s->last_displayed_line = view->nlines;
5375 } else
5376 view->count = 0;
5377 break;
5378 case ']':
5379 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5380 s->diff_context++;
5381 s->matched_line = 0;
5382 diff_view_indicate_progress(view);
5383 err = create_diff(s);
5384 } else
5385 view->count = 0;
5386 break;
5387 case '<':
5388 case ',':
5389 case 'K':
5390 up = 1;
5391 /* FALL THROUGH */
5392 case '>':
5393 case '.':
5394 case 'J':
5395 if (s->parent_view == NULL) {
5396 view->count = 0;
5397 break;
5399 s->parent_view->count = view->count;
5401 if (s->parent_view->type == TOG_VIEW_LOG) {
5402 ls = &s->parent_view->state.log;
5403 old_selected_entry = ls->selected_entry;
5405 err = input_log_view(NULL, s->parent_view,
5406 up ? KEY_UP : KEY_DOWN);
5407 if (err)
5408 break;
5409 view->count = s->parent_view->count;
5411 if (old_selected_entry == ls->selected_entry)
5412 break;
5414 err = set_selected_commit(s, ls->selected_entry);
5415 if (err)
5416 break;
5417 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5418 struct tog_blame_view_state *bs;
5419 struct got_object_id *id, *prev_id;
5421 bs = &s->parent_view->state.blame;
5422 prev_id = get_annotation_for_line(bs->blame.lines,
5423 bs->blame.nlines, bs->last_diffed_line);
5425 err = input_blame_view(&view, s->parent_view,
5426 up ? KEY_UP : KEY_DOWN);
5427 if (err)
5428 break;
5429 view->count = s->parent_view->count;
5431 if (prev_id == NULL)
5432 break;
5433 id = get_selected_commit_id(bs->blame.lines,
5434 bs->blame.nlines, bs->first_displayed_line,
5435 bs->selected_line);
5436 if (id == NULL)
5437 break;
5439 if (!got_object_id_cmp(prev_id, id))
5440 break;
5442 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5443 if (err)
5444 break;
5446 s->first_displayed_line = 1;
5447 s->last_displayed_line = view->nlines;
5448 s->matched_line = 0;
5449 view->x = 0;
5451 diff_view_indicate_progress(view);
5452 err = create_diff(s);
5453 break;
5454 default:
5455 view->count = 0;
5456 break;
5459 return err;
5462 static const struct got_error *
5463 cmd_diff(int argc, char *argv[])
5465 const struct got_error *error = NULL;
5466 struct got_repository *repo = NULL;
5467 struct got_worktree *worktree = NULL;
5468 struct got_object_id *id1 = NULL, *id2 = NULL;
5469 char *repo_path = NULL, *cwd = NULL;
5470 char *id_str1 = NULL, *id_str2 = NULL;
5471 char *label1 = NULL, *label2 = NULL;
5472 int diff_context = 3, ignore_whitespace = 0;
5473 int ch, force_text_diff = 0;
5474 const char *errstr;
5475 struct tog_view *view;
5476 int *pack_fds = NULL;
5478 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5479 switch (ch) {
5480 case 'a':
5481 force_text_diff = 1;
5482 break;
5483 case 'C':
5484 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5485 &errstr);
5486 if (errstr != NULL)
5487 errx(1, "number of context lines is %s: %s",
5488 errstr, errstr);
5489 break;
5490 case 'r':
5491 repo_path = realpath(optarg, NULL);
5492 if (repo_path == NULL)
5493 return got_error_from_errno2("realpath",
5494 optarg);
5495 got_path_strip_trailing_slashes(repo_path);
5496 break;
5497 case 'w':
5498 ignore_whitespace = 1;
5499 break;
5500 default:
5501 usage_diff();
5502 /* NOTREACHED */
5506 argc -= optind;
5507 argv += optind;
5509 if (argc == 0) {
5510 usage_diff(); /* TODO show local worktree changes */
5511 } else if (argc == 2) {
5512 id_str1 = argv[0];
5513 id_str2 = argv[1];
5514 } else
5515 usage_diff();
5517 error = got_repo_pack_fds_open(&pack_fds);
5518 if (error)
5519 goto done;
5521 if (repo_path == NULL) {
5522 cwd = getcwd(NULL, 0);
5523 if (cwd == NULL)
5524 return got_error_from_errno("getcwd");
5525 error = got_worktree_open(&worktree, cwd);
5526 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5527 goto done;
5528 if (worktree)
5529 repo_path =
5530 strdup(got_worktree_get_repo_path(worktree));
5531 else
5532 repo_path = strdup(cwd);
5533 if (repo_path == NULL) {
5534 error = got_error_from_errno("strdup");
5535 goto done;
5539 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5540 if (error)
5541 goto done;
5543 init_curses();
5545 error = apply_unveil(got_repo_get_path(repo), NULL);
5546 if (error)
5547 goto done;
5549 error = tog_load_refs(repo, 0);
5550 if (error)
5551 goto done;
5553 error = got_repo_match_object_id(&id1, &label1, id_str1,
5554 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5555 if (error)
5556 goto done;
5558 error = got_repo_match_object_id(&id2, &label2, id_str2,
5559 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5560 if (error)
5561 goto done;
5563 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5564 if (view == NULL) {
5565 error = got_error_from_errno("view_open");
5566 goto done;
5568 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5569 ignore_whitespace, force_text_diff, NULL, repo);
5570 if (error)
5571 goto done;
5572 error = view_loop(view);
5573 done:
5574 free(label1);
5575 free(label2);
5576 free(repo_path);
5577 free(cwd);
5578 if (repo) {
5579 const struct got_error *close_err = got_repo_close(repo);
5580 if (error == NULL)
5581 error = close_err;
5583 if (worktree)
5584 got_worktree_close(worktree);
5585 if (pack_fds) {
5586 const struct got_error *pack_err =
5587 got_repo_pack_fds_close(pack_fds);
5588 if (error == NULL)
5589 error = pack_err;
5591 tog_free_refs();
5592 return error;
5595 __dead static void
5596 usage_blame(void)
5598 endwin();
5599 fprintf(stderr,
5600 "usage: %s blame [-c commit] [-r repository-path] path\n",
5601 getprogname());
5602 exit(1);
5605 struct tog_blame_line {
5606 int annotated;
5607 struct got_object_id *id;
5610 static const struct got_error *
5611 draw_blame(struct tog_view *view)
5613 struct tog_blame_view_state *s = &view->state.blame;
5614 struct tog_blame *blame = &s->blame;
5615 regmatch_t *regmatch = &view->regmatch;
5616 const struct got_error *err;
5617 int lineno = 0, nprinted = 0;
5618 char *line = NULL;
5619 size_t linesize = 0;
5620 ssize_t linelen;
5621 wchar_t *wline;
5622 int width;
5623 struct tog_blame_line *blame_line;
5624 struct got_object_id *prev_id = NULL;
5625 char *id_str;
5626 struct tog_color *tc;
5628 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5629 if (err)
5630 return err;
5632 rewind(blame->f);
5633 werase(view->window);
5635 if (asprintf(&line, "commit %s", id_str) == -1) {
5636 err = got_error_from_errno("asprintf");
5637 free(id_str);
5638 return err;
5641 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5642 free(line);
5643 line = NULL;
5644 if (err)
5645 return err;
5646 if (view_needs_focus_indication(view))
5647 wstandout(view->window);
5648 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5649 if (tc)
5650 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5651 waddwstr(view->window, wline);
5652 while (width++ < view->ncols)
5653 waddch(view->window, ' ');
5654 if (tc)
5655 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5656 if (view_needs_focus_indication(view))
5657 wstandend(view->window);
5658 free(wline);
5659 wline = NULL;
5661 if (view->gline > blame->nlines)
5662 view->gline = blame->nlines;
5664 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5665 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5666 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5667 free(id_str);
5668 return got_error_from_errno("asprintf");
5670 free(id_str);
5671 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5672 free(line);
5673 line = NULL;
5674 if (err)
5675 return err;
5676 waddwstr(view->window, wline);
5677 free(wline);
5678 wline = NULL;
5679 if (width < view->ncols - 1)
5680 waddch(view->window, '\n');
5682 s->eof = 0;
5683 view->maxx = 0;
5684 while (nprinted < view->nlines - 2) {
5685 linelen = getline(&line, &linesize, blame->f);
5686 if (linelen == -1) {
5687 if (feof(blame->f)) {
5688 s->eof = 1;
5689 break;
5691 free(line);
5692 return got_ferror(blame->f, GOT_ERR_IO);
5694 if (++lineno < s->first_displayed_line)
5695 continue;
5696 if (view->gline && !gotoline(view, &lineno, &nprinted))
5697 continue;
5699 /* Set view->maxx based on full line length. */
5700 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5701 if (err) {
5702 free(line);
5703 return err;
5705 free(wline);
5706 wline = NULL;
5707 view->maxx = MAX(view->maxx, width);
5709 if (nprinted == s->selected_line - 1)
5710 wstandout(view->window);
5712 if (blame->nlines > 0) {
5713 blame_line = &blame->lines[lineno - 1];
5714 if (blame_line->annotated && prev_id &&
5715 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5716 !(nprinted == s->selected_line - 1)) {
5717 waddstr(view->window, " ");
5718 } else if (blame_line->annotated) {
5719 char *id_str;
5720 err = got_object_id_str(&id_str,
5721 blame_line->id);
5722 if (err) {
5723 free(line);
5724 return err;
5726 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5727 if (tc)
5728 wattr_on(view->window,
5729 COLOR_PAIR(tc->colorpair), NULL);
5730 wprintw(view->window, "%.8s", id_str);
5731 if (tc)
5732 wattr_off(view->window,
5733 COLOR_PAIR(tc->colorpair), NULL);
5734 free(id_str);
5735 prev_id = blame_line->id;
5736 } else {
5737 waddstr(view->window, "........");
5738 prev_id = NULL;
5740 } else {
5741 waddstr(view->window, "........");
5742 prev_id = NULL;
5745 if (nprinted == s->selected_line - 1)
5746 wstandend(view->window);
5747 waddstr(view->window, " ");
5749 if (view->ncols <= 9) {
5750 width = 9;
5751 } else if (s->first_displayed_line + nprinted ==
5752 s->matched_line &&
5753 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5754 err = add_matched_line(&width, line, view->ncols - 9, 9,
5755 view->window, view->x, regmatch);
5756 if (err) {
5757 free(line);
5758 return err;
5760 width += 9;
5761 } else {
5762 int skip;
5763 err = format_line(&wline, &width, &skip, line,
5764 view->x, view->ncols - 9, 9, 1);
5765 if (err) {
5766 free(line);
5767 return err;
5769 waddwstr(view->window, &wline[skip]);
5770 width += 9;
5771 free(wline);
5772 wline = NULL;
5775 if (width <= view->ncols - 1)
5776 waddch(view->window, '\n');
5777 if (++nprinted == 1)
5778 s->first_displayed_line = lineno;
5780 free(line);
5781 s->last_displayed_line = lineno;
5783 view_border(view);
5785 return NULL;
5788 static const struct got_error *
5789 blame_cb(void *arg, int nlines, int lineno,
5790 struct got_commit_object *commit, struct got_object_id *id)
5792 const struct got_error *err = NULL;
5793 struct tog_blame_cb_args *a = arg;
5794 struct tog_blame_line *line;
5795 int errcode;
5797 if (nlines != a->nlines ||
5798 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5799 return got_error(GOT_ERR_RANGE);
5801 errcode = pthread_mutex_lock(&tog_mutex);
5802 if (errcode)
5803 return got_error_set_errno(errcode, "pthread_mutex_lock");
5805 if (*a->quit) { /* user has quit the blame view */
5806 err = got_error(GOT_ERR_ITER_COMPLETED);
5807 goto done;
5810 if (lineno == -1)
5811 goto done; /* no change in this commit */
5813 line = &a->lines[lineno - 1];
5814 if (line->annotated)
5815 goto done;
5817 line->id = got_object_id_dup(id);
5818 if (line->id == NULL) {
5819 err = got_error_from_errno("got_object_id_dup");
5820 goto done;
5822 line->annotated = 1;
5823 done:
5824 errcode = pthread_mutex_unlock(&tog_mutex);
5825 if (errcode)
5826 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5827 return err;
5830 static void *
5831 blame_thread(void *arg)
5833 const struct got_error *err, *close_err;
5834 struct tog_blame_thread_args *ta = arg;
5835 struct tog_blame_cb_args *a = ta->cb_args;
5836 int errcode, fd1 = -1, fd2 = -1;
5837 FILE *f1 = NULL, *f2 = NULL;
5839 fd1 = got_opentempfd();
5840 if (fd1 == -1)
5841 return (void *)got_error_from_errno("got_opentempfd");
5843 fd2 = got_opentempfd();
5844 if (fd2 == -1) {
5845 err = got_error_from_errno("got_opentempfd");
5846 goto done;
5849 f1 = got_opentemp();
5850 if (f1 == NULL) {
5851 err = (void *)got_error_from_errno("got_opentemp");
5852 goto done;
5854 f2 = got_opentemp();
5855 if (f2 == NULL) {
5856 err = (void *)got_error_from_errno("got_opentemp");
5857 goto done;
5860 err = block_signals_used_by_main_thread();
5861 if (err)
5862 goto done;
5864 err = got_blame(ta->path, a->commit_id, ta->repo,
5865 tog_diff_algo, blame_cb, ta->cb_args,
5866 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5867 if (err && err->code == GOT_ERR_CANCELLED)
5868 err = NULL;
5870 errcode = pthread_mutex_lock(&tog_mutex);
5871 if (errcode) {
5872 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5873 goto done;
5876 close_err = got_repo_close(ta->repo);
5877 if (err == NULL)
5878 err = close_err;
5879 ta->repo = NULL;
5880 *ta->complete = 1;
5882 errcode = pthread_mutex_unlock(&tog_mutex);
5883 if (errcode && err == NULL)
5884 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5886 done:
5887 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5888 err = got_error_from_errno("close");
5889 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5890 err = got_error_from_errno("close");
5891 if (f1 && fclose(f1) == EOF && err == NULL)
5892 err = got_error_from_errno("fclose");
5893 if (f2 && fclose(f2) == EOF && err == NULL)
5894 err = got_error_from_errno("fclose");
5896 return (void *)err;
5899 static struct got_object_id *
5900 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5901 int first_displayed_line, int selected_line)
5903 struct tog_blame_line *line;
5905 if (nlines <= 0)
5906 return NULL;
5908 line = &lines[first_displayed_line - 1 + selected_line - 1];
5909 if (!line->annotated)
5910 return NULL;
5912 return line->id;
5915 static struct got_object_id *
5916 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5917 int lineno)
5919 struct tog_blame_line *line;
5921 if (nlines <= 0 || lineno >= nlines)
5922 return NULL;
5924 line = &lines[lineno - 1];
5925 if (!line->annotated)
5926 return NULL;
5928 return line->id;
5931 static const struct got_error *
5932 stop_blame(struct tog_blame *blame)
5934 const struct got_error *err = NULL;
5935 int i;
5937 if (blame->thread) {
5938 int errcode;
5939 errcode = pthread_mutex_unlock(&tog_mutex);
5940 if (errcode)
5941 return got_error_set_errno(errcode,
5942 "pthread_mutex_unlock");
5943 errcode = pthread_join(blame->thread, (void **)&err);
5944 if (errcode)
5945 return got_error_set_errno(errcode, "pthread_join");
5946 errcode = pthread_mutex_lock(&tog_mutex);
5947 if (errcode)
5948 return got_error_set_errno(errcode,
5949 "pthread_mutex_lock");
5950 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5951 err = NULL;
5952 blame->thread = NULL;
5954 if (blame->thread_args.repo) {
5955 const struct got_error *close_err;
5956 close_err = got_repo_close(blame->thread_args.repo);
5957 if (err == NULL)
5958 err = close_err;
5959 blame->thread_args.repo = NULL;
5961 if (blame->f) {
5962 if (fclose(blame->f) == EOF && err == NULL)
5963 err = got_error_from_errno("fclose");
5964 blame->f = NULL;
5966 if (blame->lines) {
5967 for (i = 0; i < blame->nlines; i++)
5968 free(blame->lines[i].id);
5969 free(blame->lines);
5970 blame->lines = NULL;
5972 free(blame->cb_args.commit_id);
5973 blame->cb_args.commit_id = NULL;
5974 if (blame->pack_fds) {
5975 const struct got_error *pack_err =
5976 got_repo_pack_fds_close(blame->pack_fds);
5977 if (err == NULL)
5978 err = pack_err;
5979 blame->pack_fds = NULL;
5981 return err;
5984 static const struct got_error *
5985 cancel_blame_view(void *arg)
5987 const struct got_error *err = NULL;
5988 int *done = arg;
5989 int errcode;
5991 errcode = pthread_mutex_lock(&tog_mutex);
5992 if (errcode)
5993 return got_error_set_errno(errcode,
5994 "pthread_mutex_unlock");
5996 if (*done)
5997 err = got_error(GOT_ERR_CANCELLED);
5999 errcode = pthread_mutex_unlock(&tog_mutex);
6000 if (errcode)
6001 return got_error_set_errno(errcode,
6002 "pthread_mutex_lock");
6004 return err;
6007 static const struct got_error *
6008 run_blame(struct tog_view *view)
6010 struct tog_blame_view_state *s = &view->state.blame;
6011 struct tog_blame *blame = &s->blame;
6012 const struct got_error *err = NULL;
6013 struct got_commit_object *commit = NULL;
6014 struct got_blob_object *blob = NULL;
6015 struct got_repository *thread_repo = NULL;
6016 struct got_object_id *obj_id = NULL;
6017 int obj_type, fd = -1;
6018 int *pack_fds = NULL;
6020 err = got_object_open_as_commit(&commit, s->repo,
6021 &s->blamed_commit->id);
6022 if (err)
6023 return err;
6025 fd = got_opentempfd();
6026 if (fd == -1) {
6027 err = got_error_from_errno("got_opentempfd");
6028 goto done;
6031 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6032 if (err)
6033 goto done;
6035 err = got_object_get_type(&obj_type, s->repo, obj_id);
6036 if (err)
6037 goto done;
6039 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6040 err = got_error(GOT_ERR_OBJ_TYPE);
6041 goto done;
6044 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6045 if (err)
6046 goto done;
6047 blame->f = got_opentemp();
6048 if (blame->f == NULL) {
6049 err = got_error_from_errno("got_opentemp");
6050 goto done;
6052 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6053 &blame->line_offsets, blame->f, blob);
6054 if (err)
6055 goto done;
6056 if (blame->nlines == 0) {
6057 s->blame_complete = 1;
6058 goto done;
6061 /* Don't include \n at EOF in the blame line count. */
6062 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6063 blame->nlines--;
6065 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6066 if (blame->lines == NULL) {
6067 err = got_error_from_errno("calloc");
6068 goto done;
6071 err = got_repo_pack_fds_open(&pack_fds);
6072 if (err)
6073 goto done;
6074 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6075 pack_fds);
6076 if (err)
6077 goto done;
6079 blame->pack_fds = pack_fds;
6080 blame->cb_args.view = view;
6081 blame->cb_args.lines = blame->lines;
6082 blame->cb_args.nlines = blame->nlines;
6083 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6084 if (blame->cb_args.commit_id == NULL) {
6085 err = got_error_from_errno("got_object_id_dup");
6086 goto done;
6088 blame->cb_args.quit = &s->done;
6090 blame->thread_args.path = s->path;
6091 blame->thread_args.repo = thread_repo;
6092 blame->thread_args.cb_args = &blame->cb_args;
6093 blame->thread_args.complete = &s->blame_complete;
6094 blame->thread_args.cancel_cb = cancel_blame_view;
6095 blame->thread_args.cancel_arg = &s->done;
6096 s->blame_complete = 0;
6098 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6099 s->first_displayed_line = 1;
6100 s->last_displayed_line = view->nlines;
6101 s->selected_line = 1;
6103 s->matched_line = 0;
6105 done:
6106 if (commit)
6107 got_object_commit_close(commit);
6108 if (fd != -1 && close(fd) == -1 && err == NULL)
6109 err = got_error_from_errno("close");
6110 if (blob)
6111 got_object_blob_close(blob);
6112 free(obj_id);
6113 if (err)
6114 stop_blame(blame);
6115 return err;
6118 static const struct got_error *
6119 open_blame_view(struct tog_view *view, char *path,
6120 struct got_object_id *commit_id, struct got_repository *repo)
6122 const struct got_error *err = NULL;
6123 struct tog_blame_view_state *s = &view->state.blame;
6125 STAILQ_INIT(&s->blamed_commits);
6127 s->path = strdup(path);
6128 if (s->path == NULL)
6129 return got_error_from_errno("strdup");
6131 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6132 if (err) {
6133 free(s->path);
6134 return err;
6137 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6138 s->first_displayed_line = 1;
6139 s->last_displayed_line = view->nlines;
6140 s->selected_line = 1;
6141 s->blame_complete = 0;
6142 s->repo = repo;
6143 s->commit_id = commit_id;
6144 memset(&s->blame, 0, sizeof(s->blame));
6146 STAILQ_INIT(&s->colors);
6147 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6148 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6149 get_color_value("TOG_COLOR_COMMIT"));
6150 if (err)
6151 return err;
6154 view->show = show_blame_view;
6155 view->input = input_blame_view;
6156 view->reset = reset_blame_view;
6157 view->close = close_blame_view;
6158 view->search_start = search_start_blame_view;
6159 view->search_setup = search_setup_blame_view;
6160 view->search_next = search_next_view_match;
6162 return run_blame(view);
6165 static const struct got_error *
6166 close_blame_view(struct tog_view *view)
6168 const struct got_error *err = NULL;
6169 struct tog_blame_view_state *s = &view->state.blame;
6171 if (s->blame.thread)
6172 err = stop_blame(&s->blame);
6174 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6175 struct got_object_qid *blamed_commit;
6176 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6177 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6178 got_object_qid_free(blamed_commit);
6181 free(s->path);
6182 free_colors(&s->colors);
6183 return err;
6186 static const struct got_error *
6187 search_start_blame_view(struct tog_view *view)
6189 struct tog_blame_view_state *s = &view->state.blame;
6191 s->matched_line = 0;
6192 return NULL;
6195 static void
6196 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6197 size_t *nlines, int **first, int **last, int **match, int **selected)
6199 struct tog_blame_view_state *s = &view->state.blame;
6201 *f = s->blame.f;
6202 *nlines = s->blame.nlines;
6203 *line_offsets = s->blame.line_offsets;
6204 *match = &s->matched_line;
6205 *first = &s->first_displayed_line;
6206 *last = &s->last_displayed_line;
6207 *selected = &s->selected_line;
6210 static const struct got_error *
6211 show_blame_view(struct tog_view *view)
6213 const struct got_error *err = NULL;
6214 struct tog_blame_view_state *s = &view->state.blame;
6215 int errcode;
6217 if (s->blame.thread == NULL && !s->blame_complete) {
6218 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6219 &s->blame.thread_args);
6220 if (errcode)
6221 return got_error_set_errno(errcode, "pthread_create");
6223 halfdelay(1); /* fast refresh while annotating */
6226 if (s->blame_complete)
6227 halfdelay(10); /* disable fast refresh */
6229 err = draw_blame(view);
6231 view_border(view);
6232 return err;
6235 static const struct got_error *
6236 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6237 struct got_repository *repo, struct got_object_id *id)
6239 struct tog_view *log_view;
6240 const struct got_error *err = NULL;
6242 *new_view = NULL;
6244 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6245 if (log_view == NULL)
6246 return got_error_from_errno("view_open");
6248 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6249 if (err)
6250 view_close(log_view);
6251 else
6252 *new_view = log_view;
6254 return err;
6257 static const struct got_error *
6258 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6260 const struct got_error *err = NULL, *thread_err = NULL;
6261 struct tog_view *diff_view;
6262 struct tog_blame_view_state *s = &view->state.blame;
6263 int eos, nscroll, begin_y = 0, begin_x = 0;
6265 eos = nscroll = view->nlines - 2;
6266 if (view_is_hsplit_top(view))
6267 --eos; /* border */
6269 switch (ch) {
6270 case '0':
6271 view->x = 0;
6272 break;
6273 case '$':
6274 view->x = MAX(view->maxx - view->ncols / 3, 0);
6275 view->count = 0;
6276 break;
6277 case KEY_RIGHT:
6278 case 'l':
6279 if (view->x + view->ncols / 3 < view->maxx)
6280 view->x += 2; /* move two columns right */
6281 else
6282 view->count = 0;
6283 break;
6284 case KEY_LEFT:
6285 case 'h':
6286 view->x -= MIN(view->x, 2); /* move two columns back */
6287 if (view->x <= 0)
6288 view->count = 0;
6289 break;
6290 case 'q':
6291 s->done = 1;
6292 break;
6293 case 'g':
6294 case KEY_HOME:
6295 s->selected_line = 1;
6296 s->first_displayed_line = 1;
6297 view->count = 0;
6298 break;
6299 case 'G':
6300 case KEY_END:
6301 if (s->blame.nlines < eos) {
6302 s->selected_line = s->blame.nlines;
6303 s->first_displayed_line = 1;
6304 } else {
6305 s->selected_line = eos;
6306 s->first_displayed_line = s->blame.nlines - (eos - 1);
6308 view->count = 0;
6309 break;
6310 case 'k':
6311 case KEY_UP:
6312 case CTRL('p'):
6313 if (s->selected_line > 1)
6314 s->selected_line--;
6315 else if (s->selected_line == 1 &&
6316 s->first_displayed_line > 1)
6317 s->first_displayed_line--;
6318 else
6319 view->count = 0;
6320 break;
6321 case CTRL('u'):
6322 case 'u':
6323 nscroll /= 2;
6324 /* FALL THROUGH */
6325 case KEY_PPAGE:
6326 case CTRL('b'):
6327 case 'b':
6328 if (s->first_displayed_line == 1) {
6329 if (view->count > 1)
6330 nscroll += nscroll;
6331 s->selected_line = MAX(1, s->selected_line - nscroll);
6332 view->count = 0;
6333 break;
6335 if (s->first_displayed_line > nscroll)
6336 s->first_displayed_line -= nscroll;
6337 else
6338 s->first_displayed_line = 1;
6339 break;
6340 case 'j':
6341 case KEY_DOWN:
6342 case CTRL('n'):
6343 if (s->selected_line < eos && s->first_displayed_line +
6344 s->selected_line <= s->blame.nlines)
6345 s->selected_line++;
6346 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6347 s->first_displayed_line++;
6348 else
6349 view->count = 0;
6350 break;
6351 case 'c':
6352 case 'p': {
6353 struct got_object_id *id = NULL;
6355 view->count = 0;
6356 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6357 s->first_displayed_line, s->selected_line);
6358 if (id == NULL)
6359 break;
6360 if (ch == 'p') {
6361 struct got_commit_object *commit, *pcommit;
6362 struct got_object_qid *pid;
6363 struct got_object_id *blob_id = NULL;
6364 int obj_type;
6365 err = got_object_open_as_commit(&commit,
6366 s->repo, id);
6367 if (err)
6368 break;
6369 pid = STAILQ_FIRST(
6370 got_object_commit_get_parent_ids(commit));
6371 if (pid == NULL) {
6372 got_object_commit_close(commit);
6373 break;
6375 /* Check if path history ends here. */
6376 err = got_object_open_as_commit(&pcommit,
6377 s->repo, &pid->id);
6378 if (err)
6379 break;
6380 err = got_object_id_by_path(&blob_id, s->repo,
6381 pcommit, s->path);
6382 got_object_commit_close(pcommit);
6383 if (err) {
6384 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6385 err = NULL;
6386 got_object_commit_close(commit);
6387 break;
6389 err = got_object_get_type(&obj_type, s->repo,
6390 blob_id);
6391 free(blob_id);
6392 /* Can't blame non-blob type objects. */
6393 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6394 got_object_commit_close(commit);
6395 break;
6397 err = got_object_qid_alloc(&s->blamed_commit,
6398 &pid->id);
6399 got_object_commit_close(commit);
6400 } else {
6401 if (got_object_id_cmp(id,
6402 &s->blamed_commit->id) == 0)
6403 break;
6404 err = got_object_qid_alloc(&s->blamed_commit,
6405 id);
6407 if (err)
6408 break;
6409 s->done = 1;
6410 thread_err = stop_blame(&s->blame);
6411 s->done = 0;
6412 if (thread_err)
6413 break;
6414 STAILQ_INSERT_HEAD(&s->blamed_commits,
6415 s->blamed_commit, entry);
6416 err = run_blame(view);
6417 if (err)
6418 break;
6419 break;
6421 case 'C': {
6422 struct got_object_qid *first;
6424 view->count = 0;
6425 first = STAILQ_FIRST(&s->blamed_commits);
6426 if (!got_object_id_cmp(&first->id, s->commit_id))
6427 break;
6428 s->done = 1;
6429 thread_err = stop_blame(&s->blame);
6430 s->done = 0;
6431 if (thread_err)
6432 break;
6433 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6434 got_object_qid_free(s->blamed_commit);
6435 s->blamed_commit =
6436 STAILQ_FIRST(&s->blamed_commits);
6437 err = run_blame(view);
6438 if (err)
6439 break;
6440 break;
6442 case 'L':
6443 view->count = 0;
6444 s->id_to_log = get_selected_commit_id(s->blame.lines,
6445 s->blame.nlines, s->first_displayed_line, s->selected_line);
6446 if (s->id_to_log)
6447 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6448 break;
6449 case KEY_ENTER:
6450 case '\r': {
6451 struct got_object_id *id = NULL;
6452 struct got_object_qid *pid;
6453 struct got_commit_object *commit = NULL;
6455 view->count = 0;
6456 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6457 s->first_displayed_line, s->selected_line);
6458 if (id == NULL)
6459 break;
6460 err = got_object_open_as_commit(&commit, s->repo, id);
6461 if (err)
6462 break;
6463 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6464 if (*new_view) {
6465 /* traversed from diff view, release diff resources */
6466 err = close_diff_view(*new_view);
6467 if (err)
6468 break;
6469 diff_view = *new_view;
6470 } else {
6471 if (view_is_parent_view(view))
6472 view_get_split(view, &begin_y, &begin_x);
6474 diff_view = view_open(0, 0, begin_y, begin_x,
6475 TOG_VIEW_DIFF);
6476 if (diff_view == NULL) {
6477 got_object_commit_close(commit);
6478 err = got_error_from_errno("view_open");
6479 break;
6482 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6483 id, NULL, NULL, 3, 0, 0, view, s->repo);
6484 got_object_commit_close(commit);
6485 if (err) {
6486 view_close(diff_view);
6487 break;
6489 s->last_diffed_line = s->first_displayed_line - 1 +
6490 s->selected_line;
6491 if (*new_view)
6492 break; /* still open from active diff view */
6493 if (view_is_parent_view(view) &&
6494 view->mode == TOG_VIEW_SPLIT_HRZN) {
6495 err = view_init_hsplit(view, begin_y);
6496 if (err)
6497 break;
6500 view->focussed = 0;
6501 diff_view->focussed = 1;
6502 diff_view->mode = view->mode;
6503 diff_view->nlines = view->lines - begin_y;
6504 if (view_is_parent_view(view)) {
6505 view_transfer_size(diff_view, view);
6506 err = view_close_child(view);
6507 if (err)
6508 break;
6509 err = view_set_child(view, diff_view);
6510 if (err)
6511 break;
6512 view->focus_child = 1;
6513 } else
6514 *new_view = diff_view;
6515 if (err)
6516 break;
6517 break;
6519 case CTRL('d'):
6520 case 'd':
6521 nscroll /= 2;
6522 /* FALL THROUGH */
6523 case KEY_NPAGE:
6524 case CTRL('f'):
6525 case 'f':
6526 case ' ':
6527 if (s->last_displayed_line >= s->blame.nlines &&
6528 s->selected_line >= MIN(s->blame.nlines,
6529 view->nlines - 2)) {
6530 view->count = 0;
6531 break;
6533 if (s->last_displayed_line >= s->blame.nlines &&
6534 s->selected_line < view->nlines - 2) {
6535 s->selected_line +=
6536 MIN(nscroll, s->last_displayed_line -
6537 s->first_displayed_line - s->selected_line + 1);
6539 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6540 s->first_displayed_line += nscroll;
6541 else
6542 s->first_displayed_line =
6543 s->blame.nlines - (view->nlines - 3);
6544 break;
6545 case KEY_RESIZE:
6546 if (s->selected_line > view->nlines - 2) {
6547 s->selected_line = MIN(s->blame.nlines,
6548 view->nlines - 2);
6550 break;
6551 default:
6552 view->count = 0;
6553 break;
6555 return thread_err ? thread_err : err;
6558 static const struct got_error *
6559 reset_blame_view(struct tog_view *view)
6561 const struct got_error *err;
6562 struct tog_blame_view_state *s = &view->state.blame;
6564 view->count = 0;
6565 s->done = 1;
6566 err = stop_blame(&s->blame);
6567 s->done = 0;
6568 if (err)
6569 return err;
6570 return run_blame(view);
6573 static const struct got_error *
6574 cmd_blame(int argc, char *argv[])
6576 const struct got_error *error;
6577 struct got_repository *repo = NULL;
6578 struct got_worktree *worktree = NULL;
6579 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6580 char *link_target = NULL;
6581 struct got_object_id *commit_id = NULL;
6582 struct got_commit_object *commit = NULL;
6583 char *commit_id_str = NULL;
6584 int ch;
6585 struct tog_view *view;
6586 int *pack_fds = NULL;
6588 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6589 switch (ch) {
6590 case 'c':
6591 commit_id_str = optarg;
6592 break;
6593 case 'r':
6594 repo_path = realpath(optarg, NULL);
6595 if (repo_path == NULL)
6596 return got_error_from_errno2("realpath",
6597 optarg);
6598 break;
6599 default:
6600 usage_blame();
6601 /* NOTREACHED */
6605 argc -= optind;
6606 argv += optind;
6608 if (argc != 1)
6609 usage_blame();
6611 error = got_repo_pack_fds_open(&pack_fds);
6612 if (error != NULL)
6613 goto done;
6615 if (repo_path == NULL) {
6616 cwd = getcwd(NULL, 0);
6617 if (cwd == NULL)
6618 return got_error_from_errno("getcwd");
6619 error = got_worktree_open(&worktree, cwd);
6620 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6621 goto done;
6622 if (worktree)
6623 repo_path =
6624 strdup(got_worktree_get_repo_path(worktree));
6625 else
6626 repo_path = strdup(cwd);
6627 if (repo_path == NULL) {
6628 error = got_error_from_errno("strdup");
6629 goto done;
6633 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6634 if (error != NULL)
6635 goto done;
6637 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6638 worktree);
6639 if (error)
6640 goto done;
6642 init_curses();
6644 error = apply_unveil(got_repo_get_path(repo), NULL);
6645 if (error)
6646 goto done;
6648 error = tog_load_refs(repo, 0);
6649 if (error)
6650 goto done;
6652 if (commit_id_str == NULL) {
6653 struct got_reference *head_ref;
6654 error = got_ref_open(&head_ref, repo, worktree ?
6655 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6656 if (error != NULL)
6657 goto done;
6658 error = got_ref_resolve(&commit_id, repo, head_ref);
6659 got_ref_close(head_ref);
6660 } else {
6661 error = got_repo_match_object_id(&commit_id, NULL,
6662 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6664 if (error != NULL)
6665 goto done;
6667 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6668 if (view == NULL) {
6669 error = got_error_from_errno("view_open");
6670 goto done;
6673 error = got_object_open_as_commit(&commit, repo, commit_id);
6674 if (error)
6675 goto done;
6677 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6678 commit, repo);
6679 if (error)
6680 goto done;
6682 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6683 commit_id, repo);
6684 if (error)
6685 goto done;
6686 if (worktree) {
6687 /* Release work tree lock. */
6688 got_worktree_close(worktree);
6689 worktree = NULL;
6691 error = view_loop(view);
6692 done:
6693 free(repo_path);
6694 free(in_repo_path);
6695 free(link_target);
6696 free(cwd);
6697 free(commit_id);
6698 if (commit)
6699 got_object_commit_close(commit);
6700 if (worktree)
6701 got_worktree_close(worktree);
6702 if (repo) {
6703 const struct got_error *close_err = got_repo_close(repo);
6704 if (error == NULL)
6705 error = close_err;
6707 if (pack_fds) {
6708 const struct got_error *pack_err =
6709 got_repo_pack_fds_close(pack_fds);
6710 if (error == NULL)
6711 error = pack_err;
6713 tog_free_refs();
6714 return error;
6717 static const struct got_error *
6718 draw_tree_entries(struct tog_view *view, const char *parent_path)
6720 struct tog_tree_view_state *s = &view->state.tree;
6721 const struct got_error *err = NULL;
6722 struct got_tree_entry *te;
6723 wchar_t *wline;
6724 char *index = NULL;
6725 struct tog_color *tc;
6726 int width, n, nentries, i = 1;
6727 int limit = view->nlines;
6729 s->ndisplayed = 0;
6730 if (view_is_hsplit_top(view))
6731 --limit; /* border */
6733 werase(view->window);
6735 if (limit == 0)
6736 return NULL;
6738 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6739 0, 0);
6740 if (err)
6741 return err;
6742 if (view_needs_focus_indication(view))
6743 wstandout(view->window);
6744 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6745 if (tc)
6746 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6747 waddwstr(view->window, wline);
6748 free(wline);
6749 wline = NULL;
6750 while (width++ < view->ncols)
6751 waddch(view->window, ' ');
6752 if (tc)
6753 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6754 if (view_needs_focus_indication(view))
6755 wstandend(view->window);
6756 if (--limit <= 0)
6757 return NULL;
6759 i += s->selected;
6760 if (s->first_displayed_entry) {
6761 i += got_tree_entry_get_index(s->first_displayed_entry);
6762 if (s->tree != s->root)
6763 ++i; /* account for ".." entry */
6765 nentries = got_object_tree_get_nentries(s->tree);
6766 if (asprintf(&index, "[%d/%d] %s",
6767 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6768 return got_error_from_errno("asprintf");
6769 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6770 free(index);
6771 if (err)
6772 return err;
6773 waddwstr(view->window, wline);
6774 free(wline);
6775 wline = NULL;
6776 if (width < view->ncols - 1)
6777 waddch(view->window, '\n');
6778 if (--limit <= 0)
6779 return NULL;
6780 waddch(view->window, '\n');
6781 if (--limit <= 0)
6782 return NULL;
6784 if (s->first_displayed_entry == NULL) {
6785 te = got_object_tree_get_first_entry(s->tree);
6786 if (s->selected == 0) {
6787 if (view->focussed)
6788 wstandout(view->window);
6789 s->selected_entry = NULL;
6791 waddstr(view->window, " ..\n"); /* parent directory */
6792 if (s->selected == 0 && view->focussed)
6793 wstandend(view->window);
6794 s->ndisplayed++;
6795 if (--limit <= 0)
6796 return NULL;
6797 n = 1;
6798 } else {
6799 n = 0;
6800 te = s->first_displayed_entry;
6803 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6804 char *line = NULL, *id_str = NULL, *link_target = NULL;
6805 const char *modestr = "";
6806 mode_t mode;
6808 te = got_object_tree_get_entry(s->tree, i);
6809 mode = got_tree_entry_get_mode(te);
6811 if (s->show_ids) {
6812 err = got_object_id_str(&id_str,
6813 got_tree_entry_get_id(te));
6814 if (err)
6815 return got_error_from_errno(
6816 "got_object_id_str");
6818 if (got_object_tree_entry_is_submodule(te))
6819 modestr = "$";
6820 else if (S_ISLNK(mode)) {
6821 int i;
6823 err = got_tree_entry_get_symlink_target(&link_target,
6824 te, s->repo);
6825 if (err) {
6826 free(id_str);
6827 return err;
6829 for (i = 0; i < strlen(link_target); i++) {
6830 if (!isprint((unsigned char)link_target[i]))
6831 link_target[i] = '?';
6833 modestr = "@";
6835 else if (S_ISDIR(mode))
6836 modestr = "/";
6837 else if (mode & S_IXUSR)
6838 modestr = "*";
6839 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6840 got_tree_entry_get_name(te), modestr,
6841 link_target ? " -> ": "",
6842 link_target ? link_target : "") == -1) {
6843 free(id_str);
6844 free(link_target);
6845 return got_error_from_errno("asprintf");
6847 free(id_str);
6848 free(link_target);
6849 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6850 0, 0);
6851 if (err) {
6852 free(line);
6853 break;
6855 if (n == s->selected) {
6856 if (view->focussed)
6857 wstandout(view->window);
6858 s->selected_entry = te;
6860 tc = match_color(&s->colors, line);
6861 if (tc)
6862 wattr_on(view->window,
6863 COLOR_PAIR(tc->colorpair), NULL);
6864 waddwstr(view->window, wline);
6865 if (tc)
6866 wattr_off(view->window,
6867 COLOR_PAIR(tc->colorpair), NULL);
6868 if (width < view->ncols - 1)
6869 waddch(view->window, '\n');
6870 if (n == s->selected && view->focussed)
6871 wstandend(view->window);
6872 free(line);
6873 free(wline);
6874 wline = NULL;
6875 n++;
6876 s->ndisplayed++;
6877 s->last_displayed_entry = te;
6878 if (--limit <= 0)
6879 break;
6882 return err;
6885 static void
6886 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6888 struct got_tree_entry *te;
6889 int isroot = s->tree == s->root;
6890 int i = 0;
6892 if (s->first_displayed_entry == NULL)
6893 return;
6895 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6896 while (i++ < maxscroll) {
6897 if (te == NULL) {
6898 if (!isroot)
6899 s->first_displayed_entry = NULL;
6900 break;
6902 s->first_displayed_entry = te;
6903 te = got_tree_entry_get_prev(s->tree, te);
6907 static const struct got_error *
6908 tree_scroll_down(struct tog_view *view, int maxscroll)
6910 struct tog_tree_view_state *s = &view->state.tree;
6911 struct got_tree_entry *next, *last;
6912 int n = 0;
6914 if (s->first_displayed_entry)
6915 next = got_tree_entry_get_next(s->tree,
6916 s->first_displayed_entry);
6917 else
6918 next = got_object_tree_get_first_entry(s->tree);
6920 last = s->last_displayed_entry;
6921 while (next && n++ < maxscroll) {
6922 if (last) {
6923 s->last_displayed_entry = last;
6924 last = got_tree_entry_get_next(s->tree, last);
6926 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6927 s->first_displayed_entry = next;
6928 next = got_tree_entry_get_next(s->tree, next);
6932 return NULL;
6935 static const struct got_error *
6936 tree_entry_path(char **path, struct tog_parent_trees *parents,
6937 struct got_tree_entry *te)
6939 const struct got_error *err = NULL;
6940 struct tog_parent_tree *pt;
6941 size_t len = 2; /* for leading slash and NUL */
6943 TAILQ_FOREACH(pt, parents, entry)
6944 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6945 + 1 /* slash */;
6946 if (te)
6947 len += strlen(got_tree_entry_get_name(te));
6949 *path = calloc(1, len);
6950 if (path == NULL)
6951 return got_error_from_errno("calloc");
6953 (*path)[0] = '/';
6954 pt = TAILQ_LAST(parents, tog_parent_trees);
6955 while (pt) {
6956 const char *name = got_tree_entry_get_name(pt->selected_entry);
6957 if (strlcat(*path, name, len) >= len) {
6958 err = got_error(GOT_ERR_NO_SPACE);
6959 goto done;
6961 if (strlcat(*path, "/", len) >= len) {
6962 err = got_error(GOT_ERR_NO_SPACE);
6963 goto done;
6965 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6967 if (te) {
6968 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6969 err = got_error(GOT_ERR_NO_SPACE);
6970 goto done;
6973 done:
6974 if (err) {
6975 free(*path);
6976 *path = NULL;
6978 return err;
6981 static const struct got_error *
6982 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6983 struct got_tree_entry *te, struct tog_parent_trees *parents,
6984 struct got_object_id *commit_id, struct got_repository *repo)
6986 const struct got_error *err = NULL;
6987 char *path;
6988 struct tog_view *blame_view;
6990 *new_view = NULL;
6992 err = tree_entry_path(&path, parents, te);
6993 if (err)
6994 return err;
6996 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6997 if (blame_view == NULL) {
6998 err = got_error_from_errno("view_open");
6999 goto done;
7002 err = open_blame_view(blame_view, path, commit_id, repo);
7003 if (err) {
7004 if (err->code == GOT_ERR_CANCELLED)
7005 err = NULL;
7006 view_close(blame_view);
7007 } else
7008 *new_view = blame_view;
7009 done:
7010 free(path);
7011 return err;
7014 static const struct got_error *
7015 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7016 struct tog_tree_view_state *s)
7018 struct tog_view *log_view;
7019 const struct got_error *err = NULL;
7020 char *path;
7022 *new_view = NULL;
7024 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7025 if (log_view == NULL)
7026 return got_error_from_errno("view_open");
7028 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7029 if (err)
7030 return err;
7032 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7033 path, 0);
7034 if (err)
7035 view_close(log_view);
7036 else
7037 *new_view = log_view;
7038 free(path);
7039 return err;
7042 static const struct got_error *
7043 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7044 const char *head_ref_name, struct got_repository *repo)
7046 const struct got_error *err = NULL;
7047 char *commit_id_str = NULL;
7048 struct tog_tree_view_state *s = &view->state.tree;
7049 struct got_commit_object *commit = NULL;
7051 TAILQ_INIT(&s->parents);
7052 STAILQ_INIT(&s->colors);
7054 s->commit_id = got_object_id_dup(commit_id);
7055 if (s->commit_id == NULL)
7056 return got_error_from_errno("got_object_id_dup");
7058 err = got_object_open_as_commit(&commit, repo, commit_id);
7059 if (err)
7060 goto done;
7063 * The root is opened here and will be closed when the view is closed.
7064 * Any visited subtrees and their path-wise parents are opened and
7065 * closed on demand.
7067 err = got_object_open_as_tree(&s->root, repo,
7068 got_object_commit_get_tree_id(commit));
7069 if (err)
7070 goto done;
7071 s->tree = s->root;
7073 err = got_object_id_str(&commit_id_str, commit_id);
7074 if (err != NULL)
7075 goto done;
7077 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7078 err = got_error_from_errno("asprintf");
7079 goto done;
7082 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7083 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7084 if (head_ref_name) {
7085 s->head_ref_name = strdup(head_ref_name);
7086 if (s->head_ref_name == NULL) {
7087 err = got_error_from_errno("strdup");
7088 goto done;
7091 s->repo = repo;
7093 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7094 err = add_color(&s->colors, "\\$$",
7095 TOG_COLOR_TREE_SUBMODULE,
7096 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7097 if (err)
7098 goto done;
7099 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7100 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7101 if (err)
7102 goto done;
7103 err = add_color(&s->colors, "/$",
7104 TOG_COLOR_TREE_DIRECTORY,
7105 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7106 if (err)
7107 goto done;
7109 err = add_color(&s->colors, "\\*$",
7110 TOG_COLOR_TREE_EXECUTABLE,
7111 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7112 if (err)
7113 goto done;
7115 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7116 get_color_value("TOG_COLOR_COMMIT"));
7117 if (err)
7118 goto done;
7121 view->show = show_tree_view;
7122 view->input = input_tree_view;
7123 view->close = close_tree_view;
7124 view->search_start = search_start_tree_view;
7125 view->search_next = search_next_tree_view;
7126 done:
7127 free(commit_id_str);
7128 if (commit)
7129 got_object_commit_close(commit);
7130 if (err)
7131 close_tree_view(view);
7132 return err;
7135 static const struct got_error *
7136 close_tree_view(struct tog_view *view)
7138 struct tog_tree_view_state *s = &view->state.tree;
7140 free_colors(&s->colors);
7141 free(s->tree_label);
7142 s->tree_label = NULL;
7143 free(s->commit_id);
7144 s->commit_id = NULL;
7145 free(s->head_ref_name);
7146 s->head_ref_name = NULL;
7147 while (!TAILQ_EMPTY(&s->parents)) {
7148 struct tog_parent_tree *parent;
7149 parent = TAILQ_FIRST(&s->parents);
7150 TAILQ_REMOVE(&s->parents, parent, entry);
7151 if (parent->tree != s->root)
7152 got_object_tree_close(parent->tree);
7153 free(parent);
7156 if (s->tree != NULL && s->tree != s->root)
7157 got_object_tree_close(s->tree);
7158 if (s->root)
7159 got_object_tree_close(s->root);
7160 return NULL;
7163 static const struct got_error *
7164 search_start_tree_view(struct tog_view *view)
7166 struct tog_tree_view_state *s = &view->state.tree;
7168 s->matched_entry = NULL;
7169 return NULL;
7172 static int
7173 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7175 regmatch_t regmatch;
7177 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7178 0) == 0;
7181 static const struct got_error *
7182 search_next_tree_view(struct tog_view *view)
7184 struct tog_tree_view_state *s = &view->state.tree;
7185 struct got_tree_entry *te = NULL;
7187 if (!view->searching) {
7188 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7189 return NULL;
7192 if (s->matched_entry) {
7193 if (view->searching == TOG_SEARCH_FORWARD) {
7194 if (s->selected_entry)
7195 te = got_tree_entry_get_next(s->tree,
7196 s->selected_entry);
7197 else
7198 te = got_object_tree_get_first_entry(s->tree);
7199 } else {
7200 if (s->selected_entry == NULL)
7201 te = got_object_tree_get_last_entry(s->tree);
7202 else
7203 te = got_tree_entry_get_prev(s->tree,
7204 s->selected_entry);
7206 } else {
7207 if (s->selected_entry)
7208 te = s->selected_entry;
7209 else if (view->searching == TOG_SEARCH_FORWARD)
7210 te = got_object_tree_get_first_entry(s->tree);
7211 else
7212 te = got_object_tree_get_last_entry(s->tree);
7215 while (1) {
7216 if (te == NULL) {
7217 if (s->matched_entry == NULL) {
7218 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7219 return NULL;
7221 if (view->searching == TOG_SEARCH_FORWARD)
7222 te = got_object_tree_get_first_entry(s->tree);
7223 else
7224 te = got_object_tree_get_last_entry(s->tree);
7227 if (match_tree_entry(te, &view->regex)) {
7228 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7229 s->matched_entry = te;
7230 break;
7233 if (view->searching == TOG_SEARCH_FORWARD)
7234 te = got_tree_entry_get_next(s->tree, te);
7235 else
7236 te = got_tree_entry_get_prev(s->tree, te);
7239 if (s->matched_entry) {
7240 s->first_displayed_entry = s->matched_entry;
7241 s->selected = 0;
7244 return NULL;
7247 static const struct got_error *
7248 show_tree_view(struct tog_view *view)
7250 const struct got_error *err = NULL;
7251 struct tog_tree_view_state *s = &view->state.tree;
7252 char *parent_path;
7254 err = tree_entry_path(&parent_path, &s->parents, NULL);
7255 if (err)
7256 return err;
7258 err = draw_tree_entries(view, parent_path);
7259 free(parent_path);
7261 view_border(view);
7262 return err;
7265 static const struct got_error *
7266 tree_goto_line(struct tog_view *view, int nlines)
7268 const struct got_error *err = NULL;
7269 struct tog_tree_view_state *s = &view->state.tree;
7270 struct got_tree_entry **fte, **lte, **ste;
7271 int g, last, first = 1, i = 1;
7272 int root = s->tree == s->root;
7273 int off = root ? 1 : 2;
7275 g = view->gline;
7276 view->gline = 0;
7278 if (g == 0)
7279 g = 1;
7280 else if (g > got_object_tree_get_nentries(s->tree))
7281 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7283 fte = &s->first_displayed_entry;
7284 lte = &s->last_displayed_entry;
7285 ste = &s->selected_entry;
7287 if (*fte != NULL) {
7288 first = got_tree_entry_get_index(*fte);
7289 first += off; /* account for ".." */
7291 last = got_tree_entry_get_index(*lte);
7292 last += off;
7294 if (g >= first && g <= last && g - first < nlines) {
7295 s->selected = g - first;
7296 return NULL; /* gline is on the current page */
7299 if (*ste != NULL) {
7300 i = got_tree_entry_get_index(*ste);
7301 i += off;
7304 if (i < g) {
7305 err = tree_scroll_down(view, g - i);
7306 if (err)
7307 return err;
7308 if (got_tree_entry_get_index(*lte) >=
7309 got_object_tree_get_nentries(s->tree) - 1 &&
7310 first + s->selected < g &&
7311 s->selected < s->ndisplayed - 1) {
7312 first = got_tree_entry_get_index(*fte);
7313 first += off;
7314 s->selected = g - first;
7316 } else if (i > g)
7317 tree_scroll_up(s, i - g);
7319 if (g < nlines &&
7320 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7321 s->selected = g - 1;
7323 return NULL;
7326 static const struct got_error *
7327 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7329 const struct got_error *err = NULL;
7330 struct tog_tree_view_state *s = &view->state.tree;
7331 struct got_tree_entry *te;
7332 int n, nscroll = view->nlines - 3;
7334 if (view->gline)
7335 return tree_goto_line(view, nscroll);
7337 switch (ch) {
7338 case 'i':
7339 s->show_ids = !s->show_ids;
7340 view->count = 0;
7341 break;
7342 case 'L':
7343 view->count = 0;
7344 if (!s->selected_entry)
7345 break;
7346 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7347 break;
7348 case 'R':
7349 view->count = 0;
7350 err = view_request_new(new_view, view, TOG_VIEW_REF);
7351 break;
7352 case 'g':
7353 case KEY_HOME:
7354 s->selected = 0;
7355 view->count = 0;
7356 if (s->tree == s->root)
7357 s->first_displayed_entry =
7358 got_object_tree_get_first_entry(s->tree);
7359 else
7360 s->first_displayed_entry = NULL;
7361 break;
7362 case 'G':
7363 case KEY_END: {
7364 int eos = view->nlines - 3;
7366 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7367 --eos; /* border */
7368 s->selected = 0;
7369 view->count = 0;
7370 te = got_object_tree_get_last_entry(s->tree);
7371 for (n = 0; n < eos; n++) {
7372 if (te == NULL) {
7373 if (s->tree != s->root) {
7374 s->first_displayed_entry = NULL;
7375 n++;
7377 break;
7379 s->first_displayed_entry = te;
7380 te = got_tree_entry_get_prev(s->tree, te);
7382 if (n > 0)
7383 s->selected = n - 1;
7384 break;
7386 case 'k':
7387 case KEY_UP:
7388 case CTRL('p'):
7389 if (s->selected > 0) {
7390 s->selected--;
7391 break;
7393 tree_scroll_up(s, 1);
7394 if (s->selected_entry == NULL ||
7395 (s->tree == s->root && s->selected_entry ==
7396 got_object_tree_get_first_entry(s->tree)))
7397 view->count = 0;
7398 break;
7399 case CTRL('u'):
7400 case 'u':
7401 nscroll /= 2;
7402 /* FALL THROUGH */
7403 case KEY_PPAGE:
7404 case CTRL('b'):
7405 case 'b':
7406 if (s->tree == s->root) {
7407 if (got_object_tree_get_first_entry(s->tree) ==
7408 s->first_displayed_entry)
7409 s->selected -= MIN(s->selected, nscroll);
7410 } else {
7411 if (s->first_displayed_entry == NULL)
7412 s->selected -= MIN(s->selected, nscroll);
7414 tree_scroll_up(s, MAX(0, nscroll));
7415 if (s->selected_entry == NULL ||
7416 (s->tree == s->root && s->selected_entry ==
7417 got_object_tree_get_first_entry(s->tree)))
7418 view->count = 0;
7419 break;
7420 case 'j':
7421 case KEY_DOWN:
7422 case CTRL('n'):
7423 if (s->selected < s->ndisplayed - 1) {
7424 s->selected++;
7425 break;
7427 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7428 == NULL) {
7429 /* can't scroll any further */
7430 view->count = 0;
7431 break;
7433 tree_scroll_down(view, 1);
7434 break;
7435 case CTRL('d'):
7436 case 'd':
7437 nscroll /= 2;
7438 /* FALL THROUGH */
7439 case KEY_NPAGE:
7440 case CTRL('f'):
7441 case 'f':
7442 case ' ':
7443 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7444 == NULL) {
7445 /* can't scroll any further; move cursor down */
7446 if (s->selected < s->ndisplayed - 1)
7447 s->selected += MIN(nscroll,
7448 s->ndisplayed - s->selected - 1);
7449 else
7450 view->count = 0;
7451 break;
7453 tree_scroll_down(view, nscroll);
7454 break;
7455 case KEY_ENTER:
7456 case '\r':
7457 case KEY_BACKSPACE:
7458 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7459 struct tog_parent_tree *parent;
7460 /* user selected '..' */
7461 if (s->tree == s->root) {
7462 view->count = 0;
7463 break;
7465 parent = TAILQ_FIRST(&s->parents);
7466 TAILQ_REMOVE(&s->parents, parent,
7467 entry);
7468 got_object_tree_close(s->tree);
7469 s->tree = parent->tree;
7470 s->first_displayed_entry =
7471 parent->first_displayed_entry;
7472 s->selected_entry =
7473 parent->selected_entry;
7474 s->selected = parent->selected;
7475 if (s->selected > view->nlines - 3) {
7476 err = offset_selection_down(view);
7477 if (err)
7478 break;
7480 free(parent);
7481 } else if (S_ISDIR(got_tree_entry_get_mode(
7482 s->selected_entry))) {
7483 struct got_tree_object *subtree;
7484 view->count = 0;
7485 err = got_object_open_as_tree(&subtree, s->repo,
7486 got_tree_entry_get_id(s->selected_entry));
7487 if (err)
7488 break;
7489 err = tree_view_visit_subtree(s, subtree);
7490 if (err) {
7491 got_object_tree_close(subtree);
7492 break;
7494 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7495 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7496 break;
7497 case KEY_RESIZE:
7498 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7499 s->selected = view->nlines - 4;
7500 view->count = 0;
7501 break;
7502 default:
7503 view->count = 0;
7504 break;
7507 return err;
7510 __dead static void
7511 usage_tree(void)
7513 endwin();
7514 fprintf(stderr,
7515 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7516 getprogname());
7517 exit(1);
7520 static const struct got_error *
7521 cmd_tree(int argc, char *argv[])
7523 const struct got_error *error;
7524 struct got_repository *repo = NULL;
7525 struct got_worktree *worktree = NULL;
7526 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7527 struct got_object_id *commit_id = NULL;
7528 struct got_commit_object *commit = NULL;
7529 const char *commit_id_arg = NULL;
7530 char *label = NULL;
7531 struct got_reference *ref = NULL;
7532 const char *head_ref_name = NULL;
7533 int ch;
7534 struct tog_view *view;
7535 int *pack_fds = NULL;
7537 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7538 switch (ch) {
7539 case 'c':
7540 commit_id_arg = optarg;
7541 break;
7542 case 'r':
7543 repo_path = realpath(optarg, NULL);
7544 if (repo_path == NULL)
7545 return got_error_from_errno2("realpath",
7546 optarg);
7547 break;
7548 default:
7549 usage_tree();
7550 /* NOTREACHED */
7554 argc -= optind;
7555 argv += optind;
7557 if (argc > 1)
7558 usage_tree();
7560 error = got_repo_pack_fds_open(&pack_fds);
7561 if (error != NULL)
7562 goto done;
7564 if (repo_path == NULL) {
7565 cwd = getcwd(NULL, 0);
7566 if (cwd == NULL)
7567 return got_error_from_errno("getcwd");
7568 error = got_worktree_open(&worktree, cwd);
7569 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7570 goto done;
7571 if (worktree)
7572 repo_path =
7573 strdup(got_worktree_get_repo_path(worktree));
7574 else
7575 repo_path = strdup(cwd);
7576 if (repo_path == NULL) {
7577 error = got_error_from_errno("strdup");
7578 goto done;
7582 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7583 if (error != NULL)
7584 goto done;
7586 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7587 repo, worktree);
7588 if (error)
7589 goto done;
7591 init_curses();
7593 error = apply_unveil(got_repo_get_path(repo), NULL);
7594 if (error)
7595 goto done;
7597 error = tog_load_refs(repo, 0);
7598 if (error)
7599 goto done;
7601 if (commit_id_arg == NULL) {
7602 error = got_repo_match_object_id(&commit_id, &label,
7603 worktree ? got_worktree_get_head_ref_name(worktree) :
7604 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7605 if (error)
7606 goto done;
7607 head_ref_name = label;
7608 } else {
7609 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7610 if (error == NULL)
7611 head_ref_name = got_ref_get_name(ref);
7612 else if (error->code != GOT_ERR_NOT_REF)
7613 goto done;
7614 error = got_repo_match_object_id(&commit_id, NULL,
7615 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7616 if (error)
7617 goto done;
7620 error = got_object_open_as_commit(&commit, repo, commit_id);
7621 if (error)
7622 goto done;
7624 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7625 if (view == NULL) {
7626 error = got_error_from_errno("view_open");
7627 goto done;
7629 error = open_tree_view(view, commit_id, head_ref_name, repo);
7630 if (error)
7631 goto done;
7632 if (!got_path_is_root_dir(in_repo_path)) {
7633 error = tree_view_walk_path(&view->state.tree, commit,
7634 in_repo_path);
7635 if (error)
7636 goto done;
7639 if (worktree) {
7640 /* Release work tree lock. */
7641 got_worktree_close(worktree);
7642 worktree = NULL;
7644 error = view_loop(view);
7645 done:
7646 free(repo_path);
7647 free(cwd);
7648 free(commit_id);
7649 free(label);
7650 if (ref)
7651 got_ref_close(ref);
7652 if (repo) {
7653 const struct got_error *close_err = got_repo_close(repo);
7654 if (error == NULL)
7655 error = close_err;
7657 if (pack_fds) {
7658 const struct got_error *pack_err =
7659 got_repo_pack_fds_close(pack_fds);
7660 if (error == NULL)
7661 error = pack_err;
7663 tog_free_refs();
7664 return error;
7667 static const struct got_error *
7668 ref_view_load_refs(struct tog_ref_view_state *s)
7670 struct got_reflist_entry *sre;
7671 struct tog_reflist_entry *re;
7673 s->nrefs = 0;
7674 TAILQ_FOREACH(sre, &tog_refs, entry) {
7675 if (strncmp(got_ref_get_name(sre->ref),
7676 "refs/got/", 9) == 0 &&
7677 strncmp(got_ref_get_name(sre->ref),
7678 "refs/got/backup/", 16) != 0)
7679 continue;
7681 re = malloc(sizeof(*re));
7682 if (re == NULL)
7683 return got_error_from_errno("malloc");
7685 re->ref = got_ref_dup(sre->ref);
7686 if (re->ref == NULL)
7687 return got_error_from_errno("got_ref_dup");
7688 re->idx = s->nrefs++;
7689 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7692 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7693 return NULL;
7696 static void
7697 ref_view_free_refs(struct tog_ref_view_state *s)
7699 struct tog_reflist_entry *re;
7701 while (!TAILQ_EMPTY(&s->refs)) {
7702 re = TAILQ_FIRST(&s->refs);
7703 TAILQ_REMOVE(&s->refs, re, entry);
7704 got_ref_close(re->ref);
7705 free(re);
7709 static const struct got_error *
7710 open_ref_view(struct tog_view *view, struct got_repository *repo)
7712 const struct got_error *err = NULL;
7713 struct tog_ref_view_state *s = &view->state.ref;
7715 s->selected_entry = 0;
7716 s->repo = repo;
7718 TAILQ_INIT(&s->refs);
7719 STAILQ_INIT(&s->colors);
7721 err = ref_view_load_refs(s);
7722 if (err)
7723 return err;
7725 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7726 err = add_color(&s->colors, "^refs/heads/",
7727 TOG_COLOR_REFS_HEADS,
7728 get_color_value("TOG_COLOR_REFS_HEADS"));
7729 if (err)
7730 goto done;
7732 err = add_color(&s->colors, "^refs/tags/",
7733 TOG_COLOR_REFS_TAGS,
7734 get_color_value("TOG_COLOR_REFS_TAGS"));
7735 if (err)
7736 goto done;
7738 err = add_color(&s->colors, "^refs/remotes/",
7739 TOG_COLOR_REFS_REMOTES,
7740 get_color_value("TOG_COLOR_REFS_REMOTES"));
7741 if (err)
7742 goto done;
7744 err = add_color(&s->colors, "^refs/got/backup/",
7745 TOG_COLOR_REFS_BACKUP,
7746 get_color_value("TOG_COLOR_REFS_BACKUP"));
7747 if (err)
7748 goto done;
7751 view->show = show_ref_view;
7752 view->input = input_ref_view;
7753 view->close = close_ref_view;
7754 view->search_start = search_start_ref_view;
7755 view->search_next = search_next_ref_view;
7756 done:
7757 if (err)
7758 free_colors(&s->colors);
7759 return err;
7762 static const struct got_error *
7763 close_ref_view(struct tog_view *view)
7765 struct tog_ref_view_state *s = &view->state.ref;
7767 ref_view_free_refs(s);
7768 free_colors(&s->colors);
7770 return NULL;
7773 static const struct got_error *
7774 resolve_reflist_entry(struct got_object_id **commit_id,
7775 struct tog_reflist_entry *re, struct got_repository *repo)
7777 const struct got_error *err = NULL;
7778 struct got_object_id *obj_id;
7779 struct got_tag_object *tag = NULL;
7780 int obj_type;
7782 *commit_id = NULL;
7784 err = got_ref_resolve(&obj_id, repo, re->ref);
7785 if (err)
7786 return err;
7788 err = got_object_get_type(&obj_type, repo, obj_id);
7789 if (err)
7790 goto done;
7792 switch (obj_type) {
7793 case GOT_OBJ_TYPE_COMMIT:
7794 *commit_id = obj_id;
7795 break;
7796 case GOT_OBJ_TYPE_TAG:
7797 err = got_object_open_as_tag(&tag, repo, obj_id);
7798 if (err)
7799 goto done;
7800 free(obj_id);
7801 err = got_object_get_type(&obj_type, repo,
7802 got_object_tag_get_object_id(tag));
7803 if (err)
7804 goto done;
7805 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7806 err = got_error(GOT_ERR_OBJ_TYPE);
7807 goto done;
7809 *commit_id = got_object_id_dup(
7810 got_object_tag_get_object_id(tag));
7811 if (*commit_id == NULL) {
7812 err = got_error_from_errno("got_object_id_dup");
7813 goto done;
7815 break;
7816 default:
7817 err = got_error(GOT_ERR_OBJ_TYPE);
7818 break;
7821 done:
7822 if (tag)
7823 got_object_tag_close(tag);
7824 if (err) {
7825 free(*commit_id);
7826 *commit_id = NULL;
7828 return err;
7831 static const struct got_error *
7832 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7833 struct tog_reflist_entry *re, struct got_repository *repo)
7835 struct tog_view *log_view;
7836 const struct got_error *err = NULL;
7837 struct got_object_id *commit_id = NULL;
7839 *new_view = NULL;
7841 err = resolve_reflist_entry(&commit_id, re, repo);
7842 if (err) {
7843 if (err->code != GOT_ERR_OBJ_TYPE)
7844 return err;
7845 else
7846 return NULL;
7849 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7850 if (log_view == NULL) {
7851 err = got_error_from_errno("view_open");
7852 goto done;
7855 err = open_log_view(log_view, commit_id, repo,
7856 got_ref_get_name(re->ref), "", 0);
7857 done:
7858 if (err)
7859 view_close(log_view);
7860 else
7861 *new_view = log_view;
7862 free(commit_id);
7863 return err;
7866 static void
7867 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7869 struct tog_reflist_entry *re;
7870 int i = 0;
7872 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7873 return;
7875 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7876 while (i++ < maxscroll) {
7877 if (re == NULL)
7878 break;
7879 s->first_displayed_entry = re;
7880 re = TAILQ_PREV(re, tog_reflist_head, entry);
7884 static const struct got_error *
7885 ref_scroll_down(struct tog_view *view, int maxscroll)
7887 struct tog_ref_view_state *s = &view->state.ref;
7888 struct tog_reflist_entry *next, *last;
7889 int n = 0;
7891 if (s->first_displayed_entry)
7892 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7893 else
7894 next = TAILQ_FIRST(&s->refs);
7896 last = s->last_displayed_entry;
7897 while (next && n++ < maxscroll) {
7898 if (last) {
7899 s->last_displayed_entry = last;
7900 last = TAILQ_NEXT(last, entry);
7902 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7903 s->first_displayed_entry = next;
7904 next = TAILQ_NEXT(next, entry);
7908 return NULL;
7911 static const struct got_error *
7912 search_start_ref_view(struct tog_view *view)
7914 struct tog_ref_view_state *s = &view->state.ref;
7916 s->matched_entry = NULL;
7917 return NULL;
7920 static int
7921 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7923 regmatch_t regmatch;
7925 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7926 0) == 0;
7929 static const struct got_error *
7930 search_next_ref_view(struct tog_view *view)
7932 struct tog_ref_view_state *s = &view->state.ref;
7933 struct tog_reflist_entry *re = NULL;
7935 if (!view->searching) {
7936 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7937 return NULL;
7940 if (s->matched_entry) {
7941 if (view->searching == TOG_SEARCH_FORWARD) {
7942 if (s->selected_entry)
7943 re = TAILQ_NEXT(s->selected_entry, entry);
7944 else
7945 re = TAILQ_PREV(s->selected_entry,
7946 tog_reflist_head, entry);
7947 } else {
7948 if (s->selected_entry == NULL)
7949 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7950 else
7951 re = TAILQ_PREV(s->selected_entry,
7952 tog_reflist_head, entry);
7954 } else {
7955 if (s->selected_entry)
7956 re = s->selected_entry;
7957 else if (view->searching == TOG_SEARCH_FORWARD)
7958 re = TAILQ_FIRST(&s->refs);
7959 else
7960 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7963 while (1) {
7964 if (re == NULL) {
7965 if (s->matched_entry == NULL) {
7966 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7967 return NULL;
7969 if (view->searching == TOG_SEARCH_FORWARD)
7970 re = TAILQ_FIRST(&s->refs);
7971 else
7972 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7975 if (match_reflist_entry(re, &view->regex)) {
7976 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7977 s->matched_entry = re;
7978 break;
7981 if (view->searching == TOG_SEARCH_FORWARD)
7982 re = TAILQ_NEXT(re, entry);
7983 else
7984 re = TAILQ_PREV(re, tog_reflist_head, entry);
7987 if (s->matched_entry) {
7988 s->first_displayed_entry = s->matched_entry;
7989 s->selected = 0;
7992 return NULL;
7995 static const struct got_error *
7996 show_ref_view(struct tog_view *view)
7998 const struct got_error *err = NULL;
7999 struct tog_ref_view_state *s = &view->state.ref;
8000 struct tog_reflist_entry *re;
8001 char *line = NULL;
8002 wchar_t *wline;
8003 struct tog_color *tc;
8004 int width, n;
8005 int limit = view->nlines;
8007 werase(view->window);
8009 s->ndisplayed = 0;
8010 if (view_is_hsplit_top(view))
8011 --limit; /* border */
8013 if (limit == 0)
8014 return NULL;
8016 re = s->first_displayed_entry;
8018 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8019 s->nrefs) == -1)
8020 return got_error_from_errno("asprintf");
8022 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8023 if (err) {
8024 free(line);
8025 return err;
8027 if (view_needs_focus_indication(view))
8028 wstandout(view->window);
8029 waddwstr(view->window, wline);
8030 while (width++ < view->ncols)
8031 waddch(view->window, ' ');
8032 if (view_needs_focus_indication(view))
8033 wstandend(view->window);
8034 free(wline);
8035 wline = NULL;
8036 free(line);
8037 line = NULL;
8038 if (--limit <= 0)
8039 return NULL;
8041 n = 0;
8042 while (re && limit > 0) {
8043 char *line = NULL;
8044 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8046 if (s->show_date) {
8047 struct got_commit_object *ci;
8048 struct got_tag_object *tag;
8049 struct got_object_id *id;
8050 struct tm tm;
8051 time_t t;
8053 err = got_ref_resolve(&id, s->repo, re->ref);
8054 if (err)
8055 return err;
8056 err = got_object_open_as_tag(&tag, s->repo, id);
8057 if (err) {
8058 if (err->code != GOT_ERR_OBJ_TYPE) {
8059 free(id);
8060 return err;
8062 err = got_object_open_as_commit(&ci, s->repo,
8063 id);
8064 if (err) {
8065 free(id);
8066 return err;
8068 t = got_object_commit_get_committer_time(ci);
8069 got_object_commit_close(ci);
8070 } else {
8071 t = got_object_tag_get_tagger_time(tag);
8072 got_object_tag_close(tag);
8074 free(id);
8075 if (gmtime_r(&t, &tm) == NULL)
8076 return got_error_from_errno("gmtime_r");
8077 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8078 return got_error(GOT_ERR_NO_SPACE);
8080 if (got_ref_is_symbolic(re->ref)) {
8081 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8082 ymd : "", got_ref_get_name(re->ref),
8083 got_ref_get_symref_target(re->ref)) == -1)
8084 return got_error_from_errno("asprintf");
8085 } else if (s->show_ids) {
8086 struct got_object_id *id;
8087 char *id_str;
8088 err = got_ref_resolve(&id, s->repo, re->ref);
8089 if (err)
8090 return err;
8091 err = got_object_id_str(&id_str, id);
8092 if (err) {
8093 free(id);
8094 return err;
8096 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8097 got_ref_get_name(re->ref), id_str) == -1) {
8098 err = got_error_from_errno("asprintf");
8099 free(id);
8100 free(id_str);
8101 return err;
8103 free(id);
8104 free(id_str);
8105 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8106 got_ref_get_name(re->ref)) == -1)
8107 return got_error_from_errno("asprintf");
8109 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
8110 0, 0);
8111 if (err) {
8112 free(line);
8113 return err;
8115 if (n == s->selected) {
8116 if (view->focussed)
8117 wstandout(view->window);
8118 s->selected_entry = re;
8120 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8121 if (tc)
8122 wattr_on(view->window,
8123 COLOR_PAIR(tc->colorpair), NULL);
8124 waddwstr(view->window, wline);
8125 if (tc)
8126 wattr_off(view->window,
8127 COLOR_PAIR(tc->colorpair), NULL);
8128 if (width < view->ncols - 1)
8129 waddch(view->window, '\n');
8130 if (n == s->selected && view->focussed)
8131 wstandend(view->window);
8132 free(line);
8133 free(wline);
8134 wline = NULL;
8135 n++;
8136 s->ndisplayed++;
8137 s->last_displayed_entry = re;
8139 limit--;
8140 re = TAILQ_NEXT(re, entry);
8143 view_border(view);
8144 return err;
8147 static const struct got_error *
8148 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8149 struct tog_reflist_entry *re, struct got_repository *repo)
8151 const struct got_error *err = NULL;
8152 struct got_object_id *commit_id = NULL;
8153 struct tog_view *tree_view;
8155 *new_view = NULL;
8157 err = resolve_reflist_entry(&commit_id, re, repo);
8158 if (err) {
8159 if (err->code != GOT_ERR_OBJ_TYPE)
8160 return err;
8161 else
8162 return NULL;
8166 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8167 if (tree_view == NULL) {
8168 err = got_error_from_errno("view_open");
8169 goto done;
8172 err = open_tree_view(tree_view, commit_id,
8173 got_ref_get_name(re->ref), repo);
8174 if (err)
8175 goto done;
8177 *new_view = tree_view;
8178 done:
8179 free(commit_id);
8180 return err;
8183 static const struct got_error *
8184 ref_goto_line(struct tog_view *view, int nlines)
8186 const struct got_error *err = NULL;
8187 struct tog_ref_view_state *s = &view->state.ref;
8188 int g, idx = s->selected_entry->idx;
8190 g = view->gline;
8191 view->gline = 0;
8193 if (g == 0)
8194 g = 1;
8195 else if (g > s->nrefs)
8196 g = s->nrefs;
8198 if (g >= s->first_displayed_entry->idx + 1 &&
8199 g <= s->last_displayed_entry->idx + 1 &&
8200 g - s->first_displayed_entry->idx - 1 < nlines) {
8201 s->selected = g - s->first_displayed_entry->idx - 1;
8202 return NULL;
8205 if (idx + 1 < g) {
8206 err = ref_scroll_down(view, g - idx - 1);
8207 if (err)
8208 return err;
8209 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8210 s->first_displayed_entry->idx + s->selected < g &&
8211 s->selected < s->ndisplayed - 1)
8212 s->selected = g - s->first_displayed_entry->idx - 1;
8213 } else if (idx + 1 > g)
8214 ref_scroll_up(s, idx - g + 1);
8216 if (g < nlines && s->first_displayed_entry->idx == 0)
8217 s->selected = g - 1;
8219 return NULL;
8223 static const struct got_error *
8224 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8226 const struct got_error *err = NULL;
8227 struct tog_ref_view_state *s = &view->state.ref;
8228 struct tog_reflist_entry *re;
8229 int n, nscroll = view->nlines - 1;
8231 if (view->gline)
8232 return ref_goto_line(view, nscroll);
8234 switch (ch) {
8235 case 'i':
8236 s->show_ids = !s->show_ids;
8237 view->count = 0;
8238 break;
8239 case 'm':
8240 s->show_date = !s->show_date;
8241 view->count = 0;
8242 break;
8243 case 'o':
8244 s->sort_by_date = !s->sort_by_date;
8245 view->count = 0;
8246 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8247 got_ref_cmp_by_commit_timestamp_descending :
8248 tog_ref_cmp_by_name, s->repo);
8249 if (err)
8250 break;
8251 got_reflist_object_id_map_free(tog_refs_idmap);
8252 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8253 &tog_refs, s->repo);
8254 if (err)
8255 break;
8256 ref_view_free_refs(s);
8257 err = ref_view_load_refs(s);
8258 break;
8259 case KEY_ENTER:
8260 case '\r':
8261 view->count = 0;
8262 if (!s->selected_entry)
8263 break;
8264 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8265 break;
8266 case 'T':
8267 view->count = 0;
8268 if (!s->selected_entry)
8269 break;
8270 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8271 break;
8272 case 'g':
8273 case KEY_HOME:
8274 s->selected = 0;
8275 view->count = 0;
8276 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8277 break;
8278 case 'G':
8279 case KEY_END: {
8280 int eos = view->nlines - 1;
8282 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8283 --eos; /* border */
8284 s->selected = 0;
8285 view->count = 0;
8286 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8287 for (n = 0; n < eos; n++) {
8288 if (re == NULL)
8289 break;
8290 s->first_displayed_entry = re;
8291 re = TAILQ_PREV(re, tog_reflist_head, entry);
8293 if (n > 0)
8294 s->selected = n - 1;
8295 break;
8297 case 'k':
8298 case KEY_UP:
8299 case CTRL('p'):
8300 if (s->selected > 0) {
8301 s->selected--;
8302 break;
8304 ref_scroll_up(s, 1);
8305 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8306 view->count = 0;
8307 break;
8308 case CTRL('u'):
8309 case 'u':
8310 nscroll /= 2;
8311 /* FALL THROUGH */
8312 case KEY_PPAGE:
8313 case CTRL('b'):
8314 case 'b':
8315 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8316 s->selected -= MIN(nscroll, s->selected);
8317 ref_scroll_up(s, MAX(0, nscroll));
8318 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8319 view->count = 0;
8320 break;
8321 case 'j':
8322 case KEY_DOWN:
8323 case CTRL('n'):
8324 if (s->selected < s->ndisplayed - 1) {
8325 s->selected++;
8326 break;
8328 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8329 /* can't scroll any further */
8330 view->count = 0;
8331 break;
8333 ref_scroll_down(view, 1);
8334 break;
8335 case CTRL('d'):
8336 case 'd':
8337 nscroll /= 2;
8338 /* FALL THROUGH */
8339 case KEY_NPAGE:
8340 case CTRL('f'):
8341 case 'f':
8342 case ' ':
8343 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8344 /* can't scroll any further; move cursor down */
8345 if (s->selected < s->ndisplayed - 1)
8346 s->selected += MIN(nscroll,
8347 s->ndisplayed - s->selected - 1);
8348 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8349 s->selected += s->ndisplayed - s->selected - 1;
8350 view->count = 0;
8351 break;
8353 ref_scroll_down(view, nscroll);
8354 break;
8355 case CTRL('l'):
8356 view->count = 0;
8357 tog_free_refs();
8358 err = tog_load_refs(s->repo, s->sort_by_date);
8359 if (err)
8360 break;
8361 ref_view_free_refs(s);
8362 err = ref_view_load_refs(s);
8363 break;
8364 case KEY_RESIZE:
8365 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8366 s->selected = view->nlines - 2;
8367 break;
8368 default:
8369 view->count = 0;
8370 break;
8373 return err;
8376 __dead static void
8377 usage_ref(void)
8379 endwin();
8380 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8381 getprogname());
8382 exit(1);
8385 static const struct got_error *
8386 cmd_ref(int argc, char *argv[])
8388 const struct got_error *error;
8389 struct got_repository *repo = NULL;
8390 struct got_worktree *worktree = NULL;
8391 char *cwd = NULL, *repo_path = NULL;
8392 int ch;
8393 struct tog_view *view;
8394 int *pack_fds = NULL;
8396 while ((ch = getopt(argc, argv, "r:")) != -1) {
8397 switch (ch) {
8398 case 'r':
8399 repo_path = realpath(optarg, NULL);
8400 if (repo_path == NULL)
8401 return got_error_from_errno2("realpath",
8402 optarg);
8403 break;
8404 default:
8405 usage_ref();
8406 /* NOTREACHED */
8410 argc -= optind;
8411 argv += optind;
8413 if (argc > 1)
8414 usage_ref();
8416 error = got_repo_pack_fds_open(&pack_fds);
8417 if (error != NULL)
8418 goto done;
8420 if (repo_path == NULL) {
8421 cwd = getcwd(NULL, 0);
8422 if (cwd == NULL)
8423 return got_error_from_errno("getcwd");
8424 error = got_worktree_open(&worktree, cwd);
8425 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8426 goto done;
8427 if (worktree)
8428 repo_path =
8429 strdup(got_worktree_get_repo_path(worktree));
8430 else
8431 repo_path = strdup(cwd);
8432 if (repo_path == NULL) {
8433 error = got_error_from_errno("strdup");
8434 goto done;
8438 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8439 if (error != NULL)
8440 goto done;
8442 init_curses();
8444 error = apply_unveil(got_repo_get_path(repo), NULL);
8445 if (error)
8446 goto done;
8448 error = tog_load_refs(repo, 0);
8449 if (error)
8450 goto done;
8452 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8453 if (view == NULL) {
8454 error = got_error_from_errno("view_open");
8455 goto done;
8458 error = open_ref_view(view, repo);
8459 if (error)
8460 goto done;
8462 if (worktree) {
8463 /* Release work tree lock. */
8464 got_worktree_close(worktree);
8465 worktree = NULL;
8467 error = view_loop(view);
8468 done:
8469 free(repo_path);
8470 free(cwd);
8471 if (repo) {
8472 const struct got_error *close_err = got_repo_close(repo);
8473 if (close_err)
8474 error = close_err;
8476 if (pack_fds) {
8477 const struct got_error *pack_err =
8478 got_repo_pack_fds_close(pack_fds);
8479 if (error == NULL)
8480 error = pack_err;
8482 tog_free_refs();
8483 return error;
8486 static const struct got_error*
8487 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8488 const char *str)
8490 size_t len;
8492 if (win == NULL)
8493 win = stdscr;
8495 len = strlen(str);
8496 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8498 if (focus)
8499 wstandout(win);
8500 if (mvwprintw(win, y, x, "%s", str) == ERR)
8501 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8502 if (focus)
8503 wstandend(win);
8505 return NULL;
8508 static const struct got_error *
8509 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8511 off_t *p;
8513 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8514 if (p == NULL) {
8515 free(*line_offsets);
8516 *line_offsets = NULL;
8517 return got_error_from_errno("reallocarray");
8520 *line_offsets = p;
8521 (*line_offsets)[*nlines] = off;
8522 ++(*nlines);
8523 return NULL;
8526 static const struct got_error *
8527 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8529 *ret = 0;
8531 for (;n > 0; --n, ++km) {
8532 char *t0, *t, *k;
8533 size_t len = 1;
8535 if (km->keys == NULL)
8536 continue;
8538 t = t0 = strdup(km->keys);
8539 if (t0 == NULL)
8540 return got_error_from_errno("strdup");
8542 len += strlen(t);
8543 while ((k = strsep(&t, " ")) != NULL)
8544 len += strlen(k) > 1 ? 2 : 0;
8545 free(t0);
8546 *ret = MAX(*ret, len);
8549 return NULL;
8553 * Write keymap section headers, keys, and key info in km to f.
8554 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8555 * wrap control and symbolic keys in guillemets, else use <>.
8557 static const struct got_error *
8558 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8560 int n, len = width;
8562 if (km->keys) {
8563 static const char *u8_glyph[] = {
8564 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8565 "\xe2\x80\xba" /* U+203A (utf8 >) */
8567 char *t0, *t, *k;
8568 int cs, s, first = 1;
8570 cs = got_locale_is_utf8();
8572 t = t0 = strdup(km->keys);
8573 if (t0 == NULL)
8574 return got_error_from_errno("strdup");
8576 len = strlen(km->keys);
8577 while ((k = strsep(&t, " ")) != NULL) {
8578 s = strlen(k) > 1; /* control or symbolic key */
8579 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8580 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8581 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8582 if (n < 0) {
8583 free(t0);
8584 return got_error_from_errno("fprintf");
8586 first = 0;
8587 len += s ? 2 : 0;
8588 *off += n;
8590 free(t0);
8592 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8593 if (n < 0)
8594 return got_error_from_errno("fprintf");
8595 *off += n;
8597 return NULL;
8600 static const struct got_error *
8601 format_help(struct tog_help_view_state *s)
8603 const struct got_error *err = NULL;
8604 off_t off = 0;
8605 int i, max, n, show = s->all;
8606 static const struct tog_key_map km[] = {
8607 #define KEYMAP_(info, type) { NULL, (info), type }
8608 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8609 GENERATE_HELP
8610 #undef KEYMAP_
8611 #undef KEY_
8614 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8615 if (err)
8616 return err;
8618 n = nitems(km);
8619 err = max_key_str(&max, km, n);
8620 if (err)
8621 return err;
8623 for (i = 0; i < n; ++i) {
8624 if (km[i].keys == NULL) {
8625 show = s->all;
8626 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8627 km[i].type == s->type || s->all)
8628 show = 1;
8630 if (show) {
8631 err = format_help_line(&off, s->f, &km[i], max);
8632 if (err)
8633 return err;
8634 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8635 if (err)
8636 return err;
8639 fputc('\n', s->f);
8640 ++off;
8641 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8642 return err;
8645 static const struct got_error *
8646 create_help(struct tog_help_view_state *s)
8648 FILE *f;
8649 const struct got_error *err;
8651 free(s->line_offsets);
8652 s->line_offsets = NULL;
8653 s->nlines = 0;
8655 f = got_opentemp();
8656 if (f == NULL)
8657 return got_error_from_errno("got_opentemp");
8658 s->f = f;
8660 err = format_help(s);
8661 if (err)
8662 return err;
8664 if (s->f && fflush(s->f) != 0)
8665 return got_error_from_errno("fflush");
8667 return NULL;
8670 static const struct got_error *
8671 search_start_help_view(struct tog_view *view)
8673 view->state.help.matched_line = 0;
8674 return NULL;
8677 static void
8678 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8679 size_t *nlines, int **first, int **last, int **match, int **selected)
8681 struct tog_help_view_state *s = &view->state.help;
8683 *f = s->f;
8684 *nlines = s->nlines;
8685 *line_offsets = s->line_offsets;
8686 *match = &s->matched_line;
8687 *first = &s->first_displayed_line;
8688 *last = &s->last_displayed_line;
8689 *selected = &s->selected_line;
8692 static const struct got_error *
8693 show_help_view(struct tog_view *view)
8695 struct tog_help_view_state *s = &view->state.help;
8696 const struct got_error *err;
8697 regmatch_t *regmatch = &view->regmatch;
8698 wchar_t *wline;
8699 char *line;
8700 ssize_t linelen;
8701 size_t linesz = 0;
8702 int width, nprinted = 0, rc = 0;
8703 int eos = view->nlines;
8705 if (view_is_hsplit_top(view))
8706 --eos; /* account for border */
8708 s->lineno = 0;
8709 rewind(s->f);
8710 werase(view->window);
8712 if (view->gline > s->nlines - 1)
8713 view->gline = s->nlines - 1;
8715 err = win_draw_center(view->window, 0, 0, view->ncols,
8716 view_needs_focus_indication(view),
8717 "tog help (press q to return to tog)");
8718 if (err)
8719 return err;
8720 if (eos <= 1)
8721 return NULL;
8722 waddstr(view->window, "\n\n");
8723 eos -= 2;
8725 s->eof = 0;
8726 view->maxx = 0;
8727 line = NULL;
8728 while (eos > 0 && nprinted < eos) {
8729 attr_t attr = 0;
8731 linelen = getline(&line, &linesz, s->f);
8732 if (linelen == -1) {
8733 if (!feof(s->f)) {
8734 free(line);
8735 return got_ferror(s->f, GOT_ERR_IO);
8737 s->eof = 1;
8738 break;
8740 if (++s->lineno < s->first_displayed_line)
8741 continue;
8742 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8743 continue;
8744 if (s->lineno == view->hiline)
8745 attr = A_STANDOUT;
8747 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8748 view->x ? 1 : 0);
8749 if (err) {
8750 free(line);
8751 return err;
8753 view->maxx = MAX(view->maxx, width);
8754 free(wline);
8755 wline = NULL;
8757 if (attr)
8758 wattron(view->window, attr);
8759 if (s->first_displayed_line + nprinted == s->matched_line &&
8760 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8761 err = add_matched_line(&width, line, view->ncols - 1, 0,
8762 view->window, view->x, regmatch);
8763 if (err) {
8764 free(line);
8765 return err;
8767 } else {
8768 int skip;
8770 err = format_line(&wline, &width, &skip, line,
8771 view->x, view->ncols - 1, 0, view->x ? 1 : 0);
8772 if (err) {
8773 free(line);
8774 return err;
8776 rc = waddwstr(view->window, &wline[skip]);
8777 free(wline);
8778 wline = NULL;
8779 if (rc == ERR)
8780 return got_error_msg(GOT_ERR_IO, "waddwstr");
8782 if (s->lineno == view->hiline) {
8783 while (width++ < view->ncols)
8784 waddch(view->window, ' ');
8785 } else {
8786 if (width <= view->ncols)
8787 waddch(view->window, '\n');
8789 if (attr)
8790 wattroff(view->window, attr);
8791 if (++nprinted == 1)
8792 s->first_displayed_line = s->lineno;
8794 free(line);
8795 if (nprinted > 0)
8796 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8797 else
8798 s->last_displayed_line = s->first_displayed_line;
8800 view_border(view);
8802 if (s->eof) {
8803 rc = waddnstr(view->window,
8804 "See the tog(1) manual page for full documentation",
8805 view->ncols - 1);
8806 if (rc == ERR)
8807 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8808 } else {
8809 wmove(view->window, view->nlines - 1, 0);
8810 wclrtoeol(view->window);
8811 wstandout(view->window);
8812 rc = waddnstr(view->window, "scroll down for more...",
8813 view->ncols - 1);
8814 if (rc == ERR)
8815 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8816 if (getcurx(view->window) < view->ncols - 6) {
8817 rc = wprintw(view->window, "[%.0f%%]",
8818 100.00 * s->last_displayed_line / s->nlines);
8819 if (rc == ERR)
8820 return got_error_msg(GOT_ERR_IO, "wprintw");
8822 wstandend(view->window);
8825 return NULL;
8828 static const struct got_error *
8829 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8831 struct tog_help_view_state *s = &view->state.help;
8832 const struct got_error *err = NULL;
8833 char *line = NULL;
8834 ssize_t linelen;
8835 size_t linesz = 0;
8836 int eos, nscroll;
8838 eos = nscroll = view->nlines;
8839 if (view_is_hsplit_top(view))
8840 --eos; /* border */
8842 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8844 switch (ch) {
8845 case '0':
8846 view->x = 0;
8847 break;
8848 case '$':
8849 view->x = MAX(view->maxx - view->ncols / 3, 0);
8850 view->count = 0;
8851 break;
8852 case KEY_RIGHT:
8853 case 'l':
8854 if (view->x + view->ncols / 3 < view->maxx)
8855 view->x += 2;
8856 else
8857 view->count = 0;
8858 break;
8859 case KEY_LEFT:
8860 case 'h':
8861 view->x -= MIN(view->x, 2);
8862 if (view->x <= 0)
8863 view->count = 0;
8864 break;
8865 case 'g':
8866 case KEY_HOME:
8867 s->first_displayed_line = 1;
8868 view->count = 0;
8869 break;
8870 case 'G':
8871 case KEY_END:
8872 view->count = 0;
8873 if (s->eof)
8874 break;
8875 s->first_displayed_line = (s->nlines - eos) + 3;
8876 s->eof = 1;
8877 break;
8878 case 'k':
8879 case KEY_UP:
8880 if (s->first_displayed_line > 1)
8881 --s->first_displayed_line;
8882 else
8883 view->count = 0;
8884 break;
8885 case CTRL('u'):
8886 case 'u':
8887 nscroll /= 2;
8888 /* FALL THROUGH */
8889 case KEY_PPAGE:
8890 case CTRL('b'):
8891 case 'b':
8892 if (s->first_displayed_line == 1) {
8893 view->count = 0;
8894 break;
8896 while (--nscroll > 0 && s->first_displayed_line > 1)
8897 s->first_displayed_line--;
8898 break;
8899 case 'j':
8900 case KEY_DOWN:
8901 case CTRL('n'):
8902 if (!s->eof)
8903 ++s->first_displayed_line;
8904 else
8905 view->count = 0;
8906 break;
8907 case CTRL('d'):
8908 case 'd':
8909 nscroll /= 2;
8910 /* FALL THROUGH */
8911 case KEY_NPAGE:
8912 case CTRL('f'):
8913 case 'f':
8914 case ' ':
8915 if (s->eof) {
8916 view->count = 0;
8917 break;
8919 while (!s->eof && --nscroll > 0) {
8920 linelen = getline(&line, &linesz, s->f);
8921 s->first_displayed_line++;
8922 if (linelen == -1) {
8923 if (feof(s->f))
8924 s->eof = 1;
8925 else
8926 err = got_ferror(s->f, GOT_ERR_IO);
8927 break;
8930 free(line);
8931 break;
8932 default:
8933 view->count = 0;
8934 break;
8937 return err;
8940 static const struct got_error *
8941 close_help_view(struct tog_view *view)
8943 struct tog_help_view_state *s = &view->state.help;
8945 free(s->line_offsets);
8946 s->line_offsets = NULL;
8947 if (fclose(s->f) == EOF)
8948 return got_error_from_errno("fclose");
8950 return NULL;
8953 static const struct got_error *
8954 reset_help_view(struct tog_view *view)
8956 struct tog_help_view_state *s = &view->state.help;
8959 if (s->f && fclose(s->f) == EOF)
8960 return got_error_from_errno("fclose");
8962 wclear(view->window);
8963 view->count = 0;
8964 view->x = 0;
8965 s->all = !s->all;
8966 s->first_displayed_line = 1;
8967 s->last_displayed_line = view->nlines;
8968 s->matched_line = 0;
8970 return create_help(s);
8973 static const struct got_error *
8974 open_help_view(struct tog_view *view, struct tog_view *parent)
8976 const struct got_error *err = NULL;
8977 struct tog_help_view_state *s = &view->state.help;
8979 s->type = (enum tog_keymap_type)parent->type;
8980 s->first_displayed_line = 1;
8981 s->last_displayed_line = view->nlines;
8982 s->selected_line = 1;
8984 view->show = show_help_view;
8985 view->input = input_help_view;
8986 view->reset = reset_help_view;
8987 view->close = close_help_view;
8988 view->search_start = search_start_help_view;
8989 view->search_setup = search_setup_help_view;
8990 view->search_next = search_next_view_match;
8992 err = create_help(s);
8993 return err;
8996 static const struct got_error *
8997 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8998 enum tog_view_type request, int y, int x)
9000 const struct got_error *err = NULL;
9002 *new_view = NULL;
9004 switch (request) {
9005 case TOG_VIEW_DIFF:
9006 if (view->type == TOG_VIEW_LOG) {
9007 struct tog_log_view_state *s = &view->state.log;
9009 err = open_diff_view_for_commit(new_view, y, x,
9010 s->selected_entry->commit, s->selected_entry->id,
9011 view, s->repo);
9012 } else
9013 return got_error_msg(GOT_ERR_NOT_IMPL,
9014 "parent/child view pair not supported");
9015 break;
9016 case TOG_VIEW_BLAME:
9017 if (view->type == TOG_VIEW_TREE) {
9018 struct tog_tree_view_state *s = &view->state.tree;
9020 err = blame_tree_entry(new_view, y, x,
9021 s->selected_entry, &s->parents, s->commit_id,
9022 s->repo);
9023 } else
9024 return got_error_msg(GOT_ERR_NOT_IMPL,
9025 "parent/child view pair not supported");
9026 break;
9027 case TOG_VIEW_LOG:
9028 if (view->type == TOG_VIEW_BLAME)
9029 err = log_annotated_line(new_view, y, x,
9030 view->state.blame.repo, view->state.blame.id_to_log);
9031 else if (view->type == TOG_VIEW_TREE)
9032 err = log_selected_tree_entry(new_view, y, x,
9033 &view->state.tree);
9034 else if (view->type == TOG_VIEW_REF)
9035 err = log_ref_entry(new_view, y, x,
9036 view->state.ref.selected_entry,
9037 view->state.ref.repo);
9038 else
9039 return got_error_msg(GOT_ERR_NOT_IMPL,
9040 "parent/child view pair not supported");
9041 break;
9042 case TOG_VIEW_TREE:
9043 if (view->type == TOG_VIEW_LOG)
9044 err = browse_commit_tree(new_view, y, x,
9045 view->state.log.selected_entry,
9046 view->state.log.in_repo_path,
9047 view->state.log.head_ref_name,
9048 view->state.log.repo);
9049 else if (view->type == TOG_VIEW_REF)
9050 err = browse_ref_tree(new_view, y, x,
9051 view->state.ref.selected_entry,
9052 view->state.ref.repo);
9053 else
9054 return got_error_msg(GOT_ERR_NOT_IMPL,
9055 "parent/child view pair not supported");
9056 break;
9057 case TOG_VIEW_REF:
9058 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9059 if (*new_view == NULL)
9060 return got_error_from_errno("view_open");
9061 if (view->type == TOG_VIEW_LOG)
9062 err = open_ref_view(*new_view, view->state.log.repo);
9063 else if (view->type == TOG_VIEW_TREE)
9064 err = open_ref_view(*new_view, view->state.tree.repo);
9065 else
9066 err = got_error_msg(GOT_ERR_NOT_IMPL,
9067 "parent/child view pair not supported");
9068 if (err)
9069 view_close(*new_view);
9070 break;
9071 case TOG_VIEW_HELP:
9072 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9073 if (*new_view == NULL)
9074 return got_error_from_errno("view_open");
9075 err = open_help_view(*new_view, view);
9076 if (err)
9077 view_close(*new_view);
9078 break;
9079 default:
9080 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9083 return err;
9087 * If view was scrolled down to move the selected line into view when opening a
9088 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9090 static void
9091 offset_selection_up(struct tog_view *view)
9093 switch (view->type) {
9094 case TOG_VIEW_BLAME: {
9095 struct tog_blame_view_state *s = &view->state.blame;
9096 if (s->first_displayed_line == 1) {
9097 s->selected_line = MAX(s->selected_line - view->offset,
9098 1);
9099 break;
9101 if (s->first_displayed_line > view->offset)
9102 s->first_displayed_line -= view->offset;
9103 else
9104 s->first_displayed_line = 1;
9105 s->selected_line += view->offset;
9106 break;
9108 case TOG_VIEW_LOG:
9109 log_scroll_up(&view->state.log, view->offset);
9110 view->state.log.selected += view->offset;
9111 break;
9112 case TOG_VIEW_REF:
9113 ref_scroll_up(&view->state.ref, view->offset);
9114 view->state.ref.selected += view->offset;
9115 break;
9116 case TOG_VIEW_TREE:
9117 tree_scroll_up(&view->state.tree, view->offset);
9118 view->state.tree.selected += view->offset;
9119 break;
9120 default:
9121 break;
9124 view->offset = 0;
9128 * If the selected line is in the section of screen covered by the bottom split,
9129 * scroll down offset lines to move it into view and index its new position.
9131 static const struct got_error *
9132 offset_selection_down(struct tog_view *view)
9134 const struct got_error *err = NULL;
9135 const struct got_error *(*scrolld)(struct tog_view *, int);
9136 int *selected = NULL;
9137 int header, offset;
9139 switch (view->type) {
9140 case TOG_VIEW_BLAME: {
9141 struct tog_blame_view_state *s = &view->state.blame;
9142 header = 3;
9143 scrolld = NULL;
9144 if (s->selected_line > view->nlines - header) {
9145 offset = abs(view->nlines - s->selected_line - header);
9146 s->first_displayed_line += offset;
9147 s->selected_line -= offset;
9148 view->offset = offset;
9150 break;
9152 case TOG_VIEW_LOG: {
9153 struct tog_log_view_state *s = &view->state.log;
9154 scrolld = &log_scroll_down;
9155 header = view_is_parent_view(view) ? 3 : 2;
9156 selected = &s->selected;
9157 break;
9159 case TOG_VIEW_REF: {
9160 struct tog_ref_view_state *s = &view->state.ref;
9161 scrolld = &ref_scroll_down;
9162 header = 3;
9163 selected = &s->selected;
9164 break;
9166 case TOG_VIEW_TREE: {
9167 struct tog_tree_view_state *s = &view->state.tree;
9168 scrolld = &tree_scroll_down;
9169 header = 5;
9170 selected = &s->selected;
9171 break;
9173 default:
9174 selected = NULL;
9175 scrolld = NULL;
9176 header = 0;
9177 break;
9180 if (selected && *selected > view->nlines - header) {
9181 offset = abs(view->nlines - *selected - header);
9182 view->offset = offset;
9183 if (scrolld && offset) {
9184 err = scrolld(view, offset);
9185 *selected -= offset;
9189 return err;
9192 static void
9193 list_commands(FILE *fp)
9195 size_t i;
9197 fprintf(fp, "commands:");
9198 for (i = 0; i < nitems(tog_commands); i++) {
9199 const struct tog_cmd *cmd = &tog_commands[i];
9200 fprintf(fp, " %s", cmd->name);
9202 fputc('\n', fp);
9205 __dead static void
9206 usage(int hflag, int status)
9208 FILE *fp = (status == 0) ? stdout : stderr;
9210 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9211 getprogname());
9212 if (hflag) {
9213 fprintf(fp, "lazy usage: %s path\n", getprogname());
9214 list_commands(fp);
9216 exit(status);
9219 static char **
9220 make_argv(int argc, ...)
9222 va_list ap;
9223 char **argv;
9224 int i;
9226 va_start(ap, argc);
9228 argv = calloc(argc, sizeof(char *));
9229 if (argv == NULL)
9230 err(1, "calloc");
9231 for (i = 0; i < argc; i++) {
9232 argv[i] = strdup(va_arg(ap, char *));
9233 if (argv[i] == NULL)
9234 err(1, "strdup");
9237 va_end(ap);
9238 return argv;
9242 * Try to convert 'tog path' into a 'tog log path' command.
9243 * The user could simply have mistyped the command rather than knowingly
9244 * provided a path. So check whether argv[0] can in fact be resolved
9245 * to a path in the HEAD commit and print a special error if not.
9246 * This hack is for mpi@ <3
9248 static const struct got_error *
9249 tog_log_with_path(int argc, char *argv[])
9251 const struct got_error *error = NULL, *close_err;
9252 const struct tog_cmd *cmd = NULL;
9253 struct got_repository *repo = NULL;
9254 struct got_worktree *worktree = NULL;
9255 struct got_object_id *commit_id = NULL, *id = NULL;
9256 struct got_commit_object *commit = NULL;
9257 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9258 char *commit_id_str = NULL, **cmd_argv = NULL;
9259 int *pack_fds = NULL;
9261 cwd = getcwd(NULL, 0);
9262 if (cwd == NULL)
9263 return got_error_from_errno("getcwd");
9265 error = got_repo_pack_fds_open(&pack_fds);
9266 if (error != NULL)
9267 goto done;
9269 error = got_worktree_open(&worktree, cwd);
9270 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9271 goto done;
9273 if (worktree)
9274 repo_path = strdup(got_worktree_get_repo_path(worktree));
9275 else
9276 repo_path = strdup(cwd);
9277 if (repo_path == NULL) {
9278 error = got_error_from_errno("strdup");
9279 goto done;
9282 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9283 if (error != NULL)
9284 goto done;
9286 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9287 repo, worktree);
9288 if (error)
9289 goto done;
9291 error = tog_load_refs(repo, 0);
9292 if (error)
9293 goto done;
9294 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9295 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9296 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9297 if (error)
9298 goto done;
9300 if (worktree) {
9301 got_worktree_close(worktree);
9302 worktree = NULL;
9305 error = got_object_open_as_commit(&commit, repo, commit_id);
9306 if (error)
9307 goto done;
9309 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9310 if (error) {
9311 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9312 goto done;
9313 fprintf(stderr, "%s: '%s' is no known command or path\n",
9314 getprogname(), argv[0]);
9315 usage(1, 1);
9316 /* not reached */
9319 error = got_object_id_str(&commit_id_str, commit_id);
9320 if (error)
9321 goto done;
9323 cmd = &tog_commands[0]; /* log */
9324 argc = 4;
9325 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9326 error = cmd->cmd_main(argc, cmd_argv);
9327 done:
9328 if (repo) {
9329 close_err = got_repo_close(repo);
9330 if (error == NULL)
9331 error = close_err;
9333 if (commit)
9334 got_object_commit_close(commit);
9335 if (worktree)
9336 got_worktree_close(worktree);
9337 if (pack_fds) {
9338 const struct got_error *pack_err =
9339 got_repo_pack_fds_close(pack_fds);
9340 if (error == NULL)
9341 error = pack_err;
9343 free(id);
9344 free(commit_id_str);
9345 free(commit_id);
9346 free(cwd);
9347 free(repo_path);
9348 free(in_repo_path);
9349 if (cmd_argv) {
9350 int i;
9351 for (i = 0; i < argc; i++)
9352 free(cmd_argv[i]);
9353 free(cmd_argv);
9355 tog_free_refs();
9356 return error;
9359 int
9360 main(int argc, char *argv[])
9362 const struct got_error *error = NULL;
9363 const struct tog_cmd *cmd = NULL;
9364 int ch, hflag = 0, Vflag = 0;
9365 char **cmd_argv = NULL;
9366 static const struct option longopts[] = {
9367 { "version", no_argument, NULL, 'V' },
9368 { NULL, 0, NULL, 0}
9370 char *diff_algo_str = NULL;
9372 if (!isatty(STDIN_FILENO))
9373 errx(1, "standard input is not a tty");
9375 setlocale(LC_CTYPE, "");
9377 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9378 switch (ch) {
9379 case 'h':
9380 hflag = 1;
9381 break;
9382 case 'V':
9383 Vflag = 1;
9384 break;
9385 default:
9386 usage(hflag, 1);
9387 /* NOTREACHED */
9391 argc -= optind;
9392 argv += optind;
9393 optind = 1;
9394 optreset = 1;
9396 if (Vflag) {
9397 got_version_print_str();
9398 return 0;
9401 #ifndef PROFILE
9402 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9403 NULL) == -1)
9404 err(1, "pledge");
9405 #endif
9407 if (argc == 0) {
9408 if (hflag)
9409 usage(hflag, 0);
9410 /* Build an argument vector which runs a default command. */
9411 cmd = &tog_commands[0];
9412 argc = 1;
9413 cmd_argv = make_argv(argc, cmd->name);
9414 } else {
9415 size_t i;
9417 /* Did the user specify a command? */
9418 for (i = 0; i < nitems(tog_commands); i++) {
9419 if (strncmp(tog_commands[i].name, argv[0],
9420 strlen(argv[0])) == 0) {
9421 cmd = &tog_commands[i];
9422 break;
9427 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9428 if (diff_algo_str) {
9429 if (strcasecmp(diff_algo_str, "patience") == 0)
9430 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9431 if (strcasecmp(diff_algo_str, "myers") == 0)
9432 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9435 if (cmd == NULL) {
9436 if (argc != 1)
9437 usage(0, 1);
9438 /* No command specified; try log with a path */
9439 error = tog_log_with_path(argc, argv);
9440 } else {
9441 if (hflag)
9442 cmd->cmd_usage();
9443 else
9444 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9447 endwin();
9448 putchar('\n');
9449 if (cmd_argv) {
9450 int i;
9451 for (i = 0; i < argc; i++)
9452 free(cmd_argv[i]);
9453 free(cmd_argv);
9456 if (error && error->code != GOT_ERR_CANCELLED &&
9457 error->code != GOT_ERR_EOF &&
9458 error->code != GOT_ERR_PRIVSEP_EXIT &&
9459 error->code != GOT_ERR_PRIVSEP_PIPE &&
9460 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9461 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9462 return 0;