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);
4582 if (s_nlines == 0 && *d_nlines == 0)
4583 return NULL;
4586 * If commit info was in dst, increment line offsets
4587 * of the appended diff content, but skip s_lines[0]
4588 * because offset zero is already in *d_lines.
4590 if (*d_nlines > 0) {
4591 for (i = 1; i < s_nlines; ++i)
4592 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4594 if (s_nlines > 0) {
4595 --s_nlines;
4596 ++s_lines;
4600 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4601 if (p == NULL) {
4602 /* d_lines is freed in close_diff_view() */
4603 return got_error_from_errno("reallocarray");
4606 *d_lines = p;
4608 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4609 *d_nlines += s_nlines;
4611 return NULL;
4614 static const struct got_error *
4615 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4616 struct got_object_id *commit_id, struct got_reflist_head *refs,
4617 struct got_repository *repo, int ignore_ws, int force_text_diff,
4618 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4620 const struct got_error *err = NULL;
4621 char datebuf[26], *datestr;
4622 struct got_commit_object *commit;
4623 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4624 time_t committer_time;
4625 const char *author, *committer;
4626 char *refs_str = NULL;
4627 struct got_pathlist_entry *pe;
4628 off_t outoff = 0;
4629 int n;
4631 if (refs) {
4632 err = build_refs_str(&refs_str, refs, commit_id, repo);
4633 if (err)
4634 return err;
4637 err = got_object_open_as_commit(&commit, repo, commit_id);
4638 if (err)
4639 return err;
4641 err = got_object_id_str(&id_str, commit_id);
4642 if (err) {
4643 err = got_error_from_errno("got_object_id_str");
4644 goto done;
4647 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4648 if (err)
4649 goto done;
4651 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4652 refs_str ? refs_str : "", refs_str ? ")" : "");
4653 if (n < 0) {
4654 err = got_error_from_errno("fprintf");
4655 goto done;
4657 outoff += n;
4658 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4659 if (err)
4660 goto done;
4662 n = fprintf(outfile, "from: %s\n",
4663 got_object_commit_get_author(commit));
4664 if (n < 0) {
4665 err = got_error_from_errno("fprintf");
4666 goto done;
4668 outoff += n;
4669 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4670 if (err)
4671 goto done;
4673 author = got_object_commit_get_author(commit);
4674 committer = got_object_commit_get_committer(commit);
4675 if (strcmp(author, committer) != 0) {
4676 n = fprintf(outfile, "via: %s\n", committer);
4677 if (n < 0) {
4678 err = got_error_from_errno("fprintf");
4679 goto done;
4681 outoff += n;
4682 err = add_line_metadata(lines, nlines, outoff,
4683 GOT_DIFF_LINE_AUTHOR);
4684 if (err)
4685 goto done;
4687 committer_time = got_object_commit_get_committer_time(commit);
4688 datestr = get_datestr(&committer_time, datebuf);
4689 if (datestr) {
4690 n = fprintf(outfile, "date: %s UTC\n", datestr);
4691 if (n < 0) {
4692 err = got_error_from_errno("fprintf");
4693 goto done;
4695 outoff += n;
4696 err = add_line_metadata(lines, nlines, outoff,
4697 GOT_DIFF_LINE_DATE);
4698 if (err)
4699 goto done;
4701 if (got_object_commit_get_nparents(commit) > 1) {
4702 const struct got_object_id_queue *parent_ids;
4703 struct got_object_qid *qid;
4704 int pn = 1;
4705 parent_ids = got_object_commit_get_parent_ids(commit);
4706 STAILQ_FOREACH(qid, parent_ids, entry) {
4707 err = got_object_id_str(&id_str, &qid->id);
4708 if (err)
4709 goto done;
4710 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4711 if (n < 0) {
4712 err = got_error_from_errno("fprintf");
4713 goto done;
4715 outoff += n;
4716 err = add_line_metadata(lines, nlines, outoff,
4717 GOT_DIFF_LINE_META);
4718 if (err)
4719 goto done;
4720 free(id_str);
4721 id_str = NULL;
4725 err = got_object_commit_get_logmsg(&logmsg, commit);
4726 if (err)
4727 goto done;
4728 s = logmsg;
4729 while ((line = strsep(&s, "\n")) != NULL) {
4730 n = fprintf(outfile, "%s\n", line);
4731 if (n < 0) {
4732 err = got_error_from_errno("fprintf");
4733 goto done;
4735 outoff += n;
4736 err = add_line_metadata(lines, nlines, outoff,
4737 GOT_DIFF_LINE_LOGMSG);
4738 if (err)
4739 goto done;
4742 TAILQ_FOREACH(pe, dsa->paths, entry) {
4743 struct got_diff_changed_path *cp = pe->data;
4744 int pad = dsa->max_path_len - pe->path_len + 1;
4746 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4747 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4748 dsa->rm_cols + 1, cp->rm);
4749 if (n < 0) {
4750 err = got_error_from_errno("fprintf");
4751 goto done;
4753 outoff += n;
4754 err = add_line_metadata(lines, nlines, outoff,
4755 GOT_DIFF_LINE_CHANGES);
4756 if (err)
4757 goto done;
4760 fputc('\n', outfile);
4761 outoff++;
4762 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4763 if (err)
4764 goto done;
4766 n = fprintf(outfile,
4767 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4768 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4769 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4770 if (n < 0) {
4771 err = got_error_from_errno("fprintf");
4772 goto done;
4774 outoff += n;
4775 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4776 if (err)
4777 goto done;
4779 fputc('\n', outfile);
4780 outoff++;
4781 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4782 done:
4783 free(id_str);
4784 free(logmsg);
4785 free(refs_str);
4786 got_object_commit_close(commit);
4787 if (err) {
4788 free(*lines);
4789 *lines = NULL;
4790 *nlines = 0;
4792 return err;
4795 static const struct got_error *
4796 create_diff(struct tog_diff_view_state *s)
4798 const struct got_error *err = NULL;
4799 FILE *f = NULL, *tmp_diff_file = NULL;
4800 int obj_type;
4801 struct got_diff_line *lines = NULL;
4802 struct got_pathlist_head changed_paths;
4804 TAILQ_INIT(&changed_paths);
4806 free(s->lines);
4807 s->lines = malloc(sizeof(*s->lines));
4808 if (s->lines == NULL)
4809 return got_error_from_errno("malloc");
4810 s->nlines = 0;
4812 f = got_opentemp();
4813 if (f == NULL) {
4814 err = got_error_from_errno("got_opentemp");
4815 goto done;
4817 tmp_diff_file = got_opentemp();
4818 if (tmp_diff_file == NULL) {
4819 err = got_error_from_errno("got_opentemp");
4820 goto done;
4822 if (s->f && fclose(s->f) == EOF) {
4823 err = got_error_from_errno("fclose");
4824 goto done;
4826 s->f = f;
4828 if (s->id1)
4829 err = got_object_get_type(&obj_type, s->repo, s->id1);
4830 else
4831 err = got_object_get_type(&obj_type, s->repo, s->id2);
4832 if (err)
4833 goto done;
4835 switch (obj_type) {
4836 case GOT_OBJ_TYPE_BLOB:
4837 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4838 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4839 s->label1, s->label2, tog_diff_algo, s->diff_context,
4840 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
4841 s->f);
4842 break;
4843 case GOT_OBJ_TYPE_TREE:
4844 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4845 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4846 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4847 s->force_text_diff, NULL, s->repo, s->f);
4848 break;
4849 case GOT_OBJ_TYPE_COMMIT: {
4850 const struct got_object_id_queue *parent_ids;
4851 struct got_object_qid *pid;
4852 struct got_commit_object *commit2;
4853 struct got_reflist_head *refs;
4854 size_t nlines = 0;
4855 struct got_diffstat_cb_arg dsa = {
4856 0, 0, 0, 0, 0, 0,
4857 &changed_paths,
4858 s->ignore_whitespace,
4859 s->force_text_diff,
4860 tog_diff_algo
4863 lines = malloc(sizeof(*lines));
4864 if (lines == NULL) {
4865 err = got_error_from_errno("malloc");
4866 goto done;
4869 /* build diff first in tmp file then append to commit info */
4870 err = got_diff_objects_as_commits(&lines, &nlines,
4871 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4872 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4873 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
4874 if (err)
4875 break;
4877 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4878 if (err)
4879 goto done;
4880 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4881 /* Show commit info if we're diffing to a parent/root commit. */
4882 if (s->id1 == NULL) {
4883 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4884 refs, s->repo, s->ignore_whitespace,
4885 s->force_text_diff, &dsa, s->f);
4886 if (err)
4887 goto done;
4888 } else {
4889 parent_ids = got_object_commit_get_parent_ids(commit2);
4890 STAILQ_FOREACH(pid, parent_ids, entry) {
4891 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4892 err = write_commit_info(&s->lines,
4893 &s->nlines, s->id2, refs, s->repo,
4894 s->ignore_whitespace,
4895 s->force_text_diff, &dsa, s->f);
4896 if (err)
4897 goto done;
4898 break;
4902 got_object_commit_close(commit2);
4904 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
4905 lines, nlines);
4906 break;
4908 default:
4909 err = got_error(GOT_ERR_OBJ_TYPE);
4910 break;
4912 done:
4913 free(lines);
4914 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4915 if (s->f && fflush(s->f) != 0 && err == NULL)
4916 err = got_error_from_errno("fflush");
4917 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
4918 err = got_error_from_errno("fclose");
4919 return err;
4922 static void
4923 diff_view_indicate_progress(struct tog_view *view)
4925 mvwaddstr(view->window, 0, 0, "diffing...");
4926 update_panels();
4927 doupdate();
4930 static const struct got_error *
4931 search_start_diff_view(struct tog_view *view)
4933 struct tog_diff_view_state *s = &view->state.diff;
4935 s->matched_line = 0;
4936 return NULL;
4939 static void
4940 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4941 size_t *nlines, int **first, int **last, int **match, int **selected)
4943 struct tog_diff_view_state *s = &view->state.diff;
4945 *f = s->f;
4946 *nlines = s->nlines;
4947 *line_offsets = NULL;
4948 *match = &s->matched_line;
4949 *first = &s->first_displayed_line;
4950 *last = &s->last_displayed_line;
4951 *selected = &s->selected_line;
4954 static const struct got_error *
4955 search_next_view_match(struct tog_view *view)
4957 const struct got_error *err = NULL;
4958 FILE *f;
4959 int lineno;
4960 char *line = NULL;
4961 size_t linesize = 0;
4962 ssize_t linelen;
4963 off_t *line_offsets;
4964 size_t nlines = 0;
4965 int *first, *last, *match, *selected;
4967 if (!view->search_setup)
4968 return got_error_msg(GOT_ERR_NOT_IMPL,
4969 "view search not supported");
4970 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4971 &match, &selected);
4973 if (!view->searching) {
4974 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4975 return NULL;
4978 if (*match) {
4979 if (view->searching == TOG_SEARCH_FORWARD)
4980 lineno = *match + 1;
4981 else
4982 lineno = *match - 1;
4983 } else
4984 lineno = *first - 1 + *selected;
4986 while (1) {
4987 off_t offset;
4989 if (lineno <= 0 || lineno > nlines) {
4990 if (*match == 0) {
4991 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4992 break;
4995 if (view->searching == TOG_SEARCH_FORWARD)
4996 lineno = 1;
4997 else
4998 lineno = nlines;
5001 offset = view->type == TOG_VIEW_DIFF ?
5002 view->state.diff.lines[lineno - 1].offset :
5003 line_offsets[lineno - 1];
5004 if (fseeko(f, offset, SEEK_SET) != 0) {
5005 free(line);
5006 return got_error_from_errno("fseeko");
5008 linelen = getline(&line, &linesize, f);
5009 if (linelen != -1) {
5010 char *exstr;
5011 err = expand_tab(&exstr, line);
5012 if (err)
5013 break;
5014 if (match_line(exstr, &view->regex, 1,
5015 &view->regmatch)) {
5016 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5017 *match = lineno;
5018 free(exstr);
5019 break;
5021 free(exstr);
5023 if (view->searching == TOG_SEARCH_FORWARD)
5024 lineno++;
5025 else
5026 lineno--;
5028 free(line);
5030 if (*match) {
5031 *first = *match;
5032 *selected = 1;
5035 return err;
5038 static const struct got_error *
5039 close_diff_view(struct tog_view *view)
5041 const struct got_error *err = NULL;
5042 struct tog_diff_view_state *s = &view->state.diff;
5044 free(s->id1);
5045 s->id1 = NULL;
5046 free(s->id2);
5047 s->id2 = NULL;
5048 if (s->f && fclose(s->f) == EOF)
5049 err = got_error_from_errno("fclose");
5050 s->f = NULL;
5051 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5052 err = got_error_from_errno("fclose");
5053 s->f1 = NULL;
5054 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5055 err = got_error_from_errno("fclose");
5056 s->f2 = NULL;
5057 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5058 err = got_error_from_errno("close");
5059 s->fd1 = -1;
5060 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5061 err = got_error_from_errno("close");
5062 s->fd2 = -1;
5063 free(s->lines);
5064 s->lines = NULL;
5065 s->nlines = 0;
5066 return err;
5069 static const struct got_error *
5070 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5071 struct got_object_id *id2, const char *label1, const char *label2,
5072 int diff_context, int ignore_whitespace, int force_text_diff,
5073 struct tog_view *parent_view, struct got_repository *repo)
5075 const struct got_error *err;
5076 struct tog_diff_view_state *s = &view->state.diff;
5078 memset(s, 0, sizeof(*s));
5079 s->fd1 = -1;
5080 s->fd2 = -1;
5082 if (id1 != NULL && id2 != NULL) {
5083 int type1, type2;
5084 err = got_object_get_type(&type1, repo, id1);
5085 if (err)
5086 return err;
5087 err = got_object_get_type(&type2, repo, id2);
5088 if (err)
5089 return err;
5091 if (type1 != type2)
5092 return got_error(GOT_ERR_OBJ_TYPE);
5094 s->first_displayed_line = 1;
5095 s->last_displayed_line = view->nlines;
5096 s->selected_line = 1;
5097 s->repo = repo;
5098 s->id1 = id1;
5099 s->id2 = id2;
5100 s->label1 = label1;
5101 s->label2 = label2;
5103 if (id1) {
5104 s->id1 = got_object_id_dup(id1);
5105 if (s->id1 == NULL)
5106 return got_error_from_errno("got_object_id_dup");
5107 } else
5108 s->id1 = NULL;
5110 s->id2 = got_object_id_dup(id2);
5111 if (s->id2 == NULL) {
5112 err = got_error_from_errno("got_object_id_dup");
5113 goto done;
5116 s->f1 = got_opentemp();
5117 if (s->f1 == NULL) {
5118 err = got_error_from_errno("got_opentemp");
5119 goto done;
5122 s->f2 = got_opentemp();
5123 if (s->f2 == NULL) {
5124 err = got_error_from_errno("got_opentemp");
5125 goto done;
5128 s->fd1 = got_opentempfd();
5129 if (s->fd1 == -1) {
5130 err = got_error_from_errno("got_opentempfd");
5131 goto done;
5134 s->fd2 = got_opentempfd();
5135 if (s->fd2 == -1) {
5136 err = got_error_from_errno("got_opentempfd");
5137 goto done;
5140 s->diff_context = diff_context;
5141 s->ignore_whitespace = ignore_whitespace;
5142 s->force_text_diff = force_text_diff;
5143 s->parent_view = parent_view;
5144 s->repo = repo;
5146 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5147 int rc;
5149 rc = init_pair(GOT_DIFF_LINE_MINUS,
5150 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5151 if (rc != ERR)
5152 rc = init_pair(GOT_DIFF_LINE_PLUS,
5153 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5154 if (rc != ERR)
5155 rc = init_pair(GOT_DIFF_LINE_HUNK,
5156 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5157 if (rc != ERR)
5158 rc = init_pair(GOT_DIFF_LINE_META,
5159 get_color_value("TOG_COLOR_DIFF_META"), -1);
5160 if (rc != ERR)
5161 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5162 get_color_value("TOG_COLOR_DIFF_META"), -1);
5163 if (rc != ERR)
5164 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5165 get_color_value("TOG_COLOR_DIFF_META"), -1);
5166 if (rc != ERR)
5167 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5168 get_color_value("TOG_COLOR_DIFF_META"), -1);
5169 if (rc != ERR)
5170 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5171 get_color_value("TOG_COLOR_AUTHOR"), -1);
5172 if (rc != ERR)
5173 rc = init_pair(GOT_DIFF_LINE_DATE,
5174 get_color_value("TOG_COLOR_DATE"), -1);
5175 if (rc == ERR) {
5176 err = got_error(GOT_ERR_RANGE);
5177 goto done;
5181 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5182 view_is_splitscreen(view))
5183 show_log_view(parent_view); /* draw border */
5184 diff_view_indicate_progress(view);
5186 err = create_diff(s);
5188 view->show = show_diff_view;
5189 view->input = input_diff_view;
5190 view->reset = reset_diff_view;
5191 view->close = close_diff_view;
5192 view->search_start = search_start_diff_view;
5193 view->search_setup = search_setup_diff_view;
5194 view->search_next = search_next_view_match;
5195 done:
5196 if (err)
5197 close_diff_view(view);
5198 return err;
5201 static const struct got_error *
5202 show_diff_view(struct tog_view *view)
5204 const struct got_error *err;
5205 struct tog_diff_view_state *s = &view->state.diff;
5206 char *id_str1 = NULL, *id_str2, *header;
5207 const char *label1, *label2;
5209 if (s->id1) {
5210 err = got_object_id_str(&id_str1, s->id1);
5211 if (err)
5212 return err;
5213 label1 = s->label1 ? s->label1 : id_str1;
5214 } else
5215 label1 = "/dev/null";
5217 err = got_object_id_str(&id_str2, s->id2);
5218 if (err)
5219 return err;
5220 label2 = s->label2 ? s->label2 : id_str2;
5222 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5223 err = got_error_from_errno("asprintf");
5224 free(id_str1);
5225 free(id_str2);
5226 return err;
5228 free(id_str1);
5229 free(id_str2);
5231 err = draw_file(view, header);
5232 free(header);
5233 return err;
5236 static const struct got_error *
5237 set_selected_commit(struct tog_diff_view_state *s,
5238 struct commit_queue_entry *entry)
5240 const struct got_error *err;
5241 const struct got_object_id_queue *parent_ids;
5242 struct got_commit_object *selected_commit;
5243 struct got_object_qid *pid;
5245 free(s->id2);
5246 s->id2 = got_object_id_dup(entry->id);
5247 if (s->id2 == NULL)
5248 return got_error_from_errno("got_object_id_dup");
5250 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5251 if (err)
5252 return err;
5253 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5254 free(s->id1);
5255 pid = STAILQ_FIRST(parent_ids);
5256 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5257 got_object_commit_close(selected_commit);
5258 return NULL;
5261 static const struct got_error *
5262 reset_diff_view(struct tog_view *view)
5264 struct tog_diff_view_state *s = &view->state.diff;
5266 view->count = 0;
5267 wclear(view->window);
5268 s->first_displayed_line = 1;
5269 s->last_displayed_line = view->nlines;
5270 s->matched_line = 0;
5271 diff_view_indicate_progress(view);
5272 return create_diff(s);
5275 static void
5276 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5278 int start, i;
5280 i = start = s->first_displayed_line - 1;
5282 while (s->lines[i].type != type) {
5283 if (i == 0)
5284 i = s->nlines - 1;
5285 if (--i == start)
5286 return; /* do nothing, requested type not in file */
5289 s->selected_line = 1;
5290 s->first_displayed_line = i;
5293 static void
5294 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5296 int start, i;
5298 i = start = s->first_displayed_line + 1;
5300 while (s->lines[i].type != type) {
5301 if (i == s->nlines - 1)
5302 i = 0;
5303 if (++i == start)
5304 return; /* do nothing, requested type not in file */
5307 s->selected_line = 1;
5308 s->first_displayed_line = i;
5311 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5312 int, int, int);
5313 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5314 int, int);
5316 static const struct got_error *
5317 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5319 const struct got_error *err = NULL;
5320 struct tog_diff_view_state *s = &view->state.diff;
5321 struct tog_log_view_state *ls;
5322 struct commit_queue_entry *old_selected_entry;
5323 char *line = NULL;
5324 size_t linesize = 0;
5325 ssize_t linelen;
5326 int i, nscroll = view->nlines - 1, up = 0;
5328 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5330 switch (ch) {
5331 case '0':
5332 case '$':
5333 case KEY_RIGHT:
5334 case 'l':
5335 case KEY_LEFT:
5336 case 'h':
5337 horizontal_scroll_input(view, ch);
5338 break;
5339 case 'a':
5340 case 'w':
5341 if (ch == 'a') {
5342 s->force_text_diff = !s->force_text_diff;
5343 view->action = s->force_text_diff ?
5344 "force ASCII text enabled" :
5345 "force ASCII text disabled";
5347 else if (ch == 'w') {
5348 s->ignore_whitespace = !s->ignore_whitespace;
5349 view->action = s->ignore_whitespace ?
5350 "ignore whitespace enabled" :
5351 "ignore whitespace disabled";
5353 err = reset_diff_view(view);
5354 break;
5355 case 'g':
5356 case KEY_HOME:
5357 s->first_displayed_line = 1;
5358 view->count = 0;
5359 break;
5360 case 'G':
5361 case KEY_END:
5362 view->count = 0;
5363 if (s->eof)
5364 break;
5366 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5367 s->eof = 1;
5368 break;
5369 case 'k':
5370 case KEY_UP:
5371 case CTRL('p'):
5372 if (s->first_displayed_line > 1)
5373 s->first_displayed_line--;
5374 else
5375 view->count = 0;
5376 break;
5377 case CTRL('u'):
5378 case 'u':
5379 nscroll /= 2;
5380 /* FALL THROUGH */
5381 case KEY_PPAGE:
5382 case CTRL('b'):
5383 case 'b':
5384 if (s->first_displayed_line == 1) {
5385 view->count = 0;
5386 break;
5388 i = 0;
5389 while (i++ < nscroll && s->first_displayed_line > 1)
5390 s->first_displayed_line--;
5391 break;
5392 case 'j':
5393 case KEY_DOWN:
5394 case CTRL('n'):
5395 if (!s->eof)
5396 s->first_displayed_line++;
5397 else
5398 view->count = 0;
5399 break;
5400 case CTRL('d'):
5401 case 'd':
5402 nscroll /= 2;
5403 /* FALL THROUGH */
5404 case KEY_NPAGE:
5405 case CTRL('f'):
5406 case 'f':
5407 case ' ':
5408 if (s->eof) {
5409 view->count = 0;
5410 break;
5412 i = 0;
5413 while (!s->eof && i++ < nscroll) {
5414 linelen = getline(&line, &linesize, s->f);
5415 s->first_displayed_line++;
5416 if (linelen == -1) {
5417 if (feof(s->f)) {
5418 s->eof = 1;
5419 } else
5420 err = got_ferror(s->f, GOT_ERR_IO);
5421 break;
5424 free(line);
5425 break;
5426 case '(':
5427 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5428 break;
5429 case ')':
5430 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5431 break;
5432 case '{':
5433 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5434 break;
5435 case '}':
5436 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5437 break;
5438 case '[':
5439 if (s->diff_context > 0) {
5440 s->diff_context--;
5441 s->matched_line = 0;
5442 diff_view_indicate_progress(view);
5443 err = create_diff(s);
5444 if (s->first_displayed_line + view->nlines - 1 >
5445 s->nlines) {
5446 s->first_displayed_line = 1;
5447 s->last_displayed_line = view->nlines;
5449 } else
5450 view->count = 0;
5451 break;
5452 case ']':
5453 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5454 s->diff_context++;
5455 s->matched_line = 0;
5456 diff_view_indicate_progress(view);
5457 err = create_diff(s);
5458 } else
5459 view->count = 0;
5460 break;
5461 case '<':
5462 case ',':
5463 case 'K':
5464 up = 1;
5465 /* FALL THROUGH */
5466 case '>':
5467 case '.':
5468 case 'J':
5469 if (s->parent_view == NULL) {
5470 view->count = 0;
5471 break;
5473 s->parent_view->count = view->count;
5475 if (s->parent_view->type == TOG_VIEW_LOG) {
5476 ls = &s->parent_view->state.log;
5477 old_selected_entry = ls->selected_entry;
5479 err = input_log_view(NULL, s->parent_view,
5480 up ? KEY_UP : KEY_DOWN);
5481 if (err)
5482 break;
5483 view->count = s->parent_view->count;
5485 if (old_selected_entry == ls->selected_entry)
5486 break;
5488 err = set_selected_commit(s, ls->selected_entry);
5489 if (err)
5490 break;
5491 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5492 struct tog_blame_view_state *bs;
5493 struct got_object_id *id, *prev_id;
5495 bs = &s->parent_view->state.blame;
5496 prev_id = get_annotation_for_line(bs->blame.lines,
5497 bs->blame.nlines, bs->last_diffed_line);
5499 err = input_blame_view(&view, s->parent_view,
5500 up ? KEY_UP : KEY_DOWN);
5501 if (err)
5502 break;
5503 view->count = s->parent_view->count;
5505 if (prev_id == NULL)
5506 break;
5507 id = get_selected_commit_id(bs->blame.lines,
5508 bs->blame.nlines, bs->first_displayed_line,
5509 bs->selected_line);
5510 if (id == NULL)
5511 break;
5513 if (!got_object_id_cmp(prev_id, id))
5514 break;
5516 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5517 if (err)
5518 break;
5520 s->first_displayed_line = 1;
5521 s->last_displayed_line = view->nlines;
5522 s->matched_line = 0;
5523 view->x = 0;
5525 diff_view_indicate_progress(view);
5526 err = create_diff(s);
5527 break;
5528 default:
5529 view->count = 0;
5530 break;
5533 return err;
5536 static const struct got_error *
5537 cmd_diff(int argc, char *argv[])
5539 const struct got_error *error = NULL;
5540 struct got_repository *repo = NULL;
5541 struct got_worktree *worktree = NULL;
5542 struct got_object_id *id1 = NULL, *id2 = NULL;
5543 char *repo_path = NULL, *cwd = NULL;
5544 char *id_str1 = NULL, *id_str2 = NULL;
5545 char *label1 = NULL, *label2 = NULL;
5546 int diff_context = 3, ignore_whitespace = 0;
5547 int ch, force_text_diff = 0;
5548 const char *errstr;
5549 struct tog_view *view;
5550 int *pack_fds = NULL;
5552 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5553 switch (ch) {
5554 case 'a':
5555 force_text_diff = 1;
5556 break;
5557 case 'C':
5558 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5559 &errstr);
5560 if (errstr != NULL)
5561 errx(1, "number of context lines is %s: %s",
5562 errstr, errstr);
5563 break;
5564 case 'r':
5565 repo_path = realpath(optarg, NULL);
5566 if (repo_path == NULL)
5567 return got_error_from_errno2("realpath",
5568 optarg);
5569 got_path_strip_trailing_slashes(repo_path);
5570 break;
5571 case 'w':
5572 ignore_whitespace = 1;
5573 break;
5574 default:
5575 usage_diff();
5576 /* NOTREACHED */
5580 argc -= optind;
5581 argv += optind;
5583 if (argc == 0) {
5584 usage_diff(); /* TODO show local worktree changes */
5585 } else if (argc == 2) {
5586 id_str1 = argv[0];
5587 id_str2 = argv[1];
5588 } else
5589 usage_diff();
5591 error = got_repo_pack_fds_open(&pack_fds);
5592 if (error)
5593 goto done;
5595 if (repo_path == NULL) {
5596 cwd = getcwd(NULL, 0);
5597 if (cwd == NULL)
5598 return got_error_from_errno("getcwd");
5599 error = got_worktree_open(&worktree, cwd);
5600 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5601 goto done;
5602 if (worktree)
5603 repo_path =
5604 strdup(got_worktree_get_repo_path(worktree));
5605 else
5606 repo_path = strdup(cwd);
5607 if (repo_path == NULL) {
5608 error = got_error_from_errno("strdup");
5609 goto done;
5613 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5614 if (error)
5615 goto done;
5617 init_curses();
5619 error = apply_unveil(got_repo_get_path(repo), NULL);
5620 if (error)
5621 goto done;
5623 error = tog_load_refs(repo, 0);
5624 if (error)
5625 goto done;
5627 error = got_repo_match_object_id(&id1, &label1, id_str1,
5628 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5629 if (error)
5630 goto done;
5632 error = got_repo_match_object_id(&id2, &label2, id_str2,
5633 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5634 if (error)
5635 goto done;
5637 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5638 if (view == NULL) {
5639 error = got_error_from_errno("view_open");
5640 goto done;
5642 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5643 ignore_whitespace, force_text_diff, NULL, repo);
5644 if (error)
5645 goto done;
5646 error = view_loop(view);
5647 done:
5648 free(label1);
5649 free(label2);
5650 free(repo_path);
5651 free(cwd);
5652 if (repo) {
5653 const struct got_error *close_err = got_repo_close(repo);
5654 if (error == NULL)
5655 error = close_err;
5657 if (worktree)
5658 got_worktree_close(worktree);
5659 if (pack_fds) {
5660 const struct got_error *pack_err =
5661 got_repo_pack_fds_close(pack_fds);
5662 if (error == NULL)
5663 error = pack_err;
5665 tog_free_refs();
5666 return error;
5669 __dead static void
5670 usage_blame(void)
5672 endwin();
5673 fprintf(stderr,
5674 "usage: %s blame [-c commit] [-r repository-path] path\n",
5675 getprogname());
5676 exit(1);
5679 struct tog_blame_line {
5680 int annotated;
5681 struct got_object_id *id;
5684 static const struct got_error *
5685 draw_blame(struct tog_view *view)
5687 struct tog_blame_view_state *s = &view->state.blame;
5688 struct tog_blame *blame = &s->blame;
5689 regmatch_t *regmatch = &view->regmatch;
5690 const struct got_error *err;
5691 int lineno = 0, nprinted = 0;
5692 char *line = NULL;
5693 size_t linesize = 0;
5694 ssize_t linelen;
5695 wchar_t *wline;
5696 int width;
5697 struct tog_blame_line *blame_line;
5698 struct got_object_id *prev_id = NULL;
5699 char *id_str;
5700 struct tog_color *tc;
5702 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5703 if (err)
5704 return err;
5706 rewind(blame->f);
5707 werase(view->window);
5709 if (asprintf(&line, "commit %s", id_str) == -1) {
5710 err = got_error_from_errno("asprintf");
5711 free(id_str);
5712 return err;
5715 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5716 free(line);
5717 line = NULL;
5718 if (err)
5719 return err;
5720 if (view_needs_focus_indication(view))
5721 wstandout(view->window);
5722 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5723 if (tc)
5724 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5725 waddwstr(view->window, wline);
5726 while (width++ < view->ncols)
5727 waddch(view->window, ' ');
5728 if (tc)
5729 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5730 if (view_needs_focus_indication(view))
5731 wstandend(view->window);
5732 free(wline);
5733 wline = NULL;
5735 if (view->gline > blame->nlines)
5736 view->gline = blame->nlines;
5738 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5739 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5740 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5741 free(id_str);
5742 return got_error_from_errno("asprintf");
5744 free(id_str);
5745 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5746 free(line);
5747 line = NULL;
5748 if (err)
5749 return err;
5750 waddwstr(view->window, wline);
5751 free(wline);
5752 wline = NULL;
5753 if (width < view->ncols - 1)
5754 waddch(view->window, '\n');
5756 s->eof = 0;
5757 view->maxx = 0;
5758 while (nprinted < view->nlines - 2) {
5759 linelen = getline(&line, &linesize, blame->f);
5760 if (linelen == -1) {
5761 if (feof(blame->f)) {
5762 s->eof = 1;
5763 break;
5765 free(line);
5766 return got_ferror(blame->f, GOT_ERR_IO);
5768 if (++lineno < s->first_displayed_line)
5769 continue;
5770 if (view->gline && !gotoline(view, &lineno, &nprinted))
5771 continue;
5773 /* Set view->maxx based on full line length. */
5774 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5775 if (err) {
5776 free(line);
5777 return err;
5779 free(wline);
5780 wline = NULL;
5781 view->maxx = MAX(view->maxx, width);
5783 if (nprinted == s->selected_line - 1)
5784 wstandout(view->window);
5786 if (blame->nlines > 0) {
5787 blame_line = &blame->lines[lineno - 1];
5788 if (blame_line->annotated && prev_id &&
5789 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5790 !(nprinted == s->selected_line - 1)) {
5791 waddstr(view->window, " ");
5792 } else if (blame_line->annotated) {
5793 char *id_str;
5794 err = got_object_id_str(&id_str,
5795 blame_line->id);
5796 if (err) {
5797 free(line);
5798 return err;
5800 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5801 if (tc)
5802 wattr_on(view->window,
5803 COLOR_PAIR(tc->colorpair), NULL);
5804 wprintw(view->window, "%.8s", id_str);
5805 if (tc)
5806 wattr_off(view->window,
5807 COLOR_PAIR(tc->colorpair), NULL);
5808 free(id_str);
5809 prev_id = blame_line->id;
5810 } else {
5811 waddstr(view->window, "........");
5812 prev_id = NULL;
5814 } else {
5815 waddstr(view->window, "........");
5816 prev_id = NULL;
5819 if (nprinted == s->selected_line - 1)
5820 wstandend(view->window);
5821 waddstr(view->window, " ");
5823 if (view->ncols <= 9) {
5824 width = 9;
5825 } else if (s->first_displayed_line + nprinted ==
5826 s->matched_line &&
5827 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5828 err = add_matched_line(&width, line, view->ncols - 9, 9,
5829 view->window, view->x, regmatch);
5830 if (err) {
5831 free(line);
5832 return err;
5834 width += 9;
5835 } else {
5836 int skip;
5837 err = format_line(&wline, &width, &skip, line,
5838 view->x, view->ncols - 9, 9, 1);
5839 if (err) {
5840 free(line);
5841 return err;
5843 waddwstr(view->window, &wline[skip]);
5844 width += 9;
5845 free(wline);
5846 wline = NULL;
5849 if (width <= view->ncols - 1)
5850 waddch(view->window, '\n');
5851 if (++nprinted == 1)
5852 s->first_displayed_line = lineno;
5854 free(line);
5855 s->last_displayed_line = lineno;
5857 view_border(view);
5859 return NULL;
5862 static const struct got_error *
5863 blame_cb(void *arg, int nlines, int lineno,
5864 struct got_commit_object *commit, struct got_object_id *id)
5866 const struct got_error *err = NULL;
5867 struct tog_blame_cb_args *a = arg;
5868 struct tog_blame_line *line;
5869 int errcode;
5871 if (nlines != a->nlines ||
5872 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5873 return got_error(GOT_ERR_RANGE);
5875 errcode = pthread_mutex_lock(&tog_mutex);
5876 if (errcode)
5877 return got_error_set_errno(errcode, "pthread_mutex_lock");
5879 if (*a->quit) { /* user has quit the blame view */
5880 err = got_error(GOT_ERR_ITER_COMPLETED);
5881 goto done;
5884 if (lineno == -1)
5885 goto done; /* no change in this commit */
5887 line = &a->lines[lineno - 1];
5888 if (line->annotated)
5889 goto done;
5891 line->id = got_object_id_dup(id);
5892 if (line->id == NULL) {
5893 err = got_error_from_errno("got_object_id_dup");
5894 goto done;
5896 line->annotated = 1;
5897 done:
5898 errcode = pthread_mutex_unlock(&tog_mutex);
5899 if (errcode)
5900 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5901 return err;
5904 static void *
5905 blame_thread(void *arg)
5907 const struct got_error *err, *close_err;
5908 struct tog_blame_thread_args *ta = arg;
5909 struct tog_blame_cb_args *a = ta->cb_args;
5910 int errcode, fd1 = -1, fd2 = -1;
5911 FILE *f1 = NULL, *f2 = NULL;
5913 fd1 = got_opentempfd();
5914 if (fd1 == -1)
5915 return (void *)got_error_from_errno("got_opentempfd");
5917 fd2 = got_opentempfd();
5918 if (fd2 == -1) {
5919 err = got_error_from_errno("got_opentempfd");
5920 goto done;
5923 f1 = got_opentemp();
5924 if (f1 == NULL) {
5925 err = (void *)got_error_from_errno("got_opentemp");
5926 goto done;
5928 f2 = got_opentemp();
5929 if (f2 == NULL) {
5930 err = (void *)got_error_from_errno("got_opentemp");
5931 goto done;
5934 err = block_signals_used_by_main_thread();
5935 if (err)
5936 goto done;
5938 err = got_blame(ta->path, a->commit_id, ta->repo,
5939 tog_diff_algo, blame_cb, ta->cb_args,
5940 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5941 if (err && err->code == GOT_ERR_CANCELLED)
5942 err = NULL;
5944 errcode = pthread_mutex_lock(&tog_mutex);
5945 if (errcode) {
5946 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5947 goto done;
5950 close_err = got_repo_close(ta->repo);
5951 if (err == NULL)
5952 err = close_err;
5953 ta->repo = NULL;
5954 *ta->complete = 1;
5956 errcode = pthread_mutex_unlock(&tog_mutex);
5957 if (errcode && err == NULL)
5958 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5960 done:
5961 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5962 err = got_error_from_errno("close");
5963 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5964 err = got_error_from_errno("close");
5965 if (f1 && fclose(f1) == EOF && err == NULL)
5966 err = got_error_from_errno("fclose");
5967 if (f2 && fclose(f2) == EOF && err == NULL)
5968 err = got_error_from_errno("fclose");
5970 return (void *)err;
5973 static struct got_object_id *
5974 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5975 int first_displayed_line, int selected_line)
5977 struct tog_blame_line *line;
5979 if (nlines <= 0)
5980 return NULL;
5982 line = &lines[first_displayed_line - 1 + selected_line - 1];
5983 if (!line->annotated)
5984 return NULL;
5986 return line->id;
5989 static struct got_object_id *
5990 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5991 int lineno)
5993 struct tog_blame_line *line;
5995 if (nlines <= 0 || lineno >= nlines)
5996 return NULL;
5998 line = &lines[lineno - 1];
5999 if (!line->annotated)
6000 return NULL;
6002 return line->id;
6005 static const struct got_error *
6006 stop_blame(struct tog_blame *blame)
6008 const struct got_error *err = NULL;
6009 int i;
6011 if (blame->thread) {
6012 int errcode;
6013 errcode = pthread_mutex_unlock(&tog_mutex);
6014 if (errcode)
6015 return got_error_set_errno(errcode,
6016 "pthread_mutex_unlock");
6017 errcode = pthread_join(blame->thread, (void **)&err);
6018 if (errcode)
6019 return got_error_set_errno(errcode, "pthread_join");
6020 errcode = pthread_mutex_lock(&tog_mutex);
6021 if (errcode)
6022 return got_error_set_errno(errcode,
6023 "pthread_mutex_lock");
6024 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6025 err = NULL;
6026 blame->thread = NULL;
6028 if (blame->thread_args.repo) {
6029 const struct got_error *close_err;
6030 close_err = got_repo_close(blame->thread_args.repo);
6031 if (err == NULL)
6032 err = close_err;
6033 blame->thread_args.repo = NULL;
6035 if (blame->f) {
6036 if (fclose(blame->f) == EOF && err == NULL)
6037 err = got_error_from_errno("fclose");
6038 blame->f = NULL;
6040 if (blame->lines) {
6041 for (i = 0; i < blame->nlines; i++)
6042 free(blame->lines[i].id);
6043 free(blame->lines);
6044 blame->lines = NULL;
6046 free(blame->cb_args.commit_id);
6047 blame->cb_args.commit_id = NULL;
6048 if (blame->pack_fds) {
6049 const struct got_error *pack_err =
6050 got_repo_pack_fds_close(blame->pack_fds);
6051 if (err == NULL)
6052 err = pack_err;
6053 blame->pack_fds = NULL;
6055 return err;
6058 static const struct got_error *
6059 cancel_blame_view(void *arg)
6061 const struct got_error *err = NULL;
6062 int *done = arg;
6063 int errcode;
6065 errcode = pthread_mutex_lock(&tog_mutex);
6066 if (errcode)
6067 return got_error_set_errno(errcode,
6068 "pthread_mutex_unlock");
6070 if (*done)
6071 err = got_error(GOT_ERR_CANCELLED);
6073 errcode = pthread_mutex_unlock(&tog_mutex);
6074 if (errcode)
6075 return got_error_set_errno(errcode,
6076 "pthread_mutex_lock");
6078 return err;
6081 static const struct got_error *
6082 run_blame(struct tog_view *view)
6084 struct tog_blame_view_state *s = &view->state.blame;
6085 struct tog_blame *blame = &s->blame;
6086 const struct got_error *err = NULL;
6087 struct got_commit_object *commit = NULL;
6088 struct got_blob_object *blob = NULL;
6089 struct got_repository *thread_repo = NULL;
6090 struct got_object_id *obj_id = NULL;
6091 int obj_type, fd = -1;
6092 int *pack_fds = NULL;
6094 err = got_object_open_as_commit(&commit, s->repo,
6095 &s->blamed_commit->id);
6096 if (err)
6097 return err;
6099 fd = got_opentempfd();
6100 if (fd == -1) {
6101 err = got_error_from_errno("got_opentempfd");
6102 goto done;
6105 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6106 if (err)
6107 goto done;
6109 err = got_object_get_type(&obj_type, s->repo, obj_id);
6110 if (err)
6111 goto done;
6113 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6114 err = got_error(GOT_ERR_OBJ_TYPE);
6115 goto done;
6118 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6119 if (err)
6120 goto done;
6121 blame->f = got_opentemp();
6122 if (blame->f == NULL) {
6123 err = got_error_from_errno("got_opentemp");
6124 goto done;
6126 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6127 &blame->line_offsets, blame->f, blob);
6128 if (err)
6129 goto done;
6130 if (blame->nlines == 0) {
6131 s->blame_complete = 1;
6132 goto done;
6135 /* Don't include \n at EOF in the blame line count. */
6136 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6137 blame->nlines--;
6139 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6140 if (blame->lines == NULL) {
6141 err = got_error_from_errno("calloc");
6142 goto done;
6145 err = got_repo_pack_fds_open(&pack_fds);
6146 if (err)
6147 goto done;
6148 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6149 pack_fds);
6150 if (err)
6151 goto done;
6153 blame->pack_fds = pack_fds;
6154 blame->cb_args.view = view;
6155 blame->cb_args.lines = blame->lines;
6156 blame->cb_args.nlines = blame->nlines;
6157 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6158 if (blame->cb_args.commit_id == NULL) {
6159 err = got_error_from_errno("got_object_id_dup");
6160 goto done;
6162 blame->cb_args.quit = &s->done;
6164 blame->thread_args.path = s->path;
6165 blame->thread_args.repo = thread_repo;
6166 blame->thread_args.cb_args = &blame->cb_args;
6167 blame->thread_args.complete = &s->blame_complete;
6168 blame->thread_args.cancel_cb = cancel_blame_view;
6169 blame->thread_args.cancel_arg = &s->done;
6170 s->blame_complete = 0;
6172 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6173 s->first_displayed_line = 1;
6174 s->last_displayed_line = view->nlines;
6175 s->selected_line = 1;
6177 s->matched_line = 0;
6179 done:
6180 if (commit)
6181 got_object_commit_close(commit);
6182 if (fd != -1 && close(fd) == -1 && err == NULL)
6183 err = got_error_from_errno("close");
6184 if (blob)
6185 got_object_blob_close(blob);
6186 free(obj_id);
6187 if (err)
6188 stop_blame(blame);
6189 return err;
6192 static const struct got_error *
6193 open_blame_view(struct tog_view *view, char *path,
6194 struct got_object_id *commit_id, struct got_repository *repo)
6196 const struct got_error *err = NULL;
6197 struct tog_blame_view_state *s = &view->state.blame;
6199 STAILQ_INIT(&s->blamed_commits);
6201 s->path = strdup(path);
6202 if (s->path == NULL)
6203 return got_error_from_errno("strdup");
6205 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6206 if (err) {
6207 free(s->path);
6208 return err;
6211 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6212 s->first_displayed_line = 1;
6213 s->last_displayed_line = view->nlines;
6214 s->selected_line = 1;
6215 s->blame_complete = 0;
6216 s->repo = repo;
6217 s->commit_id = commit_id;
6218 memset(&s->blame, 0, sizeof(s->blame));
6220 STAILQ_INIT(&s->colors);
6221 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6222 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6223 get_color_value("TOG_COLOR_COMMIT"));
6224 if (err)
6225 return err;
6228 view->show = show_blame_view;
6229 view->input = input_blame_view;
6230 view->reset = reset_blame_view;
6231 view->close = close_blame_view;
6232 view->search_start = search_start_blame_view;
6233 view->search_setup = search_setup_blame_view;
6234 view->search_next = search_next_view_match;
6236 return run_blame(view);
6239 static const struct got_error *
6240 close_blame_view(struct tog_view *view)
6242 const struct got_error *err = NULL;
6243 struct tog_blame_view_state *s = &view->state.blame;
6245 if (s->blame.thread)
6246 err = stop_blame(&s->blame);
6248 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6249 struct got_object_qid *blamed_commit;
6250 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6251 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6252 got_object_qid_free(blamed_commit);
6255 free(s->path);
6256 free_colors(&s->colors);
6257 return err;
6260 static const struct got_error *
6261 search_start_blame_view(struct tog_view *view)
6263 struct tog_blame_view_state *s = &view->state.blame;
6265 s->matched_line = 0;
6266 return NULL;
6269 static void
6270 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6271 size_t *nlines, int **first, int **last, int **match, int **selected)
6273 struct tog_blame_view_state *s = &view->state.blame;
6275 *f = s->blame.f;
6276 *nlines = s->blame.nlines;
6277 *line_offsets = s->blame.line_offsets;
6278 *match = &s->matched_line;
6279 *first = &s->first_displayed_line;
6280 *last = &s->last_displayed_line;
6281 *selected = &s->selected_line;
6284 static const struct got_error *
6285 show_blame_view(struct tog_view *view)
6287 const struct got_error *err = NULL;
6288 struct tog_blame_view_state *s = &view->state.blame;
6289 int errcode;
6291 if (s->blame.thread == NULL && !s->blame_complete) {
6292 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6293 &s->blame.thread_args);
6294 if (errcode)
6295 return got_error_set_errno(errcode, "pthread_create");
6297 halfdelay(1); /* fast refresh while annotating */
6300 if (s->blame_complete)
6301 halfdelay(10); /* disable fast refresh */
6303 err = draw_blame(view);
6305 view_border(view);
6306 return err;
6309 static const struct got_error *
6310 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6311 struct got_repository *repo, struct got_object_id *id)
6313 struct tog_view *log_view;
6314 const struct got_error *err = NULL;
6316 *new_view = NULL;
6318 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6319 if (log_view == NULL)
6320 return got_error_from_errno("view_open");
6322 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6323 if (err)
6324 view_close(log_view);
6325 else
6326 *new_view = log_view;
6328 return err;
6331 static const struct got_error *
6332 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6334 const struct got_error *err = NULL, *thread_err = NULL;
6335 struct tog_view *diff_view;
6336 struct tog_blame_view_state *s = &view->state.blame;
6337 int eos, nscroll, begin_y = 0, begin_x = 0;
6339 eos = nscroll = view->nlines - 2;
6340 if (view_is_hsplit_top(view))
6341 --eos; /* border */
6343 switch (ch) {
6344 case '0':
6345 case '$':
6346 case KEY_RIGHT:
6347 case 'l':
6348 case KEY_LEFT:
6349 case 'h':
6350 horizontal_scroll_input(view, ch);
6351 break;
6352 case 'q':
6353 s->done = 1;
6354 break;
6355 case 'g':
6356 case KEY_HOME:
6357 s->selected_line = 1;
6358 s->first_displayed_line = 1;
6359 view->count = 0;
6360 break;
6361 case 'G':
6362 case KEY_END:
6363 if (s->blame.nlines < eos) {
6364 s->selected_line = s->blame.nlines;
6365 s->first_displayed_line = 1;
6366 } else {
6367 s->selected_line = eos;
6368 s->first_displayed_line = s->blame.nlines - (eos - 1);
6370 view->count = 0;
6371 break;
6372 case 'k':
6373 case KEY_UP:
6374 case CTRL('p'):
6375 if (s->selected_line > 1)
6376 s->selected_line--;
6377 else if (s->selected_line == 1 &&
6378 s->first_displayed_line > 1)
6379 s->first_displayed_line--;
6380 else
6381 view->count = 0;
6382 break;
6383 case CTRL('u'):
6384 case 'u':
6385 nscroll /= 2;
6386 /* FALL THROUGH */
6387 case KEY_PPAGE:
6388 case CTRL('b'):
6389 case 'b':
6390 if (s->first_displayed_line == 1) {
6391 if (view->count > 1)
6392 nscroll += nscroll;
6393 s->selected_line = MAX(1, s->selected_line - nscroll);
6394 view->count = 0;
6395 break;
6397 if (s->first_displayed_line > nscroll)
6398 s->first_displayed_line -= nscroll;
6399 else
6400 s->first_displayed_line = 1;
6401 break;
6402 case 'j':
6403 case KEY_DOWN:
6404 case CTRL('n'):
6405 if (s->selected_line < eos && s->first_displayed_line +
6406 s->selected_line <= s->blame.nlines)
6407 s->selected_line++;
6408 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6409 s->first_displayed_line++;
6410 else
6411 view->count = 0;
6412 break;
6413 case 'c':
6414 case 'p': {
6415 struct got_object_id *id = NULL;
6417 view->count = 0;
6418 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6419 s->first_displayed_line, s->selected_line);
6420 if (id == NULL)
6421 break;
6422 if (ch == 'p') {
6423 struct got_commit_object *commit, *pcommit;
6424 struct got_object_qid *pid;
6425 struct got_object_id *blob_id = NULL;
6426 int obj_type;
6427 err = got_object_open_as_commit(&commit,
6428 s->repo, id);
6429 if (err)
6430 break;
6431 pid = STAILQ_FIRST(
6432 got_object_commit_get_parent_ids(commit));
6433 if (pid == NULL) {
6434 got_object_commit_close(commit);
6435 break;
6437 /* Check if path history ends here. */
6438 err = got_object_open_as_commit(&pcommit,
6439 s->repo, &pid->id);
6440 if (err)
6441 break;
6442 err = got_object_id_by_path(&blob_id, s->repo,
6443 pcommit, s->path);
6444 got_object_commit_close(pcommit);
6445 if (err) {
6446 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6447 err = NULL;
6448 got_object_commit_close(commit);
6449 break;
6451 err = got_object_get_type(&obj_type, s->repo,
6452 blob_id);
6453 free(blob_id);
6454 /* Can't blame non-blob type objects. */
6455 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6456 got_object_commit_close(commit);
6457 break;
6459 err = got_object_qid_alloc(&s->blamed_commit,
6460 &pid->id);
6461 got_object_commit_close(commit);
6462 } else {
6463 if (got_object_id_cmp(id,
6464 &s->blamed_commit->id) == 0)
6465 break;
6466 err = got_object_qid_alloc(&s->blamed_commit,
6467 id);
6469 if (err)
6470 break;
6471 s->done = 1;
6472 thread_err = stop_blame(&s->blame);
6473 s->done = 0;
6474 if (thread_err)
6475 break;
6476 STAILQ_INSERT_HEAD(&s->blamed_commits,
6477 s->blamed_commit, entry);
6478 err = run_blame(view);
6479 if (err)
6480 break;
6481 break;
6483 case 'C': {
6484 struct got_object_qid *first;
6486 view->count = 0;
6487 first = STAILQ_FIRST(&s->blamed_commits);
6488 if (!got_object_id_cmp(&first->id, s->commit_id))
6489 break;
6490 s->done = 1;
6491 thread_err = stop_blame(&s->blame);
6492 s->done = 0;
6493 if (thread_err)
6494 break;
6495 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6496 got_object_qid_free(s->blamed_commit);
6497 s->blamed_commit =
6498 STAILQ_FIRST(&s->blamed_commits);
6499 err = run_blame(view);
6500 if (err)
6501 break;
6502 break;
6504 case 'L':
6505 view->count = 0;
6506 s->id_to_log = get_selected_commit_id(s->blame.lines,
6507 s->blame.nlines, s->first_displayed_line, s->selected_line);
6508 if (s->id_to_log)
6509 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6510 break;
6511 case KEY_ENTER:
6512 case '\r': {
6513 struct got_object_id *id = NULL;
6514 struct got_object_qid *pid;
6515 struct got_commit_object *commit = NULL;
6517 view->count = 0;
6518 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6519 s->first_displayed_line, s->selected_line);
6520 if (id == NULL)
6521 break;
6522 err = got_object_open_as_commit(&commit, s->repo, id);
6523 if (err)
6524 break;
6525 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6526 if (*new_view) {
6527 /* traversed from diff view, release diff resources */
6528 err = close_diff_view(*new_view);
6529 if (err)
6530 break;
6531 diff_view = *new_view;
6532 } else {
6533 if (view_is_parent_view(view))
6534 view_get_split(view, &begin_y, &begin_x);
6536 diff_view = view_open(0, 0, begin_y, begin_x,
6537 TOG_VIEW_DIFF);
6538 if (diff_view == NULL) {
6539 got_object_commit_close(commit);
6540 err = got_error_from_errno("view_open");
6541 break;
6544 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6545 id, NULL, NULL, 3, 0, 0, view, s->repo);
6546 got_object_commit_close(commit);
6547 if (err) {
6548 view_close(diff_view);
6549 break;
6551 s->last_diffed_line = s->first_displayed_line - 1 +
6552 s->selected_line;
6553 if (*new_view)
6554 break; /* still open from active diff view */
6555 if (view_is_parent_view(view) &&
6556 view->mode == TOG_VIEW_SPLIT_HRZN) {
6557 err = view_init_hsplit(view, begin_y);
6558 if (err)
6559 break;
6562 view->focussed = 0;
6563 diff_view->focussed = 1;
6564 diff_view->mode = view->mode;
6565 diff_view->nlines = view->lines - begin_y;
6566 if (view_is_parent_view(view)) {
6567 view_transfer_size(diff_view, view);
6568 err = view_close_child(view);
6569 if (err)
6570 break;
6571 err = view_set_child(view, diff_view);
6572 if (err)
6573 break;
6574 view->focus_child = 1;
6575 } else
6576 *new_view = diff_view;
6577 if (err)
6578 break;
6579 break;
6581 case CTRL('d'):
6582 case 'd':
6583 nscroll /= 2;
6584 /* FALL THROUGH */
6585 case KEY_NPAGE:
6586 case CTRL('f'):
6587 case 'f':
6588 case ' ':
6589 if (s->last_displayed_line >= s->blame.nlines &&
6590 s->selected_line >= MIN(s->blame.nlines,
6591 view->nlines - 2)) {
6592 view->count = 0;
6593 break;
6595 if (s->last_displayed_line >= s->blame.nlines &&
6596 s->selected_line < view->nlines - 2) {
6597 s->selected_line +=
6598 MIN(nscroll, s->last_displayed_line -
6599 s->first_displayed_line - s->selected_line + 1);
6601 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6602 s->first_displayed_line += nscroll;
6603 else
6604 s->first_displayed_line =
6605 s->blame.nlines - (view->nlines - 3);
6606 break;
6607 case KEY_RESIZE:
6608 if (s->selected_line > view->nlines - 2) {
6609 s->selected_line = MIN(s->blame.nlines,
6610 view->nlines - 2);
6612 break;
6613 default:
6614 view->count = 0;
6615 break;
6617 return thread_err ? thread_err : err;
6620 static const struct got_error *
6621 reset_blame_view(struct tog_view *view)
6623 const struct got_error *err;
6624 struct tog_blame_view_state *s = &view->state.blame;
6626 view->count = 0;
6627 s->done = 1;
6628 err = stop_blame(&s->blame);
6629 s->done = 0;
6630 if (err)
6631 return err;
6632 return run_blame(view);
6635 static const struct got_error *
6636 cmd_blame(int argc, char *argv[])
6638 const struct got_error *error;
6639 struct got_repository *repo = NULL;
6640 struct got_worktree *worktree = NULL;
6641 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6642 char *link_target = NULL;
6643 struct got_object_id *commit_id = NULL;
6644 struct got_commit_object *commit = NULL;
6645 char *commit_id_str = NULL;
6646 int ch;
6647 struct tog_view *view;
6648 int *pack_fds = NULL;
6650 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6651 switch (ch) {
6652 case 'c':
6653 commit_id_str = optarg;
6654 break;
6655 case 'r':
6656 repo_path = realpath(optarg, NULL);
6657 if (repo_path == NULL)
6658 return got_error_from_errno2("realpath",
6659 optarg);
6660 break;
6661 default:
6662 usage_blame();
6663 /* NOTREACHED */
6667 argc -= optind;
6668 argv += optind;
6670 if (argc != 1)
6671 usage_blame();
6673 error = got_repo_pack_fds_open(&pack_fds);
6674 if (error != NULL)
6675 goto done;
6677 if (repo_path == NULL) {
6678 cwd = getcwd(NULL, 0);
6679 if (cwd == NULL)
6680 return got_error_from_errno("getcwd");
6681 error = got_worktree_open(&worktree, cwd);
6682 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6683 goto done;
6684 if (worktree)
6685 repo_path =
6686 strdup(got_worktree_get_repo_path(worktree));
6687 else
6688 repo_path = strdup(cwd);
6689 if (repo_path == NULL) {
6690 error = got_error_from_errno("strdup");
6691 goto done;
6695 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6696 if (error != NULL)
6697 goto done;
6699 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6700 worktree);
6701 if (error)
6702 goto done;
6704 init_curses();
6706 error = apply_unveil(got_repo_get_path(repo), NULL);
6707 if (error)
6708 goto done;
6710 error = tog_load_refs(repo, 0);
6711 if (error)
6712 goto done;
6714 if (commit_id_str == NULL) {
6715 struct got_reference *head_ref;
6716 error = got_ref_open(&head_ref, repo, worktree ?
6717 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6718 if (error != NULL)
6719 goto done;
6720 error = got_ref_resolve(&commit_id, repo, head_ref);
6721 got_ref_close(head_ref);
6722 } else {
6723 error = got_repo_match_object_id(&commit_id, NULL,
6724 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6726 if (error != NULL)
6727 goto done;
6729 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6730 if (view == NULL) {
6731 error = got_error_from_errno("view_open");
6732 goto done;
6735 error = got_object_open_as_commit(&commit, repo, commit_id);
6736 if (error)
6737 goto done;
6739 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6740 commit, repo);
6741 if (error)
6742 goto done;
6744 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6745 commit_id, repo);
6746 if (error)
6747 goto done;
6748 if (worktree) {
6749 /* Release work tree lock. */
6750 got_worktree_close(worktree);
6751 worktree = NULL;
6753 error = view_loop(view);
6754 done:
6755 free(repo_path);
6756 free(in_repo_path);
6757 free(link_target);
6758 free(cwd);
6759 free(commit_id);
6760 if (commit)
6761 got_object_commit_close(commit);
6762 if (worktree)
6763 got_worktree_close(worktree);
6764 if (repo) {
6765 const struct got_error *close_err = got_repo_close(repo);
6766 if (error == NULL)
6767 error = close_err;
6769 if (pack_fds) {
6770 const struct got_error *pack_err =
6771 got_repo_pack_fds_close(pack_fds);
6772 if (error == NULL)
6773 error = pack_err;
6775 tog_free_refs();
6776 return error;
6779 static const struct got_error *
6780 draw_tree_entries(struct tog_view *view, const char *parent_path)
6782 struct tog_tree_view_state *s = &view->state.tree;
6783 const struct got_error *err = NULL;
6784 struct got_tree_entry *te;
6785 wchar_t *wline;
6786 char *index = NULL;
6787 struct tog_color *tc;
6788 int width, n, nentries, scrollx, i = 1;
6789 int limit = view->nlines;
6791 s->ndisplayed = 0;
6792 if (view_is_hsplit_top(view))
6793 --limit; /* border */
6795 werase(view->window);
6797 if (limit == 0)
6798 return NULL;
6800 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6801 0, 0);
6802 if (err)
6803 return err;
6804 if (view_needs_focus_indication(view))
6805 wstandout(view->window);
6806 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6807 if (tc)
6808 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6809 waddwstr(view->window, wline);
6810 free(wline);
6811 wline = NULL;
6812 while (width++ < view->ncols)
6813 waddch(view->window, ' ');
6814 if (tc)
6815 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6816 if (view_needs_focus_indication(view))
6817 wstandend(view->window);
6818 if (--limit <= 0)
6819 return NULL;
6821 i += s->selected;
6822 if (s->first_displayed_entry) {
6823 i += got_tree_entry_get_index(s->first_displayed_entry);
6824 if (s->tree != s->root)
6825 ++i; /* account for ".." entry */
6827 nentries = got_object_tree_get_nentries(s->tree);
6828 if (asprintf(&index, "[%d/%d] %s",
6829 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6830 return got_error_from_errno("asprintf");
6831 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6832 free(index);
6833 if (err)
6834 return err;
6835 waddwstr(view->window, wline);
6836 free(wline);
6837 wline = NULL;
6838 if (width < view->ncols - 1)
6839 waddch(view->window, '\n');
6840 if (--limit <= 0)
6841 return NULL;
6842 waddch(view->window, '\n');
6843 if (--limit <= 0)
6844 return NULL;
6846 if (s->first_displayed_entry == NULL) {
6847 te = got_object_tree_get_first_entry(s->tree);
6848 if (s->selected == 0) {
6849 if (view->focussed)
6850 wstandout(view->window);
6851 s->selected_entry = NULL;
6853 waddstr(view->window, " ..\n"); /* parent directory */
6854 if (s->selected == 0 && view->focussed)
6855 wstandend(view->window);
6856 s->ndisplayed++;
6857 if (--limit <= 0)
6858 return NULL;
6859 n = 1;
6860 } else {
6861 n = 0;
6862 te = s->first_displayed_entry;
6865 view->maxx = 0;
6866 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6867 char *line = NULL, *id_str = NULL, *link_target = NULL;
6868 const char *modestr = "";
6869 mode_t mode;
6871 te = got_object_tree_get_entry(s->tree, i);
6872 mode = got_tree_entry_get_mode(te);
6874 if (s->show_ids) {
6875 err = got_object_id_str(&id_str,
6876 got_tree_entry_get_id(te));
6877 if (err)
6878 return got_error_from_errno(
6879 "got_object_id_str");
6881 if (got_object_tree_entry_is_submodule(te))
6882 modestr = "$";
6883 else if (S_ISLNK(mode)) {
6884 int i;
6886 err = got_tree_entry_get_symlink_target(&link_target,
6887 te, s->repo);
6888 if (err) {
6889 free(id_str);
6890 return err;
6892 for (i = 0; i < strlen(link_target); i++) {
6893 if (!isprint((unsigned char)link_target[i]))
6894 link_target[i] = '?';
6896 modestr = "@";
6898 else if (S_ISDIR(mode))
6899 modestr = "/";
6900 else if (mode & S_IXUSR)
6901 modestr = "*";
6902 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6903 got_tree_entry_get_name(te), modestr,
6904 link_target ? " -> ": "",
6905 link_target ? link_target : "") == -1) {
6906 free(id_str);
6907 free(link_target);
6908 return got_error_from_errno("asprintf");
6910 free(id_str);
6911 free(link_target);
6913 /* use full line width to determine view->maxx */
6914 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
6915 if (err) {
6916 free(line);
6917 break;
6919 view->maxx = MAX(view->maxx, width);
6920 free(wline);
6921 wline = NULL;
6923 err = format_line(&wline, &width, &scrollx, line, view->x,
6924 view->ncols, 0, 0);
6925 if (err) {
6926 free(line);
6927 break;
6929 if (n == s->selected) {
6930 if (view->focussed)
6931 wstandout(view->window);
6932 s->selected_entry = te;
6934 tc = match_color(&s->colors, line);
6935 if (tc)
6936 wattr_on(view->window,
6937 COLOR_PAIR(tc->colorpair), NULL);
6938 waddwstr(view->window, &wline[scrollx]);
6939 if (tc)
6940 wattr_off(view->window,
6941 COLOR_PAIR(tc->colorpair), NULL);
6942 if (width < view->ncols)
6943 waddch(view->window, '\n');
6944 if (n == s->selected && view->focussed)
6945 wstandend(view->window);
6946 free(line);
6947 free(wline);
6948 wline = NULL;
6949 n++;
6950 s->ndisplayed++;
6951 s->last_displayed_entry = te;
6952 if (--limit <= 0)
6953 break;
6956 return err;
6959 static void
6960 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6962 struct got_tree_entry *te;
6963 int isroot = s->tree == s->root;
6964 int i = 0;
6966 if (s->first_displayed_entry == NULL)
6967 return;
6969 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6970 while (i++ < maxscroll) {
6971 if (te == NULL) {
6972 if (!isroot)
6973 s->first_displayed_entry = NULL;
6974 break;
6976 s->first_displayed_entry = te;
6977 te = got_tree_entry_get_prev(s->tree, te);
6981 static const struct got_error *
6982 tree_scroll_down(struct tog_view *view, int maxscroll)
6984 struct tog_tree_view_state *s = &view->state.tree;
6985 struct got_tree_entry *next, *last;
6986 int n = 0;
6988 if (s->first_displayed_entry)
6989 next = got_tree_entry_get_next(s->tree,
6990 s->first_displayed_entry);
6991 else
6992 next = got_object_tree_get_first_entry(s->tree);
6994 last = s->last_displayed_entry;
6995 while (next && n++ < maxscroll) {
6996 if (last) {
6997 s->last_displayed_entry = last;
6998 last = got_tree_entry_get_next(s->tree, last);
7000 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7001 s->first_displayed_entry = next;
7002 next = got_tree_entry_get_next(s->tree, next);
7006 return NULL;
7009 static const struct got_error *
7010 tree_entry_path(char **path, struct tog_parent_trees *parents,
7011 struct got_tree_entry *te)
7013 const struct got_error *err = NULL;
7014 struct tog_parent_tree *pt;
7015 size_t len = 2; /* for leading slash and NUL */
7017 TAILQ_FOREACH(pt, parents, entry)
7018 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7019 + 1 /* slash */;
7020 if (te)
7021 len += strlen(got_tree_entry_get_name(te));
7023 *path = calloc(1, len);
7024 if (path == NULL)
7025 return got_error_from_errno("calloc");
7027 (*path)[0] = '/';
7028 pt = TAILQ_LAST(parents, tog_parent_trees);
7029 while (pt) {
7030 const char *name = got_tree_entry_get_name(pt->selected_entry);
7031 if (strlcat(*path, name, len) >= len) {
7032 err = got_error(GOT_ERR_NO_SPACE);
7033 goto done;
7035 if (strlcat(*path, "/", len) >= len) {
7036 err = got_error(GOT_ERR_NO_SPACE);
7037 goto done;
7039 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7041 if (te) {
7042 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7043 err = got_error(GOT_ERR_NO_SPACE);
7044 goto done;
7047 done:
7048 if (err) {
7049 free(*path);
7050 *path = NULL;
7052 return err;
7055 static const struct got_error *
7056 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7057 struct got_tree_entry *te, struct tog_parent_trees *parents,
7058 struct got_object_id *commit_id, struct got_repository *repo)
7060 const struct got_error *err = NULL;
7061 char *path;
7062 struct tog_view *blame_view;
7064 *new_view = NULL;
7066 err = tree_entry_path(&path, parents, te);
7067 if (err)
7068 return err;
7070 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7071 if (blame_view == NULL) {
7072 err = got_error_from_errno("view_open");
7073 goto done;
7076 err = open_blame_view(blame_view, path, commit_id, repo);
7077 if (err) {
7078 if (err->code == GOT_ERR_CANCELLED)
7079 err = NULL;
7080 view_close(blame_view);
7081 } else
7082 *new_view = blame_view;
7083 done:
7084 free(path);
7085 return err;
7088 static const struct got_error *
7089 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7090 struct tog_tree_view_state *s)
7092 struct tog_view *log_view;
7093 const struct got_error *err = NULL;
7094 char *path;
7096 *new_view = NULL;
7098 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7099 if (log_view == NULL)
7100 return got_error_from_errno("view_open");
7102 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7103 if (err)
7104 return err;
7106 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7107 path, 0);
7108 if (err)
7109 view_close(log_view);
7110 else
7111 *new_view = log_view;
7112 free(path);
7113 return err;
7116 static const struct got_error *
7117 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7118 const char *head_ref_name, struct got_repository *repo)
7120 const struct got_error *err = NULL;
7121 char *commit_id_str = NULL;
7122 struct tog_tree_view_state *s = &view->state.tree;
7123 struct got_commit_object *commit = NULL;
7125 TAILQ_INIT(&s->parents);
7126 STAILQ_INIT(&s->colors);
7128 s->commit_id = got_object_id_dup(commit_id);
7129 if (s->commit_id == NULL)
7130 return got_error_from_errno("got_object_id_dup");
7132 err = got_object_open_as_commit(&commit, repo, commit_id);
7133 if (err)
7134 goto done;
7137 * The root is opened here and will be closed when the view is closed.
7138 * Any visited subtrees and their path-wise parents are opened and
7139 * closed on demand.
7141 err = got_object_open_as_tree(&s->root, repo,
7142 got_object_commit_get_tree_id(commit));
7143 if (err)
7144 goto done;
7145 s->tree = s->root;
7147 err = got_object_id_str(&commit_id_str, commit_id);
7148 if (err != NULL)
7149 goto done;
7151 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7152 err = got_error_from_errno("asprintf");
7153 goto done;
7156 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7157 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7158 if (head_ref_name) {
7159 s->head_ref_name = strdup(head_ref_name);
7160 if (s->head_ref_name == NULL) {
7161 err = got_error_from_errno("strdup");
7162 goto done;
7165 s->repo = repo;
7167 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7168 err = add_color(&s->colors, "\\$$",
7169 TOG_COLOR_TREE_SUBMODULE,
7170 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7171 if (err)
7172 goto done;
7173 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7174 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7175 if (err)
7176 goto done;
7177 err = add_color(&s->colors, "/$",
7178 TOG_COLOR_TREE_DIRECTORY,
7179 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7180 if (err)
7181 goto done;
7183 err = add_color(&s->colors, "\\*$",
7184 TOG_COLOR_TREE_EXECUTABLE,
7185 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7186 if (err)
7187 goto done;
7189 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7190 get_color_value("TOG_COLOR_COMMIT"));
7191 if (err)
7192 goto done;
7195 view->show = show_tree_view;
7196 view->input = input_tree_view;
7197 view->close = close_tree_view;
7198 view->search_start = search_start_tree_view;
7199 view->search_next = search_next_tree_view;
7200 done:
7201 free(commit_id_str);
7202 if (commit)
7203 got_object_commit_close(commit);
7204 if (err)
7205 close_tree_view(view);
7206 return err;
7209 static const struct got_error *
7210 close_tree_view(struct tog_view *view)
7212 struct tog_tree_view_state *s = &view->state.tree;
7214 free_colors(&s->colors);
7215 free(s->tree_label);
7216 s->tree_label = NULL;
7217 free(s->commit_id);
7218 s->commit_id = NULL;
7219 free(s->head_ref_name);
7220 s->head_ref_name = NULL;
7221 while (!TAILQ_EMPTY(&s->parents)) {
7222 struct tog_parent_tree *parent;
7223 parent = TAILQ_FIRST(&s->parents);
7224 TAILQ_REMOVE(&s->parents, parent, entry);
7225 if (parent->tree != s->root)
7226 got_object_tree_close(parent->tree);
7227 free(parent);
7230 if (s->tree != NULL && s->tree != s->root)
7231 got_object_tree_close(s->tree);
7232 if (s->root)
7233 got_object_tree_close(s->root);
7234 return NULL;
7237 static const struct got_error *
7238 search_start_tree_view(struct tog_view *view)
7240 struct tog_tree_view_state *s = &view->state.tree;
7242 s->matched_entry = NULL;
7243 return NULL;
7246 static int
7247 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7249 regmatch_t regmatch;
7251 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7252 0) == 0;
7255 static const struct got_error *
7256 search_next_tree_view(struct tog_view *view)
7258 struct tog_tree_view_state *s = &view->state.tree;
7259 struct got_tree_entry *te = NULL;
7261 if (!view->searching) {
7262 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7263 return NULL;
7266 if (s->matched_entry) {
7267 if (view->searching == TOG_SEARCH_FORWARD) {
7268 if (s->selected_entry)
7269 te = got_tree_entry_get_next(s->tree,
7270 s->selected_entry);
7271 else
7272 te = got_object_tree_get_first_entry(s->tree);
7273 } else {
7274 if (s->selected_entry == NULL)
7275 te = got_object_tree_get_last_entry(s->tree);
7276 else
7277 te = got_tree_entry_get_prev(s->tree,
7278 s->selected_entry);
7280 } else {
7281 if (s->selected_entry)
7282 te = s->selected_entry;
7283 else if (view->searching == TOG_SEARCH_FORWARD)
7284 te = got_object_tree_get_first_entry(s->tree);
7285 else
7286 te = got_object_tree_get_last_entry(s->tree);
7289 while (1) {
7290 if (te == NULL) {
7291 if (s->matched_entry == NULL) {
7292 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7293 return NULL;
7295 if (view->searching == TOG_SEARCH_FORWARD)
7296 te = got_object_tree_get_first_entry(s->tree);
7297 else
7298 te = got_object_tree_get_last_entry(s->tree);
7301 if (match_tree_entry(te, &view->regex)) {
7302 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7303 s->matched_entry = te;
7304 break;
7307 if (view->searching == TOG_SEARCH_FORWARD)
7308 te = got_tree_entry_get_next(s->tree, te);
7309 else
7310 te = got_tree_entry_get_prev(s->tree, te);
7313 if (s->matched_entry) {
7314 s->first_displayed_entry = s->matched_entry;
7315 s->selected = 0;
7318 return NULL;
7321 static const struct got_error *
7322 show_tree_view(struct tog_view *view)
7324 const struct got_error *err = NULL;
7325 struct tog_tree_view_state *s = &view->state.tree;
7326 char *parent_path;
7328 err = tree_entry_path(&parent_path, &s->parents, NULL);
7329 if (err)
7330 return err;
7332 err = draw_tree_entries(view, parent_path);
7333 free(parent_path);
7335 view_border(view);
7336 return err;
7339 static const struct got_error *
7340 tree_goto_line(struct tog_view *view, int nlines)
7342 const struct got_error *err = NULL;
7343 struct tog_tree_view_state *s = &view->state.tree;
7344 struct got_tree_entry **fte, **lte, **ste;
7345 int g, last, first = 1, i = 1;
7346 int root = s->tree == s->root;
7347 int off = root ? 1 : 2;
7349 g = view->gline;
7350 view->gline = 0;
7352 if (g == 0)
7353 g = 1;
7354 else if (g > got_object_tree_get_nentries(s->tree))
7355 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7357 fte = &s->first_displayed_entry;
7358 lte = &s->last_displayed_entry;
7359 ste = &s->selected_entry;
7361 if (*fte != NULL) {
7362 first = got_tree_entry_get_index(*fte);
7363 first += off; /* account for ".." */
7365 last = got_tree_entry_get_index(*lte);
7366 last += off;
7368 if (g >= first && g <= last && g - first < nlines) {
7369 s->selected = g - first;
7370 return NULL; /* gline is on the current page */
7373 if (*ste != NULL) {
7374 i = got_tree_entry_get_index(*ste);
7375 i += off;
7378 if (i < g) {
7379 err = tree_scroll_down(view, g - i);
7380 if (err)
7381 return err;
7382 if (got_tree_entry_get_index(*lte) >=
7383 got_object_tree_get_nentries(s->tree) - 1 &&
7384 first + s->selected < g &&
7385 s->selected < s->ndisplayed - 1) {
7386 first = got_tree_entry_get_index(*fte);
7387 first += off;
7388 s->selected = g - first;
7390 } else if (i > g)
7391 tree_scroll_up(s, i - g);
7393 if (g < nlines &&
7394 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7395 s->selected = g - 1;
7397 return NULL;
7400 static const struct got_error *
7401 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7403 const struct got_error *err = NULL;
7404 struct tog_tree_view_state *s = &view->state.tree;
7405 struct got_tree_entry *te;
7406 int n, nscroll = view->nlines - 3;
7408 if (view->gline)
7409 return tree_goto_line(view, nscroll);
7411 switch (ch) {
7412 case '0':
7413 case '$':
7414 case KEY_RIGHT:
7415 case 'l':
7416 case KEY_LEFT:
7417 case 'h':
7418 horizontal_scroll_input(view, ch);
7419 break;
7420 case 'i':
7421 s->show_ids = !s->show_ids;
7422 view->count = 0;
7423 break;
7424 case 'L':
7425 view->count = 0;
7426 if (!s->selected_entry)
7427 break;
7428 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7429 break;
7430 case 'R':
7431 view->count = 0;
7432 err = view_request_new(new_view, view, TOG_VIEW_REF);
7433 break;
7434 case 'g':
7435 case '=':
7436 case KEY_HOME:
7437 s->selected = 0;
7438 view->count = 0;
7439 if (s->tree == s->root)
7440 s->first_displayed_entry =
7441 got_object_tree_get_first_entry(s->tree);
7442 else
7443 s->first_displayed_entry = NULL;
7444 break;
7445 case 'G':
7446 case '*':
7447 case KEY_END: {
7448 int eos = view->nlines - 3;
7450 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7451 --eos; /* border */
7452 s->selected = 0;
7453 view->count = 0;
7454 te = got_object_tree_get_last_entry(s->tree);
7455 for (n = 0; n < eos; n++) {
7456 if (te == NULL) {
7457 if (s->tree != s->root) {
7458 s->first_displayed_entry = NULL;
7459 n++;
7461 break;
7463 s->first_displayed_entry = te;
7464 te = got_tree_entry_get_prev(s->tree, te);
7466 if (n > 0)
7467 s->selected = n - 1;
7468 break;
7470 case 'k':
7471 case KEY_UP:
7472 case CTRL('p'):
7473 if (s->selected > 0) {
7474 s->selected--;
7475 break;
7477 tree_scroll_up(s, 1);
7478 if (s->selected_entry == NULL ||
7479 (s->tree == s->root && s->selected_entry ==
7480 got_object_tree_get_first_entry(s->tree)))
7481 view->count = 0;
7482 break;
7483 case CTRL('u'):
7484 case 'u':
7485 nscroll /= 2;
7486 /* FALL THROUGH */
7487 case KEY_PPAGE:
7488 case CTRL('b'):
7489 case 'b':
7490 if (s->tree == s->root) {
7491 if (got_object_tree_get_first_entry(s->tree) ==
7492 s->first_displayed_entry)
7493 s->selected -= MIN(s->selected, nscroll);
7494 } else {
7495 if (s->first_displayed_entry == NULL)
7496 s->selected -= MIN(s->selected, nscroll);
7498 tree_scroll_up(s, MAX(0, nscroll));
7499 if (s->selected_entry == NULL ||
7500 (s->tree == s->root && s->selected_entry ==
7501 got_object_tree_get_first_entry(s->tree)))
7502 view->count = 0;
7503 break;
7504 case 'j':
7505 case KEY_DOWN:
7506 case CTRL('n'):
7507 if (s->selected < s->ndisplayed - 1) {
7508 s->selected++;
7509 break;
7511 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7512 == NULL) {
7513 /* can't scroll any further */
7514 view->count = 0;
7515 break;
7517 tree_scroll_down(view, 1);
7518 break;
7519 case CTRL('d'):
7520 case 'd':
7521 nscroll /= 2;
7522 /* FALL THROUGH */
7523 case KEY_NPAGE:
7524 case CTRL('f'):
7525 case 'f':
7526 case ' ':
7527 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7528 == NULL) {
7529 /* can't scroll any further; move cursor down */
7530 if (s->selected < s->ndisplayed - 1)
7531 s->selected += MIN(nscroll,
7532 s->ndisplayed - s->selected - 1);
7533 else
7534 view->count = 0;
7535 break;
7537 tree_scroll_down(view, nscroll);
7538 break;
7539 case KEY_ENTER:
7540 case '\r':
7541 case KEY_BACKSPACE:
7542 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7543 struct tog_parent_tree *parent;
7544 /* user selected '..' */
7545 if (s->tree == s->root) {
7546 view->count = 0;
7547 break;
7549 parent = TAILQ_FIRST(&s->parents);
7550 TAILQ_REMOVE(&s->parents, parent,
7551 entry);
7552 got_object_tree_close(s->tree);
7553 s->tree = parent->tree;
7554 s->first_displayed_entry =
7555 parent->first_displayed_entry;
7556 s->selected_entry =
7557 parent->selected_entry;
7558 s->selected = parent->selected;
7559 if (s->selected > view->nlines - 3) {
7560 err = offset_selection_down(view);
7561 if (err)
7562 break;
7564 free(parent);
7565 } else if (S_ISDIR(got_tree_entry_get_mode(
7566 s->selected_entry))) {
7567 struct got_tree_object *subtree;
7568 view->count = 0;
7569 err = got_object_open_as_tree(&subtree, s->repo,
7570 got_tree_entry_get_id(s->selected_entry));
7571 if (err)
7572 break;
7573 err = tree_view_visit_subtree(s, subtree);
7574 if (err) {
7575 got_object_tree_close(subtree);
7576 break;
7578 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7579 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7580 break;
7581 case KEY_RESIZE:
7582 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7583 s->selected = view->nlines - 4;
7584 view->count = 0;
7585 break;
7586 default:
7587 view->count = 0;
7588 break;
7591 return err;
7594 __dead static void
7595 usage_tree(void)
7597 endwin();
7598 fprintf(stderr,
7599 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7600 getprogname());
7601 exit(1);
7604 static const struct got_error *
7605 cmd_tree(int argc, char *argv[])
7607 const struct got_error *error;
7608 struct got_repository *repo = NULL;
7609 struct got_worktree *worktree = NULL;
7610 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7611 struct got_object_id *commit_id = NULL;
7612 struct got_commit_object *commit = NULL;
7613 const char *commit_id_arg = NULL;
7614 char *label = NULL;
7615 struct got_reference *ref = NULL;
7616 const char *head_ref_name = NULL;
7617 int ch;
7618 struct tog_view *view;
7619 int *pack_fds = NULL;
7621 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7622 switch (ch) {
7623 case 'c':
7624 commit_id_arg = optarg;
7625 break;
7626 case 'r':
7627 repo_path = realpath(optarg, NULL);
7628 if (repo_path == NULL)
7629 return got_error_from_errno2("realpath",
7630 optarg);
7631 break;
7632 default:
7633 usage_tree();
7634 /* NOTREACHED */
7638 argc -= optind;
7639 argv += optind;
7641 if (argc > 1)
7642 usage_tree();
7644 error = got_repo_pack_fds_open(&pack_fds);
7645 if (error != NULL)
7646 goto done;
7648 if (repo_path == NULL) {
7649 cwd = getcwd(NULL, 0);
7650 if (cwd == NULL)
7651 return got_error_from_errno("getcwd");
7652 error = got_worktree_open(&worktree, cwd);
7653 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7654 goto done;
7655 if (worktree)
7656 repo_path =
7657 strdup(got_worktree_get_repo_path(worktree));
7658 else
7659 repo_path = strdup(cwd);
7660 if (repo_path == NULL) {
7661 error = got_error_from_errno("strdup");
7662 goto done;
7666 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7667 if (error != NULL)
7668 goto done;
7670 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7671 repo, worktree);
7672 if (error)
7673 goto done;
7675 init_curses();
7677 error = apply_unveil(got_repo_get_path(repo), NULL);
7678 if (error)
7679 goto done;
7681 error = tog_load_refs(repo, 0);
7682 if (error)
7683 goto done;
7685 if (commit_id_arg == NULL) {
7686 error = got_repo_match_object_id(&commit_id, &label,
7687 worktree ? got_worktree_get_head_ref_name(worktree) :
7688 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7689 if (error)
7690 goto done;
7691 head_ref_name = label;
7692 } else {
7693 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7694 if (error == NULL)
7695 head_ref_name = got_ref_get_name(ref);
7696 else if (error->code != GOT_ERR_NOT_REF)
7697 goto done;
7698 error = got_repo_match_object_id(&commit_id, NULL,
7699 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7700 if (error)
7701 goto done;
7704 error = got_object_open_as_commit(&commit, repo, commit_id);
7705 if (error)
7706 goto done;
7708 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7709 if (view == NULL) {
7710 error = got_error_from_errno("view_open");
7711 goto done;
7713 error = open_tree_view(view, commit_id, head_ref_name, repo);
7714 if (error)
7715 goto done;
7716 if (!got_path_is_root_dir(in_repo_path)) {
7717 error = tree_view_walk_path(&view->state.tree, commit,
7718 in_repo_path);
7719 if (error)
7720 goto done;
7723 if (worktree) {
7724 /* Release work tree lock. */
7725 got_worktree_close(worktree);
7726 worktree = NULL;
7728 error = view_loop(view);
7729 done:
7730 free(repo_path);
7731 free(cwd);
7732 free(commit_id);
7733 free(label);
7734 if (ref)
7735 got_ref_close(ref);
7736 if (repo) {
7737 const struct got_error *close_err = got_repo_close(repo);
7738 if (error == NULL)
7739 error = close_err;
7741 if (pack_fds) {
7742 const struct got_error *pack_err =
7743 got_repo_pack_fds_close(pack_fds);
7744 if (error == NULL)
7745 error = pack_err;
7747 tog_free_refs();
7748 return error;
7751 static const struct got_error *
7752 ref_view_load_refs(struct tog_ref_view_state *s)
7754 struct got_reflist_entry *sre;
7755 struct tog_reflist_entry *re;
7757 s->nrefs = 0;
7758 TAILQ_FOREACH(sre, &tog_refs, entry) {
7759 if (strncmp(got_ref_get_name(sre->ref),
7760 "refs/got/", 9) == 0 &&
7761 strncmp(got_ref_get_name(sre->ref),
7762 "refs/got/backup/", 16) != 0)
7763 continue;
7765 re = malloc(sizeof(*re));
7766 if (re == NULL)
7767 return got_error_from_errno("malloc");
7769 re->ref = got_ref_dup(sre->ref);
7770 if (re->ref == NULL)
7771 return got_error_from_errno("got_ref_dup");
7772 re->idx = s->nrefs++;
7773 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7776 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7777 return NULL;
7780 static void
7781 ref_view_free_refs(struct tog_ref_view_state *s)
7783 struct tog_reflist_entry *re;
7785 while (!TAILQ_EMPTY(&s->refs)) {
7786 re = TAILQ_FIRST(&s->refs);
7787 TAILQ_REMOVE(&s->refs, re, entry);
7788 got_ref_close(re->ref);
7789 free(re);
7793 static const struct got_error *
7794 open_ref_view(struct tog_view *view, struct got_repository *repo)
7796 const struct got_error *err = NULL;
7797 struct tog_ref_view_state *s = &view->state.ref;
7799 s->selected_entry = 0;
7800 s->repo = repo;
7802 TAILQ_INIT(&s->refs);
7803 STAILQ_INIT(&s->colors);
7805 err = ref_view_load_refs(s);
7806 if (err)
7807 return err;
7809 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7810 err = add_color(&s->colors, "^refs/heads/",
7811 TOG_COLOR_REFS_HEADS,
7812 get_color_value("TOG_COLOR_REFS_HEADS"));
7813 if (err)
7814 goto done;
7816 err = add_color(&s->colors, "^refs/tags/",
7817 TOG_COLOR_REFS_TAGS,
7818 get_color_value("TOG_COLOR_REFS_TAGS"));
7819 if (err)
7820 goto done;
7822 err = add_color(&s->colors, "^refs/remotes/",
7823 TOG_COLOR_REFS_REMOTES,
7824 get_color_value("TOG_COLOR_REFS_REMOTES"));
7825 if (err)
7826 goto done;
7828 err = add_color(&s->colors, "^refs/got/backup/",
7829 TOG_COLOR_REFS_BACKUP,
7830 get_color_value("TOG_COLOR_REFS_BACKUP"));
7831 if (err)
7832 goto done;
7835 view->show = show_ref_view;
7836 view->input = input_ref_view;
7837 view->close = close_ref_view;
7838 view->search_start = search_start_ref_view;
7839 view->search_next = search_next_ref_view;
7840 done:
7841 if (err)
7842 free_colors(&s->colors);
7843 return err;
7846 static const struct got_error *
7847 close_ref_view(struct tog_view *view)
7849 struct tog_ref_view_state *s = &view->state.ref;
7851 ref_view_free_refs(s);
7852 free_colors(&s->colors);
7854 return NULL;
7857 static const struct got_error *
7858 resolve_reflist_entry(struct got_object_id **commit_id,
7859 struct tog_reflist_entry *re, struct got_repository *repo)
7861 const struct got_error *err = NULL;
7862 struct got_object_id *obj_id;
7863 struct got_tag_object *tag = NULL;
7864 int obj_type;
7866 *commit_id = NULL;
7868 err = got_ref_resolve(&obj_id, repo, re->ref);
7869 if (err)
7870 return err;
7872 err = got_object_get_type(&obj_type, repo, obj_id);
7873 if (err)
7874 goto done;
7876 switch (obj_type) {
7877 case GOT_OBJ_TYPE_COMMIT:
7878 *commit_id = obj_id;
7879 break;
7880 case GOT_OBJ_TYPE_TAG:
7881 err = got_object_open_as_tag(&tag, repo, obj_id);
7882 if (err)
7883 goto done;
7884 free(obj_id);
7885 err = got_object_get_type(&obj_type, repo,
7886 got_object_tag_get_object_id(tag));
7887 if (err)
7888 goto done;
7889 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7890 err = got_error(GOT_ERR_OBJ_TYPE);
7891 goto done;
7893 *commit_id = got_object_id_dup(
7894 got_object_tag_get_object_id(tag));
7895 if (*commit_id == NULL) {
7896 err = got_error_from_errno("got_object_id_dup");
7897 goto done;
7899 break;
7900 default:
7901 err = got_error(GOT_ERR_OBJ_TYPE);
7902 break;
7905 done:
7906 if (tag)
7907 got_object_tag_close(tag);
7908 if (err) {
7909 free(*commit_id);
7910 *commit_id = NULL;
7912 return err;
7915 static const struct got_error *
7916 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7917 struct tog_reflist_entry *re, struct got_repository *repo)
7919 struct tog_view *log_view;
7920 const struct got_error *err = NULL;
7921 struct got_object_id *commit_id = NULL;
7923 *new_view = NULL;
7925 err = resolve_reflist_entry(&commit_id, re, repo);
7926 if (err) {
7927 if (err->code != GOT_ERR_OBJ_TYPE)
7928 return err;
7929 else
7930 return NULL;
7933 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7934 if (log_view == NULL) {
7935 err = got_error_from_errno("view_open");
7936 goto done;
7939 err = open_log_view(log_view, commit_id, repo,
7940 got_ref_get_name(re->ref), "", 0);
7941 done:
7942 if (err)
7943 view_close(log_view);
7944 else
7945 *new_view = log_view;
7946 free(commit_id);
7947 return err;
7950 static void
7951 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7953 struct tog_reflist_entry *re;
7954 int i = 0;
7956 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7957 return;
7959 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7960 while (i++ < maxscroll) {
7961 if (re == NULL)
7962 break;
7963 s->first_displayed_entry = re;
7964 re = TAILQ_PREV(re, tog_reflist_head, entry);
7968 static const struct got_error *
7969 ref_scroll_down(struct tog_view *view, int maxscroll)
7971 struct tog_ref_view_state *s = &view->state.ref;
7972 struct tog_reflist_entry *next, *last;
7973 int n = 0;
7975 if (s->first_displayed_entry)
7976 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7977 else
7978 next = TAILQ_FIRST(&s->refs);
7980 last = s->last_displayed_entry;
7981 while (next && n++ < maxscroll) {
7982 if (last) {
7983 s->last_displayed_entry = last;
7984 last = TAILQ_NEXT(last, entry);
7986 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7987 s->first_displayed_entry = next;
7988 next = TAILQ_NEXT(next, entry);
7992 return NULL;
7995 static const struct got_error *
7996 search_start_ref_view(struct tog_view *view)
7998 struct tog_ref_view_state *s = &view->state.ref;
8000 s->matched_entry = NULL;
8001 return NULL;
8004 static int
8005 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8007 regmatch_t regmatch;
8009 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8010 0) == 0;
8013 static const struct got_error *
8014 search_next_ref_view(struct tog_view *view)
8016 struct tog_ref_view_state *s = &view->state.ref;
8017 struct tog_reflist_entry *re = NULL;
8019 if (!view->searching) {
8020 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8021 return NULL;
8024 if (s->matched_entry) {
8025 if (view->searching == TOG_SEARCH_FORWARD) {
8026 if (s->selected_entry)
8027 re = TAILQ_NEXT(s->selected_entry, entry);
8028 else
8029 re = TAILQ_PREV(s->selected_entry,
8030 tog_reflist_head, entry);
8031 } else {
8032 if (s->selected_entry == NULL)
8033 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8034 else
8035 re = TAILQ_PREV(s->selected_entry,
8036 tog_reflist_head, entry);
8038 } else {
8039 if (s->selected_entry)
8040 re = s->selected_entry;
8041 else if (view->searching == TOG_SEARCH_FORWARD)
8042 re = TAILQ_FIRST(&s->refs);
8043 else
8044 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8047 while (1) {
8048 if (re == NULL) {
8049 if (s->matched_entry == NULL) {
8050 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8051 return NULL;
8053 if (view->searching == TOG_SEARCH_FORWARD)
8054 re = TAILQ_FIRST(&s->refs);
8055 else
8056 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8059 if (match_reflist_entry(re, &view->regex)) {
8060 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8061 s->matched_entry = re;
8062 break;
8065 if (view->searching == TOG_SEARCH_FORWARD)
8066 re = TAILQ_NEXT(re, entry);
8067 else
8068 re = TAILQ_PREV(re, tog_reflist_head, entry);
8071 if (s->matched_entry) {
8072 s->first_displayed_entry = s->matched_entry;
8073 s->selected = 0;
8076 return NULL;
8079 static const struct got_error *
8080 show_ref_view(struct tog_view *view)
8082 const struct got_error *err = NULL;
8083 struct tog_ref_view_state *s = &view->state.ref;
8084 struct tog_reflist_entry *re;
8085 char *line = NULL;
8086 wchar_t *wline;
8087 struct tog_color *tc;
8088 int width, n, scrollx;
8089 int limit = view->nlines;
8091 werase(view->window);
8093 s->ndisplayed = 0;
8094 if (view_is_hsplit_top(view))
8095 --limit; /* border */
8097 if (limit == 0)
8098 return NULL;
8100 re = s->first_displayed_entry;
8102 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8103 s->nrefs) == -1)
8104 return got_error_from_errno("asprintf");
8106 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8107 if (err) {
8108 free(line);
8109 return err;
8111 if (view_needs_focus_indication(view))
8112 wstandout(view->window);
8113 waddwstr(view->window, wline);
8114 while (width++ < view->ncols)
8115 waddch(view->window, ' ');
8116 if (view_needs_focus_indication(view))
8117 wstandend(view->window);
8118 free(wline);
8119 wline = NULL;
8120 free(line);
8121 line = NULL;
8122 if (--limit <= 0)
8123 return NULL;
8125 n = 0;
8126 view->maxx = 0;
8127 while (re && limit > 0) {
8128 char *line = NULL;
8129 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8131 if (s->show_date) {
8132 struct got_commit_object *ci;
8133 struct got_tag_object *tag;
8134 struct got_object_id *id;
8135 struct tm tm;
8136 time_t t;
8138 err = got_ref_resolve(&id, s->repo, re->ref);
8139 if (err)
8140 return err;
8141 err = got_object_open_as_tag(&tag, s->repo, id);
8142 if (err) {
8143 if (err->code != GOT_ERR_OBJ_TYPE) {
8144 free(id);
8145 return err;
8147 err = got_object_open_as_commit(&ci, s->repo,
8148 id);
8149 if (err) {
8150 free(id);
8151 return err;
8153 t = got_object_commit_get_committer_time(ci);
8154 got_object_commit_close(ci);
8155 } else {
8156 t = got_object_tag_get_tagger_time(tag);
8157 got_object_tag_close(tag);
8159 free(id);
8160 if (gmtime_r(&t, &tm) == NULL)
8161 return got_error_from_errno("gmtime_r");
8162 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8163 return got_error(GOT_ERR_NO_SPACE);
8165 if (got_ref_is_symbolic(re->ref)) {
8166 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8167 ymd : "", got_ref_get_name(re->ref),
8168 got_ref_get_symref_target(re->ref)) == -1)
8169 return got_error_from_errno("asprintf");
8170 } else if (s->show_ids) {
8171 struct got_object_id *id;
8172 char *id_str;
8173 err = got_ref_resolve(&id, s->repo, re->ref);
8174 if (err)
8175 return err;
8176 err = got_object_id_str(&id_str, id);
8177 if (err) {
8178 free(id);
8179 return err;
8181 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8182 got_ref_get_name(re->ref), id_str) == -1) {
8183 err = got_error_from_errno("asprintf");
8184 free(id);
8185 free(id_str);
8186 return err;
8188 free(id);
8189 free(id_str);
8190 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8191 got_ref_get_name(re->ref)) == -1)
8192 return got_error_from_errno("asprintf");
8194 /* use full line width to determine view->maxx */
8195 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8196 if (err) {
8197 free(line);
8198 return err;
8200 view->maxx = MAX(view->maxx, width);
8201 free(wline);
8202 wline = NULL;
8204 err = format_line(&wline, &width, &scrollx, line, view->x,
8205 view->ncols, 0, 0);
8206 if (err) {
8207 free(line);
8208 return err;
8210 if (n == s->selected) {
8211 if (view->focussed)
8212 wstandout(view->window);
8213 s->selected_entry = re;
8215 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8216 if (tc)
8217 wattr_on(view->window,
8218 COLOR_PAIR(tc->colorpair), NULL);
8219 waddwstr(view->window, &wline[scrollx]);
8220 if (tc)
8221 wattr_off(view->window,
8222 COLOR_PAIR(tc->colorpair), NULL);
8223 if (width < view->ncols)
8224 waddch(view->window, '\n');
8225 if (n == s->selected && view->focussed)
8226 wstandend(view->window);
8227 free(line);
8228 free(wline);
8229 wline = NULL;
8230 n++;
8231 s->ndisplayed++;
8232 s->last_displayed_entry = re;
8234 limit--;
8235 re = TAILQ_NEXT(re, entry);
8238 view_border(view);
8239 return err;
8242 static const struct got_error *
8243 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8244 struct tog_reflist_entry *re, struct got_repository *repo)
8246 const struct got_error *err = NULL;
8247 struct got_object_id *commit_id = NULL;
8248 struct tog_view *tree_view;
8250 *new_view = NULL;
8252 err = resolve_reflist_entry(&commit_id, re, repo);
8253 if (err) {
8254 if (err->code != GOT_ERR_OBJ_TYPE)
8255 return err;
8256 else
8257 return NULL;
8261 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8262 if (tree_view == NULL) {
8263 err = got_error_from_errno("view_open");
8264 goto done;
8267 err = open_tree_view(tree_view, commit_id,
8268 got_ref_get_name(re->ref), repo);
8269 if (err)
8270 goto done;
8272 *new_view = tree_view;
8273 done:
8274 free(commit_id);
8275 return err;
8278 static const struct got_error *
8279 ref_goto_line(struct tog_view *view, int nlines)
8281 const struct got_error *err = NULL;
8282 struct tog_ref_view_state *s = &view->state.ref;
8283 int g, idx = s->selected_entry->idx;
8285 g = view->gline;
8286 view->gline = 0;
8288 if (g == 0)
8289 g = 1;
8290 else if (g > s->nrefs)
8291 g = s->nrefs;
8293 if (g >= s->first_displayed_entry->idx + 1 &&
8294 g <= s->last_displayed_entry->idx + 1 &&
8295 g - s->first_displayed_entry->idx - 1 < nlines) {
8296 s->selected = g - s->first_displayed_entry->idx - 1;
8297 return NULL;
8300 if (idx + 1 < g) {
8301 err = ref_scroll_down(view, g - idx - 1);
8302 if (err)
8303 return err;
8304 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8305 s->first_displayed_entry->idx + s->selected < g &&
8306 s->selected < s->ndisplayed - 1)
8307 s->selected = g - s->first_displayed_entry->idx - 1;
8308 } else if (idx + 1 > g)
8309 ref_scroll_up(s, idx - g + 1);
8311 if (g < nlines && s->first_displayed_entry->idx == 0)
8312 s->selected = g - 1;
8314 return NULL;
8318 static const struct got_error *
8319 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8321 const struct got_error *err = NULL;
8322 struct tog_ref_view_state *s = &view->state.ref;
8323 struct tog_reflist_entry *re;
8324 int n, nscroll = view->nlines - 1;
8326 if (view->gline)
8327 return ref_goto_line(view, nscroll);
8329 switch (ch) {
8330 case '0':
8331 case '$':
8332 case KEY_RIGHT:
8333 case 'l':
8334 case KEY_LEFT:
8335 case 'h':
8336 horizontal_scroll_input(view, ch);
8337 break;
8338 case 'i':
8339 s->show_ids = !s->show_ids;
8340 view->count = 0;
8341 break;
8342 case 'm':
8343 s->show_date = !s->show_date;
8344 view->count = 0;
8345 break;
8346 case 'o':
8347 s->sort_by_date = !s->sort_by_date;
8348 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8349 view->count = 0;
8350 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8351 got_ref_cmp_by_commit_timestamp_descending :
8352 tog_ref_cmp_by_name, s->repo);
8353 if (err)
8354 break;
8355 got_reflist_object_id_map_free(tog_refs_idmap);
8356 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8357 &tog_refs, s->repo);
8358 if (err)
8359 break;
8360 ref_view_free_refs(s);
8361 err = ref_view_load_refs(s);
8362 break;
8363 case KEY_ENTER:
8364 case '\r':
8365 view->count = 0;
8366 if (!s->selected_entry)
8367 break;
8368 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8369 break;
8370 case 'T':
8371 view->count = 0;
8372 if (!s->selected_entry)
8373 break;
8374 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8375 break;
8376 case 'g':
8377 case '=':
8378 case KEY_HOME:
8379 s->selected = 0;
8380 view->count = 0;
8381 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8382 break;
8383 case 'G':
8384 case '*':
8385 case KEY_END: {
8386 int eos = view->nlines - 1;
8388 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8389 --eos; /* border */
8390 s->selected = 0;
8391 view->count = 0;
8392 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8393 for (n = 0; n < eos; n++) {
8394 if (re == NULL)
8395 break;
8396 s->first_displayed_entry = re;
8397 re = TAILQ_PREV(re, tog_reflist_head, entry);
8399 if (n > 0)
8400 s->selected = n - 1;
8401 break;
8403 case 'k':
8404 case KEY_UP:
8405 case CTRL('p'):
8406 if (s->selected > 0) {
8407 s->selected--;
8408 break;
8410 ref_scroll_up(s, 1);
8411 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8412 view->count = 0;
8413 break;
8414 case CTRL('u'):
8415 case 'u':
8416 nscroll /= 2;
8417 /* FALL THROUGH */
8418 case KEY_PPAGE:
8419 case CTRL('b'):
8420 case 'b':
8421 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8422 s->selected -= MIN(nscroll, s->selected);
8423 ref_scroll_up(s, MAX(0, nscroll));
8424 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8425 view->count = 0;
8426 break;
8427 case 'j':
8428 case KEY_DOWN:
8429 case CTRL('n'):
8430 if (s->selected < s->ndisplayed - 1) {
8431 s->selected++;
8432 break;
8434 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8435 /* can't scroll any further */
8436 view->count = 0;
8437 break;
8439 ref_scroll_down(view, 1);
8440 break;
8441 case CTRL('d'):
8442 case 'd':
8443 nscroll /= 2;
8444 /* FALL THROUGH */
8445 case KEY_NPAGE:
8446 case CTRL('f'):
8447 case 'f':
8448 case ' ':
8449 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8450 /* can't scroll any further; move cursor down */
8451 if (s->selected < s->ndisplayed - 1)
8452 s->selected += MIN(nscroll,
8453 s->ndisplayed - s->selected - 1);
8454 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8455 s->selected += s->ndisplayed - s->selected - 1;
8456 view->count = 0;
8457 break;
8459 ref_scroll_down(view, nscroll);
8460 break;
8461 case CTRL('l'):
8462 view->count = 0;
8463 tog_free_refs();
8464 err = tog_load_refs(s->repo, s->sort_by_date);
8465 if (err)
8466 break;
8467 ref_view_free_refs(s);
8468 err = ref_view_load_refs(s);
8469 break;
8470 case KEY_RESIZE:
8471 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8472 s->selected = view->nlines - 2;
8473 break;
8474 default:
8475 view->count = 0;
8476 break;
8479 return err;
8482 __dead static void
8483 usage_ref(void)
8485 endwin();
8486 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8487 getprogname());
8488 exit(1);
8491 static const struct got_error *
8492 cmd_ref(int argc, char *argv[])
8494 const struct got_error *error;
8495 struct got_repository *repo = NULL;
8496 struct got_worktree *worktree = NULL;
8497 char *cwd = NULL, *repo_path = NULL;
8498 int ch;
8499 struct tog_view *view;
8500 int *pack_fds = NULL;
8502 while ((ch = getopt(argc, argv, "r:")) != -1) {
8503 switch (ch) {
8504 case 'r':
8505 repo_path = realpath(optarg, NULL);
8506 if (repo_path == NULL)
8507 return got_error_from_errno2("realpath",
8508 optarg);
8509 break;
8510 default:
8511 usage_ref();
8512 /* NOTREACHED */
8516 argc -= optind;
8517 argv += optind;
8519 if (argc > 1)
8520 usage_ref();
8522 error = got_repo_pack_fds_open(&pack_fds);
8523 if (error != NULL)
8524 goto done;
8526 if (repo_path == NULL) {
8527 cwd = getcwd(NULL, 0);
8528 if (cwd == NULL)
8529 return got_error_from_errno("getcwd");
8530 error = got_worktree_open(&worktree, cwd);
8531 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8532 goto done;
8533 if (worktree)
8534 repo_path =
8535 strdup(got_worktree_get_repo_path(worktree));
8536 else
8537 repo_path = strdup(cwd);
8538 if (repo_path == NULL) {
8539 error = got_error_from_errno("strdup");
8540 goto done;
8544 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8545 if (error != NULL)
8546 goto done;
8548 init_curses();
8550 error = apply_unveil(got_repo_get_path(repo), NULL);
8551 if (error)
8552 goto done;
8554 error = tog_load_refs(repo, 0);
8555 if (error)
8556 goto done;
8558 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8559 if (view == NULL) {
8560 error = got_error_from_errno("view_open");
8561 goto done;
8564 error = open_ref_view(view, repo);
8565 if (error)
8566 goto done;
8568 if (worktree) {
8569 /* Release work tree lock. */
8570 got_worktree_close(worktree);
8571 worktree = NULL;
8573 error = view_loop(view);
8574 done:
8575 free(repo_path);
8576 free(cwd);
8577 if (repo) {
8578 const struct got_error *close_err = got_repo_close(repo);
8579 if (close_err)
8580 error = close_err;
8582 if (pack_fds) {
8583 const struct got_error *pack_err =
8584 got_repo_pack_fds_close(pack_fds);
8585 if (error == NULL)
8586 error = pack_err;
8588 tog_free_refs();
8589 return error;
8592 static const struct got_error*
8593 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8594 const char *str)
8596 size_t len;
8598 if (win == NULL)
8599 win = stdscr;
8601 len = strlen(str);
8602 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8604 if (focus)
8605 wstandout(win);
8606 if (mvwprintw(win, y, x, "%s", str) == ERR)
8607 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8608 if (focus)
8609 wstandend(win);
8611 return NULL;
8614 static const struct got_error *
8615 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8617 off_t *p;
8619 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8620 if (p == NULL) {
8621 free(*line_offsets);
8622 *line_offsets = NULL;
8623 return got_error_from_errno("reallocarray");
8626 *line_offsets = p;
8627 (*line_offsets)[*nlines] = off;
8628 ++(*nlines);
8629 return NULL;
8632 static const struct got_error *
8633 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8635 *ret = 0;
8637 for (;n > 0; --n, ++km) {
8638 char *t0, *t, *k;
8639 size_t len = 1;
8641 if (km->keys == NULL)
8642 continue;
8644 t = t0 = strdup(km->keys);
8645 if (t0 == NULL)
8646 return got_error_from_errno("strdup");
8648 len += strlen(t);
8649 while ((k = strsep(&t, " ")) != NULL)
8650 len += strlen(k) > 1 ? 2 : 0;
8651 free(t0);
8652 *ret = MAX(*ret, len);
8655 return NULL;
8659 * Write keymap section headers, keys, and key info in km to f.
8660 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8661 * wrap control and symbolic keys in guillemets, else use <>.
8663 static const struct got_error *
8664 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8666 int n, len = width;
8668 if (km->keys) {
8669 static const char *u8_glyph[] = {
8670 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8671 "\xe2\x80\xba" /* U+203A (utf8 >) */
8673 char *t0, *t, *k;
8674 int cs, s, first = 1;
8676 cs = got_locale_is_utf8();
8678 t = t0 = strdup(km->keys);
8679 if (t0 == NULL)
8680 return got_error_from_errno("strdup");
8682 len = strlen(km->keys);
8683 while ((k = strsep(&t, " ")) != NULL) {
8684 s = strlen(k) > 1; /* control or symbolic key */
8685 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8686 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8687 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8688 if (n < 0) {
8689 free(t0);
8690 return got_error_from_errno("fprintf");
8692 first = 0;
8693 len += s ? 2 : 0;
8694 *off += n;
8696 free(t0);
8698 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8699 if (n < 0)
8700 return got_error_from_errno("fprintf");
8701 *off += n;
8703 return NULL;
8706 static const struct got_error *
8707 format_help(struct tog_help_view_state *s)
8709 const struct got_error *err = NULL;
8710 off_t off = 0;
8711 int i, max, n, show = s->all;
8712 static const struct tog_key_map km[] = {
8713 #define KEYMAP_(info, type) { NULL, (info), type }
8714 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8715 GENERATE_HELP
8716 #undef KEYMAP_
8717 #undef KEY_
8720 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8721 if (err)
8722 return err;
8724 n = nitems(km);
8725 err = max_key_str(&max, km, n);
8726 if (err)
8727 return err;
8729 for (i = 0; i < n; ++i) {
8730 if (km[i].keys == NULL) {
8731 show = s->all;
8732 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8733 km[i].type == s->type || s->all)
8734 show = 1;
8736 if (show) {
8737 err = format_help_line(&off, s->f, &km[i], max);
8738 if (err)
8739 return err;
8740 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8741 if (err)
8742 return err;
8745 fputc('\n', s->f);
8746 ++off;
8747 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8748 return err;
8751 static const struct got_error *
8752 create_help(struct tog_help_view_state *s)
8754 FILE *f;
8755 const struct got_error *err;
8757 free(s->line_offsets);
8758 s->line_offsets = NULL;
8759 s->nlines = 0;
8761 f = got_opentemp();
8762 if (f == NULL)
8763 return got_error_from_errno("got_opentemp");
8764 s->f = f;
8766 err = format_help(s);
8767 if (err)
8768 return err;
8770 if (s->f && fflush(s->f) != 0)
8771 return got_error_from_errno("fflush");
8773 return NULL;
8776 static const struct got_error *
8777 search_start_help_view(struct tog_view *view)
8779 view->state.help.matched_line = 0;
8780 return NULL;
8783 static void
8784 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8785 size_t *nlines, int **first, int **last, int **match, int **selected)
8787 struct tog_help_view_state *s = &view->state.help;
8789 *f = s->f;
8790 *nlines = s->nlines;
8791 *line_offsets = s->line_offsets;
8792 *match = &s->matched_line;
8793 *first = &s->first_displayed_line;
8794 *last = &s->last_displayed_line;
8795 *selected = &s->selected_line;
8798 static const struct got_error *
8799 show_help_view(struct tog_view *view)
8801 struct tog_help_view_state *s = &view->state.help;
8802 const struct got_error *err;
8803 regmatch_t *regmatch = &view->regmatch;
8804 wchar_t *wline;
8805 char *line;
8806 ssize_t linelen;
8807 size_t linesz = 0;
8808 int width, nprinted = 0, rc = 0;
8809 int eos = view->nlines;
8811 if (view_is_hsplit_top(view))
8812 --eos; /* account for border */
8814 s->lineno = 0;
8815 rewind(s->f);
8816 werase(view->window);
8818 if (view->gline > s->nlines - 1)
8819 view->gline = s->nlines - 1;
8821 err = win_draw_center(view->window, 0, 0, view->ncols,
8822 view_needs_focus_indication(view),
8823 "tog help (press q to return to tog)");
8824 if (err)
8825 return err;
8826 if (eos <= 1)
8827 return NULL;
8828 waddstr(view->window, "\n\n");
8829 eos -= 2;
8831 s->eof = 0;
8832 view->maxx = 0;
8833 line = NULL;
8834 while (eos > 0 && nprinted < eos) {
8835 attr_t attr = 0;
8837 linelen = getline(&line, &linesz, s->f);
8838 if (linelen == -1) {
8839 if (!feof(s->f)) {
8840 free(line);
8841 return got_ferror(s->f, GOT_ERR_IO);
8843 s->eof = 1;
8844 break;
8846 if (++s->lineno < s->first_displayed_line)
8847 continue;
8848 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8849 continue;
8850 if (s->lineno == view->hiline)
8851 attr = A_STANDOUT;
8853 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8854 view->x ? 1 : 0);
8855 if (err) {
8856 free(line);
8857 return err;
8859 view->maxx = MAX(view->maxx, width);
8860 free(wline);
8861 wline = NULL;
8863 if (attr)
8864 wattron(view->window, attr);
8865 if (s->first_displayed_line + nprinted == s->matched_line &&
8866 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8867 err = add_matched_line(&width, line, view->ncols - 1, 0,
8868 view->window, view->x, regmatch);
8869 if (err) {
8870 free(line);
8871 return err;
8873 } else {
8874 int skip;
8876 err = format_line(&wline, &width, &skip, line,
8877 view->x, view->ncols, 0, view->x ? 1 : 0);
8878 if (err) {
8879 free(line);
8880 return err;
8882 waddwstr(view->window, &wline[skip]);
8883 free(wline);
8884 wline = NULL;
8886 if (s->lineno == view->hiline) {
8887 while (width++ < view->ncols)
8888 waddch(view->window, ' ');
8889 } else {
8890 if (width < view->ncols)
8891 waddch(view->window, '\n');
8893 if (attr)
8894 wattroff(view->window, attr);
8895 if (++nprinted == 1)
8896 s->first_displayed_line = s->lineno;
8898 free(line);
8899 if (nprinted > 0)
8900 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8901 else
8902 s->last_displayed_line = s->first_displayed_line;
8904 view_border(view);
8906 if (s->eof) {
8907 rc = waddnstr(view->window,
8908 "See the tog(1) manual page for full documentation",
8909 view->ncols - 1);
8910 if (rc == ERR)
8911 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8912 } else {
8913 wmove(view->window, view->nlines - 1, 0);
8914 wclrtoeol(view->window);
8915 wstandout(view->window);
8916 rc = waddnstr(view->window, "scroll down for more...",
8917 view->ncols - 1);
8918 if (rc == ERR)
8919 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8920 if (getcurx(view->window) < view->ncols - 6) {
8921 rc = wprintw(view->window, "[%.0f%%]",
8922 100.00 * s->last_displayed_line / s->nlines);
8923 if (rc == ERR)
8924 return got_error_msg(GOT_ERR_IO, "wprintw");
8926 wstandend(view->window);
8929 return NULL;
8932 static const struct got_error *
8933 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8935 struct tog_help_view_state *s = &view->state.help;
8936 const struct got_error *err = NULL;
8937 char *line = NULL;
8938 ssize_t linelen;
8939 size_t linesz = 0;
8940 int eos, nscroll;
8942 eos = nscroll = view->nlines;
8943 if (view_is_hsplit_top(view))
8944 --eos; /* border */
8946 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8948 switch (ch) {
8949 case '0':
8950 case '$':
8951 case KEY_RIGHT:
8952 case 'l':
8953 case KEY_LEFT:
8954 case 'h':
8955 horizontal_scroll_input(view, ch);
8956 break;
8957 case 'g':
8958 case KEY_HOME:
8959 s->first_displayed_line = 1;
8960 view->count = 0;
8961 break;
8962 case 'G':
8963 case KEY_END:
8964 view->count = 0;
8965 if (s->eof)
8966 break;
8967 s->first_displayed_line = (s->nlines - eos) + 3;
8968 s->eof = 1;
8969 break;
8970 case 'k':
8971 case KEY_UP:
8972 if (s->first_displayed_line > 1)
8973 --s->first_displayed_line;
8974 else
8975 view->count = 0;
8976 break;
8977 case CTRL('u'):
8978 case 'u':
8979 nscroll /= 2;
8980 /* FALL THROUGH */
8981 case KEY_PPAGE:
8982 case CTRL('b'):
8983 case 'b':
8984 if (s->first_displayed_line == 1) {
8985 view->count = 0;
8986 break;
8988 while (--nscroll > 0 && s->first_displayed_line > 1)
8989 s->first_displayed_line--;
8990 break;
8991 case 'j':
8992 case KEY_DOWN:
8993 case CTRL('n'):
8994 if (!s->eof)
8995 ++s->first_displayed_line;
8996 else
8997 view->count = 0;
8998 break;
8999 case CTRL('d'):
9000 case 'd':
9001 nscroll /= 2;
9002 /* FALL THROUGH */
9003 case KEY_NPAGE:
9004 case CTRL('f'):
9005 case 'f':
9006 case ' ':
9007 if (s->eof) {
9008 view->count = 0;
9009 break;
9011 while (!s->eof && --nscroll > 0) {
9012 linelen = getline(&line, &linesz, s->f);
9013 s->first_displayed_line++;
9014 if (linelen == -1) {
9015 if (feof(s->f))
9016 s->eof = 1;
9017 else
9018 err = got_ferror(s->f, GOT_ERR_IO);
9019 break;
9022 free(line);
9023 break;
9024 default:
9025 view->count = 0;
9026 break;
9029 return err;
9032 static const struct got_error *
9033 close_help_view(struct tog_view *view)
9035 struct tog_help_view_state *s = &view->state.help;
9037 free(s->line_offsets);
9038 s->line_offsets = NULL;
9039 if (fclose(s->f) == EOF)
9040 return got_error_from_errno("fclose");
9042 return NULL;
9045 static const struct got_error *
9046 reset_help_view(struct tog_view *view)
9048 struct tog_help_view_state *s = &view->state.help;
9051 if (s->f && fclose(s->f) == EOF)
9052 return got_error_from_errno("fclose");
9054 wclear(view->window);
9055 view->count = 0;
9056 view->x = 0;
9057 s->all = !s->all;
9058 s->first_displayed_line = 1;
9059 s->last_displayed_line = view->nlines;
9060 s->matched_line = 0;
9062 return create_help(s);
9065 static const struct got_error *
9066 open_help_view(struct tog_view *view, struct tog_view *parent)
9068 const struct got_error *err = NULL;
9069 struct tog_help_view_state *s = &view->state.help;
9071 s->type = (enum tog_keymap_type)parent->type;
9072 s->first_displayed_line = 1;
9073 s->last_displayed_line = view->nlines;
9074 s->selected_line = 1;
9076 view->show = show_help_view;
9077 view->input = input_help_view;
9078 view->reset = reset_help_view;
9079 view->close = close_help_view;
9080 view->search_start = search_start_help_view;
9081 view->search_setup = search_setup_help_view;
9082 view->search_next = search_next_view_match;
9084 err = create_help(s);
9085 return err;
9088 static const struct got_error *
9089 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9090 enum tog_view_type request, int y, int x)
9092 const struct got_error *err = NULL;
9094 *new_view = NULL;
9096 switch (request) {
9097 case TOG_VIEW_DIFF:
9098 if (view->type == TOG_VIEW_LOG) {
9099 struct tog_log_view_state *s = &view->state.log;
9101 err = open_diff_view_for_commit(new_view, y, x,
9102 s->selected_entry->commit, s->selected_entry->id,
9103 view, s->repo);
9104 } else
9105 return got_error_msg(GOT_ERR_NOT_IMPL,
9106 "parent/child view pair not supported");
9107 break;
9108 case TOG_VIEW_BLAME:
9109 if (view->type == TOG_VIEW_TREE) {
9110 struct tog_tree_view_state *s = &view->state.tree;
9112 err = blame_tree_entry(new_view, y, x,
9113 s->selected_entry, &s->parents, s->commit_id,
9114 s->repo);
9115 } else
9116 return got_error_msg(GOT_ERR_NOT_IMPL,
9117 "parent/child view pair not supported");
9118 break;
9119 case TOG_VIEW_LOG:
9120 if (view->type == TOG_VIEW_BLAME)
9121 err = log_annotated_line(new_view, y, x,
9122 view->state.blame.repo, view->state.blame.id_to_log);
9123 else if (view->type == TOG_VIEW_TREE)
9124 err = log_selected_tree_entry(new_view, y, x,
9125 &view->state.tree);
9126 else if (view->type == TOG_VIEW_REF)
9127 err = log_ref_entry(new_view, y, x,
9128 view->state.ref.selected_entry,
9129 view->state.ref.repo);
9130 else
9131 return got_error_msg(GOT_ERR_NOT_IMPL,
9132 "parent/child view pair not supported");
9133 break;
9134 case TOG_VIEW_TREE:
9135 if (view->type == TOG_VIEW_LOG)
9136 err = browse_commit_tree(new_view, y, x,
9137 view->state.log.selected_entry,
9138 view->state.log.in_repo_path,
9139 view->state.log.head_ref_name,
9140 view->state.log.repo);
9141 else if (view->type == TOG_VIEW_REF)
9142 err = browse_ref_tree(new_view, y, x,
9143 view->state.ref.selected_entry,
9144 view->state.ref.repo);
9145 else
9146 return got_error_msg(GOT_ERR_NOT_IMPL,
9147 "parent/child view pair not supported");
9148 break;
9149 case TOG_VIEW_REF:
9150 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9151 if (*new_view == NULL)
9152 return got_error_from_errno("view_open");
9153 if (view->type == TOG_VIEW_LOG)
9154 err = open_ref_view(*new_view, view->state.log.repo);
9155 else if (view->type == TOG_VIEW_TREE)
9156 err = open_ref_view(*new_view, view->state.tree.repo);
9157 else
9158 err = got_error_msg(GOT_ERR_NOT_IMPL,
9159 "parent/child view pair not supported");
9160 if (err)
9161 view_close(*new_view);
9162 break;
9163 case TOG_VIEW_HELP:
9164 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9165 if (*new_view == NULL)
9166 return got_error_from_errno("view_open");
9167 err = open_help_view(*new_view, view);
9168 if (err)
9169 view_close(*new_view);
9170 break;
9171 default:
9172 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9175 return err;
9179 * If view was scrolled down to move the selected line into view when opening a
9180 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9182 static void
9183 offset_selection_up(struct tog_view *view)
9185 switch (view->type) {
9186 case TOG_VIEW_BLAME: {
9187 struct tog_blame_view_state *s = &view->state.blame;
9188 if (s->first_displayed_line == 1) {
9189 s->selected_line = MAX(s->selected_line - view->offset,
9190 1);
9191 break;
9193 if (s->first_displayed_line > view->offset)
9194 s->first_displayed_line -= view->offset;
9195 else
9196 s->first_displayed_line = 1;
9197 s->selected_line += view->offset;
9198 break;
9200 case TOG_VIEW_LOG:
9201 log_scroll_up(&view->state.log, view->offset);
9202 view->state.log.selected += view->offset;
9203 break;
9204 case TOG_VIEW_REF:
9205 ref_scroll_up(&view->state.ref, view->offset);
9206 view->state.ref.selected += view->offset;
9207 break;
9208 case TOG_VIEW_TREE:
9209 tree_scroll_up(&view->state.tree, view->offset);
9210 view->state.tree.selected += view->offset;
9211 break;
9212 default:
9213 break;
9216 view->offset = 0;
9220 * If the selected line is in the section of screen covered by the bottom split,
9221 * scroll down offset lines to move it into view and index its new position.
9223 static const struct got_error *
9224 offset_selection_down(struct tog_view *view)
9226 const struct got_error *err = NULL;
9227 const struct got_error *(*scrolld)(struct tog_view *, int);
9228 int *selected = NULL;
9229 int header, offset;
9231 switch (view->type) {
9232 case TOG_VIEW_BLAME: {
9233 struct tog_blame_view_state *s = &view->state.blame;
9234 header = 3;
9235 scrolld = NULL;
9236 if (s->selected_line > view->nlines - header) {
9237 offset = abs(view->nlines - s->selected_line - header);
9238 s->first_displayed_line += offset;
9239 s->selected_line -= offset;
9240 view->offset = offset;
9242 break;
9244 case TOG_VIEW_LOG: {
9245 struct tog_log_view_state *s = &view->state.log;
9246 scrolld = &log_scroll_down;
9247 header = view_is_parent_view(view) ? 3 : 2;
9248 selected = &s->selected;
9249 break;
9251 case TOG_VIEW_REF: {
9252 struct tog_ref_view_state *s = &view->state.ref;
9253 scrolld = &ref_scroll_down;
9254 header = 3;
9255 selected = &s->selected;
9256 break;
9258 case TOG_VIEW_TREE: {
9259 struct tog_tree_view_state *s = &view->state.tree;
9260 scrolld = &tree_scroll_down;
9261 header = 5;
9262 selected = &s->selected;
9263 break;
9265 default:
9266 selected = NULL;
9267 scrolld = NULL;
9268 header = 0;
9269 break;
9272 if (selected && *selected > view->nlines - header) {
9273 offset = abs(view->nlines - *selected - header);
9274 view->offset = offset;
9275 if (scrolld && offset) {
9276 err = scrolld(view, offset);
9277 *selected -= offset;
9281 return err;
9284 static void
9285 list_commands(FILE *fp)
9287 size_t i;
9289 fprintf(fp, "commands:");
9290 for (i = 0; i < nitems(tog_commands); i++) {
9291 const struct tog_cmd *cmd = &tog_commands[i];
9292 fprintf(fp, " %s", cmd->name);
9294 fputc('\n', fp);
9297 __dead static void
9298 usage(int hflag, int status)
9300 FILE *fp = (status == 0) ? stdout : stderr;
9302 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9303 getprogname());
9304 if (hflag) {
9305 fprintf(fp, "lazy usage: %s path\n", getprogname());
9306 list_commands(fp);
9308 exit(status);
9311 static char **
9312 make_argv(int argc, ...)
9314 va_list ap;
9315 char **argv;
9316 int i;
9318 va_start(ap, argc);
9320 argv = calloc(argc, sizeof(char *));
9321 if (argv == NULL)
9322 err(1, "calloc");
9323 for (i = 0; i < argc; i++) {
9324 argv[i] = strdup(va_arg(ap, char *));
9325 if (argv[i] == NULL)
9326 err(1, "strdup");
9329 va_end(ap);
9330 return argv;
9334 * Try to convert 'tog path' into a 'tog log path' command.
9335 * The user could simply have mistyped the command rather than knowingly
9336 * provided a path. So check whether argv[0] can in fact be resolved
9337 * to a path in the HEAD commit and print a special error if not.
9338 * This hack is for mpi@ <3
9340 static const struct got_error *
9341 tog_log_with_path(int argc, char *argv[])
9343 const struct got_error *error = NULL, *close_err;
9344 const struct tog_cmd *cmd = NULL;
9345 struct got_repository *repo = NULL;
9346 struct got_worktree *worktree = NULL;
9347 struct got_object_id *commit_id = NULL, *id = NULL;
9348 struct got_commit_object *commit = NULL;
9349 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9350 char *commit_id_str = NULL, **cmd_argv = NULL;
9351 int *pack_fds = NULL;
9353 cwd = getcwd(NULL, 0);
9354 if (cwd == NULL)
9355 return got_error_from_errno("getcwd");
9357 error = got_repo_pack_fds_open(&pack_fds);
9358 if (error != NULL)
9359 goto done;
9361 error = got_worktree_open(&worktree, cwd);
9362 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9363 goto done;
9365 if (worktree)
9366 repo_path = strdup(got_worktree_get_repo_path(worktree));
9367 else
9368 repo_path = strdup(cwd);
9369 if (repo_path == NULL) {
9370 error = got_error_from_errno("strdup");
9371 goto done;
9374 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9375 if (error != NULL)
9376 goto done;
9378 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9379 repo, worktree);
9380 if (error)
9381 goto done;
9383 error = tog_load_refs(repo, 0);
9384 if (error)
9385 goto done;
9386 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9387 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9388 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9389 if (error)
9390 goto done;
9392 if (worktree) {
9393 got_worktree_close(worktree);
9394 worktree = NULL;
9397 error = got_object_open_as_commit(&commit, repo, commit_id);
9398 if (error)
9399 goto done;
9401 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9402 if (error) {
9403 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9404 goto done;
9405 fprintf(stderr, "%s: '%s' is no known command or path\n",
9406 getprogname(), argv[0]);
9407 usage(1, 1);
9408 /* not reached */
9411 error = got_object_id_str(&commit_id_str, commit_id);
9412 if (error)
9413 goto done;
9415 cmd = &tog_commands[0]; /* log */
9416 argc = 4;
9417 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9418 error = cmd->cmd_main(argc, cmd_argv);
9419 done:
9420 if (repo) {
9421 close_err = got_repo_close(repo);
9422 if (error == NULL)
9423 error = close_err;
9425 if (commit)
9426 got_object_commit_close(commit);
9427 if (worktree)
9428 got_worktree_close(worktree);
9429 if (pack_fds) {
9430 const struct got_error *pack_err =
9431 got_repo_pack_fds_close(pack_fds);
9432 if (error == NULL)
9433 error = pack_err;
9435 free(id);
9436 free(commit_id_str);
9437 free(commit_id);
9438 free(cwd);
9439 free(repo_path);
9440 free(in_repo_path);
9441 if (cmd_argv) {
9442 int i;
9443 for (i = 0; i < argc; i++)
9444 free(cmd_argv[i]);
9445 free(cmd_argv);
9447 tog_free_refs();
9448 return error;
9451 int
9452 main(int argc, char *argv[])
9454 const struct got_error *error = NULL;
9455 const struct tog_cmd *cmd = NULL;
9456 int ch, hflag = 0, Vflag = 0;
9457 char **cmd_argv = NULL;
9458 static const struct option longopts[] = {
9459 { "version", no_argument, NULL, 'V' },
9460 { NULL, 0, NULL, 0}
9462 char *diff_algo_str = NULL;
9464 setlocale(LC_CTYPE, "");
9466 #ifndef PROFILE
9467 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9468 NULL) == -1)
9469 err(1, "pledge");
9470 #endif
9472 if (!isatty(STDIN_FILENO))
9473 errx(1, "standard input is not a tty");
9475 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9476 switch (ch) {
9477 case 'h':
9478 hflag = 1;
9479 break;
9480 case 'V':
9481 Vflag = 1;
9482 break;
9483 default:
9484 usage(hflag, 1);
9485 /* NOTREACHED */
9489 argc -= optind;
9490 argv += optind;
9491 optind = 1;
9492 optreset = 1;
9494 if (Vflag) {
9495 got_version_print_str();
9496 return 0;
9499 if (argc == 0) {
9500 if (hflag)
9501 usage(hflag, 0);
9502 /* Build an argument vector which runs a default command. */
9503 cmd = &tog_commands[0];
9504 argc = 1;
9505 cmd_argv = make_argv(argc, cmd->name);
9506 } else {
9507 size_t i;
9509 /* Did the user specify a command? */
9510 for (i = 0; i < nitems(tog_commands); i++) {
9511 if (strncmp(tog_commands[i].name, argv[0],
9512 strlen(argv[0])) == 0) {
9513 cmd = &tog_commands[i];
9514 break;
9519 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9520 if (diff_algo_str) {
9521 if (strcasecmp(diff_algo_str, "patience") == 0)
9522 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9523 if (strcasecmp(diff_algo_str, "myers") == 0)
9524 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9527 if (cmd == NULL) {
9528 if (argc != 1)
9529 usage(0, 1);
9530 /* No command specified; try log with a path */
9531 error = tog_log_with_path(argc, argv);
9532 } else {
9533 if (hflag)
9534 cmd->cmd_usage();
9535 else
9536 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9539 endwin();
9540 if (cmd_argv) {
9541 int i;
9542 for (i = 0; i < argc; i++)
9543 free(cmd_argv[i]);
9544 free(cmd_argv);
9547 if (error && error->code != GOT_ERR_CANCELLED &&
9548 error->code != GOT_ERR_EOF &&
9549 error->code != GOT_ERR_PRIVSEP_EXIT &&
9550 error->code != GOT_ERR_PRIVSEP_PIPE &&
9551 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9552 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9553 return 0;