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, int fast_refresh)
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 (!fast_refresh)
1325 halfdelay(10);
1326 if (ret == ERR)
1327 return NULL;
1329 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1330 err = view->search_start(view);
1331 if (err) {
1332 regfree(&view->regex);
1333 return err;
1335 view->search_started = 1;
1336 view->searching = TOG_SEARCH_FORWARD;
1337 view->search_next_done = 0;
1338 view->search_next(view);
1341 return NULL;
1344 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1345 static const struct got_error *
1346 switch_split(struct tog_view *view)
1348 const struct got_error *err = NULL;
1349 struct tog_view *v = NULL;
1351 if (view->parent)
1352 v = view->parent;
1353 else
1354 v = view;
1356 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1357 v->mode = TOG_VIEW_SPLIT_VERT;
1358 else
1359 v->mode = TOG_VIEW_SPLIT_HRZN;
1361 if (!v->child)
1362 return NULL;
1363 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1364 v->mode = TOG_VIEW_SPLIT_NONE;
1366 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1367 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1368 v->child->begin_y = v->child->resized_y;
1369 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1370 v->child->begin_x = v->child->resized_x;
1373 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1374 v->ncols = COLS;
1375 v->child->ncols = COLS;
1376 v->child->nscrolled = LINES - v->child->nlines;
1378 err = view_init_hsplit(v, v->child->begin_y);
1379 if (err)
1380 return err;
1382 v->child->mode = v->mode;
1383 v->child->nlines = v->lines - v->child->begin_y;
1384 v->focus_child = 1;
1386 err = view_fullscreen(v);
1387 if (err)
1388 return err;
1389 err = view_splitscreen(v->child);
1390 if (err)
1391 return err;
1393 if (v->mode == TOG_VIEW_SPLIT_NONE)
1394 v->mode = TOG_VIEW_SPLIT_VERT;
1395 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1396 err = offset_selection_down(v);
1397 if (err)
1398 return err;
1399 err = offset_selection_down(v->child);
1400 if (err)
1401 return err;
1402 } else {
1403 offset_selection_up(v);
1404 offset_selection_up(v->child);
1406 if (v->resize)
1407 err = v->resize(v, 0);
1408 else if (v->child->resize)
1409 err = v->child->resize(v->child, 0);
1411 return err;
1415 * Compute view->count from numeric input. Assign total to view->count and
1416 * return first non-numeric key entered.
1418 static int
1419 get_compound_key(struct tog_view *view, int c)
1421 struct tog_view *v = view;
1422 int x, n = 0;
1424 if (view_is_hsplit_top(view))
1425 v = view->child;
1426 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1427 v = view->parent;
1429 view->count = 0;
1430 cbreak(); /* block for input */
1431 nodelay(view->window, FALSE);
1432 wmove(v->window, v->nlines - 1, 0);
1433 wclrtoeol(v->window);
1434 waddch(v->window, ':');
1436 do {
1437 x = getcurx(v->window);
1438 if (x != ERR && x < view->ncols) {
1439 waddch(v->window, c);
1440 wrefresh(v->window);
1444 * Don't overflow. Max valid request should be the greatest
1445 * between the longest and total lines; cap at 10 million.
1447 if (n >= 9999999)
1448 n = 9999999;
1449 else
1450 n = n * 10 + (c - '0');
1451 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1453 if (c == 'G' || c == 'g') { /* nG key map */
1454 view->gline = view->hiline = n;
1455 n = 0;
1456 c = 0;
1459 /* Massage excessive or inapplicable values at the input handler. */
1460 view->count = n;
1462 return c;
1465 static void
1466 action_report(struct tog_view *view)
1468 struct tog_view *v = view;
1470 if (view_is_hsplit_top(view))
1471 v = view->child;
1472 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1473 v = view->parent;
1475 wmove(v->window, v->nlines - 1, 0);
1476 wclrtoeol(v->window);
1477 wprintw(v->window, ":%s", view->action);
1478 wrefresh(v->window);
1481 * Clear action status report. Only clear in blame view
1482 * once annotating is complete, otherwise it's too fast.
1484 if (view->type == TOG_VIEW_BLAME) {
1485 if (view->state.blame.blame_complete)
1486 view->action = NULL;
1487 } else
1488 view->action = NULL;
1491 static const struct got_error *
1492 view_input(struct tog_view **new, int *done, struct tog_view *view,
1493 struct tog_view_list_head *views, int fast_refresh)
1495 const struct got_error *err = NULL;
1496 struct tog_view *v;
1497 int ch, errcode;
1499 *new = NULL;
1501 if (view->action)
1502 action_report(view);
1504 /* Clear "no matches" indicator. */
1505 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1506 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1507 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1508 view->count = 0;
1511 if (view->searching && !view->search_next_done) {
1512 errcode = pthread_mutex_unlock(&tog_mutex);
1513 if (errcode)
1514 return got_error_set_errno(errcode,
1515 "pthread_mutex_unlock");
1516 sched_yield();
1517 errcode = pthread_mutex_lock(&tog_mutex);
1518 if (errcode)
1519 return got_error_set_errno(errcode,
1520 "pthread_mutex_lock");
1521 view->search_next(view);
1522 return NULL;
1525 /* Allow threads to make progress while we are waiting for input. */
1526 errcode = pthread_mutex_unlock(&tog_mutex);
1527 if (errcode)
1528 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1529 /* If we have an unfinished count, let C-g or backspace abort. */
1530 if (view->count && --view->count) {
1531 cbreak();
1532 nodelay(view->window, TRUE);
1533 ch = wgetch(view->window);
1534 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1535 view->count = 0;
1536 else
1537 ch = view->ch;
1538 } else {
1539 ch = wgetch(view->window);
1540 if (ch >= '1' && ch <= '9')
1541 view->ch = ch = get_compound_key(view, ch);
1543 if (view->hiline && ch != ERR && ch != 0)
1544 view->hiline = 0; /* key pressed, clear line highlight */
1545 nodelay(view->window, TRUE);
1546 errcode = pthread_mutex_lock(&tog_mutex);
1547 if (errcode)
1548 return got_error_set_errno(errcode, "pthread_mutex_lock");
1550 if (tog_sigwinch_received || tog_sigcont_received) {
1551 tog_resizeterm();
1552 tog_sigwinch_received = 0;
1553 tog_sigcont_received = 0;
1554 TAILQ_FOREACH(v, views, entry) {
1555 err = view_resize(v);
1556 if (err)
1557 return err;
1558 err = v->input(new, v, KEY_RESIZE);
1559 if (err)
1560 return err;
1561 if (v->child) {
1562 err = view_resize(v->child);
1563 if (err)
1564 return err;
1565 err = v->child->input(new, v->child,
1566 KEY_RESIZE);
1567 if (err)
1568 return err;
1569 if (v->child->resized_x || v->child->resized_y) {
1570 err = view_resize_split(v, 0);
1571 if (err)
1572 return err;
1578 switch (ch) {
1579 case '?':
1580 case 'H':
1581 case KEY_F(1):
1582 if (view->type == TOG_VIEW_HELP)
1583 err = view->reset(view);
1584 else
1585 err = view_request_new(new, view, TOG_VIEW_HELP);
1586 break;
1587 case '\t':
1588 view->count = 0;
1589 if (view->child) {
1590 view->focussed = 0;
1591 view->child->focussed = 1;
1592 view->focus_child = 1;
1593 } else if (view->parent) {
1594 view->focussed = 0;
1595 view->parent->focussed = 1;
1596 view->parent->focus_child = 0;
1597 if (!view_is_splitscreen(view)) {
1598 if (view->parent->resize) {
1599 err = view->parent->resize(view->parent,
1600 0);
1601 if (err)
1602 return err;
1604 offset_selection_up(view->parent);
1605 err = view_fullscreen(view->parent);
1606 if (err)
1607 return err;
1610 break;
1611 case 'q':
1612 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1613 if (view->parent->resize) {
1614 /* might need more commits to fill fullscreen */
1615 err = view->parent->resize(view->parent, 0);
1616 if (err)
1617 break;
1619 offset_selection_up(view->parent);
1621 err = view->input(new, view, ch);
1622 view->dying = 1;
1623 break;
1624 case 'Q':
1625 *done = 1;
1626 break;
1627 case 'F':
1628 view->count = 0;
1629 if (view_is_parent_view(view)) {
1630 if (view->child == NULL)
1631 break;
1632 if (view_is_splitscreen(view->child)) {
1633 view->focussed = 0;
1634 view->child->focussed = 1;
1635 err = view_fullscreen(view->child);
1636 } else {
1637 err = view_splitscreen(view->child);
1638 if (!err)
1639 err = view_resize_split(view, 0);
1641 if (err)
1642 break;
1643 err = view->child->input(new, view->child,
1644 KEY_RESIZE);
1645 } else {
1646 if (view_is_splitscreen(view)) {
1647 view->parent->focussed = 0;
1648 view->focussed = 1;
1649 err = view_fullscreen(view);
1650 } else {
1651 err = view_splitscreen(view);
1652 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1653 err = view_resize(view->parent);
1654 if (!err)
1655 err = view_resize_split(view, 0);
1657 if (err)
1658 break;
1659 err = view->input(new, view, KEY_RESIZE);
1661 if (err)
1662 break;
1663 if (view->resize) {
1664 err = view->resize(view, 0);
1665 if (err)
1666 break;
1668 if (view->parent)
1669 err = offset_selection_down(view->parent);
1670 if (!err)
1671 err = offset_selection_down(view);
1672 break;
1673 case 'S':
1674 view->count = 0;
1675 err = switch_split(view);
1676 break;
1677 case '-':
1678 err = view_resize_split(view, -1);
1679 break;
1680 case '+':
1681 err = view_resize_split(view, 1);
1682 break;
1683 case KEY_RESIZE:
1684 break;
1685 case '/':
1686 view->count = 0;
1687 if (view->search_start)
1688 view_search_start(view, fast_refresh);
1689 else
1690 err = view->input(new, view, ch);
1691 break;
1692 case 'N':
1693 case 'n':
1694 if (view->search_started && view->search_next) {
1695 view->searching = (ch == 'n' ?
1696 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1697 view->search_next_done = 0;
1698 view->search_next(view);
1699 } else
1700 err = view->input(new, view, ch);
1701 break;
1702 case 'A':
1703 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1704 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1705 view->action = "Patience diff algorithm";
1706 } else {
1707 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1708 view->action = "Myers diff algorithm";
1710 TAILQ_FOREACH(v, views, entry) {
1711 if (v->reset) {
1712 err = v->reset(v);
1713 if (err)
1714 return err;
1716 if (v->child && v->child->reset) {
1717 err = v->child->reset(v->child);
1718 if (err)
1719 return err;
1722 break;
1723 default:
1724 err = view->input(new, view, ch);
1725 break;
1728 return err;
1731 static int
1732 view_needs_focus_indication(struct tog_view *view)
1734 if (view_is_parent_view(view)) {
1735 if (view->child == NULL || view->child->focussed)
1736 return 0;
1737 if (!view_is_splitscreen(view->child))
1738 return 0;
1739 } else if (!view_is_splitscreen(view))
1740 return 0;
1742 return view->focussed;
1745 static const struct got_error *
1746 view_loop(struct tog_view *view)
1748 const struct got_error *err = NULL;
1749 struct tog_view_list_head views;
1750 struct tog_view *new_view;
1751 char *mode;
1752 int fast_refresh = 10;
1753 int done = 0, errcode;
1755 mode = getenv("TOG_VIEW_SPLIT_MODE");
1756 if (!mode || !(*mode == 'h' || *mode == 'H'))
1757 view->mode = TOG_VIEW_SPLIT_VERT;
1758 else
1759 view->mode = TOG_VIEW_SPLIT_HRZN;
1761 errcode = pthread_mutex_lock(&tog_mutex);
1762 if (errcode)
1763 return got_error_set_errno(errcode, "pthread_mutex_lock");
1765 TAILQ_INIT(&views);
1766 TAILQ_INSERT_HEAD(&views, view, entry);
1768 view->focussed = 1;
1769 err = view->show(view);
1770 if (err)
1771 return err;
1772 update_panels();
1773 doupdate();
1774 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1775 !tog_fatal_signal_received()) {
1776 /* Refresh fast during initialization, then become slower. */
1777 if (fast_refresh && --fast_refresh == 0)
1778 halfdelay(10); /* switch to once per second */
1780 err = view_input(&new_view, &done, view, &views, fast_refresh);
1781 if (err)
1782 break;
1784 if (view->dying && view == TAILQ_FIRST(&views) &&
1785 TAILQ_NEXT(view, entry) == NULL)
1786 done = 1;
1787 if (done) {
1788 struct tog_view *v;
1791 * When we quit, scroll the screen up a single line
1792 * so we don't lose any information.
1794 TAILQ_FOREACH(v, &views, entry) {
1795 wmove(v->window, 0, 0);
1796 wdeleteln(v->window);
1797 wnoutrefresh(v->window);
1798 if (v->child && !view_is_fullscreen(v)) {
1799 wmove(v->child->window, 0, 0);
1800 wdeleteln(v->child->window);
1801 wnoutrefresh(v->child->window);
1804 doupdate();
1807 if (view->dying) {
1808 struct tog_view *v, *prev = NULL;
1810 if (view_is_parent_view(view))
1811 prev = TAILQ_PREV(view, tog_view_list_head,
1812 entry);
1813 else if (view->parent)
1814 prev = view->parent;
1816 if (view->parent) {
1817 view->parent->child = NULL;
1818 view->parent->focus_child = 0;
1819 /* Restore fullscreen line height. */
1820 view->parent->nlines = view->parent->lines;
1821 err = view_resize(view->parent);
1822 if (err)
1823 break;
1824 /* Make resized splits persist. */
1825 view_transfer_size(view->parent, view);
1826 } else
1827 TAILQ_REMOVE(&views, view, entry);
1829 err = view_close(view);
1830 if (err)
1831 goto done;
1833 view = NULL;
1834 TAILQ_FOREACH(v, &views, entry) {
1835 if (v->focussed)
1836 break;
1838 if (view == NULL && new_view == NULL) {
1839 /* No view has focus. Try to pick one. */
1840 if (prev)
1841 view = prev;
1842 else if (!TAILQ_EMPTY(&views)) {
1843 view = TAILQ_LAST(&views,
1844 tog_view_list_head);
1846 if (view) {
1847 if (view->focus_child) {
1848 view->child->focussed = 1;
1849 view = view->child;
1850 } else
1851 view->focussed = 1;
1855 if (new_view) {
1856 struct tog_view *v, *t;
1857 /* Only allow one parent view per type. */
1858 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1859 if (v->type != new_view->type)
1860 continue;
1861 TAILQ_REMOVE(&views, v, entry);
1862 err = view_close(v);
1863 if (err)
1864 goto done;
1865 break;
1867 TAILQ_INSERT_TAIL(&views, new_view, entry);
1868 view = new_view;
1870 if (view && !done) {
1871 if (view_is_parent_view(view)) {
1872 if (view->child && view->child->focussed)
1873 view = view->child;
1874 } else {
1875 if (view->parent && view->parent->focussed)
1876 view = view->parent;
1878 show_panel(view->panel);
1879 if (view->child && view_is_splitscreen(view->child))
1880 show_panel(view->child->panel);
1881 if (view->parent && view_is_splitscreen(view)) {
1882 err = view->parent->show(view->parent);
1883 if (err)
1884 goto done;
1886 err = view->show(view);
1887 if (err)
1888 goto done;
1889 if (view->child) {
1890 err = view->child->show(view->child);
1891 if (err)
1892 goto done;
1894 update_panels();
1895 doupdate();
1898 done:
1899 while (!TAILQ_EMPTY(&views)) {
1900 const struct got_error *close_err;
1901 view = TAILQ_FIRST(&views);
1902 TAILQ_REMOVE(&views, view, entry);
1903 close_err = view_close(view);
1904 if (close_err && err == NULL)
1905 err = close_err;
1908 errcode = pthread_mutex_unlock(&tog_mutex);
1909 if (errcode && err == NULL)
1910 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1912 return err;
1915 __dead static void
1916 usage_log(void)
1918 endwin();
1919 fprintf(stderr,
1920 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1921 getprogname());
1922 exit(1);
1925 /* Create newly allocated wide-character string equivalent to a byte string. */
1926 static const struct got_error *
1927 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1929 char *vis = NULL;
1930 const struct got_error *err = NULL;
1932 *ws = NULL;
1933 *wlen = mbstowcs(NULL, s, 0);
1934 if (*wlen == (size_t)-1) {
1935 int vislen;
1936 if (errno != EILSEQ)
1937 return got_error_from_errno("mbstowcs");
1939 /* byte string invalid in current encoding; try to "fix" it */
1940 err = got_mbsavis(&vis, &vislen, s);
1941 if (err)
1942 return err;
1943 *wlen = mbstowcs(NULL, vis, 0);
1944 if (*wlen == (size_t)-1) {
1945 err = got_error_from_errno("mbstowcs"); /* give up */
1946 goto done;
1950 *ws = calloc(*wlen + 1, sizeof(**ws));
1951 if (*ws == NULL) {
1952 err = got_error_from_errno("calloc");
1953 goto done;
1956 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1957 err = got_error_from_errno("mbstowcs");
1958 done:
1959 free(vis);
1960 if (err) {
1961 free(*ws);
1962 *ws = NULL;
1963 *wlen = 0;
1965 return err;
1968 static const struct got_error *
1969 expand_tab(char **ptr, const char *src)
1971 char *dst;
1972 size_t len, n, idx = 0, sz = 0;
1974 *ptr = NULL;
1975 n = len = strlen(src);
1976 dst = malloc(n + 1);
1977 if (dst == NULL)
1978 return got_error_from_errno("malloc");
1980 while (idx < len && src[idx]) {
1981 const char c = src[idx];
1983 if (c == '\t') {
1984 size_t nb = TABSIZE - sz % TABSIZE;
1985 char *p;
1987 p = realloc(dst, n + nb);
1988 if (p == NULL) {
1989 free(dst);
1990 return got_error_from_errno("realloc");
1993 dst = p;
1994 n += nb;
1995 memset(dst + sz, ' ', nb);
1996 sz += nb;
1997 } else
1998 dst[sz++] = src[idx];
1999 ++idx;
2002 dst[sz] = '\0';
2003 *ptr = dst;
2004 return NULL;
2008 * Advance at most n columns from wline starting at offset off.
2009 * Return the index to the first character after the span operation.
2010 * Return the combined column width of all spanned wide character in
2011 * *rcol.
2013 static int
2014 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2016 int width, i, cols = 0;
2018 if (n == 0) {
2019 *rcol = cols;
2020 return off;
2023 for (i = off; wline[i] != L'\0'; ++i) {
2024 if (wline[i] == L'\t')
2025 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2026 else
2027 width = wcwidth(wline[i]);
2029 if (width == -1) {
2030 width = 1;
2031 wline[i] = L'.';
2034 if (cols + width > n)
2035 break;
2036 cols += width;
2039 *rcol = cols;
2040 return i;
2044 * Format a line for display, ensuring that it won't overflow a width limit.
2045 * With scrolling, the width returned refers to the scrolled version of the
2046 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2048 static const struct got_error *
2049 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2050 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2052 const struct got_error *err = NULL;
2053 int cols;
2054 wchar_t *wline = NULL;
2055 char *exstr = NULL;
2056 size_t wlen;
2057 int i, scrollx;
2059 *wlinep = NULL;
2060 *widthp = 0;
2062 if (expand) {
2063 err = expand_tab(&exstr, line);
2064 if (err)
2065 return err;
2068 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2069 free(exstr);
2070 if (err)
2071 return err;
2073 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2075 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2076 wline[wlen - 1] = L'\0';
2077 wlen--;
2079 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2080 wline[wlen - 1] = L'\0';
2081 wlen--;
2084 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2085 wline[i] = L'\0';
2087 if (widthp)
2088 *widthp = cols;
2089 if (scrollxp)
2090 *scrollxp = scrollx;
2091 if (err)
2092 free(wline);
2093 else
2094 *wlinep = wline;
2095 return err;
2098 static const struct got_error*
2099 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2100 struct got_object_id *id, struct got_repository *repo)
2102 static const struct got_error *err = NULL;
2103 struct got_reflist_entry *re;
2104 char *s;
2105 const char *name;
2107 *refs_str = NULL;
2109 TAILQ_FOREACH(re, refs, entry) {
2110 struct got_tag_object *tag = NULL;
2111 struct got_object_id *ref_id;
2112 int cmp;
2114 name = got_ref_get_name(re->ref);
2115 if (strcmp(name, GOT_REF_HEAD) == 0)
2116 continue;
2117 if (strncmp(name, "refs/", 5) == 0)
2118 name += 5;
2119 if (strncmp(name, "got/", 4) == 0 &&
2120 strncmp(name, "got/backup/", 11) != 0)
2121 continue;
2122 if (strncmp(name, "heads/", 6) == 0)
2123 name += 6;
2124 if (strncmp(name, "remotes/", 8) == 0) {
2125 name += 8;
2126 s = strstr(name, "/" GOT_REF_HEAD);
2127 if (s != NULL && s[strlen(s)] == '\0')
2128 continue;
2130 err = got_ref_resolve(&ref_id, repo, re->ref);
2131 if (err)
2132 break;
2133 if (strncmp(name, "tags/", 5) == 0) {
2134 err = got_object_open_as_tag(&tag, repo, ref_id);
2135 if (err) {
2136 if (err->code != GOT_ERR_OBJ_TYPE) {
2137 free(ref_id);
2138 break;
2140 /* Ref points at something other than a tag. */
2141 err = NULL;
2142 tag = NULL;
2145 cmp = got_object_id_cmp(tag ?
2146 got_object_tag_get_object_id(tag) : ref_id, id);
2147 free(ref_id);
2148 if (tag)
2149 got_object_tag_close(tag);
2150 if (cmp != 0)
2151 continue;
2152 s = *refs_str;
2153 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2154 s ? ", " : "", name) == -1) {
2155 err = got_error_from_errno("asprintf");
2156 free(s);
2157 *refs_str = NULL;
2158 break;
2160 free(s);
2163 return err;
2166 static const struct got_error *
2167 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2168 int col_tab_align)
2170 char *smallerthan;
2172 smallerthan = strchr(author, '<');
2173 if (smallerthan && smallerthan[1] != '\0')
2174 author = smallerthan + 1;
2175 author[strcspn(author, "@>")] = '\0';
2176 return format_line(wauthor, author_width, NULL, author, 0, limit,
2177 col_tab_align, 0);
2180 static const struct got_error *
2181 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2182 struct got_object_id *id, const size_t date_display_cols,
2183 int author_display_cols)
2185 struct tog_log_view_state *s = &view->state.log;
2186 const struct got_error *err = NULL;
2187 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2188 char *logmsg0 = NULL, *logmsg = NULL;
2189 char *author = NULL;
2190 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2191 int author_width, logmsg_width;
2192 char *newline, *line = NULL;
2193 int col, limit, scrollx;
2194 const int avail = view->ncols;
2195 struct tm tm;
2196 time_t committer_time;
2197 struct tog_color *tc;
2199 committer_time = got_object_commit_get_committer_time(commit);
2200 if (gmtime_r(&committer_time, &tm) == NULL)
2201 return got_error_from_errno("gmtime_r");
2202 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2203 return got_error(GOT_ERR_NO_SPACE);
2205 if (avail <= date_display_cols)
2206 limit = MIN(sizeof(datebuf) - 1, avail);
2207 else
2208 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2209 tc = get_color(&s->colors, TOG_COLOR_DATE);
2210 if (tc)
2211 wattr_on(view->window,
2212 COLOR_PAIR(tc->colorpair), NULL);
2213 waddnstr(view->window, datebuf, limit);
2214 if (tc)
2215 wattr_off(view->window,
2216 COLOR_PAIR(tc->colorpair), NULL);
2217 col = limit;
2218 if (col > avail)
2219 goto done;
2221 if (avail >= 120) {
2222 char *id_str;
2223 err = got_object_id_str(&id_str, id);
2224 if (err)
2225 goto done;
2226 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2227 if (tc)
2228 wattr_on(view->window,
2229 COLOR_PAIR(tc->colorpair), NULL);
2230 wprintw(view->window, "%.8s ", id_str);
2231 if (tc)
2232 wattr_off(view->window,
2233 COLOR_PAIR(tc->colorpair), NULL);
2234 free(id_str);
2235 col += 9;
2236 if (col > avail)
2237 goto done;
2240 if (s->use_committer)
2241 author = strdup(got_object_commit_get_committer(commit));
2242 else
2243 author = strdup(got_object_commit_get_author(commit));
2244 if (author == NULL) {
2245 err = got_error_from_errno("strdup");
2246 goto done;
2248 err = format_author(&wauthor, &author_width, author, avail - col, col);
2249 if (err)
2250 goto done;
2251 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2252 if (tc)
2253 wattr_on(view->window,
2254 COLOR_PAIR(tc->colorpair), NULL);
2255 waddwstr(view->window, wauthor);
2256 col += author_width;
2257 while (col < avail && author_width < author_display_cols + 2) {
2258 waddch(view->window, ' ');
2259 col++;
2260 author_width++;
2262 if (tc)
2263 wattr_off(view->window,
2264 COLOR_PAIR(tc->colorpair), NULL);
2265 if (col > avail)
2266 goto done;
2268 err = got_object_commit_get_logmsg(&logmsg0, commit);
2269 if (err)
2270 goto done;
2271 logmsg = logmsg0;
2272 while (*logmsg == '\n')
2273 logmsg++;
2274 newline = strchr(logmsg, '\n');
2275 if (newline)
2276 *newline = '\0';
2277 limit = avail - col;
2278 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2279 limit--; /* for the border */
2280 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2281 limit, col, 1);
2282 if (err)
2283 goto done;
2284 waddwstr(view->window, &wlogmsg[scrollx]);
2285 col += MAX(logmsg_width, 0);
2286 while (col < avail) {
2287 waddch(view->window, ' ');
2288 col++;
2290 done:
2291 free(logmsg0);
2292 free(wlogmsg);
2293 free(author);
2294 free(wauthor);
2295 free(line);
2296 return err;
2299 static struct commit_queue_entry *
2300 alloc_commit_queue_entry(struct got_commit_object *commit,
2301 struct got_object_id *id)
2303 struct commit_queue_entry *entry;
2304 struct got_object_id *dup;
2306 entry = calloc(1, sizeof(*entry));
2307 if (entry == NULL)
2308 return NULL;
2310 dup = got_object_id_dup(id);
2311 if (dup == NULL) {
2312 free(entry);
2313 return NULL;
2316 entry->id = dup;
2317 entry->commit = commit;
2318 return entry;
2321 static void
2322 pop_commit(struct commit_queue *commits)
2324 struct commit_queue_entry *entry;
2326 entry = TAILQ_FIRST(&commits->head);
2327 TAILQ_REMOVE(&commits->head, entry, entry);
2328 got_object_commit_close(entry->commit);
2329 commits->ncommits--;
2330 free(entry->id);
2331 free(entry);
2334 static void
2335 free_commits(struct commit_queue *commits)
2337 while (!TAILQ_EMPTY(&commits->head))
2338 pop_commit(commits);
2341 static const struct got_error *
2342 match_commit(int *have_match, struct got_object_id *id,
2343 struct got_commit_object *commit, regex_t *regex)
2345 const struct got_error *err = NULL;
2346 regmatch_t regmatch;
2347 char *id_str = NULL, *logmsg = NULL;
2349 *have_match = 0;
2351 err = got_object_id_str(&id_str, id);
2352 if (err)
2353 return err;
2355 err = got_object_commit_get_logmsg(&logmsg, commit);
2356 if (err)
2357 goto done;
2359 if (regexec(regex, got_object_commit_get_author(commit), 1,
2360 &regmatch, 0) == 0 ||
2361 regexec(regex, got_object_commit_get_committer(commit), 1,
2362 &regmatch, 0) == 0 ||
2363 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2364 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2365 *have_match = 1;
2366 done:
2367 free(id_str);
2368 free(logmsg);
2369 return err;
2372 static const struct got_error *
2373 queue_commits(struct tog_log_thread_args *a)
2375 const struct got_error *err = NULL;
2378 * We keep all commits open throughout the lifetime of the log
2379 * view in order to avoid having to re-fetch commits from disk
2380 * while updating the display.
2382 do {
2383 struct got_object_id id;
2384 struct got_commit_object *commit;
2385 struct commit_queue_entry *entry;
2386 int limit_match = 0;
2387 int errcode;
2389 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2390 NULL, NULL);
2391 if (err)
2392 break;
2394 err = got_object_open_as_commit(&commit, a->repo, &id);
2395 if (err)
2396 break;
2397 entry = alloc_commit_queue_entry(commit, &id);
2398 if (entry == NULL) {
2399 err = got_error_from_errno("alloc_commit_queue_entry");
2400 break;
2403 errcode = pthread_mutex_lock(&tog_mutex);
2404 if (errcode) {
2405 err = got_error_set_errno(errcode,
2406 "pthread_mutex_lock");
2407 break;
2410 entry->idx = a->real_commits->ncommits;
2411 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2412 a->real_commits->ncommits++;
2414 if (*a->limiting) {
2415 err = match_commit(&limit_match, &id, commit,
2416 a->limit_regex);
2417 if (err)
2418 break;
2420 if (limit_match) {
2421 struct commit_queue_entry *matched;
2423 matched = alloc_commit_queue_entry(
2424 entry->commit, entry->id);
2425 if (matched == NULL) {
2426 err = got_error_from_errno(
2427 "alloc_commit_queue_entry");
2428 break;
2430 matched->commit = entry->commit;
2431 got_object_commit_retain(entry->commit);
2433 matched->idx = a->limit_commits->ncommits;
2434 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2435 matched, entry);
2436 a->limit_commits->ncommits++;
2440 * This is how we signal log_thread() that we
2441 * have found a match, and that it should be
2442 * counted as a new entry for the view.
2444 a->limit_match = limit_match;
2447 if (*a->searching == TOG_SEARCH_FORWARD &&
2448 !*a->search_next_done) {
2449 int have_match;
2450 err = match_commit(&have_match, &id, commit, a->regex);
2451 if (err)
2452 break;
2454 if (*a->limiting) {
2455 if (limit_match && have_match)
2456 *a->search_next_done =
2457 TOG_SEARCH_HAVE_MORE;
2458 } else if (have_match)
2459 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2462 errcode = pthread_mutex_unlock(&tog_mutex);
2463 if (errcode && err == NULL)
2464 err = got_error_set_errno(errcode,
2465 "pthread_mutex_unlock");
2466 if (err)
2467 break;
2468 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2470 return err;
2473 static void
2474 select_commit(struct tog_log_view_state *s)
2476 struct commit_queue_entry *entry;
2477 int ncommits = 0;
2479 entry = s->first_displayed_entry;
2480 while (entry) {
2481 if (ncommits == s->selected) {
2482 s->selected_entry = entry;
2483 break;
2485 entry = TAILQ_NEXT(entry, entry);
2486 ncommits++;
2490 static const struct got_error *
2491 draw_commits(struct tog_view *view)
2493 const struct got_error *err = NULL;
2494 struct tog_log_view_state *s = &view->state.log;
2495 struct commit_queue_entry *entry = s->selected_entry;
2496 int limit = view->nlines;
2497 int width;
2498 int ncommits, author_cols = 4;
2499 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2500 char *refs_str = NULL;
2501 wchar_t *wline;
2502 struct tog_color *tc;
2503 static const size_t date_display_cols = 12;
2505 if (view_is_hsplit_top(view))
2506 --limit; /* account for border */
2508 if (s->selected_entry &&
2509 !(view->searching && view->search_next_done == 0)) {
2510 struct got_reflist_head *refs;
2511 err = got_object_id_str(&id_str, s->selected_entry->id);
2512 if (err)
2513 return err;
2514 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2515 s->selected_entry->id);
2516 if (refs) {
2517 err = build_refs_str(&refs_str, refs,
2518 s->selected_entry->id, s->repo);
2519 if (err)
2520 goto done;
2524 if (s->thread_args.commits_needed == 0)
2525 halfdelay(10); /* disable fast refresh */
2527 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2528 if (asprintf(&ncommits_str, " [%d/%d] %s",
2529 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2530 (view->searching && !view->search_next_done) ?
2531 "searching..." : "loading...") == -1) {
2532 err = got_error_from_errno("asprintf");
2533 goto done;
2535 } else {
2536 const char *search_str = NULL;
2537 const char *limit_str = NULL;
2539 if (view->searching) {
2540 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2541 search_str = "no more matches";
2542 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2543 search_str = "no matches found";
2544 else if (!view->search_next_done)
2545 search_str = "searching...";
2548 if (s->limit_view && s->commits->ncommits == 0)
2549 limit_str = "no matches found";
2551 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2552 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2553 search_str ? search_str : (refs_str ? refs_str : ""),
2554 limit_str ? limit_str : "") == -1) {
2555 err = got_error_from_errno("asprintf");
2556 goto done;
2560 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2561 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2562 "........................................",
2563 s->in_repo_path, ncommits_str) == -1) {
2564 err = got_error_from_errno("asprintf");
2565 header = NULL;
2566 goto done;
2568 } else if (asprintf(&header, "commit %s%s",
2569 id_str ? id_str : "........................................",
2570 ncommits_str) == -1) {
2571 err = got_error_from_errno("asprintf");
2572 header = NULL;
2573 goto done;
2575 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2576 if (err)
2577 goto done;
2579 werase(view->window);
2581 if (view_needs_focus_indication(view))
2582 wstandout(view->window);
2583 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2584 if (tc)
2585 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2586 waddwstr(view->window, wline);
2587 while (width < view->ncols) {
2588 waddch(view->window, ' ');
2589 width++;
2591 if (tc)
2592 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2593 if (view_needs_focus_indication(view))
2594 wstandend(view->window);
2595 free(wline);
2596 if (limit <= 1)
2597 goto done;
2599 /* Grow author column size if necessary, and set view->maxx. */
2600 entry = s->first_displayed_entry;
2601 ncommits = 0;
2602 view->maxx = 0;
2603 while (entry) {
2604 struct got_commit_object *c = entry->commit;
2605 char *author, *eol, *msg, *msg0;
2606 wchar_t *wauthor, *wmsg;
2607 int width;
2608 if (ncommits >= limit - 1)
2609 break;
2610 if (s->use_committer)
2611 author = strdup(got_object_commit_get_committer(c));
2612 else
2613 author = strdup(got_object_commit_get_author(c));
2614 if (author == NULL) {
2615 err = got_error_from_errno("strdup");
2616 goto done;
2618 err = format_author(&wauthor, &width, author, COLS,
2619 date_display_cols);
2620 if (author_cols < width)
2621 author_cols = width;
2622 free(wauthor);
2623 free(author);
2624 if (err)
2625 goto done;
2626 err = got_object_commit_get_logmsg(&msg0, c);
2627 if (err)
2628 goto done;
2629 msg = msg0;
2630 while (*msg == '\n')
2631 ++msg;
2632 if ((eol = strchr(msg, '\n')))
2633 *eol = '\0';
2634 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2635 date_display_cols + author_cols, 0);
2636 if (err)
2637 goto done;
2638 view->maxx = MAX(view->maxx, width);
2639 free(msg0);
2640 free(wmsg);
2641 ncommits++;
2642 entry = TAILQ_NEXT(entry, entry);
2645 entry = s->first_displayed_entry;
2646 s->last_displayed_entry = s->first_displayed_entry;
2647 ncommits = 0;
2648 while (entry) {
2649 if (ncommits >= limit - 1)
2650 break;
2651 if (ncommits == s->selected)
2652 wstandout(view->window);
2653 err = draw_commit(view, entry->commit, entry->id,
2654 date_display_cols, author_cols);
2655 if (ncommits == s->selected)
2656 wstandend(view->window);
2657 if (err)
2658 goto done;
2659 ncommits++;
2660 s->last_displayed_entry = entry;
2661 entry = TAILQ_NEXT(entry, entry);
2664 view_border(view);
2665 done:
2666 free(id_str);
2667 free(refs_str);
2668 free(ncommits_str);
2669 free(header);
2670 return err;
2673 static void
2674 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2676 struct commit_queue_entry *entry;
2677 int nscrolled = 0;
2679 entry = TAILQ_FIRST(&s->commits->head);
2680 if (s->first_displayed_entry == entry)
2681 return;
2683 entry = s->first_displayed_entry;
2684 while (entry && nscrolled < maxscroll) {
2685 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2686 if (entry) {
2687 s->first_displayed_entry = entry;
2688 nscrolled++;
2693 static const struct got_error *
2694 trigger_log_thread(struct tog_view *view, int wait)
2696 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2697 int errcode;
2699 halfdelay(1); /* fast refresh while loading commits */
2701 while (!ta->log_complete && !tog_thread_error &&
2702 (ta->commits_needed > 0 || ta->load_all)) {
2703 /* Wake the log thread. */
2704 errcode = pthread_cond_signal(&ta->need_commits);
2705 if (errcode)
2706 return got_error_set_errno(errcode,
2707 "pthread_cond_signal");
2710 * The mutex will be released while the view loop waits
2711 * in wgetch(), at which time the log thread will run.
2713 if (!wait)
2714 break;
2716 /* Display progress update in log view. */
2717 show_log_view(view);
2718 update_panels();
2719 doupdate();
2721 /* Wait right here while next commit is being loaded. */
2722 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2723 if (errcode)
2724 return got_error_set_errno(errcode,
2725 "pthread_cond_wait");
2727 /* Display progress update in log view. */
2728 show_log_view(view);
2729 update_panels();
2730 doupdate();
2733 return NULL;
2736 static const struct got_error *
2737 request_log_commits(struct tog_view *view)
2739 struct tog_log_view_state *state = &view->state.log;
2740 const struct got_error *err = NULL;
2742 if (state->thread_args.log_complete)
2743 return NULL;
2745 state->thread_args.commits_needed += view->nscrolled;
2746 err = trigger_log_thread(view, 1);
2747 view->nscrolled = 0;
2749 return err;
2752 static const struct got_error *
2753 log_scroll_down(struct tog_view *view, int maxscroll)
2755 struct tog_log_view_state *s = &view->state.log;
2756 const struct got_error *err = NULL;
2757 struct commit_queue_entry *pentry;
2758 int nscrolled = 0, ncommits_needed;
2760 if (s->last_displayed_entry == NULL)
2761 return NULL;
2763 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2764 if (s->commits->ncommits < ncommits_needed &&
2765 !s->thread_args.log_complete) {
2767 * Ask the log thread for required amount of commits.
2769 s->thread_args.commits_needed +=
2770 ncommits_needed - s->commits->ncommits;
2771 err = trigger_log_thread(view, 1);
2772 if (err)
2773 return err;
2776 do {
2777 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2778 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2779 break;
2781 s->last_displayed_entry = pentry ?
2782 pentry : s->last_displayed_entry;
2784 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2785 if (pentry == NULL)
2786 break;
2787 s->first_displayed_entry = pentry;
2788 } while (++nscrolled < maxscroll);
2790 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2791 view->nscrolled += nscrolled;
2792 else
2793 view->nscrolled = 0;
2795 return err;
2798 static const struct got_error *
2799 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2800 struct got_commit_object *commit, struct got_object_id *commit_id,
2801 struct tog_view *log_view, struct got_repository *repo)
2803 const struct got_error *err;
2804 struct got_object_qid *parent_id;
2805 struct tog_view *diff_view;
2807 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2808 if (diff_view == NULL)
2809 return got_error_from_errno("view_open");
2811 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2812 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2813 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2814 if (err == NULL)
2815 *new_view = diff_view;
2816 return err;
2819 static const struct got_error *
2820 tree_view_visit_subtree(struct tog_tree_view_state *s,
2821 struct got_tree_object *subtree)
2823 struct tog_parent_tree *parent;
2825 parent = calloc(1, sizeof(*parent));
2826 if (parent == NULL)
2827 return got_error_from_errno("calloc");
2829 parent->tree = s->tree;
2830 parent->first_displayed_entry = s->first_displayed_entry;
2831 parent->selected_entry = s->selected_entry;
2832 parent->selected = s->selected;
2833 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2834 s->tree = subtree;
2835 s->selected = 0;
2836 s->first_displayed_entry = NULL;
2837 return NULL;
2840 static const struct got_error *
2841 tree_view_walk_path(struct tog_tree_view_state *s,
2842 struct got_commit_object *commit, const char *path)
2844 const struct got_error *err = NULL;
2845 struct got_tree_object *tree = NULL;
2846 const char *p;
2847 char *slash, *subpath = NULL;
2849 /* Walk the path and open corresponding tree objects. */
2850 p = path;
2851 while (*p) {
2852 struct got_tree_entry *te;
2853 struct got_object_id *tree_id;
2854 char *te_name;
2856 while (p[0] == '/')
2857 p++;
2859 /* Ensure the correct subtree entry is selected. */
2860 slash = strchr(p, '/');
2861 if (slash == NULL)
2862 te_name = strdup(p);
2863 else
2864 te_name = strndup(p, slash - p);
2865 if (te_name == NULL) {
2866 err = got_error_from_errno("strndup");
2867 break;
2869 te = got_object_tree_find_entry(s->tree, te_name);
2870 if (te == NULL) {
2871 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2872 free(te_name);
2873 break;
2875 free(te_name);
2876 s->first_displayed_entry = s->selected_entry = te;
2878 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2879 break; /* jump to this file's entry */
2881 slash = strchr(p, '/');
2882 if (slash)
2883 subpath = strndup(path, slash - path);
2884 else
2885 subpath = strdup(path);
2886 if (subpath == NULL) {
2887 err = got_error_from_errno("strdup");
2888 break;
2891 err = got_object_id_by_path(&tree_id, s->repo, commit,
2892 subpath);
2893 if (err)
2894 break;
2896 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2897 free(tree_id);
2898 if (err)
2899 break;
2901 err = tree_view_visit_subtree(s, tree);
2902 if (err) {
2903 got_object_tree_close(tree);
2904 break;
2906 if (slash == NULL)
2907 break;
2908 free(subpath);
2909 subpath = NULL;
2910 p = slash;
2913 free(subpath);
2914 return err;
2917 static const struct got_error *
2918 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2919 struct commit_queue_entry *entry, const char *path,
2920 const char *head_ref_name, struct got_repository *repo)
2922 const struct got_error *err = NULL;
2923 struct tog_tree_view_state *s;
2924 struct tog_view *tree_view;
2926 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2927 if (tree_view == NULL)
2928 return got_error_from_errno("view_open");
2930 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2931 if (err)
2932 return err;
2933 s = &tree_view->state.tree;
2935 *new_view = tree_view;
2937 if (got_path_is_root_dir(path))
2938 return NULL;
2940 return tree_view_walk_path(s, entry->commit, path);
2943 static const struct got_error *
2944 block_signals_used_by_main_thread(void)
2946 sigset_t sigset;
2947 int errcode;
2949 if (sigemptyset(&sigset) == -1)
2950 return got_error_from_errno("sigemptyset");
2952 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2953 if (sigaddset(&sigset, SIGWINCH) == -1)
2954 return got_error_from_errno("sigaddset");
2955 if (sigaddset(&sigset, SIGCONT) == -1)
2956 return got_error_from_errno("sigaddset");
2957 if (sigaddset(&sigset, SIGINT) == -1)
2958 return got_error_from_errno("sigaddset");
2959 if (sigaddset(&sigset, SIGTERM) == -1)
2960 return got_error_from_errno("sigaddset");
2962 /* ncurses handles SIGTSTP */
2963 if (sigaddset(&sigset, SIGTSTP) == -1)
2964 return got_error_from_errno("sigaddset");
2966 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2967 if (errcode)
2968 return got_error_set_errno(errcode, "pthread_sigmask");
2970 return NULL;
2973 static void *
2974 log_thread(void *arg)
2976 const struct got_error *err = NULL;
2977 int errcode = 0;
2978 struct tog_log_thread_args *a = arg;
2979 int done = 0;
2982 * Sync startup with main thread such that we begin our
2983 * work once view_input() has released the mutex.
2985 errcode = pthread_mutex_lock(&tog_mutex);
2986 if (errcode) {
2987 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2988 return (void *)err;
2991 err = block_signals_used_by_main_thread();
2992 if (err) {
2993 pthread_mutex_unlock(&tog_mutex);
2994 goto done;
2997 while (!done && !err && !tog_fatal_signal_received()) {
2998 errcode = pthread_mutex_unlock(&tog_mutex);
2999 if (errcode) {
3000 err = got_error_set_errno(errcode,
3001 "pthread_mutex_unlock");
3002 goto done;
3004 err = queue_commits(a);
3005 if (err) {
3006 if (err->code != GOT_ERR_ITER_COMPLETED)
3007 goto done;
3008 err = NULL;
3009 done = 1;
3010 } else if (a->commits_needed > 0 && !a->load_all) {
3011 if (*a->limiting) {
3012 if (a->limit_match)
3013 a->commits_needed--;
3014 } else
3015 a->commits_needed--;
3018 errcode = pthread_mutex_lock(&tog_mutex);
3019 if (errcode) {
3020 err = got_error_set_errno(errcode,
3021 "pthread_mutex_lock");
3022 goto done;
3023 } else if (*a->quit)
3024 done = 1;
3025 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3026 *a->first_displayed_entry =
3027 TAILQ_FIRST(&a->limit_commits->head);
3028 *a->selected_entry = *a->first_displayed_entry;
3029 } else if (*a->first_displayed_entry == NULL) {
3030 *a->first_displayed_entry =
3031 TAILQ_FIRST(&a->real_commits->head);
3032 *a->selected_entry = *a->first_displayed_entry;
3035 errcode = pthread_cond_signal(&a->commit_loaded);
3036 if (errcode) {
3037 err = got_error_set_errno(errcode,
3038 "pthread_cond_signal");
3039 pthread_mutex_unlock(&tog_mutex);
3040 goto done;
3043 if (done)
3044 a->commits_needed = 0;
3045 else {
3046 if (a->commits_needed == 0 && !a->load_all) {
3047 errcode = pthread_cond_wait(&a->need_commits,
3048 &tog_mutex);
3049 if (errcode) {
3050 err = got_error_set_errno(errcode,
3051 "pthread_cond_wait");
3052 pthread_mutex_unlock(&tog_mutex);
3053 goto done;
3055 if (*a->quit)
3056 done = 1;
3060 a->log_complete = 1;
3061 errcode = pthread_mutex_unlock(&tog_mutex);
3062 if (errcode)
3063 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3064 done:
3065 if (err) {
3066 tog_thread_error = 1;
3067 pthread_cond_signal(&a->commit_loaded);
3069 return (void *)err;
3072 static const struct got_error *
3073 stop_log_thread(struct tog_log_view_state *s)
3075 const struct got_error *err = NULL, *thread_err = NULL;
3076 int errcode;
3078 if (s->thread) {
3079 s->quit = 1;
3080 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3081 if (errcode)
3082 return got_error_set_errno(errcode,
3083 "pthread_cond_signal");
3084 errcode = pthread_mutex_unlock(&tog_mutex);
3085 if (errcode)
3086 return got_error_set_errno(errcode,
3087 "pthread_mutex_unlock");
3088 errcode = pthread_join(s->thread, (void **)&thread_err);
3089 if (errcode)
3090 return got_error_set_errno(errcode, "pthread_join");
3091 errcode = pthread_mutex_lock(&tog_mutex);
3092 if (errcode)
3093 return got_error_set_errno(errcode,
3094 "pthread_mutex_lock");
3095 s->thread = NULL;
3098 if (s->thread_args.repo) {
3099 err = got_repo_close(s->thread_args.repo);
3100 s->thread_args.repo = NULL;
3103 if (s->thread_args.pack_fds) {
3104 const struct got_error *pack_err =
3105 got_repo_pack_fds_close(s->thread_args.pack_fds);
3106 if (err == NULL)
3107 err = pack_err;
3108 s->thread_args.pack_fds = NULL;
3111 if (s->thread_args.graph) {
3112 got_commit_graph_close(s->thread_args.graph);
3113 s->thread_args.graph = NULL;
3116 return err ? err : thread_err;
3119 static const struct got_error *
3120 close_log_view(struct tog_view *view)
3122 const struct got_error *err = NULL;
3123 struct tog_log_view_state *s = &view->state.log;
3124 int errcode;
3126 err = stop_log_thread(s);
3128 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3129 if (errcode && err == NULL)
3130 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3132 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3133 if (errcode && err == NULL)
3134 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3136 free_commits(&s->limit_commits);
3137 free_commits(&s->real_commits);
3138 free(s->in_repo_path);
3139 s->in_repo_path = NULL;
3140 free(s->start_id);
3141 s->start_id = NULL;
3142 free(s->head_ref_name);
3143 s->head_ref_name = NULL;
3144 return err;
3148 * We use two queues to implement the limit feature: first consists of
3149 * commits matching the current limit_regex; second is the real queue
3150 * of all known commits (real_commits). When the user starts limiting,
3151 * we swap queues such that all movement and displaying functionality
3152 * works with very slight change.
3154 static const struct got_error *
3155 limit_log_view(struct tog_view *view)
3157 struct tog_log_view_state *s = &view->state.log;
3158 struct commit_queue_entry *entry;
3159 struct tog_view *v = view;
3160 const struct got_error *err = NULL;
3161 char pattern[1024];
3162 int ret;
3164 if (view_is_hsplit_top(view))
3165 v = view->child;
3166 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3167 v = view->parent;
3169 /* Get the pattern */
3170 wmove(v->window, v->nlines - 1, 0);
3171 wclrtoeol(v->window);
3172 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3173 nodelay(v->window, FALSE);
3174 nocbreak();
3175 echo();
3176 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3177 cbreak();
3178 noecho();
3179 nodelay(v->window, TRUE);
3180 if (ret == ERR)
3181 return NULL;
3183 if (*pattern == '\0') {
3185 * Safety measure for the situation where the user
3186 * resets limit without previously limiting anything.
3188 if (!s->limit_view)
3189 return NULL;
3192 * User could have pressed Ctrl+L, which refreshed the
3193 * commit queues, it means we can't save previously
3194 * (before limit took place) displayed entries,
3195 * because they would point to already free'ed memory,
3196 * so we are forced to always select first entry of
3197 * the queue.
3199 s->commits = &s->real_commits;
3200 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3201 s->selected_entry = s->first_displayed_entry;
3202 s->selected = 0;
3203 s->limit_view = 0;
3205 return NULL;
3208 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3209 return NULL;
3211 s->limit_view = 1;
3213 /* Clear the screen while loading limit view */
3214 s->first_displayed_entry = NULL;
3215 s->last_displayed_entry = NULL;
3216 s->selected_entry = NULL;
3217 s->commits = &s->limit_commits;
3219 /* Prepare limit queue for new search */
3220 free_commits(&s->limit_commits);
3221 s->limit_commits.ncommits = 0;
3223 /* First process commits, which are in queue already */
3224 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3225 int have_match = 0;
3227 err = match_commit(&have_match, entry->id,
3228 entry->commit, &s->limit_regex);
3229 if (err)
3230 return err;
3232 if (have_match) {
3233 struct commit_queue_entry *matched;
3235 matched = alloc_commit_queue_entry(entry->commit,
3236 entry->id);
3237 if (matched == NULL) {
3238 err = got_error_from_errno(
3239 "alloc_commit_queue_entry");
3240 break;
3242 matched->commit = entry->commit;
3243 got_object_commit_retain(entry->commit);
3245 matched->idx = s->limit_commits.ncommits;
3246 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3247 matched, entry);
3248 s->limit_commits.ncommits++;
3252 /* Second process all the commits, until we fill the screen */
3253 if (s->limit_commits.ncommits < view->nlines - 1 &&
3254 !s->thread_args.log_complete) {
3255 s->thread_args.commits_needed +=
3256 view->nlines - s->limit_commits.ncommits - 1;
3257 err = trigger_log_thread(view, 1);
3258 if (err)
3259 return err;
3262 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3263 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3264 s->selected = 0;
3266 return NULL;
3269 static const struct got_error *
3270 search_start_log_view(struct tog_view *view)
3272 struct tog_log_view_state *s = &view->state.log;
3274 s->matched_entry = NULL;
3275 s->search_entry = NULL;
3276 return NULL;
3279 static const struct got_error *
3280 search_next_log_view(struct tog_view *view)
3282 const struct got_error *err = NULL;
3283 struct tog_log_view_state *s = &view->state.log;
3284 struct commit_queue_entry *entry;
3286 /* Display progress update in log view. */
3287 show_log_view(view);
3288 update_panels();
3289 doupdate();
3291 if (s->search_entry) {
3292 int errcode, ch;
3293 errcode = pthread_mutex_unlock(&tog_mutex);
3294 if (errcode)
3295 return got_error_set_errno(errcode,
3296 "pthread_mutex_unlock");
3297 ch = wgetch(view->window);
3298 errcode = pthread_mutex_lock(&tog_mutex);
3299 if (errcode)
3300 return got_error_set_errno(errcode,
3301 "pthread_mutex_lock");
3302 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3303 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3304 return NULL;
3306 if (view->searching == TOG_SEARCH_FORWARD)
3307 entry = TAILQ_NEXT(s->search_entry, entry);
3308 else
3309 entry = TAILQ_PREV(s->search_entry,
3310 commit_queue_head, entry);
3311 } else if (s->matched_entry) {
3313 * If the user has moved the cursor after we hit a match,
3314 * the position from where we should continue searching
3315 * might have changed.
3317 if (view->searching == TOG_SEARCH_FORWARD)
3318 entry = TAILQ_NEXT(s->selected_entry, entry);
3319 else
3320 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3321 entry);
3322 } else {
3323 entry = s->selected_entry;
3326 while (1) {
3327 int have_match = 0;
3329 if (entry == NULL) {
3330 if (s->thread_args.log_complete ||
3331 view->searching == TOG_SEARCH_BACKWARD) {
3332 view->search_next_done =
3333 (s->matched_entry == NULL ?
3334 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3335 s->search_entry = NULL;
3336 return NULL;
3339 * Poke the log thread for more commits and return,
3340 * allowing the main loop to make progress. Search
3341 * will resume at s->search_entry once we come back.
3343 s->thread_args.commits_needed++;
3344 return trigger_log_thread(view, 0);
3347 err = match_commit(&have_match, entry->id, entry->commit,
3348 &view->regex);
3349 if (err)
3350 break;
3351 if (have_match) {
3352 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3353 s->matched_entry = entry;
3354 break;
3357 s->search_entry = entry;
3358 if (view->searching == TOG_SEARCH_FORWARD)
3359 entry = TAILQ_NEXT(entry, entry);
3360 else
3361 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3364 if (s->matched_entry) {
3365 int cur = s->selected_entry->idx;
3366 while (cur < s->matched_entry->idx) {
3367 err = input_log_view(NULL, view, KEY_DOWN);
3368 if (err)
3369 return err;
3370 cur++;
3372 while (cur > s->matched_entry->idx) {
3373 err = input_log_view(NULL, view, KEY_UP);
3374 if (err)
3375 return err;
3376 cur--;
3380 s->search_entry = NULL;
3382 return NULL;
3385 static const struct got_error *
3386 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3387 struct got_repository *repo, const char *head_ref_name,
3388 const char *in_repo_path, int log_branches)
3390 const struct got_error *err = NULL;
3391 struct tog_log_view_state *s = &view->state.log;
3392 struct got_repository *thread_repo = NULL;
3393 struct got_commit_graph *thread_graph = NULL;
3394 int errcode;
3396 if (in_repo_path != s->in_repo_path) {
3397 free(s->in_repo_path);
3398 s->in_repo_path = strdup(in_repo_path);
3399 if (s->in_repo_path == NULL)
3400 return got_error_from_errno("strdup");
3403 /* The commit queue only contains commits being displayed. */
3404 TAILQ_INIT(&s->real_commits.head);
3405 s->real_commits.ncommits = 0;
3406 s->commits = &s->real_commits;
3408 TAILQ_INIT(&s->limit_commits.head);
3409 s->limit_view = 0;
3410 s->limit_commits.ncommits = 0;
3412 s->repo = repo;
3413 if (head_ref_name) {
3414 s->head_ref_name = strdup(head_ref_name);
3415 if (s->head_ref_name == NULL) {
3416 err = got_error_from_errno("strdup");
3417 goto done;
3420 s->start_id = got_object_id_dup(start_id);
3421 if (s->start_id == NULL) {
3422 err = got_error_from_errno("got_object_id_dup");
3423 goto done;
3425 s->log_branches = log_branches;
3426 s->use_committer = 1;
3428 STAILQ_INIT(&s->colors);
3429 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3430 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3431 get_color_value("TOG_COLOR_COMMIT"));
3432 if (err)
3433 goto done;
3434 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3435 get_color_value("TOG_COLOR_AUTHOR"));
3436 if (err) {
3437 free_colors(&s->colors);
3438 goto done;
3440 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3441 get_color_value("TOG_COLOR_DATE"));
3442 if (err) {
3443 free_colors(&s->colors);
3444 goto done;
3448 view->show = show_log_view;
3449 view->input = input_log_view;
3450 view->resize = resize_log_view;
3451 view->close = close_log_view;
3452 view->search_start = search_start_log_view;
3453 view->search_next = search_next_log_view;
3455 if (s->thread_args.pack_fds == NULL) {
3456 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3457 if (err)
3458 goto done;
3460 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3461 s->thread_args.pack_fds);
3462 if (err)
3463 goto done;
3464 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3465 !s->log_branches);
3466 if (err)
3467 goto done;
3468 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3469 s->repo, NULL, NULL);
3470 if (err)
3471 goto done;
3473 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3474 if (errcode) {
3475 err = got_error_set_errno(errcode, "pthread_cond_init");
3476 goto done;
3478 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3479 if (errcode) {
3480 err = got_error_set_errno(errcode, "pthread_cond_init");
3481 goto done;
3484 s->thread_args.commits_needed = view->nlines;
3485 s->thread_args.graph = thread_graph;
3486 s->thread_args.real_commits = &s->real_commits;
3487 s->thread_args.limit_commits = &s->limit_commits;
3488 s->thread_args.in_repo_path = s->in_repo_path;
3489 s->thread_args.start_id = s->start_id;
3490 s->thread_args.repo = thread_repo;
3491 s->thread_args.log_complete = 0;
3492 s->thread_args.quit = &s->quit;
3493 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3494 s->thread_args.selected_entry = &s->selected_entry;
3495 s->thread_args.searching = &view->searching;
3496 s->thread_args.search_next_done = &view->search_next_done;
3497 s->thread_args.regex = &view->regex;
3498 s->thread_args.limiting = &s->limit_view;
3499 s->thread_args.limit_regex = &s->limit_regex;
3500 s->thread_args.limit_commits = &s->limit_commits;
3501 done:
3502 if (err)
3503 close_log_view(view);
3504 return err;
3507 static const struct got_error *
3508 show_log_view(struct tog_view *view)
3510 const struct got_error *err;
3511 struct tog_log_view_state *s = &view->state.log;
3513 if (s->thread == NULL) {
3514 int errcode = pthread_create(&s->thread, NULL, log_thread,
3515 &s->thread_args);
3516 if (errcode)
3517 return got_error_set_errno(errcode, "pthread_create");
3518 if (s->thread_args.commits_needed > 0) {
3519 err = trigger_log_thread(view, 1);
3520 if (err)
3521 return err;
3525 return draw_commits(view);
3528 static void
3529 log_move_cursor_up(struct tog_view *view, int page, int home)
3531 struct tog_log_view_state *s = &view->state.log;
3533 if (s->first_displayed_entry == NULL)
3534 return;
3535 if (s->selected_entry->idx == 0)
3536 view->count = 0;
3538 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3539 || home)
3540 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3542 if (!page && !home && s->selected > 0)
3543 --s->selected;
3544 else
3545 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3547 select_commit(s);
3548 return;
3551 static const struct got_error *
3552 log_move_cursor_down(struct tog_view *view, int page)
3554 struct tog_log_view_state *s = &view->state.log;
3555 const struct got_error *err = NULL;
3556 int eos = view->nlines - 2;
3558 if (s->first_displayed_entry == NULL)
3559 return NULL;
3561 if (s->thread_args.log_complete &&
3562 s->selected_entry->idx >= s->commits->ncommits - 1)
3563 return NULL;
3565 if (view_is_hsplit_top(view))
3566 --eos; /* border consumes the last line */
3568 if (!page) {
3569 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3570 ++s->selected;
3571 else
3572 err = log_scroll_down(view, 1);
3573 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3574 struct commit_queue_entry *entry;
3575 int n;
3577 s->selected = 0;
3578 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3579 s->last_displayed_entry = entry;
3580 for (n = 0; n <= eos; n++) {
3581 if (entry == NULL)
3582 break;
3583 s->first_displayed_entry = entry;
3584 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3586 if (n > 0)
3587 s->selected = n - 1;
3588 } else {
3589 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3590 s->thread_args.log_complete)
3591 s->selected += MIN(page,
3592 s->commits->ncommits - s->selected_entry->idx - 1);
3593 else
3594 err = log_scroll_down(view, page);
3596 if (err)
3597 return err;
3600 * We might necessarily overshoot in horizontal
3601 * splits; if so, select the last displayed commit.
3603 if (s->first_displayed_entry && s->last_displayed_entry) {
3604 s->selected = MIN(s->selected,
3605 s->last_displayed_entry->idx -
3606 s->first_displayed_entry->idx);
3609 select_commit(s);
3611 if (s->thread_args.log_complete &&
3612 s->selected_entry->idx == s->commits->ncommits - 1)
3613 view->count = 0;
3615 return NULL;
3618 static void
3619 view_get_split(struct tog_view *view, int *y, int *x)
3621 *x = 0;
3622 *y = 0;
3624 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3625 if (view->child && view->child->resized_y)
3626 *y = view->child->resized_y;
3627 else if (view->resized_y)
3628 *y = view->resized_y;
3629 else
3630 *y = view_split_begin_y(view->lines);
3631 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3632 if (view->child && view->child->resized_x)
3633 *x = view->child->resized_x;
3634 else if (view->resized_x)
3635 *x = view->resized_x;
3636 else
3637 *x = view_split_begin_x(view->begin_x);
3641 /* Split view horizontally at y and offset view->state->selected line. */
3642 static const struct got_error *
3643 view_init_hsplit(struct tog_view *view, int y)
3645 const struct got_error *err = NULL;
3647 view->nlines = y;
3648 view->ncols = COLS;
3649 err = view_resize(view);
3650 if (err)
3651 return err;
3653 err = offset_selection_down(view);
3655 return err;
3658 static const struct got_error *
3659 log_goto_line(struct tog_view *view, int nlines)
3661 const struct got_error *err = NULL;
3662 struct tog_log_view_state *s = &view->state.log;
3663 int g, idx = s->selected_entry->idx;
3665 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3666 return NULL;
3668 g = view->gline;
3669 view->gline = 0;
3671 if (g >= s->first_displayed_entry->idx + 1 &&
3672 g <= s->last_displayed_entry->idx + 1 &&
3673 g - s->first_displayed_entry->idx - 1 < nlines) {
3674 s->selected = g - s->first_displayed_entry->idx - 1;
3675 select_commit(s);
3676 return NULL;
3679 if (idx + 1 < g) {
3680 err = log_move_cursor_down(view, g - idx - 1);
3681 if (!err && g > s->selected_entry->idx + 1)
3682 err = log_move_cursor_down(view,
3683 g - s->first_displayed_entry->idx - 1);
3684 if (err)
3685 return err;
3686 } else if (idx + 1 > g)
3687 log_move_cursor_up(view, idx - g + 1, 0);
3689 if (g < nlines && s->first_displayed_entry->idx == 0)
3690 s->selected = g - 1;
3692 select_commit(s);
3693 return NULL;
3697 static void
3698 horizontal_scroll_input(struct tog_view *view, int ch)
3701 switch (ch) {
3702 case KEY_LEFT:
3703 case 'h':
3704 view->x -= MIN(view->x, 2);
3705 if (view->x <= 0)
3706 view->count = 0;
3707 break;
3708 case KEY_RIGHT:
3709 case 'l':
3710 if (view->x + view->ncols / 2 < view->maxx)
3711 view->x += 2;
3712 else
3713 view->count = 0;
3714 break;
3715 case '0':
3716 view->x = 0;
3717 break;
3718 case '$':
3719 view->x = MAX(view->maxx - view->ncols / 2, 0);
3720 view->count = 0;
3721 break;
3722 default:
3723 break;
3727 static const struct got_error *
3728 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3730 const struct got_error *err = NULL;
3731 struct tog_log_view_state *s = &view->state.log;
3732 int eos, nscroll;
3734 if (s->thread_args.load_all) {
3735 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3736 s->thread_args.load_all = 0;
3737 else if (s->thread_args.log_complete) {
3738 err = log_move_cursor_down(view, s->commits->ncommits);
3739 s->thread_args.load_all = 0;
3741 if (err)
3742 return err;
3745 eos = nscroll = view->nlines - 1;
3746 if (view_is_hsplit_top(view))
3747 --eos; /* border */
3749 if (view->gline)
3750 return log_goto_line(view, eos);
3752 switch (ch) {
3753 case '&':
3754 err = limit_log_view(view);
3755 break;
3756 case 'q':
3757 s->quit = 1;
3758 break;
3759 case '0':
3760 case '$':
3761 case KEY_RIGHT:
3762 case 'l':
3763 case KEY_LEFT:
3764 case 'h':
3765 horizontal_scroll_input(view, ch);
3766 break;
3767 case 'k':
3768 case KEY_UP:
3769 case '<':
3770 case ',':
3771 case CTRL('p'):
3772 log_move_cursor_up(view, 0, 0);
3773 break;
3774 case 'g':
3775 case '=':
3776 case KEY_HOME:
3777 log_move_cursor_up(view, 0, 1);
3778 view->count = 0;
3779 break;
3780 case CTRL('u'):
3781 case 'u':
3782 nscroll /= 2;
3783 /* FALL THROUGH */
3784 case KEY_PPAGE:
3785 case CTRL('b'):
3786 case 'b':
3787 log_move_cursor_up(view, nscroll, 0);
3788 break;
3789 case 'j':
3790 case KEY_DOWN:
3791 case '>':
3792 case '.':
3793 case CTRL('n'):
3794 err = log_move_cursor_down(view, 0);
3795 break;
3796 case '@':
3797 s->use_committer = !s->use_committer;
3798 view->action = s->use_committer ?
3799 "show committer" : "show commit author";
3800 break;
3801 case 'G':
3802 case '*':
3803 case KEY_END: {
3804 /* We don't know yet how many commits, so we're forced to
3805 * traverse them all. */
3806 view->count = 0;
3807 s->thread_args.load_all = 1;
3808 if (!s->thread_args.log_complete)
3809 return trigger_log_thread(view, 0);
3810 err = log_move_cursor_down(view, s->commits->ncommits);
3811 s->thread_args.load_all = 0;
3812 break;
3814 case CTRL('d'):
3815 case 'd':
3816 nscroll /= 2;
3817 /* FALL THROUGH */
3818 case KEY_NPAGE:
3819 case CTRL('f'):
3820 case 'f':
3821 case ' ':
3822 err = log_move_cursor_down(view, nscroll);
3823 break;
3824 case KEY_RESIZE:
3825 if (s->selected > view->nlines - 2)
3826 s->selected = view->nlines - 2;
3827 if (s->selected > s->commits->ncommits - 1)
3828 s->selected = s->commits->ncommits - 1;
3829 select_commit(s);
3830 if (s->commits->ncommits < view->nlines - 1 &&
3831 !s->thread_args.log_complete) {
3832 s->thread_args.commits_needed += (view->nlines - 1) -
3833 s->commits->ncommits;
3834 err = trigger_log_thread(view, 1);
3836 break;
3837 case KEY_ENTER:
3838 case '\r':
3839 view->count = 0;
3840 if (s->selected_entry == NULL)
3841 break;
3842 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3843 break;
3844 case 'T':
3845 view->count = 0;
3846 if (s->selected_entry == NULL)
3847 break;
3848 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3849 break;
3850 case KEY_BACKSPACE:
3851 case CTRL('l'):
3852 case 'B':
3853 view->count = 0;
3854 if (ch == KEY_BACKSPACE &&
3855 got_path_is_root_dir(s->in_repo_path))
3856 break;
3857 err = stop_log_thread(s);
3858 if (err)
3859 return err;
3860 if (ch == KEY_BACKSPACE) {
3861 char *parent_path;
3862 err = got_path_dirname(&parent_path, s->in_repo_path);
3863 if (err)
3864 return err;
3865 free(s->in_repo_path);
3866 s->in_repo_path = parent_path;
3867 s->thread_args.in_repo_path = s->in_repo_path;
3868 } else if (ch == CTRL('l')) {
3869 struct got_object_id *start_id;
3870 err = got_repo_match_object_id(&start_id, NULL,
3871 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3872 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3873 if (err) {
3874 if (s->head_ref_name == NULL ||
3875 err->code != GOT_ERR_NOT_REF)
3876 return err;
3877 /* Try to cope with deleted references. */
3878 free(s->head_ref_name);
3879 s->head_ref_name = NULL;
3880 err = got_repo_match_object_id(&start_id,
3881 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
3882 &tog_refs, s->repo);
3883 if (err)
3884 return err;
3886 free(s->start_id);
3887 s->start_id = start_id;
3888 s->thread_args.start_id = s->start_id;
3889 } else /* 'B' */
3890 s->log_branches = !s->log_branches;
3892 if (s->thread_args.pack_fds == NULL) {
3893 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3894 if (err)
3895 return err;
3897 err = got_repo_open(&s->thread_args.repo,
3898 got_repo_get_path(s->repo), NULL,
3899 s->thread_args.pack_fds);
3900 if (err)
3901 return err;
3902 tog_free_refs();
3903 err = tog_load_refs(s->repo, 0);
3904 if (err)
3905 return err;
3906 err = got_commit_graph_open(&s->thread_args.graph,
3907 s->in_repo_path, !s->log_branches);
3908 if (err)
3909 return err;
3910 err = got_commit_graph_iter_start(s->thread_args.graph,
3911 s->start_id, s->repo, NULL, NULL);
3912 if (err)
3913 return err;
3914 free_commits(&s->real_commits);
3915 free_commits(&s->limit_commits);
3916 s->first_displayed_entry = NULL;
3917 s->last_displayed_entry = NULL;
3918 s->selected_entry = NULL;
3919 s->selected = 0;
3920 s->thread_args.log_complete = 0;
3921 s->quit = 0;
3922 s->thread_args.commits_needed = view->lines;
3923 s->matched_entry = NULL;
3924 s->search_entry = NULL;
3925 view->offset = 0;
3926 break;
3927 case 'R':
3928 view->count = 0;
3929 err = view_request_new(new_view, view, TOG_VIEW_REF);
3930 break;
3931 default:
3932 view->count = 0;
3933 break;
3936 return err;
3939 static const struct got_error *
3940 apply_unveil(const char *repo_path, const char *worktree_path)
3942 const struct got_error *error;
3944 #ifdef PROFILE
3945 if (unveil("gmon.out", "rwc") != 0)
3946 return got_error_from_errno2("unveil", "gmon.out");
3947 #endif
3948 if (repo_path && unveil(repo_path, "r") != 0)
3949 return got_error_from_errno2("unveil", repo_path);
3951 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3952 return got_error_from_errno2("unveil", worktree_path);
3954 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3955 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3957 error = got_privsep_unveil_exec_helpers();
3958 if (error != NULL)
3959 return error;
3961 if (unveil(NULL, NULL) != 0)
3962 return got_error_from_errno("unveil");
3964 return NULL;
3967 static void
3968 init_curses(void)
3971 * Override default signal handlers before starting ncurses.
3972 * This should prevent ncurses from installing its own
3973 * broken cleanup() signal handler.
3975 signal(SIGWINCH, tog_sigwinch);
3976 signal(SIGPIPE, tog_sigpipe);
3977 signal(SIGCONT, tog_sigcont);
3978 signal(SIGINT, tog_sigint);
3979 signal(SIGTERM, tog_sigterm);
3981 initscr();
3982 cbreak();
3983 halfdelay(1); /* Do fast refresh while initial view is loading. */
3984 noecho();
3985 nonl();
3986 intrflush(stdscr, FALSE);
3987 keypad(stdscr, TRUE);
3988 curs_set(0);
3989 if (getenv("TOG_COLORS") != NULL) {
3990 start_color();
3991 use_default_colors();
3995 static const struct got_error *
3996 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3997 struct got_repository *repo, struct got_worktree *worktree)
3999 const struct got_error *err = NULL;
4001 if (argc == 0) {
4002 *in_repo_path = strdup("/");
4003 if (*in_repo_path == NULL)
4004 return got_error_from_errno("strdup");
4005 return NULL;
4008 if (worktree) {
4009 const char *prefix = got_worktree_get_path_prefix(worktree);
4010 char *p;
4012 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4013 if (err)
4014 return err;
4015 if (asprintf(in_repo_path, "%s%s%s", prefix,
4016 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4017 p) == -1) {
4018 err = got_error_from_errno("asprintf");
4019 *in_repo_path = NULL;
4021 free(p);
4022 } else
4023 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4025 return err;
4028 static const struct got_error *
4029 cmd_log(int argc, char *argv[])
4031 const struct got_error *error;
4032 struct got_repository *repo = NULL;
4033 struct got_worktree *worktree = NULL;
4034 struct got_object_id *start_id = NULL;
4035 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4036 char *start_commit = NULL, *label = NULL;
4037 struct got_reference *ref = NULL;
4038 const char *head_ref_name = NULL;
4039 int ch, log_branches = 0;
4040 struct tog_view *view;
4041 int *pack_fds = NULL;
4043 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4044 switch (ch) {
4045 case 'b':
4046 log_branches = 1;
4047 break;
4048 case 'c':
4049 start_commit = optarg;
4050 break;
4051 case 'r':
4052 repo_path = realpath(optarg, NULL);
4053 if (repo_path == NULL)
4054 return got_error_from_errno2("realpath",
4055 optarg);
4056 break;
4057 default:
4058 usage_log();
4059 /* NOTREACHED */
4063 argc -= optind;
4064 argv += optind;
4066 if (argc > 1)
4067 usage_log();
4069 error = got_repo_pack_fds_open(&pack_fds);
4070 if (error != NULL)
4071 goto done;
4073 if (repo_path == NULL) {
4074 cwd = getcwd(NULL, 0);
4075 if (cwd == NULL)
4076 return got_error_from_errno("getcwd");
4077 error = got_worktree_open(&worktree, cwd);
4078 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4079 goto done;
4080 if (worktree)
4081 repo_path =
4082 strdup(got_worktree_get_repo_path(worktree));
4083 else
4084 repo_path = strdup(cwd);
4085 if (repo_path == NULL) {
4086 error = got_error_from_errno("strdup");
4087 goto done;
4091 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4092 if (error != NULL)
4093 goto done;
4095 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4096 repo, worktree);
4097 if (error)
4098 goto done;
4100 init_curses();
4102 error = apply_unveil(got_repo_get_path(repo),
4103 worktree ? got_worktree_get_root_path(worktree) : NULL);
4104 if (error)
4105 goto done;
4107 /* already loaded by tog_log_with_path()? */
4108 if (TAILQ_EMPTY(&tog_refs)) {
4109 error = tog_load_refs(repo, 0);
4110 if (error)
4111 goto done;
4114 if (start_commit == NULL) {
4115 error = got_repo_match_object_id(&start_id, &label,
4116 worktree ? got_worktree_get_head_ref_name(worktree) :
4117 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4118 if (error)
4119 goto done;
4120 head_ref_name = label;
4121 } else {
4122 error = got_ref_open(&ref, repo, start_commit, 0);
4123 if (error == NULL)
4124 head_ref_name = got_ref_get_name(ref);
4125 else if (error->code != GOT_ERR_NOT_REF)
4126 goto done;
4127 error = got_repo_match_object_id(&start_id, NULL,
4128 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4129 if (error)
4130 goto done;
4133 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4134 if (view == NULL) {
4135 error = got_error_from_errno("view_open");
4136 goto done;
4138 error = open_log_view(view, start_id, repo, head_ref_name,
4139 in_repo_path, log_branches);
4140 if (error)
4141 goto done;
4142 if (worktree) {
4143 /* Release work tree lock. */
4144 got_worktree_close(worktree);
4145 worktree = NULL;
4147 error = view_loop(view);
4148 done:
4149 free(in_repo_path);
4150 free(repo_path);
4151 free(cwd);
4152 free(start_id);
4153 free(label);
4154 if (ref)
4155 got_ref_close(ref);
4156 if (repo) {
4157 const struct got_error *close_err = got_repo_close(repo);
4158 if (error == NULL)
4159 error = close_err;
4161 if (worktree)
4162 got_worktree_close(worktree);
4163 if (pack_fds) {
4164 const struct got_error *pack_err =
4165 got_repo_pack_fds_close(pack_fds);
4166 if (error == NULL)
4167 error = pack_err;
4169 tog_free_refs();
4170 return error;
4173 __dead static void
4174 usage_diff(void)
4176 endwin();
4177 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4178 "object1 object2\n", getprogname());
4179 exit(1);
4182 static int
4183 match_line(const char *line, regex_t *regex, size_t nmatch,
4184 regmatch_t *regmatch)
4186 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4189 static struct tog_color *
4190 match_color(struct tog_colors *colors, const char *line)
4192 struct tog_color *tc = NULL;
4194 STAILQ_FOREACH(tc, colors, entry) {
4195 if (match_line(line, &tc->regex, 0, NULL))
4196 return tc;
4199 return NULL;
4202 static const struct got_error *
4203 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4204 WINDOW *window, int skipcol, regmatch_t *regmatch)
4206 const struct got_error *err = NULL;
4207 char *exstr = NULL;
4208 wchar_t *wline = NULL;
4209 int rme, rms, n, width, scrollx;
4210 int width0 = 0, width1 = 0, width2 = 0;
4211 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4213 *wtotal = 0;
4215 rms = regmatch->rm_so;
4216 rme = regmatch->rm_eo;
4218 err = expand_tab(&exstr, line);
4219 if (err)
4220 return err;
4222 /* Split the line into 3 segments, according to match offsets. */
4223 seg0 = strndup(exstr, rms);
4224 if (seg0 == NULL) {
4225 err = got_error_from_errno("strndup");
4226 goto done;
4228 seg1 = strndup(exstr + rms, rme - rms);
4229 if (seg1 == NULL) {
4230 err = got_error_from_errno("strndup");
4231 goto done;
4233 seg2 = strdup(exstr + rme);
4234 if (seg2 == NULL) {
4235 err = got_error_from_errno("strndup");
4236 goto done;
4239 /* draw up to matched token if we haven't scrolled past it */
4240 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4241 col_tab_align, 1);
4242 if (err)
4243 goto done;
4244 n = MAX(width0 - skipcol, 0);
4245 if (n) {
4246 free(wline);
4247 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4248 wlimit, col_tab_align, 1);
4249 if (err)
4250 goto done;
4251 waddwstr(window, &wline[scrollx]);
4252 wlimit -= width;
4253 *wtotal += width;
4256 if (wlimit > 0) {
4257 int i = 0, w = 0;
4258 size_t wlen;
4260 free(wline);
4261 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4262 col_tab_align, 1);
4263 if (err)
4264 goto done;
4265 wlen = wcslen(wline);
4266 while (i < wlen) {
4267 width = wcwidth(wline[i]);
4268 if (width == -1) {
4269 /* should not happen, tabs are expanded */
4270 err = got_error(GOT_ERR_RANGE);
4271 goto done;
4273 if (width0 + w + width > skipcol)
4274 break;
4275 w += width;
4276 i++;
4278 /* draw (visible part of) matched token (if scrolled into it) */
4279 if (width1 - w > 0) {
4280 wattron(window, A_STANDOUT);
4281 waddwstr(window, &wline[i]);
4282 wattroff(window, A_STANDOUT);
4283 wlimit -= (width1 - w);
4284 *wtotal += (width1 - w);
4288 if (wlimit > 0) { /* draw rest of line */
4289 free(wline);
4290 if (skipcol > width0 + width1) {
4291 err = format_line(&wline, &width2, &scrollx, seg2,
4292 skipcol - (width0 + width1), wlimit,
4293 col_tab_align, 1);
4294 if (err)
4295 goto done;
4296 waddwstr(window, &wline[scrollx]);
4297 } else {
4298 err = format_line(&wline, &width2, NULL, seg2, 0,
4299 wlimit, col_tab_align, 1);
4300 if (err)
4301 goto done;
4302 waddwstr(window, wline);
4304 *wtotal += width2;
4306 done:
4307 free(wline);
4308 free(exstr);
4309 free(seg0);
4310 free(seg1);
4311 free(seg2);
4312 return err;
4315 static int
4316 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4318 FILE *f = NULL;
4319 int *eof, *first, *selected;
4321 if (view->type == TOG_VIEW_DIFF) {
4322 struct tog_diff_view_state *s = &view->state.diff;
4324 first = &s->first_displayed_line;
4325 selected = first;
4326 eof = &s->eof;
4327 f = s->f;
4328 } else if (view->type == TOG_VIEW_HELP) {
4329 struct tog_help_view_state *s = &view->state.help;
4331 first = &s->first_displayed_line;
4332 selected = first;
4333 eof = &s->eof;
4334 f = s->f;
4335 } else if (view->type == TOG_VIEW_BLAME) {
4336 struct tog_blame_view_state *s = &view->state.blame;
4338 first = &s->first_displayed_line;
4339 selected = &s->selected_line;
4340 eof = &s->eof;
4341 f = s->blame.f;
4342 } else
4343 return 0;
4345 /* Center gline in the middle of the page like vi(1). */
4346 if (*lineno < view->gline - (view->nlines - 3) / 2)
4347 return 0;
4348 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4349 rewind(f);
4350 *eof = 0;
4351 *first = 1;
4352 *lineno = 0;
4353 *nprinted = 0;
4354 return 0;
4357 *selected = view->gline <= (view->nlines - 3) / 2 ?
4358 view->gline : (view->nlines - 3) / 2 + 1;
4359 view->gline = 0;
4361 return 1;
4364 static const struct got_error *
4365 draw_file(struct tog_view *view, const char *header)
4367 struct tog_diff_view_state *s = &view->state.diff;
4368 regmatch_t *regmatch = &view->regmatch;
4369 const struct got_error *err;
4370 int nprinted = 0;
4371 char *line;
4372 size_t linesize = 0;
4373 ssize_t linelen;
4374 wchar_t *wline;
4375 int width;
4376 int max_lines = view->nlines;
4377 int nlines = s->nlines;
4378 off_t line_offset;
4380 s->lineno = s->first_displayed_line - 1;
4381 line_offset = s->lines[s->first_displayed_line - 1].offset;
4382 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4383 return got_error_from_errno("fseek");
4385 werase(view->window);
4387 if (view->gline > s->nlines - 1)
4388 view->gline = s->nlines - 1;
4390 if (header) {
4391 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4392 1 : view->gline - (view->nlines - 3) / 2 :
4393 s->lineno + s->selected_line;
4395 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4396 return got_error_from_errno("asprintf");
4397 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4398 0, 0);
4399 free(line);
4400 if (err)
4401 return err;
4403 if (view_needs_focus_indication(view))
4404 wstandout(view->window);
4405 waddwstr(view->window, wline);
4406 free(wline);
4407 wline = NULL;
4408 while (width++ < view->ncols)
4409 waddch(view->window, ' ');
4410 if (view_needs_focus_indication(view))
4411 wstandend(view->window);
4413 if (max_lines <= 1)
4414 return NULL;
4415 max_lines--;
4418 s->eof = 0;
4419 view->maxx = 0;
4420 line = NULL;
4421 while (max_lines > 0 && nprinted < max_lines) {
4422 enum got_diff_line_type linetype;
4423 attr_t attr = 0;
4425 linelen = getline(&line, &linesize, s->f);
4426 if (linelen == -1) {
4427 if (feof(s->f)) {
4428 s->eof = 1;
4429 break;
4431 free(line);
4432 return got_ferror(s->f, GOT_ERR_IO);
4435 if (++s->lineno < s->first_displayed_line)
4436 continue;
4437 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4438 continue;
4439 if (s->lineno == view->hiline)
4440 attr = A_STANDOUT;
4442 /* Set view->maxx based on full line length. */
4443 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4444 view->x ? 1 : 0);
4445 if (err) {
4446 free(line);
4447 return err;
4449 view->maxx = MAX(view->maxx, width);
4450 free(wline);
4451 wline = NULL;
4453 linetype = s->lines[s->lineno].type;
4454 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4455 linetype < GOT_DIFF_LINE_CONTEXT)
4456 attr |= COLOR_PAIR(linetype);
4457 if (attr)
4458 wattron(view->window, attr);
4459 if (s->first_displayed_line + nprinted == s->matched_line &&
4460 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4461 err = add_matched_line(&width, line, view->ncols, 0,
4462 view->window, view->x, regmatch);
4463 if (err) {
4464 free(line);
4465 return err;
4467 } else {
4468 int skip;
4469 err = format_line(&wline, &width, &skip, line,
4470 view->x, view->ncols, 0, view->x ? 1 : 0);
4471 if (err) {
4472 free(line);
4473 return err;
4475 waddwstr(view->window, &wline[skip]);
4476 free(wline);
4477 wline = NULL;
4479 if (s->lineno == view->hiline) {
4480 /* highlight full gline length */
4481 while (width++ < view->ncols)
4482 waddch(view->window, ' ');
4483 } else {
4484 if (width <= view->ncols - 1)
4485 waddch(view->window, '\n');
4487 if (attr)
4488 wattroff(view->window, attr);
4489 if (++nprinted == 1)
4490 s->first_displayed_line = s->lineno;
4492 free(line);
4493 if (nprinted >= 1)
4494 s->last_displayed_line = s->first_displayed_line +
4495 (nprinted - 1);
4496 else
4497 s->last_displayed_line = s->first_displayed_line;
4499 view_border(view);
4501 if (s->eof) {
4502 while (nprinted < view->nlines) {
4503 waddch(view->window, '\n');
4504 nprinted++;
4507 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4508 view->ncols, 0, 0);
4509 if (err) {
4510 return err;
4513 wstandout(view->window);
4514 waddwstr(view->window, wline);
4515 free(wline);
4516 wline = NULL;
4517 wstandend(view->window);
4520 return NULL;
4523 static char *
4524 get_datestr(time_t *time, char *datebuf)
4526 struct tm mytm, *tm;
4527 char *p, *s;
4529 tm = gmtime_r(time, &mytm);
4530 if (tm == NULL)
4531 return NULL;
4532 s = asctime_r(tm, datebuf);
4533 if (s == NULL)
4534 return NULL;
4535 p = strchr(s, '\n');
4536 if (p)
4537 *p = '\0';
4538 return s;
4541 static const struct got_error *
4542 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4543 off_t off, uint8_t type)
4545 struct got_diff_line *p;
4547 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4548 if (p == NULL)
4549 return got_error_from_errno("reallocarray");
4550 *lines = p;
4551 (*lines)[*nlines].offset = off;
4552 (*lines)[*nlines].type = type;
4553 (*nlines)++;
4555 return NULL;
4558 static const struct got_error *
4559 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4560 struct got_diff_line *s_lines, size_t s_nlines)
4562 struct got_diff_line *p;
4563 char buf[BUFSIZ];
4564 size_t i, r;
4566 if (fseeko(src, 0L, SEEK_SET) == -1)
4567 return got_error_from_errno("fseeko");
4569 for (;;) {
4570 r = fread(buf, 1, sizeof(buf), src);
4571 if (r == 0) {
4572 if (ferror(src))
4573 return got_error_from_errno("fread");
4574 if (feof(src))
4575 break;
4577 if (fwrite(buf, 1, r, dst) != r)
4578 return got_ferror(dst, GOT_ERR_IO);
4581 if (s_nlines == 0 && *d_nlines == 0)
4582 return NULL;
4585 * If commit info was in dst, increment line offsets
4586 * of the appended diff content, but skip s_lines[0]
4587 * because offset zero is already in *d_lines.
4589 if (*d_nlines > 0) {
4590 for (i = 1; i < s_nlines; ++i)
4591 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4593 if (s_nlines > 0) {
4594 --s_nlines;
4595 ++s_lines;
4599 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4600 if (p == NULL) {
4601 /* d_lines is freed in close_diff_view() */
4602 return got_error_from_errno("reallocarray");
4605 *d_lines = p;
4607 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4608 *d_nlines += s_nlines;
4610 return NULL;
4613 static const struct got_error *
4614 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4615 struct got_object_id *commit_id, struct got_reflist_head *refs,
4616 struct got_repository *repo, int ignore_ws, int force_text_diff,
4617 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4619 const struct got_error *err = NULL;
4620 char datebuf[26], *datestr;
4621 struct got_commit_object *commit;
4622 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4623 time_t committer_time;
4624 const char *author, *committer;
4625 char *refs_str = NULL;
4626 struct got_pathlist_entry *pe;
4627 off_t outoff = 0;
4628 int n;
4630 if (refs) {
4631 err = build_refs_str(&refs_str, refs, commit_id, repo);
4632 if (err)
4633 return err;
4636 err = got_object_open_as_commit(&commit, repo, commit_id);
4637 if (err)
4638 return err;
4640 err = got_object_id_str(&id_str, commit_id);
4641 if (err) {
4642 err = got_error_from_errno("got_object_id_str");
4643 goto done;
4646 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4647 if (err)
4648 goto done;
4650 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4651 refs_str ? refs_str : "", refs_str ? ")" : "");
4652 if (n < 0) {
4653 err = got_error_from_errno("fprintf");
4654 goto done;
4656 outoff += n;
4657 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4658 if (err)
4659 goto done;
4661 n = fprintf(outfile, "from: %s\n",
4662 got_object_commit_get_author(commit));
4663 if (n < 0) {
4664 err = got_error_from_errno("fprintf");
4665 goto done;
4667 outoff += n;
4668 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4669 if (err)
4670 goto done;
4672 author = got_object_commit_get_author(commit);
4673 committer = got_object_commit_get_committer(commit);
4674 if (strcmp(author, committer) != 0) {
4675 n = fprintf(outfile, "via: %s\n", committer);
4676 if (n < 0) {
4677 err = got_error_from_errno("fprintf");
4678 goto done;
4680 outoff += n;
4681 err = add_line_metadata(lines, nlines, outoff,
4682 GOT_DIFF_LINE_AUTHOR);
4683 if (err)
4684 goto done;
4686 committer_time = got_object_commit_get_committer_time(commit);
4687 datestr = get_datestr(&committer_time, datebuf);
4688 if (datestr) {
4689 n = fprintf(outfile, "date: %s UTC\n", datestr);
4690 if (n < 0) {
4691 err = got_error_from_errno("fprintf");
4692 goto done;
4694 outoff += n;
4695 err = add_line_metadata(lines, nlines, outoff,
4696 GOT_DIFF_LINE_DATE);
4697 if (err)
4698 goto done;
4700 if (got_object_commit_get_nparents(commit) > 1) {
4701 const struct got_object_id_queue *parent_ids;
4702 struct got_object_qid *qid;
4703 int pn = 1;
4704 parent_ids = got_object_commit_get_parent_ids(commit);
4705 STAILQ_FOREACH(qid, parent_ids, entry) {
4706 err = got_object_id_str(&id_str, &qid->id);
4707 if (err)
4708 goto done;
4709 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4710 if (n < 0) {
4711 err = got_error_from_errno("fprintf");
4712 goto done;
4714 outoff += n;
4715 err = add_line_metadata(lines, nlines, outoff,
4716 GOT_DIFF_LINE_META);
4717 if (err)
4718 goto done;
4719 free(id_str);
4720 id_str = NULL;
4724 err = got_object_commit_get_logmsg(&logmsg, commit);
4725 if (err)
4726 goto done;
4727 s = logmsg;
4728 while ((line = strsep(&s, "\n")) != NULL) {
4729 n = fprintf(outfile, "%s\n", line);
4730 if (n < 0) {
4731 err = got_error_from_errno("fprintf");
4732 goto done;
4734 outoff += n;
4735 err = add_line_metadata(lines, nlines, outoff,
4736 GOT_DIFF_LINE_LOGMSG);
4737 if (err)
4738 goto done;
4741 TAILQ_FOREACH(pe, dsa->paths, entry) {
4742 struct got_diff_changed_path *cp = pe->data;
4743 int pad = dsa->max_path_len - pe->path_len + 1;
4745 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4746 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4747 dsa->rm_cols + 1, cp->rm);
4748 if (n < 0) {
4749 err = got_error_from_errno("fprintf");
4750 goto done;
4752 outoff += n;
4753 err = add_line_metadata(lines, nlines, outoff,
4754 GOT_DIFF_LINE_CHANGES);
4755 if (err)
4756 goto done;
4759 fputc('\n', outfile);
4760 outoff++;
4761 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4762 if (err)
4763 goto done;
4765 n = fprintf(outfile,
4766 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4767 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4768 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4769 if (n < 0) {
4770 err = got_error_from_errno("fprintf");
4771 goto done;
4773 outoff += n;
4774 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4775 if (err)
4776 goto done;
4778 fputc('\n', outfile);
4779 outoff++;
4780 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4781 done:
4782 free(id_str);
4783 free(logmsg);
4784 free(refs_str);
4785 got_object_commit_close(commit);
4786 if (err) {
4787 free(*lines);
4788 *lines = NULL;
4789 *nlines = 0;
4791 return err;
4794 static const struct got_error *
4795 create_diff(struct tog_diff_view_state *s)
4797 const struct got_error *err = NULL;
4798 FILE *f = NULL, *tmp_diff_file = NULL;
4799 int obj_type;
4800 struct got_diff_line *lines = NULL;
4801 struct got_pathlist_head changed_paths;
4803 TAILQ_INIT(&changed_paths);
4805 free(s->lines);
4806 s->lines = malloc(sizeof(*s->lines));
4807 if (s->lines == NULL)
4808 return got_error_from_errno("malloc");
4809 s->nlines = 0;
4811 f = got_opentemp();
4812 if (f == NULL) {
4813 err = got_error_from_errno("got_opentemp");
4814 goto done;
4816 tmp_diff_file = got_opentemp();
4817 if (tmp_diff_file == NULL) {
4818 err = got_error_from_errno("got_opentemp");
4819 goto done;
4821 if (s->f && fclose(s->f) == EOF) {
4822 err = got_error_from_errno("fclose");
4823 goto done;
4825 s->f = f;
4827 if (s->id1)
4828 err = got_object_get_type(&obj_type, s->repo, s->id1);
4829 else
4830 err = got_object_get_type(&obj_type, s->repo, s->id2);
4831 if (err)
4832 goto done;
4834 switch (obj_type) {
4835 case GOT_OBJ_TYPE_BLOB:
4836 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4837 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4838 s->label1, s->label2, tog_diff_algo, s->diff_context,
4839 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
4840 s->f);
4841 break;
4842 case GOT_OBJ_TYPE_TREE:
4843 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4844 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4845 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4846 s->force_text_diff, NULL, s->repo, s->f);
4847 break;
4848 case GOT_OBJ_TYPE_COMMIT: {
4849 const struct got_object_id_queue *parent_ids;
4850 struct got_object_qid *pid;
4851 struct got_commit_object *commit2;
4852 struct got_reflist_head *refs;
4853 size_t nlines = 0;
4854 struct got_diffstat_cb_arg dsa = {
4855 0, 0, 0, 0, 0, 0,
4856 &changed_paths,
4857 s->ignore_whitespace,
4858 s->force_text_diff,
4859 tog_diff_algo
4862 lines = malloc(sizeof(*lines));
4863 if (lines == NULL) {
4864 err = got_error_from_errno("malloc");
4865 goto done;
4868 /* build diff first in tmp file then append to commit info */
4869 err = got_diff_objects_as_commits(&lines, &nlines,
4870 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4871 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4872 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
4873 if (err)
4874 break;
4876 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4877 if (err)
4878 goto done;
4879 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4880 /* Show commit info if we're diffing to a parent/root commit. */
4881 if (s->id1 == NULL) {
4882 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4883 refs, s->repo, s->ignore_whitespace,
4884 s->force_text_diff, &dsa, s->f);
4885 if (err)
4886 goto done;
4887 } else {
4888 parent_ids = got_object_commit_get_parent_ids(commit2);
4889 STAILQ_FOREACH(pid, parent_ids, entry) {
4890 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4891 err = write_commit_info(&s->lines,
4892 &s->nlines, s->id2, refs, s->repo,
4893 s->ignore_whitespace,
4894 s->force_text_diff, &dsa, s->f);
4895 if (err)
4896 goto done;
4897 break;
4901 got_object_commit_close(commit2);
4903 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
4904 lines, nlines);
4905 break;
4907 default:
4908 err = got_error(GOT_ERR_OBJ_TYPE);
4909 break;
4911 done:
4912 free(lines);
4913 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4914 if (s->f && fflush(s->f) != 0 && err == NULL)
4915 err = got_error_from_errno("fflush");
4916 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
4917 err = got_error_from_errno("fclose");
4918 return err;
4921 static void
4922 diff_view_indicate_progress(struct tog_view *view)
4924 mvwaddstr(view->window, 0, 0, "diffing...");
4925 update_panels();
4926 doupdate();
4929 static const struct got_error *
4930 search_start_diff_view(struct tog_view *view)
4932 struct tog_diff_view_state *s = &view->state.diff;
4934 s->matched_line = 0;
4935 return NULL;
4938 static void
4939 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4940 size_t *nlines, int **first, int **last, int **match, int **selected)
4942 struct tog_diff_view_state *s = &view->state.diff;
4944 *f = s->f;
4945 *nlines = s->nlines;
4946 *line_offsets = NULL;
4947 *match = &s->matched_line;
4948 *first = &s->first_displayed_line;
4949 *last = &s->last_displayed_line;
4950 *selected = &s->selected_line;
4953 static const struct got_error *
4954 search_next_view_match(struct tog_view *view)
4956 const struct got_error *err = NULL;
4957 FILE *f;
4958 int lineno;
4959 char *line = NULL;
4960 size_t linesize = 0;
4961 ssize_t linelen;
4962 off_t *line_offsets;
4963 size_t nlines = 0;
4964 int *first, *last, *match, *selected;
4966 if (!view->search_setup)
4967 return got_error_msg(GOT_ERR_NOT_IMPL,
4968 "view search not supported");
4969 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4970 &match, &selected);
4972 if (!view->searching) {
4973 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4974 return NULL;
4977 if (*match) {
4978 if (view->searching == TOG_SEARCH_FORWARD)
4979 lineno = *match + 1;
4980 else
4981 lineno = *match - 1;
4982 } else
4983 lineno = *first - 1 + *selected;
4985 while (1) {
4986 off_t offset;
4988 if (lineno <= 0 || lineno > nlines) {
4989 if (*match == 0) {
4990 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4991 break;
4994 if (view->searching == TOG_SEARCH_FORWARD)
4995 lineno = 1;
4996 else
4997 lineno = nlines;
5000 offset = view->type == TOG_VIEW_DIFF ?
5001 view->state.diff.lines[lineno - 1].offset :
5002 line_offsets[lineno - 1];
5003 if (fseeko(f, offset, SEEK_SET) != 0) {
5004 free(line);
5005 return got_error_from_errno("fseeko");
5007 linelen = getline(&line, &linesize, f);
5008 if (linelen != -1) {
5009 char *exstr;
5010 err = expand_tab(&exstr, line);
5011 if (err)
5012 break;
5013 if (match_line(exstr, &view->regex, 1,
5014 &view->regmatch)) {
5015 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5016 *match = lineno;
5017 free(exstr);
5018 break;
5020 free(exstr);
5022 if (view->searching == TOG_SEARCH_FORWARD)
5023 lineno++;
5024 else
5025 lineno--;
5027 free(line);
5029 if (*match) {
5030 *first = *match;
5031 *selected = 1;
5034 return err;
5037 static const struct got_error *
5038 close_diff_view(struct tog_view *view)
5040 const struct got_error *err = NULL;
5041 struct tog_diff_view_state *s = &view->state.diff;
5043 free(s->id1);
5044 s->id1 = NULL;
5045 free(s->id2);
5046 s->id2 = NULL;
5047 if (s->f && fclose(s->f) == EOF)
5048 err = got_error_from_errno("fclose");
5049 s->f = NULL;
5050 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5051 err = got_error_from_errno("fclose");
5052 s->f1 = NULL;
5053 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5054 err = got_error_from_errno("fclose");
5055 s->f2 = NULL;
5056 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5057 err = got_error_from_errno("close");
5058 s->fd1 = -1;
5059 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5060 err = got_error_from_errno("close");
5061 s->fd2 = -1;
5062 free(s->lines);
5063 s->lines = NULL;
5064 s->nlines = 0;
5065 return err;
5068 static const struct got_error *
5069 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5070 struct got_object_id *id2, const char *label1, const char *label2,
5071 int diff_context, int ignore_whitespace, int force_text_diff,
5072 struct tog_view *parent_view, struct got_repository *repo)
5074 const struct got_error *err;
5075 struct tog_diff_view_state *s = &view->state.diff;
5077 memset(s, 0, sizeof(*s));
5078 s->fd1 = -1;
5079 s->fd2 = -1;
5081 if (id1 != NULL && id2 != NULL) {
5082 int type1, type2;
5083 err = got_object_get_type(&type1, repo, id1);
5084 if (err)
5085 return err;
5086 err = got_object_get_type(&type2, repo, id2);
5087 if (err)
5088 return err;
5090 if (type1 != type2)
5091 return got_error(GOT_ERR_OBJ_TYPE);
5093 s->first_displayed_line = 1;
5094 s->last_displayed_line = view->nlines;
5095 s->selected_line = 1;
5096 s->repo = repo;
5097 s->id1 = id1;
5098 s->id2 = id2;
5099 s->label1 = label1;
5100 s->label2 = label2;
5102 if (id1) {
5103 s->id1 = got_object_id_dup(id1);
5104 if (s->id1 == NULL)
5105 return got_error_from_errno("got_object_id_dup");
5106 } else
5107 s->id1 = NULL;
5109 s->id2 = got_object_id_dup(id2);
5110 if (s->id2 == NULL) {
5111 err = got_error_from_errno("got_object_id_dup");
5112 goto done;
5115 s->f1 = got_opentemp();
5116 if (s->f1 == NULL) {
5117 err = got_error_from_errno("got_opentemp");
5118 goto done;
5121 s->f2 = got_opentemp();
5122 if (s->f2 == NULL) {
5123 err = got_error_from_errno("got_opentemp");
5124 goto done;
5127 s->fd1 = got_opentempfd();
5128 if (s->fd1 == -1) {
5129 err = got_error_from_errno("got_opentempfd");
5130 goto done;
5133 s->fd2 = got_opentempfd();
5134 if (s->fd2 == -1) {
5135 err = got_error_from_errno("got_opentempfd");
5136 goto done;
5139 s->diff_context = diff_context;
5140 s->ignore_whitespace = ignore_whitespace;
5141 s->force_text_diff = force_text_diff;
5142 s->parent_view = parent_view;
5143 s->repo = repo;
5145 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5146 int rc;
5148 rc = init_pair(GOT_DIFF_LINE_MINUS,
5149 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5150 if (rc != ERR)
5151 rc = init_pair(GOT_DIFF_LINE_PLUS,
5152 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5153 if (rc != ERR)
5154 rc = init_pair(GOT_DIFF_LINE_HUNK,
5155 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5156 if (rc != ERR)
5157 rc = init_pair(GOT_DIFF_LINE_META,
5158 get_color_value("TOG_COLOR_DIFF_META"), -1);
5159 if (rc != ERR)
5160 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5161 get_color_value("TOG_COLOR_DIFF_META"), -1);
5162 if (rc != ERR)
5163 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5164 get_color_value("TOG_COLOR_DIFF_META"), -1);
5165 if (rc != ERR)
5166 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5167 get_color_value("TOG_COLOR_DIFF_META"), -1);
5168 if (rc != ERR)
5169 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5170 get_color_value("TOG_COLOR_AUTHOR"), -1);
5171 if (rc != ERR)
5172 rc = init_pair(GOT_DIFF_LINE_DATE,
5173 get_color_value("TOG_COLOR_DATE"), -1);
5174 if (rc == ERR) {
5175 err = got_error(GOT_ERR_RANGE);
5176 goto done;
5180 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5181 view_is_splitscreen(view))
5182 show_log_view(parent_view); /* draw border */
5183 diff_view_indicate_progress(view);
5185 err = create_diff(s);
5187 view->show = show_diff_view;
5188 view->input = input_diff_view;
5189 view->reset = reset_diff_view;
5190 view->close = close_diff_view;
5191 view->search_start = search_start_diff_view;
5192 view->search_setup = search_setup_diff_view;
5193 view->search_next = search_next_view_match;
5194 done:
5195 if (err)
5196 close_diff_view(view);
5197 return err;
5200 static const struct got_error *
5201 show_diff_view(struct tog_view *view)
5203 const struct got_error *err;
5204 struct tog_diff_view_state *s = &view->state.diff;
5205 char *id_str1 = NULL, *id_str2, *header;
5206 const char *label1, *label2;
5208 if (s->id1) {
5209 err = got_object_id_str(&id_str1, s->id1);
5210 if (err)
5211 return err;
5212 label1 = s->label1 ? s->label1 : id_str1;
5213 } else
5214 label1 = "/dev/null";
5216 err = got_object_id_str(&id_str2, s->id2);
5217 if (err)
5218 return err;
5219 label2 = s->label2 ? s->label2 : id_str2;
5221 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5222 err = got_error_from_errno("asprintf");
5223 free(id_str1);
5224 free(id_str2);
5225 return err;
5227 free(id_str1);
5228 free(id_str2);
5230 err = draw_file(view, header);
5231 free(header);
5232 return err;
5235 static const struct got_error *
5236 set_selected_commit(struct tog_diff_view_state *s,
5237 struct commit_queue_entry *entry)
5239 const struct got_error *err;
5240 const struct got_object_id_queue *parent_ids;
5241 struct got_commit_object *selected_commit;
5242 struct got_object_qid *pid;
5244 free(s->id2);
5245 s->id2 = got_object_id_dup(entry->id);
5246 if (s->id2 == NULL)
5247 return got_error_from_errno("got_object_id_dup");
5249 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5250 if (err)
5251 return err;
5252 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5253 free(s->id1);
5254 pid = STAILQ_FIRST(parent_ids);
5255 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5256 got_object_commit_close(selected_commit);
5257 return NULL;
5260 static const struct got_error *
5261 reset_diff_view(struct tog_view *view)
5263 struct tog_diff_view_state *s = &view->state.diff;
5265 view->count = 0;
5266 wclear(view->window);
5267 s->first_displayed_line = 1;
5268 s->last_displayed_line = view->nlines;
5269 s->matched_line = 0;
5270 diff_view_indicate_progress(view);
5271 return create_diff(s);
5274 static void
5275 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5277 int start, i;
5279 i = start = s->first_displayed_line - 1;
5281 while (s->lines[i].type != type) {
5282 if (i == 0)
5283 i = s->nlines - 1;
5284 if (--i == start)
5285 return; /* do nothing, requested type not in file */
5288 s->selected_line = 1;
5289 s->first_displayed_line = i;
5292 static void
5293 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5295 int start, i;
5297 i = start = s->first_displayed_line + 1;
5299 while (s->lines[i].type != type) {
5300 if (i == s->nlines - 1)
5301 i = 0;
5302 if (++i == start)
5303 return; /* do nothing, requested type not in file */
5306 s->selected_line = 1;
5307 s->first_displayed_line = i;
5310 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5311 int, int, int);
5312 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5313 int, int);
5315 static const struct got_error *
5316 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5318 const struct got_error *err = NULL;
5319 struct tog_diff_view_state *s = &view->state.diff;
5320 struct tog_log_view_state *ls;
5321 struct commit_queue_entry *old_selected_entry;
5322 char *line = NULL;
5323 size_t linesize = 0;
5324 ssize_t linelen;
5325 int i, nscroll = view->nlines - 1, up = 0;
5327 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5329 switch (ch) {
5330 case '0':
5331 case '$':
5332 case KEY_RIGHT:
5333 case 'l':
5334 case KEY_LEFT:
5335 case 'h':
5336 horizontal_scroll_input(view, ch);
5337 break;
5338 case 'a':
5339 case 'w':
5340 if (ch == 'a') {
5341 s->force_text_diff = !s->force_text_diff;
5342 view->action = s->force_text_diff ?
5343 "force ASCII text enabled" :
5344 "force ASCII text disabled";
5346 else if (ch == 'w') {
5347 s->ignore_whitespace = !s->ignore_whitespace;
5348 view->action = s->ignore_whitespace ?
5349 "ignore whitespace enabled" :
5350 "ignore whitespace disabled";
5352 err = reset_diff_view(view);
5353 break;
5354 case 'g':
5355 case KEY_HOME:
5356 s->first_displayed_line = 1;
5357 view->count = 0;
5358 break;
5359 case 'G':
5360 case KEY_END:
5361 view->count = 0;
5362 if (s->eof)
5363 break;
5365 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5366 s->eof = 1;
5367 break;
5368 case 'k':
5369 case KEY_UP:
5370 case CTRL('p'):
5371 if (s->first_displayed_line > 1)
5372 s->first_displayed_line--;
5373 else
5374 view->count = 0;
5375 break;
5376 case CTRL('u'):
5377 case 'u':
5378 nscroll /= 2;
5379 /* FALL THROUGH */
5380 case KEY_PPAGE:
5381 case CTRL('b'):
5382 case 'b':
5383 if (s->first_displayed_line == 1) {
5384 view->count = 0;
5385 break;
5387 i = 0;
5388 while (i++ < nscroll && s->first_displayed_line > 1)
5389 s->first_displayed_line--;
5390 break;
5391 case 'j':
5392 case KEY_DOWN:
5393 case CTRL('n'):
5394 if (!s->eof)
5395 s->first_displayed_line++;
5396 else
5397 view->count = 0;
5398 break;
5399 case CTRL('d'):
5400 case 'd':
5401 nscroll /= 2;
5402 /* FALL THROUGH */
5403 case KEY_NPAGE:
5404 case CTRL('f'):
5405 case 'f':
5406 case ' ':
5407 if (s->eof) {
5408 view->count = 0;
5409 break;
5411 i = 0;
5412 while (!s->eof && i++ < nscroll) {
5413 linelen = getline(&line, &linesize, s->f);
5414 s->first_displayed_line++;
5415 if (linelen == -1) {
5416 if (feof(s->f)) {
5417 s->eof = 1;
5418 } else
5419 err = got_ferror(s->f, GOT_ERR_IO);
5420 break;
5423 free(line);
5424 break;
5425 case '(':
5426 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5427 break;
5428 case ')':
5429 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5430 break;
5431 case '{':
5432 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5433 break;
5434 case '}':
5435 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5436 break;
5437 case '[':
5438 if (s->diff_context > 0) {
5439 s->diff_context--;
5440 s->matched_line = 0;
5441 diff_view_indicate_progress(view);
5442 err = create_diff(s);
5443 if (s->first_displayed_line + view->nlines - 1 >
5444 s->nlines) {
5445 s->first_displayed_line = 1;
5446 s->last_displayed_line = view->nlines;
5448 } else
5449 view->count = 0;
5450 break;
5451 case ']':
5452 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5453 s->diff_context++;
5454 s->matched_line = 0;
5455 diff_view_indicate_progress(view);
5456 err = create_diff(s);
5457 } else
5458 view->count = 0;
5459 break;
5460 case '<':
5461 case ',':
5462 case 'K':
5463 up = 1;
5464 /* FALL THROUGH */
5465 case '>':
5466 case '.':
5467 case 'J':
5468 if (s->parent_view == NULL) {
5469 view->count = 0;
5470 break;
5472 s->parent_view->count = view->count;
5474 if (s->parent_view->type == TOG_VIEW_LOG) {
5475 ls = &s->parent_view->state.log;
5476 old_selected_entry = ls->selected_entry;
5478 err = input_log_view(NULL, s->parent_view,
5479 up ? KEY_UP : KEY_DOWN);
5480 if (err)
5481 break;
5482 view->count = s->parent_view->count;
5484 if (old_selected_entry == ls->selected_entry)
5485 break;
5487 err = set_selected_commit(s, ls->selected_entry);
5488 if (err)
5489 break;
5490 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5491 struct tog_blame_view_state *bs;
5492 struct got_object_id *id, *prev_id;
5494 bs = &s->parent_view->state.blame;
5495 prev_id = get_annotation_for_line(bs->blame.lines,
5496 bs->blame.nlines, bs->last_diffed_line);
5498 err = input_blame_view(&view, s->parent_view,
5499 up ? KEY_UP : KEY_DOWN);
5500 if (err)
5501 break;
5502 view->count = s->parent_view->count;
5504 if (prev_id == NULL)
5505 break;
5506 id = get_selected_commit_id(bs->blame.lines,
5507 bs->blame.nlines, bs->first_displayed_line,
5508 bs->selected_line);
5509 if (id == NULL)
5510 break;
5512 if (!got_object_id_cmp(prev_id, id))
5513 break;
5515 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5516 if (err)
5517 break;
5519 s->first_displayed_line = 1;
5520 s->last_displayed_line = view->nlines;
5521 s->matched_line = 0;
5522 view->x = 0;
5524 diff_view_indicate_progress(view);
5525 err = create_diff(s);
5526 break;
5527 default:
5528 view->count = 0;
5529 break;
5532 return err;
5535 static const struct got_error *
5536 cmd_diff(int argc, char *argv[])
5538 const struct got_error *error = NULL;
5539 struct got_repository *repo = NULL;
5540 struct got_worktree *worktree = NULL;
5541 struct got_object_id *id1 = NULL, *id2 = NULL;
5542 char *repo_path = NULL, *cwd = NULL;
5543 char *id_str1 = NULL, *id_str2 = NULL;
5544 char *label1 = NULL, *label2 = NULL;
5545 int diff_context = 3, ignore_whitespace = 0;
5546 int ch, force_text_diff = 0;
5547 const char *errstr;
5548 struct tog_view *view;
5549 int *pack_fds = NULL;
5551 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5552 switch (ch) {
5553 case 'a':
5554 force_text_diff = 1;
5555 break;
5556 case 'C':
5557 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5558 &errstr);
5559 if (errstr != NULL)
5560 errx(1, "number of context lines is %s: %s",
5561 errstr, errstr);
5562 break;
5563 case 'r':
5564 repo_path = realpath(optarg, NULL);
5565 if (repo_path == NULL)
5566 return got_error_from_errno2("realpath",
5567 optarg);
5568 got_path_strip_trailing_slashes(repo_path);
5569 break;
5570 case 'w':
5571 ignore_whitespace = 1;
5572 break;
5573 default:
5574 usage_diff();
5575 /* NOTREACHED */
5579 argc -= optind;
5580 argv += optind;
5582 if (argc == 0) {
5583 usage_diff(); /* TODO show local worktree changes */
5584 } else if (argc == 2) {
5585 id_str1 = argv[0];
5586 id_str2 = argv[1];
5587 } else
5588 usage_diff();
5590 error = got_repo_pack_fds_open(&pack_fds);
5591 if (error)
5592 goto done;
5594 if (repo_path == NULL) {
5595 cwd = getcwd(NULL, 0);
5596 if (cwd == NULL)
5597 return got_error_from_errno("getcwd");
5598 error = got_worktree_open(&worktree, cwd);
5599 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5600 goto done;
5601 if (worktree)
5602 repo_path =
5603 strdup(got_worktree_get_repo_path(worktree));
5604 else
5605 repo_path = strdup(cwd);
5606 if (repo_path == NULL) {
5607 error = got_error_from_errno("strdup");
5608 goto done;
5612 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5613 if (error)
5614 goto done;
5616 init_curses();
5618 error = apply_unveil(got_repo_get_path(repo), NULL);
5619 if (error)
5620 goto done;
5622 error = tog_load_refs(repo, 0);
5623 if (error)
5624 goto done;
5626 error = got_repo_match_object_id(&id1, &label1, id_str1,
5627 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5628 if (error)
5629 goto done;
5631 error = got_repo_match_object_id(&id2, &label2, id_str2,
5632 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5633 if (error)
5634 goto done;
5636 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5637 if (view == NULL) {
5638 error = got_error_from_errno("view_open");
5639 goto done;
5641 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5642 ignore_whitespace, force_text_diff, NULL, repo);
5643 if (error)
5644 goto done;
5645 error = view_loop(view);
5646 done:
5647 free(label1);
5648 free(label2);
5649 free(repo_path);
5650 free(cwd);
5651 if (repo) {
5652 const struct got_error *close_err = got_repo_close(repo);
5653 if (error == NULL)
5654 error = close_err;
5656 if (worktree)
5657 got_worktree_close(worktree);
5658 if (pack_fds) {
5659 const struct got_error *pack_err =
5660 got_repo_pack_fds_close(pack_fds);
5661 if (error == NULL)
5662 error = pack_err;
5664 tog_free_refs();
5665 return error;
5668 __dead static void
5669 usage_blame(void)
5671 endwin();
5672 fprintf(stderr,
5673 "usage: %s blame [-c commit] [-r repository-path] path\n",
5674 getprogname());
5675 exit(1);
5678 struct tog_blame_line {
5679 int annotated;
5680 struct got_object_id *id;
5683 static const struct got_error *
5684 draw_blame(struct tog_view *view)
5686 struct tog_blame_view_state *s = &view->state.blame;
5687 struct tog_blame *blame = &s->blame;
5688 regmatch_t *regmatch = &view->regmatch;
5689 const struct got_error *err;
5690 int lineno = 0, nprinted = 0;
5691 char *line = NULL;
5692 size_t linesize = 0;
5693 ssize_t linelen;
5694 wchar_t *wline;
5695 int width;
5696 struct tog_blame_line *blame_line;
5697 struct got_object_id *prev_id = NULL;
5698 char *id_str;
5699 struct tog_color *tc;
5701 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5702 if (err)
5703 return err;
5705 rewind(blame->f);
5706 werase(view->window);
5708 if (asprintf(&line, "commit %s", id_str) == -1) {
5709 err = got_error_from_errno("asprintf");
5710 free(id_str);
5711 return err;
5714 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5715 free(line);
5716 line = NULL;
5717 if (err)
5718 return err;
5719 if (view_needs_focus_indication(view))
5720 wstandout(view->window);
5721 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5722 if (tc)
5723 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5724 waddwstr(view->window, wline);
5725 while (width++ < view->ncols)
5726 waddch(view->window, ' ');
5727 if (tc)
5728 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5729 if (view_needs_focus_indication(view))
5730 wstandend(view->window);
5731 free(wline);
5732 wline = NULL;
5734 if (view->gline > blame->nlines)
5735 view->gline = blame->nlines;
5737 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5738 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5739 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5740 free(id_str);
5741 return got_error_from_errno("asprintf");
5743 free(id_str);
5744 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5745 free(line);
5746 line = NULL;
5747 if (err)
5748 return err;
5749 waddwstr(view->window, wline);
5750 free(wline);
5751 wline = NULL;
5752 if (width < view->ncols - 1)
5753 waddch(view->window, '\n');
5755 s->eof = 0;
5756 view->maxx = 0;
5757 while (nprinted < view->nlines - 2) {
5758 linelen = getline(&line, &linesize, blame->f);
5759 if (linelen == -1) {
5760 if (feof(blame->f)) {
5761 s->eof = 1;
5762 break;
5764 free(line);
5765 return got_ferror(blame->f, GOT_ERR_IO);
5767 if (++lineno < s->first_displayed_line)
5768 continue;
5769 if (view->gline && !gotoline(view, &lineno, &nprinted))
5770 continue;
5772 /* Set view->maxx based on full line length. */
5773 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5774 if (err) {
5775 free(line);
5776 return err;
5778 free(wline);
5779 wline = NULL;
5780 view->maxx = MAX(view->maxx, width);
5782 if (nprinted == s->selected_line - 1)
5783 wstandout(view->window);
5785 if (blame->nlines > 0) {
5786 blame_line = &blame->lines[lineno - 1];
5787 if (blame_line->annotated && prev_id &&
5788 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5789 !(nprinted == s->selected_line - 1)) {
5790 waddstr(view->window, " ");
5791 } else if (blame_line->annotated) {
5792 char *id_str;
5793 err = got_object_id_str(&id_str,
5794 blame_line->id);
5795 if (err) {
5796 free(line);
5797 return err;
5799 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5800 if (tc)
5801 wattr_on(view->window,
5802 COLOR_PAIR(tc->colorpair), NULL);
5803 wprintw(view->window, "%.8s", id_str);
5804 if (tc)
5805 wattr_off(view->window,
5806 COLOR_PAIR(tc->colorpair), NULL);
5807 free(id_str);
5808 prev_id = blame_line->id;
5809 } else {
5810 waddstr(view->window, "........");
5811 prev_id = NULL;
5813 } else {
5814 waddstr(view->window, "........");
5815 prev_id = NULL;
5818 if (nprinted == s->selected_line - 1)
5819 wstandend(view->window);
5820 waddstr(view->window, " ");
5822 if (view->ncols <= 9) {
5823 width = 9;
5824 } else if (s->first_displayed_line + nprinted ==
5825 s->matched_line &&
5826 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5827 err = add_matched_line(&width, line, view->ncols - 9, 9,
5828 view->window, view->x, regmatch);
5829 if (err) {
5830 free(line);
5831 return err;
5833 width += 9;
5834 } else {
5835 int skip;
5836 err = format_line(&wline, &width, &skip, line,
5837 view->x, view->ncols - 9, 9, 1);
5838 if (err) {
5839 free(line);
5840 return err;
5842 waddwstr(view->window, &wline[skip]);
5843 width += 9;
5844 free(wline);
5845 wline = NULL;
5848 if (width <= view->ncols - 1)
5849 waddch(view->window, '\n');
5850 if (++nprinted == 1)
5851 s->first_displayed_line = lineno;
5853 free(line);
5854 s->last_displayed_line = lineno;
5856 view_border(view);
5858 return NULL;
5861 static const struct got_error *
5862 blame_cb(void *arg, int nlines, int lineno,
5863 struct got_commit_object *commit, struct got_object_id *id)
5865 const struct got_error *err = NULL;
5866 struct tog_blame_cb_args *a = arg;
5867 struct tog_blame_line *line;
5868 int errcode;
5870 if (nlines != a->nlines ||
5871 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5872 return got_error(GOT_ERR_RANGE);
5874 errcode = pthread_mutex_lock(&tog_mutex);
5875 if (errcode)
5876 return got_error_set_errno(errcode, "pthread_mutex_lock");
5878 if (*a->quit) { /* user has quit the blame view */
5879 err = got_error(GOT_ERR_ITER_COMPLETED);
5880 goto done;
5883 if (lineno == -1)
5884 goto done; /* no change in this commit */
5886 line = &a->lines[lineno - 1];
5887 if (line->annotated)
5888 goto done;
5890 line->id = got_object_id_dup(id);
5891 if (line->id == NULL) {
5892 err = got_error_from_errno("got_object_id_dup");
5893 goto done;
5895 line->annotated = 1;
5896 done:
5897 errcode = pthread_mutex_unlock(&tog_mutex);
5898 if (errcode)
5899 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5900 return err;
5903 static void *
5904 blame_thread(void *arg)
5906 const struct got_error *err, *close_err;
5907 struct tog_blame_thread_args *ta = arg;
5908 struct tog_blame_cb_args *a = ta->cb_args;
5909 int errcode, fd1 = -1, fd2 = -1;
5910 FILE *f1 = NULL, *f2 = NULL;
5912 fd1 = got_opentempfd();
5913 if (fd1 == -1)
5914 return (void *)got_error_from_errno("got_opentempfd");
5916 fd2 = got_opentempfd();
5917 if (fd2 == -1) {
5918 err = got_error_from_errno("got_opentempfd");
5919 goto done;
5922 f1 = got_opentemp();
5923 if (f1 == NULL) {
5924 err = (void *)got_error_from_errno("got_opentemp");
5925 goto done;
5927 f2 = got_opentemp();
5928 if (f2 == NULL) {
5929 err = (void *)got_error_from_errno("got_opentemp");
5930 goto done;
5933 err = block_signals_used_by_main_thread();
5934 if (err)
5935 goto done;
5937 err = got_blame(ta->path, a->commit_id, ta->repo,
5938 tog_diff_algo, blame_cb, ta->cb_args,
5939 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5940 if (err && err->code == GOT_ERR_CANCELLED)
5941 err = NULL;
5943 errcode = pthread_mutex_lock(&tog_mutex);
5944 if (errcode) {
5945 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5946 goto done;
5949 close_err = got_repo_close(ta->repo);
5950 if (err == NULL)
5951 err = close_err;
5952 ta->repo = NULL;
5953 *ta->complete = 1;
5955 errcode = pthread_mutex_unlock(&tog_mutex);
5956 if (errcode && err == NULL)
5957 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5959 done:
5960 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5961 err = got_error_from_errno("close");
5962 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5963 err = got_error_from_errno("close");
5964 if (f1 && fclose(f1) == EOF && err == NULL)
5965 err = got_error_from_errno("fclose");
5966 if (f2 && fclose(f2) == EOF && err == NULL)
5967 err = got_error_from_errno("fclose");
5969 return (void *)err;
5972 static struct got_object_id *
5973 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5974 int first_displayed_line, int selected_line)
5976 struct tog_blame_line *line;
5978 if (nlines <= 0)
5979 return NULL;
5981 line = &lines[first_displayed_line - 1 + selected_line - 1];
5982 if (!line->annotated)
5983 return NULL;
5985 return line->id;
5988 static struct got_object_id *
5989 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5990 int lineno)
5992 struct tog_blame_line *line;
5994 if (nlines <= 0 || lineno >= nlines)
5995 return NULL;
5997 line = &lines[lineno - 1];
5998 if (!line->annotated)
5999 return NULL;
6001 return line->id;
6004 static const struct got_error *
6005 stop_blame(struct tog_blame *blame)
6007 const struct got_error *err = NULL;
6008 int i;
6010 if (blame->thread) {
6011 int errcode;
6012 errcode = pthread_mutex_unlock(&tog_mutex);
6013 if (errcode)
6014 return got_error_set_errno(errcode,
6015 "pthread_mutex_unlock");
6016 errcode = pthread_join(blame->thread, (void **)&err);
6017 if (errcode)
6018 return got_error_set_errno(errcode, "pthread_join");
6019 errcode = pthread_mutex_lock(&tog_mutex);
6020 if (errcode)
6021 return got_error_set_errno(errcode,
6022 "pthread_mutex_lock");
6023 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6024 err = NULL;
6025 blame->thread = NULL;
6027 if (blame->thread_args.repo) {
6028 const struct got_error *close_err;
6029 close_err = got_repo_close(blame->thread_args.repo);
6030 if (err == NULL)
6031 err = close_err;
6032 blame->thread_args.repo = NULL;
6034 if (blame->f) {
6035 if (fclose(blame->f) == EOF && err == NULL)
6036 err = got_error_from_errno("fclose");
6037 blame->f = NULL;
6039 if (blame->lines) {
6040 for (i = 0; i < blame->nlines; i++)
6041 free(blame->lines[i].id);
6042 free(blame->lines);
6043 blame->lines = NULL;
6045 free(blame->cb_args.commit_id);
6046 blame->cb_args.commit_id = NULL;
6047 if (blame->pack_fds) {
6048 const struct got_error *pack_err =
6049 got_repo_pack_fds_close(blame->pack_fds);
6050 if (err == NULL)
6051 err = pack_err;
6052 blame->pack_fds = NULL;
6054 return err;
6057 static const struct got_error *
6058 cancel_blame_view(void *arg)
6060 const struct got_error *err = NULL;
6061 int *done = arg;
6062 int errcode;
6064 errcode = pthread_mutex_lock(&tog_mutex);
6065 if (errcode)
6066 return got_error_set_errno(errcode,
6067 "pthread_mutex_unlock");
6069 if (*done)
6070 err = got_error(GOT_ERR_CANCELLED);
6072 errcode = pthread_mutex_unlock(&tog_mutex);
6073 if (errcode)
6074 return got_error_set_errno(errcode,
6075 "pthread_mutex_lock");
6077 return err;
6080 static const struct got_error *
6081 run_blame(struct tog_view *view)
6083 struct tog_blame_view_state *s = &view->state.blame;
6084 struct tog_blame *blame = &s->blame;
6085 const struct got_error *err = NULL;
6086 struct got_commit_object *commit = NULL;
6087 struct got_blob_object *blob = NULL;
6088 struct got_repository *thread_repo = NULL;
6089 struct got_object_id *obj_id = NULL;
6090 int obj_type, fd = -1;
6091 int *pack_fds = NULL;
6093 err = got_object_open_as_commit(&commit, s->repo,
6094 &s->blamed_commit->id);
6095 if (err)
6096 return err;
6098 fd = got_opentempfd();
6099 if (fd == -1) {
6100 err = got_error_from_errno("got_opentempfd");
6101 goto done;
6104 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6105 if (err)
6106 goto done;
6108 err = got_object_get_type(&obj_type, s->repo, obj_id);
6109 if (err)
6110 goto done;
6112 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6113 err = got_error(GOT_ERR_OBJ_TYPE);
6114 goto done;
6117 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6118 if (err)
6119 goto done;
6120 blame->f = got_opentemp();
6121 if (blame->f == NULL) {
6122 err = got_error_from_errno("got_opentemp");
6123 goto done;
6125 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6126 &blame->line_offsets, blame->f, blob);
6127 if (err)
6128 goto done;
6129 if (blame->nlines == 0) {
6130 s->blame_complete = 1;
6131 goto done;
6134 /* Don't include \n at EOF in the blame line count. */
6135 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6136 blame->nlines--;
6138 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6139 if (blame->lines == NULL) {
6140 err = got_error_from_errno("calloc");
6141 goto done;
6144 err = got_repo_pack_fds_open(&pack_fds);
6145 if (err)
6146 goto done;
6147 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6148 pack_fds);
6149 if (err)
6150 goto done;
6152 blame->pack_fds = pack_fds;
6153 blame->cb_args.view = view;
6154 blame->cb_args.lines = blame->lines;
6155 blame->cb_args.nlines = blame->nlines;
6156 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6157 if (blame->cb_args.commit_id == NULL) {
6158 err = got_error_from_errno("got_object_id_dup");
6159 goto done;
6161 blame->cb_args.quit = &s->done;
6163 blame->thread_args.path = s->path;
6164 blame->thread_args.repo = thread_repo;
6165 blame->thread_args.cb_args = &blame->cb_args;
6166 blame->thread_args.complete = &s->blame_complete;
6167 blame->thread_args.cancel_cb = cancel_blame_view;
6168 blame->thread_args.cancel_arg = &s->done;
6169 s->blame_complete = 0;
6171 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6172 s->first_displayed_line = 1;
6173 s->last_displayed_line = view->nlines;
6174 s->selected_line = 1;
6176 s->matched_line = 0;
6178 done:
6179 if (commit)
6180 got_object_commit_close(commit);
6181 if (fd != -1 && close(fd) == -1 && err == NULL)
6182 err = got_error_from_errno("close");
6183 if (blob)
6184 got_object_blob_close(blob);
6185 free(obj_id);
6186 if (err)
6187 stop_blame(blame);
6188 return err;
6191 static const struct got_error *
6192 open_blame_view(struct tog_view *view, char *path,
6193 struct got_object_id *commit_id, struct got_repository *repo)
6195 const struct got_error *err = NULL;
6196 struct tog_blame_view_state *s = &view->state.blame;
6198 STAILQ_INIT(&s->blamed_commits);
6200 s->path = strdup(path);
6201 if (s->path == NULL)
6202 return got_error_from_errno("strdup");
6204 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6205 if (err) {
6206 free(s->path);
6207 return err;
6210 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6211 s->first_displayed_line = 1;
6212 s->last_displayed_line = view->nlines;
6213 s->selected_line = 1;
6214 s->blame_complete = 0;
6215 s->repo = repo;
6216 s->commit_id = commit_id;
6217 memset(&s->blame, 0, sizeof(s->blame));
6219 STAILQ_INIT(&s->colors);
6220 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6221 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6222 get_color_value("TOG_COLOR_COMMIT"));
6223 if (err)
6224 return err;
6227 view->show = show_blame_view;
6228 view->input = input_blame_view;
6229 view->reset = reset_blame_view;
6230 view->close = close_blame_view;
6231 view->search_start = search_start_blame_view;
6232 view->search_setup = search_setup_blame_view;
6233 view->search_next = search_next_view_match;
6235 return run_blame(view);
6238 static const struct got_error *
6239 close_blame_view(struct tog_view *view)
6241 const struct got_error *err = NULL;
6242 struct tog_blame_view_state *s = &view->state.blame;
6244 if (s->blame.thread)
6245 err = stop_blame(&s->blame);
6247 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6248 struct got_object_qid *blamed_commit;
6249 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6250 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6251 got_object_qid_free(blamed_commit);
6254 free(s->path);
6255 free_colors(&s->colors);
6256 return err;
6259 static const struct got_error *
6260 search_start_blame_view(struct tog_view *view)
6262 struct tog_blame_view_state *s = &view->state.blame;
6264 s->matched_line = 0;
6265 return NULL;
6268 static void
6269 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6270 size_t *nlines, int **first, int **last, int **match, int **selected)
6272 struct tog_blame_view_state *s = &view->state.blame;
6274 *f = s->blame.f;
6275 *nlines = s->blame.nlines;
6276 *line_offsets = s->blame.line_offsets;
6277 *match = &s->matched_line;
6278 *first = &s->first_displayed_line;
6279 *last = &s->last_displayed_line;
6280 *selected = &s->selected_line;
6283 static const struct got_error *
6284 show_blame_view(struct tog_view *view)
6286 const struct got_error *err = NULL;
6287 struct tog_blame_view_state *s = &view->state.blame;
6288 int errcode;
6290 if (s->blame.thread == NULL && !s->blame_complete) {
6291 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6292 &s->blame.thread_args);
6293 if (errcode)
6294 return got_error_set_errno(errcode, "pthread_create");
6296 halfdelay(1); /* fast refresh while annotating */
6299 if (s->blame_complete)
6300 halfdelay(10); /* disable fast refresh */
6302 err = draw_blame(view);
6304 view_border(view);
6305 return err;
6308 static const struct got_error *
6309 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6310 struct got_repository *repo, struct got_object_id *id)
6312 struct tog_view *log_view;
6313 const struct got_error *err = NULL;
6315 *new_view = NULL;
6317 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6318 if (log_view == NULL)
6319 return got_error_from_errno("view_open");
6321 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6322 if (err)
6323 view_close(log_view);
6324 else
6325 *new_view = log_view;
6327 return err;
6330 static const struct got_error *
6331 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6333 const struct got_error *err = NULL, *thread_err = NULL;
6334 struct tog_view *diff_view;
6335 struct tog_blame_view_state *s = &view->state.blame;
6336 int eos, nscroll, begin_y = 0, begin_x = 0;
6338 eos = nscroll = view->nlines - 2;
6339 if (view_is_hsplit_top(view))
6340 --eos; /* border */
6342 switch (ch) {
6343 case '0':
6344 case '$':
6345 case KEY_RIGHT:
6346 case 'l':
6347 case KEY_LEFT:
6348 case 'h':
6349 horizontal_scroll_input(view, ch);
6350 break;
6351 case 'q':
6352 s->done = 1;
6353 break;
6354 case 'g':
6355 case KEY_HOME:
6356 s->selected_line = 1;
6357 s->first_displayed_line = 1;
6358 view->count = 0;
6359 break;
6360 case 'G':
6361 case KEY_END:
6362 if (s->blame.nlines < eos) {
6363 s->selected_line = s->blame.nlines;
6364 s->first_displayed_line = 1;
6365 } else {
6366 s->selected_line = eos;
6367 s->first_displayed_line = s->blame.nlines - (eos - 1);
6369 view->count = 0;
6370 break;
6371 case 'k':
6372 case KEY_UP:
6373 case CTRL('p'):
6374 if (s->selected_line > 1)
6375 s->selected_line--;
6376 else if (s->selected_line == 1 &&
6377 s->first_displayed_line > 1)
6378 s->first_displayed_line--;
6379 else
6380 view->count = 0;
6381 break;
6382 case CTRL('u'):
6383 case 'u':
6384 nscroll /= 2;
6385 /* FALL THROUGH */
6386 case KEY_PPAGE:
6387 case CTRL('b'):
6388 case 'b':
6389 if (s->first_displayed_line == 1) {
6390 if (view->count > 1)
6391 nscroll += nscroll;
6392 s->selected_line = MAX(1, s->selected_line - nscroll);
6393 view->count = 0;
6394 break;
6396 if (s->first_displayed_line > nscroll)
6397 s->first_displayed_line -= nscroll;
6398 else
6399 s->first_displayed_line = 1;
6400 break;
6401 case 'j':
6402 case KEY_DOWN:
6403 case CTRL('n'):
6404 if (s->selected_line < eos && s->first_displayed_line +
6405 s->selected_line <= s->blame.nlines)
6406 s->selected_line++;
6407 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6408 s->first_displayed_line++;
6409 else
6410 view->count = 0;
6411 break;
6412 case 'c':
6413 case 'p': {
6414 struct got_object_id *id = NULL;
6416 view->count = 0;
6417 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6418 s->first_displayed_line, s->selected_line);
6419 if (id == NULL)
6420 break;
6421 if (ch == 'p') {
6422 struct got_commit_object *commit, *pcommit;
6423 struct got_object_qid *pid;
6424 struct got_object_id *blob_id = NULL;
6425 int obj_type;
6426 err = got_object_open_as_commit(&commit,
6427 s->repo, id);
6428 if (err)
6429 break;
6430 pid = STAILQ_FIRST(
6431 got_object_commit_get_parent_ids(commit));
6432 if (pid == NULL) {
6433 got_object_commit_close(commit);
6434 break;
6436 /* Check if path history ends here. */
6437 err = got_object_open_as_commit(&pcommit,
6438 s->repo, &pid->id);
6439 if (err)
6440 break;
6441 err = got_object_id_by_path(&blob_id, s->repo,
6442 pcommit, s->path);
6443 got_object_commit_close(pcommit);
6444 if (err) {
6445 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6446 err = NULL;
6447 got_object_commit_close(commit);
6448 break;
6450 err = got_object_get_type(&obj_type, s->repo,
6451 blob_id);
6452 free(blob_id);
6453 /* Can't blame non-blob type objects. */
6454 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6455 got_object_commit_close(commit);
6456 break;
6458 err = got_object_qid_alloc(&s->blamed_commit,
6459 &pid->id);
6460 got_object_commit_close(commit);
6461 } else {
6462 if (got_object_id_cmp(id,
6463 &s->blamed_commit->id) == 0)
6464 break;
6465 err = got_object_qid_alloc(&s->blamed_commit,
6466 id);
6468 if (err)
6469 break;
6470 s->done = 1;
6471 thread_err = stop_blame(&s->blame);
6472 s->done = 0;
6473 if (thread_err)
6474 break;
6475 STAILQ_INSERT_HEAD(&s->blamed_commits,
6476 s->blamed_commit, entry);
6477 err = run_blame(view);
6478 if (err)
6479 break;
6480 break;
6482 case 'C': {
6483 struct got_object_qid *first;
6485 view->count = 0;
6486 first = STAILQ_FIRST(&s->blamed_commits);
6487 if (!got_object_id_cmp(&first->id, s->commit_id))
6488 break;
6489 s->done = 1;
6490 thread_err = stop_blame(&s->blame);
6491 s->done = 0;
6492 if (thread_err)
6493 break;
6494 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6495 got_object_qid_free(s->blamed_commit);
6496 s->blamed_commit =
6497 STAILQ_FIRST(&s->blamed_commits);
6498 err = run_blame(view);
6499 if (err)
6500 break;
6501 break;
6503 case 'L':
6504 view->count = 0;
6505 s->id_to_log = get_selected_commit_id(s->blame.lines,
6506 s->blame.nlines, s->first_displayed_line, s->selected_line);
6507 if (s->id_to_log)
6508 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6509 break;
6510 case KEY_ENTER:
6511 case '\r': {
6512 struct got_object_id *id = NULL;
6513 struct got_object_qid *pid;
6514 struct got_commit_object *commit = NULL;
6516 view->count = 0;
6517 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6518 s->first_displayed_line, s->selected_line);
6519 if (id == NULL)
6520 break;
6521 err = got_object_open_as_commit(&commit, s->repo, id);
6522 if (err)
6523 break;
6524 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6525 if (*new_view) {
6526 /* traversed from diff view, release diff resources */
6527 err = close_diff_view(*new_view);
6528 if (err)
6529 break;
6530 diff_view = *new_view;
6531 } else {
6532 if (view_is_parent_view(view))
6533 view_get_split(view, &begin_y, &begin_x);
6535 diff_view = view_open(0, 0, begin_y, begin_x,
6536 TOG_VIEW_DIFF);
6537 if (diff_view == NULL) {
6538 got_object_commit_close(commit);
6539 err = got_error_from_errno("view_open");
6540 break;
6543 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6544 id, NULL, NULL, 3, 0, 0, view, s->repo);
6545 got_object_commit_close(commit);
6546 if (err) {
6547 view_close(diff_view);
6548 break;
6550 s->last_diffed_line = s->first_displayed_line - 1 +
6551 s->selected_line;
6552 if (*new_view)
6553 break; /* still open from active diff view */
6554 if (view_is_parent_view(view) &&
6555 view->mode == TOG_VIEW_SPLIT_HRZN) {
6556 err = view_init_hsplit(view, begin_y);
6557 if (err)
6558 break;
6561 view->focussed = 0;
6562 diff_view->focussed = 1;
6563 diff_view->mode = view->mode;
6564 diff_view->nlines = view->lines - begin_y;
6565 if (view_is_parent_view(view)) {
6566 view_transfer_size(diff_view, view);
6567 err = view_close_child(view);
6568 if (err)
6569 break;
6570 err = view_set_child(view, diff_view);
6571 if (err)
6572 break;
6573 view->focus_child = 1;
6574 } else
6575 *new_view = diff_view;
6576 if (err)
6577 break;
6578 break;
6580 case CTRL('d'):
6581 case 'd':
6582 nscroll /= 2;
6583 /* FALL THROUGH */
6584 case KEY_NPAGE:
6585 case CTRL('f'):
6586 case 'f':
6587 case ' ':
6588 if (s->last_displayed_line >= s->blame.nlines &&
6589 s->selected_line >= MIN(s->blame.nlines,
6590 view->nlines - 2)) {
6591 view->count = 0;
6592 break;
6594 if (s->last_displayed_line >= s->blame.nlines &&
6595 s->selected_line < view->nlines - 2) {
6596 s->selected_line +=
6597 MIN(nscroll, s->last_displayed_line -
6598 s->first_displayed_line - s->selected_line + 1);
6600 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6601 s->first_displayed_line += nscroll;
6602 else
6603 s->first_displayed_line =
6604 s->blame.nlines - (view->nlines - 3);
6605 break;
6606 case KEY_RESIZE:
6607 if (s->selected_line > view->nlines - 2) {
6608 s->selected_line = MIN(s->blame.nlines,
6609 view->nlines - 2);
6611 break;
6612 default:
6613 view->count = 0;
6614 break;
6616 return thread_err ? thread_err : err;
6619 static const struct got_error *
6620 reset_blame_view(struct tog_view *view)
6622 const struct got_error *err;
6623 struct tog_blame_view_state *s = &view->state.blame;
6625 view->count = 0;
6626 s->done = 1;
6627 err = stop_blame(&s->blame);
6628 s->done = 0;
6629 if (err)
6630 return err;
6631 return run_blame(view);
6634 static const struct got_error *
6635 cmd_blame(int argc, char *argv[])
6637 const struct got_error *error;
6638 struct got_repository *repo = NULL;
6639 struct got_worktree *worktree = NULL;
6640 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6641 char *link_target = NULL;
6642 struct got_object_id *commit_id = NULL;
6643 struct got_commit_object *commit = NULL;
6644 char *commit_id_str = NULL;
6645 int ch;
6646 struct tog_view *view;
6647 int *pack_fds = NULL;
6649 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6650 switch (ch) {
6651 case 'c':
6652 commit_id_str = optarg;
6653 break;
6654 case 'r':
6655 repo_path = realpath(optarg, NULL);
6656 if (repo_path == NULL)
6657 return got_error_from_errno2("realpath",
6658 optarg);
6659 break;
6660 default:
6661 usage_blame();
6662 /* NOTREACHED */
6666 argc -= optind;
6667 argv += optind;
6669 if (argc != 1)
6670 usage_blame();
6672 error = got_repo_pack_fds_open(&pack_fds);
6673 if (error != NULL)
6674 goto done;
6676 if (repo_path == NULL) {
6677 cwd = getcwd(NULL, 0);
6678 if (cwd == NULL)
6679 return got_error_from_errno("getcwd");
6680 error = got_worktree_open(&worktree, cwd);
6681 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6682 goto done;
6683 if (worktree)
6684 repo_path =
6685 strdup(got_worktree_get_repo_path(worktree));
6686 else
6687 repo_path = strdup(cwd);
6688 if (repo_path == NULL) {
6689 error = got_error_from_errno("strdup");
6690 goto done;
6694 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6695 if (error != NULL)
6696 goto done;
6698 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6699 worktree);
6700 if (error)
6701 goto done;
6703 init_curses();
6705 error = apply_unveil(got_repo_get_path(repo), NULL);
6706 if (error)
6707 goto done;
6709 error = tog_load_refs(repo, 0);
6710 if (error)
6711 goto done;
6713 if (commit_id_str == NULL) {
6714 struct got_reference *head_ref;
6715 error = got_ref_open(&head_ref, repo, worktree ?
6716 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6717 if (error != NULL)
6718 goto done;
6719 error = got_ref_resolve(&commit_id, repo, head_ref);
6720 got_ref_close(head_ref);
6721 } else {
6722 error = got_repo_match_object_id(&commit_id, NULL,
6723 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6725 if (error != NULL)
6726 goto done;
6728 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6729 if (view == NULL) {
6730 error = got_error_from_errno("view_open");
6731 goto done;
6734 error = got_object_open_as_commit(&commit, repo, commit_id);
6735 if (error)
6736 goto done;
6738 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6739 commit, repo);
6740 if (error)
6741 goto done;
6743 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6744 commit_id, repo);
6745 if (error)
6746 goto done;
6747 if (worktree) {
6748 /* Release work tree lock. */
6749 got_worktree_close(worktree);
6750 worktree = NULL;
6752 error = view_loop(view);
6753 done:
6754 free(repo_path);
6755 free(in_repo_path);
6756 free(link_target);
6757 free(cwd);
6758 free(commit_id);
6759 if (commit)
6760 got_object_commit_close(commit);
6761 if (worktree)
6762 got_worktree_close(worktree);
6763 if (repo) {
6764 const struct got_error *close_err = got_repo_close(repo);
6765 if (error == NULL)
6766 error = close_err;
6768 if (pack_fds) {
6769 const struct got_error *pack_err =
6770 got_repo_pack_fds_close(pack_fds);
6771 if (error == NULL)
6772 error = pack_err;
6774 tog_free_refs();
6775 return error;
6778 static const struct got_error *
6779 draw_tree_entries(struct tog_view *view, const char *parent_path)
6781 struct tog_tree_view_state *s = &view->state.tree;
6782 const struct got_error *err = NULL;
6783 struct got_tree_entry *te;
6784 wchar_t *wline;
6785 char *index = NULL;
6786 struct tog_color *tc;
6787 int width, n, nentries, scrollx, i = 1;
6788 int limit = view->nlines;
6790 s->ndisplayed = 0;
6791 if (view_is_hsplit_top(view))
6792 --limit; /* border */
6794 werase(view->window);
6796 if (limit == 0)
6797 return NULL;
6799 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6800 0, 0);
6801 if (err)
6802 return err;
6803 if (view_needs_focus_indication(view))
6804 wstandout(view->window);
6805 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6806 if (tc)
6807 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6808 waddwstr(view->window, wline);
6809 free(wline);
6810 wline = NULL;
6811 while (width++ < view->ncols)
6812 waddch(view->window, ' ');
6813 if (tc)
6814 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6815 if (view_needs_focus_indication(view))
6816 wstandend(view->window);
6817 if (--limit <= 0)
6818 return NULL;
6820 i += s->selected;
6821 if (s->first_displayed_entry) {
6822 i += got_tree_entry_get_index(s->first_displayed_entry);
6823 if (s->tree != s->root)
6824 ++i; /* account for ".." entry */
6826 nentries = got_object_tree_get_nentries(s->tree);
6827 if (asprintf(&index, "[%d/%d] %s",
6828 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6829 return got_error_from_errno("asprintf");
6830 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6831 free(index);
6832 if (err)
6833 return err;
6834 waddwstr(view->window, wline);
6835 free(wline);
6836 wline = NULL;
6837 if (width < view->ncols - 1)
6838 waddch(view->window, '\n');
6839 if (--limit <= 0)
6840 return NULL;
6841 waddch(view->window, '\n');
6842 if (--limit <= 0)
6843 return NULL;
6845 if (s->first_displayed_entry == NULL) {
6846 te = got_object_tree_get_first_entry(s->tree);
6847 if (s->selected == 0) {
6848 if (view->focussed)
6849 wstandout(view->window);
6850 s->selected_entry = NULL;
6852 waddstr(view->window, " ..\n"); /* parent directory */
6853 if (s->selected == 0 && view->focussed)
6854 wstandend(view->window);
6855 s->ndisplayed++;
6856 if (--limit <= 0)
6857 return NULL;
6858 n = 1;
6859 } else {
6860 n = 0;
6861 te = s->first_displayed_entry;
6864 view->maxx = 0;
6865 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6866 char *line = NULL, *id_str = NULL, *link_target = NULL;
6867 const char *modestr = "";
6868 mode_t mode;
6870 te = got_object_tree_get_entry(s->tree, i);
6871 mode = got_tree_entry_get_mode(te);
6873 if (s->show_ids) {
6874 err = got_object_id_str(&id_str,
6875 got_tree_entry_get_id(te));
6876 if (err)
6877 return got_error_from_errno(
6878 "got_object_id_str");
6880 if (got_object_tree_entry_is_submodule(te))
6881 modestr = "$";
6882 else if (S_ISLNK(mode)) {
6883 int i;
6885 err = got_tree_entry_get_symlink_target(&link_target,
6886 te, s->repo);
6887 if (err) {
6888 free(id_str);
6889 return err;
6891 for (i = 0; i < strlen(link_target); i++) {
6892 if (!isprint((unsigned char)link_target[i]))
6893 link_target[i] = '?';
6895 modestr = "@";
6897 else if (S_ISDIR(mode))
6898 modestr = "/";
6899 else if (mode & S_IXUSR)
6900 modestr = "*";
6901 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6902 got_tree_entry_get_name(te), modestr,
6903 link_target ? " -> ": "",
6904 link_target ? link_target : "") == -1) {
6905 free(id_str);
6906 free(link_target);
6907 return got_error_from_errno("asprintf");
6909 free(id_str);
6910 free(link_target);
6912 /* use full line width to determine view->maxx */
6913 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
6914 if (err) {
6915 free(line);
6916 break;
6918 view->maxx = MAX(view->maxx, width);
6919 free(wline);
6920 wline = NULL;
6922 err = format_line(&wline, &width, &scrollx, line, view->x,
6923 view->ncols, 0, 0);
6924 if (err) {
6925 free(line);
6926 break;
6928 if (n == s->selected) {
6929 if (view->focussed)
6930 wstandout(view->window);
6931 s->selected_entry = te;
6933 tc = match_color(&s->colors, line);
6934 if (tc)
6935 wattr_on(view->window,
6936 COLOR_PAIR(tc->colorpair), NULL);
6937 waddwstr(view->window, &wline[scrollx]);
6938 if (tc)
6939 wattr_off(view->window,
6940 COLOR_PAIR(tc->colorpair), NULL);
6941 if (width < view->ncols)
6942 waddch(view->window, '\n');
6943 if (n == s->selected && view->focussed)
6944 wstandend(view->window);
6945 free(line);
6946 free(wline);
6947 wline = NULL;
6948 n++;
6949 s->ndisplayed++;
6950 s->last_displayed_entry = te;
6951 if (--limit <= 0)
6952 break;
6955 return err;
6958 static void
6959 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6961 struct got_tree_entry *te;
6962 int isroot = s->tree == s->root;
6963 int i = 0;
6965 if (s->first_displayed_entry == NULL)
6966 return;
6968 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6969 while (i++ < maxscroll) {
6970 if (te == NULL) {
6971 if (!isroot)
6972 s->first_displayed_entry = NULL;
6973 break;
6975 s->first_displayed_entry = te;
6976 te = got_tree_entry_get_prev(s->tree, te);
6980 static const struct got_error *
6981 tree_scroll_down(struct tog_view *view, int maxscroll)
6983 struct tog_tree_view_state *s = &view->state.tree;
6984 struct got_tree_entry *next, *last;
6985 int n = 0;
6987 if (s->first_displayed_entry)
6988 next = got_tree_entry_get_next(s->tree,
6989 s->first_displayed_entry);
6990 else
6991 next = got_object_tree_get_first_entry(s->tree);
6993 last = s->last_displayed_entry;
6994 while (next && n++ < maxscroll) {
6995 if (last) {
6996 s->last_displayed_entry = last;
6997 last = got_tree_entry_get_next(s->tree, last);
6999 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7000 s->first_displayed_entry = next;
7001 next = got_tree_entry_get_next(s->tree, next);
7005 return NULL;
7008 static const struct got_error *
7009 tree_entry_path(char **path, struct tog_parent_trees *parents,
7010 struct got_tree_entry *te)
7012 const struct got_error *err = NULL;
7013 struct tog_parent_tree *pt;
7014 size_t len = 2; /* for leading slash and NUL */
7016 TAILQ_FOREACH(pt, parents, entry)
7017 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7018 + 1 /* slash */;
7019 if (te)
7020 len += strlen(got_tree_entry_get_name(te));
7022 *path = calloc(1, len);
7023 if (path == NULL)
7024 return got_error_from_errno("calloc");
7026 (*path)[0] = '/';
7027 pt = TAILQ_LAST(parents, tog_parent_trees);
7028 while (pt) {
7029 const char *name = got_tree_entry_get_name(pt->selected_entry);
7030 if (strlcat(*path, name, len) >= len) {
7031 err = got_error(GOT_ERR_NO_SPACE);
7032 goto done;
7034 if (strlcat(*path, "/", len) >= len) {
7035 err = got_error(GOT_ERR_NO_SPACE);
7036 goto done;
7038 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7040 if (te) {
7041 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7042 err = got_error(GOT_ERR_NO_SPACE);
7043 goto done;
7046 done:
7047 if (err) {
7048 free(*path);
7049 *path = NULL;
7051 return err;
7054 static const struct got_error *
7055 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7056 struct got_tree_entry *te, struct tog_parent_trees *parents,
7057 struct got_object_id *commit_id, struct got_repository *repo)
7059 const struct got_error *err = NULL;
7060 char *path;
7061 struct tog_view *blame_view;
7063 *new_view = NULL;
7065 err = tree_entry_path(&path, parents, te);
7066 if (err)
7067 return err;
7069 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7070 if (blame_view == NULL) {
7071 err = got_error_from_errno("view_open");
7072 goto done;
7075 err = open_blame_view(blame_view, path, commit_id, repo);
7076 if (err) {
7077 if (err->code == GOT_ERR_CANCELLED)
7078 err = NULL;
7079 view_close(blame_view);
7080 } else
7081 *new_view = blame_view;
7082 done:
7083 free(path);
7084 return err;
7087 static const struct got_error *
7088 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7089 struct tog_tree_view_state *s)
7091 struct tog_view *log_view;
7092 const struct got_error *err = NULL;
7093 char *path;
7095 *new_view = NULL;
7097 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7098 if (log_view == NULL)
7099 return got_error_from_errno("view_open");
7101 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7102 if (err)
7103 return err;
7105 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7106 path, 0);
7107 if (err)
7108 view_close(log_view);
7109 else
7110 *new_view = log_view;
7111 free(path);
7112 return err;
7115 static const struct got_error *
7116 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7117 const char *head_ref_name, struct got_repository *repo)
7119 const struct got_error *err = NULL;
7120 char *commit_id_str = NULL;
7121 struct tog_tree_view_state *s = &view->state.tree;
7122 struct got_commit_object *commit = NULL;
7124 TAILQ_INIT(&s->parents);
7125 STAILQ_INIT(&s->colors);
7127 s->commit_id = got_object_id_dup(commit_id);
7128 if (s->commit_id == NULL)
7129 return got_error_from_errno("got_object_id_dup");
7131 err = got_object_open_as_commit(&commit, repo, commit_id);
7132 if (err)
7133 goto done;
7136 * The root is opened here and will be closed when the view is closed.
7137 * Any visited subtrees and their path-wise parents are opened and
7138 * closed on demand.
7140 err = got_object_open_as_tree(&s->root, repo,
7141 got_object_commit_get_tree_id(commit));
7142 if (err)
7143 goto done;
7144 s->tree = s->root;
7146 err = got_object_id_str(&commit_id_str, commit_id);
7147 if (err != NULL)
7148 goto done;
7150 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7151 err = got_error_from_errno("asprintf");
7152 goto done;
7155 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7156 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7157 if (head_ref_name) {
7158 s->head_ref_name = strdup(head_ref_name);
7159 if (s->head_ref_name == NULL) {
7160 err = got_error_from_errno("strdup");
7161 goto done;
7164 s->repo = repo;
7166 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7167 err = add_color(&s->colors, "\\$$",
7168 TOG_COLOR_TREE_SUBMODULE,
7169 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7170 if (err)
7171 goto done;
7172 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7173 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7174 if (err)
7175 goto done;
7176 err = add_color(&s->colors, "/$",
7177 TOG_COLOR_TREE_DIRECTORY,
7178 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7179 if (err)
7180 goto done;
7182 err = add_color(&s->colors, "\\*$",
7183 TOG_COLOR_TREE_EXECUTABLE,
7184 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7185 if (err)
7186 goto done;
7188 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7189 get_color_value("TOG_COLOR_COMMIT"));
7190 if (err)
7191 goto done;
7194 view->show = show_tree_view;
7195 view->input = input_tree_view;
7196 view->close = close_tree_view;
7197 view->search_start = search_start_tree_view;
7198 view->search_next = search_next_tree_view;
7199 done:
7200 free(commit_id_str);
7201 if (commit)
7202 got_object_commit_close(commit);
7203 if (err)
7204 close_tree_view(view);
7205 return err;
7208 static const struct got_error *
7209 close_tree_view(struct tog_view *view)
7211 struct tog_tree_view_state *s = &view->state.tree;
7213 free_colors(&s->colors);
7214 free(s->tree_label);
7215 s->tree_label = NULL;
7216 free(s->commit_id);
7217 s->commit_id = NULL;
7218 free(s->head_ref_name);
7219 s->head_ref_name = NULL;
7220 while (!TAILQ_EMPTY(&s->parents)) {
7221 struct tog_parent_tree *parent;
7222 parent = TAILQ_FIRST(&s->parents);
7223 TAILQ_REMOVE(&s->parents, parent, entry);
7224 if (parent->tree != s->root)
7225 got_object_tree_close(parent->tree);
7226 free(parent);
7229 if (s->tree != NULL && s->tree != s->root)
7230 got_object_tree_close(s->tree);
7231 if (s->root)
7232 got_object_tree_close(s->root);
7233 return NULL;
7236 static const struct got_error *
7237 search_start_tree_view(struct tog_view *view)
7239 struct tog_tree_view_state *s = &view->state.tree;
7241 s->matched_entry = NULL;
7242 return NULL;
7245 static int
7246 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7248 regmatch_t regmatch;
7250 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7251 0) == 0;
7254 static const struct got_error *
7255 search_next_tree_view(struct tog_view *view)
7257 struct tog_tree_view_state *s = &view->state.tree;
7258 struct got_tree_entry *te = NULL;
7260 if (!view->searching) {
7261 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7262 return NULL;
7265 if (s->matched_entry) {
7266 if (view->searching == TOG_SEARCH_FORWARD) {
7267 if (s->selected_entry)
7268 te = got_tree_entry_get_next(s->tree,
7269 s->selected_entry);
7270 else
7271 te = got_object_tree_get_first_entry(s->tree);
7272 } else {
7273 if (s->selected_entry == NULL)
7274 te = got_object_tree_get_last_entry(s->tree);
7275 else
7276 te = got_tree_entry_get_prev(s->tree,
7277 s->selected_entry);
7279 } else {
7280 if (s->selected_entry)
7281 te = s->selected_entry;
7282 else if (view->searching == TOG_SEARCH_FORWARD)
7283 te = got_object_tree_get_first_entry(s->tree);
7284 else
7285 te = got_object_tree_get_last_entry(s->tree);
7288 while (1) {
7289 if (te == NULL) {
7290 if (s->matched_entry == NULL) {
7291 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7292 return NULL;
7294 if (view->searching == TOG_SEARCH_FORWARD)
7295 te = got_object_tree_get_first_entry(s->tree);
7296 else
7297 te = got_object_tree_get_last_entry(s->tree);
7300 if (match_tree_entry(te, &view->regex)) {
7301 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7302 s->matched_entry = te;
7303 break;
7306 if (view->searching == TOG_SEARCH_FORWARD)
7307 te = got_tree_entry_get_next(s->tree, te);
7308 else
7309 te = got_tree_entry_get_prev(s->tree, te);
7312 if (s->matched_entry) {
7313 s->first_displayed_entry = s->matched_entry;
7314 s->selected = 0;
7317 return NULL;
7320 static const struct got_error *
7321 show_tree_view(struct tog_view *view)
7323 const struct got_error *err = NULL;
7324 struct tog_tree_view_state *s = &view->state.tree;
7325 char *parent_path;
7327 err = tree_entry_path(&parent_path, &s->parents, NULL);
7328 if (err)
7329 return err;
7331 err = draw_tree_entries(view, parent_path);
7332 free(parent_path);
7334 view_border(view);
7335 return err;
7338 static const struct got_error *
7339 tree_goto_line(struct tog_view *view, int nlines)
7341 const struct got_error *err = NULL;
7342 struct tog_tree_view_state *s = &view->state.tree;
7343 struct got_tree_entry **fte, **lte, **ste;
7344 int g, last, first = 1, i = 1;
7345 int root = s->tree == s->root;
7346 int off = root ? 1 : 2;
7348 g = view->gline;
7349 view->gline = 0;
7351 if (g == 0)
7352 g = 1;
7353 else if (g > got_object_tree_get_nentries(s->tree))
7354 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7356 fte = &s->first_displayed_entry;
7357 lte = &s->last_displayed_entry;
7358 ste = &s->selected_entry;
7360 if (*fte != NULL) {
7361 first = got_tree_entry_get_index(*fte);
7362 first += off; /* account for ".." */
7364 last = got_tree_entry_get_index(*lte);
7365 last += off;
7367 if (g >= first && g <= last && g - first < nlines) {
7368 s->selected = g - first;
7369 return NULL; /* gline is on the current page */
7372 if (*ste != NULL) {
7373 i = got_tree_entry_get_index(*ste);
7374 i += off;
7377 if (i < g) {
7378 err = tree_scroll_down(view, g - i);
7379 if (err)
7380 return err;
7381 if (got_tree_entry_get_index(*lte) >=
7382 got_object_tree_get_nentries(s->tree) - 1 &&
7383 first + s->selected < g &&
7384 s->selected < s->ndisplayed - 1) {
7385 first = got_tree_entry_get_index(*fte);
7386 first += off;
7387 s->selected = g - first;
7389 } else if (i > g)
7390 tree_scroll_up(s, i - g);
7392 if (g < nlines &&
7393 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7394 s->selected = g - 1;
7396 return NULL;
7399 static const struct got_error *
7400 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7402 const struct got_error *err = NULL;
7403 struct tog_tree_view_state *s = &view->state.tree;
7404 struct got_tree_entry *te;
7405 int n, nscroll = view->nlines - 3;
7407 if (view->gline)
7408 return tree_goto_line(view, nscroll);
7410 switch (ch) {
7411 case '0':
7412 case '$':
7413 case KEY_RIGHT:
7414 case 'l':
7415 case KEY_LEFT:
7416 case 'h':
7417 horizontal_scroll_input(view, ch);
7418 break;
7419 case 'i':
7420 s->show_ids = !s->show_ids;
7421 view->count = 0;
7422 break;
7423 case 'L':
7424 view->count = 0;
7425 if (!s->selected_entry)
7426 break;
7427 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7428 break;
7429 case 'R':
7430 view->count = 0;
7431 err = view_request_new(new_view, view, TOG_VIEW_REF);
7432 break;
7433 case 'g':
7434 case '=':
7435 case KEY_HOME:
7436 s->selected = 0;
7437 view->count = 0;
7438 if (s->tree == s->root)
7439 s->first_displayed_entry =
7440 got_object_tree_get_first_entry(s->tree);
7441 else
7442 s->first_displayed_entry = NULL;
7443 break;
7444 case 'G':
7445 case '*':
7446 case KEY_END: {
7447 int eos = view->nlines - 3;
7449 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7450 --eos; /* border */
7451 s->selected = 0;
7452 view->count = 0;
7453 te = got_object_tree_get_last_entry(s->tree);
7454 for (n = 0; n < eos; n++) {
7455 if (te == NULL) {
7456 if (s->tree != s->root) {
7457 s->first_displayed_entry = NULL;
7458 n++;
7460 break;
7462 s->first_displayed_entry = te;
7463 te = got_tree_entry_get_prev(s->tree, te);
7465 if (n > 0)
7466 s->selected = n - 1;
7467 break;
7469 case 'k':
7470 case KEY_UP:
7471 case CTRL('p'):
7472 if (s->selected > 0) {
7473 s->selected--;
7474 break;
7476 tree_scroll_up(s, 1);
7477 if (s->selected_entry == NULL ||
7478 (s->tree == s->root && s->selected_entry ==
7479 got_object_tree_get_first_entry(s->tree)))
7480 view->count = 0;
7481 break;
7482 case CTRL('u'):
7483 case 'u':
7484 nscroll /= 2;
7485 /* FALL THROUGH */
7486 case KEY_PPAGE:
7487 case CTRL('b'):
7488 case 'b':
7489 if (s->tree == s->root) {
7490 if (got_object_tree_get_first_entry(s->tree) ==
7491 s->first_displayed_entry)
7492 s->selected -= MIN(s->selected, nscroll);
7493 } else {
7494 if (s->first_displayed_entry == NULL)
7495 s->selected -= MIN(s->selected, nscroll);
7497 tree_scroll_up(s, MAX(0, nscroll));
7498 if (s->selected_entry == NULL ||
7499 (s->tree == s->root && s->selected_entry ==
7500 got_object_tree_get_first_entry(s->tree)))
7501 view->count = 0;
7502 break;
7503 case 'j':
7504 case KEY_DOWN:
7505 case CTRL('n'):
7506 if (s->selected < s->ndisplayed - 1) {
7507 s->selected++;
7508 break;
7510 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7511 == NULL) {
7512 /* can't scroll any further */
7513 view->count = 0;
7514 break;
7516 tree_scroll_down(view, 1);
7517 break;
7518 case CTRL('d'):
7519 case 'd':
7520 nscroll /= 2;
7521 /* FALL THROUGH */
7522 case KEY_NPAGE:
7523 case CTRL('f'):
7524 case 'f':
7525 case ' ':
7526 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7527 == NULL) {
7528 /* can't scroll any further; move cursor down */
7529 if (s->selected < s->ndisplayed - 1)
7530 s->selected += MIN(nscroll,
7531 s->ndisplayed - s->selected - 1);
7532 else
7533 view->count = 0;
7534 break;
7536 tree_scroll_down(view, nscroll);
7537 break;
7538 case KEY_ENTER:
7539 case '\r':
7540 case KEY_BACKSPACE:
7541 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7542 struct tog_parent_tree *parent;
7543 /* user selected '..' */
7544 if (s->tree == s->root) {
7545 view->count = 0;
7546 break;
7548 parent = TAILQ_FIRST(&s->parents);
7549 TAILQ_REMOVE(&s->parents, parent,
7550 entry);
7551 got_object_tree_close(s->tree);
7552 s->tree = parent->tree;
7553 s->first_displayed_entry =
7554 parent->first_displayed_entry;
7555 s->selected_entry =
7556 parent->selected_entry;
7557 s->selected = parent->selected;
7558 if (s->selected > view->nlines - 3) {
7559 err = offset_selection_down(view);
7560 if (err)
7561 break;
7563 free(parent);
7564 } else if (S_ISDIR(got_tree_entry_get_mode(
7565 s->selected_entry))) {
7566 struct got_tree_object *subtree;
7567 view->count = 0;
7568 err = got_object_open_as_tree(&subtree, s->repo,
7569 got_tree_entry_get_id(s->selected_entry));
7570 if (err)
7571 break;
7572 err = tree_view_visit_subtree(s, subtree);
7573 if (err) {
7574 got_object_tree_close(subtree);
7575 break;
7577 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7578 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7579 break;
7580 case KEY_RESIZE:
7581 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7582 s->selected = view->nlines - 4;
7583 view->count = 0;
7584 break;
7585 default:
7586 view->count = 0;
7587 break;
7590 return err;
7593 __dead static void
7594 usage_tree(void)
7596 endwin();
7597 fprintf(stderr,
7598 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7599 getprogname());
7600 exit(1);
7603 static const struct got_error *
7604 cmd_tree(int argc, char *argv[])
7606 const struct got_error *error;
7607 struct got_repository *repo = NULL;
7608 struct got_worktree *worktree = NULL;
7609 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7610 struct got_object_id *commit_id = NULL;
7611 struct got_commit_object *commit = NULL;
7612 const char *commit_id_arg = NULL;
7613 char *label = NULL;
7614 struct got_reference *ref = NULL;
7615 const char *head_ref_name = NULL;
7616 int ch;
7617 struct tog_view *view;
7618 int *pack_fds = NULL;
7620 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7621 switch (ch) {
7622 case 'c':
7623 commit_id_arg = optarg;
7624 break;
7625 case 'r':
7626 repo_path = realpath(optarg, NULL);
7627 if (repo_path == NULL)
7628 return got_error_from_errno2("realpath",
7629 optarg);
7630 break;
7631 default:
7632 usage_tree();
7633 /* NOTREACHED */
7637 argc -= optind;
7638 argv += optind;
7640 if (argc > 1)
7641 usage_tree();
7643 error = got_repo_pack_fds_open(&pack_fds);
7644 if (error != NULL)
7645 goto done;
7647 if (repo_path == NULL) {
7648 cwd = getcwd(NULL, 0);
7649 if (cwd == NULL)
7650 return got_error_from_errno("getcwd");
7651 error = got_worktree_open(&worktree, cwd);
7652 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7653 goto done;
7654 if (worktree)
7655 repo_path =
7656 strdup(got_worktree_get_repo_path(worktree));
7657 else
7658 repo_path = strdup(cwd);
7659 if (repo_path == NULL) {
7660 error = got_error_from_errno("strdup");
7661 goto done;
7665 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7666 if (error != NULL)
7667 goto done;
7669 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7670 repo, worktree);
7671 if (error)
7672 goto done;
7674 init_curses();
7676 error = apply_unveil(got_repo_get_path(repo), NULL);
7677 if (error)
7678 goto done;
7680 error = tog_load_refs(repo, 0);
7681 if (error)
7682 goto done;
7684 if (commit_id_arg == NULL) {
7685 error = got_repo_match_object_id(&commit_id, &label,
7686 worktree ? got_worktree_get_head_ref_name(worktree) :
7687 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7688 if (error)
7689 goto done;
7690 head_ref_name = label;
7691 } else {
7692 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7693 if (error == NULL)
7694 head_ref_name = got_ref_get_name(ref);
7695 else if (error->code != GOT_ERR_NOT_REF)
7696 goto done;
7697 error = got_repo_match_object_id(&commit_id, NULL,
7698 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7699 if (error)
7700 goto done;
7703 error = got_object_open_as_commit(&commit, repo, commit_id);
7704 if (error)
7705 goto done;
7707 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7708 if (view == NULL) {
7709 error = got_error_from_errno("view_open");
7710 goto done;
7712 error = open_tree_view(view, commit_id, head_ref_name, repo);
7713 if (error)
7714 goto done;
7715 if (!got_path_is_root_dir(in_repo_path)) {
7716 error = tree_view_walk_path(&view->state.tree, commit,
7717 in_repo_path);
7718 if (error)
7719 goto done;
7722 if (worktree) {
7723 /* Release work tree lock. */
7724 got_worktree_close(worktree);
7725 worktree = NULL;
7727 error = view_loop(view);
7728 done:
7729 free(repo_path);
7730 free(cwd);
7731 free(commit_id);
7732 free(label);
7733 if (ref)
7734 got_ref_close(ref);
7735 if (repo) {
7736 const struct got_error *close_err = got_repo_close(repo);
7737 if (error == NULL)
7738 error = close_err;
7740 if (pack_fds) {
7741 const struct got_error *pack_err =
7742 got_repo_pack_fds_close(pack_fds);
7743 if (error == NULL)
7744 error = pack_err;
7746 tog_free_refs();
7747 return error;
7750 static const struct got_error *
7751 ref_view_load_refs(struct tog_ref_view_state *s)
7753 struct got_reflist_entry *sre;
7754 struct tog_reflist_entry *re;
7756 s->nrefs = 0;
7757 TAILQ_FOREACH(sre, &tog_refs, entry) {
7758 if (strncmp(got_ref_get_name(sre->ref),
7759 "refs/got/", 9) == 0 &&
7760 strncmp(got_ref_get_name(sre->ref),
7761 "refs/got/backup/", 16) != 0)
7762 continue;
7764 re = malloc(sizeof(*re));
7765 if (re == NULL)
7766 return got_error_from_errno("malloc");
7768 re->ref = got_ref_dup(sre->ref);
7769 if (re->ref == NULL)
7770 return got_error_from_errno("got_ref_dup");
7771 re->idx = s->nrefs++;
7772 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7775 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7776 return NULL;
7779 static void
7780 ref_view_free_refs(struct tog_ref_view_state *s)
7782 struct tog_reflist_entry *re;
7784 while (!TAILQ_EMPTY(&s->refs)) {
7785 re = TAILQ_FIRST(&s->refs);
7786 TAILQ_REMOVE(&s->refs, re, entry);
7787 got_ref_close(re->ref);
7788 free(re);
7792 static const struct got_error *
7793 open_ref_view(struct tog_view *view, struct got_repository *repo)
7795 const struct got_error *err = NULL;
7796 struct tog_ref_view_state *s = &view->state.ref;
7798 s->selected_entry = 0;
7799 s->repo = repo;
7801 TAILQ_INIT(&s->refs);
7802 STAILQ_INIT(&s->colors);
7804 err = ref_view_load_refs(s);
7805 if (err)
7806 return err;
7808 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7809 err = add_color(&s->colors, "^refs/heads/",
7810 TOG_COLOR_REFS_HEADS,
7811 get_color_value("TOG_COLOR_REFS_HEADS"));
7812 if (err)
7813 goto done;
7815 err = add_color(&s->colors, "^refs/tags/",
7816 TOG_COLOR_REFS_TAGS,
7817 get_color_value("TOG_COLOR_REFS_TAGS"));
7818 if (err)
7819 goto done;
7821 err = add_color(&s->colors, "^refs/remotes/",
7822 TOG_COLOR_REFS_REMOTES,
7823 get_color_value("TOG_COLOR_REFS_REMOTES"));
7824 if (err)
7825 goto done;
7827 err = add_color(&s->colors, "^refs/got/backup/",
7828 TOG_COLOR_REFS_BACKUP,
7829 get_color_value("TOG_COLOR_REFS_BACKUP"));
7830 if (err)
7831 goto done;
7834 view->show = show_ref_view;
7835 view->input = input_ref_view;
7836 view->close = close_ref_view;
7837 view->search_start = search_start_ref_view;
7838 view->search_next = search_next_ref_view;
7839 done:
7840 if (err)
7841 free_colors(&s->colors);
7842 return err;
7845 static const struct got_error *
7846 close_ref_view(struct tog_view *view)
7848 struct tog_ref_view_state *s = &view->state.ref;
7850 ref_view_free_refs(s);
7851 free_colors(&s->colors);
7853 return NULL;
7856 static const struct got_error *
7857 resolve_reflist_entry(struct got_object_id **commit_id,
7858 struct tog_reflist_entry *re, struct got_repository *repo)
7860 const struct got_error *err = NULL;
7861 struct got_object_id *obj_id;
7862 struct got_tag_object *tag = NULL;
7863 int obj_type;
7865 *commit_id = NULL;
7867 err = got_ref_resolve(&obj_id, repo, re->ref);
7868 if (err)
7869 return err;
7871 err = got_object_get_type(&obj_type, repo, obj_id);
7872 if (err)
7873 goto done;
7875 switch (obj_type) {
7876 case GOT_OBJ_TYPE_COMMIT:
7877 *commit_id = obj_id;
7878 break;
7879 case GOT_OBJ_TYPE_TAG:
7880 err = got_object_open_as_tag(&tag, repo, obj_id);
7881 if (err)
7882 goto done;
7883 free(obj_id);
7884 err = got_object_get_type(&obj_type, repo,
7885 got_object_tag_get_object_id(tag));
7886 if (err)
7887 goto done;
7888 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7889 err = got_error(GOT_ERR_OBJ_TYPE);
7890 goto done;
7892 *commit_id = got_object_id_dup(
7893 got_object_tag_get_object_id(tag));
7894 if (*commit_id == NULL) {
7895 err = got_error_from_errno("got_object_id_dup");
7896 goto done;
7898 break;
7899 default:
7900 err = got_error(GOT_ERR_OBJ_TYPE);
7901 break;
7904 done:
7905 if (tag)
7906 got_object_tag_close(tag);
7907 if (err) {
7908 free(*commit_id);
7909 *commit_id = NULL;
7911 return err;
7914 static const struct got_error *
7915 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7916 struct tog_reflist_entry *re, struct got_repository *repo)
7918 struct tog_view *log_view;
7919 const struct got_error *err = NULL;
7920 struct got_object_id *commit_id = NULL;
7922 *new_view = NULL;
7924 err = resolve_reflist_entry(&commit_id, re, repo);
7925 if (err) {
7926 if (err->code != GOT_ERR_OBJ_TYPE)
7927 return err;
7928 else
7929 return NULL;
7932 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7933 if (log_view == NULL) {
7934 err = got_error_from_errno("view_open");
7935 goto done;
7938 err = open_log_view(log_view, commit_id, repo,
7939 got_ref_get_name(re->ref), "", 0);
7940 done:
7941 if (err)
7942 view_close(log_view);
7943 else
7944 *new_view = log_view;
7945 free(commit_id);
7946 return err;
7949 static void
7950 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7952 struct tog_reflist_entry *re;
7953 int i = 0;
7955 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7956 return;
7958 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7959 while (i++ < maxscroll) {
7960 if (re == NULL)
7961 break;
7962 s->first_displayed_entry = re;
7963 re = TAILQ_PREV(re, tog_reflist_head, entry);
7967 static const struct got_error *
7968 ref_scroll_down(struct tog_view *view, int maxscroll)
7970 struct tog_ref_view_state *s = &view->state.ref;
7971 struct tog_reflist_entry *next, *last;
7972 int n = 0;
7974 if (s->first_displayed_entry)
7975 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7976 else
7977 next = TAILQ_FIRST(&s->refs);
7979 last = s->last_displayed_entry;
7980 while (next && n++ < maxscroll) {
7981 if (last) {
7982 s->last_displayed_entry = last;
7983 last = TAILQ_NEXT(last, entry);
7985 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7986 s->first_displayed_entry = next;
7987 next = TAILQ_NEXT(next, entry);
7991 return NULL;
7994 static const struct got_error *
7995 search_start_ref_view(struct tog_view *view)
7997 struct tog_ref_view_state *s = &view->state.ref;
7999 s->matched_entry = NULL;
8000 return NULL;
8003 static int
8004 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8006 regmatch_t regmatch;
8008 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8009 0) == 0;
8012 static const struct got_error *
8013 search_next_ref_view(struct tog_view *view)
8015 struct tog_ref_view_state *s = &view->state.ref;
8016 struct tog_reflist_entry *re = NULL;
8018 if (!view->searching) {
8019 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8020 return NULL;
8023 if (s->matched_entry) {
8024 if (view->searching == TOG_SEARCH_FORWARD) {
8025 if (s->selected_entry)
8026 re = TAILQ_NEXT(s->selected_entry, entry);
8027 else
8028 re = TAILQ_PREV(s->selected_entry,
8029 tog_reflist_head, entry);
8030 } else {
8031 if (s->selected_entry == NULL)
8032 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8033 else
8034 re = TAILQ_PREV(s->selected_entry,
8035 tog_reflist_head, entry);
8037 } else {
8038 if (s->selected_entry)
8039 re = s->selected_entry;
8040 else if (view->searching == TOG_SEARCH_FORWARD)
8041 re = TAILQ_FIRST(&s->refs);
8042 else
8043 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8046 while (1) {
8047 if (re == NULL) {
8048 if (s->matched_entry == NULL) {
8049 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8050 return NULL;
8052 if (view->searching == TOG_SEARCH_FORWARD)
8053 re = TAILQ_FIRST(&s->refs);
8054 else
8055 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8058 if (match_reflist_entry(re, &view->regex)) {
8059 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8060 s->matched_entry = re;
8061 break;
8064 if (view->searching == TOG_SEARCH_FORWARD)
8065 re = TAILQ_NEXT(re, entry);
8066 else
8067 re = TAILQ_PREV(re, tog_reflist_head, entry);
8070 if (s->matched_entry) {
8071 s->first_displayed_entry = s->matched_entry;
8072 s->selected = 0;
8075 return NULL;
8078 static const struct got_error *
8079 show_ref_view(struct tog_view *view)
8081 const struct got_error *err = NULL;
8082 struct tog_ref_view_state *s = &view->state.ref;
8083 struct tog_reflist_entry *re;
8084 char *line = NULL;
8085 wchar_t *wline;
8086 struct tog_color *tc;
8087 int width, n, scrollx;
8088 int limit = view->nlines;
8090 werase(view->window);
8092 s->ndisplayed = 0;
8093 if (view_is_hsplit_top(view))
8094 --limit; /* border */
8096 if (limit == 0)
8097 return NULL;
8099 re = s->first_displayed_entry;
8101 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8102 s->nrefs) == -1)
8103 return got_error_from_errno("asprintf");
8105 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8106 if (err) {
8107 free(line);
8108 return err;
8110 if (view_needs_focus_indication(view))
8111 wstandout(view->window);
8112 waddwstr(view->window, wline);
8113 while (width++ < view->ncols)
8114 waddch(view->window, ' ');
8115 if (view_needs_focus_indication(view))
8116 wstandend(view->window);
8117 free(wline);
8118 wline = NULL;
8119 free(line);
8120 line = NULL;
8121 if (--limit <= 0)
8122 return NULL;
8124 n = 0;
8125 view->maxx = 0;
8126 while (re && limit > 0) {
8127 char *line = NULL;
8128 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8130 if (s->show_date) {
8131 struct got_commit_object *ci;
8132 struct got_tag_object *tag;
8133 struct got_object_id *id;
8134 struct tm tm;
8135 time_t t;
8137 err = got_ref_resolve(&id, s->repo, re->ref);
8138 if (err)
8139 return err;
8140 err = got_object_open_as_tag(&tag, s->repo, id);
8141 if (err) {
8142 if (err->code != GOT_ERR_OBJ_TYPE) {
8143 free(id);
8144 return err;
8146 err = got_object_open_as_commit(&ci, s->repo,
8147 id);
8148 if (err) {
8149 free(id);
8150 return err;
8152 t = got_object_commit_get_committer_time(ci);
8153 got_object_commit_close(ci);
8154 } else {
8155 t = got_object_tag_get_tagger_time(tag);
8156 got_object_tag_close(tag);
8158 free(id);
8159 if (gmtime_r(&t, &tm) == NULL)
8160 return got_error_from_errno("gmtime_r");
8161 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8162 return got_error(GOT_ERR_NO_SPACE);
8164 if (got_ref_is_symbolic(re->ref)) {
8165 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8166 ymd : "", got_ref_get_name(re->ref),
8167 got_ref_get_symref_target(re->ref)) == -1)
8168 return got_error_from_errno("asprintf");
8169 } else if (s->show_ids) {
8170 struct got_object_id *id;
8171 char *id_str;
8172 err = got_ref_resolve(&id, s->repo, re->ref);
8173 if (err)
8174 return err;
8175 err = got_object_id_str(&id_str, id);
8176 if (err) {
8177 free(id);
8178 return err;
8180 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8181 got_ref_get_name(re->ref), id_str) == -1) {
8182 err = got_error_from_errno("asprintf");
8183 free(id);
8184 free(id_str);
8185 return err;
8187 free(id);
8188 free(id_str);
8189 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8190 got_ref_get_name(re->ref)) == -1)
8191 return got_error_from_errno("asprintf");
8193 /* use full line width to determine view->maxx */
8194 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8195 if (err) {
8196 free(line);
8197 return err;
8199 view->maxx = MAX(view->maxx, width);
8200 free(wline);
8201 wline = NULL;
8203 err = format_line(&wline, &width, &scrollx, line, view->x,
8204 view->ncols, 0, 0);
8205 if (err) {
8206 free(line);
8207 return err;
8209 if (n == s->selected) {
8210 if (view->focussed)
8211 wstandout(view->window);
8212 s->selected_entry = re;
8214 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8215 if (tc)
8216 wattr_on(view->window,
8217 COLOR_PAIR(tc->colorpair), NULL);
8218 waddwstr(view->window, &wline[scrollx]);
8219 if (tc)
8220 wattr_off(view->window,
8221 COLOR_PAIR(tc->colorpair), NULL);
8222 if (width < view->ncols)
8223 waddch(view->window, '\n');
8224 if (n == s->selected && view->focussed)
8225 wstandend(view->window);
8226 free(line);
8227 free(wline);
8228 wline = NULL;
8229 n++;
8230 s->ndisplayed++;
8231 s->last_displayed_entry = re;
8233 limit--;
8234 re = TAILQ_NEXT(re, entry);
8237 view_border(view);
8238 return err;
8241 static const struct got_error *
8242 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8243 struct tog_reflist_entry *re, struct got_repository *repo)
8245 const struct got_error *err = NULL;
8246 struct got_object_id *commit_id = NULL;
8247 struct tog_view *tree_view;
8249 *new_view = NULL;
8251 err = resolve_reflist_entry(&commit_id, re, repo);
8252 if (err) {
8253 if (err->code != GOT_ERR_OBJ_TYPE)
8254 return err;
8255 else
8256 return NULL;
8260 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8261 if (tree_view == NULL) {
8262 err = got_error_from_errno("view_open");
8263 goto done;
8266 err = open_tree_view(tree_view, commit_id,
8267 got_ref_get_name(re->ref), repo);
8268 if (err)
8269 goto done;
8271 *new_view = tree_view;
8272 done:
8273 free(commit_id);
8274 return err;
8277 static const struct got_error *
8278 ref_goto_line(struct tog_view *view, int nlines)
8280 const struct got_error *err = NULL;
8281 struct tog_ref_view_state *s = &view->state.ref;
8282 int g, idx = s->selected_entry->idx;
8284 g = view->gline;
8285 view->gline = 0;
8287 if (g == 0)
8288 g = 1;
8289 else if (g > s->nrefs)
8290 g = s->nrefs;
8292 if (g >= s->first_displayed_entry->idx + 1 &&
8293 g <= s->last_displayed_entry->idx + 1 &&
8294 g - s->first_displayed_entry->idx - 1 < nlines) {
8295 s->selected = g - s->first_displayed_entry->idx - 1;
8296 return NULL;
8299 if (idx + 1 < g) {
8300 err = ref_scroll_down(view, g - idx - 1);
8301 if (err)
8302 return err;
8303 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8304 s->first_displayed_entry->idx + s->selected < g &&
8305 s->selected < s->ndisplayed - 1)
8306 s->selected = g - s->first_displayed_entry->idx - 1;
8307 } else if (idx + 1 > g)
8308 ref_scroll_up(s, idx - g + 1);
8310 if (g < nlines && s->first_displayed_entry->idx == 0)
8311 s->selected = g - 1;
8313 return NULL;
8317 static const struct got_error *
8318 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8320 const struct got_error *err = NULL;
8321 struct tog_ref_view_state *s = &view->state.ref;
8322 struct tog_reflist_entry *re;
8323 int n, nscroll = view->nlines - 1;
8325 if (view->gline)
8326 return ref_goto_line(view, nscroll);
8328 switch (ch) {
8329 case '0':
8330 case '$':
8331 case KEY_RIGHT:
8332 case 'l':
8333 case KEY_LEFT:
8334 case 'h':
8335 horizontal_scroll_input(view, ch);
8336 break;
8337 case 'i':
8338 s->show_ids = !s->show_ids;
8339 view->count = 0;
8340 break;
8341 case 'm':
8342 s->show_date = !s->show_date;
8343 view->count = 0;
8344 break;
8345 case 'o':
8346 s->sort_by_date = !s->sort_by_date;
8347 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8348 view->count = 0;
8349 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8350 got_ref_cmp_by_commit_timestamp_descending :
8351 tog_ref_cmp_by_name, s->repo);
8352 if (err)
8353 break;
8354 got_reflist_object_id_map_free(tog_refs_idmap);
8355 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8356 &tog_refs, s->repo);
8357 if (err)
8358 break;
8359 ref_view_free_refs(s);
8360 err = ref_view_load_refs(s);
8361 break;
8362 case KEY_ENTER:
8363 case '\r':
8364 view->count = 0;
8365 if (!s->selected_entry)
8366 break;
8367 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8368 break;
8369 case 'T':
8370 view->count = 0;
8371 if (!s->selected_entry)
8372 break;
8373 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8374 break;
8375 case 'g':
8376 case '=':
8377 case KEY_HOME:
8378 s->selected = 0;
8379 view->count = 0;
8380 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8381 break;
8382 case 'G':
8383 case '*':
8384 case KEY_END: {
8385 int eos = view->nlines - 1;
8387 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8388 --eos; /* border */
8389 s->selected = 0;
8390 view->count = 0;
8391 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8392 for (n = 0; n < eos; n++) {
8393 if (re == NULL)
8394 break;
8395 s->first_displayed_entry = re;
8396 re = TAILQ_PREV(re, tog_reflist_head, entry);
8398 if (n > 0)
8399 s->selected = n - 1;
8400 break;
8402 case 'k':
8403 case KEY_UP:
8404 case CTRL('p'):
8405 if (s->selected > 0) {
8406 s->selected--;
8407 break;
8409 ref_scroll_up(s, 1);
8410 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8411 view->count = 0;
8412 break;
8413 case CTRL('u'):
8414 case 'u':
8415 nscroll /= 2;
8416 /* FALL THROUGH */
8417 case KEY_PPAGE:
8418 case CTRL('b'):
8419 case 'b':
8420 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8421 s->selected -= MIN(nscroll, s->selected);
8422 ref_scroll_up(s, MAX(0, nscroll));
8423 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8424 view->count = 0;
8425 break;
8426 case 'j':
8427 case KEY_DOWN:
8428 case CTRL('n'):
8429 if (s->selected < s->ndisplayed - 1) {
8430 s->selected++;
8431 break;
8433 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8434 /* can't scroll any further */
8435 view->count = 0;
8436 break;
8438 ref_scroll_down(view, 1);
8439 break;
8440 case CTRL('d'):
8441 case 'd':
8442 nscroll /= 2;
8443 /* FALL THROUGH */
8444 case KEY_NPAGE:
8445 case CTRL('f'):
8446 case 'f':
8447 case ' ':
8448 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8449 /* can't scroll any further; move cursor down */
8450 if (s->selected < s->ndisplayed - 1)
8451 s->selected += MIN(nscroll,
8452 s->ndisplayed - s->selected - 1);
8453 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8454 s->selected += s->ndisplayed - s->selected - 1;
8455 view->count = 0;
8456 break;
8458 ref_scroll_down(view, nscroll);
8459 break;
8460 case CTRL('l'):
8461 view->count = 0;
8462 tog_free_refs();
8463 err = tog_load_refs(s->repo, s->sort_by_date);
8464 if (err)
8465 break;
8466 ref_view_free_refs(s);
8467 err = ref_view_load_refs(s);
8468 break;
8469 case KEY_RESIZE:
8470 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8471 s->selected = view->nlines - 2;
8472 break;
8473 default:
8474 view->count = 0;
8475 break;
8478 return err;
8481 __dead static void
8482 usage_ref(void)
8484 endwin();
8485 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8486 getprogname());
8487 exit(1);
8490 static const struct got_error *
8491 cmd_ref(int argc, char *argv[])
8493 const struct got_error *error;
8494 struct got_repository *repo = NULL;
8495 struct got_worktree *worktree = NULL;
8496 char *cwd = NULL, *repo_path = NULL;
8497 int ch;
8498 struct tog_view *view;
8499 int *pack_fds = NULL;
8501 while ((ch = getopt(argc, argv, "r:")) != -1) {
8502 switch (ch) {
8503 case 'r':
8504 repo_path = realpath(optarg, NULL);
8505 if (repo_path == NULL)
8506 return got_error_from_errno2("realpath",
8507 optarg);
8508 break;
8509 default:
8510 usage_ref();
8511 /* NOTREACHED */
8515 argc -= optind;
8516 argv += optind;
8518 if (argc > 1)
8519 usage_ref();
8521 error = got_repo_pack_fds_open(&pack_fds);
8522 if (error != NULL)
8523 goto done;
8525 if (repo_path == NULL) {
8526 cwd = getcwd(NULL, 0);
8527 if (cwd == NULL)
8528 return got_error_from_errno("getcwd");
8529 error = got_worktree_open(&worktree, cwd);
8530 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8531 goto done;
8532 if (worktree)
8533 repo_path =
8534 strdup(got_worktree_get_repo_path(worktree));
8535 else
8536 repo_path = strdup(cwd);
8537 if (repo_path == NULL) {
8538 error = got_error_from_errno("strdup");
8539 goto done;
8543 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8544 if (error != NULL)
8545 goto done;
8547 init_curses();
8549 error = apply_unveil(got_repo_get_path(repo), NULL);
8550 if (error)
8551 goto done;
8553 error = tog_load_refs(repo, 0);
8554 if (error)
8555 goto done;
8557 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8558 if (view == NULL) {
8559 error = got_error_from_errno("view_open");
8560 goto done;
8563 error = open_ref_view(view, repo);
8564 if (error)
8565 goto done;
8567 if (worktree) {
8568 /* Release work tree lock. */
8569 got_worktree_close(worktree);
8570 worktree = NULL;
8572 error = view_loop(view);
8573 done:
8574 free(repo_path);
8575 free(cwd);
8576 if (repo) {
8577 const struct got_error *close_err = got_repo_close(repo);
8578 if (close_err)
8579 error = close_err;
8581 if (pack_fds) {
8582 const struct got_error *pack_err =
8583 got_repo_pack_fds_close(pack_fds);
8584 if (error == NULL)
8585 error = pack_err;
8587 tog_free_refs();
8588 return error;
8591 static const struct got_error*
8592 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8593 const char *str)
8595 size_t len;
8597 if (win == NULL)
8598 win = stdscr;
8600 len = strlen(str);
8601 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8603 if (focus)
8604 wstandout(win);
8605 if (mvwprintw(win, y, x, "%s", str) == ERR)
8606 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8607 if (focus)
8608 wstandend(win);
8610 return NULL;
8613 static const struct got_error *
8614 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8616 off_t *p;
8618 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8619 if (p == NULL) {
8620 free(*line_offsets);
8621 *line_offsets = NULL;
8622 return got_error_from_errno("reallocarray");
8625 *line_offsets = p;
8626 (*line_offsets)[*nlines] = off;
8627 ++(*nlines);
8628 return NULL;
8631 static const struct got_error *
8632 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8634 *ret = 0;
8636 for (;n > 0; --n, ++km) {
8637 char *t0, *t, *k;
8638 size_t len = 1;
8640 if (km->keys == NULL)
8641 continue;
8643 t = t0 = strdup(km->keys);
8644 if (t0 == NULL)
8645 return got_error_from_errno("strdup");
8647 len += strlen(t);
8648 while ((k = strsep(&t, " ")) != NULL)
8649 len += strlen(k) > 1 ? 2 : 0;
8650 free(t0);
8651 *ret = MAX(*ret, len);
8654 return NULL;
8658 * Write keymap section headers, keys, and key info in km to f.
8659 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8660 * wrap control and symbolic keys in guillemets, else use <>.
8662 static const struct got_error *
8663 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8665 int n, len = width;
8667 if (km->keys) {
8668 static const char *u8_glyph[] = {
8669 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8670 "\xe2\x80\xba" /* U+203A (utf8 >) */
8672 char *t0, *t, *k;
8673 int cs, s, first = 1;
8675 cs = got_locale_is_utf8();
8677 t = t0 = strdup(km->keys);
8678 if (t0 == NULL)
8679 return got_error_from_errno("strdup");
8681 len = strlen(km->keys);
8682 while ((k = strsep(&t, " ")) != NULL) {
8683 s = strlen(k) > 1; /* control or symbolic key */
8684 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8685 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8686 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8687 if (n < 0) {
8688 free(t0);
8689 return got_error_from_errno("fprintf");
8691 first = 0;
8692 len += s ? 2 : 0;
8693 *off += n;
8695 free(t0);
8697 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8698 if (n < 0)
8699 return got_error_from_errno("fprintf");
8700 *off += n;
8702 return NULL;
8705 static const struct got_error *
8706 format_help(struct tog_help_view_state *s)
8708 const struct got_error *err = NULL;
8709 off_t off = 0;
8710 int i, max, n, show = s->all;
8711 static const struct tog_key_map km[] = {
8712 #define KEYMAP_(info, type) { NULL, (info), type }
8713 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8714 GENERATE_HELP
8715 #undef KEYMAP_
8716 #undef KEY_
8719 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8720 if (err)
8721 return err;
8723 n = nitems(km);
8724 err = max_key_str(&max, km, n);
8725 if (err)
8726 return err;
8728 for (i = 0; i < n; ++i) {
8729 if (km[i].keys == NULL) {
8730 show = s->all;
8731 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8732 km[i].type == s->type || s->all)
8733 show = 1;
8735 if (show) {
8736 err = format_help_line(&off, s->f, &km[i], max);
8737 if (err)
8738 return err;
8739 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8740 if (err)
8741 return err;
8744 fputc('\n', s->f);
8745 ++off;
8746 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8747 return err;
8750 static const struct got_error *
8751 create_help(struct tog_help_view_state *s)
8753 FILE *f;
8754 const struct got_error *err;
8756 free(s->line_offsets);
8757 s->line_offsets = NULL;
8758 s->nlines = 0;
8760 f = got_opentemp();
8761 if (f == NULL)
8762 return got_error_from_errno("got_opentemp");
8763 s->f = f;
8765 err = format_help(s);
8766 if (err)
8767 return err;
8769 if (s->f && fflush(s->f) != 0)
8770 return got_error_from_errno("fflush");
8772 return NULL;
8775 static const struct got_error *
8776 search_start_help_view(struct tog_view *view)
8778 view->state.help.matched_line = 0;
8779 return NULL;
8782 static void
8783 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8784 size_t *nlines, int **first, int **last, int **match, int **selected)
8786 struct tog_help_view_state *s = &view->state.help;
8788 *f = s->f;
8789 *nlines = s->nlines;
8790 *line_offsets = s->line_offsets;
8791 *match = &s->matched_line;
8792 *first = &s->first_displayed_line;
8793 *last = &s->last_displayed_line;
8794 *selected = &s->selected_line;
8797 static const struct got_error *
8798 show_help_view(struct tog_view *view)
8800 struct tog_help_view_state *s = &view->state.help;
8801 const struct got_error *err;
8802 regmatch_t *regmatch = &view->regmatch;
8803 wchar_t *wline;
8804 char *line;
8805 ssize_t linelen;
8806 size_t linesz = 0;
8807 int width, nprinted = 0, rc = 0;
8808 int eos = view->nlines;
8810 if (view_is_hsplit_top(view))
8811 --eos; /* account for border */
8813 s->lineno = 0;
8814 rewind(s->f);
8815 werase(view->window);
8817 if (view->gline > s->nlines - 1)
8818 view->gline = s->nlines - 1;
8820 err = win_draw_center(view->window, 0, 0, view->ncols,
8821 view_needs_focus_indication(view),
8822 "tog help (press q to return to tog)");
8823 if (err)
8824 return err;
8825 if (eos <= 1)
8826 return NULL;
8827 waddstr(view->window, "\n\n");
8828 eos -= 2;
8830 s->eof = 0;
8831 view->maxx = 0;
8832 line = NULL;
8833 while (eos > 0 && nprinted < eos) {
8834 attr_t attr = 0;
8836 linelen = getline(&line, &linesz, s->f);
8837 if (linelen == -1) {
8838 if (!feof(s->f)) {
8839 free(line);
8840 return got_ferror(s->f, GOT_ERR_IO);
8842 s->eof = 1;
8843 break;
8845 if (++s->lineno < s->first_displayed_line)
8846 continue;
8847 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8848 continue;
8849 if (s->lineno == view->hiline)
8850 attr = A_STANDOUT;
8852 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8853 view->x ? 1 : 0);
8854 if (err) {
8855 free(line);
8856 return err;
8858 view->maxx = MAX(view->maxx, width);
8859 free(wline);
8860 wline = NULL;
8862 if (attr)
8863 wattron(view->window, attr);
8864 if (s->first_displayed_line + nprinted == s->matched_line &&
8865 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8866 err = add_matched_line(&width, line, view->ncols - 1, 0,
8867 view->window, view->x, regmatch);
8868 if (err) {
8869 free(line);
8870 return err;
8872 } else {
8873 int skip;
8875 err = format_line(&wline, &width, &skip, line,
8876 view->x, view->ncols, 0, view->x ? 1 : 0);
8877 if (err) {
8878 free(line);
8879 return err;
8881 waddwstr(view->window, &wline[skip]);
8882 free(wline);
8883 wline = NULL;
8885 if (s->lineno == view->hiline) {
8886 while (width++ < view->ncols)
8887 waddch(view->window, ' ');
8888 } else {
8889 if (width < view->ncols)
8890 waddch(view->window, '\n');
8892 if (attr)
8893 wattroff(view->window, attr);
8894 if (++nprinted == 1)
8895 s->first_displayed_line = s->lineno;
8897 free(line);
8898 if (nprinted > 0)
8899 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8900 else
8901 s->last_displayed_line = s->first_displayed_line;
8903 view_border(view);
8905 if (s->eof) {
8906 rc = waddnstr(view->window,
8907 "See the tog(1) manual page for full documentation",
8908 view->ncols - 1);
8909 if (rc == ERR)
8910 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8911 } else {
8912 wmove(view->window, view->nlines - 1, 0);
8913 wclrtoeol(view->window);
8914 wstandout(view->window);
8915 rc = waddnstr(view->window, "scroll down for more...",
8916 view->ncols - 1);
8917 if (rc == ERR)
8918 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8919 if (getcurx(view->window) < view->ncols - 6) {
8920 rc = wprintw(view->window, "[%.0f%%]",
8921 100.00 * s->last_displayed_line / s->nlines);
8922 if (rc == ERR)
8923 return got_error_msg(GOT_ERR_IO, "wprintw");
8925 wstandend(view->window);
8928 return NULL;
8931 static const struct got_error *
8932 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8934 struct tog_help_view_state *s = &view->state.help;
8935 const struct got_error *err = NULL;
8936 char *line = NULL;
8937 ssize_t linelen;
8938 size_t linesz = 0;
8939 int eos, nscroll;
8941 eos = nscroll = view->nlines;
8942 if (view_is_hsplit_top(view))
8943 --eos; /* border */
8945 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8947 switch (ch) {
8948 case '0':
8949 case '$':
8950 case KEY_RIGHT:
8951 case 'l':
8952 case KEY_LEFT:
8953 case 'h':
8954 horizontal_scroll_input(view, ch);
8955 break;
8956 case 'g':
8957 case KEY_HOME:
8958 s->first_displayed_line = 1;
8959 view->count = 0;
8960 break;
8961 case 'G':
8962 case KEY_END:
8963 view->count = 0;
8964 if (s->eof)
8965 break;
8966 s->first_displayed_line = (s->nlines - eos) + 3;
8967 s->eof = 1;
8968 break;
8969 case 'k':
8970 case KEY_UP:
8971 if (s->first_displayed_line > 1)
8972 --s->first_displayed_line;
8973 else
8974 view->count = 0;
8975 break;
8976 case CTRL('u'):
8977 case 'u':
8978 nscroll /= 2;
8979 /* FALL THROUGH */
8980 case KEY_PPAGE:
8981 case CTRL('b'):
8982 case 'b':
8983 if (s->first_displayed_line == 1) {
8984 view->count = 0;
8985 break;
8987 while (--nscroll > 0 && s->first_displayed_line > 1)
8988 s->first_displayed_line--;
8989 break;
8990 case 'j':
8991 case KEY_DOWN:
8992 case CTRL('n'):
8993 if (!s->eof)
8994 ++s->first_displayed_line;
8995 else
8996 view->count = 0;
8997 break;
8998 case CTRL('d'):
8999 case 'd':
9000 nscroll /= 2;
9001 /* FALL THROUGH */
9002 case KEY_NPAGE:
9003 case CTRL('f'):
9004 case 'f':
9005 case ' ':
9006 if (s->eof) {
9007 view->count = 0;
9008 break;
9010 while (!s->eof && --nscroll > 0) {
9011 linelen = getline(&line, &linesz, s->f);
9012 s->first_displayed_line++;
9013 if (linelen == -1) {
9014 if (feof(s->f))
9015 s->eof = 1;
9016 else
9017 err = got_ferror(s->f, GOT_ERR_IO);
9018 break;
9021 free(line);
9022 break;
9023 default:
9024 view->count = 0;
9025 break;
9028 return err;
9031 static const struct got_error *
9032 close_help_view(struct tog_view *view)
9034 struct tog_help_view_state *s = &view->state.help;
9036 free(s->line_offsets);
9037 s->line_offsets = NULL;
9038 if (fclose(s->f) == EOF)
9039 return got_error_from_errno("fclose");
9041 return NULL;
9044 static const struct got_error *
9045 reset_help_view(struct tog_view *view)
9047 struct tog_help_view_state *s = &view->state.help;
9050 if (s->f && fclose(s->f) == EOF)
9051 return got_error_from_errno("fclose");
9053 wclear(view->window);
9054 view->count = 0;
9055 view->x = 0;
9056 s->all = !s->all;
9057 s->first_displayed_line = 1;
9058 s->last_displayed_line = view->nlines;
9059 s->matched_line = 0;
9061 return create_help(s);
9064 static const struct got_error *
9065 open_help_view(struct tog_view *view, struct tog_view *parent)
9067 const struct got_error *err = NULL;
9068 struct tog_help_view_state *s = &view->state.help;
9070 s->type = (enum tog_keymap_type)parent->type;
9071 s->first_displayed_line = 1;
9072 s->last_displayed_line = view->nlines;
9073 s->selected_line = 1;
9075 view->show = show_help_view;
9076 view->input = input_help_view;
9077 view->reset = reset_help_view;
9078 view->close = close_help_view;
9079 view->search_start = search_start_help_view;
9080 view->search_setup = search_setup_help_view;
9081 view->search_next = search_next_view_match;
9083 err = create_help(s);
9084 return err;
9087 static const struct got_error *
9088 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9089 enum tog_view_type request, int y, int x)
9091 const struct got_error *err = NULL;
9093 *new_view = NULL;
9095 switch (request) {
9096 case TOG_VIEW_DIFF:
9097 if (view->type == TOG_VIEW_LOG) {
9098 struct tog_log_view_state *s = &view->state.log;
9100 err = open_diff_view_for_commit(new_view, y, x,
9101 s->selected_entry->commit, s->selected_entry->id,
9102 view, s->repo);
9103 } else
9104 return got_error_msg(GOT_ERR_NOT_IMPL,
9105 "parent/child view pair not supported");
9106 break;
9107 case TOG_VIEW_BLAME:
9108 if (view->type == TOG_VIEW_TREE) {
9109 struct tog_tree_view_state *s = &view->state.tree;
9111 err = blame_tree_entry(new_view, y, x,
9112 s->selected_entry, &s->parents, s->commit_id,
9113 s->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_LOG:
9119 if (view->type == TOG_VIEW_BLAME)
9120 err = log_annotated_line(new_view, y, x,
9121 view->state.blame.repo, view->state.blame.id_to_log);
9122 else if (view->type == TOG_VIEW_TREE)
9123 err = log_selected_tree_entry(new_view, y, x,
9124 &view->state.tree);
9125 else if (view->type == TOG_VIEW_REF)
9126 err = log_ref_entry(new_view, y, x,
9127 view->state.ref.selected_entry,
9128 view->state.ref.repo);
9129 else
9130 return got_error_msg(GOT_ERR_NOT_IMPL,
9131 "parent/child view pair not supported");
9132 break;
9133 case TOG_VIEW_TREE:
9134 if (view->type == TOG_VIEW_LOG)
9135 err = browse_commit_tree(new_view, y, x,
9136 view->state.log.selected_entry,
9137 view->state.log.in_repo_path,
9138 view->state.log.head_ref_name,
9139 view->state.log.repo);
9140 else if (view->type == TOG_VIEW_REF)
9141 err = browse_ref_tree(new_view, y, x,
9142 view->state.ref.selected_entry,
9143 view->state.ref.repo);
9144 else
9145 return got_error_msg(GOT_ERR_NOT_IMPL,
9146 "parent/child view pair not supported");
9147 break;
9148 case TOG_VIEW_REF:
9149 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9150 if (*new_view == NULL)
9151 return got_error_from_errno("view_open");
9152 if (view->type == TOG_VIEW_LOG)
9153 err = open_ref_view(*new_view, view->state.log.repo);
9154 else if (view->type == TOG_VIEW_TREE)
9155 err = open_ref_view(*new_view, view->state.tree.repo);
9156 else
9157 err = got_error_msg(GOT_ERR_NOT_IMPL,
9158 "parent/child view pair not supported");
9159 if (err)
9160 view_close(*new_view);
9161 break;
9162 case TOG_VIEW_HELP:
9163 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9164 if (*new_view == NULL)
9165 return got_error_from_errno("view_open");
9166 err = open_help_view(*new_view, view);
9167 if (err)
9168 view_close(*new_view);
9169 break;
9170 default:
9171 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9174 return err;
9178 * If view was scrolled down to move the selected line into view when opening a
9179 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9181 static void
9182 offset_selection_up(struct tog_view *view)
9184 switch (view->type) {
9185 case TOG_VIEW_BLAME: {
9186 struct tog_blame_view_state *s = &view->state.blame;
9187 if (s->first_displayed_line == 1) {
9188 s->selected_line = MAX(s->selected_line - view->offset,
9189 1);
9190 break;
9192 if (s->first_displayed_line > view->offset)
9193 s->first_displayed_line -= view->offset;
9194 else
9195 s->first_displayed_line = 1;
9196 s->selected_line += view->offset;
9197 break;
9199 case TOG_VIEW_LOG:
9200 log_scroll_up(&view->state.log, view->offset);
9201 view->state.log.selected += view->offset;
9202 break;
9203 case TOG_VIEW_REF:
9204 ref_scroll_up(&view->state.ref, view->offset);
9205 view->state.ref.selected += view->offset;
9206 break;
9207 case TOG_VIEW_TREE:
9208 tree_scroll_up(&view->state.tree, view->offset);
9209 view->state.tree.selected += view->offset;
9210 break;
9211 default:
9212 break;
9215 view->offset = 0;
9219 * If the selected line is in the section of screen covered by the bottom split,
9220 * scroll down offset lines to move it into view and index its new position.
9222 static const struct got_error *
9223 offset_selection_down(struct tog_view *view)
9225 const struct got_error *err = NULL;
9226 const struct got_error *(*scrolld)(struct tog_view *, int);
9227 int *selected = NULL;
9228 int header, offset;
9230 switch (view->type) {
9231 case TOG_VIEW_BLAME: {
9232 struct tog_blame_view_state *s = &view->state.blame;
9233 header = 3;
9234 scrolld = NULL;
9235 if (s->selected_line > view->nlines - header) {
9236 offset = abs(view->nlines - s->selected_line - header);
9237 s->first_displayed_line += offset;
9238 s->selected_line -= offset;
9239 view->offset = offset;
9241 break;
9243 case TOG_VIEW_LOG: {
9244 struct tog_log_view_state *s = &view->state.log;
9245 scrolld = &log_scroll_down;
9246 header = view_is_parent_view(view) ? 3 : 2;
9247 selected = &s->selected;
9248 break;
9250 case TOG_VIEW_REF: {
9251 struct tog_ref_view_state *s = &view->state.ref;
9252 scrolld = &ref_scroll_down;
9253 header = 3;
9254 selected = &s->selected;
9255 break;
9257 case TOG_VIEW_TREE: {
9258 struct tog_tree_view_state *s = &view->state.tree;
9259 scrolld = &tree_scroll_down;
9260 header = 5;
9261 selected = &s->selected;
9262 break;
9264 default:
9265 selected = NULL;
9266 scrolld = NULL;
9267 header = 0;
9268 break;
9271 if (selected && *selected > view->nlines - header) {
9272 offset = abs(view->nlines - *selected - header);
9273 view->offset = offset;
9274 if (scrolld && offset) {
9275 err = scrolld(view, offset);
9276 *selected -= offset;
9280 return err;
9283 static void
9284 list_commands(FILE *fp)
9286 size_t i;
9288 fprintf(fp, "commands:");
9289 for (i = 0; i < nitems(tog_commands); i++) {
9290 const struct tog_cmd *cmd = &tog_commands[i];
9291 fprintf(fp, " %s", cmd->name);
9293 fputc('\n', fp);
9296 __dead static void
9297 usage(int hflag, int status)
9299 FILE *fp = (status == 0) ? stdout : stderr;
9301 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9302 getprogname());
9303 if (hflag) {
9304 fprintf(fp, "lazy usage: %s path\n", getprogname());
9305 list_commands(fp);
9307 exit(status);
9310 static char **
9311 make_argv(int argc, ...)
9313 va_list ap;
9314 char **argv;
9315 int i;
9317 va_start(ap, argc);
9319 argv = calloc(argc, sizeof(char *));
9320 if (argv == NULL)
9321 err(1, "calloc");
9322 for (i = 0; i < argc; i++) {
9323 argv[i] = strdup(va_arg(ap, char *));
9324 if (argv[i] == NULL)
9325 err(1, "strdup");
9328 va_end(ap);
9329 return argv;
9333 * Try to convert 'tog path' into a 'tog log path' command.
9334 * The user could simply have mistyped the command rather than knowingly
9335 * provided a path. So check whether argv[0] can in fact be resolved
9336 * to a path in the HEAD commit and print a special error if not.
9337 * This hack is for mpi@ <3
9339 static const struct got_error *
9340 tog_log_with_path(int argc, char *argv[])
9342 const struct got_error *error = NULL, *close_err;
9343 const struct tog_cmd *cmd = NULL;
9344 struct got_repository *repo = NULL;
9345 struct got_worktree *worktree = NULL;
9346 struct got_object_id *commit_id = NULL, *id = NULL;
9347 struct got_commit_object *commit = NULL;
9348 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9349 char *commit_id_str = NULL, **cmd_argv = NULL;
9350 int *pack_fds = NULL;
9352 cwd = getcwd(NULL, 0);
9353 if (cwd == NULL)
9354 return got_error_from_errno("getcwd");
9356 error = got_repo_pack_fds_open(&pack_fds);
9357 if (error != NULL)
9358 goto done;
9360 error = got_worktree_open(&worktree, cwd);
9361 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9362 goto done;
9364 if (worktree)
9365 repo_path = strdup(got_worktree_get_repo_path(worktree));
9366 else
9367 repo_path = strdup(cwd);
9368 if (repo_path == NULL) {
9369 error = got_error_from_errno("strdup");
9370 goto done;
9373 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9374 if (error != NULL)
9375 goto done;
9377 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9378 repo, worktree);
9379 if (error)
9380 goto done;
9382 error = tog_load_refs(repo, 0);
9383 if (error)
9384 goto done;
9385 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9386 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9387 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9388 if (error)
9389 goto done;
9391 if (worktree) {
9392 got_worktree_close(worktree);
9393 worktree = NULL;
9396 error = got_object_open_as_commit(&commit, repo, commit_id);
9397 if (error)
9398 goto done;
9400 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9401 if (error) {
9402 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9403 goto done;
9404 fprintf(stderr, "%s: '%s' is no known command or path\n",
9405 getprogname(), argv[0]);
9406 usage(1, 1);
9407 /* not reached */
9410 error = got_object_id_str(&commit_id_str, commit_id);
9411 if (error)
9412 goto done;
9414 cmd = &tog_commands[0]; /* log */
9415 argc = 4;
9416 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9417 error = cmd->cmd_main(argc, cmd_argv);
9418 done:
9419 if (repo) {
9420 close_err = got_repo_close(repo);
9421 if (error == NULL)
9422 error = close_err;
9424 if (commit)
9425 got_object_commit_close(commit);
9426 if (worktree)
9427 got_worktree_close(worktree);
9428 if (pack_fds) {
9429 const struct got_error *pack_err =
9430 got_repo_pack_fds_close(pack_fds);
9431 if (error == NULL)
9432 error = pack_err;
9434 free(id);
9435 free(commit_id_str);
9436 free(commit_id);
9437 free(cwd);
9438 free(repo_path);
9439 free(in_repo_path);
9440 if (cmd_argv) {
9441 int i;
9442 for (i = 0; i < argc; i++)
9443 free(cmd_argv[i]);
9444 free(cmd_argv);
9446 tog_free_refs();
9447 return error;
9450 int
9451 main(int argc, char *argv[])
9453 const struct got_error *error = NULL;
9454 const struct tog_cmd *cmd = NULL;
9455 int ch, hflag = 0, Vflag = 0;
9456 char **cmd_argv = NULL;
9457 static const struct option longopts[] = {
9458 { "version", no_argument, NULL, 'V' },
9459 { NULL, 0, NULL, 0}
9461 char *diff_algo_str = NULL;
9463 setlocale(LC_CTYPE, "");
9465 #ifndef PROFILE
9466 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9467 NULL) == -1)
9468 err(1, "pledge");
9469 #endif
9471 if (!isatty(STDIN_FILENO))
9472 errx(1, "standard input is not a tty");
9474 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9475 switch (ch) {
9476 case 'h':
9477 hflag = 1;
9478 break;
9479 case 'V':
9480 Vflag = 1;
9481 break;
9482 default:
9483 usage(hflag, 1);
9484 /* NOTREACHED */
9488 argc -= optind;
9489 argv += optind;
9490 optind = 1;
9491 optreset = 1;
9493 if (Vflag) {
9494 got_version_print_str();
9495 return 0;
9498 if (argc == 0) {
9499 if (hflag)
9500 usage(hflag, 0);
9501 /* Build an argument vector which runs a default command. */
9502 cmd = &tog_commands[0];
9503 argc = 1;
9504 cmd_argv = make_argv(argc, cmd->name);
9505 } else {
9506 size_t i;
9508 /* Did the user specify a command? */
9509 for (i = 0; i < nitems(tog_commands); i++) {
9510 if (strncmp(tog_commands[i].name, argv[0],
9511 strlen(argv[0])) == 0) {
9512 cmd = &tog_commands[i];
9513 break;
9518 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9519 if (diff_algo_str) {
9520 if (strcasecmp(diff_algo_str, "patience") == 0)
9521 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9522 if (strcasecmp(diff_algo_str, "myers") == 0)
9523 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9526 if (cmd == NULL) {
9527 if (argc != 1)
9528 usage(0, 1);
9529 /* No command specified; try log with a path */
9530 error = tog_log_with_path(argc, argv);
9531 } else {
9532 if (hflag)
9533 cmd->cmd_usage();
9534 else
9535 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9538 endwin();
9539 if (cmd_argv) {
9540 int i;
9541 for (i = 0; i < argc; i++)
9542 free(cmd_argv[i]);
9543 free(cmd_argv);
9546 if (error && error->code != GOT_ERR_CANCELLED &&
9547 error->code != GOT_ERR_EOF &&
9548 error->code != GOT_ERR_PRIVSEP_EXIT &&
9549 error->code != GOT_ERR_PRIVSEP_PIPE &&
9550 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9551 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9552 return 0;