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", "Go to line N (default: first line)"), \
537 KEY_("Home =", "Go to the first line"), \
538 KEY_("G", "Go to line N (default: last line)"), \
539 KEY_("End *", "Go to the last line"), \
540 KEY_("l Right", "Scroll the view right"), \
541 KEY_("h Left", "Scroll the view left"), \
542 KEY_("$", "Scroll view to the rightmost position"), \
543 KEY_("0", "Scroll view to the leftmost position"), \
544 KEY_("-", "Decrease size of the focussed split"), \
545 KEY_("+", "Increase size of the focussed split"), \
546 KEY_("Tab", "Switch focus between views"), \
547 KEY_("F", "Toggle fullscreen mode"), \
548 KEY_("/", "Open prompt to enter search term"), \
549 KEY_("n", "Find next line/token matching the current search term"), \
550 KEY_("N", "Find previous line/token matching the current search term"),\
551 KEY_("q", "Quit the focussed view; Quit help screen"), \
552 KEY_("Q", "Quit tog"), \
554 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
555 KEY_("< ,", "Move cursor up one commit"), \
556 KEY_("> .", "Move cursor down one commit"), \
557 KEY_("Enter", "Open diff view of the selected commit"), \
558 KEY_("B", "Reload the log view and toggle display of merged commits"), \
559 KEY_("R", "Open ref view of all repository references"), \
560 KEY_("T", "Display tree view of the repository from the selected" \
561 " commit"), \
562 KEY_("@", "Toggle between displaying author and committer name"), \
563 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
564 KEY_("C-g Backspace", "Cancel current search or log operation"), \
565 KEY_("C-l", "Reload the log view with new commits in the repository"), \
567 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
568 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
569 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
570 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
571 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
572 " data"), \
573 KEY_("(", "Go to the previous file in the diff"), \
574 KEY_(")", "Go to the next file in the diff"), \
575 KEY_("{", "Go to the previous hunk in the diff"), \
576 KEY_("}", "Go to the next hunk in the diff"), \
577 KEY_("[", "Decrease the number of context lines"), \
578 KEY_("]", "Increase the number of context lines"), \
579 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
581 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
582 KEY_("Enter", "Display diff view of the selected line's commit"), \
583 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
584 KEY_("L", "Open log view for the currently selected annotated line"), \
585 KEY_("C", "Reload view with the previously blamed commit"), \
586 KEY_("c", "Reload view with the version of the file found in the" \
587 " selected line's commit"), \
588 KEY_("p", "Reload view with the version of the file found in the" \
589 " selected line's parent commit"), \
591 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
592 KEY_("Enter", "Enter selected directory or open blame view of the" \
593 " selected file"), \
594 KEY_("L", "Open log view for the selected entry"), \
595 KEY_("R", "Open ref view of all repository references"), \
596 KEY_("i", "Show object IDs for all tree entries"), \
597 KEY_("Backspace", "Return to the parent directory"), \
599 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
600 KEY_("Enter", "Display log view of the selected reference"), \
601 KEY_("T", "Display tree view of the selected reference"), \
602 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
603 KEY_("m", "Toggle display of last modified date for each reference"), \
604 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
605 KEY_("C-l", "Reload view with all repository references")
607 struct tog_key_map {
608 const char *keys;
609 const char *info;
610 enum tog_keymap_type type;
611 };
613 /*
614 * We implement two types of views: parent views and child views.
616 * The 'Tab' key switches focus between a parent view and its child view.
617 * Child views are shown side-by-side to their parent view, provided
618 * there is enough screen estate.
620 * When a new view is opened from within a parent view, this new view
621 * becomes a child view of the parent view, replacing any existing child.
623 * When a new view is opened from within a child view, this new view
624 * becomes a parent view which will obscure the views below until the
625 * user quits the new parent view by typing 'q'.
627 * This list of views contains parent views only.
628 * Child views are only pointed to by their parent view.
629 */
630 TAILQ_HEAD(tog_view_list_head, tog_view);
632 struct tog_view {
633 TAILQ_ENTRY(tog_view) entry;
634 WINDOW *window;
635 PANEL *panel;
636 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
637 int resized_y, resized_x; /* begin_y/x based on user resizing */
638 int maxx, x; /* max column and current start column */
639 int lines, cols; /* copies of LINES and COLS */
640 int nscrolled, offset; /* lines scrolled and hsplit line offset */
641 int gline, hiline; /* navigate to and highlight this nG line */
642 int ch, count; /* current keymap and count prefix */
643 int resized; /* set when in a resize event */
644 int focussed; /* Only set on one parent or child view at a time. */
645 int dying;
646 struct tog_view *parent;
647 struct tog_view *child;
649 /*
650 * This flag is initially set on parent views when a new child view
651 * is created. It gets toggled when the 'Tab' key switches focus
652 * between parent and child.
653 * The flag indicates whether focus should be passed on to our child
654 * view if this parent view gets picked for focus after another parent
655 * view was closed. This prevents child views from losing focus in such
656 * situations.
657 */
658 int focus_child;
660 enum tog_view_mode mode;
661 /* type-specific state */
662 enum tog_view_type type;
663 union {
664 struct tog_diff_view_state diff;
665 struct tog_log_view_state log;
666 struct tog_blame_view_state blame;
667 struct tog_tree_view_state tree;
668 struct tog_ref_view_state ref;
669 struct tog_help_view_state help;
670 } state;
672 const struct got_error *(*show)(struct tog_view *);
673 const struct got_error *(*input)(struct tog_view **,
674 struct tog_view *, int);
675 const struct got_error *(*reset)(struct tog_view *);
676 const struct got_error *(*resize)(struct tog_view *, int);
677 const struct got_error *(*close)(struct tog_view *);
679 const struct got_error *(*search_start)(struct tog_view *);
680 const struct got_error *(*search_next)(struct tog_view *);
681 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
682 int **, int **, int **, int **);
683 int search_started;
684 int searching;
685 #define TOG_SEARCH_FORWARD 1
686 #define TOG_SEARCH_BACKWARD 2
687 int search_next_done;
688 #define TOG_SEARCH_HAVE_MORE 1
689 #define TOG_SEARCH_NO_MORE 2
690 #define TOG_SEARCH_HAVE_NONE 3
691 regex_t regex;
692 regmatch_t regmatch;
693 };
695 static const struct got_error *open_diff_view(struct tog_view *,
696 struct got_object_id *, struct got_object_id *,
697 const char *, const char *, int, int, int, struct tog_view *,
698 struct got_repository *);
699 static const struct got_error *show_diff_view(struct tog_view *);
700 static const struct got_error *input_diff_view(struct tog_view **,
701 struct tog_view *, int);
702 static const struct got_error *reset_diff_view(struct tog_view *);
703 static const struct got_error* close_diff_view(struct tog_view *);
704 static const struct got_error *search_start_diff_view(struct tog_view *);
705 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
706 size_t *, int **, int **, int **, int **);
707 static const struct got_error *search_next_view_match(struct tog_view *);
709 static const struct got_error *open_log_view(struct tog_view *,
710 struct got_object_id *, struct got_repository *,
711 const char *, const char *, int);
712 static const struct got_error * show_log_view(struct tog_view *);
713 static const struct got_error *input_log_view(struct tog_view **,
714 struct tog_view *, int);
715 static const struct got_error *resize_log_view(struct tog_view *, int);
716 static const struct got_error *close_log_view(struct tog_view *);
717 static const struct got_error *search_start_log_view(struct tog_view *);
718 static const struct got_error *search_next_log_view(struct tog_view *);
720 static const struct got_error *open_blame_view(struct tog_view *, char *,
721 struct got_object_id *, struct got_repository *);
722 static const struct got_error *show_blame_view(struct tog_view *);
723 static const struct got_error *input_blame_view(struct tog_view **,
724 struct tog_view *, int);
725 static const struct got_error *reset_blame_view(struct tog_view *);
726 static const struct got_error *close_blame_view(struct tog_view *);
727 static const struct got_error *search_start_blame_view(struct tog_view *);
728 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
729 size_t *, int **, int **, int **, int **);
731 static const struct got_error *open_tree_view(struct tog_view *,
732 struct got_object_id *, const char *, struct got_repository *);
733 static const struct got_error *show_tree_view(struct tog_view *);
734 static const struct got_error *input_tree_view(struct tog_view **,
735 struct tog_view *, int);
736 static const struct got_error *close_tree_view(struct tog_view *);
737 static const struct got_error *search_start_tree_view(struct tog_view *);
738 static const struct got_error *search_next_tree_view(struct tog_view *);
740 static const struct got_error *open_ref_view(struct tog_view *,
741 struct got_repository *);
742 static const struct got_error *show_ref_view(struct tog_view *);
743 static const struct got_error *input_ref_view(struct tog_view **,
744 struct tog_view *, int);
745 static const struct got_error *close_ref_view(struct tog_view *);
746 static const struct got_error *search_start_ref_view(struct tog_view *);
747 static const struct got_error *search_next_ref_view(struct tog_view *);
749 static const struct got_error *open_help_view(struct tog_view *,
750 struct tog_view *);
751 static const struct got_error *show_help_view(struct tog_view *);
752 static const struct got_error *input_help_view(struct tog_view **,
753 struct tog_view *, int);
754 static const struct got_error *reset_help_view(struct tog_view *);
755 static const struct got_error* close_help_view(struct tog_view *);
756 static const struct got_error *search_start_help_view(struct tog_view *);
757 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
758 size_t *, int **, int **, int **, int **);
760 static volatile sig_atomic_t tog_sigwinch_received;
761 static volatile sig_atomic_t tog_sigpipe_received;
762 static volatile sig_atomic_t tog_sigcont_received;
763 static volatile sig_atomic_t tog_sigint_received;
764 static volatile sig_atomic_t tog_sigterm_received;
766 static void
767 tog_sigwinch(int signo)
769 tog_sigwinch_received = 1;
772 static void
773 tog_sigpipe(int signo)
775 tog_sigpipe_received = 1;
778 static void
779 tog_sigcont(int signo)
781 tog_sigcont_received = 1;
784 static void
785 tog_sigint(int signo)
787 tog_sigint_received = 1;
790 static void
791 tog_sigterm(int signo)
793 tog_sigterm_received = 1;
796 static int
797 tog_fatal_signal_received(void)
799 return (tog_sigpipe_received ||
800 tog_sigint_received || tog_sigterm_received);
803 static const struct got_error *
804 view_close(struct tog_view *view)
806 const struct got_error *err = NULL, *child_err = NULL;
808 if (view->child) {
809 child_err = view_close(view->child);
810 view->child = NULL;
812 if (view->close)
813 err = view->close(view);
814 if (view->panel)
815 del_panel(view->panel);
816 if (view->window)
817 delwin(view->window);
818 free(view);
819 return err ? err : child_err;
822 static struct tog_view *
823 view_open(int nlines, int ncols, int begin_y, int begin_x,
824 enum tog_view_type type)
826 struct tog_view *view = calloc(1, sizeof(*view));
828 if (view == NULL)
829 return NULL;
831 view->type = type;
832 view->lines = LINES;
833 view->cols = COLS;
834 view->nlines = nlines ? nlines : LINES - begin_y;
835 view->ncols = ncols ? ncols : COLS - begin_x;
836 view->begin_y = begin_y;
837 view->begin_x = begin_x;
838 view->window = newwin(nlines, ncols, begin_y, begin_x);
839 if (view->window == NULL) {
840 view_close(view);
841 return NULL;
843 view->panel = new_panel(view->window);
844 if (view->panel == NULL ||
845 set_panel_userptr(view->panel, view) != OK) {
846 view_close(view);
847 return NULL;
850 keypad(view->window, TRUE);
851 return view;
854 static int
855 view_split_begin_x(int begin_x)
857 if (begin_x > 0 || COLS < 120)
858 return 0;
859 return (COLS - MAX(COLS / 2, 80));
862 /* XXX Stub till we decide what to do. */
863 static int
864 view_split_begin_y(int lines)
866 return lines * HSPLIT_SCALE;
869 static const struct got_error *view_resize(struct tog_view *);
871 static const struct got_error *
872 view_splitscreen(struct tog_view *view)
874 const struct got_error *err = NULL;
876 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
877 if (view->resized_y && view->resized_y < view->lines)
878 view->begin_y = view->resized_y;
879 else
880 view->begin_y = view_split_begin_y(view->nlines);
881 view->begin_x = 0;
882 } else if (!view->resized) {
883 if (view->resized_x && view->resized_x < view->cols - 1 &&
884 view->cols > 119)
885 view->begin_x = view->resized_x;
886 else
887 view->begin_x = view_split_begin_x(0);
888 view->begin_y = 0;
890 view->nlines = LINES - view->begin_y;
891 view->ncols = COLS - view->begin_x;
892 view->lines = LINES;
893 view->cols = COLS;
894 err = view_resize(view);
895 if (err)
896 return err;
898 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
899 view->parent->nlines = view->begin_y;
901 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
902 return got_error_from_errno("mvwin");
904 return NULL;
907 static const struct got_error *
908 view_fullscreen(struct tog_view *view)
910 const struct got_error *err = NULL;
912 view->begin_x = 0;
913 view->begin_y = view->resized ? view->begin_y : 0;
914 view->nlines = view->resized ? view->nlines : LINES;
915 view->ncols = COLS;
916 view->lines = LINES;
917 view->cols = COLS;
918 err = view_resize(view);
919 if (err)
920 return err;
922 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
923 return got_error_from_errno("mvwin");
925 return NULL;
928 static int
929 view_is_parent_view(struct tog_view *view)
931 return view->parent == NULL;
934 static int
935 view_is_splitscreen(struct tog_view *view)
937 return view->begin_x > 0 || view->begin_y > 0;
940 static int
941 view_is_fullscreen(struct tog_view *view)
943 return view->nlines == LINES && view->ncols == COLS;
946 static int
947 view_is_hsplit_top(struct tog_view *view)
949 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
950 view_is_splitscreen(view->child);
953 static void
954 view_border(struct tog_view *view)
956 PANEL *panel;
957 const struct tog_view *view_above;
959 if (view->parent)
960 return view_border(view->parent);
962 panel = panel_above(view->panel);
963 if (panel == NULL)
964 return;
966 view_above = panel_userptr(panel);
967 if (view->mode == TOG_VIEW_SPLIT_HRZN)
968 mvwhline(view->window, view_above->begin_y - 1,
969 view->begin_x, got_locale_is_utf8() ?
970 ACS_HLINE : '-', view->ncols);
971 else
972 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
973 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
976 static const struct got_error *view_init_hsplit(struct tog_view *, int);
977 static const struct got_error *request_log_commits(struct tog_view *);
978 static const struct got_error *offset_selection_down(struct tog_view *);
979 static void offset_selection_up(struct tog_view *);
980 static void view_get_split(struct tog_view *, int *, int *);
982 static const struct got_error *
983 view_resize(struct tog_view *view)
985 const struct got_error *err = NULL;
986 int dif, nlines, ncols;
988 dif = LINES - view->lines; /* line difference */
990 if (view->lines > LINES)
991 nlines = view->nlines - (view->lines - LINES);
992 else
993 nlines = view->nlines + (LINES - view->lines);
994 if (view->cols > COLS)
995 ncols = view->ncols - (view->cols - COLS);
996 else
997 ncols = view->ncols + (COLS - view->cols);
999 if (view->child) {
1000 int hs = view->child->begin_y;
1002 if (!view_is_fullscreen(view))
1003 view->child->begin_x = view_split_begin_x(view->begin_x);
1004 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1005 view->child->begin_x == 0) {
1006 ncols = COLS;
1008 view_fullscreen(view->child);
1009 if (view->child->focussed)
1010 show_panel(view->child->panel);
1011 else
1012 show_panel(view->panel);
1013 } else {
1014 ncols = view->child->begin_x;
1016 view_splitscreen(view->child);
1017 show_panel(view->child->panel);
1020 * XXX This is ugly and needs to be moved into the above
1021 * logic but "works" for now and my attempts at moving it
1022 * break either 'tab' or 'F' key maps in horizontal splits.
1024 if (hs) {
1025 err = view_splitscreen(view->child);
1026 if (err)
1027 return err;
1028 if (dif < 0) { /* top split decreased */
1029 err = offset_selection_down(view);
1030 if (err)
1031 return err;
1033 view_border(view);
1034 update_panels();
1035 doupdate();
1036 show_panel(view->child->panel);
1037 nlines = view->nlines;
1039 } else if (view->parent == NULL)
1040 ncols = COLS;
1042 if (view->resize && dif > 0) {
1043 err = view->resize(view, dif);
1044 if (err)
1045 return err;
1048 if (wresize(view->window, nlines, ncols) == ERR)
1049 return got_error_from_errno("wresize");
1050 if (replace_panel(view->panel, view->window) == ERR)
1051 return got_error_from_errno("replace_panel");
1052 wclear(view->window);
1054 view->nlines = nlines;
1055 view->ncols = ncols;
1056 view->lines = LINES;
1057 view->cols = COLS;
1059 return NULL;
1062 static const struct got_error *
1063 resize_log_view(struct tog_view *view, int increase)
1065 struct tog_log_view_state *s = &view->state.log;
1066 const struct got_error *err = NULL;
1067 int n = 0;
1069 if (s->selected_entry)
1070 n = s->selected_entry->idx + view->lines - s->selected;
1073 * Request commits to account for the increased
1074 * height so we have enough to populate the view.
1076 if (s->commits->ncommits < n) {
1077 view->nscrolled = n - s->commits->ncommits + increase + 1;
1078 err = request_log_commits(view);
1081 return err;
1084 static void
1085 view_adjust_offset(struct tog_view *view, int n)
1087 if (n == 0)
1088 return;
1090 if (view->parent && view->parent->offset) {
1091 if (view->parent->offset + n >= 0)
1092 view->parent->offset += n;
1093 else
1094 view->parent->offset = 0;
1095 } else if (view->offset) {
1096 if (view->offset - n >= 0)
1097 view->offset -= n;
1098 else
1099 view->offset = 0;
1103 static const struct got_error *
1104 view_resize_split(struct tog_view *view, int resize)
1106 const struct got_error *err = NULL;
1107 struct tog_view *v = NULL;
1109 if (view->parent)
1110 v = view->parent;
1111 else
1112 v = view;
1114 if (!v->child || !view_is_splitscreen(v->child))
1115 return NULL;
1117 v->resized = v->child->resized = resize; /* lock for resize event */
1119 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1120 if (v->child->resized_y)
1121 v->child->begin_y = v->child->resized_y;
1122 if (view->parent)
1123 v->child->begin_y -= resize;
1124 else
1125 v->child->begin_y += resize;
1126 if (v->child->begin_y < 3) {
1127 view->count = 0;
1128 v->child->begin_y = 3;
1129 } else if (v->child->begin_y > LINES - 1) {
1130 view->count = 0;
1131 v->child->begin_y = LINES - 1;
1133 v->ncols = COLS;
1134 v->child->ncols = COLS;
1135 view_adjust_offset(view, resize);
1136 err = view_init_hsplit(v, v->child->begin_y);
1137 if (err)
1138 return err;
1139 v->child->resized_y = v->child->begin_y;
1140 } else {
1141 if (v->child->resized_x)
1142 v->child->begin_x = v->child->resized_x;
1143 if (view->parent)
1144 v->child->begin_x -= resize;
1145 else
1146 v->child->begin_x += resize;
1147 if (v->child->begin_x < 11) {
1148 view->count = 0;
1149 v->child->begin_x = 11;
1150 } else if (v->child->begin_x > COLS - 1) {
1151 view->count = 0;
1152 v->child->begin_x = COLS - 1;
1154 v->child->resized_x = v->child->begin_x;
1157 v->child->mode = v->mode;
1158 v->child->nlines = v->lines - v->child->begin_y;
1159 v->child->ncols = v->cols - v->child->begin_x;
1160 v->focus_child = 1;
1162 err = view_fullscreen(v);
1163 if (err)
1164 return err;
1165 err = view_splitscreen(v->child);
1166 if (err)
1167 return err;
1169 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1170 err = offset_selection_down(v->child);
1171 if (err)
1172 return err;
1175 if (v->resize)
1176 err = v->resize(v, 0);
1177 else if (v->child->resize)
1178 err = v->child->resize(v->child, 0);
1180 v->resized = v->child->resized = 0;
1182 return err;
1185 static void
1186 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1188 struct tog_view *v = src->child ? src->child : src;
1190 dst->resized_x = v->resized_x;
1191 dst->resized_y = v->resized_y;
1194 static const struct got_error *
1195 view_close_child(struct tog_view *view)
1197 const struct got_error *err = NULL;
1199 if (view->child == NULL)
1200 return NULL;
1202 err = view_close(view->child);
1203 view->child = NULL;
1204 return err;
1207 static const struct got_error *
1208 view_set_child(struct tog_view *view, struct tog_view *child)
1210 const struct got_error *err = NULL;
1212 view->child = child;
1213 child->parent = view;
1215 err = view_resize(view);
1216 if (err)
1217 return err;
1219 if (view->child->resized_x || view->child->resized_y)
1220 err = view_resize_split(view, 0);
1222 return err;
1225 static const struct got_error *view_dispatch_request(struct tog_view **,
1226 struct tog_view *, enum tog_view_type, int, int);
1228 static const struct got_error *
1229 view_request_new(struct tog_view **requested, struct tog_view *view,
1230 enum tog_view_type request)
1232 struct tog_view *new_view = NULL;
1233 const struct got_error *err;
1234 int y = 0, x = 0;
1236 *requested = NULL;
1238 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1239 view_get_split(view, &y, &x);
1241 err = view_dispatch_request(&new_view, view, request, y, x);
1242 if (err)
1243 return err;
1245 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1246 request != TOG_VIEW_HELP) {
1247 err = view_init_hsplit(view, y);
1248 if (err)
1249 return err;
1252 view->focussed = 0;
1253 new_view->focussed = 1;
1254 new_view->mode = view->mode;
1255 new_view->nlines = request == TOG_VIEW_HELP ?
1256 view->lines : view->lines - y;
1258 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1259 view_transfer_size(new_view, view);
1260 err = view_close_child(view);
1261 if (err)
1262 return err;
1263 err = view_set_child(view, new_view);
1264 if (err)
1265 return err;
1266 view->focus_child = 1;
1267 } else
1268 *requested = new_view;
1270 return NULL;
1273 static void
1274 tog_resizeterm(void)
1276 int cols, lines;
1277 struct winsize size;
1279 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1280 cols = 80; /* Default */
1281 lines = 24;
1282 } else {
1283 cols = size.ws_col;
1284 lines = size.ws_row;
1286 resize_term(lines, cols);
1289 static const struct got_error *
1290 view_search_start(struct tog_view *view)
1292 const struct got_error *err = NULL;
1293 struct tog_view *v = view;
1294 char pattern[1024];
1295 int ret;
1297 if (view->search_started) {
1298 regfree(&view->regex);
1299 view->searching = 0;
1300 memset(&view->regmatch, 0, sizeof(view->regmatch));
1302 view->search_started = 0;
1304 if (view->nlines < 1)
1305 return NULL;
1307 if (view_is_hsplit_top(view))
1308 v = view->child;
1309 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1310 v = view->parent;
1312 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1313 wclrtoeol(v->window);
1315 nodelay(v->window, FALSE); /* block for search term input */
1316 nocbreak();
1317 echo();
1318 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1319 wrefresh(v->window);
1320 cbreak();
1321 noecho();
1322 nodelay(v->window, TRUE);
1323 if (ret == ERR)
1324 return NULL;
1326 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1327 err = view->search_start(view);
1328 if (err) {
1329 regfree(&view->regex);
1330 return err;
1332 view->search_started = 1;
1333 view->searching = TOG_SEARCH_FORWARD;
1334 view->search_next_done = 0;
1335 view->search_next(view);
1338 return NULL;
1341 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1342 static const struct got_error *
1343 switch_split(struct tog_view *view)
1345 const struct got_error *err = NULL;
1346 struct tog_view *v = NULL;
1348 if (view->parent)
1349 v = view->parent;
1350 else
1351 v = view;
1353 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1354 v->mode = TOG_VIEW_SPLIT_VERT;
1355 else
1356 v->mode = TOG_VIEW_SPLIT_HRZN;
1358 if (!v->child)
1359 return NULL;
1360 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1361 v->mode = TOG_VIEW_SPLIT_NONE;
1363 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1364 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1365 v->child->begin_y = v->child->resized_y;
1366 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1367 v->child->begin_x = v->child->resized_x;
1370 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1371 v->ncols = COLS;
1372 v->child->ncols = COLS;
1373 v->child->nscrolled = LINES - v->child->nlines;
1375 err = view_init_hsplit(v, v->child->begin_y);
1376 if (err)
1377 return err;
1379 v->child->mode = v->mode;
1380 v->child->nlines = v->lines - v->child->begin_y;
1381 v->focus_child = 1;
1383 err = view_fullscreen(v);
1384 if (err)
1385 return err;
1386 err = view_splitscreen(v->child);
1387 if (err)
1388 return err;
1390 if (v->mode == TOG_VIEW_SPLIT_NONE)
1391 v->mode = TOG_VIEW_SPLIT_VERT;
1392 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1393 err = offset_selection_down(v);
1394 if (err)
1395 return err;
1396 err = offset_selection_down(v->child);
1397 if (err)
1398 return err;
1399 } else {
1400 offset_selection_up(v);
1401 offset_selection_up(v->child);
1403 if (v->resize)
1404 err = v->resize(v, 0);
1405 else if (v->child->resize)
1406 err = v->child->resize(v->child, 0);
1408 return err;
1412 * Compute view->count from numeric input. Assign total to view->count and
1413 * return first non-numeric key entered.
1415 static int
1416 get_compound_key(struct tog_view *view, int c)
1418 struct tog_view *v = view;
1419 int x, n = 0;
1421 if (view_is_hsplit_top(view))
1422 v = view->child;
1423 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1424 v = view->parent;
1426 view->count = 0;
1427 cbreak(); /* block for input */
1428 nodelay(view->window, FALSE);
1429 wmove(v->window, v->nlines - 1, 0);
1430 wclrtoeol(v->window);
1431 waddch(v->window, ':');
1433 do {
1434 x = getcurx(v->window);
1435 if (x != ERR && x < view->ncols) {
1436 waddch(v->window, c);
1437 wrefresh(v->window);
1441 * Don't overflow. Max valid request should be the greatest
1442 * between the longest and total lines; cap at 10 million.
1444 if (n >= 9999999)
1445 n = 9999999;
1446 else
1447 n = n * 10 + (c - '0');
1448 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1450 if (c == 'G' || c == 'g') { /* nG key map */
1451 view->gline = view->hiline = n;
1452 n = 0;
1453 c = 0;
1456 /* Massage excessive or inapplicable values at the input handler. */
1457 view->count = n;
1459 return c;
1462 static const struct got_error *
1463 view_input(struct tog_view **new, int *done, struct tog_view *view,
1464 struct tog_view_list_head *views)
1466 const struct got_error *err = NULL;
1467 struct tog_view *v;
1468 int ch, errcode;
1470 *new = NULL;
1472 /* Clear "no matches" indicator. */
1473 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1474 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1475 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1476 view->count = 0;
1479 if (view->searching && !view->search_next_done) {
1480 errcode = pthread_mutex_unlock(&tog_mutex);
1481 if (errcode)
1482 return got_error_set_errno(errcode,
1483 "pthread_mutex_unlock");
1484 sched_yield();
1485 errcode = pthread_mutex_lock(&tog_mutex);
1486 if (errcode)
1487 return got_error_set_errno(errcode,
1488 "pthread_mutex_lock");
1489 view->search_next(view);
1490 return NULL;
1493 /* Allow threads to make progress while we are waiting for input. */
1494 errcode = pthread_mutex_unlock(&tog_mutex);
1495 if (errcode)
1496 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1497 /* If we have an unfinished count, let C-g or backspace abort. */
1498 if (view->count && --view->count) {
1499 cbreak();
1500 nodelay(view->window, TRUE);
1501 ch = wgetch(view->window);
1502 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1503 view->count = 0;
1504 else
1505 ch = view->ch;
1506 } else {
1507 ch = wgetch(view->window);
1508 if (ch >= '1' && ch <= '9')
1509 view->ch = ch = get_compound_key(view, ch);
1511 if (view->hiline && ch != ERR && ch != 0)
1512 view->hiline = 0; /* key pressed, clear line highlight */
1513 nodelay(view->window, TRUE);
1514 errcode = pthread_mutex_lock(&tog_mutex);
1515 if (errcode)
1516 return got_error_set_errno(errcode, "pthread_mutex_lock");
1518 if (tog_sigwinch_received || tog_sigcont_received) {
1519 tog_resizeterm();
1520 tog_sigwinch_received = 0;
1521 tog_sigcont_received = 0;
1522 TAILQ_FOREACH(v, views, entry) {
1523 err = view_resize(v);
1524 if (err)
1525 return err;
1526 err = v->input(new, v, KEY_RESIZE);
1527 if (err)
1528 return err;
1529 if (v->child) {
1530 err = view_resize(v->child);
1531 if (err)
1532 return err;
1533 err = v->child->input(new, v->child,
1534 KEY_RESIZE);
1535 if (err)
1536 return err;
1537 if (v->child->resized_x || v->child->resized_y) {
1538 err = view_resize_split(v, 0);
1539 if (err)
1540 return err;
1546 switch (ch) {
1547 case '?':
1548 case 'H':
1549 case KEY_F(1):
1550 if (view->type == TOG_VIEW_HELP)
1551 err = view->reset(view);
1552 else
1553 err = view_request_new(new, view, TOG_VIEW_HELP);
1554 break;
1555 case '\t':
1556 view->count = 0;
1557 if (view->child) {
1558 view->focussed = 0;
1559 view->child->focussed = 1;
1560 view->focus_child = 1;
1561 } else if (view->parent) {
1562 view->focussed = 0;
1563 view->parent->focussed = 1;
1564 view->parent->focus_child = 0;
1565 if (!view_is_splitscreen(view)) {
1566 if (view->parent->resize) {
1567 err = view->parent->resize(view->parent,
1568 0);
1569 if (err)
1570 return err;
1572 offset_selection_up(view->parent);
1573 err = view_fullscreen(view->parent);
1574 if (err)
1575 return err;
1578 break;
1579 case 'q':
1580 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1581 if (view->parent->resize) {
1582 /* might need more commits to fill fullscreen */
1583 err = view->parent->resize(view->parent, 0);
1584 if (err)
1585 break;
1587 offset_selection_up(view->parent);
1589 err = view->input(new, view, ch);
1590 view->dying = 1;
1591 break;
1592 case 'Q':
1593 *done = 1;
1594 break;
1595 case 'F':
1596 view->count = 0;
1597 if (view_is_parent_view(view)) {
1598 if (view->child == NULL)
1599 break;
1600 if (view_is_splitscreen(view->child)) {
1601 view->focussed = 0;
1602 view->child->focussed = 1;
1603 err = view_fullscreen(view->child);
1604 } else {
1605 err = view_splitscreen(view->child);
1606 if (!err)
1607 err = view_resize_split(view, 0);
1609 if (err)
1610 break;
1611 err = view->child->input(new, view->child,
1612 KEY_RESIZE);
1613 } else {
1614 if (view_is_splitscreen(view)) {
1615 view->parent->focussed = 0;
1616 view->focussed = 1;
1617 err = view_fullscreen(view);
1618 } else {
1619 err = view_splitscreen(view);
1620 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1621 err = view_resize(view->parent);
1622 if (!err)
1623 err = view_resize_split(view, 0);
1625 if (err)
1626 break;
1627 err = view->input(new, view, KEY_RESIZE);
1629 if (err)
1630 break;
1631 if (view->resize) {
1632 err = view->resize(view, 0);
1633 if (err)
1634 break;
1636 if (view->parent)
1637 err = offset_selection_down(view->parent);
1638 if (!err)
1639 err = offset_selection_down(view);
1640 break;
1641 case 'S':
1642 view->count = 0;
1643 err = switch_split(view);
1644 break;
1645 case '-':
1646 err = view_resize_split(view, -1);
1647 break;
1648 case '+':
1649 err = view_resize_split(view, 1);
1650 break;
1651 case KEY_RESIZE:
1652 break;
1653 case '/':
1654 view->count = 0;
1655 if (view->search_start)
1656 view_search_start(view);
1657 else
1658 err = view->input(new, view, ch);
1659 break;
1660 case 'N':
1661 case 'n':
1662 if (view->search_started && view->search_next) {
1663 view->searching = (ch == 'n' ?
1664 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1665 view->search_next_done = 0;
1666 view->search_next(view);
1667 } else
1668 err = view->input(new, view, ch);
1669 break;
1670 case 'A':
1671 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1672 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1673 else
1674 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1675 TAILQ_FOREACH(v, views, entry) {
1676 if (v->reset) {
1677 err = v->reset(v);
1678 if (err)
1679 return err;
1681 if (v->child && v->child->reset) {
1682 err = v->child->reset(v->child);
1683 if (err)
1684 return err;
1687 break;
1688 default:
1689 err = view->input(new, view, ch);
1690 break;
1693 return err;
1696 static int
1697 view_needs_focus_indication(struct tog_view *view)
1699 if (view_is_parent_view(view)) {
1700 if (view->child == NULL || view->child->focussed)
1701 return 0;
1702 if (!view_is_splitscreen(view->child))
1703 return 0;
1704 } else if (!view_is_splitscreen(view))
1705 return 0;
1707 return view->focussed;
1710 static const struct got_error *
1711 view_loop(struct tog_view *view)
1713 const struct got_error *err = NULL;
1714 struct tog_view_list_head views;
1715 struct tog_view *new_view;
1716 char *mode;
1717 int fast_refresh = 10;
1718 int done = 0, errcode;
1720 mode = getenv("TOG_VIEW_SPLIT_MODE");
1721 if (!mode || !(*mode == 'h' || *mode == 'H'))
1722 view->mode = TOG_VIEW_SPLIT_VERT;
1723 else
1724 view->mode = TOG_VIEW_SPLIT_HRZN;
1726 errcode = pthread_mutex_lock(&tog_mutex);
1727 if (errcode)
1728 return got_error_set_errno(errcode, "pthread_mutex_lock");
1730 TAILQ_INIT(&views);
1731 TAILQ_INSERT_HEAD(&views, view, entry);
1733 view->focussed = 1;
1734 err = view->show(view);
1735 if (err)
1736 return err;
1737 update_panels();
1738 doupdate();
1739 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1740 !tog_fatal_signal_received()) {
1741 /* Refresh fast during initialization, then become slower. */
1742 if (fast_refresh && fast_refresh-- == 0)
1743 halfdelay(10); /* switch to once per second */
1745 err = view_input(&new_view, &done, view, &views);
1746 if (err)
1747 break;
1748 if (view->dying) {
1749 struct tog_view *v, *prev = NULL;
1751 if (view_is_parent_view(view))
1752 prev = TAILQ_PREV(view, tog_view_list_head,
1753 entry);
1754 else if (view->parent)
1755 prev = view->parent;
1757 if (view->parent) {
1758 view->parent->child = NULL;
1759 view->parent->focus_child = 0;
1760 /* Restore fullscreen line height. */
1761 view->parent->nlines = view->parent->lines;
1762 err = view_resize(view->parent);
1763 if (err)
1764 break;
1765 /* Make resized splits persist. */
1766 view_transfer_size(view->parent, view);
1767 } else
1768 TAILQ_REMOVE(&views, view, entry);
1770 err = view_close(view);
1771 if (err)
1772 goto done;
1774 view = NULL;
1775 TAILQ_FOREACH(v, &views, entry) {
1776 if (v->focussed)
1777 break;
1779 if (view == NULL && new_view == NULL) {
1780 /* No view has focus. Try to pick one. */
1781 if (prev)
1782 view = prev;
1783 else if (!TAILQ_EMPTY(&views)) {
1784 view = TAILQ_LAST(&views,
1785 tog_view_list_head);
1787 if (view) {
1788 if (view->focus_child) {
1789 view->child->focussed = 1;
1790 view = view->child;
1791 } else
1792 view->focussed = 1;
1796 if (new_view) {
1797 struct tog_view *v, *t;
1798 /* Only allow one parent view per type. */
1799 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1800 if (v->type != new_view->type)
1801 continue;
1802 TAILQ_REMOVE(&views, v, entry);
1803 err = view_close(v);
1804 if (err)
1805 goto done;
1806 break;
1808 TAILQ_INSERT_TAIL(&views, new_view, entry);
1809 view = new_view;
1811 if (view) {
1812 if (view_is_parent_view(view)) {
1813 if (view->child && view->child->focussed)
1814 view = view->child;
1815 } else {
1816 if (view->parent && view->parent->focussed)
1817 view = view->parent;
1819 show_panel(view->panel);
1820 if (view->child && view_is_splitscreen(view->child))
1821 show_panel(view->child->panel);
1822 if (view->parent && view_is_splitscreen(view)) {
1823 err = view->parent->show(view->parent);
1824 if (err)
1825 goto done;
1827 err = view->show(view);
1828 if (err)
1829 goto done;
1830 if (view->child) {
1831 err = view->child->show(view->child);
1832 if (err)
1833 goto done;
1835 update_panels();
1836 doupdate();
1839 done:
1840 while (!TAILQ_EMPTY(&views)) {
1841 const struct got_error *close_err;
1842 view = TAILQ_FIRST(&views);
1843 TAILQ_REMOVE(&views, view, entry);
1844 close_err = view_close(view);
1845 if (close_err && err == NULL)
1846 err = close_err;
1849 errcode = pthread_mutex_unlock(&tog_mutex);
1850 if (errcode && err == NULL)
1851 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1853 return err;
1856 __dead static void
1857 usage_log(void)
1859 endwin();
1860 fprintf(stderr,
1861 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1862 getprogname());
1863 exit(1);
1866 /* Create newly allocated wide-character string equivalent to a byte string. */
1867 static const struct got_error *
1868 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1870 char *vis = NULL;
1871 const struct got_error *err = NULL;
1873 *ws = NULL;
1874 *wlen = mbstowcs(NULL, s, 0);
1875 if (*wlen == (size_t)-1) {
1876 int vislen;
1877 if (errno != EILSEQ)
1878 return got_error_from_errno("mbstowcs");
1880 /* byte string invalid in current encoding; try to "fix" it */
1881 err = got_mbsavis(&vis, &vislen, s);
1882 if (err)
1883 return err;
1884 *wlen = mbstowcs(NULL, vis, 0);
1885 if (*wlen == (size_t)-1) {
1886 err = got_error_from_errno("mbstowcs"); /* give up */
1887 goto done;
1891 *ws = calloc(*wlen + 1, sizeof(**ws));
1892 if (*ws == NULL) {
1893 err = got_error_from_errno("calloc");
1894 goto done;
1897 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1898 err = got_error_from_errno("mbstowcs");
1899 done:
1900 free(vis);
1901 if (err) {
1902 free(*ws);
1903 *ws = NULL;
1904 *wlen = 0;
1906 return err;
1909 static const struct got_error *
1910 expand_tab(char **ptr, const char *src)
1912 char *dst;
1913 size_t len, n, idx = 0, sz = 0;
1915 *ptr = NULL;
1916 n = len = strlen(src);
1917 dst = malloc(n + 1);
1918 if (dst == NULL)
1919 return got_error_from_errno("malloc");
1921 while (idx < len && src[idx]) {
1922 const char c = src[idx];
1924 if (c == '\t') {
1925 size_t nb = TABSIZE - sz % TABSIZE;
1926 char *p;
1928 p = realloc(dst, n + nb);
1929 if (p == NULL) {
1930 free(dst);
1931 return got_error_from_errno("realloc");
1934 dst = p;
1935 n += nb;
1936 memset(dst + sz, ' ', nb);
1937 sz += nb;
1938 } else
1939 dst[sz++] = src[idx];
1940 ++idx;
1943 dst[sz] = '\0';
1944 *ptr = dst;
1945 return NULL;
1949 * Advance at most n columns from wline starting at offset off.
1950 * Return the index to the first character after the span operation.
1951 * Return the combined column width of all spanned wide character in
1952 * *rcol.
1954 static int
1955 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1957 int width, i, cols = 0;
1959 if (n == 0) {
1960 *rcol = cols;
1961 return off;
1964 for (i = off; wline[i] != L'\0'; ++i) {
1965 if (wline[i] == L'\t')
1966 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1967 else
1968 width = wcwidth(wline[i]);
1970 if (width == -1) {
1971 width = 1;
1972 wline[i] = L'.';
1975 if (cols + width > n)
1976 break;
1977 cols += width;
1980 *rcol = cols;
1981 return i;
1985 * Format a line for display, ensuring that it won't overflow a width limit.
1986 * With scrolling, the width returned refers to the scrolled version of the
1987 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1989 static const struct got_error *
1990 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1991 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1993 const struct got_error *err = NULL;
1994 int cols;
1995 wchar_t *wline = NULL;
1996 char *exstr = NULL;
1997 size_t wlen;
1998 int i, scrollx;
2000 *wlinep = NULL;
2001 *widthp = 0;
2003 if (expand) {
2004 err = expand_tab(&exstr, line);
2005 if (err)
2006 return err;
2009 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2010 free(exstr);
2011 if (err)
2012 return err;
2014 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2016 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2017 wline[wlen - 1] = L'\0';
2018 wlen--;
2020 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2021 wline[wlen - 1] = L'\0';
2022 wlen--;
2025 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2026 wline[i] = L'\0';
2028 if (widthp)
2029 *widthp = cols;
2030 if (scrollxp)
2031 *scrollxp = scrollx;
2032 if (err)
2033 free(wline);
2034 else
2035 *wlinep = wline;
2036 return err;
2039 static const struct got_error*
2040 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2041 struct got_object_id *id, struct got_repository *repo)
2043 static const struct got_error *err = NULL;
2044 struct got_reflist_entry *re;
2045 char *s;
2046 const char *name;
2048 *refs_str = NULL;
2050 TAILQ_FOREACH(re, refs, entry) {
2051 struct got_tag_object *tag = NULL;
2052 struct got_object_id *ref_id;
2053 int cmp;
2055 name = got_ref_get_name(re->ref);
2056 if (strcmp(name, GOT_REF_HEAD) == 0)
2057 continue;
2058 if (strncmp(name, "refs/", 5) == 0)
2059 name += 5;
2060 if (strncmp(name, "got/", 4) == 0 &&
2061 strncmp(name, "got/backup/", 11) != 0)
2062 continue;
2063 if (strncmp(name, "heads/", 6) == 0)
2064 name += 6;
2065 if (strncmp(name, "remotes/", 8) == 0) {
2066 name += 8;
2067 s = strstr(name, "/" GOT_REF_HEAD);
2068 if (s != NULL && s[strlen(s)] == '\0')
2069 continue;
2071 err = got_ref_resolve(&ref_id, repo, re->ref);
2072 if (err)
2073 break;
2074 if (strncmp(name, "tags/", 5) == 0) {
2075 err = got_object_open_as_tag(&tag, repo, ref_id);
2076 if (err) {
2077 if (err->code != GOT_ERR_OBJ_TYPE) {
2078 free(ref_id);
2079 break;
2081 /* Ref points at something other than a tag. */
2082 err = NULL;
2083 tag = NULL;
2086 cmp = got_object_id_cmp(tag ?
2087 got_object_tag_get_object_id(tag) : ref_id, id);
2088 free(ref_id);
2089 if (tag)
2090 got_object_tag_close(tag);
2091 if (cmp != 0)
2092 continue;
2093 s = *refs_str;
2094 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2095 s ? ", " : "", name) == -1) {
2096 err = got_error_from_errno("asprintf");
2097 free(s);
2098 *refs_str = NULL;
2099 break;
2101 free(s);
2104 return err;
2107 static const struct got_error *
2108 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2109 int col_tab_align)
2111 char *smallerthan;
2113 smallerthan = strchr(author, '<');
2114 if (smallerthan && smallerthan[1] != '\0')
2115 author = smallerthan + 1;
2116 author[strcspn(author, "@>")] = '\0';
2117 return format_line(wauthor, author_width, NULL, author, 0, limit,
2118 col_tab_align, 0);
2121 static const struct got_error *
2122 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2123 struct got_object_id *id, const size_t date_display_cols,
2124 int author_display_cols)
2126 struct tog_log_view_state *s = &view->state.log;
2127 const struct got_error *err = NULL;
2128 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2129 char *logmsg0 = NULL, *logmsg = NULL;
2130 char *author = NULL;
2131 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2132 int author_width, logmsg_width;
2133 char *newline, *line = NULL;
2134 int col, limit, scrollx;
2135 const int avail = view->ncols;
2136 struct tm tm;
2137 time_t committer_time;
2138 struct tog_color *tc;
2140 committer_time = got_object_commit_get_committer_time(commit);
2141 if (gmtime_r(&committer_time, &tm) == NULL)
2142 return got_error_from_errno("gmtime_r");
2143 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2144 return got_error(GOT_ERR_NO_SPACE);
2146 if (avail <= date_display_cols)
2147 limit = MIN(sizeof(datebuf) - 1, avail);
2148 else
2149 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2150 tc = get_color(&s->colors, TOG_COLOR_DATE);
2151 if (tc)
2152 wattr_on(view->window,
2153 COLOR_PAIR(tc->colorpair), NULL);
2154 waddnstr(view->window, datebuf, limit);
2155 if (tc)
2156 wattr_off(view->window,
2157 COLOR_PAIR(tc->colorpair), NULL);
2158 col = limit;
2159 if (col > avail)
2160 goto done;
2162 if (avail >= 120) {
2163 char *id_str;
2164 err = got_object_id_str(&id_str, id);
2165 if (err)
2166 goto done;
2167 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2168 if (tc)
2169 wattr_on(view->window,
2170 COLOR_PAIR(tc->colorpair), NULL);
2171 wprintw(view->window, "%.8s ", id_str);
2172 if (tc)
2173 wattr_off(view->window,
2174 COLOR_PAIR(tc->colorpair), NULL);
2175 free(id_str);
2176 col += 9;
2177 if (col > avail)
2178 goto done;
2181 if (s->use_committer)
2182 author = strdup(got_object_commit_get_committer(commit));
2183 else
2184 author = strdup(got_object_commit_get_author(commit));
2185 if (author == NULL) {
2186 err = got_error_from_errno("strdup");
2187 goto done;
2189 err = format_author(&wauthor, &author_width, author, avail - col, col);
2190 if (err)
2191 goto done;
2192 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2193 if (tc)
2194 wattr_on(view->window,
2195 COLOR_PAIR(tc->colorpair), NULL);
2196 waddwstr(view->window, wauthor);
2197 col += author_width;
2198 while (col < avail && author_width < author_display_cols + 2) {
2199 waddch(view->window, ' ');
2200 col++;
2201 author_width++;
2203 if (tc)
2204 wattr_off(view->window,
2205 COLOR_PAIR(tc->colorpair), NULL);
2206 if (col > avail)
2207 goto done;
2209 err = got_object_commit_get_logmsg(&logmsg0, commit);
2210 if (err)
2211 goto done;
2212 logmsg = logmsg0;
2213 while (*logmsg == '\n')
2214 logmsg++;
2215 newline = strchr(logmsg, '\n');
2216 if (newline)
2217 *newline = '\0';
2218 limit = avail - col;
2219 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2220 limit--; /* for the border */
2221 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2222 limit, col, 1);
2223 if (err)
2224 goto done;
2225 waddwstr(view->window, &wlogmsg[scrollx]);
2226 col += MAX(logmsg_width, 0);
2227 while (col < avail) {
2228 waddch(view->window, ' ');
2229 col++;
2231 done:
2232 free(logmsg0);
2233 free(wlogmsg);
2234 free(author);
2235 free(wauthor);
2236 free(line);
2237 return err;
2240 static struct commit_queue_entry *
2241 alloc_commit_queue_entry(struct got_commit_object *commit,
2242 struct got_object_id *id)
2244 struct commit_queue_entry *entry;
2245 struct got_object_id *dup;
2247 entry = calloc(1, sizeof(*entry));
2248 if (entry == NULL)
2249 return NULL;
2251 dup = got_object_id_dup(id);
2252 if (dup == NULL) {
2253 free(entry);
2254 return NULL;
2257 entry->id = dup;
2258 entry->commit = commit;
2259 return entry;
2262 static void
2263 pop_commit(struct commit_queue *commits)
2265 struct commit_queue_entry *entry;
2267 entry = TAILQ_FIRST(&commits->head);
2268 TAILQ_REMOVE(&commits->head, entry, entry);
2269 got_object_commit_close(entry->commit);
2270 commits->ncommits--;
2271 free(entry->id);
2272 free(entry);
2275 static void
2276 free_commits(struct commit_queue *commits)
2278 while (!TAILQ_EMPTY(&commits->head))
2279 pop_commit(commits);
2282 static const struct got_error *
2283 match_commit(int *have_match, struct got_object_id *id,
2284 struct got_commit_object *commit, regex_t *regex)
2286 const struct got_error *err = NULL;
2287 regmatch_t regmatch;
2288 char *id_str = NULL, *logmsg = NULL;
2290 *have_match = 0;
2292 err = got_object_id_str(&id_str, id);
2293 if (err)
2294 return err;
2296 err = got_object_commit_get_logmsg(&logmsg, commit);
2297 if (err)
2298 goto done;
2300 if (regexec(regex, got_object_commit_get_author(commit), 1,
2301 &regmatch, 0) == 0 ||
2302 regexec(regex, got_object_commit_get_committer(commit), 1,
2303 &regmatch, 0) == 0 ||
2304 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2305 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2306 *have_match = 1;
2307 done:
2308 free(id_str);
2309 free(logmsg);
2310 return err;
2313 static const struct got_error *
2314 queue_commits(struct tog_log_thread_args *a)
2316 const struct got_error *err = NULL;
2319 * We keep all commits open throughout the lifetime of the log
2320 * view in order to avoid having to re-fetch commits from disk
2321 * while updating the display.
2323 do {
2324 struct got_object_id id;
2325 struct got_commit_object *commit;
2326 struct commit_queue_entry *entry;
2327 int limit_match = 0;
2328 int errcode;
2330 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2331 NULL, NULL);
2332 if (err)
2333 break;
2335 err = got_object_open_as_commit(&commit, a->repo, &id);
2336 if (err)
2337 break;
2338 entry = alloc_commit_queue_entry(commit, &id);
2339 if (entry == NULL) {
2340 err = got_error_from_errno("alloc_commit_queue_entry");
2341 break;
2344 errcode = pthread_mutex_lock(&tog_mutex);
2345 if (errcode) {
2346 err = got_error_set_errno(errcode,
2347 "pthread_mutex_lock");
2348 break;
2351 entry->idx = a->real_commits->ncommits;
2352 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2353 a->real_commits->ncommits++;
2355 if (*a->limiting) {
2356 err = match_commit(&limit_match, &id, commit,
2357 a->limit_regex);
2358 if (err)
2359 break;
2361 if (limit_match) {
2362 struct commit_queue_entry *matched;
2364 matched = alloc_commit_queue_entry(
2365 entry->commit, entry->id);
2366 if (matched == NULL) {
2367 err = got_error_from_errno(
2368 "alloc_commit_queue_entry");
2369 break;
2371 matched->commit = entry->commit;
2372 got_object_commit_retain(entry->commit);
2374 matched->idx = a->limit_commits->ncommits;
2375 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2376 matched, entry);
2377 a->limit_commits->ncommits++;
2381 * This is how we signal log_thread() that we
2382 * have found a match, and that it should be
2383 * counted as a new entry for the view.
2385 a->limit_match = limit_match;
2388 if (*a->searching == TOG_SEARCH_FORWARD &&
2389 !*a->search_next_done) {
2390 int have_match;
2391 err = match_commit(&have_match, &id, commit, a->regex);
2392 if (err)
2393 break;
2395 if (*a->limiting) {
2396 if (limit_match && have_match)
2397 *a->search_next_done =
2398 TOG_SEARCH_HAVE_MORE;
2399 } else if (have_match)
2400 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2403 errcode = pthread_mutex_unlock(&tog_mutex);
2404 if (errcode && err == NULL)
2405 err = got_error_set_errno(errcode,
2406 "pthread_mutex_unlock");
2407 if (err)
2408 break;
2409 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2411 return err;
2414 static void
2415 select_commit(struct tog_log_view_state *s)
2417 struct commit_queue_entry *entry;
2418 int ncommits = 0;
2420 entry = s->first_displayed_entry;
2421 while (entry) {
2422 if (ncommits == s->selected) {
2423 s->selected_entry = entry;
2424 break;
2426 entry = TAILQ_NEXT(entry, entry);
2427 ncommits++;
2431 static const struct got_error *
2432 draw_commits(struct tog_view *view)
2434 const struct got_error *err = NULL;
2435 struct tog_log_view_state *s = &view->state.log;
2436 struct commit_queue_entry *entry = s->selected_entry;
2437 int limit = view->nlines;
2438 int width;
2439 int ncommits, author_cols = 4;
2440 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2441 char *refs_str = NULL;
2442 wchar_t *wline;
2443 struct tog_color *tc;
2444 static const size_t date_display_cols = 12;
2446 if (view_is_hsplit_top(view))
2447 --limit; /* account for border */
2449 if (s->selected_entry &&
2450 !(view->searching && view->search_next_done == 0)) {
2451 struct got_reflist_head *refs;
2452 err = got_object_id_str(&id_str, s->selected_entry->id);
2453 if (err)
2454 return err;
2455 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2456 s->selected_entry->id);
2457 if (refs) {
2458 err = build_refs_str(&refs_str, refs,
2459 s->selected_entry->id, s->repo);
2460 if (err)
2461 goto done;
2465 if (s->thread_args.commits_needed == 0)
2466 halfdelay(10); /* disable fast refresh */
2468 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2469 if (asprintf(&ncommits_str, " [%d/%d] %s",
2470 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2471 (view->searching && !view->search_next_done) ?
2472 "searching..." : "loading...") == -1) {
2473 err = got_error_from_errno("asprintf");
2474 goto done;
2476 } else {
2477 const char *search_str = NULL;
2478 const char *limit_str = NULL;
2480 if (view->searching) {
2481 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2482 search_str = "no more matches";
2483 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2484 search_str = "no matches found";
2485 else if (!view->search_next_done)
2486 search_str = "searching...";
2489 if (s->limit_view && s->commits->ncommits == 0)
2490 limit_str = "no matches found";
2492 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2493 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2494 search_str ? search_str : (refs_str ? refs_str : ""),
2495 limit_str ? limit_str : "") == -1) {
2496 err = got_error_from_errno("asprintf");
2497 goto done;
2501 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2502 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2503 "........................................",
2504 s->in_repo_path, ncommits_str) == -1) {
2505 err = got_error_from_errno("asprintf");
2506 header = NULL;
2507 goto done;
2509 } else if (asprintf(&header, "commit %s%s",
2510 id_str ? id_str : "........................................",
2511 ncommits_str) == -1) {
2512 err = got_error_from_errno("asprintf");
2513 header = NULL;
2514 goto done;
2516 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2517 if (err)
2518 goto done;
2520 werase(view->window);
2522 if (view_needs_focus_indication(view))
2523 wstandout(view->window);
2524 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2525 if (tc)
2526 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2527 waddwstr(view->window, wline);
2528 while (width < view->ncols) {
2529 waddch(view->window, ' ');
2530 width++;
2532 if (tc)
2533 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2534 if (view_needs_focus_indication(view))
2535 wstandend(view->window);
2536 free(wline);
2537 if (limit <= 1)
2538 goto done;
2540 /* Grow author column size if necessary, and set view->maxx. */
2541 entry = s->first_displayed_entry;
2542 ncommits = 0;
2543 view->maxx = 0;
2544 while (entry) {
2545 struct got_commit_object *c = entry->commit;
2546 char *author, *eol, *msg, *msg0;
2547 wchar_t *wauthor, *wmsg;
2548 int width;
2549 if (ncommits >= limit - 1)
2550 break;
2551 if (s->use_committer)
2552 author = strdup(got_object_commit_get_committer(c));
2553 else
2554 author = strdup(got_object_commit_get_author(c));
2555 if (author == NULL) {
2556 err = got_error_from_errno("strdup");
2557 goto done;
2559 err = format_author(&wauthor, &width, author, COLS,
2560 date_display_cols);
2561 if (author_cols < width)
2562 author_cols = width;
2563 free(wauthor);
2564 free(author);
2565 if (err)
2566 goto done;
2567 err = got_object_commit_get_logmsg(&msg0, c);
2568 if (err)
2569 goto done;
2570 msg = msg0;
2571 while (*msg == '\n')
2572 ++msg;
2573 if ((eol = strchr(msg, '\n')))
2574 *eol = '\0';
2575 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2576 date_display_cols + author_cols, 0);
2577 if (err)
2578 goto done;
2579 view->maxx = MAX(view->maxx, width);
2580 free(msg0);
2581 free(wmsg);
2582 ncommits++;
2583 entry = TAILQ_NEXT(entry, entry);
2586 entry = s->first_displayed_entry;
2587 s->last_displayed_entry = s->first_displayed_entry;
2588 ncommits = 0;
2589 while (entry) {
2590 if (ncommits >= limit - 1)
2591 break;
2592 if (ncommits == s->selected)
2593 wstandout(view->window);
2594 err = draw_commit(view, entry->commit, entry->id,
2595 date_display_cols, author_cols);
2596 if (ncommits == s->selected)
2597 wstandend(view->window);
2598 if (err)
2599 goto done;
2600 ncommits++;
2601 s->last_displayed_entry = entry;
2602 entry = TAILQ_NEXT(entry, entry);
2605 view_border(view);
2606 done:
2607 free(id_str);
2608 free(refs_str);
2609 free(ncommits_str);
2610 free(header);
2611 return err;
2614 static void
2615 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2617 struct commit_queue_entry *entry;
2618 int nscrolled = 0;
2620 entry = TAILQ_FIRST(&s->commits->head);
2621 if (s->first_displayed_entry == entry)
2622 return;
2624 entry = s->first_displayed_entry;
2625 while (entry && nscrolled < maxscroll) {
2626 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2627 if (entry) {
2628 s->first_displayed_entry = entry;
2629 nscrolled++;
2634 static const struct got_error *
2635 trigger_log_thread(struct tog_view *view, int wait)
2637 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2638 int errcode;
2640 halfdelay(1); /* fast refresh while loading commits */
2642 while (!ta->log_complete && !tog_thread_error &&
2643 (ta->commits_needed > 0 || ta->load_all)) {
2644 /* Wake the log thread. */
2645 errcode = pthread_cond_signal(&ta->need_commits);
2646 if (errcode)
2647 return got_error_set_errno(errcode,
2648 "pthread_cond_signal");
2651 * The mutex will be released while the view loop waits
2652 * in wgetch(), at which time the log thread will run.
2654 if (!wait)
2655 break;
2657 /* Display progress update in log view. */
2658 show_log_view(view);
2659 update_panels();
2660 doupdate();
2662 /* Wait right here while next commit is being loaded. */
2663 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2664 if (errcode)
2665 return got_error_set_errno(errcode,
2666 "pthread_cond_wait");
2668 /* Display progress update in log view. */
2669 show_log_view(view);
2670 update_panels();
2671 doupdate();
2674 return NULL;
2677 static const struct got_error *
2678 request_log_commits(struct tog_view *view)
2680 struct tog_log_view_state *state = &view->state.log;
2681 const struct got_error *err = NULL;
2683 if (state->thread_args.log_complete)
2684 return NULL;
2686 state->thread_args.commits_needed += view->nscrolled;
2687 err = trigger_log_thread(view, 1);
2688 view->nscrolled = 0;
2690 return err;
2693 static const struct got_error *
2694 log_scroll_down(struct tog_view *view, int maxscroll)
2696 struct tog_log_view_state *s = &view->state.log;
2697 const struct got_error *err = NULL;
2698 struct commit_queue_entry *pentry;
2699 int nscrolled = 0, ncommits_needed;
2701 if (s->last_displayed_entry == NULL)
2702 return NULL;
2704 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2705 if (s->commits->ncommits < ncommits_needed &&
2706 !s->thread_args.log_complete) {
2708 * Ask the log thread for required amount of commits.
2710 s->thread_args.commits_needed +=
2711 ncommits_needed - s->commits->ncommits;
2712 err = trigger_log_thread(view, 1);
2713 if (err)
2714 return err;
2717 do {
2718 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2719 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2720 break;
2722 s->last_displayed_entry = pentry ?
2723 pentry : s->last_displayed_entry;
2725 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2726 if (pentry == NULL)
2727 break;
2728 s->first_displayed_entry = pentry;
2729 } while (++nscrolled < maxscroll);
2731 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2732 view->nscrolled += nscrolled;
2733 else
2734 view->nscrolled = 0;
2736 return err;
2739 static const struct got_error *
2740 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2741 struct got_commit_object *commit, struct got_object_id *commit_id,
2742 struct tog_view *log_view, struct got_repository *repo)
2744 const struct got_error *err;
2745 struct got_object_qid *parent_id;
2746 struct tog_view *diff_view;
2748 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2749 if (diff_view == NULL)
2750 return got_error_from_errno("view_open");
2752 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2753 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2754 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2755 if (err == NULL)
2756 *new_view = diff_view;
2757 return err;
2760 static const struct got_error *
2761 tree_view_visit_subtree(struct tog_tree_view_state *s,
2762 struct got_tree_object *subtree)
2764 struct tog_parent_tree *parent;
2766 parent = calloc(1, sizeof(*parent));
2767 if (parent == NULL)
2768 return got_error_from_errno("calloc");
2770 parent->tree = s->tree;
2771 parent->first_displayed_entry = s->first_displayed_entry;
2772 parent->selected_entry = s->selected_entry;
2773 parent->selected = s->selected;
2774 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2775 s->tree = subtree;
2776 s->selected = 0;
2777 s->first_displayed_entry = NULL;
2778 return NULL;
2781 static const struct got_error *
2782 tree_view_walk_path(struct tog_tree_view_state *s,
2783 struct got_commit_object *commit, const char *path)
2785 const struct got_error *err = NULL;
2786 struct got_tree_object *tree = NULL;
2787 const char *p;
2788 char *slash, *subpath = NULL;
2790 /* Walk the path and open corresponding tree objects. */
2791 p = path;
2792 while (*p) {
2793 struct got_tree_entry *te;
2794 struct got_object_id *tree_id;
2795 char *te_name;
2797 while (p[0] == '/')
2798 p++;
2800 /* Ensure the correct subtree entry is selected. */
2801 slash = strchr(p, '/');
2802 if (slash == NULL)
2803 te_name = strdup(p);
2804 else
2805 te_name = strndup(p, slash - p);
2806 if (te_name == NULL) {
2807 err = got_error_from_errno("strndup");
2808 break;
2810 te = got_object_tree_find_entry(s->tree, te_name);
2811 if (te == NULL) {
2812 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2813 free(te_name);
2814 break;
2816 free(te_name);
2817 s->first_displayed_entry = s->selected_entry = te;
2819 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2820 break; /* jump to this file's entry */
2822 slash = strchr(p, '/');
2823 if (slash)
2824 subpath = strndup(path, slash - path);
2825 else
2826 subpath = strdup(path);
2827 if (subpath == NULL) {
2828 err = got_error_from_errno("strdup");
2829 break;
2832 err = got_object_id_by_path(&tree_id, s->repo, commit,
2833 subpath);
2834 if (err)
2835 break;
2837 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2838 free(tree_id);
2839 if (err)
2840 break;
2842 err = tree_view_visit_subtree(s, tree);
2843 if (err) {
2844 got_object_tree_close(tree);
2845 break;
2847 if (slash == NULL)
2848 break;
2849 free(subpath);
2850 subpath = NULL;
2851 p = slash;
2854 free(subpath);
2855 return err;
2858 static const struct got_error *
2859 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2860 struct commit_queue_entry *entry, const char *path,
2861 const char *head_ref_name, struct got_repository *repo)
2863 const struct got_error *err = NULL;
2864 struct tog_tree_view_state *s;
2865 struct tog_view *tree_view;
2867 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2868 if (tree_view == NULL)
2869 return got_error_from_errno("view_open");
2871 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2872 if (err)
2873 return err;
2874 s = &tree_view->state.tree;
2876 *new_view = tree_view;
2878 if (got_path_is_root_dir(path))
2879 return NULL;
2881 return tree_view_walk_path(s, entry->commit, path);
2884 static const struct got_error *
2885 block_signals_used_by_main_thread(void)
2887 sigset_t sigset;
2888 int errcode;
2890 if (sigemptyset(&sigset) == -1)
2891 return got_error_from_errno("sigemptyset");
2893 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2894 if (sigaddset(&sigset, SIGWINCH) == -1)
2895 return got_error_from_errno("sigaddset");
2896 if (sigaddset(&sigset, SIGCONT) == -1)
2897 return got_error_from_errno("sigaddset");
2898 if (sigaddset(&sigset, SIGINT) == -1)
2899 return got_error_from_errno("sigaddset");
2900 if (sigaddset(&sigset, SIGTERM) == -1)
2901 return got_error_from_errno("sigaddset");
2903 /* ncurses handles SIGTSTP */
2904 if (sigaddset(&sigset, SIGTSTP) == -1)
2905 return got_error_from_errno("sigaddset");
2907 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2908 if (errcode)
2909 return got_error_set_errno(errcode, "pthread_sigmask");
2911 return NULL;
2914 static void *
2915 log_thread(void *arg)
2917 const struct got_error *err = NULL;
2918 int errcode = 0;
2919 struct tog_log_thread_args *a = arg;
2920 int done = 0;
2923 * Sync startup with main thread such that we begin our
2924 * work once view_input() has released the mutex.
2926 errcode = pthread_mutex_lock(&tog_mutex);
2927 if (errcode) {
2928 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2929 return (void *)err;
2932 err = block_signals_used_by_main_thread();
2933 if (err) {
2934 pthread_mutex_unlock(&tog_mutex);
2935 goto done;
2938 while (!done && !err && !tog_fatal_signal_received()) {
2939 errcode = pthread_mutex_unlock(&tog_mutex);
2940 if (errcode) {
2941 err = got_error_set_errno(errcode,
2942 "pthread_mutex_unlock");
2943 goto done;
2945 err = queue_commits(a);
2946 if (err) {
2947 if (err->code != GOT_ERR_ITER_COMPLETED)
2948 goto done;
2949 err = NULL;
2950 done = 1;
2951 } else if (a->commits_needed > 0 && !a->load_all) {
2952 if (*a->limiting) {
2953 if (a->limit_match)
2954 a->commits_needed--;
2955 } else
2956 a->commits_needed--;
2959 errcode = pthread_mutex_lock(&tog_mutex);
2960 if (errcode) {
2961 err = got_error_set_errno(errcode,
2962 "pthread_mutex_lock");
2963 goto done;
2964 } else if (*a->quit)
2965 done = 1;
2966 else if (*a->limiting && *a->first_displayed_entry == NULL) {
2967 *a->first_displayed_entry =
2968 TAILQ_FIRST(&a->limit_commits->head);
2969 *a->selected_entry = *a->first_displayed_entry;
2970 } else if (*a->first_displayed_entry == NULL) {
2971 *a->first_displayed_entry =
2972 TAILQ_FIRST(&a->real_commits->head);
2973 *a->selected_entry = *a->first_displayed_entry;
2976 errcode = pthread_cond_signal(&a->commit_loaded);
2977 if (errcode) {
2978 err = got_error_set_errno(errcode,
2979 "pthread_cond_signal");
2980 pthread_mutex_unlock(&tog_mutex);
2981 goto done;
2984 if (done)
2985 a->commits_needed = 0;
2986 else {
2987 if (a->commits_needed == 0 && !a->load_all) {
2988 errcode = pthread_cond_wait(&a->need_commits,
2989 &tog_mutex);
2990 if (errcode) {
2991 err = got_error_set_errno(errcode,
2992 "pthread_cond_wait");
2993 pthread_mutex_unlock(&tog_mutex);
2994 goto done;
2996 if (*a->quit)
2997 done = 1;
3001 a->log_complete = 1;
3002 errcode = pthread_mutex_unlock(&tog_mutex);
3003 if (errcode)
3004 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3005 done:
3006 if (err) {
3007 tog_thread_error = 1;
3008 pthread_cond_signal(&a->commit_loaded);
3010 return (void *)err;
3013 static const struct got_error *
3014 stop_log_thread(struct tog_log_view_state *s)
3016 const struct got_error *err = NULL, *thread_err = NULL;
3017 int errcode;
3019 if (s->thread) {
3020 s->quit = 1;
3021 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3022 if (errcode)
3023 return got_error_set_errno(errcode,
3024 "pthread_cond_signal");
3025 errcode = pthread_mutex_unlock(&tog_mutex);
3026 if (errcode)
3027 return got_error_set_errno(errcode,
3028 "pthread_mutex_unlock");
3029 errcode = pthread_join(s->thread, (void **)&thread_err);
3030 if (errcode)
3031 return got_error_set_errno(errcode, "pthread_join");
3032 errcode = pthread_mutex_lock(&tog_mutex);
3033 if (errcode)
3034 return got_error_set_errno(errcode,
3035 "pthread_mutex_lock");
3036 s->thread = NULL;
3039 if (s->thread_args.repo) {
3040 err = got_repo_close(s->thread_args.repo);
3041 s->thread_args.repo = NULL;
3044 if (s->thread_args.pack_fds) {
3045 const struct got_error *pack_err =
3046 got_repo_pack_fds_close(s->thread_args.pack_fds);
3047 if (err == NULL)
3048 err = pack_err;
3049 s->thread_args.pack_fds = NULL;
3052 if (s->thread_args.graph) {
3053 got_commit_graph_close(s->thread_args.graph);
3054 s->thread_args.graph = NULL;
3057 return err ? err : thread_err;
3060 static const struct got_error *
3061 close_log_view(struct tog_view *view)
3063 const struct got_error *err = NULL;
3064 struct tog_log_view_state *s = &view->state.log;
3065 int errcode;
3067 err = stop_log_thread(s);
3069 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3070 if (errcode && err == NULL)
3071 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3073 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3074 if (errcode && err == NULL)
3075 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3077 free_commits(&s->limit_commits);
3078 free_commits(&s->real_commits);
3079 free(s->in_repo_path);
3080 s->in_repo_path = NULL;
3081 free(s->start_id);
3082 s->start_id = NULL;
3083 free(s->head_ref_name);
3084 s->head_ref_name = NULL;
3085 return err;
3089 * We use two queues to implement the limit feature: first consists of
3090 * commits matching the current limit_regex; second is the real queue
3091 * of all known commits (real_commits). When the user starts limiting,
3092 * we swap queues such that all movement and displaying functionality
3093 * works with very slight change.
3095 static const struct got_error *
3096 limit_log_view(struct tog_view *view)
3098 struct tog_log_view_state *s = &view->state.log;
3099 struct commit_queue_entry *entry;
3100 struct tog_view *v = view;
3101 const struct got_error *err = NULL;
3102 char pattern[1024];
3103 int ret;
3105 if (view_is_hsplit_top(view))
3106 v = view->child;
3107 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3108 v = view->parent;
3110 /* Get the pattern */
3111 wmove(v->window, v->nlines - 1, 0);
3112 wclrtoeol(v->window);
3113 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3114 nodelay(v->window, FALSE);
3115 nocbreak();
3116 echo();
3117 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3118 cbreak();
3119 noecho();
3120 nodelay(v->window, TRUE);
3121 if (ret == ERR)
3122 return NULL;
3124 if (*pattern == '\0') {
3126 * Safety measure for the situation where the user
3127 * resets limit without previously limiting anything.
3129 if (!s->limit_view)
3130 return NULL;
3133 * User could have pressed Ctrl+L, which refreshed the
3134 * commit queues, it means we can't save previously
3135 * (before limit took place) displayed entries,
3136 * because they would point to already free'ed memory,
3137 * so we are forced to always select first entry of
3138 * the queue.
3140 s->commits = &s->real_commits;
3141 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3142 s->selected_entry = s->first_displayed_entry;
3143 s->selected = 0;
3144 s->limit_view = 0;
3146 return NULL;
3149 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3150 return NULL;
3152 s->limit_view = 1;
3154 /* Clear the screen while loading limit view */
3155 s->first_displayed_entry = NULL;
3156 s->last_displayed_entry = NULL;
3157 s->selected_entry = NULL;
3158 s->commits = &s->limit_commits;
3160 /* Prepare limit queue for new search */
3161 free_commits(&s->limit_commits);
3162 s->limit_commits.ncommits = 0;
3164 /* First process commits, which are in queue already */
3165 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3166 int have_match = 0;
3168 err = match_commit(&have_match, entry->id,
3169 entry->commit, &s->limit_regex);
3170 if (err)
3171 return err;
3173 if (have_match) {
3174 struct commit_queue_entry *matched;
3176 matched = alloc_commit_queue_entry(entry->commit,
3177 entry->id);
3178 if (matched == NULL) {
3179 err = got_error_from_errno(
3180 "alloc_commit_queue_entry");
3181 break;
3183 matched->commit = entry->commit;
3184 got_object_commit_retain(entry->commit);
3186 matched->idx = s->limit_commits.ncommits;
3187 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3188 matched, entry);
3189 s->limit_commits.ncommits++;
3193 /* Second process all the commits, until we fill the screen */
3194 if (s->limit_commits.ncommits < view->nlines - 1 &&
3195 !s->thread_args.log_complete) {
3196 s->thread_args.commits_needed +=
3197 view->nlines - s->limit_commits.ncommits - 1;
3198 err = trigger_log_thread(view, 1);
3199 if (err)
3200 return err;
3203 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3204 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3205 s->selected = 0;
3207 return NULL;
3210 static const struct got_error *
3211 search_start_log_view(struct tog_view *view)
3213 struct tog_log_view_state *s = &view->state.log;
3215 s->matched_entry = NULL;
3216 s->search_entry = NULL;
3217 return NULL;
3220 static const struct got_error *
3221 search_next_log_view(struct tog_view *view)
3223 const struct got_error *err = NULL;
3224 struct tog_log_view_state *s = &view->state.log;
3225 struct commit_queue_entry *entry;
3227 /* Display progress update in log view. */
3228 show_log_view(view);
3229 update_panels();
3230 doupdate();
3232 if (s->search_entry) {
3233 int errcode, ch;
3234 errcode = pthread_mutex_unlock(&tog_mutex);
3235 if (errcode)
3236 return got_error_set_errno(errcode,
3237 "pthread_mutex_unlock");
3238 ch = wgetch(view->window);
3239 errcode = pthread_mutex_lock(&tog_mutex);
3240 if (errcode)
3241 return got_error_set_errno(errcode,
3242 "pthread_mutex_lock");
3243 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3244 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3245 return NULL;
3247 if (view->searching == TOG_SEARCH_FORWARD)
3248 entry = TAILQ_NEXT(s->search_entry, entry);
3249 else
3250 entry = TAILQ_PREV(s->search_entry,
3251 commit_queue_head, entry);
3252 } else if (s->matched_entry) {
3254 * If the user has moved the cursor after we hit a match,
3255 * the position from where we should continue searching
3256 * might have changed.
3258 if (view->searching == TOG_SEARCH_FORWARD)
3259 entry = TAILQ_NEXT(s->selected_entry, entry);
3260 else
3261 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3262 entry);
3263 } else {
3264 entry = s->selected_entry;
3267 while (1) {
3268 int have_match = 0;
3270 if (entry == NULL) {
3271 if (s->thread_args.log_complete ||
3272 view->searching == TOG_SEARCH_BACKWARD) {
3273 view->search_next_done =
3274 (s->matched_entry == NULL ?
3275 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3276 s->search_entry = NULL;
3277 return NULL;
3280 * Poke the log thread for more commits and return,
3281 * allowing the main loop to make progress. Search
3282 * will resume at s->search_entry once we come back.
3284 s->thread_args.commits_needed++;
3285 return trigger_log_thread(view, 0);
3288 err = match_commit(&have_match, entry->id, entry->commit,
3289 &view->regex);
3290 if (err)
3291 break;
3292 if (have_match) {
3293 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3294 s->matched_entry = entry;
3295 break;
3298 s->search_entry = entry;
3299 if (view->searching == TOG_SEARCH_FORWARD)
3300 entry = TAILQ_NEXT(entry, entry);
3301 else
3302 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3305 if (s->matched_entry) {
3306 int cur = s->selected_entry->idx;
3307 while (cur < s->matched_entry->idx) {
3308 err = input_log_view(NULL, view, KEY_DOWN);
3309 if (err)
3310 return err;
3311 cur++;
3313 while (cur > s->matched_entry->idx) {
3314 err = input_log_view(NULL, view, KEY_UP);
3315 if (err)
3316 return err;
3317 cur--;
3321 s->search_entry = NULL;
3323 return NULL;
3326 static const struct got_error *
3327 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3328 struct got_repository *repo, const char *head_ref_name,
3329 const char *in_repo_path, int log_branches)
3331 const struct got_error *err = NULL;
3332 struct tog_log_view_state *s = &view->state.log;
3333 struct got_repository *thread_repo = NULL;
3334 struct got_commit_graph *thread_graph = NULL;
3335 int errcode;
3337 if (in_repo_path != s->in_repo_path) {
3338 free(s->in_repo_path);
3339 s->in_repo_path = strdup(in_repo_path);
3340 if (s->in_repo_path == NULL)
3341 return got_error_from_errno("strdup");
3344 /* The commit queue only contains commits being displayed. */
3345 TAILQ_INIT(&s->real_commits.head);
3346 s->real_commits.ncommits = 0;
3347 s->commits = &s->real_commits;
3349 TAILQ_INIT(&s->limit_commits.head);
3350 s->limit_view = 0;
3351 s->limit_commits.ncommits = 0;
3353 s->repo = repo;
3354 if (head_ref_name) {
3355 s->head_ref_name = strdup(head_ref_name);
3356 if (s->head_ref_name == NULL) {
3357 err = got_error_from_errno("strdup");
3358 goto done;
3361 s->start_id = got_object_id_dup(start_id);
3362 if (s->start_id == NULL) {
3363 err = got_error_from_errno("got_object_id_dup");
3364 goto done;
3366 s->log_branches = log_branches;
3367 s->use_committer = 1;
3369 STAILQ_INIT(&s->colors);
3370 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3371 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3372 get_color_value("TOG_COLOR_COMMIT"));
3373 if (err)
3374 goto done;
3375 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3376 get_color_value("TOG_COLOR_AUTHOR"));
3377 if (err) {
3378 free_colors(&s->colors);
3379 goto done;
3381 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3382 get_color_value("TOG_COLOR_DATE"));
3383 if (err) {
3384 free_colors(&s->colors);
3385 goto done;
3389 view->show = show_log_view;
3390 view->input = input_log_view;
3391 view->resize = resize_log_view;
3392 view->close = close_log_view;
3393 view->search_start = search_start_log_view;
3394 view->search_next = search_next_log_view;
3396 if (s->thread_args.pack_fds == NULL) {
3397 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3398 if (err)
3399 goto done;
3401 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3402 s->thread_args.pack_fds);
3403 if (err)
3404 goto done;
3405 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3406 !s->log_branches);
3407 if (err)
3408 goto done;
3409 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3410 s->repo, NULL, NULL);
3411 if (err)
3412 goto done;
3414 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3415 if (errcode) {
3416 err = got_error_set_errno(errcode, "pthread_cond_init");
3417 goto done;
3419 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3420 if (errcode) {
3421 err = got_error_set_errno(errcode, "pthread_cond_init");
3422 goto done;
3425 s->thread_args.commits_needed = view->nlines;
3426 s->thread_args.graph = thread_graph;
3427 s->thread_args.real_commits = &s->real_commits;
3428 s->thread_args.limit_commits = &s->limit_commits;
3429 s->thread_args.in_repo_path = s->in_repo_path;
3430 s->thread_args.start_id = s->start_id;
3431 s->thread_args.repo = thread_repo;
3432 s->thread_args.log_complete = 0;
3433 s->thread_args.quit = &s->quit;
3434 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3435 s->thread_args.selected_entry = &s->selected_entry;
3436 s->thread_args.searching = &view->searching;
3437 s->thread_args.search_next_done = &view->search_next_done;
3438 s->thread_args.regex = &view->regex;
3439 s->thread_args.limiting = &s->limit_view;
3440 s->thread_args.limit_regex = &s->limit_regex;
3441 s->thread_args.limit_commits = &s->limit_commits;
3442 done:
3443 if (err)
3444 close_log_view(view);
3445 return err;
3448 static const struct got_error *
3449 show_log_view(struct tog_view *view)
3451 const struct got_error *err;
3452 struct tog_log_view_state *s = &view->state.log;
3454 if (s->thread == NULL) {
3455 int errcode = pthread_create(&s->thread, NULL, log_thread,
3456 &s->thread_args);
3457 if (errcode)
3458 return got_error_set_errno(errcode, "pthread_create");
3459 if (s->thread_args.commits_needed > 0) {
3460 err = trigger_log_thread(view, 1);
3461 if (err)
3462 return err;
3466 return draw_commits(view);
3469 static void
3470 log_move_cursor_up(struct tog_view *view, int page, int home)
3472 struct tog_log_view_state *s = &view->state.log;
3474 if (s->first_displayed_entry == NULL)
3475 return;
3476 if (s->selected_entry->idx == 0)
3477 view->count = 0;
3479 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3480 || home)
3481 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3483 if (!page && !home && s->selected > 0)
3484 --s->selected;
3485 else
3486 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3488 select_commit(s);
3489 return;
3492 static const struct got_error *
3493 log_move_cursor_down(struct tog_view *view, int page)
3495 struct tog_log_view_state *s = &view->state.log;
3496 const struct got_error *err = NULL;
3497 int eos = view->nlines - 2;
3499 if (s->first_displayed_entry == NULL)
3500 return NULL;
3502 if (s->thread_args.log_complete &&
3503 s->selected_entry->idx >= s->commits->ncommits - 1)
3504 return NULL;
3506 if (view_is_hsplit_top(view))
3507 --eos; /* border consumes the last line */
3509 if (!page) {
3510 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3511 ++s->selected;
3512 else
3513 err = log_scroll_down(view, 1);
3514 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3515 struct commit_queue_entry *entry;
3516 int n;
3518 s->selected = 0;
3519 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3520 s->last_displayed_entry = entry;
3521 for (n = 0; n <= eos; n++) {
3522 if (entry == NULL)
3523 break;
3524 s->first_displayed_entry = entry;
3525 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3527 if (n > 0)
3528 s->selected = n - 1;
3529 } else {
3530 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3531 s->thread_args.log_complete)
3532 s->selected += MIN(page,
3533 s->commits->ncommits - s->selected_entry->idx - 1);
3534 else
3535 err = log_scroll_down(view, page);
3537 if (err)
3538 return err;
3541 * We might necessarily overshoot in horizontal
3542 * splits; if so, select the last displayed commit.
3544 if (s->first_displayed_entry && s->last_displayed_entry) {
3545 s->selected = MIN(s->selected,
3546 s->last_displayed_entry->idx -
3547 s->first_displayed_entry->idx);
3550 select_commit(s);
3552 if (s->thread_args.log_complete &&
3553 s->selected_entry->idx == s->commits->ncommits - 1)
3554 view->count = 0;
3556 return NULL;
3559 static void
3560 view_get_split(struct tog_view *view, int *y, int *x)
3562 *x = 0;
3563 *y = 0;
3565 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3566 if (view->child && view->child->resized_y)
3567 *y = view->child->resized_y;
3568 else if (view->resized_y)
3569 *y = view->resized_y;
3570 else
3571 *y = view_split_begin_y(view->lines);
3572 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3573 if (view->child && view->child->resized_x)
3574 *x = view->child->resized_x;
3575 else if (view->resized_x)
3576 *x = view->resized_x;
3577 else
3578 *x = view_split_begin_x(view->begin_x);
3582 /* Split view horizontally at y and offset view->state->selected line. */
3583 static const struct got_error *
3584 view_init_hsplit(struct tog_view *view, int y)
3586 const struct got_error *err = NULL;
3588 view->nlines = y;
3589 view->ncols = COLS;
3590 err = view_resize(view);
3591 if (err)
3592 return err;
3594 err = offset_selection_down(view);
3596 return err;
3599 static const struct got_error *
3600 log_goto_line(struct tog_view *view, int nlines)
3602 const struct got_error *err = NULL;
3603 struct tog_log_view_state *s = &view->state.log;
3604 int g, idx = s->selected_entry->idx;
3606 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3607 return NULL;
3609 g = view->gline;
3610 view->gline = 0;
3612 if (g >= s->first_displayed_entry->idx + 1 &&
3613 g <= s->last_displayed_entry->idx + 1 &&
3614 g - s->first_displayed_entry->idx - 1 < nlines) {
3615 s->selected = g - s->first_displayed_entry->idx - 1;
3616 select_commit(s);
3617 return NULL;
3620 if (idx + 1 < g) {
3621 err = log_move_cursor_down(view, g - idx - 1);
3622 if (!err && g > s->selected_entry->idx + 1)
3623 err = log_move_cursor_down(view,
3624 g - s->first_displayed_entry->idx - 1);
3625 if (err)
3626 return err;
3627 } else if (idx + 1 > g)
3628 log_move_cursor_up(view, idx - g + 1, 0);
3630 if (g < nlines && s->first_displayed_entry->idx == 0)
3631 s->selected = g - 1;
3633 select_commit(s);
3634 return NULL;
3638 static const struct got_error *
3639 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3641 const struct got_error *err = NULL;
3642 struct tog_log_view_state *s = &view->state.log;
3643 int eos, nscroll;
3645 if (s->thread_args.load_all) {
3646 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3647 s->thread_args.load_all = 0;
3648 else if (s->thread_args.log_complete) {
3649 err = log_move_cursor_down(view, s->commits->ncommits);
3650 s->thread_args.load_all = 0;
3652 if (err)
3653 return err;
3656 eos = nscroll = view->nlines - 1;
3657 if (view_is_hsplit_top(view))
3658 --eos; /* border */
3660 if (view->gline)
3661 return log_goto_line(view, eos);
3663 switch (ch) {
3664 case '&':
3665 err = limit_log_view(view);
3666 break;
3667 case 'q':
3668 s->quit = 1;
3669 break;
3670 case '0':
3671 view->x = 0;
3672 break;
3673 case '$':
3674 view->x = MAX(view->maxx - view->ncols / 2, 0);
3675 view->count = 0;
3676 break;
3677 case KEY_RIGHT:
3678 case 'l':
3679 if (view->x + view->ncols / 2 < view->maxx)
3680 view->x += 2; /* move two columns right */
3681 else
3682 view->count = 0;
3683 break;
3684 case KEY_LEFT:
3685 case 'h':
3686 view->x -= MIN(view->x, 2); /* move two columns back */
3687 if (view->x <= 0)
3688 view->count = 0;
3689 break;
3690 case 'k':
3691 case KEY_UP:
3692 case '<':
3693 case ',':
3694 case CTRL('p'):
3695 log_move_cursor_up(view, 0, 0);
3696 break;
3697 case 'g':
3698 case '=':
3699 case KEY_HOME:
3700 log_move_cursor_up(view, 0, 1);
3701 view->count = 0;
3702 break;
3703 case CTRL('u'):
3704 case 'u':
3705 nscroll /= 2;
3706 /* FALL THROUGH */
3707 case KEY_PPAGE:
3708 case CTRL('b'):
3709 case 'b':
3710 log_move_cursor_up(view, nscroll, 0);
3711 break;
3712 case 'j':
3713 case KEY_DOWN:
3714 case '>':
3715 case '.':
3716 case CTRL('n'):
3717 err = log_move_cursor_down(view, 0);
3718 break;
3719 case '@':
3720 s->use_committer = !s->use_committer;
3721 break;
3722 case 'G':
3723 case '*':
3724 case KEY_END: {
3725 /* We don't know yet how many commits, so we're forced to
3726 * traverse them all. */
3727 view->count = 0;
3728 s->thread_args.load_all = 1;
3729 if (!s->thread_args.log_complete)
3730 return trigger_log_thread(view, 0);
3731 err = log_move_cursor_down(view, s->commits->ncommits);
3732 s->thread_args.load_all = 0;
3733 break;
3735 case CTRL('d'):
3736 case 'd':
3737 nscroll /= 2;
3738 /* FALL THROUGH */
3739 case KEY_NPAGE:
3740 case CTRL('f'):
3741 case 'f':
3742 case ' ':
3743 err = log_move_cursor_down(view, nscroll);
3744 break;
3745 case KEY_RESIZE:
3746 if (s->selected > view->nlines - 2)
3747 s->selected = view->nlines - 2;
3748 if (s->selected > s->commits->ncommits - 1)
3749 s->selected = s->commits->ncommits - 1;
3750 select_commit(s);
3751 if (s->commits->ncommits < view->nlines - 1 &&
3752 !s->thread_args.log_complete) {
3753 s->thread_args.commits_needed += (view->nlines - 1) -
3754 s->commits->ncommits;
3755 err = trigger_log_thread(view, 1);
3757 break;
3758 case KEY_ENTER:
3759 case '\r':
3760 view->count = 0;
3761 if (s->selected_entry == NULL)
3762 break;
3763 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3764 break;
3765 case 'T':
3766 view->count = 0;
3767 if (s->selected_entry == NULL)
3768 break;
3769 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3770 break;
3771 case KEY_BACKSPACE:
3772 case CTRL('l'):
3773 case 'B':
3774 view->count = 0;
3775 if (ch == KEY_BACKSPACE &&
3776 got_path_is_root_dir(s->in_repo_path))
3777 break;
3778 err = stop_log_thread(s);
3779 if (err)
3780 return err;
3781 if (ch == KEY_BACKSPACE) {
3782 char *parent_path;
3783 err = got_path_dirname(&parent_path, s->in_repo_path);
3784 if (err)
3785 return err;
3786 free(s->in_repo_path);
3787 s->in_repo_path = parent_path;
3788 s->thread_args.in_repo_path = s->in_repo_path;
3789 } else if (ch == CTRL('l')) {
3790 struct got_object_id *start_id;
3791 err = got_repo_match_object_id(&start_id, NULL,
3792 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3793 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3794 if (err) {
3795 if (s->head_ref_name == NULL ||
3796 err->code != GOT_ERR_NOT_REF)
3797 return err;
3798 /* Try to cope with deleted references. */
3799 free(s->head_ref_name);
3800 s->head_ref_name = NULL;
3801 err = got_repo_match_object_id(&start_id,
3802 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
3803 &tog_refs, s->repo);
3804 if (err)
3805 return err;
3807 free(s->start_id);
3808 s->start_id = start_id;
3809 s->thread_args.start_id = s->start_id;
3810 } else /* 'B' */
3811 s->log_branches = !s->log_branches;
3813 if (s->thread_args.pack_fds == NULL) {
3814 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3815 if (err)
3816 return err;
3818 err = got_repo_open(&s->thread_args.repo,
3819 got_repo_get_path(s->repo), NULL,
3820 s->thread_args.pack_fds);
3821 if (err)
3822 return err;
3823 tog_free_refs();
3824 err = tog_load_refs(s->repo, 0);
3825 if (err)
3826 return err;
3827 err = got_commit_graph_open(&s->thread_args.graph,
3828 s->in_repo_path, !s->log_branches);
3829 if (err)
3830 return err;
3831 err = got_commit_graph_iter_start(s->thread_args.graph,
3832 s->start_id, s->repo, NULL, NULL);
3833 if (err)
3834 return err;
3835 free_commits(&s->real_commits);
3836 free_commits(&s->limit_commits);
3837 s->first_displayed_entry = NULL;
3838 s->last_displayed_entry = NULL;
3839 s->selected_entry = NULL;
3840 s->selected = 0;
3841 s->thread_args.log_complete = 0;
3842 s->quit = 0;
3843 s->thread_args.commits_needed = view->lines;
3844 s->matched_entry = NULL;
3845 s->search_entry = NULL;
3846 view->offset = 0;
3847 break;
3848 case 'R':
3849 view->count = 0;
3850 err = view_request_new(new_view, view, TOG_VIEW_REF);
3851 break;
3852 default:
3853 view->count = 0;
3854 break;
3857 return err;
3860 static const struct got_error *
3861 apply_unveil(const char *repo_path, const char *worktree_path)
3863 const struct got_error *error;
3865 #ifdef PROFILE
3866 if (unveil("gmon.out", "rwc") != 0)
3867 return got_error_from_errno2("unveil", "gmon.out");
3868 #endif
3869 if (repo_path && unveil(repo_path, "r") != 0)
3870 return got_error_from_errno2("unveil", repo_path);
3872 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3873 return got_error_from_errno2("unveil", worktree_path);
3875 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3876 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3878 error = got_privsep_unveil_exec_helpers();
3879 if (error != NULL)
3880 return error;
3882 if (unveil(NULL, NULL) != 0)
3883 return got_error_from_errno("unveil");
3885 return NULL;
3888 static void
3889 init_curses(void)
3892 * Override default signal handlers before starting ncurses.
3893 * This should prevent ncurses from installing its own
3894 * broken cleanup() signal handler.
3896 signal(SIGWINCH, tog_sigwinch);
3897 signal(SIGPIPE, tog_sigpipe);
3898 signal(SIGCONT, tog_sigcont);
3899 signal(SIGINT, tog_sigint);
3900 signal(SIGTERM, tog_sigterm);
3902 initscr();
3903 cbreak();
3904 halfdelay(1); /* Do fast refresh while initial view is loading. */
3905 noecho();
3906 nonl();
3907 intrflush(stdscr, FALSE);
3908 keypad(stdscr, TRUE);
3909 curs_set(0);
3910 if (getenv("TOG_COLORS") != NULL) {
3911 start_color();
3912 use_default_colors();
3916 static const struct got_error *
3917 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3918 struct got_repository *repo, struct got_worktree *worktree)
3920 const struct got_error *err = NULL;
3922 if (argc == 0) {
3923 *in_repo_path = strdup("/");
3924 if (*in_repo_path == NULL)
3925 return got_error_from_errno("strdup");
3926 return NULL;
3929 if (worktree) {
3930 const char *prefix = got_worktree_get_path_prefix(worktree);
3931 char *p;
3933 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3934 if (err)
3935 return err;
3936 if (asprintf(in_repo_path, "%s%s%s", prefix,
3937 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3938 p) == -1) {
3939 err = got_error_from_errno("asprintf");
3940 *in_repo_path = NULL;
3942 free(p);
3943 } else
3944 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3946 return err;
3949 static const struct got_error *
3950 cmd_log(int argc, char *argv[])
3952 const struct got_error *error;
3953 struct got_repository *repo = NULL;
3954 struct got_worktree *worktree = NULL;
3955 struct got_object_id *start_id = NULL;
3956 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3957 char *start_commit = NULL, *label = NULL;
3958 struct got_reference *ref = NULL;
3959 const char *head_ref_name = NULL;
3960 int ch, log_branches = 0;
3961 struct tog_view *view;
3962 int *pack_fds = NULL;
3964 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3965 switch (ch) {
3966 case 'b':
3967 log_branches = 1;
3968 break;
3969 case 'c':
3970 start_commit = optarg;
3971 break;
3972 case 'r':
3973 repo_path = realpath(optarg, NULL);
3974 if (repo_path == NULL)
3975 return got_error_from_errno2("realpath",
3976 optarg);
3977 break;
3978 default:
3979 usage_log();
3980 /* NOTREACHED */
3984 argc -= optind;
3985 argv += optind;
3987 if (argc > 1)
3988 usage_log();
3990 error = got_repo_pack_fds_open(&pack_fds);
3991 if (error != NULL)
3992 goto done;
3994 if (repo_path == NULL) {
3995 cwd = getcwd(NULL, 0);
3996 if (cwd == NULL)
3997 return got_error_from_errno("getcwd");
3998 error = got_worktree_open(&worktree, cwd);
3999 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4000 goto done;
4001 if (worktree)
4002 repo_path =
4003 strdup(got_worktree_get_repo_path(worktree));
4004 else
4005 repo_path = strdup(cwd);
4006 if (repo_path == NULL) {
4007 error = got_error_from_errno("strdup");
4008 goto done;
4012 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4013 if (error != NULL)
4014 goto done;
4016 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4017 repo, worktree);
4018 if (error)
4019 goto done;
4021 init_curses();
4023 error = apply_unveil(got_repo_get_path(repo),
4024 worktree ? got_worktree_get_root_path(worktree) : NULL);
4025 if (error)
4026 goto done;
4028 /* already loaded by tog_log_with_path()? */
4029 if (TAILQ_EMPTY(&tog_refs)) {
4030 error = tog_load_refs(repo, 0);
4031 if (error)
4032 goto done;
4035 if (start_commit == NULL) {
4036 error = got_repo_match_object_id(&start_id, &label,
4037 worktree ? got_worktree_get_head_ref_name(worktree) :
4038 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4039 if (error)
4040 goto done;
4041 head_ref_name = label;
4042 } else {
4043 error = got_ref_open(&ref, repo, start_commit, 0);
4044 if (error == NULL)
4045 head_ref_name = got_ref_get_name(ref);
4046 else if (error->code != GOT_ERR_NOT_REF)
4047 goto done;
4048 error = got_repo_match_object_id(&start_id, NULL,
4049 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4050 if (error)
4051 goto done;
4054 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4055 if (view == NULL) {
4056 error = got_error_from_errno("view_open");
4057 goto done;
4059 error = open_log_view(view, start_id, repo, head_ref_name,
4060 in_repo_path, log_branches);
4061 if (error)
4062 goto done;
4063 if (worktree) {
4064 /* Release work tree lock. */
4065 got_worktree_close(worktree);
4066 worktree = NULL;
4068 error = view_loop(view);
4069 done:
4070 free(in_repo_path);
4071 free(repo_path);
4072 free(cwd);
4073 free(start_id);
4074 free(label);
4075 if (ref)
4076 got_ref_close(ref);
4077 if (repo) {
4078 const struct got_error *close_err = got_repo_close(repo);
4079 if (error == NULL)
4080 error = close_err;
4082 if (worktree)
4083 got_worktree_close(worktree);
4084 if (pack_fds) {
4085 const struct got_error *pack_err =
4086 got_repo_pack_fds_close(pack_fds);
4087 if (error == NULL)
4088 error = pack_err;
4090 tog_free_refs();
4091 return error;
4094 __dead static void
4095 usage_diff(void)
4097 endwin();
4098 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4099 "object1 object2\n", getprogname());
4100 exit(1);
4103 static int
4104 match_line(const char *line, regex_t *regex, size_t nmatch,
4105 regmatch_t *regmatch)
4107 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4110 static struct tog_color *
4111 match_color(struct tog_colors *colors, const char *line)
4113 struct tog_color *tc = NULL;
4115 STAILQ_FOREACH(tc, colors, entry) {
4116 if (match_line(line, &tc->regex, 0, NULL))
4117 return tc;
4120 return NULL;
4123 static const struct got_error *
4124 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4125 WINDOW *window, int skipcol, regmatch_t *regmatch)
4127 const struct got_error *err = NULL;
4128 char *exstr = NULL;
4129 wchar_t *wline = NULL;
4130 int rme, rms, n, width, scrollx;
4131 int width0 = 0, width1 = 0, width2 = 0;
4132 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4134 *wtotal = 0;
4136 rms = regmatch->rm_so;
4137 rme = regmatch->rm_eo;
4139 err = expand_tab(&exstr, line);
4140 if (err)
4141 return err;
4143 /* Split the line into 3 segments, according to match offsets. */
4144 seg0 = strndup(exstr, rms);
4145 if (seg0 == NULL) {
4146 err = got_error_from_errno("strndup");
4147 goto done;
4149 seg1 = strndup(exstr + rms, rme - rms);
4150 if (seg1 == NULL) {
4151 err = got_error_from_errno("strndup");
4152 goto done;
4154 seg2 = strdup(exstr + rme);
4155 if (seg2 == NULL) {
4156 err = got_error_from_errno("strndup");
4157 goto done;
4160 /* draw up to matched token if we haven't scrolled past it */
4161 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4162 col_tab_align, 1);
4163 if (err)
4164 goto done;
4165 n = MAX(width0 - skipcol, 0);
4166 if (n) {
4167 free(wline);
4168 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4169 wlimit, col_tab_align, 1);
4170 if (err)
4171 goto done;
4172 waddwstr(window, &wline[scrollx]);
4173 wlimit -= width;
4174 *wtotal += width;
4177 if (wlimit > 0) {
4178 int i = 0, w = 0;
4179 size_t wlen;
4181 free(wline);
4182 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4183 col_tab_align, 1);
4184 if (err)
4185 goto done;
4186 wlen = wcslen(wline);
4187 while (i < wlen) {
4188 width = wcwidth(wline[i]);
4189 if (width == -1) {
4190 /* should not happen, tabs are expanded */
4191 err = got_error(GOT_ERR_RANGE);
4192 goto done;
4194 if (width0 + w + width > skipcol)
4195 break;
4196 w += width;
4197 i++;
4199 /* draw (visible part of) matched token (if scrolled into it) */
4200 if (width1 - w > 0) {
4201 wattron(window, A_STANDOUT);
4202 waddwstr(window, &wline[i]);
4203 wattroff(window, A_STANDOUT);
4204 wlimit -= (width1 - w);
4205 *wtotal += (width1 - w);
4209 if (wlimit > 0) { /* draw rest of line */
4210 free(wline);
4211 if (skipcol > width0 + width1) {
4212 err = format_line(&wline, &width2, &scrollx, seg2,
4213 skipcol - (width0 + width1), wlimit,
4214 col_tab_align, 1);
4215 if (err)
4216 goto done;
4217 waddwstr(window, &wline[scrollx]);
4218 } else {
4219 err = format_line(&wline, &width2, NULL, seg2, 0,
4220 wlimit, col_tab_align, 1);
4221 if (err)
4222 goto done;
4223 waddwstr(window, wline);
4225 *wtotal += width2;
4227 done:
4228 free(wline);
4229 free(exstr);
4230 free(seg0);
4231 free(seg1);
4232 free(seg2);
4233 return err;
4236 static int
4237 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4239 FILE *f = NULL;
4240 int *eof, *first, *selected;
4242 if (view->type == TOG_VIEW_DIFF) {
4243 struct tog_diff_view_state *s = &view->state.diff;
4245 first = &s->first_displayed_line;
4246 selected = first;
4247 eof = &s->eof;
4248 f = s->f;
4249 } else if (view->type == TOG_VIEW_HELP) {
4250 struct tog_help_view_state *s = &view->state.help;
4252 first = &s->first_displayed_line;
4253 selected = first;
4254 eof = &s->eof;
4255 f = s->f;
4256 } else if (view->type == TOG_VIEW_BLAME) {
4257 struct tog_blame_view_state *s = &view->state.blame;
4259 first = &s->first_displayed_line;
4260 selected = &s->selected_line;
4261 eof = &s->eof;
4262 f = s->blame.f;
4263 } else
4264 return 0;
4266 /* Center gline in the middle of the page like vi(1). */
4267 if (*lineno < view->gline - (view->nlines - 3) / 2)
4268 return 0;
4269 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4270 rewind(f);
4271 *eof = 0;
4272 *first = 1;
4273 *lineno = 0;
4274 *nprinted = 0;
4275 return 0;
4278 *selected = view->gline <= (view->nlines - 3) / 2 ?
4279 view->gline : (view->nlines - 3) / 2 + 1;
4280 view->gline = 0;
4282 return 1;
4285 static const struct got_error *
4286 draw_file(struct tog_view *view, const char *header)
4288 struct tog_diff_view_state *s = &view->state.diff;
4289 regmatch_t *regmatch = &view->regmatch;
4290 const struct got_error *err;
4291 int nprinted = 0;
4292 char *line;
4293 size_t linesize = 0;
4294 ssize_t linelen;
4295 wchar_t *wline;
4296 int width;
4297 int max_lines = view->nlines;
4298 int nlines = s->nlines;
4299 off_t line_offset;
4301 s->lineno = s->first_displayed_line - 1;
4302 line_offset = s->lines[s->first_displayed_line - 1].offset;
4303 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4304 return got_error_from_errno("fseek");
4306 werase(view->window);
4308 if (view->gline > s->nlines - 1)
4309 view->gline = s->nlines - 1;
4311 if (header) {
4312 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4313 1 : view->gline - (view->nlines - 3) / 2 :
4314 s->lineno + s->selected_line;
4316 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4317 return got_error_from_errno("asprintf");
4318 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4319 0, 0);
4320 free(line);
4321 if (err)
4322 return err;
4324 if (view_needs_focus_indication(view))
4325 wstandout(view->window);
4326 waddwstr(view->window, wline);
4327 free(wline);
4328 wline = NULL;
4329 while (width++ < view->ncols)
4330 waddch(view->window, ' ');
4331 if (view_needs_focus_indication(view))
4332 wstandend(view->window);
4334 if (max_lines <= 1)
4335 return NULL;
4336 max_lines--;
4339 s->eof = 0;
4340 view->maxx = 0;
4341 line = NULL;
4342 while (max_lines > 0 && nprinted < max_lines) {
4343 enum got_diff_line_type linetype;
4344 attr_t attr = 0;
4346 linelen = getline(&line, &linesize, s->f);
4347 if (linelen == -1) {
4348 if (feof(s->f)) {
4349 s->eof = 1;
4350 break;
4352 free(line);
4353 return got_ferror(s->f, GOT_ERR_IO);
4356 if (++s->lineno < s->first_displayed_line)
4357 continue;
4358 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4359 continue;
4360 if (s->lineno == view->hiline)
4361 attr = A_STANDOUT;
4363 /* Set view->maxx based on full line length. */
4364 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4365 view->x ? 1 : 0);
4366 if (err) {
4367 free(line);
4368 return err;
4370 view->maxx = MAX(view->maxx, width);
4371 free(wline);
4372 wline = NULL;
4374 linetype = s->lines[s->lineno].type;
4375 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4376 linetype < GOT_DIFF_LINE_CONTEXT)
4377 attr |= COLOR_PAIR(linetype);
4378 if (attr)
4379 wattron(view->window, attr);
4380 if (s->first_displayed_line + nprinted == s->matched_line &&
4381 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4382 err = add_matched_line(&width, line, view->ncols, 0,
4383 view->window, view->x, regmatch);
4384 if (err) {
4385 free(line);
4386 return err;
4388 } else {
4389 int skip;
4390 err = format_line(&wline, &width, &skip, line,
4391 view->x, view->ncols, 0, view->x ? 1 : 0);
4392 if (err) {
4393 free(line);
4394 return err;
4396 waddwstr(view->window, &wline[skip]);
4397 free(wline);
4398 wline = NULL;
4400 if (s->lineno == view->hiline) {
4401 /* highlight full gline length */
4402 while (width++ < view->ncols)
4403 waddch(view->window, ' ');
4404 } else {
4405 if (width <= view->ncols - 1)
4406 waddch(view->window, '\n');
4408 if (attr)
4409 wattroff(view->window, attr);
4410 if (++nprinted == 1)
4411 s->first_displayed_line = s->lineno;
4413 free(line);
4414 if (nprinted >= 1)
4415 s->last_displayed_line = s->first_displayed_line +
4416 (nprinted - 1);
4417 else
4418 s->last_displayed_line = s->first_displayed_line;
4420 view_border(view);
4422 if (s->eof) {
4423 while (nprinted < view->nlines) {
4424 waddch(view->window, '\n');
4425 nprinted++;
4428 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4429 view->ncols, 0, 0);
4430 if (err) {
4431 return err;
4434 wstandout(view->window);
4435 waddwstr(view->window, wline);
4436 free(wline);
4437 wline = NULL;
4438 wstandend(view->window);
4441 return NULL;
4444 static char *
4445 get_datestr(time_t *time, char *datebuf)
4447 struct tm mytm, *tm;
4448 char *p, *s;
4450 tm = gmtime_r(time, &mytm);
4451 if (tm == NULL)
4452 return NULL;
4453 s = asctime_r(tm, datebuf);
4454 if (s == NULL)
4455 return NULL;
4456 p = strchr(s, '\n');
4457 if (p)
4458 *p = '\0';
4459 return s;
4462 static const struct got_error *
4463 get_changed_paths(struct got_pathlist_head *paths,
4464 struct got_commit_object *commit, struct got_repository *repo,
4465 struct got_diffstat_cb_arg *dsa)
4467 const struct got_error *err = NULL;
4468 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4469 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4470 struct got_object_qid *qid;
4471 FILE *f1 = NULL, *f2 = NULL;
4472 int fd1 = -1, fd2 = -1;
4474 f1 = got_opentemp();
4475 if (f1 == NULL) {
4476 err = got_error_from_errno("got_opentemp");
4477 goto done;
4479 f2 = got_opentemp();
4480 if (f2 == NULL) {
4481 err = got_error_from_errno("got_opentemp");
4482 goto done;
4485 fd1 = got_opentempfd();
4486 if (fd1 == -1) {
4487 err = got_error_from_errno("got_opentempfd");
4488 goto done;
4490 fd2 = got_opentempfd();
4491 if (fd2 == -1) {
4492 err = got_error_from_errno("got_opentempfd");
4493 goto done;
4496 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4497 if (qid != NULL) {
4498 struct got_commit_object *pcommit;
4499 err = got_object_open_as_commit(&pcommit, repo,
4500 &qid->id);
4501 if (err)
4502 return err;
4504 tree_id1 = got_object_id_dup(
4505 got_object_commit_get_tree_id(pcommit));
4506 if (tree_id1 == NULL) {
4507 got_object_commit_close(pcommit);
4508 return got_error_from_errno("got_object_id_dup");
4510 got_object_commit_close(pcommit);
4514 if (tree_id1) {
4515 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4516 if (err)
4517 goto done;
4520 tree_id2 = got_object_commit_get_tree_id(commit);
4521 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4522 if (err)
4523 goto done;
4525 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
4526 got_diff_tree_compute_diffstat, dsa, 1);
4527 done:
4528 if (tree1)
4529 got_object_tree_close(tree1);
4530 if (tree2)
4531 got_object_tree_close(tree2);
4532 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4533 err = got_error_from_errno("close");
4534 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4535 err = got_error_from_errno("close");
4536 if (f1 && fclose(f1) == EOF && err == NULL)
4537 err = got_error_from_errno("fclose");
4538 if (f2 && fclose(f2) == EOF && err == NULL)
4539 err = got_error_from_errno("fclose");
4540 free(tree_id1);
4541 return err;
4544 static const struct got_error *
4545 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4546 off_t off, uint8_t type)
4548 struct got_diff_line *p;
4550 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4551 if (p == NULL)
4552 return got_error_from_errno("reallocarray");
4553 *lines = p;
4554 (*lines)[*nlines].offset = off;
4555 (*lines)[*nlines].type = type;
4556 (*nlines)++;
4558 return NULL;
4561 static const struct got_error *
4562 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4563 struct got_object_id *commit_id, struct got_reflist_head *refs,
4564 struct got_repository *repo, int ignore_ws, int force_text_diff,
4565 FILE *outfile)
4567 const struct got_error *err = NULL;
4568 char datebuf[26], *datestr;
4569 struct got_commit_object *commit;
4570 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4571 time_t committer_time;
4572 const char *author, *committer;
4573 char *refs_str = NULL;
4574 struct got_pathlist_head changed_paths;
4575 struct got_pathlist_entry *pe;
4576 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0, &changed_paths,
4577 ignore_ws, force_text_diff, tog_diff_algo };
4578 off_t outoff = 0;
4579 int n;
4581 TAILQ_INIT(&changed_paths);
4583 if (refs) {
4584 err = build_refs_str(&refs_str, refs, commit_id, repo);
4585 if (err)
4586 return err;
4589 err = got_object_open_as_commit(&commit, repo, commit_id);
4590 if (err)
4591 return err;
4593 err = got_object_id_str(&id_str, commit_id);
4594 if (err) {
4595 err = got_error_from_errno("got_object_id_str");
4596 goto done;
4599 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4600 if (err)
4601 goto done;
4603 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4604 refs_str ? refs_str : "", refs_str ? ")" : "");
4605 if (n < 0) {
4606 err = got_error_from_errno("fprintf");
4607 goto done;
4609 outoff += n;
4610 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4611 if (err)
4612 goto done;
4614 n = fprintf(outfile, "from: %s\n",
4615 got_object_commit_get_author(commit));
4616 if (n < 0) {
4617 err = got_error_from_errno("fprintf");
4618 goto done;
4620 outoff += n;
4621 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4622 if (err)
4623 goto done;
4625 author = got_object_commit_get_author(commit);
4626 committer = got_object_commit_get_committer(commit);
4627 if (strcmp(author, committer) != 0) {
4628 n = fprintf(outfile, "via: %s\n", committer);
4629 if (n < 0) {
4630 err = got_error_from_errno("fprintf");
4631 goto done;
4633 outoff += n;
4634 err = add_line_metadata(lines, nlines, outoff,
4635 GOT_DIFF_LINE_AUTHOR);
4636 if (err)
4637 goto done;
4639 committer_time = got_object_commit_get_committer_time(commit);
4640 datestr = get_datestr(&committer_time, datebuf);
4641 if (datestr) {
4642 n = fprintf(outfile, "date: %s UTC\n", datestr);
4643 if (n < 0) {
4644 err = got_error_from_errno("fprintf");
4645 goto done;
4647 outoff += n;
4648 err = add_line_metadata(lines, nlines, outoff,
4649 GOT_DIFF_LINE_DATE);
4650 if (err)
4651 goto done;
4653 if (got_object_commit_get_nparents(commit) > 1) {
4654 const struct got_object_id_queue *parent_ids;
4655 struct got_object_qid *qid;
4656 int pn = 1;
4657 parent_ids = got_object_commit_get_parent_ids(commit);
4658 STAILQ_FOREACH(qid, parent_ids, entry) {
4659 err = got_object_id_str(&id_str, &qid->id);
4660 if (err)
4661 goto done;
4662 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4663 if (n < 0) {
4664 err = got_error_from_errno("fprintf");
4665 goto done;
4667 outoff += n;
4668 err = add_line_metadata(lines, nlines, outoff,
4669 GOT_DIFF_LINE_META);
4670 if (err)
4671 goto done;
4672 free(id_str);
4673 id_str = NULL;
4677 err = got_object_commit_get_logmsg(&logmsg, commit);
4678 if (err)
4679 goto done;
4680 s = logmsg;
4681 while ((line = strsep(&s, "\n")) != NULL) {
4682 n = fprintf(outfile, "%s\n", line);
4683 if (n < 0) {
4684 err = got_error_from_errno("fprintf");
4685 goto done;
4687 outoff += n;
4688 err = add_line_metadata(lines, nlines, outoff,
4689 GOT_DIFF_LINE_LOGMSG);
4690 if (err)
4691 goto done;
4694 err = get_changed_paths(&changed_paths, commit, repo, &dsa);
4695 if (err)
4696 goto done;
4698 TAILQ_FOREACH(pe, &changed_paths, entry) {
4699 struct got_diff_changed_path *cp = pe->data;
4700 int pad = dsa.max_path_len - pe->path_len + 1;
4702 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4703 pe->path, pad, ' ', dsa.add_cols + 1, cp->add,
4704 dsa.rm_cols + 1, cp->rm);
4705 if (n < 0) {
4706 err = got_error_from_errno("fprintf");
4707 goto done;
4709 outoff += n;
4710 err = add_line_metadata(lines, nlines, outoff,
4711 GOT_DIFF_LINE_CHANGES);
4712 if (err)
4713 goto done;
4716 fputc('\n', outfile);
4717 outoff++;
4718 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4719 if (err)
4720 goto done;
4722 n = fprintf(outfile,
4723 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4724 dsa.nfiles, dsa.nfiles > 1 ? "s" : "", dsa.ins,
4725 dsa.ins != 1 ? "s" : "", dsa.del, dsa.del != 1 ? "s" : "");
4726 if (n < 0) {
4727 err = got_error_from_errno("fprintf");
4728 goto done;
4730 outoff += n;
4731 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4732 if (err)
4733 goto done;
4735 fputc('\n', outfile);
4736 outoff++;
4737 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4738 done:
4739 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4740 free(id_str);
4741 free(logmsg);
4742 free(refs_str);
4743 got_object_commit_close(commit);
4744 if (err) {
4745 free(*lines);
4746 *lines = NULL;
4747 *nlines = 0;
4749 return err;
4752 static const struct got_error *
4753 create_diff(struct tog_diff_view_state *s)
4755 const struct got_error *err = NULL;
4756 FILE *f = NULL;
4757 int obj_type;
4759 free(s->lines);
4760 s->lines = malloc(sizeof(*s->lines));
4761 if (s->lines == NULL)
4762 return got_error_from_errno("malloc");
4763 s->nlines = 0;
4765 f = got_opentemp();
4766 if (f == NULL) {
4767 err = got_error_from_errno("got_opentemp");
4768 goto done;
4770 if (s->f && fclose(s->f) == EOF) {
4771 err = got_error_from_errno("fclose");
4772 goto done;
4774 s->f = f;
4776 if (s->id1)
4777 err = got_object_get_type(&obj_type, s->repo, s->id1);
4778 else
4779 err = got_object_get_type(&obj_type, s->repo, s->id2);
4780 if (err)
4781 goto done;
4783 switch (obj_type) {
4784 case GOT_OBJ_TYPE_BLOB:
4785 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4786 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4787 s->label1, s->label2, tog_diff_algo, s->diff_context,
4788 s->ignore_whitespace, s->force_text_diff, 0, NULL, s->repo,
4789 s->f);
4790 break;
4791 case GOT_OBJ_TYPE_TREE:
4792 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4793 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4794 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4795 s->force_text_diff, 0, NULL, s->repo, s->f);
4796 break;
4797 case GOT_OBJ_TYPE_COMMIT: {
4798 const struct got_object_id_queue *parent_ids;
4799 struct got_object_qid *pid;
4800 struct got_commit_object *commit2;
4801 struct got_reflist_head *refs;
4803 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4804 if (err)
4805 goto done;
4806 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4807 /* Show commit info if we're diffing to a parent/root commit. */
4808 if (s->id1 == NULL) {
4809 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4810 refs, s->repo, s->ignore_whitespace,
4811 s->force_text_diff, s->f);
4812 if (err)
4813 goto done;
4814 } else {
4815 parent_ids = got_object_commit_get_parent_ids(commit2);
4816 STAILQ_FOREACH(pid, parent_ids, entry) {
4817 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4818 err = write_commit_info(&s->lines,
4819 &s->nlines, s->id2, refs, s->repo,
4820 s->ignore_whitespace,
4821 s->force_text_diff, s->f);
4822 if (err)
4823 goto done;
4824 break;
4828 got_object_commit_close(commit2);
4830 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4831 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4832 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4833 s->force_text_diff, 0, NULL, s->repo, s->f);
4834 break;
4836 default:
4837 err = got_error(GOT_ERR_OBJ_TYPE);
4838 break;
4840 done:
4841 if (s->f && fflush(s->f) != 0 && err == NULL)
4842 err = got_error_from_errno("fflush");
4843 return err;
4846 static void
4847 diff_view_indicate_progress(struct tog_view *view)
4849 mvwaddstr(view->window, 0, 0, "diffing...");
4850 update_panels();
4851 doupdate();
4854 static const struct got_error *
4855 search_start_diff_view(struct tog_view *view)
4857 struct tog_diff_view_state *s = &view->state.diff;
4859 s->matched_line = 0;
4860 return NULL;
4863 static void
4864 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4865 size_t *nlines, int **first, int **last, int **match, int **selected)
4867 struct tog_diff_view_state *s = &view->state.diff;
4869 *f = s->f;
4870 *nlines = s->nlines;
4871 *line_offsets = NULL;
4872 *match = &s->matched_line;
4873 *first = &s->first_displayed_line;
4874 *last = &s->last_displayed_line;
4875 *selected = &s->selected_line;
4878 static const struct got_error *
4879 search_next_view_match(struct tog_view *view)
4881 const struct got_error *err = NULL;
4882 FILE *f;
4883 int lineno;
4884 char *line = NULL;
4885 size_t linesize = 0;
4886 ssize_t linelen;
4887 off_t *line_offsets;
4888 size_t nlines = 0;
4889 int *first, *last, *match, *selected;
4891 if (!view->search_setup)
4892 return got_error_msg(GOT_ERR_NOT_IMPL,
4893 "view search not supported");
4894 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4895 &match, &selected);
4897 if (!view->searching) {
4898 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4899 return NULL;
4902 if (*match) {
4903 if (view->searching == TOG_SEARCH_FORWARD)
4904 lineno = *match + 1;
4905 else
4906 lineno = *match - 1;
4907 } else
4908 lineno = *first - 1 + *selected;
4910 while (1) {
4911 off_t offset;
4913 if (lineno <= 0 || lineno > nlines) {
4914 if (*match == 0) {
4915 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4916 break;
4919 if (view->searching == TOG_SEARCH_FORWARD)
4920 lineno = 1;
4921 else
4922 lineno = nlines;
4925 offset = view->type == TOG_VIEW_DIFF ?
4926 view->state.diff.lines[lineno - 1].offset :
4927 line_offsets[lineno - 1];
4928 if (fseeko(f, offset, SEEK_SET) != 0) {
4929 free(line);
4930 return got_error_from_errno("fseeko");
4932 linelen = getline(&line, &linesize, f);
4933 if (linelen != -1) {
4934 char *exstr;
4935 err = expand_tab(&exstr, line);
4936 if (err)
4937 break;
4938 if (match_line(exstr, &view->regex, 1,
4939 &view->regmatch)) {
4940 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4941 *match = lineno;
4942 free(exstr);
4943 break;
4945 free(exstr);
4947 if (view->searching == TOG_SEARCH_FORWARD)
4948 lineno++;
4949 else
4950 lineno--;
4952 free(line);
4954 if (*match) {
4955 *first = *match;
4956 *selected = 1;
4959 return err;
4962 static const struct got_error *
4963 close_diff_view(struct tog_view *view)
4965 const struct got_error *err = NULL;
4966 struct tog_diff_view_state *s = &view->state.diff;
4968 free(s->id1);
4969 s->id1 = NULL;
4970 free(s->id2);
4971 s->id2 = NULL;
4972 if (s->f && fclose(s->f) == EOF)
4973 err = got_error_from_errno("fclose");
4974 s->f = NULL;
4975 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4976 err = got_error_from_errno("fclose");
4977 s->f1 = NULL;
4978 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4979 err = got_error_from_errno("fclose");
4980 s->f2 = NULL;
4981 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4982 err = got_error_from_errno("close");
4983 s->fd1 = -1;
4984 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4985 err = got_error_from_errno("close");
4986 s->fd2 = -1;
4987 free(s->lines);
4988 s->lines = NULL;
4989 s->nlines = 0;
4990 return err;
4993 static const struct got_error *
4994 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4995 struct got_object_id *id2, const char *label1, const char *label2,
4996 int diff_context, int ignore_whitespace, int force_text_diff,
4997 struct tog_view *parent_view, struct got_repository *repo)
4999 const struct got_error *err;
5000 struct tog_diff_view_state *s = &view->state.diff;
5002 memset(s, 0, sizeof(*s));
5003 s->fd1 = -1;
5004 s->fd2 = -1;
5006 if (id1 != NULL && id2 != NULL) {
5007 int type1, type2;
5008 err = got_object_get_type(&type1, repo, id1);
5009 if (err)
5010 return err;
5011 err = got_object_get_type(&type2, repo, id2);
5012 if (err)
5013 return err;
5015 if (type1 != type2)
5016 return got_error(GOT_ERR_OBJ_TYPE);
5018 s->first_displayed_line = 1;
5019 s->last_displayed_line = view->nlines;
5020 s->selected_line = 1;
5021 s->repo = repo;
5022 s->id1 = id1;
5023 s->id2 = id2;
5024 s->label1 = label1;
5025 s->label2 = label2;
5027 if (id1) {
5028 s->id1 = got_object_id_dup(id1);
5029 if (s->id1 == NULL)
5030 return got_error_from_errno("got_object_id_dup");
5031 } else
5032 s->id1 = NULL;
5034 s->id2 = got_object_id_dup(id2);
5035 if (s->id2 == NULL) {
5036 err = got_error_from_errno("got_object_id_dup");
5037 goto done;
5040 s->f1 = got_opentemp();
5041 if (s->f1 == NULL) {
5042 err = got_error_from_errno("got_opentemp");
5043 goto done;
5046 s->f2 = got_opentemp();
5047 if (s->f2 == NULL) {
5048 err = got_error_from_errno("got_opentemp");
5049 goto done;
5052 s->fd1 = got_opentempfd();
5053 if (s->fd1 == -1) {
5054 err = got_error_from_errno("got_opentempfd");
5055 goto done;
5058 s->fd2 = got_opentempfd();
5059 if (s->fd2 == -1) {
5060 err = got_error_from_errno("got_opentempfd");
5061 goto done;
5064 s->diff_context = diff_context;
5065 s->ignore_whitespace = ignore_whitespace;
5066 s->force_text_diff = force_text_diff;
5067 s->parent_view = parent_view;
5068 s->repo = repo;
5070 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5071 int rc;
5073 rc = init_pair(GOT_DIFF_LINE_MINUS,
5074 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5075 if (rc != ERR)
5076 rc = init_pair(GOT_DIFF_LINE_PLUS,
5077 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5078 if (rc != ERR)
5079 rc = init_pair(GOT_DIFF_LINE_HUNK,
5080 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5081 if (rc != ERR)
5082 rc = init_pair(GOT_DIFF_LINE_META,
5083 get_color_value("TOG_COLOR_DIFF_META"), -1);
5084 if (rc != ERR)
5085 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5086 get_color_value("TOG_COLOR_DIFF_META"), -1);
5087 if (rc != ERR)
5088 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5089 get_color_value("TOG_COLOR_DIFF_META"), -1);
5090 if (rc != ERR)
5091 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5092 get_color_value("TOG_COLOR_DIFF_META"), -1);
5093 if (rc != ERR)
5094 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5095 get_color_value("TOG_COLOR_AUTHOR"), -1);
5096 if (rc != ERR)
5097 rc = init_pair(GOT_DIFF_LINE_DATE,
5098 get_color_value("TOG_COLOR_DATE"), -1);
5099 if (rc == ERR) {
5100 err = got_error(GOT_ERR_RANGE);
5101 goto done;
5105 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5106 view_is_splitscreen(view))
5107 show_log_view(parent_view); /* draw border */
5108 diff_view_indicate_progress(view);
5110 err = create_diff(s);
5112 view->show = show_diff_view;
5113 view->input = input_diff_view;
5114 view->reset = reset_diff_view;
5115 view->close = close_diff_view;
5116 view->search_start = search_start_diff_view;
5117 view->search_setup = search_setup_diff_view;
5118 view->search_next = search_next_view_match;
5119 done:
5120 if (err)
5121 close_diff_view(view);
5122 return err;
5125 static const struct got_error *
5126 show_diff_view(struct tog_view *view)
5128 const struct got_error *err;
5129 struct tog_diff_view_state *s = &view->state.diff;
5130 char *id_str1 = NULL, *id_str2, *header;
5131 const char *label1, *label2;
5133 if (s->id1) {
5134 err = got_object_id_str(&id_str1, s->id1);
5135 if (err)
5136 return err;
5137 label1 = s->label1 ? s->label1 : id_str1;
5138 } else
5139 label1 = "/dev/null";
5141 err = got_object_id_str(&id_str2, s->id2);
5142 if (err)
5143 return err;
5144 label2 = s->label2 ? s->label2 : id_str2;
5146 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5147 err = got_error_from_errno("asprintf");
5148 free(id_str1);
5149 free(id_str2);
5150 return err;
5152 free(id_str1);
5153 free(id_str2);
5155 err = draw_file(view, header);
5156 free(header);
5157 return err;
5160 static const struct got_error *
5161 set_selected_commit(struct tog_diff_view_state *s,
5162 struct commit_queue_entry *entry)
5164 const struct got_error *err;
5165 const struct got_object_id_queue *parent_ids;
5166 struct got_commit_object *selected_commit;
5167 struct got_object_qid *pid;
5169 free(s->id2);
5170 s->id2 = got_object_id_dup(entry->id);
5171 if (s->id2 == NULL)
5172 return got_error_from_errno("got_object_id_dup");
5174 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5175 if (err)
5176 return err;
5177 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5178 free(s->id1);
5179 pid = STAILQ_FIRST(parent_ids);
5180 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5181 got_object_commit_close(selected_commit);
5182 return NULL;
5185 static const struct got_error *
5186 reset_diff_view(struct tog_view *view)
5188 struct tog_diff_view_state *s = &view->state.diff;
5190 view->count = 0;
5191 wclear(view->window);
5192 s->first_displayed_line = 1;
5193 s->last_displayed_line = view->nlines;
5194 s->matched_line = 0;
5195 diff_view_indicate_progress(view);
5196 return create_diff(s);
5199 static void
5200 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5202 int start, i;
5204 i = start = s->first_displayed_line - 1;
5206 while (s->lines[i].type != type) {
5207 if (i == 0)
5208 i = s->nlines - 1;
5209 if (--i == start)
5210 return; /* do nothing, requested type not in file */
5213 s->selected_line = 1;
5214 s->first_displayed_line = i;
5217 static void
5218 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5220 int start, i;
5222 i = start = s->first_displayed_line + 1;
5224 while (s->lines[i].type != type) {
5225 if (i == s->nlines - 1)
5226 i = 0;
5227 if (++i == start)
5228 return; /* do nothing, requested type not in file */
5231 s->selected_line = 1;
5232 s->first_displayed_line = i;
5235 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5236 int, int, int);
5237 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5238 int, int);
5240 static const struct got_error *
5241 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5243 const struct got_error *err = NULL;
5244 struct tog_diff_view_state *s = &view->state.diff;
5245 struct tog_log_view_state *ls;
5246 struct commit_queue_entry *old_selected_entry;
5247 char *line = NULL;
5248 size_t linesize = 0;
5249 ssize_t linelen;
5250 int i, nscroll = view->nlines - 1, up = 0;
5252 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5254 switch (ch) {
5255 case '0':
5256 view->x = 0;
5257 break;
5258 case '$':
5259 view->x = MAX(view->maxx - view->ncols / 3, 0);
5260 view->count = 0;
5261 break;
5262 case KEY_RIGHT:
5263 case 'l':
5264 if (view->x + view->ncols / 3 < view->maxx)
5265 view->x += 2; /* move two columns right */
5266 else
5267 view->count = 0;
5268 break;
5269 case KEY_LEFT:
5270 case 'h':
5271 view->x -= MIN(view->x, 2); /* move two columns back */
5272 if (view->x <= 0)
5273 view->count = 0;
5274 break;
5275 case 'a':
5276 case 'w':
5277 if (ch == 'a')
5278 s->force_text_diff = !s->force_text_diff;
5279 else if (ch == 'w')
5280 s->ignore_whitespace = !s->ignore_whitespace;
5281 err = reset_diff_view(view);
5282 break;
5283 case 'g':
5284 case KEY_HOME:
5285 s->first_displayed_line = 1;
5286 view->count = 0;
5287 break;
5288 case 'G':
5289 case KEY_END:
5290 view->count = 0;
5291 if (s->eof)
5292 break;
5294 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5295 s->eof = 1;
5296 break;
5297 case 'k':
5298 case KEY_UP:
5299 case CTRL('p'):
5300 if (s->first_displayed_line > 1)
5301 s->first_displayed_line--;
5302 else
5303 view->count = 0;
5304 break;
5305 case CTRL('u'):
5306 case 'u':
5307 nscroll /= 2;
5308 /* FALL THROUGH */
5309 case KEY_PPAGE:
5310 case CTRL('b'):
5311 case 'b':
5312 if (s->first_displayed_line == 1) {
5313 view->count = 0;
5314 break;
5316 i = 0;
5317 while (i++ < nscroll && s->first_displayed_line > 1)
5318 s->first_displayed_line--;
5319 break;
5320 case 'j':
5321 case KEY_DOWN:
5322 case CTRL('n'):
5323 if (!s->eof)
5324 s->first_displayed_line++;
5325 else
5326 view->count = 0;
5327 break;
5328 case CTRL('d'):
5329 case 'd':
5330 nscroll /= 2;
5331 /* FALL THROUGH */
5332 case KEY_NPAGE:
5333 case CTRL('f'):
5334 case 'f':
5335 case ' ':
5336 if (s->eof) {
5337 view->count = 0;
5338 break;
5340 i = 0;
5341 while (!s->eof && i++ < nscroll) {
5342 linelen = getline(&line, &linesize, s->f);
5343 s->first_displayed_line++;
5344 if (linelen == -1) {
5345 if (feof(s->f)) {
5346 s->eof = 1;
5347 } else
5348 err = got_ferror(s->f, GOT_ERR_IO);
5349 break;
5352 free(line);
5353 break;
5354 case '(':
5355 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5356 break;
5357 case ')':
5358 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5359 break;
5360 case '{':
5361 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5362 break;
5363 case '}':
5364 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5365 break;
5366 case '[':
5367 if (s->diff_context > 0) {
5368 s->diff_context--;
5369 s->matched_line = 0;
5370 diff_view_indicate_progress(view);
5371 err = create_diff(s);
5372 if (s->first_displayed_line + view->nlines - 1 >
5373 s->nlines) {
5374 s->first_displayed_line = 1;
5375 s->last_displayed_line = view->nlines;
5377 } else
5378 view->count = 0;
5379 break;
5380 case ']':
5381 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5382 s->diff_context++;
5383 s->matched_line = 0;
5384 diff_view_indicate_progress(view);
5385 err = create_diff(s);
5386 } else
5387 view->count = 0;
5388 break;
5389 case '<':
5390 case ',':
5391 case 'K':
5392 up = 1;
5393 /* FALL THROUGH */
5394 case '>':
5395 case '.':
5396 case 'J':
5397 if (s->parent_view == NULL) {
5398 view->count = 0;
5399 break;
5401 s->parent_view->count = view->count;
5403 if (s->parent_view->type == TOG_VIEW_LOG) {
5404 ls = &s->parent_view->state.log;
5405 old_selected_entry = ls->selected_entry;
5407 err = input_log_view(NULL, s->parent_view,
5408 up ? KEY_UP : KEY_DOWN);
5409 if (err)
5410 break;
5411 view->count = s->parent_view->count;
5413 if (old_selected_entry == ls->selected_entry)
5414 break;
5416 err = set_selected_commit(s, ls->selected_entry);
5417 if (err)
5418 break;
5419 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5420 struct tog_blame_view_state *bs;
5421 struct got_object_id *id, *prev_id;
5423 bs = &s->parent_view->state.blame;
5424 prev_id = get_annotation_for_line(bs->blame.lines,
5425 bs->blame.nlines, bs->last_diffed_line);
5427 err = input_blame_view(&view, s->parent_view,
5428 up ? KEY_UP : KEY_DOWN);
5429 if (err)
5430 break;
5431 view->count = s->parent_view->count;
5433 if (prev_id == NULL)
5434 break;
5435 id = get_selected_commit_id(bs->blame.lines,
5436 bs->blame.nlines, bs->first_displayed_line,
5437 bs->selected_line);
5438 if (id == NULL)
5439 break;
5441 if (!got_object_id_cmp(prev_id, id))
5442 break;
5444 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5445 if (err)
5446 break;
5448 s->first_displayed_line = 1;
5449 s->last_displayed_line = view->nlines;
5450 s->matched_line = 0;
5451 view->x = 0;
5453 diff_view_indicate_progress(view);
5454 err = create_diff(s);
5455 break;
5456 default:
5457 view->count = 0;
5458 break;
5461 return err;
5464 static const struct got_error *
5465 cmd_diff(int argc, char *argv[])
5467 const struct got_error *error = NULL;
5468 struct got_repository *repo = NULL;
5469 struct got_worktree *worktree = NULL;
5470 struct got_object_id *id1 = NULL, *id2 = NULL;
5471 char *repo_path = NULL, *cwd = NULL;
5472 char *id_str1 = NULL, *id_str2 = NULL;
5473 char *label1 = NULL, *label2 = NULL;
5474 int diff_context = 3, ignore_whitespace = 0;
5475 int ch, force_text_diff = 0;
5476 const char *errstr;
5477 struct tog_view *view;
5478 int *pack_fds = NULL;
5480 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5481 switch (ch) {
5482 case 'a':
5483 force_text_diff = 1;
5484 break;
5485 case 'C':
5486 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5487 &errstr);
5488 if (errstr != NULL)
5489 errx(1, "number of context lines is %s: %s",
5490 errstr, errstr);
5491 break;
5492 case 'r':
5493 repo_path = realpath(optarg, NULL);
5494 if (repo_path == NULL)
5495 return got_error_from_errno2("realpath",
5496 optarg);
5497 got_path_strip_trailing_slashes(repo_path);
5498 break;
5499 case 'w':
5500 ignore_whitespace = 1;
5501 break;
5502 default:
5503 usage_diff();
5504 /* NOTREACHED */
5508 argc -= optind;
5509 argv += optind;
5511 if (argc == 0) {
5512 usage_diff(); /* TODO show local worktree changes */
5513 } else if (argc == 2) {
5514 id_str1 = argv[0];
5515 id_str2 = argv[1];
5516 } else
5517 usage_diff();
5519 error = got_repo_pack_fds_open(&pack_fds);
5520 if (error)
5521 goto done;
5523 if (repo_path == NULL) {
5524 cwd = getcwd(NULL, 0);
5525 if (cwd == NULL)
5526 return got_error_from_errno("getcwd");
5527 error = got_worktree_open(&worktree, cwd);
5528 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5529 goto done;
5530 if (worktree)
5531 repo_path =
5532 strdup(got_worktree_get_repo_path(worktree));
5533 else
5534 repo_path = strdup(cwd);
5535 if (repo_path == NULL) {
5536 error = got_error_from_errno("strdup");
5537 goto done;
5541 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5542 if (error)
5543 goto done;
5545 init_curses();
5547 error = apply_unveil(got_repo_get_path(repo), NULL);
5548 if (error)
5549 goto done;
5551 error = tog_load_refs(repo, 0);
5552 if (error)
5553 goto done;
5555 error = got_repo_match_object_id(&id1, &label1, id_str1,
5556 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5557 if (error)
5558 goto done;
5560 error = got_repo_match_object_id(&id2, &label2, id_str2,
5561 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5562 if (error)
5563 goto done;
5565 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5566 if (view == NULL) {
5567 error = got_error_from_errno("view_open");
5568 goto done;
5570 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5571 ignore_whitespace, force_text_diff, NULL, repo);
5572 if (error)
5573 goto done;
5574 error = view_loop(view);
5575 done:
5576 free(label1);
5577 free(label2);
5578 free(repo_path);
5579 free(cwd);
5580 if (repo) {
5581 const struct got_error *close_err = got_repo_close(repo);
5582 if (error == NULL)
5583 error = close_err;
5585 if (worktree)
5586 got_worktree_close(worktree);
5587 if (pack_fds) {
5588 const struct got_error *pack_err =
5589 got_repo_pack_fds_close(pack_fds);
5590 if (error == NULL)
5591 error = pack_err;
5593 tog_free_refs();
5594 return error;
5597 __dead static void
5598 usage_blame(void)
5600 endwin();
5601 fprintf(stderr,
5602 "usage: %s blame [-c commit] [-r repository-path] path\n",
5603 getprogname());
5604 exit(1);
5607 struct tog_blame_line {
5608 int annotated;
5609 struct got_object_id *id;
5612 static const struct got_error *
5613 draw_blame(struct tog_view *view)
5615 struct tog_blame_view_state *s = &view->state.blame;
5616 struct tog_blame *blame = &s->blame;
5617 regmatch_t *regmatch = &view->regmatch;
5618 const struct got_error *err;
5619 int lineno = 0, nprinted = 0;
5620 char *line = NULL;
5621 size_t linesize = 0;
5622 ssize_t linelen;
5623 wchar_t *wline;
5624 int width;
5625 struct tog_blame_line *blame_line;
5626 struct got_object_id *prev_id = NULL;
5627 char *id_str;
5628 struct tog_color *tc;
5630 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5631 if (err)
5632 return err;
5634 rewind(blame->f);
5635 werase(view->window);
5637 if (asprintf(&line, "commit %s", id_str) == -1) {
5638 err = got_error_from_errno("asprintf");
5639 free(id_str);
5640 return err;
5643 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5644 free(line);
5645 line = NULL;
5646 if (err)
5647 return err;
5648 if (view_needs_focus_indication(view))
5649 wstandout(view->window);
5650 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5651 if (tc)
5652 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5653 waddwstr(view->window, wline);
5654 while (width++ < view->ncols)
5655 waddch(view->window, ' ');
5656 if (tc)
5657 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5658 if (view_needs_focus_indication(view))
5659 wstandend(view->window);
5660 free(wline);
5661 wline = NULL;
5663 if (view->gline > blame->nlines)
5664 view->gline = blame->nlines;
5666 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5667 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5668 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5669 free(id_str);
5670 return got_error_from_errno("asprintf");
5672 free(id_str);
5673 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5674 free(line);
5675 line = NULL;
5676 if (err)
5677 return err;
5678 waddwstr(view->window, wline);
5679 free(wline);
5680 wline = NULL;
5681 if (width < view->ncols - 1)
5682 waddch(view->window, '\n');
5684 s->eof = 0;
5685 view->maxx = 0;
5686 while (nprinted < view->nlines - 2) {
5687 linelen = getline(&line, &linesize, blame->f);
5688 if (linelen == -1) {
5689 if (feof(blame->f)) {
5690 s->eof = 1;
5691 break;
5693 free(line);
5694 return got_ferror(blame->f, GOT_ERR_IO);
5696 if (++lineno < s->first_displayed_line)
5697 continue;
5698 if (view->gline && !gotoline(view, &lineno, &nprinted))
5699 continue;
5701 /* Set view->maxx based on full line length. */
5702 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5703 if (err) {
5704 free(line);
5705 return err;
5707 free(wline);
5708 wline = NULL;
5709 view->maxx = MAX(view->maxx, width);
5711 if (nprinted == s->selected_line - 1)
5712 wstandout(view->window);
5714 if (blame->nlines > 0) {
5715 blame_line = &blame->lines[lineno - 1];
5716 if (blame_line->annotated && prev_id &&
5717 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5718 !(nprinted == s->selected_line - 1)) {
5719 waddstr(view->window, " ");
5720 } else if (blame_line->annotated) {
5721 char *id_str;
5722 err = got_object_id_str(&id_str,
5723 blame_line->id);
5724 if (err) {
5725 free(line);
5726 return err;
5728 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5729 if (tc)
5730 wattr_on(view->window,
5731 COLOR_PAIR(tc->colorpair), NULL);
5732 wprintw(view->window, "%.8s", id_str);
5733 if (tc)
5734 wattr_off(view->window,
5735 COLOR_PAIR(tc->colorpair), NULL);
5736 free(id_str);
5737 prev_id = blame_line->id;
5738 } else {
5739 waddstr(view->window, "........");
5740 prev_id = NULL;
5742 } else {
5743 waddstr(view->window, "........");
5744 prev_id = NULL;
5747 if (nprinted == s->selected_line - 1)
5748 wstandend(view->window);
5749 waddstr(view->window, " ");
5751 if (view->ncols <= 9) {
5752 width = 9;
5753 } else if (s->first_displayed_line + nprinted ==
5754 s->matched_line &&
5755 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5756 err = add_matched_line(&width, line, view->ncols - 9, 9,
5757 view->window, view->x, regmatch);
5758 if (err) {
5759 free(line);
5760 return err;
5762 width += 9;
5763 } else {
5764 int skip;
5765 err = format_line(&wline, &width, &skip, line,
5766 view->x, view->ncols - 9, 9, 1);
5767 if (err) {
5768 free(line);
5769 return err;
5771 waddwstr(view->window, &wline[skip]);
5772 width += 9;
5773 free(wline);
5774 wline = NULL;
5777 if (width <= view->ncols - 1)
5778 waddch(view->window, '\n');
5779 if (++nprinted == 1)
5780 s->first_displayed_line = lineno;
5782 free(line);
5783 s->last_displayed_line = lineno;
5785 view_border(view);
5787 return NULL;
5790 static const struct got_error *
5791 blame_cb(void *arg, int nlines, int lineno,
5792 struct got_commit_object *commit, struct got_object_id *id)
5794 const struct got_error *err = NULL;
5795 struct tog_blame_cb_args *a = arg;
5796 struct tog_blame_line *line;
5797 int errcode;
5799 if (nlines != a->nlines ||
5800 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5801 return got_error(GOT_ERR_RANGE);
5803 errcode = pthread_mutex_lock(&tog_mutex);
5804 if (errcode)
5805 return got_error_set_errno(errcode, "pthread_mutex_lock");
5807 if (*a->quit) { /* user has quit the blame view */
5808 err = got_error(GOT_ERR_ITER_COMPLETED);
5809 goto done;
5812 if (lineno == -1)
5813 goto done; /* no change in this commit */
5815 line = &a->lines[lineno - 1];
5816 if (line->annotated)
5817 goto done;
5819 line->id = got_object_id_dup(id);
5820 if (line->id == NULL) {
5821 err = got_error_from_errno("got_object_id_dup");
5822 goto done;
5824 line->annotated = 1;
5825 done:
5826 errcode = pthread_mutex_unlock(&tog_mutex);
5827 if (errcode)
5828 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5829 return err;
5832 static void *
5833 blame_thread(void *arg)
5835 const struct got_error *err, *close_err;
5836 struct tog_blame_thread_args *ta = arg;
5837 struct tog_blame_cb_args *a = ta->cb_args;
5838 int errcode, fd1 = -1, fd2 = -1;
5839 FILE *f1 = NULL, *f2 = NULL;
5841 fd1 = got_opentempfd();
5842 if (fd1 == -1)
5843 return (void *)got_error_from_errno("got_opentempfd");
5845 fd2 = got_opentempfd();
5846 if (fd2 == -1) {
5847 err = got_error_from_errno("got_opentempfd");
5848 goto done;
5851 f1 = got_opentemp();
5852 if (f1 == NULL) {
5853 err = (void *)got_error_from_errno("got_opentemp");
5854 goto done;
5856 f2 = got_opentemp();
5857 if (f2 == NULL) {
5858 err = (void *)got_error_from_errno("got_opentemp");
5859 goto done;
5862 err = block_signals_used_by_main_thread();
5863 if (err)
5864 goto done;
5866 err = got_blame(ta->path, a->commit_id, ta->repo,
5867 tog_diff_algo, blame_cb, ta->cb_args,
5868 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5869 if (err && err->code == GOT_ERR_CANCELLED)
5870 err = NULL;
5872 errcode = pthread_mutex_lock(&tog_mutex);
5873 if (errcode) {
5874 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5875 goto done;
5878 close_err = got_repo_close(ta->repo);
5879 if (err == NULL)
5880 err = close_err;
5881 ta->repo = NULL;
5882 *ta->complete = 1;
5884 errcode = pthread_mutex_unlock(&tog_mutex);
5885 if (errcode && err == NULL)
5886 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5888 done:
5889 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5890 err = got_error_from_errno("close");
5891 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5892 err = got_error_from_errno("close");
5893 if (f1 && fclose(f1) == EOF && err == NULL)
5894 err = got_error_from_errno("fclose");
5895 if (f2 && fclose(f2) == EOF && err == NULL)
5896 err = got_error_from_errno("fclose");
5898 return (void *)err;
5901 static struct got_object_id *
5902 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5903 int first_displayed_line, int selected_line)
5905 struct tog_blame_line *line;
5907 if (nlines <= 0)
5908 return NULL;
5910 line = &lines[first_displayed_line - 1 + selected_line - 1];
5911 if (!line->annotated)
5912 return NULL;
5914 return line->id;
5917 static struct got_object_id *
5918 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5919 int lineno)
5921 struct tog_blame_line *line;
5923 if (nlines <= 0 || lineno >= nlines)
5924 return NULL;
5926 line = &lines[lineno - 1];
5927 if (!line->annotated)
5928 return NULL;
5930 return line->id;
5933 static const struct got_error *
5934 stop_blame(struct tog_blame *blame)
5936 const struct got_error *err = NULL;
5937 int i;
5939 if (blame->thread) {
5940 int errcode;
5941 errcode = pthread_mutex_unlock(&tog_mutex);
5942 if (errcode)
5943 return got_error_set_errno(errcode,
5944 "pthread_mutex_unlock");
5945 errcode = pthread_join(blame->thread, (void **)&err);
5946 if (errcode)
5947 return got_error_set_errno(errcode, "pthread_join");
5948 errcode = pthread_mutex_lock(&tog_mutex);
5949 if (errcode)
5950 return got_error_set_errno(errcode,
5951 "pthread_mutex_lock");
5952 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5953 err = NULL;
5954 blame->thread = NULL;
5956 if (blame->thread_args.repo) {
5957 const struct got_error *close_err;
5958 close_err = got_repo_close(blame->thread_args.repo);
5959 if (err == NULL)
5960 err = close_err;
5961 blame->thread_args.repo = NULL;
5963 if (blame->f) {
5964 if (fclose(blame->f) == EOF && err == NULL)
5965 err = got_error_from_errno("fclose");
5966 blame->f = NULL;
5968 if (blame->lines) {
5969 for (i = 0; i < blame->nlines; i++)
5970 free(blame->lines[i].id);
5971 free(blame->lines);
5972 blame->lines = NULL;
5974 free(blame->cb_args.commit_id);
5975 blame->cb_args.commit_id = NULL;
5976 if (blame->pack_fds) {
5977 const struct got_error *pack_err =
5978 got_repo_pack_fds_close(blame->pack_fds);
5979 if (err == NULL)
5980 err = pack_err;
5981 blame->pack_fds = NULL;
5983 return err;
5986 static const struct got_error *
5987 cancel_blame_view(void *arg)
5989 const struct got_error *err = NULL;
5990 int *done = arg;
5991 int errcode;
5993 errcode = pthread_mutex_lock(&tog_mutex);
5994 if (errcode)
5995 return got_error_set_errno(errcode,
5996 "pthread_mutex_unlock");
5998 if (*done)
5999 err = got_error(GOT_ERR_CANCELLED);
6001 errcode = pthread_mutex_unlock(&tog_mutex);
6002 if (errcode)
6003 return got_error_set_errno(errcode,
6004 "pthread_mutex_lock");
6006 return err;
6009 static const struct got_error *
6010 run_blame(struct tog_view *view)
6012 struct tog_blame_view_state *s = &view->state.blame;
6013 struct tog_blame *blame = &s->blame;
6014 const struct got_error *err = NULL;
6015 struct got_commit_object *commit = NULL;
6016 struct got_blob_object *blob = NULL;
6017 struct got_repository *thread_repo = NULL;
6018 struct got_object_id *obj_id = NULL;
6019 int obj_type, fd = -1;
6020 int *pack_fds = NULL;
6022 err = got_object_open_as_commit(&commit, s->repo,
6023 &s->blamed_commit->id);
6024 if (err)
6025 return err;
6027 fd = got_opentempfd();
6028 if (fd == -1) {
6029 err = got_error_from_errno("got_opentempfd");
6030 goto done;
6033 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6034 if (err)
6035 goto done;
6037 err = got_object_get_type(&obj_type, s->repo, obj_id);
6038 if (err)
6039 goto done;
6041 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6042 err = got_error(GOT_ERR_OBJ_TYPE);
6043 goto done;
6046 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6047 if (err)
6048 goto done;
6049 blame->f = got_opentemp();
6050 if (blame->f == NULL) {
6051 err = got_error_from_errno("got_opentemp");
6052 goto done;
6054 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6055 &blame->line_offsets, blame->f, blob);
6056 if (err)
6057 goto done;
6058 if (blame->nlines == 0) {
6059 s->blame_complete = 1;
6060 goto done;
6063 /* Don't include \n at EOF in the blame line count. */
6064 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6065 blame->nlines--;
6067 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6068 if (blame->lines == NULL) {
6069 err = got_error_from_errno("calloc");
6070 goto done;
6073 err = got_repo_pack_fds_open(&pack_fds);
6074 if (err)
6075 goto done;
6076 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6077 pack_fds);
6078 if (err)
6079 goto done;
6081 blame->pack_fds = pack_fds;
6082 blame->cb_args.view = view;
6083 blame->cb_args.lines = blame->lines;
6084 blame->cb_args.nlines = blame->nlines;
6085 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6086 if (blame->cb_args.commit_id == NULL) {
6087 err = got_error_from_errno("got_object_id_dup");
6088 goto done;
6090 blame->cb_args.quit = &s->done;
6092 blame->thread_args.path = s->path;
6093 blame->thread_args.repo = thread_repo;
6094 blame->thread_args.cb_args = &blame->cb_args;
6095 blame->thread_args.complete = &s->blame_complete;
6096 blame->thread_args.cancel_cb = cancel_blame_view;
6097 blame->thread_args.cancel_arg = &s->done;
6098 s->blame_complete = 0;
6100 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6101 s->first_displayed_line = 1;
6102 s->last_displayed_line = view->nlines;
6103 s->selected_line = 1;
6105 s->matched_line = 0;
6107 done:
6108 if (commit)
6109 got_object_commit_close(commit);
6110 if (fd != -1 && close(fd) == -1 && err == NULL)
6111 err = got_error_from_errno("close");
6112 if (blob)
6113 got_object_blob_close(blob);
6114 free(obj_id);
6115 if (err)
6116 stop_blame(blame);
6117 return err;
6120 static const struct got_error *
6121 open_blame_view(struct tog_view *view, char *path,
6122 struct got_object_id *commit_id, struct got_repository *repo)
6124 const struct got_error *err = NULL;
6125 struct tog_blame_view_state *s = &view->state.blame;
6127 STAILQ_INIT(&s->blamed_commits);
6129 s->path = strdup(path);
6130 if (s->path == NULL)
6131 return got_error_from_errno("strdup");
6133 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6134 if (err) {
6135 free(s->path);
6136 return err;
6139 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6140 s->first_displayed_line = 1;
6141 s->last_displayed_line = view->nlines;
6142 s->selected_line = 1;
6143 s->blame_complete = 0;
6144 s->repo = repo;
6145 s->commit_id = commit_id;
6146 memset(&s->blame, 0, sizeof(s->blame));
6148 STAILQ_INIT(&s->colors);
6149 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6150 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6151 get_color_value("TOG_COLOR_COMMIT"));
6152 if (err)
6153 return err;
6156 view->show = show_blame_view;
6157 view->input = input_blame_view;
6158 view->reset = reset_blame_view;
6159 view->close = close_blame_view;
6160 view->search_start = search_start_blame_view;
6161 view->search_setup = search_setup_blame_view;
6162 view->search_next = search_next_view_match;
6164 return run_blame(view);
6167 static const struct got_error *
6168 close_blame_view(struct tog_view *view)
6170 const struct got_error *err = NULL;
6171 struct tog_blame_view_state *s = &view->state.blame;
6173 if (s->blame.thread)
6174 err = stop_blame(&s->blame);
6176 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6177 struct got_object_qid *blamed_commit;
6178 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6179 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6180 got_object_qid_free(blamed_commit);
6183 free(s->path);
6184 free_colors(&s->colors);
6185 return err;
6188 static const struct got_error *
6189 search_start_blame_view(struct tog_view *view)
6191 struct tog_blame_view_state *s = &view->state.blame;
6193 s->matched_line = 0;
6194 return NULL;
6197 static void
6198 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6199 size_t *nlines, int **first, int **last, int **match, int **selected)
6201 struct tog_blame_view_state *s = &view->state.blame;
6203 *f = s->blame.f;
6204 *nlines = s->blame.nlines;
6205 *line_offsets = s->blame.line_offsets;
6206 *match = &s->matched_line;
6207 *first = &s->first_displayed_line;
6208 *last = &s->last_displayed_line;
6209 *selected = &s->selected_line;
6212 static const struct got_error *
6213 show_blame_view(struct tog_view *view)
6215 const struct got_error *err = NULL;
6216 struct tog_blame_view_state *s = &view->state.blame;
6217 int errcode;
6219 if (s->blame.thread == NULL && !s->blame_complete) {
6220 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6221 &s->blame.thread_args);
6222 if (errcode)
6223 return got_error_set_errno(errcode, "pthread_create");
6225 halfdelay(1); /* fast refresh while annotating */
6228 if (s->blame_complete)
6229 halfdelay(10); /* disable fast refresh */
6231 err = draw_blame(view);
6233 view_border(view);
6234 return err;
6237 static const struct got_error *
6238 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6239 struct got_repository *repo, struct got_object_id *id)
6241 struct tog_view *log_view;
6242 const struct got_error *err = NULL;
6244 *new_view = NULL;
6246 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6247 if (log_view == NULL)
6248 return got_error_from_errno("view_open");
6250 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6251 if (err)
6252 view_close(log_view);
6253 else
6254 *new_view = log_view;
6256 return err;
6259 static const struct got_error *
6260 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6262 const struct got_error *err = NULL, *thread_err = NULL;
6263 struct tog_view *diff_view;
6264 struct tog_blame_view_state *s = &view->state.blame;
6265 int eos, nscroll, begin_y = 0, begin_x = 0;
6267 eos = nscroll = view->nlines - 2;
6268 if (view_is_hsplit_top(view))
6269 --eos; /* border */
6271 switch (ch) {
6272 case '0':
6273 view->x = 0;
6274 break;
6275 case '$':
6276 view->x = MAX(view->maxx - view->ncols / 3, 0);
6277 view->count = 0;
6278 break;
6279 case KEY_RIGHT:
6280 case 'l':
6281 if (view->x + view->ncols / 3 < view->maxx)
6282 view->x += 2; /* move two columns right */
6283 else
6284 view->count = 0;
6285 break;
6286 case KEY_LEFT:
6287 case 'h':
6288 view->x -= MIN(view->x, 2); /* move two columns back */
6289 if (view->x <= 0)
6290 view->count = 0;
6291 break;
6292 case 'q':
6293 s->done = 1;
6294 break;
6295 case 'g':
6296 case KEY_HOME:
6297 s->selected_line = 1;
6298 s->first_displayed_line = 1;
6299 view->count = 0;
6300 break;
6301 case 'G':
6302 case KEY_END:
6303 if (s->blame.nlines < eos) {
6304 s->selected_line = s->blame.nlines;
6305 s->first_displayed_line = 1;
6306 } else {
6307 s->selected_line = eos;
6308 s->first_displayed_line = s->blame.nlines - (eos - 1);
6310 view->count = 0;
6311 break;
6312 case 'k':
6313 case KEY_UP:
6314 case CTRL('p'):
6315 if (s->selected_line > 1)
6316 s->selected_line--;
6317 else if (s->selected_line == 1 &&
6318 s->first_displayed_line > 1)
6319 s->first_displayed_line--;
6320 else
6321 view->count = 0;
6322 break;
6323 case CTRL('u'):
6324 case 'u':
6325 nscroll /= 2;
6326 /* FALL THROUGH */
6327 case KEY_PPAGE:
6328 case CTRL('b'):
6329 case 'b':
6330 if (s->first_displayed_line == 1) {
6331 if (view->count > 1)
6332 nscroll += nscroll;
6333 s->selected_line = MAX(1, s->selected_line - nscroll);
6334 view->count = 0;
6335 break;
6337 if (s->first_displayed_line > nscroll)
6338 s->first_displayed_line -= nscroll;
6339 else
6340 s->first_displayed_line = 1;
6341 break;
6342 case 'j':
6343 case KEY_DOWN:
6344 case CTRL('n'):
6345 if (s->selected_line < eos && s->first_displayed_line +
6346 s->selected_line <= s->blame.nlines)
6347 s->selected_line++;
6348 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6349 s->first_displayed_line++;
6350 else
6351 view->count = 0;
6352 break;
6353 case 'c':
6354 case 'p': {
6355 struct got_object_id *id = NULL;
6357 view->count = 0;
6358 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6359 s->first_displayed_line, s->selected_line);
6360 if (id == NULL)
6361 break;
6362 if (ch == 'p') {
6363 struct got_commit_object *commit, *pcommit;
6364 struct got_object_qid *pid;
6365 struct got_object_id *blob_id = NULL;
6366 int obj_type;
6367 err = got_object_open_as_commit(&commit,
6368 s->repo, id);
6369 if (err)
6370 break;
6371 pid = STAILQ_FIRST(
6372 got_object_commit_get_parent_ids(commit));
6373 if (pid == NULL) {
6374 got_object_commit_close(commit);
6375 break;
6377 /* Check if path history ends here. */
6378 err = got_object_open_as_commit(&pcommit,
6379 s->repo, &pid->id);
6380 if (err)
6381 break;
6382 err = got_object_id_by_path(&blob_id, s->repo,
6383 pcommit, s->path);
6384 got_object_commit_close(pcommit);
6385 if (err) {
6386 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6387 err = NULL;
6388 got_object_commit_close(commit);
6389 break;
6391 err = got_object_get_type(&obj_type, s->repo,
6392 blob_id);
6393 free(blob_id);
6394 /* Can't blame non-blob type objects. */
6395 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6396 got_object_commit_close(commit);
6397 break;
6399 err = got_object_qid_alloc(&s->blamed_commit,
6400 &pid->id);
6401 got_object_commit_close(commit);
6402 } else {
6403 if (got_object_id_cmp(id,
6404 &s->blamed_commit->id) == 0)
6405 break;
6406 err = got_object_qid_alloc(&s->blamed_commit,
6407 id);
6409 if (err)
6410 break;
6411 s->done = 1;
6412 thread_err = stop_blame(&s->blame);
6413 s->done = 0;
6414 if (thread_err)
6415 break;
6416 STAILQ_INSERT_HEAD(&s->blamed_commits,
6417 s->blamed_commit, entry);
6418 err = run_blame(view);
6419 if (err)
6420 break;
6421 break;
6423 case 'C': {
6424 struct got_object_qid *first;
6426 view->count = 0;
6427 first = STAILQ_FIRST(&s->blamed_commits);
6428 if (!got_object_id_cmp(&first->id, s->commit_id))
6429 break;
6430 s->done = 1;
6431 thread_err = stop_blame(&s->blame);
6432 s->done = 0;
6433 if (thread_err)
6434 break;
6435 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6436 got_object_qid_free(s->blamed_commit);
6437 s->blamed_commit =
6438 STAILQ_FIRST(&s->blamed_commits);
6439 err = run_blame(view);
6440 if (err)
6441 break;
6442 break;
6444 case 'L':
6445 view->count = 0;
6446 s->id_to_log = get_selected_commit_id(s->blame.lines,
6447 s->blame.nlines, s->first_displayed_line, s->selected_line);
6448 if (s->id_to_log)
6449 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6450 break;
6451 case KEY_ENTER:
6452 case '\r': {
6453 struct got_object_id *id = NULL;
6454 struct got_object_qid *pid;
6455 struct got_commit_object *commit = NULL;
6457 view->count = 0;
6458 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6459 s->first_displayed_line, s->selected_line);
6460 if (id == NULL)
6461 break;
6462 err = got_object_open_as_commit(&commit, s->repo, id);
6463 if (err)
6464 break;
6465 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6466 if (*new_view) {
6467 /* traversed from diff view, release diff resources */
6468 err = close_diff_view(*new_view);
6469 if (err)
6470 break;
6471 diff_view = *new_view;
6472 } else {
6473 if (view_is_parent_view(view))
6474 view_get_split(view, &begin_y, &begin_x);
6476 diff_view = view_open(0, 0, begin_y, begin_x,
6477 TOG_VIEW_DIFF);
6478 if (diff_view == NULL) {
6479 got_object_commit_close(commit);
6480 err = got_error_from_errno("view_open");
6481 break;
6484 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6485 id, NULL, NULL, 3, 0, 0, view, s->repo);
6486 got_object_commit_close(commit);
6487 if (err) {
6488 view_close(diff_view);
6489 break;
6491 s->last_diffed_line = s->first_displayed_line - 1 +
6492 s->selected_line;
6493 if (*new_view)
6494 break; /* still open from active diff view */
6495 if (view_is_parent_view(view) &&
6496 view->mode == TOG_VIEW_SPLIT_HRZN) {
6497 err = view_init_hsplit(view, begin_y);
6498 if (err)
6499 break;
6502 view->focussed = 0;
6503 diff_view->focussed = 1;
6504 diff_view->mode = view->mode;
6505 diff_view->nlines = view->lines - begin_y;
6506 if (view_is_parent_view(view)) {
6507 view_transfer_size(diff_view, view);
6508 err = view_close_child(view);
6509 if (err)
6510 break;
6511 err = view_set_child(view, diff_view);
6512 if (err)
6513 break;
6514 view->focus_child = 1;
6515 } else
6516 *new_view = diff_view;
6517 if (err)
6518 break;
6519 break;
6521 case CTRL('d'):
6522 case 'd':
6523 nscroll /= 2;
6524 /* FALL THROUGH */
6525 case KEY_NPAGE:
6526 case CTRL('f'):
6527 case 'f':
6528 case ' ':
6529 if (s->last_displayed_line >= s->blame.nlines &&
6530 s->selected_line >= MIN(s->blame.nlines,
6531 view->nlines - 2)) {
6532 view->count = 0;
6533 break;
6535 if (s->last_displayed_line >= s->blame.nlines &&
6536 s->selected_line < view->nlines - 2) {
6537 s->selected_line +=
6538 MIN(nscroll, s->last_displayed_line -
6539 s->first_displayed_line - s->selected_line + 1);
6541 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6542 s->first_displayed_line += nscroll;
6543 else
6544 s->first_displayed_line =
6545 s->blame.nlines - (view->nlines - 3);
6546 break;
6547 case KEY_RESIZE:
6548 if (s->selected_line > view->nlines - 2) {
6549 s->selected_line = MIN(s->blame.nlines,
6550 view->nlines - 2);
6552 break;
6553 default:
6554 view->count = 0;
6555 break;
6557 return thread_err ? thread_err : err;
6560 static const struct got_error *
6561 reset_blame_view(struct tog_view *view)
6563 const struct got_error *err;
6564 struct tog_blame_view_state *s = &view->state.blame;
6566 view->count = 0;
6567 s->done = 1;
6568 err = stop_blame(&s->blame);
6569 s->done = 0;
6570 if (err)
6571 return err;
6572 return run_blame(view);
6575 static const struct got_error *
6576 cmd_blame(int argc, char *argv[])
6578 const struct got_error *error;
6579 struct got_repository *repo = NULL;
6580 struct got_worktree *worktree = NULL;
6581 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6582 char *link_target = NULL;
6583 struct got_object_id *commit_id = NULL;
6584 struct got_commit_object *commit = NULL;
6585 char *commit_id_str = NULL;
6586 int ch;
6587 struct tog_view *view;
6588 int *pack_fds = NULL;
6590 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6591 switch (ch) {
6592 case 'c':
6593 commit_id_str = optarg;
6594 break;
6595 case 'r':
6596 repo_path = realpath(optarg, NULL);
6597 if (repo_path == NULL)
6598 return got_error_from_errno2("realpath",
6599 optarg);
6600 break;
6601 default:
6602 usage_blame();
6603 /* NOTREACHED */
6607 argc -= optind;
6608 argv += optind;
6610 if (argc != 1)
6611 usage_blame();
6613 error = got_repo_pack_fds_open(&pack_fds);
6614 if (error != NULL)
6615 goto done;
6617 if (repo_path == NULL) {
6618 cwd = getcwd(NULL, 0);
6619 if (cwd == NULL)
6620 return got_error_from_errno("getcwd");
6621 error = got_worktree_open(&worktree, cwd);
6622 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6623 goto done;
6624 if (worktree)
6625 repo_path =
6626 strdup(got_worktree_get_repo_path(worktree));
6627 else
6628 repo_path = strdup(cwd);
6629 if (repo_path == NULL) {
6630 error = got_error_from_errno("strdup");
6631 goto done;
6635 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6636 if (error != NULL)
6637 goto done;
6639 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6640 worktree);
6641 if (error)
6642 goto done;
6644 init_curses();
6646 error = apply_unveil(got_repo_get_path(repo), NULL);
6647 if (error)
6648 goto done;
6650 error = tog_load_refs(repo, 0);
6651 if (error)
6652 goto done;
6654 if (commit_id_str == NULL) {
6655 struct got_reference *head_ref;
6656 error = got_ref_open(&head_ref, repo, worktree ?
6657 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6658 if (error != NULL)
6659 goto done;
6660 error = got_ref_resolve(&commit_id, repo, head_ref);
6661 got_ref_close(head_ref);
6662 } else {
6663 error = got_repo_match_object_id(&commit_id, NULL,
6664 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6666 if (error != NULL)
6667 goto done;
6669 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6670 if (view == NULL) {
6671 error = got_error_from_errno("view_open");
6672 goto done;
6675 error = got_object_open_as_commit(&commit, repo, commit_id);
6676 if (error)
6677 goto done;
6679 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6680 commit, repo);
6681 if (error)
6682 goto done;
6684 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6685 commit_id, repo);
6686 if (error)
6687 goto done;
6688 if (worktree) {
6689 /* Release work tree lock. */
6690 got_worktree_close(worktree);
6691 worktree = NULL;
6693 error = view_loop(view);
6694 done:
6695 free(repo_path);
6696 free(in_repo_path);
6697 free(link_target);
6698 free(cwd);
6699 free(commit_id);
6700 if (commit)
6701 got_object_commit_close(commit);
6702 if (worktree)
6703 got_worktree_close(worktree);
6704 if (repo) {
6705 const struct got_error *close_err = got_repo_close(repo);
6706 if (error == NULL)
6707 error = close_err;
6709 if (pack_fds) {
6710 const struct got_error *pack_err =
6711 got_repo_pack_fds_close(pack_fds);
6712 if (error == NULL)
6713 error = pack_err;
6715 tog_free_refs();
6716 return error;
6719 static const struct got_error *
6720 draw_tree_entries(struct tog_view *view, const char *parent_path)
6722 struct tog_tree_view_state *s = &view->state.tree;
6723 const struct got_error *err = NULL;
6724 struct got_tree_entry *te;
6725 wchar_t *wline;
6726 char *index = NULL;
6727 struct tog_color *tc;
6728 int width, n, nentries, i = 1;
6729 int limit = view->nlines;
6731 s->ndisplayed = 0;
6732 if (view_is_hsplit_top(view))
6733 --limit; /* border */
6735 werase(view->window);
6737 if (limit == 0)
6738 return NULL;
6740 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6741 0, 0);
6742 if (err)
6743 return err;
6744 if (view_needs_focus_indication(view))
6745 wstandout(view->window);
6746 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6747 if (tc)
6748 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6749 waddwstr(view->window, wline);
6750 free(wline);
6751 wline = NULL;
6752 while (width++ < view->ncols)
6753 waddch(view->window, ' ');
6754 if (tc)
6755 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6756 if (view_needs_focus_indication(view))
6757 wstandend(view->window);
6758 if (--limit <= 0)
6759 return NULL;
6761 i += s->selected;
6762 if (s->first_displayed_entry) {
6763 i += got_tree_entry_get_index(s->first_displayed_entry);
6764 if (s->tree != s->root)
6765 ++i; /* account for ".." entry */
6767 nentries = got_object_tree_get_nentries(s->tree);
6768 if (asprintf(&index, "[%d/%d] %s",
6769 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6770 return got_error_from_errno("asprintf");
6771 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6772 free(index);
6773 if (err)
6774 return err;
6775 waddwstr(view->window, wline);
6776 free(wline);
6777 wline = NULL;
6778 if (width < view->ncols - 1)
6779 waddch(view->window, '\n');
6780 if (--limit <= 0)
6781 return NULL;
6782 waddch(view->window, '\n');
6783 if (--limit <= 0)
6784 return NULL;
6786 if (s->first_displayed_entry == NULL) {
6787 te = got_object_tree_get_first_entry(s->tree);
6788 if (s->selected == 0) {
6789 if (view->focussed)
6790 wstandout(view->window);
6791 s->selected_entry = NULL;
6793 waddstr(view->window, " ..\n"); /* parent directory */
6794 if (s->selected == 0 && view->focussed)
6795 wstandend(view->window);
6796 s->ndisplayed++;
6797 if (--limit <= 0)
6798 return NULL;
6799 n = 1;
6800 } else {
6801 n = 0;
6802 te = s->first_displayed_entry;
6805 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6806 char *line = NULL, *id_str = NULL, *link_target = NULL;
6807 const char *modestr = "";
6808 mode_t mode;
6810 te = got_object_tree_get_entry(s->tree, i);
6811 mode = got_tree_entry_get_mode(te);
6813 if (s->show_ids) {
6814 err = got_object_id_str(&id_str,
6815 got_tree_entry_get_id(te));
6816 if (err)
6817 return got_error_from_errno(
6818 "got_object_id_str");
6820 if (got_object_tree_entry_is_submodule(te))
6821 modestr = "$";
6822 else if (S_ISLNK(mode)) {
6823 int i;
6825 err = got_tree_entry_get_symlink_target(&link_target,
6826 te, s->repo);
6827 if (err) {
6828 free(id_str);
6829 return err;
6831 for (i = 0; i < strlen(link_target); i++) {
6832 if (!isprint((unsigned char)link_target[i]))
6833 link_target[i] = '?';
6835 modestr = "@";
6837 else if (S_ISDIR(mode))
6838 modestr = "/";
6839 else if (mode & S_IXUSR)
6840 modestr = "*";
6841 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6842 got_tree_entry_get_name(te), modestr,
6843 link_target ? " -> ": "",
6844 link_target ? link_target : "") == -1) {
6845 free(id_str);
6846 free(link_target);
6847 return got_error_from_errno("asprintf");
6849 free(id_str);
6850 free(link_target);
6851 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6852 0, 0);
6853 if (err) {
6854 free(line);
6855 break;
6857 if (n == s->selected) {
6858 if (view->focussed)
6859 wstandout(view->window);
6860 s->selected_entry = te;
6862 tc = match_color(&s->colors, line);
6863 if (tc)
6864 wattr_on(view->window,
6865 COLOR_PAIR(tc->colorpair), NULL);
6866 waddwstr(view->window, wline);
6867 if (tc)
6868 wattr_off(view->window,
6869 COLOR_PAIR(tc->colorpair), NULL);
6870 if (width < view->ncols - 1)
6871 waddch(view->window, '\n');
6872 if (n == s->selected && view->focussed)
6873 wstandend(view->window);
6874 free(line);
6875 free(wline);
6876 wline = NULL;
6877 n++;
6878 s->ndisplayed++;
6879 s->last_displayed_entry = te;
6880 if (--limit <= 0)
6881 break;
6884 return err;
6887 static void
6888 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6890 struct got_tree_entry *te;
6891 int isroot = s->tree == s->root;
6892 int i = 0;
6894 if (s->first_displayed_entry == NULL)
6895 return;
6897 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6898 while (i++ < maxscroll) {
6899 if (te == NULL) {
6900 if (!isroot)
6901 s->first_displayed_entry = NULL;
6902 break;
6904 s->first_displayed_entry = te;
6905 te = got_tree_entry_get_prev(s->tree, te);
6909 static const struct got_error *
6910 tree_scroll_down(struct tog_view *view, int maxscroll)
6912 struct tog_tree_view_state *s = &view->state.tree;
6913 struct got_tree_entry *next, *last;
6914 int n = 0;
6916 if (s->first_displayed_entry)
6917 next = got_tree_entry_get_next(s->tree,
6918 s->first_displayed_entry);
6919 else
6920 next = got_object_tree_get_first_entry(s->tree);
6922 last = s->last_displayed_entry;
6923 while (next && n++ < maxscroll) {
6924 if (last) {
6925 s->last_displayed_entry = last;
6926 last = got_tree_entry_get_next(s->tree, last);
6928 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6929 s->first_displayed_entry = next;
6930 next = got_tree_entry_get_next(s->tree, next);
6934 return NULL;
6937 static const struct got_error *
6938 tree_entry_path(char **path, struct tog_parent_trees *parents,
6939 struct got_tree_entry *te)
6941 const struct got_error *err = NULL;
6942 struct tog_parent_tree *pt;
6943 size_t len = 2; /* for leading slash and NUL */
6945 TAILQ_FOREACH(pt, parents, entry)
6946 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6947 + 1 /* slash */;
6948 if (te)
6949 len += strlen(got_tree_entry_get_name(te));
6951 *path = calloc(1, len);
6952 if (path == NULL)
6953 return got_error_from_errno("calloc");
6955 (*path)[0] = '/';
6956 pt = TAILQ_LAST(parents, tog_parent_trees);
6957 while (pt) {
6958 const char *name = got_tree_entry_get_name(pt->selected_entry);
6959 if (strlcat(*path, name, len) >= len) {
6960 err = got_error(GOT_ERR_NO_SPACE);
6961 goto done;
6963 if (strlcat(*path, "/", len) >= len) {
6964 err = got_error(GOT_ERR_NO_SPACE);
6965 goto done;
6967 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6969 if (te) {
6970 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6971 err = got_error(GOT_ERR_NO_SPACE);
6972 goto done;
6975 done:
6976 if (err) {
6977 free(*path);
6978 *path = NULL;
6980 return err;
6983 static const struct got_error *
6984 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6985 struct got_tree_entry *te, struct tog_parent_trees *parents,
6986 struct got_object_id *commit_id, struct got_repository *repo)
6988 const struct got_error *err = NULL;
6989 char *path;
6990 struct tog_view *blame_view;
6992 *new_view = NULL;
6994 err = tree_entry_path(&path, parents, te);
6995 if (err)
6996 return err;
6998 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6999 if (blame_view == NULL) {
7000 err = got_error_from_errno("view_open");
7001 goto done;
7004 err = open_blame_view(blame_view, path, commit_id, repo);
7005 if (err) {
7006 if (err->code == GOT_ERR_CANCELLED)
7007 err = NULL;
7008 view_close(blame_view);
7009 } else
7010 *new_view = blame_view;
7011 done:
7012 free(path);
7013 return err;
7016 static const struct got_error *
7017 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7018 struct tog_tree_view_state *s)
7020 struct tog_view *log_view;
7021 const struct got_error *err = NULL;
7022 char *path;
7024 *new_view = NULL;
7026 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7027 if (log_view == NULL)
7028 return got_error_from_errno("view_open");
7030 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7031 if (err)
7032 return err;
7034 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7035 path, 0);
7036 if (err)
7037 view_close(log_view);
7038 else
7039 *new_view = log_view;
7040 free(path);
7041 return err;
7044 static const struct got_error *
7045 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7046 const char *head_ref_name, struct got_repository *repo)
7048 const struct got_error *err = NULL;
7049 char *commit_id_str = NULL;
7050 struct tog_tree_view_state *s = &view->state.tree;
7051 struct got_commit_object *commit = NULL;
7053 TAILQ_INIT(&s->parents);
7054 STAILQ_INIT(&s->colors);
7056 s->commit_id = got_object_id_dup(commit_id);
7057 if (s->commit_id == NULL)
7058 return got_error_from_errno("got_object_id_dup");
7060 err = got_object_open_as_commit(&commit, repo, commit_id);
7061 if (err)
7062 goto done;
7065 * The root is opened here and will be closed when the view is closed.
7066 * Any visited subtrees and their path-wise parents are opened and
7067 * closed on demand.
7069 err = got_object_open_as_tree(&s->root, repo,
7070 got_object_commit_get_tree_id(commit));
7071 if (err)
7072 goto done;
7073 s->tree = s->root;
7075 err = got_object_id_str(&commit_id_str, commit_id);
7076 if (err != NULL)
7077 goto done;
7079 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7080 err = got_error_from_errno("asprintf");
7081 goto done;
7084 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7085 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7086 if (head_ref_name) {
7087 s->head_ref_name = strdup(head_ref_name);
7088 if (s->head_ref_name == NULL) {
7089 err = got_error_from_errno("strdup");
7090 goto done;
7093 s->repo = repo;
7095 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7096 err = add_color(&s->colors, "\\$$",
7097 TOG_COLOR_TREE_SUBMODULE,
7098 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7099 if (err)
7100 goto done;
7101 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7102 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7103 if (err)
7104 goto done;
7105 err = add_color(&s->colors, "/$",
7106 TOG_COLOR_TREE_DIRECTORY,
7107 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7108 if (err)
7109 goto done;
7111 err = add_color(&s->colors, "\\*$",
7112 TOG_COLOR_TREE_EXECUTABLE,
7113 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7114 if (err)
7115 goto done;
7117 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7118 get_color_value("TOG_COLOR_COMMIT"));
7119 if (err)
7120 goto done;
7123 view->show = show_tree_view;
7124 view->input = input_tree_view;
7125 view->close = close_tree_view;
7126 view->search_start = search_start_tree_view;
7127 view->search_next = search_next_tree_view;
7128 done:
7129 free(commit_id_str);
7130 if (commit)
7131 got_object_commit_close(commit);
7132 if (err)
7133 close_tree_view(view);
7134 return err;
7137 static const struct got_error *
7138 close_tree_view(struct tog_view *view)
7140 struct tog_tree_view_state *s = &view->state.tree;
7142 free_colors(&s->colors);
7143 free(s->tree_label);
7144 s->tree_label = NULL;
7145 free(s->commit_id);
7146 s->commit_id = NULL;
7147 free(s->head_ref_name);
7148 s->head_ref_name = NULL;
7149 while (!TAILQ_EMPTY(&s->parents)) {
7150 struct tog_parent_tree *parent;
7151 parent = TAILQ_FIRST(&s->parents);
7152 TAILQ_REMOVE(&s->parents, parent, entry);
7153 if (parent->tree != s->root)
7154 got_object_tree_close(parent->tree);
7155 free(parent);
7158 if (s->tree != NULL && s->tree != s->root)
7159 got_object_tree_close(s->tree);
7160 if (s->root)
7161 got_object_tree_close(s->root);
7162 return NULL;
7165 static const struct got_error *
7166 search_start_tree_view(struct tog_view *view)
7168 struct tog_tree_view_state *s = &view->state.tree;
7170 s->matched_entry = NULL;
7171 return NULL;
7174 static int
7175 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7177 regmatch_t regmatch;
7179 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7180 0) == 0;
7183 static const struct got_error *
7184 search_next_tree_view(struct tog_view *view)
7186 struct tog_tree_view_state *s = &view->state.tree;
7187 struct got_tree_entry *te = NULL;
7189 if (!view->searching) {
7190 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7191 return NULL;
7194 if (s->matched_entry) {
7195 if (view->searching == TOG_SEARCH_FORWARD) {
7196 if (s->selected_entry)
7197 te = got_tree_entry_get_next(s->tree,
7198 s->selected_entry);
7199 else
7200 te = got_object_tree_get_first_entry(s->tree);
7201 } else {
7202 if (s->selected_entry == NULL)
7203 te = got_object_tree_get_last_entry(s->tree);
7204 else
7205 te = got_tree_entry_get_prev(s->tree,
7206 s->selected_entry);
7208 } else {
7209 if (s->selected_entry)
7210 te = s->selected_entry;
7211 else if (view->searching == TOG_SEARCH_FORWARD)
7212 te = got_object_tree_get_first_entry(s->tree);
7213 else
7214 te = got_object_tree_get_last_entry(s->tree);
7217 while (1) {
7218 if (te == NULL) {
7219 if (s->matched_entry == NULL) {
7220 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7221 return NULL;
7223 if (view->searching == TOG_SEARCH_FORWARD)
7224 te = got_object_tree_get_first_entry(s->tree);
7225 else
7226 te = got_object_tree_get_last_entry(s->tree);
7229 if (match_tree_entry(te, &view->regex)) {
7230 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7231 s->matched_entry = te;
7232 break;
7235 if (view->searching == TOG_SEARCH_FORWARD)
7236 te = got_tree_entry_get_next(s->tree, te);
7237 else
7238 te = got_tree_entry_get_prev(s->tree, te);
7241 if (s->matched_entry) {
7242 s->first_displayed_entry = s->matched_entry;
7243 s->selected = 0;
7246 return NULL;
7249 static const struct got_error *
7250 show_tree_view(struct tog_view *view)
7252 const struct got_error *err = NULL;
7253 struct tog_tree_view_state *s = &view->state.tree;
7254 char *parent_path;
7256 err = tree_entry_path(&parent_path, &s->parents, NULL);
7257 if (err)
7258 return err;
7260 err = draw_tree_entries(view, parent_path);
7261 free(parent_path);
7263 view_border(view);
7264 return err;
7267 static const struct got_error *
7268 tree_goto_line(struct tog_view *view, int nlines)
7270 const struct got_error *err = NULL;
7271 struct tog_tree_view_state *s = &view->state.tree;
7272 struct got_tree_entry **fte, **lte, **ste;
7273 int g, last, first = 1, i = 1;
7274 int root = s->tree == s->root;
7275 int off = root ? 1 : 2;
7277 g = view->gline;
7278 view->gline = 0;
7280 if (g == 0)
7281 g = 1;
7282 else if (g > got_object_tree_get_nentries(s->tree))
7283 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7285 fte = &s->first_displayed_entry;
7286 lte = &s->last_displayed_entry;
7287 ste = &s->selected_entry;
7289 if (*fte != NULL) {
7290 first = got_tree_entry_get_index(*fte);
7291 first += off; /* account for ".." */
7293 last = got_tree_entry_get_index(*lte);
7294 last += off;
7296 if (g >= first && g <= last && g - first < nlines) {
7297 s->selected = g - first;
7298 return NULL; /* gline is on the current page */
7301 if (*ste != NULL) {
7302 i = got_tree_entry_get_index(*ste);
7303 i += off;
7306 if (i < g) {
7307 err = tree_scroll_down(view, g - i);
7308 if (err)
7309 return err;
7310 if (got_tree_entry_get_index(*lte) >=
7311 got_object_tree_get_nentries(s->tree) - 1 &&
7312 first + s->selected < g &&
7313 s->selected < s->ndisplayed - 1) {
7314 first = got_tree_entry_get_index(*fte);
7315 first += off;
7316 s->selected = g - first;
7318 } else if (i > g)
7319 tree_scroll_up(s, i - g);
7321 if (g < nlines &&
7322 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7323 s->selected = g - 1;
7325 return NULL;
7328 static const struct got_error *
7329 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7331 const struct got_error *err = NULL;
7332 struct tog_tree_view_state *s = &view->state.tree;
7333 struct got_tree_entry *te;
7334 int n, nscroll = view->nlines - 3;
7336 if (view->gline)
7337 return tree_goto_line(view, nscroll);
7339 switch (ch) {
7340 case 'i':
7341 s->show_ids = !s->show_ids;
7342 view->count = 0;
7343 break;
7344 case 'L':
7345 view->count = 0;
7346 if (!s->selected_entry)
7347 break;
7348 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7349 break;
7350 case 'R':
7351 view->count = 0;
7352 err = view_request_new(new_view, view, TOG_VIEW_REF);
7353 break;
7354 case 'g':
7355 case '=':
7356 case KEY_HOME:
7357 s->selected = 0;
7358 view->count = 0;
7359 if (s->tree == s->root)
7360 s->first_displayed_entry =
7361 got_object_tree_get_first_entry(s->tree);
7362 else
7363 s->first_displayed_entry = NULL;
7364 break;
7365 case 'G':
7366 case '*':
7367 case KEY_END: {
7368 int eos = view->nlines - 3;
7370 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7371 --eos; /* border */
7372 s->selected = 0;
7373 view->count = 0;
7374 te = got_object_tree_get_last_entry(s->tree);
7375 for (n = 0; n < eos; n++) {
7376 if (te == NULL) {
7377 if (s->tree != s->root) {
7378 s->first_displayed_entry = NULL;
7379 n++;
7381 break;
7383 s->first_displayed_entry = te;
7384 te = got_tree_entry_get_prev(s->tree, te);
7386 if (n > 0)
7387 s->selected = n - 1;
7388 break;
7390 case 'k':
7391 case KEY_UP:
7392 case CTRL('p'):
7393 if (s->selected > 0) {
7394 s->selected--;
7395 break;
7397 tree_scroll_up(s, 1);
7398 if (s->selected_entry == NULL ||
7399 (s->tree == s->root && s->selected_entry ==
7400 got_object_tree_get_first_entry(s->tree)))
7401 view->count = 0;
7402 break;
7403 case CTRL('u'):
7404 case 'u':
7405 nscroll /= 2;
7406 /* FALL THROUGH */
7407 case KEY_PPAGE:
7408 case CTRL('b'):
7409 case 'b':
7410 if (s->tree == s->root) {
7411 if (got_object_tree_get_first_entry(s->tree) ==
7412 s->first_displayed_entry)
7413 s->selected -= MIN(s->selected, nscroll);
7414 } else {
7415 if (s->first_displayed_entry == NULL)
7416 s->selected -= MIN(s->selected, nscroll);
7418 tree_scroll_up(s, MAX(0, nscroll));
7419 if (s->selected_entry == NULL ||
7420 (s->tree == s->root && s->selected_entry ==
7421 got_object_tree_get_first_entry(s->tree)))
7422 view->count = 0;
7423 break;
7424 case 'j':
7425 case KEY_DOWN:
7426 case CTRL('n'):
7427 if (s->selected < s->ndisplayed - 1) {
7428 s->selected++;
7429 break;
7431 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7432 == NULL) {
7433 /* can't scroll any further */
7434 view->count = 0;
7435 break;
7437 tree_scroll_down(view, 1);
7438 break;
7439 case CTRL('d'):
7440 case 'd':
7441 nscroll /= 2;
7442 /* FALL THROUGH */
7443 case KEY_NPAGE:
7444 case CTRL('f'):
7445 case 'f':
7446 case ' ':
7447 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7448 == NULL) {
7449 /* can't scroll any further; move cursor down */
7450 if (s->selected < s->ndisplayed - 1)
7451 s->selected += MIN(nscroll,
7452 s->ndisplayed - s->selected - 1);
7453 else
7454 view->count = 0;
7455 break;
7457 tree_scroll_down(view, nscroll);
7458 break;
7459 case KEY_ENTER:
7460 case '\r':
7461 case KEY_BACKSPACE:
7462 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7463 struct tog_parent_tree *parent;
7464 /* user selected '..' */
7465 if (s->tree == s->root) {
7466 view->count = 0;
7467 break;
7469 parent = TAILQ_FIRST(&s->parents);
7470 TAILQ_REMOVE(&s->parents, parent,
7471 entry);
7472 got_object_tree_close(s->tree);
7473 s->tree = parent->tree;
7474 s->first_displayed_entry =
7475 parent->first_displayed_entry;
7476 s->selected_entry =
7477 parent->selected_entry;
7478 s->selected = parent->selected;
7479 if (s->selected > view->nlines - 3) {
7480 err = offset_selection_down(view);
7481 if (err)
7482 break;
7484 free(parent);
7485 } else if (S_ISDIR(got_tree_entry_get_mode(
7486 s->selected_entry))) {
7487 struct got_tree_object *subtree;
7488 view->count = 0;
7489 err = got_object_open_as_tree(&subtree, s->repo,
7490 got_tree_entry_get_id(s->selected_entry));
7491 if (err)
7492 break;
7493 err = tree_view_visit_subtree(s, subtree);
7494 if (err) {
7495 got_object_tree_close(subtree);
7496 break;
7498 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7499 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7500 break;
7501 case KEY_RESIZE:
7502 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7503 s->selected = view->nlines - 4;
7504 view->count = 0;
7505 break;
7506 default:
7507 view->count = 0;
7508 break;
7511 return err;
7514 __dead static void
7515 usage_tree(void)
7517 endwin();
7518 fprintf(stderr,
7519 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7520 getprogname());
7521 exit(1);
7524 static const struct got_error *
7525 cmd_tree(int argc, char *argv[])
7527 const struct got_error *error;
7528 struct got_repository *repo = NULL;
7529 struct got_worktree *worktree = NULL;
7530 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7531 struct got_object_id *commit_id = NULL;
7532 struct got_commit_object *commit = NULL;
7533 const char *commit_id_arg = NULL;
7534 char *label = NULL;
7535 struct got_reference *ref = NULL;
7536 const char *head_ref_name = NULL;
7537 int ch;
7538 struct tog_view *view;
7539 int *pack_fds = NULL;
7541 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7542 switch (ch) {
7543 case 'c':
7544 commit_id_arg = optarg;
7545 break;
7546 case 'r':
7547 repo_path = realpath(optarg, NULL);
7548 if (repo_path == NULL)
7549 return got_error_from_errno2("realpath",
7550 optarg);
7551 break;
7552 default:
7553 usage_tree();
7554 /* NOTREACHED */
7558 argc -= optind;
7559 argv += optind;
7561 if (argc > 1)
7562 usage_tree();
7564 error = got_repo_pack_fds_open(&pack_fds);
7565 if (error != NULL)
7566 goto done;
7568 if (repo_path == NULL) {
7569 cwd = getcwd(NULL, 0);
7570 if (cwd == NULL)
7571 return got_error_from_errno("getcwd");
7572 error = got_worktree_open(&worktree, cwd);
7573 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7574 goto done;
7575 if (worktree)
7576 repo_path =
7577 strdup(got_worktree_get_repo_path(worktree));
7578 else
7579 repo_path = strdup(cwd);
7580 if (repo_path == NULL) {
7581 error = got_error_from_errno("strdup");
7582 goto done;
7586 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7587 if (error != NULL)
7588 goto done;
7590 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7591 repo, worktree);
7592 if (error)
7593 goto done;
7595 init_curses();
7597 error = apply_unveil(got_repo_get_path(repo), NULL);
7598 if (error)
7599 goto done;
7601 error = tog_load_refs(repo, 0);
7602 if (error)
7603 goto done;
7605 if (commit_id_arg == NULL) {
7606 error = got_repo_match_object_id(&commit_id, &label,
7607 worktree ? got_worktree_get_head_ref_name(worktree) :
7608 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7609 if (error)
7610 goto done;
7611 head_ref_name = label;
7612 } else {
7613 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7614 if (error == NULL)
7615 head_ref_name = got_ref_get_name(ref);
7616 else if (error->code != GOT_ERR_NOT_REF)
7617 goto done;
7618 error = got_repo_match_object_id(&commit_id, NULL,
7619 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7620 if (error)
7621 goto done;
7624 error = got_object_open_as_commit(&commit, repo, commit_id);
7625 if (error)
7626 goto done;
7628 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7629 if (view == NULL) {
7630 error = got_error_from_errno("view_open");
7631 goto done;
7633 error = open_tree_view(view, commit_id, head_ref_name, repo);
7634 if (error)
7635 goto done;
7636 if (!got_path_is_root_dir(in_repo_path)) {
7637 error = tree_view_walk_path(&view->state.tree, commit,
7638 in_repo_path);
7639 if (error)
7640 goto done;
7643 if (worktree) {
7644 /* Release work tree lock. */
7645 got_worktree_close(worktree);
7646 worktree = NULL;
7648 error = view_loop(view);
7649 done:
7650 free(repo_path);
7651 free(cwd);
7652 free(commit_id);
7653 free(label);
7654 if (ref)
7655 got_ref_close(ref);
7656 if (repo) {
7657 const struct got_error *close_err = got_repo_close(repo);
7658 if (error == NULL)
7659 error = close_err;
7661 if (pack_fds) {
7662 const struct got_error *pack_err =
7663 got_repo_pack_fds_close(pack_fds);
7664 if (error == NULL)
7665 error = pack_err;
7667 tog_free_refs();
7668 return error;
7671 static const struct got_error *
7672 ref_view_load_refs(struct tog_ref_view_state *s)
7674 struct got_reflist_entry *sre;
7675 struct tog_reflist_entry *re;
7677 s->nrefs = 0;
7678 TAILQ_FOREACH(sre, &tog_refs, entry) {
7679 if (strncmp(got_ref_get_name(sre->ref),
7680 "refs/got/", 9) == 0 &&
7681 strncmp(got_ref_get_name(sre->ref),
7682 "refs/got/backup/", 16) != 0)
7683 continue;
7685 re = malloc(sizeof(*re));
7686 if (re == NULL)
7687 return got_error_from_errno("malloc");
7689 re->ref = got_ref_dup(sre->ref);
7690 if (re->ref == NULL)
7691 return got_error_from_errno("got_ref_dup");
7692 re->idx = s->nrefs++;
7693 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7696 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7697 return NULL;
7700 static void
7701 ref_view_free_refs(struct tog_ref_view_state *s)
7703 struct tog_reflist_entry *re;
7705 while (!TAILQ_EMPTY(&s->refs)) {
7706 re = TAILQ_FIRST(&s->refs);
7707 TAILQ_REMOVE(&s->refs, re, entry);
7708 got_ref_close(re->ref);
7709 free(re);
7713 static const struct got_error *
7714 open_ref_view(struct tog_view *view, struct got_repository *repo)
7716 const struct got_error *err = NULL;
7717 struct tog_ref_view_state *s = &view->state.ref;
7719 s->selected_entry = 0;
7720 s->repo = repo;
7722 TAILQ_INIT(&s->refs);
7723 STAILQ_INIT(&s->colors);
7725 err = ref_view_load_refs(s);
7726 if (err)
7727 return err;
7729 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7730 err = add_color(&s->colors, "^refs/heads/",
7731 TOG_COLOR_REFS_HEADS,
7732 get_color_value("TOG_COLOR_REFS_HEADS"));
7733 if (err)
7734 goto done;
7736 err = add_color(&s->colors, "^refs/tags/",
7737 TOG_COLOR_REFS_TAGS,
7738 get_color_value("TOG_COLOR_REFS_TAGS"));
7739 if (err)
7740 goto done;
7742 err = add_color(&s->colors, "^refs/remotes/",
7743 TOG_COLOR_REFS_REMOTES,
7744 get_color_value("TOG_COLOR_REFS_REMOTES"));
7745 if (err)
7746 goto done;
7748 err = add_color(&s->colors, "^refs/got/backup/",
7749 TOG_COLOR_REFS_BACKUP,
7750 get_color_value("TOG_COLOR_REFS_BACKUP"));
7751 if (err)
7752 goto done;
7755 view->show = show_ref_view;
7756 view->input = input_ref_view;
7757 view->close = close_ref_view;
7758 view->search_start = search_start_ref_view;
7759 view->search_next = search_next_ref_view;
7760 done:
7761 if (err)
7762 free_colors(&s->colors);
7763 return err;
7766 static const struct got_error *
7767 close_ref_view(struct tog_view *view)
7769 struct tog_ref_view_state *s = &view->state.ref;
7771 ref_view_free_refs(s);
7772 free_colors(&s->colors);
7774 return NULL;
7777 static const struct got_error *
7778 resolve_reflist_entry(struct got_object_id **commit_id,
7779 struct tog_reflist_entry *re, struct got_repository *repo)
7781 const struct got_error *err = NULL;
7782 struct got_object_id *obj_id;
7783 struct got_tag_object *tag = NULL;
7784 int obj_type;
7786 *commit_id = NULL;
7788 err = got_ref_resolve(&obj_id, repo, re->ref);
7789 if (err)
7790 return err;
7792 err = got_object_get_type(&obj_type, repo, obj_id);
7793 if (err)
7794 goto done;
7796 switch (obj_type) {
7797 case GOT_OBJ_TYPE_COMMIT:
7798 *commit_id = obj_id;
7799 break;
7800 case GOT_OBJ_TYPE_TAG:
7801 err = got_object_open_as_tag(&tag, repo, obj_id);
7802 if (err)
7803 goto done;
7804 free(obj_id);
7805 err = got_object_get_type(&obj_type, repo,
7806 got_object_tag_get_object_id(tag));
7807 if (err)
7808 goto done;
7809 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7810 err = got_error(GOT_ERR_OBJ_TYPE);
7811 goto done;
7813 *commit_id = got_object_id_dup(
7814 got_object_tag_get_object_id(tag));
7815 if (*commit_id == NULL) {
7816 err = got_error_from_errno("got_object_id_dup");
7817 goto done;
7819 break;
7820 default:
7821 err = got_error(GOT_ERR_OBJ_TYPE);
7822 break;
7825 done:
7826 if (tag)
7827 got_object_tag_close(tag);
7828 if (err) {
7829 free(*commit_id);
7830 *commit_id = NULL;
7832 return err;
7835 static const struct got_error *
7836 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7837 struct tog_reflist_entry *re, struct got_repository *repo)
7839 struct tog_view *log_view;
7840 const struct got_error *err = NULL;
7841 struct got_object_id *commit_id = NULL;
7843 *new_view = NULL;
7845 err = resolve_reflist_entry(&commit_id, re, repo);
7846 if (err) {
7847 if (err->code != GOT_ERR_OBJ_TYPE)
7848 return err;
7849 else
7850 return NULL;
7853 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7854 if (log_view == NULL) {
7855 err = got_error_from_errno("view_open");
7856 goto done;
7859 err = open_log_view(log_view, commit_id, repo,
7860 got_ref_get_name(re->ref), "", 0);
7861 done:
7862 if (err)
7863 view_close(log_view);
7864 else
7865 *new_view = log_view;
7866 free(commit_id);
7867 return err;
7870 static void
7871 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7873 struct tog_reflist_entry *re;
7874 int i = 0;
7876 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7877 return;
7879 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7880 while (i++ < maxscroll) {
7881 if (re == NULL)
7882 break;
7883 s->first_displayed_entry = re;
7884 re = TAILQ_PREV(re, tog_reflist_head, entry);
7888 static const struct got_error *
7889 ref_scroll_down(struct tog_view *view, int maxscroll)
7891 struct tog_ref_view_state *s = &view->state.ref;
7892 struct tog_reflist_entry *next, *last;
7893 int n = 0;
7895 if (s->first_displayed_entry)
7896 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7897 else
7898 next = TAILQ_FIRST(&s->refs);
7900 last = s->last_displayed_entry;
7901 while (next && n++ < maxscroll) {
7902 if (last) {
7903 s->last_displayed_entry = last;
7904 last = TAILQ_NEXT(last, entry);
7906 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7907 s->first_displayed_entry = next;
7908 next = TAILQ_NEXT(next, entry);
7912 return NULL;
7915 static const struct got_error *
7916 search_start_ref_view(struct tog_view *view)
7918 struct tog_ref_view_state *s = &view->state.ref;
7920 s->matched_entry = NULL;
7921 return NULL;
7924 static int
7925 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7927 regmatch_t regmatch;
7929 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7930 0) == 0;
7933 static const struct got_error *
7934 search_next_ref_view(struct tog_view *view)
7936 struct tog_ref_view_state *s = &view->state.ref;
7937 struct tog_reflist_entry *re = NULL;
7939 if (!view->searching) {
7940 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7941 return NULL;
7944 if (s->matched_entry) {
7945 if (view->searching == TOG_SEARCH_FORWARD) {
7946 if (s->selected_entry)
7947 re = TAILQ_NEXT(s->selected_entry, entry);
7948 else
7949 re = TAILQ_PREV(s->selected_entry,
7950 tog_reflist_head, entry);
7951 } else {
7952 if (s->selected_entry == NULL)
7953 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7954 else
7955 re = TAILQ_PREV(s->selected_entry,
7956 tog_reflist_head, entry);
7958 } else {
7959 if (s->selected_entry)
7960 re = s->selected_entry;
7961 else if (view->searching == TOG_SEARCH_FORWARD)
7962 re = TAILQ_FIRST(&s->refs);
7963 else
7964 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7967 while (1) {
7968 if (re == NULL) {
7969 if (s->matched_entry == NULL) {
7970 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7971 return NULL;
7973 if (view->searching == TOG_SEARCH_FORWARD)
7974 re = TAILQ_FIRST(&s->refs);
7975 else
7976 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7979 if (match_reflist_entry(re, &view->regex)) {
7980 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7981 s->matched_entry = re;
7982 break;
7985 if (view->searching == TOG_SEARCH_FORWARD)
7986 re = TAILQ_NEXT(re, entry);
7987 else
7988 re = TAILQ_PREV(re, tog_reflist_head, entry);
7991 if (s->matched_entry) {
7992 s->first_displayed_entry = s->matched_entry;
7993 s->selected = 0;
7996 return NULL;
7999 static const struct got_error *
8000 show_ref_view(struct tog_view *view)
8002 const struct got_error *err = NULL;
8003 struct tog_ref_view_state *s = &view->state.ref;
8004 struct tog_reflist_entry *re;
8005 char *line = NULL;
8006 wchar_t *wline;
8007 struct tog_color *tc;
8008 int width, n;
8009 int limit = view->nlines;
8011 werase(view->window);
8013 s->ndisplayed = 0;
8014 if (view_is_hsplit_top(view))
8015 --limit; /* border */
8017 if (limit == 0)
8018 return NULL;
8020 re = s->first_displayed_entry;
8022 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8023 s->nrefs) == -1)
8024 return got_error_from_errno("asprintf");
8026 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8027 if (err) {
8028 free(line);
8029 return err;
8031 if (view_needs_focus_indication(view))
8032 wstandout(view->window);
8033 waddwstr(view->window, wline);
8034 while (width++ < view->ncols)
8035 waddch(view->window, ' ');
8036 if (view_needs_focus_indication(view))
8037 wstandend(view->window);
8038 free(wline);
8039 wline = NULL;
8040 free(line);
8041 line = NULL;
8042 if (--limit <= 0)
8043 return NULL;
8045 n = 0;
8046 while (re && limit > 0) {
8047 char *line = NULL;
8048 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8050 if (s->show_date) {
8051 struct got_commit_object *ci;
8052 struct got_tag_object *tag;
8053 struct got_object_id *id;
8054 struct tm tm;
8055 time_t t;
8057 err = got_ref_resolve(&id, s->repo, re->ref);
8058 if (err)
8059 return err;
8060 err = got_object_open_as_tag(&tag, s->repo, id);
8061 if (err) {
8062 if (err->code != GOT_ERR_OBJ_TYPE) {
8063 free(id);
8064 return err;
8066 err = got_object_open_as_commit(&ci, s->repo,
8067 id);
8068 if (err) {
8069 free(id);
8070 return err;
8072 t = got_object_commit_get_committer_time(ci);
8073 got_object_commit_close(ci);
8074 } else {
8075 t = got_object_tag_get_tagger_time(tag);
8076 got_object_tag_close(tag);
8078 free(id);
8079 if (gmtime_r(&t, &tm) == NULL)
8080 return got_error_from_errno("gmtime_r");
8081 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8082 return got_error(GOT_ERR_NO_SPACE);
8084 if (got_ref_is_symbolic(re->ref)) {
8085 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8086 ymd : "", got_ref_get_name(re->ref),
8087 got_ref_get_symref_target(re->ref)) == -1)
8088 return got_error_from_errno("asprintf");
8089 } else if (s->show_ids) {
8090 struct got_object_id *id;
8091 char *id_str;
8092 err = got_ref_resolve(&id, s->repo, re->ref);
8093 if (err)
8094 return err;
8095 err = got_object_id_str(&id_str, id);
8096 if (err) {
8097 free(id);
8098 return err;
8100 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8101 got_ref_get_name(re->ref), id_str) == -1) {
8102 err = got_error_from_errno("asprintf");
8103 free(id);
8104 free(id_str);
8105 return err;
8107 free(id);
8108 free(id_str);
8109 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8110 got_ref_get_name(re->ref)) == -1)
8111 return got_error_from_errno("asprintf");
8113 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
8114 0, 0);
8115 if (err) {
8116 free(line);
8117 return err;
8119 if (n == s->selected) {
8120 if (view->focussed)
8121 wstandout(view->window);
8122 s->selected_entry = re;
8124 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8125 if (tc)
8126 wattr_on(view->window,
8127 COLOR_PAIR(tc->colorpair), NULL);
8128 waddwstr(view->window, wline);
8129 if (tc)
8130 wattr_off(view->window,
8131 COLOR_PAIR(tc->colorpair), NULL);
8132 if (width < view->ncols - 1)
8133 waddch(view->window, '\n');
8134 if (n == s->selected && view->focussed)
8135 wstandend(view->window);
8136 free(line);
8137 free(wline);
8138 wline = NULL;
8139 n++;
8140 s->ndisplayed++;
8141 s->last_displayed_entry = re;
8143 limit--;
8144 re = TAILQ_NEXT(re, entry);
8147 view_border(view);
8148 return err;
8151 static const struct got_error *
8152 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8153 struct tog_reflist_entry *re, struct got_repository *repo)
8155 const struct got_error *err = NULL;
8156 struct got_object_id *commit_id = NULL;
8157 struct tog_view *tree_view;
8159 *new_view = NULL;
8161 err = resolve_reflist_entry(&commit_id, re, repo);
8162 if (err) {
8163 if (err->code != GOT_ERR_OBJ_TYPE)
8164 return err;
8165 else
8166 return NULL;
8170 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8171 if (tree_view == NULL) {
8172 err = got_error_from_errno("view_open");
8173 goto done;
8176 err = open_tree_view(tree_view, commit_id,
8177 got_ref_get_name(re->ref), repo);
8178 if (err)
8179 goto done;
8181 *new_view = tree_view;
8182 done:
8183 free(commit_id);
8184 return err;
8187 static const struct got_error *
8188 ref_goto_line(struct tog_view *view, int nlines)
8190 const struct got_error *err = NULL;
8191 struct tog_ref_view_state *s = &view->state.ref;
8192 int g, idx = s->selected_entry->idx;
8194 g = view->gline;
8195 view->gline = 0;
8197 if (g == 0)
8198 g = 1;
8199 else if (g > s->nrefs)
8200 g = s->nrefs;
8202 if (g >= s->first_displayed_entry->idx + 1 &&
8203 g <= s->last_displayed_entry->idx + 1 &&
8204 g - s->first_displayed_entry->idx - 1 < nlines) {
8205 s->selected = g - s->first_displayed_entry->idx - 1;
8206 return NULL;
8209 if (idx + 1 < g) {
8210 err = ref_scroll_down(view, g - idx - 1);
8211 if (err)
8212 return err;
8213 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8214 s->first_displayed_entry->idx + s->selected < g &&
8215 s->selected < s->ndisplayed - 1)
8216 s->selected = g - s->first_displayed_entry->idx - 1;
8217 } else if (idx + 1 > g)
8218 ref_scroll_up(s, idx - g + 1);
8220 if (g < nlines && s->first_displayed_entry->idx == 0)
8221 s->selected = g - 1;
8223 return NULL;
8227 static const struct got_error *
8228 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8230 const struct got_error *err = NULL;
8231 struct tog_ref_view_state *s = &view->state.ref;
8232 struct tog_reflist_entry *re;
8233 int n, nscroll = view->nlines - 1;
8235 if (view->gline)
8236 return ref_goto_line(view, nscroll);
8238 switch (ch) {
8239 case 'i':
8240 s->show_ids = !s->show_ids;
8241 view->count = 0;
8242 break;
8243 case 'm':
8244 s->show_date = !s->show_date;
8245 view->count = 0;
8246 break;
8247 case 'o':
8248 s->sort_by_date = !s->sort_by_date;
8249 view->count = 0;
8250 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8251 got_ref_cmp_by_commit_timestamp_descending :
8252 tog_ref_cmp_by_name, s->repo);
8253 if (err)
8254 break;
8255 got_reflist_object_id_map_free(tog_refs_idmap);
8256 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8257 &tog_refs, s->repo);
8258 if (err)
8259 break;
8260 ref_view_free_refs(s);
8261 err = ref_view_load_refs(s);
8262 break;
8263 case KEY_ENTER:
8264 case '\r':
8265 view->count = 0;
8266 if (!s->selected_entry)
8267 break;
8268 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8269 break;
8270 case 'T':
8271 view->count = 0;
8272 if (!s->selected_entry)
8273 break;
8274 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8275 break;
8276 case 'g':
8277 case '=':
8278 case KEY_HOME:
8279 s->selected = 0;
8280 view->count = 0;
8281 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8282 break;
8283 case 'G':
8284 case '*':
8285 case KEY_END: {
8286 int eos = view->nlines - 1;
8288 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8289 --eos; /* border */
8290 s->selected = 0;
8291 view->count = 0;
8292 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8293 for (n = 0; n < eos; n++) {
8294 if (re == NULL)
8295 break;
8296 s->first_displayed_entry = re;
8297 re = TAILQ_PREV(re, tog_reflist_head, entry);
8299 if (n > 0)
8300 s->selected = n - 1;
8301 break;
8303 case 'k':
8304 case KEY_UP:
8305 case CTRL('p'):
8306 if (s->selected > 0) {
8307 s->selected--;
8308 break;
8310 ref_scroll_up(s, 1);
8311 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8312 view->count = 0;
8313 break;
8314 case CTRL('u'):
8315 case 'u':
8316 nscroll /= 2;
8317 /* FALL THROUGH */
8318 case KEY_PPAGE:
8319 case CTRL('b'):
8320 case 'b':
8321 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8322 s->selected -= MIN(nscroll, s->selected);
8323 ref_scroll_up(s, MAX(0, nscroll));
8324 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8325 view->count = 0;
8326 break;
8327 case 'j':
8328 case KEY_DOWN:
8329 case CTRL('n'):
8330 if (s->selected < s->ndisplayed - 1) {
8331 s->selected++;
8332 break;
8334 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8335 /* can't scroll any further */
8336 view->count = 0;
8337 break;
8339 ref_scroll_down(view, 1);
8340 break;
8341 case CTRL('d'):
8342 case 'd':
8343 nscroll /= 2;
8344 /* FALL THROUGH */
8345 case KEY_NPAGE:
8346 case CTRL('f'):
8347 case 'f':
8348 case ' ':
8349 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8350 /* can't scroll any further; move cursor down */
8351 if (s->selected < s->ndisplayed - 1)
8352 s->selected += MIN(nscroll,
8353 s->ndisplayed - s->selected - 1);
8354 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8355 s->selected += s->ndisplayed - s->selected - 1;
8356 view->count = 0;
8357 break;
8359 ref_scroll_down(view, nscroll);
8360 break;
8361 case CTRL('l'):
8362 view->count = 0;
8363 tog_free_refs();
8364 err = tog_load_refs(s->repo, s->sort_by_date);
8365 if (err)
8366 break;
8367 ref_view_free_refs(s);
8368 err = ref_view_load_refs(s);
8369 break;
8370 case KEY_RESIZE:
8371 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8372 s->selected = view->nlines - 2;
8373 break;
8374 default:
8375 view->count = 0;
8376 break;
8379 return err;
8382 __dead static void
8383 usage_ref(void)
8385 endwin();
8386 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8387 getprogname());
8388 exit(1);
8391 static const struct got_error *
8392 cmd_ref(int argc, char *argv[])
8394 const struct got_error *error;
8395 struct got_repository *repo = NULL;
8396 struct got_worktree *worktree = NULL;
8397 char *cwd = NULL, *repo_path = NULL;
8398 int ch;
8399 struct tog_view *view;
8400 int *pack_fds = NULL;
8402 while ((ch = getopt(argc, argv, "r:")) != -1) {
8403 switch (ch) {
8404 case 'r':
8405 repo_path = realpath(optarg, NULL);
8406 if (repo_path == NULL)
8407 return got_error_from_errno2("realpath",
8408 optarg);
8409 break;
8410 default:
8411 usage_ref();
8412 /* NOTREACHED */
8416 argc -= optind;
8417 argv += optind;
8419 if (argc > 1)
8420 usage_ref();
8422 error = got_repo_pack_fds_open(&pack_fds);
8423 if (error != NULL)
8424 goto done;
8426 if (repo_path == NULL) {
8427 cwd = getcwd(NULL, 0);
8428 if (cwd == NULL)
8429 return got_error_from_errno("getcwd");
8430 error = got_worktree_open(&worktree, cwd);
8431 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8432 goto done;
8433 if (worktree)
8434 repo_path =
8435 strdup(got_worktree_get_repo_path(worktree));
8436 else
8437 repo_path = strdup(cwd);
8438 if (repo_path == NULL) {
8439 error = got_error_from_errno("strdup");
8440 goto done;
8444 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8445 if (error != NULL)
8446 goto done;
8448 init_curses();
8450 error = apply_unveil(got_repo_get_path(repo), NULL);
8451 if (error)
8452 goto done;
8454 error = tog_load_refs(repo, 0);
8455 if (error)
8456 goto done;
8458 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8459 if (view == NULL) {
8460 error = got_error_from_errno("view_open");
8461 goto done;
8464 error = open_ref_view(view, repo);
8465 if (error)
8466 goto done;
8468 if (worktree) {
8469 /* Release work tree lock. */
8470 got_worktree_close(worktree);
8471 worktree = NULL;
8473 error = view_loop(view);
8474 done:
8475 free(repo_path);
8476 free(cwd);
8477 if (repo) {
8478 const struct got_error *close_err = got_repo_close(repo);
8479 if (close_err)
8480 error = close_err;
8482 if (pack_fds) {
8483 const struct got_error *pack_err =
8484 got_repo_pack_fds_close(pack_fds);
8485 if (error == NULL)
8486 error = pack_err;
8488 tog_free_refs();
8489 return error;
8492 static const struct got_error*
8493 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8494 const char *str)
8496 size_t len;
8498 if (win == NULL)
8499 win = stdscr;
8501 len = strlen(str);
8502 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8504 if (focus)
8505 wstandout(win);
8506 if (mvwprintw(win, y, x, "%s", str) == ERR)
8507 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8508 if (focus)
8509 wstandend(win);
8511 return NULL;
8514 static const struct got_error *
8515 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8517 off_t *p;
8519 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8520 if (p == NULL) {
8521 free(*line_offsets);
8522 *line_offsets = NULL;
8523 return got_error_from_errno("reallocarray");
8526 *line_offsets = p;
8527 (*line_offsets)[*nlines] = off;
8528 ++(*nlines);
8529 return NULL;
8532 static const struct got_error *
8533 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8535 *ret = 0;
8537 for (;n > 0; --n, ++km) {
8538 char *t0, *t, *k;
8539 size_t len = 1;
8541 if (km->keys == NULL)
8542 continue;
8544 t = t0 = strdup(km->keys);
8545 if (t0 == NULL)
8546 return got_error_from_errno("strdup");
8548 len += strlen(t);
8549 while ((k = strsep(&t, " ")) != NULL)
8550 len += strlen(k) > 1 ? 2 : 0;
8551 free(t0);
8552 *ret = MAX(*ret, len);
8555 return NULL;
8559 * Write keymap section headers, keys, and key info in km to f.
8560 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8561 * wrap control and symbolic keys in guillemets, else use <>.
8563 static const struct got_error *
8564 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8566 int n, len = width;
8568 if (km->keys) {
8569 static const char *u8_glyph[] = {
8570 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8571 "\xe2\x80\xba" /* U+203A (utf8 >) */
8573 char *t0, *t, *k;
8574 int cs, s, first = 1;
8576 cs = got_locale_is_utf8();
8578 t = t0 = strdup(km->keys);
8579 if (t0 == NULL)
8580 return got_error_from_errno("strdup");
8582 len = strlen(km->keys);
8583 while ((k = strsep(&t, " ")) != NULL) {
8584 s = strlen(k) > 1; /* control or symbolic key */
8585 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8586 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8587 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8588 if (n < 0) {
8589 free(t0);
8590 return got_error_from_errno("fprintf");
8592 first = 0;
8593 len += s ? 2 : 0;
8594 *off += n;
8596 free(t0);
8598 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8599 if (n < 0)
8600 return got_error_from_errno("fprintf");
8601 *off += n;
8603 return NULL;
8606 static const struct got_error *
8607 format_help(struct tog_help_view_state *s)
8609 const struct got_error *err = NULL;
8610 off_t off = 0;
8611 int i, max, n, show = s->all;
8612 static const struct tog_key_map km[] = {
8613 #define KEYMAP_(info, type) { NULL, (info), type }
8614 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8615 GENERATE_HELP
8616 #undef KEYMAP_
8617 #undef KEY_
8620 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8621 if (err)
8622 return err;
8624 n = nitems(km);
8625 err = max_key_str(&max, km, n);
8626 if (err)
8627 return err;
8629 for (i = 0; i < n; ++i) {
8630 if (km[i].keys == NULL) {
8631 show = s->all;
8632 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8633 km[i].type == s->type || s->all)
8634 show = 1;
8636 if (show) {
8637 err = format_help_line(&off, s->f, &km[i], max);
8638 if (err)
8639 return err;
8640 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8641 if (err)
8642 return err;
8645 fputc('\n', s->f);
8646 ++off;
8647 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8648 return err;
8651 static const struct got_error *
8652 create_help(struct tog_help_view_state *s)
8654 FILE *f;
8655 const struct got_error *err;
8657 free(s->line_offsets);
8658 s->line_offsets = NULL;
8659 s->nlines = 0;
8661 f = got_opentemp();
8662 if (f == NULL)
8663 return got_error_from_errno("got_opentemp");
8664 s->f = f;
8666 err = format_help(s);
8667 if (err)
8668 return err;
8670 if (s->f && fflush(s->f) != 0)
8671 return got_error_from_errno("fflush");
8673 return NULL;
8676 static const struct got_error *
8677 search_start_help_view(struct tog_view *view)
8679 view->state.help.matched_line = 0;
8680 return NULL;
8683 static void
8684 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8685 size_t *nlines, int **first, int **last, int **match, int **selected)
8687 struct tog_help_view_state *s = &view->state.help;
8689 *f = s->f;
8690 *nlines = s->nlines;
8691 *line_offsets = s->line_offsets;
8692 *match = &s->matched_line;
8693 *first = &s->first_displayed_line;
8694 *last = &s->last_displayed_line;
8695 *selected = &s->selected_line;
8698 static const struct got_error *
8699 show_help_view(struct tog_view *view)
8701 struct tog_help_view_state *s = &view->state.help;
8702 const struct got_error *err;
8703 regmatch_t *regmatch = &view->regmatch;
8704 wchar_t *wline;
8705 char *line;
8706 ssize_t linelen;
8707 size_t linesz = 0;
8708 int width, nprinted = 0, rc = 0;
8709 int eos = view->nlines;
8711 if (view_is_hsplit_top(view))
8712 --eos; /* account for border */
8714 s->lineno = 0;
8715 rewind(s->f);
8716 werase(view->window);
8718 if (view->gline > s->nlines - 1)
8719 view->gline = s->nlines - 1;
8721 err = win_draw_center(view->window, 0, 0, view->ncols,
8722 view_needs_focus_indication(view),
8723 "tog help (press q to return to tog)");
8724 if (err)
8725 return err;
8726 if (eos <= 1)
8727 return NULL;
8728 waddstr(view->window, "\n\n");
8729 eos -= 2;
8731 s->eof = 0;
8732 view->maxx = 0;
8733 line = NULL;
8734 while (eos > 0 && nprinted < eos) {
8735 attr_t attr = 0;
8737 linelen = getline(&line, &linesz, s->f);
8738 if (linelen == -1) {
8739 if (!feof(s->f)) {
8740 free(line);
8741 return got_ferror(s->f, GOT_ERR_IO);
8743 s->eof = 1;
8744 break;
8746 if (++s->lineno < s->first_displayed_line)
8747 continue;
8748 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8749 continue;
8750 if (s->lineno == view->hiline)
8751 attr = A_STANDOUT;
8753 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8754 view->x ? 1 : 0);
8755 if (err) {
8756 free(line);
8757 return err;
8759 view->maxx = MAX(view->maxx, width);
8760 free(wline);
8761 wline = NULL;
8763 if (attr)
8764 wattron(view->window, attr);
8765 if (s->first_displayed_line + nprinted == s->matched_line &&
8766 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8767 err = add_matched_line(&width, line, view->ncols - 1, 0,
8768 view->window, view->x, regmatch);
8769 if (err) {
8770 free(line);
8771 return err;
8773 } else {
8774 int skip;
8776 err = format_line(&wline, &width, &skip, line,
8777 view->x, view->ncols - 1, 0, view->x ? 1 : 0);
8778 if (err) {
8779 free(line);
8780 return err;
8782 rc = waddwstr(view->window, &wline[skip]);
8783 free(wline);
8784 wline = NULL;
8785 if (rc == ERR)
8786 return got_error_msg(GOT_ERR_IO, "waddwstr");
8788 if (s->lineno == view->hiline) {
8789 while (width++ < view->ncols)
8790 waddch(view->window, ' ');
8791 } else {
8792 if (width <= view->ncols)
8793 waddch(view->window, '\n');
8795 if (attr)
8796 wattroff(view->window, attr);
8797 if (++nprinted == 1)
8798 s->first_displayed_line = s->lineno;
8800 free(line);
8801 if (nprinted > 0)
8802 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8803 else
8804 s->last_displayed_line = s->first_displayed_line;
8806 view_border(view);
8808 if (s->eof) {
8809 rc = waddnstr(view->window,
8810 "See the tog(1) manual page for full documentation",
8811 view->ncols - 1);
8812 if (rc == ERR)
8813 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8814 } else {
8815 wmove(view->window, view->nlines - 1, 0);
8816 wclrtoeol(view->window);
8817 wstandout(view->window);
8818 rc = waddnstr(view->window, "scroll down for more...",
8819 view->ncols - 1);
8820 if (rc == ERR)
8821 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8822 if (getcurx(view->window) < view->ncols - 6) {
8823 rc = wprintw(view->window, "[%.0f%%]",
8824 100.00 * s->last_displayed_line / s->nlines);
8825 if (rc == ERR)
8826 return got_error_msg(GOT_ERR_IO, "wprintw");
8828 wstandend(view->window);
8831 return NULL;
8834 static const struct got_error *
8835 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8837 struct tog_help_view_state *s = &view->state.help;
8838 const struct got_error *err = NULL;
8839 char *line = NULL;
8840 ssize_t linelen;
8841 size_t linesz = 0;
8842 int eos, nscroll;
8844 eos = nscroll = view->nlines;
8845 if (view_is_hsplit_top(view))
8846 --eos; /* border */
8848 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8850 switch (ch) {
8851 case '0':
8852 view->x = 0;
8853 break;
8854 case '$':
8855 view->x = MAX(view->maxx - view->ncols / 3, 0);
8856 view->count = 0;
8857 break;
8858 case KEY_RIGHT:
8859 case 'l':
8860 if (view->x + view->ncols / 3 < view->maxx)
8861 view->x += 2;
8862 else
8863 view->count = 0;
8864 break;
8865 case KEY_LEFT:
8866 case 'h':
8867 view->x -= MIN(view->x, 2);
8868 if (view->x <= 0)
8869 view->count = 0;
8870 break;
8871 case 'g':
8872 case KEY_HOME:
8873 s->first_displayed_line = 1;
8874 view->count = 0;
8875 break;
8876 case 'G':
8877 case KEY_END:
8878 view->count = 0;
8879 if (s->eof)
8880 break;
8881 s->first_displayed_line = (s->nlines - eos) + 3;
8882 s->eof = 1;
8883 break;
8884 case 'k':
8885 case KEY_UP:
8886 if (s->first_displayed_line > 1)
8887 --s->first_displayed_line;
8888 else
8889 view->count = 0;
8890 break;
8891 case CTRL('u'):
8892 case 'u':
8893 nscroll /= 2;
8894 /* FALL THROUGH */
8895 case KEY_PPAGE:
8896 case CTRL('b'):
8897 case 'b':
8898 if (s->first_displayed_line == 1) {
8899 view->count = 0;
8900 break;
8902 while (--nscroll > 0 && s->first_displayed_line > 1)
8903 s->first_displayed_line--;
8904 break;
8905 case 'j':
8906 case KEY_DOWN:
8907 case CTRL('n'):
8908 if (!s->eof)
8909 ++s->first_displayed_line;
8910 else
8911 view->count = 0;
8912 break;
8913 case CTRL('d'):
8914 case 'd':
8915 nscroll /= 2;
8916 /* FALL THROUGH */
8917 case KEY_NPAGE:
8918 case CTRL('f'):
8919 case 'f':
8920 case ' ':
8921 if (s->eof) {
8922 view->count = 0;
8923 break;
8925 while (!s->eof && --nscroll > 0) {
8926 linelen = getline(&line, &linesz, s->f);
8927 s->first_displayed_line++;
8928 if (linelen == -1) {
8929 if (feof(s->f))
8930 s->eof = 1;
8931 else
8932 err = got_ferror(s->f, GOT_ERR_IO);
8933 break;
8936 free(line);
8937 break;
8938 default:
8939 view->count = 0;
8940 break;
8943 return err;
8946 static const struct got_error *
8947 close_help_view(struct tog_view *view)
8949 struct tog_help_view_state *s = &view->state.help;
8951 free(s->line_offsets);
8952 s->line_offsets = NULL;
8953 if (fclose(s->f) == EOF)
8954 return got_error_from_errno("fclose");
8956 return NULL;
8959 static const struct got_error *
8960 reset_help_view(struct tog_view *view)
8962 struct tog_help_view_state *s = &view->state.help;
8965 if (s->f && fclose(s->f) == EOF)
8966 return got_error_from_errno("fclose");
8968 wclear(view->window);
8969 view->count = 0;
8970 view->x = 0;
8971 s->all = !s->all;
8972 s->first_displayed_line = 1;
8973 s->last_displayed_line = view->nlines;
8974 s->matched_line = 0;
8976 return create_help(s);
8979 static const struct got_error *
8980 open_help_view(struct tog_view *view, struct tog_view *parent)
8982 const struct got_error *err = NULL;
8983 struct tog_help_view_state *s = &view->state.help;
8985 s->type = (enum tog_keymap_type)parent->type;
8986 s->first_displayed_line = 1;
8987 s->last_displayed_line = view->nlines;
8988 s->selected_line = 1;
8990 view->show = show_help_view;
8991 view->input = input_help_view;
8992 view->reset = reset_help_view;
8993 view->close = close_help_view;
8994 view->search_start = search_start_help_view;
8995 view->search_setup = search_setup_help_view;
8996 view->search_next = search_next_view_match;
8998 err = create_help(s);
8999 return err;
9002 static const struct got_error *
9003 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9004 enum tog_view_type request, int y, int x)
9006 const struct got_error *err = NULL;
9008 *new_view = NULL;
9010 switch (request) {
9011 case TOG_VIEW_DIFF:
9012 if (view->type == TOG_VIEW_LOG) {
9013 struct tog_log_view_state *s = &view->state.log;
9015 err = open_diff_view_for_commit(new_view, y, x,
9016 s->selected_entry->commit, s->selected_entry->id,
9017 view, s->repo);
9018 } else
9019 return got_error_msg(GOT_ERR_NOT_IMPL,
9020 "parent/child view pair not supported");
9021 break;
9022 case TOG_VIEW_BLAME:
9023 if (view->type == TOG_VIEW_TREE) {
9024 struct tog_tree_view_state *s = &view->state.tree;
9026 err = blame_tree_entry(new_view, y, x,
9027 s->selected_entry, &s->parents, s->commit_id,
9028 s->repo);
9029 } else
9030 return got_error_msg(GOT_ERR_NOT_IMPL,
9031 "parent/child view pair not supported");
9032 break;
9033 case TOG_VIEW_LOG:
9034 if (view->type == TOG_VIEW_BLAME)
9035 err = log_annotated_line(new_view, y, x,
9036 view->state.blame.repo, view->state.blame.id_to_log);
9037 else if (view->type == TOG_VIEW_TREE)
9038 err = log_selected_tree_entry(new_view, y, x,
9039 &view->state.tree);
9040 else if (view->type == TOG_VIEW_REF)
9041 err = log_ref_entry(new_view, y, x,
9042 view->state.ref.selected_entry,
9043 view->state.ref.repo);
9044 else
9045 return got_error_msg(GOT_ERR_NOT_IMPL,
9046 "parent/child view pair not supported");
9047 break;
9048 case TOG_VIEW_TREE:
9049 if (view->type == TOG_VIEW_LOG)
9050 err = browse_commit_tree(new_view, y, x,
9051 view->state.log.selected_entry,
9052 view->state.log.in_repo_path,
9053 view->state.log.head_ref_name,
9054 view->state.log.repo);
9055 else if (view->type == TOG_VIEW_REF)
9056 err = browse_ref_tree(new_view, y, x,
9057 view->state.ref.selected_entry,
9058 view->state.ref.repo);
9059 else
9060 return got_error_msg(GOT_ERR_NOT_IMPL,
9061 "parent/child view pair not supported");
9062 break;
9063 case TOG_VIEW_REF:
9064 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9065 if (*new_view == NULL)
9066 return got_error_from_errno("view_open");
9067 if (view->type == TOG_VIEW_LOG)
9068 err = open_ref_view(*new_view, view->state.log.repo);
9069 else if (view->type == TOG_VIEW_TREE)
9070 err = open_ref_view(*new_view, view->state.tree.repo);
9071 else
9072 err = got_error_msg(GOT_ERR_NOT_IMPL,
9073 "parent/child view pair not supported");
9074 if (err)
9075 view_close(*new_view);
9076 break;
9077 case TOG_VIEW_HELP:
9078 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9079 if (*new_view == NULL)
9080 return got_error_from_errno("view_open");
9081 err = open_help_view(*new_view, view);
9082 if (err)
9083 view_close(*new_view);
9084 break;
9085 default:
9086 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9089 return err;
9093 * If view was scrolled down to move the selected line into view when opening a
9094 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9096 static void
9097 offset_selection_up(struct tog_view *view)
9099 switch (view->type) {
9100 case TOG_VIEW_BLAME: {
9101 struct tog_blame_view_state *s = &view->state.blame;
9102 if (s->first_displayed_line == 1) {
9103 s->selected_line = MAX(s->selected_line - view->offset,
9104 1);
9105 break;
9107 if (s->first_displayed_line > view->offset)
9108 s->first_displayed_line -= view->offset;
9109 else
9110 s->first_displayed_line = 1;
9111 s->selected_line += view->offset;
9112 break;
9114 case TOG_VIEW_LOG:
9115 log_scroll_up(&view->state.log, view->offset);
9116 view->state.log.selected += view->offset;
9117 break;
9118 case TOG_VIEW_REF:
9119 ref_scroll_up(&view->state.ref, view->offset);
9120 view->state.ref.selected += view->offset;
9121 break;
9122 case TOG_VIEW_TREE:
9123 tree_scroll_up(&view->state.tree, view->offset);
9124 view->state.tree.selected += view->offset;
9125 break;
9126 default:
9127 break;
9130 view->offset = 0;
9134 * If the selected line is in the section of screen covered by the bottom split,
9135 * scroll down offset lines to move it into view and index its new position.
9137 static const struct got_error *
9138 offset_selection_down(struct tog_view *view)
9140 const struct got_error *err = NULL;
9141 const struct got_error *(*scrolld)(struct tog_view *, int);
9142 int *selected = NULL;
9143 int header, offset;
9145 switch (view->type) {
9146 case TOG_VIEW_BLAME: {
9147 struct tog_blame_view_state *s = &view->state.blame;
9148 header = 3;
9149 scrolld = NULL;
9150 if (s->selected_line > view->nlines - header) {
9151 offset = abs(view->nlines - s->selected_line - header);
9152 s->first_displayed_line += offset;
9153 s->selected_line -= offset;
9154 view->offset = offset;
9156 break;
9158 case TOG_VIEW_LOG: {
9159 struct tog_log_view_state *s = &view->state.log;
9160 scrolld = &log_scroll_down;
9161 header = view_is_parent_view(view) ? 3 : 2;
9162 selected = &s->selected;
9163 break;
9165 case TOG_VIEW_REF: {
9166 struct tog_ref_view_state *s = &view->state.ref;
9167 scrolld = &ref_scroll_down;
9168 header = 3;
9169 selected = &s->selected;
9170 break;
9172 case TOG_VIEW_TREE: {
9173 struct tog_tree_view_state *s = &view->state.tree;
9174 scrolld = &tree_scroll_down;
9175 header = 5;
9176 selected = &s->selected;
9177 break;
9179 default:
9180 selected = NULL;
9181 scrolld = NULL;
9182 header = 0;
9183 break;
9186 if (selected && *selected > view->nlines - header) {
9187 offset = abs(view->nlines - *selected - header);
9188 view->offset = offset;
9189 if (scrolld && offset) {
9190 err = scrolld(view, offset);
9191 *selected -= offset;
9195 return err;
9198 static void
9199 list_commands(FILE *fp)
9201 size_t i;
9203 fprintf(fp, "commands:");
9204 for (i = 0; i < nitems(tog_commands); i++) {
9205 const struct tog_cmd *cmd = &tog_commands[i];
9206 fprintf(fp, " %s", cmd->name);
9208 fputc('\n', fp);
9211 __dead static void
9212 usage(int hflag, int status)
9214 FILE *fp = (status == 0) ? stdout : stderr;
9216 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9217 getprogname());
9218 if (hflag) {
9219 fprintf(fp, "lazy usage: %s path\n", getprogname());
9220 list_commands(fp);
9222 exit(status);
9225 static char **
9226 make_argv(int argc, ...)
9228 va_list ap;
9229 char **argv;
9230 int i;
9232 va_start(ap, argc);
9234 argv = calloc(argc, sizeof(char *));
9235 if (argv == NULL)
9236 err(1, "calloc");
9237 for (i = 0; i < argc; i++) {
9238 argv[i] = strdup(va_arg(ap, char *));
9239 if (argv[i] == NULL)
9240 err(1, "strdup");
9243 va_end(ap);
9244 return argv;
9248 * Try to convert 'tog path' into a 'tog log path' command.
9249 * The user could simply have mistyped the command rather than knowingly
9250 * provided a path. So check whether argv[0] can in fact be resolved
9251 * to a path in the HEAD commit and print a special error if not.
9252 * This hack is for mpi@ <3
9254 static const struct got_error *
9255 tog_log_with_path(int argc, char *argv[])
9257 const struct got_error *error = NULL, *close_err;
9258 const struct tog_cmd *cmd = NULL;
9259 struct got_repository *repo = NULL;
9260 struct got_worktree *worktree = NULL;
9261 struct got_object_id *commit_id = NULL, *id = NULL;
9262 struct got_commit_object *commit = NULL;
9263 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9264 char *commit_id_str = NULL, **cmd_argv = NULL;
9265 int *pack_fds = NULL;
9267 cwd = getcwd(NULL, 0);
9268 if (cwd == NULL)
9269 return got_error_from_errno("getcwd");
9271 error = got_repo_pack_fds_open(&pack_fds);
9272 if (error != NULL)
9273 goto done;
9275 error = got_worktree_open(&worktree, cwd);
9276 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9277 goto done;
9279 if (worktree)
9280 repo_path = strdup(got_worktree_get_repo_path(worktree));
9281 else
9282 repo_path = strdup(cwd);
9283 if (repo_path == NULL) {
9284 error = got_error_from_errno("strdup");
9285 goto done;
9288 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9289 if (error != NULL)
9290 goto done;
9292 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9293 repo, worktree);
9294 if (error)
9295 goto done;
9297 error = tog_load_refs(repo, 0);
9298 if (error)
9299 goto done;
9300 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9301 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9302 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9303 if (error)
9304 goto done;
9306 if (worktree) {
9307 got_worktree_close(worktree);
9308 worktree = NULL;
9311 error = got_object_open_as_commit(&commit, repo, commit_id);
9312 if (error)
9313 goto done;
9315 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9316 if (error) {
9317 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9318 goto done;
9319 fprintf(stderr, "%s: '%s' is no known command or path\n",
9320 getprogname(), argv[0]);
9321 usage(1, 1);
9322 /* not reached */
9325 error = got_object_id_str(&commit_id_str, commit_id);
9326 if (error)
9327 goto done;
9329 cmd = &tog_commands[0]; /* log */
9330 argc = 4;
9331 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9332 error = cmd->cmd_main(argc, cmd_argv);
9333 done:
9334 if (repo) {
9335 close_err = got_repo_close(repo);
9336 if (error == NULL)
9337 error = close_err;
9339 if (commit)
9340 got_object_commit_close(commit);
9341 if (worktree)
9342 got_worktree_close(worktree);
9343 if (pack_fds) {
9344 const struct got_error *pack_err =
9345 got_repo_pack_fds_close(pack_fds);
9346 if (error == NULL)
9347 error = pack_err;
9349 free(id);
9350 free(commit_id_str);
9351 free(commit_id);
9352 free(cwd);
9353 free(repo_path);
9354 free(in_repo_path);
9355 if (cmd_argv) {
9356 int i;
9357 for (i = 0; i < argc; i++)
9358 free(cmd_argv[i]);
9359 free(cmd_argv);
9361 tog_free_refs();
9362 return error;
9365 int
9366 main(int argc, char *argv[])
9368 const struct got_error *error = NULL;
9369 const struct tog_cmd *cmd = NULL;
9370 int ch, hflag = 0, Vflag = 0;
9371 char **cmd_argv = NULL;
9372 static const struct option longopts[] = {
9373 { "version", no_argument, NULL, 'V' },
9374 { NULL, 0, NULL, 0}
9376 char *diff_algo_str = NULL;
9378 if (!isatty(STDIN_FILENO))
9379 errx(1, "standard input is not a tty");
9381 setlocale(LC_CTYPE, "");
9383 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9384 switch (ch) {
9385 case 'h':
9386 hflag = 1;
9387 break;
9388 case 'V':
9389 Vflag = 1;
9390 break;
9391 default:
9392 usage(hflag, 1);
9393 /* NOTREACHED */
9397 argc -= optind;
9398 argv += optind;
9399 optind = 1;
9400 optreset = 1;
9402 if (Vflag) {
9403 got_version_print_str();
9404 return 0;
9407 #ifndef PROFILE
9408 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9409 NULL) == -1)
9410 err(1, "pledge");
9411 #endif
9413 if (argc == 0) {
9414 if (hflag)
9415 usage(hflag, 0);
9416 /* Build an argument vector which runs a default command. */
9417 cmd = &tog_commands[0];
9418 argc = 1;
9419 cmd_argv = make_argv(argc, cmd->name);
9420 } else {
9421 size_t i;
9423 /* Did the user specify a command? */
9424 for (i = 0; i < nitems(tog_commands); i++) {
9425 if (strncmp(tog_commands[i].name, argv[0],
9426 strlen(argv[0])) == 0) {
9427 cmd = &tog_commands[i];
9428 break;
9433 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9434 if (diff_algo_str) {
9435 if (strcasecmp(diff_algo_str, "patience") == 0)
9436 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9437 if (strcasecmp(diff_algo_str, "myers") == 0)
9438 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9441 if (cmd == NULL) {
9442 if (argc != 1)
9443 usage(0, 1);
9444 /* No command specified; try log with a path */
9445 error = tog_log_with_path(argc, argv);
9446 } else {
9447 if (hflag)
9448 cmd->cmd_usage();
9449 else
9450 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9453 endwin();
9454 putchar('\n');
9455 if (cmd_argv) {
9456 int i;
9457 for (i = 0; i < argc; i++)
9458 free(cmd_argv[i]);
9459 free(cmd_argv);
9462 if (error && error->code != GOT_ERR_CANCELLED &&
9463 error->code != GOT_ERR_EOF &&
9464 error->code != GOT_ERR_PRIVSEP_EXIT &&
9465 error->code != GOT_ERR_PRIVSEP_PIPE &&
9466 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9467 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9468 return 0;