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 const char *action;
694 };
696 static const struct got_error *open_diff_view(struct tog_view *,
697 struct got_object_id *, struct got_object_id *,
698 const char *, const char *, int, int, int, struct tog_view *,
699 struct got_repository *);
700 static const struct got_error *show_diff_view(struct tog_view *);
701 static const struct got_error *input_diff_view(struct tog_view **,
702 struct tog_view *, int);
703 static const struct got_error *reset_diff_view(struct tog_view *);
704 static const struct got_error* close_diff_view(struct tog_view *);
705 static const struct got_error *search_start_diff_view(struct tog_view *);
706 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
707 size_t *, int **, int **, int **, int **);
708 static const struct got_error *search_next_view_match(struct tog_view *);
710 static const struct got_error *open_log_view(struct tog_view *,
711 struct got_object_id *, struct got_repository *,
712 const char *, const char *, int);
713 static const struct got_error * show_log_view(struct tog_view *);
714 static const struct got_error *input_log_view(struct tog_view **,
715 struct tog_view *, int);
716 static const struct got_error *resize_log_view(struct tog_view *, int);
717 static const struct got_error *close_log_view(struct tog_view *);
718 static const struct got_error *search_start_log_view(struct tog_view *);
719 static const struct got_error *search_next_log_view(struct tog_view *);
721 static const struct got_error *open_blame_view(struct tog_view *, char *,
722 struct got_object_id *, struct got_repository *);
723 static const struct got_error *show_blame_view(struct tog_view *);
724 static const struct got_error *input_blame_view(struct tog_view **,
725 struct tog_view *, int);
726 static const struct got_error *reset_blame_view(struct tog_view *);
727 static const struct got_error *close_blame_view(struct tog_view *);
728 static const struct got_error *search_start_blame_view(struct tog_view *);
729 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
730 size_t *, int **, int **, int **, int **);
732 static const struct got_error *open_tree_view(struct tog_view *,
733 struct got_object_id *, const char *, struct got_repository *);
734 static const struct got_error *show_tree_view(struct tog_view *);
735 static const struct got_error *input_tree_view(struct tog_view **,
736 struct tog_view *, int);
737 static const struct got_error *close_tree_view(struct tog_view *);
738 static const struct got_error *search_start_tree_view(struct tog_view *);
739 static const struct got_error *search_next_tree_view(struct tog_view *);
741 static const struct got_error *open_ref_view(struct tog_view *,
742 struct got_repository *);
743 static const struct got_error *show_ref_view(struct tog_view *);
744 static const struct got_error *input_ref_view(struct tog_view **,
745 struct tog_view *, int);
746 static const struct got_error *close_ref_view(struct tog_view *);
747 static const struct got_error *search_start_ref_view(struct tog_view *);
748 static const struct got_error *search_next_ref_view(struct tog_view *);
750 static const struct got_error *open_help_view(struct tog_view *,
751 struct tog_view *);
752 static const struct got_error *show_help_view(struct tog_view *);
753 static const struct got_error *input_help_view(struct tog_view **,
754 struct tog_view *, int);
755 static const struct got_error *reset_help_view(struct tog_view *);
756 static const struct got_error* close_help_view(struct tog_view *);
757 static const struct got_error *search_start_help_view(struct tog_view *);
758 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
759 size_t *, int **, int **, int **, int **);
761 static volatile sig_atomic_t tog_sigwinch_received;
762 static volatile sig_atomic_t tog_sigpipe_received;
763 static volatile sig_atomic_t tog_sigcont_received;
764 static volatile sig_atomic_t tog_sigint_received;
765 static volatile sig_atomic_t tog_sigterm_received;
767 static void
768 tog_sigwinch(int signo)
770 tog_sigwinch_received = 1;
773 static void
774 tog_sigpipe(int signo)
776 tog_sigpipe_received = 1;
779 static void
780 tog_sigcont(int signo)
782 tog_sigcont_received = 1;
785 static void
786 tog_sigint(int signo)
788 tog_sigint_received = 1;
791 static void
792 tog_sigterm(int signo)
794 tog_sigterm_received = 1;
797 static int
798 tog_fatal_signal_received(void)
800 return (tog_sigpipe_received ||
801 tog_sigint_received || tog_sigterm_received);
804 static const struct got_error *
805 view_close(struct tog_view *view)
807 const struct got_error *err = NULL, *child_err = NULL;
809 if (view->child) {
810 child_err = view_close(view->child);
811 view->child = NULL;
813 if (view->close)
814 err = view->close(view);
815 if (view->panel)
816 del_panel(view->panel);
817 if (view->window)
818 delwin(view->window);
819 free(view);
820 return err ? err : child_err;
823 static struct tog_view *
824 view_open(int nlines, int ncols, int begin_y, int begin_x,
825 enum tog_view_type type)
827 struct tog_view *view = calloc(1, sizeof(*view));
829 if (view == NULL)
830 return NULL;
832 view->type = type;
833 view->lines = LINES;
834 view->cols = COLS;
835 view->nlines = nlines ? nlines : LINES - begin_y;
836 view->ncols = ncols ? ncols : COLS - begin_x;
837 view->begin_y = begin_y;
838 view->begin_x = begin_x;
839 view->window = newwin(nlines, ncols, begin_y, begin_x);
840 if (view->window == NULL) {
841 view_close(view);
842 return NULL;
844 view->panel = new_panel(view->window);
845 if (view->panel == NULL ||
846 set_panel_userptr(view->panel, view) != OK) {
847 view_close(view);
848 return NULL;
851 keypad(view->window, TRUE);
852 return view;
855 static int
856 view_split_begin_x(int begin_x)
858 if (begin_x > 0 || COLS < 120)
859 return 0;
860 return (COLS - MAX(COLS / 2, 80));
863 /* XXX Stub till we decide what to do. */
864 static int
865 view_split_begin_y(int lines)
867 return lines * HSPLIT_SCALE;
870 static const struct got_error *view_resize(struct tog_view *);
872 static const struct got_error *
873 view_splitscreen(struct tog_view *view)
875 const struct got_error *err = NULL;
877 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
878 if (view->resized_y && view->resized_y < view->lines)
879 view->begin_y = view->resized_y;
880 else
881 view->begin_y = view_split_begin_y(view->nlines);
882 view->begin_x = 0;
883 } else if (!view->resized) {
884 if (view->resized_x && view->resized_x < view->cols - 1 &&
885 view->cols > 119)
886 view->begin_x = view->resized_x;
887 else
888 view->begin_x = view_split_begin_x(0);
889 view->begin_y = 0;
891 view->nlines = LINES - view->begin_y;
892 view->ncols = COLS - view->begin_x;
893 view->lines = LINES;
894 view->cols = COLS;
895 err = view_resize(view);
896 if (err)
897 return err;
899 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
900 view->parent->nlines = view->begin_y;
902 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
903 return got_error_from_errno("mvwin");
905 return NULL;
908 static const struct got_error *
909 view_fullscreen(struct tog_view *view)
911 const struct got_error *err = NULL;
913 view->begin_x = 0;
914 view->begin_y = view->resized ? view->begin_y : 0;
915 view->nlines = view->resized ? view->nlines : LINES;
916 view->ncols = COLS;
917 view->lines = LINES;
918 view->cols = COLS;
919 err = view_resize(view);
920 if (err)
921 return err;
923 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
924 return got_error_from_errno("mvwin");
926 return NULL;
929 static int
930 view_is_parent_view(struct tog_view *view)
932 return view->parent == NULL;
935 static int
936 view_is_splitscreen(struct tog_view *view)
938 return view->begin_x > 0 || view->begin_y > 0;
941 static int
942 view_is_fullscreen(struct tog_view *view)
944 return view->nlines == LINES && view->ncols == COLS;
947 static int
948 view_is_hsplit_top(struct tog_view *view)
950 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
951 view_is_splitscreen(view->child);
954 static void
955 view_border(struct tog_view *view)
957 PANEL *panel;
958 const struct tog_view *view_above;
960 if (view->parent)
961 return view_border(view->parent);
963 panel = panel_above(view->panel);
964 if (panel == NULL)
965 return;
967 view_above = panel_userptr(panel);
968 if (view->mode == TOG_VIEW_SPLIT_HRZN)
969 mvwhline(view->window, view_above->begin_y - 1,
970 view->begin_x, got_locale_is_utf8() ?
971 ACS_HLINE : '-', view->ncols);
972 else
973 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
974 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
977 static const struct got_error *view_init_hsplit(struct tog_view *, int);
978 static const struct got_error *request_log_commits(struct tog_view *);
979 static const struct got_error *offset_selection_down(struct tog_view *);
980 static void offset_selection_up(struct tog_view *);
981 static void view_get_split(struct tog_view *, int *, int *);
983 static const struct got_error *
984 view_resize(struct tog_view *view)
986 const struct got_error *err = NULL;
987 int dif, nlines, ncols;
989 dif = LINES - view->lines; /* line difference */
991 if (view->lines > LINES)
992 nlines = view->nlines - (view->lines - LINES);
993 else
994 nlines = view->nlines + (LINES - view->lines);
995 if (view->cols > COLS)
996 ncols = view->ncols - (view->cols - COLS);
997 else
998 ncols = view->ncols + (COLS - view->cols);
1000 if (view->child) {
1001 int hs = view->child->begin_y;
1003 if (!view_is_fullscreen(view))
1004 view->child->begin_x = view_split_begin_x(view->begin_x);
1005 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1006 view->child->begin_x == 0) {
1007 ncols = COLS;
1009 view_fullscreen(view->child);
1010 if (view->child->focussed)
1011 show_panel(view->child->panel);
1012 else
1013 show_panel(view->panel);
1014 } else {
1015 ncols = view->child->begin_x;
1017 view_splitscreen(view->child);
1018 show_panel(view->child->panel);
1021 * XXX This is ugly and needs to be moved into the above
1022 * logic but "works" for now and my attempts at moving it
1023 * break either 'tab' or 'F' key maps in horizontal splits.
1025 if (hs) {
1026 err = view_splitscreen(view->child);
1027 if (err)
1028 return err;
1029 if (dif < 0) { /* top split decreased */
1030 err = offset_selection_down(view);
1031 if (err)
1032 return err;
1034 view_border(view);
1035 update_panels();
1036 doupdate();
1037 show_panel(view->child->panel);
1038 nlines = view->nlines;
1040 } else if (view->parent == NULL)
1041 ncols = COLS;
1043 if (view->resize && dif > 0) {
1044 err = view->resize(view, dif);
1045 if (err)
1046 return err;
1049 if (wresize(view->window, nlines, ncols) == ERR)
1050 return got_error_from_errno("wresize");
1051 if (replace_panel(view->panel, view->window) == ERR)
1052 return got_error_from_errno("replace_panel");
1053 wclear(view->window);
1055 view->nlines = nlines;
1056 view->ncols = ncols;
1057 view->lines = LINES;
1058 view->cols = COLS;
1060 return NULL;
1063 static const struct got_error *
1064 resize_log_view(struct tog_view *view, int increase)
1066 struct tog_log_view_state *s = &view->state.log;
1067 const struct got_error *err = NULL;
1068 int n = 0;
1070 if (s->selected_entry)
1071 n = s->selected_entry->idx + view->lines - s->selected;
1074 * Request commits to account for the increased
1075 * height so we have enough to populate the view.
1077 if (s->commits->ncommits < n) {
1078 view->nscrolled = n - s->commits->ncommits + increase + 1;
1079 err = request_log_commits(view);
1082 return err;
1085 static void
1086 view_adjust_offset(struct tog_view *view, int n)
1088 if (n == 0)
1089 return;
1091 if (view->parent && view->parent->offset) {
1092 if (view->parent->offset + n >= 0)
1093 view->parent->offset += n;
1094 else
1095 view->parent->offset = 0;
1096 } else if (view->offset) {
1097 if (view->offset - n >= 0)
1098 view->offset -= n;
1099 else
1100 view->offset = 0;
1104 static const struct got_error *
1105 view_resize_split(struct tog_view *view, int resize)
1107 const struct got_error *err = NULL;
1108 struct tog_view *v = NULL;
1110 if (view->parent)
1111 v = view->parent;
1112 else
1113 v = view;
1115 if (!v->child || !view_is_splitscreen(v->child))
1116 return NULL;
1118 v->resized = v->child->resized = resize; /* lock for resize event */
1120 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1121 if (v->child->resized_y)
1122 v->child->begin_y = v->child->resized_y;
1123 if (view->parent)
1124 v->child->begin_y -= resize;
1125 else
1126 v->child->begin_y += resize;
1127 if (v->child->begin_y < 3) {
1128 view->count = 0;
1129 v->child->begin_y = 3;
1130 } else if (v->child->begin_y > LINES - 1) {
1131 view->count = 0;
1132 v->child->begin_y = LINES - 1;
1134 v->ncols = COLS;
1135 v->child->ncols = COLS;
1136 view_adjust_offset(view, resize);
1137 err = view_init_hsplit(v, v->child->begin_y);
1138 if (err)
1139 return err;
1140 v->child->resized_y = v->child->begin_y;
1141 } else {
1142 if (v->child->resized_x)
1143 v->child->begin_x = v->child->resized_x;
1144 if (view->parent)
1145 v->child->begin_x -= resize;
1146 else
1147 v->child->begin_x += resize;
1148 if (v->child->begin_x < 11) {
1149 view->count = 0;
1150 v->child->begin_x = 11;
1151 } else if (v->child->begin_x > COLS - 1) {
1152 view->count = 0;
1153 v->child->begin_x = COLS - 1;
1155 v->child->resized_x = v->child->begin_x;
1158 v->child->mode = v->mode;
1159 v->child->nlines = v->lines - v->child->begin_y;
1160 v->child->ncols = v->cols - v->child->begin_x;
1161 v->focus_child = 1;
1163 err = view_fullscreen(v);
1164 if (err)
1165 return err;
1166 err = view_splitscreen(v->child);
1167 if (err)
1168 return err;
1170 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1171 err = offset_selection_down(v->child);
1172 if (err)
1173 return err;
1176 if (v->resize)
1177 err = v->resize(v, 0);
1178 else if (v->child->resize)
1179 err = v->child->resize(v->child, 0);
1181 v->resized = v->child->resized = 0;
1183 return err;
1186 static void
1187 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1189 struct tog_view *v = src->child ? src->child : src;
1191 dst->resized_x = v->resized_x;
1192 dst->resized_y = v->resized_y;
1195 static const struct got_error *
1196 view_close_child(struct tog_view *view)
1198 const struct got_error *err = NULL;
1200 if (view->child == NULL)
1201 return NULL;
1203 err = view_close(view->child);
1204 view->child = NULL;
1205 return err;
1208 static const struct got_error *
1209 view_set_child(struct tog_view *view, struct tog_view *child)
1211 const struct got_error *err = NULL;
1213 view->child = child;
1214 child->parent = view;
1216 err = view_resize(view);
1217 if (err)
1218 return err;
1220 if (view->child->resized_x || view->child->resized_y)
1221 err = view_resize_split(view, 0);
1223 return err;
1226 static const struct got_error *view_dispatch_request(struct tog_view **,
1227 struct tog_view *, enum tog_view_type, int, int);
1229 static const struct got_error *
1230 view_request_new(struct tog_view **requested, struct tog_view *view,
1231 enum tog_view_type request)
1233 struct tog_view *new_view = NULL;
1234 const struct got_error *err;
1235 int y = 0, x = 0;
1237 *requested = NULL;
1239 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1240 view_get_split(view, &y, &x);
1242 err = view_dispatch_request(&new_view, view, request, y, x);
1243 if (err)
1244 return err;
1246 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1247 request != TOG_VIEW_HELP) {
1248 err = view_init_hsplit(view, y);
1249 if (err)
1250 return err;
1253 view->focussed = 0;
1254 new_view->focussed = 1;
1255 new_view->mode = view->mode;
1256 new_view->nlines = request == TOG_VIEW_HELP ?
1257 view->lines : view->lines - y;
1259 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1260 view_transfer_size(new_view, view);
1261 err = view_close_child(view);
1262 if (err)
1263 return err;
1264 err = view_set_child(view, new_view);
1265 if (err)
1266 return err;
1267 view->focus_child = 1;
1268 } else
1269 *requested = new_view;
1271 return NULL;
1274 static void
1275 tog_resizeterm(void)
1277 int cols, lines;
1278 struct winsize size;
1280 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1281 cols = 80; /* Default */
1282 lines = 24;
1283 } else {
1284 cols = size.ws_col;
1285 lines = size.ws_row;
1287 resize_term(lines, cols);
1290 static const struct got_error *
1291 view_search_start(struct tog_view *view)
1293 const struct got_error *err = NULL;
1294 struct tog_view *v = view;
1295 char pattern[1024];
1296 int ret;
1298 if (view->search_started) {
1299 regfree(&view->regex);
1300 view->searching = 0;
1301 memset(&view->regmatch, 0, sizeof(view->regmatch));
1303 view->search_started = 0;
1305 if (view->nlines < 1)
1306 return NULL;
1308 if (view_is_hsplit_top(view))
1309 v = view->child;
1310 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1311 v = view->parent;
1313 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1314 wclrtoeol(v->window);
1316 nodelay(v->window, FALSE); /* block for search term input */
1317 nocbreak();
1318 echo();
1319 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1320 wrefresh(v->window);
1321 cbreak();
1322 noecho();
1323 nodelay(v->window, TRUE);
1324 if (ret == ERR)
1325 return NULL;
1327 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1328 err = view->search_start(view);
1329 if (err) {
1330 regfree(&view->regex);
1331 return err;
1333 view->search_started = 1;
1334 view->searching = TOG_SEARCH_FORWARD;
1335 view->search_next_done = 0;
1336 view->search_next(view);
1339 return NULL;
1342 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1343 static const struct got_error *
1344 switch_split(struct tog_view *view)
1346 const struct got_error *err = NULL;
1347 struct tog_view *v = NULL;
1349 if (view->parent)
1350 v = view->parent;
1351 else
1352 v = view;
1354 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1355 v->mode = TOG_VIEW_SPLIT_VERT;
1356 else
1357 v->mode = TOG_VIEW_SPLIT_HRZN;
1359 if (!v->child)
1360 return NULL;
1361 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1362 v->mode = TOG_VIEW_SPLIT_NONE;
1364 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1365 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1366 v->child->begin_y = v->child->resized_y;
1367 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1368 v->child->begin_x = v->child->resized_x;
1371 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1372 v->ncols = COLS;
1373 v->child->ncols = COLS;
1374 v->child->nscrolled = LINES - v->child->nlines;
1376 err = view_init_hsplit(v, v->child->begin_y);
1377 if (err)
1378 return err;
1380 v->child->mode = v->mode;
1381 v->child->nlines = v->lines - v->child->begin_y;
1382 v->focus_child = 1;
1384 err = view_fullscreen(v);
1385 if (err)
1386 return err;
1387 err = view_splitscreen(v->child);
1388 if (err)
1389 return err;
1391 if (v->mode == TOG_VIEW_SPLIT_NONE)
1392 v->mode = TOG_VIEW_SPLIT_VERT;
1393 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1394 err = offset_selection_down(v);
1395 if (err)
1396 return err;
1397 err = offset_selection_down(v->child);
1398 if (err)
1399 return err;
1400 } else {
1401 offset_selection_up(v);
1402 offset_selection_up(v->child);
1404 if (v->resize)
1405 err = v->resize(v, 0);
1406 else if (v->child->resize)
1407 err = v->child->resize(v->child, 0);
1409 return err;
1413 * Compute view->count from numeric input. Assign total to view->count and
1414 * return first non-numeric key entered.
1416 static int
1417 get_compound_key(struct tog_view *view, int c)
1419 struct tog_view *v = view;
1420 int x, n = 0;
1422 if (view_is_hsplit_top(view))
1423 v = view->child;
1424 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1425 v = view->parent;
1427 view->count = 0;
1428 cbreak(); /* block for input */
1429 nodelay(view->window, FALSE);
1430 wmove(v->window, v->nlines - 1, 0);
1431 wclrtoeol(v->window);
1432 waddch(v->window, ':');
1434 do {
1435 x = getcurx(v->window);
1436 if (x != ERR && x < view->ncols) {
1437 waddch(v->window, c);
1438 wrefresh(v->window);
1442 * Don't overflow. Max valid request should be the greatest
1443 * between the longest and total lines; cap at 10 million.
1445 if (n >= 9999999)
1446 n = 9999999;
1447 else
1448 n = n * 10 + (c - '0');
1449 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1451 if (c == 'G' || c == 'g') { /* nG key map */
1452 view->gline = view->hiline = n;
1453 n = 0;
1454 c = 0;
1457 /* Massage excessive or inapplicable values at the input handler. */
1458 view->count = n;
1460 return c;
1463 static void
1464 action_report(struct tog_view *view)
1466 struct tog_view *v = view;
1468 if (view_is_hsplit_top(view))
1469 v = view->child;
1470 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1471 v = view->parent;
1473 wmove(v->window, v->nlines - 1, 0);
1474 wclrtoeol(v->window);
1475 wprintw(v->window, ":%s", view->action);
1476 wrefresh(v->window);
1479 * Clear action status report. Only clear in blame view
1480 * once annotating is complete, otherwise it's too fast.
1482 if (view->type == TOG_VIEW_BLAME) {
1483 if (view->state.blame.blame_complete)
1484 view->action = NULL;
1485 } else
1486 view->action = NULL;
1489 static const struct got_error *
1490 view_input(struct tog_view **new, int *done, struct tog_view *view,
1491 struct tog_view_list_head *views)
1493 const struct got_error *err = NULL;
1494 struct tog_view *v;
1495 int ch, errcode;
1497 *new = NULL;
1499 if (view->action)
1500 action_report(view);
1502 /* Clear "no matches" indicator. */
1503 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1504 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1505 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1506 view->count = 0;
1509 if (view->searching && !view->search_next_done) {
1510 errcode = pthread_mutex_unlock(&tog_mutex);
1511 if (errcode)
1512 return got_error_set_errno(errcode,
1513 "pthread_mutex_unlock");
1514 sched_yield();
1515 errcode = pthread_mutex_lock(&tog_mutex);
1516 if (errcode)
1517 return got_error_set_errno(errcode,
1518 "pthread_mutex_lock");
1519 view->search_next(view);
1520 return NULL;
1523 /* Allow threads to make progress while we are waiting for input. */
1524 errcode = pthread_mutex_unlock(&tog_mutex);
1525 if (errcode)
1526 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1527 /* If we have an unfinished count, let C-g or backspace abort. */
1528 if (view->count && --view->count) {
1529 cbreak();
1530 nodelay(view->window, TRUE);
1531 ch = wgetch(view->window);
1532 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1533 view->count = 0;
1534 else
1535 ch = view->ch;
1536 } else {
1537 ch = wgetch(view->window);
1538 if (ch >= '1' && ch <= '9')
1539 view->ch = ch = get_compound_key(view, ch);
1541 if (view->hiline && ch != ERR && ch != 0)
1542 view->hiline = 0; /* key pressed, clear line highlight */
1543 nodelay(view->window, TRUE);
1544 errcode = pthread_mutex_lock(&tog_mutex);
1545 if (errcode)
1546 return got_error_set_errno(errcode, "pthread_mutex_lock");
1548 if (tog_sigwinch_received || tog_sigcont_received) {
1549 tog_resizeterm();
1550 tog_sigwinch_received = 0;
1551 tog_sigcont_received = 0;
1552 TAILQ_FOREACH(v, views, entry) {
1553 err = view_resize(v);
1554 if (err)
1555 return err;
1556 err = v->input(new, v, KEY_RESIZE);
1557 if (err)
1558 return err;
1559 if (v->child) {
1560 err = view_resize(v->child);
1561 if (err)
1562 return err;
1563 err = v->child->input(new, v->child,
1564 KEY_RESIZE);
1565 if (err)
1566 return err;
1567 if (v->child->resized_x || v->child->resized_y) {
1568 err = view_resize_split(v, 0);
1569 if (err)
1570 return err;
1576 switch (ch) {
1577 case '?':
1578 case 'H':
1579 case KEY_F(1):
1580 if (view->type == TOG_VIEW_HELP)
1581 err = view->reset(view);
1582 else
1583 err = view_request_new(new, view, TOG_VIEW_HELP);
1584 break;
1585 case '\t':
1586 view->count = 0;
1587 if (view->child) {
1588 view->focussed = 0;
1589 view->child->focussed = 1;
1590 view->focus_child = 1;
1591 } else if (view->parent) {
1592 view->focussed = 0;
1593 view->parent->focussed = 1;
1594 view->parent->focus_child = 0;
1595 if (!view_is_splitscreen(view)) {
1596 if (view->parent->resize) {
1597 err = view->parent->resize(view->parent,
1598 0);
1599 if (err)
1600 return err;
1602 offset_selection_up(view->parent);
1603 err = view_fullscreen(view->parent);
1604 if (err)
1605 return err;
1608 break;
1609 case 'q':
1610 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1611 if (view->parent->resize) {
1612 /* might need more commits to fill fullscreen */
1613 err = view->parent->resize(view->parent, 0);
1614 if (err)
1615 break;
1617 offset_selection_up(view->parent);
1619 err = view->input(new, view, ch);
1620 view->dying = 1;
1621 break;
1622 case 'Q':
1623 *done = 1;
1624 break;
1625 case 'F':
1626 view->count = 0;
1627 if (view_is_parent_view(view)) {
1628 if (view->child == NULL)
1629 break;
1630 if (view_is_splitscreen(view->child)) {
1631 view->focussed = 0;
1632 view->child->focussed = 1;
1633 err = view_fullscreen(view->child);
1634 } else {
1635 err = view_splitscreen(view->child);
1636 if (!err)
1637 err = view_resize_split(view, 0);
1639 if (err)
1640 break;
1641 err = view->child->input(new, view->child,
1642 KEY_RESIZE);
1643 } else {
1644 if (view_is_splitscreen(view)) {
1645 view->parent->focussed = 0;
1646 view->focussed = 1;
1647 err = view_fullscreen(view);
1648 } else {
1649 err = view_splitscreen(view);
1650 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1651 err = view_resize(view->parent);
1652 if (!err)
1653 err = view_resize_split(view, 0);
1655 if (err)
1656 break;
1657 err = view->input(new, view, KEY_RESIZE);
1659 if (err)
1660 break;
1661 if (view->resize) {
1662 err = view->resize(view, 0);
1663 if (err)
1664 break;
1666 if (view->parent)
1667 err = offset_selection_down(view->parent);
1668 if (!err)
1669 err = offset_selection_down(view);
1670 break;
1671 case 'S':
1672 view->count = 0;
1673 err = switch_split(view);
1674 break;
1675 case '-':
1676 err = view_resize_split(view, -1);
1677 break;
1678 case '+':
1679 err = view_resize_split(view, 1);
1680 break;
1681 case KEY_RESIZE:
1682 break;
1683 case '/':
1684 view->count = 0;
1685 if (view->search_start)
1686 view_search_start(view);
1687 else
1688 err = view->input(new, view, ch);
1689 break;
1690 case 'N':
1691 case 'n':
1692 if (view->search_started && view->search_next) {
1693 view->searching = (ch == 'n' ?
1694 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1695 view->search_next_done = 0;
1696 view->search_next(view);
1697 } else
1698 err = view->input(new, view, ch);
1699 break;
1700 case 'A':
1701 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1702 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1703 view->action = "Patience diff algorithm";
1704 } else {
1705 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1706 view->action = "Myers diff algorithm";
1708 TAILQ_FOREACH(v, views, entry) {
1709 if (v->reset) {
1710 err = v->reset(v);
1711 if (err)
1712 return err;
1714 if (v->child && v->child->reset) {
1715 err = v->child->reset(v->child);
1716 if (err)
1717 return err;
1720 break;
1721 default:
1722 err = view->input(new, view, ch);
1723 break;
1726 return err;
1729 static int
1730 view_needs_focus_indication(struct tog_view *view)
1732 if (view_is_parent_view(view)) {
1733 if (view->child == NULL || view->child->focussed)
1734 return 0;
1735 if (!view_is_splitscreen(view->child))
1736 return 0;
1737 } else if (!view_is_splitscreen(view))
1738 return 0;
1740 return view->focussed;
1743 static const struct got_error *
1744 view_loop(struct tog_view *view)
1746 const struct got_error *err = NULL;
1747 struct tog_view_list_head views;
1748 struct tog_view *new_view;
1749 char *mode;
1750 int fast_refresh = 10;
1751 int done = 0, errcode;
1753 mode = getenv("TOG_VIEW_SPLIT_MODE");
1754 if (!mode || !(*mode == 'h' || *mode == 'H'))
1755 view->mode = TOG_VIEW_SPLIT_VERT;
1756 else
1757 view->mode = TOG_VIEW_SPLIT_HRZN;
1759 errcode = pthread_mutex_lock(&tog_mutex);
1760 if (errcode)
1761 return got_error_set_errno(errcode, "pthread_mutex_lock");
1763 TAILQ_INIT(&views);
1764 TAILQ_INSERT_HEAD(&views, view, entry);
1766 view->focussed = 1;
1767 err = view->show(view);
1768 if (err)
1769 return err;
1770 update_panels();
1771 doupdate();
1772 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1773 !tog_fatal_signal_received()) {
1774 /* Refresh fast during initialization, then become slower. */
1775 if (fast_refresh && --fast_refresh == 0)
1776 halfdelay(10); /* switch to once per second */
1778 err = view_input(&new_view, &done, view, &views);
1779 if (err)
1780 break;
1782 if (view->dying && view == TAILQ_FIRST(&views) &&
1783 TAILQ_NEXT(view, entry) == NULL)
1784 done = 1;
1785 if (done) {
1786 struct tog_view *v;
1789 * When we quit, scroll the screen up a single line
1790 * so we don't lose any information.
1792 TAILQ_FOREACH(v, &views, entry) {
1793 wmove(v->window, 0, 0);
1794 wdeleteln(v->window);
1795 wnoutrefresh(v->window);
1796 if (v->child && !view_is_fullscreen(v)) {
1797 wmove(v->child->window, 0, 0);
1798 wdeleteln(v->child->window);
1799 wnoutrefresh(v->child->window);
1802 doupdate();
1805 if (view->dying) {
1806 struct tog_view *v, *prev = NULL;
1808 if (view_is_parent_view(view))
1809 prev = TAILQ_PREV(view, tog_view_list_head,
1810 entry);
1811 else if (view->parent)
1812 prev = view->parent;
1814 if (view->parent) {
1815 view->parent->child = NULL;
1816 view->parent->focus_child = 0;
1817 /* Restore fullscreen line height. */
1818 view->parent->nlines = view->parent->lines;
1819 err = view_resize(view->parent);
1820 if (err)
1821 break;
1822 /* Make resized splits persist. */
1823 view_transfer_size(view->parent, view);
1824 } else
1825 TAILQ_REMOVE(&views, view, entry);
1827 err = view_close(view);
1828 if (err)
1829 goto done;
1831 view = NULL;
1832 TAILQ_FOREACH(v, &views, entry) {
1833 if (v->focussed)
1834 break;
1836 if (view == NULL && new_view == NULL) {
1837 /* No view has focus. Try to pick one. */
1838 if (prev)
1839 view = prev;
1840 else if (!TAILQ_EMPTY(&views)) {
1841 view = TAILQ_LAST(&views,
1842 tog_view_list_head);
1844 if (view) {
1845 if (view->focus_child) {
1846 view->child->focussed = 1;
1847 view = view->child;
1848 } else
1849 view->focussed = 1;
1853 if (new_view) {
1854 struct tog_view *v, *t;
1855 /* Only allow one parent view per type. */
1856 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1857 if (v->type != new_view->type)
1858 continue;
1859 TAILQ_REMOVE(&views, v, entry);
1860 err = view_close(v);
1861 if (err)
1862 goto done;
1863 break;
1865 TAILQ_INSERT_TAIL(&views, new_view, entry);
1866 view = new_view;
1868 if (view && !done) {
1869 if (view_is_parent_view(view)) {
1870 if (view->child && view->child->focussed)
1871 view = view->child;
1872 } else {
1873 if (view->parent && view->parent->focussed)
1874 view = view->parent;
1876 show_panel(view->panel);
1877 if (view->child && view_is_splitscreen(view->child))
1878 show_panel(view->child->panel);
1879 if (view->parent && view_is_splitscreen(view)) {
1880 err = view->parent->show(view->parent);
1881 if (err)
1882 goto done;
1884 err = view->show(view);
1885 if (err)
1886 goto done;
1887 if (view->child) {
1888 err = view->child->show(view->child);
1889 if (err)
1890 goto done;
1892 update_panels();
1893 doupdate();
1896 done:
1897 while (!TAILQ_EMPTY(&views)) {
1898 const struct got_error *close_err;
1899 view = TAILQ_FIRST(&views);
1900 TAILQ_REMOVE(&views, view, entry);
1901 close_err = view_close(view);
1902 if (close_err && err == NULL)
1903 err = close_err;
1906 errcode = pthread_mutex_unlock(&tog_mutex);
1907 if (errcode && err == NULL)
1908 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1910 return err;
1913 __dead static void
1914 usage_log(void)
1916 endwin();
1917 fprintf(stderr,
1918 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1919 getprogname());
1920 exit(1);
1923 /* Create newly allocated wide-character string equivalent to a byte string. */
1924 static const struct got_error *
1925 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1927 char *vis = NULL;
1928 const struct got_error *err = NULL;
1930 *ws = NULL;
1931 *wlen = mbstowcs(NULL, s, 0);
1932 if (*wlen == (size_t)-1) {
1933 int vislen;
1934 if (errno != EILSEQ)
1935 return got_error_from_errno("mbstowcs");
1937 /* byte string invalid in current encoding; try to "fix" it */
1938 err = got_mbsavis(&vis, &vislen, s);
1939 if (err)
1940 return err;
1941 *wlen = mbstowcs(NULL, vis, 0);
1942 if (*wlen == (size_t)-1) {
1943 err = got_error_from_errno("mbstowcs"); /* give up */
1944 goto done;
1948 *ws = calloc(*wlen + 1, sizeof(**ws));
1949 if (*ws == NULL) {
1950 err = got_error_from_errno("calloc");
1951 goto done;
1954 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1955 err = got_error_from_errno("mbstowcs");
1956 done:
1957 free(vis);
1958 if (err) {
1959 free(*ws);
1960 *ws = NULL;
1961 *wlen = 0;
1963 return err;
1966 static const struct got_error *
1967 expand_tab(char **ptr, const char *src)
1969 char *dst;
1970 size_t len, n, idx = 0, sz = 0;
1972 *ptr = NULL;
1973 n = len = strlen(src);
1974 dst = malloc(n + 1);
1975 if (dst == NULL)
1976 return got_error_from_errno("malloc");
1978 while (idx < len && src[idx]) {
1979 const char c = src[idx];
1981 if (c == '\t') {
1982 size_t nb = TABSIZE - sz % TABSIZE;
1983 char *p;
1985 p = realloc(dst, n + nb);
1986 if (p == NULL) {
1987 free(dst);
1988 return got_error_from_errno("realloc");
1991 dst = p;
1992 n += nb;
1993 memset(dst + sz, ' ', nb);
1994 sz += nb;
1995 } else
1996 dst[sz++] = src[idx];
1997 ++idx;
2000 dst[sz] = '\0';
2001 *ptr = dst;
2002 return NULL;
2006 * Advance at most n columns from wline starting at offset off.
2007 * Return the index to the first character after the span operation.
2008 * Return the combined column width of all spanned wide character in
2009 * *rcol.
2011 static int
2012 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2014 int width, i, cols = 0;
2016 if (n == 0) {
2017 *rcol = cols;
2018 return off;
2021 for (i = off; wline[i] != L'\0'; ++i) {
2022 if (wline[i] == L'\t')
2023 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2024 else
2025 width = wcwidth(wline[i]);
2027 if (width == -1) {
2028 width = 1;
2029 wline[i] = L'.';
2032 if (cols + width > n)
2033 break;
2034 cols += width;
2037 *rcol = cols;
2038 return i;
2042 * Format a line for display, ensuring that it won't overflow a width limit.
2043 * With scrolling, the width returned refers to the scrolled version of the
2044 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2046 static const struct got_error *
2047 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2048 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2050 const struct got_error *err = NULL;
2051 int cols;
2052 wchar_t *wline = NULL;
2053 char *exstr = NULL;
2054 size_t wlen;
2055 int i, scrollx;
2057 *wlinep = NULL;
2058 *widthp = 0;
2060 if (expand) {
2061 err = expand_tab(&exstr, line);
2062 if (err)
2063 return err;
2066 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2067 free(exstr);
2068 if (err)
2069 return err;
2071 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2073 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2074 wline[wlen - 1] = L'\0';
2075 wlen--;
2077 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2078 wline[wlen - 1] = L'\0';
2079 wlen--;
2082 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2083 wline[i] = L'\0';
2085 if (widthp)
2086 *widthp = cols;
2087 if (scrollxp)
2088 *scrollxp = scrollx;
2089 if (err)
2090 free(wline);
2091 else
2092 *wlinep = wline;
2093 return err;
2096 static const struct got_error*
2097 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2098 struct got_object_id *id, struct got_repository *repo)
2100 static const struct got_error *err = NULL;
2101 struct got_reflist_entry *re;
2102 char *s;
2103 const char *name;
2105 *refs_str = NULL;
2107 TAILQ_FOREACH(re, refs, entry) {
2108 struct got_tag_object *tag = NULL;
2109 struct got_object_id *ref_id;
2110 int cmp;
2112 name = got_ref_get_name(re->ref);
2113 if (strcmp(name, GOT_REF_HEAD) == 0)
2114 continue;
2115 if (strncmp(name, "refs/", 5) == 0)
2116 name += 5;
2117 if (strncmp(name, "got/", 4) == 0 &&
2118 strncmp(name, "got/backup/", 11) != 0)
2119 continue;
2120 if (strncmp(name, "heads/", 6) == 0)
2121 name += 6;
2122 if (strncmp(name, "remotes/", 8) == 0) {
2123 name += 8;
2124 s = strstr(name, "/" GOT_REF_HEAD);
2125 if (s != NULL && s[strlen(s)] == '\0')
2126 continue;
2128 err = got_ref_resolve(&ref_id, repo, re->ref);
2129 if (err)
2130 break;
2131 if (strncmp(name, "tags/", 5) == 0) {
2132 err = got_object_open_as_tag(&tag, repo, ref_id);
2133 if (err) {
2134 if (err->code != GOT_ERR_OBJ_TYPE) {
2135 free(ref_id);
2136 break;
2138 /* Ref points at something other than a tag. */
2139 err = NULL;
2140 tag = NULL;
2143 cmp = got_object_id_cmp(tag ?
2144 got_object_tag_get_object_id(tag) : ref_id, id);
2145 free(ref_id);
2146 if (tag)
2147 got_object_tag_close(tag);
2148 if (cmp != 0)
2149 continue;
2150 s = *refs_str;
2151 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2152 s ? ", " : "", name) == -1) {
2153 err = got_error_from_errno("asprintf");
2154 free(s);
2155 *refs_str = NULL;
2156 break;
2158 free(s);
2161 return err;
2164 static const struct got_error *
2165 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2166 int col_tab_align)
2168 char *smallerthan;
2170 smallerthan = strchr(author, '<');
2171 if (smallerthan && smallerthan[1] != '\0')
2172 author = smallerthan + 1;
2173 author[strcspn(author, "@>")] = '\0';
2174 return format_line(wauthor, author_width, NULL, author, 0, limit,
2175 col_tab_align, 0);
2178 static const struct got_error *
2179 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2180 struct got_object_id *id, const size_t date_display_cols,
2181 int author_display_cols)
2183 struct tog_log_view_state *s = &view->state.log;
2184 const struct got_error *err = NULL;
2185 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2186 char *logmsg0 = NULL, *logmsg = NULL;
2187 char *author = NULL;
2188 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2189 int author_width, logmsg_width;
2190 char *newline, *line = NULL;
2191 int col, limit, scrollx;
2192 const int avail = view->ncols;
2193 struct tm tm;
2194 time_t committer_time;
2195 struct tog_color *tc;
2197 committer_time = got_object_commit_get_committer_time(commit);
2198 if (gmtime_r(&committer_time, &tm) == NULL)
2199 return got_error_from_errno("gmtime_r");
2200 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2201 return got_error(GOT_ERR_NO_SPACE);
2203 if (avail <= date_display_cols)
2204 limit = MIN(sizeof(datebuf) - 1, avail);
2205 else
2206 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2207 tc = get_color(&s->colors, TOG_COLOR_DATE);
2208 if (tc)
2209 wattr_on(view->window,
2210 COLOR_PAIR(tc->colorpair), NULL);
2211 waddnstr(view->window, datebuf, limit);
2212 if (tc)
2213 wattr_off(view->window,
2214 COLOR_PAIR(tc->colorpair), NULL);
2215 col = limit;
2216 if (col > avail)
2217 goto done;
2219 if (avail >= 120) {
2220 char *id_str;
2221 err = got_object_id_str(&id_str, id);
2222 if (err)
2223 goto done;
2224 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2225 if (tc)
2226 wattr_on(view->window,
2227 COLOR_PAIR(tc->colorpair), NULL);
2228 wprintw(view->window, "%.8s ", id_str);
2229 if (tc)
2230 wattr_off(view->window,
2231 COLOR_PAIR(tc->colorpair), NULL);
2232 free(id_str);
2233 col += 9;
2234 if (col > avail)
2235 goto done;
2238 if (s->use_committer)
2239 author = strdup(got_object_commit_get_committer(commit));
2240 else
2241 author = strdup(got_object_commit_get_author(commit));
2242 if (author == NULL) {
2243 err = got_error_from_errno("strdup");
2244 goto done;
2246 err = format_author(&wauthor, &author_width, author, avail - col, col);
2247 if (err)
2248 goto done;
2249 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2250 if (tc)
2251 wattr_on(view->window,
2252 COLOR_PAIR(tc->colorpair), NULL);
2253 waddwstr(view->window, wauthor);
2254 col += author_width;
2255 while (col < avail && author_width < author_display_cols + 2) {
2256 waddch(view->window, ' ');
2257 col++;
2258 author_width++;
2260 if (tc)
2261 wattr_off(view->window,
2262 COLOR_PAIR(tc->colorpair), NULL);
2263 if (col > avail)
2264 goto done;
2266 err = got_object_commit_get_logmsg(&logmsg0, commit);
2267 if (err)
2268 goto done;
2269 logmsg = logmsg0;
2270 while (*logmsg == '\n')
2271 logmsg++;
2272 newline = strchr(logmsg, '\n');
2273 if (newline)
2274 *newline = '\0';
2275 limit = avail - col;
2276 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2277 limit--; /* for the border */
2278 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2279 limit, col, 1);
2280 if (err)
2281 goto done;
2282 waddwstr(view->window, &wlogmsg[scrollx]);
2283 col += MAX(logmsg_width, 0);
2284 while (col < avail) {
2285 waddch(view->window, ' ');
2286 col++;
2288 done:
2289 free(logmsg0);
2290 free(wlogmsg);
2291 free(author);
2292 free(wauthor);
2293 free(line);
2294 return err;
2297 static struct commit_queue_entry *
2298 alloc_commit_queue_entry(struct got_commit_object *commit,
2299 struct got_object_id *id)
2301 struct commit_queue_entry *entry;
2302 struct got_object_id *dup;
2304 entry = calloc(1, sizeof(*entry));
2305 if (entry == NULL)
2306 return NULL;
2308 dup = got_object_id_dup(id);
2309 if (dup == NULL) {
2310 free(entry);
2311 return NULL;
2314 entry->id = dup;
2315 entry->commit = commit;
2316 return entry;
2319 static void
2320 pop_commit(struct commit_queue *commits)
2322 struct commit_queue_entry *entry;
2324 entry = TAILQ_FIRST(&commits->head);
2325 TAILQ_REMOVE(&commits->head, entry, entry);
2326 got_object_commit_close(entry->commit);
2327 commits->ncommits--;
2328 free(entry->id);
2329 free(entry);
2332 static void
2333 free_commits(struct commit_queue *commits)
2335 while (!TAILQ_EMPTY(&commits->head))
2336 pop_commit(commits);
2339 static const struct got_error *
2340 match_commit(int *have_match, struct got_object_id *id,
2341 struct got_commit_object *commit, regex_t *regex)
2343 const struct got_error *err = NULL;
2344 regmatch_t regmatch;
2345 char *id_str = NULL, *logmsg = NULL;
2347 *have_match = 0;
2349 err = got_object_id_str(&id_str, id);
2350 if (err)
2351 return err;
2353 err = got_object_commit_get_logmsg(&logmsg, commit);
2354 if (err)
2355 goto done;
2357 if (regexec(regex, got_object_commit_get_author(commit), 1,
2358 &regmatch, 0) == 0 ||
2359 regexec(regex, got_object_commit_get_committer(commit), 1,
2360 &regmatch, 0) == 0 ||
2361 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2362 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2363 *have_match = 1;
2364 done:
2365 free(id_str);
2366 free(logmsg);
2367 return err;
2370 static const struct got_error *
2371 queue_commits(struct tog_log_thread_args *a)
2373 const struct got_error *err = NULL;
2376 * We keep all commits open throughout the lifetime of the log
2377 * view in order to avoid having to re-fetch commits from disk
2378 * while updating the display.
2380 do {
2381 struct got_object_id id;
2382 struct got_commit_object *commit;
2383 struct commit_queue_entry *entry;
2384 int limit_match = 0;
2385 int errcode;
2387 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2388 NULL, NULL);
2389 if (err)
2390 break;
2392 err = got_object_open_as_commit(&commit, a->repo, &id);
2393 if (err)
2394 break;
2395 entry = alloc_commit_queue_entry(commit, &id);
2396 if (entry == NULL) {
2397 err = got_error_from_errno("alloc_commit_queue_entry");
2398 break;
2401 errcode = pthread_mutex_lock(&tog_mutex);
2402 if (errcode) {
2403 err = got_error_set_errno(errcode,
2404 "pthread_mutex_lock");
2405 break;
2408 entry->idx = a->real_commits->ncommits;
2409 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2410 a->real_commits->ncommits++;
2412 if (*a->limiting) {
2413 err = match_commit(&limit_match, &id, commit,
2414 a->limit_regex);
2415 if (err)
2416 break;
2418 if (limit_match) {
2419 struct commit_queue_entry *matched;
2421 matched = alloc_commit_queue_entry(
2422 entry->commit, entry->id);
2423 if (matched == NULL) {
2424 err = got_error_from_errno(
2425 "alloc_commit_queue_entry");
2426 break;
2428 matched->commit = entry->commit;
2429 got_object_commit_retain(entry->commit);
2431 matched->idx = a->limit_commits->ncommits;
2432 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2433 matched, entry);
2434 a->limit_commits->ncommits++;
2438 * This is how we signal log_thread() that we
2439 * have found a match, and that it should be
2440 * counted as a new entry for the view.
2442 a->limit_match = limit_match;
2445 if (*a->searching == TOG_SEARCH_FORWARD &&
2446 !*a->search_next_done) {
2447 int have_match;
2448 err = match_commit(&have_match, &id, commit, a->regex);
2449 if (err)
2450 break;
2452 if (*a->limiting) {
2453 if (limit_match && have_match)
2454 *a->search_next_done =
2455 TOG_SEARCH_HAVE_MORE;
2456 } else if (have_match)
2457 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2460 errcode = pthread_mutex_unlock(&tog_mutex);
2461 if (errcode && err == NULL)
2462 err = got_error_set_errno(errcode,
2463 "pthread_mutex_unlock");
2464 if (err)
2465 break;
2466 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2468 return err;
2471 static void
2472 select_commit(struct tog_log_view_state *s)
2474 struct commit_queue_entry *entry;
2475 int ncommits = 0;
2477 entry = s->first_displayed_entry;
2478 while (entry) {
2479 if (ncommits == s->selected) {
2480 s->selected_entry = entry;
2481 break;
2483 entry = TAILQ_NEXT(entry, entry);
2484 ncommits++;
2488 static const struct got_error *
2489 draw_commits(struct tog_view *view)
2491 const struct got_error *err = NULL;
2492 struct tog_log_view_state *s = &view->state.log;
2493 struct commit_queue_entry *entry = s->selected_entry;
2494 int limit = view->nlines;
2495 int width;
2496 int ncommits, author_cols = 4;
2497 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2498 char *refs_str = NULL;
2499 wchar_t *wline;
2500 struct tog_color *tc;
2501 static const size_t date_display_cols = 12;
2503 if (view_is_hsplit_top(view))
2504 --limit; /* account for border */
2506 if (s->selected_entry &&
2507 !(view->searching && view->search_next_done == 0)) {
2508 struct got_reflist_head *refs;
2509 err = got_object_id_str(&id_str, s->selected_entry->id);
2510 if (err)
2511 return err;
2512 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2513 s->selected_entry->id);
2514 if (refs) {
2515 err = build_refs_str(&refs_str, refs,
2516 s->selected_entry->id, s->repo);
2517 if (err)
2518 goto done;
2522 if (s->thread_args.commits_needed == 0)
2523 halfdelay(10); /* disable fast refresh */
2525 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2526 if (asprintf(&ncommits_str, " [%d/%d] %s",
2527 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2528 (view->searching && !view->search_next_done) ?
2529 "searching..." : "loading...") == -1) {
2530 err = got_error_from_errno("asprintf");
2531 goto done;
2533 } else {
2534 const char *search_str = NULL;
2535 const char *limit_str = NULL;
2537 if (view->searching) {
2538 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2539 search_str = "no more matches";
2540 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2541 search_str = "no matches found";
2542 else if (!view->search_next_done)
2543 search_str = "searching...";
2546 if (s->limit_view && s->commits->ncommits == 0)
2547 limit_str = "no matches found";
2549 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2550 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2551 search_str ? search_str : (refs_str ? refs_str : ""),
2552 limit_str ? limit_str : "") == -1) {
2553 err = got_error_from_errno("asprintf");
2554 goto done;
2558 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2559 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2560 "........................................",
2561 s->in_repo_path, ncommits_str) == -1) {
2562 err = got_error_from_errno("asprintf");
2563 header = NULL;
2564 goto done;
2566 } else if (asprintf(&header, "commit %s%s",
2567 id_str ? id_str : "........................................",
2568 ncommits_str) == -1) {
2569 err = got_error_from_errno("asprintf");
2570 header = NULL;
2571 goto done;
2573 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2574 if (err)
2575 goto done;
2577 werase(view->window);
2579 if (view_needs_focus_indication(view))
2580 wstandout(view->window);
2581 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2582 if (tc)
2583 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2584 waddwstr(view->window, wline);
2585 while (width < view->ncols) {
2586 waddch(view->window, ' ');
2587 width++;
2589 if (tc)
2590 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2591 if (view_needs_focus_indication(view))
2592 wstandend(view->window);
2593 free(wline);
2594 if (limit <= 1)
2595 goto done;
2597 /* Grow author column size if necessary, and set view->maxx. */
2598 entry = s->first_displayed_entry;
2599 ncommits = 0;
2600 view->maxx = 0;
2601 while (entry) {
2602 struct got_commit_object *c = entry->commit;
2603 char *author, *eol, *msg, *msg0;
2604 wchar_t *wauthor, *wmsg;
2605 int width;
2606 if (ncommits >= limit - 1)
2607 break;
2608 if (s->use_committer)
2609 author = strdup(got_object_commit_get_committer(c));
2610 else
2611 author = strdup(got_object_commit_get_author(c));
2612 if (author == NULL) {
2613 err = got_error_from_errno("strdup");
2614 goto done;
2616 err = format_author(&wauthor, &width, author, COLS,
2617 date_display_cols);
2618 if (author_cols < width)
2619 author_cols = width;
2620 free(wauthor);
2621 free(author);
2622 if (err)
2623 goto done;
2624 err = got_object_commit_get_logmsg(&msg0, c);
2625 if (err)
2626 goto done;
2627 msg = msg0;
2628 while (*msg == '\n')
2629 ++msg;
2630 if ((eol = strchr(msg, '\n')))
2631 *eol = '\0';
2632 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2633 date_display_cols + author_cols, 0);
2634 if (err)
2635 goto done;
2636 view->maxx = MAX(view->maxx, width);
2637 free(msg0);
2638 free(wmsg);
2639 ncommits++;
2640 entry = TAILQ_NEXT(entry, entry);
2643 entry = s->first_displayed_entry;
2644 s->last_displayed_entry = s->first_displayed_entry;
2645 ncommits = 0;
2646 while (entry) {
2647 if (ncommits >= limit - 1)
2648 break;
2649 if (ncommits == s->selected)
2650 wstandout(view->window);
2651 err = draw_commit(view, entry->commit, entry->id,
2652 date_display_cols, author_cols);
2653 if (ncommits == s->selected)
2654 wstandend(view->window);
2655 if (err)
2656 goto done;
2657 ncommits++;
2658 s->last_displayed_entry = entry;
2659 entry = TAILQ_NEXT(entry, entry);
2662 view_border(view);
2663 done:
2664 free(id_str);
2665 free(refs_str);
2666 free(ncommits_str);
2667 free(header);
2668 return err;
2671 static void
2672 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2674 struct commit_queue_entry *entry;
2675 int nscrolled = 0;
2677 entry = TAILQ_FIRST(&s->commits->head);
2678 if (s->first_displayed_entry == entry)
2679 return;
2681 entry = s->first_displayed_entry;
2682 while (entry && nscrolled < maxscroll) {
2683 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2684 if (entry) {
2685 s->first_displayed_entry = entry;
2686 nscrolled++;
2691 static const struct got_error *
2692 trigger_log_thread(struct tog_view *view, int wait)
2694 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2695 int errcode;
2697 halfdelay(1); /* fast refresh while loading commits */
2699 while (!ta->log_complete && !tog_thread_error &&
2700 (ta->commits_needed > 0 || ta->load_all)) {
2701 /* Wake the log thread. */
2702 errcode = pthread_cond_signal(&ta->need_commits);
2703 if (errcode)
2704 return got_error_set_errno(errcode,
2705 "pthread_cond_signal");
2708 * The mutex will be released while the view loop waits
2709 * in wgetch(), at which time the log thread will run.
2711 if (!wait)
2712 break;
2714 /* Display progress update in log view. */
2715 show_log_view(view);
2716 update_panels();
2717 doupdate();
2719 /* Wait right here while next commit is being loaded. */
2720 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2721 if (errcode)
2722 return got_error_set_errno(errcode,
2723 "pthread_cond_wait");
2725 /* Display progress update in log view. */
2726 show_log_view(view);
2727 update_panels();
2728 doupdate();
2731 return NULL;
2734 static const struct got_error *
2735 request_log_commits(struct tog_view *view)
2737 struct tog_log_view_state *state = &view->state.log;
2738 const struct got_error *err = NULL;
2740 if (state->thread_args.log_complete)
2741 return NULL;
2743 state->thread_args.commits_needed += view->nscrolled;
2744 err = trigger_log_thread(view, 1);
2745 view->nscrolled = 0;
2747 return err;
2750 static const struct got_error *
2751 log_scroll_down(struct tog_view *view, int maxscroll)
2753 struct tog_log_view_state *s = &view->state.log;
2754 const struct got_error *err = NULL;
2755 struct commit_queue_entry *pentry;
2756 int nscrolled = 0, ncommits_needed;
2758 if (s->last_displayed_entry == NULL)
2759 return NULL;
2761 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2762 if (s->commits->ncommits < ncommits_needed &&
2763 !s->thread_args.log_complete) {
2765 * Ask the log thread for required amount of commits.
2767 s->thread_args.commits_needed +=
2768 ncommits_needed - s->commits->ncommits;
2769 err = trigger_log_thread(view, 1);
2770 if (err)
2771 return err;
2774 do {
2775 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2776 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2777 break;
2779 s->last_displayed_entry = pentry ?
2780 pentry : s->last_displayed_entry;
2782 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2783 if (pentry == NULL)
2784 break;
2785 s->first_displayed_entry = pentry;
2786 } while (++nscrolled < maxscroll);
2788 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2789 view->nscrolled += nscrolled;
2790 else
2791 view->nscrolled = 0;
2793 return err;
2796 static const struct got_error *
2797 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2798 struct got_commit_object *commit, struct got_object_id *commit_id,
2799 struct tog_view *log_view, struct got_repository *repo)
2801 const struct got_error *err;
2802 struct got_object_qid *parent_id;
2803 struct tog_view *diff_view;
2805 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2806 if (diff_view == NULL)
2807 return got_error_from_errno("view_open");
2809 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2810 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2811 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2812 if (err == NULL)
2813 *new_view = diff_view;
2814 return err;
2817 static const struct got_error *
2818 tree_view_visit_subtree(struct tog_tree_view_state *s,
2819 struct got_tree_object *subtree)
2821 struct tog_parent_tree *parent;
2823 parent = calloc(1, sizeof(*parent));
2824 if (parent == NULL)
2825 return got_error_from_errno("calloc");
2827 parent->tree = s->tree;
2828 parent->first_displayed_entry = s->first_displayed_entry;
2829 parent->selected_entry = s->selected_entry;
2830 parent->selected = s->selected;
2831 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2832 s->tree = subtree;
2833 s->selected = 0;
2834 s->first_displayed_entry = NULL;
2835 return NULL;
2838 static const struct got_error *
2839 tree_view_walk_path(struct tog_tree_view_state *s,
2840 struct got_commit_object *commit, const char *path)
2842 const struct got_error *err = NULL;
2843 struct got_tree_object *tree = NULL;
2844 const char *p;
2845 char *slash, *subpath = NULL;
2847 /* Walk the path and open corresponding tree objects. */
2848 p = path;
2849 while (*p) {
2850 struct got_tree_entry *te;
2851 struct got_object_id *tree_id;
2852 char *te_name;
2854 while (p[0] == '/')
2855 p++;
2857 /* Ensure the correct subtree entry is selected. */
2858 slash = strchr(p, '/');
2859 if (slash == NULL)
2860 te_name = strdup(p);
2861 else
2862 te_name = strndup(p, slash - p);
2863 if (te_name == NULL) {
2864 err = got_error_from_errno("strndup");
2865 break;
2867 te = got_object_tree_find_entry(s->tree, te_name);
2868 if (te == NULL) {
2869 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2870 free(te_name);
2871 break;
2873 free(te_name);
2874 s->first_displayed_entry = s->selected_entry = te;
2876 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2877 break; /* jump to this file's entry */
2879 slash = strchr(p, '/');
2880 if (slash)
2881 subpath = strndup(path, slash - path);
2882 else
2883 subpath = strdup(path);
2884 if (subpath == NULL) {
2885 err = got_error_from_errno("strdup");
2886 break;
2889 err = got_object_id_by_path(&tree_id, s->repo, commit,
2890 subpath);
2891 if (err)
2892 break;
2894 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2895 free(tree_id);
2896 if (err)
2897 break;
2899 err = tree_view_visit_subtree(s, tree);
2900 if (err) {
2901 got_object_tree_close(tree);
2902 break;
2904 if (slash == NULL)
2905 break;
2906 free(subpath);
2907 subpath = NULL;
2908 p = slash;
2911 free(subpath);
2912 return err;
2915 static const struct got_error *
2916 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2917 struct commit_queue_entry *entry, const char *path,
2918 const char *head_ref_name, struct got_repository *repo)
2920 const struct got_error *err = NULL;
2921 struct tog_tree_view_state *s;
2922 struct tog_view *tree_view;
2924 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2925 if (tree_view == NULL)
2926 return got_error_from_errno("view_open");
2928 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2929 if (err)
2930 return err;
2931 s = &tree_view->state.tree;
2933 *new_view = tree_view;
2935 if (got_path_is_root_dir(path))
2936 return NULL;
2938 return tree_view_walk_path(s, entry->commit, path);
2941 static const struct got_error *
2942 block_signals_used_by_main_thread(void)
2944 sigset_t sigset;
2945 int errcode;
2947 if (sigemptyset(&sigset) == -1)
2948 return got_error_from_errno("sigemptyset");
2950 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2951 if (sigaddset(&sigset, SIGWINCH) == -1)
2952 return got_error_from_errno("sigaddset");
2953 if (sigaddset(&sigset, SIGCONT) == -1)
2954 return got_error_from_errno("sigaddset");
2955 if (sigaddset(&sigset, SIGINT) == -1)
2956 return got_error_from_errno("sigaddset");
2957 if (sigaddset(&sigset, SIGTERM) == -1)
2958 return got_error_from_errno("sigaddset");
2960 /* ncurses handles SIGTSTP */
2961 if (sigaddset(&sigset, SIGTSTP) == -1)
2962 return got_error_from_errno("sigaddset");
2964 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2965 if (errcode)
2966 return got_error_set_errno(errcode, "pthread_sigmask");
2968 return NULL;
2971 static void *
2972 log_thread(void *arg)
2974 const struct got_error *err = NULL;
2975 int errcode = 0;
2976 struct tog_log_thread_args *a = arg;
2977 int done = 0;
2980 * Sync startup with main thread such that we begin our
2981 * work once view_input() has released the mutex.
2983 errcode = pthread_mutex_lock(&tog_mutex);
2984 if (errcode) {
2985 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2986 return (void *)err;
2989 err = block_signals_used_by_main_thread();
2990 if (err) {
2991 pthread_mutex_unlock(&tog_mutex);
2992 goto done;
2995 while (!done && !err && !tog_fatal_signal_received()) {
2996 errcode = pthread_mutex_unlock(&tog_mutex);
2997 if (errcode) {
2998 err = got_error_set_errno(errcode,
2999 "pthread_mutex_unlock");
3000 goto done;
3002 err = queue_commits(a);
3003 if (err) {
3004 if (err->code != GOT_ERR_ITER_COMPLETED)
3005 goto done;
3006 err = NULL;
3007 done = 1;
3008 } else if (a->commits_needed > 0 && !a->load_all) {
3009 if (*a->limiting) {
3010 if (a->limit_match)
3011 a->commits_needed--;
3012 } else
3013 a->commits_needed--;
3016 errcode = pthread_mutex_lock(&tog_mutex);
3017 if (errcode) {
3018 err = got_error_set_errno(errcode,
3019 "pthread_mutex_lock");
3020 goto done;
3021 } else if (*a->quit)
3022 done = 1;
3023 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3024 *a->first_displayed_entry =
3025 TAILQ_FIRST(&a->limit_commits->head);
3026 *a->selected_entry = *a->first_displayed_entry;
3027 } else if (*a->first_displayed_entry == NULL) {
3028 *a->first_displayed_entry =
3029 TAILQ_FIRST(&a->real_commits->head);
3030 *a->selected_entry = *a->first_displayed_entry;
3033 errcode = pthread_cond_signal(&a->commit_loaded);
3034 if (errcode) {
3035 err = got_error_set_errno(errcode,
3036 "pthread_cond_signal");
3037 pthread_mutex_unlock(&tog_mutex);
3038 goto done;
3041 if (done)
3042 a->commits_needed = 0;
3043 else {
3044 if (a->commits_needed == 0 && !a->load_all) {
3045 errcode = pthread_cond_wait(&a->need_commits,
3046 &tog_mutex);
3047 if (errcode) {
3048 err = got_error_set_errno(errcode,
3049 "pthread_cond_wait");
3050 pthread_mutex_unlock(&tog_mutex);
3051 goto done;
3053 if (*a->quit)
3054 done = 1;
3058 a->log_complete = 1;
3059 errcode = pthread_mutex_unlock(&tog_mutex);
3060 if (errcode)
3061 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3062 done:
3063 if (err) {
3064 tog_thread_error = 1;
3065 pthread_cond_signal(&a->commit_loaded);
3067 return (void *)err;
3070 static const struct got_error *
3071 stop_log_thread(struct tog_log_view_state *s)
3073 const struct got_error *err = NULL, *thread_err = NULL;
3074 int errcode;
3076 if (s->thread) {
3077 s->quit = 1;
3078 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3079 if (errcode)
3080 return got_error_set_errno(errcode,
3081 "pthread_cond_signal");
3082 errcode = pthread_mutex_unlock(&tog_mutex);
3083 if (errcode)
3084 return got_error_set_errno(errcode,
3085 "pthread_mutex_unlock");
3086 errcode = pthread_join(s->thread, (void **)&thread_err);
3087 if (errcode)
3088 return got_error_set_errno(errcode, "pthread_join");
3089 errcode = pthread_mutex_lock(&tog_mutex);
3090 if (errcode)
3091 return got_error_set_errno(errcode,
3092 "pthread_mutex_lock");
3093 s->thread = NULL;
3096 if (s->thread_args.repo) {
3097 err = got_repo_close(s->thread_args.repo);
3098 s->thread_args.repo = NULL;
3101 if (s->thread_args.pack_fds) {
3102 const struct got_error *pack_err =
3103 got_repo_pack_fds_close(s->thread_args.pack_fds);
3104 if (err == NULL)
3105 err = pack_err;
3106 s->thread_args.pack_fds = NULL;
3109 if (s->thread_args.graph) {
3110 got_commit_graph_close(s->thread_args.graph);
3111 s->thread_args.graph = NULL;
3114 return err ? err : thread_err;
3117 static const struct got_error *
3118 close_log_view(struct tog_view *view)
3120 const struct got_error *err = NULL;
3121 struct tog_log_view_state *s = &view->state.log;
3122 int errcode;
3124 err = stop_log_thread(s);
3126 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3127 if (errcode && err == NULL)
3128 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3130 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3131 if (errcode && err == NULL)
3132 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3134 free_commits(&s->limit_commits);
3135 free_commits(&s->real_commits);
3136 free(s->in_repo_path);
3137 s->in_repo_path = NULL;
3138 free(s->start_id);
3139 s->start_id = NULL;
3140 free(s->head_ref_name);
3141 s->head_ref_name = NULL;
3142 return err;
3146 * We use two queues to implement the limit feature: first consists of
3147 * commits matching the current limit_regex; second is the real queue
3148 * of all known commits (real_commits). When the user starts limiting,
3149 * we swap queues such that all movement and displaying functionality
3150 * works with very slight change.
3152 static const struct got_error *
3153 limit_log_view(struct tog_view *view)
3155 struct tog_log_view_state *s = &view->state.log;
3156 struct commit_queue_entry *entry;
3157 struct tog_view *v = view;
3158 const struct got_error *err = NULL;
3159 char pattern[1024];
3160 int ret;
3162 if (view_is_hsplit_top(view))
3163 v = view->child;
3164 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3165 v = view->parent;
3167 /* Get the pattern */
3168 wmove(v->window, v->nlines - 1, 0);
3169 wclrtoeol(v->window);
3170 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3171 nodelay(v->window, FALSE);
3172 nocbreak();
3173 echo();
3174 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3175 cbreak();
3176 noecho();
3177 nodelay(v->window, TRUE);
3178 if (ret == ERR)
3179 return NULL;
3181 if (*pattern == '\0') {
3183 * Safety measure for the situation where the user
3184 * resets limit without previously limiting anything.
3186 if (!s->limit_view)
3187 return NULL;
3190 * User could have pressed Ctrl+L, which refreshed the
3191 * commit queues, it means we can't save previously
3192 * (before limit took place) displayed entries,
3193 * because they would point to already free'ed memory,
3194 * so we are forced to always select first entry of
3195 * the queue.
3197 s->commits = &s->real_commits;
3198 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3199 s->selected_entry = s->first_displayed_entry;
3200 s->selected = 0;
3201 s->limit_view = 0;
3203 return NULL;
3206 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3207 return NULL;
3209 s->limit_view = 1;
3211 /* Clear the screen while loading limit view */
3212 s->first_displayed_entry = NULL;
3213 s->last_displayed_entry = NULL;
3214 s->selected_entry = NULL;
3215 s->commits = &s->limit_commits;
3217 /* Prepare limit queue for new search */
3218 free_commits(&s->limit_commits);
3219 s->limit_commits.ncommits = 0;
3221 /* First process commits, which are in queue already */
3222 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3223 int have_match = 0;
3225 err = match_commit(&have_match, entry->id,
3226 entry->commit, &s->limit_regex);
3227 if (err)
3228 return err;
3230 if (have_match) {
3231 struct commit_queue_entry *matched;
3233 matched = alloc_commit_queue_entry(entry->commit,
3234 entry->id);
3235 if (matched == NULL) {
3236 err = got_error_from_errno(
3237 "alloc_commit_queue_entry");
3238 break;
3240 matched->commit = entry->commit;
3241 got_object_commit_retain(entry->commit);
3243 matched->idx = s->limit_commits.ncommits;
3244 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3245 matched, entry);
3246 s->limit_commits.ncommits++;
3250 /* Second process all the commits, until we fill the screen */
3251 if (s->limit_commits.ncommits < view->nlines - 1 &&
3252 !s->thread_args.log_complete) {
3253 s->thread_args.commits_needed +=
3254 view->nlines - s->limit_commits.ncommits - 1;
3255 err = trigger_log_thread(view, 1);
3256 if (err)
3257 return err;
3260 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3261 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3262 s->selected = 0;
3264 return NULL;
3267 static const struct got_error *
3268 search_start_log_view(struct tog_view *view)
3270 struct tog_log_view_state *s = &view->state.log;
3272 s->matched_entry = NULL;
3273 s->search_entry = NULL;
3274 return NULL;
3277 static const struct got_error *
3278 search_next_log_view(struct tog_view *view)
3280 const struct got_error *err = NULL;
3281 struct tog_log_view_state *s = &view->state.log;
3282 struct commit_queue_entry *entry;
3284 /* Display progress update in log view. */
3285 show_log_view(view);
3286 update_panels();
3287 doupdate();
3289 if (s->search_entry) {
3290 int errcode, ch;
3291 errcode = pthread_mutex_unlock(&tog_mutex);
3292 if (errcode)
3293 return got_error_set_errno(errcode,
3294 "pthread_mutex_unlock");
3295 ch = wgetch(view->window);
3296 errcode = pthread_mutex_lock(&tog_mutex);
3297 if (errcode)
3298 return got_error_set_errno(errcode,
3299 "pthread_mutex_lock");
3300 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3301 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3302 return NULL;
3304 if (view->searching == TOG_SEARCH_FORWARD)
3305 entry = TAILQ_NEXT(s->search_entry, entry);
3306 else
3307 entry = TAILQ_PREV(s->search_entry,
3308 commit_queue_head, entry);
3309 } else if (s->matched_entry) {
3311 * If the user has moved the cursor after we hit a match,
3312 * the position from where we should continue searching
3313 * might have changed.
3315 if (view->searching == TOG_SEARCH_FORWARD)
3316 entry = TAILQ_NEXT(s->selected_entry, entry);
3317 else
3318 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3319 entry);
3320 } else {
3321 entry = s->selected_entry;
3324 while (1) {
3325 int have_match = 0;
3327 if (entry == NULL) {
3328 if (s->thread_args.log_complete ||
3329 view->searching == TOG_SEARCH_BACKWARD) {
3330 view->search_next_done =
3331 (s->matched_entry == NULL ?
3332 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3333 s->search_entry = NULL;
3334 return NULL;
3337 * Poke the log thread for more commits and return,
3338 * allowing the main loop to make progress. Search
3339 * will resume at s->search_entry once we come back.
3341 s->thread_args.commits_needed++;
3342 return trigger_log_thread(view, 0);
3345 err = match_commit(&have_match, entry->id, entry->commit,
3346 &view->regex);
3347 if (err)
3348 break;
3349 if (have_match) {
3350 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3351 s->matched_entry = entry;
3352 break;
3355 s->search_entry = entry;
3356 if (view->searching == TOG_SEARCH_FORWARD)
3357 entry = TAILQ_NEXT(entry, entry);
3358 else
3359 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3362 if (s->matched_entry) {
3363 int cur = s->selected_entry->idx;
3364 while (cur < s->matched_entry->idx) {
3365 err = input_log_view(NULL, view, KEY_DOWN);
3366 if (err)
3367 return err;
3368 cur++;
3370 while (cur > s->matched_entry->idx) {
3371 err = input_log_view(NULL, view, KEY_UP);
3372 if (err)
3373 return err;
3374 cur--;
3378 s->search_entry = NULL;
3380 return NULL;
3383 static const struct got_error *
3384 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3385 struct got_repository *repo, const char *head_ref_name,
3386 const char *in_repo_path, int log_branches)
3388 const struct got_error *err = NULL;
3389 struct tog_log_view_state *s = &view->state.log;
3390 struct got_repository *thread_repo = NULL;
3391 struct got_commit_graph *thread_graph = NULL;
3392 int errcode;
3394 if (in_repo_path != s->in_repo_path) {
3395 free(s->in_repo_path);
3396 s->in_repo_path = strdup(in_repo_path);
3397 if (s->in_repo_path == NULL)
3398 return got_error_from_errno("strdup");
3401 /* The commit queue only contains commits being displayed. */
3402 TAILQ_INIT(&s->real_commits.head);
3403 s->real_commits.ncommits = 0;
3404 s->commits = &s->real_commits;
3406 TAILQ_INIT(&s->limit_commits.head);
3407 s->limit_view = 0;
3408 s->limit_commits.ncommits = 0;
3410 s->repo = repo;
3411 if (head_ref_name) {
3412 s->head_ref_name = strdup(head_ref_name);
3413 if (s->head_ref_name == NULL) {
3414 err = got_error_from_errno("strdup");
3415 goto done;
3418 s->start_id = got_object_id_dup(start_id);
3419 if (s->start_id == NULL) {
3420 err = got_error_from_errno("got_object_id_dup");
3421 goto done;
3423 s->log_branches = log_branches;
3424 s->use_committer = 1;
3426 STAILQ_INIT(&s->colors);
3427 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3428 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3429 get_color_value("TOG_COLOR_COMMIT"));
3430 if (err)
3431 goto done;
3432 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3433 get_color_value("TOG_COLOR_AUTHOR"));
3434 if (err) {
3435 free_colors(&s->colors);
3436 goto done;
3438 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3439 get_color_value("TOG_COLOR_DATE"));
3440 if (err) {
3441 free_colors(&s->colors);
3442 goto done;
3446 view->show = show_log_view;
3447 view->input = input_log_view;
3448 view->resize = resize_log_view;
3449 view->close = close_log_view;
3450 view->search_start = search_start_log_view;
3451 view->search_next = search_next_log_view;
3453 if (s->thread_args.pack_fds == NULL) {
3454 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3455 if (err)
3456 goto done;
3458 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3459 s->thread_args.pack_fds);
3460 if (err)
3461 goto done;
3462 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3463 !s->log_branches);
3464 if (err)
3465 goto done;
3466 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3467 s->repo, NULL, NULL);
3468 if (err)
3469 goto done;
3471 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3472 if (errcode) {
3473 err = got_error_set_errno(errcode, "pthread_cond_init");
3474 goto done;
3476 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3477 if (errcode) {
3478 err = got_error_set_errno(errcode, "pthread_cond_init");
3479 goto done;
3482 s->thread_args.commits_needed = view->nlines;
3483 s->thread_args.graph = thread_graph;
3484 s->thread_args.real_commits = &s->real_commits;
3485 s->thread_args.limit_commits = &s->limit_commits;
3486 s->thread_args.in_repo_path = s->in_repo_path;
3487 s->thread_args.start_id = s->start_id;
3488 s->thread_args.repo = thread_repo;
3489 s->thread_args.log_complete = 0;
3490 s->thread_args.quit = &s->quit;
3491 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3492 s->thread_args.selected_entry = &s->selected_entry;
3493 s->thread_args.searching = &view->searching;
3494 s->thread_args.search_next_done = &view->search_next_done;
3495 s->thread_args.regex = &view->regex;
3496 s->thread_args.limiting = &s->limit_view;
3497 s->thread_args.limit_regex = &s->limit_regex;
3498 s->thread_args.limit_commits = &s->limit_commits;
3499 done:
3500 if (err)
3501 close_log_view(view);
3502 return err;
3505 static const struct got_error *
3506 show_log_view(struct tog_view *view)
3508 const struct got_error *err;
3509 struct tog_log_view_state *s = &view->state.log;
3511 if (s->thread == NULL) {
3512 int errcode = pthread_create(&s->thread, NULL, log_thread,
3513 &s->thread_args);
3514 if (errcode)
3515 return got_error_set_errno(errcode, "pthread_create");
3516 if (s->thread_args.commits_needed > 0) {
3517 err = trigger_log_thread(view, 1);
3518 if (err)
3519 return err;
3523 return draw_commits(view);
3526 static void
3527 log_move_cursor_up(struct tog_view *view, int page, int home)
3529 struct tog_log_view_state *s = &view->state.log;
3531 if (s->first_displayed_entry == NULL)
3532 return;
3533 if (s->selected_entry->idx == 0)
3534 view->count = 0;
3536 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3537 || home)
3538 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3540 if (!page && !home && s->selected > 0)
3541 --s->selected;
3542 else
3543 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3545 select_commit(s);
3546 return;
3549 static const struct got_error *
3550 log_move_cursor_down(struct tog_view *view, int page)
3552 struct tog_log_view_state *s = &view->state.log;
3553 const struct got_error *err = NULL;
3554 int eos = view->nlines - 2;
3556 if (s->first_displayed_entry == NULL)
3557 return NULL;
3559 if (s->thread_args.log_complete &&
3560 s->selected_entry->idx >= s->commits->ncommits - 1)
3561 return NULL;
3563 if (view_is_hsplit_top(view))
3564 --eos; /* border consumes the last line */
3566 if (!page) {
3567 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3568 ++s->selected;
3569 else
3570 err = log_scroll_down(view, 1);
3571 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3572 struct commit_queue_entry *entry;
3573 int n;
3575 s->selected = 0;
3576 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3577 s->last_displayed_entry = entry;
3578 for (n = 0; n <= eos; n++) {
3579 if (entry == NULL)
3580 break;
3581 s->first_displayed_entry = entry;
3582 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3584 if (n > 0)
3585 s->selected = n - 1;
3586 } else {
3587 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3588 s->thread_args.log_complete)
3589 s->selected += MIN(page,
3590 s->commits->ncommits - s->selected_entry->idx - 1);
3591 else
3592 err = log_scroll_down(view, page);
3594 if (err)
3595 return err;
3598 * We might necessarily overshoot in horizontal
3599 * splits; if so, select the last displayed commit.
3601 if (s->first_displayed_entry && s->last_displayed_entry) {
3602 s->selected = MIN(s->selected,
3603 s->last_displayed_entry->idx -
3604 s->first_displayed_entry->idx);
3607 select_commit(s);
3609 if (s->thread_args.log_complete &&
3610 s->selected_entry->idx == s->commits->ncommits - 1)
3611 view->count = 0;
3613 return NULL;
3616 static void
3617 view_get_split(struct tog_view *view, int *y, int *x)
3619 *x = 0;
3620 *y = 0;
3622 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3623 if (view->child && view->child->resized_y)
3624 *y = view->child->resized_y;
3625 else if (view->resized_y)
3626 *y = view->resized_y;
3627 else
3628 *y = view_split_begin_y(view->lines);
3629 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3630 if (view->child && view->child->resized_x)
3631 *x = view->child->resized_x;
3632 else if (view->resized_x)
3633 *x = view->resized_x;
3634 else
3635 *x = view_split_begin_x(view->begin_x);
3639 /* Split view horizontally at y and offset view->state->selected line. */
3640 static const struct got_error *
3641 view_init_hsplit(struct tog_view *view, int y)
3643 const struct got_error *err = NULL;
3645 view->nlines = y;
3646 view->ncols = COLS;
3647 err = view_resize(view);
3648 if (err)
3649 return err;
3651 err = offset_selection_down(view);
3653 return err;
3656 static const struct got_error *
3657 log_goto_line(struct tog_view *view, int nlines)
3659 const struct got_error *err = NULL;
3660 struct tog_log_view_state *s = &view->state.log;
3661 int g, idx = s->selected_entry->idx;
3663 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3664 return NULL;
3666 g = view->gline;
3667 view->gline = 0;
3669 if (g >= s->first_displayed_entry->idx + 1 &&
3670 g <= s->last_displayed_entry->idx + 1 &&
3671 g - s->first_displayed_entry->idx - 1 < nlines) {
3672 s->selected = g - s->first_displayed_entry->idx - 1;
3673 select_commit(s);
3674 return NULL;
3677 if (idx + 1 < g) {
3678 err = log_move_cursor_down(view, g - idx - 1);
3679 if (!err && g > s->selected_entry->idx + 1)
3680 err = log_move_cursor_down(view,
3681 g - s->first_displayed_entry->idx - 1);
3682 if (err)
3683 return err;
3684 } else if (idx + 1 > g)
3685 log_move_cursor_up(view, idx - g + 1, 0);
3687 if (g < nlines && s->first_displayed_entry->idx == 0)
3688 s->selected = g - 1;
3690 select_commit(s);
3691 return NULL;
3695 static const struct got_error *
3696 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3698 const struct got_error *err = NULL;
3699 struct tog_log_view_state *s = &view->state.log;
3700 int eos, nscroll;
3702 if (s->thread_args.load_all) {
3703 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3704 s->thread_args.load_all = 0;
3705 else if (s->thread_args.log_complete) {
3706 err = log_move_cursor_down(view, s->commits->ncommits);
3707 s->thread_args.load_all = 0;
3709 if (err)
3710 return err;
3713 eos = nscroll = view->nlines - 1;
3714 if (view_is_hsplit_top(view))
3715 --eos; /* border */
3717 if (view->gline)
3718 return log_goto_line(view, eos);
3720 switch (ch) {
3721 case '&':
3722 err = limit_log_view(view);
3723 break;
3724 case 'q':
3725 s->quit = 1;
3726 break;
3727 case '0':
3728 view->x = 0;
3729 break;
3730 case '$':
3731 view->x = MAX(view->maxx - view->ncols / 2, 0);
3732 view->count = 0;
3733 break;
3734 case KEY_RIGHT:
3735 case 'l':
3736 if (view->x + view->ncols / 2 < view->maxx)
3737 view->x += 2; /* move two columns right */
3738 else
3739 view->count = 0;
3740 break;
3741 case KEY_LEFT:
3742 case 'h':
3743 view->x -= MIN(view->x, 2); /* move two columns back */
3744 if (view->x <= 0)
3745 view->count = 0;
3746 break;
3747 case 'k':
3748 case KEY_UP:
3749 case '<':
3750 case ',':
3751 case CTRL('p'):
3752 log_move_cursor_up(view, 0, 0);
3753 break;
3754 case 'g':
3755 case '=':
3756 case KEY_HOME:
3757 log_move_cursor_up(view, 0, 1);
3758 view->count = 0;
3759 break;
3760 case CTRL('u'):
3761 case 'u':
3762 nscroll /= 2;
3763 /* FALL THROUGH */
3764 case KEY_PPAGE:
3765 case CTRL('b'):
3766 case 'b':
3767 log_move_cursor_up(view, nscroll, 0);
3768 break;
3769 case 'j':
3770 case KEY_DOWN:
3771 case '>':
3772 case '.':
3773 case CTRL('n'):
3774 err = log_move_cursor_down(view, 0);
3775 break;
3776 case '@':
3777 s->use_committer = !s->use_committer;
3778 view->action = s->use_committer ?
3779 "show committer" : "show commit author";
3780 break;
3781 case 'G':
3782 case '*':
3783 case KEY_END: {
3784 /* We don't know yet how many commits, so we're forced to
3785 * traverse them all. */
3786 view->count = 0;
3787 s->thread_args.load_all = 1;
3788 if (!s->thread_args.log_complete)
3789 return trigger_log_thread(view, 0);
3790 err = log_move_cursor_down(view, s->commits->ncommits);
3791 s->thread_args.load_all = 0;
3792 break;
3794 case CTRL('d'):
3795 case 'd':
3796 nscroll /= 2;
3797 /* FALL THROUGH */
3798 case KEY_NPAGE:
3799 case CTRL('f'):
3800 case 'f':
3801 case ' ':
3802 err = log_move_cursor_down(view, nscroll);
3803 break;
3804 case KEY_RESIZE:
3805 if (s->selected > view->nlines - 2)
3806 s->selected = view->nlines - 2;
3807 if (s->selected > s->commits->ncommits - 1)
3808 s->selected = s->commits->ncommits - 1;
3809 select_commit(s);
3810 if (s->commits->ncommits < view->nlines - 1 &&
3811 !s->thread_args.log_complete) {
3812 s->thread_args.commits_needed += (view->nlines - 1) -
3813 s->commits->ncommits;
3814 err = trigger_log_thread(view, 1);
3816 break;
3817 case KEY_ENTER:
3818 case '\r':
3819 view->count = 0;
3820 if (s->selected_entry == NULL)
3821 break;
3822 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3823 break;
3824 case 'T':
3825 view->count = 0;
3826 if (s->selected_entry == NULL)
3827 break;
3828 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3829 break;
3830 case KEY_BACKSPACE:
3831 case CTRL('l'):
3832 case 'B':
3833 view->count = 0;
3834 if (ch == KEY_BACKSPACE &&
3835 got_path_is_root_dir(s->in_repo_path))
3836 break;
3837 err = stop_log_thread(s);
3838 if (err)
3839 return err;
3840 if (ch == KEY_BACKSPACE) {
3841 char *parent_path;
3842 err = got_path_dirname(&parent_path, s->in_repo_path);
3843 if (err)
3844 return err;
3845 free(s->in_repo_path);
3846 s->in_repo_path = parent_path;
3847 s->thread_args.in_repo_path = s->in_repo_path;
3848 } else if (ch == CTRL('l')) {
3849 struct got_object_id *start_id;
3850 err = got_repo_match_object_id(&start_id, NULL,
3851 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3852 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3853 if (err) {
3854 if (s->head_ref_name == NULL ||
3855 err->code != GOT_ERR_NOT_REF)
3856 return err;
3857 /* Try to cope with deleted references. */
3858 free(s->head_ref_name);
3859 s->head_ref_name = NULL;
3860 err = got_repo_match_object_id(&start_id,
3861 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
3862 &tog_refs, s->repo);
3863 if (err)
3864 return err;
3866 free(s->start_id);
3867 s->start_id = start_id;
3868 s->thread_args.start_id = s->start_id;
3869 } else /* 'B' */
3870 s->log_branches = !s->log_branches;
3872 if (s->thread_args.pack_fds == NULL) {
3873 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3874 if (err)
3875 return err;
3877 err = got_repo_open(&s->thread_args.repo,
3878 got_repo_get_path(s->repo), NULL,
3879 s->thread_args.pack_fds);
3880 if (err)
3881 return err;
3882 tog_free_refs();
3883 err = tog_load_refs(s->repo, 0);
3884 if (err)
3885 return err;
3886 err = got_commit_graph_open(&s->thread_args.graph,
3887 s->in_repo_path, !s->log_branches);
3888 if (err)
3889 return err;
3890 err = got_commit_graph_iter_start(s->thread_args.graph,
3891 s->start_id, s->repo, NULL, NULL);
3892 if (err)
3893 return err;
3894 free_commits(&s->real_commits);
3895 free_commits(&s->limit_commits);
3896 s->first_displayed_entry = NULL;
3897 s->last_displayed_entry = NULL;
3898 s->selected_entry = NULL;
3899 s->selected = 0;
3900 s->thread_args.log_complete = 0;
3901 s->quit = 0;
3902 s->thread_args.commits_needed = view->lines;
3903 s->matched_entry = NULL;
3904 s->search_entry = NULL;
3905 view->offset = 0;
3906 break;
3907 case 'R':
3908 view->count = 0;
3909 err = view_request_new(new_view, view, TOG_VIEW_REF);
3910 break;
3911 default:
3912 view->count = 0;
3913 break;
3916 return err;
3919 static const struct got_error *
3920 apply_unveil(const char *repo_path, const char *worktree_path)
3922 const struct got_error *error;
3924 #ifdef PROFILE
3925 if (unveil("gmon.out", "rwc") != 0)
3926 return got_error_from_errno2("unveil", "gmon.out");
3927 #endif
3928 if (repo_path && unveil(repo_path, "r") != 0)
3929 return got_error_from_errno2("unveil", repo_path);
3931 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3932 return got_error_from_errno2("unveil", worktree_path);
3934 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3935 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3937 error = got_privsep_unveil_exec_helpers();
3938 if (error != NULL)
3939 return error;
3941 if (unveil(NULL, NULL) != 0)
3942 return got_error_from_errno("unveil");
3944 return NULL;
3947 static void
3948 init_curses(void)
3951 * Override default signal handlers before starting ncurses.
3952 * This should prevent ncurses from installing its own
3953 * broken cleanup() signal handler.
3955 signal(SIGWINCH, tog_sigwinch);
3956 signal(SIGPIPE, tog_sigpipe);
3957 signal(SIGCONT, tog_sigcont);
3958 signal(SIGINT, tog_sigint);
3959 signal(SIGTERM, tog_sigterm);
3961 initscr();
3962 cbreak();
3963 halfdelay(1); /* Do fast refresh while initial view is loading. */
3964 noecho();
3965 nonl();
3966 intrflush(stdscr, FALSE);
3967 keypad(stdscr, TRUE);
3968 curs_set(0);
3969 if (getenv("TOG_COLORS") != NULL) {
3970 start_color();
3971 use_default_colors();
3975 static const struct got_error *
3976 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3977 struct got_repository *repo, struct got_worktree *worktree)
3979 const struct got_error *err = NULL;
3981 if (argc == 0) {
3982 *in_repo_path = strdup("/");
3983 if (*in_repo_path == NULL)
3984 return got_error_from_errno("strdup");
3985 return NULL;
3988 if (worktree) {
3989 const char *prefix = got_worktree_get_path_prefix(worktree);
3990 char *p;
3992 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3993 if (err)
3994 return err;
3995 if (asprintf(in_repo_path, "%s%s%s", prefix,
3996 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3997 p) == -1) {
3998 err = got_error_from_errno("asprintf");
3999 *in_repo_path = NULL;
4001 free(p);
4002 } else
4003 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4005 return err;
4008 static const struct got_error *
4009 cmd_log(int argc, char *argv[])
4011 const struct got_error *error;
4012 struct got_repository *repo = NULL;
4013 struct got_worktree *worktree = NULL;
4014 struct got_object_id *start_id = NULL;
4015 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4016 char *start_commit = NULL, *label = NULL;
4017 struct got_reference *ref = NULL;
4018 const char *head_ref_name = NULL;
4019 int ch, log_branches = 0;
4020 struct tog_view *view;
4021 int *pack_fds = NULL;
4023 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4024 switch (ch) {
4025 case 'b':
4026 log_branches = 1;
4027 break;
4028 case 'c':
4029 start_commit = optarg;
4030 break;
4031 case 'r':
4032 repo_path = realpath(optarg, NULL);
4033 if (repo_path == NULL)
4034 return got_error_from_errno2("realpath",
4035 optarg);
4036 break;
4037 default:
4038 usage_log();
4039 /* NOTREACHED */
4043 argc -= optind;
4044 argv += optind;
4046 if (argc > 1)
4047 usage_log();
4049 error = got_repo_pack_fds_open(&pack_fds);
4050 if (error != NULL)
4051 goto done;
4053 if (repo_path == NULL) {
4054 cwd = getcwd(NULL, 0);
4055 if (cwd == NULL)
4056 return got_error_from_errno("getcwd");
4057 error = got_worktree_open(&worktree, cwd);
4058 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4059 goto done;
4060 if (worktree)
4061 repo_path =
4062 strdup(got_worktree_get_repo_path(worktree));
4063 else
4064 repo_path = strdup(cwd);
4065 if (repo_path == NULL) {
4066 error = got_error_from_errno("strdup");
4067 goto done;
4071 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4072 if (error != NULL)
4073 goto done;
4075 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4076 repo, worktree);
4077 if (error)
4078 goto done;
4080 init_curses();
4082 error = apply_unveil(got_repo_get_path(repo),
4083 worktree ? got_worktree_get_root_path(worktree) : NULL);
4084 if (error)
4085 goto done;
4087 /* already loaded by tog_log_with_path()? */
4088 if (TAILQ_EMPTY(&tog_refs)) {
4089 error = tog_load_refs(repo, 0);
4090 if (error)
4091 goto done;
4094 if (start_commit == NULL) {
4095 error = got_repo_match_object_id(&start_id, &label,
4096 worktree ? got_worktree_get_head_ref_name(worktree) :
4097 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4098 if (error)
4099 goto done;
4100 head_ref_name = label;
4101 } else {
4102 error = got_ref_open(&ref, repo, start_commit, 0);
4103 if (error == NULL)
4104 head_ref_name = got_ref_get_name(ref);
4105 else if (error->code != GOT_ERR_NOT_REF)
4106 goto done;
4107 error = got_repo_match_object_id(&start_id, NULL,
4108 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4109 if (error)
4110 goto done;
4113 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4114 if (view == NULL) {
4115 error = got_error_from_errno("view_open");
4116 goto done;
4118 error = open_log_view(view, start_id, repo, head_ref_name,
4119 in_repo_path, log_branches);
4120 if (error)
4121 goto done;
4122 if (worktree) {
4123 /* Release work tree lock. */
4124 got_worktree_close(worktree);
4125 worktree = NULL;
4127 error = view_loop(view);
4128 done:
4129 free(in_repo_path);
4130 free(repo_path);
4131 free(cwd);
4132 free(start_id);
4133 free(label);
4134 if (ref)
4135 got_ref_close(ref);
4136 if (repo) {
4137 const struct got_error *close_err = got_repo_close(repo);
4138 if (error == NULL)
4139 error = close_err;
4141 if (worktree)
4142 got_worktree_close(worktree);
4143 if (pack_fds) {
4144 const struct got_error *pack_err =
4145 got_repo_pack_fds_close(pack_fds);
4146 if (error == NULL)
4147 error = pack_err;
4149 tog_free_refs();
4150 return error;
4153 __dead static void
4154 usage_diff(void)
4156 endwin();
4157 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4158 "object1 object2\n", getprogname());
4159 exit(1);
4162 static int
4163 match_line(const char *line, regex_t *regex, size_t nmatch,
4164 regmatch_t *regmatch)
4166 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4169 static struct tog_color *
4170 match_color(struct tog_colors *colors, const char *line)
4172 struct tog_color *tc = NULL;
4174 STAILQ_FOREACH(tc, colors, entry) {
4175 if (match_line(line, &tc->regex, 0, NULL))
4176 return tc;
4179 return NULL;
4182 static const struct got_error *
4183 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4184 WINDOW *window, int skipcol, regmatch_t *regmatch)
4186 const struct got_error *err = NULL;
4187 char *exstr = NULL;
4188 wchar_t *wline = NULL;
4189 int rme, rms, n, width, scrollx;
4190 int width0 = 0, width1 = 0, width2 = 0;
4191 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4193 *wtotal = 0;
4195 rms = regmatch->rm_so;
4196 rme = regmatch->rm_eo;
4198 err = expand_tab(&exstr, line);
4199 if (err)
4200 return err;
4202 /* Split the line into 3 segments, according to match offsets. */
4203 seg0 = strndup(exstr, rms);
4204 if (seg0 == NULL) {
4205 err = got_error_from_errno("strndup");
4206 goto done;
4208 seg1 = strndup(exstr + rms, rme - rms);
4209 if (seg1 == NULL) {
4210 err = got_error_from_errno("strndup");
4211 goto done;
4213 seg2 = strdup(exstr + rme);
4214 if (seg2 == NULL) {
4215 err = got_error_from_errno("strndup");
4216 goto done;
4219 /* draw up to matched token if we haven't scrolled past it */
4220 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4221 col_tab_align, 1);
4222 if (err)
4223 goto done;
4224 n = MAX(width0 - skipcol, 0);
4225 if (n) {
4226 free(wline);
4227 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4228 wlimit, col_tab_align, 1);
4229 if (err)
4230 goto done;
4231 waddwstr(window, &wline[scrollx]);
4232 wlimit -= width;
4233 *wtotal += width;
4236 if (wlimit > 0) {
4237 int i = 0, w = 0;
4238 size_t wlen;
4240 free(wline);
4241 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4242 col_tab_align, 1);
4243 if (err)
4244 goto done;
4245 wlen = wcslen(wline);
4246 while (i < wlen) {
4247 width = wcwidth(wline[i]);
4248 if (width == -1) {
4249 /* should not happen, tabs are expanded */
4250 err = got_error(GOT_ERR_RANGE);
4251 goto done;
4253 if (width0 + w + width > skipcol)
4254 break;
4255 w += width;
4256 i++;
4258 /* draw (visible part of) matched token (if scrolled into it) */
4259 if (width1 - w > 0) {
4260 wattron(window, A_STANDOUT);
4261 waddwstr(window, &wline[i]);
4262 wattroff(window, A_STANDOUT);
4263 wlimit -= (width1 - w);
4264 *wtotal += (width1 - w);
4268 if (wlimit > 0) { /* draw rest of line */
4269 free(wline);
4270 if (skipcol > width0 + width1) {
4271 err = format_line(&wline, &width2, &scrollx, seg2,
4272 skipcol - (width0 + width1), wlimit,
4273 col_tab_align, 1);
4274 if (err)
4275 goto done;
4276 waddwstr(window, &wline[scrollx]);
4277 } else {
4278 err = format_line(&wline, &width2, NULL, seg2, 0,
4279 wlimit, col_tab_align, 1);
4280 if (err)
4281 goto done;
4282 waddwstr(window, wline);
4284 *wtotal += width2;
4286 done:
4287 free(wline);
4288 free(exstr);
4289 free(seg0);
4290 free(seg1);
4291 free(seg2);
4292 return err;
4295 static int
4296 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4298 FILE *f = NULL;
4299 int *eof, *first, *selected;
4301 if (view->type == TOG_VIEW_DIFF) {
4302 struct tog_diff_view_state *s = &view->state.diff;
4304 first = &s->first_displayed_line;
4305 selected = first;
4306 eof = &s->eof;
4307 f = s->f;
4308 } else if (view->type == TOG_VIEW_HELP) {
4309 struct tog_help_view_state *s = &view->state.help;
4311 first = &s->first_displayed_line;
4312 selected = first;
4313 eof = &s->eof;
4314 f = s->f;
4315 } else if (view->type == TOG_VIEW_BLAME) {
4316 struct tog_blame_view_state *s = &view->state.blame;
4318 first = &s->first_displayed_line;
4319 selected = &s->selected_line;
4320 eof = &s->eof;
4321 f = s->blame.f;
4322 } else
4323 return 0;
4325 /* Center gline in the middle of the page like vi(1). */
4326 if (*lineno < view->gline - (view->nlines - 3) / 2)
4327 return 0;
4328 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4329 rewind(f);
4330 *eof = 0;
4331 *first = 1;
4332 *lineno = 0;
4333 *nprinted = 0;
4334 return 0;
4337 *selected = view->gline <= (view->nlines - 3) / 2 ?
4338 view->gline : (view->nlines - 3) / 2 + 1;
4339 view->gline = 0;
4341 return 1;
4344 static const struct got_error *
4345 draw_file(struct tog_view *view, const char *header)
4347 struct tog_diff_view_state *s = &view->state.diff;
4348 regmatch_t *regmatch = &view->regmatch;
4349 const struct got_error *err;
4350 int nprinted = 0;
4351 char *line;
4352 size_t linesize = 0;
4353 ssize_t linelen;
4354 wchar_t *wline;
4355 int width;
4356 int max_lines = view->nlines;
4357 int nlines = s->nlines;
4358 off_t line_offset;
4360 s->lineno = s->first_displayed_line - 1;
4361 line_offset = s->lines[s->first_displayed_line - 1].offset;
4362 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4363 return got_error_from_errno("fseek");
4365 werase(view->window);
4367 if (view->gline > s->nlines - 1)
4368 view->gline = s->nlines - 1;
4370 if (header) {
4371 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4372 1 : view->gline - (view->nlines - 3) / 2 :
4373 s->lineno + s->selected_line;
4375 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4376 return got_error_from_errno("asprintf");
4377 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4378 0, 0);
4379 free(line);
4380 if (err)
4381 return err;
4383 if (view_needs_focus_indication(view))
4384 wstandout(view->window);
4385 waddwstr(view->window, wline);
4386 free(wline);
4387 wline = NULL;
4388 while (width++ < view->ncols)
4389 waddch(view->window, ' ');
4390 if (view_needs_focus_indication(view))
4391 wstandend(view->window);
4393 if (max_lines <= 1)
4394 return NULL;
4395 max_lines--;
4398 s->eof = 0;
4399 view->maxx = 0;
4400 line = NULL;
4401 while (max_lines > 0 && nprinted < max_lines) {
4402 enum got_diff_line_type linetype;
4403 attr_t attr = 0;
4405 linelen = getline(&line, &linesize, s->f);
4406 if (linelen == -1) {
4407 if (feof(s->f)) {
4408 s->eof = 1;
4409 break;
4411 free(line);
4412 return got_ferror(s->f, GOT_ERR_IO);
4415 if (++s->lineno < s->first_displayed_line)
4416 continue;
4417 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4418 continue;
4419 if (s->lineno == view->hiline)
4420 attr = A_STANDOUT;
4422 /* Set view->maxx based on full line length. */
4423 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4424 view->x ? 1 : 0);
4425 if (err) {
4426 free(line);
4427 return err;
4429 view->maxx = MAX(view->maxx, width);
4430 free(wline);
4431 wline = NULL;
4433 linetype = s->lines[s->lineno].type;
4434 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4435 linetype < GOT_DIFF_LINE_CONTEXT)
4436 attr |= COLOR_PAIR(linetype);
4437 if (attr)
4438 wattron(view->window, attr);
4439 if (s->first_displayed_line + nprinted == s->matched_line &&
4440 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4441 err = add_matched_line(&width, line, view->ncols, 0,
4442 view->window, view->x, regmatch);
4443 if (err) {
4444 free(line);
4445 return err;
4447 } else {
4448 int skip;
4449 err = format_line(&wline, &width, &skip, line,
4450 view->x, view->ncols, 0, view->x ? 1 : 0);
4451 if (err) {
4452 free(line);
4453 return err;
4455 waddwstr(view->window, &wline[skip]);
4456 free(wline);
4457 wline = NULL;
4459 if (s->lineno == view->hiline) {
4460 /* highlight full gline length */
4461 while (width++ < view->ncols)
4462 waddch(view->window, ' ');
4463 } else {
4464 if (width <= view->ncols - 1)
4465 waddch(view->window, '\n');
4467 if (attr)
4468 wattroff(view->window, attr);
4469 if (++nprinted == 1)
4470 s->first_displayed_line = s->lineno;
4472 free(line);
4473 if (nprinted >= 1)
4474 s->last_displayed_line = s->first_displayed_line +
4475 (nprinted - 1);
4476 else
4477 s->last_displayed_line = s->first_displayed_line;
4479 view_border(view);
4481 if (s->eof) {
4482 while (nprinted < view->nlines) {
4483 waddch(view->window, '\n');
4484 nprinted++;
4487 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4488 view->ncols, 0, 0);
4489 if (err) {
4490 return err;
4493 wstandout(view->window);
4494 waddwstr(view->window, wline);
4495 free(wline);
4496 wline = NULL;
4497 wstandend(view->window);
4500 return NULL;
4503 static char *
4504 get_datestr(time_t *time, char *datebuf)
4506 struct tm mytm, *tm;
4507 char *p, *s;
4509 tm = gmtime_r(time, &mytm);
4510 if (tm == NULL)
4511 return NULL;
4512 s = asctime_r(tm, datebuf);
4513 if (s == NULL)
4514 return NULL;
4515 p = strchr(s, '\n');
4516 if (p)
4517 *p = '\0';
4518 return s;
4521 static const struct got_error *
4522 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4523 off_t off, uint8_t type)
4525 struct got_diff_line *p;
4527 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4528 if (p == NULL)
4529 return got_error_from_errno("reallocarray");
4530 *lines = p;
4531 (*lines)[*nlines].offset = off;
4532 (*lines)[*nlines].type = type;
4533 (*nlines)++;
4535 return NULL;
4538 static const struct got_error *
4539 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4540 struct got_diff_line *s_lines, size_t s_nlines)
4542 struct got_diff_line *p;
4543 char buf[BUFSIZ];
4544 size_t i, r;
4546 if (fseeko(src, 0L, SEEK_SET) == -1)
4547 return got_error_from_errno("fseeko");
4549 for (;;) {
4550 r = fread(buf, 1, sizeof(buf), src);
4551 if (r == 0) {
4552 if (ferror(src))
4553 return got_error_from_errno("fread");
4554 if (feof(src))
4555 break;
4557 if (fwrite(buf, 1, r, dst) != r)
4558 return got_ferror(dst, GOT_ERR_IO);
4562 * The diff driver initialises the first line at offset zero when the
4563 * array isn't prepopulated, skip it; we already have it in *d_lines.
4565 for (i = 1; i < s_nlines; ++i)
4566 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4568 --s_nlines;
4570 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4571 if (p == NULL) {
4572 /* d_lines is freed in close_diff_view() */
4573 return got_error_from_errno("reallocarray");
4576 *d_lines = p;
4578 memcpy(*d_lines + *d_nlines, s_lines + 1, s_nlines * sizeof(*s_lines));
4579 *d_nlines += s_nlines;
4581 return NULL;
4584 static const struct got_error *
4585 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4586 struct got_object_id *commit_id, struct got_reflist_head *refs,
4587 struct got_repository *repo, int ignore_ws, int force_text_diff,
4588 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4590 const struct got_error *err = NULL;
4591 char datebuf[26], *datestr;
4592 struct got_commit_object *commit;
4593 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4594 time_t committer_time;
4595 const char *author, *committer;
4596 char *refs_str = NULL;
4597 struct got_pathlist_entry *pe;
4598 off_t outoff = 0;
4599 int n;
4601 if (refs) {
4602 err = build_refs_str(&refs_str, refs, commit_id, repo);
4603 if (err)
4604 return err;
4607 err = got_object_open_as_commit(&commit, repo, commit_id);
4608 if (err)
4609 return err;
4611 err = got_object_id_str(&id_str, commit_id);
4612 if (err) {
4613 err = got_error_from_errno("got_object_id_str");
4614 goto done;
4617 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4618 if (err)
4619 goto done;
4621 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4622 refs_str ? refs_str : "", refs_str ? ")" : "");
4623 if (n < 0) {
4624 err = got_error_from_errno("fprintf");
4625 goto done;
4627 outoff += n;
4628 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4629 if (err)
4630 goto done;
4632 n = fprintf(outfile, "from: %s\n",
4633 got_object_commit_get_author(commit));
4634 if (n < 0) {
4635 err = got_error_from_errno("fprintf");
4636 goto done;
4638 outoff += n;
4639 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4640 if (err)
4641 goto done;
4643 author = got_object_commit_get_author(commit);
4644 committer = got_object_commit_get_committer(commit);
4645 if (strcmp(author, committer) != 0) {
4646 n = fprintf(outfile, "via: %s\n", committer);
4647 if (n < 0) {
4648 err = got_error_from_errno("fprintf");
4649 goto done;
4651 outoff += n;
4652 err = add_line_metadata(lines, nlines, outoff,
4653 GOT_DIFF_LINE_AUTHOR);
4654 if (err)
4655 goto done;
4657 committer_time = got_object_commit_get_committer_time(commit);
4658 datestr = get_datestr(&committer_time, datebuf);
4659 if (datestr) {
4660 n = fprintf(outfile, "date: %s UTC\n", datestr);
4661 if (n < 0) {
4662 err = got_error_from_errno("fprintf");
4663 goto done;
4665 outoff += n;
4666 err = add_line_metadata(lines, nlines, outoff,
4667 GOT_DIFF_LINE_DATE);
4668 if (err)
4669 goto done;
4671 if (got_object_commit_get_nparents(commit) > 1) {
4672 const struct got_object_id_queue *parent_ids;
4673 struct got_object_qid *qid;
4674 int pn = 1;
4675 parent_ids = got_object_commit_get_parent_ids(commit);
4676 STAILQ_FOREACH(qid, parent_ids, entry) {
4677 err = got_object_id_str(&id_str, &qid->id);
4678 if (err)
4679 goto done;
4680 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4681 if (n < 0) {
4682 err = got_error_from_errno("fprintf");
4683 goto done;
4685 outoff += n;
4686 err = add_line_metadata(lines, nlines, outoff,
4687 GOT_DIFF_LINE_META);
4688 if (err)
4689 goto done;
4690 free(id_str);
4691 id_str = NULL;
4695 err = got_object_commit_get_logmsg(&logmsg, commit);
4696 if (err)
4697 goto done;
4698 s = logmsg;
4699 while ((line = strsep(&s, "\n")) != NULL) {
4700 n = fprintf(outfile, "%s\n", line);
4701 if (n < 0) {
4702 err = got_error_from_errno("fprintf");
4703 goto done;
4705 outoff += n;
4706 err = add_line_metadata(lines, nlines, outoff,
4707 GOT_DIFF_LINE_LOGMSG);
4708 if (err)
4709 goto done;
4712 TAILQ_FOREACH(pe, dsa->paths, entry) {
4713 struct got_diff_changed_path *cp = pe->data;
4714 int pad = dsa->max_path_len - pe->path_len + 1;
4716 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4717 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4718 dsa->rm_cols + 1, cp->rm);
4719 if (n < 0) {
4720 err = got_error_from_errno("fprintf");
4721 goto done;
4723 outoff += n;
4724 err = add_line_metadata(lines, nlines, outoff,
4725 GOT_DIFF_LINE_CHANGES);
4726 if (err)
4727 goto done;
4730 fputc('\n', outfile);
4731 outoff++;
4732 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4733 if (err)
4734 goto done;
4736 n = fprintf(outfile,
4737 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4738 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4739 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4740 if (n < 0) {
4741 err = got_error_from_errno("fprintf");
4742 goto done;
4744 outoff += n;
4745 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4746 if (err)
4747 goto done;
4749 fputc('\n', outfile);
4750 outoff++;
4751 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4752 done:
4753 free(id_str);
4754 free(logmsg);
4755 free(refs_str);
4756 got_object_commit_close(commit);
4757 if (err) {
4758 free(*lines);
4759 *lines = NULL;
4760 *nlines = 0;
4762 return err;
4765 static const struct got_error *
4766 create_diff(struct tog_diff_view_state *s)
4768 const struct got_error *err = NULL;
4769 FILE *f = NULL, *tmp_diff_file = NULL;
4770 int obj_type;
4771 struct got_diff_line *lines = NULL;
4772 struct got_pathlist_head changed_paths;
4774 TAILQ_INIT(&changed_paths);
4776 free(s->lines);
4777 s->lines = malloc(sizeof(*s->lines));
4778 if (s->lines == NULL)
4779 return got_error_from_errno("malloc");
4780 s->nlines = 0;
4782 f = got_opentemp();
4783 if (f == NULL) {
4784 err = got_error_from_errno("got_opentemp");
4785 goto done;
4787 tmp_diff_file = got_opentemp();
4788 if (tmp_diff_file == NULL) {
4789 err = got_error_from_errno("got_opentemp");
4790 goto done;
4792 if (s->f && fclose(s->f) == EOF) {
4793 err = got_error_from_errno("fclose");
4794 goto done;
4796 s->f = f;
4798 if (s->id1)
4799 err = got_object_get_type(&obj_type, s->repo, s->id1);
4800 else
4801 err = got_object_get_type(&obj_type, s->repo, s->id2);
4802 if (err)
4803 goto done;
4805 switch (obj_type) {
4806 case GOT_OBJ_TYPE_BLOB:
4807 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4808 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4809 s->label1, s->label2, tog_diff_algo, s->diff_context,
4810 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
4811 s->f);
4812 break;
4813 case GOT_OBJ_TYPE_TREE:
4814 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4815 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4816 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4817 s->force_text_diff, NULL, s->repo, s->f);
4818 break;
4819 case GOT_OBJ_TYPE_COMMIT: {
4820 const struct got_object_id_queue *parent_ids;
4821 struct got_object_qid *pid;
4822 struct got_commit_object *commit2;
4823 struct got_reflist_head *refs;
4824 size_t nlines = 0;
4825 struct got_diffstat_cb_arg dsa = {
4826 0, 0, 0, 0, 0, 0,
4827 &changed_paths,
4828 s->ignore_whitespace,
4829 s->force_text_diff,
4830 tog_diff_algo
4833 lines = malloc(sizeof(*lines));
4834 if (lines == NULL) {
4835 err = got_error_from_errno("malloc");
4836 goto done;
4839 /* build diff first in tmp file then append to commit info */
4840 err = got_diff_objects_as_commits(&lines, &nlines,
4841 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4842 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4843 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
4844 if (err)
4845 break;
4847 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4848 if (err)
4849 goto done;
4850 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4851 /* Show commit info if we're diffing to a parent/root commit. */
4852 if (s->id1 == NULL) {
4853 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4854 refs, s->repo, s->ignore_whitespace,
4855 s->force_text_diff, &dsa, s->f);
4856 if (err)
4857 goto done;
4858 } else {
4859 parent_ids = got_object_commit_get_parent_ids(commit2);
4860 STAILQ_FOREACH(pid, parent_ids, entry) {
4861 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4862 err = write_commit_info(&s->lines,
4863 &s->nlines, s->id2, refs, s->repo,
4864 s->ignore_whitespace,
4865 s->force_text_diff, &dsa, s->f);
4866 if (err)
4867 goto done;
4868 break;
4872 got_object_commit_close(commit2);
4874 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
4875 lines, nlines);
4876 break;
4878 default:
4879 err = got_error(GOT_ERR_OBJ_TYPE);
4880 break;
4882 done:
4883 free(lines);
4884 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4885 if (s->f && fflush(s->f) != 0 && err == NULL)
4886 err = got_error_from_errno("fflush");
4887 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
4888 err = got_error_from_errno("fclose");
4889 return err;
4892 static void
4893 diff_view_indicate_progress(struct tog_view *view)
4895 mvwaddstr(view->window, 0, 0, "diffing...");
4896 update_panels();
4897 doupdate();
4900 static const struct got_error *
4901 search_start_diff_view(struct tog_view *view)
4903 struct tog_diff_view_state *s = &view->state.diff;
4905 s->matched_line = 0;
4906 return NULL;
4909 static void
4910 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4911 size_t *nlines, int **first, int **last, int **match, int **selected)
4913 struct tog_diff_view_state *s = &view->state.diff;
4915 *f = s->f;
4916 *nlines = s->nlines;
4917 *line_offsets = NULL;
4918 *match = &s->matched_line;
4919 *first = &s->first_displayed_line;
4920 *last = &s->last_displayed_line;
4921 *selected = &s->selected_line;
4924 static const struct got_error *
4925 search_next_view_match(struct tog_view *view)
4927 const struct got_error *err = NULL;
4928 FILE *f;
4929 int lineno;
4930 char *line = NULL;
4931 size_t linesize = 0;
4932 ssize_t linelen;
4933 off_t *line_offsets;
4934 size_t nlines = 0;
4935 int *first, *last, *match, *selected;
4937 if (!view->search_setup)
4938 return got_error_msg(GOT_ERR_NOT_IMPL,
4939 "view search not supported");
4940 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4941 &match, &selected);
4943 if (!view->searching) {
4944 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4945 return NULL;
4948 if (*match) {
4949 if (view->searching == TOG_SEARCH_FORWARD)
4950 lineno = *match + 1;
4951 else
4952 lineno = *match - 1;
4953 } else
4954 lineno = *first - 1 + *selected;
4956 while (1) {
4957 off_t offset;
4959 if (lineno <= 0 || lineno > nlines) {
4960 if (*match == 0) {
4961 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4962 break;
4965 if (view->searching == TOG_SEARCH_FORWARD)
4966 lineno = 1;
4967 else
4968 lineno = nlines;
4971 offset = view->type == TOG_VIEW_DIFF ?
4972 view->state.diff.lines[lineno - 1].offset :
4973 line_offsets[lineno - 1];
4974 if (fseeko(f, offset, SEEK_SET) != 0) {
4975 free(line);
4976 return got_error_from_errno("fseeko");
4978 linelen = getline(&line, &linesize, f);
4979 if (linelen != -1) {
4980 char *exstr;
4981 err = expand_tab(&exstr, line);
4982 if (err)
4983 break;
4984 if (match_line(exstr, &view->regex, 1,
4985 &view->regmatch)) {
4986 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4987 *match = lineno;
4988 free(exstr);
4989 break;
4991 free(exstr);
4993 if (view->searching == TOG_SEARCH_FORWARD)
4994 lineno++;
4995 else
4996 lineno--;
4998 free(line);
5000 if (*match) {
5001 *first = *match;
5002 *selected = 1;
5005 return err;
5008 static const struct got_error *
5009 close_diff_view(struct tog_view *view)
5011 const struct got_error *err = NULL;
5012 struct tog_diff_view_state *s = &view->state.diff;
5014 free(s->id1);
5015 s->id1 = NULL;
5016 free(s->id2);
5017 s->id2 = NULL;
5018 if (s->f && fclose(s->f) == EOF)
5019 err = got_error_from_errno("fclose");
5020 s->f = NULL;
5021 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5022 err = got_error_from_errno("fclose");
5023 s->f1 = NULL;
5024 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5025 err = got_error_from_errno("fclose");
5026 s->f2 = NULL;
5027 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5028 err = got_error_from_errno("close");
5029 s->fd1 = -1;
5030 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5031 err = got_error_from_errno("close");
5032 s->fd2 = -1;
5033 free(s->lines);
5034 s->lines = NULL;
5035 s->nlines = 0;
5036 return err;
5039 static const struct got_error *
5040 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5041 struct got_object_id *id2, const char *label1, const char *label2,
5042 int diff_context, int ignore_whitespace, int force_text_diff,
5043 struct tog_view *parent_view, struct got_repository *repo)
5045 const struct got_error *err;
5046 struct tog_diff_view_state *s = &view->state.diff;
5048 memset(s, 0, sizeof(*s));
5049 s->fd1 = -1;
5050 s->fd2 = -1;
5052 if (id1 != NULL && id2 != NULL) {
5053 int type1, type2;
5054 err = got_object_get_type(&type1, repo, id1);
5055 if (err)
5056 return err;
5057 err = got_object_get_type(&type2, repo, id2);
5058 if (err)
5059 return err;
5061 if (type1 != type2)
5062 return got_error(GOT_ERR_OBJ_TYPE);
5064 s->first_displayed_line = 1;
5065 s->last_displayed_line = view->nlines;
5066 s->selected_line = 1;
5067 s->repo = repo;
5068 s->id1 = id1;
5069 s->id2 = id2;
5070 s->label1 = label1;
5071 s->label2 = label2;
5073 if (id1) {
5074 s->id1 = got_object_id_dup(id1);
5075 if (s->id1 == NULL)
5076 return got_error_from_errno("got_object_id_dup");
5077 } else
5078 s->id1 = NULL;
5080 s->id2 = got_object_id_dup(id2);
5081 if (s->id2 == NULL) {
5082 err = got_error_from_errno("got_object_id_dup");
5083 goto done;
5086 s->f1 = got_opentemp();
5087 if (s->f1 == NULL) {
5088 err = got_error_from_errno("got_opentemp");
5089 goto done;
5092 s->f2 = got_opentemp();
5093 if (s->f2 == NULL) {
5094 err = got_error_from_errno("got_opentemp");
5095 goto done;
5098 s->fd1 = got_opentempfd();
5099 if (s->fd1 == -1) {
5100 err = got_error_from_errno("got_opentempfd");
5101 goto done;
5104 s->fd2 = got_opentempfd();
5105 if (s->fd2 == -1) {
5106 err = got_error_from_errno("got_opentempfd");
5107 goto done;
5110 s->diff_context = diff_context;
5111 s->ignore_whitespace = ignore_whitespace;
5112 s->force_text_diff = force_text_diff;
5113 s->parent_view = parent_view;
5114 s->repo = repo;
5116 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5117 int rc;
5119 rc = init_pair(GOT_DIFF_LINE_MINUS,
5120 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5121 if (rc != ERR)
5122 rc = init_pair(GOT_DIFF_LINE_PLUS,
5123 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5124 if (rc != ERR)
5125 rc = init_pair(GOT_DIFF_LINE_HUNK,
5126 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5127 if (rc != ERR)
5128 rc = init_pair(GOT_DIFF_LINE_META,
5129 get_color_value("TOG_COLOR_DIFF_META"), -1);
5130 if (rc != ERR)
5131 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5132 get_color_value("TOG_COLOR_DIFF_META"), -1);
5133 if (rc != ERR)
5134 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5135 get_color_value("TOG_COLOR_DIFF_META"), -1);
5136 if (rc != ERR)
5137 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5138 get_color_value("TOG_COLOR_DIFF_META"), -1);
5139 if (rc != ERR)
5140 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5141 get_color_value("TOG_COLOR_AUTHOR"), -1);
5142 if (rc != ERR)
5143 rc = init_pair(GOT_DIFF_LINE_DATE,
5144 get_color_value("TOG_COLOR_DATE"), -1);
5145 if (rc == ERR) {
5146 err = got_error(GOT_ERR_RANGE);
5147 goto done;
5151 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5152 view_is_splitscreen(view))
5153 show_log_view(parent_view); /* draw border */
5154 diff_view_indicate_progress(view);
5156 err = create_diff(s);
5158 view->show = show_diff_view;
5159 view->input = input_diff_view;
5160 view->reset = reset_diff_view;
5161 view->close = close_diff_view;
5162 view->search_start = search_start_diff_view;
5163 view->search_setup = search_setup_diff_view;
5164 view->search_next = search_next_view_match;
5165 done:
5166 if (err)
5167 close_diff_view(view);
5168 return err;
5171 static const struct got_error *
5172 show_diff_view(struct tog_view *view)
5174 const struct got_error *err;
5175 struct tog_diff_view_state *s = &view->state.diff;
5176 char *id_str1 = NULL, *id_str2, *header;
5177 const char *label1, *label2;
5179 if (s->id1) {
5180 err = got_object_id_str(&id_str1, s->id1);
5181 if (err)
5182 return err;
5183 label1 = s->label1 ? s->label1 : id_str1;
5184 } else
5185 label1 = "/dev/null";
5187 err = got_object_id_str(&id_str2, s->id2);
5188 if (err)
5189 return err;
5190 label2 = s->label2 ? s->label2 : id_str2;
5192 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5193 err = got_error_from_errno("asprintf");
5194 free(id_str1);
5195 free(id_str2);
5196 return err;
5198 free(id_str1);
5199 free(id_str2);
5201 err = draw_file(view, header);
5202 free(header);
5203 return err;
5206 static const struct got_error *
5207 set_selected_commit(struct tog_diff_view_state *s,
5208 struct commit_queue_entry *entry)
5210 const struct got_error *err;
5211 const struct got_object_id_queue *parent_ids;
5212 struct got_commit_object *selected_commit;
5213 struct got_object_qid *pid;
5215 free(s->id2);
5216 s->id2 = got_object_id_dup(entry->id);
5217 if (s->id2 == NULL)
5218 return got_error_from_errno("got_object_id_dup");
5220 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5221 if (err)
5222 return err;
5223 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5224 free(s->id1);
5225 pid = STAILQ_FIRST(parent_ids);
5226 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5227 got_object_commit_close(selected_commit);
5228 return NULL;
5231 static const struct got_error *
5232 reset_diff_view(struct tog_view *view)
5234 struct tog_diff_view_state *s = &view->state.diff;
5236 view->count = 0;
5237 wclear(view->window);
5238 s->first_displayed_line = 1;
5239 s->last_displayed_line = view->nlines;
5240 s->matched_line = 0;
5241 diff_view_indicate_progress(view);
5242 return create_diff(s);
5245 static void
5246 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5248 int start, i;
5250 i = start = s->first_displayed_line - 1;
5252 while (s->lines[i].type != type) {
5253 if (i == 0)
5254 i = s->nlines - 1;
5255 if (--i == start)
5256 return; /* do nothing, requested type not in file */
5259 s->selected_line = 1;
5260 s->first_displayed_line = i;
5263 static void
5264 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5266 int start, i;
5268 i = start = s->first_displayed_line + 1;
5270 while (s->lines[i].type != type) {
5271 if (i == s->nlines - 1)
5272 i = 0;
5273 if (++i == start)
5274 return; /* do nothing, requested type not in file */
5277 s->selected_line = 1;
5278 s->first_displayed_line = i;
5281 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5282 int, int, int);
5283 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5284 int, int);
5286 static const struct got_error *
5287 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5289 const struct got_error *err = NULL;
5290 struct tog_diff_view_state *s = &view->state.diff;
5291 struct tog_log_view_state *ls;
5292 struct commit_queue_entry *old_selected_entry;
5293 char *line = NULL;
5294 size_t linesize = 0;
5295 ssize_t linelen;
5296 int i, nscroll = view->nlines - 1, up = 0;
5298 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5300 switch (ch) {
5301 case '0':
5302 view->x = 0;
5303 break;
5304 case '$':
5305 view->x = MAX(view->maxx - view->ncols / 3, 0);
5306 view->count = 0;
5307 break;
5308 case KEY_RIGHT:
5309 case 'l':
5310 if (view->x + view->ncols / 3 < view->maxx)
5311 view->x += 2; /* move two columns right */
5312 else
5313 view->count = 0;
5314 break;
5315 case KEY_LEFT:
5316 case 'h':
5317 view->x -= MIN(view->x, 2); /* move two columns back */
5318 if (view->x <= 0)
5319 view->count = 0;
5320 break;
5321 case 'a':
5322 case 'w':
5323 if (ch == 'a') {
5324 s->force_text_diff = !s->force_text_diff;
5325 view->action = s->force_text_diff ?
5326 "force ASCII text enabled" :
5327 "force ASCII text disabled";
5329 else if (ch == 'w') {
5330 s->ignore_whitespace = !s->ignore_whitespace;
5331 view->action = s->ignore_whitespace ?
5332 "ignore whitespace enabled" :
5333 "ignore whitespace disabled";
5335 err = reset_diff_view(view);
5336 break;
5337 case 'g':
5338 case KEY_HOME:
5339 s->first_displayed_line = 1;
5340 view->count = 0;
5341 break;
5342 case 'G':
5343 case KEY_END:
5344 view->count = 0;
5345 if (s->eof)
5346 break;
5348 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5349 s->eof = 1;
5350 break;
5351 case 'k':
5352 case KEY_UP:
5353 case CTRL('p'):
5354 if (s->first_displayed_line > 1)
5355 s->first_displayed_line--;
5356 else
5357 view->count = 0;
5358 break;
5359 case CTRL('u'):
5360 case 'u':
5361 nscroll /= 2;
5362 /* FALL THROUGH */
5363 case KEY_PPAGE:
5364 case CTRL('b'):
5365 case 'b':
5366 if (s->first_displayed_line == 1) {
5367 view->count = 0;
5368 break;
5370 i = 0;
5371 while (i++ < nscroll && s->first_displayed_line > 1)
5372 s->first_displayed_line--;
5373 break;
5374 case 'j':
5375 case KEY_DOWN:
5376 case CTRL('n'):
5377 if (!s->eof)
5378 s->first_displayed_line++;
5379 else
5380 view->count = 0;
5381 break;
5382 case CTRL('d'):
5383 case 'd':
5384 nscroll /= 2;
5385 /* FALL THROUGH */
5386 case KEY_NPAGE:
5387 case CTRL('f'):
5388 case 'f':
5389 case ' ':
5390 if (s->eof) {
5391 view->count = 0;
5392 break;
5394 i = 0;
5395 while (!s->eof && i++ < nscroll) {
5396 linelen = getline(&line, &linesize, s->f);
5397 s->first_displayed_line++;
5398 if (linelen == -1) {
5399 if (feof(s->f)) {
5400 s->eof = 1;
5401 } else
5402 err = got_ferror(s->f, GOT_ERR_IO);
5403 break;
5406 free(line);
5407 break;
5408 case '(':
5409 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5410 break;
5411 case ')':
5412 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5413 break;
5414 case '{':
5415 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5416 break;
5417 case '}':
5418 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5419 break;
5420 case '[':
5421 if (s->diff_context > 0) {
5422 s->diff_context--;
5423 s->matched_line = 0;
5424 diff_view_indicate_progress(view);
5425 err = create_diff(s);
5426 if (s->first_displayed_line + view->nlines - 1 >
5427 s->nlines) {
5428 s->first_displayed_line = 1;
5429 s->last_displayed_line = view->nlines;
5431 } else
5432 view->count = 0;
5433 break;
5434 case ']':
5435 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5436 s->diff_context++;
5437 s->matched_line = 0;
5438 diff_view_indicate_progress(view);
5439 err = create_diff(s);
5440 } else
5441 view->count = 0;
5442 break;
5443 case '<':
5444 case ',':
5445 case 'K':
5446 up = 1;
5447 /* FALL THROUGH */
5448 case '>':
5449 case '.':
5450 case 'J':
5451 if (s->parent_view == NULL) {
5452 view->count = 0;
5453 break;
5455 s->parent_view->count = view->count;
5457 if (s->parent_view->type == TOG_VIEW_LOG) {
5458 ls = &s->parent_view->state.log;
5459 old_selected_entry = ls->selected_entry;
5461 err = input_log_view(NULL, s->parent_view,
5462 up ? KEY_UP : KEY_DOWN);
5463 if (err)
5464 break;
5465 view->count = s->parent_view->count;
5467 if (old_selected_entry == ls->selected_entry)
5468 break;
5470 err = set_selected_commit(s, ls->selected_entry);
5471 if (err)
5472 break;
5473 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5474 struct tog_blame_view_state *bs;
5475 struct got_object_id *id, *prev_id;
5477 bs = &s->parent_view->state.blame;
5478 prev_id = get_annotation_for_line(bs->blame.lines,
5479 bs->blame.nlines, bs->last_diffed_line);
5481 err = input_blame_view(&view, s->parent_view,
5482 up ? KEY_UP : KEY_DOWN);
5483 if (err)
5484 break;
5485 view->count = s->parent_view->count;
5487 if (prev_id == NULL)
5488 break;
5489 id = get_selected_commit_id(bs->blame.lines,
5490 bs->blame.nlines, bs->first_displayed_line,
5491 bs->selected_line);
5492 if (id == NULL)
5493 break;
5495 if (!got_object_id_cmp(prev_id, id))
5496 break;
5498 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5499 if (err)
5500 break;
5502 s->first_displayed_line = 1;
5503 s->last_displayed_line = view->nlines;
5504 s->matched_line = 0;
5505 view->x = 0;
5507 diff_view_indicate_progress(view);
5508 err = create_diff(s);
5509 break;
5510 default:
5511 view->count = 0;
5512 break;
5515 return err;
5518 static const struct got_error *
5519 cmd_diff(int argc, char *argv[])
5521 const struct got_error *error = NULL;
5522 struct got_repository *repo = NULL;
5523 struct got_worktree *worktree = NULL;
5524 struct got_object_id *id1 = NULL, *id2 = NULL;
5525 char *repo_path = NULL, *cwd = NULL;
5526 char *id_str1 = NULL, *id_str2 = NULL;
5527 char *label1 = NULL, *label2 = NULL;
5528 int diff_context = 3, ignore_whitespace = 0;
5529 int ch, force_text_diff = 0;
5530 const char *errstr;
5531 struct tog_view *view;
5532 int *pack_fds = NULL;
5534 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5535 switch (ch) {
5536 case 'a':
5537 force_text_diff = 1;
5538 break;
5539 case 'C':
5540 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5541 &errstr);
5542 if (errstr != NULL)
5543 errx(1, "number of context lines is %s: %s",
5544 errstr, errstr);
5545 break;
5546 case 'r':
5547 repo_path = realpath(optarg, NULL);
5548 if (repo_path == NULL)
5549 return got_error_from_errno2("realpath",
5550 optarg);
5551 got_path_strip_trailing_slashes(repo_path);
5552 break;
5553 case 'w':
5554 ignore_whitespace = 1;
5555 break;
5556 default:
5557 usage_diff();
5558 /* NOTREACHED */
5562 argc -= optind;
5563 argv += optind;
5565 if (argc == 0) {
5566 usage_diff(); /* TODO show local worktree changes */
5567 } else if (argc == 2) {
5568 id_str1 = argv[0];
5569 id_str2 = argv[1];
5570 } else
5571 usage_diff();
5573 error = got_repo_pack_fds_open(&pack_fds);
5574 if (error)
5575 goto done;
5577 if (repo_path == NULL) {
5578 cwd = getcwd(NULL, 0);
5579 if (cwd == NULL)
5580 return got_error_from_errno("getcwd");
5581 error = got_worktree_open(&worktree, cwd);
5582 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5583 goto done;
5584 if (worktree)
5585 repo_path =
5586 strdup(got_worktree_get_repo_path(worktree));
5587 else
5588 repo_path = strdup(cwd);
5589 if (repo_path == NULL) {
5590 error = got_error_from_errno("strdup");
5591 goto done;
5595 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5596 if (error)
5597 goto done;
5599 init_curses();
5601 error = apply_unveil(got_repo_get_path(repo), NULL);
5602 if (error)
5603 goto done;
5605 error = tog_load_refs(repo, 0);
5606 if (error)
5607 goto done;
5609 error = got_repo_match_object_id(&id1, &label1, id_str1,
5610 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5611 if (error)
5612 goto done;
5614 error = got_repo_match_object_id(&id2, &label2, id_str2,
5615 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5616 if (error)
5617 goto done;
5619 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5620 if (view == NULL) {
5621 error = got_error_from_errno("view_open");
5622 goto done;
5624 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5625 ignore_whitespace, force_text_diff, NULL, repo);
5626 if (error)
5627 goto done;
5628 error = view_loop(view);
5629 done:
5630 free(label1);
5631 free(label2);
5632 free(repo_path);
5633 free(cwd);
5634 if (repo) {
5635 const struct got_error *close_err = got_repo_close(repo);
5636 if (error == NULL)
5637 error = close_err;
5639 if (worktree)
5640 got_worktree_close(worktree);
5641 if (pack_fds) {
5642 const struct got_error *pack_err =
5643 got_repo_pack_fds_close(pack_fds);
5644 if (error == NULL)
5645 error = pack_err;
5647 tog_free_refs();
5648 return error;
5651 __dead static void
5652 usage_blame(void)
5654 endwin();
5655 fprintf(stderr,
5656 "usage: %s blame [-c commit] [-r repository-path] path\n",
5657 getprogname());
5658 exit(1);
5661 struct tog_blame_line {
5662 int annotated;
5663 struct got_object_id *id;
5666 static const struct got_error *
5667 draw_blame(struct tog_view *view)
5669 struct tog_blame_view_state *s = &view->state.blame;
5670 struct tog_blame *blame = &s->blame;
5671 regmatch_t *regmatch = &view->regmatch;
5672 const struct got_error *err;
5673 int lineno = 0, nprinted = 0;
5674 char *line = NULL;
5675 size_t linesize = 0;
5676 ssize_t linelen;
5677 wchar_t *wline;
5678 int width;
5679 struct tog_blame_line *blame_line;
5680 struct got_object_id *prev_id = NULL;
5681 char *id_str;
5682 struct tog_color *tc;
5684 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5685 if (err)
5686 return err;
5688 rewind(blame->f);
5689 werase(view->window);
5691 if (asprintf(&line, "commit %s", id_str) == -1) {
5692 err = got_error_from_errno("asprintf");
5693 free(id_str);
5694 return err;
5697 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5698 free(line);
5699 line = NULL;
5700 if (err)
5701 return err;
5702 if (view_needs_focus_indication(view))
5703 wstandout(view->window);
5704 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5705 if (tc)
5706 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5707 waddwstr(view->window, wline);
5708 while (width++ < view->ncols)
5709 waddch(view->window, ' ');
5710 if (tc)
5711 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5712 if (view_needs_focus_indication(view))
5713 wstandend(view->window);
5714 free(wline);
5715 wline = NULL;
5717 if (view->gline > blame->nlines)
5718 view->gline = blame->nlines;
5720 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5721 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5722 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5723 free(id_str);
5724 return got_error_from_errno("asprintf");
5726 free(id_str);
5727 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5728 free(line);
5729 line = NULL;
5730 if (err)
5731 return err;
5732 waddwstr(view->window, wline);
5733 free(wline);
5734 wline = NULL;
5735 if (width < view->ncols - 1)
5736 waddch(view->window, '\n');
5738 s->eof = 0;
5739 view->maxx = 0;
5740 while (nprinted < view->nlines - 2) {
5741 linelen = getline(&line, &linesize, blame->f);
5742 if (linelen == -1) {
5743 if (feof(blame->f)) {
5744 s->eof = 1;
5745 break;
5747 free(line);
5748 return got_ferror(blame->f, GOT_ERR_IO);
5750 if (++lineno < s->first_displayed_line)
5751 continue;
5752 if (view->gline && !gotoline(view, &lineno, &nprinted))
5753 continue;
5755 /* Set view->maxx based on full line length. */
5756 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5757 if (err) {
5758 free(line);
5759 return err;
5761 free(wline);
5762 wline = NULL;
5763 view->maxx = MAX(view->maxx, width);
5765 if (nprinted == s->selected_line - 1)
5766 wstandout(view->window);
5768 if (blame->nlines > 0) {
5769 blame_line = &blame->lines[lineno - 1];
5770 if (blame_line->annotated && prev_id &&
5771 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5772 !(nprinted == s->selected_line - 1)) {
5773 waddstr(view->window, " ");
5774 } else if (blame_line->annotated) {
5775 char *id_str;
5776 err = got_object_id_str(&id_str,
5777 blame_line->id);
5778 if (err) {
5779 free(line);
5780 return err;
5782 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5783 if (tc)
5784 wattr_on(view->window,
5785 COLOR_PAIR(tc->colorpair), NULL);
5786 wprintw(view->window, "%.8s", id_str);
5787 if (tc)
5788 wattr_off(view->window,
5789 COLOR_PAIR(tc->colorpair), NULL);
5790 free(id_str);
5791 prev_id = blame_line->id;
5792 } else {
5793 waddstr(view->window, "........");
5794 prev_id = NULL;
5796 } else {
5797 waddstr(view->window, "........");
5798 prev_id = NULL;
5801 if (nprinted == s->selected_line - 1)
5802 wstandend(view->window);
5803 waddstr(view->window, " ");
5805 if (view->ncols <= 9) {
5806 width = 9;
5807 } else if (s->first_displayed_line + nprinted ==
5808 s->matched_line &&
5809 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5810 err = add_matched_line(&width, line, view->ncols - 9, 9,
5811 view->window, view->x, regmatch);
5812 if (err) {
5813 free(line);
5814 return err;
5816 width += 9;
5817 } else {
5818 int skip;
5819 err = format_line(&wline, &width, &skip, line,
5820 view->x, view->ncols - 9, 9, 1);
5821 if (err) {
5822 free(line);
5823 return err;
5825 waddwstr(view->window, &wline[skip]);
5826 width += 9;
5827 free(wline);
5828 wline = NULL;
5831 if (width <= view->ncols - 1)
5832 waddch(view->window, '\n');
5833 if (++nprinted == 1)
5834 s->first_displayed_line = lineno;
5836 free(line);
5837 s->last_displayed_line = lineno;
5839 view_border(view);
5841 return NULL;
5844 static const struct got_error *
5845 blame_cb(void *arg, int nlines, int lineno,
5846 struct got_commit_object *commit, struct got_object_id *id)
5848 const struct got_error *err = NULL;
5849 struct tog_blame_cb_args *a = arg;
5850 struct tog_blame_line *line;
5851 int errcode;
5853 if (nlines != a->nlines ||
5854 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5855 return got_error(GOT_ERR_RANGE);
5857 errcode = pthread_mutex_lock(&tog_mutex);
5858 if (errcode)
5859 return got_error_set_errno(errcode, "pthread_mutex_lock");
5861 if (*a->quit) { /* user has quit the blame view */
5862 err = got_error(GOT_ERR_ITER_COMPLETED);
5863 goto done;
5866 if (lineno == -1)
5867 goto done; /* no change in this commit */
5869 line = &a->lines[lineno - 1];
5870 if (line->annotated)
5871 goto done;
5873 line->id = got_object_id_dup(id);
5874 if (line->id == NULL) {
5875 err = got_error_from_errno("got_object_id_dup");
5876 goto done;
5878 line->annotated = 1;
5879 done:
5880 errcode = pthread_mutex_unlock(&tog_mutex);
5881 if (errcode)
5882 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5883 return err;
5886 static void *
5887 blame_thread(void *arg)
5889 const struct got_error *err, *close_err;
5890 struct tog_blame_thread_args *ta = arg;
5891 struct tog_blame_cb_args *a = ta->cb_args;
5892 int errcode, fd1 = -1, fd2 = -1;
5893 FILE *f1 = NULL, *f2 = NULL;
5895 fd1 = got_opentempfd();
5896 if (fd1 == -1)
5897 return (void *)got_error_from_errno("got_opentempfd");
5899 fd2 = got_opentempfd();
5900 if (fd2 == -1) {
5901 err = got_error_from_errno("got_opentempfd");
5902 goto done;
5905 f1 = got_opentemp();
5906 if (f1 == NULL) {
5907 err = (void *)got_error_from_errno("got_opentemp");
5908 goto done;
5910 f2 = got_opentemp();
5911 if (f2 == NULL) {
5912 err = (void *)got_error_from_errno("got_opentemp");
5913 goto done;
5916 err = block_signals_used_by_main_thread();
5917 if (err)
5918 goto done;
5920 err = got_blame(ta->path, a->commit_id, ta->repo,
5921 tog_diff_algo, blame_cb, ta->cb_args,
5922 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5923 if (err && err->code == GOT_ERR_CANCELLED)
5924 err = NULL;
5926 errcode = pthread_mutex_lock(&tog_mutex);
5927 if (errcode) {
5928 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5929 goto done;
5932 close_err = got_repo_close(ta->repo);
5933 if (err == NULL)
5934 err = close_err;
5935 ta->repo = NULL;
5936 *ta->complete = 1;
5938 errcode = pthread_mutex_unlock(&tog_mutex);
5939 if (errcode && err == NULL)
5940 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5942 done:
5943 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5944 err = got_error_from_errno("close");
5945 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5946 err = got_error_from_errno("close");
5947 if (f1 && fclose(f1) == EOF && err == NULL)
5948 err = got_error_from_errno("fclose");
5949 if (f2 && fclose(f2) == EOF && err == NULL)
5950 err = got_error_from_errno("fclose");
5952 return (void *)err;
5955 static struct got_object_id *
5956 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5957 int first_displayed_line, int selected_line)
5959 struct tog_blame_line *line;
5961 if (nlines <= 0)
5962 return NULL;
5964 line = &lines[first_displayed_line - 1 + selected_line - 1];
5965 if (!line->annotated)
5966 return NULL;
5968 return line->id;
5971 static struct got_object_id *
5972 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5973 int lineno)
5975 struct tog_blame_line *line;
5977 if (nlines <= 0 || lineno >= nlines)
5978 return NULL;
5980 line = &lines[lineno - 1];
5981 if (!line->annotated)
5982 return NULL;
5984 return line->id;
5987 static const struct got_error *
5988 stop_blame(struct tog_blame *blame)
5990 const struct got_error *err = NULL;
5991 int i;
5993 if (blame->thread) {
5994 int errcode;
5995 errcode = pthread_mutex_unlock(&tog_mutex);
5996 if (errcode)
5997 return got_error_set_errno(errcode,
5998 "pthread_mutex_unlock");
5999 errcode = pthread_join(blame->thread, (void **)&err);
6000 if (errcode)
6001 return got_error_set_errno(errcode, "pthread_join");
6002 errcode = pthread_mutex_lock(&tog_mutex);
6003 if (errcode)
6004 return got_error_set_errno(errcode,
6005 "pthread_mutex_lock");
6006 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6007 err = NULL;
6008 blame->thread = NULL;
6010 if (blame->thread_args.repo) {
6011 const struct got_error *close_err;
6012 close_err = got_repo_close(blame->thread_args.repo);
6013 if (err == NULL)
6014 err = close_err;
6015 blame->thread_args.repo = NULL;
6017 if (blame->f) {
6018 if (fclose(blame->f) == EOF && err == NULL)
6019 err = got_error_from_errno("fclose");
6020 blame->f = NULL;
6022 if (blame->lines) {
6023 for (i = 0; i < blame->nlines; i++)
6024 free(blame->lines[i].id);
6025 free(blame->lines);
6026 blame->lines = NULL;
6028 free(blame->cb_args.commit_id);
6029 blame->cb_args.commit_id = NULL;
6030 if (blame->pack_fds) {
6031 const struct got_error *pack_err =
6032 got_repo_pack_fds_close(blame->pack_fds);
6033 if (err == NULL)
6034 err = pack_err;
6035 blame->pack_fds = NULL;
6037 return err;
6040 static const struct got_error *
6041 cancel_blame_view(void *arg)
6043 const struct got_error *err = NULL;
6044 int *done = arg;
6045 int errcode;
6047 errcode = pthread_mutex_lock(&tog_mutex);
6048 if (errcode)
6049 return got_error_set_errno(errcode,
6050 "pthread_mutex_unlock");
6052 if (*done)
6053 err = got_error(GOT_ERR_CANCELLED);
6055 errcode = pthread_mutex_unlock(&tog_mutex);
6056 if (errcode)
6057 return got_error_set_errno(errcode,
6058 "pthread_mutex_lock");
6060 return err;
6063 static const struct got_error *
6064 run_blame(struct tog_view *view)
6066 struct tog_blame_view_state *s = &view->state.blame;
6067 struct tog_blame *blame = &s->blame;
6068 const struct got_error *err = NULL;
6069 struct got_commit_object *commit = NULL;
6070 struct got_blob_object *blob = NULL;
6071 struct got_repository *thread_repo = NULL;
6072 struct got_object_id *obj_id = NULL;
6073 int obj_type, fd = -1;
6074 int *pack_fds = NULL;
6076 err = got_object_open_as_commit(&commit, s->repo,
6077 &s->blamed_commit->id);
6078 if (err)
6079 return err;
6081 fd = got_opentempfd();
6082 if (fd == -1) {
6083 err = got_error_from_errno("got_opentempfd");
6084 goto done;
6087 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6088 if (err)
6089 goto done;
6091 err = got_object_get_type(&obj_type, s->repo, obj_id);
6092 if (err)
6093 goto done;
6095 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6096 err = got_error(GOT_ERR_OBJ_TYPE);
6097 goto done;
6100 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6101 if (err)
6102 goto done;
6103 blame->f = got_opentemp();
6104 if (blame->f == NULL) {
6105 err = got_error_from_errno("got_opentemp");
6106 goto done;
6108 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6109 &blame->line_offsets, blame->f, blob);
6110 if (err)
6111 goto done;
6112 if (blame->nlines == 0) {
6113 s->blame_complete = 1;
6114 goto done;
6117 /* Don't include \n at EOF in the blame line count. */
6118 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6119 blame->nlines--;
6121 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6122 if (blame->lines == NULL) {
6123 err = got_error_from_errno("calloc");
6124 goto done;
6127 err = got_repo_pack_fds_open(&pack_fds);
6128 if (err)
6129 goto done;
6130 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6131 pack_fds);
6132 if (err)
6133 goto done;
6135 blame->pack_fds = pack_fds;
6136 blame->cb_args.view = view;
6137 blame->cb_args.lines = blame->lines;
6138 blame->cb_args.nlines = blame->nlines;
6139 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6140 if (blame->cb_args.commit_id == NULL) {
6141 err = got_error_from_errno("got_object_id_dup");
6142 goto done;
6144 blame->cb_args.quit = &s->done;
6146 blame->thread_args.path = s->path;
6147 blame->thread_args.repo = thread_repo;
6148 blame->thread_args.cb_args = &blame->cb_args;
6149 blame->thread_args.complete = &s->blame_complete;
6150 blame->thread_args.cancel_cb = cancel_blame_view;
6151 blame->thread_args.cancel_arg = &s->done;
6152 s->blame_complete = 0;
6154 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6155 s->first_displayed_line = 1;
6156 s->last_displayed_line = view->nlines;
6157 s->selected_line = 1;
6159 s->matched_line = 0;
6161 done:
6162 if (commit)
6163 got_object_commit_close(commit);
6164 if (fd != -1 && close(fd) == -1 && err == NULL)
6165 err = got_error_from_errno("close");
6166 if (blob)
6167 got_object_blob_close(blob);
6168 free(obj_id);
6169 if (err)
6170 stop_blame(blame);
6171 return err;
6174 static const struct got_error *
6175 open_blame_view(struct tog_view *view, char *path,
6176 struct got_object_id *commit_id, struct got_repository *repo)
6178 const struct got_error *err = NULL;
6179 struct tog_blame_view_state *s = &view->state.blame;
6181 STAILQ_INIT(&s->blamed_commits);
6183 s->path = strdup(path);
6184 if (s->path == NULL)
6185 return got_error_from_errno("strdup");
6187 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6188 if (err) {
6189 free(s->path);
6190 return err;
6193 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6194 s->first_displayed_line = 1;
6195 s->last_displayed_line = view->nlines;
6196 s->selected_line = 1;
6197 s->blame_complete = 0;
6198 s->repo = repo;
6199 s->commit_id = commit_id;
6200 memset(&s->blame, 0, sizeof(s->blame));
6202 STAILQ_INIT(&s->colors);
6203 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6204 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6205 get_color_value("TOG_COLOR_COMMIT"));
6206 if (err)
6207 return err;
6210 view->show = show_blame_view;
6211 view->input = input_blame_view;
6212 view->reset = reset_blame_view;
6213 view->close = close_blame_view;
6214 view->search_start = search_start_blame_view;
6215 view->search_setup = search_setup_blame_view;
6216 view->search_next = search_next_view_match;
6218 return run_blame(view);
6221 static const struct got_error *
6222 close_blame_view(struct tog_view *view)
6224 const struct got_error *err = NULL;
6225 struct tog_blame_view_state *s = &view->state.blame;
6227 if (s->blame.thread)
6228 err = stop_blame(&s->blame);
6230 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6231 struct got_object_qid *blamed_commit;
6232 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6233 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6234 got_object_qid_free(blamed_commit);
6237 free(s->path);
6238 free_colors(&s->colors);
6239 return err;
6242 static const struct got_error *
6243 search_start_blame_view(struct tog_view *view)
6245 struct tog_blame_view_state *s = &view->state.blame;
6247 s->matched_line = 0;
6248 return NULL;
6251 static void
6252 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6253 size_t *nlines, int **first, int **last, int **match, int **selected)
6255 struct tog_blame_view_state *s = &view->state.blame;
6257 *f = s->blame.f;
6258 *nlines = s->blame.nlines;
6259 *line_offsets = s->blame.line_offsets;
6260 *match = &s->matched_line;
6261 *first = &s->first_displayed_line;
6262 *last = &s->last_displayed_line;
6263 *selected = &s->selected_line;
6266 static const struct got_error *
6267 show_blame_view(struct tog_view *view)
6269 const struct got_error *err = NULL;
6270 struct tog_blame_view_state *s = &view->state.blame;
6271 int errcode;
6273 if (s->blame.thread == NULL && !s->blame_complete) {
6274 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6275 &s->blame.thread_args);
6276 if (errcode)
6277 return got_error_set_errno(errcode, "pthread_create");
6279 halfdelay(1); /* fast refresh while annotating */
6282 if (s->blame_complete)
6283 halfdelay(10); /* disable fast refresh */
6285 err = draw_blame(view);
6287 view_border(view);
6288 return err;
6291 static const struct got_error *
6292 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6293 struct got_repository *repo, struct got_object_id *id)
6295 struct tog_view *log_view;
6296 const struct got_error *err = NULL;
6298 *new_view = NULL;
6300 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6301 if (log_view == NULL)
6302 return got_error_from_errno("view_open");
6304 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6305 if (err)
6306 view_close(log_view);
6307 else
6308 *new_view = log_view;
6310 return err;
6313 static const struct got_error *
6314 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6316 const struct got_error *err = NULL, *thread_err = NULL;
6317 struct tog_view *diff_view;
6318 struct tog_blame_view_state *s = &view->state.blame;
6319 int eos, nscroll, begin_y = 0, begin_x = 0;
6321 eos = nscroll = view->nlines - 2;
6322 if (view_is_hsplit_top(view))
6323 --eos; /* border */
6325 switch (ch) {
6326 case '0':
6327 view->x = 0;
6328 break;
6329 case '$':
6330 view->x = MAX(view->maxx - view->ncols / 3, 0);
6331 view->count = 0;
6332 break;
6333 case KEY_RIGHT:
6334 case 'l':
6335 if (view->x + view->ncols / 3 < view->maxx)
6336 view->x += 2; /* move two columns right */
6337 else
6338 view->count = 0;
6339 break;
6340 case KEY_LEFT:
6341 case 'h':
6342 view->x -= MIN(view->x, 2); /* move two columns back */
6343 if (view->x <= 0)
6344 view->count = 0;
6345 break;
6346 case 'q':
6347 s->done = 1;
6348 break;
6349 case 'g':
6350 case KEY_HOME:
6351 s->selected_line = 1;
6352 s->first_displayed_line = 1;
6353 view->count = 0;
6354 break;
6355 case 'G':
6356 case KEY_END:
6357 if (s->blame.nlines < eos) {
6358 s->selected_line = s->blame.nlines;
6359 s->first_displayed_line = 1;
6360 } else {
6361 s->selected_line = eos;
6362 s->first_displayed_line = s->blame.nlines - (eos - 1);
6364 view->count = 0;
6365 break;
6366 case 'k':
6367 case KEY_UP:
6368 case CTRL('p'):
6369 if (s->selected_line > 1)
6370 s->selected_line--;
6371 else if (s->selected_line == 1 &&
6372 s->first_displayed_line > 1)
6373 s->first_displayed_line--;
6374 else
6375 view->count = 0;
6376 break;
6377 case CTRL('u'):
6378 case 'u':
6379 nscroll /= 2;
6380 /* FALL THROUGH */
6381 case KEY_PPAGE:
6382 case CTRL('b'):
6383 case 'b':
6384 if (s->first_displayed_line == 1) {
6385 if (view->count > 1)
6386 nscroll += nscroll;
6387 s->selected_line = MAX(1, s->selected_line - nscroll);
6388 view->count = 0;
6389 break;
6391 if (s->first_displayed_line > nscroll)
6392 s->first_displayed_line -= nscroll;
6393 else
6394 s->first_displayed_line = 1;
6395 break;
6396 case 'j':
6397 case KEY_DOWN:
6398 case CTRL('n'):
6399 if (s->selected_line < eos && s->first_displayed_line +
6400 s->selected_line <= s->blame.nlines)
6401 s->selected_line++;
6402 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6403 s->first_displayed_line++;
6404 else
6405 view->count = 0;
6406 break;
6407 case 'c':
6408 case 'p': {
6409 struct got_object_id *id = NULL;
6411 view->count = 0;
6412 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6413 s->first_displayed_line, s->selected_line);
6414 if (id == NULL)
6415 break;
6416 if (ch == 'p') {
6417 struct got_commit_object *commit, *pcommit;
6418 struct got_object_qid *pid;
6419 struct got_object_id *blob_id = NULL;
6420 int obj_type;
6421 err = got_object_open_as_commit(&commit,
6422 s->repo, id);
6423 if (err)
6424 break;
6425 pid = STAILQ_FIRST(
6426 got_object_commit_get_parent_ids(commit));
6427 if (pid == NULL) {
6428 got_object_commit_close(commit);
6429 break;
6431 /* Check if path history ends here. */
6432 err = got_object_open_as_commit(&pcommit,
6433 s->repo, &pid->id);
6434 if (err)
6435 break;
6436 err = got_object_id_by_path(&blob_id, s->repo,
6437 pcommit, s->path);
6438 got_object_commit_close(pcommit);
6439 if (err) {
6440 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6441 err = NULL;
6442 got_object_commit_close(commit);
6443 break;
6445 err = got_object_get_type(&obj_type, s->repo,
6446 blob_id);
6447 free(blob_id);
6448 /* Can't blame non-blob type objects. */
6449 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6450 got_object_commit_close(commit);
6451 break;
6453 err = got_object_qid_alloc(&s->blamed_commit,
6454 &pid->id);
6455 got_object_commit_close(commit);
6456 } else {
6457 if (got_object_id_cmp(id,
6458 &s->blamed_commit->id) == 0)
6459 break;
6460 err = got_object_qid_alloc(&s->blamed_commit,
6461 id);
6463 if (err)
6464 break;
6465 s->done = 1;
6466 thread_err = stop_blame(&s->blame);
6467 s->done = 0;
6468 if (thread_err)
6469 break;
6470 STAILQ_INSERT_HEAD(&s->blamed_commits,
6471 s->blamed_commit, entry);
6472 err = run_blame(view);
6473 if (err)
6474 break;
6475 break;
6477 case 'C': {
6478 struct got_object_qid *first;
6480 view->count = 0;
6481 first = STAILQ_FIRST(&s->blamed_commits);
6482 if (!got_object_id_cmp(&first->id, s->commit_id))
6483 break;
6484 s->done = 1;
6485 thread_err = stop_blame(&s->blame);
6486 s->done = 0;
6487 if (thread_err)
6488 break;
6489 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6490 got_object_qid_free(s->blamed_commit);
6491 s->blamed_commit =
6492 STAILQ_FIRST(&s->blamed_commits);
6493 err = run_blame(view);
6494 if (err)
6495 break;
6496 break;
6498 case 'L':
6499 view->count = 0;
6500 s->id_to_log = get_selected_commit_id(s->blame.lines,
6501 s->blame.nlines, s->first_displayed_line, s->selected_line);
6502 if (s->id_to_log)
6503 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6504 break;
6505 case KEY_ENTER:
6506 case '\r': {
6507 struct got_object_id *id = NULL;
6508 struct got_object_qid *pid;
6509 struct got_commit_object *commit = NULL;
6511 view->count = 0;
6512 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6513 s->first_displayed_line, s->selected_line);
6514 if (id == NULL)
6515 break;
6516 err = got_object_open_as_commit(&commit, s->repo, id);
6517 if (err)
6518 break;
6519 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6520 if (*new_view) {
6521 /* traversed from diff view, release diff resources */
6522 err = close_diff_view(*new_view);
6523 if (err)
6524 break;
6525 diff_view = *new_view;
6526 } else {
6527 if (view_is_parent_view(view))
6528 view_get_split(view, &begin_y, &begin_x);
6530 diff_view = view_open(0, 0, begin_y, begin_x,
6531 TOG_VIEW_DIFF);
6532 if (diff_view == NULL) {
6533 got_object_commit_close(commit);
6534 err = got_error_from_errno("view_open");
6535 break;
6538 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6539 id, NULL, NULL, 3, 0, 0, view, s->repo);
6540 got_object_commit_close(commit);
6541 if (err) {
6542 view_close(diff_view);
6543 break;
6545 s->last_diffed_line = s->first_displayed_line - 1 +
6546 s->selected_line;
6547 if (*new_view)
6548 break; /* still open from active diff view */
6549 if (view_is_parent_view(view) &&
6550 view->mode == TOG_VIEW_SPLIT_HRZN) {
6551 err = view_init_hsplit(view, begin_y);
6552 if (err)
6553 break;
6556 view->focussed = 0;
6557 diff_view->focussed = 1;
6558 diff_view->mode = view->mode;
6559 diff_view->nlines = view->lines - begin_y;
6560 if (view_is_parent_view(view)) {
6561 view_transfer_size(diff_view, view);
6562 err = view_close_child(view);
6563 if (err)
6564 break;
6565 err = view_set_child(view, diff_view);
6566 if (err)
6567 break;
6568 view->focus_child = 1;
6569 } else
6570 *new_view = diff_view;
6571 if (err)
6572 break;
6573 break;
6575 case CTRL('d'):
6576 case 'd':
6577 nscroll /= 2;
6578 /* FALL THROUGH */
6579 case KEY_NPAGE:
6580 case CTRL('f'):
6581 case 'f':
6582 case ' ':
6583 if (s->last_displayed_line >= s->blame.nlines &&
6584 s->selected_line >= MIN(s->blame.nlines,
6585 view->nlines - 2)) {
6586 view->count = 0;
6587 break;
6589 if (s->last_displayed_line >= s->blame.nlines &&
6590 s->selected_line < view->nlines - 2) {
6591 s->selected_line +=
6592 MIN(nscroll, s->last_displayed_line -
6593 s->first_displayed_line - s->selected_line + 1);
6595 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6596 s->first_displayed_line += nscroll;
6597 else
6598 s->first_displayed_line =
6599 s->blame.nlines - (view->nlines - 3);
6600 break;
6601 case KEY_RESIZE:
6602 if (s->selected_line > view->nlines - 2) {
6603 s->selected_line = MIN(s->blame.nlines,
6604 view->nlines - 2);
6606 break;
6607 default:
6608 view->count = 0;
6609 break;
6611 return thread_err ? thread_err : err;
6614 static const struct got_error *
6615 reset_blame_view(struct tog_view *view)
6617 const struct got_error *err;
6618 struct tog_blame_view_state *s = &view->state.blame;
6620 view->count = 0;
6621 s->done = 1;
6622 err = stop_blame(&s->blame);
6623 s->done = 0;
6624 if (err)
6625 return err;
6626 return run_blame(view);
6629 static const struct got_error *
6630 cmd_blame(int argc, char *argv[])
6632 const struct got_error *error;
6633 struct got_repository *repo = NULL;
6634 struct got_worktree *worktree = NULL;
6635 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6636 char *link_target = NULL;
6637 struct got_object_id *commit_id = NULL;
6638 struct got_commit_object *commit = NULL;
6639 char *commit_id_str = NULL;
6640 int ch;
6641 struct tog_view *view;
6642 int *pack_fds = NULL;
6644 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6645 switch (ch) {
6646 case 'c':
6647 commit_id_str = optarg;
6648 break;
6649 case 'r':
6650 repo_path = realpath(optarg, NULL);
6651 if (repo_path == NULL)
6652 return got_error_from_errno2("realpath",
6653 optarg);
6654 break;
6655 default:
6656 usage_blame();
6657 /* NOTREACHED */
6661 argc -= optind;
6662 argv += optind;
6664 if (argc != 1)
6665 usage_blame();
6667 error = got_repo_pack_fds_open(&pack_fds);
6668 if (error != NULL)
6669 goto done;
6671 if (repo_path == NULL) {
6672 cwd = getcwd(NULL, 0);
6673 if (cwd == NULL)
6674 return got_error_from_errno("getcwd");
6675 error = got_worktree_open(&worktree, cwd);
6676 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6677 goto done;
6678 if (worktree)
6679 repo_path =
6680 strdup(got_worktree_get_repo_path(worktree));
6681 else
6682 repo_path = strdup(cwd);
6683 if (repo_path == NULL) {
6684 error = got_error_from_errno("strdup");
6685 goto done;
6689 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6690 if (error != NULL)
6691 goto done;
6693 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6694 worktree);
6695 if (error)
6696 goto done;
6698 init_curses();
6700 error = apply_unveil(got_repo_get_path(repo), NULL);
6701 if (error)
6702 goto done;
6704 error = tog_load_refs(repo, 0);
6705 if (error)
6706 goto done;
6708 if (commit_id_str == NULL) {
6709 struct got_reference *head_ref;
6710 error = got_ref_open(&head_ref, repo, worktree ?
6711 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6712 if (error != NULL)
6713 goto done;
6714 error = got_ref_resolve(&commit_id, repo, head_ref);
6715 got_ref_close(head_ref);
6716 } else {
6717 error = got_repo_match_object_id(&commit_id, NULL,
6718 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6720 if (error != NULL)
6721 goto done;
6723 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6724 if (view == NULL) {
6725 error = got_error_from_errno("view_open");
6726 goto done;
6729 error = got_object_open_as_commit(&commit, repo, commit_id);
6730 if (error)
6731 goto done;
6733 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6734 commit, repo);
6735 if (error)
6736 goto done;
6738 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6739 commit_id, repo);
6740 if (error)
6741 goto done;
6742 if (worktree) {
6743 /* Release work tree lock. */
6744 got_worktree_close(worktree);
6745 worktree = NULL;
6747 error = view_loop(view);
6748 done:
6749 free(repo_path);
6750 free(in_repo_path);
6751 free(link_target);
6752 free(cwd);
6753 free(commit_id);
6754 if (commit)
6755 got_object_commit_close(commit);
6756 if (worktree)
6757 got_worktree_close(worktree);
6758 if (repo) {
6759 const struct got_error *close_err = got_repo_close(repo);
6760 if (error == NULL)
6761 error = close_err;
6763 if (pack_fds) {
6764 const struct got_error *pack_err =
6765 got_repo_pack_fds_close(pack_fds);
6766 if (error == NULL)
6767 error = pack_err;
6769 tog_free_refs();
6770 return error;
6773 static const struct got_error *
6774 draw_tree_entries(struct tog_view *view, const char *parent_path)
6776 struct tog_tree_view_state *s = &view->state.tree;
6777 const struct got_error *err = NULL;
6778 struct got_tree_entry *te;
6779 wchar_t *wline;
6780 char *index = NULL;
6781 struct tog_color *tc;
6782 int width, n, nentries, i = 1;
6783 int limit = view->nlines;
6785 s->ndisplayed = 0;
6786 if (view_is_hsplit_top(view))
6787 --limit; /* border */
6789 werase(view->window);
6791 if (limit == 0)
6792 return NULL;
6794 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6795 0, 0);
6796 if (err)
6797 return err;
6798 if (view_needs_focus_indication(view))
6799 wstandout(view->window);
6800 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6801 if (tc)
6802 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6803 waddwstr(view->window, wline);
6804 free(wline);
6805 wline = NULL;
6806 while (width++ < view->ncols)
6807 waddch(view->window, ' ');
6808 if (tc)
6809 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6810 if (view_needs_focus_indication(view))
6811 wstandend(view->window);
6812 if (--limit <= 0)
6813 return NULL;
6815 i += s->selected;
6816 if (s->first_displayed_entry) {
6817 i += got_tree_entry_get_index(s->first_displayed_entry);
6818 if (s->tree != s->root)
6819 ++i; /* account for ".." entry */
6821 nentries = got_object_tree_get_nentries(s->tree);
6822 if (asprintf(&index, "[%d/%d] %s",
6823 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6824 return got_error_from_errno("asprintf");
6825 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6826 free(index);
6827 if (err)
6828 return err;
6829 waddwstr(view->window, wline);
6830 free(wline);
6831 wline = NULL;
6832 if (width < view->ncols - 1)
6833 waddch(view->window, '\n');
6834 if (--limit <= 0)
6835 return NULL;
6836 waddch(view->window, '\n');
6837 if (--limit <= 0)
6838 return NULL;
6840 if (s->first_displayed_entry == NULL) {
6841 te = got_object_tree_get_first_entry(s->tree);
6842 if (s->selected == 0) {
6843 if (view->focussed)
6844 wstandout(view->window);
6845 s->selected_entry = NULL;
6847 waddstr(view->window, " ..\n"); /* parent directory */
6848 if (s->selected == 0 && view->focussed)
6849 wstandend(view->window);
6850 s->ndisplayed++;
6851 if (--limit <= 0)
6852 return NULL;
6853 n = 1;
6854 } else {
6855 n = 0;
6856 te = s->first_displayed_entry;
6859 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6860 char *line = NULL, *id_str = NULL, *link_target = NULL;
6861 const char *modestr = "";
6862 mode_t mode;
6864 te = got_object_tree_get_entry(s->tree, i);
6865 mode = got_tree_entry_get_mode(te);
6867 if (s->show_ids) {
6868 err = got_object_id_str(&id_str,
6869 got_tree_entry_get_id(te));
6870 if (err)
6871 return got_error_from_errno(
6872 "got_object_id_str");
6874 if (got_object_tree_entry_is_submodule(te))
6875 modestr = "$";
6876 else if (S_ISLNK(mode)) {
6877 int i;
6879 err = got_tree_entry_get_symlink_target(&link_target,
6880 te, s->repo);
6881 if (err) {
6882 free(id_str);
6883 return err;
6885 for (i = 0; i < strlen(link_target); i++) {
6886 if (!isprint((unsigned char)link_target[i]))
6887 link_target[i] = '?';
6889 modestr = "@";
6891 else if (S_ISDIR(mode))
6892 modestr = "/";
6893 else if (mode & S_IXUSR)
6894 modestr = "*";
6895 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6896 got_tree_entry_get_name(te), modestr,
6897 link_target ? " -> ": "",
6898 link_target ? link_target : "") == -1) {
6899 free(id_str);
6900 free(link_target);
6901 return got_error_from_errno("asprintf");
6903 free(id_str);
6904 free(link_target);
6905 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6906 0, 0);
6907 if (err) {
6908 free(line);
6909 break;
6911 if (n == s->selected) {
6912 if (view->focussed)
6913 wstandout(view->window);
6914 s->selected_entry = te;
6916 tc = match_color(&s->colors, line);
6917 if (tc)
6918 wattr_on(view->window,
6919 COLOR_PAIR(tc->colorpair), NULL);
6920 waddwstr(view->window, wline);
6921 if (tc)
6922 wattr_off(view->window,
6923 COLOR_PAIR(tc->colorpair), NULL);
6924 if (width < view->ncols - 1)
6925 waddch(view->window, '\n');
6926 if (n == s->selected && view->focussed)
6927 wstandend(view->window);
6928 free(line);
6929 free(wline);
6930 wline = NULL;
6931 n++;
6932 s->ndisplayed++;
6933 s->last_displayed_entry = te;
6934 if (--limit <= 0)
6935 break;
6938 return err;
6941 static void
6942 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6944 struct got_tree_entry *te;
6945 int isroot = s->tree == s->root;
6946 int i = 0;
6948 if (s->first_displayed_entry == NULL)
6949 return;
6951 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6952 while (i++ < maxscroll) {
6953 if (te == NULL) {
6954 if (!isroot)
6955 s->first_displayed_entry = NULL;
6956 break;
6958 s->first_displayed_entry = te;
6959 te = got_tree_entry_get_prev(s->tree, te);
6963 static const struct got_error *
6964 tree_scroll_down(struct tog_view *view, int maxscroll)
6966 struct tog_tree_view_state *s = &view->state.tree;
6967 struct got_tree_entry *next, *last;
6968 int n = 0;
6970 if (s->first_displayed_entry)
6971 next = got_tree_entry_get_next(s->tree,
6972 s->first_displayed_entry);
6973 else
6974 next = got_object_tree_get_first_entry(s->tree);
6976 last = s->last_displayed_entry;
6977 while (next && n++ < maxscroll) {
6978 if (last) {
6979 s->last_displayed_entry = last;
6980 last = got_tree_entry_get_next(s->tree, last);
6982 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6983 s->first_displayed_entry = next;
6984 next = got_tree_entry_get_next(s->tree, next);
6988 return NULL;
6991 static const struct got_error *
6992 tree_entry_path(char **path, struct tog_parent_trees *parents,
6993 struct got_tree_entry *te)
6995 const struct got_error *err = NULL;
6996 struct tog_parent_tree *pt;
6997 size_t len = 2; /* for leading slash and NUL */
6999 TAILQ_FOREACH(pt, parents, entry)
7000 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7001 + 1 /* slash */;
7002 if (te)
7003 len += strlen(got_tree_entry_get_name(te));
7005 *path = calloc(1, len);
7006 if (path == NULL)
7007 return got_error_from_errno("calloc");
7009 (*path)[0] = '/';
7010 pt = TAILQ_LAST(parents, tog_parent_trees);
7011 while (pt) {
7012 const char *name = got_tree_entry_get_name(pt->selected_entry);
7013 if (strlcat(*path, name, len) >= len) {
7014 err = got_error(GOT_ERR_NO_SPACE);
7015 goto done;
7017 if (strlcat(*path, "/", len) >= len) {
7018 err = got_error(GOT_ERR_NO_SPACE);
7019 goto done;
7021 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7023 if (te) {
7024 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7025 err = got_error(GOT_ERR_NO_SPACE);
7026 goto done;
7029 done:
7030 if (err) {
7031 free(*path);
7032 *path = NULL;
7034 return err;
7037 static const struct got_error *
7038 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7039 struct got_tree_entry *te, struct tog_parent_trees *parents,
7040 struct got_object_id *commit_id, struct got_repository *repo)
7042 const struct got_error *err = NULL;
7043 char *path;
7044 struct tog_view *blame_view;
7046 *new_view = NULL;
7048 err = tree_entry_path(&path, parents, te);
7049 if (err)
7050 return err;
7052 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7053 if (blame_view == NULL) {
7054 err = got_error_from_errno("view_open");
7055 goto done;
7058 err = open_blame_view(blame_view, path, commit_id, repo);
7059 if (err) {
7060 if (err->code == GOT_ERR_CANCELLED)
7061 err = NULL;
7062 view_close(blame_view);
7063 } else
7064 *new_view = blame_view;
7065 done:
7066 free(path);
7067 return err;
7070 static const struct got_error *
7071 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7072 struct tog_tree_view_state *s)
7074 struct tog_view *log_view;
7075 const struct got_error *err = NULL;
7076 char *path;
7078 *new_view = NULL;
7080 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7081 if (log_view == NULL)
7082 return got_error_from_errno("view_open");
7084 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7085 if (err)
7086 return err;
7088 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7089 path, 0);
7090 if (err)
7091 view_close(log_view);
7092 else
7093 *new_view = log_view;
7094 free(path);
7095 return err;
7098 static const struct got_error *
7099 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7100 const char *head_ref_name, struct got_repository *repo)
7102 const struct got_error *err = NULL;
7103 char *commit_id_str = NULL;
7104 struct tog_tree_view_state *s = &view->state.tree;
7105 struct got_commit_object *commit = NULL;
7107 TAILQ_INIT(&s->parents);
7108 STAILQ_INIT(&s->colors);
7110 s->commit_id = got_object_id_dup(commit_id);
7111 if (s->commit_id == NULL)
7112 return got_error_from_errno("got_object_id_dup");
7114 err = got_object_open_as_commit(&commit, repo, commit_id);
7115 if (err)
7116 goto done;
7119 * The root is opened here and will be closed when the view is closed.
7120 * Any visited subtrees and their path-wise parents are opened and
7121 * closed on demand.
7123 err = got_object_open_as_tree(&s->root, repo,
7124 got_object_commit_get_tree_id(commit));
7125 if (err)
7126 goto done;
7127 s->tree = s->root;
7129 err = got_object_id_str(&commit_id_str, commit_id);
7130 if (err != NULL)
7131 goto done;
7133 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7134 err = got_error_from_errno("asprintf");
7135 goto done;
7138 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7139 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7140 if (head_ref_name) {
7141 s->head_ref_name = strdup(head_ref_name);
7142 if (s->head_ref_name == NULL) {
7143 err = got_error_from_errno("strdup");
7144 goto done;
7147 s->repo = repo;
7149 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7150 err = add_color(&s->colors, "\\$$",
7151 TOG_COLOR_TREE_SUBMODULE,
7152 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7153 if (err)
7154 goto done;
7155 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7156 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7157 if (err)
7158 goto done;
7159 err = add_color(&s->colors, "/$",
7160 TOG_COLOR_TREE_DIRECTORY,
7161 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7162 if (err)
7163 goto done;
7165 err = add_color(&s->colors, "\\*$",
7166 TOG_COLOR_TREE_EXECUTABLE,
7167 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7168 if (err)
7169 goto done;
7171 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7172 get_color_value("TOG_COLOR_COMMIT"));
7173 if (err)
7174 goto done;
7177 view->show = show_tree_view;
7178 view->input = input_tree_view;
7179 view->close = close_tree_view;
7180 view->search_start = search_start_tree_view;
7181 view->search_next = search_next_tree_view;
7182 done:
7183 free(commit_id_str);
7184 if (commit)
7185 got_object_commit_close(commit);
7186 if (err)
7187 close_tree_view(view);
7188 return err;
7191 static const struct got_error *
7192 close_tree_view(struct tog_view *view)
7194 struct tog_tree_view_state *s = &view->state.tree;
7196 free_colors(&s->colors);
7197 free(s->tree_label);
7198 s->tree_label = NULL;
7199 free(s->commit_id);
7200 s->commit_id = NULL;
7201 free(s->head_ref_name);
7202 s->head_ref_name = NULL;
7203 while (!TAILQ_EMPTY(&s->parents)) {
7204 struct tog_parent_tree *parent;
7205 parent = TAILQ_FIRST(&s->parents);
7206 TAILQ_REMOVE(&s->parents, parent, entry);
7207 if (parent->tree != s->root)
7208 got_object_tree_close(parent->tree);
7209 free(parent);
7212 if (s->tree != NULL && s->tree != s->root)
7213 got_object_tree_close(s->tree);
7214 if (s->root)
7215 got_object_tree_close(s->root);
7216 return NULL;
7219 static const struct got_error *
7220 search_start_tree_view(struct tog_view *view)
7222 struct tog_tree_view_state *s = &view->state.tree;
7224 s->matched_entry = NULL;
7225 return NULL;
7228 static int
7229 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7231 regmatch_t regmatch;
7233 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7234 0) == 0;
7237 static const struct got_error *
7238 search_next_tree_view(struct tog_view *view)
7240 struct tog_tree_view_state *s = &view->state.tree;
7241 struct got_tree_entry *te = NULL;
7243 if (!view->searching) {
7244 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7245 return NULL;
7248 if (s->matched_entry) {
7249 if (view->searching == TOG_SEARCH_FORWARD) {
7250 if (s->selected_entry)
7251 te = got_tree_entry_get_next(s->tree,
7252 s->selected_entry);
7253 else
7254 te = got_object_tree_get_first_entry(s->tree);
7255 } else {
7256 if (s->selected_entry == NULL)
7257 te = got_object_tree_get_last_entry(s->tree);
7258 else
7259 te = got_tree_entry_get_prev(s->tree,
7260 s->selected_entry);
7262 } else {
7263 if (s->selected_entry)
7264 te = s->selected_entry;
7265 else if (view->searching == TOG_SEARCH_FORWARD)
7266 te = got_object_tree_get_first_entry(s->tree);
7267 else
7268 te = got_object_tree_get_last_entry(s->tree);
7271 while (1) {
7272 if (te == NULL) {
7273 if (s->matched_entry == NULL) {
7274 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7275 return NULL;
7277 if (view->searching == TOG_SEARCH_FORWARD)
7278 te = got_object_tree_get_first_entry(s->tree);
7279 else
7280 te = got_object_tree_get_last_entry(s->tree);
7283 if (match_tree_entry(te, &view->regex)) {
7284 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7285 s->matched_entry = te;
7286 break;
7289 if (view->searching == TOG_SEARCH_FORWARD)
7290 te = got_tree_entry_get_next(s->tree, te);
7291 else
7292 te = got_tree_entry_get_prev(s->tree, te);
7295 if (s->matched_entry) {
7296 s->first_displayed_entry = s->matched_entry;
7297 s->selected = 0;
7300 return NULL;
7303 static const struct got_error *
7304 show_tree_view(struct tog_view *view)
7306 const struct got_error *err = NULL;
7307 struct tog_tree_view_state *s = &view->state.tree;
7308 char *parent_path;
7310 err = tree_entry_path(&parent_path, &s->parents, NULL);
7311 if (err)
7312 return err;
7314 err = draw_tree_entries(view, parent_path);
7315 free(parent_path);
7317 view_border(view);
7318 return err;
7321 static const struct got_error *
7322 tree_goto_line(struct tog_view *view, int nlines)
7324 const struct got_error *err = NULL;
7325 struct tog_tree_view_state *s = &view->state.tree;
7326 struct got_tree_entry **fte, **lte, **ste;
7327 int g, last, first = 1, i = 1;
7328 int root = s->tree == s->root;
7329 int off = root ? 1 : 2;
7331 g = view->gline;
7332 view->gline = 0;
7334 if (g == 0)
7335 g = 1;
7336 else if (g > got_object_tree_get_nentries(s->tree))
7337 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7339 fte = &s->first_displayed_entry;
7340 lte = &s->last_displayed_entry;
7341 ste = &s->selected_entry;
7343 if (*fte != NULL) {
7344 first = got_tree_entry_get_index(*fte);
7345 first += off; /* account for ".." */
7347 last = got_tree_entry_get_index(*lte);
7348 last += off;
7350 if (g >= first && g <= last && g - first < nlines) {
7351 s->selected = g - first;
7352 return NULL; /* gline is on the current page */
7355 if (*ste != NULL) {
7356 i = got_tree_entry_get_index(*ste);
7357 i += off;
7360 if (i < g) {
7361 err = tree_scroll_down(view, g - i);
7362 if (err)
7363 return err;
7364 if (got_tree_entry_get_index(*lte) >=
7365 got_object_tree_get_nentries(s->tree) - 1 &&
7366 first + s->selected < g &&
7367 s->selected < s->ndisplayed - 1) {
7368 first = got_tree_entry_get_index(*fte);
7369 first += off;
7370 s->selected = g - first;
7372 } else if (i > g)
7373 tree_scroll_up(s, i - g);
7375 if (g < nlines &&
7376 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7377 s->selected = g - 1;
7379 return NULL;
7382 static const struct got_error *
7383 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7385 const struct got_error *err = NULL;
7386 struct tog_tree_view_state *s = &view->state.tree;
7387 struct got_tree_entry *te;
7388 int n, nscroll = view->nlines - 3;
7390 if (view->gline)
7391 return tree_goto_line(view, nscroll);
7393 switch (ch) {
7394 case 'i':
7395 s->show_ids = !s->show_ids;
7396 view->count = 0;
7397 break;
7398 case 'L':
7399 view->count = 0;
7400 if (!s->selected_entry)
7401 break;
7402 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7403 break;
7404 case 'R':
7405 view->count = 0;
7406 err = view_request_new(new_view, view, TOG_VIEW_REF);
7407 break;
7408 case 'g':
7409 case '=':
7410 case KEY_HOME:
7411 s->selected = 0;
7412 view->count = 0;
7413 if (s->tree == s->root)
7414 s->first_displayed_entry =
7415 got_object_tree_get_first_entry(s->tree);
7416 else
7417 s->first_displayed_entry = NULL;
7418 break;
7419 case 'G':
7420 case '*':
7421 case KEY_END: {
7422 int eos = view->nlines - 3;
7424 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7425 --eos; /* border */
7426 s->selected = 0;
7427 view->count = 0;
7428 te = got_object_tree_get_last_entry(s->tree);
7429 for (n = 0; n < eos; n++) {
7430 if (te == NULL) {
7431 if (s->tree != s->root) {
7432 s->first_displayed_entry = NULL;
7433 n++;
7435 break;
7437 s->first_displayed_entry = te;
7438 te = got_tree_entry_get_prev(s->tree, te);
7440 if (n > 0)
7441 s->selected = n - 1;
7442 break;
7444 case 'k':
7445 case KEY_UP:
7446 case CTRL('p'):
7447 if (s->selected > 0) {
7448 s->selected--;
7449 break;
7451 tree_scroll_up(s, 1);
7452 if (s->selected_entry == NULL ||
7453 (s->tree == s->root && s->selected_entry ==
7454 got_object_tree_get_first_entry(s->tree)))
7455 view->count = 0;
7456 break;
7457 case CTRL('u'):
7458 case 'u':
7459 nscroll /= 2;
7460 /* FALL THROUGH */
7461 case KEY_PPAGE:
7462 case CTRL('b'):
7463 case 'b':
7464 if (s->tree == s->root) {
7465 if (got_object_tree_get_first_entry(s->tree) ==
7466 s->first_displayed_entry)
7467 s->selected -= MIN(s->selected, nscroll);
7468 } else {
7469 if (s->first_displayed_entry == NULL)
7470 s->selected -= MIN(s->selected, nscroll);
7472 tree_scroll_up(s, MAX(0, nscroll));
7473 if (s->selected_entry == NULL ||
7474 (s->tree == s->root && s->selected_entry ==
7475 got_object_tree_get_first_entry(s->tree)))
7476 view->count = 0;
7477 break;
7478 case 'j':
7479 case KEY_DOWN:
7480 case CTRL('n'):
7481 if (s->selected < s->ndisplayed - 1) {
7482 s->selected++;
7483 break;
7485 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7486 == NULL) {
7487 /* can't scroll any further */
7488 view->count = 0;
7489 break;
7491 tree_scroll_down(view, 1);
7492 break;
7493 case CTRL('d'):
7494 case 'd':
7495 nscroll /= 2;
7496 /* FALL THROUGH */
7497 case KEY_NPAGE:
7498 case CTRL('f'):
7499 case 'f':
7500 case ' ':
7501 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7502 == NULL) {
7503 /* can't scroll any further; move cursor down */
7504 if (s->selected < s->ndisplayed - 1)
7505 s->selected += MIN(nscroll,
7506 s->ndisplayed - s->selected - 1);
7507 else
7508 view->count = 0;
7509 break;
7511 tree_scroll_down(view, nscroll);
7512 break;
7513 case KEY_ENTER:
7514 case '\r':
7515 case KEY_BACKSPACE:
7516 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7517 struct tog_parent_tree *parent;
7518 /* user selected '..' */
7519 if (s->tree == s->root) {
7520 view->count = 0;
7521 break;
7523 parent = TAILQ_FIRST(&s->parents);
7524 TAILQ_REMOVE(&s->parents, parent,
7525 entry);
7526 got_object_tree_close(s->tree);
7527 s->tree = parent->tree;
7528 s->first_displayed_entry =
7529 parent->first_displayed_entry;
7530 s->selected_entry =
7531 parent->selected_entry;
7532 s->selected = parent->selected;
7533 if (s->selected > view->nlines - 3) {
7534 err = offset_selection_down(view);
7535 if (err)
7536 break;
7538 free(parent);
7539 } else if (S_ISDIR(got_tree_entry_get_mode(
7540 s->selected_entry))) {
7541 struct got_tree_object *subtree;
7542 view->count = 0;
7543 err = got_object_open_as_tree(&subtree, s->repo,
7544 got_tree_entry_get_id(s->selected_entry));
7545 if (err)
7546 break;
7547 err = tree_view_visit_subtree(s, subtree);
7548 if (err) {
7549 got_object_tree_close(subtree);
7550 break;
7552 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7553 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7554 break;
7555 case KEY_RESIZE:
7556 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7557 s->selected = view->nlines - 4;
7558 view->count = 0;
7559 break;
7560 default:
7561 view->count = 0;
7562 break;
7565 return err;
7568 __dead static void
7569 usage_tree(void)
7571 endwin();
7572 fprintf(stderr,
7573 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7574 getprogname());
7575 exit(1);
7578 static const struct got_error *
7579 cmd_tree(int argc, char *argv[])
7581 const struct got_error *error;
7582 struct got_repository *repo = NULL;
7583 struct got_worktree *worktree = NULL;
7584 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7585 struct got_object_id *commit_id = NULL;
7586 struct got_commit_object *commit = NULL;
7587 const char *commit_id_arg = NULL;
7588 char *label = NULL;
7589 struct got_reference *ref = NULL;
7590 const char *head_ref_name = NULL;
7591 int ch;
7592 struct tog_view *view;
7593 int *pack_fds = NULL;
7595 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7596 switch (ch) {
7597 case 'c':
7598 commit_id_arg = optarg;
7599 break;
7600 case 'r':
7601 repo_path = realpath(optarg, NULL);
7602 if (repo_path == NULL)
7603 return got_error_from_errno2("realpath",
7604 optarg);
7605 break;
7606 default:
7607 usage_tree();
7608 /* NOTREACHED */
7612 argc -= optind;
7613 argv += optind;
7615 if (argc > 1)
7616 usage_tree();
7618 error = got_repo_pack_fds_open(&pack_fds);
7619 if (error != NULL)
7620 goto done;
7622 if (repo_path == NULL) {
7623 cwd = getcwd(NULL, 0);
7624 if (cwd == NULL)
7625 return got_error_from_errno("getcwd");
7626 error = got_worktree_open(&worktree, cwd);
7627 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7628 goto done;
7629 if (worktree)
7630 repo_path =
7631 strdup(got_worktree_get_repo_path(worktree));
7632 else
7633 repo_path = strdup(cwd);
7634 if (repo_path == NULL) {
7635 error = got_error_from_errno("strdup");
7636 goto done;
7640 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7641 if (error != NULL)
7642 goto done;
7644 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7645 repo, worktree);
7646 if (error)
7647 goto done;
7649 init_curses();
7651 error = apply_unveil(got_repo_get_path(repo), NULL);
7652 if (error)
7653 goto done;
7655 error = tog_load_refs(repo, 0);
7656 if (error)
7657 goto done;
7659 if (commit_id_arg == NULL) {
7660 error = got_repo_match_object_id(&commit_id, &label,
7661 worktree ? got_worktree_get_head_ref_name(worktree) :
7662 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7663 if (error)
7664 goto done;
7665 head_ref_name = label;
7666 } else {
7667 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7668 if (error == NULL)
7669 head_ref_name = got_ref_get_name(ref);
7670 else if (error->code != GOT_ERR_NOT_REF)
7671 goto done;
7672 error = got_repo_match_object_id(&commit_id, NULL,
7673 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7674 if (error)
7675 goto done;
7678 error = got_object_open_as_commit(&commit, repo, commit_id);
7679 if (error)
7680 goto done;
7682 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7683 if (view == NULL) {
7684 error = got_error_from_errno("view_open");
7685 goto done;
7687 error = open_tree_view(view, commit_id, head_ref_name, repo);
7688 if (error)
7689 goto done;
7690 if (!got_path_is_root_dir(in_repo_path)) {
7691 error = tree_view_walk_path(&view->state.tree, commit,
7692 in_repo_path);
7693 if (error)
7694 goto done;
7697 if (worktree) {
7698 /* Release work tree lock. */
7699 got_worktree_close(worktree);
7700 worktree = NULL;
7702 error = view_loop(view);
7703 done:
7704 free(repo_path);
7705 free(cwd);
7706 free(commit_id);
7707 free(label);
7708 if (ref)
7709 got_ref_close(ref);
7710 if (repo) {
7711 const struct got_error *close_err = got_repo_close(repo);
7712 if (error == NULL)
7713 error = close_err;
7715 if (pack_fds) {
7716 const struct got_error *pack_err =
7717 got_repo_pack_fds_close(pack_fds);
7718 if (error == NULL)
7719 error = pack_err;
7721 tog_free_refs();
7722 return error;
7725 static const struct got_error *
7726 ref_view_load_refs(struct tog_ref_view_state *s)
7728 struct got_reflist_entry *sre;
7729 struct tog_reflist_entry *re;
7731 s->nrefs = 0;
7732 TAILQ_FOREACH(sre, &tog_refs, entry) {
7733 if (strncmp(got_ref_get_name(sre->ref),
7734 "refs/got/", 9) == 0 &&
7735 strncmp(got_ref_get_name(sre->ref),
7736 "refs/got/backup/", 16) != 0)
7737 continue;
7739 re = malloc(sizeof(*re));
7740 if (re == NULL)
7741 return got_error_from_errno("malloc");
7743 re->ref = got_ref_dup(sre->ref);
7744 if (re->ref == NULL)
7745 return got_error_from_errno("got_ref_dup");
7746 re->idx = s->nrefs++;
7747 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7750 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7751 return NULL;
7754 static void
7755 ref_view_free_refs(struct tog_ref_view_state *s)
7757 struct tog_reflist_entry *re;
7759 while (!TAILQ_EMPTY(&s->refs)) {
7760 re = TAILQ_FIRST(&s->refs);
7761 TAILQ_REMOVE(&s->refs, re, entry);
7762 got_ref_close(re->ref);
7763 free(re);
7767 static const struct got_error *
7768 open_ref_view(struct tog_view *view, struct got_repository *repo)
7770 const struct got_error *err = NULL;
7771 struct tog_ref_view_state *s = &view->state.ref;
7773 s->selected_entry = 0;
7774 s->repo = repo;
7776 TAILQ_INIT(&s->refs);
7777 STAILQ_INIT(&s->colors);
7779 err = ref_view_load_refs(s);
7780 if (err)
7781 return err;
7783 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7784 err = add_color(&s->colors, "^refs/heads/",
7785 TOG_COLOR_REFS_HEADS,
7786 get_color_value("TOG_COLOR_REFS_HEADS"));
7787 if (err)
7788 goto done;
7790 err = add_color(&s->colors, "^refs/tags/",
7791 TOG_COLOR_REFS_TAGS,
7792 get_color_value("TOG_COLOR_REFS_TAGS"));
7793 if (err)
7794 goto done;
7796 err = add_color(&s->colors, "^refs/remotes/",
7797 TOG_COLOR_REFS_REMOTES,
7798 get_color_value("TOG_COLOR_REFS_REMOTES"));
7799 if (err)
7800 goto done;
7802 err = add_color(&s->colors, "^refs/got/backup/",
7803 TOG_COLOR_REFS_BACKUP,
7804 get_color_value("TOG_COLOR_REFS_BACKUP"));
7805 if (err)
7806 goto done;
7809 view->show = show_ref_view;
7810 view->input = input_ref_view;
7811 view->close = close_ref_view;
7812 view->search_start = search_start_ref_view;
7813 view->search_next = search_next_ref_view;
7814 done:
7815 if (err)
7816 free_colors(&s->colors);
7817 return err;
7820 static const struct got_error *
7821 close_ref_view(struct tog_view *view)
7823 struct tog_ref_view_state *s = &view->state.ref;
7825 ref_view_free_refs(s);
7826 free_colors(&s->colors);
7828 return NULL;
7831 static const struct got_error *
7832 resolve_reflist_entry(struct got_object_id **commit_id,
7833 struct tog_reflist_entry *re, struct got_repository *repo)
7835 const struct got_error *err = NULL;
7836 struct got_object_id *obj_id;
7837 struct got_tag_object *tag = NULL;
7838 int obj_type;
7840 *commit_id = NULL;
7842 err = got_ref_resolve(&obj_id, repo, re->ref);
7843 if (err)
7844 return err;
7846 err = got_object_get_type(&obj_type, repo, obj_id);
7847 if (err)
7848 goto done;
7850 switch (obj_type) {
7851 case GOT_OBJ_TYPE_COMMIT:
7852 *commit_id = obj_id;
7853 break;
7854 case GOT_OBJ_TYPE_TAG:
7855 err = got_object_open_as_tag(&tag, repo, obj_id);
7856 if (err)
7857 goto done;
7858 free(obj_id);
7859 err = got_object_get_type(&obj_type, repo,
7860 got_object_tag_get_object_id(tag));
7861 if (err)
7862 goto done;
7863 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7864 err = got_error(GOT_ERR_OBJ_TYPE);
7865 goto done;
7867 *commit_id = got_object_id_dup(
7868 got_object_tag_get_object_id(tag));
7869 if (*commit_id == NULL) {
7870 err = got_error_from_errno("got_object_id_dup");
7871 goto done;
7873 break;
7874 default:
7875 err = got_error(GOT_ERR_OBJ_TYPE);
7876 break;
7879 done:
7880 if (tag)
7881 got_object_tag_close(tag);
7882 if (err) {
7883 free(*commit_id);
7884 *commit_id = NULL;
7886 return err;
7889 static const struct got_error *
7890 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7891 struct tog_reflist_entry *re, struct got_repository *repo)
7893 struct tog_view *log_view;
7894 const struct got_error *err = NULL;
7895 struct got_object_id *commit_id = NULL;
7897 *new_view = NULL;
7899 err = resolve_reflist_entry(&commit_id, re, repo);
7900 if (err) {
7901 if (err->code != GOT_ERR_OBJ_TYPE)
7902 return err;
7903 else
7904 return NULL;
7907 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7908 if (log_view == NULL) {
7909 err = got_error_from_errno("view_open");
7910 goto done;
7913 err = open_log_view(log_view, commit_id, repo,
7914 got_ref_get_name(re->ref), "", 0);
7915 done:
7916 if (err)
7917 view_close(log_view);
7918 else
7919 *new_view = log_view;
7920 free(commit_id);
7921 return err;
7924 static void
7925 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7927 struct tog_reflist_entry *re;
7928 int i = 0;
7930 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7931 return;
7933 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7934 while (i++ < maxscroll) {
7935 if (re == NULL)
7936 break;
7937 s->first_displayed_entry = re;
7938 re = TAILQ_PREV(re, tog_reflist_head, entry);
7942 static const struct got_error *
7943 ref_scroll_down(struct tog_view *view, int maxscroll)
7945 struct tog_ref_view_state *s = &view->state.ref;
7946 struct tog_reflist_entry *next, *last;
7947 int n = 0;
7949 if (s->first_displayed_entry)
7950 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7951 else
7952 next = TAILQ_FIRST(&s->refs);
7954 last = s->last_displayed_entry;
7955 while (next && n++ < maxscroll) {
7956 if (last) {
7957 s->last_displayed_entry = last;
7958 last = TAILQ_NEXT(last, entry);
7960 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7961 s->first_displayed_entry = next;
7962 next = TAILQ_NEXT(next, entry);
7966 return NULL;
7969 static const struct got_error *
7970 search_start_ref_view(struct tog_view *view)
7972 struct tog_ref_view_state *s = &view->state.ref;
7974 s->matched_entry = NULL;
7975 return NULL;
7978 static int
7979 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7981 regmatch_t regmatch;
7983 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7984 0) == 0;
7987 static const struct got_error *
7988 search_next_ref_view(struct tog_view *view)
7990 struct tog_ref_view_state *s = &view->state.ref;
7991 struct tog_reflist_entry *re = NULL;
7993 if (!view->searching) {
7994 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7995 return NULL;
7998 if (s->matched_entry) {
7999 if (view->searching == TOG_SEARCH_FORWARD) {
8000 if (s->selected_entry)
8001 re = TAILQ_NEXT(s->selected_entry, entry);
8002 else
8003 re = TAILQ_PREV(s->selected_entry,
8004 tog_reflist_head, entry);
8005 } else {
8006 if (s->selected_entry == NULL)
8007 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8008 else
8009 re = TAILQ_PREV(s->selected_entry,
8010 tog_reflist_head, entry);
8012 } else {
8013 if (s->selected_entry)
8014 re = s->selected_entry;
8015 else if (view->searching == TOG_SEARCH_FORWARD)
8016 re = TAILQ_FIRST(&s->refs);
8017 else
8018 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8021 while (1) {
8022 if (re == NULL) {
8023 if (s->matched_entry == NULL) {
8024 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8025 return NULL;
8027 if (view->searching == TOG_SEARCH_FORWARD)
8028 re = TAILQ_FIRST(&s->refs);
8029 else
8030 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8033 if (match_reflist_entry(re, &view->regex)) {
8034 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8035 s->matched_entry = re;
8036 break;
8039 if (view->searching == TOG_SEARCH_FORWARD)
8040 re = TAILQ_NEXT(re, entry);
8041 else
8042 re = TAILQ_PREV(re, tog_reflist_head, entry);
8045 if (s->matched_entry) {
8046 s->first_displayed_entry = s->matched_entry;
8047 s->selected = 0;
8050 return NULL;
8053 static const struct got_error *
8054 show_ref_view(struct tog_view *view)
8056 const struct got_error *err = NULL;
8057 struct tog_ref_view_state *s = &view->state.ref;
8058 struct tog_reflist_entry *re;
8059 char *line = NULL;
8060 wchar_t *wline;
8061 struct tog_color *tc;
8062 int width, n;
8063 int limit = view->nlines;
8065 werase(view->window);
8067 s->ndisplayed = 0;
8068 if (view_is_hsplit_top(view))
8069 --limit; /* border */
8071 if (limit == 0)
8072 return NULL;
8074 re = s->first_displayed_entry;
8076 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8077 s->nrefs) == -1)
8078 return got_error_from_errno("asprintf");
8080 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8081 if (err) {
8082 free(line);
8083 return err;
8085 if (view_needs_focus_indication(view))
8086 wstandout(view->window);
8087 waddwstr(view->window, wline);
8088 while (width++ < view->ncols)
8089 waddch(view->window, ' ');
8090 if (view_needs_focus_indication(view))
8091 wstandend(view->window);
8092 free(wline);
8093 wline = NULL;
8094 free(line);
8095 line = NULL;
8096 if (--limit <= 0)
8097 return NULL;
8099 n = 0;
8100 while (re && limit > 0) {
8101 char *line = NULL;
8102 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8104 if (s->show_date) {
8105 struct got_commit_object *ci;
8106 struct got_tag_object *tag;
8107 struct got_object_id *id;
8108 struct tm tm;
8109 time_t t;
8111 err = got_ref_resolve(&id, s->repo, re->ref);
8112 if (err)
8113 return err;
8114 err = got_object_open_as_tag(&tag, s->repo, id);
8115 if (err) {
8116 if (err->code != GOT_ERR_OBJ_TYPE) {
8117 free(id);
8118 return err;
8120 err = got_object_open_as_commit(&ci, s->repo,
8121 id);
8122 if (err) {
8123 free(id);
8124 return err;
8126 t = got_object_commit_get_committer_time(ci);
8127 got_object_commit_close(ci);
8128 } else {
8129 t = got_object_tag_get_tagger_time(tag);
8130 got_object_tag_close(tag);
8132 free(id);
8133 if (gmtime_r(&t, &tm) == NULL)
8134 return got_error_from_errno("gmtime_r");
8135 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8136 return got_error(GOT_ERR_NO_SPACE);
8138 if (got_ref_is_symbolic(re->ref)) {
8139 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8140 ymd : "", got_ref_get_name(re->ref),
8141 got_ref_get_symref_target(re->ref)) == -1)
8142 return got_error_from_errno("asprintf");
8143 } else if (s->show_ids) {
8144 struct got_object_id *id;
8145 char *id_str;
8146 err = got_ref_resolve(&id, s->repo, re->ref);
8147 if (err)
8148 return err;
8149 err = got_object_id_str(&id_str, id);
8150 if (err) {
8151 free(id);
8152 return err;
8154 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8155 got_ref_get_name(re->ref), id_str) == -1) {
8156 err = got_error_from_errno("asprintf");
8157 free(id);
8158 free(id_str);
8159 return err;
8161 free(id);
8162 free(id_str);
8163 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8164 got_ref_get_name(re->ref)) == -1)
8165 return got_error_from_errno("asprintf");
8167 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
8168 0, 0);
8169 if (err) {
8170 free(line);
8171 return err;
8173 if (n == s->selected) {
8174 if (view->focussed)
8175 wstandout(view->window);
8176 s->selected_entry = re;
8178 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8179 if (tc)
8180 wattr_on(view->window,
8181 COLOR_PAIR(tc->colorpair), NULL);
8182 waddwstr(view->window, wline);
8183 if (tc)
8184 wattr_off(view->window,
8185 COLOR_PAIR(tc->colorpair), NULL);
8186 if (width < view->ncols - 1)
8187 waddch(view->window, '\n');
8188 if (n == s->selected && view->focussed)
8189 wstandend(view->window);
8190 free(line);
8191 free(wline);
8192 wline = NULL;
8193 n++;
8194 s->ndisplayed++;
8195 s->last_displayed_entry = re;
8197 limit--;
8198 re = TAILQ_NEXT(re, entry);
8201 view_border(view);
8202 return err;
8205 static const struct got_error *
8206 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8207 struct tog_reflist_entry *re, struct got_repository *repo)
8209 const struct got_error *err = NULL;
8210 struct got_object_id *commit_id = NULL;
8211 struct tog_view *tree_view;
8213 *new_view = NULL;
8215 err = resolve_reflist_entry(&commit_id, re, repo);
8216 if (err) {
8217 if (err->code != GOT_ERR_OBJ_TYPE)
8218 return err;
8219 else
8220 return NULL;
8224 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8225 if (tree_view == NULL) {
8226 err = got_error_from_errno("view_open");
8227 goto done;
8230 err = open_tree_view(tree_view, commit_id,
8231 got_ref_get_name(re->ref), repo);
8232 if (err)
8233 goto done;
8235 *new_view = tree_view;
8236 done:
8237 free(commit_id);
8238 return err;
8241 static const struct got_error *
8242 ref_goto_line(struct tog_view *view, int nlines)
8244 const struct got_error *err = NULL;
8245 struct tog_ref_view_state *s = &view->state.ref;
8246 int g, idx = s->selected_entry->idx;
8248 g = view->gline;
8249 view->gline = 0;
8251 if (g == 0)
8252 g = 1;
8253 else if (g > s->nrefs)
8254 g = s->nrefs;
8256 if (g >= s->first_displayed_entry->idx + 1 &&
8257 g <= s->last_displayed_entry->idx + 1 &&
8258 g - s->first_displayed_entry->idx - 1 < nlines) {
8259 s->selected = g - s->first_displayed_entry->idx - 1;
8260 return NULL;
8263 if (idx + 1 < g) {
8264 err = ref_scroll_down(view, g - idx - 1);
8265 if (err)
8266 return err;
8267 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8268 s->first_displayed_entry->idx + s->selected < g &&
8269 s->selected < s->ndisplayed - 1)
8270 s->selected = g - s->first_displayed_entry->idx - 1;
8271 } else if (idx + 1 > g)
8272 ref_scroll_up(s, idx - g + 1);
8274 if (g < nlines && s->first_displayed_entry->idx == 0)
8275 s->selected = g - 1;
8277 return NULL;
8281 static const struct got_error *
8282 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8284 const struct got_error *err = NULL;
8285 struct tog_ref_view_state *s = &view->state.ref;
8286 struct tog_reflist_entry *re;
8287 int n, nscroll = view->nlines - 1;
8289 if (view->gline)
8290 return ref_goto_line(view, nscroll);
8292 switch (ch) {
8293 case 'i':
8294 s->show_ids = !s->show_ids;
8295 view->count = 0;
8296 break;
8297 case 'm':
8298 s->show_date = !s->show_date;
8299 view->count = 0;
8300 break;
8301 case 'o':
8302 s->sort_by_date = !s->sort_by_date;
8303 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8304 view->count = 0;
8305 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8306 got_ref_cmp_by_commit_timestamp_descending :
8307 tog_ref_cmp_by_name, s->repo);
8308 if (err)
8309 break;
8310 got_reflist_object_id_map_free(tog_refs_idmap);
8311 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8312 &tog_refs, s->repo);
8313 if (err)
8314 break;
8315 ref_view_free_refs(s);
8316 err = ref_view_load_refs(s);
8317 break;
8318 case KEY_ENTER:
8319 case '\r':
8320 view->count = 0;
8321 if (!s->selected_entry)
8322 break;
8323 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8324 break;
8325 case 'T':
8326 view->count = 0;
8327 if (!s->selected_entry)
8328 break;
8329 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8330 break;
8331 case 'g':
8332 case '=':
8333 case KEY_HOME:
8334 s->selected = 0;
8335 view->count = 0;
8336 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8337 break;
8338 case 'G':
8339 case '*':
8340 case KEY_END: {
8341 int eos = view->nlines - 1;
8343 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8344 --eos; /* border */
8345 s->selected = 0;
8346 view->count = 0;
8347 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8348 for (n = 0; n < eos; n++) {
8349 if (re == NULL)
8350 break;
8351 s->first_displayed_entry = re;
8352 re = TAILQ_PREV(re, tog_reflist_head, entry);
8354 if (n > 0)
8355 s->selected = n - 1;
8356 break;
8358 case 'k':
8359 case KEY_UP:
8360 case CTRL('p'):
8361 if (s->selected > 0) {
8362 s->selected--;
8363 break;
8365 ref_scroll_up(s, 1);
8366 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8367 view->count = 0;
8368 break;
8369 case CTRL('u'):
8370 case 'u':
8371 nscroll /= 2;
8372 /* FALL THROUGH */
8373 case KEY_PPAGE:
8374 case CTRL('b'):
8375 case 'b':
8376 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8377 s->selected -= MIN(nscroll, s->selected);
8378 ref_scroll_up(s, MAX(0, nscroll));
8379 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8380 view->count = 0;
8381 break;
8382 case 'j':
8383 case KEY_DOWN:
8384 case CTRL('n'):
8385 if (s->selected < s->ndisplayed - 1) {
8386 s->selected++;
8387 break;
8389 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8390 /* can't scroll any further */
8391 view->count = 0;
8392 break;
8394 ref_scroll_down(view, 1);
8395 break;
8396 case CTRL('d'):
8397 case 'd':
8398 nscroll /= 2;
8399 /* FALL THROUGH */
8400 case KEY_NPAGE:
8401 case CTRL('f'):
8402 case 'f':
8403 case ' ':
8404 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8405 /* can't scroll any further; move cursor down */
8406 if (s->selected < s->ndisplayed - 1)
8407 s->selected += MIN(nscroll,
8408 s->ndisplayed - s->selected - 1);
8409 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8410 s->selected += s->ndisplayed - s->selected - 1;
8411 view->count = 0;
8412 break;
8414 ref_scroll_down(view, nscroll);
8415 break;
8416 case CTRL('l'):
8417 view->count = 0;
8418 tog_free_refs();
8419 err = tog_load_refs(s->repo, s->sort_by_date);
8420 if (err)
8421 break;
8422 ref_view_free_refs(s);
8423 err = ref_view_load_refs(s);
8424 break;
8425 case KEY_RESIZE:
8426 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8427 s->selected = view->nlines - 2;
8428 break;
8429 default:
8430 view->count = 0;
8431 break;
8434 return err;
8437 __dead static void
8438 usage_ref(void)
8440 endwin();
8441 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8442 getprogname());
8443 exit(1);
8446 static const struct got_error *
8447 cmd_ref(int argc, char *argv[])
8449 const struct got_error *error;
8450 struct got_repository *repo = NULL;
8451 struct got_worktree *worktree = NULL;
8452 char *cwd = NULL, *repo_path = NULL;
8453 int ch;
8454 struct tog_view *view;
8455 int *pack_fds = NULL;
8457 while ((ch = getopt(argc, argv, "r:")) != -1) {
8458 switch (ch) {
8459 case 'r':
8460 repo_path = realpath(optarg, NULL);
8461 if (repo_path == NULL)
8462 return got_error_from_errno2("realpath",
8463 optarg);
8464 break;
8465 default:
8466 usage_ref();
8467 /* NOTREACHED */
8471 argc -= optind;
8472 argv += optind;
8474 if (argc > 1)
8475 usage_ref();
8477 error = got_repo_pack_fds_open(&pack_fds);
8478 if (error != NULL)
8479 goto done;
8481 if (repo_path == NULL) {
8482 cwd = getcwd(NULL, 0);
8483 if (cwd == NULL)
8484 return got_error_from_errno("getcwd");
8485 error = got_worktree_open(&worktree, cwd);
8486 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8487 goto done;
8488 if (worktree)
8489 repo_path =
8490 strdup(got_worktree_get_repo_path(worktree));
8491 else
8492 repo_path = strdup(cwd);
8493 if (repo_path == NULL) {
8494 error = got_error_from_errno("strdup");
8495 goto done;
8499 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8500 if (error != NULL)
8501 goto done;
8503 init_curses();
8505 error = apply_unveil(got_repo_get_path(repo), NULL);
8506 if (error)
8507 goto done;
8509 error = tog_load_refs(repo, 0);
8510 if (error)
8511 goto done;
8513 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8514 if (view == NULL) {
8515 error = got_error_from_errno("view_open");
8516 goto done;
8519 error = open_ref_view(view, repo);
8520 if (error)
8521 goto done;
8523 if (worktree) {
8524 /* Release work tree lock. */
8525 got_worktree_close(worktree);
8526 worktree = NULL;
8528 error = view_loop(view);
8529 done:
8530 free(repo_path);
8531 free(cwd);
8532 if (repo) {
8533 const struct got_error *close_err = got_repo_close(repo);
8534 if (close_err)
8535 error = close_err;
8537 if (pack_fds) {
8538 const struct got_error *pack_err =
8539 got_repo_pack_fds_close(pack_fds);
8540 if (error == NULL)
8541 error = pack_err;
8543 tog_free_refs();
8544 return error;
8547 static const struct got_error*
8548 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8549 const char *str)
8551 size_t len;
8553 if (win == NULL)
8554 win = stdscr;
8556 len = strlen(str);
8557 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8559 if (focus)
8560 wstandout(win);
8561 if (mvwprintw(win, y, x, "%s", str) == ERR)
8562 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8563 if (focus)
8564 wstandend(win);
8566 return NULL;
8569 static const struct got_error *
8570 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8572 off_t *p;
8574 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8575 if (p == NULL) {
8576 free(*line_offsets);
8577 *line_offsets = NULL;
8578 return got_error_from_errno("reallocarray");
8581 *line_offsets = p;
8582 (*line_offsets)[*nlines] = off;
8583 ++(*nlines);
8584 return NULL;
8587 static const struct got_error *
8588 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8590 *ret = 0;
8592 for (;n > 0; --n, ++km) {
8593 char *t0, *t, *k;
8594 size_t len = 1;
8596 if (km->keys == NULL)
8597 continue;
8599 t = t0 = strdup(km->keys);
8600 if (t0 == NULL)
8601 return got_error_from_errno("strdup");
8603 len += strlen(t);
8604 while ((k = strsep(&t, " ")) != NULL)
8605 len += strlen(k) > 1 ? 2 : 0;
8606 free(t0);
8607 *ret = MAX(*ret, len);
8610 return NULL;
8614 * Write keymap section headers, keys, and key info in km to f.
8615 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8616 * wrap control and symbolic keys in guillemets, else use <>.
8618 static const struct got_error *
8619 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8621 int n, len = width;
8623 if (km->keys) {
8624 static const char *u8_glyph[] = {
8625 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8626 "\xe2\x80\xba" /* U+203A (utf8 >) */
8628 char *t0, *t, *k;
8629 int cs, s, first = 1;
8631 cs = got_locale_is_utf8();
8633 t = t0 = strdup(km->keys);
8634 if (t0 == NULL)
8635 return got_error_from_errno("strdup");
8637 len = strlen(km->keys);
8638 while ((k = strsep(&t, " ")) != NULL) {
8639 s = strlen(k) > 1; /* control or symbolic key */
8640 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8641 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8642 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8643 if (n < 0) {
8644 free(t0);
8645 return got_error_from_errno("fprintf");
8647 first = 0;
8648 len += s ? 2 : 0;
8649 *off += n;
8651 free(t0);
8653 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8654 if (n < 0)
8655 return got_error_from_errno("fprintf");
8656 *off += n;
8658 return NULL;
8661 static const struct got_error *
8662 format_help(struct tog_help_view_state *s)
8664 const struct got_error *err = NULL;
8665 off_t off = 0;
8666 int i, max, n, show = s->all;
8667 static const struct tog_key_map km[] = {
8668 #define KEYMAP_(info, type) { NULL, (info), type }
8669 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8670 GENERATE_HELP
8671 #undef KEYMAP_
8672 #undef KEY_
8675 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8676 if (err)
8677 return err;
8679 n = nitems(km);
8680 err = max_key_str(&max, km, n);
8681 if (err)
8682 return err;
8684 for (i = 0; i < n; ++i) {
8685 if (km[i].keys == NULL) {
8686 show = s->all;
8687 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8688 km[i].type == s->type || s->all)
8689 show = 1;
8691 if (show) {
8692 err = format_help_line(&off, s->f, &km[i], max);
8693 if (err)
8694 return err;
8695 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8696 if (err)
8697 return err;
8700 fputc('\n', s->f);
8701 ++off;
8702 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8703 return err;
8706 static const struct got_error *
8707 create_help(struct tog_help_view_state *s)
8709 FILE *f;
8710 const struct got_error *err;
8712 free(s->line_offsets);
8713 s->line_offsets = NULL;
8714 s->nlines = 0;
8716 f = got_opentemp();
8717 if (f == NULL)
8718 return got_error_from_errno("got_opentemp");
8719 s->f = f;
8721 err = format_help(s);
8722 if (err)
8723 return err;
8725 if (s->f && fflush(s->f) != 0)
8726 return got_error_from_errno("fflush");
8728 return NULL;
8731 static const struct got_error *
8732 search_start_help_view(struct tog_view *view)
8734 view->state.help.matched_line = 0;
8735 return NULL;
8738 static void
8739 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8740 size_t *nlines, int **first, int **last, int **match, int **selected)
8742 struct tog_help_view_state *s = &view->state.help;
8744 *f = s->f;
8745 *nlines = s->nlines;
8746 *line_offsets = s->line_offsets;
8747 *match = &s->matched_line;
8748 *first = &s->first_displayed_line;
8749 *last = &s->last_displayed_line;
8750 *selected = &s->selected_line;
8753 static const struct got_error *
8754 show_help_view(struct tog_view *view)
8756 struct tog_help_view_state *s = &view->state.help;
8757 const struct got_error *err;
8758 regmatch_t *regmatch = &view->regmatch;
8759 wchar_t *wline;
8760 char *line;
8761 ssize_t linelen;
8762 size_t linesz = 0;
8763 int width, nprinted = 0, rc = 0;
8764 int eos = view->nlines;
8766 if (view_is_hsplit_top(view))
8767 --eos; /* account for border */
8769 s->lineno = 0;
8770 rewind(s->f);
8771 werase(view->window);
8773 if (view->gline > s->nlines - 1)
8774 view->gline = s->nlines - 1;
8776 err = win_draw_center(view->window, 0, 0, view->ncols,
8777 view_needs_focus_indication(view),
8778 "tog help (press q to return to tog)");
8779 if (err)
8780 return err;
8781 if (eos <= 1)
8782 return NULL;
8783 waddstr(view->window, "\n\n");
8784 eos -= 2;
8786 s->eof = 0;
8787 view->maxx = 0;
8788 line = NULL;
8789 while (eos > 0 && nprinted < eos) {
8790 attr_t attr = 0;
8792 linelen = getline(&line, &linesz, s->f);
8793 if (linelen == -1) {
8794 if (!feof(s->f)) {
8795 free(line);
8796 return got_ferror(s->f, GOT_ERR_IO);
8798 s->eof = 1;
8799 break;
8801 if (++s->lineno < s->first_displayed_line)
8802 continue;
8803 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8804 continue;
8805 if (s->lineno == view->hiline)
8806 attr = A_STANDOUT;
8808 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8809 view->x ? 1 : 0);
8810 if (err) {
8811 free(line);
8812 return err;
8814 view->maxx = MAX(view->maxx, width);
8815 free(wline);
8816 wline = NULL;
8818 if (attr)
8819 wattron(view->window, attr);
8820 if (s->first_displayed_line + nprinted == s->matched_line &&
8821 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8822 err = add_matched_line(&width, line, view->ncols - 1, 0,
8823 view->window, view->x, regmatch);
8824 if (err) {
8825 free(line);
8826 return err;
8828 } else {
8829 int skip;
8831 err = format_line(&wline, &width, &skip, line,
8832 view->x, view->ncols - 1, 0, view->x ? 1 : 0);
8833 if (err) {
8834 free(line);
8835 return err;
8837 rc = waddwstr(view->window, &wline[skip]);
8838 free(wline);
8839 wline = NULL;
8840 if (rc == ERR)
8841 return got_error_msg(GOT_ERR_IO, "waddwstr");
8843 if (s->lineno == view->hiline) {
8844 while (width++ < view->ncols)
8845 waddch(view->window, ' ');
8846 } else {
8847 if (width <= view->ncols)
8848 waddch(view->window, '\n');
8850 if (attr)
8851 wattroff(view->window, attr);
8852 if (++nprinted == 1)
8853 s->first_displayed_line = s->lineno;
8855 free(line);
8856 if (nprinted > 0)
8857 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8858 else
8859 s->last_displayed_line = s->first_displayed_line;
8861 view_border(view);
8863 if (s->eof) {
8864 rc = waddnstr(view->window,
8865 "See the tog(1) manual page for full documentation",
8866 view->ncols - 1);
8867 if (rc == ERR)
8868 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8869 } else {
8870 wmove(view->window, view->nlines - 1, 0);
8871 wclrtoeol(view->window);
8872 wstandout(view->window);
8873 rc = waddnstr(view->window, "scroll down for more...",
8874 view->ncols - 1);
8875 if (rc == ERR)
8876 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8877 if (getcurx(view->window) < view->ncols - 6) {
8878 rc = wprintw(view->window, "[%.0f%%]",
8879 100.00 * s->last_displayed_line / s->nlines);
8880 if (rc == ERR)
8881 return got_error_msg(GOT_ERR_IO, "wprintw");
8883 wstandend(view->window);
8886 return NULL;
8889 static const struct got_error *
8890 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8892 struct tog_help_view_state *s = &view->state.help;
8893 const struct got_error *err = NULL;
8894 char *line = NULL;
8895 ssize_t linelen;
8896 size_t linesz = 0;
8897 int eos, nscroll;
8899 eos = nscroll = view->nlines;
8900 if (view_is_hsplit_top(view))
8901 --eos; /* border */
8903 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8905 switch (ch) {
8906 case '0':
8907 view->x = 0;
8908 break;
8909 case '$':
8910 view->x = MAX(view->maxx - view->ncols / 3, 0);
8911 view->count = 0;
8912 break;
8913 case KEY_RIGHT:
8914 case 'l':
8915 if (view->x + view->ncols / 3 < view->maxx)
8916 view->x += 2;
8917 else
8918 view->count = 0;
8919 break;
8920 case KEY_LEFT:
8921 case 'h':
8922 view->x -= MIN(view->x, 2);
8923 if (view->x <= 0)
8924 view->count = 0;
8925 break;
8926 case 'g':
8927 case KEY_HOME:
8928 s->first_displayed_line = 1;
8929 view->count = 0;
8930 break;
8931 case 'G':
8932 case KEY_END:
8933 view->count = 0;
8934 if (s->eof)
8935 break;
8936 s->first_displayed_line = (s->nlines - eos) + 3;
8937 s->eof = 1;
8938 break;
8939 case 'k':
8940 case KEY_UP:
8941 if (s->first_displayed_line > 1)
8942 --s->first_displayed_line;
8943 else
8944 view->count = 0;
8945 break;
8946 case CTRL('u'):
8947 case 'u':
8948 nscroll /= 2;
8949 /* FALL THROUGH */
8950 case KEY_PPAGE:
8951 case CTRL('b'):
8952 case 'b':
8953 if (s->first_displayed_line == 1) {
8954 view->count = 0;
8955 break;
8957 while (--nscroll > 0 && s->first_displayed_line > 1)
8958 s->first_displayed_line--;
8959 break;
8960 case 'j':
8961 case KEY_DOWN:
8962 case CTRL('n'):
8963 if (!s->eof)
8964 ++s->first_displayed_line;
8965 else
8966 view->count = 0;
8967 break;
8968 case CTRL('d'):
8969 case 'd':
8970 nscroll /= 2;
8971 /* FALL THROUGH */
8972 case KEY_NPAGE:
8973 case CTRL('f'):
8974 case 'f':
8975 case ' ':
8976 if (s->eof) {
8977 view->count = 0;
8978 break;
8980 while (!s->eof && --nscroll > 0) {
8981 linelen = getline(&line, &linesz, s->f);
8982 s->first_displayed_line++;
8983 if (linelen == -1) {
8984 if (feof(s->f))
8985 s->eof = 1;
8986 else
8987 err = got_ferror(s->f, GOT_ERR_IO);
8988 break;
8991 free(line);
8992 break;
8993 default:
8994 view->count = 0;
8995 break;
8998 return err;
9001 static const struct got_error *
9002 close_help_view(struct tog_view *view)
9004 struct tog_help_view_state *s = &view->state.help;
9006 free(s->line_offsets);
9007 s->line_offsets = NULL;
9008 if (fclose(s->f) == EOF)
9009 return got_error_from_errno("fclose");
9011 return NULL;
9014 static const struct got_error *
9015 reset_help_view(struct tog_view *view)
9017 struct tog_help_view_state *s = &view->state.help;
9020 if (s->f && fclose(s->f) == EOF)
9021 return got_error_from_errno("fclose");
9023 wclear(view->window);
9024 view->count = 0;
9025 view->x = 0;
9026 s->all = !s->all;
9027 s->first_displayed_line = 1;
9028 s->last_displayed_line = view->nlines;
9029 s->matched_line = 0;
9031 return create_help(s);
9034 static const struct got_error *
9035 open_help_view(struct tog_view *view, struct tog_view *parent)
9037 const struct got_error *err = NULL;
9038 struct tog_help_view_state *s = &view->state.help;
9040 s->type = (enum tog_keymap_type)parent->type;
9041 s->first_displayed_line = 1;
9042 s->last_displayed_line = view->nlines;
9043 s->selected_line = 1;
9045 view->show = show_help_view;
9046 view->input = input_help_view;
9047 view->reset = reset_help_view;
9048 view->close = close_help_view;
9049 view->search_start = search_start_help_view;
9050 view->search_setup = search_setup_help_view;
9051 view->search_next = search_next_view_match;
9053 err = create_help(s);
9054 return err;
9057 static const struct got_error *
9058 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9059 enum tog_view_type request, int y, int x)
9061 const struct got_error *err = NULL;
9063 *new_view = NULL;
9065 switch (request) {
9066 case TOG_VIEW_DIFF:
9067 if (view->type == TOG_VIEW_LOG) {
9068 struct tog_log_view_state *s = &view->state.log;
9070 err = open_diff_view_for_commit(new_view, y, x,
9071 s->selected_entry->commit, s->selected_entry->id,
9072 view, s->repo);
9073 } else
9074 return got_error_msg(GOT_ERR_NOT_IMPL,
9075 "parent/child view pair not supported");
9076 break;
9077 case TOG_VIEW_BLAME:
9078 if (view->type == TOG_VIEW_TREE) {
9079 struct tog_tree_view_state *s = &view->state.tree;
9081 err = blame_tree_entry(new_view, y, x,
9082 s->selected_entry, &s->parents, s->commit_id,
9083 s->repo);
9084 } else
9085 return got_error_msg(GOT_ERR_NOT_IMPL,
9086 "parent/child view pair not supported");
9087 break;
9088 case TOG_VIEW_LOG:
9089 if (view->type == TOG_VIEW_BLAME)
9090 err = log_annotated_line(new_view, y, x,
9091 view->state.blame.repo, view->state.blame.id_to_log);
9092 else if (view->type == TOG_VIEW_TREE)
9093 err = log_selected_tree_entry(new_view, y, x,
9094 &view->state.tree);
9095 else if (view->type == TOG_VIEW_REF)
9096 err = log_ref_entry(new_view, y, x,
9097 view->state.ref.selected_entry,
9098 view->state.ref.repo);
9099 else
9100 return got_error_msg(GOT_ERR_NOT_IMPL,
9101 "parent/child view pair not supported");
9102 break;
9103 case TOG_VIEW_TREE:
9104 if (view->type == TOG_VIEW_LOG)
9105 err = browse_commit_tree(new_view, y, x,
9106 view->state.log.selected_entry,
9107 view->state.log.in_repo_path,
9108 view->state.log.head_ref_name,
9109 view->state.log.repo);
9110 else if (view->type == TOG_VIEW_REF)
9111 err = browse_ref_tree(new_view, y, x,
9112 view->state.ref.selected_entry,
9113 view->state.ref.repo);
9114 else
9115 return got_error_msg(GOT_ERR_NOT_IMPL,
9116 "parent/child view pair not supported");
9117 break;
9118 case TOG_VIEW_REF:
9119 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9120 if (*new_view == NULL)
9121 return got_error_from_errno("view_open");
9122 if (view->type == TOG_VIEW_LOG)
9123 err = open_ref_view(*new_view, view->state.log.repo);
9124 else if (view->type == TOG_VIEW_TREE)
9125 err = open_ref_view(*new_view, view->state.tree.repo);
9126 else
9127 err = got_error_msg(GOT_ERR_NOT_IMPL,
9128 "parent/child view pair not supported");
9129 if (err)
9130 view_close(*new_view);
9131 break;
9132 case TOG_VIEW_HELP:
9133 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9134 if (*new_view == NULL)
9135 return got_error_from_errno("view_open");
9136 err = open_help_view(*new_view, view);
9137 if (err)
9138 view_close(*new_view);
9139 break;
9140 default:
9141 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9144 return err;
9148 * If view was scrolled down to move the selected line into view when opening a
9149 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9151 static void
9152 offset_selection_up(struct tog_view *view)
9154 switch (view->type) {
9155 case TOG_VIEW_BLAME: {
9156 struct tog_blame_view_state *s = &view->state.blame;
9157 if (s->first_displayed_line == 1) {
9158 s->selected_line = MAX(s->selected_line - view->offset,
9159 1);
9160 break;
9162 if (s->first_displayed_line > view->offset)
9163 s->first_displayed_line -= view->offset;
9164 else
9165 s->first_displayed_line = 1;
9166 s->selected_line += view->offset;
9167 break;
9169 case TOG_VIEW_LOG:
9170 log_scroll_up(&view->state.log, view->offset);
9171 view->state.log.selected += view->offset;
9172 break;
9173 case TOG_VIEW_REF:
9174 ref_scroll_up(&view->state.ref, view->offset);
9175 view->state.ref.selected += view->offset;
9176 break;
9177 case TOG_VIEW_TREE:
9178 tree_scroll_up(&view->state.tree, view->offset);
9179 view->state.tree.selected += view->offset;
9180 break;
9181 default:
9182 break;
9185 view->offset = 0;
9189 * If the selected line is in the section of screen covered by the bottom split,
9190 * scroll down offset lines to move it into view and index its new position.
9192 static const struct got_error *
9193 offset_selection_down(struct tog_view *view)
9195 const struct got_error *err = NULL;
9196 const struct got_error *(*scrolld)(struct tog_view *, int);
9197 int *selected = NULL;
9198 int header, offset;
9200 switch (view->type) {
9201 case TOG_VIEW_BLAME: {
9202 struct tog_blame_view_state *s = &view->state.blame;
9203 header = 3;
9204 scrolld = NULL;
9205 if (s->selected_line > view->nlines - header) {
9206 offset = abs(view->nlines - s->selected_line - header);
9207 s->first_displayed_line += offset;
9208 s->selected_line -= offset;
9209 view->offset = offset;
9211 break;
9213 case TOG_VIEW_LOG: {
9214 struct tog_log_view_state *s = &view->state.log;
9215 scrolld = &log_scroll_down;
9216 header = view_is_parent_view(view) ? 3 : 2;
9217 selected = &s->selected;
9218 break;
9220 case TOG_VIEW_REF: {
9221 struct tog_ref_view_state *s = &view->state.ref;
9222 scrolld = &ref_scroll_down;
9223 header = 3;
9224 selected = &s->selected;
9225 break;
9227 case TOG_VIEW_TREE: {
9228 struct tog_tree_view_state *s = &view->state.tree;
9229 scrolld = &tree_scroll_down;
9230 header = 5;
9231 selected = &s->selected;
9232 break;
9234 default:
9235 selected = NULL;
9236 scrolld = NULL;
9237 header = 0;
9238 break;
9241 if (selected && *selected > view->nlines - header) {
9242 offset = abs(view->nlines - *selected - header);
9243 view->offset = offset;
9244 if (scrolld && offset) {
9245 err = scrolld(view, offset);
9246 *selected -= offset;
9250 return err;
9253 static void
9254 list_commands(FILE *fp)
9256 size_t i;
9258 fprintf(fp, "commands:");
9259 for (i = 0; i < nitems(tog_commands); i++) {
9260 const struct tog_cmd *cmd = &tog_commands[i];
9261 fprintf(fp, " %s", cmd->name);
9263 fputc('\n', fp);
9266 __dead static void
9267 usage(int hflag, int status)
9269 FILE *fp = (status == 0) ? stdout : stderr;
9271 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9272 getprogname());
9273 if (hflag) {
9274 fprintf(fp, "lazy usage: %s path\n", getprogname());
9275 list_commands(fp);
9277 exit(status);
9280 static char **
9281 make_argv(int argc, ...)
9283 va_list ap;
9284 char **argv;
9285 int i;
9287 va_start(ap, argc);
9289 argv = calloc(argc, sizeof(char *));
9290 if (argv == NULL)
9291 err(1, "calloc");
9292 for (i = 0; i < argc; i++) {
9293 argv[i] = strdup(va_arg(ap, char *));
9294 if (argv[i] == NULL)
9295 err(1, "strdup");
9298 va_end(ap);
9299 return argv;
9303 * Try to convert 'tog path' into a 'tog log path' command.
9304 * The user could simply have mistyped the command rather than knowingly
9305 * provided a path. So check whether argv[0] can in fact be resolved
9306 * to a path in the HEAD commit and print a special error if not.
9307 * This hack is for mpi@ <3
9309 static const struct got_error *
9310 tog_log_with_path(int argc, char *argv[])
9312 const struct got_error *error = NULL, *close_err;
9313 const struct tog_cmd *cmd = NULL;
9314 struct got_repository *repo = NULL;
9315 struct got_worktree *worktree = NULL;
9316 struct got_object_id *commit_id = NULL, *id = NULL;
9317 struct got_commit_object *commit = NULL;
9318 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9319 char *commit_id_str = NULL, **cmd_argv = NULL;
9320 int *pack_fds = NULL;
9322 cwd = getcwd(NULL, 0);
9323 if (cwd == NULL)
9324 return got_error_from_errno("getcwd");
9326 error = got_repo_pack_fds_open(&pack_fds);
9327 if (error != NULL)
9328 goto done;
9330 error = got_worktree_open(&worktree, cwd);
9331 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9332 goto done;
9334 if (worktree)
9335 repo_path = strdup(got_worktree_get_repo_path(worktree));
9336 else
9337 repo_path = strdup(cwd);
9338 if (repo_path == NULL) {
9339 error = got_error_from_errno("strdup");
9340 goto done;
9343 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9344 if (error != NULL)
9345 goto done;
9347 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9348 repo, worktree);
9349 if (error)
9350 goto done;
9352 error = tog_load_refs(repo, 0);
9353 if (error)
9354 goto done;
9355 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9356 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9357 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9358 if (error)
9359 goto done;
9361 if (worktree) {
9362 got_worktree_close(worktree);
9363 worktree = NULL;
9366 error = got_object_open_as_commit(&commit, repo, commit_id);
9367 if (error)
9368 goto done;
9370 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9371 if (error) {
9372 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9373 goto done;
9374 fprintf(stderr, "%s: '%s' is no known command or path\n",
9375 getprogname(), argv[0]);
9376 usage(1, 1);
9377 /* not reached */
9380 error = got_object_id_str(&commit_id_str, commit_id);
9381 if (error)
9382 goto done;
9384 cmd = &tog_commands[0]; /* log */
9385 argc = 4;
9386 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9387 error = cmd->cmd_main(argc, cmd_argv);
9388 done:
9389 if (repo) {
9390 close_err = got_repo_close(repo);
9391 if (error == NULL)
9392 error = close_err;
9394 if (commit)
9395 got_object_commit_close(commit);
9396 if (worktree)
9397 got_worktree_close(worktree);
9398 if (pack_fds) {
9399 const struct got_error *pack_err =
9400 got_repo_pack_fds_close(pack_fds);
9401 if (error == NULL)
9402 error = pack_err;
9404 free(id);
9405 free(commit_id_str);
9406 free(commit_id);
9407 free(cwd);
9408 free(repo_path);
9409 free(in_repo_path);
9410 if (cmd_argv) {
9411 int i;
9412 for (i = 0; i < argc; i++)
9413 free(cmd_argv[i]);
9414 free(cmd_argv);
9416 tog_free_refs();
9417 return error;
9420 int
9421 main(int argc, char *argv[])
9423 const struct got_error *error = NULL;
9424 const struct tog_cmd *cmd = NULL;
9425 int ch, hflag = 0, Vflag = 0;
9426 char **cmd_argv = NULL;
9427 static const struct option longopts[] = {
9428 { "version", no_argument, NULL, 'V' },
9429 { NULL, 0, NULL, 0}
9431 char *diff_algo_str = NULL;
9433 if (!isatty(STDIN_FILENO))
9434 errx(1, "standard input is not a tty");
9436 setlocale(LC_CTYPE, "");
9438 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9439 switch (ch) {
9440 case 'h':
9441 hflag = 1;
9442 break;
9443 case 'V':
9444 Vflag = 1;
9445 break;
9446 default:
9447 usage(hflag, 1);
9448 /* NOTREACHED */
9452 argc -= optind;
9453 argv += optind;
9454 optind = 1;
9455 optreset = 1;
9457 if (Vflag) {
9458 got_version_print_str();
9459 return 0;
9462 #ifndef PROFILE
9463 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9464 NULL) == -1)
9465 err(1, "pledge");
9466 #endif
9468 if (argc == 0) {
9469 if (hflag)
9470 usage(hflag, 0);
9471 /* Build an argument vector which runs a default command. */
9472 cmd = &tog_commands[0];
9473 argc = 1;
9474 cmd_argv = make_argv(argc, cmd->name);
9475 } else {
9476 size_t i;
9478 /* Did the user specify a command? */
9479 for (i = 0; i < nitems(tog_commands); i++) {
9480 if (strncmp(tog_commands[i].name, argv[0],
9481 strlen(argv[0])) == 0) {
9482 cmd = &tog_commands[i];
9483 break;
9488 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9489 if (diff_algo_str) {
9490 if (strcasecmp(diff_algo_str, "patience") == 0)
9491 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9492 if (strcasecmp(diff_algo_str, "myers") == 0)
9493 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9496 if (cmd == NULL) {
9497 if (argc != 1)
9498 usage(0, 1);
9499 /* No command specified; try log with a path */
9500 error = tog_log_with_path(argc, argv);
9501 } else {
9502 if (hflag)
9503 cmd->cmd_usage();
9504 else
9505 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9508 endwin();
9509 if (cmd_argv) {
9510 int i;
9511 for (i = 0; i < argc; i++)
9512 free(cmd_argv[i]);
9513 free(cmd_argv);
9516 if (error && error->code != GOT_ERR_CANCELLED &&
9517 error->code != GOT_ERR_EOF &&
9518 error->code != GOT_ERR_PRIVSEP_EXIT &&
9519 error->code != GOT_ERR_PRIVSEP_PIPE &&
9520 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9521 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9522 return 0;