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 <sha2.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_diff.h"
51 #include "got_opentemp.h"
52 #include "got_utf8.h"
53 #include "got_cancel.h"
54 #include "got_commit_graph.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_path.h"
58 #include "got_worktree.h"
60 #ifndef MIN
61 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
62 #endif
64 #ifndef MAX
65 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
66 #endif
68 #define CTRL(x) ((x) & 0x1f)
70 #ifndef nitems
71 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
72 #endif
74 struct tog_cmd {
75 const char *name;
76 const struct got_error *(*cmd_main)(int, char *[]);
77 void (*cmd_usage)(void);
78 };
80 __dead static void usage(int, int);
81 __dead static void usage_log(void);
82 __dead static void usage_diff(void);
83 __dead static void usage_blame(void);
84 __dead static void usage_tree(void);
85 __dead static void usage_ref(void);
87 static const struct got_error* cmd_log(int, char *[]);
88 static const struct got_error* cmd_diff(int, char *[]);
89 static const struct got_error* cmd_blame(int, char *[]);
90 static const struct got_error* cmd_tree(int, char *[]);
91 static const struct got_error* cmd_ref(int, char *[]);
93 static const struct tog_cmd tog_commands[] = {
94 { "log", cmd_log, usage_log },
95 { "diff", cmd_diff, usage_diff },
96 { "blame", cmd_blame, usage_blame },
97 { "tree", cmd_tree, usage_tree },
98 { "ref", cmd_ref, usage_ref },
99 };
101 enum tog_view_type {
102 TOG_VIEW_DIFF,
103 TOG_VIEW_LOG,
104 TOG_VIEW_BLAME,
105 TOG_VIEW_TREE,
106 TOG_VIEW_REF,
107 TOG_VIEW_HELP
108 };
110 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
111 enum tog_keymap_type {
112 TOG_KEYMAP_KEYS = -2,
113 TOG_KEYMAP_GLOBAL,
114 TOG_KEYMAP_DIFF,
115 TOG_KEYMAP_LOG,
116 TOG_KEYMAP_BLAME,
117 TOG_KEYMAP_TREE,
118 TOG_KEYMAP_REF,
119 TOG_KEYMAP_HELP
120 };
122 enum tog_view_mode {
123 TOG_VIEW_SPLIT_NONE,
124 TOG_VIEW_SPLIT_VERT,
125 TOG_VIEW_SPLIT_HRZN
126 };
128 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
130 #define TOG_EOF_STRING "(END)"
132 struct commit_queue_entry {
133 TAILQ_ENTRY(commit_queue_entry) entry;
134 struct got_object_id *id;
135 struct got_commit_object *commit;
136 int idx;
137 };
138 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
139 struct commit_queue {
140 int ncommits;
141 struct commit_queue_head head;
142 };
144 struct tog_color {
145 STAILQ_ENTRY(tog_color) entry;
146 regex_t regex;
147 short colorpair;
148 };
149 STAILQ_HEAD(tog_colors, tog_color);
151 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
152 static struct got_reflist_object_id_map *tog_refs_idmap;
153 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
155 static const struct got_error *
156 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
157 struct got_reference* re2)
159 const char *name1 = got_ref_get_name(re1);
160 const char *name2 = got_ref_get_name(re2);
161 int isbackup1, isbackup2;
163 /* Sort backup refs towards the bottom of the list. */
164 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
165 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
166 if (!isbackup1 && isbackup2) {
167 *cmp = -1;
168 return NULL;
169 } else if (isbackup1 && !isbackup2) {
170 *cmp = 1;
171 return NULL;
174 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
175 return NULL;
178 static const struct got_error *
179 tog_load_refs(struct got_repository *repo, int sort_by_date)
181 const struct got_error *err;
183 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
184 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
185 repo);
186 if (err)
187 return err;
189 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
190 repo);
193 static void
194 tog_free_refs(void)
196 if (tog_refs_idmap) {
197 got_reflist_object_id_map_free(tog_refs_idmap);
198 tog_refs_idmap = NULL;
200 got_ref_list_free(&tog_refs);
203 static const struct got_error *
204 add_color(struct tog_colors *colors, const char *pattern,
205 int idx, short color)
207 const struct got_error *err = NULL;
208 struct tog_color *tc;
209 int regerr = 0;
211 if (idx < 1 || idx > COLOR_PAIRS - 1)
212 return NULL;
214 init_pair(idx, color, -1);
216 tc = calloc(1, sizeof(*tc));
217 if (tc == NULL)
218 return got_error_from_errno("calloc");
219 regerr = regcomp(&tc->regex, pattern,
220 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
221 if (regerr) {
222 static char regerr_msg[512];
223 static char err_msg[512];
224 regerror(regerr, &tc->regex, regerr_msg,
225 sizeof(regerr_msg));
226 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
227 regerr_msg);
228 err = got_error_msg(GOT_ERR_REGEX, err_msg);
229 free(tc);
230 return err;
232 tc->colorpair = idx;
233 STAILQ_INSERT_HEAD(colors, tc, entry);
234 return NULL;
237 static void
238 free_colors(struct tog_colors *colors)
240 struct tog_color *tc;
242 while (!STAILQ_EMPTY(colors)) {
243 tc = STAILQ_FIRST(colors);
244 STAILQ_REMOVE_HEAD(colors, entry);
245 regfree(&tc->regex);
246 free(tc);
250 static struct tog_color *
251 get_color(struct tog_colors *colors, int colorpair)
253 struct tog_color *tc = NULL;
255 STAILQ_FOREACH(tc, colors, entry) {
256 if (tc->colorpair == colorpair)
257 return tc;
260 return NULL;
263 static int
264 default_color_value(const char *envvar)
266 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
267 return COLOR_MAGENTA;
268 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
269 return COLOR_CYAN;
270 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
271 return COLOR_YELLOW;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
273 return COLOR_GREEN;
274 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
275 return COLOR_MAGENTA;
276 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
279 return COLOR_CYAN;
280 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
281 return COLOR_GREEN;
282 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
283 return COLOR_GREEN;
284 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
285 return COLOR_CYAN;
286 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
287 return COLOR_YELLOW;
288 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
289 return COLOR_GREEN;
290 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
291 return COLOR_MAGENTA;
292 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
293 return COLOR_YELLOW;
294 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
295 return COLOR_CYAN;
297 return -1;
300 static int
301 get_color_value(const char *envvar)
303 const char *val = getenv(envvar);
305 if (val == NULL)
306 return default_color_value(envvar);
308 if (strcasecmp(val, "black") == 0)
309 return COLOR_BLACK;
310 if (strcasecmp(val, "red") == 0)
311 return COLOR_RED;
312 if (strcasecmp(val, "green") == 0)
313 return COLOR_GREEN;
314 if (strcasecmp(val, "yellow") == 0)
315 return COLOR_YELLOW;
316 if (strcasecmp(val, "blue") == 0)
317 return COLOR_BLUE;
318 if (strcasecmp(val, "magenta") == 0)
319 return COLOR_MAGENTA;
320 if (strcasecmp(val, "cyan") == 0)
321 return COLOR_CYAN;
322 if (strcasecmp(val, "white") == 0)
323 return COLOR_WHITE;
324 if (strcasecmp(val, "default") == 0)
325 return -1;
327 return default_color_value(envvar);
330 struct tog_diff_view_state {
331 struct got_object_id *id1, *id2;
332 const char *label1, *label2;
333 FILE *f, *f1, *f2;
334 int fd1, fd2;
335 int lineno;
336 int first_displayed_line;
337 int last_displayed_line;
338 int eof;
339 int diff_context;
340 int ignore_whitespace;
341 int force_text_diff;
342 struct got_repository *repo;
343 struct got_diff_line *lines;
344 size_t nlines;
345 int matched_line;
346 int selected_line;
348 /* passed from log or blame view; may be NULL */
349 struct tog_view *parent_view;
350 };
352 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
353 static volatile sig_atomic_t tog_thread_error;
355 struct tog_log_thread_args {
356 pthread_cond_t need_commits;
357 pthread_cond_t commit_loaded;
358 int commits_needed;
359 int load_all;
360 struct got_commit_graph *graph;
361 struct commit_queue *real_commits;
362 const char *in_repo_path;
363 struct got_object_id *start_id;
364 struct got_repository *repo;
365 int *pack_fds;
366 int log_complete;
367 sig_atomic_t *quit;
368 struct commit_queue_entry **first_displayed_entry;
369 struct commit_queue_entry **selected_entry;
370 int *searching;
371 int *search_next_done;
372 regex_t *regex;
373 int *limiting;
374 int limit_match;
375 regex_t *limit_regex;
376 struct commit_queue *limit_commits;
377 };
379 struct tog_log_view_state {
380 struct commit_queue *commits;
381 struct commit_queue_entry *first_displayed_entry;
382 struct commit_queue_entry *last_displayed_entry;
383 struct commit_queue_entry *selected_entry;
384 struct commit_queue real_commits;
385 int selected;
386 char *in_repo_path;
387 char *head_ref_name;
388 int log_branches;
389 struct got_repository *repo;
390 struct got_object_id *start_id;
391 sig_atomic_t quit;
392 pthread_t thread;
393 struct tog_log_thread_args thread_args;
394 struct commit_queue_entry *matched_entry;
395 struct commit_queue_entry *search_entry;
396 struct tog_colors colors;
397 int use_committer;
398 int limit_view;
399 regex_t limit_regex;
400 struct commit_queue limit_commits;
401 };
403 #define TOG_COLOR_DIFF_MINUS 1
404 #define TOG_COLOR_DIFF_PLUS 2
405 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
406 #define TOG_COLOR_DIFF_META 4
407 #define TOG_COLOR_TREE_SUBMODULE 5
408 #define TOG_COLOR_TREE_SYMLINK 6
409 #define TOG_COLOR_TREE_DIRECTORY 7
410 #define TOG_COLOR_TREE_EXECUTABLE 8
411 #define TOG_COLOR_COMMIT 9
412 #define TOG_COLOR_AUTHOR 10
413 #define TOG_COLOR_DATE 11
414 #define TOG_COLOR_REFS_HEADS 12
415 #define TOG_COLOR_REFS_TAGS 13
416 #define TOG_COLOR_REFS_REMOTES 14
417 #define TOG_COLOR_REFS_BACKUP 15
419 struct tog_blame_cb_args {
420 struct tog_blame_line *lines; /* one per line */
421 int nlines;
423 struct tog_view *view;
424 struct got_object_id *commit_id;
425 int *quit;
426 };
428 struct tog_blame_thread_args {
429 const char *path;
430 struct got_repository *repo;
431 struct tog_blame_cb_args *cb_args;
432 int *complete;
433 got_cancel_cb cancel_cb;
434 void *cancel_arg;
435 };
437 struct tog_blame {
438 FILE *f;
439 off_t filesize;
440 struct tog_blame_line *lines;
441 int nlines;
442 off_t *line_offsets;
443 pthread_t thread;
444 struct tog_blame_thread_args thread_args;
445 struct tog_blame_cb_args cb_args;
446 const char *path;
447 int *pack_fds;
448 };
450 struct tog_blame_view_state {
451 int first_displayed_line;
452 int last_displayed_line;
453 int selected_line;
454 int last_diffed_line;
455 int blame_complete;
456 int eof;
457 int done;
458 struct got_object_id_queue blamed_commits;
459 struct got_object_qid *blamed_commit;
460 char *path;
461 struct got_repository *repo;
462 struct got_object_id *commit_id;
463 struct got_object_id *id_to_log;
464 struct tog_blame blame;
465 int matched_line;
466 struct tog_colors colors;
467 };
469 struct tog_parent_tree {
470 TAILQ_ENTRY(tog_parent_tree) entry;
471 struct got_tree_object *tree;
472 struct got_tree_entry *first_displayed_entry;
473 struct got_tree_entry *selected_entry;
474 int selected;
475 };
477 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
479 struct tog_tree_view_state {
480 char *tree_label;
481 struct got_object_id *commit_id;/* commit which this tree belongs to */
482 struct got_tree_object *root; /* the commit's root tree entry */
483 struct got_tree_object *tree; /* currently displayed (sub-)tree */
484 struct got_tree_entry *first_displayed_entry;
485 struct got_tree_entry *last_displayed_entry;
486 struct got_tree_entry *selected_entry;
487 int ndisplayed, selected, show_ids;
488 struct tog_parent_trees parents; /* parent trees of current sub-tree */
489 char *head_ref_name;
490 struct got_repository *repo;
491 struct got_tree_entry *matched_entry;
492 struct tog_colors colors;
493 };
495 struct tog_reflist_entry {
496 TAILQ_ENTRY(tog_reflist_entry) entry;
497 struct got_reference *ref;
498 int idx;
499 };
501 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
503 struct tog_ref_view_state {
504 struct tog_reflist_head refs;
505 struct tog_reflist_entry *first_displayed_entry;
506 struct tog_reflist_entry *last_displayed_entry;
507 struct tog_reflist_entry *selected_entry;
508 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
509 struct got_repository *repo;
510 struct tog_reflist_entry *matched_entry;
511 struct tog_colors colors;
512 };
514 struct tog_help_view_state {
515 FILE *f;
516 off_t *line_offsets;
517 size_t nlines;
518 int lineno;
519 int first_displayed_line;
520 int last_displayed_line;
521 int eof;
522 int matched_line;
523 int selected_line;
524 int all;
525 enum tog_keymap_type type;
526 };
528 #define GENERATE_HELP \
529 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
530 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
531 KEY_("k C-p Up", "Move cursor or page up one line"), \
532 KEY_("j C-n Down", "Move cursor or page down one line"), \
533 KEY_("C-b b PgUp", "Scroll the view up one page"), \
534 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
535 KEY_("C-u u", "Scroll the view up one half page"), \
536 KEY_("C-d d", "Scroll the view down one half page"), \
537 KEY_("g", "Go to line N (default: first line)"), \
538 KEY_("Home =", "Go to the first line"), \
539 KEY_("G", "Go to line N (default: last line)"), \
540 KEY_("End *", "Go to the last line"), \
541 KEY_("l Right", "Scroll the view right"), \
542 KEY_("h Left", "Scroll the view left"), \
543 KEY_("$", "Scroll view to the rightmost position"), \
544 KEY_("0", "Scroll view to the leftmost position"), \
545 KEY_("-", "Decrease size of the focussed split"), \
546 KEY_("+", "Increase size of the focussed split"), \
547 KEY_("Tab", "Switch focus between views"), \
548 KEY_("F", "Toggle fullscreen mode"), \
549 KEY_("/", "Open prompt to enter search term"), \
550 KEY_("n", "Find next line/token matching the current search term"), \
551 KEY_("N", "Find previous line/token matching the current search term"),\
552 KEY_("q", "Quit the focussed view; Quit help screen"), \
553 KEY_("Q", "Quit tog"), \
555 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
556 KEY_("< ,", "Move cursor up one commit"), \
557 KEY_("> .", "Move cursor down one commit"), \
558 KEY_("Enter", "Open diff view of the selected commit"), \
559 KEY_("B", "Reload the log view and toggle display of merged commits"), \
560 KEY_("R", "Open ref view of all repository references"), \
561 KEY_("T", "Display tree view of the repository from the selected" \
562 " commit"), \
563 KEY_("@", "Toggle between displaying author and committer name"), \
564 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
565 KEY_("C-g Backspace", "Cancel current search or log operation"), \
566 KEY_("C-l", "Reload the log view with new commits in the repository"), \
568 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
569 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
570 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
571 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
572 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
573 " data"), \
574 KEY_("(", "Go to the previous file in the diff"), \
575 KEY_(")", "Go to the next file in the diff"), \
576 KEY_("{", "Go to the previous hunk in the diff"), \
577 KEY_("}", "Go to the next hunk in the diff"), \
578 KEY_("[", "Decrease the number of context lines"), \
579 KEY_("]", "Increase the number of context lines"), \
580 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
582 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
583 KEY_("Enter", "Display diff view of the selected line's commit"), \
584 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
585 KEY_("L", "Open log view for the currently selected annotated line"), \
586 KEY_("C", "Reload view with the previously blamed commit"), \
587 KEY_("c", "Reload view with the version of the file found in the" \
588 " selected line's commit"), \
589 KEY_("p", "Reload view with the version of the file found in the" \
590 " selected line's parent commit"), \
592 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
593 KEY_("Enter", "Enter selected directory or open blame view of the" \
594 " selected file"), \
595 KEY_("L", "Open log view for the selected entry"), \
596 KEY_("R", "Open ref view of all repository references"), \
597 KEY_("i", "Show object IDs for all tree entries"), \
598 KEY_("Backspace", "Return to the parent directory"), \
600 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
601 KEY_("Enter", "Display log view of the selected reference"), \
602 KEY_("T", "Display tree view of the selected reference"), \
603 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
604 KEY_("m", "Toggle display of last modified date for each reference"), \
605 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
606 KEY_("C-l", "Reload view with all repository references")
608 struct tog_key_map {
609 const char *keys;
610 const char *info;
611 enum tog_keymap_type type;
612 };
614 /*
615 * We implement two types of views: parent views and child views.
617 * The 'Tab' key switches focus between a parent view and its child view.
618 * Child views are shown side-by-side to their parent view, provided
619 * there is enough screen estate.
621 * When a new view is opened from within a parent view, this new view
622 * becomes a child view of the parent view, replacing any existing child.
624 * When a new view is opened from within a child view, this new view
625 * becomes a parent view which will obscure the views below until the
626 * user quits the new parent view by typing 'q'.
628 * This list of views contains parent views only.
629 * Child views are only pointed to by their parent view.
630 */
631 TAILQ_HEAD(tog_view_list_head, tog_view);
633 struct tog_view {
634 TAILQ_ENTRY(tog_view) entry;
635 WINDOW *window;
636 PANEL *panel;
637 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
638 int resized_y, resized_x; /* begin_y/x based on user resizing */
639 int maxx, x; /* max column and current start column */
640 int lines, cols; /* copies of LINES and COLS */
641 int nscrolled, offset; /* lines scrolled and hsplit line offset */
642 int gline, hiline; /* navigate to and highlight this nG line */
643 int ch, count; /* current keymap and count prefix */
644 int resized; /* set when in a resize event */
645 int focussed; /* Only set on one parent or child view at a time. */
646 int dying;
647 struct tog_view *parent;
648 struct tog_view *child;
650 /*
651 * This flag is initially set on parent views when a new child view
652 * is created. It gets toggled when the 'Tab' key switches focus
653 * between parent and child.
654 * The flag indicates whether focus should be passed on to our child
655 * view if this parent view gets picked for focus after another parent
656 * view was closed. This prevents child views from losing focus in such
657 * situations.
658 */
659 int focus_child;
661 enum tog_view_mode mode;
662 /* type-specific state */
663 enum tog_view_type type;
664 union {
665 struct tog_diff_view_state diff;
666 struct tog_log_view_state log;
667 struct tog_blame_view_state blame;
668 struct tog_tree_view_state tree;
669 struct tog_ref_view_state ref;
670 struct tog_help_view_state help;
671 } state;
673 const struct got_error *(*show)(struct tog_view *);
674 const struct got_error *(*input)(struct tog_view **,
675 struct tog_view *, int);
676 const struct got_error *(*reset)(struct tog_view *);
677 const struct got_error *(*resize)(struct tog_view *, int);
678 const struct got_error *(*close)(struct tog_view *);
680 const struct got_error *(*search_start)(struct tog_view *);
681 const struct got_error *(*search_next)(struct tog_view *);
682 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
683 int **, int **, int **, int **);
684 int search_started;
685 int searching;
686 #define TOG_SEARCH_FORWARD 1
687 #define TOG_SEARCH_BACKWARD 2
688 int search_next_done;
689 #define TOG_SEARCH_HAVE_MORE 1
690 #define TOG_SEARCH_NO_MORE 2
691 #define TOG_SEARCH_HAVE_NONE 3
692 regex_t regex;
693 regmatch_t regmatch;
694 const char *action;
695 };
697 static const struct got_error *open_diff_view(struct tog_view *,
698 struct got_object_id *, struct got_object_id *,
699 const char *, const char *, int, int, int, struct tog_view *,
700 struct got_repository *);
701 static const struct got_error *show_diff_view(struct tog_view *);
702 static const struct got_error *input_diff_view(struct tog_view **,
703 struct tog_view *, int);
704 static const struct got_error *reset_diff_view(struct tog_view *);
705 static const struct got_error* close_diff_view(struct tog_view *);
706 static const struct got_error *search_start_diff_view(struct tog_view *);
707 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
708 size_t *, int **, int **, int **, int **);
709 static const struct got_error *search_next_view_match(struct tog_view *);
711 static const struct got_error *open_log_view(struct tog_view *,
712 struct got_object_id *, struct got_repository *,
713 const char *, const char *, int);
714 static const struct got_error * show_log_view(struct tog_view *);
715 static const struct got_error *input_log_view(struct tog_view **,
716 struct tog_view *, int);
717 static const struct got_error *resize_log_view(struct tog_view *, int);
718 static const struct got_error *close_log_view(struct tog_view *);
719 static const struct got_error *search_start_log_view(struct tog_view *);
720 static const struct got_error *search_next_log_view(struct tog_view *);
722 static const struct got_error *open_blame_view(struct tog_view *, char *,
723 struct got_object_id *, struct got_repository *);
724 static const struct got_error *show_blame_view(struct tog_view *);
725 static const struct got_error *input_blame_view(struct tog_view **,
726 struct tog_view *, int);
727 static const struct got_error *reset_blame_view(struct tog_view *);
728 static const struct got_error *close_blame_view(struct tog_view *);
729 static const struct got_error *search_start_blame_view(struct tog_view *);
730 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
731 size_t *, int **, int **, int **, int **);
733 static const struct got_error *open_tree_view(struct tog_view *,
734 struct got_object_id *, const char *, struct got_repository *);
735 static const struct got_error *show_tree_view(struct tog_view *);
736 static const struct got_error *input_tree_view(struct tog_view **,
737 struct tog_view *, int);
738 static const struct got_error *close_tree_view(struct tog_view *);
739 static const struct got_error *search_start_tree_view(struct tog_view *);
740 static const struct got_error *search_next_tree_view(struct tog_view *);
742 static const struct got_error *open_ref_view(struct tog_view *,
743 struct got_repository *);
744 static const struct got_error *show_ref_view(struct tog_view *);
745 static const struct got_error *input_ref_view(struct tog_view **,
746 struct tog_view *, int);
747 static const struct got_error *close_ref_view(struct tog_view *);
748 static const struct got_error *search_start_ref_view(struct tog_view *);
749 static const struct got_error *search_next_ref_view(struct tog_view *);
751 static const struct got_error *open_help_view(struct tog_view *,
752 struct tog_view *);
753 static const struct got_error *show_help_view(struct tog_view *);
754 static const struct got_error *input_help_view(struct tog_view **,
755 struct tog_view *, int);
756 static const struct got_error *reset_help_view(struct tog_view *);
757 static const struct got_error* close_help_view(struct tog_view *);
758 static const struct got_error *search_start_help_view(struct tog_view *);
759 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
760 size_t *, int **, int **, int **, int **);
762 static volatile sig_atomic_t tog_sigwinch_received;
763 static volatile sig_atomic_t tog_sigpipe_received;
764 static volatile sig_atomic_t tog_sigcont_received;
765 static volatile sig_atomic_t tog_sigint_received;
766 static volatile sig_atomic_t tog_sigterm_received;
768 static void
769 tog_sigwinch(int signo)
771 tog_sigwinch_received = 1;
774 static void
775 tog_sigpipe(int signo)
777 tog_sigpipe_received = 1;
780 static void
781 tog_sigcont(int signo)
783 tog_sigcont_received = 1;
786 static void
787 tog_sigint(int signo)
789 tog_sigint_received = 1;
792 static void
793 tog_sigterm(int signo)
795 tog_sigterm_received = 1;
798 static int
799 tog_fatal_signal_received(void)
801 return (tog_sigpipe_received ||
802 tog_sigint_received || tog_sigterm_received);
805 static const struct got_error *
806 view_close(struct tog_view *view)
808 const struct got_error *err = NULL, *child_err = NULL;
810 if (view->child) {
811 child_err = view_close(view->child);
812 view->child = NULL;
814 if (view->close)
815 err = view->close(view);
816 if (view->panel)
817 del_panel(view->panel);
818 if (view->window)
819 delwin(view->window);
820 free(view);
821 return err ? err : child_err;
824 static struct tog_view *
825 view_open(int nlines, int ncols, int begin_y, int begin_x,
826 enum tog_view_type type)
828 struct tog_view *view = calloc(1, sizeof(*view));
830 if (view == NULL)
831 return NULL;
833 view->type = type;
834 view->lines = LINES;
835 view->cols = COLS;
836 view->nlines = nlines ? nlines : LINES - begin_y;
837 view->ncols = ncols ? ncols : COLS - begin_x;
838 view->begin_y = begin_y;
839 view->begin_x = begin_x;
840 view->window = newwin(nlines, ncols, begin_y, begin_x);
841 if (view->window == NULL) {
842 view_close(view);
843 return NULL;
845 view->panel = new_panel(view->window);
846 if (view->panel == NULL ||
847 set_panel_userptr(view->panel, view) != OK) {
848 view_close(view);
849 return NULL;
852 keypad(view->window, TRUE);
853 return view;
856 static int
857 view_split_begin_x(int begin_x)
859 if (begin_x > 0 || COLS < 120)
860 return 0;
861 return (COLS - MAX(COLS / 2, 80));
864 /* XXX Stub till we decide what to do. */
865 static int
866 view_split_begin_y(int lines)
868 return lines * HSPLIT_SCALE;
871 static const struct got_error *view_resize(struct tog_view *);
873 static const struct got_error *
874 view_splitscreen(struct tog_view *view)
876 const struct got_error *err = NULL;
878 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
879 if (view->resized_y && view->resized_y < view->lines)
880 view->begin_y = view->resized_y;
881 else
882 view->begin_y = view_split_begin_y(view->nlines);
883 view->begin_x = 0;
884 } else if (!view->resized) {
885 if (view->resized_x && view->resized_x < view->cols - 1 &&
886 view->cols > 119)
887 view->begin_x = view->resized_x;
888 else
889 view->begin_x = view_split_begin_x(0);
890 view->begin_y = 0;
892 view->nlines = LINES - view->begin_y;
893 view->ncols = COLS - view->begin_x;
894 view->lines = LINES;
895 view->cols = COLS;
896 err = view_resize(view);
897 if (err)
898 return err;
900 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
901 view->parent->nlines = view->begin_y;
903 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
904 return got_error_from_errno("mvwin");
906 return NULL;
909 static const struct got_error *
910 view_fullscreen(struct tog_view *view)
912 const struct got_error *err = NULL;
914 view->begin_x = 0;
915 view->begin_y = view->resized ? view->begin_y : 0;
916 view->nlines = view->resized ? view->nlines : LINES;
917 view->ncols = COLS;
918 view->lines = LINES;
919 view->cols = COLS;
920 err = view_resize(view);
921 if (err)
922 return err;
924 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
925 return got_error_from_errno("mvwin");
927 return NULL;
930 static int
931 view_is_parent_view(struct tog_view *view)
933 return view->parent == NULL;
936 static int
937 view_is_splitscreen(struct tog_view *view)
939 return view->begin_x > 0 || view->begin_y > 0;
942 static int
943 view_is_fullscreen(struct tog_view *view)
945 return view->nlines == LINES && view->ncols == COLS;
948 static int
949 view_is_hsplit_top(struct tog_view *view)
951 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
952 view_is_splitscreen(view->child);
955 static void
956 view_border(struct tog_view *view)
958 PANEL *panel;
959 const struct tog_view *view_above;
961 if (view->parent)
962 return view_border(view->parent);
964 panel = panel_above(view->panel);
965 if (panel == NULL)
966 return;
968 view_above = panel_userptr(panel);
969 if (view->mode == TOG_VIEW_SPLIT_HRZN)
970 mvwhline(view->window, view_above->begin_y - 1,
971 view->begin_x, got_locale_is_utf8() ?
972 ACS_HLINE : '-', view->ncols);
973 else
974 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
975 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
978 static const struct got_error *view_init_hsplit(struct tog_view *, int);
979 static const struct got_error *request_log_commits(struct tog_view *);
980 static const struct got_error *offset_selection_down(struct tog_view *);
981 static void offset_selection_up(struct tog_view *);
982 static void view_get_split(struct tog_view *, int *, int *);
984 static const struct got_error *
985 view_resize(struct tog_view *view)
987 const struct got_error *err = NULL;
988 int dif, nlines, ncols;
990 dif = LINES - view->lines; /* line difference */
992 if (view->lines > LINES)
993 nlines = view->nlines - (view->lines - LINES);
994 else
995 nlines = view->nlines + (LINES - view->lines);
996 if (view->cols > COLS)
997 ncols = view->ncols - (view->cols - COLS);
998 else
999 ncols = view->ncols + (COLS - view->cols);
1001 if (view->child) {
1002 int hs = view->child->begin_y;
1004 if (!view_is_fullscreen(view))
1005 view->child->begin_x = view_split_begin_x(view->begin_x);
1006 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1007 view->child->begin_x == 0) {
1008 ncols = COLS;
1010 view_fullscreen(view->child);
1011 if (view->child->focussed)
1012 show_panel(view->child->panel);
1013 else
1014 show_panel(view->panel);
1015 } else {
1016 ncols = view->child->begin_x;
1018 view_splitscreen(view->child);
1019 show_panel(view->child->panel);
1022 * XXX This is ugly and needs to be moved into the above
1023 * logic but "works" for now and my attempts at moving it
1024 * break either 'tab' or 'F' key maps in horizontal splits.
1026 if (hs) {
1027 err = view_splitscreen(view->child);
1028 if (err)
1029 return err;
1030 if (dif < 0) { /* top split decreased */
1031 err = offset_selection_down(view);
1032 if (err)
1033 return err;
1035 view_border(view);
1036 update_panels();
1037 doupdate();
1038 show_panel(view->child->panel);
1039 nlines = view->nlines;
1041 } else if (view->parent == NULL)
1042 ncols = COLS;
1044 if (view->resize && dif > 0) {
1045 err = view->resize(view, dif);
1046 if (err)
1047 return err;
1050 if (wresize(view->window, nlines, ncols) == ERR)
1051 return got_error_from_errno("wresize");
1052 if (replace_panel(view->panel, view->window) == ERR)
1053 return got_error_from_errno("replace_panel");
1054 wclear(view->window);
1056 view->nlines = nlines;
1057 view->ncols = ncols;
1058 view->lines = LINES;
1059 view->cols = COLS;
1061 return NULL;
1064 static const struct got_error *
1065 resize_log_view(struct tog_view *view, int increase)
1067 struct tog_log_view_state *s = &view->state.log;
1068 const struct got_error *err = NULL;
1069 int n = 0;
1071 if (s->selected_entry)
1072 n = s->selected_entry->idx + view->lines - s->selected;
1075 * Request commits to account for the increased
1076 * height so we have enough to populate the view.
1078 if (s->commits->ncommits < n) {
1079 view->nscrolled = n - s->commits->ncommits + increase + 1;
1080 err = request_log_commits(view);
1083 return err;
1086 static void
1087 view_adjust_offset(struct tog_view *view, int n)
1089 if (n == 0)
1090 return;
1092 if (view->parent && view->parent->offset) {
1093 if (view->parent->offset + n >= 0)
1094 view->parent->offset += n;
1095 else
1096 view->parent->offset = 0;
1097 } else if (view->offset) {
1098 if (view->offset - n >= 0)
1099 view->offset -= n;
1100 else
1101 view->offset = 0;
1105 static const struct got_error *
1106 view_resize_split(struct tog_view *view, int resize)
1108 const struct got_error *err = NULL;
1109 struct tog_view *v = NULL;
1111 if (view->parent)
1112 v = view->parent;
1113 else
1114 v = view;
1116 if (!v->child || !view_is_splitscreen(v->child))
1117 return NULL;
1119 v->resized = v->child->resized = resize; /* lock for resize event */
1121 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1122 if (v->child->resized_y)
1123 v->child->begin_y = v->child->resized_y;
1124 if (view->parent)
1125 v->child->begin_y -= resize;
1126 else
1127 v->child->begin_y += resize;
1128 if (v->child->begin_y < 3) {
1129 view->count = 0;
1130 v->child->begin_y = 3;
1131 } else if (v->child->begin_y > LINES - 1) {
1132 view->count = 0;
1133 v->child->begin_y = LINES - 1;
1135 v->ncols = COLS;
1136 v->child->ncols = COLS;
1137 view_adjust_offset(view, resize);
1138 err = view_init_hsplit(v, v->child->begin_y);
1139 if (err)
1140 return err;
1141 v->child->resized_y = v->child->begin_y;
1142 } else {
1143 if (v->child->resized_x)
1144 v->child->begin_x = v->child->resized_x;
1145 if (view->parent)
1146 v->child->begin_x -= resize;
1147 else
1148 v->child->begin_x += resize;
1149 if (v->child->begin_x < 11) {
1150 view->count = 0;
1151 v->child->begin_x = 11;
1152 } else if (v->child->begin_x > COLS - 1) {
1153 view->count = 0;
1154 v->child->begin_x = COLS - 1;
1156 v->child->resized_x = v->child->begin_x;
1159 v->child->mode = v->mode;
1160 v->child->nlines = v->lines - v->child->begin_y;
1161 v->child->ncols = v->cols - v->child->begin_x;
1162 v->focus_child = 1;
1164 err = view_fullscreen(v);
1165 if (err)
1166 return err;
1167 err = view_splitscreen(v->child);
1168 if (err)
1169 return err;
1171 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1172 err = offset_selection_down(v->child);
1173 if (err)
1174 return err;
1177 if (v->resize)
1178 err = v->resize(v, 0);
1179 else if (v->child->resize)
1180 err = v->child->resize(v->child, 0);
1182 v->resized = v->child->resized = 0;
1184 return err;
1187 static void
1188 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1190 struct tog_view *v = src->child ? src->child : src;
1192 dst->resized_x = v->resized_x;
1193 dst->resized_y = v->resized_y;
1196 static const struct got_error *
1197 view_close_child(struct tog_view *view)
1199 const struct got_error *err = NULL;
1201 if (view->child == NULL)
1202 return NULL;
1204 err = view_close(view->child);
1205 view->child = NULL;
1206 return err;
1209 static const struct got_error *
1210 view_set_child(struct tog_view *view, struct tog_view *child)
1212 const struct got_error *err = NULL;
1214 view->child = child;
1215 child->parent = view;
1217 err = view_resize(view);
1218 if (err)
1219 return err;
1221 if (view->child->resized_x || view->child->resized_y)
1222 err = view_resize_split(view, 0);
1224 return err;
1227 static const struct got_error *view_dispatch_request(struct tog_view **,
1228 struct tog_view *, enum tog_view_type, int, int);
1230 static const struct got_error *
1231 view_request_new(struct tog_view **requested, struct tog_view *view,
1232 enum tog_view_type request)
1234 struct tog_view *new_view = NULL;
1235 const struct got_error *err;
1236 int y = 0, x = 0;
1238 *requested = NULL;
1240 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1241 view_get_split(view, &y, &x);
1243 err = view_dispatch_request(&new_view, view, request, y, x);
1244 if (err)
1245 return err;
1247 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1248 request != TOG_VIEW_HELP) {
1249 err = view_init_hsplit(view, y);
1250 if (err)
1251 return err;
1254 view->focussed = 0;
1255 new_view->focussed = 1;
1256 new_view->mode = view->mode;
1257 new_view->nlines = request == TOG_VIEW_HELP ?
1258 view->lines : view->lines - y;
1260 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1261 view_transfer_size(new_view, view);
1262 err = view_close_child(view);
1263 if (err)
1264 return err;
1265 err = view_set_child(view, new_view);
1266 if (err)
1267 return err;
1268 view->focus_child = 1;
1269 } else
1270 *requested = new_view;
1272 return NULL;
1275 static void
1276 tog_resizeterm(void)
1278 int cols, lines;
1279 struct winsize size;
1281 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1282 cols = 80; /* Default */
1283 lines = 24;
1284 } else {
1285 cols = size.ws_col;
1286 lines = size.ws_row;
1288 resize_term(lines, cols);
1291 static const struct got_error *
1292 view_search_start(struct tog_view *view, int fast_refresh)
1294 const struct got_error *err = NULL;
1295 struct tog_view *v = view;
1296 char pattern[1024];
1297 int ret;
1299 if (view->search_started) {
1300 regfree(&view->regex);
1301 view->searching = 0;
1302 memset(&view->regmatch, 0, sizeof(view->regmatch));
1304 view->search_started = 0;
1306 if (view->nlines < 1)
1307 return NULL;
1309 if (view_is_hsplit_top(view))
1310 v = view->child;
1311 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1312 v = view->parent;
1314 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1315 wclrtoeol(v->window);
1317 nodelay(v->window, FALSE); /* block for search term input */
1318 nocbreak();
1319 echo();
1320 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1321 wrefresh(v->window);
1322 cbreak();
1323 noecho();
1324 nodelay(v->window, TRUE);
1325 if (!fast_refresh)
1326 halfdelay(10);
1327 if (ret == ERR)
1328 return NULL;
1330 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1331 err = view->search_start(view);
1332 if (err) {
1333 regfree(&view->regex);
1334 return err;
1336 view->search_started = 1;
1337 view->searching = TOG_SEARCH_FORWARD;
1338 view->search_next_done = 0;
1339 view->search_next(view);
1342 return NULL;
1345 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1346 static const struct got_error *
1347 switch_split(struct tog_view *view)
1349 const struct got_error *err = NULL;
1350 struct tog_view *v = NULL;
1352 if (view->parent)
1353 v = view->parent;
1354 else
1355 v = view;
1357 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1358 v->mode = TOG_VIEW_SPLIT_VERT;
1359 else
1360 v->mode = TOG_VIEW_SPLIT_HRZN;
1362 if (!v->child)
1363 return NULL;
1364 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1365 v->mode = TOG_VIEW_SPLIT_NONE;
1367 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1368 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1369 v->child->begin_y = v->child->resized_y;
1370 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1371 v->child->begin_x = v->child->resized_x;
1374 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1375 v->ncols = COLS;
1376 v->child->ncols = COLS;
1377 v->child->nscrolled = LINES - v->child->nlines;
1379 err = view_init_hsplit(v, v->child->begin_y);
1380 if (err)
1381 return err;
1383 v->child->mode = v->mode;
1384 v->child->nlines = v->lines - v->child->begin_y;
1385 v->focus_child = 1;
1387 err = view_fullscreen(v);
1388 if (err)
1389 return err;
1390 err = view_splitscreen(v->child);
1391 if (err)
1392 return err;
1394 if (v->mode == TOG_VIEW_SPLIT_NONE)
1395 v->mode = TOG_VIEW_SPLIT_VERT;
1396 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1397 err = offset_selection_down(v);
1398 if (err)
1399 return err;
1400 err = offset_selection_down(v->child);
1401 if (err)
1402 return err;
1403 } else {
1404 offset_selection_up(v);
1405 offset_selection_up(v->child);
1407 if (v->resize)
1408 err = v->resize(v, 0);
1409 else if (v->child->resize)
1410 err = v->child->resize(v->child, 0);
1412 return err;
1416 * Compute view->count from numeric input. Assign total to view->count and
1417 * return first non-numeric key entered.
1419 static int
1420 get_compound_key(struct tog_view *view, int c)
1422 struct tog_view *v = view;
1423 int x, n = 0;
1425 if (view_is_hsplit_top(view))
1426 v = view->child;
1427 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1428 v = view->parent;
1430 view->count = 0;
1431 cbreak(); /* block for input */
1432 nodelay(view->window, FALSE);
1433 wmove(v->window, v->nlines - 1, 0);
1434 wclrtoeol(v->window);
1435 waddch(v->window, ':');
1437 do {
1438 x = getcurx(v->window);
1439 if (x != ERR && x < view->ncols) {
1440 waddch(v->window, c);
1441 wrefresh(v->window);
1445 * Don't overflow. Max valid request should be the greatest
1446 * between the longest and total lines; cap at 10 million.
1448 if (n >= 9999999)
1449 n = 9999999;
1450 else
1451 n = n * 10 + (c - '0');
1452 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1454 if (c == 'G' || c == 'g') { /* nG key map */
1455 view->gline = view->hiline = n;
1456 n = 0;
1457 c = 0;
1460 /* Massage excessive or inapplicable values at the input handler. */
1461 view->count = n;
1463 return c;
1466 static void
1467 action_report(struct tog_view *view)
1469 struct tog_view *v = view;
1471 if (view_is_hsplit_top(view))
1472 v = view->child;
1473 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1474 v = view->parent;
1476 wmove(v->window, v->nlines - 1, 0);
1477 wclrtoeol(v->window);
1478 wprintw(v->window, ":%s", view->action);
1479 wrefresh(v->window);
1482 * Clear action status report. Only clear in blame view
1483 * once annotating is complete, otherwise it's too fast.
1485 if (view->type == TOG_VIEW_BLAME) {
1486 if (view->state.blame.blame_complete)
1487 view->action = NULL;
1488 } else
1489 view->action = NULL;
1492 static const struct got_error *
1493 view_input(struct tog_view **new, int *done, struct tog_view *view,
1494 struct tog_view_list_head *views, int fast_refresh)
1496 const struct got_error *err = NULL;
1497 struct tog_view *v;
1498 int ch, errcode;
1500 *new = NULL;
1502 if (view->action)
1503 action_report(view);
1505 /* Clear "no matches" indicator. */
1506 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1507 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1508 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1509 view->count = 0;
1512 if (view->searching && !view->search_next_done) {
1513 errcode = pthread_mutex_unlock(&tog_mutex);
1514 if (errcode)
1515 return got_error_set_errno(errcode,
1516 "pthread_mutex_unlock");
1517 sched_yield();
1518 errcode = pthread_mutex_lock(&tog_mutex);
1519 if (errcode)
1520 return got_error_set_errno(errcode,
1521 "pthread_mutex_lock");
1522 view->search_next(view);
1523 return NULL;
1526 /* Allow threads to make progress while we are waiting for input. */
1527 errcode = pthread_mutex_unlock(&tog_mutex);
1528 if (errcode)
1529 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1530 /* If we have an unfinished count, let C-g or backspace abort. */
1531 if (view->count && --view->count) {
1532 cbreak();
1533 nodelay(view->window, TRUE);
1534 ch = wgetch(view->window);
1535 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1536 view->count = 0;
1537 else
1538 ch = view->ch;
1539 } else {
1540 ch = wgetch(view->window);
1541 if (ch >= '1' && ch <= '9')
1542 view->ch = ch = get_compound_key(view, ch);
1544 if (view->hiline && ch != ERR && ch != 0)
1545 view->hiline = 0; /* key pressed, clear line highlight */
1546 nodelay(view->window, TRUE);
1547 errcode = pthread_mutex_lock(&tog_mutex);
1548 if (errcode)
1549 return got_error_set_errno(errcode, "pthread_mutex_lock");
1551 if (tog_sigwinch_received || tog_sigcont_received) {
1552 tog_resizeterm();
1553 tog_sigwinch_received = 0;
1554 tog_sigcont_received = 0;
1555 TAILQ_FOREACH(v, views, entry) {
1556 err = view_resize(v);
1557 if (err)
1558 return err;
1559 err = v->input(new, v, KEY_RESIZE);
1560 if (err)
1561 return err;
1562 if (v->child) {
1563 err = view_resize(v->child);
1564 if (err)
1565 return err;
1566 err = v->child->input(new, v->child,
1567 KEY_RESIZE);
1568 if (err)
1569 return err;
1570 if (v->child->resized_x || v->child->resized_y) {
1571 err = view_resize_split(v, 0);
1572 if (err)
1573 return err;
1579 switch (ch) {
1580 case '?':
1581 case 'H':
1582 case KEY_F(1):
1583 if (view->type == TOG_VIEW_HELP)
1584 err = view->reset(view);
1585 else
1586 err = view_request_new(new, view, TOG_VIEW_HELP);
1587 break;
1588 case '\t':
1589 view->count = 0;
1590 if (view->child) {
1591 view->focussed = 0;
1592 view->child->focussed = 1;
1593 view->focus_child = 1;
1594 } else if (view->parent) {
1595 view->focussed = 0;
1596 view->parent->focussed = 1;
1597 view->parent->focus_child = 0;
1598 if (!view_is_splitscreen(view)) {
1599 if (view->parent->resize) {
1600 err = view->parent->resize(view->parent,
1601 0);
1602 if (err)
1603 return err;
1605 offset_selection_up(view->parent);
1606 err = view_fullscreen(view->parent);
1607 if (err)
1608 return err;
1611 break;
1612 case 'q':
1613 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1614 if (view->parent->resize) {
1615 /* might need more commits to fill fullscreen */
1616 err = view->parent->resize(view->parent, 0);
1617 if (err)
1618 break;
1620 offset_selection_up(view->parent);
1622 err = view->input(new, view, ch);
1623 view->dying = 1;
1624 break;
1625 case 'Q':
1626 *done = 1;
1627 break;
1628 case 'F':
1629 view->count = 0;
1630 if (view_is_parent_view(view)) {
1631 if (view->child == NULL)
1632 break;
1633 if (view_is_splitscreen(view->child)) {
1634 view->focussed = 0;
1635 view->child->focussed = 1;
1636 err = view_fullscreen(view->child);
1637 } else {
1638 err = view_splitscreen(view->child);
1639 if (!err)
1640 err = view_resize_split(view, 0);
1642 if (err)
1643 break;
1644 err = view->child->input(new, view->child,
1645 KEY_RESIZE);
1646 } else {
1647 if (view_is_splitscreen(view)) {
1648 view->parent->focussed = 0;
1649 view->focussed = 1;
1650 err = view_fullscreen(view);
1651 } else {
1652 err = view_splitscreen(view);
1653 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1654 err = view_resize(view->parent);
1655 if (!err)
1656 err = view_resize_split(view, 0);
1658 if (err)
1659 break;
1660 err = view->input(new, view, KEY_RESIZE);
1662 if (err)
1663 break;
1664 if (view->resize) {
1665 err = view->resize(view, 0);
1666 if (err)
1667 break;
1669 if (view->parent)
1670 err = offset_selection_down(view->parent);
1671 if (!err)
1672 err = offset_selection_down(view);
1673 break;
1674 case 'S':
1675 view->count = 0;
1676 err = switch_split(view);
1677 break;
1678 case '-':
1679 err = view_resize_split(view, -1);
1680 break;
1681 case '+':
1682 err = view_resize_split(view, 1);
1683 break;
1684 case KEY_RESIZE:
1685 break;
1686 case '/':
1687 view->count = 0;
1688 if (view->search_start)
1689 view_search_start(view, fast_refresh);
1690 else
1691 err = view->input(new, view, ch);
1692 break;
1693 case 'N':
1694 case 'n':
1695 if (view->search_started && view->search_next) {
1696 view->searching = (ch == 'n' ?
1697 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1698 view->search_next_done = 0;
1699 view->search_next(view);
1700 } else
1701 err = view->input(new, view, ch);
1702 break;
1703 case 'A':
1704 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1705 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1706 view->action = "Patience diff algorithm";
1707 } else {
1708 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1709 view->action = "Myers diff algorithm";
1711 TAILQ_FOREACH(v, views, entry) {
1712 if (v->reset) {
1713 err = v->reset(v);
1714 if (err)
1715 return err;
1717 if (v->child && v->child->reset) {
1718 err = v->child->reset(v->child);
1719 if (err)
1720 return err;
1723 break;
1724 default:
1725 err = view->input(new, view, ch);
1726 break;
1729 return err;
1732 static int
1733 view_needs_focus_indication(struct tog_view *view)
1735 if (view_is_parent_view(view)) {
1736 if (view->child == NULL || view->child->focussed)
1737 return 0;
1738 if (!view_is_splitscreen(view->child))
1739 return 0;
1740 } else if (!view_is_splitscreen(view))
1741 return 0;
1743 return view->focussed;
1746 static const struct got_error *
1747 view_loop(struct tog_view *view)
1749 const struct got_error *err = NULL;
1750 struct tog_view_list_head views;
1751 struct tog_view *new_view;
1752 char *mode;
1753 int fast_refresh = 10;
1754 int done = 0, errcode;
1756 mode = getenv("TOG_VIEW_SPLIT_MODE");
1757 if (!mode || !(*mode == 'h' || *mode == 'H'))
1758 view->mode = TOG_VIEW_SPLIT_VERT;
1759 else
1760 view->mode = TOG_VIEW_SPLIT_HRZN;
1762 errcode = pthread_mutex_lock(&tog_mutex);
1763 if (errcode)
1764 return got_error_set_errno(errcode, "pthread_mutex_lock");
1766 TAILQ_INIT(&views);
1767 TAILQ_INSERT_HEAD(&views, view, entry);
1769 view->focussed = 1;
1770 err = view->show(view);
1771 if (err)
1772 return err;
1773 update_panels();
1774 doupdate();
1775 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1776 !tog_fatal_signal_received()) {
1777 /* Refresh fast during initialization, then become slower. */
1778 if (fast_refresh && --fast_refresh == 0)
1779 halfdelay(10); /* switch to once per second */
1781 err = view_input(&new_view, &done, view, &views, fast_refresh);
1782 if (err)
1783 break;
1785 if (view->dying && view == TAILQ_FIRST(&views) &&
1786 TAILQ_NEXT(view, entry) == NULL)
1787 done = 1;
1788 if (done) {
1789 struct tog_view *v;
1792 * When we quit, scroll the screen up a single line
1793 * so we don't lose any information.
1795 TAILQ_FOREACH(v, &views, entry) {
1796 wmove(v->window, 0, 0);
1797 wdeleteln(v->window);
1798 wnoutrefresh(v->window);
1799 if (v->child && !view_is_fullscreen(v)) {
1800 wmove(v->child->window, 0, 0);
1801 wdeleteln(v->child->window);
1802 wnoutrefresh(v->child->window);
1805 doupdate();
1808 if (view->dying) {
1809 struct tog_view *v, *prev = NULL;
1811 if (view_is_parent_view(view))
1812 prev = TAILQ_PREV(view, tog_view_list_head,
1813 entry);
1814 else if (view->parent)
1815 prev = view->parent;
1817 if (view->parent) {
1818 view->parent->child = NULL;
1819 view->parent->focus_child = 0;
1820 /* Restore fullscreen line height. */
1821 view->parent->nlines = view->parent->lines;
1822 err = view_resize(view->parent);
1823 if (err)
1824 break;
1825 /* Make resized splits persist. */
1826 view_transfer_size(view->parent, view);
1827 } else
1828 TAILQ_REMOVE(&views, view, entry);
1830 err = view_close(view);
1831 if (err)
1832 goto done;
1834 view = NULL;
1835 TAILQ_FOREACH(v, &views, entry) {
1836 if (v->focussed)
1837 break;
1839 if (view == NULL && new_view == NULL) {
1840 /* No view has focus. Try to pick one. */
1841 if (prev)
1842 view = prev;
1843 else if (!TAILQ_EMPTY(&views)) {
1844 view = TAILQ_LAST(&views,
1845 tog_view_list_head);
1847 if (view) {
1848 if (view->focus_child) {
1849 view->child->focussed = 1;
1850 view = view->child;
1851 } else
1852 view->focussed = 1;
1856 if (new_view) {
1857 struct tog_view *v, *t;
1858 /* Only allow one parent view per type. */
1859 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1860 if (v->type != new_view->type)
1861 continue;
1862 TAILQ_REMOVE(&views, v, entry);
1863 err = view_close(v);
1864 if (err)
1865 goto done;
1866 break;
1868 TAILQ_INSERT_TAIL(&views, new_view, entry);
1869 view = new_view;
1871 if (view && !done) {
1872 if (view_is_parent_view(view)) {
1873 if (view->child && view->child->focussed)
1874 view = view->child;
1875 } else {
1876 if (view->parent && view->parent->focussed)
1877 view = view->parent;
1879 show_panel(view->panel);
1880 if (view->child && view_is_splitscreen(view->child))
1881 show_panel(view->child->panel);
1882 if (view->parent && view_is_splitscreen(view)) {
1883 err = view->parent->show(view->parent);
1884 if (err)
1885 goto done;
1887 err = view->show(view);
1888 if (err)
1889 goto done;
1890 if (view->child) {
1891 err = view->child->show(view->child);
1892 if (err)
1893 goto done;
1895 update_panels();
1896 doupdate();
1899 done:
1900 while (!TAILQ_EMPTY(&views)) {
1901 const struct got_error *close_err;
1902 view = TAILQ_FIRST(&views);
1903 TAILQ_REMOVE(&views, view, entry);
1904 close_err = view_close(view);
1905 if (close_err && err == NULL)
1906 err = close_err;
1909 errcode = pthread_mutex_unlock(&tog_mutex);
1910 if (errcode && err == NULL)
1911 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1913 return err;
1916 __dead static void
1917 usage_log(void)
1919 endwin();
1920 fprintf(stderr,
1921 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1922 getprogname());
1923 exit(1);
1926 /* Create newly allocated wide-character string equivalent to a byte string. */
1927 static const struct got_error *
1928 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1930 char *vis = NULL;
1931 const struct got_error *err = NULL;
1933 *ws = NULL;
1934 *wlen = mbstowcs(NULL, s, 0);
1935 if (*wlen == (size_t)-1) {
1936 int vislen;
1937 if (errno != EILSEQ)
1938 return got_error_from_errno("mbstowcs");
1940 /* byte string invalid in current encoding; try to "fix" it */
1941 err = got_mbsavis(&vis, &vislen, s);
1942 if (err)
1943 return err;
1944 *wlen = mbstowcs(NULL, vis, 0);
1945 if (*wlen == (size_t)-1) {
1946 err = got_error_from_errno("mbstowcs"); /* give up */
1947 goto done;
1951 *ws = calloc(*wlen + 1, sizeof(**ws));
1952 if (*ws == NULL) {
1953 err = got_error_from_errno("calloc");
1954 goto done;
1957 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1958 err = got_error_from_errno("mbstowcs");
1959 done:
1960 free(vis);
1961 if (err) {
1962 free(*ws);
1963 *ws = NULL;
1964 *wlen = 0;
1966 return err;
1969 static const struct got_error *
1970 expand_tab(char **ptr, const char *src)
1972 char *dst;
1973 size_t len, n, idx = 0, sz = 0;
1975 *ptr = NULL;
1976 n = len = strlen(src);
1977 dst = malloc(n + 1);
1978 if (dst == NULL)
1979 return got_error_from_errno("malloc");
1981 while (idx < len && src[idx]) {
1982 const char c = src[idx];
1984 if (c == '\t') {
1985 size_t nb = TABSIZE - sz % TABSIZE;
1986 char *p;
1988 p = realloc(dst, n + nb);
1989 if (p == NULL) {
1990 free(dst);
1991 return got_error_from_errno("realloc");
1994 dst = p;
1995 n += nb;
1996 memset(dst + sz, ' ', nb);
1997 sz += nb;
1998 } else
1999 dst[sz++] = src[idx];
2000 ++idx;
2003 dst[sz] = '\0';
2004 *ptr = dst;
2005 return NULL;
2009 * Advance at most n columns from wline starting at offset off.
2010 * Return the index to the first character after the span operation.
2011 * Return the combined column width of all spanned wide character in
2012 * *rcol.
2014 static int
2015 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2017 int width, i, cols = 0;
2019 if (n == 0) {
2020 *rcol = cols;
2021 return off;
2024 for (i = off; wline[i] != L'\0'; ++i) {
2025 if (wline[i] == L'\t')
2026 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2027 else
2028 width = wcwidth(wline[i]);
2030 if (width == -1) {
2031 width = 1;
2032 wline[i] = L'.';
2035 if (cols + width > n)
2036 break;
2037 cols += width;
2040 *rcol = cols;
2041 return i;
2045 * Format a line for display, ensuring that it won't overflow a width limit.
2046 * With scrolling, the width returned refers to the scrolled version of the
2047 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2049 static const struct got_error *
2050 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2051 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2053 const struct got_error *err = NULL;
2054 int cols;
2055 wchar_t *wline = NULL;
2056 char *exstr = NULL;
2057 size_t wlen;
2058 int i, scrollx;
2060 *wlinep = NULL;
2061 *widthp = 0;
2063 if (expand) {
2064 err = expand_tab(&exstr, line);
2065 if (err)
2066 return err;
2069 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2070 free(exstr);
2071 if (err)
2072 return err;
2074 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2076 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2077 wline[wlen - 1] = L'\0';
2078 wlen--;
2080 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2081 wline[wlen - 1] = L'\0';
2082 wlen--;
2085 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2086 wline[i] = L'\0';
2088 if (widthp)
2089 *widthp = cols;
2090 if (scrollxp)
2091 *scrollxp = scrollx;
2092 if (err)
2093 free(wline);
2094 else
2095 *wlinep = wline;
2096 return err;
2099 static const struct got_error*
2100 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2101 struct got_object_id *id, struct got_repository *repo)
2103 static const struct got_error *err = NULL;
2104 struct got_reflist_entry *re;
2105 char *s;
2106 const char *name;
2108 *refs_str = NULL;
2110 TAILQ_FOREACH(re, refs, entry) {
2111 struct got_tag_object *tag = NULL;
2112 struct got_object_id *ref_id;
2113 int cmp;
2115 name = got_ref_get_name(re->ref);
2116 if (strcmp(name, GOT_REF_HEAD) == 0)
2117 continue;
2118 if (strncmp(name, "refs/", 5) == 0)
2119 name += 5;
2120 if (strncmp(name, "got/", 4) == 0 &&
2121 strncmp(name, "got/backup/", 11) != 0)
2122 continue;
2123 if (strncmp(name, "heads/", 6) == 0)
2124 name += 6;
2125 if (strncmp(name, "remotes/", 8) == 0) {
2126 name += 8;
2127 s = strstr(name, "/" GOT_REF_HEAD);
2128 if (s != NULL && s[strlen(s)] == '\0')
2129 continue;
2131 err = got_ref_resolve(&ref_id, repo, re->ref);
2132 if (err)
2133 break;
2134 if (strncmp(name, "tags/", 5) == 0) {
2135 err = got_object_open_as_tag(&tag, repo, ref_id);
2136 if (err) {
2137 if (err->code != GOT_ERR_OBJ_TYPE) {
2138 free(ref_id);
2139 break;
2141 /* Ref points at something other than a tag. */
2142 err = NULL;
2143 tag = NULL;
2146 cmp = got_object_id_cmp(tag ?
2147 got_object_tag_get_object_id(tag) : ref_id, id);
2148 free(ref_id);
2149 if (tag)
2150 got_object_tag_close(tag);
2151 if (cmp != 0)
2152 continue;
2153 s = *refs_str;
2154 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2155 s ? ", " : "", name) == -1) {
2156 err = got_error_from_errno("asprintf");
2157 free(s);
2158 *refs_str = NULL;
2159 break;
2161 free(s);
2164 return err;
2167 static const struct got_error *
2168 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2169 int col_tab_align)
2171 char *smallerthan;
2173 smallerthan = strchr(author, '<');
2174 if (smallerthan && smallerthan[1] != '\0')
2175 author = smallerthan + 1;
2176 author[strcspn(author, "@>")] = '\0';
2177 return format_line(wauthor, author_width, NULL, author, 0, limit,
2178 col_tab_align, 0);
2181 static const struct got_error *
2182 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2183 struct got_object_id *id, const size_t date_display_cols,
2184 int author_display_cols)
2186 struct tog_log_view_state *s = &view->state.log;
2187 const struct got_error *err = NULL;
2188 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2189 char *logmsg0 = NULL, *logmsg = NULL;
2190 char *author = NULL;
2191 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2192 int author_width, logmsg_width;
2193 char *newline, *line = NULL;
2194 int col, limit, scrollx;
2195 const int avail = view->ncols;
2196 struct tm tm;
2197 time_t committer_time;
2198 struct tog_color *tc;
2200 committer_time = got_object_commit_get_committer_time(commit);
2201 if (gmtime_r(&committer_time, &tm) == NULL)
2202 return got_error_from_errno("gmtime_r");
2203 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2204 return got_error(GOT_ERR_NO_SPACE);
2206 if (avail <= date_display_cols)
2207 limit = MIN(sizeof(datebuf) - 1, avail);
2208 else
2209 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2210 tc = get_color(&s->colors, TOG_COLOR_DATE);
2211 if (tc)
2212 wattr_on(view->window,
2213 COLOR_PAIR(tc->colorpair), NULL);
2214 waddnstr(view->window, datebuf, limit);
2215 if (tc)
2216 wattr_off(view->window,
2217 COLOR_PAIR(tc->colorpair), NULL);
2218 col = limit;
2219 if (col > avail)
2220 goto done;
2222 if (avail >= 120) {
2223 char *id_str;
2224 err = got_object_id_str(&id_str, id);
2225 if (err)
2226 goto done;
2227 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2228 if (tc)
2229 wattr_on(view->window,
2230 COLOR_PAIR(tc->colorpair), NULL);
2231 wprintw(view->window, "%.8s ", id_str);
2232 if (tc)
2233 wattr_off(view->window,
2234 COLOR_PAIR(tc->colorpair), NULL);
2235 free(id_str);
2236 col += 9;
2237 if (col > avail)
2238 goto done;
2241 if (s->use_committer)
2242 author = strdup(got_object_commit_get_committer(commit));
2243 else
2244 author = strdup(got_object_commit_get_author(commit));
2245 if (author == NULL) {
2246 err = got_error_from_errno("strdup");
2247 goto done;
2249 err = format_author(&wauthor, &author_width, author, avail - col, col);
2250 if (err)
2251 goto done;
2252 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2253 if (tc)
2254 wattr_on(view->window,
2255 COLOR_PAIR(tc->colorpair), NULL);
2256 waddwstr(view->window, wauthor);
2257 col += author_width;
2258 while (col < avail && author_width < author_display_cols + 2) {
2259 waddch(view->window, ' ');
2260 col++;
2261 author_width++;
2263 if (tc)
2264 wattr_off(view->window,
2265 COLOR_PAIR(tc->colorpair), NULL);
2266 if (col > avail)
2267 goto done;
2269 err = got_object_commit_get_logmsg(&logmsg0, commit);
2270 if (err)
2271 goto done;
2272 logmsg = logmsg0;
2273 while (*logmsg == '\n')
2274 logmsg++;
2275 newline = strchr(logmsg, '\n');
2276 if (newline)
2277 *newline = '\0';
2278 limit = avail - col;
2279 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2280 limit--; /* for the border */
2281 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2282 limit, col, 1);
2283 if (err)
2284 goto done;
2285 waddwstr(view->window, &wlogmsg[scrollx]);
2286 col += MAX(logmsg_width, 0);
2287 while (col < avail) {
2288 waddch(view->window, ' ');
2289 col++;
2291 done:
2292 free(logmsg0);
2293 free(wlogmsg);
2294 free(author);
2295 free(wauthor);
2296 free(line);
2297 return err;
2300 static struct commit_queue_entry *
2301 alloc_commit_queue_entry(struct got_commit_object *commit,
2302 struct got_object_id *id)
2304 struct commit_queue_entry *entry;
2305 struct got_object_id *dup;
2307 entry = calloc(1, sizeof(*entry));
2308 if (entry == NULL)
2309 return NULL;
2311 dup = got_object_id_dup(id);
2312 if (dup == NULL) {
2313 free(entry);
2314 return NULL;
2317 entry->id = dup;
2318 entry->commit = commit;
2319 return entry;
2322 static void
2323 pop_commit(struct commit_queue *commits)
2325 struct commit_queue_entry *entry;
2327 entry = TAILQ_FIRST(&commits->head);
2328 TAILQ_REMOVE(&commits->head, entry, entry);
2329 got_object_commit_close(entry->commit);
2330 commits->ncommits--;
2331 free(entry->id);
2332 free(entry);
2335 static void
2336 free_commits(struct commit_queue *commits)
2338 while (!TAILQ_EMPTY(&commits->head))
2339 pop_commit(commits);
2342 static const struct got_error *
2343 match_commit(int *have_match, struct got_object_id *id,
2344 struct got_commit_object *commit, regex_t *regex)
2346 const struct got_error *err = NULL;
2347 regmatch_t regmatch;
2348 char *id_str = NULL, *logmsg = NULL;
2350 *have_match = 0;
2352 err = got_object_id_str(&id_str, id);
2353 if (err)
2354 return err;
2356 err = got_object_commit_get_logmsg(&logmsg, commit);
2357 if (err)
2358 goto done;
2360 if (regexec(regex, got_object_commit_get_author(commit), 1,
2361 &regmatch, 0) == 0 ||
2362 regexec(regex, got_object_commit_get_committer(commit), 1,
2363 &regmatch, 0) == 0 ||
2364 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2365 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2366 *have_match = 1;
2367 done:
2368 free(id_str);
2369 free(logmsg);
2370 return err;
2373 static const struct got_error *
2374 queue_commits(struct tog_log_thread_args *a)
2376 const struct got_error *err = NULL;
2379 * We keep all commits open throughout the lifetime of the log
2380 * view in order to avoid having to re-fetch commits from disk
2381 * while updating the display.
2383 do {
2384 struct got_object_id id;
2385 struct got_commit_object *commit;
2386 struct commit_queue_entry *entry;
2387 int limit_match = 0;
2388 int errcode;
2390 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2391 NULL, NULL);
2392 if (err)
2393 break;
2395 err = got_object_open_as_commit(&commit, a->repo, &id);
2396 if (err)
2397 break;
2398 entry = alloc_commit_queue_entry(commit, &id);
2399 if (entry == NULL) {
2400 err = got_error_from_errno("alloc_commit_queue_entry");
2401 break;
2404 errcode = pthread_mutex_lock(&tog_mutex);
2405 if (errcode) {
2406 err = got_error_set_errno(errcode,
2407 "pthread_mutex_lock");
2408 break;
2411 entry->idx = a->real_commits->ncommits;
2412 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2413 a->real_commits->ncommits++;
2415 if (*a->limiting) {
2416 err = match_commit(&limit_match, &id, commit,
2417 a->limit_regex);
2418 if (err)
2419 break;
2421 if (limit_match) {
2422 struct commit_queue_entry *matched;
2424 matched = alloc_commit_queue_entry(
2425 entry->commit, entry->id);
2426 if (matched == NULL) {
2427 err = got_error_from_errno(
2428 "alloc_commit_queue_entry");
2429 break;
2431 matched->commit = entry->commit;
2432 got_object_commit_retain(entry->commit);
2434 matched->idx = a->limit_commits->ncommits;
2435 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2436 matched, entry);
2437 a->limit_commits->ncommits++;
2441 * This is how we signal log_thread() that we
2442 * have found a match, and that it should be
2443 * counted as a new entry for the view.
2445 a->limit_match = limit_match;
2448 if (*a->searching == TOG_SEARCH_FORWARD &&
2449 !*a->search_next_done) {
2450 int have_match;
2451 err = match_commit(&have_match, &id, commit, a->regex);
2452 if (err)
2453 break;
2455 if (*a->limiting) {
2456 if (limit_match && have_match)
2457 *a->search_next_done =
2458 TOG_SEARCH_HAVE_MORE;
2459 } else if (have_match)
2460 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2463 errcode = pthread_mutex_unlock(&tog_mutex);
2464 if (errcode && err == NULL)
2465 err = got_error_set_errno(errcode,
2466 "pthread_mutex_unlock");
2467 if (err)
2468 break;
2469 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2471 return err;
2474 static void
2475 select_commit(struct tog_log_view_state *s)
2477 struct commit_queue_entry *entry;
2478 int ncommits = 0;
2480 entry = s->first_displayed_entry;
2481 while (entry) {
2482 if (ncommits == s->selected) {
2483 s->selected_entry = entry;
2484 break;
2486 entry = TAILQ_NEXT(entry, entry);
2487 ncommits++;
2491 static const struct got_error *
2492 draw_commits(struct tog_view *view)
2494 const struct got_error *err = NULL;
2495 struct tog_log_view_state *s = &view->state.log;
2496 struct commit_queue_entry *entry = s->selected_entry;
2497 int limit = view->nlines;
2498 int width;
2499 int ncommits, author_cols = 4;
2500 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2501 char *refs_str = NULL;
2502 wchar_t *wline;
2503 struct tog_color *tc;
2504 static const size_t date_display_cols = 12;
2506 if (view_is_hsplit_top(view))
2507 --limit; /* account for border */
2509 if (s->selected_entry &&
2510 !(view->searching && view->search_next_done == 0)) {
2511 struct got_reflist_head *refs;
2512 err = got_object_id_str(&id_str, s->selected_entry->id);
2513 if (err)
2514 return err;
2515 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2516 s->selected_entry->id);
2517 if (refs) {
2518 err = build_refs_str(&refs_str, refs,
2519 s->selected_entry->id, s->repo);
2520 if (err)
2521 goto done;
2525 if (s->thread_args.commits_needed == 0)
2526 halfdelay(10); /* disable fast refresh */
2528 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2529 if (asprintf(&ncommits_str, " [%d/%d] %s",
2530 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2531 (view->searching && !view->search_next_done) ?
2532 "searching..." : "loading...") == -1) {
2533 err = got_error_from_errno("asprintf");
2534 goto done;
2536 } else {
2537 const char *search_str = NULL;
2538 const char *limit_str = NULL;
2540 if (view->searching) {
2541 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2542 search_str = "no more matches";
2543 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2544 search_str = "no matches found";
2545 else if (!view->search_next_done)
2546 search_str = "searching...";
2549 if (s->limit_view && s->commits->ncommits == 0)
2550 limit_str = "no matches found";
2552 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2553 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2554 search_str ? search_str : (refs_str ? refs_str : ""),
2555 limit_str ? limit_str : "") == -1) {
2556 err = got_error_from_errno("asprintf");
2557 goto done;
2561 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2562 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2563 "........................................",
2564 s->in_repo_path, ncommits_str) == -1) {
2565 err = got_error_from_errno("asprintf");
2566 header = NULL;
2567 goto done;
2569 } else if (asprintf(&header, "commit %s%s",
2570 id_str ? id_str : "........................................",
2571 ncommits_str) == -1) {
2572 err = got_error_from_errno("asprintf");
2573 header = NULL;
2574 goto done;
2576 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2577 if (err)
2578 goto done;
2580 werase(view->window);
2582 if (view_needs_focus_indication(view))
2583 wstandout(view->window);
2584 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2585 if (tc)
2586 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2587 waddwstr(view->window, wline);
2588 while (width < view->ncols) {
2589 waddch(view->window, ' ');
2590 width++;
2592 if (tc)
2593 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2594 if (view_needs_focus_indication(view))
2595 wstandend(view->window);
2596 free(wline);
2597 if (limit <= 1)
2598 goto done;
2600 /* Grow author column size if necessary, and set view->maxx. */
2601 entry = s->first_displayed_entry;
2602 ncommits = 0;
2603 view->maxx = 0;
2604 while (entry) {
2605 struct got_commit_object *c = entry->commit;
2606 char *author, *eol, *msg, *msg0;
2607 wchar_t *wauthor, *wmsg;
2608 int width;
2609 if (ncommits >= limit - 1)
2610 break;
2611 if (s->use_committer)
2612 author = strdup(got_object_commit_get_committer(c));
2613 else
2614 author = strdup(got_object_commit_get_author(c));
2615 if (author == NULL) {
2616 err = got_error_from_errno("strdup");
2617 goto done;
2619 err = format_author(&wauthor, &width, author, COLS,
2620 date_display_cols);
2621 if (author_cols < width)
2622 author_cols = width;
2623 free(wauthor);
2624 free(author);
2625 if (err)
2626 goto done;
2627 err = got_object_commit_get_logmsg(&msg0, c);
2628 if (err)
2629 goto done;
2630 msg = msg0;
2631 while (*msg == '\n')
2632 ++msg;
2633 if ((eol = strchr(msg, '\n')))
2634 *eol = '\0';
2635 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2636 date_display_cols + author_cols, 0);
2637 if (err)
2638 goto done;
2639 view->maxx = MAX(view->maxx, width);
2640 free(msg0);
2641 free(wmsg);
2642 ncommits++;
2643 entry = TAILQ_NEXT(entry, entry);
2646 entry = s->first_displayed_entry;
2647 s->last_displayed_entry = s->first_displayed_entry;
2648 ncommits = 0;
2649 while (entry) {
2650 if (ncommits >= limit - 1)
2651 break;
2652 if (ncommits == s->selected)
2653 wstandout(view->window);
2654 err = draw_commit(view, entry->commit, entry->id,
2655 date_display_cols, author_cols);
2656 if (ncommits == s->selected)
2657 wstandend(view->window);
2658 if (err)
2659 goto done;
2660 ncommits++;
2661 s->last_displayed_entry = entry;
2662 entry = TAILQ_NEXT(entry, entry);
2665 view_border(view);
2666 done:
2667 free(id_str);
2668 free(refs_str);
2669 free(ncommits_str);
2670 free(header);
2671 return err;
2674 static void
2675 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2677 struct commit_queue_entry *entry;
2678 int nscrolled = 0;
2680 entry = TAILQ_FIRST(&s->commits->head);
2681 if (s->first_displayed_entry == entry)
2682 return;
2684 entry = s->first_displayed_entry;
2685 while (entry && nscrolled < maxscroll) {
2686 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2687 if (entry) {
2688 s->first_displayed_entry = entry;
2689 nscrolled++;
2694 static const struct got_error *
2695 trigger_log_thread(struct tog_view *view, int wait)
2697 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2698 int errcode;
2700 halfdelay(1); /* fast refresh while loading commits */
2702 while (!ta->log_complete && !tog_thread_error &&
2703 (ta->commits_needed > 0 || ta->load_all)) {
2704 /* Wake the log thread. */
2705 errcode = pthread_cond_signal(&ta->need_commits);
2706 if (errcode)
2707 return got_error_set_errno(errcode,
2708 "pthread_cond_signal");
2711 * The mutex will be released while the view loop waits
2712 * in wgetch(), at which time the log thread will run.
2714 if (!wait)
2715 break;
2717 /* Display progress update in log view. */
2718 show_log_view(view);
2719 update_panels();
2720 doupdate();
2722 /* Wait right here while next commit is being loaded. */
2723 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2724 if (errcode)
2725 return got_error_set_errno(errcode,
2726 "pthread_cond_wait");
2728 /* Display progress update in log view. */
2729 show_log_view(view);
2730 update_panels();
2731 doupdate();
2734 return NULL;
2737 static const struct got_error *
2738 request_log_commits(struct tog_view *view)
2740 struct tog_log_view_state *state = &view->state.log;
2741 const struct got_error *err = NULL;
2743 if (state->thread_args.log_complete)
2744 return NULL;
2746 state->thread_args.commits_needed += view->nscrolled;
2747 err = trigger_log_thread(view, 1);
2748 view->nscrolled = 0;
2750 return err;
2753 static const struct got_error *
2754 log_scroll_down(struct tog_view *view, int maxscroll)
2756 struct tog_log_view_state *s = &view->state.log;
2757 const struct got_error *err = NULL;
2758 struct commit_queue_entry *pentry;
2759 int nscrolled = 0, ncommits_needed;
2761 if (s->last_displayed_entry == NULL)
2762 return NULL;
2764 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2765 if (s->commits->ncommits < ncommits_needed &&
2766 !s->thread_args.log_complete) {
2768 * Ask the log thread for required amount of commits.
2770 s->thread_args.commits_needed +=
2771 ncommits_needed - s->commits->ncommits;
2772 err = trigger_log_thread(view, 1);
2773 if (err)
2774 return err;
2777 do {
2778 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2779 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2780 break;
2782 s->last_displayed_entry = pentry ?
2783 pentry : s->last_displayed_entry;
2785 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2786 if (pentry == NULL)
2787 break;
2788 s->first_displayed_entry = pentry;
2789 } while (++nscrolled < maxscroll);
2791 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2792 view->nscrolled += nscrolled;
2793 else
2794 view->nscrolled = 0;
2796 return err;
2799 static const struct got_error *
2800 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2801 struct got_commit_object *commit, struct got_object_id *commit_id,
2802 struct tog_view *log_view, struct got_repository *repo)
2804 const struct got_error *err;
2805 struct got_object_qid *parent_id;
2806 struct tog_view *diff_view;
2808 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2809 if (diff_view == NULL)
2810 return got_error_from_errno("view_open");
2812 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2813 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2814 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2815 if (err == NULL)
2816 *new_view = diff_view;
2817 return err;
2820 static const struct got_error *
2821 tree_view_visit_subtree(struct tog_tree_view_state *s,
2822 struct got_tree_object *subtree)
2824 struct tog_parent_tree *parent;
2826 parent = calloc(1, sizeof(*parent));
2827 if (parent == NULL)
2828 return got_error_from_errno("calloc");
2830 parent->tree = s->tree;
2831 parent->first_displayed_entry = s->first_displayed_entry;
2832 parent->selected_entry = s->selected_entry;
2833 parent->selected = s->selected;
2834 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2835 s->tree = subtree;
2836 s->selected = 0;
2837 s->first_displayed_entry = NULL;
2838 return NULL;
2841 static const struct got_error *
2842 tree_view_walk_path(struct tog_tree_view_state *s,
2843 struct got_commit_object *commit, const char *path)
2845 const struct got_error *err = NULL;
2846 struct got_tree_object *tree = NULL;
2847 const char *p;
2848 char *slash, *subpath = NULL;
2850 /* Walk the path and open corresponding tree objects. */
2851 p = path;
2852 while (*p) {
2853 struct got_tree_entry *te;
2854 struct got_object_id *tree_id;
2855 char *te_name;
2857 while (p[0] == '/')
2858 p++;
2860 /* Ensure the correct subtree entry is selected. */
2861 slash = strchr(p, '/');
2862 if (slash == NULL)
2863 te_name = strdup(p);
2864 else
2865 te_name = strndup(p, slash - p);
2866 if (te_name == NULL) {
2867 err = got_error_from_errno("strndup");
2868 break;
2870 te = got_object_tree_find_entry(s->tree, te_name);
2871 if (te == NULL) {
2872 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2873 free(te_name);
2874 break;
2876 free(te_name);
2877 s->first_displayed_entry = s->selected_entry = te;
2879 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2880 break; /* jump to this file's entry */
2882 slash = strchr(p, '/');
2883 if (slash)
2884 subpath = strndup(path, slash - path);
2885 else
2886 subpath = strdup(path);
2887 if (subpath == NULL) {
2888 err = got_error_from_errno("strdup");
2889 break;
2892 err = got_object_id_by_path(&tree_id, s->repo, commit,
2893 subpath);
2894 if (err)
2895 break;
2897 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2898 free(tree_id);
2899 if (err)
2900 break;
2902 err = tree_view_visit_subtree(s, tree);
2903 if (err) {
2904 got_object_tree_close(tree);
2905 break;
2907 if (slash == NULL)
2908 break;
2909 free(subpath);
2910 subpath = NULL;
2911 p = slash;
2914 free(subpath);
2915 return err;
2918 static const struct got_error *
2919 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2920 struct commit_queue_entry *entry, const char *path,
2921 const char *head_ref_name, struct got_repository *repo)
2923 const struct got_error *err = NULL;
2924 struct tog_tree_view_state *s;
2925 struct tog_view *tree_view;
2927 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2928 if (tree_view == NULL)
2929 return got_error_from_errno("view_open");
2931 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2932 if (err)
2933 return err;
2934 s = &tree_view->state.tree;
2936 *new_view = tree_view;
2938 if (got_path_is_root_dir(path))
2939 return NULL;
2941 return tree_view_walk_path(s, entry->commit, path);
2944 static const struct got_error *
2945 block_signals_used_by_main_thread(void)
2947 sigset_t sigset;
2948 int errcode;
2950 if (sigemptyset(&sigset) == -1)
2951 return got_error_from_errno("sigemptyset");
2953 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2954 if (sigaddset(&sigset, SIGWINCH) == -1)
2955 return got_error_from_errno("sigaddset");
2956 if (sigaddset(&sigset, SIGCONT) == -1)
2957 return got_error_from_errno("sigaddset");
2958 if (sigaddset(&sigset, SIGINT) == -1)
2959 return got_error_from_errno("sigaddset");
2960 if (sigaddset(&sigset, SIGTERM) == -1)
2961 return got_error_from_errno("sigaddset");
2963 /* ncurses handles SIGTSTP */
2964 if (sigaddset(&sigset, SIGTSTP) == -1)
2965 return got_error_from_errno("sigaddset");
2967 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2968 if (errcode)
2969 return got_error_set_errno(errcode, "pthread_sigmask");
2971 return NULL;
2974 static void *
2975 log_thread(void *arg)
2977 const struct got_error *err = NULL;
2978 int errcode = 0;
2979 struct tog_log_thread_args *a = arg;
2980 int done = 0;
2983 * Sync startup with main thread such that we begin our
2984 * work once view_input() has released the mutex.
2986 errcode = pthread_mutex_lock(&tog_mutex);
2987 if (errcode) {
2988 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2989 return (void *)err;
2992 err = block_signals_used_by_main_thread();
2993 if (err) {
2994 pthread_mutex_unlock(&tog_mutex);
2995 goto done;
2998 while (!done && !err && !tog_fatal_signal_received()) {
2999 errcode = pthread_mutex_unlock(&tog_mutex);
3000 if (errcode) {
3001 err = got_error_set_errno(errcode,
3002 "pthread_mutex_unlock");
3003 goto done;
3005 err = queue_commits(a);
3006 if (err) {
3007 if (err->code != GOT_ERR_ITER_COMPLETED)
3008 goto done;
3009 err = NULL;
3010 done = 1;
3011 } else if (a->commits_needed > 0 && !a->load_all) {
3012 if (*a->limiting) {
3013 if (a->limit_match)
3014 a->commits_needed--;
3015 } else
3016 a->commits_needed--;
3019 errcode = pthread_mutex_lock(&tog_mutex);
3020 if (errcode) {
3021 err = got_error_set_errno(errcode,
3022 "pthread_mutex_lock");
3023 goto done;
3024 } else if (*a->quit)
3025 done = 1;
3026 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3027 *a->first_displayed_entry =
3028 TAILQ_FIRST(&a->limit_commits->head);
3029 *a->selected_entry = *a->first_displayed_entry;
3030 } else if (*a->first_displayed_entry == NULL) {
3031 *a->first_displayed_entry =
3032 TAILQ_FIRST(&a->real_commits->head);
3033 *a->selected_entry = *a->first_displayed_entry;
3036 errcode = pthread_cond_signal(&a->commit_loaded);
3037 if (errcode) {
3038 err = got_error_set_errno(errcode,
3039 "pthread_cond_signal");
3040 pthread_mutex_unlock(&tog_mutex);
3041 goto done;
3044 if (done)
3045 a->commits_needed = 0;
3046 else {
3047 if (a->commits_needed == 0 && !a->load_all) {
3048 errcode = pthread_cond_wait(&a->need_commits,
3049 &tog_mutex);
3050 if (errcode) {
3051 err = got_error_set_errno(errcode,
3052 "pthread_cond_wait");
3053 pthread_mutex_unlock(&tog_mutex);
3054 goto done;
3056 if (*a->quit)
3057 done = 1;
3061 a->log_complete = 1;
3062 errcode = pthread_mutex_unlock(&tog_mutex);
3063 if (errcode)
3064 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3065 done:
3066 if (err) {
3067 tog_thread_error = 1;
3068 pthread_cond_signal(&a->commit_loaded);
3070 return (void *)err;
3073 static const struct got_error *
3074 stop_log_thread(struct tog_log_view_state *s)
3076 const struct got_error *err = NULL, *thread_err = NULL;
3077 int errcode;
3079 if (s->thread) {
3080 s->quit = 1;
3081 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3082 if (errcode)
3083 return got_error_set_errno(errcode,
3084 "pthread_cond_signal");
3085 errcode = pthread_mutex_unlock(&tog_mutex);
3086 if (errcode)
3087 return got_error_set_errno(errcode,
3088 "pthread_mutex_unlock");
3089 errcode = pthread_join(s->thread, (void **)&thread_err);
3090 if (errcode)
3091 return got_error_set_errno(errcode, "pthread_join");
3092 errcode = pthread_mutex_lock(&tog_mutex);
3093 if (errcode)
3094 return got_error_set_errno(errcode,
3095 "pthread_mutex_lock");
3096 s->thread = NULL;
3099 if (s->thread_args.repo) {
3100 err = got_repo_close(s->thread_args.repo);
3101 s->thread_args.repo = NULL;
3104 if (s->thread_args.pack_fds) {
3105 const struct got_error *pack_err =
3106 got_repo_pack_fds_close(s->thread_args.pack_fds);
3107 if (err == NULL)
3108 err = pack_err;
3109 s->thread_args.pack_fds = NULL;
3112 if (s->thread_args.graph) {
3113 got_commit_graph_close(s->thread_args.graph);
3114 s->thread_args.graph = NULL;
3117 return err ? err : thread_err;
3120 static const struct got_error *
3121 close_log_view(struct tog_view *view)
3123 const struct got_error *err = NULL;
3124 struct tog_log_view_state *s = &view->state.log;
3125 int errcode;
3127 err = stop_log_thread(s);
3129 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3130 if (errcode && err == NULL)
3131 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3133 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3134 if (errcode && err == NULL)
3135 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3137 free_commits(&s->limit_commits);
3138 free_commits(&s->real_commits);
3139 free(s->in_repo_path);
3140 s->in_repo_path = NULL;
3141 free(s->start_id);
3142 s->start_id = NULL;
3143 free(s->head_ref_name);
3144 s->head_ref_name = NULL;
3145 return err;
3149 * We use two queues to implement the limit feature: first consists of
3150 * commits matching the current limit_regex; second is the real queue
3151 * of all known commits (real_commits). When the user starts limiting,
3152 * we swap queues such that all movement and displaying functionality
3153 * works with very slight change.
3155 static const struct got_error *
3156 limit_log_view(struct tog_view *view)
3158 struct tog_log_view_state *s = &view->state.log;
3159 struct commit_queue_entry *entry;
3160 struct tog_view *v = view;
3161 const struct got_error *err = NULL;
3162 char pattern[1024];
3163 int ret;
3165 if (view_is_hsplit_top(view))
3166 v = view->child;
3167 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3168 v = view->parent;
3170 /* Get the pattern */
3171 wmove(v->window, v->nlines - 1, 0);
3172 wclrtoeol(v->window);
3173 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3174 nodelay(v->window, FALSE);
3175 nocbreak();
3176 echo();
3177 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3178 cbreak();
3179 noecho();
3180 nodelay(v->window, TRUE);
3181 if (ret == ERR)
3182 return NULL;
3184 if (*pattern == '\0') {
3186 * Safety measure for the situation where the user
3187 * resets limit without previously limiting anything.
3189 if (!s->limit_view)
3190 return NULL;
3193 * User could have pressed Ctrl+L, which refreshed the
3194 * commit queues, it means we can't save previously
3195 * (before limit took place) displayed entries,
3196 * because they would point to already free'ed memory,
3197 * so we are forced to always select first entry of
3198 * the queue.
3200 s->commits = &s->real_commits;
3201 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3202 s->selected_entry = s->first_displayed_entry;
3203 s->selected = 0;
3204 s->limit_view = 0;
3206 return NULL;
3209 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3210 return NULL;
3212 s->limit_view = 1;
3214 /* Clear the screen while loading limit view */
3215 s->first_displayed_entry = NULL;
3216 s->last_displayed_entry = NULL;
3217 s->selected_entry = NULL;
3218 s->commits = &s->limit_commits;
3220 /* Prepare limit queue for new search */
3221 free_commits(&s->limit_commits);
3222 s->limit_commits.ncommits = 0;
3224 /* First process commits, which are in queue already */
3225 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3226 int have_match = 0;
3228 err = match_commit(&have_match, entry->id,
3229 entry->commit, &s->limit_regex);
3230 if (err)
3231 return err;
3233 if (have_match) {
3234 struct commit_queue_entry *matched;
3236 matched = alloc_commit_queue_entry(entry->commit,
3237 entry->id);
3238 if (matched == NULL) {
3239 err = got_error_from_errno(
3240 "alloc_commit_queue_entry");
3241 break;
3243 matched->commit = entry->commit;
3244 got_object_commit_retain(entry->commit);
3246 matched->idx = s->limit_commits.ncommits;
3247 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3248 matched, entry);
3249 s->limit_commits.ncommits++;
3253 /* Second process all the commits, until we fill the screen */
3254 if (s->limit_commits.ncommits < view->nlines - 1 &&
3255 !s->thread_args.log_complete) {
3256 s->thread_args.commits_needed +=
3257 view->nlines - s->limit_commits.ncommits - 1;
3258 err = trigger_log_thread(view, 1);
3259 if (err)
3260 return err;
3263 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3264 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3265 s->selected = 0;
3267 return NULL;
3270 static const struct got_error *
3271 search_start_log_view(struct tog_view *view)
3273 struct tog_log_view_state *s = &view->state.log;
3275 s->matched_entry = NULL;
3276 s->search_entry = NULL;
3277 return NULL;
3280 static const struct got_error *
3281 search_next_log_view(struct tog_view *view)
3283 const struct got_error *err = NULL;
3284 struct tog_log_view_state *s = &view->state.log;
3285 struct commit_queue_entry *entry;
3287 /* Display progress update in log view. */
3288 show_log_view(view);
3289 update_panels();
3290 doupdate();
3292 if (s->search_entry) {
3293 int errcode, ch;
3294 errcode = pthread_mutex_unlock(&tog_mutex);
3295 if (errcode)
3296 return got_error_set_errno(errcode,
3297 "pthread_mutex_unlock");
3298 ch = wgetch(view->window);
3299 errcode = pthread_mutex_lock(&tog_mutex);
3300 if (errcode)
3301 return got_error_set_errno(errcode,
3302 "pthread_mutex_lock");
3303 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3304 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3305 return NULL;
3307 if (view->searching == TOG_SEARCH_FORWARD)
3308 entry = TAILQ_NEXT(s->search_entry, entry);
3309 else
3310 entry = TAILQ_PREV(s->search_entry,
3311 commit_queue_head, entry);
3312 } else if (s->matched_entry) {
3314 * If the user has moved the cursor after we hit a match,
3315 * the position from where we should continue searching
3316 * might have changed.
3318 if (view->searching == TOG_SEARCH_FORWARD)
3319 entry = TAILQ_NEXT(s->selected_entry, entry);
3320 else
3321 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3322 entry);
3323 } else {
3324 entry = s->selected_entry;
3327 while (1) {
3328 int have_match = 0;
3330 if (entry == NULL) {
3331 if (s->thread_args.log_complete ||
3332 view->searching == TOG_SEARCH_BACKWARD) {
3333 view->search_next_done =
3334 (s->matched_entry == NULL ?
3335 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3336 s->search_entry = NULL;
3337 return NULL;
3340 * Poke the log thread for more commits and return,
3341 * allowing the main loop to make progress. Search
3342 * will resume at s->search_entry once we come back.
3344 s->thread_args.commits_needed++;
3345 return trigger_log_thread(view, 0);
3348 err = match_commit(&have_match, entry->id, entry->commit,
3349 &view->regex);
3350 if (err)
3351 break;
3352 if (have_match) {
3353 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3354 s->matched_entry = entry;
3355 break;
3358 s->search_entry = entry;
3359 if (view->searching == TOG_SEARCH_FORWARD)
3360 entry = TAILQ_NEXT(entry, entry);
3361 else
3362 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3365 if (s->matched_entry) {
3366 int cur = s->selected_entry->idx;
3367 while (cur < s->matched_entry->idx) {
3368 err = input_log_view(NULL, view, KEY_DOWN);
3369 if (err)
3370 return err;
3371 cur++;
3373 while (cur > s->matched_entry->idx) {
3374 err = input_log_view(NULL, view, KEY_UP);
3375 if (err)
3376 return err;
3377 cur--;
3381 s->search_entry = NULL;
3383 return NULL;
3386 static const struct got_error *
3387 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3388 struct got_repository *repo, const char *head_ref_name,
3389 const char *in_repo_path, int log_branches)
3391 const struct got_error *err = NULL;
3392 struct tog_log_view_state *s = &view->state.log;
3393 struct got_repository *thread_repo = NULL;
3394 struct got_commit_graph *thread_graph = NULL;
3395 int errcode;
3397 if (in_repo_path != s->in_repo_path) {
3398 free(s->in_repo_path);
3399 s->in_repo_path = strdup(in_repo_path);
3400 if (s->in_repo_path == NULL)
3401 return got_error_from_errno("strdup");
3404 /* The commit queue only contains commits being displayed. */
3405 TAILQ_INIT(&s->real_commits.head);
3406 s->real_commits.ncommits = 0;
3407 s->commits = &s->real_commits;
3409 TAILQ_INIT(&s->limit_commits.head);
3410 s->limit_view = 0;
3411 s->limit_commits.ncommits = 0;
3413 s->repo = repo;
3414 if (head_ref_name) {
3415 s->head_ref_name = strdup(head_ref_name);
3416 if (s->head_ref_name == NULL) {
3417 err = got_error_from_errno("strdup");
3418 goto done;
3421 s->start_id = got_object_id_dup(start_id);
3422 if (s->start_id == NULL) {
3423 err = got_error_from_errno("got_object_id_dup");
3424 goto done;
3426 s->log_branches = log_branches;
3427 s->use_committer = 1;
3429 STAILQ_INIT(&s->colors);
3430 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3431 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3432 get_color_value("TOG_COLOR_COMMIT"));
3433 if (err)
3434 goto done;
3435 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3436 get_color_value("TOG_COLOR_AUTHOR"));
3437 if (err) {
3438 free_colors(&s->colors);
3439 goto done;
3441 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3442 get_color_value("TOG_COLOR_DATE"));
3443 if (err) {
3444 free_colors(&s->colors);
3445 goto done;
3449 view->show = show_log_view;
3450 view->input = input_log_view;
3451 view->resize = resize_log_view;
3452 view->close = close_log_view;
3453 view->search_start = search_start_log_view;
3454 view->search_next = search_next_log_view;
3456 if (s->thread_args.pack_fds == NULL) {
3457 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3458 if (err)
3459 goto done;
3461 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3462 s->thread_args.pack_fds);
3463 if (err)
3464 goto done;
3465 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3466 !s->log_branches);
3467 if (err)
3468 goto done;
3469 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3470 s->repo, NULL, NULL);
3471 if (err)
3472 goto done;
3474 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3475 if (errcode) {
3476 err = got_error_set_errno(errcode, "pthread_cond_init");
3477 goto done;
3479 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3480 if (errcode) {
3481 err = got_error_set_errno(errcode, "pthread_cond_init");
3482 goto done;
3485 s->thread_args.commits_needed = view->nlines;
3486 s->thread_args.graph = thread_graph;
3487 s->thread_args.real_commits = &s->real_commits;
3488 s->thread_args.limit_commits = &s->limit_commits;
3489 s->thread_args.in_repo_path = s->in_repo_path;
3490 s->thread_args.start_id = s->start_id;
3491 s->thread_args.repo = thread_repo;
3492 s->thread_args.log_complete = 0;
3493 s->thread_args.quit = &s->quit;
3494 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3495 s->thread_args.selected_entry = &s->selected_entry;
3496 s->thread_args.searching = &view->searching;
3497 s->thread_args.search_next_done = &view->search_next_done;
3498 s->thread_args.regex = &view->regex;
3499 s->thread_args.limiting = &s->limit_view;
3500 s->thread_args.limit_regex = &s->limit_regex;
3501 s->thread_args.limit_commits = &s->limit_commits;
3502 done:
3503 if (err)
3504 close_log_view(view);
3505 return err;
3508 static const struct got_error *
3509 show_log_view(struct tog_view *view)
3511 const struct got_error *err;
3512 struct tog_log_view_state *s = &view->state.log;
3514 if (s->thread == NULL) {
3515 int errcode = pthread_create(&s->thread, NULL, log_thread,
3516 &s->thread_args);
3517 if (errcode)
3518 return got_error_set_errno(errcode, "pthread_create");
3519 if (s->thread_args.commits_needed > 0) {
3520 err = trigger_log_thread(view, 1);
3521 if (err)
3522 return err;
3526 return draw_commits(view);
3529 static void
3530 log_move_cursor_up(struct tog_view *view, int page, int home)
3532 struct tog_log_view_state *s = &view->state.log;
3534 if (s->first_displayed_entry == NULL)
3535 return;
3536 if (s->selected_entry->idx == 0)
3537 view->count = 0;
3539 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3540 || home)
3541 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3543 if (!page && !home && s->selected > 0)
3544 --s->selected;
3545 else
3546 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3548 select_commit(s);
3549 return;
3552 static const struct got_error *
3553 log_move_cursor_down(struct tog_view *view, int page)
3555 struct tog_log_view_state *s = &view->state.log;
3556 const struct got_error *err = NULL;
3557 int eos = view->nlines - 2;
3559 if (s->first_displayed_entry == NULL)
3560 return NULL;
3562 if (s->thread_args.log_complete &&
3563 s->selected_entry->idx >= s->commits->ncommits - 1)
3564 return NULL;
3566 if (view_is_hsplit_top(view))
3567 --eos; /* border consumes the last line */
3569 if (!page) {
3570 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3571 ++s->selected;
3572 else
3573 err = log_scroll_down(view, 1);
3574 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3575 struct commit_queue_entry *entry;
3576 int n;
3578 s->selected = 0;
3579 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3580 s->last_displayed_entry = entry;
3581 for (n = 0; n <= eos; n++) {
3582 if (entry == NULL)
3583 break;
3584 s->first_displayed_entry = entry;
3585 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3587 if (n > 0)
3588 s->selected = n - 1;
3589 } else {
3590 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3591 s->thread_args.log_complete)
3592 s->selected += MIN(page,
3593 s->commits->ncommits - s->selected_entry->idx - 1);
3594 else
3595 err = log_scroll_down(view, page);
3597 if (err)
3598 return err;
3601 * We might necessarily overshoot in horizontal
3602 * splits; if so, select the last displayed commit.
3604 if (s->first_displayed_entry && s->last_displayed_entry) {
3605 s->selected = MIN(s->selected,
3606 s->last_displayed_entry->idx -
3607 s->first_displayed_entry->idx);
3610 select_commit(s);
3612 if (s->thread_args.log_complete &&
3613 s->selected_entry->idx == s->commits->ncommits - 1)
3614 view->count = 0;
3616 return NULL;
3619 static void
3620 view_get_split(struct tog_view *view, int *y, int *x)
3622 *x = 0;
3623 *y = 0;
3625 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3626 if (view->child && view->child->resized_y)
3627 *y = view->child->resized_y;
3628 else if (view->resized_y)
3629 *y = view->resized_y;
3630 else
3631 *y = view_split_begin_y(view->lines);
3632 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3633 if (view->child && view->child->resized_x)
3634 *x = view->child->resized_x;
3635 else if (view->resized_x)
3636 *x = view->resized_x;
3637 else
3638 *x = view_split_begin_x(view->begin_x);
3642 /* Split view horizontally at y and offset view->state->selected line. */
3643 static const struct got_error *
3644 view_init_hsplit(struct tog_view *view, int y)
3646 const struct got_error *err = NULL;
3648 view->nlines = y;
3649 view->ncols = COLS;
3650 err = view_resize(view);
3651 if (err)
3652 return err;
3654 err = offset_selection_down(view);
3656 return err;
3659 static const struct got_error *
3660 log_goto_line(struct tog_view *view, int nlines)
3662 const struct got_error *err = NULL;
3663 struct tog_log_view_state *s = &view->state.log;
3664 int g, idx = s->selected_entry->idx;
3666 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3667 return NULL;
3669 g = view->gline;
3670 view->gline = 0;
3672 if (g >= s->first_displayed_entry->idx + 1 &&
3673 g <= s->last_displayed_entry->idx + 1 &&
3674 g - s->first_displayed_entry->idx - 1 < nlines) {
3675 s->selected = g - s->first_displayed_entry->idx - 1;
3676 select_commit(s);
3677 return NULL;
3680 if (idx + 1 < g) {
3681 err = log_move_cursor_down(view, g - idx - 1);
3682 if (!err && g > s->selected_entry->idx + 1)
3683 err = log_move_cursor_down(view,
3684 g - s->first_displayed_entry->idx - 1);
3685 if (err)
3686 return err;
3687 } else if (idx + 1 > g)
3688 log_move_cursor_up(view, idx - g + 1, 0);
3690 if (g < nlines && s->first_displayed_entry->idx == 0)
3691 s->selected = g - 1;
3693 select_commit(s);
3694 return NULL;
3698 static void
3699 horizontal_scroll_input(struct tog_view *view, int ch)
3702 switch (ch) {
3703 case KEY_LEFT:
3704 case 'h':
3705 view->x -= MIN(view->x, 2);
3706 if (view->x <= 0)
3707 view->count = 0;
3708 break;
3709 case KEY_RIGHT:
3710 case 'l':
3711 if (view->x + view->ncols / 2 < view->maxx)
3712 view->x += 2;
3713 else
3714 view->count = 0;
3715 break;
3716 case '0':
3717 view->x = 0;
3718 break;
3719 case '$':
3720 view->x = MAX(view->maxx - view->ncols / 2, 0);
3721 view->count = 0;
3722 break;
3723 default:
3724 break;
3728 static const struct got_error *
3729 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3731 const struct got_error *err = NULL;
3732 struct tog_log_view_state *s = &view->state.log;
3733 int eos, nscroll;
3735 if (s->thread_args.load_all) {
3736 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3737 s->thread_args.load_all = 0;
3738 else if (s->thread_args.log_complete) {
3739 err = log_move_cursor_down(view, s->commits->ncommits);
3740 s->thread_args.load_all = 0;
3742 if (err)
3743 return err;
3746 eos = nscroll = view->nlines - 1;
3747 if (view_is_hsplit_top(view))
3748 --eos; /* border */
3750 if (view->gline)
3751 return log_goto_line(view, eos);
3753 switch (ch) {
3754 case '&':
3755 err = limit_log_view(view);
3756 break;
3757 case 'q':
3758 s->quit = 1;
3759 break;
3760 case '0':
3761 case '$':
3762 case KEY_RIGHT:
3763 case 'l':
3764 case KEY_LEFT:
3765 case 'h':
3766 horizontal_scroll_input(view, ch);
3767 break;
3768 case 'k':
3769 case KEY_UP:
3770 case '<':
3771 case ',':
3772 case CTRL('p'):
3773 log_move_cursor_up(view, 0, 0);
3774 break;
3775 case 'g':
3776 case '=':
3777 case KEY_HOME:
3778 log_move_cursor_up(view, 0, 1);
3779 view->count = 0;
3780 break;
3781 case CTRL('u'):
3782 case 'u':
3783 nscroll /= 2;
3784 /* FALL THROUGH */
3785 case KEY_PPAGE:
3786 case CTRL('b'):
3787 case 'b':
3788 log_move_cursor_up(view, nscroll, 0);
3789 break;
3790 case 'j':
3791 case KEY_DOWN:
3792 case '>':
3793 case '.':
3794 case CTRL('n'):
3795 err = log_move_cursor_down(view, 0);
3796 break;
3797 case '@':
3798 s->use_committer = !s->use_committer;
3799 view->action = s->use_committer ?
3800 "show committer" : "show commit author";
3801 break;
3802 case 'G':
3803 case '*':
3804 case KEY_END: {
3805 /* We don't know yet how many commits, so we're forced to
3806 * traverse them all. */
3807 view->count = 0;
3808 s->thread_args.load_all = 1;
3809 if (!s->thread_args.log_complete)
3810 return trigger_log_thread(view, 0);
3811 err = log_move_cursor_down(view, s->commits->ncommits);
3812 s->thread_args.load_all = 0;
3813 break;
3815 case CTRL('d'):
3816 case 'd':
3817 nscroll /= 2;
3818 /* FALL THROUGH */
3819 case KEY_NPAGE:
3820 case CTRL('f'):
3821 case 'f':
3822 case ' ':
3823 err = log_move_cursor_down(view, nscroll);
3824 break;
3825 case KEY_RESIZE:
3826 if (s->selected > view->nlines - 2)
3827 s->selected = view->nlines - 2;
3828 if (s->selected > s->commits->ncommits - 1)
3829 s->selected = s->commits->ncommits - 1;
3830 select_commit(s);
3831 if (s->commits->ncommits < view->nlines - 1 &&
3832 !s->thread_args.log_complete) {
3833 s->thread_args.commits_needed += (view->nlines - 1) -
3834 s->commits->ncommits;
3835 err = trigger_log_thread(view, 1);
3837 break;
3838 case KEY_ENTER:
3839 case '\r':
3840 view->count = 0;
3841 if (s->selected_entry == NULL)
3842 break;
3843 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3844 break;
3845 case 'T':
3846 view->count = 0;
3847 if (s->selected_entry == NULL)
3848 break;
3849 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3850 break;
3851 case KEY_BACKSPACE:
3852 case CTRL('l'):
3853 case 'B':
3854 view->count = 0;
3855 if (ch == KEY_BACKSPACE &&
3856 got_path_is_root_dir(s->in_repo_path))
3857 break;
3858 err = stop_log_thread(s);
3859 if (err)
3860 return err;
3861 if (ch == KEY_BACKSPACE) {
3862 char *parent_path;
3863 err = got_path_dirname(&parent_path, s->in_repo_path);
3864 if (err)
3865 return err;
3866 free(s->in_repo_path);
3867 s->in_repo_path = parent_path;
3868 s->thread_args.in_repo_path = s->in_repo_path;
3869 } else if (ch == CTRL('l')) {
3870 struct got_object_id *start_id;
3871 err = got_repo_match_object_id(&start_id, NULL,
3872 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3873 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3874 if (err) {
3875 if (s->head_ref_name == NULL ||
3876 err->code != GOT_ERR_NOT_REF)
3877 return err;
3878 /* Try to cope with deleted references. */
3879 free(s->head_ref_name);
3880 s->head_ref_name = NULL;
3881 err = got_repo_match_object_id(&start_id,
3882 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
3883 &tog_refs, s->repo);
3884 if (err)
3885 return err;
3887 free(s->start_id);
3888 s->start_id = start_id;
3889 s->thread_args.start_id = s->start_id;
3890 } else /* 'B' */
3891 s->log_branches = !s->log_branches;
3893 if (s->thread_args.pack_fds == NULL) {
3894 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3895 if (err)
3896 return err;
3898 err = got_repo_open(&s->thread_args.repo,
3899 got_repo_get_path(s->repo), NULL,
3900 s->thread_args.pack_fds);
3901 if (err)
3902 return err;
3903 tog_free_refs();
3904 err = tog_load_refs(s->repo, 0);
3905 if (err)
3906 return err;
3907 err = got_commit_graph_open(&s->thread_args.graph,
3908 s->in_repo_path, !s->log_branches);
3909 if (err)
3910 return err;
3911 err = got_commit_graph_iter_start(s->thread_args.graph,
3912 s->start_id, s->repo, NULL, NULL);
3913 if (err)
3914 return err;
3915 free_commits(&s->real_commits);
3916 free_commits(&s->limit_commits);
3917 s->first_displayed_entry = NULL;
3918 s->last_displayed_entry = NULL;
3919 s->selected_entry = NULL;
3920 s->selected = 0;
3921 s->thread_args.log_complete = 0;
3922 s->quit = 0;
3923 s->thread_args.commits_needed = view->lines;
3924 s->matched_entry = NULL;
3925 s->search_entry = NULL;
3926 view->offset = 0;
3927 break;
3928 case 'R':
3929 view->count = 0;
3930 err = view_request_new(new_view, view, TOG_VIEW_REF);
3931 break;
3932 default:
3933 view->count = 0;
3934 break;
3937 return err;
3940 static const struct got_error *
3941 apply_unveil(const char *repo_path, const char *worktree_path)
3943 const struct got_error *error;
3945 #ifdef PROFILE
3946 if (unveil("gmon.out", "rwc") != 0)
3947 return got_error_from_errno2("unveil", "gmon.out");
3948 #endif
3949 if (repo_path && unveil(repo_path, "r") != 0)
3950 return got_error_from_errno2("unveil", repo_path);
3952 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3953 return got_error_from_errno2("unveil", worktree_path);
3955 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3956 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3958 error = got_privsep_unveil_exec_helpers();
3959 if (error != NULL)
3960 return error;
3962 if (unveil(NULL, NULL) != 0)
3963 return got_error_from_errno("unveil");
3965 return NULL;
3968 static void
3969 init_curses(void)
3972 * Override default signal handlers before starting ncurses.
3973 * This should prevent ncurses from installing its own
3974 * broken cleanup() signal handler.
3976 signal(SIGWINCH, tog_sigwinch);
3977 signal(SIGPIPE, tog_sigpipe);
3978 signal(SIGCONT, tog_sigcont);
3979 signal(SIGINT, tog_sigint);
3980 signal(SIGTERM, tog_sigterm);
3982 initscr();
3983 cbreak();
3984 halfdelay(1); /* Do fast refresh while initial view is loading. */
3985 noecho();
3986 nonl();
3987 intrflush(stdscr, FALSE);
3988 keypad(stdscr, TRUE);
3989 curs_set(0);
3990 if (getenv("TOG_COLORS") != NULL) {
3991 start_color();
3992 use_default_colors();
3996 static const struct got_error *
3997 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3998 struct got_repository *repo, struct got_worktree *worktree)
4000 const struct got_error *err = NULL;
4002 if (argc == 0) {
4003 *in_repo_path = strdup("/");
4004 if (*in_repo_path == NULL)
4005 return got_error_from_errno("strdup");
4006 return NULL;
4009 if (worktree) {
4010 const char *prefix = got_worktree_get_path_prefix(worktree);
4011 char *p;
4013 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4014 if (err)
4015 return err;
4016 if (asprintf(in_repo_path, "%s%s%s", prefix,
4017 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4018 p) == -1) {
4019 err = got_error_from_errno("asprintf");
4020 *in_repo_path = NULL;
4022 free(p);
4023 } else
4024 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4026 return err;
4029 static const struct got_error *
4030 cmd_log(int argc, char *argv[])
4032 const struct got_error *error;
4033 struct got_repository *repo = NULL;
4034 struct got_worktree *worktree = NULL;
4035 struct got_object_id *start_id = NULL;
4036 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4037 char *start_commit = NULL, *label = NULL;
4038 struct got_reference *ref = NULL;
4039 const char *head_ref_name = NULL;
4040 int ch, log_branches = 0;
4041 struct tog_view *view;
4042 int *pack_fds = NULL;
4044 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4045 switch (ch) {
4046 case 'b':
4047 log_branches = 1;
4048 break;
4049 case 'c':
4050 start_commit = optarg;
4051 break;
4052 case 'r':
4053 repo_path = realpath(optarg, NULL);
4054 if (repo_path == NULL)
4055 return got_error_from_errno2("realpath",
4056 optarg);
4057 break;
4058 default:
4059 usage_log();
4060 /* NOTREACHED */
4064 argc -= optind;
4065 argv += optind;
4067 if (argc > 1)
4068 usage_log();
4070 error = got_repo_pack_fds_open(&pack_fds);
4071 if (error != NULL)
4072 goto done;
4074 if (repo_path == NULL) {
4075 cwd = getcwd(NULL, 0);
4076 if (cwd == NULL)
4077 return got_error_from_errno("getcwd");
4078 error = got_worktree_open(&worktree, cwd);
4079 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4080 goto done;
4081 if (worktree)
4082 repo_path =
4083 strdup(got_worktree_get_repo_path(worktree));
4084 else
4085 repo_path = strdup(cwd);
4086 if (repo_path == NULL) {
4087 error = got_error_from_errno("strdup");
4088 goto done;
4092 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4093 if (error != NULL)
4094 goto done;
4096 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4097 repo, worktree);
4098 if (error)
4099 goto done;
4101 init_curses();
4103 error = apply_unveil(got_repo_get_path(repo),
4104 worktree ? got_worktree_get_root_path(worktree) : NULL);
4105 if (error)
4106 goto done;
4108 /* already loaded by tog_log_with_path()? */
4109 if (TAILQ_EMPTY(&tog_refs)) {
4110 error = tog_load_refs(repo, 0);
4111 if (error)
4112 goto done;
4115 if (start_commit == NULL) {
4116 error = got_repo_match_object_id(&start_id, &label,
4117 worktree ? got_worktree_get_head_ref_name(worktree) :
4118 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4119 if (error)
4120 goto done;
4121 head_ref_name = label;
4122 } else {
4123 error = got_ref_open(&ref, repo, start_commit, 0);
4124 if (error == NULL)
4125 head_ref_name = got_ref_get_name(ref);
4126 else if (error->code != GOT_ERR_NOT_REF)
4127 goto done;
4128 error = got_repo_match_object_id(&start_id, NULL,
4129 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4130 if (error)
4131 goto done;
4134 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4135 if (view == NULL) {
4136 error = got_error_from_errno("view_open");
4137 goto done;
4139 error = open_log_view(view, start_id, repo, head_ref_name,
4140 in_repo_path, log_branches);
4141 if (error)
4142 goto done;
4143 if (worktree) {
4144 /* Release work tree lock. */
4145 got_worktree_close(worktree);
4146 worktree = NULL;
4148 error = view_loop(view);
4149 done:
4150 free(in_repo_path);
4151 free(repo_path);
4152 free(cwd);
4153 free(start_id);
4154 free(label);
4155 if (ref)
4156 got_ref_close(ref);
4157 if (repo) {
4158 const struct got_error *close_err = got_repo_close(repo);
4159 if (error == NULL)
4160 error = close_err;
4162 if (worktree)
4163 got_worktree_close(worktree);
4164 if (pack_fds) {
4165 const struct got_error *pack_err =
4166 got_repo_pack_fds_close(pack_fds);
4167 if (error == NULL)
4168 error = pack_err;
4170 tog_free_refs();
4171 return error;
4174 __dead static void
4175 usage_diff(void)
4177 endwin();
4178 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4179 "object1 object2\n", getprogname());
4180 exit(1);
4183 static int
4184 match_line(const char *line, regex_t *regex, size_t nmatch,
4185 regmatch_t *regmatch)
4187 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4190 static struct tog_color *
4191 match_color(struct tog_colors *colors, const char *line)
4193 struct tog_color *tc = NULL;
4195 STAILQ_FOREACH(tc, colors, entry) {
4196 if (match_line(line, &tc->regex, 0, NULL))
4197 return tc;
4200 return NULL;
4203 static const struct got_error *
4204 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4205 WINDOW *window, int skipcol, regmatch_t *regmatch)
4207 const struct got_error *err = NULL;
4208 char *exstr = NULL;
4209 wchar_t *wline = NULL;
4210 int rme, rms, n, width, scrollx;
4211 int width0 = 0, width1 = 0, width2 = 0;
4212 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4214 *wtotal = 0;
4216 rms = regmatch->rm_so;
4217 rme = regmatch->rm_eo;
4219 err = expand_tab(&exstr, line);
4220 if (err)
4221 return err;
4223 /* Split the line into 3 segments, according to match offsets. */
4224 seg0 = strndup(exstr, rms);
4225 if (seg0 == NULL) {
4226 err = got_error_from_errno("strndup");
4227 goto done;
4229 seg1 = strndup(exstr + rms, rme - rms);
4230 if (seg1 == NULL) {
4231 err = got_error_from_errno("strndup");
4232 goto done;
4234 seg2 = strdup(exstr + rme);
4235 if (seg2 == NULL) {
4236 err = got_error_from_errno("strndup");
4237 goto done;
4240 /* draw up to matched token if we haven't scrolled past it */
4241 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4242 col_tab_align, 1);
4243 if (err)
4244 goto done;
4245 n = MAX(width0 - skipcol, 0);
4246 if (n) {
4247 free(wline);
4248 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4249 wlimit, col_tab_align, 1);
4250 if (err)
4251 goto done;
4252 waddwstr(window, &wline[scrollx]);
4253 wlimit -= width;
4254 *wtotal += width;
4257 if (wlimit > 0) {
4258 int i = 0, w = 0;
4259 size_t wlen;
4261 free(wline);
4262 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4263 col_tab_align, 1);
4264 if (err)
4265 goto done;
4266 wlen = wcslen(wline);
4267 while (i < wlen) {
4268 width = wcwidth(wline[i]);
4269 if (width == -1) {
4270 /* should not happen, tabs are expanded */
4271 err = got_error(GOT_ERR_RANGE);
4272 goto done;
4274 if (width0 + w + width > skipcol)
4275 break;
4276 w += width;
4277 i++;
4279 /* draw (visible part of) matched token (if scrolled into it) */
4280 if (width1 - w > 0) {
4281 wattron(window, A_STANDOUT);
4282 waddwstr(window, &wline[i]);
4283 wattroff(window, A_STANDOUT);
4284 wlimit -= (width1 - w);
4285 *wtotal += (width1 - w);
4289 if (wlimit > 0) { /* draw rest of line */
4290 free(wline);
4291 if (skipcol > width0 + width1) {
4292 err = format_line(&wline, &width2, &scrollx, seg2,
4293 skipcol - (width0 + width1), wlimit,
4294 col_tab_align, 1);
4295 if (err)
4296 goto done;
4297 waddwstr(window, &wline[scrollx]);
4298 } else {
4299 err = format_line(&wline, &width2, NULL, seg2, 0,
4300 wlimit, col_tab_align, 1);
4301 if (err)
4302 goto done;
4303 waddwstr(window, wline);
4305 *wtotal += width2;
4307 done:
4308 free(wline);
4309 free(exstr);
4310 free(seg0);
4311 free(seg1);
4312 free(seg2);
4313 return err;
4316 static int
4317 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4319 FILE *f = NULL;
4320 int *eof, *first, *selected;
4322 if (view->type == TOG_VIEW_DIFF) {
4323 struct tog_diff_view_state *s = &view->state.diff;
4325 first = &s->first_displayed_line;
4326 selected = first;
4327 eof = &s->eof;
4328 f = s->f;
4329 } else if (view->type == TOG_VIEW_HELP) {
4330 struct tog_help_view_state *s = &view->state.help;
4332 first = &s->first_displayed_line;
4333 selected = first;
4334 eof = &s->eof;
4335 f = s->f;
4336 } else if (view->type == TOG_VIEW_BLAME) {
4337 struct tog_blame_view_state *s = &view->state.blame;
4339 first = &s->first_displayed_line;
4340 selected = &s->selected_line;
4341 eof = &s->eof;
4342 f = s->blame.f;
4343 } else
4344 return 0;
4346 /* Center gline in the middle of the page like vi(1). */
4347 if (*lineno < view->gline - (view->nlines - 3) / 2)
4348 return 0;
4349 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4350 rewind(f);
4351 *eof = 0;
4352 *first = 1;
4353 *lineno = 0;
4354 *nprinted = 0;
4355 return 0;
4358 *selected = view->gline <= (view->nlines - 3) / 2 ?
4359 view->gline : (view->nlines - 3) / 2 + 1;
4360 view->gline = 0;
4362 return 1;
4365 static const struct got_error *
4366 draw_file(struct tog_view *view, const char *header)
4368 struct tog_diff_view_state *s = &view->state.diff;
4369 regmatch_t *regmatch = &view->regmatch;
4370 const struct got_error *err;
4371 int nprinted = 0;
4372 char *line;
4373 size_t linesize = 0;
4374 ssize_t linelen;
4375 wchar_t *wline;
4376 int width;
4377 int max_lines = view->nlines;
4378 int nlines = s->nlines;
4379 off_t line_offset;
4381 s->lineno = s->first_displayed_line - 1;
4382 line_offset = s->lines[s->first_displayed_line - 1].offset;
4383 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4384 return got_error_from_errno("fseek");
4386 werase(view->window);
4388 if (view->gline > s->nlines - 1)
4389 view->gline = s->nlines - 1;
4391 if (header) {
4392 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4393 1 : view->gline - (view->nlines - 3) / 2 :
4394 s->lineno + s->selected_line;
4396 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4397 return got_error_from_errno("asprintf");
4398 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4399 0, 0);
4400 free(line);
4401 if (err)
4402 return err;
4404 if (view_needs_focus_indication(view))
4405 wstandout(view->window);
4406 waddwstr(view->window, wline);
4407 free(wline);
4408 wline = NULL;
4409 while (width++ < view->ncols)
4410 waddch(view->window, ' ');
4411 if (view_needs_focus_indication(view))
4412 wstandend(view->window);
4414 if (max_lines <= 1)
4415 return NULL;
4416 max_lines--;
4419 s->eof = 0;
4420 view->maxx = 0;
4421 line = NULL;
4422 while (max_lines > 0 && nprinted < max_lines) {
4423 enum got_diff_line_type linetype;
4424 attr_t attr = 0;
4426 linelen = getline(&line, &linesize, s->f);
4427 if (linelen == -1) {
4428 if (feof(s->f)) {
4429 s->eof = 1;
4430 break;
4432 free(line);
4433 return got_ferror(s->f, GOT_ERR_IO);
4436 if (++s->lineno < s->first_displayed_line)
4437 continue;
4438 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4439 continue;
4440 if (s->lineno == view->hiline)
4441 attr = A_STANDOUT;
4443 /* Set view->maxx based on full line length. */
4444 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4445 view->x ? 1 : 0);
4446 if (err) {
4447 free(line);
4448 return err;
4450 view->maxx = MAX(view->maxx, width);
4451 free(wline);
4452 wline = NULL;
4454 linetype = s->lines[s->lineno].type;
4455 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4456 linetype < GOT_DIFF_LINE_CONTEXT)
4457 attr |= COLOR_PAIR(linetype);
4458 if (attr)
4459 wattron(view->window, attr);
4460 if (s->first_displayed_line + nprinted == s->matched_line &&
4461 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4462 err = add_matched_line(&width, line, view->ncols, 0,
4463 view->window, view->x, regmatch);
4464 if (err) {
4465 free(line);
4466 return err;
4468 } else {
4469 int skip;
4470 err = format_line(&wline, &width, &skip, line,
4471 view->x, view->ncols, 0, view->x ? 1 : 0);
4472 if (err) {
4473 free(line);
4474 return err;
4476 waddwstr(view->window, &wline[skip]);
4477 free(wline);
4478 wline = NULL;
4480 if (s->lineno == view->hiline) {
4481 /* highlight full gline length */
4482 while (width++ < view->ncols)
4483 waddch(view->window, ' ');
4484 } else {
4485 if (width <= view->ncols - 1)
4486 waddch(view->window, '\n');
4488 if (attr)
4489 wattroff(view->window, attr);
4490 if (++nprinted == 1)
4491 s->first_displayed_line = s->lineno;
4493 free(line);
4494 if (nprinted >= 1)
4495 s->last_displayed_line = s->first_displayed_line +
4496 (nprinted - 1);
4497 else
4498 s->last_displayed_line = s->first_displayed_line;
4500 view_border(view);
4502 if (s->eof) {
4503 while (nprinted < view->nlines) {
4504 waddch(view->window, '\n');
4505 nprinted++;
4508 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4509 view->ncols, 0, 0);
4510 if (err) {
4511 return err;
4514 wstandout(view->window);
4515 waddwstr(view->window, wline);
4516 free(wline);
4517 wline = NULL;
4518 wstandend(view->window);
4521 return NULL;
4524 static char *
4525 get_datestr(time_t *time, char *datebuf)
4527 struct tm mytm, *tm;
4528 char *p, *s;
4530 tm = gmtime_r(time, &mytm);
4531 if (tm == NULL)
4532 return NULL;
4533 s = asctime_r(tm, datebuf);
4534 if (s == NULL)
4535 return NULL;
4536 p = strchr(s, '\n');
4537 if (p)
4538 *p = '\0';
4539 return s;
4542 static const struct got_error *
4543 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4544 off_t off, uint8_t type)
4546 struct got_diff_line *p;
4548 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4549 if (p == NULL)
4550 return got_error_from_errno("reallocarray");
4551 *lines = p;
4552 (*lines)[*nlines].offset = off;
4553 (*lines)[*nlines].type = type;
4554 (*nlines)++;
4556 return NULL;
4559 static const struct got_error *
4560 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4561 struct got_diff_line *s_lines, size_t s_nlines)
4563 struct got_diff_line *p;
4564 char buf[BUFSIZ];
4565 size_t i, r;
4567 if (fseeko(src, 0L, SEEK_SET) == -1)
4568 return got_error_from_errno("fseeko");
4570 for (;;) {
4571 r = fread(buf, 1, sizeof(buf), src);
4572 if (r == 0) {
4573 if (ferror(src))
4574 return got_error_from_errno("fread");
4575 if (feof(src))
4576 break;
4578 if (fwrite(buf, 1, r, dst) != r)
4579 return got_ferror(dst, GOT_ERR_IO);
4583 * The diff driver initialises the first line at offset zero when the
4584 * array isn't prepopulated, skip it; we already have it in *d_lines.
4586 for (i = 1; i < s_nlines; ++i)
4587 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4589 --s_nlines;
4591 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4592 if (p == NULL) {
4593 /* d_lines is freed in close_diff_view() */
4594 return got_error_from_errno("reallocarray");
4597 *d_lines = p;
4599 memcpy(*d_lines + *d_nlines, s_lines + 1, s_nlines * sizeof(*s_lines));
4600 *d_nlines += s_nlines;
4602 return NULL;
4605 static const struct got_error *
4606 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4607 struct got_object_id *commit_id, struct got_reflist_head *refs,
4608 struct got_repository *repo, int ignore_ws, int force_text_diff,
4609 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4611 const struct got_error *err = NULL;
4612 char datebuf[26], *datestr;
4613 struct got_commit_object *commit;
4614 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4615 time_t committer_time;
4616 const char *author, *committer;
4617 char *refs_str = NULL;
4618 struct got_pathlist_entry *pe;
4619 off_t outoff = 0;
4620 int n;
4622 if (refs) {
4623 err = build_refs_str(&refs_str, refs, commit_id, repo);
4624 if (err)
4625 return err;
4628 err = got_object_open_as_commit(&commit, repo, commit_id);
4629 if (err)
4630 return err;
4632 err = got_object_id_str(&id_str, commit_id);
4633 if (err) {
4634 err = got_error_from_errno("got_object_id_str");
4635 goto done;
4638 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4639 if (err)
4640 goto done;
4642 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4643 refs_str ? refs_str : "", refs_str ? ")" : "");
4644 if (n < 0) {
4645 err = got_error_from_errno("fprintf");
4646 goto done;
4648 outoff += n;
4649 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4650 if (err)
4651 goto done;
4653 n = fprintf(outfile, "from: %s\n",
4654 got_object_commit_get_author(commit));
4655 if (n < 0) {
4656 err = got_error_from_errno("fprintf");
4657 goto done;
4659 outoff += n;
4660 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4661 if (err)
4662 goto done;
4664 author = got_object_commit_get_author(commit);
4665 committer = got_object_commit_get_committer(commit);
4666 if (strcmp(author, committer) != 0) {
4667 n = fprintf(outfile, "via: %s\n", committer);
4668 if (n < 0) {
4669 err = got_error_from_errno("fprintf");
4670 goto done;
4672 outoff += n;
4673 err = add_line_metadata(lines, nlines, outoff,
4674 GOT_DIFF_LINE_AUTHOR);
4675 if (err)
4676 goto done;
4678 committer_time = got_object_commit_get_committer_time(commit);
4679 datestr = get_datestr(&committer_time, datebuf);
4680 if (datestr) {
4681 n = fprintf(outfile, "date: %s UTC\n", datestr);
4682 if (n < 0) {
4683 err = got_error_from_errno("fprintf");
4684 goto done;
4686 outoff += n;
4687 err = add_line_metadata(lines, nlines, outoff,
4688 GOT_DIFF_LINE_DATE);
4689 if (err)
4690 goto done;
4692 if (got_object_commit_get_nparents(commit) > 1) {
4693 const struct got_object_id_queue *parent_ids;
4694 struct got_object_qid *qid;
4695 int pn = 1;
4696 parent_ids = got_object_commit_get_parent_ids(commit);
4697 STAILQ_FOREACH(qid, parent_ids, entry) {
4698 err = got_object_id_str(&id_str, &qid->id);
4699 if (err)
4700 goto done;
4701 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4702 if (n < 0) {
4703 err = got_error_from_errno("fprintf");
4704 goto done;
4706 outoff += n;
4707 err = add_line_metadata(lines, nlines, outoff,
4708 GOT_DIFF_LINE_META);
4709 if (err)
4710 goto done;
4711 free(id_str);
4712 id_str = NULL;
4716 err = got_object_commit_get_logmsg(&logmsg, commit);
4717 if (err)
4718 goto done;
4719 s = logmsg;
4720 while ((line = strsep(&s, "\n")) != NULL) {
4721 n = fprintf(outfile, "%s\n", line);
4722 if (n < 0) {
4723 err = got_error_from_errno("fprintf");
4724 goto done;
4726 outoff += n;
4727 err = add_line_metadata(lines, nlines, outoff,
4728 GOT_DIFF_LINE_LOGMSG);
4729 if (err)
4730 goto done;
4733 TAILQ_FOREACH(pe, dsa->paths, entry) {
4734 struct got_diff_changed_path *cp = pe->data;
4735 int pad = dsa->max_path_len - pe->path_len + 1;
4737 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4738 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4739 dsa->rm_cols + 1, cp->rm);
4740 if (n < 0) {
4741 err = got_error_from_errno("fprintf");
4742 goto done;
4744 outoff += n;
4745 err = add_line_metadata(lines, nlines, outoff,
4746 GOT_DIFF_LINE_CHANGES);
4747 if (err)
4748 goto done;
4751 fputc('\n', outfile);
4752 outoff++;
4753 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4754 if (err)
4755 goto done;
4757 n = fprintf(outfile,
4758 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4759 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4760 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4761 if (n < 0) {
4762 err = got_error_from_errno("fprintf");
4763 goto done;
4765 outoff += n;
4766 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4767 if (err)
4768 goto done;
4770 fputc('\n', outfile);
4771 outoff++;
4772 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4773 done:
4774 free(id_str);
4775 free(logmsg);
4776 free(refs_str);
4777 got_object_commit_close(commit);
4778 if (err) {
4779 free(*lines);
4780 *lines = NULL;
4781 *nlines = 0;
4783 return err;
4786 static const struct got_error *
4787 create_diff(struct tog_diff_view_state *s)
4789 const struct got_error *err = NULL;
4790 FILE *f = NULL, *tmp_diff_file = NULL;
4791 int obj_type;
4792 struct got_diff_line *lines = NULL;
4793 struct got_pathlist_head changed_paths;
4795 TAILQ_INIT(&changed_paths);
4797 free(s->lines);
4798 s->lines = malloc(sizeof(*s->lines));
4799 if (s->lines == NULL)
4800 return got_error_from_errno("malloc");
4801 s->nlines = 0;
4803 f = got_opentemp();
4804 if (f == NULL) {
4805 err = got_error_from_errno("got_opentemp");
4806 goto done;
4808 tmp_diff_file = got_opentemp();
4809 if (tmp_diff_file == NULL) {
4810 err = got_error_from_errno("got_opentemp");
4811 goto done;
4813 if (s->f && fclose(s->f) == EOF) {
4814 err = got_error_from_errno("fclose");
4815 goto done;
4817 s->f = f;
4819 if (s->id1)
4820 err = got_object_get_type(&obj_type, s->repo, s->id1);
4821 else
4822 err = got_object_get_type(&obj_type, s->repo, s->id2);
4823 if (err)
4824 goto done;
4826 switch (obj_type) {
4827 case GOT_OBJ_TYPE_BLOB:
4828 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4829 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4830 s->label1, s->label2, tog_diff_algo, s->diff_context,
4831 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
4832 s->f);
4833 break;
4834 case GOT_OBJ_TYPE_TREE:
4835 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4836 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4837 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4838 s->force_text_diff, NULL, s->repo, s->f);
4839 break;
4840 case GOT_OBJ_TYPE_COMMIT: {
4841 const struct got_object_id_queue *parent_ids;
4842 struct got_object_qid *pid;
4843 struct got_commit_object *commit2;
4844 struct got_reflist_head *refs;
4845 size_t nlines = 0;
4846 struct got_diffstat_cb_arg dsa = {
4847 0, 0, 0, 0, 0, 0,
4848 &changed_paths,
4849 s->ignore_whitespace,
4850 s->force_text_diff,
4851 tog_diff_algo
4854 lines = malloc(sizeof(*lines));
4855 if (lines == NULL) {
4856 err = got_error_from_errno("malloc");
4857 goto done;
4860 /* build diff first in tmp file then append to commit info */
4861 err = got_diff_objects_as_commits(&lines, &nlines,
4862 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4863 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4864 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
4865 if (err)
4866 break;
4868 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4869 if (err)
4870 goto done;
4871 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4872 /* Show commit info if we're diffing to a parent/root commit. */
4873 if (s->id1 == NULL) {
4874 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4875 refs, s->repo, s->ignore_whitespace,
4876 s->force_text_diff, &dsa, s->f);
4877 if (err)
4878 goto done;
4879 } else {
4880 parent_ids = got_object_commit_get_parent_ids(commit2);
4881 STAILQ_FOREACH(pid, parent_ids, entry) {
4882 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4883 err = write_commit_info(&s->lines,
4884 &s->nlines, s->id2, refs, s->repo,
4885 s->ignore_whitespace,
4886 s->force_text_diff, &dsa, s->f);
4887 if (err)
4888 goto done;
4889 break;
4893 got_object_commit_close(commit2);
4895 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
4896 lines, nlines);
4897 break;
4899 default:
4900 err = got_error(GOT_ERR_OBJ_TYPE);
4901 break;
4903 done:
4904 free(lines);
4905 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4906 if (s->f && fflush(s->f) != 0 && err == NULL)
4907 err = got_error_from_errno("fflush");
4908 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
4909 err = got_error_from_errno("fclose");
4910 return err;
4913 static void
4914 diff_view_indicate_progress(struct tog_view *view)
4916 mvwaddstr(view->window, 0, 0, "diffing...");
4917 update_panels();
4918 doupdate();
4921 static const struct got_error *
4922 search_start_diff_view(struct tog_view *view)
4924 struct tog_diff_view_state *s = &view->state.diff;
4926 s->matched_line = 0;
4927 return NULL;
4930 static void
4931 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4932 size_t *nlines, int **first, int **last, int **match, int **selected)
4934 struct tog_diff_view_state *s = &view->state.diff;
4936 *f = s->f;
4937 *nlines = s->nlines;
4938 *line_offsets = NULL;
4939 *match = &s->matched_line;
4940 *first = &s->first_displayed_line;
4941 *last = &s->last_displayed_line;
4942 *selected = &s->selected_line;
4945 static const struct got_error *
4946 search_next_view_match(struct tog_view *view)
4948 const struct got_error *err = NULL;
4949 FILE *f;
4950 int lineno;
4951 char *line = NULL;
4952 size_t linesize = 0;
4953 ssize_t linelen;
4954 off_t *line_offsets;
4955 size_t nlines = 0;
4956 int *first, *last, *match, *selected;
4958 if (!view->search_setup)
4959 return got_error_msg(GOT_ERR_NOT_IMPL,
4960 "view search not supported");
4961 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4962 &match, &selected);
4964 if (!view->searching) {
4965 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4966 return NULL;
4969 if (*match) {
4970 if (view->searching == TOG_SEARCH_FORWARD)
4971 lineno = *match + 1;
4972 else
4973 lineno = *match - 1;
4974 } else
4975 lineno = *first - 1 + *selected;
4977 while (1) {
4978 off_t offset;
4980 if (lineno <= 0 || lineno > nlines) {
4981 if (*match == 0) {
4982 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4983 break;
4986 if (view->searching == TOG_SEARCH_FORWARD)
4987 lineno = 1;
4988 else
4989 lineno = nlines;
4992 offset = view->type == TOG_VIEW_DIFF ?
4993 view->state.diff.lines[lineno - 1].offset :
4994 line_offsets[lineno - 1];
4995 if (fseeko(f, offset, SEEK_SET) != 0) {
4996 free(line);
4997 return got_error_from_errno("fseeko");
4999 linelen = getline(&line, &linesize, f);
5000 if (linelen != -1) {
5001 char *exstr;
5002 err = expand_tab(&exstr, line);
5003 if (err)
5004 break;
5005 if (match_line(exstr, &view->regex, 1,
5006 &view->regmatch)) {
5007 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5008 *match = lineno;
5009 free(exstr);
5010 break;
5012 free(exstr);
5014 if (view->searching == TOG_SEARCH_FORWARD)
5015 lineno++;
5016 else
5017 lineno--;
5019 free(line);
5021 if (*match) {
5022 *first = *match;
5023 *selected = 1;
5026 return err;
5029 static const struct got_error *
5030 close_diff_view(struct tog_view *view)
5032 const struct got_error *err = NULL;
5033 struct tog_diff_view_state *s = &view->state.diff;
5035 free(s->id1);
5036 s->id1 = NULL;
5037 free(s->id2);
5038 s->id2 = NULL;
5039 if (s->f && fclose(s->f) == EOF)
5040 err = got_error_from_errno("fclose");
5041 s->f = NULL;
5042 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5043 err = got_error_from_errno("fclose");
5044 s->f1 = NULL;
5045 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5046 err = got_error_from_errno("fclose");
5047 s->f2 = NULL;
5048 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5049 err = got_error_from_errno("close");
5050 s->fd1 = -1;
5051 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5052 err = got_error_from_errno("close");
5053 s->fd2 = -1;
5054 free(s->lines);
5055 s->lines = NULL;
5056 s->nlines = 0;
5057 return err;
5060 static const struct got_error *
5061 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5062 struct got_object_id *id2, const char *label1, const char *label2,
5063 int diff_context, int ignore_whitespace, int force_text_diff,
5064 struct tog_view *parent_view, struct got_repository *repo)
5066 const struct got_error *err;
5067 struct tog_diff_view_state *s = &view->state.diff;
5069 memset(s, 0, sizeof(*s));
5070 s->fd1 = -1;
5071 s->fd2 = -1;
5073 if (id1 != NULL && id2 != NULL) {
5074 int type1, type2;
5075 err = got_object_get_type(&type1, repo, id1);
5076 if (err)
5077 return err;
5078 err = got_object_get_type(&type2, repo, id2);
5079 if (err)
5080 return err;
5082 if (type1 != type2)
5083 return got_error(GOT_ERR_OBJ_TYPE);
5085 s->first_displayed_line = 1;
5086 s->last_displayed_line = view->nlines;
5087 s->selected_line = 1;
5088 s->repo = repo;
5089 s->id1 = id1;
5090 s->id2 = id2;
5091 s->label1 = label1;
5092 s->label2 = label2;
5094 if (id1) {
5095 s->id1 = got_object_id_dup(id1);
5096 if (s->id1 == NULL)
5097 return got_error_from_errno("got_object_id_dup");
5098 } else
5099 s->id1 = NULL;
5101 s->id2 = got_object_id_dup(id2);
5102 if (s->id2 == NULL) {
5103 err = got_error_from_errno("got_object_id_dup");
5104 goto done;
5107 s->f1 = got_opentemp();
5108 if (s->f1 == NULL) {
5109 err = got_error_from_errno("got_opentemp");
5110 goto done;
5113 s->f2 = got_opentemp();
5114 if (s->f2 == NULL) {
5115 err = got_error_from_errno("got_opentemp");
5116 goto done;
5119 s->fd1 = got_opentempfd();
5120 if (s->fd1 == -1) {
5121 err = got_error_from_errno("got_opentempfd");
5122 goto done;
5125 s->fd2 = got_opentempfd();
5126 if (s->fd2 == -1) {
5127 err = got_error_from_errno("got_opentempfd");
5128 goto done;
5131 s->diff_context = diff_context;
5132 s->ignore_whitespace = ignore_whitespace;
5133 s->force_text_diff = force_text_diff;
5134 s->parent_view = parent_view;
5135 s->repo = repo;
5137 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5138 int rc;
5140 rc = init_pair(GOT_DIFF_LINE_MINUS,
5141 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5142 if (rc != ERR)
5143 rc = init_pair(GOT_DIFF_LINE_PLUS,
5144 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5145 if (rc != ERR)
5146 rc = init_pair(GOT_DIFF_LINE_HUNK,
5147 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5148 if (rc != ERR)
5149 rc = init_pair(GOT_DIFF_LINE_META,
5150 get_color_value("TOG_COLOR_DIFF_META"), -1);
5151 if (rc != ERR)
5152 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5153 get_color_value("TOG_COLOR_DIFF_META"), -1);
5154 if (rc != ERR)
5155 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5156 get_color_value("TOG_COLOR_DIFF_META"), -1);
5157 if (rc != ERR)
5158 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5159 get_color_value("TOG_COLOR_DIFF_META"), -1);
5160 if (rc != ERR)
5161 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5162 get_color_value("TOG_COLOR_AUTHOR"), -1);
5163 if (rc != ERR)
5164 rc = init_pair(GOT_DIFF_LINE_DATE,
5165 get_color_value("TOG_COLOR_DATE"), -1);
5166 if (rc == ERR) {
5167 err = got_error(GOT_ERR_RANGE);
5168 goto done;
5172 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5173 view_is_splitscreen(view))
5174 show_log_view(parent_view); /* draw border */
5175 diff_view_indicate_progress(view);
5177 err = create_diff(s);
5179 view->show = show_diff_view;
5180 view->input = input_diff_view;
5181 view->reset = reset_diff_view;
5182 view->close = close_diff_view;
5183 view->search_start = search_start_diff_view;
5184 view->search_setup = search_setup_diff_view;
5185 view->search_next = search_next_view_match;
5186 done:
5187 if (err)
5188 close_diff_view(view);
5189 return err;
5192 static const struct got_error *
5193 show_diff_view(struct tog_view *view)
5195 const struct got_error *err;
5196 struct tog_diff_view_state *s = &view->state.diff;
5197 char *id_str1 = NULL, *id_str2, *header;
5198 const char *label1, *label2;
5200 if (s->id1) {
5201 err = got_object_id_str(&id_str1, s->id1);
5202 if (err)
5203 return err;
5204 label1 = s->label1 ? s->label1 : id_str1;
5205 } else
5206 label1 = "/dev/null";
5208 err = got_object_id_str(&id_str2, s->id2);
5209 if (err)
5210 return err;
5211 label2 = s->label2 ? s->label2 : id_str2;
5213 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5214 err = got_error_from_errno("asprintf");
5215 free(id_str1);
5216 free(id_str2);
5217 return err;
5219 free(id_str1);
5220 free(id_str2);
5222 err = draw_file(view, header);
5223 free(header);
5224 return err;
5227 static const struct got_error *
5228 set_selected_commit(struct tog_diff_view_state *s,
5229 struct commit_queue_entry *entry)
5231 const struct got_error *err;
5232 const struct got_object_id_queue *parent_ids;
5233 struct got_commit_object *selected_commit;
5234 struct got_object_qid *pid;
5236 free(s->id2);
5237 s->id2 = got_object_id_dup(entry->id);
5238 if (s->id2 == NULL)
5239 return got_error_from_errno("got_object_id_dup");
5241 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5242 if (err)
5243 return err;
5244 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5245 free(s->id1);
5246 pid = STAILQ_FIRST(parent_ids);
5247 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5248 got_object_commit_close(selected_commit);
5249 return NULL;
5252 static const struct got_error *
5253 reset_diff_view(struct tog_view *view)
5255 struct tog_diff_view_state *s = &view->state.diff;
5257 view->count = 0;
5258 wclear(view->window);
5259 s->first_displayed_line = 1;
5260 s->last_displayed_line = view->nlines;
5261 s->matched_line = 0;
5262 diff_view_indicate_progress(view);
5263 return create_diff(s);
5266 static void
5267 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5269 int start, i;
5271 i = start = s->first_displayed_line - 1;
5273 while (s->lines[i].type != type) {
5274 if (i == 0)
5275 i = s->nlines - 1;
5276 if (--i == start)
5277 return; /* do nothing, requested type not in file */
5280 s->selected_line = 1;
5281 s->first_displayed_line = i;
5284 static void
5285 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5287 int start, i;
5289 i = start = s->first_displayed_line + 1;
5291 while (s->lines[i].type != type) {
5292 if (i == s->nlines - 1)
5293 i = 0;
5294 if (++i == start)
5295 return; /* do nothing, requested type not in file */
5298 s->selected_line = 1;
5299 s->first_displayed_line = i;
5302 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5303 int, int, int);
5304 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5305 int, int);
5307 static const struct got_error *
5308 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5310 const struct got_error *err = NULL;
5311 struct tog_diff_view_state *s = &view->state.diff;
5312 struct tog_log_view_state *ls;
5313 struct commit_queue_entry *old_selected_entry;
5314 char *line = NULL;
5315 size_t linesize = 0;
5316 ssize_t linelen;
5317 int i, nscroll = view->nlines - 1, up = 0;
5319 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5321 switch (ch) {
5322 case '0':
5323 case '$':
5324 case KEY_RIGHT:
5325 case 'l':
5326 case KEY_LEFT:
5327 case 'h':
5328 horizontal_scroll_input(view, ch);
5329 break;
5330 case 'a':
5331 case 'w':
5332 if (ch == 'a') {
5333 s->force_text_diff = !s->force_text_diff;
5334 view->action = s->force_text_diff ?
5335 "force ASCII text enabled" :
5336 "force ASCII text disabled";
5338 else if (ch == 'w') {
5339 s->ignore_whitespace = !s->ignore_whitespace;
5340 view->action = s->ignore_whitespace ?
5341 "ignore whitespace enabled" :
5342 "ignore whitespace disabled";
5344 err = reset_diff_view(view);
5345 break;
5346 case 'g':
5347 case KEY_HOME:
5348 s->first_displayed_line = 1;
5349 view->count = 0;
5350 break;
5351 case 'G':
5352 case KEY_END:
5353 view->count = 0;
5354 if (s->eof)
5355 break;
5357 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5358 s->eof = 1;
5359 break;
5360 case 'k':
5361 case KEY_UP:
5362 case CTRL('p'):
5363 if (s->first_displayed_line > 1)
5364 s->first_displayed_line--;
5365 else
5366 view->count = 0;
5367 break;
5368 case CTRL('u'):
5369 case 'u':
5370 nscroll /= 2;
5371 /* FALL THROUGH */
5372 case KEY_PPAGE:
5373 case CTRL('b'):
5374 case 'b':
5375 if (s->first_displayed_line == 1) {
5376 view->count = 0;
5377 break;
5379 i = 0;
5380 while (i++ < nscroll && s->first_displayed_line > 1)
5381 s->first_displayed_line--;
5382 break;
5383 case 'j':
5384 case KEY_DOWN:
5385 case CTRL('n'):
5386 if (!s->eof)
5387 s->first_displayed_line++;
5388 else
5389 view->count = 0;
5390 break;
5391 case CTRL('d'):
5392 case 'd':
5393 nscroll /= 2;
5394 /* FALL THROUGH */
5395 case KEY_NPAGE:
5396 case CTRL('f'):
5397 case 'f':
5398 case ' ':
5399 if (s->eof) {
5400 view->count = 0;
5401 break;
5403 i = 0;
5404 while (!s->eof && i++ < nscroll) {
5405 linelen = getline(&line, &linesize, s->f);
5406 s->first_displayed_line++;
5407 if (linelen == -1) {
5408 if (feof(s->f)) {
5409 s->eof = 1;
5410 } else
5411 err = got_ferror(s->f, GOT_ERR_IO);
5412 break;
5415 free(line);
5416 break;
5417 case '(':
5418 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5419 break;
5420 case ')':
5421 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5422 break;
5423 case '{':
5424 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5425 break;
5426 case '}':
5427 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5428 break;
5429 case '[':
5430 if (s->diff_context > 0) {
5431 s->diff_context--;
5432 s->matched_line = 0;
5433 diff_view_indicate_progress(view);
5434 err = create_diff(s);
5435 if (s->first_displayed_line + view->nlines - 1 >
5436 s->nlines) {
5437 s->first_displayed_line = 1;
5438 s->last_displayed_line = view->nlines;
5440 } else
5441 view->count = 0;
5442 break;
5443 case ']':
5444 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5445 s->diff_context++;
5446 s->matched_line = 0;
5447 diff_view_indicate_progress(view);
5448 err = create_diff(s);
5449 } else
5450 view->count = 0;
5451 break;
5452 case '<':
5453 case ',':
5454 case 'K':
5455 up = 1;
5456 /* FALL THROUGH */
5457 case '>':
5458 case '.':
5459 case 'J':
5460 if (s->parent_view == NULL) {
5461 view->count = 0;
5462 break;
5464 s->parent_view->count = view->count;
5466 if (s->parent_view->type == TOG_VIEW_LOG) {
5467 ls = &s->parent_view->state.log;
5468 old_selected_entry = ls->selected_entry;
5470 err = input_log_view(NULL, s->parent_view,
5471 up ? KEY_UP : KEY_DOWN);
5472 if (err)
5473 break;
5474 view->count = s->parent_view->count;
5476 if (old_selected_entry == ls->selected_entry)
5477 break;
5479 err = set_selected_commit(s, ls->selected_entry);
5480 if (err)
5481 break;
5482 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5483 struct tog_blame_view_state *bs;
5484 struct got_object_id *id, *prev_id;
5486 bs = &s->parent_view->state.blame;
5487 prev_id = get_annotation_for_line(bs->blame.lines,
5488 bs->blame.nlines, bs->last_diffed_line);
5490 err = input_blame_view(&view, s->parent_view,
5491 up ? KEY_UP : KEY_DOWN);
5492 if (err)
5493 break;
5494 view->count = s->parent_view->count;
5496 if (prev_id == NULL)
5497 break;
5498 id = get_selected_commit_id(bs->blame.lines,
5499 bs->blame.nlines, bs->first_displayed_line,
5500 bs->selected_line);
5501 if (id == NULL)
5502 break;
5504 if (!got_object_id_cmp(prev_id, id))
5505 break;
5507 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5508 if (err)
5509 break;
5511 s->first_displayed_line = 1;
5512 s->last_displayed_line = view->nlines;
5513 s->matched_line = 0;
5514 view->x = 0;
5516 diff_view_indicate_progress(view);
5517 err = create_diff(s);
5518 break;
5519 default:
5520 view->count = 0;
5521 break;
5524 return err;
5527 static const struct got_error *
5528 cmd_diff(int argc, char *argv[])
5530 const struct got_error *error = NULL;
5531 struct got_repository *repo = NULL;
5532 struct got_worktree *worktree = NULL;
5533 struct got_object_id *id1 = NULL, *id2 = NULL;
5534 char *repo_path = NULL, *cwd = NULL;
5535 char *id_str1 = NULL, *id_str2 = NULL;
5536 char *label1 = NULL, *label2 = NULL;
5537 int diff_context = 3, ignore_whitespace = 0;
5538 int ch, force_text_diff = 0;
5539 const char *errstr;
5540 struct tog_view *view;
5541 int *pack_fds = NULL;
5543 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5544 switch (ch) {
5545 case 'a':
5546 force_text_diff = 1;
5547 break;
5548 case 'C':
5549 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5550 &errstr);
5551 if (errstr != NULL)
5552 errx(1, "number of context lines is %s: %s",
5553 errstr, errstr);
5554 break;
5555 case 'r':
5556 repo_path = realpath(optarg, NULL);
5557 if (repo_path == NULL)
5558 return got_error_from_errno2("realpath",
5559 optarg);
5560 got_path_strip_trailing_slashes(repo_path);
5561 break;
5562 case 'w':
5563 ignore_whitespace = 1;
5564 break;
5565 default:
5566 usage_diff();
5567 /* NOTREACHED */
5571 argc -= optind;
5572 argv += optind;
5574 if (argc == 0) {
5575 usage_diff(); /* TODO show local worktree changes */
5576 } else if (argc == 2) {
5577 id_str1 = argv[0];
5578 id_str2 = argv[1];
5579 } else
5580 usage_diff();
5582 error = got_repo_pack_fds_open(&pack_fds);
5583 if (error)
5584 goto done;
5586 if (repo_path == NULL) {
5587 cwd = getcwd(NULL, 0);
5588 if (cwd == NULL)
5589 return got_error_from_errno("getcwd");
5590 error = got_worktree_open(&worktree, cwd);
5591 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5592 goto done;
5593 if (worktree)
5594 repo_path =
5595 strdup(got_worktree_get_repo_path(worktree));
5596 else
5597 repo_path = strdup(cwd);
5598 if (repo_path == NULL) {
5599 error = got_error_from_errno("strdup");
5600 goto done;
5604 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5605 if (error)
5606 goto done;
5608 init_curses();
5610 error = apply_unveil(got_repo_get_path(repo), NULL);
5611 if (error)
5612 goto done;
5614 error = tog_load_refs(repo, 0);
5615 if (error)
5616 goto done;
5618 error = got_repo_match_object_id(&id1, &label1, id_str1,
5619 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5620 if (error)
5621 goto done;
5623 error = got_repo_match_object_id(&id2, &label2, id_str2,
5624 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5625 if (error)
5626 goto done;
5628 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5629 if (view == NULL) {
5630 error = got_error_from_errno("view_open");
5631 goto done;
5633 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5634 ignore_whitespace, force_text_diff, NULL, repo);
5635 if (error)
5636 goto done;
5637 error = view_loop(view);
5638 done:
5639 free(label1);
5640 free(label2);
5641 free(repo_path);
5642 free(cwd);
5643 if (repo) {
5644 const struct got_error *close_err = got_repo_close(repo);
5645 if (error == NULL)
5646 error = close_err;
5648 if (worktree)
5649 got_worktree_close(worktree);
5650 if (pack_fds) {
5651 const struct got_error *pack_err =
5652 got_repo_pack_fds_close(pack_fds);
5653 if (error == NULL)
5654 error = pack_err;
5656 tog_free_refs();
5657 return error;
5660 __dead static void
5661 usage_blame(void)
5663 endwin();
5664 fprintf(stderr,
5665 "usage: %s blame [-c commit] [-r repository-path] path\n",
5666 getprogname());
5667 exit(1);
5670 struct tog_blame_line {
5671 int annotated;
5672 struct got_object_id *id;
5675 static const struct got_error *
5676 draw_blame(struct tog_view *view)
5678 struct tog_blame_view_state *s = &view->state.blame;
5679 struct tog_blame *blame = &s->blame;
5680 regmatch_t *regmatch = &view->regmatch;
5681 const struct got_error *err;
5682 int lineno = 0, nprinted = 0;
5683 char *line = NULL;
5684 size_t linesize = 0;
5685 ssize_t linelen;
5686 wchar_t *wline;
5687 int width;
5688 struct tog_blame_line *blame_line;
5689 struct got_object_id *prev_id = NULL;
5690 char *id_str;
5691 struct tog_color *tc;
5693 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5694 if (err)
5695 return err;
5697 rewind(blame->f);
5698 werase(view->window);
5700 if (asprintf(&line, "commit %s", id_str) == -1) {
5701 err = got_error_from_errno("asprintf");
5702 free(id_str);
5703 return err;
5706 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5707 free(line);
5708 line = NULL;
5709 if (err)
5710 return err;
5711 if (view_needs_focus_indication(view))
5712 wstandout(view->window);
5713 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5714 if (tc)
5715 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5716 waddwstr(view->window, wline);
5717 while (width++ < view->ncols)
5718 waddch(view->window, ' ');
5719 if (tc)
5720 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5721 if (view_needs_focus_indication(view))
5722 wstandend(view->window);
5723 free(wline);
5724 wline = NULL;
5726 if (view->gline > blame->nlines)
5727 view->gline = blame->nlines;
5729 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5730 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5731 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5732 free(id_str);
5733 return got_error_from_errno("asprintf");
5735 free(id_str);
5736 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5737 free(line);
5738 line = NULL;
5739 if (err)
5740 return err;
5741 waddwstr(view->window, wline);
5742 free(wline);
5743 wline = NULL;
5744 if (width < view->ncols - 1)
5745 waddch(view->window, '\n');
5747 s->eof = 0;
5748 view->maxx = 0;
5749 while (nprinted < view->nlines - 2) {
5750 linelen = getline(&line, &linesize, blame->f);
5751 if (linelen == -1) {
5752 if (feof(blame->f)) {
5753 s->eof = 1;
5754 break;
5756 free(line);
5757 return got_ferror(blame->f, GOT_ERR_IO);
5759 if (++lineno < s->first_displayed_line)
5760 continue;
5761 if (view->gline && !gotoline(view, &lineno, &nprinted))
5762 continue;
5764 /* Set view->maxx based on full line length. */
5765 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5766 if (err) {
5767 free(line);
5768 return err;
5770 free(wline);
5771 wline = NULL;
5772 view->maxx = MAX(view->maxx, width);
5774 if (nprinted == s->selected_line - 1)
5775 wstandout(view->window);
5777 if (blame->nlines > 0) {
5778 blame_line = &blame->lines[lineno - 1];
5779 if (blame_line->annotated && prev_id &&
5780 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5781 !(nprinted == s->selected_line - 1)) {
5782 waddstr(view->window, " ");
5783 } else if (blame_line->annotated) {
5784 char *id_str;
5785 err = got_object_id_str(&id_str,
5786 blame_line->id);
5787 if (err) {
5788 free(line);
5789 return err;
5791 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5792 if (tc)
5793 wattr_on(view->window,
5794 COLOR_PAIR(tc->colorpair), NULL);
5795 wprintw(view->window, "%.8s", id_str);
5796 if (tc)
5797 wattr_off(view->window,
5798 COLOR_PAIR(tc->colorpair), NULL);
5799 free(id_str);
5800 prev_id = blame_line->id;
5801 } else {
5802 waddstr(view->window, "........");
5803 prev_id = NULL;
5805 } else {
5806 waddstr(view->window, "........");
5807 prev_id = NULL;
5810 if (nprinted == s->selected_line - 1)
5811 wstandend(view->window);
5812 waddstr(view->window, " ");
5814 if (view->ncols <= 9) {
5815 width = 9;
5816 } else if (s->first_displayed_line + nprinted ==
5817 s->matched_line &&
5818 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5819 err = add_matched_line(&width, line, view->ncols - 9, 9,
5820 view->window, view->x, regmatch);
5821 if (err) {
5822 free(line);
5823 return err;
5825 width += 9;
5826 } else {
5827 int skip;
5828 err = format_line(&wline, &width, &skip, line,
5829 view->x, view->ncols - 9, 9, 1);
5830 if (err) {
5831 free(line);
5832 return err;
5834 waddwstr(view->window, &wline[skip]);
5835 width += 9;
5836 free(wline);
5837 wline = NULL;
5840 if (width <= view->ncols - 1)
5841 waddch(view->window, '\n');
5842 if (++nprinted == 1)
5843 s->first_displayed_line = lineno;
5845 free(line);
5846 s->last_displayed_line = lineno;
5848 view_border(view);
5850 return NULL;
5853 static const struct got_error *
5854 blame_cb(void *arg, int nlines, int lineno,
5855 struct got_commit_object *commit, struct got_object_id *id)
5857 const struct got_error *err = NULL;
5858 struct tog_blame_cb_args *a = arg;
5859 struct tog_blame_line *line;
5860 int errcode;
5862 if (nlines != a->nlines ||
5863 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5864 return got_error(GOT_ERR_RANGE);
5866 errcode = pthread_mutex_lock(&tog_mutex);
5867 if (errcode)
5868 return got_error_set_errno(errcode, "pthread_mutex_lock");
5870 if (*a->quit) { /* user has quit the blame view */
5871 err = got_error(GOT_ERR_ITER_COMPLETED);
5872 goto done;
5875 if (lineno == -1)
5876 goto done; /* no change in this commit */
5878 line = &a->lines[lineno - 1];
5879 if (line->annotated)
5880 goto done;
5882 line->id = got_object_id_dup(id);
5883 if (line->id == NULL) {
5884 err = got_error_from_errno("got_object_id_dup");
5885 goto done;
5887 line->annotated = 1;
5888 done:
5889 errcode = pthread_mutex_unlock(&tog_mutex);
5890 if (errcode)
5891 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5892 return err;
5895 static void *
5896 blame_thread(void *arg)
5898 const struct got_error *err, *close_err;
5899 struct tog_blame_thread_args *ta = arg;
5900 struct tog_blame_cb_args *a = ta->cb_args;
5901 int errcode, fd1 = -1, fd2 = -1;
5902 FILE *f1 = NULL, *f2 = NULL;
5904 fd1 = got_opentempfd();
5905 if (fd1 == -1)
5906 return (void *)got_error_from_errno("got_opentempfd");
5908 fd2 = got_opentempfd();
5909 if (fd2 == -1) {
5910 err = got_error_from_errno("got_opentempfd");
5911 goto done;
5914 f1 = got_opentemp();
5915 if (f1 == NULL) {
5916 err = (void *)got_error_from_errno("got_opentemp");
5917 goto done;
5919 f2 = got_opentemp();
5920 if (f2 == NULL) {
5921 err = (void *)got_error_from_errno("got_opentemp");
5922 goto done;
5925 err = block_signals_used_by_main_thread();
5926 if (err)
5927 goto done;
5929 err = got_blame(ta->path, a->commit_id, ta->repo,
5930 tog_diff_algo, blame_cb, ta->cb_args,
5931 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5932 if (err && err->code == GOT_ERR_CANCELLED)
5933 err = NULL;
5935 errcode = pthread_mutex_lock(&tog_mutex);
5936 if (errcode) {
5937 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5938 goto done;
5941 close_err = got_repo_close(ta->repo);
5942 if (err == NULL)
5943 err = close_err;
5944 ta->repo = NULL;
5945 *ta->complete = 1;
5947 errcode = pthread_mutex_unlock(&tog_mutex);
5948 if (errcode && err == NULL)
5949 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5951 done:
5952 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5953 err = got_error_from_errno("close");
5954 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5955 err = got_error_from_errno("close");
5956 if (f1 && fclose(f1) == EOF && err == NULL)
5957 err = got_error_from_errno("fclose");
5958 if (f2 && fclose(f2) == EOF && err == NULL)
5959 err = got_error_from_errno("fclose");
5961 return (void *)err;
5964 static struct got_object_id *
5965 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5966 int first_displayed_line, int selected_line)
5968 struct tog_blame_line *line;
5970 if (nlines <= 0)
5971 return NULL;
5973 line = &lines[first_displayed_line - 1 + selected_line - 1];
5974 if (!line->annotated)
5975 return NULL;
5977 return line->id;
5980 static struct got_object_id *
5981 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5982 int lineno)
5984 struct tog_blame_line *line;
5986 if (nlines <= 0 || lineno >= nlines)
5987 return NULL;
5989 line = &lines[lineno - 1];
5990 if (!line->annotated)
5991 return NULL;
5993 return line->id;
5996 static const struct got_error *
5997 stop_blame(struct tog_blame *blame)
5999 const struct got_error *err = NULL;
6000 int i;
6002 if (blame->thread) {
6003 int errcode;
6004 errcode = pthread_mutex_unlock(&tog_mutex);
6005 if (errcode)
6006 return got_error_set_errno(errcode,
6007 "pthread_mutex_unlock");
6008 errcode = pthread_join(blame->thread, (void **)&err);
6009 if (errcode)
6010 return got_error_set_errno(errcode, "pthread_join");
6011 errcode = pthread_mutex_lock(&tog_mutex);
6012 if (errcode)
6013 return got_error_set_errno(errcode,
6014 "pthread_mutex_lock");
6015 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6016 err = NULL;
6017 blame->thread = NULL;
6019 if (blame->thread_args.repo) {
6020 const struct got_error *close_err;
6021 close_err = got_repo_close(blame->thread_args.repo);
6022 if (err == NULL)
6023 err = close_err;
6024 blame->thread_args.repo = NULL;
6026 if (blame->f) {
6027 if (fclose(blame->f) == EOF && err == NULL)
6028 err = got_error_from_errno("fclose");
6029 blame->f = NULL;
6031 if (blame->lines) {
6032 for (i = 0; i < blame->nlines; i++)
6033 free(blame->lines[i].id);
6034 free(blame->lines);
6035 blame->lines = NULL;
6037 free(blame->cb_args.commit_id);
6038 blame->cb_args.commit_id = NULL;
6039 if (blame->pack_fds) {
6040 const struct got_error *pack_err =
6041 got_repo_pack_fds_close(blame->pack_fds);
6042 if (err == NULL)
6043 err = pack_err;
6044 blame->pack_fds = NULL;
6046 return err;
6049 static const struct got_error *
6050 cancel_blame_view(void *arg)
6052 const struct got_error *err = NULL;
6053 int *done = arg;
6054 int errcode;
6056 errcode = pthread_mutex_lock(&tog_mutex);
6057 if (errcode)
6058 return got_error_set_errno(errcode,
6059 "pthread_mutex_unlock");
6061 if (*done)
6062 err = got_error(GOT_ERR_CANCELLED);
6064 errcode = pthread_mutex_unlock(&tog_mutex);
6065 if (errcode)
6066 return got_error_set_errno(errcode,
6067 "pthread_mutex_lock");
6069 return err;
6072 static const struct got_error *
6073 run_blame(struct tog_view *view)
6075 struct tog_blame_view_state *s = &view->state.blame;
6076 struct tog_blame *blame = &s->blame;
6077 const struct got_error *err = NULL;
6078 struct got_commit_object *commit = NULL;
6079 struct got_blob_object *blob = NULL;
6080 struct got_repository *thread_repo = NULL;
6081 struct got_object_id *obj_id = NULL;
6082 int obj_type, fd = -1;
6083 int *pack_fds = NULL;
6085 err = got_object_open_as_commit(&commit, s->repo,
6086 &s->blamed_commit->id);
6087 if (err)
6088 return err;
6090 fd = got_opentempfd();
6091 if (fd == -1) {
6092 err = got_error_from_errno("got_opentempfd");
6093 goto done;
6096 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6097 if (err)
6098 goto done;
6100 err = got_object_get_type(&obj_type, s->repo, obj_id);
6101 if (err)
6102 goto done;
6104 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6105 err = got_error(GOT_ERR_OBJ_TYPE);
6106 goto done;
6109 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6110 if (err)
6111 goto done;
6112 blame->f = got_opentemp();
6113 if (blame->f == NULL) {
6114 err = got_error_from_errno("got_opentemp");
6115 goto done;
6117 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6118 &blame->line_offsets, blame->f, blob);
6119 if (err)
6120 goto done;
6121 if (blame->nlines == 0) {
6122 s->blame_complete = 1;
6123 goto done;
6126 /* Don't include \n at EOF in the blame line count. */
6127 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6128 blame->nlines--;
6130 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6131 if (blame->lines == NULL) {
6132 err = got_error_from_errno("calloc");
6133 goto done;
6136 err = got_repo_pack_fds_open(&pack_fds);
6137 if (err)
6138 goto done;
6139 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6140 pack_fds);
6141 if (err)
6142 goto done;
6144 blame->pack_fds = pack_fds;
6145 blame->cb_args.view = view;
6146 blame->cb_args.lines = blame->lines;
6147 blame->cb_args.nlines = blame->nlines;
6148 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6149 if (blame->cb_args.commit_id == NULL) {
6150 err = got_error_from_errno("got_object_id_dup");
6151 goto done;
6153 blame->cb_args.quit = &s->done;
6155 blame->thread_args.path = s->path;
6156 blame->thread_args.repo = thread_repo;
6157 blame->thread_args.cb_args = &blame->cb_args;
6158 blame->thread_args.complete = &s->blame_complete;
6159 blame->thread_args.cancel_cb = cancel_blame_view;
6160 blame->thread_args.cancel_arg = &s->done;
6161 s->blame_complete = 0;
6163 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6164 s->first_displayed_line = 1;
6165 s->last_displayed_line = view->nlines;
6166 s->selected_line = 1;
6168 s->matched_line = 0;
6170 done:
6171 if (commit)
6172 got_object_commit_close(commit);
6173 if (fd != -1 && close(fd) == -1 && err == NULL)
6174 err = got_error_from_errno("close");
6175 if (blob)
6176 got_object_blob_close(blob);
6177 free(obj_id);
6178 if (err)
6179 stop_blame(blame);
6180 return err;
6183 static const struct got_error *
6184 open_blame_view(struct tog_view *view, char *path,
6185 struct got_object_id *commit_id, struct got_repository *repo)
6187 const struct got_error *err = NULL;
6188 struct tog_blame_view_state *s = &view->state.blame;
6190 STAILQ_INIT(&s->blamed_commits);
6192 s->path = strdup(path);
6193 if (s->path == NULL)
6194 return got_error_from_errno("strdup");
6196 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6197 if (err) {
6198 free(s->path);
6199 return err;
6202 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6203 s->first_displayed_line = 1;
6204 s->last_displayed_line = view->nlines;
6205 s->selected_line = 1;
6206 s->blame_complete = 0;
6207 s->repo = repo;
6208 s->commit_id = commit_id;
6209 memset(&s->blame, 0, sizeof(s->blame));
6211 STAILQ_INIT(&s->colors);
6212 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6213 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6214 get_color_value("TOG_COLOR_COMMIT"));
6215 if (err)
6216 return err;
6219 view->show = show_blame_view;
6220 view->input = input_blame_view;
6221 view->reset = reset_blame_view;
6222 view->close = close_blame_view;
6223 view->search_start = search_start_blame_view;
6224 view->search_setup = search_setup_blame_view;
6225 view->search_next = search_next_view_match;
6227 return run_blame(view);
6230 static const struct got_error *
6231 close_blame_view(struct tog_view *view)
6233 const struct got_error *err = NULL;
6234 struct tog_blame_view_state *s = &view->state.blame;
6236 if (s->blame.thread)
6237 err = stop_blame(&s->blame);
6239 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6240 struct got_object_qid *blamed_commit;
6241 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6242 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6243 got_object_qid_free(blamed_commit);
6246 free(s->path);
6247 free_colors(&s->colors);
6248 return err;
6251 static const struct got_error *
6252 search_start_blame_view(struct tog_view *view)
6254 struct tog_blame_view_state *s = &view->state.blame;
6256 s->matched_line = 0;
6257 return NULL;
6260 static void
6261 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6262 size_t *nlines, int **first, int **last, int **match, int **selected)
6264 struct tog_blame_view_state *s = &view->state.blame;
6266 *f = s->blame.f;
6267 *nlines = s->blame.nlines;
6268 *line_offsets = s->blame.line_offsets;
6269 *match = &s->matched_line;
6270 *first = &s->first_displayed_line;
6271 *last = &s->last_displayed_line;
6272 *selected = &s->selected_line;
6275 static const struct got_error *
6276 show_blame_view(struct tog_view *view)
6278 const struct got_error *err = NULL;
6279 struct tog_blame_view_state *s = &view->state.blame;
6280 int errcode;
6282 if (s->blame.thread == NULL && !s->blame_complete) {
6283 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6284 &s->blame.thread_args);
6285 if (errcode)
6286 return got_error_set_errno(errcode, "pthread_create");
6288 halfdelay(1); /* fast refresh while annotating */
6291 if (s->blame_complete)
6292 halfdelay(10); /* disable fast refresh */
6294 err = draw_blame(view);
6296 view_border(view);
6297 return err;
6300 static const struct got_error *
6301 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6302 struct got_repository *repo, struct got_object_id *id)
6304 struct tog_view *log_view;
6305 const struct got_error *err = NULL;
6307 *new_view = NULL;
6309 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6310 if (log_view == NULL)
6311 return got_error_from_errno("view_open");
6313 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6314 if (err)
6315 view_close(log_view);
6316 else
6317 *new_view = log_view;
6319 return err;
6322 static const struct got_error *
6323 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6325 const struct got_error *err = NULL, *thread_err = NULL;
6326 struct tog_view *diff_view;
6327 struct tog_blame_view_state *s = &view->state.blame;
6328 int eos, nscroll, begin_y = 0, begin_x = 0;
6330 eos = nscroll = view->nlines - 2;
6331 if (view_is_hsplit_top(view))
6332 --eos; /* border */
6334 switch (ch) {
6335 case '0':
6336 case '$':
6337 case KEY_RIGHT:
6338 case 'l':
6339 case KEY_LEFT:
6340 case 'h':
6341 horizontal_scroll_input(view, ch);
6342 break;
6343 case 'q':
6344 s->done = 1;
6345 break;
6346 case 'g':
6347 case KEY_HOME:
6348 s->selected_line = 1;
6349 s->first_displayed_line = 1;
6350 view->count = 0;
6351 break;
6352 case 'G':
6353 case KEY_END:
6354 if (s->blame.nlines < eos) {
6355 s->selected_line = s->blame.nlines;
6356 s->first_displayed_line = 1;
6357 } else {
6358 s->selected_line = eos;
6359 s->first_displayed_line = s->blame.nlines - (eos - 1);
6361 view->count = 0;
6362 break;
6363 case 'k':
6364 case KEY_UP:
6365 case CTRL('p'):
6366 if (s->selected_line > 1)
6367 s->selected_line--;
6368 else if (s->selected_line == 1 &&
6369 s->first_displayed_line > 1)
6370 s->first_displayed_line--;
6371 else
6372 view->count = 0;
6373 break;
6374 case CTRL('u'):
6375 case 'u':
6376 nscroll /= 2;
6377 /* FALL THROUGH */
6378 case KEY_PPAGE:
6379 case CTRL('b'):
6380 case 'b':
6381 if (s->first_displayed_line == 1) {
6382 if (view->count > 1)
6383 nscroll += nscroll;
6384 s->selected_line = MAX(1, s->selected_line - nscroll);
6385 view->count = 0;
6386 break;
6388 if (s->first_displayed_line > nscroll)
6389 s->first_displayed_line -= nscroll;
6390 else
6391 s->first_displayed_line = 1;
6392 break;
6393 case 'j':
6394 case KEY_DOWN:
6395 case CTRL('n'):
6396 if (s->selected_line < eos && s->first_displayed_line +
6397 s->selected_line <= s->blame.nlines)
6398 s->selected_line++;
6399 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6400 s->first_displayed_line++;
6401 else
6402 view->count = 0;
6403 break;
6404 case 'c':
6405 case 'p': {
6406 struct got_object_id *id = NULL;
6408 view->count = 0;
6409 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6410 s->first_displayed_line, s->selected_line);
6411 if (id == NULL)
6412 break;
6413 if (ch == 'p') {
6414 struct got_commit_object *commit, *pcommit;
6415 struct got_object_qid *pid;
6416 struct got_object_id *blob_id = NULL;
6417 int obj_type;
6418 err = got_object_open_as_commit(&commit,
6419 s->repo, id);
6420 if (err)
6421 break;
6422 pid = STAILQ_FIRST(
6423 got_object_commit_get_parent_ids(commit));
6424 if (pid == NULL) {
6425 got_object_commit_close(commit);
6426 break;
6428 /* Check if path history ends here. */
6429 err = got_object_open_as_commit(&pcommit,
6430 s->repo, &pid->id);
6431 if (err)
6432 break;
6433 err = got_object_id_by_path(&blob_id, s->repo,
6434 pcommit, s->path);
6435 got_object_commit_close(pcommit);
6436 if (err) {
6437 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6438 err = NULL;
6439 got_object_commit_close(commit);
6440 break;
6442 err = got_object_get_type(&obj_type, s->repo,
6443 blob_id);
6444 free(blob_id);
6445 /* Can't blame non-blob type objects. */
6446 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6447 got_object_commit_close(commit);
6448 break;
6450 err = got_object_qid_alloc(&s->blamed_commit,
6451 &pid->id);
6452 got_object_commit_close(commit);
6453 } else {
6454 if (got_object_id_cmp(id,
6455 &s->blamed_commit->id) == 0)
6456 break;
6457 err = got_object_qid_alloc(&s->blamed_commit,
6458 id);
6460 if (err)
6461 break;
6462 s->done = 1;
6463 thread_err = stop_blame(&s->blame);
6464 s->done = 0;
6465 if (thread_err)
6466 break;
6467 STAILQ_INSERT_HEAD(&s->blamed_commits,
6468 s->blamed_commit, entry);
6469 err = run_blame(view);
6470 if (err)
6471 break;
6472 break;
6474 case 'C': {
6475 struct got_object_qid *first;
6477 view->count = 0;
6478 first = STAILQ_FIRST(&s->blamed_commits);
6479 if (!got_object_id_cmp(&first->id, s->commit_id))
6480 break;
6481 s->done = 1;
6482 thread_err = stop_blame(&s->blame);
6483 s->done = 0;
6484 if (thread_err)
6485 break;
6486 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6487 got_object_qid_free(s->blamed_commit);
6488 s->blamed_commit =
6489 STAILQ_FIRST(&s->blamed_commits);
6490 err = run_blame(view);
6491 if (err)
6492 break;
6493 break;
6495 case 'L':
6496 view->count = 0;
6497 s->id_to_log = get_selected_commit_id(s->blame.lines,
6498 s->blame.nlines, s->first_displayed_line, s->selected_line);
6499 if (s->id_to_log)
6500 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6501 break;
6502 case KEY_ENTER:
6503 case '\r': {
6504 struct got_object_id *id = NULL;
6505 struct got_object_qid *pid;
6506 struct got_commit_object *commit = NULL;
6508 view->count = 0;
6509 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6510 s->first_displayed_line, s->selected_line);
6511 if (id == NULL)
6512 break;
6513 err = got_object_open_as_commit(&commit, s->repo, id);
6514 if (err)
6515 break;
6516 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6517 if (*new_view) {
6518 /* traversed from diff view, release diff resources */
6519 err = close_diff_view(*new_view);
6520 if (err)
6521 break;
6522 diff_view = *new_view;
6523 } else {
6524 if (view_is_parent_view(view))
6525 view_get_split(view, &begin_y, &begin_x);
6527 diff_view = view_open(0, 0, begin_y, begin_x,
6528 TOG_VIEW_DIFF);
6529 if (diff_view == NULL) {
6530 got_object_commit_close(commit);
6531 err = got_error_from_errno("view_open");
6532 break;
6535 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6536 id, NULL, NULL, 3, 0, 0, view, s->repo);
6537 got_object_commit_close(commit);
6538 if (err) {
6539 view_close(diff_view);
6540 break;
6542 s->last_diffed_line = s->first_displayed_line - 1 +
6543 s->selected_line;
6544 if (*new_view)
6545 break; /* still open from active diff view */
6546 if (view_is_parent_view(view) &&
6547 view->mode == TOG_VIEW_SPLIT_HRZN) {
6548 err = view_init_hsplit(view, begin_y);
6549 if (err)
6550 break;
6553 view->focussed = 0;
6554 diff_view->focussed = 1;
6555 diff_view->mode = view->mode;
6556 diff_view->nlines = view->lines - begin_y;
6557 if (view_is_parent_view(view)) {
6558 view_transfer_size(diff_view, view);
6559 err = view_close_child(view);
6560 if (err)
6561 break;
6562 err = view_set_child(view, diff_view);
6563 if (err)
6564 break;
6565 view->focus_child = 1;
6566 } else
6567 *new_view = diff_view;
6568 if (err)
6569 break;
6570 break;
6572 case CTRL('d'):
6573 case 'd':
6574 nscroll /= 2;
6575 /* FALL THROUGH */
6576 case KEY_NPAGE:
6577 case CTRL('f'):
6578 case 'f':
6579 case ' ':
6580 if (s->last_displayed_line >= s->blame.nlines &&
6581 s->selected_line >= MIN(s->blame.nlines,
6582 view->nlines - 2)) {
6583 view->count = 0;
6584 break;
6586 if (s->last_displayed_line >= s->blame.nlines &&
6587 s->selected_line < view->nlines - 2) {
6588 s->selected_line +=
6589 MIN(nscroll, s->last_displayed_line -
6590 s->first_displayed_line - s->selected_line + 1);
6592 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6593 s->first_displayed_line += nscroll;
6594 else
6595 s->first_displayed_line =
6596 s->blame.nlines - (view->nlines - 3);
6597 break;
6598 case KEY_RESIZE:
6599 if (s->selected_line > view->nlines - 2) {
6600 s->selected_line = MIN(s->blame.nlines,
6601 view->nlines - 2);
6603 break;
6604 default:
6605 view->count = 0;
6606 break;
6608 return thread_err ? thread_err : err;
6611 static const struct got_error *
6612 reset_blame_view(struct tog_view *view)
6614 const struct got_error *err;
6615 struct tog_blame_view_state *s = &view->state.blame;
6617 view->count = 0;
6618 s->done = 1;
6619 err = stop_blame(&s->blame);
6620 s->done = 0;
6621 if (err)
6622 return err;
6623 return run_blame(view);
6626 static const struct got_error *
6627 cmd_blame(int argc, char *argv[])
6629 const struct got_error *error;
6630 struct got_repository *repo = NULL;
6631 struct got_worktree *worktree = NULL;
6632 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6633 char *link_target = NULL;
6634 struct got_object_id *commit_id = NULL;
6635 struct got_commit_object *commit = NULL;
6636 char *commit_id_str = NULL;
6637 int ch;
6638 struct tog_view *view;
6639 int *pack_fds = NULL;
6641 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6642 switch (ch) {
6643 case 'c':
6644 commit_id_str = optarg;
6645 break;
6646 case 'r':
6647 repo_path = realpath(optarg, NULL);
6648 if (repo_path == NULL)
6649 return got_error_from_errno2("realpath",
6650 optarg);
6651 break;
6652 default:
6653 usage_blame();
6654 /* NOTREACHED */
6658 argc -= optind;
6659 argv += optind;
6661 if (argc != 1)
6662 usage_blame();
6664 error = got_repo_pack_fds_open(&pack_fds);
6665 if (error != NULL)
6666 goto done;
6668 if (repo_path == NULL) {
6669 cwd = getcwd(NULL, 0);
6670 if (cwd == NULL)
6671 return got_error_from_errno("getcwd");
6672 error = got_worktree_open(&worktree, cwd);
6673 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6674 goto done;
6675 if (worktree)
6676 repo_path =
6677 strdup(got_worktree_get_repo_path(worktree));
6678 else
6679 repo_path = strdup(cwd);
6680 if (repo_path == NULL) {
6681 error = got_error_from_errno("strdup");
6682 goto done;
6686 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6687 if (error != NULL)
6688 goto done;
6690 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6691 worktree);
6692 if (error)
6693 goto done;
6695 init_curses();
6697 error = apply_unveil(got_repo_get_path(repo), NULL);
6698 if (error)
6699 goto done;
6701 error = tog_load_refs(repo, 0);
6702 if (error)
6703 goto done;
6705 if (commit_id_str == NULL) {
6706 struct got_reference *head_ref;
6707 error = got_ref_open(&head_ref, repo, worktree ?
6708 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6709 if (error != NULL)
6710 goto done;
6711 error = got_ref_resolve(&commit_id, repo, head_ref);
6712 got_ref_close(head_ref);
6713 } else {
6714 error = got_repo_match_object_id(&commit_id, NULL,
6715 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6717 if (error != NULL)
6718 goto done;
6720 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6721 if (view == NULL) {
6722 error = got_error_from_errno("view_open");
6723 goto done;
6726 error = got_object_open_as_commit(&commit, repo, commit_id);
6727 if (error)
6728 goto done;
6730 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6731 commit, repo);
6732 if (error)
6733 goto done;
6735 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6736 commit_id, repo);
6737 if (error)
6738 goto done;
6739 if (worktree) {
6740 /* Release work tree lock. */
6741 got_worktree_close(worktree);
6742 worktree = NULL;
6744 error = view_loop(view);
6745 done:
6746 free(repo_path);
6747 free(in_repo_path);
6748 free(link_target);
6749 free(cwd);
6750 free(commit_id);
6751 if (commit)
6752 got_object_commit_close(commit);
6753 if (worktree)
6754 got_worktree_close(worktree);
6755 if (repo) {
6756 const struct got_error *close_err = got_repo_close(repo);
6757 if (error == NULL)
6758 error = close_err;
6760 if (pack_fds) {
6761 const struct got_error *pack_err =
6762 got_repo_pack_fds_close(pack_fds);
6763 if (error == NULL)
6764 error = pack_err;
6766 tog_free_refs();
6767 return error;
6770 static const struct got_error *
6771 draw_tree_entries(struct tog_view *view, const char *parent_path)
6773 struct tog_tree_view_state *s = &view->state.tree;
6774 const struct got_error *err = NULL;
6775 struct got_tree_entry *te;
6776 wchar_t *wline;
6777 char *index = NULL;
6778 struct tog_color *tc;
6779 int width, n, nentries, scrollx, i = 1;
6780 int limit = view->nlines;
6782 s->ndisplayed = 0;
6783 if (view_is_hsplit_top(view))
6784 --limit; /* border */
6786 werase(view->window);
6788 if (limit == 0)
6789 return NULL;
6791 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6792 0, 0);
6793 if (err)
6794 return err;
6795 if (view_needs_focus_indication(view))
6796 wstandout(view->window);
6797 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6798 if (tc)
6799 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6800 waddwstr(view->window, wline);
6801 free(wline);
6802 wline = NULL;
6803 while (width++ < view->ncols)
6804 waddch(view->window, ' ');
6805 if (tc)
6806 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6807 if (view_needs_focus_indication(view))
6808 wstandend(view->window);
6809 if (--limit <= 0)
6810 return NULL;
6812 i += s->selected;
6813 if (s->first_displayed_entry) {
6814 i += got_tree_entry_get_index(s->first_displayed_entry);
6815 if (s->tree != s->root)
6816 ++i; /* account for ".." entry */
6818 nentries = got_object_tree_get_nentries(s->tree);
6819 if (asprintf(&index, "[%d/%d] %s",
6820 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6821 return got_error_from_errno("asprintf");
6822 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6823 free(index);
6824 if (err)
6825 return err;
6826 waddwstr(view->window, wline);
6827 free(wline);
6828 wline = NULL;
6829 if (width < view->ncols - 1)
6830 waddch(view->window, '\n');
6831 if (--limit <= 0)
6832 return NULL;
6833 waddch(view->window, '\n');
6834 if (--limit <= 0)
6835 return NULL;
6837 if (s->first_displayed_entry == NULL) {
6838 te = got_object_tree_get_first_entry(s->tree);
6839 if (s->selected == 0) {
6840 if (view->focussed)
6841 wstandout(view->window);
6842 s->selected_entry = NULL;
6844 waddstr(view->window, " ..\n"); /* parent directory */
6845 if (s->selected == 0 && view->focussed)
6846 wstandend(view->window);
6847 s->ndisplayed++;
6848 if (--limit <= 0)
6849 return NULL;
6850 n = 1;
6851 } else {
6852 n = 0;
6853 te = s->first_displayed_entry;
6856 view->maxx = 0;
6857 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6858 char *line = NULL, *id_str = NULL, *link_target = NULL;
6859 const char *modestr = "";
6860 mode_t mode;
6862 te = got_object_tree_get_entry(s->tree, i);
6863 mode = got_tree_entry_get_mode(te);
6865 if (s->show_ids) {
6866 err = got_object_id_str(&id_str,
6867 got_tree_entry_get_id(te));
6868 if (err)
6869 return got_error_from_errno(
6870 "got_object_id_str");
6872 if (got_object_tree_entry_is_submodule(te))
6873 modestr = "$";
6874 else if (S_ISLNK(mode)) {
6875 int i;
6877 err = got_tree_entry_get_symlink_target(&link_target,
6878 te, s->repo);
6879 if (err) {
6880 free(id_str);
6881 return err;
6883 for (i = 0; i < strlen(link_target); i++) {
6884 if (!isprint((unsigned char)link_target[i]))
6885 link_target[i] = '?';
6887 modestr = "@";
6889 else if (S_ISDIR(mode))
6890 modestr = "/";
6891 else if (mode & S_IXUSR)
6892 modestr = "*";
6893 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6894 got_tree_entry_get_name(te), modestr,
6895 link_target ? " -> ": "",
6896 link_target ? link_target : "") == -1) {
6897 free(id_str);
6898 free(link_target);
6899 return got_error_from_errno("asprintf");
6901 free(id_str);
6902 free(link_target);
6904 /* use full line width to determine view->maxx */
6905 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
6906 if (err) {
6907 free(line);
6908 break;
6910 view->maxx = MAX(view->maxx, width);
6911 free(wline);
6912 wline = NULL;
6914 err = format_line(&wline, &width, &scrollx, line, view->x,
6915 view->ncols, 0, 0);
6916 if (err) {
6917 free(line);
6918 break;
6920 if (n == s->selected) {
6921 if (view->focussed)
6922 wstandout(view->window);
6923 s->selected_entry = te;
6925 tc = match_color(&s->colors, line);
6926 if (tc)
6927 wattr_on(view->window,
6928 COLOR_PAIR(tc->colorpair), NULL);
6929 waddwstr(view->window, &wline[scrollx]);
6930 if (tc)
6931 wattr_off(view->window,
6932 COLOR_PAIR(tc->colorpair), NULL);
6933 if (width < view->ncols)
6934 waddch(view->window, '\n');
6935 if (n == s->selected && view->focussed)
6936 wstandend(view->window);
6937 free(line);
6938 free(wline);
6939 wline = NULL;
6940 n++;
6941 s->ndisplayed++;
6942 s->last_displayed_entry = te;
6943 if (--limit <= 0)
6944 break;
6947 return err;
6950 static void
6951 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6953 struct got_tree_entry *te;
6954 int isroot = s->tree == s->root;
6955 int i = 0;
6957 if (s->first_displayed_entry == NULL)
6958 return;
6960 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6961 while (i++ < maxscroll) {
6962 if (te == NULL) {
6963 if (!isroot)
6964 s->first_displayed_entry = NULL;
6965 break;
6967 s->first_displayed_entry = te;
6968 te = got_tree_entry_get_prev(s->tree, te);
6972 static const struct got_error *
6973 tree_scroll_down(struct tog_view *view, int maxscroll)
6975 struct tog_tree_view_state *s = &view->state.tree;
6976 struct got_tree_entry *next, *last;
6977 int n = 0;
6979 if (s->first_displayed_entry)
6980 next = got_tree_entry_get_next(s->tree,
6981 s->first_displayed_entry);
6982 else
6983 next = got_object_tree_get_first_entry(s->tree);
6985 last = s->last_displayed_entry;
6986 while (next && n++ < maxscroll) {
6987 if (last) {
6988 s->last_displayed_entry = last;
6989 last = got_tree_entry_get_next(s->tree, last);
6991 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6992 s->first_displayed_entry = next;
6993 next = got_tree_entry_get_next(s->tree, next);
6997 return NULL;
7000 static const struct got_error *
7001 tree_entry_path(char **path, struct tog_parent_trees *parents,
7002 struct got_tree_entry *te)
7004 const struct got_error *err = NULL;
7005 struct tog_parent_tree *pt;
7006 size_t len = 2; /* for leading slash and NUL */
7008 TAILQ_FOREACH(pt, parents, entry)
7009 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7010 + 1 /* slash */;
7011 if (te)
7012 len += strlen(got_tree_entry_get_name(te));
7014 *path = calloc(1, len);
7015 if (path == NULL)
7016 return got_error_from_errno("calloc");
7018 (*path)[0] = '/';
7019 pt = TAILQ_LAST(parents, tog_parent_trees);
7020 while (pt) {
7021 const char *name = got_tree_entry_get_name(pt->selected_entry);
7022 if (strlcat(*path, name, len) >= len) {
7023 err = got_error(GOT_ERR_NO_SPACE);
7024 goto done;
7026 if (strlcat(*path, "/", len) >= len) {
7027 err = got_error(GOT_ERR_NO_SPACE);
7028 goto done;
7030 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7032 if (te) {
7033 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7034 err = got_error(GOT_ERR_NO_SPACE);
7035 goto done;
7038 done:
7039 if (err) {
7040 free(*path);
7041 *path = NULL;
7043 return err;
7046 static const struct got_error *
7047 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7048 struct got_tree_entry *te, struct tog_parent_trees *parents,
7049 struct got_object_id *commit_id, struct got_repository *repo)
7051 const struct got_error *err = NULL;
7052 char *path;
7053 struct tog_view *blame_view;
7055 *new_view = NULL;
7057 err = tree_entry_path(&path, parents, te);
7058 if (err)
7059 return err;
7061 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7062 if (blame_view == NULL) {
7063 err = got_error_from_errno("view_open");
7064 goto done;
7067 err = open_blame_view(blame_view, path, commit_id, repo);
7068 if (err) {
7069 if (err->code == GOT_ERR_CANCELLED)
7070 err = NULL;
7071 view_close(blame_view);
7072 } else
7073 *new_view = blame_view;
7074 done:
7075 free(path);
7076 return err;
7079 static const struct got_error *
7080 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7081 struct tog_tree_view_state *s)
7083 struct tog_view *log_view;
7084 const struct got_error *err = NULL;
7085 char *path;
7087 *new_view = NULL;
7089 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7090 if (log_view == NULL)
7091 return got_error_from_errno("view_open");
7093 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7094 if (err)
7095 return err;
7097 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7098 path, 0);
7099 if (err)
7100 view_close(log_view);
7101 else
7102 *new_view = log_view;
7103 free(path);
7104 return err;
7107 static const struct got_error *
7108 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7109 const char *head_ref_name, struct got_repository *repo)
7111 const struct got_error *err = NULL;
7112 char *commit_id_str = NULL;
7113 struct tog_tree_view_state *s = &view->state.tree;
7114 struct got_commit_object *commit = NULL;
7116 TAILQ_INIT(&s->parents);
7117 STAILQ_INIT(&s->colors);
7119 s->commit_id = got_object_id_dup(commit_id);
7120 if (s->commit_id == NULL)
7121 return got_error_from_errno("got_object_id_dup");
7123 err = got_object_open_as_commit(&commit, repo, commit_id);
7124 if (err)
7125 goto done;
7128 * The root is opened here and will be closed when the view is closed.
7129 * Any visited subtrees and their path-wise parents are opened and
7130 * closed on demand.
7132 err = got_object_open_as_tree(&s->root, repo,
7133 got_object_commit_get_tree_id(commit));
7134 if (err)
7135 goto done;
7136 s->tree = s->root;
7138 err = got_object_id_str(&commit_id_str, commit_id);
7139 if (err != NULL)
7140 goto done;
7142 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7143 err = got_error_from_errno("asprintf");
7144 goto done;
7147 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7148 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7149 if (head_ref_name) {
7150 s->head_ref_name = strdup(head_ref_name);
7151 if (s->head_ref_name == NULL) {
7152 err = got_error_from_errno("strdup");
7153 goto done;
7156 s->repo = repo;
7158 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7159 err = add_color(&s->colors, "\\$$",
7160 TOG_COLOR_TREE_SUBMODULE,
7161 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7162 if (err)
7163 goto done;
7164 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7165 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7166 if (err)
7167 goto done;
7168 err = add_color(&s->colors, "/$",
7169 TOG_COLOR_TREE_DIRECTORY,
7170 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7171 if (err)
7172 goto done;
7174 err = add_color(&s->colors, "\\*$",
7175 TOG_COLOR_TREE_EXECUTABLE,
7176 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7177 if (err)
7178 goto done;
7180 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7181 get_color_value("TOG_COLOR_COMMIT"));
7182 if (err)
7183 goto done;
7186 view->show = show_tree_view;
7187 view->input = input_tree_view;
7188 view->close = close_tree_view;
7189 view->search_start = search_start_tree_view;
7190 view->search_next = search_next_tree_view;
7191 done:
7192 free(commit_id_str);
7193 if (commit)
7194 got_object_commit_close(commit);
7195 if (err)
7196 close_tree_view(view);
7197 return err;
7200 static const struct got_error *
7201 close_tree_view(struct tog_view *view)
7203 struct tog_tree_view_state *s = &view->state.tree;
7205 free_colors(&s->colors);
7206 free(s->tree_label);
7207 s->tree_label = NULL;
7208 free(s->commit_id);
7209 s->commit_id = NULL;
7210 free(s->head_ref_name);
7211 s->head_ref_name = NULL;
7212 while (!TAILQ_EMPTY(&s->parents)) {
7213 struct tog_parent_tree *parent;
7214 parent = TAILQ_FIRST(&s->parents);
7215 TAILQ_REMOVE(&s->parents, parent, entry);
7216 if (parent->tree != s->root)
7217 got_object_tree_close(parent->tree);
7218 free(parent);
7221 if (s->tree != NULL && s->tree != s->root)
7222 got_object_tree_close(s->tree);
7223 if (s->root)
7224 got_object_tree_close(s->root);
7225 return NULL;
7228 static const struct got_error *
7229 search_start_tree_view(struct tog_view *view)
7231 struct tog_tree_view_state *s = &view->state.tree;
7233 s->matched_entry = NULL;
7234 return NULL;
7237 static int
7238 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7240 regmatch_t regmatch;
7242 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7243 0) == 0;
7246 static const struct got_error *
7247 search_next_tree_view(struct tog_view *view)
7249 struct tog_tree_view_state *s = &view->state.tree;
7250 struct got_tree_entry *te = NULL;
7252 if (!view->searching) {
7253 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7254 return NULL;
7257 if (s->matched_entry) {
7258 if (view->searching == TOG_SEARCH_FORWARD) {
7259 if (s->selected_entry)
7260 te = got_tree_entry_get_next(s->tree,
7261 s->selected_entry);
7262 else
7263 te = got_object_tree_get_first_entry(s->tree);
7264 } else {
7265 if (s->selected_entry == NULL)
7266 te = got_object_tree_get_last_entry(s->tree);
7267 else
7268 te = got_tree_entry_get_prev(s->tree,
7269 s->selected_entry);
7271 } else {
7272 if (s->selected_entry)
7273 te = s->selected_entry;
7274 else if (view->searching == TOG_SEARCH_FORWARD)
7275 te = got_object_tree_get_first_entry(s->tree);
7276 else
7277 te = got_object_tree_get_last_entry(s->tree);
7280 while (1) {
7281 if (te == NULL) {
7282 if (s->matched_entry == NULL) {
7283 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7284 return NULL;
7286 if (view->searching == TOG_SEARCH_FORWARD)
7287 te = got_object_tree_get_first_entry(s->tree);
7288 else
7289 te = got_object_tree_get_last_entry(s->tree);
7292 if (match_tree_entry(te, &view->regex)) {
7293 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7294 s->matched_entry = te;
7295 break;
7298 if (view->searching == TOG_SEARCH_FORWARD)
7299 te = got_tree_entry_get_next(s->tree, te);
7300 else
7301 te = got_tree_entry_get_prev(s->tree, te);
7304 if (s->matched_entry) {
7305 s->first_displayed_entry = s->matched_entry;
7306 s->selected = 0;
7309 return NULL;
7312 static const struct got_error *
7313 show_tree_view(struct tog_view *view)
7315 const struct got_error *err = NULL;
7316 struct tog_tree_view_state *s = &view->state.tree;
7317 char *parent_path;
7319 err = tree_entry_path(&parent_path, &s->parents, NULL);
7320 if (err)
7321 return err;
7323 err = draw_tree_entries(view, parent_path);
7324 free(parent_path);
7326 view_border(view);
7327 return err;
7330 static const struct got_error *
7331 tree_goto_line(struct tog_view *view, int nlines)
7333 const struct got_error *err = NULL;
7334 struct tog_tree_view_state *s = &view->state.tree;
7335 struct got_tree_entry **fte, **lte, **ste;
7336 int g, last, first = 1, i = 1;
7337 int root = s->tree == s->root;
7338 int off = root ? 1 : 2;
7340 g = view->gline;
7341 view->gline = 0;
7343 if (g == 0)
7344 g = 1;
7345 else if (g > got_object_tree_get_nentries(s->tree))
7346 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7348 fte = &s->first_displayed_entry;
7349 lte = &s->last_displayed_entry;
7350 ste = &s->selected_entry;
7352 if (*fte != NULL) {
7353 first = got_tree_entry_get_index(*fte);
7354 first += off; /* account for ".." */
7356 last = got_tree_entry_get_index(*lte);
7357 last += off;
7359 if (g >= first && g <= last && g - first < nlines) {
7360 s->selected = g - first;
7361 return NULL; /* gline is on the current page */
7364 if (*ste != NULL) {
7365 i = got_tree_entry_get_index(*ste);
7366 i += off;
7369 if (i < g) {
7370 err = tree_scroll_down(view, g - i);
7371 if (err)
7372 return err;
7373 if (got_tree_entry_get_index(*lte) >=
7374 got_object_tree_get_nentries(s->tree) - 1 &&
7375 first + s->selected < g &&
7376 s->selected < s->ndisplayed - 1) {
7377 first = got_tree_entry_get_index(*fte);
7378 first += off;
7379 s->selected = g - first;
7381 } else if (i > g)
7382 tree_scroll_up(s, i - g);
7384 if (g < nlines &&
7385 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7386 s->selected = g - 1;
7388 return NULL;
7391 static const struct got_error *
7392 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7394 const struct got_error *err = NULL;
7395 struct tog_tree_view_state *s = &view->state.tree;
7396 struct got_tree_entry *te;
7397 int n, nscroll = view->nlines - 3;
7399 if (view->gline)
7400 return tree_goto_line(view, nscroll);
7402 switch (ch) {
7403 case '0':
7404 case '$':
7405 case KEY_RIGHT:
7406 case 'l':
7407 case KEY_LEFT:
7408 case 'h':
7409 horizontal_scroll_input(view, ch);
7410 break;
7411 case 'i':
7412 s->show_ids = !s->show_ids;
7413 view->count = 0;
7414 break;
7415 case 'L':
7416 view->count = 0;
7417 if (!s->selected_entry)
7418 break;
7419 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7420 break;
7421 case 'R':
7422 view->count = 0;
7423 err = view_request_new(new_view, view, TOG_VIEW_REF);
7424 break;
7425 case 'g':
7426 case '=':
7427 case KEY_HOME:
7428 s->selected = 0;
7429 view->count = 0;
7430 if (s->tree == s->root)
7431 s->first_displayed_entry =
7432 got_object_tree_get_first_entry(s->tree);
7433 else
7434 s->first_displayed_entry = NULL;
7435 break;
7436 case 'G':
7437 case '*':
7438 case KEY_END: {
7439 int eos = view->nlines - 3;
7441 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7442 --eos; /* border */
7443 s->selected = 0;
7444 view->count = 0;
7445 te = got_object_tree_get_last_entry(s->tree);
7446 for (n = 0; n < eos; n++) {
7447 if (te == NULL) {
7448 if (s->tree != s->root) {
7449 s->first_displayed_entry = NULL;
7450 n++;
7452 break;
7454 s->first_displayed_entry = te;
7455 te = got_tree_entry_get_prev(s->tree, te);
7457 if (n > 0)
7458 s->selected = n - 1;
7459 break;
7461 case 'k':
7462 case KEY_UP:
7463 case CTRL('p'):
7464 if (s->selected > 0) {
7465 s->selected--;
7466 break;
7468 tree_scroll_up(s, 1);
7469 if (s->selected_entry == NULL ||
7470 (s->tree == s->root && s->selected_entry ==
7471 got_object_tree_get_first_entry(s->tree)))
7472 view->count = 0;
7473 break;
7474 case CTRL('u'):
7475 case 'u':
7476 nscroll /= 2;
7477 /* FALL THROUGH */
7478 case KEY_PPAGE:
7479 case CTRL('b'):
7480 case 'b':
7481 if (s->tree == s->root) {
7482 if (got_object_tree_get_first_entry(s->tree) ==
7483 s->first_displayed_entry)
7484 s->selected -= MIN(s->selected, nscroll);
7485 } else {
7486 if (s->first_displayed_entry == NULL)
7487 s->selected -= MIN(s->selected, nscroll);
7489 tree_scroll_up(s, MAX(0, nscroll));
7490 if (s->selected_entry == NULL ||
7491 (s->tree == s->root && s->selected_entry ==
7492 got_object_tree_get_first_entry(s->tree)))
7493 view->count = 0;
7494 break;
7495 case 'j':
7496 case KEY_DOWN:
7497 case CTRL('n'):
7498 if (s->selected < s->ndisplayed - 1) {
7499 s->selected++;
7500 break;
7502 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7503 == NULL) {
7504 /* can't scroll any further */
7505 view->count = 0;
7506 break;
7508 tree_scroll_down(view, 1);
7509 break;
7510 case CTRL('d'):
7511 case 'd':
7512 nscroll /= 2;
7513 /* FALL THROUGH */
7514 case KEY_NPAGE:
7515 case CTRL('f'):
7516 case 'f':
7517 case ' ':
7518 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7519 == NULL) {
7520 /* can't scroll any further; move cursor down */
7521 if (s->selected < s->ndisplayed - 1)
7522 s->selected += MIN(nscroll,
7523 s->ndisplayed - s->selected - 1);
7524 else
7525 view->count = 0;
7526 break;
7528 tree_scroll_down(view, nscroll);
7529 break;
7530 case KEY_ENTER:
7531 case '\r':
7532 case KEY_BACKSPACE:
7533 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7534 struct tog_parent_tree *parent;
7535 /* user selected '..' */
7536 if (s->tree == s->root) {
7537 view->count = 0;
7538 break;
7540 parent = TAILQ_FIRST(&s->parents);
7541 TAILQ_REMOVE(&s->parents, parent,
7542 entry);
7543 got_object_tree_close(s->tree);
7544 s->tree = parent->tree;
7545 s->first_displayed_entry =
7546 parent->first_displayed_entry;
7547 s->selected_entry =
7548 parent->selected_entry;
7549 s->selected = parent->selected;
7550 if (s->selected > view->nlines - 3) {
7551 err = offset_selection_down(view);
7552 if (err)
7553 break;
7555 free(parent);
7556 } else if (S_ISDIR(got_tree_entry_get_mode(
7557 s->selected_entry))) {
7558 struct got_tree_object *subtree;
7559 view->count = 0;
7560 err = got_object_open_as_tree(&subtree, s->repo,
7561 got_tree_entry_get_id(s->selected_entry));
7562 if (err)
7563 break;
7564 err = tree_view_visit_subtree(s, subtree);
7565 if (err) {
7566 got_object_tree_close(subtree);
7567 break;
7569 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7570 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7571 break;
7572 case KEY_RESIZE:
7573 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7574 s->selected = view->nlines - 4;
7575 view->count = 0;
7576 break;
7577 default:
7578 view->count = 0;
7579 break;
7582 return err;
7585 __dead static void
7586 usage_tree(void)
7588 endwin();
7589 fprintf(stderr,
7590 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7591 getprogname());
7592 exit(1);
7595 static const struct got_error *
7596 cmd_tree(int argc, char *argv[])
7598 const struct got_error *error;
7599 struct got_repository *repo = NULL;
7600 struct got_worktree *worktree = NULL;
7601 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7602 struct got_object_id *commit_id = NULL;
7603 struct got_commit_object *commit = NULL;
7604 const char *commit_id_arg = NULL;
7605 char *label = NULL;
7606 struct got_reference *ref = NULL;
7607 const char *head_ref_name = NULL;
7608 int ch;
7609 struct tog_view *view;
7610 int *pack_fds = NULL;
7612 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7613 switch (ch) {
7614 case 'c':
7615 commit_id_arg = optarg;
7616 break;
7617 case 'r':
7618 repo_path = realpath(optarg, NULL);
7619 if (repo_path == NULL)
7620 return got_error_from_errno2("realpath",
7621 optarg);
7622 break;
7623 default:
7624 usage_tree();
7625 /* NOTREACHED */
7629 argc -= optind;
7630 argv += optind;
7632 if (argc > 1)
7633 usage_tree();
7635 error = got_repo_pack_fds_open(&pack_fds);
7636 if (error != NULL)
7637 goto done;
7639 if (repo_path == NULL) {
7640 cwd = getcwd(NULL, 0);
7641 if (cwd == NULL)
7642 return got_error_from_errno("getcwd");
7643 error = got_worktree_open(&worktree, cwd);
7644 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7645 goto done;
7646 if (worktree)
7647 repo_path =
7648 strdup(got_worktree_get_repo_path(worktree));
7649 else
7650 repo_path = strdup(cwd);
7651 if (repo_path == NULL) {
7652 error = got_error_from_errno("strdup");
7653 goto done;
7657 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7658 if (error != NULL)
7659 goto done;
7661 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7662 repo, worktree);
7663 if (error)
7664 goto done;
7666 init_curses();
7668 error = apply_unveil(got_repo_get_path(repo), NULL);
7669 if (error)
7670 goto done;
7672 error = tog_load_refs(repo, 0);
7673 if (error)
7674 goto done;
7676 if (commit_id_arg == NULL) {
7677 error = got_repo_match_object_id(&commit_id, &label,
7678 worktree ? got_worktree_get_head_ref_name(worktree) :
7679 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7680 if (error)
7681 goto done;
7682 head_ref_name = label;
7683 } else {
7684 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7685 if (error == NULL)
7686 head_ref_name = got_ref_get_name(ref);
7687 else if (error->code != GOT_ERR_NOT_REF)
7688 goto done;
7689 error = got_repo_match_object_id(&commit_id, NULL,
7690 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7691 if (error)
7692 goto done;
7695 error = got_object_open_as_commit(&commit, repo, commit_id);
7696 if (error)
7697 goto done;
7699 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7700 if (view == NULL) {
7701 error = got_error_from_errno("view_open");
7702 goto done;
7704 error = open_tree_view(view, commit_id, head_ref_name, repo);
7705 if (error)
7706 goto done;
7707 if (!got_path_is_root_dir(in_repo_path)) {
7708 error = tree_view_walk_path(&view->state.tree, commit,
7709 in_repo_path);
7710 if (error)
7711 goto done;
7714 if (worktree) {
7715 /* Release work tree lock. */
7716 got_worktree_close(worktree);
7717 worktree = NULL;
7719 error = view_loop(view);
7720 done:
7721 free(repo_path);
7722 free(cwd);
7723 free(commit_id);
7724 free(label);
7725 if (ref)
7726 got_ref_close(ref);
7727 if (repo) {
7728 const struct got_error *close_err = got_repo_close(repo);
7729 if (error == NULL)
7730 error = close_err;
7732 if (pack_fds) {
7733 const struct got_error *pack_err =
7734 got_repo_pack_fds_close(pack_fds);
7735 if (error == NULL)
7736 error = pack_err;
7738 tog_free_refs();
7739 return error;
7742 static const struct got_error *
7743 ref_view_load_refs(struct tog_ref_view_state *s)
7745 struct got_reflist_entry *sre;
7746 struct tog_reflist_entry *re;
7748 s->nrefs = 0;
7749 TAILQ_FOREACH(sre, &tog_refs, entry) {
7750 if (strncmp(got_ref_get_name(sre->ref),
7751 "refs/got/", 9) == 0 &&
7752 strncmp(got_ref_get_name(sre->ref),
7753 "refs/got/backup/", 16) != 0)
7754 continue;
7756 re = malloc(sizeof(*re));
7757 if (re == NULL)
7758 return got_error_from_errno("malloc");
7760 re->ref = got_ref_dup(sre->ref);
7761 if (re->ref == NULL)
7762 return got_error_from_errno("got_ref_dup");
7763 re->idx = s->nrefs++;
7764 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7767 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7768 return NULL;
7771 static void
7772 ref_view_free_refs(struct tog_ref_view_state *s)
7774 struct tog_reflist_entry *re;
7776 while (!TAILQ_EMPTY(&s->refs)) {
7777 re = TAILQ_FIRST(&s->refs);
7778 TAILQ_REMOVE(&s->refs, re, entry);
7779 got_ref_close(re->ref);
7780 free(re);
7784 static const struct got_error *
7785 open_ref_view(struct tog_view *view, struct got_repository *repo)
7787 const struct got_error *err = NULL;
7788 struct tog_ref_view_state *s = &view->state.ref;
7790 s->selected_entry = 0;
7791 s->repo = repo;
7793 TAILQ_INIT(&s->refs);
7794 STAILQ_INIT(&s->colors);
7796 err = ref_view_load_refs(s);
7797 if (err)
7798 return err;
7800 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7801 err = add_color(&s->colors, "^refs/heads/",
7802 TOG_COLOR_REFS_HEADS,
7803 get_color_value("TOG_COLOR_REFS_HEADS"));
7804 if (err)
7805 goto done;
7807 err = add_color(&s->colors, "^refs/tags/",
7808 TOG_COLOR_REFS_TAGS,
7809 get_color_value("TOG_COLOR_REFS_TAGS"));
7810 if (err)
7811 goto done;
7813 err = add_color(&s->colors, "^refs/remotes/",
7814 TOG_COLOR_REFS_REMOTES,
7815 get_color_value("TOG_COLOR_REFS_REMOTES"));
7816 if (err)
7817 goto done;
7819 err = add_color(&s->colors, "^refs/got/backup/",
7820 TOG_COLOR_REFS_BACKUP,
7821 get_color_value("TOG_COLOR_REFS_BACKUP"));
7822 if (err)
7823 goto done;
7826 view->show = show_ref_view;
7827 view->input = input_ref_view;
7828 view->close = close_ref_view;
7829 view->search_start = search_start_ref_view;
7830 view->search_next = search_next_ref_view;
7831 done:
7832 if (err)
7833 free_colors(&s->colors);
7834 return err;
7837 static const struct got_error *
7838 close_ref_view(struct tog_view *view)
7840 struct tog_ref_view_state *s = &view->state.ref;
7842 ref_view_free_refs(s);
7843 free_colors(&s->colors);
7845 return NULL;
7848 static const struct got_error *
7849 resolve_reflist_entry(struct got_object_id **commit_id,
7850 struct tog_reflist_entry *re, struct got_repository *repo)
7852 const struct got_error *err = NULL;
7853 struct got_object_id *obj_id;
7854 struct got_tag_object *tag = NULL;
7855 int obj_type;
7857 *commit_id = NULL;
7859 err = got_ref_resolve(&obj_id, repo, re->ref);
7860 if (err)
7861 return err;
7863 err = got_object_get_type(&obj_type, repo, obj_id);
7864 if (err)
7865 goto done;
7867 switch (obj_type) {
7868 case GOT_OBJ_TYPE_COMMIT:
7869 *commit_id = obj_id;
7870 break;
7871 case GOT_OBJ_TYPE_TAG:
7872 err = got_object_open_as_tag(&tag, repo, obj_id);
7873 if (err)
7874 goto done;
7875 free(obj_id);
7876 err = got_object_get_type(&obj_type, repo,
7877 got_object_tag_get_object_id(tag));
7878 if (err)
7879 goto done;
7880 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7881 err = got_error(GOT_ERR_OBJ_TYPE);
7882 goto done;
7884 *commit_id = got_object_id_dup(
7885 got_object_tag_get_object_id(tag));
7886 if (*commit_id == NULL) {
7887 err = got_error_from_errno("got_object_id_dup");
7888 goto done;
7890 break;
7891 default:
7892 err = got_error(GOT_ERR_OBJ_TYPE);
7893 break;
7896 done:
7897 if (tag)
7898 got_object_tag_close(tag);
7899 if (err) {
7900 free(*commit_id);
7901 *commit_id = NULL;
7903 return err;
7906 static const struct got_error *
7907 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7908 struct tog_reflist_entry *re, struct got_repository *repo)
7910 struct tog_view *log_view;
7911 const struct got_error *err = NULL;
7912 struct got_object_id *commit_id = NULL;
7914 *new_view = NULL;
7916 err = resolve_reflist_entry(&commit_id, re, repo);
7917 if (err) {
7918 if (err->code != GOT_ERR_OBJ_TYPE)
7919 return err;
7920 else
7921 return NULL;
7924 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7925 if (log_view == NULL) {
7926 err = got_error_from_errno("view_open");
7927 goto done;
7930 err = open_log_view(log_view, commit_id, repo,
7931 got_ref_get_name(re->ref), "", 0);
7932 done:
7933 if (err)
7934 view_close(log_view);
7935 else
7936 *new_view = log_view;
7937 free(commit_id);
7938 return err;
7941 static void
7942 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7944 struct tog_reflist_entry *re;
7945 int i = 0;
7947 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7948 return;
7950 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7951 while (i++ < maxscroll) {
7952 if (re == NULL)
7953 break;
7954 s->first_displayed_entry = re;
7955 re = TAILQ_PREV(re, tog_reflist_head, entry);
7959 static const struct got_error *
7960 ref_scroll_down(struct tog_view *view, int maxscroll)
7962 struct tog_ref_view_state *s = &view->state.ref;
7963 struct tog_reflist_entry *next, *last;
7964 int n = 0;
7966 if (s->first_displayed_entry)
7967 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7968 else
7969 next = TAILQ_FIRST(&s->refs);
7971 last = s->last_displayed_entry;
7972 while (next && n++ < maxscroll) {
7973 if (last) {
7974 s->last_displayed_entry = last;
7975 last = TAILQ_NEXT(last, entry);
7977 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7978 s->first_displayed_entry = next;
7979 next = TAILQ_NEXT(next, entry);
7983 return NULL;
7986 static const struct got_error *
7987 search_start_ref_view(struct tog_view *view)
7989 struct tog_ref_view_state *s = &view->state.ref;
7991 s->matched_entry = NULL;
7992 return NULL;
7995 static int
7996 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7998 regmatch_t regmatch;
8000 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8001 0) == 0;
8004 static const struct got_error *
8005 search_next_ref_view(struct tog_view *view)
8007 struct tog_ref_view_state *s = &view->state.ref;
8008 struct tog_reflist_entry *re = NULL;
8010 if (!view->searching) {
8011 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8012 return NULL;
8015 if (s->matched_entry) {
8016 if (view->searching == TOG_SEARCH_FORWARD) {
8017 if (s->selected_entry)
8018 re = TAILQ_NEXT(s->selected_entry, entry);
8019 else
8020 re = TAILQ_PREV(s->selected_entry,
8021 tog_reflist_head, entry);
8022 } else {
8023 if (s->selected_entry == NULL)
8024 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8025 else
8026 re = TAILQ_PREV(s->selected_entry,
8027 tog_reflist_head, entry);
8029 } else {
8030 if (s->selected_entry)
8031 re = s->selected_entry;
8032 else if (view->searching == TOG_SEARCH_FORWARD)
8033 re = TAILQ_FIRST(&s->refs);
8034 else
8035 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8038 while (1) {
8039 if (re == NULL) {
8040 if (s->matched_entry == NULL) {
8041 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8042 return NULL;
8044 if (view->searching == TOG_SEARCH_FORWARD)
8045 re = TAILQ_FIRST(&s->refs);
8046 else
8047 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8050 if (match_reflist_entry(re, &view->regex)) {
8051 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8052 s->matched_entry = re;
8053 break;
8056 if (view->searching == TOG_SEARCH_FORWARD)
8057 re = TAILQ_NEXT(re, entry);
8058 else
8059 re = TAILQ_PREV(re, tog_reflist_head, entry);
8062 if (s->matched_entry) {
8063 s->first_displayed_entry = s->matched_entry;
8064 s->selected = 0;
8067 return NULL;
8070 static const struct got_error *
8071 show_ref_view(struct tog_view *view)
8073 const struct got_error *err = NULL;
8074 struct tog_ref_view_state *s = &view->state.ref;
8075 struct tog_reflist_entry *re;
8076 char *line = NULL;
8077 wchar_t *wline;
8078 struct tog_color *tc;
8079 int width, n, scrollx;
8080 int limit = view->nlines;
8082 werase(view->window);
8084 s->ndisplayed = 0;
8085 if (view_is_hsplit_top(view))
8086 --limit; /* border */
8088 if (limit == 0)
8089 return NULL;
8091 re = s->first_displayed_entry;
8093 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8094 s->nrefs) == -1)
8095 return got_error_from_errno("asprintf");
8097 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8098 if (err) {
8099 free(line);
8100 return err;
8102 if (view_needs_focus_indication(view))
8103 wstandout(view->window);
8104 waddwstr(view->window, wline);
8105 while (width++ < view->ncols)
8106 waddch(view->window, ' ');
8107 if (view_needs_focus_indication(view))
8108 wstandend(view->window);
8109 free(wline);
8110 wline = NULL;
8111 free(line);
8112 line = NULL;
8113 if (--limit <= 0)
8114 return NULL;
8116 n = 0;
8117 view->maxx = 0;
8118 while (re && limit > 0) {
8119 char *line = NULL;
8120 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8122 if (s->show_date) {
8123 struct got_commit_object *ci;
8124 struct got_tag_object *tag;
8125 struct got_object_id *id;
8126 struct tm tm;
8127 time_t t;
8129 err = got_ref_resolve(&id, s->repo, re->ref);
8130 if (err)
8131 return err;
8132 err = got_object_open_as_tag(&tag, s->repo, id);
8133 if (err) {
8134 if (err->code != GOT_ERR_OBJ_TYPE) {
8135 free(id);
8136 return err;
8138 err = got_object_open_as_commit(&ci, s->repo,
8139 id);
8140 if (err) {
8141 free(id);
8142 return err;
8144 t = got_object_commit_get_committer_time(ci);
8145 got_object_commit_close(ci);
8146 } else {
8147 t = got_object_tag_get_tagger_time(tag);
8148 got_object_tag_close(tag);
8150 free(id);
8151 if (gmtime_r(&t, &tm) == NULL)
8152 return got_error_from_errno("gmtime_r");
8153 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8154 return got_error(GOT_ERR_NO_SPACE);
8156 if (got_ref_is_symbolic(re->ref)) {
8157 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8158 ymd : "", got_ref_get_name(re->ref),
8159 got_ref_get_symref_target(re->ref)) == -1)
8160 return got_error_from_errno("asprintf");
8161 } else if (s->show_ids) {
8162 struct got_object_id *id;
8163 char *id_str;
8164 err = got_ref_resolve(&id, s->repo, re->ref);
8165 if (err)
8166 return err;
8167 err = got_object_id_str(&id_str, id);
8168 if (err) {
8169 free(id);
8170 return err;
8172 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8173 got_ref_get_name(re->ref), id_str) == -1) {
8174 err = got_error_from_errno("asprintf");
8175 free(id);
8176 free(id_str);
8177 return err;
8179 free(id);
8180 free(id_str);
8181 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8182 got_ref_get_name(re->ref)) == -1)
8183 return got_error_from_errno("asprintf");
8185 /* use full line width to determine view->maxx */
8186 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8187 if (err) {
8188 free(line);
8189 return err;
8191 view->maxx = MAX(view->maxx, width);
8192 free(wline);
8193 wline = NULL;
8195 err = format_line(&wline, &width, &scrollx, line, view->x,
8196 view->ncols, 0, 0);
8197 if (err) {
8198 free(line);
8199 return err;
8201 if (n == s->selected) {
8202 if (view->focussed)
8203 wstandout(view->window);
8204 s->selected_entry = re;
8206 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8207 if (tc)
8208 wattr_on(view->window,
8209 COLOR_PAIR(tc->colorpair), NULL);
8210 waddwstr(view->window, &wline[scrollx]);
8211 if (tc)
8212 wattr_off(view->window,
8213 COLOR_PAIR(tc->colorpair), NULL);
8214 if (width < view->ncols)
8215 waddch(view->window, '\n');
8216 if (n == s->selected && view->focussed)
8217 wstandend(view->window);
8218 free(line);
8219 free(wline);
8220 wline = NULL;
8221 n++;
8222 s->ndisplayed++;
8223 s->last_displayed_entry = re;
8225 limit--;
8226 re = TAILQ_NEXT(re, entry);
8229 view_border(view);
8230 return err;
8233 static const struct got_error *
8234 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8235 struct tog_reflist_entry *re, struct got_repository *repo)
8237 const struct got_error *err = NULL;
8238 struct got_object_id *commit_id = NULL;
8239 struct tog_view *tree_view;
8241 *new_view = NULL;
8243 err = resolve_reflist_entry(&commit_id, re, repo);
8244 if (err) {
8245 if (err->code != GOT_ERR_OBJ_TYPE)
8246 return err;
8247 else
8248 return NULL;
8252 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8253 if (tree_view == NULL) {
8254 err = got_error_from_errno("view_open");
8255 goto done;
8258 err = open_tree_view(tree_view, commit_id,
8259 got_ref_get_name(re->ref), repo);
8260 if (err)
8261 goto done;
8263 *new_view = tree_view;
8264 done:
8265 free(commit_id);
8266 return err;
8269 static const struct got_error *
8270 ref_goto_line(struct tog_view *view, int nlines)
8272 const struct got_error *err = NULL;
8273 struct tog_ref_view_state *s = &view->state.ref;
8274 int g, idx = s->selected_entry->idx;
8276 g = view->gline;
8277 view->gline = 0;
8279 if (g == 0)
8280 g = 1;
8281 else if (g > s->nrefs)
8282 g = s->nrefs;
8284 if (g >= s->first_displayed_entry->idx + 1 &&
8285 g <= s->last_displayed_entry->idx + 1 &&
8286 g - s->first_displayed_entry->idx - 1 < nlines) {
8287 s->selected = g - s->first_displayed_entry->idx - 1;
8288 return NULL;
8291 if (idx + 1 < g) {
8292 err = ref_scroll_down(view, g - idx - 1);
8293 if (err)
8294 return err;
8295 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8296 s->first_displayed_entry->idx + s->selected < g &&
8297 s->selected < s->ndisplayed - 1)
8298 s->selected = g - s->first_displayed_entry->idx - 1;
8299 } else if (idx + 1 > g)
8300 ref_scroll_up(s, idx - g + 1);
8302 if (g < nlines && s->first_displayed_entry->idx == 0)
8303 s->selected = g - 1;
8305 return NULL;
8309 static const struct got_error *
8310 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8312 const struct got_error *err = NULL;
8313 struct tog_ref_view_state *s = &view->state.ref;
8314 struct tog_reflist_entry *re;
8315 int n, nscroll = view->nlines - 1;
8317 if (view->gline)
8318 return ref_goto_line(view, nscroll);
8320 switch (ch) {
8321 case '0':
8322 case '$':
8323 case KEY_RIGHT:
8324 case 'l':
8325 case KEY_LEFT:
8326 case 'h':
8327 horizontal_scroll_input(view, ch);
8328 break;
8329 case 'i':
8330 s->show_ids = !s->show_ids;
8331 view->count = 0;
8332 break;
8333 case 'm':
8334 s->show_date = !s->show_date;
8335 view->count = 0;
8336 break;
8337 case 'o':
8338 s->sort_by_date = !s->sort_by_date;
8339 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8340 view->count = 0;
8341 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8342 got_ref_cmp_by_commit_timestamp_descending :
8343 tog_ref_cmp_by_name, s->repo);
8344 if (err)
8345 break;
8346 got_reflist_object_id_map_free(tog_refs_idmap);
8347 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8348 &tog_refs, s->repo);
8349 if (err)
8350 break;
8351 ref_view_free_refs(s);
8352 err = ref_view_load_refs(s);
8353 break;
8354 case KEY_ENTER:
8355 case '\r':
8356 view->count = 0;
8357 if (!s->selected_entry)
8358 break;
8359 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8360 break;
8361 case 'T':
8362 view->count = 0;
8363 if (!s->selected_entry)
8364 break;
8365 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8366 break;
8367 case 'g':
8368 case '=':
8369 case KEY_HOME:
8370 s->selected = 0;
8371 view->count = 0;
8372 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8373 break;
8374 case 'G':
8375 case '*':
8376 case KEY_END: {
8377 int eos = view->nlines - 1;
8379 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8380 --eos; /* border */
8381 s->selected = 0;
8382 view->count = 0;
8383 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8384 for (n = 0; n < eos; n++) {
8385 if (re == NULL)
8386 break;
8387 s->first_displayed_entry = re;
8388 re = TAILQ_PREV(re, tog_reflist_head, entry);
8390 if (n > 0)
8391 s->selected = n - 1;
8392 break;
8394 case 'k':
8395 case KEY_UP:
8396 case CTRL('p'):
8397 if (s->selected > 0) {
8398 s->selected--;
8399 break;
8401 ref_scroll_up(s, 1);
8402 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8403 view->count = 0;
8404 break;
8405 case CTRL('u'):
8406 case 'u':
8407 nscroll /= 2;
8408 /* FALL THROUGH */
8409 case KEY_PPAGE:
8410 case CTRL('b'):
8411 case 'b':
8412 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8413 s->selected -= MIN(nscroll, s->selected);
8414 ref_scroll_up(s, MAX(0, nscroll));
8415 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8416 view->count = 0;
8417 break;
8418 case 'j':
8419 case KEY_DOWN:
8420 case CTRL('n'):
8421 if (s->selected < s->ndisplayed - 1) {
8422 s->selected++;
8423 break;
8425 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8426 /* can't scroll any further */
8427 view->count = 0;
8428 break;
8430 ref_scroll_down(view, 1);
8431 break;
8432 case CTRL('d'):
8433 case 'd':
8434 nscroll /= 2;
8435 /* FALL THROUGH */
8436 case KEY_NPAGE:
8437 case CTRL('f'):
8438 case 'f':
8439 case ' ':
8440 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8441 /* can't scroll any further; move cursor down */
8442 if (s->selected < s->ndisplayed - 1)
8443 s->selected += MIN(nscroll,
8444 s->ndisplayed - s->selected - 1);
8445 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8446 s->selected += s->ndisplayed - s->selected - 1;
8447 view->count = 0;
8448 break;
8450 ref_scroll_down(view, nscroll);
8451 break;
8452 case CTRL('l'):
8453 view->count = 0;
8454 tog_free_refs();
8455 err = tog_load_refs(s->repo, s->sort_by_date);
8456 if (err)
8457 break;
8458 ref_view_free_refs(s);
8459 err = ref_view_load_refs(s);
8460 break;
8461 case KEY_RESIZE:
8462 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8463 s->selected = view->nlines - 2;
8464 break;
8465 default:
8466 view->count = 0;
8467 break;
8470 return err;
8473 __dead static void
8474 usage_ref(void)
8476 endwin();
8477 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8478 getprogname());
8479 exit(1);
8482 static const struct got_error *
8483 cmd_ref(int argc, char *argv[])
8485 const struct got_error *error;
8486 struct got_repository *repo = NULL;
8487 struct got_worktree *worktree = NULL;
8488 char *cwd = NULL, *repo_path = NULL;
8489 int ch;
8490 struct tog_view *view;
8491 int *pack_fds = NULL;
8493 while ((ch = getopt(argc, argv, "r:")) != -1) {
8494 switch (ch) {
8495 case 'r':
8496 repo_path = realpath(optarg, NULL);
8497 if (repo_path == NULL)
8498 return got_error_from_errno2("realpath",
8499 optarg);
8500 break;
8501 default:
8502 usage_ref();
8503 /* NOTREACHED */
8507 argc -= optind;
8508 argv += optind;
8510 if (argc > 1)
8511 usage_ref();
8513 error = got_repo_pack_fds_open(&pack_fds);
8514 if (error != NULL)
8515 goto done;
8517 if (repo_path == NULL) {
8518 cwd = getcwd(NULL, 0);
8519 if (cwd == NULL)
8520 return got_error_from_errno("getcwd");
8521 error = got_worktree_open(&worktree, cwd);
8522 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8523 goto done;
8524 if (worktree)
8525 repo_path =
8526 strdup(got_worktree_get_repo_path(worktree));
8527 else
8528 repo_path = strdup(cwd);
8529 if (repo_path == NULL) {
8530 error = got_error_from_errno("strdup");
8531 goto done;
8535 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8536 if (error != NULL)
8537 goto done;
8539 init_curses();
8541 error = apply_unveil(got_repo_get_path(repo), NULL);
8542 if (error)
8543 goto done;
8545 error = tog_load_refs(repo, 0);
8546 if (error)
8547 goto done;
8549 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8550 if (view == NULL) {
8551 error = got_error_from_errno("view_open");
8552 goto done;
8555 error = open_ref_view(view, repo);
8556 if (error)
8557 goto done;
8559 if (worktree) {
8560 /* Release work tree lock. */
8561 got_worktree_close(worktree);
8562 worktree = NULL;
8564 error = view_loop(view);
8565 done:
8566 free(repo_path);
8567 free(cwd);
8568 if (repo) {
8569 const struct got_error *close_err = got_repo_close(repo);
8570 if (close_err)
8571 error = close_err;
8573 if (pack_fds) {
8574 const struct got_error *pack_err =
8575 got_repo_pack_fds_close(pack_fds);
8576 if (error == NULL)
8577 error = pack_err;
8579 tog_free_refs();
8580 return error;
8583 static const struct got_error*
8584 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8585 const char *str)
8587 size_t len;
8589 if (win == NULL)
8590 win = stdscr;
8592 len = strlen(str);
8593 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8595 if (focus)
8596 wstandout(win);
8597 if (mvwprintw(win, y, x, "%s", str) == ERR)
8598 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8599 if (focus)
8600 wstandend(win);
8602 return NULL;
8605 static const struct got_error *
8606 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8608 off_t *p;
8610 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8611 if (p == NULL) {
8612 free(*line_offsets);
8613 *line_offsets = NULL;
8614 return got_error_from_errno("reallocarray");
8617 *line_offsets = p;
8618 (*line_offsets)[*nlines] = off;
8619 ++(*nlines);
8620 return NULL;
8623 static const struct got_error *
8624 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8626 *ret = 0;
8628 for (;n > 0; --n, ++km) {
8629 char *t0, *t, *k;
8630 size_t len = 1;
8632 if (km->keys == NULL)
8633 continue;
8635 t = t0 = strdup(km->keys);
8636 if (t0 == NULL)
8637 return got_error_from_errno("strdup");
8639 len += strlen(t);
8640 while ((k = strsep(&t, " ")) != NULL)
8641 len += strlen(k) > 1 ? 2 : 0;
8642 free(t0);
8643 *ret = MAX(*ret, len);
8646 return NULL;
8650 * Write keymap section headers, keys, and key info in km to f.
8651 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8652 * wrap control and symbolic keys in guillemets, else use <>.
8654 static const struct got_error *
8655 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8657 int n, len = width;
8659 if (km->keys) {
8660 static const char *u8_glyph[] = {
8661 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8662 "\xe2\x80\xba" /* U+203A (utf8 >) */
8664 char *t0, *t, *k;
8665 int cs, s, first = 1;
8667 cs = got_locale_is_utf8();
8669 t = t0 = strdup(km->keys);
8670 if (t0 == NULL)
8671 return got_error_from_errno("strdup");
8673 len = strlen(km->keys);
8674 while ((k = strsep(&t, " ")) != NULL) {
8675 s = strlen(k) > 1; /* control or symbolic key */
8676 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8677 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8678 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8679 if (n < 0) {
8680 free(t0);
8681 return got_error_from_errno("fprintf");
8683 first = 0;
8684 len += s ? 2 : 0;
8685 *off += n;
8687 free(t0);
8689 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8690 if (n < 0)
8691 return got_error_from_errno("fprintf");
8692 *off += n;
8694 return NULL;
8697 static const struct got_error *
8698 format_help(struct tog_help_view_state *s)
8700 const struct got_error *err = NULL;
8701 off_t off = 0;
8702 int i, max, n, show = s->all;
8703 static const struct tog_key_map km[] = {
8704 #define KEYMAP_(info, type) { NULL, (info), type }
8705 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8706 GENERATE_HELP
8707 #undef KEYMAP_
8708 #undef KEY_
8711 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8712 if (err)
8713 return err;
8715 n = nitems(km);
8716 err = max_key_str(&max, km, n);
8717 if (err)
8718 return err;
8720 for (i = 0; i < n; ++i) {
8721 if (km[i].keys == NULL) {
8722 show = s->all;
8723 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8724 km[i].type == s->type || s->all)
8725 show = 1;
8727 if (show) {
8728 err = format_help_line(&off, s->f, &km[i], max);
8729 if (err)
8730 return err;
8731 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8732 if (err)
8733 return err;
8736 fputc('\n', s->f);
8737 ++off;
8738 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8739 return err;
8742 static const struct got_error *
8743 create_help(struct tog_help_view_state *s)
8745 FILE *f;
8746 const struct got_error *err;
8748 free(s->line_offsets);
8749 s->line_offsets = NULL;
8750 s->nlines = 0;
8752 f = got_opentemp();
8753 if (f == NULL)
8754 return got_error_from_errno("got_opentemp");
8755 s->f = f;
8757 err = format_help(s);
8758 if (err)
8759 return err;
8761 if (s->f && fflush(s->f) != 0)
8762 return got_error_from_errno("fflush");
8764 return NULL;
8767 static const struct got_error *
8768 search_start_help_view(struct tog_view *view)
8770 view->state.help.matched_line = 0;
8771 return NULL;
8774 static void
8775 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8776 size_t *nlines, int **first, int **last, int **match, int **selected)
8778 struct tog_help_view_state *s = &view->state.help;
8780 *f = s->f;
8781 *nlines = s->nlines;
8782 *line_offsets = s->line_offsets;
8783 *match = &s->matched_line;
8784 *first = &s->first_displayed_line;
8785 *last = &s->last_displayed_line;
8786 *selected = &s->selected_line;
8789 static const struct got_error *
8790 show_help_view(struct tog_view *view)
8792 struct tog_help_view_state *s = &view->state.help;
8793 const struct got_error *err;
8794 regmatch_t *regmatch = &view->regmatch;
8795 wchar_t *wline;
8796 char *line;
8797 ssize_t linelen;
8798 size_t linesz = 0;
8799 int width, nprinted = 0, rc = 0;
8800 int eos = view->nlines;
8802 if (view_is_hsplit_top(view))
8803 --eos; /* account for border */
8805 s->lineno = 0;
8806 rewind(s->f);
8807 werase(view->window);
8809 if (view->gline > s->nlines - 1)
8810 view->gline = s->nlines - 1;
8812 err = win_draw_center(view->window, 0, 0, view->ncols,
8813 view_needs_focus_indication(view),
8814 "tog help (press q to return to tog)");
8815 if (err)
8816 return err;
8817 if (eos <= 1)
8818 return NULL;
8819 waddstr(view->window, "\n\n");
8820 eos -= 2;
8822 s->eof = 0;
8823 view->maxx = 0;
8824 line = NULL;
8825 while (eos > 0 && nprinted < eos) {
8826 attr_t attr = 0;
8828 linelen = getline(&line, &linesz, s->f);
8829 if (linelen == -1) {
8830 if (!feof(s->f)) {
8831 free(line);
8832 return got_ferror(s->f, GOT_ERR_IO);
8834 s->eof = 1;
8835 break;
8837 if (++s->lineno < s->first_displayed_line)
8838 continue;
8839 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8840 continue;
8841 if (s->lineno == view->hiline)
8842 attr = A_STANDOUT;
8844 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8845 view->x ? 1 : 0);
8846 if (err) {
8847 free(line);
8848 return err;
8850 view->maxx = MAX(view->maxx, width);
8851 free(wline);
8852 wline = NULL;
8854 if (attr)
8855 wattron(view->window, attr);
8856 if (s->first_displayed_line + nprinted == s->matched_line &&
8857 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8858 err = add_matched_line(&width, line, view->ncols - 1, 0,
8859 view->window, view->x, regmatch);
8860 if (err) {
8861 free(line);
8862 return err;
8864 } else {
8865 int skip;
8867 err = format_line(&wline, &width, &skip, line,
8868 view->x, view->ncols, 0, view->x ? 1 : 0);
8869 if (err) {
8870 free(line);
8871 return err;
8873 waddwstr(view->window, &wline[skip]);
8874 free(wline);
8875 wline = NULL;
8877 if (s->lineno == view->hiline) {
8878 while (width++ < view->ncols)
8879 waddch(view->window, ' ');
8880 } else {
8881 if (width < view->ncols)
8882 waddch(view->window, '\n');
8884 if (attr)
8885 wattroff(view->window, attr);
8886 if (++nprinted == 1)
8887 s->first_displayed_line = s->lineno;
8889 free(line);
8890 if (nprinted > 0)
8891 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8892 else
8893 s->last_displayed_line = s->first_displayed_line;
8895 view_border(view);
8897 if (s->eof) {
8898 rc = waddnstr(view->window,
8899 "See the tog(1) manual page for full documentation",
8900 view->ncols - 1);
8901 if (rc == ERR)
8902 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8903 } else {
8904 wmove(view->window, view->nlines - 1, 0);
8905 wclrtoeol(view->window);
8906 wstandout(view->window);
8907 rc = waddnstr(view->window, "scroll down for more...",
8908 view->ncols - 1);
8909 if (rc == ERR)
8910 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8911 if (getcurx(view->window) < view->ncols - 6) {
8912 rc = wprintw(view->window, "[%.0f%%]",
8913 100.00 * s->last_displayed_line / s->nlines);
8914 if (rc == ERR)
8915 return got_error_msg(GOT_ERR_IO, "wprintw");
8917 wstandend(view->window);
8920 return NULL;
8923 static const struct got_error *
8924 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8926 struct tog_help_view_state *s = &view->state.help;
8927 const struct got_error *err = NULL;
8928 char *line = NULL;
8929 ssize_t linelen;
8930 size_t linesz = 0;
8931 int eos, nscroll;
8933 eos = nscroll = view->nlines;
8934 if (view_is_hsplit_top(view))
8935 --eos; /* border */
8937 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8939 switch (ch) {
8940 case '0':
8941 case '$':
8942 case KEY_RIGHT:
8943 case 'l':
8944 case KEY_LEFT:
8945 case 'h':
8946 horizontal_scroll_input(view, ch);
8947 break;
8948 case 'g':
8949 case KEY_HOME:
8950 s->first_displayed_line = 1;
8951 view->count = 0;
8952 break;
8953 case 'G':
8954 case KEY_END:
8955 view->count = 0;
8956 if (s->eof)
8957 break;
8958 s->first_displayed_line = (s->nlines - eos) + 3;
8959 s->eof = 1;
8960 break;
8961 case 'k':
8962 case KEY_UP:
8963 if (s->first_displayed_line > 1)
8964 --s->first_displayed_line;
8965 else
8966 view->count = 0;
8967 break;
8968 case CTRL('u'):
8969 case 'u':
8970 nscroll /= 2;
8971 /* FALL THROUGH */
8972 case KEY_PPAGE:
8973 case CTRL('b'):
8974 case 'b':
8975 if (s->first_displayed_line == 1) {
8976 view->count = 0;
8977 break;
8979 while (--nscroll > 0 && s->first_displayed_line > 1)
8980 s->first_displayed_line--;
8981 break;
8982 case 'j':
8983 case KEY_DOWN:
8984 case CTRL('n'):
8985 if (!s->eof)
8986 ++s->first_displayed_line;
8987 else
8988 view->count = 0;
8989 break;
8990 case CTRL('d'):
8991 case 'd':
8992 nscroll /= 2;
8993 /* FALL THROUGH */
8994 case KEY_NPAGE:
8995 case CTRL('f'):
8996 case 'f':
8997 case ' ':
8998 if (s->eof) {
8999 view->count = 0;
9000 break;
9002 while (!s->eof && --nscroll > 0) {
9003 linelen = getline(&line, &linesz, s->f);
9004 s->first_displayed_line++;
9005 if (linelen == -1) {
9006 if (feof(s->f))
9007 s->eof = 1;
9008 else
9009 err = got_ferror(s->f, GOT_ERR_IO);
9010 break;
9013 free(line);
9014 break;
9015 default:
9016 view->count = 0;
9017 break;
9020 return err;
9023 static const struct got_error *
9024 close_help_view(struct tog_view *view)
9026 struct tog_help_view_state *s = &view->state.help;
9028 free(s->line_offsets);
9029 s->line_offsets = NULL;
9030 if (fclose(s->f) == EOF)
9031 return got_error_from_errno("fclose");
9033 return NULL;
9036 static const struct got_error *
9037 reset_help_view(struct tog_view *view)
9039 struct tog_help_view_state *s = &view->state.help;
9042 if (s->f && fclose(s->f) == EOF)
9043 return got_error_from_errno("fclose");
9045 wclear(view->window);
9046 view->count = 0;
9047 view->x = 0;
9048 s->all = !s->all;
9049 s->first_displayed_line = 1;
9050 s->last_displayed_line = view->nlines;
9051 s->matched_line = 0;
9053 return create_help(s);
9056 static const struct got_error *
9057 open_help_view(struct tog_view *view, struct tog_view *parent)
9059 const struct got_error *err = NULL;
9060 struct tog_help_view_state *s = &view->state.help;
9062 s->type = (enum tog_keymap_type)parent->type;
9063 s->first_displayed_line = 1;
9064 s->last_displayed_line = view->nlines;
9065 s->selected_line = 1;
9067 view->show = show_help_view;
9068 view->input = input_help_view;
9069 view->reset = reset_help_view;
9070 view->close = close_help_view;
9071 view->search_start = search_start_help_view;
9072 view->search_setup = search_setup_help_view;
9073 view->search_next = search_next_view_match;
9075 err = create_help(s);
9076 return err;
9079 static const struct got_error *
9080 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9081 enum tog_view_type request, int y, int x)
9083 const struct got_error *err = NULL;
9085 *new_view = NULL;
9087 switch (request) {
9088 case TOG_VIEW_DIFF:
9089 if (view->type == TOG_VIEW_LOG) {
9090 struct tog_log_view_state *s = &view->state.log;
9092 err = open_diff_view_for_commit(new_view, y, x,
9093 s->selected_entry->commit, s->selected_entry->id,
9094 view, s->repo);
9095 } else
9096 return got_error_msg(GOT_ERR_NOT_IMPL,
9097 "parent/child view pair not supported");
9098 break;
9099 case TOG_VIEW_BLAME:
9100 if (view->type == TOG_VIEW_TREE) {
9101 struct tog_tree_view_state *s = &view->state.tree;
9103 err = blame_tree_entry(new_view, y, x,
9104 s->selected_entry, &s->parents, s->commit_id,
9105 s->repo);
9106 } else
9107 return got_error_msg(GOT_ERR_NOT_IMPL,
9108 "parent/child view pair not supported");
9109 break;
9110 case TOG_VIEW_LOG:
9111 if (view->type == TOG_VIEW_BLAME)
9112 err = log_annotated_line(new_view, y, x,
9113 view->state.blame.repo, view->state.blame.id_to_log);
9114 else if (view->type == TOG_VIEW_TREE)
9115 err = log_selected_tree_entry(new_view, y, x,
9116 &view->state.tree);
9117 else if (view->type == TOG_VIEW_REF)
9118 err = log_ref_entry(new_view, y, x,
9119 view->state.ref.selected_entry,
9120 view->state.ref.repo);
9121 else
9122 return got_error_msg(GOT_ERR_NOT_IMPL,
9123 "parent/child view pair not supported");
9124 break;
9125 case TOG_VIEW_TREE:
9126 if (view->type == TOG_VIEW_LOG)
9127 err = browse_commit_tree(new_view, y, x,
9128 view->state.log.selected_entry,
9129 view->state.log.in_repo_path,
9130 view->state.log.head_ref_name,
9131 view->state.log.repo);
9132 else if (view->type == TOG_VIEW_REF)
9133 err = browse_ref_tree(new_view, y, x,
9134 view->state.ref.selected_entry,
9135 view->state.ref.repo);
9136 else
9137 return got_error_msg(GOT_ERR_NOT_IMPL,
9138 "parent/child view pair not supported");
9139 break;
9140 case TOG_VIEW_REF:
9141 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9142 if (*new_view == NULL)
9143 return got_error_from_errno("view_open");
9144 if (view->type == TOG_VIEW_LOG)
9145 err = open_ref_view(*new_view, view->state.log.repo);
9146 else if (view->type == TOG_VIEW_TREE)
9147 err = open_ref_view(*new_view, view->state.tree.repo);
9148 else
9149 err = got_error_msg(GOT_ERR_NOT_IMPL,
9150 "parent/child view pair not supported");
9151 if (err)
9152 view_close(*new_view);
9153 break;
9154 case TOG_VIEW_HELP:
9155 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9156 if (*new_view == NULL)
9157 return got_error_from_errno("view_open");
9158 err = open_help_view(*new_view, view);
9159 if (err)
9160 view_close(*new_view);
9161 break;
9162 default:
9163 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9166 return err;
9170 * If view was scrolled down to move the selected line into view when opening a
9171 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9173 static void
9174 offset_selection_up(struct tog_view *view)
9176 switch (view->type) {
9177 case TOG_VIEW_BLAME: {
9178 struct tog_blame_view_state *s = &view->state.blame;
9179 if (s->first_displayed_line == 1) {
9180 s->selected_line = MAX(s->selected_line - view->offset,
9181 1);
9182 break;
9184 if (s->first_displayed_line > view->offset)
9185 s->first_displayed_line -= view->offset;
9186 else
9187 s->first_displayed_line = 1;
9188 s->selected_line += view->offset;
9189 break;
9191 case TOG_VIEW_LOG:
9192 log_scroll_up(&view->state.log, view->offset);
9193 view->state.log.selected += view->offset;
9194 break;
9195 case TOG_VIEW_REF:
9196 ref_scroll_up(&view->state.ref, view->offset);
9197 view->state.ref.selected += view->offset;
9198 break;
9199 case TOG_VIEW_TREE:
9200 tree_scroll_up(&view->state.tree, view->offset);
9201 view->state.tree.selected += view->offset;
9202 break;
9203 default:
9204 break;
9207 view->offset = 0;
9211 * If the selected line is in the section of screen covered by the bottom split,
9212 * scroll down offset lines to move it into view and index its new position.
9214 static const struct got_error *
9215 offset_selection_down(struct tog_view *view)
9217 const struct got_error *err = NULL;
9218 const struct got_error *(*scrolld)(struct tog_view *, int);
9219 int *selected = NULL;
9220 int header, offset;
9222 switch (view->type) {
9223 case TOG_VIEW_BLAME: {
9224 struct tog_blame_view_state *s = &view->state.blame;
9225 header = 3;
9226 scrolld = NULL;
9227 if (s->selected_line > view->nlines - header) {
9228 offset = abs(view->nlines - s->selected_line - header);
9229 s->first_displayed_line += offset;
9230 s->selected_line -= offset;
9231 view->offset = offset;
9233 break;
9235 case TOG_VIEW_LOG: {
9236 struct tog_log_view_state *s = &view->state.log;
9237 scrolld = &log_scroll_down;
9238 header = view_is_parent_view(view) ? 3 : 2;
9239 selected = &s->selected;
9240 break;
9242 case TOG_VIEW_REF: {
9243 struct tog_ref_view_state *s = &view->state.ref;
9244 scrolld = &ref_scroll_down;
9245 header = 3;
9246 selected = &s->selected;
9247 break;
9249 case TOG_VIEW_TREE: {
9250 struct tog_tree_view_state *s = &view->state.tree;
9251 scrolld = &tree_scroll_down;
9252 header = 5;
9253 selected = &s->selected;
9254 break;
9256 default:
9257 selected = NULL;
9258 scrolld = NULL;
9259 header = 0;
9260 break;
9263 if (selected && *selected > view->nlines - header) {
9264 offset = abs(view->nlines - *selected - header);
9265 view->offset = offset;
9266 if (scrolld && offset) {
9267 err = scrolld(view, offset);
9268 *selected -= offset;
9272 return err;
9275 static void
9276 list_commands(FILE *fp)
9278 size_t i;
9280 fprintf(fp, "commands:");
9281 for (i = 0; i < nitems(tog_commands); i++) {
9282 const struct tog_cmd *cmd = &tog_commands[i];
9283 fprintf(fp, " %s", cmd->name);
9285 fputc('\n', fp);
9288 __dead static void
9289 usage(int hflag, int status)
9291 FILE *fp = (status == 0) ? stdout : stderr;
9293 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9294 getprogname());
9295 if (hflag) {
9296 fprintf(fp, "lazy usage: %s path\n", getprogname());
9297 list_commands(fp);
9299 exit(status);
9302 static char **
9303 make_argv(int argc, ...)
9305 va_list ap;
9306 char **argv;
9307 int i;
9309 va_start(ap, argc);
9311 argv = calloc(argc, sizeof(char *));
9312 if (argv == NULL)
9313 err(1, "calloc");
9314 for (i = 0; i < argc; i++) {
9315 argv[i] = strdup(va_arg(ap, char *));
9316 if (argv[i] == NULL)
9317 err(1, "strdup");
9320 va_end(ap);
9321 return argv;
9325 * Try to convert 'tog path' into a 'tog log path' command.
9326 * The user could simply have mistyped the command rather than knowingly
9327 * provided a path. So check whether argv[0] can in fact be resolved
9328 * to a path in the HEAD commit and print a special error if not.
9329 * This hack is for mpi@ <3
9331 static const struct got_error *
9332 tog_log_with_path(int argc, char *argv[])
9334 const struct got_error *error = NULL, *close_err;
9335 const struct tog_cmd *cmd = NULL;
9336 struct got_repository *repo = NULL;
9337 struct got_worktree *worktree = NULL;
9338 struct got_object_id *commit_id = NULL, *id = NULL;
9339 struct got_commit_object *commit = NULL;
9340 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9341 char *commit_id_str = NULL, **cmd_argv = NULL;
9342 int *pack_fds = NULL;
9344 cwd = getcwd(NULL, 0);
9345 if (cwd == NULL)
9346 return got_error_from_errno("getcwd");
9348 error = got_repo_pack_fds_open(&pack_fds);
9349 if (error != NULL)
9350 goto done;
9352 error = got_worktree_open(&worktree, cwd);
9353 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9354 goto done;
9356 if (worktree)
9357 repo_path = strdup(got_worktree_get_repo_path(worktree));
9358 else
9359 repo_path = strdup(cwd);
9360 if (repo_path == NULL) {
9361 error = got_error_from_errno("strdup");
9362 goto done;
9365 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9366 if (error != NULL)
9367 goto done;
9369 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9370 repo, worktree);
9371 if (error)
9372 goto done;
9374 error = tog_load_refs(repo, 0);
9375 if (error)
9376 goto done;
9377 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9378 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9379 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9380 if (error)
9381 goto done;
9383 if (worktree) {
9384 got_worktree_close(worktree);
9385 worktree = NULL;
9388 error = got_object_open_as_commit(&commit, repo, commit_id);
9389 if (error)
9390 goto done;
9392 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9393 if (error) {
9394 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9395 goto done;
9396 fprintf(stderr, "%s: '%s' is no known command or path\n",
9397 getprogname(), argv[0]);
9398 usage(1, 1);
9399 /* not reached */
9402 error = got_object_id_str(&commit_id_str, commit_id);
9403 if (error)
9404 goto done;
9406 cmd = &tog_commands[0]; /* log */
9407 argc = 4;
9408 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9409 error = cmd->cmd_main(argc, cmd_argv);
9410 done:
9411 if (repo) {
9412 close_err = got_repo_close(repo);
9413 if (error == NULL)
9414 error = close_err;
9416 if (commit)
9417 got_object_commit_close(commit);
9418 if (worktree)
9419 got_worktree_close(worktree);
9420 if (pack_fds) {
9421 const struct got_error *pack_err =
9422 got_repo_pack_fds_close(pack_fds);
9423 if (error == NULL)
9424 error = pack_err;
9426 free(id);
9427 free(commit_id_str);
9428 free(commit_id);
9429 free(cwd);
9430 free(repo_path);
9431 free(in_repo_path);
9432 if (cmd_argv) {
9433 int i;
9434 for (i = 0; i < argc; i++)
9435 free(cmd_argv[i]);
9436 free(cmd_argv);
9438 tog_free_refs();
9439 return error;
9442 int
9443 main(int argc, char *argv[])
9445 const struct got_error *error = NULL;
9446 const struct tog_cmd *cmd = NULL;
9447 int ch, hflag = 0, Vflag = 0;
9448 char **cmd_argv = NULL;
9449 static const struct option longopts[] = {
9450 { "version", no_argument, NULL, 'V' },
9451 { NULL, 0, NULL, 0}
9453 char *diff_algo_str = NULL;
9455 if (!isatty(STDIN_FILENO))
9456 errx(1, "standard input is not a tty");
9458 setlocale(LC_CTYPE, "");
9460 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9461 switch (ch) {
9462 case 'h':
9463 hflag = 1;
9464 break;
9465 case 'V':
9466 Vflag = 1;
9467 break;
9468 default:
9469 usage(hflag, 1);
9470 /* NOTREACHED */
9474 argc -= optind;
9475 argv += optind;
9476 optind = 1;
9477 optreset = 1;
9479 if (Vflag) {
9480 got_version_print_str();
9481 return 0;
9484 #ifndef PROFILE
9485 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9486 NULL) == -1)
9487 err(1, "pledge");
9488 #endif
9490 if (argc == 0) {
9491 if (hflag)
9492 usage(hflag, 0);
9493 /* Build an argument vector which runs a default command. */
9494 cmd = &tog_commands[0];
9495 argc = 1;
9496 cmd_argv = make_argv(argc, cmd->name);
9497 } else {
9498 size_t i;
9500 /* Did the user specify a command? */
9501 for (i = 0; i < nitems(tog_commands); i++) {
9502 if (strncmp(tog_commands[i].name, argv[0],
9503 strlen(argv[0])) == 0) {
9504 cmd = &tog_commands[i];
9505 break;
9510 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9511 if (diff_algo_str) {
9512 if (strcasecmp(diff_algo_str, "patience") == 0)
9513 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9514 if (strcasecmp(diff_algo_str, "myers") == 0)
9515 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9518 if (cmd == NULL) {
9519 if (argc != 1)
9520 usage(0, 1);
9521 /* No command specified; try log with a path */
9522 error = tog_log_with_path(argc, argv);
9523 } else {
9524 if (hflag)
9525 cmd->cmd_usage();
9526 else
9527 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9530 endwin();
9531 if (cmd_argv) {
9532 int i;
9533 for (i = 0; i < argc; i++)
9534 free(cmd_argv[i]);
9535 free(cmd_argv);
9538 if (error && error->code != GOT_ERR_CANCELLED &&
9539 error->code != GOT_ERR_EOF &&
9540 error->code != GOT_ERR_PRIVSEP_EXIT &&
9541 error->code != GOT_ERR_PRIVSEP_PIPE &&
9542 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9543 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9544 return 0;