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);
4582 * The diff driver initialises the first line at offset zero when the
4583 * array isn't prepopulated, skip it; we already have it in *d_lines.
4585 for (i = 1; i < s_nlines; ++i)
4586 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4588 --s_nlines;
4590 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4591 if (p == NULL) {
4592 /* d_lines is freed in close_diff_view() */
4593 return got_error_from_errno("reallocarray");
4596 *d_lines = p;
4598 memcpy(*d_lines + *d_nlines, s_lines + 1, s_nlines * sizeof(*s_lines));
4599 *d_nlines += s_nlines;
4601 return NULL;
4604 static const struct got_error *
4605 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4606 struct got_object_id *commit_id, struct got_reflist_head *refs,
4607 struct got_repository *repo, int ignore_ws, int force_text_diff,
4608 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4610 const struct got_error *err = NULL;
4611 char datebuf[26], *datestr;
4612 struct got_commit_object *commit;
4613 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4614 time_t committer_time;
4615 const char *author, *committer;
4616 char *refs_str = NULL;
4617 struct got_pathlist_entry *pe;
4618 off_t outoff = 0;
4619 int n;
4621 if (refs) {
4622 err = build_refs_str(&refs_str, refs, commit_id, repo);
4623 if (err)
4624 return err;
4627 err = got_object_open_as_commit(&commit, repo, commit_id);
4628 if (err)
4629 return err;
4631 err = got_object_id_str(&id_str, commit_id);
4632 if (err) {
4633 err = got_error_from_errno("got_object_id_str");
4634 goto done;
4637 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4638 if (err)
4639 goto done;
4641 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4642 refs_str ? refs_str : "", refs_str ? ")" : "");
4643 if (n < 0) {
4644 err = got_error_from_errno("fprintf");
4645 goto done;
4647 outoff += n;
4648 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4649 if (err)
4650 goto done;
4652 n = fprintf(outfile, "from: %s\n",
4653 got_object_commit_get_author(commit));
4654 if (n < 0) {
4655 err = got_error_from_errno("fprintf");
4656 goto done;
4658 outoff += n;
4659 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4660 if (err)
4661 goto done;
4663 author = got_object_commit_get_author(commit);
4664 committer = got_object_commit_get_committer(commit);
4665 if (strcmp(author, committer) != 0) {
4666 n = fprintf(outfile, "via: %s\n", committer);
4667 if (n < 0) {
4668 err = got_error_from_errno("fprintf");
4669 goto done;
4671 outoff += n;
4672 err = add_line_metadata(lines, nlines, outoff,
4673 GOT_DIFF_LINE_AUTHOR);
4674 if (err)
4675 goto done;
4677 committer_time = got_object_commit_get_committer_time(commit);
4678 datestr = get_datestr(&committer_time, datebuf);
4679 if (datestr) {
4680 n = fprintf(outfile, "date: %s UTC\n", datestr);
4681 if (n < 0) {
4682 err = got_error_from_errno("fprintf");
4683 goto done;
4685 outoff += n;
4686 err = add_line_metadata(lines, nlines, outoff,
4687 GOT_DIFF_LINE_DATE);
4688 if (err)
4689 goto done;
4691 if (got_object_commit_get_nparents(commit) > 1) {
4692 const struct got_object_id_queue *parent_ids;
4693 struct got_object_qid *qid;
4694 int pn = 1;
4695 parent_ids = got_object_commit_get_parent_ids(commit);
4696 STAILQ_FOREACH(qid, parent_ids, entry) {
4697 err = got_object_id_str(&id_str, &qid->id);
4698 if (err)
4699 goto done;
4700 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4701 if (n < 0) {
4702 err = got_error_from_errno("fprintf");
4703 goto done;
4705 outoff += n;
4706 err = add_line_metadata(lines, nlines, outoff,
4707 GOT_DIFF_LINE_META);
4708 if (err)
4709 goto done;
4710 free(id_str);
4711 id_str = NULL;
4715 err = got_object_commit_get_logmsg(&logmsg, commit);
4716 if (err)
4717 goto done;
4718 s = logmsg;
4719 while ((line = strsep(&s, "\n")) != NULL) {
4720 n = fprintf(outfile, "%s\n", line);
4721 if (n < 0) {
4722 err = got_error_from_errno("fprintf");
4723 goto done;
4725 outoff += n;
4726 err = add_line_metadata(lines, nlines, outoff,
4727 GOT_DIFF_LINE_LOGMSG);
4728 if (err)
4729 goto done;
4732 TAILQ_FOREACH(pe, dsa->paths, entry) {
4733 struct got_diff_changed_path *cp = pe->data;
4734 int pad = dsa->max_path_len - pe->path_len + 1;
4736 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4737 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4738 dsa->rm_cols + 1, cp->rm);
4739 if (n < 0) {
4740 err = got_error_from_errno("fprintf");
4741 goto done;
4743 outoff += n;
4744 err = add_line_metadata(lines, nlines, outoff,
4745 GOT_DIFF_LINE_CHANGES);
4746 if (err)
4747 goto done;
4750 fputc('\n', outfile);
4751 outoff++;
4752 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4753 if (err)
4754 goto done;
4756 n = fprintf(outfile,
4757 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4758 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4759 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4760 if (n < 0) {
4761 err = got_error_from_errno("fprintf");
4762 goto done;
4764 outoff += n;
4765 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4766 if (err)
4767 goto done;
4769 fputc('\n', outfile);
4770 outoff++;
4771 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4772 done:
4773 free(id_str);
4774 free(logmsg);
4775 free(refs_str);
4776 got_object_commit_close(commit);
4777 if (err) {
4778 free(*lines);
4779 *lines = NULL;
4780 *nlines = 0;
4782 return err;
4785 static const struct got_error *
4786 create_diff(struct tog_diff_view_state *s)
4788 const struct got_error *err = NULL;
4789 FILE *f = NULL, *tmp_diff_file = NULL;
4790 int obj_type;
4791 struct got_diff_line *lines = NULL;
4792 struct got_pathlist_head changed_paths;
4794 TAILQ_INIT(&changed_paths);
4796 free(s->lines);
4797 s->lines = malloc(sizeof(*s->lines));
4798 if (s->lines == NULL)
4799 return got_error_from_errno("malloc");
4800 s->nlines = 0;
4802 f = got_opentemp();
4803 if (f == NULL) {
4804 err = got_error_from_errno("got_opentemp");
4805 goto done;
4807 tmp_diff_file = got_opentemp();
4808 if (tmp_diff_file == NULL) {
4809 err = got_error_from_errno("got_opentemp");
4810 goto done;
4812 if (s->f && fclose(s->f) == EOF) {
4813 err = got_error_from_errno("fclose");
4814 goto done;
4816 s->f = f;
4818 if (s->id1)
4819 err = got_object_get_type(&obj_type, s->repo, s->id1);
4820 else
4821 err = got_object_get_type(&obj_type, s->repo, s->id2);
4822 if (err)
4823 goto done;
4825 switch (obj_type) {
4826 case GOT_OBJ_TYPE_BLOB:
4827 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4828 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4829 s->label1, s->label2, tog_diff_algo, s->diff_context,
4830 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
4831 s->f);
4832 break;
4833 case GOT_OBJ_TYPE_TREE:
4834 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4835 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4836 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4837 s->force_text_diff, NULL, s->repo, s->f);
4838 break;
4839 case GOT_OBJ_TYPE_COMMIT: {
4840 const struct got_object_id_queue *parent_ids;
4841 struct got_object_qid *pid;
4842 struct got_commit_object *commit2;
4843 struct got_reflist_head *refs;
4844 size_t nlines = 0;
4845 struct got_diffstat_cb_arg dsa = {
4846 0, 0, 0, 0, 0, 0,
4847 &changed_paths,
4848 s->ignore_whitespace,
4849 s->force_text_diff,
4850 tog_diff_algo
4853 lines = malloc(sizeof(*lines));
4854 if (lines == NULL) {
4855 err = got_error_from_errno("malloc");
4856 goto done;
4859 /* build diff first in tmp file then append to commit info */
4860 err = got_diff_objects_as_commits(&lines, &nlines,
4861 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4862 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4863 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
4864 if (err)
4865 break;
4867 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4868 if (err)
4869 goto done;
4870 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4871 /* Show commit info if we're diffing to a parent/root commit. */
4872 if (s->id1 == NULL) {
4873 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4874 refs, s->repo, s->ignore_whitespace,
4875 s->force_text_diff, &dsa, s->f);
4876 if (err)
4877 goto done;
4878 } else {
4879 parent_ids = got_object_commit_get_parent_ids(commit2);
4880 STAILQ_FOREACH(pid, parent_ids, entry) {
4881 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4882 err = write_commit_info(&s->lines,
4883 &s->nlines, s->id2, refs, s->repo,
4884 s->ignore_whitespace,
4885 s->force_text_diff, &dsa, s->f);
4886 if (err)
4887 goto done;
4888 break;
4892 got_object_commit_close(commit2);
4894 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
4895 lines, nlines);
4896 break;
4898 default:
4899 err = got_error(GOT_ERR_OBJ_TYPE);
4900 break;
4902 done:
4903 free(lines);
4904 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4905 if (s->f && fflush(s->f) != 0 && err == NULL)
4906 err = got_error_from_errno("fflush");
4907 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
4908 err = got_error_from_errno("fclose");
4909 return err;
4912 static void
4913 diff_view_indicate_progress(struct tog_view *view)
4915 mvwaddstr(view->window, 0, 0, "diffing...");
4916 update_panels();
4917 doupdate();
4920 static const struct got_error *
4921 search_start_diff_view(struct tog_view *view)
4923 struct tog_diff_view_state *s = &view->state.diff;
4925 s->matched_line = 0;
4926 return NULL;
4929 static void
4930 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4931 size_t *nlines, int **first, int **last, int **match, int **selected)
4933 struct tog_diff_view_state *s = &view->state.diff;
4935 *f = s->f;
4936 *nlines = s->nlines;
4937 *line_offsets = NULL;
4938 *match = &s->matched_line;
4939 *first = &s->first_displayed_line;
4940 *last = &s->last_displayed_line;
4941 *selected = &s->selected_line;
4944 static const struct got_error *
4945 search_next_view_match(struct tog_view *view)
4947 const struct got_error *err = NULL;
4948 FILE *f;
4949 int lineno;
4950 char *line = NULL;
4951 size_t linesize = 0;
4952 ssize_t linelen;
4953 off_t *line_offsets;
4954 size_t nlines = 0;
4955 int *first, *last, *match, *selected;
4957 if (!view->search_setup)
4958 return got_error_msg(GOT_ERR_NOT_IMPL,
4959 "view search not supported");
4960 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4961 &match, &selected);
4963 if (!view->searching) {
4964 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4965 return NULL;
4968 if (*match) {
4969 if (view->searching == TOG_SEARCH_FORWARD)
4970 lineno = *match + 1;
4971 else
4972 lineno = *match - 1;
4973 } else
4974 lineno = *first - 1 + *selected;
4976 while (1) {
4977 off_t offset;
4979 if (lineno <= 0 || lineno > nlines) {
4980 if (*match == 0) {
4981 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4982 break;
4985 if (view->searching == TOG_SEARCH_FORWARD)
4986 lineno = 1;
4987 else
4988 lineno = nlines;
4991 offset = view->type == TOG_VIEW_DIFF ?
4992 view->state.diff.lines[lineno - 1].offset :
4993 line_offsets[lineno - 1];
4994 if (fseeko(f, offset, SEEK_SET) != 0) {
4995 free(line);
4996 return got_error_from_errno("fseeko");
4998 linelen = getline(&line, &linesize, f);
4999 if (linelen != -1) {
5000 char *exstr;
5001 err = expand_tab(&exstr, line);
5002 if (err)
5003 break;
5004 if (match_line(exstr, &view->regex, 1,
5005 &view->regmatch)) {
5006 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5007 *match = lineno;
5008 free(exstr);
5009 break;
5011 free(exstr);
5013 if (view->searching == TOG_SEARCH_FORWARD)
5014 lineno++;
5015 else
5016 lineno--;
5018 free(line);
5020 if (*match) {
5021 *first = *match;
5022 *selected = 1;
5025 return err;
5028 static const struct got_error *
5029 close_diff_view(struct tog_view *view)
5031 const struct got_error *err = NULL;
5032 struct tog_diff_view_state *s = &view->state.diff;
5034 free(s->id1);
5035 s->id1 = NULL;
5036 free(s->id2);
5037 s->id2 = NULL;
5038 if (s->f && fclose(s->f) == EOF)
5039 err = got_error_from_errno("fclose");
5040 s->f = NULL;
5041 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5042 err = got_error_from_errno("fclose");
5043 s->f1 = NULL;
5044 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5045 err = got_error_from_errno("fclose");
5046 s->f2 = NULL;
5047 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5048 err = got_error_from_errno("close");
5049 s->fd1 = -1;
5050 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5051 err = got_error_from_errno("close");
5052 s->fd2 = -1;
5053 free(s->lines);
5054 s->lines = NULL;
5055 s->nlines = 0;
5056 return err;
5059 static const struct got_error *
5060 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5061 struct got_object_id *id2, const char *label1, const char *label2,
5062 int diff_context, int ignore_whitespace, int force_text_diff,
5063 struct tog_view *parent_view, struct got_repository *repo)
5065 const struct got_error *err;
5066 struct tog_diff_view_state *s = &view->state.diff;
5068 memset(s, 0, sizeof(*s));
5069 s->fd1 = -1;
5070 s->fd2 = -1;
5072 if (id1 != NULL && id2 != NULL) {
5073 int type1, type2;
5074 err = got_object_get_type(&type1, repo, id1);
5075 if (err)
5076 return err;
5077 err = got_object_get_type(&type2, repo, id2);
5078 if (err)
5079 return err;
5081 if (type1 != type2)
5082 return got_error(GOT_ERR_OBJ_TYPE);
5084 s->first_displayed_line = 1;
5085 s->last_displayed_line = view->nlines;
5086 s->selected_line = 1;
5087 s->repo = repo;
5088 s->id1 = id1;
5089 s->id2 = id2;
5090 s->label1 = label1;
5091 s->label2 = label2;
5093 if (id1) {
5094 s->id1 = got_object_id_dup(id1);
5095 if (s->id1 == NULL)
5096 return got_error_from_errno("got_object_id_dup");
5097 } else
5098 s->id1 = NULL;
5100 s->id2 = got_object_id_dup(id2);
5101 if (s->id2 == NULL) {
5102 err = got_error_from_errno("got_object_id_dup");
5103 goto done;
5106 s->f1 = got_opentemp();
5107 if (s->f1 == NULL) {
5108 err = got_error_from_errno("got_opentemp");
5109 goto done;
5112 s->f2 = got_opentemp();
5113 if (s->f2 == NULL) {
5114 err = got_error_from_errno("got_opentemp");
5115 goto done;
5118 s->fd1 = got_opentempfd();
5119 if (s->fd1 == -1) {
5120 err = got_error_from_errno("got_opentempfd");
5121 goto done;
5124 s->fd2 = got_opentempfd();
5125 if (s->fd2 == -1) {
5126 err = got_error_from_errno("got_opentempfd");
5127 goto done;
5130 s->diff_context = diff_context;
5131 s->ignore_whitespace = ignore_whitespace;
5132 s->force_text_diff = force_text_diff;
5133 s->parent_view = parent_view;
5134 s->repo = repo;
5136 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5137 int rc;
5139 rc = init_pair(GOT_DIFF_LINE_MINUS,
5140 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5141 if (rc != ERR)
5142 rc = init_pair(GOT_DIFF_LINE_PLUS,
5143 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5144 if (rc != ERR)
5145 rc = init_pair(GOT_DIFF_LINE_HUNK,
5146 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5147 if (rc != ERR)
5148 rc = init_pair(GOT_DIFF_LINE_META,
5149 get_color_value("TOG_COLOR_DIFF_META"), -1);
5150 if (rc != ERR)
5151 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5152 get_color_value("TOG_COLOR_DIFF_META"), -1);
5153 if (rc != ERR)
5154 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5155 get_color_value("TOG_COLOR_DIFF_META"), -1);
5156 if (rc != ERR)
5157 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5158 get_color_value("TOG_COLOR_DIFF_META"), -1);
5159 if (rc != ERR)
5160 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5161 get_color_value("TOG_COLOR_AUTHOR"), -1);
5162 if (rc != ERR)
5163 rc = init_pair(GOT_DIFF_LINE_DATE,
5164 get_color_value("TOG_COLOR_DATE"), -1);
5165 if (rc == ERR) {
5166 err = got_error(GOT_ERR_RANGE);
5167 goto done;
5171 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5172 view_is_splitscreen(view))
5173 show_log_view(parent_view); /* draw border */
5174 diff_view_indicate_progress(view);
5176 err = create_diff(s);
5178 view->show = show_diff_view;
5179 view->input = input_diff_view;
5180 view->reset = reset_diff_view;
5181 view->close = close_diff_view;
5182 view->search_start = search_start_diff_view;
5183 view->search_setup = search_setup_diff_view;
5184 view->search_next = search_next_view_match;
5185 done:
5186 if (err)
5187 close_diff_view(view);
5188 return err;
5191 static const struct got_error *
5192 show_diff_view(struct tog_view *view)
5194 const struct got_error *err;
5195 struct tog_diff_view_state *s = &view->state.diff;
5196 char *id_str1 = NULL, *id_str2, *header;
5197 const char *label1, *label2;
5199 if (s->id1) {
5200 err = got_object_id_str(&id_str1, s->id1);
5201 if (err)
5202 return err;
5203 label1 = s->label1 ? s->label1 : id_str1;
5204 } else
5205 label1 = "/dev/null";
5207 err = got_object_id_str(&id_str2, s->id2);
5208 if (err)
5209 return err;
5210 label2 = s->label2 ? s->label2 : id_str2;
5212 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5213 err = got_error_from_errno("asprintf");
5214 free(id_str1);
5215 free(id_str2);
5216 return err;
5218 free(id_str1);
5219 free(id_str2);
5221 err = draw_file(view, header);
5222 free(header);
5223 return err;
5226 static const struct got_error *
5227 set_selected_commit(struct tog_diff_view_state *s,
5228 struct commit_queue_entry *entry)
5230 const struct got_error *err;
5231 const struct got_object_id_queue *parent_ids;
5232 struct got_commit_object *selected_commit;
5233 struct got_object_qid *pid;
5235 free(s->id2);
5236 s->id2 = got_object_id_dup(entry->id);
5237 if (s->id2 == NULL)
5238 return got_error_from_errno("got_object_id_dup");
5240 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5241 if (err)
5242 return err;
5243 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5244 free(s->id1);
5245 pid = STAILQ_FIRST(parent_ids);
5246 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5247 got_object_commit_close(selected_commit);
5248 return NULL;
5251 static const struct got_error *
5252 reset_diff_view(struct tog_view *view)
5254 struct tog_diff_view_state *s = &view->state.diff;
5256 view->count = 0;
5257 wclear(view->window);
5258 s->first_displayed_line = 1;
5259 s->last_displayed_line = view->nlines;
5260 s->matched_line = 0;
5261 diff_view_indicate_progress(view);
5262 return create_diff(s);
5265 static void
5266 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5268 int start, i;
5270 i = start = s->first_displayed_line - 1;
5272 while (s->lines[i].type != type) {
5273 if (i == 0)
5274 i = s->nlines - 1;
5275 if (--i == start)
5276 return; /* do nothing, requested type not in file */
5279 s->selected_line = 1;
5280 s->first_displayed_line = i;
5283 static void
5284 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5286 int start, i;
5288 i = start = s->first_displayed_line + 1;
5290 while (s->lines[i].type != type) {
5291 if (i == s->nlines - 1)
5292 i = 0;
5293 if (++i == start)
5294 return; /* do nothing, requested type not in file */
5297 s->selected_line = 1;
5298 s->first_displayed_line = i;
5301 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5302 int, int, int);
5303 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5304 int, int);
5306 static const struct got_error *
5307 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5309 const struct got_error *err = NULL;
5310 struct tog_diff_view_state *s = &view->state.diff;
5311 struct tog_log_view_state *ls;
5312 struct commit_queue_entry *old_selected_entry;
5313 char *line = NULL;
5314 size_t linesize = 0;
5315 ssize_t linelen;
5316 int i, nscroll = view->nlines - 1, up = 0;
5318 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5320 switch (ch) {
5321 case '0':
5322 case '$':
5323 case KEY_RIGHT:
5324 case 'l':
5325 case KEY_LEFT:
5326 case 'h':
5327 horizontal_scroll_input(view, ch);
5328 break;
5329 case 'a':
5330 case 'w':
5331 if (ch == 'a') {
5332 s->force_text_diff = !s->force_text_diff;
5333 view->action = s->force_text_diff ?
5334 "force ASCII text enabled" :
5335 "force ASCII text disabled";
5337 else if (ch == 'w') {
5338 s->ignore_whitespace = !s->ignore_whitespace;
5339 view->action = s->ignore_whitespace ?
5340 "ignore whitespace enabled" :
5341 "ignore whitespace disabled";
5343 err = reset_diff_view(view);
5344 break;
5345 case 'g':
5346 case KEY_HOME:
5347 s->first_displayed_line = 1;
5348 view->count = 0;
5349 break;
5350 case 'G':
5351 case KEY_END:
5352 view->count = 0;
5353 if (s->eof)
5354 break;
5356 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5357 s->eof = 1;
5358 break;
5359 case 'k':
5360 case KEY_UP:
5361 case CTRL('p'):
5362 if (s->first_displayed_line > 1)
5363 s->first_displayed_line--;
5364 else
5365 view->count = 0;
5366 break;
5367 case CTRL('u'):
5368 case 'u':
5369 nscroll /= 2;
5370 /* FALL THROUGH */
5371 case KEY_PPAGE:
5372 case CTRL('b'):
5373 case 'b':
5374 if (s->first_displayed_line == 1) {
5375 view->count = 0;
5376 break;
5378 i = 0;
5379 while (i++ < nscroll && s->first_displayed_line > 1)
5380 s->first_displayed_line--;
5381 break;
5382 case 'j':
5383 case KEY_DOWN:
5384 case CTRL('n'):
5385 if (!s->eof)
5386 s->first_displayed_line++;
5387 else
5388 view->count = 0;
5389 break;
5390 case CTRL('d'):
5391 case 'd':
5392 nscroll /= 2;
5393 /* FALL THROUGH */
5394 case KEY_NPAGE:
5395 case CTRL('f'):
5396 case 'f':
5397 case ' ':
5398 if (s->eof) {
5399 view->count = 0;
5400 break;
5402 i = 0;
5403 while (!s->eof && i++ < nscroll) {
5404 linelen = getline(&line, &linesize, s->f);
5405 s->first_displayed_line++;
5406 if (linelen == -1) {
5407 if (feof(s->f)) {
5408 s->eof = 1;
5409 } else
5410 err = got_ferror(s->f, GOT_ERR_IO);
5411 break;
5414 free(line);
5415 break;
5416 case '(':
5417 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5418 break;
5419 case ')':
5420 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5421 break;
5422 case '{':
5423 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5424 break;
5425 case '}':
5426 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5427 break;
5428 case '[':
5429 if (s->diff_context > 0) {
5430 s->diff_context--;
5431 s->matched_line = 0;
5432 diff_view_indicate_progress(view);
5433 err = create_diff(s);
5434 if (s->first_displayed_line + view->nlines - 1 >
5435 s->nlines) {
5436 s->first_displayed_line = 1;
5437 s->last_displayed_line = view->nlines;
5439 } else
5440 view->count = 0;
5441 break;
5442 case ']':
5443 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5444 s->diff_context++;
5445 s->matched_line = 0;
5446 diff_view_indicate_progress(view);
5447 err = create_diff(s);
5448 } else
5449 view->count = 0;
5450 break;
5451 case '<':
5452 case ',':
5453 case 'K':
5454 up = 1;
5455 /* FALL THROUGH */
5456 case '>':
5457 case '.':
5458 case 'J':
5459 if (s->parent_view == NULL) {
5460 view->count = 0;
5461 break;
5463 s->parent_view->count = view->count;
5465 if (s->parent_view->type == TOG_VIEW_LOG) {
5466 ls = &s->parent_view->state.log;
5467 old_selected_entry = ls->selected_entry;
5469 err = input_log_view(NULL, s->parent_view,
5470 up ? KEY_UP : KEY_DOWN);
5471 if (err)
5472 break;
5473 view->count = s->parent_view->count;
5475 if (old_selected_entry == ls->selected_entry)
5476 break;
5478 err = set_selected_commit(s, ls->selected_entry);
5479 if (err)
5480 break;
5481 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5482 struct tog_blame_view_state *bs;
5483 struct got_object_id *id, *prev_id;
5485 bs = &s->parent_view->state.blame;
5486 prev_id = get_annotation_for_line(bs->blame.lines,
5487 bs->blame.nlines, bs->last_diffed_line);
5489 err = input_blame_view(&view, s->parent_view,
5490 up ? KEY_UP : KEY_DOWN);
5491 if (err)
5492 break;
5493 view->count = s->parent_view->count;
5495 if (prev_id == NULL)
5496 break;
5497 id = get_selected_commit_id(bs->blame.lines,
5498 bs->blame.nlines, bs->first_displayed_line,
5499 bs->selected_line);
5500 if (id == NULL)
5501 break;
5503 if (!got_object_id_cmp(prev_id, id))
5504 break;
5506 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5507 if (err)
5508 break;
5510 s->first_displayed_line = 1;
5511 s->last_displayed_line = view->nlines;
5512 s->matched_line = 0;
5513 view->x = 0;
5515 diff_view_indicate_progress(view);
5516 err = create_diff(s);
5517 break;
5518 default:
5519 view->count = 0;
5520 break;
5523 return err;
5526 static const struct got_error *
5527 cmd_diff(int argc, char *argv[])
5529 const struct got_error *error = NULL;
5530 struct got_repository *repo = NULL;
5531 struct got_worktree *worktree = NULL;
5532 struct got_object_id *id1 = NULL, *id2 = NULL;
5533 char *repo_path = NULL, *cwd = NULL;
5534 char *id_str1 = NULL, *id_str2 = NULL;
5535 char *label1 = NULL, *label2 = NULL;
5536 int diff_context = 3, ignore_whitespace = 0;
5537 int ch, force_text_diff = 0;
5538 const char *errstr;
5539 struct tog_view *view;
5540 int *pack_fds = NULL;
5542 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5543 switch (ch) {
5544 case 'a':
5545 force_text_diff = 1;
5546 break;
5547 case 'C':
5548 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5549 &errstr);
5550 if (errstr != NULL)
5551 errx(1, "number of context lines is %s: %s",
5552 errstr, errstr);
5553 break;
5554 case 'r':
5555 repo_path = realpath(optarg, NULL);
5556 if (repo_path == NULL)
5557 return got_error_from_errno2("realpath",
5558 optarg);
5559 got_path_strip_trailing_slashes(repo_path);
5560 break;
5561 case 'w':
5562 ignore_whitespace = 1;
5563 break;
5564 default:
5565 usage_diff();
5566 /* NOTREACHED */
5570 argc -= optind;
5571 argv += optind;
5573 if (argc == 0) {
5574 usage_diff(); /* TODO show local worktree changes */
5575 } else if (argc == 2) {
5576 id_str1 = argv[0];
5577 id_str2 = argv[1];
5578 } else
5579 usage_diff();
5581 error = got_repo_pack_fds_open(&pack_fds);
5582 if (error)
5583 goto done;
5585 if (repo_path == NULL) {
5586 cwd = getcwd(NULL, 0);
5587 if (cwd == NULL)
5588 return got_error_from_errno("getcwd");
5589 error = got_worktree_open(&worktree, cwd);
5590 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5591 goto done;
5592 if (worktree)
5593 repo_path =
5594 strdup(got_worktree_get_repo_path(worktree));
5595 else
5596 repo_path = strdup(cwd);
5597 if (repo_path == NULL) {
5598 error = got_error_from_errno("strdup");
5599 goto done;
5603 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5604 if (error)
5605 goto done;
5607 init_curses();
5609 error = apply_unveil(got_repo_get_path(repo), NULL);
5610 if (error)
5611 goto done;
5613 error = tog_load_refs(repo, 0);
5614 if (error)
5615 goto done;
5617 error = got_repo_match_object_id(&id1, &label1, id_str1,
5618 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5619 if (error)
5620 goto done;
5622 error = got_repo_match_object_id(&id2, &label2, id_str2,
5623 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5624 if (error)
5625 goto done;
5627 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5628 if (view == NULL) {
5629 error = got_error_from_errno("view_open");
5630 goto done;
5632 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5633 ignore_whitespace, force_text_diff, NULL, repo);
5634 if (error)
5635 goto done;
5636 error = view_loop(view);
5637 done:
5638 free(label1);
5639 free(label2);
5640 free(repo_path);
5641 free(cwd);
5642 if (repo) {
5643 const struct got_error *close_err = got_repo_close(repo);
5644 if (error == NULL)
5645 error = close_err;
5647 if (worktree)
5648 got_worktree_close(worktree);
5649 if (pack_fds) {
5650 const struct got_error *pack_err =
5651 got_repo_pack_fds_close(pack_fds);
5652 if (error == NULL)
5653 error = pack_err;
5655 tog_free_refs();
5656 return error;
5659 __dead static void
5660 usage_blame(void)
5662 endwin();
5663 fprintf(stderr,
5664 "usage: %s blame [-c commit] [-r repository-path] path\n",
5665 getprogname());
5666 exit(1);
5669 struct tog_blame_line {
5670 int annotated;
5671 struct got_object_id *id;
5674 static const struct got_error *
5675 draw_blame(struct tog_view *view)
5677 struct tog_blame_view_state *s = &view->state.blame;
5678 struct tog_blame *blame = &s->blame;
5679 regmatch_t *regmatch = &view->regmatch;
5680 const struct got_error *err;
5681 int lineno = 0, nprinted = 0;
5682 char *line = NULL;
5683 size_t linesize = 0;
5684 ssize_t linelen;
5685 wchar_t *wline;
5686 int width;
5687 struct tog_blame_line *blame_line;
5688 struct got_object_id *prev_id = NULL;
5689 char *id_str;
5690 struct tog_color *tc;
5692 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5693 if (err)
5694 return err;
5696 rewind(blame->f);
5697 werase(view->window);
5699 if (asprintf(&line, "commit %s", id_str) == -1) {
5700 err = got_error_from_errno("asprintf");
5701 free(id_str);
5702 return err;
5705 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5706 free(line);
5707 line = NULL;
5708 if (err)
5709 return err;
5710 if (view_needs_focus_indication(view))
5711 wstandout(view->window);
5712 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5713 if (tc)
5714 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5715 waddwstr(view->window, wline);
5716 while (width++ < view->ncols)
5717 waddch(view->window, ' ');
5718 if (tc)
5719 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5720 if (view_needs_focus_indication(view))
5721 wstandend(view->window);
5722 free(wline);
5723 wline = NULL;
5725 if (view->gline > blame->nlines)
5726 view->gline = blame->nlines;
5728 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5729 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5730 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5731 free(id_str);
5732 return got_error_from_errno("asprintf");
5734 free(id_str);
5735 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5736 free(line);
5737 line = NULL;
5738 if (err)
5739 return err;
5740 waddwstr(view->window, wline);
5741 free(wline);
5742 wline = NULL;
5743 if (width < view->ncols - 1)
5744 waddch(view->window, '\n');
5746 s->eof = 0;
5747 view->maxx = 0;
5748 while (nprinted < view->nlines - 2) {
5749 linelen = getline(&line, &linesize, blame->f);
5750 if (linelen == -1) {
5751 if (feof(blame->f)) {
5752 s->eof = 1;
5753 break;
5755 free(line);
5756 return got_ferror(blame->f, GOT_ERR_IO);
5758 if (++lineno < s->first_displayed_line)
5759 continue;
5760 if (view->gline && !gotoline(view, &lineno, &nprinted))
5761 continue;
5763 /* Set view->maxx based on full line length. */
5764 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5765 if (err) {
5766 free(line);
5767 return err;
5769 free(wline);
5770 wline = NULL;
5771 view->maxx = MAX(view->maxx, width);
5773 if (nprinted == s->selected_line - 1)
5774 wstandout(view->window);
5776 if (blame->nlines > 0) {
5777 blame_line = &blame->lines[lineno - 1];
5778 if (blame_line->annotated && prev_id &&
5779 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5780 !(nprinted == s->selected_line - 1)) {
5781 waddstr(view->window, " ");
5782 } else if (blame_line->annotated) {
5783 char *id_str;
5784 err = got_object_id_str(&id_str,
5785 blame_line->id);
5786 if (err) {
5787 free(line);
5788 return err;
5790 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5791 if (tc)
5792 wattr_on(view->window,
5793 COLOR_PAIR(tc->colorpair), NULL);
5794 wprintw(view->window, "%.8s", id_str);
5795 if (tc)
5796 wattr_off(view->window,
5797 COLOR_PAIR(tc->colorpair), NULL);
5798 free(id_str);
5799 prev_id = blame_line->id;
5800 } else {
5801 waddstr(view->window, "........");
5802 prev_id = NULL;
5804 } else {
5805 waddstr(view->window, "........");
5806 prev_id = NULL;
5809 if (nprinted == s->selected_line - 1)
5810 wstandend(view->window);
5811 waddstr(view->window, " ");
5813 if (view->ncols <= 9) {
5814 width = 9;
5815 } else if (s->first_displayed_line + nprinted ==
5816 s->matched_line &&
5817 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5818 err = add_matched_line(&width, line, view->ncols - 9, 9,
5819 view->window, view->x, regmatch);
5820 if (err) {
5821 free(line);
5822 return err;
5824 width += 9;
5825 } else {
5826 int skip;
5827 err = format_line(&wline, &width, &skip, line,
5828 view->x, view->ncols - 9, 9, 1);
5829 if (err) {
5830 free(line);
5831 return err;
5833 waddwstr(view->window, &wline[skip]);
5834 width += 9;
5835 free(wline);
5836 wline = NULL;
5839 if (width <= view->ncols - 1)
5840 waddch(view->window, '\n');
5841 if (++nprinted == 1)
5842 s->first_displayed_line = lineno;
5844 free(line);
5845 s->last_displayed_line = lineno;
5847 view_border(view);
5849 return NULL;
5852 static const struct got_error *
5853 blame_cb(void *arg, int nlines, int lineno,
5854 struct got_commit_object *commit, struct got_object_id *id)
5856 const struct got_error *err = NULL;
5857 struct tog_blame_cb_args *a = arg;
5858 struct tog_blame_line *line;
5859 int errcode;
5861 if (nlines != a->nlines ||
5862 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5863 return got_error(GOT_ERR_RANGE);
5865 errcode = pthread_mutex_lock(&tog_mutex);
5866 if (errcode)
5867 return got_error_set_errno(errcode, "pthread_mutex_lock");
5869 if (*a->quit) { /* user has quit the blame view */
5870 err = got_error(GOT_ERR_ITER_COMPLETED);
5871 goto done;
5874 if (lineno == -1)
5875 goto done; /* no change in this commit */
5877 line = &a->lines[lineno - 1];
5878 if (line->annotated)
5879 goto done;
5881 line->id = got_object_id_dup(id);
5882 if (line->id == NULL) {
5883 err = got_error_from_errno("got_object_id_dup");
5884 goto done;
5886 line->annotated = 1;
5887 done:
5888 errcode = pthread_mutex_unlock(&tog_mutex);
5889 if (errcode)
5890 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5891 return err;
5894 static void *
5895 blame_thread(void *arg)
5897 const struct got_error *err, *close_err;
5898 struct tog_blame_thread_args *ta = arg;
5899 struct tog_blame_cb_args *a = ta->cb_args;
5900 int errcode, fd1 = -1, fd2 = -1;
5901 FILE *f1 = NULL, *f2 = NULL;
5903 fd1 = got_opentempfd();
5904 if (fd1 == -1)
5905 return (void *)got_error_from_errno("got_opentempfd");
5907 fd2 = got_opentempfd();
5908 if (fd2 == -1) {
5909 err = got_error_from_errno("got_opentempfd");
5910 goto done;
5913 f1 = got_opentemp();
5914 if (f1 == NULL) {
5915 err = (void *)got_error_from_errno("got_opentemp");
5916 goto done;
5918 f2 = got_opentemp();
5919 if (f2 == NULL) {
5920 err = (void *)got_error_from_errno("got_opentemp");
5921 goto done;
5924 err = block_signals_used_by_main_thread();
5925 if (err)
5926 goto done;
5928 err = got_blame(ta->path, a->commit_id, ta->repo,
5929 tog_diff_algo, blame_cb, ta->cb_args,
5930 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5931 if (err && err->code == GOT_ERR_CANCELLED)
5932 err = NULL;
5934 errcode = pthread_mutex_lock(&tog_mutex);
5935 if (errcode) {
5936 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5937 goto done;
5940 close_err = got_repo_close(ta->repo);
5941 if (err == NULL)
5942 err = close_err;
5943 ta->repo = NULL;
5944 *ta->complete = 1;
5946 errcode = pthread_mutex_unlock(&tog_mutex);
5947 if (errcode && err == NULL)
5948 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5950 done:
5951 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5952 err = got_error_from_errno("close");
5953 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5954 err = got_error_from_errno("close");
5955 if (f1 && fclose(f1) == EOF && err == NULL)
5956 err = got_error_from_errno("fclose");
5957 if (f2 && fclose(f2) == EOF && err == NULL)
5958 err = got_error_from_errno("fclose");
5960 return (void *)err;
5963 static struct got_object_id *
5964 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5965 int first_displayed_line, int selected_line)
5967 struct tog_blame_line *line;
5969 if (nlines <= 0)
5970 return NULL;
5972 line = &lines[first_displayed_line - 1 + selected_line - 1];
5973 if (!line->annotated)
5974 return NULL;
5976 return line->id;
5979 static struct got_object_id *
5980 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5981 int lineno)
5983 struct tog_blame_line *line;
5985 if (nlines <= 0 || lineno >= nlines)
5986 return NULL;
5988 line = &lines[lineno - 1];
5989 if (!line->annotated)
5990 return NULL;
5992 return line->id;
5995 static const struct got_error *
5996 stop_blame(struct tog_blame *blame)
5998 const struct got_error *err = NULL;
5999 int i;
6001 if (blame->thread) {
6002 int errcode;
6003 errcode = pthread_mutex_unlock(&tog_mutex);
6004 if (errcode)
6005 return got_error_set_errno(errcode,
6006 "pthread_mutex_unlock");
6007 errcode = pthread_join(blame->thread, (void **)&err);
6008 if (errcode)
6009 return got_error_set_errno(errcode, "pthread_join");
6010 errcode = pthread_mutex_lock(&tog_mutex);
6011 if (errcode)
6012 return got_error_set_errno(errcode,
6013 "pthread_mutex_lock");
6014 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6015 err = NULL;
6016 blame->thread = NULL;
6018 if (blame->thread_args.repo) {
6019 const struct got_error *close_err;
6020 close_err = got_repo_close(blame->thread_args.repo);
6021 if (err == NULL)
6022 err = close_err;
6023 blame->thread_args.repo = NULL;
6025 if (blame->f) {
6026 if (fclose(blame->f) == EOF && err == NULL)
6027 err = got_error_from_errno("fclose");
6028 blame->f = NULL;
6030 if (blame->lines) {
6031 for (i = 0; i < blame->nlines; i++)
6032 free(blame->lines[i].id);
6033 free(blame->lines);
6034 blame->lines = NULL;
6036 free(blame->cb_args.commit_id);
6037 blame->cb_args.commit_id = NULL;
6038 if (blame->pack_fds) {
6039 const struct got_error *pack_err =
6040 got_repo_pack_fds_close(blame->pack_fds);
6041 if (err == NULL)
6042 err = pack_err;
6043 blame->pack_fds = NULL;
6045 return err;
6048 static const struct got_error *
6049 cancel_blame_view(void *arg)
6051 const struct got_error *err = NULL;
6052 int *done = arg;
6053 int errcode;
6055 errcode = pthread_mutex_lock(&tog_mutex);
6056 if (errcode)
6057 return got_error_set_errno(errcode,
6058 "pthread_mutex_unlock");
6060 if (*done)
6061 err = got_error(GOT_ERR_CANCELLED);
6063 errcode = pthread_mutex_unlock(&tog_mutex);
6064 if (errcode)
6065 return got_error_set_errno(errcode,
6066 "pthread_mutex_lock");
6068 return err;
6071 static const struct got_error *
6072 run_blame(struct tog_view *view)
6074 struct tog_blame_view_state *s = &view->state.blame;
6075 struct tog_blame *blame = &s->blame;
6076 const struct got_error *err = NULL;
6077 struct got_commit_object *commit = NULL;
6078 struct got_blob_object *blob = NULL;
6079 struct got_repository *thread_repo = NULL;
6080 struct got_object_id *obj_id = NULL;
6081 int obj_type, fd = -1;
6082 int *pack_fds = NULL;
6084 err = got_object_open_as_commit(&commit, s->repo,
6085 &s->blamed_commit->id);
6086 if (err)
6087 return err;
6089 fd = got_opentempfd();
6090 if (fd == -1) {
6091 err = got_error_from_errno("got_opentempfd");
6092 goto done;
6095 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6096 if (err)
6097 goto done;
6099 err = got_object_get_type(&obj_type, s->repo, obj_id);
6100 if (err)
6101 goto done;
6103 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6104 err = got_error(GOT_ERR_OBJ_TYPE);
6105 goto done;
6108 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6109 if (err)
6110 goto done;
6111 blame->f = got_opentemp();
6112 if (blame->f == NULL) {
6113 err = got_error_from_errno("got_opentemp");
6114 goto done;
6116 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6117 &blame->line_offsets, blame->f, blob);
6118 if (err)
6119 goto done;
6120 if (blame->nlines == 0) {
6121 s->blame_complete = 1;
6122 goto done;
6125 /* Don't include \n at EOF in the blame line count. */
6126 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6127 blame->nlines--;
6129 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6130 if (blame->lines == NULL) {
6131 err = got_error_from_errno("calloc");
6132 goto done;
6135 err = got_repo_pack_fds_open(&pack_fds);
6136 if (err)
6137 goto done;
6138 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6139 pack_fds);
6140 if (err)
6141 goto done;
6143 blame->pack_fds = pack_fds;
6144 blame->cb_args.view = view;
6145 blame->cb_args.lines = blame->lines;
6146 blame->cb_args.nlines = blame->nlines;
6147 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6148 if (blame->cb_args.commit_id == NULL) {
6149 err = got_error_from_errno("got_object_id_dup");
6150 goto done;
6152 blame->cb_args.quit = &s->done;
6154 blame->thread_args.path = s->path;
6155 blame->thread_args.repo = thread_repo;
6156 blame->thread_args.cb_args = &blame->cb_args;
6157 blame->thread_args.complete = &s->blame_complete;
6158 blame->thread_args.cancel_cb = cancel_blame_view;
6159 blame->thread_args.cancel_arg = &s->done;
6160 s->blame_complete = 0;
6162 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6163 s->first_displayed_line = 1;
6164 s->last_displayed_line = view->nlines;
6165 s->selected_line = 1;
6167 s->matched_line = 0;
6169 done:
6170 if (commit)
6171 got_object_commit_close(commit);
6172 if (fd != -1 && close(fd) == -1 && err == NULL)
6173 err = got_error_from_errno("close");
6174 if (blob)
6175 got_object_blob_close(blob);
6176 free(obj_id);
6177 if (err)
6178 stop_blame(blame);
6179 return err;
6182 static const struct got_error *
6183 open_blame_view(struct tog_view *view, char *path,
6184 struct got_object_id *commit_id, struct got_repository *repo)
6186 const struct got_error *err = NULL;
6187 struct tog_blame_view_state *s = &view->state.blame;
6189 STAILQ_INIT(&s->blamed_commits);
6191 s->path = strdup(path);
6192 if (s->path == NULL)
6193 return got_error_from_errno("strdup");
6195 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6196 if (err) {
6197 free(s->path);
6198 return err;
6201 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6202 s->first_displayed_line = 1;
6203 s->last_displayed_line = view->nlines;
6204 s->selected_line = 1;
6205 s->blame_complete = 0;
6206 s->repo = repo;
6207 s->commit_id = commit_id;
6208 memset(&s->blame, 0, sizeof(s->blame));
6210 STAILQ_INIT(&s->colors);
6211 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6212 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6213 get_color_value("TOG_COLOR_COMMIT"));
6214 if (err)
6215 return err;
6218 view->show = show_blame_view;
6219 view->input = input_blame_view;
6220 view->reset = reset_blame_view;
6221 view->close = close_blame_view;
6222 view->search_start = search_start_blame_view;
6223 view->search_setup = search_setup_blame_view;
6224 view->search_next = search_next_view_match;
6226 return run_blame(view);
6229 static const struct got_error *
6230 close_blame_view(struct tog_view *view)
6232 const struct got_error *err = NULL;
6233 struct tog_blame_view_state *s = &view->state.blame;
6235 if (s->blame.thread)
6236 err = stop_blame(&s->blame);
6238 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6239 struct got_object_qid *blamed_commit;
6240 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6241 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6242 got_object_qid_free(blamed_commit);
6245 free(s->path);
6246 free_colors(&s->colors);
6247 return err;
6250 static const struct got_error *
6251 search_start_blame_view(struct tog_view *view)
6253 struct tog_blame_view_state *s = &view->state.blame;
6255 s->matched_line = 0;
6256 return NULL;
6259 static void
6260 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6261 size_t *nlines, int **first, int **last, int **match, int **selected)
6263 struct tog_blame_view_state *s = &view->state.blame;
6265 *f = s->blame.f;
6266 *nlines = s->blame.nlines;
6267 *line_offsets = s->blame.line_offsets;
6268 *match = &s->matched_line;
6269 *first = &s->first_displayed_line;
6270 *last = &s->last_displayed_line;
6271 *selected = &s->selected_line;
6274 static const struct got_error *
6275 show_blame_view(struct tog_view *view)
6277 const struct got_error *err = NULL;
6278 struct tog_blame_view_state *s = &view->state.blame;
6279 int errcode;
6281 if (s->blame.thread == NULL && !s->blame_complete) {
6282 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6283 &s->blame.thread_args);
6284 if (errcode)
6285 return got_error_set_errno(errcode, "pthread_create");
6287 halfdelay(1); /* fast refresh while annotating */
6290 if (s->blame_complete)
6291 halfdelay(10); /* disable fast refresh */
6293 err = draw_blame(view);
6295 view_border(view);
6296 return err;
6299 static const struct got_error *
6300 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6301 struct got_repository *repo, struct got_object_id *id)
6303 struct tog_view *log_view;
6304 const struct got_error *err = NULL;
6306 *new_view = NULL;
6308 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6309 if (log_view == NULL)
6310 return got_error_from_errno("view_open");
6312 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6313 if (err)
6314 view_close(log_view);
6315 else
6316 *new_view = log_view;
6318 return err;
6321 static const struct got_error *
6322 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6324 const struct got_error *err = NULL, *thread_err = NULL;
6325 struct tog_view *diff_view;
6326 struct tog_blame_view_state *s = &view->state.blame;
6327 int eos, nscroll, begin_y = 0, begin_x = 0;
6329 eos = nscroll = view->nlines - 2;
6330 if (view_is_hsplit_top(view))
6331 --eos; /* border */
6333 switch (ch) {
6334 case '0':
6335 case '$':
6336 case KEY_RIGHT:
6337 case 'l':
6338 case KEY_LEFT:
6339 case 'h':
6340 horizontal_scroll_input(view, ch);
6341 break;
6342 case 'q':
6343 s->done = 1;
6344 break;
6345 case 'g':
6346 case KEY_HOME:
6347 s->selected_line = 1;
6348 s->first_displayed_line = 1;
6349 view->count = 0;
6350 break;
6351 case 'G':
6352 case KEY_END:
6353 if (s->blame.nlines < eos) {
6354 s->selected_line = s->blame.nlines;
6355 s->first_displayed_line = 1;
6356 } else {
6357 s->selected_line = eos;
6358 s->first_displayed_line = s->blame.nlines - (eos - 1);
6360 view->count = 0;
6361 break;
6362 case 'k':
6363 case KEY_UP:
6364 case CTRL('p'):
6365 if (s->selected_line > 1)
6366 s->selected_line--;
6367 else if (s->selected_line == 1 &&
6368 s->first_displayed_line > 1)
6369 s->first_displayed_line--;
6370 else
6371 view->count = 0;
6372 break;
6373 case CTRL('u'):
6374 case 'u':
6375 nscroll /= 2;
6376 /* FALL THROUGH */
6377 case KEY_PPAGE:
6378 case CTRL('b'):
6379 case 'b':
6380 if (s->first_displayed_line == 1) {
6381 if (view->count > 1)
6382 nscroll += nscroll;
6383 s->selected_line = MAX(1, s->selected_line - nscroll);
6384 view->count = 0;
6385 break;
6387 if (s->first_displayed_line > nscroll)
6388 s->first_displayed_line -= nscroll;
6389 else
6390 s->first_displayed_line = 1;
6391 break;
6392 case 'j':
6393 case KEY_DOWN:
6394 case CTRL('n'):
6395 if (s->selected_line < eos && s->first_displayed_line +
6396 s->selected_line <= s->blame.nlines)
6397 s->selected_line++;
6398 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6399 s->first_displayed_line++;
6400 else
6401 view->count = 0;
6402 break;
6403 case 'c':
6404 case 'p': {
6405 struct got_object_id *id = NULL;
6407 view->count = 0;
6408 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6409 s->first_displayed_line, s->selected_line);
6410 if (id == NULL)
6411 break;
6412 if (ch == 'p') {
6413 struct got_commit_object *commit, *pcommit;
6414 struct got_object_qid *pid;
6415 struct got_object_id *blob_id = NULL;
6416 int obj_type;
6417 err = got_object_open_as_commit(&commit,
6418 s->repo, id);
6419 if (err)
6420 break;
6421 pid = STAILQ_FIRST(
6422 got_object_commit_get_parent_ids(commit));
6423 if (pid == NULL) {
6424 got_object_commit_close(commit);
6425 break;
6427 /* Check if path history ends here. */
6428 err = got_object_open_as_commit(&pcommit,
6429 s->repo, &pid->id);
6430 if (err)
6431 break;
6432 err = got_object_id_by_path(&blob_id, s->repo,
6433 pcommit, s->path);
6434 got_object_commit_close(pcommit);
6435 if (err) {
6436 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6437 err = NULL;
6438 got_object_commit_close(commit);
6439 break;
6441 err = got_object_get_type(&obj_type, s->repo,
6442 blob_id);
6443 free(blob_id);
6444 /* Can't blame non-blob type objects. */
6445 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6446 got_object_commit_close(commit);
6447 break;
6449 err = got_object_qid_alloc(&s->blamed_commit,
6450 &pid->id);
6451 got_object_commit_close(commit);
6452 } else {
6453 if (got_object_id_cmp(id,
6454 &s->blamed_commit->id) == 0)
6455 break;
6456 err = got_object_qid_alloc(&s->blamed_commit,
6457 id);
6459 if (err)
6460 break;
6461 s->done = 1;
6462 thread_err = stop_blame(&s->blame);
6463 s->done = 0;
6464 if (thread_err)
6465 break;
6466 STAILQ_INSERT_HEAD(&s->blamed_commits,
6467 s->blamed_commit, entry);
6468 err = run_blame(view);
6469 if (err)
6470 break;
6471 break;
6473 case 'C': {
6474 struct got_object_qid *first;
6476 view->count = 0;
6477 first = STAILQ_FIRST(&s->blamed_commits);
6478 if (!got_object_id_cmp(&first->id, s->commit_id))
6479 break;
6480 s->done = 1;
6481 thread_err = stop_blame(&s->blame);
6482 s->done = 0;
6483 if (thread_err)
6484 break;
6485 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6486 got_object_qid_free(s->blamed_commit);
6487 s->blamed_commit =
6488 STAILQ_FIRST(&s->blamed_commits);
6489 err = run_blame(view);
6490 if (err)
6491 break;
6492 break;
6494 case 'L':
6495 view->count = 0;
6496 s->id_to_log = get_selected_commit_id(s->blame.lines,
6497 s->blame.nlines, s->first_displayed_line, s->selected_line);
6498 if (s->id_to_log)
6499 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6500 break;
6501 case KEY_ENTER:
6502 case '\r': {
6503 struct got_object_id *id = NULL;
6504 struct got_object_qid *pid;
6505 struct got_commit_object *commit = NULL;
6507 view->count = 0;
6508 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6509 s->first_displayed_line, s->selected_line);
6510 if (id == NULL)
6511 break;
6512 err = got_object_open_as_commit(&commit, s->repo, id);
6513 if (err)
6514 break;
6515 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6516 if (*new_view) {
6517 /* traversed from diff view, release diff resources */
6518 err = close_diff_view(*new_view);
6519 if (err)
6520 break;
6521 diff_view = *new_view;
6522 } else {
6523 if (view_is_parent_view(view))
6524 view_get_split(view, &begin_y, &begin_x);
6526 diff_view = view_open(0, 0, begin_y, begin_x,
6527 TOG_VIEW_DIFF);
6528 if (diff_view == NULL) {
6529 got_object_commit_close(commit);
6530 err = got_error_from_errno("view_open");
6531 break;
6534 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6535 id, NULL, NULL, 3, 0, 0, view, s->repo);
6536 got_object_commit_close(commit);
6537 if (err) {
6538 view_close(diff_view);
6539 break;
6541 s->last_diffed_line = s->first_displayed_line - 1 +
6542 s->selected_line;
6543 if (*new_view)
6544 break; /* still open from active diff view */
6545 if (view_is_parent_view(view) &&
6546 view->mode == TOG_VIEW_SPLIT_HRZN) {
6547 err = view_init_hsplit(view, begin_y);
6548 if (err)
6549 break;
6552 view->focussed = 0;
6553 diff_view->focussed = 1;
6554 diff_view->mode = view->mode;
6555 diff_view->nlines = view->lines - begin_y;
6556 if (view_is_parent_view(view)) {
6557 view_transfer_size(diff_view, view);
6558 err = view_close_child(view);
6559 if (err)
6560 break;
6561 err = view_set_child(view, diff_view);
6562 if (err)
6563 break;
6564 view->focus_child = 1;
6565 } else
6566 *new_view = diff_view;
6567 if (err)
6568 break;
6569 break;
6571 case CTRL('d'):
6572 case 'd':
6573 nscroll /= 2;
6574 /* FALL THROUGH */
6575 case KEY_NPAGE:
6576 case CTRL('f'):
6577 case 'f':
6578 case ' ':
6579 if (s->last_displayed_line >= s->blame.nlines &&
6580 s->selected_line >= MIN(s->blame.nlines,
6581 view->nlines - 2)) {
6582 view->count = 0;
6583 break;
6585 if (s->last_displayed_line >= s->blame.nlines &&
6586 s->selected_line < view->nlines - 2) {
6587 s->selected_line +=
6588 MIN(nscroll, s->last_displayed_line -
6589 s->first_displayed_line - s->selected_line + 1);
6591 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6592 s->first_displayed_line += nscroll;
6593 else
6594 s->first_displayed_line =
6595 s->blame.nlines - (view->nlines - 3);
6596 break;
6597 case KEY_RESIZE:
6598 if (s->selected_line > view->nlines - 2) {
6599 s->selected_line = MIN(s->blame.nlines,
6600 view->nlines - 2);
6602 break;
6603 default:
6604 view->count = 0;
6605 break;
6607 return thread_err ? thread_err : err;
6610 static const struct got_error *
6611 reset_blame_view(struct tog_view *view)
6613 const struct got_error *err;
6614 struct tog_blame_view_state *s = &view->state.blame;
6616 view->count = 0;
6617 s->done = 1;
6618 err = stop_blame(&s->blame);
6619 s->done = 0;
6620 if (err)
6621 return err;
6622 return run_blame(view);
6625 static const struct got_error *
6626 cmd_blame(int argc, char *argv[])
6628 const struct got_error *error;
6629 struct got_repository *repo = NULL;
6630 struct got_worktree *worktree = NULL;
6631 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6632 char *link_target = NULL;
6633 struct got_object_id *commit_id = NULL;
6634 struct got_commit_object *commit = NULL;
6635 char *commit_id_str = NULL;
6636 int ch;
6637 struct tog_view *view;
6638 int *pack_fds = NULL;
6640 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6641 switch (ch) {
6642 case 'c':
6643 commit_id_str = optarg;
6644 break;
6645 case 'r':
6646 repo_path = realpath(optarg, NULL);
6647 if (repo_path == NULL)
6648 return got_error_from_errno2("realpath",
6649 optarg);
6650 break;
6651 default:
6652 usage_blame();
6653 /* NOTREACHED */
6657 argc -= optind;
6658 argv += optind;
6660 if (argc != 1)
6661 usage_blame();
6663 error = got_repo_pack_fds_open(&pack_fds);
6664 if (error != NULL)
6665 goto done;
6667 if (repo_path == NULL) {
6668 cwd = getcwd(NULL, 0);
6669 if (cwd == NULL)
6670 return got_error_from_errno("getcwd");
6671 error = got_worktree_open(&worktree, cwd);
6672 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6673 goto done;
6674 if (worktree)
6675 repo_path =
6676 strdup(got_worktree_get_repo_path(worktree));
6677 else
6678 repo_path = strdup(cwd);
6679 if (repo_path == NULL) {
6680 error = got_error_from_errno("strdup");
6681 goto done;
6685 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6686 if (error != NULL)
6687 goto done;
6689 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6690 worktree);
6691 if (error)
6692 goto done;
6694 init_curses();
6696 error = apply_unveil(got_repo_get_path(repo), NULL);
6697 if (error)
6698 goto done;
6700 error = tog_load_refs(repo, 0);
6701 if (error)
6702 goto done;
6704 if (commit_id_str == NULL) {
6705 struct got_reference *head_ref;
6706 error = got_ref_open(&head_ref, repo, worktree ?
6707 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6708 if (error != NULL)
6709 goto done;
6710 error = got_ref_resolve(&commit_id, repo, head_ref);
6711 got_ref_close(head_ref);
6712 } else {
6713 error = got_repo_match_object_id(&commit_id, NULL,
6714 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6716 if (error != NULL)
6717 goto done;
6719 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6720 if (view == NULL) {
6721 error = got_error_from_errno("view_open");
6722 goto done;
6725 error = got_object_open_as_commit(&commit, repo, commit_id);
6726 if (error)
6727 goto done;
6729 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6730 commit, repo);
6731 if (error)
6732 goto done;
6734 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6735 commit_id, repo);
6736 if (error)
6737 goto done;
6738 if (worktree) {
6739 /* Release work tree lock. */
6740 got_worktree_close(worktree);
6741 worktree = NULL;
6743 error = view_loop(view);
6744 done:
6745 free(repo_path);
6746 free(in_repo_path);
6747 free(link_target);
6748 free(cwd);
6749 free(commit_id);
6750 if (commit)
6751 got_object_commit_close(commit);
6752 if (worktree)
6753 got_worktree_close(worktree);
6754 if (repo) {
6755 const struct got_error *close_err = got_repo_close(repo);
6756 if (error == NULL)
6757 error = close_err;
6759 if (pack_fds) {
6760 const struct got_error *pack_err =
6761 got_repo_pack_fds_close(pack_fds);
6762 if (error == NULL)
6763 error = pack_err;
6765 tog_free_refs();
6766 return error;
6769 static const struct got_error *
6770 draw_tree_entries(struct tog_view *view, const char *parent_path)
6772 struct tog_tree_view_state *s = &view->state.tree;
6773 const struct got_error *err = NULL;
6774 struct got_tree_entry *te;
6775 wchar_t *wline;
6776 char *index = NULL;
6777 struct tog_color *tc;
6778 int width, n, nentries, scrollx, i = 1;
6779 int limit = view->nlines;
6781 s->ndisplayed = 0;
6782 if (view_is_hsplit_top(view))
6783 --limit; /* border */
6785 werase(view->window);
6787 if (limit == 0)
6788 return NULL;
6790 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6791 0, 0);
6792 if (err)
6793 return err;
6794 if (view_needs_focus_indication(view))
6795 wstandout(view->window);
6796 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6797 if (tc)
6798 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6799 waddwstr(view->window, wline);
6800 free(wline);
6801 wline = NULL;
6802 while (width++ < view->ncols)
6803 waddch(view->window, ' ');
6804 if (tc)
6805 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6806 if (view_needs_focus_indication(view))
6807 wstandend(view->window);
6808 if (--limit <= 0)
6809 return NULL;
6811 i += s->selected;
6812 if (s->first_displayed_entry) {
6813 i += got_tree_entry_get_index(s->first_displayed_entry);
6814 if (s->tree != s->root)
6815 ++i; /* account for ".." entry */
6817 nentries = got_object_tree_get_nentries(s->tree);
6818 if (asprintf(&index, "[%d/%d] %s",
6819 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6820 return got_error_from_errno("asprintf");
6821 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6822 free(index);
6823 if (err)
6824 return err;
6825 waddwstr(view->window, wline);
6826 free(wline);
6827 wline = NULL;
6828 if (width < view->ncols - 1)
6829 waddch(view->window, '\n');
6830 if (--limit <= 0)
6831 return NULL;
6832 waddch(view->window, '\n');
6833 if (--limit <= 0)
6834 return NULL;
6836 if (s->first_displayed_entry == NULL) {
6837 te = got_object_tree_get_first_entry(s->tree);
6838 if (s->selected == 0) {
6839 if (view->focussed)
6840 wstandout(view->window);
6841 s->selected_entry = NULL;
6843 waddstr(view->window, " ..\n"); /* parent directory */
6844 if (s->selected == 0 && view->focussed)
6845 wstandend(view->window);
6846 s->ndisplayed++;
6847 if (--limit <= 0)
6848 return NULL;
6849 n = 1;
6850 } else {
6851 n = 0;
6852 te = s->first_displayed_entry;
6855 view->maxx = 0;
6856 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6857 char *line = NULL, *id_str = NULL, *link_target = NULL;
6858 const char *modestr = "";
6859 mode_t mode;
6861 te = got_object_tree_get_entry(s->tree, i);
6862 mode = got_tree_entry_get_mode(te);
6864 if (s->show_ids) {
6865 err = got_object_id_str(&id_str,
6866 got_tree_entry_get_id(te));
6867 if (err)
6868 return got_error_from_errno(
6869 "got_object_id_str");
6871 if (got_object_tree_entry_is_submodule(te))
6872 modestr = "$";
6873 else if (S_ISLNK(mode)) {
6874 int i;
6876 err = got_tree_entry_get_symlink_target(&link_target,
6877 te, s->repo);
6878 if (err) {
6879 free(id_str);
6880 return err;
6882 for (i = 0; i < strlen(link_target); i++) {
6883 if (!isprint((unsigned char)link_target[i]))
6884 link_target[i] = '?';
6886 modestr = "@";
6888 else if (S_ISDIR(mode))
6889 modestr = "/";
6890 else if (mode & S_IXUSR)
6891 modestr = "*";
6892 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6893 got_tree_entry_get_name(te), modestr,
6894 link_target ? " -> ": "",
6895 link_target ? link_target : "") == -1) {
6896 free(id_str);
6897 free(link_target);
6898 return got_error_from_errno("asprintf");
6900 free(id_str);
6901 free(link_target);
6903 /* use full line width to determine view->maxx */
6904 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
6905 if (err) {
6906 free(line);
6907 break;
6909 view->maxx = MAX(view->maxx, width);
6910 free(wline);
6911 wline = NULL;
6913 err = format_line(&wline, &width, &scrollx, line, view->x,
6914 view->ncols, 0, 0);
6915 if (err) {
6916 free(line);
6917 break;
6919 if (n == s->selected) {
6920 if (view->focussed)
6921 wstandout(view->window);
6922 s->selected_entry = te;
6924 tc = match_color(&s->colors, line);
6925 if (tc)
6926 wattr_on(view->window,
6927 COLOR_PAIR(tc->colorpair), NULL);
6928 waddwstr(view->window, &wline[scrollx]);
6929 if (tc)
6930 wattr_off(view->window,
6931 COLOR_PAIR(tc->colorpair), NULL);
6932 if (width < view->ncols)
6933 waddch(view->window, '\n');
6934 if (n == s->selected && view->focussed)
6935 wstandend(view->window);
6936 free(line);
6937 free(wline);
6938 wline = NULL;
6939 n++;
6940 s->ndisplayed++;
6941 s->last_displayed_entry = te;
6942 if (--limit <= 0)
6943 break;
6946 return err;
6949 static void
6950 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6952 struct got_tree_entry *te;
6953 int isroot = s->tree == s->root;
6954 int i = 0;
6956 if (s->first_displayed_entry == NULL)
6957 return;
6959 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6960 while (i++ < maxscroll) {
6961 if (te == NULL) {
6962 if (!isroot)
6963 s->first_displayed_entry = NULL;
6964 break;
6966 s->first_displayed_entry = te;
6967 te = got_tree_entry_get_prev(s->tree, te);
6971 static const struct got_error *
6972 tree_scroll_down(struct tog_view *view, int maxscroll)
6974 struct tog_tree_view_state *s = &view->state.tree;
6975 struct got_tree_entry *next, *last;
6976 int n = 0;
6978 if (s->first_displayed_entry)
6979 next = got_tree_entry_get_next(s->tree,
6980 s->first_displayed_entry);
6981 else
6982 next = got_object_tree_get_first_entry(s->tree);
6984 last = s->last_displayed_entry;
6985 while (next && n++ < maxscroll) {
6986 if (last) {
6987 s->last_displayed_entry = last;
6988 last = got_tree_entry_get_next(s->tree, last);
6990 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6991 s->first_displayed_entry = next;
6992 next = got_tree_entry_get_next(s->tree, next);
6996 return NULL;
6999 static const struct got_error *
7000 tree_entry_path(char **path, struct tog_parent_trees *parents,
7001 struct got_tree_entry *te)
7003 const struct got_error *err = NULL;
7004 struct tog_parent_tree *pt;
7005 size_t len = 2; /* for leading slash and NUL */
7007 TAILQ_FOREACH(pt, parents, entry)
7008 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7009 + 1 /* slash */;
7010 if (te)
7011 len += strlen(got_tree_entry_get_name(te));
7013 *path = calloc(1, len);
7014 if (path == NULL)
7015 return got_error_from_errno("calloc");
7017 (*path)[0] = '/';
7018 pt = TAILQ_LAST(parents, tog_parent_trees);
7019 while (pt) {
7020 const char *name = got_tree_entry_get_name(pt->selected_entry);
7021 if (strlcat(*path, name, len) >= len) {
7022 err = got_error(GOT_ERR_NO_SPACE);
7023 goto done;
7025 if (strlcat(*path, "/", len) >= len) {
7026 err = got_error(GOT_ERR_NO_SPACE);
7027 goto done;
7029 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7031 if (te) {
7032 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7033 err = got_error(GOT_ERR_NO_SPACE);
7034 goto done;
7037 done:
7038 if (err) {
7039 free(*path);
7040 *path = NULL;
7042 return err;
7045 static const struct got_error *
7046 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7047 struct got_tree_entry *te, struct tog_parent_trees *parents,
7048 struct got_object_id *commit_id, struct got_repository *repo)
7050 const struct got_error *err = NULL;
7051 char *path;
7052 struct tog_view *blame_view;
7054 *new_view = NULL;
7056 err = tree_entry_path(&path, parents, te);
7057 if (err)
7058 return err;
7060 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7061 if (blame_view == NULL) {
7062 err = got_error_from_errno("view_open");
7063 goto done;
7066 err = open_blame_view(blame_view, path, commit_id, repo);
7067 if (err) {
7068 if (err->code == GOT_ERR_CANCELLED)
7069 err = NULL;
7070 view_close(blame_view);
7071 } else
7072 *new_view = blame_view;
7073 done:
7074 free(path);
7075 return err;
7078 static const struct got_error *
7079 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7080 struct tog_tree_view_state *s)
7082 struct tog_view *log_view;
7083 const struct got_error *err = NULL;
7084 char *path;
7086 *new_view = NULL;
7088 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7089 if (log_view == NULL)
7090 return got_error_from_errno("view_open");
7092 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7093 if (err)
7094 return err;
7096 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7097 path, 0);
7098 if (err)
7099 view_close(log_view);
7100 else
7101 *new_view = log_view;
7102 free(path);
7103 return err;
7106 static const struct got_error *
7107 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7108 const char *head_ref_name, struct got_repository *repo)
7110 const struct got_error *err = NULL;
7111 char *commit_id_str = NULL;
7112 struct tog_tree_view_state *s = &view->state.tree;
7113 struct got_commit_object *commit = NULL;
7115 TAILQ_INIT(&s->parents);
7116 STAILQ_INIT(&s->colors);
7118 s->commit_id = got_object_id_dup(commit_id);
7119 if (s->commit_id == NULL)
7120 return got_error_from_errno("got_object_id_dup");
7122 err = got_object_open_as_commit(&commit, repo, commit_id);
7123 if (err)
7124 goto done;
7127 * The root is opened here and will be closed when the view is closed.
7128 * Any visited subtrees and their path-wise parents are opened and
7129 * closed on demand.
7131 err = got_object_open_as_tree(&s->root, repo,
7132 got_object_commit_get_tree_id(commit));
7133 if (err)
7134 goto done;
7135 s->tree = s->root;
7137 err = got_object_id_str(&commit_id_str, commit_id);
7138 if (err != NULL)
7139 goto done;
7141 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7142 err = got_error_from_errno("asprintf");
7143 goto done;
7146 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7147 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7148 if (head_ref_name) {
7149 s->head_ref_name = strdup(head_ref_name);
7150 if (s->head_ref_name == NULL) {
7151 err = got_error_from_errno("strdup");
7152 goto done;
7155 s->repo = repo;
7157 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7158 err = add_color(&s->colors, "\\$$",
7159 TOG_COLOR_TREE_SUBMODULE,
7160 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7161 if (err)
7162 goto done;
7163 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7164 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7165 if (err)
7166 goto done;
7167 err = add_color(&s->colors, "/$",
7168 TOG_COLOR_TREE_DIRECTORY,
7169 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7170 if (err)
7171 goto done;
7173 err = add_color(&s->colors, "\\*$",
7174 TOG_COLOR_TREE_EXECUTABLE,
7175 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7176 if (err)
7177 goto done;
7179 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7180 get_color_value("TOG_COLOR_COMMIT"));
7181 if (err)
7182 goto done;
7185 view->show = show_tree_view;
7186 view->input = input_tree_view;
7187 view->close = close_tree_view;
7188 view->search_start = search_start_tree_view;
7189 view->search_next = search_next_tree_view;
7190 done:
7191 free(commit_id_str);
7192 if (commit)
7193 got_object_commit_close(commit);
7194 if (err)
7195 close_tree_view(view);
7196 return err;
7199 static const struct got_error *
7200 close_tree_view(struct tog_view *view)
7202 struct tog_tree_view_state *s = &view->state.tree;
7204 free_colors(&s->colors);
7205 free(s->tree_label);
7206 s->tree_label = NULL;
7207 free(s->commit_id);
7208 s->commit_id = NULL;
7209 free(s->head_ref_name);
7210 s->head_ref_name = NULL;
7211 while (!TAILQ_EMPTY(&s->parents)) {
7212 struct tog_parent_tree *parent;
7213 parent = TAILQ_FIRST(&s->parents);
7214 TAILQ_REMOVE(&s->parents, parent, entry);
7215 if (parent->tree != s->root)
7216 got_object_tree_close(parent->tree);
7217 free(parent);
7220 if (s->tree != NULL && s->tree != s->root)
7221 got_object_tree_close(s->tree);
7222 if (s->root)
7223 got_object_tree_close(s->root);
7224 return NULL;
7227 static const struct got_error *
7228 search_start_tree_view(struct tog_view *view)
7230 struct tog_tree_view_state *s = &view->state.tree;
7232 s->matched_entry = NULL;
7233 return NULL;
7236 static int
7237 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7239 regmatch_t regmatch;
7241 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7242 0) == 0;
7245 static const struct got_error *
7246 search_next_tree_view(struct tog_view *view)
7248 struct tog_tree_view_state *s = &view->state.tree;
7249 struct got_tree_entry *te = NULL;
7251 if (!view->searching) {
7252 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7253 return NULL;
7256 if (s->matched_entry) {
7257 if (view->searching == TOG_SEARCH_FORWARD) {
7258 if (s->selected_entry)
7259 te = got_tree_entry_get_next(s->tree,
7260 s->selected_entry);
7261 else
7262 te = got_object_tree_get_first_entry(s->tree);
7263 } else {
7264 if (s->selected_entry == NULL)
7265 te = got_object_tree_get_last_entry(s->tree);
7266 else
7267 te = got_tree_entry_get_prev(s->tree,
7268 s->selected_entry);
7270 } else {
7271 if (s->selected_entry)
7272 te = s->selected_entry;
7273 else if (view->searching == TOG_SEARCH_FORWARD)
7274 te = got_object_tree_get_first_entry(s->tree);
7275 else
7276 te = got_object_tree_get_last_entry(s->tree);
7279 while (1) {
7280 if (te == NULL) {
7281 if (s->matched_entry == NULL) {
7282 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7283 return NULL;
7285 if (view->searching == TOG_SEARCH_FORWARD)
7286 te = got_object_tree_get_first_entry(s->tree);
7287 else
7288 te = got_object_tree_get_last_entry(s->tree);
7291 if (match_tree_entry(te, &view->regex)) {
7292 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7293 s->matched_entry = te;
7294 break;
7297 if (view->searching == TOG_SEARCH_FORWARD)
7298 te = got_tree_entry_get_next(s->tree, te);
7299 else
7300 te = got_tree_entry_get_prev(s->tree, te);
7303 if (s->matched_entry) {
7304 s->first_displayed_entry = s->matched_entry;
7305 s->selected = 0;
7308 return NULL;
7311 static const struct got_error *
7312 show_tree_view(struct tog_view *view)
7314 const struct got_error *err = NULL;
7315 struct tog_tree_view_state *s = &view->state.tree;
7316 char *parent_path;
7318 err = tree_entry_path(&parent_path, &s->parents, NULL);
7319 if (err)
7320 return err;
7322 err = draw_tree_entries(view, parent_path);
7323 free(parent_path);
7325 view_border(view);
7326 return err;
7329 static const struct got_error *
7330 tree_goto_line(struct tog_view *view, int nlines)
7332 const struct got_error *err = NULL;
7333 struct tog_tree_view_state *s = &view->state.tree;
7334 struct got_tree_entry **fte, **lte, **ste;
7335 int g, last, first = 1, i = 1;
7336 int root = s->tree == s->root;
7337 int off = root ? 1 : 2;
7339 g = view->gline;
7340 view->gline = 0;
7342 if (g == 0)
7343 g = 1;
7344 else if (g > got_object_tree_get_nentries(s->tree))
7345 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7347 fte = &s->first_displayed_entry;
7348 lte = &s->last_displayed_entry;
7349 ste = &s->selected_entry;
7351 if (*fte != NULL) {
7352 first = got_tree_entry_get_index(*fte);
7353 first += off; /* account for ".." */
7355 last = got_tree_entry_get_index(*lte);
7356 last += off;
7358 if (g >= first && g <= last && g - first < nlines) {
7359 s->selected = g - first;
7360 return NULL; /* gline is on the current page */
7363 if (*ste != NULL) {
7364 i = got_tree_entry_get_index(*ste);
7365 i += off;
7368 if (i < g) {
7369 err = tree_scroll_down(view, g - i);
7370 if (err)
7371 return err;
7372 if (got_tree_entry_get_index(*lte) >=
7373 got_object_tree_get_nentries(s->tree) - 1 &&
7374 first + s->selected < g &&
7375 s->selected < s->ndisplayed - 1) {
7376 first = got_tree_entry_get_index(*fte);
7377 first += off;
7378 s->selected = g - first;
7380 } else if (i > g)
7381 tree_scroll_up(s, i - g);
7383 if (g < nlines &&
7384 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7385 s->selected = g - 1;
7387 return NULL;
7390 static const struct got_error *
7391 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7393 const struct got_error *err = NULL;
7394 struct tog_tree_view_state *s = &view->state.tree;
7395 struct got_tree_entry *te;
7396 int n, nscroll = view->nlines - 3;
7398 if (view->gline)
7399 return tree_goto_line(view, nscroll);
7401 switch (ch) {
7402 case '0':
7403 case '$':
7404 case KEY_RIGHT:
7405 case 'l':
7406 case KEY_LEFT:
7407 case 'h':
7408 horizontal_scroll_input(view, ch);
7409 break;
7410 case 'i':
7411 s->show_ids = !s->show_ids;
7412 view->count = 0;
7413 break;
7414 case 'L':
7415 view->count = 0;
7416 if (!s->selected_entry)
7417 break;
7418 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7419 break;
7420 case 'R':
7421 view->count = 0;
7422 err = view_request_new(new_view, view, TOG_VIEW_REF);
7423 break;
7424 case 'g':
7425 case '=':
7426 case KEY_HOME:
7427 s->selected = 0;
7428 view->count = 0;
7429 if (s->tree == s->root)
7430 s->first_displayed_entry =
7431 got_object_tree_get_first_entry(s->tree);
7432 else
7433 s->first_displayed_entry = NULL;
7434 break;
7435 case 'G':
7436 case '*':
7437 case KEY_END: {
7438 int eos = view->nlines - 3;
7440 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7441 --eos; /* border */
7442 s->selected = 0;
7443 view->count = 0;
7444 te = got_object_tree_get_last_entry(s->tree);
7445 for (n = 0; n < eos; n++) {
7446 if (te == NULL) {
7447 if (s->tree != s->root) {
7448 s->first_displayed_entry = NULL;
7449 n++;
7451 break;
7453 s->first_displayed_entry = te;
7454 te = got_tree_entry_get_prev(s->tree, te);
7456 if (n > 0)
7457 s->selected = n - 1;
7458 break;
7460 case 'k':
7461 case KEY_UP:
7462 case CTRL('p'):
7463 if (s->selected > 0) {
7464 s->selected--;
7465 break;
7467 tree_scroll_up(s, 1);
7468 if (s->selected_entry == NULL ||
7469 (s->tree == s->root && s->selected_entry ==
7470 got_object_tree_get_first_entry(s->tree)))
7471 view->count = 0;
7472 break;
7473 case CTRL('u'):
7474 case 'u':
7475 nscroll /= 2;
7476 /* FALL THROUGH */
7477 case KEY_PPAGE:
7478 case CTRL('b'):
7479 case 'b':
7480 if (s->tree == s->root) {
7481 if (got_object_tree_get_first_entry(s->tree) ==
7482 s->first_displayed_entry)
7483 s->selected -= MIN(s->selected, nscroll);
7484 } else {
7485 if (s->first_displayed_entry == NULL)
7486 s->selected -= MIN(s->selected, nscroll);
7488 tree_scroll_up(s, MAX(0, nscroll));
7489 if (s->selected_entry == NULL ||
7490 (s->tree == s->root && s->selected_entry ==
7491 got_object_tree_get_first_entry(s->tree)))
7492 view->count = 0;
7493 break;
7494 case 'j':
7495 case KEY_DOWN:
7496 case CTRL('n'):
7497 if (s->selected < s->ndisplayed - 1) {
7498 s->selected++;
7499 break;
7501 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7502 == NULL) {
7503 /* can't scroll any further */
7504 view->count = 0;
7505 break;
7507 tree_scroll_down(view, 1);
7508 break;
7509 case CTRL('d'):
7510 case 'd':
7511 nscroll /= 2;
7512 /* FALL THROUGH */
7513 case KEY_NPAGE:
7514 case CTRL('f'):
7515 case 'f':
7516 case ' ':
7517 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7518 == NULL) {
7519 /* can't scroll any further; move cursor down */
7520 if (s->selected < s->ndisplayed - 1)
7521 s->selected += MIN(nscroll,
7522 s->ndisplayed - s->selected - 1);
7523 else
7524 view->count = 0;
7525 break;
7527 tree_scroll_down(view, nscroll);
7528 break;
7529 case KEY_ENTER:
7530 case '\r':
7531 case KEY_BACKSPACE:
7532 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7533 struct tog_parent_tree *parent;
7534 /* user selected '..' */
7535 if (s->tree == s->root) {
7536 view->count = 0;
7537 break;
7539 parent = TAILQ_FIRST(&s->parents);
7540 TAILQ_REMOVE(&s->parents, parent,
7541 entry);
7542 got_object_tree_close(s->tree);
7543 s->tree = parent->tree;
7544 s->first_displayed_entry =
7545 parent->first_displayed_entry;
7546 s->selected_entry =
7547 parent->selected_entry;
7548 s->selected = parent->selected;
7549 if (s->selected > view->nlines - 3) {
7550 err = offset_selection_down(view);
7551 if (err)
7552 break;
7554 free(parent);
7555 } else if (S_ISDIR(got_tree_entry_get_mode(
7556 s->selected_entry))) {
7557 struct got_tree_object *subtree;
7558 view->count = 0;
7559 err = got_object_open_as_tree(&subtree, s->repo,
7560 got_tree_entry_get_id(s->selected_entry));
7561 if (err)
7562 break;
7563 err = tree_view_visit_subtree(s, subtree);
7564 if (err) {
7565 got_object_tree_close(subtree);
7566 break;
7568 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7569 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7570 break;
7571 case KEY_RESIZE:
7572 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7573 s->selected = view->nlines - 4;
7574 view->count = 0;
7575 break;
7576 default:
7577 view->count = 0;
7578 break;
7581 return err;
7584 __dead static void
7585 usage_tree(void)
7587 endwin();
7588 fprintf(stderr,
7589 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7590 getprogname());
7591 exit(1);
7594 static const struct got_error *
7595 cmd_tree(int argc, char *argv[])
7597 const struct got_error *error;
7598 struct got_repository *repo = NULL;
7599 struct got_worktree *worktree = NULL;
7600 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7601 struct got_object_id *commit_id = NULL;
7602 struct got_commit_object *commit = NULL;
7603 const char *commit_id_arg = NULL;
7604 char *label = NULL;
7605 struct got_reference *ref = NULL;
7606 const char *head_ref_name = NULL;
7607 int ch;
7608 struct tog_view *view;
7609 int *pack_fds = NULL;
7611 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7612 switch (ch) {
7613 case 'c':
7614 commit_id_arg = optarg;
7615 break;
7616 case 'r':
7617 repo_path = realpath(optarg, NULL);
7618 if (repo_path == NULL)
7619 return got_error_from_errno2("realpath",
7620 optarg);
7621 break;
7622 default:
7623 usage_tree();
7624 /* NOTREACHED */
7628 argc -= optind;
7629 argv += optind;
7631 if (argc > 1)
7632 usage_tree();
7634 error = got_repo_pack_fds_open(&pack_fds);
7635 if (error != NULL)
7636 goto done;
7638 if (repo_path == NULL) {
7639 cwd = getcwd(NULL, 0);
7640 if (cwd == NULL)
7641 return got_error_from_errno("getcwd");
7642 error = got_worktree_open(&worktree, cwd);
7643 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7644 goto done;
7645 if (worktree)
7646 repo_path =
7647 strdup(got_worktree_get_repo_path(worktree));
7648 else
7649 repo_path = strdup(cwd);
7650 if (repo_path == NULL) {
7651 error = got_error_from_errno("strdup");
7652 goto done;
7656 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7657 if (error != NULL)
7658 goto done;
7660 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7661 repo, worktree);
7662 if (error)
7663 goto done;
7665 init_curses();
7667 error = apply_unveil(got_repo_get_path(repo), NULL);
7668 if (error)
7669 goto done;
7671 error = tog_load_refs(repo, 0);
7672 if (error)
7673 goto done;
7675 if (commit_id_arg == NULL) {
7676 error = got_repo_match_object_id(&commit_id, &label,
7677 worktree ? got_worktree_get_head_ref_name(worktree) :
7678 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7679 if (error)
7680 goto done;
7681 head_ref_name = label;
7682 } else {
7683 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7684 if (error == NULL)
7685 head_ref_name = got_ref_get_name(ref);
7686 else if (error->code != GOT_ERR_NOT_REF)
7687 goto done;
7688 error = got_repo_match_object_id(&commit_id, NULL,
7689 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7690 if (error)
7691 goto done;
7694 error = got_object_open_as_commit(&commit, repo, commit_id);
7695 if (error)
7696 goto done;
7698 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7699 if (view == NULL) {
7700 error = got_error_from_errno("view_open");
7701 goto done;
7703 error = open_tree_view(view, commit_id, head_ref_name, repo);
7704 if (error)
7705 goto done;
7706 if (!got_path_is_root_dir(in_repo_path)) {
7707 error = tree_view_walk_path(&view->state.tree, commit,
7708 in_repo_path);
7709 if (error)
7710 goto done;
7713 if (worktree) {
7714 /* Release work tree lock. */
7715 got_worktree_close(worktree);
7716 worktree = NULL;
7718 error = view_loop(view);
7719 done:
7720 free(repo_path);
7721 free(cwd);
7722 free(commit_id);
7723 free(label);
7724 if (ref)
7725 got_ref_close(ref);
7726 if (repo) {
7727 const struct got_error *close_err = got_repo_close(repo);
7728 if (error == NULL)
7729 error = close_err;
7731 if (pack_fds) {
7732 const struct got_error *pack_err =
7733 got_repo_pack_fds_close(pack_fds);
7734 if (error == NULL)
7735 error = pack_err;
7737 tog_free_refs();
7738 return error;
7741 static const struct got_error *
7742 ref_view_load_refs(struct tog_ref_view_state *s)
7744 struct got_reflist_entry *sre;
7745 struct tog_reflist_entry *re;
7747 s->nrefs = 0;
7748 TAILQ_FOREACH(sre, &tog_refs, entry) {
7749 if (strncmp(got_ref_get_name(sre->ref),
7750 "refs/got/", 9) == 0 &&
7751 strncmp(got_ref_get_name(sre->ref),
7752 "refs/got/backup/", 16) != 0)
7753 continue;
7755 re = malloc(sizeof(*re));
7756 if (re == NULL)
7757 return got_error_from_errno("malloc");
7759 re->ref = got_ref_dup(sre->ref);
7760 if (re->ref == NULL)
7761 return got_error_from_errno("got_ref_dup");
7762 re->idx = s->nrefs++;
7763 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7766 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7767 return NULL;
7770 static void
7771 ref_view_free_refs(struct tog_ref_view_state *s)
7773 struct tog_reflist_entry *re;
7775 while (!TAILQ_EMPTY(&s->refs)) {
7776 re = TAILQ_FIRST(&s->refs);
7777 TAILQ_REMOVE(&s->refs, re, entry);
7778 got_ref_close(re->ref);
7779 free(re);
7783 static const struct got_error *
7784 open_ref_view(struct tog_view *view, struct got_repository *repo)
7786 const struct got_error *err = NULL;
7787 struct tog_ref_view_state *s = &view->state.ref;
7789 s->selected_entry = 0;
7790 s->repo = repo;
7792 TAILQ_INIT(&s->refs);
7793 STAILQ_INIT(&s->colors);
7795 err = ref_view_load_refs(s);
7796 if (err)
7797 return err;
7799 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7800 err = add_color(&s->colors, "^refs/heads/",
7801 TOG_COLOR_REFS_HEADS,
7802 get_color_value("TOG_COLOR_REFS_HEADS"));
7803 if (err)
7804 goto done;
7806 err = add_color(&s->colors, "^refs/tags/",
7807 TOG_COLOR_REFS_TAGS,
7808 get_color_value("TOG_COLOR_REFS_TAGS"));
7809 if (err)
7810 goto done;
7812 err = add_color(&s->colors, "^refs/remotes/",
7813 TOG_COLOR_REFS_REMOTES,
7814 get_color_value("TOG_COLOR_REFS_REMOTES"));
7815 if (err)
7816 goto done;
7818 err = add_color(&s->colors, "^refs/got/backup/",
7819 TOG_COLOR_REFS_BACKUP,
7820 get_color_value("TOG_COLOR_REFS_BACKUP"));
7821 if (err)
7822 goto done;
7825 view->show = show_ref_view;
7826 view->input = input_ref_view;
7827 view->close = close_ref_view;
7828 view->search_start = search_start_ref_view;
7829 view->search_next = search_next_ref_view;
7830 done:
7831 if (err)
7832 free_colors(&s->colors);
7833 return err;
7836 static const struct got_error *
7837 close_ref_view(struct tog_view *view)
7839 struct tog_ref_view_state *s = &view->state.ref;
7841 ref_view_free_refs(s);
7842 free_colors(&s->colors);
7844 return NULL;
7847 static const struct got_error *
7848 resolve_reflist_entry(struct got_object_id **commit_id,
7849 struct tog_reflist_entry *re, struct got_repository *repo)
7851 const struct got_error *err = NULL;
7852 struct got_object_id *obj_id;
7853 struct got_tag_object *tag = NULL;
7854 int obj_type;
7856 *commit_id = NULL;
7858 err = got_ref_resolve(&obj_id, repo, re->ref);
7859 if (err)
7860 return err;
7862 err = got_object_get_type(&obj_type, repo, obj_id);
7863 if (err)
7864 goto done;
7866 switch (obj_type) {
7867 case GOT_OBJ_TYPE_COMMIT:
7868 *commit_id = obj_id;
7869 break;
7870 case GOT_OBJ_TYPE_TAG:
7871 err = got_object_open_as_tag(&tag, repo, obj_id);
7872 if (err)
7873 goto done;
7874 free(obj_id);
7875 err = got_object_get_type(&obj_type, repo,
7876 got_object_tag_get_object_id(tag));
7877 if (err)
7878 goto done;
7879 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7880 err = got_error(GOT_ERR_OBJ_TYPE);
7881 goto done;
7883 *commit_id = got_object_id_dup(
7884 got_object_tag_get_object_id(tag));
7885 if (*commit_id == NULL) {
7886 err = got_error_from_errno("got_object_id_dup");
7887 goto done;
7889 break;
7890 default:
7891 err = got_error(GOT_ERR_OBJ_TYPE);
7892 break;
7895 done:
7896 if (tag)
7897 got_object_tag_close(tag);
7898 if (err) {
7899 free(*commit_id);
7900 *commit_id = NULL;
7902 return err;
7905 static const struct got_error *
7906 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7907 struct tog_reflist_entry *re, struct got_repository *repo)
7909 struct tog_view *log_view;
7910 const struct got_error *err = NULL;
7911 struct got_object_id *commit_id = NULL;
7913 *new_view = NULL;
7915 err = resolve_reflist_entry(&commit_id, re, repo);
7916 if (err) {
7917 if (err->code != GOT_ERR_OBJ_TYPE)
7918 return err;
7919 else
7920 return NULL;
7923 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7924 if (log_view == NULL) {
7925 err = got_error_from_errno("view_open");
7926 goto done;
7929 err = open_log_view(log_view, commit_id, repo,
7930 got_ref_get_name(re->ref), "", 0);
7931 done:
7932 if (err)
7933 view_close(log_view);
7934 else
7935 *new_view = log_view;
7936 free(commit_id);
7937 return err;
7940 static void
7941 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7943 struct tog_reflist_entry *re;
7944 int i = 0;
7946 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7947 return;
7949 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7950 while (i++ < maxscroll) {
7951 if (re == NULL)
7952 break;
7953 s->first_displayed_entry = re;
7954 re = TAILQ_PREV(re, tog_reflist_head, entry);
7958 static const struct got_error *
7959 ref_scroll_down(struct tog_view *view, int maxscroll)
7961 struct tog_ref_view_state *s = &view->state.ref;
7962 struct tog_reflist_entry *next, *last;
7963 int n = 0;
7965 if (s->first_displayed_entry)
7966 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7967 else
7968 next = TAILQ_FIRST(&s->refs);
7970 last = s->last_displayed_entry;
7971 while (next && n++ < maxscroll) {
7972 if (last) {
7973 s->last_displayed_entry = last;
7974 last = TAILQ_NEXT(last, entry);
7976 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7977 s->first_displayed_entry = next;
7978 next = TAILQ_NEXT(next, entry);
7982 return NULL;
7985 static const struct got_error *
7986 search_start_ref_view(struct tog_view *view)
7988 struct tog_ref_view_state *s = &view->state.ref;
7990 s->matched_entry = NULL;
7991 return NULL;
7994 static int
7995 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7997 regmatch_t regmatch;
7999 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8000 0) == 0;
8003 static const struct got_error *
8004 search_next_ref_view(struct tog_view *view)
8006 struct tog_ref_view_state *s = &view->state.ref;
8007 struct tog_reflist_entry *re = NULL;
8009 if (!view->searching) {
8010 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8011 return NULL;
8014 if (s->matched_entry) {
8015 if (view->searching == TOG_SEARCH_FORWARD) {
8016 if (s->selected_entry)
8017 re = TAILQ_NEXT(s->selected_entry, entry);
8018 else
8019 re = TAILQ_PREV(s->selected_entry,
8020 tog_reflist_head, entry);
8021 } else {
8022 if (s->selected_entry == NULL)
8023 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8024 else
8025 re = TAILQ_PREV(s->selected_entry,
8026 tog_reflist_head, entry);
8028 } else {
8029 if (s->selected_entry)
8030 re = s->selected_entry;
8031 else if (view->searching == TOG_SEARCH_FORWARD)
8032 re = TAILQ_FIRST(&s->refs);
8033 else
8034 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8037 while (1) {
8038 if (re == NULL) {
8039 if (s->matched_entry == NULL) {
8040 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8041 return NULL;
8043 if (view->searching == TOG_SEARCH_FORWARD)
8044 re = TAILQ_FIRST(&s->refs);
8045 else
8046 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8049 if (match_reflist_entry(re, &view->regex)) {
8050 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8051 s->matched_entry = re;
8052 break;
8055 if (view->searching == TOG_SEARCH_FORWARD)
8056 re = TAILQ_NEXT(re, entry);
8057 else
8058 re = TAILQ_PREV(re, tog_reflist_head, entry);
8061 if (s->matched_entry) {
8062 s->first_displayed_entry = s->matched_entry;
8063 s->selected = 0;
8066 return NULL;
8069 static const struct got_error *
8070 show_ref_view(struct tog_view *view)
8072 const struct got_error *err = NULL;
8073 struct tog_ref_view_state *s = &view->state.ref;
8074 struct tog_reflist_entry *re;
8075 char *line = NULL;
8076 wchar_t *wline;
8077 struct tog_color *tc;
8078 int width, n, scrollx;
8079 int limit = view->nlines;
8081 werase(view->window);
8083 s->ndisplayed = 0;
8084 if (view_is_hsplit_top(view))
8085 --limit; /* border */
8087 if (limit == 0)
8088 return NULL;
8090 re = s->first_displayed_entry;
8092 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8093 s->nrefs) == -1)
8094 return got_error_from_errno("asprintf");
8096 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8097 if (err) {
8098 free(line);
8099 return err;
8101 if (view_needs_focus_indication(view))
8102 wstandout(view->window);
8103 waddwstr(view->window, wline);
8104 while (width++ < view->ncols)
8105 waddch(view->window, ' ');
8106 if (view_needs_focus_indication(view))
8107 wstandend(view->window);
8108 free(wline);
8109 wline = NULL;
8110 free(line);
8111 line = NULL;
8112 if (--limit <= 0)
8113 return NULL;
8115 n = 0;
8116 view->maxx = 0;
8117 while (re && limit > 0) {
8118 char *line = NULL;
8119 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8121 if (s->show_date) {
8122 struct got_commit_object *ci;
8123 struct got_tag_object *tag;
8124 struct got_object_id *id;
8125 struct tm tm;
8126 time_t t;
8128 err = got_ref_resolve(&id, s->repo, re->ref);
8129 if (err)
8130 return err;
8131 err = got_object_open_as_tag(&tag, s->repo, id);
8132 if (err) {
8133 if (err->code != GOT_ERR_OBJ_TYPE) {
8134 free(id);
8135 return err;
8137 err = got_object_open_as_commit(&ci, s->repo,
8138 id);
8139 if (err) {
8140 free(id);
8141 return err;
8143 t = got_object_commit_get_committer_time(ci);
8144 got_object_commit_close(ci);
8145 } else {
8146 t = got_object_tag_get_tagger_time(tag);
8147 got_object_tag_close(tag);
8149 free(id);
8150 if (gmtime_r(&t, &tm) == NULL)
8151 return got_error_from_errno("gmtime_r");
8152 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8153 return got_error(GOT_ERR_NO_SPACE);
8155 if (got_ref_is_symbolic(re->ref)) {
8156 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8157 ymd : "", got_ref_get_name(re->ref),
8158 got_ref_get_symref_target(re->ref)) == -1)
8159 return got_error_from_errno("asprintf");
8160 } else if (s->show_ids) {
8161 struct got_object_id *id;
8162 char *id_str;
8163 err = got_ref_resolve(&id, s->repo, re->ref);
8164 if (err)
8165 return err;
8166 err = got_object_id_str(&id_str, id);
8167 if (err) {
8168 free(id);
8169 return err;
8171 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8172 got_ref_get_name(re->ref), id_str) == -1) {
8173 err = got_error_from_errno("asprintf");
8174 free(id);
8175 free(id_str);
8176 return err;
8178 free(id);
8179 free(id_str);
8180 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8181 got_ref_get_name(re->ref)) == -1)
8182 return got_error_from_errno("asprintf");
8184 /* use full line width to determine view->maxx */
8185 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8186 if (err) {
8187 free(line);
8188 return err;
8190 view->maxx = MAX(view->maxx, width);
8191 free(wline);
8192 wline = NULL;
8194 err = format_line(&wline, &width, &scrollx, line, view->x,
8195 view->ncols, 0, 0);
8196 if (err) {
8197 free(line);
8198 return err;
8200 if (n == s->selected) {
8201 if (view->focussed)
8202 wstandout(view->window);
8203 s->selected_entry = re;
8205 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8206 if (tc)
8207 wattr_on(view->window,
8208 COLOR_PAIR(tc->colorpair), NULL);
8209 waddwstr(view->window, &wline[scrollx]);
8210 if (tc)
8211 wattr_off(view->window,
8212 COLOR_PAIR(tc->colorpair), NULL);
8213 if (width < view->ncols)
8214 waddch(view->window, '\n');
8215 if (n == s->selected && view->focussed)
8216 wstandend(view->window);
8217 free(line);
8218 free(wline);
8219 wline = NULL;
8220 n++;
8221 s->ndisplayed++;
8222 s->last_displayed_entry = re;
8224 limit--;
8225 re = TAILQ_NEXT(re, entry);
8228 view_border(view);
8229 return err;
8232 static const struct got_error *
8233 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8234 struct tog_reflist_entry *re, struct got_repository *repo)
8236 const struct got_error *err = NULL;
8237 struct got_object_id *commit_id = NULL;
8238 struct tog_view *tree_view;
8240 *new_view = NULL;
8242 err = resolve_reflist_entry(&commit_id, re, repo);
8243 if (err) {
8244 if (err->code != GOT_ERR_OBJ_TYPE)
8245 return err;
8246 else
8247 return NULL;
8251 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8252 if (tree_view == NULL) {
8253 err = got_error_from_errno("view_open");
8254 goto done;
8257 err = open_tree_view(tree_view, commit_id,
8258 got_ref_get_name(re->ref), repo);
8259 if (err)
8260 goto done;
8262 *new_view = tree_view;
8263 done:
8264 free(commit_id);
8265 return err;
8268 static const struct got_error *
8269 ref_goto_line(struct tog_view *view, int nlines)
8271 const struct got_error *err = NULL;
8272 struct tog_ref_view_state *s = &view->state.ref;
8273 int g, idx = s->selected_entry->idx;
8275 g = view->gline;
8276 view->gline = 0;
8278 if (g == 0)
8279 g = 1;
8280 else if (g > s->nrefs)
8281 g = s->nrefs;
8283 if (g >= s->first_displayed_entry->idx + 1 &&
8284 g <= s->last_displayed_entry->idx + 1 &&
8285 g - s->first_displayed_entry->idx - 1 < nlines) {
8286 s->selected = g - s->first_displayed_entry->idx - 1;
8287 return NULL;
8290 if (idx + 1 < g) {
8291 err = ref_scroll_down(view, g - idx - 1);
8292 if (err)
8293 return err;
8294 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8295 s->first_displayed_entry->idx + s->selected < g &&
8296 s->selected < s->ndisplayed - 1)
8297 s->selected = g - s->first_displayed_entry->idx - 1;
8298 } else if (idx + 1 > g)
8299 ref_scroll_up(s, idx - g + 1);
8301 if (g < nlines && s->first_displayed_entry->idx == 0)
8302 s->selected = g - 1;
8304 return NULL;
8308 static const struct got_error *
8309 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8311 const struct got_error *err = NULL;
8312 struct tog_ref_view_state *s = &view->state.ref;
8313 struct tog_reflist_entry *re;
8314 int n, nscroll = view->nlines - 1;
8316 if (view->gline)
8317 return ref_goto_line(view, nscroll);
8319 switch (ch) {
8320 case '0':
8321 case '$':
8322 case KEY_RIGHT:
8323 case 'l':
8324 case KEY_LEFT:
8325 case 'h':
8326 horizontal_scroll_input(view, ch);
8327 break;
8328 case 'i':
8329 s->show_ids = !s->show_ids;
8330 view->count = 0;
8331 break;
8332 case 'm':
8333 s->show_date = !s->show_date;
8334 view->count = 0;
8335 break;
8336 case 'o':
8337 s->sort_by_date = !s->sort_by_date;
8338 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8339 view->count = 0;
8340 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8341 got_ref_cmp_by_commit_timestamp_descending :
8342 tog_ref_cmp_by_name, s->repo);
8343 if (err)
8344 break;
8345 got_reflist_object_id_map_free(tog_refs_idmap);
8346 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8347 &tog_refs, s->repo);
8348 if (err)
8349 break;
8350 ref_view_free_refs(s);
8351 err = ref_view_load_refs(s);
8352 break;
8353 case KEY_ENTER:
8354 case '\r':
8355 view->count = 0;
8356 if (!s->selected_entry)
8357 break;
8358 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8359 break;
8360 case 'T':
8361 view->count = 0;
8362 if (!s->selected_entry)
8363 break;
8364 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8365 break;
8366 case 'g':
8367 case '=':
8368 case KEY_HOME:
8369 s->selected = 0;
8370 view->count = 0;
8371 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8372 break;
8373 case 'G':
8374 case '*':
8375 case KEY_END: {
8376 int eos = view->nlines - 1;
8378 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8379 --eos; /* border */
8380 s->selected = 0;
8381 view->count = 0;
8382 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8383 for (n = 0; n < eos; n++) {
8384 if (re == NULL)
8385 break;
8386 s->first_displayed_entry = re;
8387 re = TAILQ_PREV(re, tog_reflist_head, entry);
8389 if (n > 0)
8390 s->selected = n - 1;
8391 break;
8393 case 'k':
8394 case KEY_UP:
8395 case CTRL('p'):
8396 if (s->selected > 0) {
8397 s->selected--;
8398 break;
8400 ref_scroll_up(s, 1);
8401 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8402 view->count = 0;
8403 break;
8404 case CTRL('u'):
8405 case 'u':
8406 nscroll /= 2;
8407 /* FALL THROUGH */
8408 case KEY_PPAGE:
8409 case CTRL('b'):
8410 case 'b':
8411 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8412 s->selected -= MIN(nscroll, s->selected);
8413 ref_scroll_up(s, MAX(0, nscroll));
8414 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8415 view->count = 0;
8416 break;
8417 case 'j':
8418 case KEY_DOWN:
8419 case CTRL('n'):
8420 if (s->selected < s->ndisplayed - 1) {
8421 s->selected++;
8422 break;
8424 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8425 /* can't scroll any further */
8426 view->count = 0;
8427 break;
8429 ref_scroll_down(view, 1);
8430 break;
8431 case CTRL('d'):
8432 case 'd':
8433 nscroll /= 2;
8434 /* FALL THROUGH */
8435 case KEY_NPAGE:
8436 case CTRL('f'):
8437 case 'f':
8438 case ' ':
8439 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8440 /* can't scroll any further; move cursor down */
8441 if (s->selected < s->ndisplayed - 1)
8442 s->selected += MIN(nscroll,
8443 s->ndisplayed - s->selected - 1);
8444 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8445 s->selected += s->ndisplayed - s->selected - 1;
8446 view->count = 0;
8447 break;
8449 ref_scroll_down(view, nscroll);
8450 break;
8451 case CTRL('l'):
8452 view->count = 0;
8453 tog_free_refs();
8454 err = tog_load_refs(s->repo, s->sort_by_date);
8455 if (err)
8456 break;
8457 ref_view_free_refs(s);
8458 err = ref_view_load_refs(s);
8459 break;
8460 case KEY_RESIZE:
8461 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8462 s->selected = view->nlines - 2;
8463 break;
8464 default:
8465 view->count = 0;
8466 break;
8469 return err;
8472 __dead static void
8473 usage_ref(void)
8475 endwin();
8476 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8477 getprogname());
8478 exit(1);
8481 static const struct got_error *
8482 cmd_ref(int argc, char *argv[])
8484 const struct got_error *error;
8485 struct got_repository *repo = NULL;
8486 struct got_worktree *worktree = NULL;
8487 char *cwd = NULL, *repo_path = NULL;
8488 int ch;
8489 struct tog_view *view;
8490 int *pack_fds = NULL;
8492 while ((ch = getopt(argc, argv, "r:")) != -1) {
8493 switch (ch) {
8494 case 'r':
8495 repo_path = realpath(optarg, NULL);
8496 if (repo_path == NULL)
8497 return got_error_from_errno2("realpath",
8498 optarg);
8499 break;
8500 default:
8501 usage_ref();
8502 /* NOTREACHED */
8506 argc -= optind;
8507 argv += optind;
8509 if (argc > 1)
8510 usage_ref();
8512 error = got_repo_pack_fds_open(&pack_fds);
8513 if (error != NULL)
8514 goto done;
8516 if (repo_path == NULL) {
8517 cwd = getcwd(NULL, 0);
8518 if (cwd == NULL)
8519 return got_error_from_errno("getcwd");
8520 error = got_worktree_open(&worktree, cwd);
8521 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8522 goto done;
8523 if (worktree)
8524 repo_path =
8525 strdup(got_worktree_get_repo_path(worktree));
8526 else
8527 repo_path = strdup(cwd);
8528 if (repo_path == NULL) {
8529 error = got_error_from_errno("strdup");
8530 goto done;
8534 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8535 if (error != NULL)
8536 goto done;
8538 init_curses();
8540 error = apply_unveil(got_repo_get_path(repo), NULL);
8541 if (error)
8542 goto done;
8544 error = tog_load_refs(repo, 0);
8545 if (error)
8546 goto done;
8548 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8549 if (view == NULL) {
8550 error = got_error_from_errno("view_open");
8551 goto done;
8554 error = open_ref_view(view, repo);
8555 if (error)
8556 goto done;
8558 if (worktree) {
8559 /* Release work tree lock. */
8560 got_worktree_close(worktree);
8561 worktree = NULL;
8563 error = view_loop(view);
8564 done:
8565 free(repo_path);
8566 free(cwd);
8567 if (repo) {
8568 const struct got_error *close_err = got_repo_close(repo);
8569 if (close_err)
8570 error = close_err;
8572 if (pack_fds) {
8573 const struct got_error *pack_err =
8574 got_repo_pack_fds_close(pack_fds);
8575 if (error == NULL)
8576 error = pack_err;
8578 tog_free_refs();
8579 return error;
8582 static const struct got_error*
8583 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8584 const char *str)
8586 size_t len;
8588 if (win == NULL)
8589 win = stdscr;
8591 len = strlen(str);
8592 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8594 if (focus)
8595 wstandout(win);
8596 if (mvwprintw(win, y, x, "%s", str) == ERR)
8597 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8598 if (focus)
8599 wstandend(win);
8601 return NULL;
8604 static const struct got_error *
8605 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8607 off_t *p;
8609 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8610 if (p == NULL) {
8611 free(*line_offsets);
8612 *line_offsets = NULL;
8613 return got_error_from_errno("reallocarray");
8616 *line_offsets = p;
8617 (*line_offsets)[*nlines] = off;
8618 ++(*nlines);
8619 return NULL;
8622 static const struct got_error *
8623 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8625 *ret = 0;
8627 for (;n > 0; --n, ++km) {
8628 char *t0, *t, *k;
8629 size_t len = 1;
8631 if (km->keys == NULL)
8632 continue;
8634 t = t0 = strdup(km->keys);
8635 if (t0 == NULL)
8636 return got_error_from_errno("strdup");
8638 len += strlen(t);
8639 while ((k = strsep(&t, " ")) != NULL)
8640 len += strlen(k) > 1 ? 2 : 0;
8641 free(t0);
8642 *ret = MAX(*ret, len);
8645 return NULL;
8649 * Write keymap section headers, keys, and key info in km to f.
8650 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8651 * wrap control and symbolic keys in guillemets, else use <>.
8653 static const struct got_error *
8654 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8656 int n, len = width;
8658 if (km->keys) {
8659 static const char *u8_glyph[] = {
8660 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8661 "\xe2\x80\xba" /* U+203A (utf8 >) */
8663 char *t0, *t, *k;
8664 int cs, s, first = 1;
8666 cs = got_locale_is_utf8();
8668 t = t0 = strdup(km->keys);
8669 if (t0 == NULL)
8670 return got_error_from_errno("strdup");
8672 len = strlen(km->keys);
8673 while ((k = strsep(&t, " ")) != NULL) {
8674 s = strlen(k) > 1; /* control or symbolic key */
8675 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8676 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8677 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8678 if (n < 0) {
8679 free(t0);
8680 return got_error_from_errno("fprintf");
8682 first = 0;
8683 len += s ? 2 : 0;
8684 *off += n;
8686 free(t0);
8688 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8689 if (n < 0)
8690 return got_error_from_errno("fprintf");
8691 *off += n;
8693 return NULL;
8696 static const struct got_error *
8697 format_help(struct tog_help_view_state *s)
8699 const struct got_error *err = NULL;
8700 off_t off = 0;
8701 int i, max, n, show = s->all;
8702 static const struct tog_key_map km[] = {
8703 #define KEYMAP_(info, type) { NULL, (info), type }
8704 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8705 GENERATE_HELP
8706 #undef KEYMAP_
8707 #undef KEY_
8710 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8711 if (err)
8712 return err;
8714 n = nitems(km);
8715 err = max_key_str(&max, km, n);
8716 if (err)
8717 return err;
8719 for (i = 0; i < n; ++i) {
8720 if (km[i].keys == NULL) {
8721 show = s->all;
8722 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8723 km[i].type == s->type || s->all)
8724 show = 1;
8726 if (show) {
8727 err = format_help_line(&off, s->f, &km[i], max);
8728 if (err)
8729 return err;
8730 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8731 if (err)
8732 return err;
8735 fputc('\n', s->f);
8736 ++off;
8737 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8738 return err;
8741 static const struct got_error *
8742 create_help(struct tog_help_view_state *s)
8744 FILE *f;
8745 const struct got_error *err;
8747 free(s->line_offsets);
8748 s->line_offsets = NULL;
8749 s->nlines = 0;
8751 f = got_opentemp();
8752 if (f == NULL)
8753 return got_error_from_errno("got_opentemp");
8754 s->f = f;
8756 err = format_help(s);
8757 if (err)
8758 return err;
8760 if (s->f && fflush(s->f) != 0)
8761 return got_error_from_errno("fflush");
8763 return NULL;
8766 static const struct got_error *
8767 search_start_help_view(struct tog_view *view)
8769 view->state.help.matched_line = 0;
8770 return NULL;
8773 static void
8774 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8775 size_t *nlines, int **first, int **last, int **match, int **selected)
8777 struct tog_help_view_state *s = &view->state.help;
8779 *f = s->f;
8780 *nlines = s->nlines;
8781 *line_offsets = s->line_offsets;
8782 *match = &s->matched_line;
8783 *first = &s->first_displayed_line;
8784 *last = &s->last_displayed_line;
8785 *selected = &s->selected_line;
8788 static const struct got_error *
8789 show_help_view(struct tog_view *view)
8791 struct tog_help_view_state *s = &view->state.help;
8792 const struct got_error *err;
8793 regmatch_t *regmatch = &view->regmatch;
8794 wchar_t *wline;
8795 char *line;
8796 ssize_t linelen;
8797 size_t linesz = 0;
8798 int width, nprinted = 0, rc = 0;
8799 int eos = view->nlines;
8801 if (view_is_hsplit_top(view))
8802 --eos; /* account for border */
8804 s->lineno = 0;
8805 rewind(s->f);
8806 werase(view->window);
8808 if (view->gline > s->nlines - 1)
8809 view->gline = s->nlines - 1;
8811 err = win_draw_center(view->window, 0, 0, view->ncols,
8812 view_needs_focus_indication(view),
8813 "tog help (press q to return to tog)");
8814 if (err)
8815 return err;
8816 if (eos <= 1)
8817 return NULL;
8818 waddstr(view->window, "\n\n");
8819 eos -= 2;
8821 s->eof = 0;
8822 view->maxx = 0;
8823 line = NULL;
8824 while (eos > 0 && nprinted < eos) {
8825 attr_t attr = 0;
8827 linelen = getline(&line, &linesz, s->f);
8828 if (linelen == -1) {
8829 if (!feof(s->f)) {
8830 free(line);
8831 return got_ferror(s->f, GOT_ERR_IO);
8833 s->eof = 1;
8834 break;
8836 if (++s->lineno < s->first_displayed_line)
8837 continue;
8838 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8839 continue;
8840 if (s->lineno == view->hiline)
8841 attr = A_STANDOUT;
8843 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8844 view->x ? 1 : 0);
8845 if (err) {
8846 free(line);
8847 return err;
8849 view->maxx = MAX(view->maxx, width);
8850 free(wline);
8851 wline = NULL;
8853 if (attr)
8854 wattron(view->window, attr);
8855 if (s->first_displayed_line + nprinted == s->matched_line &&
8856 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8857 err = add_matched_line(&width, line, view->ncols - 1, 0,
8858 view->window, view->x, regmatch);
8859 if (err) {
8860 free(line);
8861 return err;
8863 } else {
8864 int skip;
8866 err = format_line(&wline, &width, &skip, line,
8867 view->x, view->ncols, 0, view->x ? 1 : 0);
8868 if (err) {
8869 free(line);
8870 return err;
8872 waddwstr(view->window, &wline[skip]);
8873 free(wline);
8874 wline = NULL;
8876 if (s->lineno == view->hiline) {
8877 while (width++ < view->ncols)
8878 waddch(view->window, ' ');
8879 } else {
8880 if (width < view->ncols)
8881 waddch(view->window, '\n');
8883 if (attr)
8884 wattroff(view->window, attr);
8885 if (++nprinted == 1)
8886 s->first_displayed_line = s->lineno;
8888 free(line);
8889 if (nprinted > 0)
8890 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8891 else
8892 s->last_displayed_line = s->first_displayed_line;
8894 view_border(view);
8896 if (s->eof) {
8897 rc = waddnstr(view->window,
8898 "See the tog(1) manual page for full documentation",
8899 view->ncols - 1);
8900 if (rc == ERR)
8901 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8902 } else {
8903 wmove(view->window, view->nlines - 1, 0);
8904 wclrtoeol(view->window);
8905 wstandout(view->window);
8906 rc = waddnstr(view->window, "scroll down for more...",
8907 view->ncols - 1);
8908 if (rc == ERR)
8909 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8910 if (getcurx(view->window) < view->ncols - 6) {
8911 rc = wprintw(view->window, "[%.0f%%]",
8912 100.00 * s->last_displayed_line / s->nlines);
8913 if (rc == ERR)
8914 return got_error_msg(GOT_ERR_IO, "wprintw");
8916 wstandend(view->window);
8919 return NULL;
8922 static const struct got_error *
8923 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8925 struct tog_help_view_state *s = &view->state.help;
8926 const struct got_error *err = NULL;
8927 char *line = NULL;
8928 ssize_t linelen;
8929 size_t linesz = 0;
8930 int eos, nscroll;
8932 eos = nscroll = view->nlines;
8933 if (view_is_hsplit_top(view))
8934 --eos; /* border */
8936 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8938 switch (ch) {
8939 case '0':
8940 case '$':
8941 case KEY_RIGHT:
8942 case 'l':
8943 case KEY_LEFT:
8944 case 'h':
8945 horizontal_scroll_input(view, ch);
8946 break;
8947 case 'g':
8948 case KEY_HOME:
8949 s->first_displayed_line = 1;
8950 view->count = 0;
8951 break;
8952 case 'G':
8953 case KEY_END:
8954 view->count = 0;
8955 if (s->eof)
8956 break;
8957 s->first_displayed_line = (s->nlines - eos) + 3;
8958 s->eof = 1;
8959 break;
8960 case 'k':
8961 case KEY_UP:
8962 if (s->first_displayed_line > 1)
8963 --s->first_displayed_line;
8964 else
8965 view->count = 0;
8966 break;
8967 case CTRL('u'):
8968 case 'u':
8969 nscroll /= 2;
8970 /* FALL THROUGH */
8971 case KEY_PPAGE:
8972 case CTRL('b'):
8973 case 'b':
8974 if (s->first_displayed_line == 1) {
8975 view->count = 0;
8976 break;
8978 while (--nscroll > 0 && s->first_displayed_line > 1)
8979 s->first_displayed_line--;
8980 break;
8981 case 'j':
8982 case KEY_DOWN:
8983 case CTRL('n'):
8984 if (!s->eof)
8985 ++s->first_displayed_line;
8986 else
8987 view->count = 0;
8988 break;
8989 case CTRL('d'):
8990 case 'd':
8991 nscroll /= 2;
8992 /* FALL THROUGH */
8993 case KEY_NPAGE:
8994 case CTRL('f'):
8995 case 'f':
8996 case ' ':
8997 if (s->eof) {
8998 view->count = 0;
8999 break;
9001 while (!s->eof && --nscroll > 0) {
9002 linelen = getline(&line, &linesz, s->f);
9003 s->first_displayed_line++;
9004 if (linelen == -1) {
9005 if (feof(s->f))
9006 s->eof = 1;
9007 else
9008 err = got_ferror(s->f, GOT_ERR_IO);
9009 break;
9012 free(line);
9013 break;
9014 default:
9015 view->count = 0;
9016 break;
9019 return err;
9022 static const struct got_error *
9023 close_help_view(struct tog_view *view)
9025 struct tog_help_view_state *s = &view->state.help;
9027 free(s->line_offsets);
9028 s->line_offsets = NULL;
9029 if (fclose(s->f) == EOF)
9030 return got_error_from_errno("fclose");
9032 return NULL;
9035 static const struct got_error *
9036 reset_help_view(struct tog_view *view)
9038 struct tog_help_view_state *s = &view->state.help;
9041 if (s->f && fclose(s->f) == EOF)
9042 return got_error_from_errno("fclose");
9044 wclear(view->window);
9045 view->count = 0;
9046 view->x = 0;
9047 s->all = !s->all;
9048 s->first_displayed_line = 1;
9049 s->last_displayed_line = view->nlines;
9050 s->matched_line = 0;
9052 return create_help(s);
9055 static const struct got_error *
9056 open_help_view(struct tog_view *view, struct tog_view *parent)
9058 const struct got_error *err = NULL;
9059 struct tog_help_view_state *s = &view->state.help;
9061 s->type = (enum tog_keymap_type)parent->type;
9062 s->first_displayed_line = 1;
9063 s->last_displayed_line = view->nlines;
9064 s->selected_line = 1;
9066 view->show = show_help_view;
9067 view->input = input_help_view;
9068 view->reset = reset_help_view;
9069 view->close = close_help_view;
9070 view->search_start = search_start_help_view;
9071 view->search_setup = search_setup_help_view;
9072 view->search_next = search_next_view_match;
9074 err = create_help(s);
9075 return err;
9078 static const struct got_error *
9079 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9080 enum tog_view_type request, int y, int x)
9082 const struct got_error *err = NULL;
9084 *new_view = NULL;
9086 switch (request) {
9087 case TOG_VIEW_DIFF:
9088 if (view->type == TOG_VIEW_LOG) {
9089 struct tog_log_view_state *s = &view->state.log;
9091 err = open_diff_view_for_commit(new_view, y, x,
9092 s->selected_entry->commit, s->selected_entry->id,
9093 view, s->repo);
9094 } else
9095 return got_error_msg(GOT_ERR_NOT_IMPL,
9096 "parent/child view pair not supported");
9097 break;
9098 case TOG_VIEW_BLAME:
9099 if (view->type == TOG_VIEW_TREE) {
9100 struct tog_tree_view_state *s = &view->state.tree;
9102 err = blame_tree_entry(new_view, y, x,
9103 s->selected_entry, &s->parents, s->commit_id,
9104 s->repo);
9105 } else
9106 return got_error_msg(GOT_ERR_NOT_IMPL,
9107 "parent/child view pair not supported");
9108 break;
9109 case TOG_VIEW_LOG:
9110 if (view->type == TOG_VIEW_BLAME)
9111 err = log_annotated_line(new_view, y, x,
9112 view->state.blame.repo, view->state.blame.id_to_log);
9113 else if (view->type == TOG_VIEW_TREE)
9114 err = log_selected_tree_entry(new_view, y, x,
9115 &view->state.tree);
9116 else if (view->type == TOG_VIEW_REF)
9117 err = log_ref_entry(new_view, y, x,
9118 view->state.ref.selected_entry,
9119 view->state.ref.repo);
9120 else
9121 return got_error_msg(GOT_ERR_NOT_IMPL,
9122 "parent/child view pair not supported");
9123 break;
9124 case TOG_VIEW_TREE:
9125 if (view->type == TOG_VIEW_LOG)
9126 err = browse_commit_tree(new_view, y, x,
9127 view->state.log.selected_entry,
9128 view->state.log.in_repo_path,
9129 view->state.log.head_ref_name,
9130 view->state.log.repo);
9131 else if (view->type == TOG_VIEW_REF)
9132 err = browse_ref_tree(new_view, y, x,
9133 view->state.ref.selected_entry,
9134 view->state.ref.repo);
9135 else
9136 return got_error_msg(GOT_ERR_NOT_IMPL,
9137 "parent/child view pair not supported");
9138 break;
9139 case TOG_VIEW_REF:
9140 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9141 if (*new_view == NULL)
9142 return got_error_from_errno("view_open");
9143 if (view->type == TOG_VIEW_LOG)
9144 err = open_ref_view(*new_view, view->state.log.repo);
9145 else if (view->type == TOG_VIEW_TREE)
9146 err = open_ref_view(*new_view, view->state.tree.repo);
9147 else
9148 err = got_error_msg(GOT_ERR_NOT_IMPL,
9149 "parent/child view pair not supported");
9150 if (err)
9151 view_close(*new_view);
9152 break;
9153 case TOG_VIEW_HELP:
9154 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9155 if (*new_view == NULL)
9156 return got_error_from_errno("view_open");
9157 err = open_help_view(*new_view, view);
9158 if (err)
9159 view_close(*new_view);
9160 break;
9161 default:
9162 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9165 return err;
9169 * If view was scrolled down to move the selected line into view when opening a
9170 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9172 static void
9173 offset_selection_up(struct tog_view *view)
9175 switch (view->type) {
9176 case TOG_VIEW_BLAME: {
9177 struct tog_blame_view_state *s = &view->state.blame;
9178 if (s->first_displayed_line == 1) {
9179 s->selected_line = MAX(s->selected_line - view->offset,
9180 1);
9181 break;
9183 if (s->first_displayed_line > view->offset)
9184 s->first_displayed_line -= view->offset;
9185 else
9186 s->first_displayed_line = 1;
9187 s->selected_line += view->offset;
9188 break;
9190 case TOG_VIEW_LOG:
9191 log_scroll_up(&view->state.log, view->offset);
9192 view->state.log.selected += view->offset;
9193 break;
9194 case TOG_VIEW_REF:
9195 ref_scroll_up(&view->state.ref, view->offset);
9196 view->state.ref.selected += view->offset;
9197 break;
9198 case TOG_VIEW_TREE:
9199 tree_scroll_up(&view->state.tree, view->offset);
9200 view->state.tree.selected += view->offset;
9201 break;
9202 default:
9203 break;
9206 view->offset = 0;
9210 * If the selected line is in the section of screen covered by the bottom split,
9211 * scroll down offset lines to move it into view and index its new position.
9213 static const struct got_error *
9214 offset_selection_down(struct tog_view *view)
9216 const struct got_error *err = NULL;
9217 const struct got_error *(*scrolld)(struct tog_view *, int);
9218 int *selected = NULL;
9219 int header, offset;
9221 switch (view->type) {
9222 case TOG_VIEW_BLAME: {
9223 struct tog_blame_view_state *s = &view->state.blame;
9224 header = 3;
9225 scrolld = NULL;
9226 if (s->selected_line > view->nlines - header) {
9227 offset = abs(view->nlines - s->selected_line - header);
9228 s->first_displayed_line += offset;
9229 s->selected_line -= offset;
9230 view->offset = offset;
9232 break;
9234 case TOG_VIEW_LOG: {
9235 struct tog_log_view_state *s = &view->state.log;
9236 scrolld = &log_scroll_down;
9237 header = view_is_parent_view(view) ? 3 : 2;
9238 selected = &s->selected;
9239 break;
9241 case TOG_VIEW_REF: {
9242 struct tog_ref_view_state *s = &view->state.ref;
9243 scrolld = &ref_scroll_down;
9244 header = 3;
9245 selected = &s->selected;
9246 break;
9248 case TOG_VIEW_TREE: {
9249 struct tog_tree_view_state *s = &view->state.tree;
9250 scrolld = &tree_scroll_down;
9251 header = 5;
9252 selected = &s->selected;
9253 break;
9255 default:
9256 selected = NULL;
9257 scrolld = NULL;
9258 header = 0;
9259 break;
9262 if (selected && *selected > view->nlines - header) {
9263 offset = abs(view->nlines - *selected - header);
9264 view->offset = offset;
9265 if (scrolld && offset) {
9266 err = scrolld(view, offset);
9267 *selected -= offset;
9271 return err;
9274 static void
9275 list_commands(FILE *fp)
9277 size_t i;
9279 fprintf(fp, "commands:");
9280 for (i = 0; i < nitems(tog_commands); i++) {
9281 const struct tog_cmd *cmd = &tog_commands[i];
9282 fprintf(fp, " %s", cmd->name);
9284 fputc('\n', fp);
9287 __dead static void
9288 usage(int hflag, int status)
9290 FILE *fp = (status == 0) ? stdout : stderr;
9292 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9293 getprogname());
9294 if (hflag) {
9295 fprintf(fp, "lazy usage: %s path\n", getprogname());
9296 list_commands(fp);
9298 exit(status);
9301 static char **
9302 make_argv(int argc, ...)
9304 va_list ap;
9305 char **argv;
9306 int i;
9308 va_start(ap, argc);
9310 argv = calloc(argc, sizeof(char *));
9311 if (argv == NULL)
9312 err(1, "calloc");
9313 for (i = 0; i < argc; i++) {
9314 argv[i] = strdup(va_arg(ap, char *));
9315 if (argv[i] == NULL)
9316 err(1, "strdup");
9319 va_end(ap);
9320 return argv;
9324 * Try to convert 'tog path' into a 'tog log path' command.
9325 * The user could simply have mistyped the command rather than knowingly
9326 * provided a path. So check whether argv[0] can in fact be resolved
9327 * to a path in the HEAD commit and print a special error if not.
9328 * This hack is for mpi@ <3
9330 static const struct got_error *
9331 tog_log_with_path(int argc, char *argv[])
9333 const struct got_error *error = NULL, *close_err;
9334 const struct tog_cmd *cmd = NULL;
9335 struct got_repository *repo = NULL;
9336 struct got_worktree *worktree = NULL;
9337 struct got_object_id *commit_id = NULL, *id = NULL;
9338 struct got_commit_object *commit = NULL;
9339 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9340 char *commit_id_str = NULL, **cmd_argv = NULL;
9341 int *pack_fds = NULL;
9343 cwd = getcwd(NULL, 0);
9344 if (cwd == NULL)
9345 return got_error_from_errno("getcwd");
9347 error = got_repo_pack_fds_open(&pack_fds);
9348 if (error != NULL)
9349 goto done;
9351 error = got_worktree_open(&worktree, cwd);
9352 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9353 goto done;
9355 if (worktree)
9356 repo_path = strdup(got_worktree_get_repo_path(worktree));
9357 else
9358 repo_path = strdup(cwd);
9359 if (repo_path == NULL) {
9360 error = got_error_from_errno("strdup");
9361 goto done;
9364 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9365 if (error != NULL)
9366 goto done;
9368 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9369 repo, worktree);
9370 if (error)
9371 goto done;
9373 error = tog_load_refs(repo, 0);
9374 if (error)
9375 goto done;
9376 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9377 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9378 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9379 if (error)
9380 goto done;
9382 if (worktree) {
9383 got_worktree_close(worktree);
9384 worktree = NULL;
9387 error = got_object_open_as_commit(&commit, repo, commit_id);
9388 if (error)
9389 goto done;
9391 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9392 if (error) {
9393 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9394 goto done;
9395 fprintf(stderr, "%s: '%s' is no known command or path\n",
9396 getprogname(), argv[0]);
9397 usage(1, 1);
9398 /* not reached */
9401 error = got_object_id_str(&commit_id_str, commit_id);
9402 if (error)
9403 goto done;
9405 cmd = &tog_commands[0]; /* log */
9406 argc = 4;
9407 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9408 error = cmd->cmd_main(argc, cmd_argv);
9409 done:
9410 if (repo) {
9411 close_err = got_repo_close(repo);
9412 if (error == NULL)
9413 error = close_err;
9415 if (commit)
9416 got_object_commit_close(commit);
9417 if (worktree)
9418 got_worktree_close(worktree);
9419 if (pack_fds) {
9420 const struct got_error *pack_err =
9421 got_repo_pack_fds_close(pack_fds);
9422 if (error == NULL)
9423 error = pack_err;
9425 free(id);
9426 free(commit_id_str);
9427 free(commit_id);
9428 free(cwd);
9429 free(repo_path);
9430 free(in_repo_path);
9431 if (cmd_argv) {
9432 int i;
9433 for (i = 0; i < argc; i++)
9434 free(cmd_argv[i]);
9435 free(cmd_argv);
9437 tog_free_refs();
9438 return error;
9441 int
9442 main(int argc, char *argv[])
9444 const struct got_error *error = NULL;
9445 const struct tog_cmd *cmd = NULL;
9446 int ch, hflag = 0, Vflag = 0;
9447 char **cmd_argv = NULL;
9448 static const struct option longopts[] = {
9449 { "version", no_argument, NULL, 'V' },
9450 { NULL, 0, NULL, 0}
9452 char *diff_algo_str = NULL;
9454 setlocale(LC_CTYPE, "");
9456 #ifndef PROFILE
9457 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9458 NULL) == -1)
9459 err(1, "pledge");
9460 #endif
9462 if (!isatty(STDIN_FILENO))
9463 errx(1, "standard input is not a tty");
9465 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9466 switch (ch) {
9467 case 'h':
9468 hflag = 1;
9469 break;
9470 case 'V':
9471 Vflag = 1;
9472 break;
9473 default:
9474 usage(hflag, 1);
9475 /* NOTREACHED */
9479 argc -= optind;
9480 argv += optind;
9481 optind = 1;
9482 optreset = 1;
9484 if (Vflag) {
9485 got_version_print_str();
9486 return 0;
9489 if (argc == 0) {
9490 if (hflag)
9491 usage(hflag, 0);
9492 /* Build an argument vector which runs a default command. */
9493 cmd = &tog_commands[0];
9494 argc = 1;
9495 cmd_argv = make_argv(argc, cmd->name);
9496 } else {
9497 size_t i;
9499 /* Did the user specify a command? */
9500 for (i = 0; i < nitems(tog_commands); i++) {
9501 if (strncmp(tog_commands[i].name, argv[0],
9502 strlen(argv[0])) == 0) {
9503 cmd = &tog_commands[i];
9504 break;
9509 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9510 if (diff_algo_str) {
9511 if (strcasecmp(diff_algo_str, "patience") == 0)
9512 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9513 if (strcasecmp(diff_algo_str, "myers") == 0)
9514 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9517 if (cmd == NULL) {
9518 if (argc != 1)
9519 usage(0, 1);
9520 /* No command specified; try log with a path */
9521 error = tog_log_with_path(argc, argv);
9522 } else {
9523 if (hflag)
9524 cmd->cmd_usage();
9525 else
9526 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9529 endwin();
9530 if (cmd_argv) {
9531 int i;
9532 for (i = 0; i < argc; i++)
9533 free(cmd_argv[i]);
9534 free(cmd_argv);
9537 if (error && error->code != GOT_ERR_CANCELLED &&
9538 error->code != GOT_ERR_EOF &&
9539 error->code != GOT_ERR_PRIVSEP_EXIT &&
9540 error->code != GOT_ERR_PRIVSEP_PIPE &&
9541 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9542 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9543 return 0;