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 #if defined(__FreeBSD__) || defined(__APPLE__)
24 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
25 #endif
26 #include <curses.h>
27 #include <panel.h>
28 #include <locale.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_compat.h"
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 TOG_VIEW_HELP
112 };
114 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
115 enum tog_keymap_type {
116 TOG_KEYMAP_KEYS = -2,
117 TOG_KEYMAP_GLOBAL,
118 TOG_KEYMAP_DIFF,
119 TOG_KEYMAP_LOG,
120 TOG_KEYMAP_BLAME,
121 TOG_KEYMAP_TREE,
122 TOG_KEYMAP_REF,
123 TOG_KEYMAP_HELP
124 };
126 enum tog_view_mode {
127 TOG_VIEW_SPLIT_NONE,
128 TOG_VIEW_SPLIT_VERT,
129 TOG_VIEW_SPLIT_HRZN
130 };
132 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
134 #define TOG_EOF_STRING "(END)"
136 struct commit_queue_entry {
137 TAILQ_ENTRY(commit_queue_entry) entry;
138 struct got_object_id *id;
139 struct got_commit_object *commit;
140 int idx;
141 };
142 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
143 struct commit_queue {
144 int ncommits;
145 struct commit_queue_head head;
146 };
148 struct tog_color {
149 STAILQ_ENTRY(tog_color) entry;
150 regex_t regex;
151 short colorpair;
152 };
153 STAILQ_HEAD(tog_colors, tog_color);
155 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
156 static struct got_reflist_object_id_map *tog_refs_idmap;
157 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
159 static const struct got_error *
160 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
161 struct got_reference* re2)
163 const char *name1 = got_ref_get_name(re1);
164 const char *name2 = got_ref_get_name(re2);
165 int isbackup1, isbackup2;
167 /* Sort backup refs towards the bottom of the list. */
168 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
169 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
170 if (!isbackup1 && isbackup2) {
171 *cmp = -1;
172 return NULL;
173 } else if (isbackup1 && !isbackup2) {
174 *cmp = 1;
175 return NULL;
178 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
179 return NULL;
182 static const struct got_error *
183 tog_load_refs(struct got_repository *repo, int sort_by_date)
185 const struct got_error *err;
187 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
188 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
189 repo);
190 if (err)
191 return err;
193 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
194 repo);
197 static void
198 tog_free_refs(void)
200 if (tog_refs_idmap) {
201 got_reflist_object_id_map_free(tog_refs_idmap);
202 tog_refs_idmap = NULL;
204 got_ref_list_free(&tog_refs);
207 static const struct got_error *
208 add_color(struct tog_colors *colors, const char *pattern,
209 int idx, short color)
211 const struct got_error *err = NULL;
212 struct tog_color *tc;
213 int regerr = 0;
215 if (idx < 1 || idx > COLOR_PAIRS - 1)
216 return NULL;
218 init_pair(idx, color, -1);
220 tc = calloc(1, sizeof(*tc));
221 if (tc == NULL)
222 return got_error_from_errno("calloc");
223 regerr = regcomp(&tc->regex, pattern,
224 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
225 if (regerr) {
226 static char regerr_msg[512];
227 static char err_msg[512];
228 regerror(regerr, &tc->regex, regerr_msg,
229 sizeof(regerr_msg));
230 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
231 regerr_msg);
232 err = got_error_msg(GOT_ERR_REGEX, err_msg);
233 free(tc);
234 return err;
236 tc->colorpair = idx;
237 STAILQ_INSERT_HEAD(colors, tc, entry);
238 return NULL;
241 static void
242 free_colors(struct tog_colors *colors)
244 struct tog_color *tc;
246 while (!STAILQ_EMPTY(colors)) {
247 tc = STAILQ_FIRST(colors);
248 STAILQ_REMOVE_HEAD(colors, entry);
249 regfree(&tc->regex);
250 free(tc);
254 static struct tog_color *
255 get_color(struct tog_colors *colors, int colorpair)
257 struct tog_color *tc = NULL;
259 STAILQ_FOREACH(tc, colors, entry) {
260 if (tc->colorpair == colorpair)
261 return tc;
264 return NULL;
267 static int
268 default_color_value(const char *envvar)
270 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
271 return COLOR_MAGENTA;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
273 return COLOR_CYAN;
274 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
275 return COLOR_YELLOW;
276 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
277 return COLOR_GREEN;
278 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
279 return COLOR_MAGENTA;
280 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
283 return COLOR_CYAN;
284 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
285 return COLOR_GREEN;
286 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
287 return COLOR_GREEN;
288 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
289 return COLOR_CYAN;
290 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
291 return COLOR_YELLOW;
292 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
293 return COLOR_GREEN;
294 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
295 return COLOR_MAGENTA;
296 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
297 return COLOR_YELLOW;
298 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
299 return COLOR_CYAN;
301 return -1;
304 static int
305 get_color_value(const char *envvar)
307 const char *val = getenv(envvar);
309 if (val == NULL)
310 return default_color_value(envvar);
312 if (strcasecmp(val, "black") == 0)
313 return COLOR_BLACK;
314 if (strcasecmp(val, "red") == 0)
315 return COLOR_RED;
316 if (strcasecmp(val, "green") == 0)
317 return COLOR_GREEN;
318 if (strcasecmp(val, "yellow") == 0)
319 return COLOR_YELLOW;
320 if (strcasecmp(val, "blue") == 0)
321 return COLOR_BLUE;
322 if (strcasecmp(val, "magenta") == 0)
323 return COLOR_MAGENTA;
324 if (strcasecmp(val, "cyan") == 0)
325 return COLOR_CYAN;
326 if (strcasecmp(val, "white") == 0)
327 return COLOR_WHITE;
328 if (strcasecmp(val, "default") == 0)
329 return -1;
331 return default_color_value(envvar);
334 struct tog_diff_view_state {
335 struct got_object_id *id1, *id2;
336 const char *label1, *label2;
337 FILE *f, *f1, *f2;
338 int fd1, fd2;
339 int lineno;
340 int first_displayed_line;
341 int last_displayed_line;
342 int eof;
343 int diff_context;
344 int ignore_whitespace;
345 int force_text_diff;
346 struct got_repository *repo;
347 struct got_diff_line *lines;
348 size_t nlines;
349 int matched_line;
350 int selected_line;
352 /* passed from log or blame view; may be NULL */
353 struct tog_view *parent_view;
354 };
356 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
357 static volatile sig_atomic_t tog_thread_error;
359 struct tog_log_thread_args {
360 pthread_cond_t need_commits;
361 pthread_cond_t commit_loaded;
362 int commits_needed;
363 int load_all;
364 struct got_commit_graph *graph;
365 struct commit_queue *real_commits;
366 const char *in_repo_path;
367 struct got_object_id *start_id;
368 struct got_repository *repo;
369 int *pack_fds;
370 int log_complete;
371 sig_atomic_t *quit;
372 struct commit_queue_entry **first_displayed_entry;
373 struct commit_queue_entry **selected_entry;
374 int *searching;
375 int *search_next_done;
376 regex_t *regex;
377 int *limiting;
378 int limit_match;
379 regex_t *limit_regex;
380 struct commit_queue *limit_commits;
381 };
383 struct tog_log_view_state {
384 struct commit_queue *commits;
385 struct commit_queue_entry *first_displayed_entry;
386 struct commit_queue_entry *last_displayed_entry;
387 struct commit_queue_entry *selected_entry;
388 struct commit_queue real_commits;
389 int selected;
390 char *in_repo_path;
391 char *head_ref_name;
392 int log_branches;
393 struct got_repository *repo;
394 struct got_object_id *start_id;
395 sig_atomic_t quit;
396 pthread_t thread;
397 struct tog_log_thread_args thread_args;
398 struct commit_queue_entry *matched_entry;
399 struct commit_queue_entry *search_entry;
400 struct tog_colors colors;
401 int use_committer;
402 int limit_view;
403 regex_t limit_regex;
404 struct commit_queue limit_commits;
405 };
407 #define TOG_COLOR_DIFF_MINUS 1
408 #define TOG_COLOR_DIFF_PLUS 2
409 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
410 #define TOG_COLOR_DIFF_META 4
411 #define TOG_COLOR_TREE_SUBMODULE 5
412 #define TOG_COLOR_TREE_SYMLINK 6
413 #define TOG_COLOR_TREE_DIRECTORY 7
414 #define TOG_COLOR_TREE_EXECUTABLE 8
415 #define TOG_COLOR_COMMIT 9
416 #define TOG_COLOR_AUTHOR 10
417 #define TOG_COLOR_DATE 11
418 #define TOG_COLOR_REFS_HEADS 12
419 #define TOG_COLOR_REFS_TAGS 13
420 #define TOG_COLOR_REFS_REMOTES 14
421 #define TOG_COLOR_REFS_BACKUP 15
423 struct tog_blame_cb_args {
424 struct tog_blame_line *lines; /* one per line */
425 int nlines;
427 struct tog_view *view;
428 struct got_object_id *commit_id;
429 int *quit;
430 };
432 struct tog_blame_thread_args {
433 const char *path;
434 struct got_repository *repo;
435 struct tog_blame_cb_args *cb_args;
436 int *complete;
437 got_cancel_cb cancel_cb;
438 void *cancel_arg;
439 };
441 struct tog_blame {
442 FILE *f;
443 off_t filesize;
444 struct tog_blame_line *lines;
445 int nlines;
446 off_t *line_offsets;
447 pthread_t thread;
448 struct tog_blame_thread_args thread_args;
449 struct tog_blame_cb_args cb_args;
450 const char *path;
451 int *pack_fds;
452 };
454 struct tog_blame_view_state {
455 int first_displayed_line;
456 int last_displayed_line;
457 int selected_line;
458 int last_diffed_line;
459 int blame_complete;
460 int eof;
461 int done;
462 struct got_object_id_queue blamed_commits;
463 struct got_object_qid *blamed_commit;
464 char *path;
465 struct got_repository *repo;
466 struct got_object_id *commit_id;
467 struct got_object_id *id_to_log;
468 struct tog_blame blame;
469 int matched_line;
470 struct tog_colors colors;
471 };
473 struct tog_parent_tree {
474 TAILQ_ENTRY(tog_parent_tree) entry;
475 struct got_tree_object *tree;
476 struct got_tree_entry *first_displayed_entry;
477 struct got_tree_entry *selected_entry;
478 int selected;
479 };
481 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
483 struct tog_tree_view_state {
484 char *tree_label;
485 struct got_object_id *commit_id;/* commit which this tree belongs to */
486 struct got_tree_object *root; /* the commit's root tree entry */
487 struct got_tree_object *tree; /* currently displayed (sub-)tree */
488 struct got_tree_entry *first_displayed_entry;
489 struct got_tree_entry *last_displayed_entry;
490 struct got_tree_entry *selected_entry;
491 int ndisplayed, selected, show_ids;
492 struct tog_parent_trees parents; /* parent trees of current sub-tree */
493 char *head_ref_name;
494 struct got_repository *repo;
495 struct got_tree_entry *matched_entry;
496 struct tog_colors colors;
497 };
499 struct tog_reflist_entry {
500 TAILQ_ENTRY(tog_reflist_entry) entry;
501 struct got_reference *ref;
502 int idx;
503 };
505 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
507 struct tog_ref_view_state {
508 struct tog_reflist_head refs;
509 struct tog_reflist_entry *first_displayed_entry;
510 struct tog_reflist_entry *last_displayed_entry;
511 struct tog_reflist_entry *selected_entry;
512 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
513 struct got_repository *repo;
514 struct tog_reflist_entry *matched_entry;
515 struct tog_colors colors;
516 };
518 struct tog_help_view_state {
519 FILE *f;
520 off_t *line_offsets;
521 size_t nlines;
522 int lineno;
523 int first_displayed_line;
524 int last_displayed_line;
525 int eof;
526 int matched_line;
527 int selected_line;
528 int all;
529 enum tog_keymap_type type;
530 };
532 #define GENERATE_HELP \
533 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
534 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
535 KEY_("k C-p Up", "Move cursor or page up one line"), \
536 KEY_("j C-n Down", "Move cursor or page down one line"), \
537 KEY_("C-b b PgUp", "Scroll the view up one page"), \
538 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
539 KEY_("C-u u", "Scroll the view up one half page"), \
540 KEY_("C-d d", "Scroll the view down one half page"), \
541 KEY_("g", "Go to line N (default: first line)"), \
542 KEY_("Home =", "Go to the first line"), \
543 KEY_("G", "Go to line N (default: last line)"), \
544 KEY_("End *", "Go to the last line"), \
545 KEY_("l Right", "Scroll the view right"), \
546 KEY_("h Left", "Scroll the view left"), \
547 KEY_("$", "Scroll view to the rightmost position"), \
548 KEY_("0", "Scroll view to the leftmost position"), \
549 KEY_("-", "Decrease size of the focussed split"), \
550 KEY_("+", "Increase size of the focussed split"), \
551 KEY_("Tab", "Switch focus between views"), \
552 KEY_("F", "Toggle fullscreen mode"), \
553 KEY_("/", "Open prompt to enter search term"), \
554 KEY_("n", "Find next line/token matching the current search term"), \
555 KEY_("N", "Find previous line/token matching the current search term"),\
556 KEY_("q", "Quit the focussed view; Quit help screen"), \
557 KEY_("Q", "Quit tog"), \
559 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
560 KEY_("< ,", "Move cursor up one commit"), \
561 KEY_("> .", "Move cursor down one commit"), \
562 KEY_("Enter", "Open diff view of the selected commit"), \
563 KEY_("B", "Reload the log view and toggle display of merged commits"), \
564 KEY_("R", "Open ref view of all repository references"), \
565 KEY_("T", "Display tree view of the repository from the selected" \
566 " commit"), \
567 KEY_("@", "Toggle between displaying author and committer name"), \
568 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
569 KEY_("C-g Backspace", "Cancel current search or log operation"), \
570 KEY_("C-l", "Reload the log view with new commits in the repository"), \
572 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
573 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
574 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
575 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
576 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
577 " data"), \
578 KEY_("(", "Go to the previous file in the diff"), \
579 KEY_(")", "Go to the next file in the diff"), \
580 KEY_("{", "Go to the previous hunk in the diff"), \
581 KEY_("}", "Go to the next hunk in the diff"), \
582 KEY_("[", "Decrease the number of context lines"), \
583 KEY_("]", "Increase the number of context lines"), \
584 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
586 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
587 KEY_("Enter", "Display diff view of the selected line's commit"), \
588 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
589 KEY_("L", "Open log view for the currently selected annotated line"), \
590 KEY_("C", "Reload view with the previously blamed commit"), \
591 KEY_("c", "Reload view with the version of the file found in the" \
592 " selected line's commit"), \
593 KEY_("p", "Reload view with the version of the file found in the" \
594 " selected line's parent commit"), \
596 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
597 KEY_("Enter", "Enter selected directory or open blame view of the" \
598 " selected file"), \
599 KEY_("L", "Open log view for the selected entry"), \
600 KEY_("R", "Open ref view of all repository references"), \
601 KEY_("i", "Show object IDs for all tree entries"), \
602 KEY_("Backspace", "Return to the parent directory"), \
604 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
605 KEY_("Enter", "Display log view of the selected reference"), \
606 KEY_("T", "Display tree view of the selected reference"), \
607 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
608 KEY_("m", "Toggle display of last modified date for each reference"), \
609 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
610 KEY_("C-l", "Reload view with all repository references")
612 struct tog_key_map {
613 const char *keys;
614 const char *info;
615 enum tog_keymap_type type;
616 };
618 /*
619 * We implement two types of views: parent views and child views.
621 * The 'Tab' key switches focus between a parent view and its child view.
622 * Child views are shown side-by-side to their parent view, provided
623 * there is enough screen estate.
625 * When a new view is opened from within a parent view, this new view
626 * becomes a child view of the parent view, replacing any existing child.
628 * When a new view is opened from within a child view, this new view
629 * becomes a parent view which will obscure the views below until the
630 * user quits the new parent view by typing 'q'.
632 * This list of views contains parent views only.
633 * Child views are only pointed to by their parent view.
634 */
635 TAILQ_HEAD(tog_view_list_head, tog_view);
637 struct tog_view {
638 TAILQ_ENTRY(tog_view) entry;
639 WINDOW *window;
640 PANEL *panel;
641 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
642 int resized_y, resized_x; /* begin_y/x based on user resizing */
643 int maxx, x; /* max column and current start column */
644 int lines, cols; /* copies of LINES and COLS */
645 int nscrolled, offset; /* lines scrolled and hsplit line offset */
646 int gline, hiline; /* navigate to and highlight this nG line */
647 int ch, count; /* current keymap and count prefix */
648 int resized; /* set when in a resize event */
649 int focussed; /* Only set on one parent or child view at a time. */
650 int dying;
651 struct tog_view *parent;
652 struct tog_view *child;
654 /*
655 * This flag is initially set on parent views when a new child view
656 * is created. It gets toggled when the 'Tab' key switches focus
657 * between parent and child.
658 * The flag indicates whether focus should be passed on to our child
659 * view if this parent view gets picked for focus after another parent
660 * view was closed. This prevents child views from losing focus in such
661 * situations.
662 */
663 int focus_child;
665 enum tog_view_mode mode;
666 /* type-specific state */
667 enum tog_view_type type;
668 union {
669 struct tog_diff_view_state diff;
670 struct tog_log_view_state log;
671 struct tog_blame_view_state blame;
672 struct tog_tree_view_state tree;
673 struct tog_ref_view_state ref;
674 struct tog_help_view_state help;
675 } state;
677 const struct got_error *(*show)(struct tog_view *);
678 const struct got_error *(*input)(struct tog_view **,
679 struct tog_view *, int);
680 const struct got_error *(*reset)(struct tog_view *);
681 const struct got_error *(*resize)(struct tog_view *, int);
682 const struct got_error *(*close)(struct tog_view *);
684 const struct got_error *(*search_start)(struct tog_view *);
685 const struct got_error *(*search_next)(struct tog_view *);
686 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
687 int **, int **, int **, int **);
688 int search_started;
689 int searching;
690 #define TOG_SEARCH_FORWARD 1
691 #define TOG_SEARCH_BACKWARD 2
692 int search_next_done;
693 #define TOG_SEARCH_HAVE_MORE 1
694 #define TOG_SEARCH_NO_MORE 2
695 #define TOG_SEARCH_HAVE_NONE 3
696 regex_t regex;
697 regmatch_t regmatch;
698 const char *action;
699 };
701 static const struct got_error *open_diff_view(struct tog_view *,
702 struct got_object_id *, struct got_object_id *,
703 const char *, const char *, int, int, int, struct tog_view *,
704 struct got_repository *);
705 static const struct got_error *show_diff_view(struct tog_view *);
706 static const struct got_error *input_diff_view(struct tog_view **,
707 struct tog_view *, int);
708 static const struct got_error *reset_diff_view(struct tog_view *);
709 static const struct got_error* close_diff_view(struct tog_view *);
710 static const struct got_error *search_start_diff_view(struct tog_view *);
711 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
712 size_t *, int **, int **, int **, int **);
713 static const struct got_error *search_next_view_match(struct tog_view *);
715 static const struct got_error *open_log_view(struct tog_view *,
716 struct got_object_id *, struct got_repository *,
717 const char *, const char *, int);
718 static const struct got_error * show_log_view(struct tog_view *);
719 static const struct got_error *input_log_view(struct tog_view **,
720 struct tog_view *, int);
721 static const struct got_error *resize_log_view(struct tog_view *, int);
722 static const struct got_error *close_log_view(struct tog_view *);
723 static const struct got_error *search_start_log_view(struct tog_view *);
724 static const struct got_error *search_next_log_view(struct tog_view *);
726 static const struct got_error *open_blame_view(struct tog_view *, char *,
727 struct got_object_id *, struct got_repository *);
728 static const struct got_error *show_blame_view(struct tog_view *);
729 static const struct got_error *input_blame_view(struct tog_view **,
730 struct tog_view *, int);
731 static const struct got_error *reset_blame_view(struct tog_view *);
732 static const struct got_error *close_blame_view(struct tog_view *);
733 static const struct got_error *search_start_blame_view(struct tog_view *);
734 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
735 size_t *, int **, int **, int **, int **);
737 static const struct got_error *open_tree_view(struct tog_view *,
738 struct got_object_id *, const char *, struct got_repository *);
739 static const struct got_error *show_tree_view(struct tog_view *);
740 static const struct got_error *input_tree_view(struct tog_view **,
741 struct tog_view *, int);
742 static const struct got_error *close_tree_view(struct tog_view *);
743 static const struct got_error *search_start_tree_view(struct tog_view *);
744 static const struct got_error *search_next_tree_view(struct tog_view *);
746 static const struct got_error *open_ref_view(struct tog_view *,
747 struct got_repository *);
748 static const struct got_error *show_ref_view(struct tog_view *);
749 static const struct got_error *input_ref_view(struct tog_view **,
750 struct tog_view *, int);
751 static const struct got_error *close_ref_view(struct tog_view *);
752 static const struct got_error *search_start_ref_view(struct tog_view *);
753 static const struct got_error *search_next_ref_view(struct tog_view *);
755 static const struct got_error *open_help_view(struct tog_view *,
756 struct tog_view *);
757 static const struct got_error *show_help_view(struct tog_view *);
758 static const struct got_error *input_help_view(struct tog_view **,
759 struct tog_view *, int);
760 static const struct got_error *reset_help_view(struct tog_view *);
761 static const struct got_error* close_help_view(struct tog_view *);
762 static const struct got_error *search_start_help_view(struct tog_view *);
763 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
764 size_t *, int **, int **, int **, int **);
766 static volatile sig_atomic_t tog_sigwinch_received;
767 static volatile sig_atomic_t tog_sigpipe_received;
768 static volatile sig_atomic_t tog_sigcont_received;
769 static volatile sig_atomic_t tog_sigint_received;
770 static volatile sig_atomic_t tog_sigterm_received;
772 static void
773 tog_sigwinch(int signo)
775 tog_sigwinch_received = 1;
778 static void
779 tog_sigpipe(int signo)
781 tog_sigpipe_received = 1;
784 static void
785 tog_sigcont(int signo)
787 tog_sigcont_received = 1;
790 static void
791 tog_sigint(int signo)
793 tog_sigint_received = 1;
796 static void
797 tog_sigterm(int signo)
799 tog_sigterm_received = 1;
802 static int
803 tog_fatal_signal_received(void)
805 return (tog_sigpipe_received ||
806 tog_sigint_received || tog_sigterm_received);
809 static const struct got_error *
810 view_close(struct tog_view *view)
812 const struct got_error *err = NULL, *child_err = NULL;
814 if (view->child) {
815 child_err = view_close(view->child);
816 view->child = NULL;
818 if (view->close)
819 err = view->close(view);
820 if (view->panel)
821 del_panel(view->panel);
822 if (view->window)
823 delwin(view->window);
824 free(view);
825 return err ? err : child_err;
828 static struct tog_view *
829 view_open(int nlines, int ncols, int begin_y, int begin_x,
830 enum tog_view_type type)
832 struct tog_view *view = calloc(1, sizeof(*view));
834 if (view == NULL)
835 return NULL;
837 view->type = type;
838 view->lines = LINES;
839 view->cols = COLS;
840 view->nlines = nlines ? nlines : LINES - begin_y;
841 view->ncols = ncols ? ncols : COLS - begin_x;
842 view->begin_y = begin_y;
843 view->begin_x = begin_x;
844 view->window = newwin(nlines, ncols, begin_y, begin_x);
845 if (view->window == NULL) {
846 view_close(view);
847 return NULL;
849 view->panel = new_panel(view->window);
850 if (view->panel == NULL ||
851 set_panel_userptr(view->panel, view) != OK) {
852 view_close(view);
853 return NULL;
856 keypad(view->window, TRUE);
857 return view;
860 static int
861 view_split_begin_x(int begin_x)
863 if (begin_x > 0 || COLS < 120)
864 return 0;
865 return (COLS - MAX(COLS / 2, 80));
868 /* XXX Stub till we decide what to do. */
869 static int
870 view_split_begin_y(int lines)
872 return lines * HSPLIT_SCALE;
875 static const struct got_error *view_resize(struct tog_view *);
877 static const struct got_error *
878 view_splitscreen(struct tog_view *view)
880 const struct got_error *err = NULL;
882 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
883 if (view->resized_y && view->resized_y < view->lines)
884 view->begin_y = view->resized_y;
885 else
886 view->begin_y = view_split_begin_y(view->nlines);
887 view->begin_x = 0;
888 } else if (!view->resized) {
889 if (view->resized_x && view->resized_x < view->cols - 1 &&
890 view->cols > 119)
891 view->begin_x = view->resized_x;
892 else
893 view->begin_x = view_split_begin_x(0);
894 view->begin_y = 0;
896 view->nlines = LINES - view->begin_y;
897 view->ncols = COLS - view->begin_x;
898 view->lines = LINES;
899 view->cols = COLS;
900 err = view_resize(view);
901 if (err)
902 return err;
904 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
905 view->parent->nlines = view->begin_y;
907 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
908 return got_error_from_errno("mvwin");
910 return NULL;
913 static const struct got_error *
914 view_fullscreen(struct tog_view *view)
916 const struct got_error *err = NULL;
918 view->begin_x = 0;
919 view->begin_y = view->resized ? view->begin_y : 0;
920 view->nlines = view->resized ? view->nlines : LINES;
921 view->ncols = COLS;
922 view->lines = LINES;
923 view->cols = COLS;
924 err = view_resize(view);
925 if (err)
926 return err;
928 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
929 return got_error_from_errno("mvwin");
931 return NULL;
934 static int
935 view_is_parent_view(struct tog_view *view)
937 return view->parent == NULL;
940 static int
941 view_is_splitscreen(struct tog_view *view)
943 return view->begin_x > 0 || view->begin_y > 0;
946 static int
947 view_is_fullscreen(struct tog_view *view)
949 return view->nlines == LINES && view->ncols == COLS;
952 static int
953 view_is_hsplit_top(struct tog_view *view)
955 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
956 view_is_splitscreen(view->child);
959 static void
960 view_border(struct tog_view *view)
962 PANEL *panel;
963 const struct tog_view *view_above;
965 if (view->parent)
966 return view_border(view->parent);
968 panel = panel_above(view->panel);
969 if (panel == NULL)
970 return;
972 view_above = panel_userptr(panel);
973 if (view->mode == TOG_VIEW_SPLIT_HRZN)
974 mvwhline(view->window, view_above->begin_y - 1,
975 view->begin_x, got_locale_is_utf8() ?
976 ACS_HLINE : '-', view->ncols);
977 else
978 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
979 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
982 static const struct got_error *view_init_hsplit(struct tog_view *, int);
983 static const struct got_error *request_log_commits(struct tog_view *);
984 static const struct got_error *offset_selection_down(struct tog_view *);
985 static void offset_selection_up(struct tog_view *);
986 static void view_get_split(struct tog_view *, int *, int *);
988 static const struct got_error *
989 view_resize(struct tog_view *view)
991 const struct got_error *err = NULL;
992 int dif, nlines, ncols;
994 dif = LINES - view->lines; /* line difference */
996 if (view->lines > LINES)
997 nlines = view->nlines - (view->lines - LINES);
998 else
999 nlines = view->nlines + (LINES - view->lines);
1000 if (view->cols > COLS)
1001 ncols = view->ncols - (view->cols - COLS);
1002 else
1003 ncols = view->ncols + (COLS - view->cols);
1005 if (view->child) {
1006 int hs = view->child->begin_y;
1008 if (!view_is_fullscreen(view))
1009 view->child->begin_x = view_split_begin_x(view->begin_x);
1010 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1011 view->child->begin_x == 0) {
1012 ncols = COLS;
1014 view_fullscreen(view->child);
1015 if (view->child->focussed)
1016 show_panel(view->child->panel);
1017 else
1018 show_panel(view->panel);
1019 } else {
1020 ncols = view->child->begin_x;
1022 view_splitscreen(view->child);
1023 show_panel(view->child->panel);
1026 * XXX This is ugly and needs to be moved into the above
1027 * logic but "works" for now and my attempts at moving it
1028 * break either 'tab' or 'F' key maps in horizontal splits.
1030 if (hs) {
1031 err = view_splitscreen(view->child);
1032 if (err)
1033 return err;
1034 if (dif < 0) { /* top split decreased */
1035 err = offset_selection_down(view);
1036 if (err)
1037 return err;
1039 view_border(view);
1040 update_panels();
1041 doupdate();
1042 show_panel(view->child->panel);
1043 nlines = view->nlines;
1045 } else if (view->parent == NULL)
1046 ncols = COLS;
1048 if (view->resize && dif > 0) {
1049 err = view->resize(view, dif);
1050 if (err)
1051 return err;
1054 if (wresize(view->window, nlines, ncols) == ERR)
1055 return got_error_from_errno("wresize");
1056 if (replace_panel(view->panel, view->window) == ERR)
1057 return got_error_from_errno("replace_panel");
1058 wclear(view->window);
1060 view->nlines = nlines;
1061 view->ncols = ncols;
1062 view->lines = LINES;
1063 view->cols = COLS;
1065 return NULL;
1068 static const struct got_error *
1069 resize_log_view(struct tog_view *view, int increase)
1071 struct tog_log_view_state *s = &view->state.log;
1072 const struct got_error *err = NULL;
1073 int n = 0;
1075 if (s->selected_entry)
1076 n = s->selected_entry->idx + view->lines - s->selected;
1079 * Request commits to account for the increased
1080 * height so we have enough to populate the view.
1082 if (s->commits->ncommits < n) {
1083 view->nscrolled = n - s->commits->ncommits + increase + 1;
1084 err = request_log_commits(view);
1087 return err;
1090 static void
1091 view_adjust_offset(struct tog_view *view, int n)
1093 if (n == 0)
1094 return;
1096 if (view->parent && view->parent->offset) {
1097 if (view->parent->offset + n >= 0)
1098 view->parent->offset += n;
1099 else
1100 view->parent->offset = 0;
1101 } else if (view->offset) {
1102 if (view->offset - n >= 0)
1103 view->offset -= n;
1104 else
1105 view->offset = 0;
1109 static const struct got_error *
1110 view_resize_split(struct tog_view *view, int resize)
1112 const struct got_error *err = NULL;
1113 struct tog_view *v = NULL;
1115 if (view->parent)
1116 v = view->parent;
1117 else
1118 v = view;
1120 if (!v->child || !view_is_splitscreen(v->child))
1121 return NULL;
1123 v->resized = v->child->resized = resize; /* lock for resize event */
1125 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1126 if (v->child->resized_y)
1127 v->child->begin_y = v->child->resized_y;
1128 if (view->parent)
1129 v->child->begin_y -= resize;
1130 else
1131 v->child->begin_y += resize;
1132 if (v->child->begin_y < 3) {
1133 view->count = 0;
1134 v->child->begin_y = 3;
1135 } else if (v->child->begin_y > LINES - 1) {
1136 view->count = 0;
1137 v->child->begin_y = LINES - 1;
1139 v->ncols = COLS;
1140 v->child->ncols = COLS;
1141 view_adjust_offset(view, resize);
1142 err = view_init_hsplit(v, v->child->begin_y);
1143 if (err)
1144 return err;
1145 v->child->resized_y = v->child->begin_y;
1146 } else {
1147 if (v->child->resized_x)
1148 v->child->begin_x = v->child->resized_x;
1149 if (view->parent)
1150 v->child->begin_x -= resize;
1151 else
1152 v->child->begin_x += resize;
1153 if (v->child->begin_x < 11) {
1154 view->count = 0;
1155 v->child->begin_x = 11;
1156 } else if (v->child->begin_x > COLS - 1) {
1157 view->count = 0;
1158 v->child->begin_x = COLS - 1;
1160 v->child->resized_x = v->child->begin_x;
1163 v->child->mode = v->mode;
1164 v->child->nlines = v->lines - v->child->begin_y;
1165 v->child->ncols = v->cols - v->child->begin_x;
1166 v->focus_child = 1;
1168 err = view_fullscreen(v);
1169 if (err)
1170 return err;
1171 err = view_splitscreen(v->child);
1172 if (err)
1173 return err;
1175 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1176 err = offset_selection_down(v->child);
1177 if (err)
1178 return err;
1181 if (v->resize)
1182 err = v->resize(v, 0);
1183 else if (v->child->resize)
1184 err = v->child->resize(v->child, 0);
1186 v->resized = v->child->resized = 0;
1188 return err;
1191 static void
1192 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1194 struct tog_view *v = src->child ? src->child : src;
1196 dst->resized_x = v->resized_x;
1197 dst->resized_y = v->resized_y;
1200 static const struct got_error *
1201 view_close_child(struct tog_view *view)
1203 const struct got_error *err = NULL;
1205 if (view->child == NULL)
1206 return NULL;
1208 err = view_close(view->child);
1209 view->child = NULL;
1210 return err;
1213 static const struct got_error *
1214 view_set_child(struct tog_view *view, struct tog_view *child)
1216 const struct got_error *err = NULL;
1218 view->child = child;
1219 child->parent = view;
1221 err = view_resize(view);
1222 if (err)
1223 return err;
1225 if (view->child->resized_x || view->child->resized_y)
1226 err = view_resize_split(view, 0);
1228 return err;
1231 static const struct got_error *view_dispatch_request(struct tog_view **,
1232 struct tog_view *, enum tog_view_type, int, int);
1234 static const struct got_error *
1235 view_request_new(struct tog_view **requested, struct tog_view *view,
1236 enum tog_view_type request)
1238 struct tog_view *new_view = NULL;
1239 const struct got_error *err;
1240 int y = 0, x = 0;
1242 *requested = NULL;
1244 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1245 view_get_split(view, &y, &x);
1247 err = view_dispatch_request(&new_view, view, request, y, x);
1248 if (err)
1249 return err;
1251 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1252 request != TOG_VIEW_HELP) {
1253 err = view_init_hsplit(view, y);
1254 if (err)
1255 return err;
1258 view->focussed = 0;
1259 new_view->focussed = 1;
1260 new_view->mode = view->mode;
1261 new_view->nlines = request == TOG_VIEW_HELP ?
1262 view->lines : view->lines - y;
1264 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1265 view_transfer_size(new_view, view);
1266 err = view_close_child(view);
1267 if (err)
1268 return err;
1269 err = view_set_child(view, new_view);
1270 if (err)
1271 return err;
1272 view->focus_child = 1;
1273 } else
1274 *requested = new_view;
1276 return NULL;
1279 static void
1280 tog_resizeterm(void)
1282 int cols, lines;
1283 struct winsize size;
1285 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1286 cols = 80; /* Default */
1287 lines = 24;
1288 } else {
1289 cols = size.ws_col;
1290 lines = size.ws_row;
1292 resize_term(lines, cols);
1295 static const struct got_error *
1296 view_search_start(struct tog_view *view)
1298 const struct got_error *err = NULL;
1299 struct tog_view *v = view;
1300 char pattern[1024];
1301 int ret;
1303 if (view->search_started) {
1304 regfree(&view->regex);
1305 view->searching = 0;
1306 memset(&view->regmatch, 0, sizeof(view->regmatch));
1308 view->search_started = 0;
1310 if (view->nlines < 1)
1311 return NULL;
1313 if (view_is_hsplit_top(view))
1314 v = view->child;
1315 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1316 v = view->parent;
1318 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1319 wclrtoeol(v->window);
1321 nodelay(v->window, FALSE); /* block for search term input */
1322 nocbreak();
1323 echo();
1324 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1325 wrefresh(v->window);
1326 cbreak();
1327 noecho();
1328 nodelay(v->window, TRUE);
1329 if (ret == ERR)
1330 return NULL;
1332 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1333 err = view->search_start(view);
1334 if (err) {
1335 regfree(&view->regex);
1336 return err;
1338 view->search_started = 1;
1339 view->searching = TOG_SEARCH_FORWARD;
1340 view->search_next_done = 0;
1341 view->search_next(view);
1344 return NULL;
1347 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1348 static const struct got_error *
1349 switch_split(struct tog_view *view)
1351 const struct got_error *err = NULL;
1352 struct tog_view *v = NULL;
1354 if (view->parent)
1355 v = view->parent;
1356 else
1357 v = view;
1359 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1360 v->mode = TOG_VIEW_SPLIT_VERT;
1361 else
1362 v->mode = TOG_VIEW_SPLIT_HRZN;
1364 if (!v->child)
1365 return NULL;
1366 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1367 v->mode = TOG_VIEW_SPLIT_NONE;
1369 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1370 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1371 v->child->begin_y = v->child->resized_y;
1372 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1373 v->child->begin_x = v->child->resized_x;
1376 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1377 v->ncols = COLS;
1378 v->child->ncols = COLS;
1379 v->child->nscrolled = LINES - v->child->nlines;
1381 err = view_init_hsplit(v, v->child->begin_y);
1382 if (err)
1383 return err;
1385 v->child->mode = v->mode;
1386 v->child->nlines = v->lines - v->child->begin_y;
1387 v->focus_child = 1;
1389 err = view_fullscreen(v);
1390 if (err)
1391 return err;
1392 err = view_splitscreen(v->child);
1393 if (err)
1394 return err;
1396 if (v->mode == TOG_VIEW_SPLIT_NONE)
1397 v->mode = TOG_VIEW_SPLIT_VERT;
1398 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1399 err = offset_selection_down(v);
1400 if (err)
1401 return err;
1402 err = offset_selection_down(v->child);
1403 if (err)
1404 return err;
1405 } else {
1406 offset_selection_up(v);
1407 offset_selection_up(v->child);
1409 if (v->resize)
1410 err = v->resize(v, 0);
1411 else if (v->child->resize)
1412 err = v->child->resize(v->child, 0);
1414 return err;
1418 * Compute view->count from numeric input. Assign total to view->count and
1419 * return first non-numeric key entered.
1421 static int
1422 get_compound_key(struct tog_view *view, int c)
1424 struct tog_view *v = view;
1425 int x, n = 0;
1427 if (view_is_hsplit_top(view))
1428 v = view->child;
1429 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1430 v = view->parent;
1432 view->count = 0;
1433 cbreak(); /* block for input */
1434 nodelay(view->window, FALSE);
1435 wmove(v->window, v->nlines - 1, 0);
1436 wclrtoeol(v->window);
1437 waddch(v->window, ':');
1439 do {
1440 x = getcurx(v->window);
1441 if (x != ERR && x < view->ncols) {
1442 waddch(v->window, c);
1443 wrefresh(v->window);
1447 * Don't overflow. Max valid request should be the greatest
1448 * between the longest and total lines; cap at 10 million.
1450 if (n >= 9999999)
1451 n = 9999999;
1452 else
1453 n = n * 10 + (c - '0');
1454 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1456 if (c == 'G' || c == 'g') { /* nG key map */
1457 view->gline = view->hiline = n;
1458 n = 0;
1459 c = 0;
1462 /* Massage excessive or inapplicable values at the input handler. */
1463 view->count = n;
1465 return c;
1468 static void
1469 action_report(struct tog_view *view)
1471 struct tog_view *v = view;
1473 if (view_is_hsplit_top(view))
1474 v = view->child;
1475 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1476 v = view->parent;
1478 wmove(v->window, v->nlines - 1, 0);
1479 wclrtoeol(v->window);
1480 wprintw(v->window, ":%s", view->action);
1481 wrefresh(v->window);
1484 * Clear action status report. Only clear in blame view
1485 * once annotating is complete, otherwise it's too fast.
1487 if (view->type == TOG_VIEW_BLAME) {
1488 if (view->state.blame.blame_complete)
1489 view->action = NULL;
1490 } else
1491 view->action = NULL;
1494 static const struct got_error *
1495 view_input(struct tog_view **new, int *done, struct tog_view *view,
1496 struct tog_view_list_head *views)
1498 const struct got_error *err = NULL;
1499 struct tog_view *v;
1500 int ch, errcode;
1502 *new = NULL;
1504 if (view->action)
1505 action_report(view);
1507 /* Clear "no matches" indicator. */
1508 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1509 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1510 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1511 view->count = 0;
1514 if (view->searching && !view->search_next_done) {
1515 errcode = pthread_mutex_unlock(&tog_mutex);
1516 if (errcode)
1517 return got_error_set_errno(errcode,
1518 "pthread_mutex_unlock");
1519 sched_yield();
1520 errcode = pthread_mutex_lock(&tog_mutex);
1521 if (errcode)
1522 return got_error_set_errno(errcode,
1523 "pthread_mutex_lock");
1524 view->search_next(view);
1525 return NULL;
1528 /* Allow threads to make progress while we are waiting for input. */
1529 errcode = pthread_mutex_unlock(&tog_mutex);
1530 if (errcode)
1531 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1532 /* If we have an unfinished count, let C-g or backspace abort. */
1533 if (view->count && --view->count) {
1534 cbreak();
1535 nodelay(view->window, TRUE);
1536 ch = wgetch(view->window);
1537 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1538 view->count = 0;
1539 else
1540 ch = view->ch;
1541 } else {
1542 ch = wgetch(view->window);
1543 if (ch >= '1' && ch <= '9')
1544 view->ch = ch = get_compound_key(view, ch);
1546 if (view->hiline && ch != ERR && ch != 0)
1547 view->hiline = 0; /* key pressed, clear line highlight */
1548 nodelay(view->window, TRUE);
1549 errcode = pthread_mutex_lock(&tog_mutex);
1550 if (errcode)
1551 return got_error_set_errno(errcode, "pthread_mutex_lock");
1553 if (tog_sigwinch_received || tog_sigcont_received) {
1554 tog_resizeterm();
1555 tog_sigwinch_received = 0;
1556 tog_sigcont_received = 0;
1557 TAILQ_FOREACH(v, views, entry) {
1558 err = view_resize(v);
1559 if (err)
1560 return err;
1561 err = v->input(new, v, KEY_RESIZE);
1562 if (err)
1563 return err;
1564 if (v->child) {
1565 err = view_resize(v->child);
1566 if (err)
1567 return err;
1568 err = v->child->input(new, v->child,
1569 KEY_RESIZE);
1570 if (err)
1571 return err;
1572 if (v->child->resized_x || v->child->resized_y) {
1573 err = view_resize_split(v, 0);
1574 if (err)
1575 return err;
1581 switch (ch) {
1582 case '?':
1583 case 'H':
1584 case KEY_F(1):
1585 if (view->type == TOG_VIEW_HELP)
1586 err = view->reset(view);
1587 else
1588 err = view_request_new(new, view, TOG_VIEW_HELP);
1589 break;
1590 case '\t':
1591 view->count = 0;
1592 if (view->child) {
1593 view->focussed = 0;
1594 view->child->focussed = 1;
1595 view->focus_child = 1;
1596 } else if (view->parent) {
1597 view->focussed = 0;
1598 view->parent->focussed = 1;
1599 view->parent->focus_child = 0;
1600 if (!view_is_splitscreen(view)) {
1601 if (view->parent->resize) {
1602 err = view->parent->resize(view->parent,
1603 0);
1604 if (err)
1605 return err;
1607 offset_selection_up(view->parent);
1608 err = view_fullscreen(view->parent);
1609 if (err)
1610 return err;
1613 break;
1614 case 'q':
1615 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1616 if (view->parent->resize) {
1617 /* might need more commits to fill fullscreen */
1618 err = view->parent->resize(view->parent, 0);
1619 if (err)
1620 break;
1622 offset_selection_up(view->parent);
1624 err = view->input(new, view, ch);
1625 view->dying = 1;
1626 break;
1627 case 'Q':
1628 *done = 1;
1629 break;
1630 case 'F':
1631 view->count = 0;
1632 if (view_is_parent_view(view)) {
1633 if (view->child == NULL)
1634 break;
1635 if (view_is_splitscreen(view->child)) {
1636 view->focussed = 0;
1637 view->child->focussed = 1;
1638 err = view_fullscreen(view->child);
1639 } else {
1640 err = view_splitscreen(view->child);
1641 if (!err)
1642 err = view_resize_split(view, 0);
1644 if (err)
1645 break;
1646 err = view->child->input(new, view->child,
1647 KEY_RESIZE);
1648 } else {
1649 if (view_is_splitscreen(view)) {
1650 view->parent->focussed = 0;
1651 view->focussed = 1;
1652 err = view_fullscreen(view);
1653 } else {
1654 err = view_splitscreen(view);
1655 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1656 err = view_resize(view->parent);
1657 if (!err)
1658 err = view_resize_split(view, 0);
1660 if (err)
1661 break;
1662 err = view->input(new, view, KEY_RESIZE);
1664 if (err)
1665 break;
1666 if (view->resize) {
1667 err = view->resize(view, 0);
1668 if (err)
1669 break;
1671 if (view->parent)
1672 err = offset_selection_down(view->parent);
1673 if (!err)
1674 err = offset_selection_down(view);
1675 break;
1676 case 'S':
1677 view->count = 0;
1678 err = switch_split(view);
1679 break;
1680 case '-':
1681 err = view_resize_split(view, -1);
1682 break;
1683 case '+':
1684 err = view_resize_split(view, 1);
1685 break;
1686 case KEY_RESIZE:
1687 break;
1688 case '/':
1689 view->count = 0;
1690 if (view->search_start)
1691 view_search_start(view);
1692 else
1693 err = view->input(new, view, ch);
1694 break;
1695 case 'N':
1696 case 'n':
1697 if (view->search_started && view->search_next) {
1698 view->searching = (ch == 'n' ?
1699 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1700 view->search_next_done = 0;
1701 view->search_next(view);
1702 } else
1703 err = view->input(new, view, ch);
1704 break;
1705 case 'A':
1706 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1707 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1708 view->action = "Patience diff algorithm";
1709 } else {
1710 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1711 view->action = "Myers diff algorithm";
1713 TAILQ_FOREACH(v, views, entry) {
1714 if (v->reset) {
1715 err = v->reset(v);
1716 if (err)
1717 return err;
1719 if (v->child && v->child->reset) {
1720 err = v->child->reset(v->child);
1721 if (err)
1722 return err;
1725 break;
1726 default:
1727 err = view->input(new, view, ch);
1728 break;
1731 return err;
1734 static int
1735 view_needs_focus_indication(struct tog_view *view)
1737 if (view_is_parent_view(view)) {
1738 if (view->child == NULL || view->child->focussed)
1739 return 0;
1740 if (!view_is_splitscreen(view->child))
1741 return 0;
1742 } else if (!view_is_splitscreen(view))
1743 return 0;
1745 return view->focussed;
1748 static const struct got_error *
1749 view_loop(struct tog_view *view)
1751 const struct got_error *err = NULL;
1752 struct tog_view_list_head views;
1753 struct tog_view *new_view;
1754 char *mode;
1755 int fast_refresh = 10;
1756 int done = 0, errcode;
1758 mode = getenv("TOG_VIEW_SPLIT_MODE");
1759 if (!mode || !(*mode == 'h' || *mode == 'H'))
1760 view->mode = TOG_VIEW_SPLIT_VERT;
1761 else
1762 view->mode = TOG_VIEW_SPLIT_HRZN;
1764 errcode = pthread_mutex_lock(&tog_mutex);
1765 if (errcode)
1766 return got_error_set_errno(errcode, "pthread_mutex_lock");
1768 TAILQ_INIT(&views);
1769 TAILQ_INSERT_HEAD(&views, view, entry);
1771 view->focussed = 1;
1772 err = view->show(view);
1773 if (err)
1774 return err;
1775 update_panels();
1776 doupdate();
1777 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1778 !tog_fatal_signal_received()) {
1779 /* Refresh fast during initialization, then become slower. */
1780 if (fast_refresh && --fast_refresh == 0)
1781 halfdelay(10); /* switch to once per second */
1783 err = view_input(&new_view, &done, view, &views);
1784 if (err)
1785 break;
1787 if (view->dying && view == TAILQ_FIRST(&views) &&
1788 TAILQ_NEXT(view, entry) == NULL)
1789 done = 1;
1790 if (done) {
1791 struct tog_view *v;
1794 * When we quit, scroll the screen up a single line
1795 * so we don't lose any information.
1797 TAILQ_FOREACH(v, &views, entry) {
1798 wmove(v->window, 0, 0);
1799 wdeleteln(v->window);
1800 wnoutrefresh(v->window);
1801 if (v->child && !view_is_fullscreen(v)) {
1802 wmove(v->child->window, 0, 0);
1803 wdeleteln(v->child->window);
1804 wnoutrefresh(v->child->window);
1807 doupdate();
1810 if (view->dying) {
1811 struct tog_view *v, *prev = NULL;
1813 if (view_is_parent_view(view))
1814 prev = TAILQ_PREV(view, tog_view_list_head,
1815 entry);
1816 else if (view->parent)
1817 prev = view->parent;
1819 if (view->parent) {
1820 view->parent->child = NULL;
1821 view->parent->focus_child = 0;
1822 /* Restore fullscreen line height. */
1823 view->parent->nlines = view->parent->lines;
1824 err = view_resize(view->parent);
1825 if (err)
1826 break;
1827 /* Make resized splits persist. */
1828 view_transfer_size(view->parent, view);
1829 } else
1830 TAILQ_REMOVE(&views, view, entry);
1832 err = view_close(view);
1833 if (err)
1834 goto done;
1836 view = NULL;
1837 TAILQ_FOREACH(v, &views, entry) {
1838 if (v->focussed)
1839 break;
1841 if (view == NULL && new_view == NULL) {
1842 /* No view has focus. Try to pick one. */
1843 if (prev)
1844 view = prev;
1845 else if (!TAILQ_EMPTY(&views)) {
1846 view = TAILQ_LAST(&views,
1847 tog_view_list_head);
1849 if (view) {
1850 if (view->focus_child) {
1851 view->child->focussed = 1;
1852 view = view->child;
1853 } else
1854 view->focussed = 1;
1858 if (new_view) {
1859 struct tog_view *v, *t;
1860 /* Only allow one parent view per type. */
1861 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1862 if (v->type != new_view->type)
1863 continue;
1864 TAILQ_REMOVE(&views, v, entry);
1865 err = view_close(v);
1866 if (err)
1867 goto done;
1868 break;
1870 TAILQ_INSERT_TAIL(&views, new_view, entry);
1871 view = new_view;
1873 if (view && !done) {
1874 if (view_is_parent_view(view)) {
1875 if (view->child && view->child->focussed)
1876 view = view->child;
1877 } else {
1878 if (view->parent && view->parent->focussed)
1879 view = view->parent;
1881 show_panel(view->panel);
1882 if (view->child && view_is_splitscreen(view->child))
1883 show_panel(view->child->panel);
1884 if (view->parent && view_is_splitscreen(view)) {
1885 err = view->parent->show(view->parent);
1886 if (err)
1887 goto done;
1889 err = view->show(view);
1890 if (err)
1891 goto done;
1892 if (view->child) {
1893 err = view->child->show(view->child);
1894 if (err)
1895 goto done;
1897 update_panels();
1898 doupdate();
1901 done:
1902 while (!TAILQ_EMPTY(&views)) {
1903 const struct got_error *close_err;
1904 view = TAILQ_FIRST(&views);
1905 TAILQ_REMOVE(&views, view, entry);
1906 close_err = view_close(view);
1907 if (close_err && err == NULL)
1908 err = close_err;
1911 errcode = pthread_mutex_unlock(&tog_mutex);
1912 if (errcode && err == NULL)
1913 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1915 return err;
1918 __dead static void
1919 usage_log(void)
1921 endwin();
1922 fprintf(stderr,
1923 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1924 getprogname());
1925 exit(1);
1928 /* Create newly allocated wide-character string equivalent to a byte string. */
1929 static const struct got_error *
1930 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1932 char *vis = NULL;
1933 const struct got_error *err = NULL;
1935 *ws = NULL;
1936 *wlen = mbstowcs(NULL, s, 0);
1937 if (*wlen == (size_t)-1) {
1938 int vislen;
1939 if (errno != EILSEQ)
1940 return got_error_from_errno("mbstowcs");
1942 /* byte string invalid in current encoding; try to "fix" it */
1943 err = got_mbsavis(&vis, &vislen, s);
1944 if (err)
1945 return err;
1946 *wlen = mbstowcs(NULL, vis, 0);
1947 if (*wlen == (size_t)-1) {
1948 err = got_error_from_errno("mbstowcs"); /* give up */
1949 goto done;
1953 *ws = calloc(*wlen + 1, sizeof(**ws));
1954 if (*ws == NULL) {
1955 err = got_error_from_errno("calloc");
1956 goto done;
1959 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1960 err = got_error_from_errno("mbstowcs");
1961 done:
1962 free(vis);
1963 if (err) {
1964 free(*ws);
1965 *ws = NULL;
1966 *wlen = 0;
1968 return err;
1971 static const struct got_error *
1972 expand_tab(char **ptr, const char *src)
1974 char *dst;
1975 size_t len, n, idx = 0, sz = 0;
1977 *ptr = NULL;
1978 n = len = strlen(src);
1979 dst = malloc(n + 1);
1980 if (dst == NULL)
1981 return got_error_from_errno("malloc");
1983 while (idx < len && src[idx]) {
1984 const char c = src[idx];
1986 if (c == '\t') {
1987 size_t nb = TABSIZE - sz % TABSIZE;
1988 char *p;
1990 p = realloc(dst, n + nb);
1991 if (p == NULL) {
1992 free(dst);
1993 return got_error_from_errno("realloc");
1996 dst = p;
1997 n += nb;
1998 memset(dst + sz, ' ', nb);
1999 sz += nb;
2000 } else
2001 dst[sz++] = src[idx];
2002 ++idx;
2005 dst[sz] = '\0';
2006 *ptr = dst;
2007 return NULL;
2011 * Advance at most n columns from wline starting at offset off.
2012 * Return the index to the first character after the span operation.
2013 * Return the combined column width of all spanned wide character in
2014 * *rcol.
2016 static int
2017 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2019 int width, i, cols = 0;
2021 if (n == 0) {
2022 *rcol = cols;
2023 return off;
2026 for (i = off; wline[i] != L'\0'; ++i) {
2027 if (wline[i] == L'\t')
2028 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2029 else
2030 width = wcwidth(wline[i]);
2032 if (width == -1) {
2033 width = 1;
2034 wline[i] = L'.';
2037 if (cols + width > n)
2038 break;
2039 cols += width;
2042 *rcol = cols;
2043 return i;
2047 * Format a line for display, ensuring that it won't overflow a width limit.
2048 * With scrolling, the width returned refers to the scrolled version of the
2049 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2051 static const struct got_error *
2052 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2053 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2055 const struct got_error *err = NULL;
2056 int cols;
2057 wchar_t *wline = NULL;
2058 char *exstr = NULL;
2059 size_t wlen;
2060 int i, scrollx;
2062 *wlinep = NULL;
2063 *widthp = 0;
2065 if (expand) {
2066 err = expand_tab(&exstr, line);
2067 if (err)
2068 return err;
2071 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2072 free(exstr);
2073 if (err)
2074 return err;
2076 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2078 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2079 wline[wlen - 1] = L'\0';
2080 wlen--;
2082 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2083 wline[wlen - 1] = L'\0';
2084 wlen--;
2087 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2088 wline[i] = L'\0';
2090 if (widthp)
2091 *widthp = cols;
2092 if (scrollxp)
2093 *scrollxp = scrollx;
2094 if (err)
2095 free(wline);
2096 else
2097 *wlinep = wline;
2098 return err;
2101 static const struct got_error*
2102 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2103 struct got_object_id *id, struct got_repository *repo)
2105 static const struct got_error *err = NULL;
2106 struct got_reflist_entry *re;
2107 char *s;
2108 const char *name;
2110 *refs_str = NULL;
2112 TAILQ_FOREACH(re, refs, entry) {
2113 struct got_tag_object *tag = NULL;
2114 struct got_object_id *ref_id;
2115 int cmp;
2117 name = got_ref_get_name(re->ref);
2118 if (strcmp(name, GOT_REF_HEAD) == 0)
2119 continue;
2120 if (strncmp(name, "refs/", 5) == 0)
2121 name += 5;
2122 if (strncmp(name, "got/", 4) == 0 &&
2123 strncmp(name, "got/backup/", 11) != 0)
2124 continue;
2125 if (strncmp(name, "heads/", 6) == 0)
2126 name += 6;
2127 if (strncmp(name, "remotes/", 8) == 0) {
2128 name += 8;
2129 s = strstr(name, "/" GOT_REF_HEAD);
2130 if (s != NULL && s[strlen(s)] == '\0')
2131 continue;
2133 err = got_ref_resolve(&ref_id, repo, re->ref);
2134 if (err)
2135 break;
2136 if (strncmp(name, "tags/", 5) == 0) {
2137 err = got_object_open_as_tag(&tag, repo, ref_id);
2138 if (err) {
2139 if (err->code != GOT_ERR_OBJ_TYPE) {
2140 free(ref_id);
2141 break;
2143 /* Ref points at something other than a tag. */
2144 err = NULL;
2145 tag = NULL;
2148 cmp = got_object_id_cmp(tag ?
2149 got_object_tag_get_object_id(tag) : ref_id, id);
2150 free(ref_id);
2151 if (tag)
2152 got_object_tag_close(tag);
2153 if (cmp != 0)
2154 continue;
2155 s = *refs_str;
2156 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2157 s ? ", " : "", name) == -1) {
2158 err = got_error_from_errno("asprintf");
2159 free(s);
2160 *refs_str = NULL;
2161 break;
2163 free(s);
2166 return err;
2169 static const struct got_error *
2170 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2171 int col_tab_align)
2173 char *smallerthan;
2175 smallerthan = strchr(author, '<');
2176 if (smallerthan && smallerthan[1] != '\0')
2177 author = smallerthan + 1;
2178 author[strcspn(author, "@>")] = '\0';
2179 return format_line(wauthor, author_width, NULL, author, 0, limit,
2180 col_tab_align, 0);
2183 static const struct got_error *
2184 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2185 struct got_object_id *id, const size_t date_display_cols,
2186 int author_display_cols)
2188 struct tog_log_view_state *s = &view->state.log;
2189 const struct got_error *err = NULL;
2190 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2191 char *logmsg0 = NULL, *logmsg = NULL;
2192 char *author = NULL;
2193 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2194 int author_width, logmsg_width;
2195 char *newline, *line = NULL;
2196 int col, limit, scrollx;
2197 const int avail = view->ncols;
2198 struct tm tm;
2199 time_t committer_time;
2200 struct tog_color *tc;
2202 committer_time = got_object_commit_get_committer_time(commit);
2203 if (gmtime_r(&committer_time, &tm) == NULL)
2204 return got_error_from_errno("gmtime_r");
2205 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2206 return got_error(GOT_ERR_NO_SPACE);
2208 if (avail <= date_display_cols)
2209 limit = MIN(sizeof(datebuf) - 1, avail);
2210 else
2211 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2212 tc = get_color(&s->colors, TOG_COLOR_DATE);
2213 if (tc)
2214 wattr_on(view->window,
2215 COLOR_PAIR(tc->colorpair), NULL);
2216 waddnstr(view->window, datebuf, limit);
2217 if (tc)
2218 wattr_off(view->window,
2219 COLOR_PAIR(tc->colorpair), NULL);
2220 col = limit;
2221 if (col > avail)
2222 goto done;
2224 if (avail >= 120) {
2225 char *id_str;
2226 err = got_object_id_str(&id_str, id);
2227 if (err)
2228 goto done;
2229 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2230 if (tc)
2231 wattr_on(view->window,
2232 COLOR_PAIR(tc->colorpair), NULL);
2233 wprintw(view->window, "%.8s ", id_str);
2234 if (tc)
2235 wattr_off(view->window,
2236 COLOR_PAIR(tc->colorpair), NULL);
2237 free(id_str);
2238 col += 9;
2239 if (col > avail)
2240 goto done;
2243 if (s->use_committer)
2244 author = strdup(got_object_commit_get_committer(commit));
2245 else
2246 author = strdup(got_object_commit_get_author(commit));
2247 if (author == NULL) {
2248 err = got_error_from_errno("strdup");
2249 goto done;
2251 err = format_author(&wauthor, &author_width, author, avail - col, col);
2252 if (err)
2253 goto done;
2254 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2255 if (tc)
2256 wattr_on(view->window,
2257 COLOR_PAIR(tc->colorpair), NULL);
2258 waddwstr(view->window, wauthor);
2259 col += author_width;
2260 while (col < avail && author_width < author_display_cols + 2) {
2261 waddch(view->window, ' ');
2262 col++;
2263 author_width++;
2265 if (tc)
2266 wattr_off(view->window,
2267 COLOR_PAIR(tc->colorpair), NULL);
2268 if (col > avail)
2269 goto done;
2271 err = got_object_commit_get_logmsg(&logmsg0, commit);
2272 if (err)
2273 goto done;
2274 logmsg = logmsg0;
2275 while (*logmsg == '\n')
2276 logmsg++;
2277 newline = strchr(logmsg, '\n');
2278 if (newline)
2279 *newline = '\0';
2280 limit = avail - col;
2281 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2282 limit--; /* for the border */
2283 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2284 limit, col, 1);
2285 if (err)
2286 goto done;
2287 waddwstr(view->window, &wlogmsg[scrollx]);
2288 col += MAX(logmsg_width, 0);
2289 while (col < avail) {
2290 waddch(view->window, ' ');
2291 col++;
2293 done:
2294 free(logmsg0);
2295 free(wlogmsg);
2296 free(author);
2297 free(wauthor);
2298 free(line);
2299 return err;
2302 static struct commit_queue_entry *
2303 alloc_commit_queue_entry(struct got_commit_object *commit,
2304 struct got_object_id *id)
2306 struct commit_queue_entry *entry;
2307 struct got_object_id *dup;
2309 entry = calloc(1, sizeof(*entry));
2310 if (entry == NULL)
2311 return NULL;
2313 dup = got_object_id_dup(id);
2314 if (dup == NULL) {
2315 free(entry);
2316 return NULL;
2319 entry->id = dup;
2320 entry->commit = commit;
2321 return entry;
2324 static void
2325 pop_commit(struct commit_queue *commits)
2327 struct commit_queue_entry *entry;
2329 entry = TAILQ_FIRST(&commits->head);
2330 TAILQ_REMOVE(&commits->head, entry, entry);
2331 got_object_commit_close(entry->commit);
2332 commits->ncommits--;
2333 free(entry->id);
2334 free(entry);
2337 static void
2338 free_commits(struct commit_queue *commits)
2340 while (!TAILQ_EMPTY(&commits->head))
2341 pop_commit(commits);
2344 static const struct got_error *
2345 match_commit(int *have_match, struct got_object_id *id,
2346 struct got_commit_object *commit, regex_t *regex)
2348 const struct got_error *err = NULL;
2349 regmatch_t regmatch;
2350 char *id_str = NULL, *logmsg = NULL;
2352 *have_match = 0;
2354 err = got_object_id_str(&id_str, id);
2355 if (err)
2356 return err;
2358 err = got_object_commit_get_logmsg(&logmsg, commit);
2359 if (err)
2360 goto done;
2362 if (regexec(regex, got_object_commit_get_author(commit), 1,
2363 &regmatch, 0) == 0 ||
2364 regexec(regex, got_object_commit_get_committer(commit), 1,
2365 &regmatch, 0) == 0 ||
2366 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2367 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2368 *have_match = 1;
2369 done:
2370 free(id_str);
2371 free(logmsg);
2372 return err;
2375 static const struct got_error *
2376 queue_commits(struct tog_log_thread_args *a)
2378 const struct got_error *err = NULL;
2381 * We keep all commits open throughout the lifetime of the log
2382 * view in order to avoid having to re-fetch commits from disk
2383 * while updating the display.
2385 do {
2386 struct got_object_id id;
2387 struct got_commit_object *commit;
2388 struct commit_queue_entry *entry;
2389 int limit_match = 0;
2390 int errcode;
2392 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2393 NULL, NULL);
2394 if (err)
2395 break;
2397 err = got_object_open_as_commit(&commit, a->repo, &id);
2398 if (err)
2399 break;
2400 entry = alloc_commit_queue_entry(commit, &id);
2401 if (entry == NULL) {
2402 err = got_error_from_errno("alloc_commit_queue_entry");
2403 break;
2406 errcode = pthread_mutex_lock(&tog_mutex);
2407 if (errcode) {
2408 err = got_error_set_errno(errcode,
2409 "pthread_mutex_lock");
2410 break;
2413 entry->idx = a->real_commits->ncommits;
2414 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2415 a->real_commits->ncommits++;
2417 if (*a->limiting) {
2418 err = match_commit(&limit_match, &id, commit,
2419 a->limit_regex);
2420 if (err)
2421 break;
2423 if (limit_match) {
2424 struct commit_queue_entry *matched;
2426 matched = alloc_commit_queue_entry(
2427 entry->commit, entry->id);
2428 if (matched == NULL) {
2429 err = got_error_from_errno(
2430 "alloc_commit_queue_entry");
2431 break;
2433 matched->commit = entry->commit;
2434 got_object_commit_retain(entry->commit);
2436 matched->idx = a->limit_commits->ncommits;
2437 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2438 matched, entry);
2439 a->limit_commits->ncommits++;
2443 * This is how we signal log_thread() that we
2444 * have found a match, and that it should be
2445 * counted as a new entry for the view.
2447 a->limit_match = limit_match;
2450 if (*a->searching == TOG_SEARCH_FORWARD &&
2451 !*a->search_next_done) {
2452 int have_match;
2453 err = match_commit(&have_match, &id, commit, a->regex);
2454 if (err)
2455 break;
2457 if (*a->limiting) {
2458 if (limit_match && have_match)
2459 *a->search_next_done =
2460 TOG_SEARCH_HAVE_MORE;
2461 } else if (have_match)
2462 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2465 errcode = pthread_mutex_unlock(&tog_mutex);
2466 if (errcode && err == NULL)
2467 err = got_error_set_errno(errcode,
2468 "pthread_mutex_unlock");
2469 if (err)
2470 break;
2471 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2473 return err;
2476 static void
2477 select_commit(struct tog_log_view_state *s)
2479 struct commit_queue_entry *entry;
2480 int ncommits = 0;
2482 entry = s->first_displayed_entry;
2483 while (entry) {
2484 if (ncommits == s->selected) {
2485 s->selected_entry = entry;
2486 break;
2488 entry = TAILQ_NEXT(entry, entry);
2489 ncommits++;
2493 static const struct got_error *
2494 draw_commits(struct tog_view *view)
2496 const struct got_error *err = NULL;
2497 struct tog_log_view_state *s = &view->state.log;
2498 struct commit_queue_entry *entry = s->selected_entry;
2499 int limit = view->nlines;
2500 int width;
2501 int ncommits, author_cols = 4;
2502 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2503 char *refs_str = NULL;
2504 wchar_t *wline;
2505 struct tog_color *tc;
2506 static const size_t date_display_cols = 12;
2508 if (view_is_hsplit_top(view))
2509 --limit; /* account for border */
2511 if (s->selected_entry &&
2512 !(view->searching && view->search_next_done == 0)) {
2513 struct got_reflist_head *refs;
2514 err = got_object_id_str(&id_str, s->selected_entry->id);
2515 if (err)
2516 return err;
2517 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2518 s->selected_entry->id);
2519 if (refs) {
2520 err = build_refs_str(&refs_str, refs,
2521 s->selected_entry->id, s->repo);
2522 if (err)
2523 goto done;
2527 if (s->thread_args.commits_needed == 0)
2528 halfdelay(10); /* disable fast refresh */
2530 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2531 if (asprintf(&ncommits_str, " [%d/%d] %s",
2532 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2533 (view->searching && !view->search_next_done) ?
2534 "searching..." : "loading...") == -1) {
2535 err = got_error_from_errno("asprintf");
2536 goto done;
2538 } else {
2539 const char *search_str = NULL;
2540 const char *limit_str = NULL;
2542 if (view->searching) {
2543 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2544 search_str = "no more matches";
2545 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2546 search_str = "no matches found";
2547 else if (!view->search_next_done)
2548 search_str = "searching...";
2551 if (s->limit_view && s->commits->ncommits == 0)
2552 limit_str = "no matches found";
2554 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2555 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2556 search_str ? search_str : (refs_str ? refs_str : ""),
2557 limit_str ? limit_str : "") == -1) {
2558 err = got_error_from_errno("asprintf");
2559 goto done;
2563 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2564 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2565 "........................................",
2566 s->in_repo_path, ncommits_str) == -1) {
2567 err = got_error_from_errno("asprintf");
2568 header = NULL;
2569 goto done;
2571 } else if (asprintf(&header, "commit %s%s",
2572 id_str ? id_str : "........................................",
2573 ncommits_str) == -1) {
2574 err = got_error_from_errno("asprintf");
2575 header = NULL;
2576 goto done;
2578 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2579 if (err)
2580 goto done;
2582 werase(view->window);
2584 if (view_needs_focus_indication(view))
2585 wstandout(view->window);
2586 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2587 if (tc)
2588 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2589 waddwstr(view->window, wline);
2590 while (width < view->ncols) {
2591 waddch(view->window, ' ');
2592 width++;
2594 if (tc)
2595 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2596 if (view_needs_focus_indication(view))
2597 wstandend(view->window);
2598 free(wline);
2599 if (limit <= 1)
2600 goto done;
2602 /* Grow author column size if necessary, and set view->maxx. */
2603 entry = s->first_displayed_entry;
2604 ncommits = 0;
2605 view->maxx = 0;
2606 while (entry) {
2607 struct got_commit_object *c = entry->commit;
2608 char *author, *eol, *msg, *msg0;
2609 wchar_t *wauthor, *wmsg;
2610 int width;
2611 if (ncommits >= limit - 1)
2612 break;
2613 if (s->use_committer)
2614 author = strdup(got_object_commit_get_committer(c));
2615 else
2616 author = strdup(got_object_commit_get_author(c));
2617 if (author == NULL) {
2618 err = got_error_from_errno("strdup");
2619 goto done;
2621 err = format_author(&wauthor, &width, author, COLS,
2622 date_display_cols);
2623 if (author_cols < width)
2624 author_cols = width;
2625 free(wauthor);
2626 free(author);
2627 if (err)
2628 goto done;
2629 err = got_object_commit_get_logmsg(&msg0, c);
2630 if (err)
2631 goto done;
2632 msg = msg0;
2633 while (*msg == '\n')
2634 ++msg;
2635 if ((eol = strchr(msg, '\n')))
2636 *eol = '\0';
2637 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2638 date_display_cols + author_cols, 0);
2639 if (err)
2640 goto done;
2641 view->maxx = MAX(view->maxx, width);
2642 free(msg0);
2643 free(wmsg);
2644 ncommits++;
2645 entry = TAILQ_NEXT(entry, entry);
2648 entry = s->first_displayed_entry;
2649 s->last_displayed_entry = s->first_displayed_entry;
2650 ncommits = 0;
2651 while (entry) {
2652 if (ncommits >= limit - 1)
2653 break;
2654 if (ncommits == s->selected)
2655 wstandout(view->window);
2656 err = draw_commit(view, entry->commit, entry->id,
2657 date_display_cols, author_cols);
2658 if (ncommits == s->selected)
2659 wstandend(view->window);
2660 if (err)
2661 goto done;
2662 ncommits++;
2663 s->last_displayed_entry = entry;
2664 entry = TAILQ_NEXT(entry, entry);
2667 view_border(view);
2668 done:
2669 free(id_str);
2670 free(refs_str);
2671 free(ncommits_str);
2672 free(header);
2673 return err;
2676 static void
2677 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2679 struct commit_queue_entry *entry;
2680 int nscrolled = 0;
2682 entry = TAILQ_FIRST(&s->commits->head);
2683 if (s->first_displayed_entry == entry)
2684 return;
2686 entry = s->first_displayed_entry;
2687 while (entry && nscrolled < maxscroll) {
2688 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2689 if (entry) {
2690 s->first_displayed_entry = entry;
2691 nscrolled++;
2696 static const struct got_error *
2697 trigger_log_thread(struct tog_view *view, int wait)
2699 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2700 int errcode;
2702 halfdelay(1); /* fast refresh while loading commits */
2704 while (!ta->log_complete && !tog_thread_error &&
2705 (ta->commits_needed > 0 || ta->load_all)) {
2706 /* Wake the log thread. */
2707 errcode = pthread_cond_signal(&ta->need_commits);
2708 if (errcode)
2709 return got_error_set_errno(errcode,
2710 "pthread_cond_signal");
2713 * The mutex will be released while the view loop waits
2714 * in wgetch(), at which time the log thread will run.
2716 if (!wait)
2717 break;
2719 /* Display progress update in log view. */
2720 show_log_view(view);
2721 update_panels();
2722 doupdate();
2724 /* Wait right here while next commit is being loaded. */
2725 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2726 if (errcode)
2727 return got_error_set_errno(errcode,
2728 "pthread_cond_wait");
2730 /* Display progress update in log view. */
2731 show_log_view(view);
2732 update_panels();
2733 doupdate();
2736 return NULL;
2739 static const struct got_error *
2740 request_log_commits(struct tog_view *view)
2742 struct tog_log_view_state *state = &view->state.log;
2743 const struct got_error *err = NULL;
2745 if (state->thread_args.log_complete)
2746 return NULL;
2748 state->thread_args.commits_needed += view->nscrolled;
2749 err = trigger_log_thread(view, 1);
2750 view->nscrolled = 0;
2752 return err;
2755 static const struct got_error *
2756 log_scroll_down(struct tog_view *view, int maxscroll)
2758 struct tog_log_view_state *s = &view->state.log;
2759 const struct got_error *err = NULL;
2760 struct commit_queue_entry *pentry;
2761 int nscrolled = 0, ncommits_needed;
2763 if (s->last_displayed_entry == NULL)
2764 return NULL;
2766 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2767 if (s->commits->ncommits < ncommits_needed &&
2768 !s->thread_args.log_complete) {
2770 * Ask the log thread for required amount of commits.
2772 s->thread_args.commits_needed +=
2773 ncommits_needed - s->commits->ncommits;
2774 err = trigger_log_thread(view, 1);
2775 if (err)
2776 return err;
2779 do {
2780 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2781 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2782 break;
2784 s->last_displayed_entry = pentry ?
2785 pentry : s->last_displayed_entry;
2787 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2788 if (pentry == NULL)
2789 break;
2790 s->first_displayed_entry = pentry;
2791 } while (++nscrolled < maxscroll);
2793 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2794 view->nscrolled += nscrolled;
2795 else
2796 view->nscrolled = 0;
2798 return err;
2801 static const struct got_error *
2802 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2803 struct got_commit_object *commit, struct got_object_id *commit_id,
2804 struct tog_view *log_view, struct got_repository *repo)
2806 const struct got_error *err;
2807 struct got_object_qid *parent_id;
2808 struct tog_view *diff_view;
2810 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2811 if (diff_view == NULL)
2812 return got_error_from_errno("view_open");
2814 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2815 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2816 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2817 if (err == NULL)
2818 *new_view = diff_view;
2819 return err;
2822 static const struct got_error *
2823 tree_view_visit_subtree(struct tog_tree_view_state *s,
2824 struct got_tree_object *subtree)
2826 struct tog_parent_tree *parent;
2828 parent = calloc(1, sizeof(*parent));
2829 if (parent == NULL)
2830 return got_error_from_errno("calloc");
2832 parent->tree = s->tree;
2833 parent->first_displayed_entry = s->first_displayed_entry;
2834 parent->selected_entry = s->selected_entry;
2835 parent->selected = s->selected;
2836 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2837 s->tree = subtree;
2838 s->selected = 0;
2839 s->first_displayed_entry = NULL;
2840 return NULL;
2843 static const struct got_error *
2844 tree_view_walk_path(struct tog_tree_view_state *s,
2845 struct got_commit_object *commit, const char *path)
2847 const struct got_error *err = NULL;
2848 struct got_tree_object *tree = NULL;
2849 const char *p;
2850 char *slash, *subpath = NULL;
2852 /* Walk the path and open corresponding tree objects. */
2853 p = path;
2854 while (*p) {
2855 struct got_tree_entry *te;
2856 struct got_object_id *tree_id;
2857 char *te_name;
2859 while (p[0] == '/')
2860 p++;
2862 /* Ensure the correct subtree entry is selected. */
2863 slash = strchr(p, '/');
2864 if (slash == NULL)
2865 te_name = strdup(p);
2866 else
2867 te_name = strndup(p, slash - p);
2868 if (te_name == NULL) {
2869 err = got_error_from_errno("strndup");
2870 break;
2872 te = got_object_tree_find_entry(s->tree, te_name);
2873 if (te == NULL) {
2874 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2875 free(te_name);
2876 break;
2878 free(te_name);
2879 s->first_displayed_entry = s->selected_entry = te;
2881 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2882 break; /* jump to this file's entry */
2884 slash = strchr(p, '/');
2885 if (slash)
2886 subpath = strndup(path, slash - path);
2887 else
2888 subpath = strdup(path);
2889 if (subpath == NULL) {
2890 err = got_error_from_errno("strdup");
2891 break;
2894 err = got_object_id_by_path(&tree_id, s->repo, commit,
2895 subpath);
2896 if (err)
2897 break;
2899 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2900 free(tree_id);
2901 if (err)
2902 break;
2904 err = tree_view_visit_subtree(s, tree);
2905 if (err) {
2906 got_object_tree_close(tree);
2907 break;
2909 if (slash == NULL)
2910 break;
2911 free(subpath);
2912 subpath = NULL;
2913 p = slash;
2916 free(subpath);
2917 return err;
2920 static const struct got_error *
2921 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2922 struct commit_queue_entry *entry, const char *path,
2923 const char *head_ref_name, struct got_repository *repo)
2925 const struct got_error *err = NULL;
2926 struct tog_tree_view_state *s;
2927 struct tog_view *tree_view;
2929 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2930 if (tree_view == NULL)
2931 return got_error_from_errno("view_open");
2933 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2934 if (err)
2935 return err;
2936 s = &tree_view->state.tree;
2938 *new_view = tree_view;
2940 if (got_path_is_root_dir(path))
2941 return NULL;
2943 return tree_view_walk_path(s, entry->commit, path);
2946 static const struct got_error *
2947 block_signals_used_by_main_thread(void)
2949 sigset_t sigset;
2950 int errcode;
2952 if (sigemptyset(&sigset) == -1)
2953 return got_error_from_errno("sigemptyset");
2955 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2956 if (sigaddset(&sigset, SIGWINCH) == -1)
2957 return got_error_from_errno("sigaddset");
2958 if (sigaddset(&sigset, SIGCONT) == -1)
2959 return got_error_from_errno("sigaddset");
2960 if (sigaddset(&sigset, SIGINT) == -1)
2961 return got_error_from_errno("sigaddset");
2962 if (sigaddset(&sigset, SIGTERM) == -1)
2963 return got_error_from_errno("sigaddset");
2965 /* ncurses handles SIGTSTP */
2966 if (sigaddset(&sigset, SIGTSTP) == -1)
2967 return got_error_from_errno("sigaddset");
2969 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2970 if (errcode)
2971 return got_error_set_errno(errcode, "pthread_sigmask");
2973 return NULL;
2976 static void *
2977 log_thread(void *arg)
2979 const struct got_error *err = NULL;
2980 int errcode = 0;
2981 struct tog_log_thread_args *a = arg;
2982 int done = 0;
2985 * Sync startup with main thread such that we begin our
2986 * work once view_input() has released the mutex.
2988 errcode = pthread_mutex_lock(&tog_mutex);
2989 if (errcode) {
2990 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2991 return (void *)err;
2994 err = block_signals_used_by_main_thread();
2995 if (err) {
2996 pthread_mutex_unlock(&tog_mutex);
2997 goto done;
3000 while (!done && !err && !tog_fatal_signal_received()) {
3001 errcode = pthread_mutex_unlock(&tog_mutex);
3002 if (errcode) {
3003 err = got_error_set_errno(errcode,
3004 "pthread_mutex_unlock");
3005 goto done;
3007 err = queue_commits(a);
3008 if (err) {
3009 if (err->code != GOT_ERR_ITER_COMPLETED)
3010 goto done;
3011 err = NULL;
3012 done = 1;
3013 } else if (a->commits_needed > 0 && !a->load_all) {
3014 if (*a->limiting) {
3015 if (a->limit_match)
3016 a->commits_needed--;
3017 } else
3018 a->commits_needed--;
3021 errcode = pthread_mutex_lock(&tog_mutex);
3022 if (errcode) {
3023 err = got_error_set_errno(errcode,
3024 "pthread_mutex_lock");
3025 goto done;
3026 } else if (*a->quit)
3027 done = 1;
3028 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3029 *a->first_displayed_entry =
3030 TAILQ_FIRST(&a->limit_commits->head);
3031 *a->selected_entry = *a->first_displayed_entry;
3032 } else if (*a->first_displayed_entry == NULL) {
3033 *a->first_displayed_entry =
3034 TAILQ_FIRST(&a->real_commits->head);
3035 *a->selected_entry = *a->first_displayed_entry;
3038 errcode = pthread_cond_signal(&a->commit_loaded);
3039 if (errcode) {
3040 err = got_error_set_errno(errcode,
3041 "pthread_cond_signal");
3042 pthread_mutex_unlock(&tog_mutex);
3043 goto done;
3046 if (done)
3047 a->commits_needed = 0;
3048 else {
3049 if (a->commits_needed == 0 && !a->load_all) {
3050 errcode = pthread_cond_wait(&a->need_commits,
3051 &tog_mutex);
3052 if (errcode) {
3053 err = got_error_set_errno(errcode,
3054 "pthread_cond_wait");
3055 pthread_mutex_unlock(&tog_mutex);
3056 goto done;
3058 if (*a->quit)
3059 done = 1;
3063 a->log_complete = 1;
3064 errcode = pthread_mutex_unlock(&tog_mutex);
3065 if (errcode)
3066 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3067 done:
3068 if (err) {
3069 tog_thread_error = 1;
3070 pthread_cond_signal(&a->commit_loaded);
3072 return (void *)err;
3075 static const struct got_error *
3076 stop_log_thread(struct tog_log_view_state *s)
3078 const struct got_error *err = NULL, *thread_err = NULL;
3079 int errcode;
3081 if (s->thread) {
3082 s->quit = 1;
3083 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3084 if (errcode)
3085 return got_error_set_errno(errcode,
3086 "pthread_cond_signal");
3087 errcode = pthread_mutex_unlock(&tog_mutex);
3088 if (errcode)
3089 return got_error_set_errno(errcode,
3090 "pthread_mutex_unlock");
3091 errcode = pthread_join(s->thread, (void **)&thread_err);
3092 if (errcode)
3093 return got_error_set_errno(errcode, "pthread_join");
3094 errcode = pthread_mutex_lock(&tog_mutex);
3095 if (errcode)
3096 return got_error_set_errno(errcode,
3097 "pthread_mutex_lock");
3098 s->thread = 0; //NULL;
3101 if (s->thread_args.repo) {
3102 err = got_repo_close(s->thread_args.repo);
3103 s->thread_args.repo = NULL;
3106 if (s->thread_args.pack_fds) {
3107 const struct got_error *pack_err =
3108 got_repo_pack_fds_close(s->thread_args.pack_fds);
3109 if (err == NULL)
3110 err = pack_err;
3111 s->thread_args.pack_fds = NULL;
3114 if (s->thread_args.graph) {
3115 got_commit_graph_close(s->thread_args.graph);
3116 s->thread_args.graph = NULL;
3119 return err ? err : thread_err;
3122 static const struct got_error *
3123 close_log_view(struct tog_view *view)
3125 const struct got_error *err = NULL;
3126 struct tog_log_view_state *s = &view->state.log;
3127 int errcode;
3129 err = stop_log_thread(s);
3131 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3132 if (errcode && err == NULL)
3133 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3135 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3136 if (errcode && err == NULL)
3137 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3139 free_commits(&s->limit_commits);
3140 free_commits(&s->real_commits);
3141 free(s->in_repo_path);
3142 s->in_repo_path = NULL;
3143 free(s->start_id);
3144 s->start_id = NULL;
3145 free(s->head_ref_name);
3146 s->head_ref_name = NULL;
3147 return err;
3151 * We use two queues to implement the limit feature: first consists of
3152 * commits matching the current limit_regex; second is the real queue
3153 * of all known commits (real_commits). When the user starts limiting,
3154 * we swap queues such that all movement and displaying functionality
3155 * works with very slight change.
3157 static const struct got_error *
3158 limit_log_view(struct tog_view *view)
3160 struct tog_log_view_state *s = &view->state.log;
3161 struct commit_queue_entry *entry;
3162 struct tog_view *v = view;
3163 const struct got_error *err = NULL;
3164 char pattern[1024];
3165 int ret;
3167 if (view_is_hsplit_top(view))
3168 v = view->child;
3169 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3170 v = view->parent;
3172 /* Get the pattern */
3173 wmove(v->window, v->nlines - 1, 0);
3174 wclrtoeol(v->window);
3175 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3176 nodelay(v->window, FALSE);
3177 nocbreak();
3178 echo();
3179 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3180 cbreak();
3181 noecho();
3182 nodelay(v->window, TRUE);
3183 if (ret == ERR)
3184 return NULL;
3186 if (*pattern == '\0') {
3188 * Safety measure for the situation where the user
3189 * resets limit without previously limiting anything.
3191 if (!s->limit_view)
3192 return NULL;
3195 * User could have pressed Ctrl+L, which refreshed the
3196 * commit queues, it means we can't save previously
3197 * (before limit took place) displayed entries,
3198 * because they would point to already free'ed memory,
3199 * so we are forced to always select first entry of
3200 * the queue.
3202 s->commits = &s->real_commits;
3203 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3204 s->selected_entry = s->first_displayed_entry;
3205 s->selected = 0;
3206 s->limit_view = 0;
3208 return NULL;
3211 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3212 return NULL;
3214 s->limit_view = 1;
3216 /* Clear the screen while loading limit view */
3217 s->first_displayed_entry = NULL;
3218 s->last_displayed_entry = NULL;
3219 s->selected_entry = NULL;
3220 s->commits = &s->limit_commits;
3222 /* Prepare limit queue for new search */
3223 free_commits(&s->limit_commits);
3224 s->limit_commits.ncommits = 0;
3226 /* First process commits, which are in queue already */
3227 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3228 int have_match = 0;
3230 err = match_commit(&have_match, entry->id,
3231 entry->commit, &s->limit_regex);
3232 if (err)
3233 return err;
3235 if (have_match) {
3236 struct commit_queue_entry *matched;
3238 matched = alloc_commit_queue_entry(entry->commit,
3239 entry->id);
3240 if (matched == NULL) {
3241 err = got_error_from_errno(
3242 "alloc_commit_queue_entry");
3243 break;
3245 matched->commit = entry->commit;
3246 got_object_commit_retain(entry->commit);
3248 matched->idx = s->limit_commits.ncommits;
3249 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3250 matched, entry);
3251 s->limit_commits.ncommits++;
3255 /* Second process all the commits, until we fill the screen */
3256 if (s->limit_commits.ncommits < view->nlines - 1 &&
3257 !s->thread_args.log_complete) {
3258 s->thread_args.commits_needed +=
3259 view->nlines - s->limit_commits.ncommits - 1;
3260 err = trigger_log_thread(view, 1);
3261 if (err)
3262 return err;
3265 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3266 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3267 s->selected = 0;
3269 return NULL;
3272 static const struct got_error *
3273 search_start_log_view(struct tog_view *view)
3275 struct tog_log_view_state *s = &view->state.log;
3277 s->matched_entry = NULL;
3278 s->search_entry = NULL;
3279 return NULL;
3282 static const struct got_error *
3283 search_next_log_view(struct tog_view *view)
3285 const struct got_error *err = NULL;
3286 struct tog_log_view_state *s = &view->state.log;
3287 struct commit_queue_entry *entry;
3289 /* Display progress update in log view. */
3290 show_log_view(view);
3291 update_panels();
3292 doupdate();
3294 if (s->search_entry) {
3295 int errcode, ch;
3296 errcode = pthread_mutex_unlock(&tog_mutex);
3297 if (errcode)
3298 return got_error_set_errno(errcode,
3299 "pthread_mutex_unlock");
3300 ch = wgetch(view->window);
3301 errcode = pthread_mutex_lock(&tog_mutex);
3302 if (errcode)
3303 return got_error_set_errno(errcode,
3304 "pthread_mutex_lock");
3305 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3306 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3307 return NULL;
3309 if (view->searching == TOG_SEARCH_FORWARD)
3310 entry = TAILQ_NEXT(s->search_entry, entry);
3311 else
3312 entry = TAILQ_PREV(s->search_entry,
3313 commit_queue_head, entry);
3314 } else if (s->matched_entry) {
3316 * If the user has moved the cursor after we hit a match,
3317 * the position from where we should continue searching
3318 * might have changed.
3320 if (view->searching == TOG_SEARCH_FORWARD)
3321 entry = TAILQ_NEXT(s->selected_entry, entry);
3322 else
3323 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3324 entry);
3325 } else {
3326 entry = s->selected_entry;
3329 while (1) {
3330 int have_match = 0;
3332 if (entry == NULL) {
3333 if (s->thread_args.log_complete ||
3334 view->searching == TOG_SEARCH_BACKWARD) {
3335 view->search_next_done =
3336 (s->matched_entry == NULL ?
3337 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3338 s->search_entry = NULL;
3339 return NULL;
3342 * Poke the log thread for more commits and return,
3343 * allowing the main loop to make progress. Search
3344 * will resume at s->search_entry once we come back.
3346 s->thread_args.commits_needed++;
3347 return trigger_log_thread(view, 0);
3350 err = match_commit(&have_match, entry->id, entry->commit,
3351 &view->regex);
3352 if (err)
3353 break;
3354 if (have_match) {
3355 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3356 s->matched_entry = entry;
3357 break;
3360 s->search_entry = entry;
3361 if (view->searching == TOG_SEARCH_FORWARD)
3362 entry = TAILQ_NEXT(entry, entry);
3363 else
3364 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3367 if (s->matched_entry) {
3368 int cur = s->selected_entry->idx;
3369 while (cur < s->matched_entry->idx) {
3370 err = input_log_view(NULL, view, KEY_DOWN);
3371 if (err)
3372 return err;
3373 cur++;
3375 while (cur > s->matched_entry->idx) {
3376 err = input_log_view(NULL, view, KEY_UP);
3377 if (err)
3378 return err;
3379 cur--;
3383 s->search_entry = NULL;
3385 return NULL;
3388 static const struct got_error *
3389 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3390 struct got_repository *repo, const char *head_ref_name,
3391 const char *in_repo_path, int log_branches)
3393 const struct got_error *err = NULL;
3394 struct tog_log_view_state *s = &view->state.log;
3395 struct got_repository *thread_repo = NULL;
3396 struct got_commit_graph *thread_graph = NULL;
3397 int errcode;
3399 if (in_repo_path != s->in_repo_path) {
3400 free(s->in_repo_path);
3401 s->in_repo_path = strdup(in_repo_path);
3402 if (s->in_repo_path == NULL)
3403 return got_error_from_errno("strdup");
3406 /* The commit queue only contains commits being displayed. */
3407 TAILQ_INIT(&s->real_commits.head);
3408 s->real_commits.ncommits = 0;
3409 s->commits = &s->real_commits;
3411 TAILQ_INIT(&s->limit_commits.head);
3412 s->limit_view = 0;
3413 s->limit_commits.ncommits = 0;
3415 s->repo = repo;
3416 if (head_ref_name) {
3417 s->head_ref_name = strdup(head_ref_name);
3418 if (s->head_ref_name == NULL) {
3419 err = got_error_from_errno("strdup");
3420 goto done;
3423 s->start_id = got_object_id_dup(start_id);
3424 if (s->start_id == NULL) {
3425 err = got_error_from_errno("got_object_id_dup");
3426 goto done;
3428 s->log_branches = log_branches;
3429 s->use_committer = 1;
3431 STAILQ_INIT(&s->colors);
3432 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3433 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3434 get_color_value("TOG_COLOR_COMMIT"));
3435 if (err)
3436 goto done;
3437 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3438 get_color_value("TOG_COLOR_AUTHOR"));
3439 if (err) {
3440 free_colors(&s->colors);
3441 goto done;
3443 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3444 get_color_value("TOG_COLOR_DATE"));
3445 if (err) {
3446 free_colors(&s->colors);
3447 goto done;
3451 view->show = show_log_view;
3452 view->input = input_log_view;
3453 view->resize = resize_log_view;
3454 view->close = close_log_view;
3455 view->search_start = search_start_log_view;
3456 view->search_next = search_next_log_view;
3458 if (s->thread_args.pack_fds == NULL) {
3459 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3460 if (err)
3461 goto done;
3463 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3464 s->thread_args.pack_fds);
3465 if (err)
3466 goto done;
3467 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3468 !s->log_branches);
3469 if (err)
3470 goto done;
3471 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3472 s->repo, NULL, NULL);
3473 if (err)
3474 goto done;
3476 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3477 if (errcode) {
3478 err = got_error_set_errno(errcode, "pthread_cond_init");
3479 goto done;
3481 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3482 if (errcode) {
3483 err = got_error_set_errno(errcode, "pthread_cond_init");
3484 goto done;
3487 s->thread_args.commits_needed = view->nlines;
3488 s->thread_args.graph = thread_graph;
3489 s->thread_args.real_commits = &s->real_commits;
3490 s->thread_args.limit_commits = &s->limit_commits;
3491 s->thread_args.in_repo_path = s->in_repo_path;
3492 s->thread_args.start_id = s->start_id;
3493 s->thread_args.repo = thread_repo;
3494 s->thread_args.log_complete = 0;
3495 s->thread_args.quit = &s->quit;
3496 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3497 s->thread_args.selected_entry = &s->selected_entry;
3498 s->thread_args.searching = &view->searching;
3499 s->thread_args.search_next_done = &view->search_next_done;
3500 s->thread_args.regex = &view->regex;
3501 s->thread_args.limiting = &s->limit_view;
3502 s->thread_args.limit_regex = &s->limit_regex;
3503 s->thread_args.limit_commits = &s->limit_commits;
3504 done:
3505 if (err)
3506 close_log_view(view);
3507 return err;
3510 static const struct got_error *
3511 show_log_view(struct tog_view *view)
3513 const struct got_error *err;
3514 struct tog_log_view_state *s = &view->state.log;
3516 if (s->thread == 0) { //NULL) {
3517 int errcode = pthread_create(&s->thread, NULL, log_thread,
3518 &s->thread_args);
3519 if (errcode)
3520 return got_error_set_errno(errcode, "pthread_create");
3521 if (s->thread_args.commits_needed > 0) {
3522 err = trigger_log_thread(view, 1);
3523 if (err)
3524 return err;
3528 return draw_commits(view);
3531 static void
3532 log_move_cursor_up(struct tog_view *view, int page, int home)
3534 struct tog_log_view_state *s = &view->state.log;
3536 if (s->first_displayed_entry == NULL)
3537 return;
3538 if (s->selected_entry->idx == 0)
3539 view->count = 0;
3541 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3542 || home)
3543 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3545 if (!page && !home && s->selected > 0)
3546 --s->selected;
3547 else
3548 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3550 select_commit(s);
3551 return;
3554 static const struct got_error *
3555 log_move_cursor_down(struct tog_view *view, int page)
3557 struct tog_log_view_state *s = &view->state.log;
3558 const struct got_error *err = NULL;
3559 int eos = view->nlines - 2;
3561 if (s->first_displayed_entry == NULL)
3562 return NULL;
3564 if (s->thread_args.log_complete &&
3565 s->selected_entry->idx >= s->commits->ncommits - 1)
3566 return NULL;
3568 if (view_is_hsplit_top(view))
3569 --eos; /* border consumes the last line */
3571 if (!page) {
3572 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3573 ++s->selected;
3574 else
3575 err = log_scroll_down(view, 1);
3576 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3577 struct commit_queue_entry *entry;
3578 int n;
3580 s->selected = 0;
3581 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3582 s->last_displayed_entry = entry;
3583 for (n = 0; n <= eos; n++) {
3584 if (entry == NULL)
3585 break;
3586 s->first_displayed_entry = entry;
3587 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3589 if (n > 0)
3590 s->selected = n - 1;
3591 } else {
3592 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3593 s->thread_args.log_complete)
3594 s->selected += MIN(page,
3595 s->commits->ncommits - s->selected_entry->idx - 1);
3596 else
3597 err = log_scroll_down(view, page);
3599 if (err)
3600 return err;
3603 * We might necessarily overshoot in horizontal
3604 * splits; if so, select the last displayed commit.
3606 if (s->first_displayed_entry && s->last_displayed_entry) {
3607 s->selected = MIN(s->selected,
3608 s->last_displayed_entry->idx -
3609 s->first_displayed_entry->idx);
3612 select_commit(s);
3614 if (s->thread_args.log_complete &&
3615 s->selected_entry->idx == s->commits->ncommits - 1)
3616 view->count = 0;
3618 return NULL;
3621 static void
3622 view_get_split(struct tog_view *view, int *y, int *x)
3624 *x = 0;
3625 *y = 0;
3627 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3628 if (view->child && view->child->resized_y)
3629 *y = view->child->resized_y;
3630 else if (view->resized_y)
3631 *y = view->resized_y;
3632 else
3633 *y = view_split_begin_y(view->lines);
3634 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3635 if (view->child && view->child->resized_x)
3636 *x = view->child->resized_x;
3637 else if (view->resized_x)
3638 *x = view->resized_x;
3639 else
3640 *x = view_split_begin_x(view->begin_x);
3644 /* Split view horizontally at y and offset view->state->selected line. */
3645 static const struct got_error *
3646 view_init_hsplit(struct tog_view *view, int y)
3648 const struct got_error *err = NULL;
3650 view->nlines = y;
3651 view->ncols = COLS;
3652 err = view_resize(view);
3653 if (err)
3654 return err;
3656 err = offset_selection_down(view);
3658 return err;
3661 static const struct got_error *
3662 log_goto_line(struct tog_view *view, int nlines)
3664 const struct got_error *err = NULL;
3665 struct tog_log_view_state *s = &view->state.log;
3666 int g, idx = s->selected_entry->idx;
3668 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3669 return NULL;
3671 g = view->gline;
3672 view->gline = 0;
3674 if (g >= s->first_displayed_entry->idx + 1 &&
3675 g <= s->last_displayed_entry->idx + 1 &&
3676 g - s->first_displayed_entry->idx - 1 < nlines) {
3677 s->selected = g - s->first_displayed_entry->idx - 1;
3678 select_commit(s);
3679 return NULL;
3682 if (idx + 1 < g) {
3683 err = log_move_cursor_down(view, g - idx - 1);
3684 if (!err && g > s->selected_entry->idx + 1)
3685 err = log_move_cursor_down(view,
3686 g - s->first_displayed_entry->idx - 1);
3687 if (err)
3688 return err;
3689 } else if (idx + 1 > g)
3690 log_move_cursor_up(view, idx - g + 1, 0);
3692 if (g < nlines && s->first_displayed_entry->idx == 0)
3693 s->selected = g - 1;
3695 select_commit(s);
3696 return NULL;
3700 static void
3701 horizontal_scroll_input(struct tog_view *view, int ch)
3704 switch (ch) {
3705 case KEY_LEFT:
3706 case 'h':
3707 view->x -= MIN(view->x, 2);
3708 if (view->x <= 0)
3709 view->count = 0;
3710 break;
3711 case KEY_RIGHT:
3712 case 'l':
3713 if (view->x + view->ncols / 2 < view->maxx)
3714 view->x += 2;
3715 else
3716 view->count = 0;
3717 break;
3718 case '0':
3719 view->x = 0;
3720 break;
3721 case '$':
3722 view->x = MAX(view->maxx - view->ncols / 2, 0);
3723 view->count = 0;
3724 break;
3725 default:
3726 break;
3730 static const struct got_error *
3731 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3733 const struct got_error *err = NULL;
3734 struct tog_log_view_state *s = &view->state.log;
3735 int eos, nscroll;
3737 if (s->thread_args.load_all) {
3738 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3739 s->thread_args.load_all = 0;
3740 else if (s->thread_args.log_complete) {
3741 err = log_move_cursor_down(view, s->commits->ncommits);
3742 s->thread_args.load_all = 0;
3744 if (err)
3745 return err;
3748 eos = nscroll = view->nlines - 1;
3749 if (view_is_hsplit_top(view))
3750 --eos; /* border */
3752 if (view->gline)
3753 return log_goto_line(view, eos);
3755 switch (ch) {
3756 case '&':
3757 err = limit_log_view(view);
3758 break;
3759 case 'q':
3760 s->quit = 1;
3761 break;
3762 case '0':
3763 case '$':
3764 case KEY_RIGHT:
3765 case 'l':
3766 case KEY_LEFT:
3767 case 'h':
3768 horizontal_scroll_input(view, ch);
3769 break;
3770 case 'k':
3771 case KEY_UP:
3772 case '<':
3773 case ',':
3774 case CTRL('p'):
3775 log_move_cursor_up(view, 0, 0);
3776 break;
3777 case 'g':
3778 case '=':
3779 case KEY_HOME:
3780 log_move_cursor_up(view, 0, 1);
3781 view->count = 0;
3782 break;
3783 case CTRL('u'):
3784 case 'u':
3785 nscroll /= 2;
3786 /* FALL THROUGH */
3787 case KEY_PPAGE:
3788 case CTRL('b'):
3789 case 'b':
3790 log_move_cursor_up(view, nscroll, 0);
3791 break;
3792 case 'j':
3793 case KEY_DOWN:
3794 case '>':
3795 case '.':
3796 case CTRL('n'):
3797 err = log_move_cursor_down(view, 0);
3798 break;
3799 case '@':
3800 s->use_committer = !s->use_committer;
3801 view->action = s->use_committer ?
3802 "show committer" : "show commit author";
3803 break;
3804 case 'G':
3805 case '*':
3806 case KEY_END: {
3807 /* We don't know yet how many commits, so we're forced to
3808 * traverse them all. */
3809 view->count = 0;
3810 s->thread_args.load_all = 1;
3811 if (!s->thread_args.log_complete)
3812 return trigger_log_thread(view, 0);
3813 err = log_move_cursor_down(view, s->commits->ncommits);
3814 s->thread_args.load_all = 0;
3815 break;
3817 case CTRL('d'):
3818 case 'd':
3819 nscroll /= 2;
3820 /* FALL THROUGH */
3821 case KEY_NPAGE:
3822 case CTRL('f'):
3823 case 'f':
3824 case ' ':
3825 err = log_move_cursor_down(view, nscroll);
3826 break;
3827 case KEY_RESIZE:
3828 if (s->selected > view->nlines - 2)
3829 s->selected = view->nlines - 2;
3830 if (s->selected > s->commits->ncommits - 1)
3831 s->selected = s->commits->ncommits - 1;
3832 select_commit(s);
3833 if (s->commits->ncommits < view->nlines - 1 &&
3834 !s->thread_args.log_complete) {
3835 s->thread_args.commits_needed += (view->nlines - 1) -
3836 s->commits->ncommits;
3837 err = trigger_log_thread(view, 1);
3839 break;
3840 case KEY_ENTER:
3841 case '\r':
3842 view->count = 0;
3843 if (s->selected_entry == NULL)
3844 break;
3845 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3846 break;
3847 case 'T':
3848 view->count = 0;
3849 if (s->selected_entry == NULL)
3850 break;
3851 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3852 break;
3853 case KEY_BACKSPACE:
3854 case CTRL('l'):
3855 case 'B':
3856 view->count = 0;
3857 if (ch == KEY_BACKSPACE &&
3858 got_path_is_root_dir(s->in_repo_path))
3859 break;
3860 err = stop_log_thread(s);
3861 if (err)
3862 return err;
3863 if (ch == KEY_BACKSPACE) {
3864 char *parent_path;
3865 err = got_path_dirname(&parent_path, s->in_repo_path);
3866 if (err)
3867 return err;
3868 free(s->in_repo_path);
3869 s->in_repo_path = parent_path;
3870 s->thread_args.in_repo_path = s->in_repo_path;
3871 } else if (ch == CTRL('l')) {
3872 struct got_object_id *start_id;
3873 err = got_repo_match_object_id(&start_id, NULL,
3874 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3875 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3876 if (err) {
3877 if (s->head_ref_name == NULL ||
3878 err->code != GOT_ERR_NOT_REF)
3879 return err;
3880 /* Try to cope with deleted references. */
3881 free(s->head_ref_name);
3882 s->head_ref_name = NULL;
3883 err = got_repo_match_object_id(&start_id,
3884 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
3885 &tog_refs, s->repo);
3886 if (err)
3887 return err;
3889 free(s->start_id);
3890 s->start_id = start_id;
3891 s->thread_args.start_id = s->start_id;
3892 } else /* 'B' */
3893 s->log_branches = !s->log_branches;
3895 if (s->thread_args.pack_fds == NULL) {
3896 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3897 if (err)
3898 return err;
3900 err = got_repo_open(&s->thread_args.repo,
3901 got_repo_get_path(s->repo), NULL,
3902 s->thread_args.pack_fds);
3903 if (err)
3904 return err;
3905 tog_free_refs();
3906 err = tog_load_refs(s->repo, 0);
3907 if (err)
3908 return err;
3909 err = got_commit_graph_open(&s->thread_args.graph,
3910 s->in_repo_path, !s->log_branches);
3911 if (err)
3912 return err;
3913 err = got_commit_graph_iter_start(s->thread_args.graph,
3914 s->start_id, s->repo, NULL, NULL);
3915 if (err)
3916 return err;
3917 free_commits(&s->real_commits);
3918 free_commits(&s->limit_commits);
3919 s->first_displayed_entry = NULL;
3920 s->last_displayed_entry = NULL;
3921 s->selected_entry = NULL;
3922 s->selected = 0;
3923 s->thread_args.log_complete = 0;
3924 s->quit = 0;
3925 s->thread_args.commits_needed = view->lines;
3926 s->matched_entry = NULL;
3927 s->search_entry = NULL;
3928 view->offset = 0;
3929 break;
3930 case 'R':
3931 view->count = 0;
3932 err = view_request_new(new_view, view, TOG_VIEW_REF);
3933 break;
3934 default:
3935 view->count = 0;
3936 break;
3939 return err;
3942 static const struct got_error *
3943 apply_unveil(const char *repo_path, const char *worktree_path)
3945 const struct got_error *error;
3947 #ifdef PROFILE
3948 if (unveil("gmon.out", "rwc") != 0)
3949 return got_error_from_errno2("unveil", "gmon.out");
3950 #endif
3951 if (repo_path && unveil(repo_path, "r") != 0)
3952 return got_error_from_errno2("unveil", repo_path);
3954 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3955 return got_error_from_errno2("unveil", worktree_path);
3957 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3958 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3960 error = got_privsep_unveil_exec_helpers();
3961 if (error != NULL)
3962 return error;
3964 if (unveil(NULL, NULL) != 0)
3965 return got_error_from_errno("unveil");
3967 return NULL;
3970 static void
3971 init_curses(void)
3974 * Override default signal handlers before starting ncurses.
3975 * This should prevent ncurses from installing its own
3976 * broken cleanup() signal handler.
3978 signal(SIGWINCH, tog_sigwinch);
3979 signal(SIGPIPE, tog_sigpipe);
3980 signal(SIGCONT, tog_sigcont);
3981 signal(SIGINT, tog_sigint);
3982 signal(SIGTERM, tog_sigterm);
3984 initscr();
3985 cbreak();
3986 halfdelay(1); /* Do fast refresh while initial view is loading. */
3987 noecho();
3988 nonl();
3989 intrflush(stdscr, FALSE);
3990 keypad(stdscr, TRUE);
3991 curs_set(0);
3992 if (getenv("TOG_COLORS") != NULL) {
3993 start_color();
3994 use_default_colors();
3998 static const struct got_error *
3999 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4000 struct got_repository *repo, struct got_worktree *worktree)
4002 const struct got_error *err = NULL;
4004 if (argc == 0) {
4005 *in_repo_path = strdup("/");
4006 if (*in_repo_path == NULL)
4007 return got_error_from_errno("strdup");
4008 return NULL;
4011 if (worktree) {
4012 const char *prefix = got_worktree_get_path_prefix(worktree);
4013 char *p;
4015 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4016 if (err)
4017 return err;
4018 if (asprintf(in_repo_path, "%s%s%s", prefix,
4019 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4020 p) == -1) {
4021 err = got_error_from_errno("asprintf");
4022 *in_repo_path = NULL;
4024 free(p);
4025 } else
4026 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4028 return err;
4031 static const struct got_error *
4032 cmd_log(int argc, char *argv[])
4034 const struct got_error *error;
4035 struct got_repository *repo = NULL;
4036 struct got_worktree *worktree = NULL;
4037 struct got_object_id *start_id = NULL;
4038 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4039 char *start_commit = NULL, *label = NULL;
4040 struct got_reference *ref = NULL;
4041 const char *head_ref_name = NULL;
4042 int ch, log_branches = 0;
4043 struct tog_view *view;
4044 int *pack_fds = NULL;
4046 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4047 switch (ch) {
4048 case 'b':
4049 log_branches = 1;
4050 break;
4051 case 'c':
4052 start_commit = optarg;
4053 break;
4054 case 'r':
4055 repo_path = realpath(optarg, NULL);
4056 if (repo_path == NULL)
4057 return got_error_from_errno2("realpath",
4058 optarg);
4059 break;
4060 default:
4061 usage_log();
4062 /* NOTREACHED */
4066 argc -= optind;
4067 argv += optind;
4069 if (argc > 1)
4070 usage_log();
4072 error = got_repo_pack_fds_open(&pack_fds);
4073 if (error != NULL)
4074 goto done;
4076 if (repo_path == NULL) {
4077 cwd = getcwd(NULL, 0);
4078 if (cwd == NULL)
4079 return got_error_from_errno("getcwd");
4080 error = got_worktree_open(&worktree, cwd);
4081 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4082 goto done;
4083 if (worktree)
4084 repo_path =
4085 strdup(got_worktree_get_repo_path(worktree));
4086 else
4087 repo_path = strdup(cwd);
4088 if (repo_path == NULL) {
4089 error = got_error_from_errno("strdup");
4090 goto done;
4094 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4095 if (error != NULL)
4096 goto done;
4098 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4099 repo, worktree);
4100 if (error)
4101 goto done;
4103 init_curses();
4105 error = apply_unveil(got_repo_get_path(repo),
4106 worktree ? got_worktree_get_root_path(worktree) : NULL);
4107 if (error)
4108 goto done;
4110 /* already loaded by tog_log_with_path()? */
4111 if (TAILQ_EMPTY(&tog_refs)) {
4112 error = tog_load_refs(repo, 0);
4113 if (error)
4114 goto done;
4117 if (start_commit == NULL) {
4118 error = got_repo_match_object_id(&start_id, &label,
4119 worktree ? got_worktree_get_head_ref_name(worktree) :
4120 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4121 if (error)
4122 goto done;
4123 head_ref_name = label;
4124 } else {
4125 error = got_ref_open(&ref, repo, start_commit, 0);
4126 if (error == NULL)
4127 head_ref_name = got_ref_get_name(ref);
4128 else if (error->code != GOT_ERR_NOT_REF)
4129 goto done;
4130 error = got_repo_match_object_id(&start_id, NULL,
4131 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4132 if (error)
4133 goto done;
4136 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4137 if (view == NULL) {
4138 error = got_error_from_errno("view_open");
4139 goto done;
4141 error = open_log_view(view, start_id, repo, head_ref_name,
4142 in_repo_path, log_branches);
4143 if (error)
4144 goto done;
4145 if (worktree) {
4146 /* Release work tree lock. */
4147 got_worktree_close(worktree);
4148 worktree = NULL;
4150 error = view_loop(view);
4151 done:
4152 free(in_repo_path);
4153 free(repo_path);
4154 free(cwd);
4155 free(start_id);
4156 free(label);
4157 if (ref)
4158 got_ref_close(ref);
4159 if (repo) {
4160 const struct got_error *close_err = got_repo_close(repo);
4161 if (error == NULL)
4162 error = close_err;
4164 if (worktree)
4165 got_worktree_close(worktree);
4166 if (pack_fds) {
4167 const struct got_error *pack_err =
4168 got_repo_pack_fds_close(pack_fds);
4169 if (error == NULL)
4170 error = pack_err;
4172 tog_free_refs();
4173 return error;
4176 __dead static void
4177 usage_diff(void)
4179 endwin();
4180 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4181 "object1 object2\n", getprogname());
4182 exit(1);
4185 static int
4186 match_line(const char *line, regex_t *regex, size_t nmatch,
4187 regmatch_t *regmatch)
4189 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4192 static struct tog_color *
4193 match_color(struct tog_colors *colors, const char *line)
4195 struct tog_color *tc = NULL;
4197 STAILQ_FOREACH(tc, colors, entry) {
4198 if (match_line(line, &tc->regex, 0, NULL))
4199 return tc;
4202 return NULL;
4205 static const struct got_error *
4206 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4207 WINDOW *window, int skipcol, regmatch_t *regmatch)
4209 const struct got_error *err = NULL;
4210 char *exstr = NULL;
4211 wchar_t *wline = NULL;
4212 int rme, rms, n, width, scrollx;
4213 int width0 = 0, width1 = 0, width2 = 0;
4214 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4216 *wtotal = 0;
4218 rms = regmatch->rm_so;
4219 rme = regmatch->rm_eo;
4221 err = expand_tab(&exstr, line);
4222 if (err)
4223 return err;
4225 /* Split the line into 3 segments, according to match offsets. */
4226 seg0 = strndup(exstr, rms);
4227 if (seg0 == NULL) {
4228 err = got_error_from_errno("strndup");
4229 goto done;
4231 seg1 = strndup(exstr + rms, rme - rms);
4232 if (seg1 == NULL) {
4233 err = got_error_from_errno("strndup");
4234 goto done;
4236 seg2 = strdup(exstr + rme);
4237 if (seg2 == NULL) {
4238 err = got_error_from_errno("strndup");
4239 goto done;
4242 /* draw up to matched token if we haven't scrolled past it */
4243 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4244 col_tab_align, 1);
4245 if (err)
4246 goto done;
4247 n = MAX(width0 - skipcol, 0);
4248 if (n) {
4249 free(wline);
4250 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4251 wlimit, col_tab_align, 1);
4252 if (err)
4253 goto done;
4254 waddwstr(window, &wline[scrollx]);
4255 wlimit -= width;
4256 *wtotal += width;
4259 if (wlimit > 0) {
4260 int i = 0, w = 0;
4261 size_t wlen;
4263 free(wline);
4264 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4265 col_tab_align, 1);
4266 if (err)
4267 goto done;
4268 wlen = wcslen(wline);
4269 while (i < wlen) {
4270 width = wcwidth(wline[i]);
4271 if (width == -1) {
4272 /* should not happen, tabs are expanded */
4273 err = got_error(GOT_ERR_RANGE);
4274 goto done;
4276 if (width0 + w + width > skipcol)
4277 break;
4278 w += width;
4279 i++;
4281 /* draw (visible part of) matched token (if scrolled into it) */
4282 if (width1 - w > 0) {
4283 wattron(window, A_STANDOUT);
4284 waddwstr(window, &wline[i]);
4285 wattroff(window, A_STANDOUT);
4286 wlimit -= (width1 - w);
4287 *wtotal += (width1 - w);
4291 if (wlimit > 0) { /* draw rest of line */
4292 free(wline);
4293 if (skipcol > width0 + width1) {
4294 err = format_line(&wline, &width2, &scrollx, seg2,
4295 skipcol - (width0 + width1), wlimit,
4296 col_tab_align, 1);
4297 if (err)
4298 goto done;
4299 waddwstr(window, &wline[scrollx]);
4300 } else {
4301 err = format_line(&wline, &width2, NULL, seg2, 0,
4302 wlimit, col_tab_align, 1);
4303 if (err)
4304 goto done;
4305 waddwstr(window, wline);
4307 *wtotal += width2;
4309 done:
4310 free(wline);
4311 free(exstr);
4312 free(seg0);
4313 free(seg1);
4314 free(seg2);
4315 return err;
4318 static int
4319 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4321 FILE *f = NULL;
4322 int *eof, *first, *selected;
4324 if (view->type == TOG_VIEW_DIFF) {
4325 struct tog_diff_view_state *s = &view->state.diff;
4327 first = &s->first_displayed_line;
4328 selected = first;
4329 eof = &s->eof;
4330 f = s->f;
4331 } else if (view->type == TOG_VIEW_HELP) {
4332 struct tog_help_view_state *s = &view->state.help;
4334 first = &s->first_displayed_line;
4335 selected = first;
4336 eof = &s->eof;
4337 f = s->f;
4338 } else if (view->type == TOG_VIEW_BLAME) {
4339 struct tog_blame_view_state *s = &view->state.blame;
4341 first = &s->first_displayed_line;
4342 selected = &s->selected_line;
4343 eof = &s->eof;
4344 f = s->blame.f;
4345 } else
4346 return 0;
4348 /* Center gline in the middle of the page like vi(1). */
4349 if (*lineno < view->gline - (view->nlines - 3) / 2)
4350 return 0;
4351 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4352 rewind(f);
4353 *eof = 0;
4354 *first = 1;
4355 *lineno = 0;
4356 *nprinted = 0;
4357 return 0;
4360 *selected = view->gline <= (view->nlines - 3) / 2 ?
4361 view->gline : (view->nlines - 3) / 2 + 1;
4362 view->gline = 0;
4364 return 1;
4367 static const struct got_error *
4368 draw_file(struct tog_view *view, const char *header)
4370 struct tog_diff_view_state *s = &view->state.diff;
4371 regmatch_t *regmatch = &view->regmatch;
4372 const struct got_error *err;
4373 int nprinted = 0;
4374 char *line;
4375 size_t linesize = 0;
4376 ssize_t linelen;
4377 wchar_t *wline;
4378 int width;
4379 int max_lines = view->nlines;
4380 int nlines = s->nlines;
4381 off_t line_offset;
4383 s->lineno = s->first_displayed_line - 1;
4384 line_offset = s->lines[s->first_displayed_line - 1].offset;
4385 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4386 return got_error_from_errno("fseek");
4388 werase(view->window);
4390 if (view->gline > s->nlines - 1)
4391 view->gline = s->nlines - 1;
4393 if (header) {
4394 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4395 1 : view->gline - (view->nlines - 3) / 2 :
4396 s->lineno + s->selected_line;
4398 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4399 return got_error_from_errno("asprintf");
4400 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4401 0, 0);
4402 free(line);
4403 if (err)
4404 return err;
4406 if (view_needs_focus_indication(view))
4407 wstandout(view->window);
4408 waddwstr(view->window, wline);
4409 free(wline);
4410 wline = NULL;
4411 while (width++ < view->ncols)
4412 waddch(view->window, ' ');
4413 if (view_needs_focus_indication(view))
4414 wstandend(view->window);
4416 if (max_lines <= 1)
4417 return NULL;
4418 max_lines--;
4421 s->eof = 0;
4422 view->maxx = 0;
4423 line = NULL;
4424 while (max_lines > 0 && nprinted < max_lines) {
4425 enum got_diff_line_type linetype;
4426 attr_t attr = 0;
4428 linelen = getline(&line, &linesize, s->f);
4429 if (linelen == -1) {
4430 if (feof(s->f)) {
4431 s->eof = 1;
4432 break;
4434 free(line);
4435 return got_ferror(s->f, GOT_ERR_IO);
4438 if (++s->lineno < s->first_displayed_line)
4439 continue;
4440 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4441 continue;
4442 if (s->lineno == view->hiline)
4443 attr = A_STANDOUT;
4445 /* Set view->maxx based on full line length. */
4446 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4447 view->x ? 1 : 0);
4448 if (err) {
4449 free(line);
4450 return err;
4452 view->maxx = MAX(view->maxx, width);
4453 free(wline);
4454 wline = NULL;
4456 linetype = s->lines[s->lineno].type;
4457 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4458 linetype < GOT_DIFF_LINE_CONTEXT)
4459 attr |= COLOR_PAIR(linetype);
4460 if (attr)
4461 wattron(view->window, attr);
4462 if (s->first_displayed_line + nprinted == s->matched_line &&
4463 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4464 err = add_matched_line(&width, line, view->ncols, 0,
4465 view->window, view->x, regmatch);
4466 if (err) {
4467 free(line);
4468 return err;
4470 } else {
4471 int skip;
4472 err = format_line(&wline, &width, &skip, line,
4473 view->x, view->ncols, 0, view->x ? 1 : 0);
4474 if (err) {
4475 free(line);
4476 return err;
4478 waddwstr(view->window, &wline[skip]);
4479 free(wline);
4480 wline = NULL;
4482 if (s->lineno == view->hiline) {
4483 /* highlight full gline length */
4484 while (width++ < view->ncols)
4485 waddch(view->window, ' ');
4486 } else {
4487 if (width <= view->ncols - 1)
4488 waddch(view->window, '\n');
4490 if (attr)
4491 wattroff(view->window, attr);
4492 if (++nprinted == 1)
4493 s->first_displayed_line = s->lineno;
4495 free(line);
4496 if (nprinted >= 1)
4497 s->last_displayed_line = s->first_displayed_line +
4498 (nprinted - 1);
4499 else
4500 s->last_displayed_line = s->first_displayed_line;
4502 view_border(view);
4504 if (s->eof) {
4505 while (nprinted < view->nlines) {
4506 waddch(view->window, '\n');
4507 nprinted++;
4510 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4511 view->ncols, 0, 0);
4512 if (err) {
4513 return err;
4516 wstandout(view->window);
4517 waddwstr(view->window, wline);
4518 free(wline);
4519 wline = NULL;
4520 wstandend(view->window);
4523 return NULL;
4526 static char *
4527 get_datestr(time_t *time, char *datebuf)
4529 struct tm mytm, *tm;
4530 char *p, *s;
4532 tm = gmtime_r(time, &mytm);
4533 if (tm == NULL)
4534 return NULL;
4535 s = asctime_r(tm, datebuf);
4536 if (s == NULL)
4537 return NULL;
4538 p = strchr(s, '\n');
4539 if (p)
4540 *p = '\0';
4541 return s;
4544 static const struct got_error *
4545 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4546 off_t off, uint8_t type)
4548 struct got_diff_line *p;
4550 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4551 if (p == NULL)
4552 return got_error_from_errno("reallocarray");
4553 *lines = p;
4554 (*lines)[*nlines].offset = off;
4555 (*lines)[*nlines].type = type;
4556 (*nlines)++;
4558 return NULL;
4561 static const struct got_error *
4562 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4563 struct got_diff_line *s_lines, size_t s_nlines)
4565 struct got_diff_line *p;
4566 char buf[BUFSIZ];
4567 size_t i, r;
4569 if (fseeko(src, 0L, SEEK_SET) == -1)
4570 return got_error_from_errno("fseeko");
4572 for (;;) {
4573 r = fread(buf, 1, sizeof(buf), src);
4574 if (r == 0) {
4575 if (ferror(src))
4576 return got_error_from_errno("fread");
4577 if (feof(src))
4578 break;
4580 if (fwrite(buf, 1, r, dst) != r)
4581 return got_ferror(dst, GOT_ERR_IO);
4585 * The diff driver initialises the first line at offset zero when the
4586 * array isn't prepopulated, skip it; we already have it in *d_lines.
4588 for (i = 1; i < s_nlines; ++i)
4589 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4591 --s_nlines;
4593 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4594 if (p == NULL) {
4595 /* d_lines is freed in close_diff_view() */
4596 return got_error_from_errno("reallocarray");
4599 *d_lines = p;
4601 memcpy(*d_lines + *d_nlines, s_lines + 1, s_nlines * sizeof(*s_lines));
4602 *d_nlines += s_nlines;
4604 return NULL;
4607 static const struct got_error *
4608 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4609 struct got_object_id *commit_id, struct got_reflist_head *refs,
4610 struct got_repository *repo, int ignore_ws, int force_text_diff,
4611 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4613 const struct got_error *err = NULL;
4614 char datebuf[26], *datestr;
4615 struct got_commit_object *commit;
4616 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4617 time_t committer_time;
4618 const char *author, *committer;
4619 char *refs_str = NULL;
4620 struct got_pathlist_entry *pe;
4621 off_t outoff = 0;
4622 int n;
4624 if (refs) {
4625 err = build_refs_str(&refs_str, refs, commit_id, repo);
4626 if (err)
4627 return err;
4630 err = got_object_open_as_commit(&commit, repo, commit_id);
4631 if (err)
4632 return err;
4634 err = got_object_id_str(&id_str, commit_id);
4635 if (err) {
4636 err = got_error_from_errno("got_object_id_str");
4637 goto done;
4640 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4641 if (err)
4642 goto done;
4644 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4645 refs_str ? refs_str : "", refs_str ? ")" : "");
4646 if (n < 0) {
4647 err = got_error_from_errno("fprintf");
4648 goto done;
4650 outoff += n;
4651 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4652 if (err)
4653 goto done;
4655 n = fprintf(outfile, "from: %s\n",
4656 got_object_commit_get_author(commit));
4657 if (n < 0) {
4658 err = got_error_from_errno("fprintf");
4659 goto done;
4661 outoff += n;
4662 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4663 if (err)
4664 goto done;
4666 author = got_object_commit_get_author(commit);
4667 committer = got_object_commit_get_committer(commit);
4668 if (strcmp(author, committer) != 0) {
4669 n = fprintf(outfile, "via: %s\n", committer);
4670 if (n < 0) {
4671 err = got_error_from_errno("fprintf");
4672 goto done;
4674 outoff += n;
4675 err = add_line_metadata(lines, nlines, outoff,
4676 GOT_DIFF_LINE_AUTHOR);
4677 if (err)
4678 goto done;
4680 committer_time = got_object_commit_get_committer_time(commit);
4681 datestr = get_datestr(&committer_time, datebuf);
4682 if (datestr) {
4683 n = fprintf(outfile, "date: %s UTC\n", datestr);
4684 if (n < 0) {
4685 err = got_error_from_errno("fprintf");
4686 goto done;
4688 outoff += n;
4689 err = add_line_metadata(lines, nlines, outoff,
4690 GOT_DIFF_LINE_DATE);
4691 if (err)
4692 goto done;
4694 if (got_object_commit_get_nparents(commit) > 1) {
4695 const struct got_object_id_queue *parent_ids;
4696 struct got_object_qid *qid;
4697 int pn = 1;
4698 parent_ids = got_object_commit_get_parent_ids(commit);
4699 STAILQ_FOREACH(qid, parent_ids, entry) {
4700 err = got_object_id_str(&id_str, &qid->id);
4701 if (err)
4702 goto done;
4703 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4704 if (n < 0) {
4705 err = got_error_from_errno("fprintf");
4706 goto done;
4708 outoff += n;
4709 err = add_line_metadata(lines, nlines, outoff,
4710 GOT_DIFF_LINE_META);
4711 if (err)
4712 goto done;
4713 free(id_str);
4714 id_str = NULL;
4718 err = got_object_commit_get_logmsg(&logmsg, commit);
4719 if (err)
4720 goto done;
4721 s = logmsg;
4722 while ((line = strsep(&s, "\n")) != NULL) {
4723 n = fprintf(outfile, "%s\n", line);
4724 if (n < 0) {
4725 err = got_error_from_errno("fprintf");
4726 goto done;
4728 outoff += n;
4729 err = add_line_metadata(lines, nlines, outoff,
4730 GOT_DIFF_LINE_LOGMSG);
4731 if (err)
4732 goto done;
4735 TAILQ_FOREACH(pe, dsa->paths, entry) {
4736 struct got_diff_changed_path *cp = pe->data;
4737 int pad = dsa->max_path_len - pe->path_len + 1;
4739 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4740 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4741 dsa->rm_cols + 1, cp->rm);
4742 if (n < 0) {
4743 err = got_error_from_errno("fprintf");
4744 goto done;
4746 outoff += n;
4747 err = add_line_metadata(lines, nlines, outoff,
4748 GOT_DIFF_LINE_CHANGES);
4749 if (err)
4750 goto done;
4753 fputc('\n', outfile);
4754 outoff++;
4755 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4756 if (err)
4757 goto done;
4759 n = fprintf(outfile,
4760 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4761 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4762 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4763 if (n < 0) {
4764 err = got_error_from_errno("fprintf");
4765 goto done;
4767 outoff += n;
4768 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4769 if (err)
4770 goto done;
4772 fputc('\n', outfile);
4773 outoff++;
4774 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4775 done:
4776 free(id_str);
4777 free(logmsg);
4778 free(refs_str);
4779 got_object_commit_close(commit);
4780 if (err) {
4781 free(*lines);
4782 *lines = NULL;
4783 *nlines = 0;
4785 return err;
4788 static const struct got_error *
4789 create_diff(struct tog_diff_view_state *s)
4791 const struct got_error *err = NULL;
4792 FILE *f = NULL, *tmp_diff_file = NULL;
4793 int obj_type;
4794 struct got_diff_line *lines = NULL;
4795 struct got_pathlist_head changed_paths;
4797 TAILQ_INIT(&changed_paths);
4799 free(s->lines);
4800 s->lines = malloc(sizeof(*s->lines));
4801 if (s->lines == NULL)
4802 return got_error_from_errno("malloc");
4803 s->nlines = 0;
4805 f = got_opentemp();
4806 if (f == NULL) {
4807 err = got_error_from_errno("got_opentemp");
4808 goto done;
4810 tmp_diff_file = got_opentemp();
4811 if (tmp_diff_file == NULL) {
4812 err = got_error_from_errno("got_opentemp");
4813 goto done;
4815 if (s->f && fclose(s->f) == EOF) {
4816 err = got_error_from_errno("fclose");
4817 goto done;
4819 s->f = f;
4821 if (s->id1)
4822 err = got_object_get_type(&obj_type, s->repo, s->id1);
4823 else
4824 err = got_object_get_type(&obj_type, s->repo, s->id2);
4825 if (err)
4826 goto done;
4828 switch (obj_type) {
4829 case GOT_OBJ_TYPE_BLOB:
4830 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4831 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4832 s->label1, s->label2, tog_diff_algo, s->diff_context,
4833 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
4834 s->f);
4835 break;
4836 case GOT_OBJ_TYPE_TREE:
4837 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4838 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4839 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4840 s->force_text_diff, NULL, s->repo, s->f);
4841 break;
4842 case GOT_OBJ_TYPE_COMMIT: {
4843 const struct got_object_id_queue *parent_ids;
4844 struct got_object_qid *pid;
4845 struct got_commit_object *commit2;
4846 struct got_reflist_head *refs;
4847 size_t nlines = 0;
4848 struct got_diffstat_cb_arg dsa = {
4849 0, 0, 0, 0, 0, 0,
4850 &changed_paths,
4851 s->ignore_whitespace,
4852 s->force_text_diff,
4853 tog_diff_algo
4856 lines = malloc(sizeof(*lines));
4857 if (lines == NULL) {
4858 err = got_error_from_errno("malloc");
4859 goto done;
4862 /* build diff first in tmp file then append to commit info */
4863 err = got_diff_objects_as_commits(&lines, &nlines,
4864 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4865 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4866 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
4867 if (err)
4868 break;
4870 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4871 if (err)
4872 goto done;
4873 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4874 /* Show commit info if we're diffing to a parent/root commit. */
4875 if (s->id1 == NULL) {
4876 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4877 refs, s->repo, s->ignore_whitespace,
4878 s->force_text_diff, &dsa, s->f);
4879 if (err)
4880 goto done;
4881 } else {
4882 parent_ids = got_object_commit_get_parent_ids(commit2);
4883 STAILQ_FOREACH(pid, parent_ids, entry) {
4884 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4885 err = write_commit_info(&s->lines,
4886 &s->nlines, s->id2, refs, s->repo,
4887 s->ignore_whitespace,
4888 s->force_text_diff, &dsa, s->f);
4889 if (err)
4890 goto done;
4891 break;
4895 got_object_commit_close(commit2);
4897 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
4898 lines, nlines);
4899 break;
4901 default:
4902 err = got_error(GOT_ERR_OBJ_TYPE);
4903 break;
4905 done:
4906 free(lines);
4907 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4908 if (s->f && fflush(s->f) != 0 && err == NULL)
4909 err = got_error_from_errno("fflush");
4910 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
4911 err = got_error_from_errno("fclose");
4912 return err;
4915 static void
4916 diff_view_indicate_progress(struct tog_view *view)
4918 mvwaddstr(view->window, 0, 0, "diffing...");
4919 update_panels();
4920 doupdate();
4923 static const struct got_error *
4924 search_start_diff_view(struct tog_view *view)
4926 struct tog_diff_view_state *s = &view->state.diff;
4928 s->matched_line = 0;
4929 return NULL;
4932 static void
4933 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4934 size_t *nlines, int **first, int **last, int **match, int **selected)
4936 struct tog_diff_view_state *s = &view->state.diff;
4938 *f = s->f;
4939 *nlines = s->nlines;
4940 *line_offsets = NULL;
4941 *match = &s->matched_line;
4942 *first = &s->first_displayed_line;
4943 *last = &s->last_displayed_line;
4944 *selected = &s->selected_line;
4947 static const struct got_error *
4948 search_next_view_match(struct tog_view *view)
4950 const struct got_error *err = NULL;
4951 FILE *f;
4952 int lineno;
4953 char *line = NULL;
4954 size_t linesize = 0;
4955 ssize_t linelen;
4956 off_t *line_offsets;
4957 size_t nlines = 0;
4958 int *first, *last, *match, *selected;
4960 if (!view->search_setup)
4961 return got_error_msg(GOT_ERR_NOT_IMPL,
4962 "view search not supported");
4963 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4964 &match, &selected);
4966 if (!view->searching) {
4967 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4968 return NULL;
4971 if (*match) {
4972 if (view->searching == TOG_SEARCH_FORWARD)
4973 lineno = *match + 1;
4974 else
4975 lineno = *match - 1;
4976 } else
4977 lineno = *first - 1 + *selected;
4979 while (1) {
4980 off_t offset;
4982 if (lineno <= 0 || lineno > nlines) {
4983 if (*match == 0) {
4984 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4985 break;
4988 if (view->searching == TOG_SEARCH_FORWARD)
4989 lineno = 1;
4990 else
4991 lineno = nlines;
4994 offset = view->type == TOG_VIEW_DIFF ?
4995 view->state.diff.lines[lineno - 1].offset :
4996 line_offsets[lineno - 1];
4997 if (fseeko(f, offset, SEEK_SET) != 0) {
4998 free(line);
4999 return got_error_from_errno("fseeko");
5001 linelen = getline(&line, &linesize, f);
5002 if (linelen != -1) {
5003 char *exstr;
5004 err = expand_tab(&exstr, line);
5005 if (err)
5006 break;
5007 if (match_line(exstr, &view->regex, 1,
5008 &view->regmatch)) {
5009 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5010 *match = lineno;
5011 free(exstr);
5012 break;
5014 free(exstr);
5016 if (view->searching == TOG_SEARCH_FORWARD)
5017 lineno++;
5018 else
5019 lineno--;
5021 free(line);
5023 if (*match) {
5024 *first = *match;
5025 *selected = 1;
5028 return err;
5031 static const struct got_error *
5032 close_diff_view(struct tog_view *view)
5034 const struct got_error *err = NULL;
5035 struct tog_diff_view_state *s = &view->state.diff;
5037 free(s->id1);
5038 s->id1 = NULL;
5039 free(s->id2);
5040 s->id2 = NULL;
5041 if (s->f && fclose(s->f) == EOF)
5042 err = got_error_from_errno("fclose");
5043 s->f = NULL;
5044 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5045 err = got_error_from_errno("fclose");
5046 s->f1 = NULL;
5047 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5048 err = got_error_from_errno("fclose");
5049 s->f2 = NULL;
5050 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5051 err = got_error_from_errno("close");
5052 s->fd1 = -1;
5053 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5054 err = got_error_from_errno("close");
5055 s->fd2 = -1;
5056 free(s->lines);
5057 s->lines = NULL;
5058 s->nlines = 0;
5059 return err;
5062 static const struct got_error *
5063 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5064 struct got_object_id *id2, const char *label1, const char *label2,
5065 int diff_context, int ignore_whitespace, int force_text_diff,
5066 struct tog_view *parent_view, struct got_repository *repo)
5068 const struct got_error *err;
5069 struct tog_diff_view_state *s = &view->state.diff;
5071 memset(s, 0, sizeof(*s));
5072 s->fd1 = -1;
5073 s->fd2 = -1;
5075 if (id1 != NULL && id2 != NULL) {
5076 int type1, type2;
5077 err = got_object_get_type(&type1, repo, id1);
5078 if (err)
5079 return err;
5080 err = got_object_get_type(&type2, repo, id2);
5081 if (err)
5082 return err;
5084 if (type1 != type2)
5085 return got_error(GOT_ERR_OBJ_TYPE);
5087 s->first_displayed_line = 1;
5088 s->last_displayed_line = view->nlines;
5089 s->selected_line = 1;
5090 s->repo = repo;
5091 s->id1 = id1;
5092 s->id2 = id2;
5093 s->label1 = label1;
5094 s->label2 = label2;
5096 if (id1) {
5097 s->id1 = got_object_id_dup(id1);
5098 if (s->id1 == NULL)
5099 return got_error_from_errno("got_object_id_dup");
5100 } else
5101 s->id1 = NULL;
5103 s->id2 = got_object_id_dup(id2);
5104 if (s->id2 == NULL) {
5105 err = got_error_from_errno("got_object_id_dup");
5106 goto done;
5109 s->f1 = got_opentemp();
5110 if (s->f1 == NULL) {
5111 err = got_error_from_errno("got_opentemp");
5112 goto done;
5115 s->f2 = got_opentemp();
5116 if (s->f2 == NULL) {
5117 err = got_error_from_errno("got_opentemp");
5118 goto done;
5121 s->fd1 = got_opentempfd();
5122 if (s->fd1 == -1) {
5123 err = got_error_from_errno("got_opentempfd");
5124 goto done;
5127 s->fd2 = got_opentempfd();
5128 if (s->fd2 == -1) {
5129 err = got_error_from_errno("got_opentempfd");
5130 goto done;
5133 s->diff_context = diff_context;
5134 s->ignore_whitespace = ignore_whitespace;
5135 s->force_text_diff = force_text_diff;
5136 s->parent_view = parent_view;
5137 s->repo = repo;
5139 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5140 int rc;
5142 rc = init_pair(GOT_DIFF_LINE_MINUS,
5143 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5144 if (rc != ERR)
5145 rc = init_pair(GOT_DIFF_LINE_PLUS,
5146 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5147 if (rc != ERR)
5148 rc = init_pair(GOT_DIFF_LINE_HUNK,
5149 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5150 if (rc != ERR)
5151 rc = init_pair(GOT_DIFF_LINE_META,
5152 get_color_value("TOG_COLOR_DIFF_META"), -1);
5153 if (rc != ERR)
5154 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5155 get_color_value("TOG_COLOR_DIFF_META"), -1);
5156 if (rc != ERR)
5157 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5158 get_color_value("TOG_COLOR_DIFF_META"), -1);
5159 if (rc != ERR)
5160 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5161 get_color_value("TOG_COLOR_DIFF_META"), -1);
5162 if (rc != ERR)
5163 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5164 get_color_value("TOG_COLOR_AUTHOR"), -1);
5165 if (rc != ERR)
5166 rc = init_pair(GOT_DIFF_LINE_DATE,
5167 get_color_value("TOG_COLOR_DATE"), -1);
5168 if (rc == ERR) {
5169 err = got_error(GOT_ERR_RANGE);
5170 goto done;
5174 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5175 view_is_splitscreen(view))
5176 show_log_view(parent_view); /* draw border */
5177 diff_view_indicate_progress(view);
5179 err = create_diff(s);
5181 view->show = show_diff_view;
5182 view->input = input_diff_view;
5183 view->reset = reset_diff_view;
5184 view->close = close_diff_view;
5185 view->search_start = search_start_diff_view;
5186 view->search_setup = search_setup_diff_view;
5187 view->search_next = search_next_view_match;
5188 done:
5189 if (err)
5190 close_diff_view(view);
5191 return err;
5194 static const struct got_error *
5195 show_diff_view(struct tog_view *view)
5197 const struct got_error *err;
5198 struct tog_diff_view_state *s = &view->state.diff;
5199 char *id_str1 = NULL, *id_str2, *header;
5200 const char *label1, *label2;
5202 if (s->id1) {
5203 err = got_object_id_str(&id_str1, s->id1);
5204 if (err)
5205 return err;
5206 label1 = s->label1 ? s->label1 : id_str1;
5207 } else
5208 label1 = "/dev/null";
5210 err = got_object_id_str(&id_str2, s->id2);
5211 if (err)
5212 return err;
5213 label2 = s->label2 ? s->label2 : id_str2;
5215 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5216 err = got_error_from_errno("asprintf");
5217 free(id_str1);
5218 free(id_str2);
5219 return err;
5221 free(id_str1);
5222 free(id_str2);
5224 err = draw_file(view, header);
5225 free(header);
5226 return err;
5229 static const struct got_error *
5230 set_selected_commit(struct tog_diff_view_state *s,
5231 struct commit_queue_entry *entry)
5233 const struct got_error *err;
5234 const struct got_object_id_queue *parent_ids;
5235 struct got_commit_object *selected_commit;
5236 struct got_object_qid *pid;
5238 free(s->id2);
5239 s->id2 = got_object_id_dup(entry->id);
5240 if (s->id2 == NULL)
5241 return got_error_from_errno("got_object_id_dup");
5243 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5244 if (err)
5245 return err;
5246 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5247 free(s->id1);
5248 pid = STAILQ_FIRST(parent_ids);
5249 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5250 got_object_commit_close(selected_commit);
5251 return NULL;
5254 static const struct got_error *
5255 reset_diff_view(struct tog_view *view)
5257 struct tog_diff_view_state *s = &view->state.diff;
5259 view->count = 0;
5260 wclear(view->window);
5261 s->first_displayed_line = 1;
5262 s->last_displayed_line = view->nlines;
5263 s->matched_line = 0;
5264 diff_view_indicate_progress(view);
5265 return create_diff(s);
5268 static void
5269 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5271 int start, i;
5273 i = start = s->first_displayed_line - 1;
5275 while (s->lines[i].type != type) {
5276 if (i == 0)
5277 i = s->nlines - 1;
5278 if (--i == start)
5279 return; /* do nothing, requested type not in file */
5282 s->selected_line = 1;
5283 s->first_displayed_line = i;
5286 static void
5287 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5289 int start, i;
5291 i = start = s->first_displayed_line + 1;
5293 while (s->lines[i].type != type) {
5294 if (i == s->nlines - 1)
5295 i = 0;
5296 if (++i == start)
5297 return; /* do nothing, requested type not in file */
5300 s->selected_line = 1;
5301 s->first_displayed_line = i;
5304 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5305 int, int, int);
5306 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5307 int, int);
5309 static const struct got_error *
5310 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5312 const struct got_error *err = NULL;
5313 struct tog_diff_view_state *s = &view->state.diff;
5314 struct tog_log_view_state *ls;
5315 struct commit_queue_entry *old_selected_entry;
5316 char *line = NULL;
5317 size_t linesize = 0;
5318 ssize_t linelen;
5319 int i, nscroll = view->nlines - 1, up = 0;
5321 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5323 switch (ch) {
5324 case '0':
5325 case '$':
5326 case KEY_RIGHT:
5327 case 'l':
5328 case KEY_LEFT:
5329 case 'h':
5330 horizontal_scroll_input(view, ch);
5331 break;
5332 case 'a':
5333 case 'w':
5334 if (ch == 'a') {
5335 s->force_text_diff = !s->force_text_diff;
5336 view->action = s->force_text_diff ?
5337 "force ASCII text enabled" :
5338 "force ASCII text disabled";
5340 else if (ch == 'w') {
5341 s->ignore_whitespace = !s->ignore_whitespace;
5342 view->action = s->ignore_whitespace ?
5343 "ignore whitespace enabled" :
5344 "ignore whitespace disabled";
5346 err = reset_diff_view(view);
5347 break;
5348 case 'g':
5349 case KEY_HOME:
5350 s->first_displayed_line = 1;
5351 view->count = 0;
5352 break;
5353 case 'G':
5354 case KEY_END:
5355 view->count = 0;
5356 if (s->eof)
5357 break;
5359 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5360 s->eof = 1;
5361 break;
5362 case 'k':
5363 case KEY_UP:
5364 case CTRL('p'):
5365 if (s->first_displayed_line > 1)
5366 s->first_displayed_line--;
5367 else
5368 view->count = 0;
5369 break;
5370 case CTRL('u'):
5371 case 'u':
5372 nscroll /= 2;
5373 /* FALL THROUGH */
5374 case KEY_PPAGE:
5375 case CTRL('b'):
5376 case 'b':
5377 if (s->first_displayed_line == 1) {
5378 view->count = 0;
5379 break;
5381 i = 0;
5382 while (i++ < nscroll && s->first_displayed_line > 1)
5383 s->first_displayed_line--;
5384 break;
5385 case 'j':
5386 case KEY_DOWN:
5387 case CTRL('n'):
5388 if (!s->eof)
5389 s->first_displayed_line++;
5390 else
5391 view->count = 0;
5392 break;
5393 case CTRL('d'):
5394 case 'd':
5395 nscroll /= 2;
5396 /* FALL THROUGH */
5397 case KEY_NPAGE:
5398 case CTRL('f'):
5399 case 'f':
5400 case ' ':
5401 if (s->eof) {
5402 view->count = 0;
5403 break;
5405 i = 0;
5406 while (!s->eof && i++ < nscroll) {
5407 linelen = getline(&line, &linesize, s->f);
5408 s->first_displayed_line++;
5409 if (linelen == -1) {
5410 if (feof(s->f)) {
5411 s->eof = 1;
5412 } else
5413 err = got_ferror(s->f, GOT_ERR_IO);
5414 break;
5417 free(line);
5418 break;
5419 case '(':
5420 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5421 break;
5422 case ')':
5423 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5424 break;
5425 case '{':
5426 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5427 break;
5428 case '}':
5429 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5430 break;
5431 case '[':
5432 if (s->diff_context > 0) {
5433 s->diff_context--;
5434 s->matched_line = 0;
5435 diff_view_indicate_progress(view);
5436 err = create_diff(s);
5437 if (s->first_displayed_line + view->nlines - 1 >
5438 s->nlines) {
5439 s->first_displayed_line = 1;
5440 s->last_displayed_line = view->nlines;
5442 } else
5443 view->count = 0;
5444 break;
5445 case ']':
5446 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5447 s->diff_context++;
5448 s->matched_line = 0;
5449 diff_view_indicate_progress(view);
5450 err = create_diff(s);
5451 } else
5452 view->count = 0;
5453 break;
5454 case '<':
5455 case ',':
5456 case 'K':
5457 up = 1;
5458 /* FALL THROUGH */
5459 case '>':
5460 case '.':
5461 case 'J':
5462 if (s->parent_view == NULL) {
5463 view->count = 0;
5464 break;
5466 s->parent_view->count = view->count;
5468 if (s->parent_view->type == TOG_VIEW_LOG) {
5469 ls = &s->parent_view->state.log;
5470 old_selected_entry = ls->selected_entry;
5472 err = input_log_view(NULL, s->parent_view,
5473 up ? KEY_UP : KEY_DOWN);
5474 if (err)
5475 break;
5476 view->count = s->parent_view->count;
5478 if (old_selected_entry == ls->selected_entry)
5479 break;
5481 err = set_selected_commit(s, ls->selected_entry);
5482 if (err)
5483 break;
5484 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5485 struct tog_blame_view_state *bs;
5486 struct got_object_id *id, *prev_id;
5488 bs = &s->parent_view->state.blame;
5489 prev_id = get_annotation_for_line(bs->blame.lines,
5490 bs->blame.nlines, bs->last_diffed_line);
5492 err = input_blame_view(&view, s->parent_view,
5493 up ? KEY_UP : KEY_DOWN);
5494 if (err)
5495 break;
5496 view->count = s->parent_view->count;
5498 if (prev_id == NULL)
5499 break;
5500 id = get_selected_commit_id(bs->blame.lines,
5501 bs->blame.nlines, bs->first_displayed_line,
5502 bs->selected_line);
5503 if (id == NULL)
5504 break;
5506 if (!got_object_id_cmp(prev_id, id))
5507 break;
5509 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5510 if (err)
5511 break;
5513 s->first_displayed_line = 1;
5514 s->last_displayed_line = view->nlines;
5515 s->matched_line = 0;
5516 view->x = 0;
5518 diff_view_indicate_progress(view);
5519 err = create_diff(s);
5520 break;
5521 default:
5522 view->count = 0;
5523 break;
5526 return err;
5529 static const struct got_error *
5530 cmd_diff(int argc, char *argv[])
5532 const struct got_error *error = NULL;
5533 struct got_repository *repo = NULL;
5534 struct got_worktree *worktree = NULL;
5535 struct got_object_id *id1 = NULL, *id2 = NULL;
5536 char *repo_path = NULL, *cwd = NULL;
5537 char *id_str1 = NULL, *id_str2 = NULL;
5538 char *label1 = NULL, *label2 = NULL;
5539 int diff_context = 3, ignore_whitespace = 0;
5540 int ch, force_text_diff = 0;
5541 const char *errstr;
5542 struct tog_view *view;
5543 int *pack_fds = NULL;
5545 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5546 switch (ch) {
5547 case 'a':
5548 force_text_diff = 1;
5549 break;
5550 case 'C':
5551 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5552 &errstr);
5553 if (errstr != NULL)
5554 errx(1, "number of context lines is %s: %s",
5555 errstr, errstr);
5556 break;
5557 case 'r':
5558 repo_path = realpath(optarg, NULL);
5559 if (repo_path == NULL)
5560 return got_error_from_errno2("realpath",
5561 optarg);
5562 got_path_strip_trailing_slashes(repo_path);
5563 break;
5564 case 'w':
5565 ignore_whitespace = 1;
5566 break;
5567 default:
5568 usage_diff();
5569 /* NOTREACHED */
5573 argc -= optind;
5574 argv += optind;
5576 if (argc == 0) {
5577 usage_diff(); /* TODO show local worktree changes */
5578 } else if (argc == 2) {
5579 id_str1 = argv[0];
5580 id_str2 = argv[1];
5581 } else
5582 usage_diff();
5584 error = got_repo_pack_fds_open(&pack_fds);
5585 if (error)
5586 goto done;
5588 if (repo_path == NULL) {
5589 cwd = getcwd(NULL, 0);
5590 if (cwd == NULL)
5591 return got_error_from_errno("getcwd");
5592 error = got_worktree_open(&worktree, cwd);
5593 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5594 goto done;
5595 if (worktree)
5596 repo_path =
5597 strdup(got_worktree_get_repo_path(worktree));
5598 else
5599 repo_path = strdup(cwd);
5600 if (repo_path == NULL) {
5601 error = got_error_from_errno("strdup");
5602 goto done;
5606 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5607 if (error)
5608 goto done;
5610 init_curses();
5612 error = apply_unveil(got_repo_get_path(repo), NULL);
5613 if (error)
5614 goto done;
5616 error = tog_load_refs(repo, 0);
5617 if (error)
5618 goto done;
5620 error = got_repo_match_object_id(&id1, &label1, id_str1,
5621 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5622 if (error)
5623 goto done;
5625 error = got_repo_match_object_id(&id2, &label2, id_str2,
5626 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5627 if (error)
5628 goto done;
5630 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5631 if (view == NULL) {
5632 error = got_error_from_errno("view_open");
5633 goto done;
5635 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5636 ignore_whitespace, force_text_diff, NULL, repo);
5637 if (error)
5638 goto done;
5639 error = view_loop(view);
5640 done:
5641 free(label1);
5642 free(label2);
5643 free(repo_path);
5644 free(cwd);
5645 if (repo) {
5646 const struct got_error *close_err = got_repo_close(repo);
5647 if (error == NULL)
5648 error = close_err;
5650 if (worktree)
5651 got_worktree_close(worktree);
5652 if (pack_fds) {
5653 const struct got_error *pack_err =
5654 got_repo_pack_fds_close(pack_fds);
5655 if (error == NULL)
5656 error = pack_err;
5658 tog_free_refs();
5659 return error;
5662 __dead static void
5663 usage_blame(void)
5665 endwin();
5666 fprintf(stderr,
5667 "usage: %s blame [-c commit] [-r repository-path] path\n",
5668 getprogname());
5669 exit(1);
5672 struct tog_blame_line {
5673 int annotated;
5674 struct got_object_id *id;
5677 static const struct got_error *
5678 draw_blame(struct tog_view *view)
5680 struct tog_blame_view_state *s = &view->state.blame;
5681 struct tog_blame *blame = &s->blame;
5682 regmatch_t *regmatch = &view->regmatch;
5683 const struct got_error *err;
5684 int lineno = 0, nprinted = 0;
5685 char *line = NULL;
5686 size_t linesize = 0;
5687 ssize_t linelen;
5688 wchar_t *wline;
5689 int width;
5690 struct tog_blame_line *blame_line;
5691 struct got_object_id *prev_id = NULL;
5692 char *id_str;
5693 struct tog_color *tc;
5695 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5696 if (err)
5697 return err;
5699 rewind(blame->f);
5700 werase(view->window);
5702 if (asprintf(&line, "commit %s", id_str) == -1) {
5703 err = got_error_from_errno("asprintf");
5704 free(id_str);
5705 return err;
5708 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5709 free(line);
5710 line = NULL;
5711 if (err)
5712 return err;
5713 if (view_needs_focus_indication(view))
5714 wstandout(view->window);
5715 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5716 if (tc)
5717 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5718 waddwstr(view->window, wline);
5719 while (width++ < view->ncols)
5720 waddch(view->window, ' ');
5721 if (tc)
5722 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5723 if (view_needs_focus_indication(view))
5724 wstandend(view->window);
5725 free(wline);
5726 wline = NULL;
5728 if (view->gline > blame->nlines)
5729 view->gline = blame->nlines;
5731 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5732 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5733 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5734 free(id_str);
5735 return got_error_from_errno("asprintf");
5737 free(id_str);
5738 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5739 free(line);
5740 line = NULL;
5741 if (err)
5742 return err;
5743 waddwstr(view->window, wline);
5744 free(wline);
5745 wline = NULL;
5746 if (width < view->ncols - 1)
5747 waddch(view->window, '\n');
5749 s->eof = 0;
5750 view->maxx = 0;
5751 while (nprinted < view->nlines - 2) {
5752 linelen = getline(&line, &linesize, blame->f);
5753 if (linelen == -1) {
5754 if (feof(blame->f)) {
5755 s->eof = 1;
5756 break;
5758 free(line);
5759 return got_ferror(blame->f, GOT_ERR_IO);
5761 if (++lineno < s->first_displayed_line)
5762 continue;
5763 if (view->gline && !gotoline(view, &lineno, &nprinted))
5764 continue;
5766 /* Set view->maxx based on full line length. */
5767 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5768 if (err) {
5769 free(line);
5770 return err;
5772 free(wline);
5773 wline = NULL;
5774 view->maxx = MAX(view->maxx, width);
5776 if (nprinted == s->selected_line - 1)
5777 wstandout(view->window);
5779 if (blame->nlines > 0) {
5780 blame_line = &blame->lines[lineno - 1];
5781 if (blame_line->annotated && prev_id &&
5782 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5783 !(nprinted == s->selected_line - 1)) {
5784 waddstr(view->window, " ");
5785 } else if (blame_line->annotated) {
5786 char *id_str;
5787 err = got_object_id_str(&id_str,
5788 blame_line->id);
5789 if (err) {
5790 free(line);
5791 return err;
5793 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5794 if (tc)
5795 wattr_on(view->window,
5796 COLOR_PAIR(tc->colorpair), NULL);
5797 wprintw(view->window, "%.8s", id_str);
5798 if (tc)
5799 wattr_off(view->window,
5800 COLOR_PAIR(tc->colorpair), NULL);
5801 free(id_str);
5802 prev_id = blame_line->id;
5803 } else {
5804 waddstr(view->window, "........");
5805 prev_id = NULL;
5807 } else {
5808 waddstr(view->window, "........");
5809 prev_id = NULL;
5812 if (nprinted == s->selected_line - 1)
5813 wstandend(view->window);
5814 waddstr(view->window, " ");
5816 if (view->ncols <= 9) {
5817 width = 9;
5818 } else if (s->first_displayed_line + nprinted ==
5819 s->matched_line &&
5820 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5821 err = add_matched_line(&width, line, view->ncols - 9, 9,
5822 view->window, view->x, regmatch);
5823 if (err) {
5824 free(line);
5825 return err;
5827 width += 9;
5828 } else {
5829 int skip;
5830 err = format_line(&wline, &width, &skip, line,
5831 view->x, view->ncols - 9, 9, 1);
5832 if (err) {
5833 free(line);
5834 return err;
5836 waddwstr(view->window, &wline[skip]);
5837 width += 9;
5838 free(wline);
5839 wline = NULL;
5842 if (width <= view->ncols - 1)
5843 waddch(view->window, '\n');
5844 if (++nprinted == 1)
5845 s->first_displayed_line = lineno;
5847 free(line);
5848 s->last_displayed_line = lineno;
5850 view_border(view);
5852 return NULL;
5855 static const struct got_error *
5856 blame_cb(void *arg, int nlines, int lineno,
5857 struct got_commit_object *commit, struct got_object_id *id)
5859 const struct got_error *err = NULL;
5860 struct tog_blame_cb_args *a = arg;
5861 struct tog_blame_line *line;
5862 int errcode;
5864 if (nlines != a->nlines ||
5865 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5866 return got_error(GOT_ERR_RANGE);
5868 errcode = pthread_mutex_lock(&tog_mutex);
5869 if (errcode)
5870 return got_error_set_errno(errcode, "pthread_mutex_lock");
5872 if (*a->quit) { /* user has quit the blame view */
5873 err = got_error(GOT_ERR_ITER_COMPLETED);
5874 goto done;
5877 if (lineno == -1)
5878 goto done; /* no change in this commit */
5880 line = &a->lines[lineno - 1];
5881 if (line->annotated)
5882 goto done;
5884 line->id = got_object_id_dup(id);
5885 if (line->id == NULL) {
5886 err = got_error_from_errno("got_object_id_dup");
5887 goto done;
5889 line->annotated = 1;
5890 done:
5891 errcode = pthread_mutex_unlock(&tog_mutex);
5892 if (errcode)
5893 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5894 return err;
5897 static void *
5898 blame_thread(void *arg)
5900 const struct got_error *err, *close_err;
5901 struct tog_blame_thread_args *ta = arg;
5902 struct tog_blame_cb_args *a = ta->cb_args;
5903 int errcode, fd1 = -1, fd2 = -1;
5904 FILE *f1 = NULL, *f2 = NULL;
5906 fd1 = got_opentempfd();
5907 if (fd1 == -1)
5908 return (void *)got_error_from_errno("got_opentempfd");
5910 fd2 = got_opentempfd();
5911 if (fd2 == -1) {
5912 err = got_error_from_errno("got_opentempfd");
5913 goto done;
5916 f1 = got_opentemp();
5917 if (f1 == NULL) {
5918 err = (void *)got_error_from_errno("got_opentemp");
5919 goto done;
5921 f2 = got_opentemp();
5922 if (f2 == NULL) {
5923 err = (void *)got_error_from_errno("got_opentemp");
5924 goto done;
5927 err = block_signals_used_by_main_thread();
5928 if (err)
5929 goto done;
5931 err = got_blame(ta->path, a->commit_id, ta->repo,
5932 tog_diff_algo, blame_cb, ta->cb_args,
5933 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5934 if (err && err->code == GOT_ERR_CANCELLED)
5935 err = NULL;
5937 errcode = pthread_mutex_lock(&tog_mutex);
5938 if (errcode) {
5939 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5940 goto done;
5943 close_err = got_repo_close(ta->repo);
5944 if (err == NULL)
5945 err = close_err;
5946 ta->repo = NULL;
5947 *ta->complete = 1;
5949 errcode = pthread_mutex_unlock(&tog_mutex);
5950 if (errcode && err == NULL)
5951 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5953 done:
5954 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5955 err = got_error_from_errno("close");
5956 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5957 err = got_error_from_errno("close");
5958 if (f1 && fclose(f1) == EOF && err == NULL)
5959 err = got_error_from_errno("fclose");
5960 if (f2 && fclose(f2) == EOF && err == NULL)
5961 err = got_error_from_errno("fclose");
5963 return (void *)err;
5966 static struct got_object_id *
5967 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5968 int first_displayed_line, int selected_line)
5970 struct tog_blame_line *line;
5972 if (nlines <= 0)
5973 return NULL;
5975 line = &lines[first_displayed_line - 1 + selected_line - 1];
5976 if (!line->annotated)
5977 return NULL;
5979 return line->id;
5982 static struct got_object_id *
5983 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5984 int lineno)
5986 struct tog_blame_line *line;
5988 if (nlines <= 0 || lineno >= nlines)
5989 return NULL;
5991 line = &lines[lineno - 1];
5992 if (!line->annotated)
5993 return NULL;
5995 return line->id;
5998 static const struct got_error *
5999 stop_blame(struct tog_blame *blame)
6001 const struct got_error *err = NULL;
6002 int i;
6004 if (blame->thread) {
6005 int errcode;
6006 errcode = pthread_mutex_unlock(&tog_mutex);
6007 if (errcode)
6008 return got_error_set_errno(errcode,
6009 "pthread_mutex_unlock");
6010 errcode = pthread_join(blame->thread, (void **)&err);
6011 if (errcode)
6012 return got_error_set_errno(errcode, "pthread_join");
6013 errcode = pthread_mutex_lock(&tog_mutex);
6014 if (errcode)
6015 return got_error_set_errno(errcode,
6016 "pthread_mutex_lock");
6017 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6018 err = NULL;
6019 blame->thread = 0; //NULL;
6021 if (blame->thread_args.repo) {
6022 const struct got_error *close_err;
6023 close_err = got_repo_close(blame->thread_args.repo);
6024 if (err == NULL)
6025 err = close_err;
6026 blame->thread_args.repo = NULL;
6028 if (blame->f) {
6029 if (fclose(blame->f) == EOF && err == NULL)
6030 err = got_error_from_errno("fclose");
6031 blame->f = NULL;
6033 if (blame->lines) {
6034 for (i = 0; i < blame->nlines; i++)
6035 free(blame->lines[i].id);
6036 free(blame->lines);
6037 blame->lines = NULL;
6039 free(blame->cb_args.commit_id);
6040 blame->cb_args.commit_id = NULL;
6041 if (blame->pack_fds) {
6042 const struct got_error *pack_err =
6043 got_repo_pack_fds_close(blame->pack_fds);
6044 if (err == NULL)
6045 err = pack_err;
6046 blame->pack_fds = NULL;
6048 return err;
6051 static const struct got_error *
6052 cancel_blame_view(void *arg)
6054 const struct got_error *err = NULL;
6055 int *done = arg;
6056 int errcode;
6058 errcode = pthread_mutex_lock(&tog_mutex);
6059 if (errcode)
6060 return got_error_set_errno(errcode,
6061 "pthread_mutex_unlock");
6063 if (*done)
6064 err = got_error(GOT_ERR_CANCELLED);
6066 errcode = pthread_mutex_unlock(&tog_mutex);
6067 if (errcode)
6068 return got_error_set_errno(errcode,
6069 "pthread_mutex_lock");
6071 return err;
6074 static const struct got_error *
6075 run_blame(struct tog_view *view)
6077 struct tog_blame_view_state *s = &view->state.blame;
6078 struct tog_blame *blame = &s->blame;
6079 const struct got_error *err = NULL;
6080 struct got_commit_object *commit = NULL;
6081 struct got_blob_object *blob = NULL;
6082 struct got_repository *thread_repo = NULL;
6083 struct got_object_id *obj_id = NULL;
6084 int obj_type, fd = -1;
6085 int *pack_fds = NULL;
6087 err = got_object_open_as_commit(&commit, s->repo,
6088 &s->blamed_commit->id);
6089 if (err)
6090 return err;
6092 fd = got_opentempfd();
6093 if (fd == -1) {
6094 err = got_error_from_errno("got_opentempfd");
6095 goto done;
6098 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6099 if (err)
6100 goto done;
6102 err = got_object_get_type(&obj_type, s->repo, obj_id);
6103 if (err)
6104 goto done;
6106 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6107 err = got_error(GOT_ERR_OBJ_TYPE);
6108 goto done;
6111 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6112 if (err)
6113 goto done;
6114 blame->f = got_opentemp();
6115 if (blame->f == NULL) {
6116 err = got_error_from_errno("got_opentemp");
6117 goto done;
6119 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6120 &blame->line_offsets, blame->f, blob);
6121 if (err)
6122 goto done;
6123 if (blame->nlines == 0) {
6124 s->blame_complete = 1;
6125 goto done;
6128 /* Don't include \n at EOF in the blame line count. */
6129 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6130 blame->nlines--;
6132 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6133 if (blame->lines == NULL) {
6134 err = got_error_from_errno("calloc");
6135 goto done;
6138 err = got_repo_pack_fds_open(&pack_fds);
6139 if (err)
6140 goto done;
6141 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6142 pack_fds);
6143 if (err)
6144 goto done;
6146 blame->pack_fds = pack_fds;
6147 blame->cb_args.view = view;
6148 blame->cb_args.lines = blame->lines;
6149 blame->cb_args.nlines = blame->nlines;
6150 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6151 if (blame->cb_args.commit_id == NULL) {
6152 err = got_error_from_errno("got_object_id_dup");
6153 goto done;
6155 blame->cb_args.quit = &s->done;
6157 blame->thread_args.path = s->path;
6158 blame->thread_args.repo = thread_repo;
6159 blame->thread_args.cb_args = &blame->cb_args;
6160 blame->thread_args.complete = &s->blame_complete;
6161 blame->thread_args.cancel_cb = cancel_blame_view;
6162 blame->thread_args.cancel_arg = &s->done;
6163 s->blame_complete = 0;
6165 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6166 s->first_displayed_line = 1;
6167 s->last_displayed_line = view->nlines;
6168 s->selected_line = 1;
6170 s->matched_line = 0;
6172 done:
6173 if (commit)
6174 got_object_commit_close(commit);
6175 if (fd != -1 && close(fd) == -1 && err == NULL)
6176 err = got_error_from_errno("close");
6177 if (blob)
6178 got_object_blob_close(blob);
6179 free(obj_id);
6180 if (err)
6181 stop_blame(blame);
6182 return err;
6185 static const struct got_error *
6186 open_blame_view(struct tog_view *view, char *path,
6187 struct got_object_id *commit_id, struct got_repository *repo)
6189 const struct got_error *err = NULL;
6190 struct tog_blame_view_state *s = &view->state.blame;
6192 STAILQ_INIT(&s->blamed_commits);
6194 s->path = strdup(path);
6195 if (s->path == NULL)
6196 return got_error_from_errno("strdup");
6198 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6199 if (err) {
6200 free(s->path);
6201 return err;
6204 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6205 s->first_displayed_line = 1;
6206 s->last_displayed_line = view->nlines;
6207 s->selected_line = 1;
6208 s->blame_complete = 0;
6209 s->repo = repo;
6210 s->commit_id = commit_id;
6211 memset(&s->blame, 0, sizeof(s->blame));
6213 STAILQ_INIT(&s->colors);
6214 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6215 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6216 get_color_value("TOG_COLOR_COMMIT"));
6217 if (err)
6218 return err;
6221 view->show = show_blame_view;
6222 view->input = input_blame_view;
6223 view->reset = reset_blame_view;
6224 view->close = close_blame_view;
6225 view->search_start = search_start_blame_view;
6226 view->search_setup = search_setup_blame_view;
6227 view->search_next = search_next_view_match;
6229 return run_blame(view);
6232 static const struct got_error *
6233 close_blame_view(struct tog_view *view)
6235 const struct got_error *err = NULL;
6236 struct tog_blame_view_state *s = &view->state.blame;
6238 if (s->blame.thread)
6239 err = stop_blame(&s->blame);
6241 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6242 struct got_object_qid *blamed_commit;
6243 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6244 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6245 got_object_qid_free(blamed_commit);
6248 free(s->path);
6249 free_colors(&s->colors);
6250 return err;
6253 static const struct got_error *
6254 search_start_blame_view(struct tog_view *view)
6256 struct tog_blame_view_state *s = &view->state.blame;
6258 s->matched_line = 0;
6259 return NULL;
6262 static void
6263 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6264 size_t *nlines, int **first, int **last, int **match, int **selected)
6266 struct tog_blame_view_state *s = &view->state.blame;
6268 *f = s->blame.f;
6269 *nlines = s->blame.nlines;
6270 *line_offsets = s->blame.line_offsets;
6271 *match = &s->matched_line;
6272 *first = &s->first_displayed_line;
6273 *last = &s->last_displayed_line;
6274 *selected = &s->selected_line;
6277 static const struct got_error *
6278 show_blame_view(struct tog_view *view)
6280 const struct got_error *err = NULL;
6281 struct tog_blame_view_state *s = &view->state.blame;
6282 int errcode;
6284 if (s->blame.thread == 0 && !s->blame_complete) {
6285 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6286 &s->blame.thread_args);
6287 if (errcode)
6288 return got_error_set_errno(errcode, "pthread_create");
6290 halfdelay(1); /* fast refresh while annotating */
6293 if (s->blame_complete)
6294 halfdelay(10); /* disable fast refresh */
6296 err = draw_blame(view);
6298 view_border(view);
6299 return err;
6302 static const struct got_error *
6303 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6304 struct got_repository *repo, struct got_object_id *id)
6306 struct tog_view *log_view;
6307 const struct got_error *err = NULL;
6309 *new_view = NULL;
6311 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6312 if (log_view == NULL)
6313 return got_error_from_errno("view_open");
6315 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6316 if (err)
6317 view_close(log_view);
6318 else
6319 *new_view = log_view;
6321 return err;
6324 static const struct got_error *
6325 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6327 const struct got_error *err = NULL, *thread_err = NULL;
6328 struct tog_view *diff_view;
6329 struct tog_blame_view_state *s = &view->state.blame;
6330 int eos, nscroll, begin_y = 0, begin_x = 0;
6332 eos = nscroll = view->nlines - 2;
6333 if (view_is_hsplit_top(view))
6334 --eos; /* border */
6336 switch (ch) {
6337 case '0':
6338 case '$':
6339 case KEY_RIGHT:
6340 case 'l':
6341 case KEY_LEFT:
6342 case 'h':
6343 horizontal_scroll_input(view, ch);
6344 break;
6345 case 'q':
6346 s->done = 1;
6347 break;
6348 case 'g':
6349 case KEY_HOME:
6350 s->selected_line = 1;
6351 s->first_displayed_line = 1;
6352 view->count = 0;
6353 break;
6354 case 'G':
6355 case KEY_END:
6356 if (s->blame.nlines < eos) {
6357 s->selected_line = s->blame.nlines;
6358 s->first_displayed_line = 1;
6359 } else {
6360 s->selected_line = eos;
6361 s->first_displayed_line = s->blame.nlines - (eos - 1);
6363 view->count = 0;
6364 break;
6365 case 'k':
6366 case KEY_UP:
6367 case CTRL('p'):
6368 if (s->selected_line > 1)
6369 s->selected_line--;
6370 else if (s->selected_line == 1 &&
6371 s->first_displayed_line > 1)
6372 s->first_displayed_line--;
6373 else
6374 view->count = 0;
6375 break;
6376 case CTRL('u'):
6377 case 'u':
6378 nscroll /= 2;
6379 /* FALL THROUGH */
6380 case KEY_PPAGE:
6381 case CTRL('b'):
6382 case 'b':
6383 if (s->first_displayed_line == 1) {
6384 if (view->count > 1)
6385 nscroll += nscroll;
6386 s->selected_line = MAX(1, s->selected_line - nscroll);
6387 view->count = 0;
6388 break;
6390 if (s->first_displayed_line > nscroll)
6391 s->first_displayed_line -= nscroll;
6392 else
6393 s->first_displayed_line = 1;
6394 break;
6395 case 'j':
6396 case KEY_DOWN:
6397 case CTRL('n'):
6398 if (s->selected_line < eos && s->first_displayed_line +
6399 s->selected_line <= s->blame.nlines)
6400 s->selected_line++;
6401 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6402 s->first_displayed_line++;
6403 else
6404 view->count = 0;
6405 break;
6406 case 'c':
6407 case 'p': {
6408 struct got_object_id *id = NULL;
6410 view->count = 0;
6411 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6412 s->first_displayed_line, s->selected_line);
6413 if (id == NULL)
6414 break;
6415 if (ch == 'p') {
6416 struct got_commit_object *commit, *pcommit;
6417 struct got_object_qid *pid;
6418 struct got_object_id *blob_id = NULL;
6419 int obj_type;
6420 err = got_object_open_as_commit(&commit,
6421 s->repo, id);
6422 if (err)
6423 break;
6424 pid = STAILQ_FIRST(
6425 got_object_commit_get_parent_ids(commit));
6426 if (pid == NULL) {
6427 got_object_commit_close(commit);
6428 break;
6430 /* Check if path history ends here. */
6431 err = got_object_open_as_commit(&pcommit,
6432 s->repo, &pid->id);
6433 if (err)
6434 break;
6435 err = got_object_id_by_path(&blob_id, s->repo,
6436 pcommit, s->path);
6437 got_object_commit_close(pcommit);
6438 if (err) {
6439 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6440 err = NULL;
6441 got_object_commit_close(commit);
6442 break;
6444 err = got_object_get_type(&obj_type, s->repo,
6445 blob_id);
6446 free(blob_id);
6447 /* Can't blame non-blob type objects. */
6448 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6449 got_object_commit_close(commit);
6450 break;
6452 err = got_object_qid_alloc(&s->blamed_commit,
6453 &pid->id);
6454 got_object_commit_close(commit);
6455 } else {
6456 if (got_object_id_cmp(id,
6457 &s->blamed_commit->id) == 0)
6458 break;
6459 err = got_object_qid_alloc(&s->blamed_commit,
6460 id);
6462 if (err)
6463 break;
6464 s->done = 1;
6465 thread_err = stop_blame(&s->blame);
6466 s->done = 0;
6467 if (thread_err)
6468 break;
6469 STAILQ_INSERT_HEAD(&s->blamed_commits,
6470 s->blamed_commit, entry);
6471 err = run_blame(view);
6472 if (err)
6473 break;
6474 break;
6476 case 'C': {
6477 struct got_object_qid *first;
6479 view->count = 0;
6480 first = STAILQ_FIRST(&s->blamed_commits);
6481 if (!got_object_id_cmp(&first->id, s->commit_id))
6482 break;
6483 s->done = 1;
6484 thread_err = stop_blame(&s->blame);
6485 s->done = 0;
6486 if (thread_err)
6487 break;
6488 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6489 got_object_qid_free(s->blamed_commit);
6490 s->blamed_commit =
6491 STAILQ_FIRST(&s->blamed_commits);
6492 err = run_blame(view);
6493 if (err)
6494 break;
6495 break;
6497 case 'L':
6498 view->count = 0;
6499 s->id_to_log = get_selected_commit_id(s->blame.lines,
6500 s->blame.nlines, s->first_displayed_line, s->selected_line);
6501 if (s->id_to_log)
6502 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6503 break;
6504 case KEY_ENTER:
6505 case '\r': {
6506 struct got_object_id *id = NULL;
6507 struct got_object_qid *pid;
6508 struct got_commit_object *commit = NULL;
6510 view->count = 0;
6511 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6512 s->first_displayed_line, s->selected_line);
6513 if (id == NULL)
6514 break;
6515 err = got_object_open_as_commit(&commit, s->repo, id);
6516 if (err)
6517 break;
6518 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6519 if (*new_view) {
6520 /* traversed from diff view, release diff resources */
6521 err = close_diff_view(*new_view);
6522 if (err)
6523 break;
6524 diff_view = *new_view;
6525 } else {
6526 if (view_is_parent_view(view))
6527 view_get_split(view, &begin_y, &begin_x);
6529 diff_view = view_open(0, 0, begin_y, begin_x,
6530 TOG_VIEW_DIFF);
6531 if (diff_view == NULL) {
6532 got_object_commit_close(commit);
6533 err = got_error_from_errno("view_open");
6534 break;
6537 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6538 id, NULL, NULL, 3, 0, 0, view, s->repo);
6539 got_object_commit_close(commit);
6540 if (err) {
6541 view_close(diff_view);
6542 break;
6544 s->last_diffed_line = s->first_displayed_line - 1 +
6545 s->selected_line;
6546 if (*new_view)
6547 break; /* still open from active diff view */
6548 if (view_is_parent_view(view) &&
6549 view->mode == TOG_VIEW_SPLIT_HRZN) {
6550 err = view_init_hsplit(view, begin_y);
6551 if (err)
6552 break;
6555 view->focussed = 0;
6556 diff_view->focussed = 1;
6557 diff_view->mode = view->mode;
6558 diff_view->nlines = view->lines - begin_y;
6559 if (view_is_parent_view(view)) {
6560 view_transfer_size(diff_view, view);
6561 err = view_close_child(view);
6562 if (err)
6563 break;
6564 err = view_set_child(view, diff_view);
6565 if (err)
6566 break;
6567 view->focus_child = 1;
6568 } else
6569 *new_view = diff_view;
6570 if (err)
6571 break;
6572 break;
6574 case CTRL('d'):
6575 case 'd':
6576 nscroll /= 2;
6577 /* FALL THROUGH */
6578 case KEY_NPAGE:
6579 case CTRL('f'):
6580 case 'f':
6581 case ' ':
6582 if (s->last_displayed_line >= s->blame.nlines &&
6583 s->selected_line >= MIN(s->blame.nlines,
6584 view->nlines - 2)) {
6585 view->count = 0;
6586 break;
6588 if (s->last_displayed_line >= s->blame.nlines &&
6589 s->selected_line < view->nlines - 2) {
6590 s->selected_line +=
6591 MIN(nscroll, s->last_displayed_line -
6592 s->first_displayed_line - s->selected_line + 1);
6594 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6595 s->first_displayed_line += nscroll;
6596 else
6597 s->first_displayed_line =
6598 s->blame.nlines - (view->nlines - 3);
6599 break;
6600 case KEY_RESIZE:
6601 if (s->selected_line > view->nlines - 2) {
6602 s->selected_line = MIN(s->blame.nlines,
6603 view->nlines - 2);
6605 break;
6606 default:
6607 view->count = 0;
6608 break;
6610 return thread_err ? thread_err : err;
6613 static const struct got_error *
6614 reset_blame_view(struct tog_view *view)
6616 const struct got_error *err;
6617 struct tog_blame_view_state *s = &view->state.blame;
6619 view->count = 0;
6620 s->done = 1;
6621 err = stop_blame(&s->blame);
6622 s->done = 0;
6623 if (err)
6624 return err;
6625 return run_blame(view);
6628 static const struct got_error *
6629 cmd_blame(int argc, char *argv[])
6631 const struct got_error *error;
6632 struct got_repository *repo = NULL;
6633 struct got_worktree *worktree = NULL;
6634 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6635 char *link_target = NULL;
6636 struct got_object_id *commit_id = NULL;
6637 struct got_commit_object *commit = NULL;
6638 char *commit_id_str = NULL;
6639 int ch;
6640 struct tog_view *view;
6641 int *pack_fds = NULL;
6643 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6644 switch (ch) {
6645 case 'c':
6646 commit_id_str = optarg;
6647 break;
6648 case 'r':
6649 repo_path = realpath(optarg, NULL);
6650 if (repo_path == NULL)
6651 return got_error_from_errno2("realpath",
6652 optarg);
6653 break;
6654 default:
6655 usage_blame();
6656 /* NOTREACHED */
6660 argc -= optind;
6661 argv += optind;
6663 if (argc != 1)
6664 usage_blame();
6666 error = got_repo_pack_fds_open(&pack_fds);
6667 if (error != NULL)
6668 goto done;
6670 if (repo_path == NULL) {
6671 cwd = getcwd(NULL, 0);
6672 if (cwd == NULL)
6673 return got_error_from_errno("getcwd");
6674 error = got_worktree_open(&worktree, cwd);
6675 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6676 goto done;
6677 if (worktree)
6678 repo_path =
6679 strdup(got_worktree_get_repo_path(worktree));
6680 else
6681 repo_path = strdup(cwd);
6682 if (repo_path == NULL) {
6683 error = got_error_from_errno("strdup");
6684 goto done;
6688 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6689 if (error != NULL)
6690 goto done;
6692 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6693 worktree);
6694 if (error)
6695 goto done;
6697 init_curses();
6699 error = apply_unveil(got_repo_get_path(repo), NULL);
6700 if (error)
6701 goto done;
6703 error = tog_load_refs(repo, 0);
6704 if (error)
6705 goto done;
6707 if (commit_id_str == NULL) {
6708 struct got_reference *head_ref;
6709 error = got_ref_open(&head_ref, repo, worktree ?
6710 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6711 if (error != NULL)
6712 goto done;
6713 error = got_ref_resolve(&commit_id, repo, head_ref);
6714 got_ref_close(head_ref);
6715 } else {
6716 error = got_repo_match_object_id(&commit_id, NULL,
6717 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6719 if (error != NULL)
6720 goto done;
6722 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6723 if (view == NULL) {
6724 error = got_error_from_errno("view_open");
6725 goto done;
6728 error = got_object_open_as_commit(&commit, repo, commit_id);
6729 if (error)
6730 goto done;
6732 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6733 commit, repo);
6734 if (error)
6735 goto done;
6737 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6738 commit_id, repo);
6739 if (error)
6740 goto done;
6741 if (worktree) {
6742 /* Release work tree lock. */
6743 got_worktree_close(worktree);
6744 worktree = NULL;
6746 error = view_loop(view);
6747 done:
6748 free(repo_path);
6749 free(in_repo_path);
6750 free(link_target);
6751 free(cwd);
6752 free(commit_id);
6753 if (commit)
6754 got_object_commit_close(commit);
6755 if (worktree)
6756 got_worktree_close(worktree);
6757 if (repo) {
6758 const struct got_error *close_err = got_repo_close(repo);
6759 if (error == NULL)
6760 error = close_err;
6762 if (pack_fds) {
6763 const struct got_error *pack_err =
6764 got_repo_pack_fds_close(pack_fds);
6765 if (error == NULL)
6766 error = pack_err;
6768 tog_free_refs();
6769 return error;
6772 static const struct got_error *
6773 draw_tree_entries(struct tog_view *view, const char *parent_path)
6775 struct tog_tree_view_state *s = &view->state.tree;
6776 const struct got_error *err = NULL;
6777 struct got_tree_entry *te;
6778 wchar_t *wline;
6779 char *index = NULL;
6780 struct tog_color *tc;
6781 int width, n, nentries, scrollx, i = 1;
6782 int limit = view->nlines;
6784 s->ndisplayed = 0;
6785 if (view_is_hsplit_top(view))
6786 --limit; /* border */
6788 werase(view->window);
6790 if (limit == 0)
6791 return NULL;
6793 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6794 0, 0);
6795 if (err)
6796 return err;
6797 if (view_needs_focus_indication(view))
6798 wstandout(view->window);
6799 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6800 if (tc)
6801 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6802 waddwstr(view->window, wline);
6803 free(wline);
6804 wline = NULL;
6805 while (width++ < view->ncols)
6806 waddch(view->window, ' ');
6807 if (tc)
6808 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6809 if (view_needs_focus_indication(view))
6810 wstandend(view->window);
6811 if (--limit <= 0)
6812 return NULL;
6814 i += s->selected;
6815 if (s->first_displayed_entry) {
6816 i += got_tree_entry_get_index(s->first_displayed_entry);
6817 if (s->tree != s->root)
6818 ++i; /* account for ".." entry */
6820 nentries = got_object_tree_get_nentries(s->tree);
6821 if (asprintf(&index, "[%d/%d] %s",
6822 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6823 return got_error_from_errno("asprintf");
6824 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6825 free(index);
6826 if (err)
6827 return err;
6828 waddwstr(view->window, wline);
6829 free(wline);
6830 wline = NULL;
6831 if (width < view->ncols - 1)
6832 waddch(view->window, '\n');
6833 if (--limit <= 0)
6834 return NULL;
6835 waddch(view->window, '\n');
6836 if (--limit <= 0)
6837 return NULL;
6839 if (s->first_displayed_entry == NULL) {
6840 te = got_object_tree_get_first_entry(s->tree);
6841 if (s->selected == 0) {
6842 if (view->focussed)
6843 wstandout(view->window);
6844 s->selected_entry = NULL;
6846 waddstr(view->window, " ..\n"); /* parent directory */
6847 if (s->selected == 0 && view->focussed)
6848 wstandend(view->window);
6849 s->ndisplayed++;
6850 if (--limit <= 0)
6851 return NULL;
6852 n = 1;
6853 } else {
6854 n = 0;
6855 te = s->first_displayed_entry;
6858 view->maxx = 0;
6859 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6860 char *line = NULL, *id_str = NULL, *link_target = NULL;
6861 const char *modestr = "";
6862 mode_t mode;
6864 te = got_object_tree_get_entry(s->tree, i);
6865 mode = got_tree_entry_get_mode(te);
6867 if (s->show_ids) {
6868 err = got_object_id_str(&id_str,
6869 got_tree_entry_get_id(te));
6870 if (err)
6871 return got_error_from_errno(
6872 "got_object_id_str");
6874 if (got_object_tree_entry_is_submodule(te))
6875 modestr = "$";
6876 else if (S_ISLNK(mode)) {
6877 int i;
6879 err = got_tree_entry_get_symlink_target(&link_target,
6880 te, s->repo);
6881 if (err) {
6882 free(id_str);
6883 return err;
6885 for (i = 0; i < strlen(link_target); i++) {
6886 if (!isprint((unsigned char)link_target[i]))
6887 link_target[i] = '?';
6889 modestr = "@";
6891 else if (S_ISDIR(mode))
6892 modestr = "/";
6893 else if (mode & S_IXUSR)
6894 modestr = "*";
6895 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6896 got_tree_entry_get_name(te), modestr,
6897 link_target ? " -> ": "",
6898 link_target ? link_target : "") == -1) {
6899 free(id_str);
6900 free(link_target);
6901 return got_error_from_errno("asprintf");
6903 free(id_str);
6904 free(link_target);
6906 /* use full line width to determine view->maxx */
6907 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
6908 if (err) {
6909 free(line);
6910 break;
6912 view->maxx = MAX(view->maxx, width);
6913 free(wline);
6914 wline = NULL;
6916 err = format_line(&wline, &width, &scrollx, line, view->x,
6917 view->ncols, 0, 0);
6918 if (err) {
6919 free(line);
6920 break;
6922 if (n == s->selected) {
6923 if (view->focussed)
6924 wstandout(view->window);
6925 s->selected_entry = te;
6927 tc = match_color(&s->colors, line);
6928 if (tc)
6929 wattr_on(view->window,
6930 COLOR_PAIR(tc->colorpair), NULL);
6931 waddwstr(view->window, &wline[scrollx]);
6932 if (tc)
6933 wattr_off(view->window,
6934 COLOR_PAIR(tc->colorpair), NULL);
6935 if (width < view->ncols)
6936 waddch(view->window, '\n');
6937 if (n == s->selected && view->focussed)
6938 wstandend(view->window);
6939 free(line);
6940 free(wline);
6941 wline = NULL;
6942 n++;
6943 s->ndisplayed++;
6944 s->last_displayed_entry = te;
6945 if (--limit <= 0)
6946 break;
6949 return err;
6952 static void
6953 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6955 struct got_tree_entry *te;
6956 int isroot = s->tree == s->root;
6957 int i = 0;
6959 if (s->first_displayed_entry == NULL)
6960 return;
6962 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6963 while (i++ < maxscroll) {
6964 if (te == NULL) {
6965 if (!isroot)
6966 s->first_displayed_entry = NULL;
6967 break;
6969 s->first_displayed_entry = te;
6970 te = got_tree_entry_get_prev(s->tree, te);
6974 static const struct got_error *
6975 tree_scroll_down(struct tog_view *view, int maxscroll)
6977 struct tog_tree_view_state *s = &view->state.tree;
6978 struct got_tree_entry *next, *last;
6979 int n = 0;
6981 if (s->first_displayed_entry)
6982 next = got_tree_entry_get_next(s->tree,
6983 s->first_displayed_entry);
6984 else
6985 next = got_object_tree_get_first_entry(s->tree);
6987 last = s->last_displayed_entry;
6988 while (next && n++ < maxscroll) {
6989 if (last) {
6990 s->last_displayed_entry = last;
6991 last = got_tree_entry_get_next(s->tree, last);
6993 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6994 s->first_displayed_entry = next;
6995 next = got_tree_entry_get_next(s->tree, next);
6999 return NULL;
7002 static const struct got_error *
7003 tree_entry_path(char **path, struct tog_parent_trees *parents,
7004 struct got_tree_entry *te)
7006 const struct got_error *err = NULL;
7007 struct tog_parent_tree *pt;
7008 size_t len = 2; /* for leading slash and NUL */
7010 TAILQ_FOREACH(pt, parents, entry)
7011 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7012 + 1 /* slash */;
7013 if (te)
7014 len += strlen(got_tree_entry_get_name(te));
7016 *path = calloc(1, len);
7017 if (path == NULL)
7018 return got_error_from_errno("calloc");
7020 (*path)[0] = '/';
7021 pt = TAILQ_LAST(parents, tog_parent_trees);
7022 while (pt) {
7023 const char *name = got_tree_entry_get_name(pt->selected_entry);
7024 if (strlcat(*path, name, len) >= len) {
7025 err = got_error(GOT_ERR_NO_SPACE);
7026 goto done;
7028 if (strlcat(*path, "/", len) >= len) {
7029 err = got_error(GOT_ERR_NO_SPACE);
7030 goto done;
7032 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7034 if (te) {
7035 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7036 err = got_error(GOT_ERR_NO_SPACE);
7037 goto done;
7040 done:
7041 if (err) {
7042 free(*path);
7043 *path = NULL;
7045 return err;
7048 static const struct got_error *
7049 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7050 struct got_tree_entry *te, struct tog_parent_trees *parents,
7051 struct got_object_id *commit_id, struct got_repository *repo)
7053 const struct got_error *err = NULL;
7054 char *path;
7055 struct tog_view *blame_view;
7057 *new_view = NULL;
7059 err = tree_entry_path(&path, parents, te);
7060 if (err)
7061 return err;
7063 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7064 if (blame_view == NULL) {
7065 err = got_error_from_errno("view_open");
7066 goto done;
7069 err = open_blame_view(blame_view, path, commit_id, repo);
7070 if (err) {
7071 if (err->code == GOT_ERR_CANCELLED)
7072 err = NULL;
7073 view_close(blame_view);
7074 } else
7075 *new_view = blame_view;
7076 done:
7077 free(path);
7078 return err;
7081 static const struct got_error *
7082 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7083 struct tog_tree_view_state *s)
7085 struct tog_view *log_view;
7086 const struct got_error *err = NULL;
7087 char *path;
7089 *new_view = NULL;
7091 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7092 if (log_view == NULL)
7093 return got_error_from_errno("view_open");
7095 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7096 if (err)
7097 return err;
7099 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7100 path, 0);
7101 if (err)
7102 view_close(log_view);
7103 else
7104 *new_view = log_view;
7105 free(path);
7106 return err;
7109 static const struct got_error *
7110 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7111 const char *head_ref_name, struct got_repository *repo)
7113 const struct got_error *err = NULL;
7114 char *commit_id_str = NULL;
7115 struct tog_tree_view_state *s = &view->state.tree;
7116 struct got_commit_object *commit = NULL;
7118 TAILQ_INIT(&s->parents);
7119 STAILQ_INIT(&s->colors);
7121 s->commit_id = got_object_id_dup(commit_id);
7122 if (s->commit_id == NULL)
7123 return got_error_from_errno("got_object_id_dup");
7125 err = got_object_open_as_commit(&commit, repo, commit_id);
7126 if (err)
7127 goto done;
7130 * The root is opened here and will be closed when the view is closed.
7131 * Any visited subtrees and their path-wise parents are opened and
7132 * closed on demand.
7134 err = got_object_open_as_tree(&s->root, repo,
7135 got_object_commit_get_tree_id(commit));
7136 if (err)
7137 goto done;
7138 s->tree = s->root;
7140 err = got_object_id_str(&commit_id_str, commit_id);
7141 if (err != NULL)
7142 goto done;
7144 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7145 err = got_error_from_errno("asprintf");
7146 goto done;
7149 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7150 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7151 if (head_ref_name) {
7152 s->head_ref_name = strdup(head_ref_name);
7153 if (s->head_ref_name == NULL) {
7154 err = got_error_from_errno("strdup");
7155 goto done;
7158 s->repo = repo;
7160 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7161 err = add_color(&s->colors, "\\$$",
7162 TOG_COLOR_TREE_SUBMODULE,
7163 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7164 if (err)
7165 goto done;
7166 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7167 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7168 if (err)
7169 goto done;
7170 err = add_color(&s->colors, "/$",
7171 TOG_COLOR_TREE_DIRECTORY,
7172 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7173 if (err)
7174 goto done;
7176 err = add_color(&s->colors, "\\*$",
7177 TOG_COLOR_TREE_EXECUTABLE,
7178 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7179 if (err)
7180 goto done;
7182 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7183 get_color_value("TOG_COLOR_COMMIT"));
7184 if (err)
7185 goto done;
7188 view->show = show_tree_view;
7189 view->input = input_tree_view;
7190 view->close = close_tree_view;
7191 view->search_start = search_start_tree_view;
7192 view->search_next = search_next_tree_view;
7193 done:
7194 free(commit_id_str);
7195 if (commit)
7196 got_object_commit_close(commit);
7197 if (err)
7198 close_tree_view(view);
7199 return err;
7202 static const struct got_error *
7203 close_tree_view(struct tog_view *view)
7205 struct tog_tree_view_state *s = &view->state.tree;
7207 free_colors(&s->colors);
7208 free(s->tree_label);
7209 s->tree_label = NULL;
7210 free(s->commit_id);
7211 s->commit_id = NULL;
7212 free(s->head_ref_name);
7213 s->head_ref_name = NULL;
7214 while (!TAILQ_EMPTY(&s->parents)) {
7215 struct tog_parent_tree *parent;
7216 parent = TAILQ_FIRST(&s->parents);
7217 TAILQ_REMOVE(&s->parents, parent, entry);
7218 if (parent->tree != s->root)
7219 got_object_tree_close(parent->tree);
7220 free(parent);
7223 if (s->tree != NULL && s->tree != s->root)
7224 got_object_tree_close(s->tree);
7225 if (s->root)
7226 got_object_tree_close(s->root);
7227 return NULL;
7230 static const struct got_error *
7231 search_start_tree_view(struct tog_view *view)
7233 struct tog_tree_view_state *s = &view->state.tree;
7235 s->matched_entry = NULL;
7236 return NULL;
7239 static int
7240 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7242 regmatch_t regmatch;
7244 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7245 0) == 0;
7248 static const struct got_error *
7249 search_next_tree_view(struct tog_view *view)
7251 struct tog_tree_view_state *s = &view->state.tree;
7252 struct got_tree_entry *te = NULL;
7254 if (!view->searching) {
7255 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7256 return NULL;
7259 if (s->matched_entry) {
7260 if (view->searching == TOG_SEARCH_FORWARD) {
7261 if (s->selected_entry)
7262 te = got_tree_entry_get_next(s->tree,
7263 s->selected_entry);
7264 else
7265 te = got_object_tree_get_first_entry(s->tree);
7266 } else {
7267 if (s->selected_entry == NULL)
7268 te = got_object_tree_get_last_entry(s->tree);
7269 else
7270 te = got_tree_entry_get_prev(s->tree,
7271 s->selected_entry);
7273 } else {
7274 if (s->selected_entry)
7275 te = s->selected_entry;
7276 else if (view->searching == TOG_SEARCH_FORWARD)
7277 te = got_object_tree_get_first_entry(s->tree);
7278 else
7279 te = got_object_tree_get_last_entry(s->tree);
7282 while (1) {
7283 if (te == NULL) {
7284 if (s->matched_entry == NULL) {
7285 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7286 return NULL;
7288 if (view->searching == TOG_SEARCH_FORWARD)
7289 te = got_object_tree_get_first_entry(s->tree);
7290 else
7291 te = got_object_tree_get_last_entry(s->tree);
7294 if (match_tree_entry(te, &view->regex)) {
7295 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7296 s->matched_entry = te;
7297 break;
7300 if (view->searching == TOG_SEARCH_FORWARD)
7301 te = got_tree_entry_get_next(s->tree, te);
7302 else
7303 te = got_tree_entry_get_prev(s->tree, te);
7306 if (s->matched_entry) {
7307 s->first_displayed_entry = s->matched_entry;
7308 s->selected = 0;
7311 return NULL;
7314 static const struct got_error *
7315 show_tree_view(struct tog_view *view)
7317 const struct got_error *err = NULL;
7318 struct tog_tree_view_state *s = &view->state.tree;
7319 char *parent_path;
7321 err = tree_entry_path(&parent_path, &s->parents, NULL);
7322 if (err)
7323 return err;
7325 err = draw_tree_entries(view, parent_path);
7326 free(parent_path);
7328 view_border(view);
7329 return err;
7332 static const struct got_error *
7333 tree_goto_line(struct tog_view *view, int nlines)
7335 const struct got_error *err = NULL;
7336 struct tog_tree_view_state *s = &view->state.tree;
7337 struct got_tree_entry **fte, **lte, **ste;
7338 int g, last, first = 1, i = 1;
7339 int root = s->tree == s->root;
7340 int off = root ? 1 : 2;
7342 g = view->gline;
7343 view->gline = 0;
7345 if (g == 0)
7346 g = 1;
7347 else if (g > got_object_tree_get_nentries(s->tree))
7348 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7350 fte = &s->first_displayed_entry;
7351 lte = &s->last_displayed_entry;
7352 ste = &s->selected_entry;
7354 if (*fte != NULL) {
7355 first = got_tree_entry_get_index(*fte);
7356 first += off; /* account for ".." */
7358 last = got_tree_entry_get_index(*lte);
7359 last += off;
7361 if (g >= first && g <= last && g - first < nlines) {
7362 s->selected = g - first;
7363 return NULL; /* gline is on the current page */
7366 if (*ste != NULL) {
7367 i = got_tree_entry_get_index(*ste);
7368 i += off;
7371 if (i < g) {
7372 err = tree_scroll_down(view, g - i);
7373 if (err)
7374 return err;
7375 if (got_tree_entry_get_index(*lte) >=
7376 got_object_tree_get_nentries(s->tree) - 1 &&
7377 first + s->selected < g &&
7378 s->selected < s->ndisplayed - 1) {
7379 first = got_tree_entry_get_index(*fte);
7380 first += off;
7381 s->selected = g - first;
7383 } else if (i > g)
7384 tree_scroll_up(s, i - g);
7386 if (g < nlines &&
7387 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7388 s->selected = g - 1;
7390 return NULL;
7393 static const struct got_error *
7394 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7396 const struct got_error *err = NULL;
7397 struct tog_tree_view_state *s = &view->state.tree;
7398 struct got_tree_entry *te;
7399 int n, nscroll = view->nlines - 3;
7401 if (view->gline)
7402 return tree_goto_line(view, nscroll);
7404 switch (ch) {
7405 case '0':
7406 case '$':
7407 case KEY_RIGHT:
7408 case 'l':
7409 case KEY_LEFT:
7410 case 'h':
7411 horizontal_scroll_input(view, ch);
7412 break;
7413 case 'i':
7414 s->show_ids = !s->show_ids;
7415 view->count = 0;
7416 break;
7417 case 'L':
7418 view->count = 0;
7419 if (!s->selected_entry)
7420 break;
7421 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7422 break;
7423 case 'R':
7424 view->count = 0;
7425 err = view_request_new(new_view, view, TOG_VIEW_REF);
7426 break;
7427 case 'g':
7428 case '=':
7429 case KEY_HOME:
7430 s->selected = 0;
7431 view->count = 0;
7432 if (s->tree == s->root)
7433 s->first_displayed_entry =
7434 got_object_tree_get_first_entry(s->tree);
7435 else
7436 s->first_displayed_entry = NULL;
7437 break;
7438 case 'G':
7439 case '*':
7440 case KEY_END: {
7441 int eos = view->nlines - 3;
7443 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7444 --eos; /* border */
7445 s->selected = 0;
7446 view->count = 0;
7447 te = got_object_tree_get_last_entry(s->tree);
7448 for (n = 0; n < eos; n++) {
7449 if (te == NULL) {
7450 if (s->tree != s->root) {
7451 s->first_displayed_entry = NULL;
7452 n++;
7454 break;
7456 s->first_displayed_entry = te;
7457 te = got_tree_entry_get_prev(s->tree, te);
7459 if (n > 0)
7460 s->selected = n - 1;
7461 break;
7463 case 'k':
7464 case KEY_UP:
7465 case CTRL('p'):
7466 if (s->selected > 0) {
7467 s->selected--;
7468 break;
7470 tree_scroll_up(s, 1);
7471 if (s->selected_entry == NULL ||
7472 (s->tree == s->root && s->selected_entry ==
7473 got_object_tree_get_first_entry(s->tree)))
7474 view->count = 0;
7475 break;
7476 case CTRL('u'):
7477 case 'u':
7478 nscroll /= 2;
7479 /* FALL THROUGH */
7480 case KEY_PPAGE:
7481 case CTRL('b'):
7482 case 'b':
7483 if (s->tree == s->root) {
7484 if (got_object_tree_get_first_entry(s->tree) ==
7485 s->first_displayed_entry)
7486 s->selected -= MIN(s->selected, nscroll);
7487 } else {
7488 if (s->first_displayed_entry == NULL)
7489 s->selected -= MIN(s->selected, nscroll);
7491 tree_scroll_up(s, MAX(0, nscroll));
7492 if (s->selected_entry == NULL ||
7493 (s->tree == s->root && s->selected_entry ==
7494 got_object_tree_get_first_entry(s->tree)))
7495 view->count = 0;
7496 break;
7497 case 'j':
7498 case KEY_DOWN:
7499 case CTRL('n'):
7500 if (s->selected < s->ndisplayed - 1) {
7501 s->selected++;
7502 break;
7504 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7505 == NULL) {
7506 /* can't scroll any further */
7507 view->count = 0;
7508 break;
7510 tree_scroll_down(view, 1);
7511 break;
7512 case CTRL('d'):
7513 case 'd':
7514 nscroll /= 2;
7515 /* FALL THROUGH */
7516 case KEY_NPAGE:
7517 case CTRL('f'):
7518 case 'f':
7519 case ' ':
7520 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7521 == NULL) {
7522 /* can't scroll any further; move cursor down */
7523 if (s->selected < s->ndisplayed - 1)
7524 s->selected += MIN(nscroll,
7525 s->ndisplayed - s->selected - 1);
7526 else
7527 view->count = 0;
7528 break;
7530 tree_scroll_down(view, nscroll);
7531 break;
7532 case KEY_ENTER:
7533 case '\r':
7534 case KEY_BACKSPACE:
7535 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7536 struct tog_parent_tree *parent;
7537 /* user selected '..' */
7538 if (s->tree == s->root) {
7539 view->count = 0;
7540 break;
7542 parent = TAILQ_FIRST(&s->parents);
7543 TAILQ_REMOVE(&s->parents, parent,
7544 entry);
7545 got_object_tree_close(s->tree);
7546 s->tree = parent->tree;
7547 s->first_displayed_entry =
7548 parent->first_displayed_entry;
7549 s->selected_entry =
7550 parent->selected_entry;
7551 s->selected = parent->selected;
7552 if (s->selected > view->nlines - 3) {
7553 err = offset_selection_down(view);
7554 if (err)
7555 break;
7557 free(parent);
7558 } else if (S_ISDIR(got_tree_entry_get_mode(
7559 s->selected_entry))) {
7560 struct got_tree_object *subtree;
7561 view->count = 0;
7562 err = got_object_open_as_tree(&subtree, s->repo,
7563 got_tree_entry_get_id(s->selected_entry));
7564 if (err)
7565 break;
7566 err = tree_view_visit_subtree(s, subtree);
7567 if (err) {
7568 got_object_tree_close(subtree);
7569 break;
7571 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7572 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7573 break;
7574 case KEY_RESIZE:
7575 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7576 s->selected = view->nlines - 4;
7577 view->count = 0;
7578 break;
7579 default:
7580 view->count = 0;
7581 break;
7584 return err;
7587 __dead static void
7588 usage_tree(void)
7590 endwin();
7591 fprintf(stderr,
7592 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7593 getprogname());
7594 exit(1);
7597 static const struct got_error *
7598 cmd_tree(int argc, char *argv[])
7600 const struct got_error *error;
7601 struct got_repository *repo = NULL;
7602 struct got_worktree *worktree = NULL;
7603 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7604 struct got_object_id *commit_id = NULL;
7605 struct got_commit_object *commit = NULL;
7606 const char *commit_id_arg = NULL;
7607 char *label = NULL;
7608 struct got_reference *ref = NULL;
7609 const char *head_ref_name = NULL;
7610 int ch;
7611 struct tog_view *view;
7612 int *pack_fds = NULL;
7614 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7615 switch (ch) {
7616 case 'c':
7617 commit_id_arg = optarg;
7618 break;
7619 case 'r':
7620 repo_path = realpath(optarg, NULL);
7621 if (repo_path == NULL)
7622 return got_error_from_errno2("realpath",
7623 optarg);
7624 break;
7625 default:
7626 usage_tree();
7627 /* NOTREACHED */
7631 argc -= optind;
7632 argv += optind;
7634 if (argc > 1)
7635 usage_tree();
7637 error = got_repo_pack_fds_open(&pack_fds);
7638 if (error != NULL)
7639 goto done;
7641 if (repo_path == NULL) {
7642 cwd = getcwd(NULL, 0);
7643 if (cwd == NULL)
7644 return got_error_from_errno("getcwd");
7645 error = got_worktree_open(&worktree, cwd);
7646 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7647 goto done;
7648 if (worktree)
7649 repo_path =
7650 strdup(got_worktree_get_repo_path(worktree));
7651 else
7652 repo_path = strdup(cwd);
7653 if (repo_path == NULL) {
7654 error = got_error_from_errno("strdup");
7655 goto done;
7659 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7660 if (error != NULL)
7661 goto done;
7663 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7664 repo, worktree);
7665 if (error)
7666 goto done;
7668 init_curses();
7670 error = apply_unveil(got_repo_get_path(repo), NULL);
7671 if (error)
7672 goto done;
7674 error = tog_load_refs(repo, 0);
7675 if (error)
7676 goto done;
7678 if (commit_id_arg == NULL) {
7679 error = got_repo_match_object_id(&commit_id, &label,
7680 worktree ? got_worktree_get_head_ref_name(worktree) :
7681 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7682 if (error)
7683 goto done;
7684 head_ref_name = label;
7685 } else {
7686 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7687 if (error == NULL)
7688 head_ref_name = got_ref_get_name(ref);
7689 else if (error->code != GOT_ERR_NOT_REF)
7690 goto done;
7691 error = got_repo_match_object_id(&commit_id, NULL,
7692 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7693 if (error)
7694 goto done;
7697 error = got_object_open_as_commit(&commit, repo, commit_id);
7698 if (error)
7699 goto done;
7701 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7702 if (view == NULL) {
7703 error = got_error_from_errno("view_open");
7704 goto done;
7706 error = open_tree_view(view, commit_id, head_ref_name, repo);
7707 if (error)
7708 goto done;
7709 if (!got_path_is_root_dir(in_repo_path)) {
7710 error = tree_view_walk_path(&view->state.tree, commit,
7711 in_repo_path);
7712 if (error)
7713 goto done;
7716 if (worktree) {
7717 /* Release work tree lock. */
7718 got_worktree_close(worktree);
7719 worktree = NULL;
7721 error = view_loop(view);
7722 done:
7723 free(repo_path);
7724 free(cwd);
7725 free(commit_id);
7726 free(label);
7727 if (ref)
7728 got_ref_close(ref);
7729 if (repo) {
7730 const struct got_error *close_err = got_repo_close(repo);
7731 if (error == NULL)
7732 error = close_err;
7734 if (pack_fds) {
7735 const struct got_error *pack_err =
7736 got_repo_pack_fds_close(pack_fds);
7737 if (error == NULL)
7738 error = pack_err;
7740 tog_free_refs();
7741 return error;
7744 static const struct got_error *
7745 ref_view_load_refs(struct tog_ref_view_state *s)
7747 struct got_reflist_entry *sre;
7748 struct tog_reflist_entry *re;
7750 s->nrefs = 0;
7751 TAILQ_FOREACH(sre, &tog_refs, entry) {
7752 if (strncmp(got_ref_get_name(sre->ref),
7753 "refs/got/", 9) == 0 &&
7754 strncmp(got_ref_get_name(sre->ref),
7755 "refs/got/backup/", 16) != 0)
7756 continue;
7758 re = malloc(sizeof(*re));
7759 if (re == NULL)
7760 return got_error_from_errno("malloc");
7762 re->ref = got_ref_dup(sre->ref);
7763 if (re->ref == NULL)
7764 return got_error_from_errno("got_ref_dup");
7765 re->idx = s->nrefs++;
7766 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7769 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7770 return NULL;
7773 static void
7774 ref_view_free_refs(struct tog_ref_view_state *s)
7776 struct tog_reflist_entry *re;
7778 while (!TAILQ_EMPTY(&s->refs)) {
7779 re = TAILQ_FIRST(&s->refs);
7780 TAILQ_REMOVE(&s->refs, re, entry);
7781 got_ref_close(re->ref);
7782 free(re);
7786 static const struct got_error *
7787 open_ref_view(struct tog_view *view, struct got_repository *repo)
7789 const struct got_error *err = NULL;
7790 struct tog_ref_view_state *s = &view->state.ref;
7792 s->selected_entry = 0;
7793 s->repo = repo;
7795 TAILQ_INIT(&s->refs);
7796 STAILQ_INIT(&s->colors);
7798 err = ref_view_load_refs(s);
7799 if (err)
7800 return err;
7802 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7803 err = add_color(&s->colors, "^refs/heads/",
7804 TOG_COLOR_REFS_HEADS,
7805 get_color_value("TOG_COLOR_REFS_HEADS"));
7806 if (err)
7807 goto done;
7809 err = add_color(&s->colors, "^refs/tags/",
7810 TOG_COLOR_REFS_TAGS,
7811 get_color_value("TOG_COLOR_REFS_TAGS"));
7812 if (err)
7813 goto done;
7815 err = add_color(&s->colors, "^refs/remotes/",
7816 TOG_COLOR_REFS_REMOTES,
7817 get_color_value("TOG_COLOR_REFS_REMOTES"));
7818 if (err)
7819 goto done;
7821 err = add_color(&s->colors, "^refs/got/backup/",
7822 TOG_COLOR_REFS_BACKUP,
7823 get_color_value("TOG_COLOR_REFS_BACKUP"));
7824 if (err)
7825 goto done;
7828 view->show = show_ref_view;
7829 view->input = input_ref_view;
7830 view->close = close_ref_view;
7831 view->search_start = search_start_ref_view;
7832 view->search_next = search_next_ref_view;
7833 done:
7834 if (err)
7835 free_colors(&s->colors);
7836 return err;
7839 static const struct got_error *
7840 close_ref_view(struct tog_view *view)
7842 struct tog_ref_view_state *s = &view->state.ref;
7844 ref_view_free_refs(s);
7845 free_colors(&s->colors);
7847 return NULL;
7850 static const struct got_error *
7851 resolve_reflist_entry(struct got_object_id **commit_id,
7852 struct tog_reflist_entry *re, struct got_repository *repo)
7854 const struct got_error *err = NULL;
7855 struct got_object_id *obj_id;
7856 struct got_tag_object *tag = NULL;
7857 int obj_type;
7859 *commit_id = NULL;
7861 err = got_ref_resolve(&obj_id, repo, re->ref);
7862 if (err)
7863 return err;
7865 err = got_object_get_type(&obj_type, repo, obj_id);
7866 if (err)
7867 goto done;
7869 switch (obj_type) {
7870 case GOT_OBJ_TYPE_COMMIT:
7871 *commit_id = obj_id;
7872 break;
7873 case GOT_OBJ_TYPE_TAG:
7874 err = got_object_open_as_tag(&tag, repo, obj_id);
7875 if (err)
7876 goto done;
7877 free(obj_id);
7878 err = got_object_get_type(&obj_type, repo,
7879 got_object_tag_get_object_id(tag));
7880 if (err)
7881 goto done;
7882 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7883 err = got_error(GOT_ERR_OBJ_TYPE);
7884 goto done;
7886 *commit_id = got_object_id_dup(
7887 got_object_tag_get_object_id(tag));
7888 if (*commit_id == NULL) {
7889 err = got_error_from_errno("got_object_id_dup");
7890 goto done;
7892 break;
7893 default:
7894 err = got_error(GOT_ERR_OBJ_TYPE);
7895 break;
7898 done:
7899 if (tag)
7900 got_object_tag_close(tag);
7901 if (err) {
7902 free(*commit_id);
7903 *commit_id = NULL;
7905 return err;
7908 static const struct got_error *
7909 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7910 struct tog_reflist_entry *re, struct got_repository *repo)
7912 struct tog_view *log_view;
7913 const struct got_error *err = NULL;
7914 struct got_object_id *commit_id = NULL;
7916 *new_view = NULL;
7918 err = resolve_reflist_entry(&commit_id, re, repo);
7919 if (err) {
7920 if (err->code != GOT_ERR_OBJ_TYPE)
7921 return err;
7922 else
7923 return NULL;
7926 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7927 if (log_view == NULL) {
7928 err = got_error_from_errno("view_open");
7929 goto done;
7932 err = open_log_view(log_view, commit_id, repo,
7933 got_ref_get_name(re->ref), "", 0);
7934 done:
7935 if (err)
7936 view_close(log_view);
7937 else
7938 *new_view = log_view;
7939 free(commit_id);
7940 return err;
7943 static void
7944 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7946 struct tog_reflist_entry *re;
7947 int i = 0;
7949 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7950 return;
7952 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7953 while (i++ < maxscroll) {
7954 if (re == NULL)
7955 break;
7956 s->first_displayed_entry = re;
7957 re = TAILQ_PREV(re, tog_reflist_head, entry);
7961 static const struct got_error *
7962 ref_scroll_down(struct tog_view *view, int maxscroll)
7964 struct tog_ref_view_state *s = &view->state.ref;
7965 struct tog_reflist_entry *next, *last;
7966 int n = 0;
7968 if (s->first_displayed_entry)
7969 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7970 else
7971 next = TAILQ_FIRST(&s->refs);
7973 last = s->last_displayed_entry;
7974 while (next && n++ < maxscroll) {
7975 if (last) {
7976 s->last_displayed_entry = last;
7977 last = TAILQ_NEXT(last, entry);
7979 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7980 s->first_displayed_entry = next;
7981 next = TAILQ_NEXT(next, entry);
7985 return NULL;
7988 static const struct got_error *
7989 search_start_ref_view(struct tog_view *view)
7991 struct tog_ref_view_state *s = &view->state.ref;
7993 s->matched_entry = NULL;
7994 return NULL;
7997 static int
7998 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8000 regmatch_t regmatch;
8002 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8003 0) == 0;
8006 static const struct got_error *
8007 search_next_ref_view(struct tog_view *view)
8009 struct tog_ref_view_state *s = &view->state.ref;
8010 struct tog_reflist_entry *re = NULL;
8012 if (!view->searching) {
8013 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8014 return NULL;
8017 if (s->matched_entry) {
8018 if (view->searching == TOG_SEARCH_FORWARD) {
8019 if (s->selected_entry)
8020 re = TAILQ_NEXT(s->selected_entry, entry);
8021 else
8022 re = TAILQ_PREV(s->selected_entry,
8023 tog_reflist_head, entry);
8024 } else {
8025 if (s->selected_entry == NULL)
8026 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8027 else
8028 re = TAILQ_PREV(s->selected_entry,
8029 tog_reflist_head, entry);
8031 } else {
8032 if (s->selected_entry)
8033 re = s->selected_entry;
8034 else if (view->searching == TOG_SEARCH_FORWARD)
8035 re = TAILQ_FIRST(&s->refs);
8036 else
8037 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8040 while (1) {
8041 if (re == NULL) {
8042 if (s->matched_entry == NULL) {
8043 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8044 return NULL;
8046 if (view->searching == TOG_SEARCH_FORWARD)
8047 re = TAILQ_FIRST(&s->refs);
8048 else
8049 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8052 if (match_reflist_entry(re, &view->regex)) {
8053 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8054 s->matched_entry = re;
8055 break;
8058 if (view->searching == TOG_SEARCH_FORWARD)
8059 re = TAILQ_NEXT(re, entry);
8060 else
8061 re = TAILQ_PREV(re, tog_reflist_head, entry);
8064 if (s->matched_entry) {
8065 s->first_displayed_entry = s->matched_entry;
8066 s->selected = 0;
8069 return NULL;
8072 static const struct got_error *
8073 show_ref_view(struct tog_view *view)
8075 const struct got_error *err = NULL;
8076 struct tog_ref_view_state *s = &view->state.ref;
8077 struct tog_reflist_entry *re;
8078 char *line = NULL;
8079 wchar_t *wline;
8080 struct tog_color *tc;
8081 int width, n, scrollx;
8082 int limit = view->nlines;
8084 werase(view->window);
8086 s->ndisplayed = 0;
8087 if (view_is_hsplit_top(view))
8088 --limit; /* border */
8090 if (limit == 0)
8091 return NULL;
8093 re = s->first_displayed_entry;
8095 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8096 s->nrefs) == -1)
8097 return got_error_from_errno("asprintf");
8099 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8100 if (err) {
8101 free(line);
8102 return err;
8104 if (view_needs_focus_indication(view))
8105 wstandout(view->window);
8106 waddwstr(view->window, wline);
8107 while (width++ < view->ncols)
8108 waddch(view->window, ' ');
8109 if (view_needs_focus_indication(view))
8110 wstandend(view->window);
8111 free(wline);
8112 wline = NULL;
8113 free(line);
8114 line = NULL;
8115 if (--limit <= 0)
8116 return NULL;
8118 n = 0;
8119 view->maxx = 0;
8120 while (re && limit > 0) {
8121 char *line = NULL;
8122 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8124 if (s->show_date) {
8125 struct got_commit_object *ci;
8126 struct got_tag_object *tag;
8127 struct got_object_id *id;
8128 struct tm tm;
8129 time_t t;
8131 err = got_ref_resolve(&id, s->repo, re->ref);
8132 if (err)
8133 return err;
8134 err = got_object_open_as_tag(&tag, s->repo, id);
8135 if (err) {
8136 if (err->code != GOT_ERR_OBJ_TYPE) {
8137 free(id);
8138 return err;
8140 err = got_object_open_as_commit(&ci, s->repo,
8141 id);
8142 if (err) {
8143 free(id);
8144 return err;
8146 t = got_object_commit_get_committer_time(ci);
8147 got_object_commit_close(ci);
8148 } else {
8149 t = got_object_tag_get_tagger_time(tag);
8150 got_object_tag_close(tag);
8152 free(id);
8153 if (gmtime_r(&t, &tm) == NULL)
8154 return got_error_from_errno("gmtime_r");
8155 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8156 return got_error(GOT_ERR_NO_SPACE);
8158 if (got_ref_is_symbolic(re->ref)) {
8159 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8160 ymd : "", got_ref_get_name(re->ref),
8161 got_ref_get_symref_target(re->ref)) == -1)
8162 return got_error_from_errno("asprintf");
8163 } else if (s->show_ids) {
8164 struct got_object_id *id;
8165 char *id_str;
8166 err = got_ref_resolve(&id, s->repo, re->ref);
8167 if (err)
8168 return err;
8169 err = got_object_id_str(&id_str, id);
8170 if (err) {
8171 free(id);
8172 return err;
8174 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8175 got_ref_get_name(re->ref), id_str) == -1) {
8176 err = got_error_from_errno("asprintf");
8177 free(id);
8178 free(id_str);
8179 return err;
8181 free(id);
8182 free(id_str);
8183 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8184 got_ref_get_name(re->ref)) == -1)
8185 return got_error_from_errno("asprintf");
8187 /* use full line width to determine view->maxx */
8188 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8189 if (err) {
8190 free(line);
8191 return err;
8193 view->maxx = MAX(view->maxx, width);
8194 free(wline);
8195 wline = NULL;
8197 err = format_line(&wline, &width, &scrollx, line, view->x,
8198 view->ncols, 0, 0);
8199 if (err) {
8200 free(line);
8201 return err;
8203 if (n == s->selected) {
8204 if (view->focussed)
8205 wstandout(view->window);
8206 s->selected_entry = re;
8208 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8209 if (tc)
8210 wattr_on(view->window,
8211 COLOR_PAIR(tc->colorpair), NULL);
8212 waddwstr(view->window, &wline[scrollx]);
8213 if (tc)
8214 wattr_off(view->window,
8215 COLOR_PAIR(tc->colorpair), NULL);
8216 if (width < view->ncols)
8217 waddch(view->window, '\n');
8218 if (n == s->selected && view->focussed)
8219 wstandend(view->window);
8220 free(line);
8221 free(wline);
8222 wline = NULL;
8223 n++;
8224 s->ndisplayed++;
8225 s->last_displayed_entry = re;
8227 limit--;
8228 re = TAILQ_NEXT(re, entry);
8231 view_border(view);
8232 return err;
8235 static const struct got_error *
8236 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8237 struct tog_reflist_entry *re, struct got_repository *repo)
8239 const struct got_error *err = NULL;
8240 struct got_object_id *commit_id = NULL;
8241 struct tog_view *tree_view;
8243 *new_view = NULL;
8245 err = resolve_reflist_entry(&commit_id, re, repo);
8246 if (err) {
8247 if (err->code != GOT_ERR_OBJ_TYPE)
8248 return err;
8249 else
8250 return NULL;
8254 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8255 if (tree_view == NULL) {
8256 err = got_error_from_errno("view_open");
8257 goto done;
8260 err = open_tree_view(tree_view, commit_id,
8261 got_ref_get_name(re->ref), repo);
8262 if (err)
8263 goto done;
8265 *new_view = tree_view;
8266 done:
8267 free(commit_id);
8268 return err;
8271 static const struct got_error *
8272 ref_goto_line(struct tog_view *view, int nlines)
8274 const struct got_error *err = NULL;
8275 struct tog_ref_view_state *s = &view->state.ref;
8276 int g, idx = s->selected_entry->idx;
8278 g = view->gline;
8279 view->gline = 0;
8281 if (g == 0)
8282 g = 1;
8283 else if (g > s->nrefs)
8284 g = s->nrefs;
8286 if (g >= s->first_displayed_entry->idx + 1 &&
8287 g <= s->last_displayed_entry->idx + 1 &&
8288 g - s->first_displayed_entry->idx - 1 < nlines) {
8289 s->selected = g - s->first_displayed_entry->idx - 1;
8290 return NULL;
8293 if (idx + 1 < g) {
8294 err = ref_scroll_down(view, g - idx - 1);
8295 if (err)
8296 return err;
8297 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8298 s->first_displayed_entry->idx + s->selected < g &&
8299 s->selected < s->ndisplayed - 1)
8300 s->selected = g - s->first_displayed_entry->idx - 1;
8301 } else if (idx + 1 > g)
8302 ref_scroll_up(s, idx - g + 1);
8304 if (g < nlines && s->first_displayed_entry->idx == 0)
8305 s->selected = g - 1;
8307 return NULL;
8311 static const struct got_error *
8312 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8314 const struct got_error *err = NULL;
8315 struct tog_ref_view_state *s = &view->state.ref;
8316 struct tog_reflist_entry *re;
8317 int n, nscroll = view->nlines - 1;
8319 if (view->gline)
8320 return ref_goto_line(view, nscroll);
8322 switch (ch) {
8323 case '0':
8324 case '$':
8325 case KEY_RIGHT:
8326 case 'l':
8327 case KEY_LEFT:
8328 case 'h':
8329 horizontal_scroll_input(view, ch);
8330 break;
8331 case 'i':
8332 s->show_ids = !s->show_ids;
8333 view->count = 0;
8334 break;
8335 case 'm':
8336 s->show_date = !s->show_date;
8337 view->count = 0;
8338 break;
8339 case 'o':
8340 s->sort_by_date = !s->sort_by_date;
8341 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8342 view->count = 0;
8343 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8344 got_ref_cmp_by_commit_timestamp_descending :
8345 tog_ref_cmp_by_name, s->repo);
8346 if (err)
8347 break;
8348 got_reflist_object_id_map_free(tog_refs_idmap);
8349 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8350 &tog_refs, s->repo);
8351 if (err)
8352 break;
8353 ref_view_free_refs(s);
8354 err = ref_view_load_refs(s);
8355 break;
8356 case KEY_ENTER:
8357 case '\r':
8358 view->count = 0;
8359 if (!s->selected_entry)
8360 break;
8361 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8362 break;
8363 case 'T':
8364 view->count = 0;
8365 if (!s->selected_entry)
8366 break;
8367 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8368 break;
8369 case 'g':
8370 case '=':
8371 case KEY_HOME:
8372 s->selected = 0;
8373 view->count = 0;
8374 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8375 break;
8376 case 'G':
8377 case '*':
8378 case KEY_END: {
8379 int eos = view->nlines - 1;
8381 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8382 --eos; /* border */
8383 s->selected = 0;
8384 view->count = 0;
8385 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8386 for (n = 0; n < eos; n++) {
8387 if (re == NULL)
8388 break;
8389 s->first_displayed_entry = re;
8390 re = TAILQ_PREV(re, tog_reflist_head, entry);
8392 if (n > 0)
8393 s->selected = n - 1;
8394 break;
8396 case 'k':
8397 case KEY_UP:
8398 case CTRL('p'):
8399 if (s->selected > 0) {
8400 s->selected--;
8401 break;
8403 ref_scroll_up(s, 1);
8404 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8405 view->count = 0;
8406 break;
8407 case CTRL('u'):
8408 case 'u':
8409 nscroll /= 2;
8410 /* FALL THROUGH */
8411 case KEY_PPAGE:
8412 case CTRL('b'):
8413 case 'b':
8414 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8415 s->selected -= MIN(nscroll, s->selected);
8416 ref_scroll_up(s, MAX(0, nscroll));
8417 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8418 view->count = 0;
8419 break;
8420 case 'j':
8421 case KEY_DOWN:
8422 case CTRL('n'):
8423 if (s->selected < s->ndisplayed - 1) {
8424 s->selected++;
8425 break;
8427 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8428 /* can't scroll any further */
8429 view->count = 0;
8430 break;
8432 ref_scroll_down(view, 1);
8433 break;
8434 case CTRL('d'):
8435 case 'd':
8436 nscroll /= 2;
8437 /* FALL THROUGH */
8438 case KEY_NPAGE:
8439 case CTRL('f'):
8440 case 'f':
8441 case ' ':
8442 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8443 /* can't scroll any further; move cursor down */
8444 if (s->selected < s->ndisplayed - 1)
8445 s->selected += MIN(nscroll,
8446 s->ndisplayed - s->selected - 1);
8447 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8448 s->selected += s->ndisplayed - s->selected - 1;
8449 view->count = 0;
8450 break;
8452 ref_scroll_down(view, nscroll);
8453 break;
8454 case CTRL('l'):
8455 view->count = 0;
8456 tog_free_refs();
8457 err = tog_load_refs(s->repo, s->sort_by_date);
8458 if (err)
8459 break;
8460 ref_view_free_refs(s);
8461 err = ref_view_load_refs(s);
8462 break;
8463 case KEY_RESIZE:
8464 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8465 s->selected = view->nlines - 2;
8466 break;
8467 default:
8468 view->count = 0;
8469 break;
8472 return err;
8475 __dead static void
8476 usage_ref(void)
8478 endwin();
8479 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8480 getprogname());
8481 exit(1);
8484 static const struct got_error *
8485 cmd_ref(int argc, char *argv[])
8487 const struct got_error *error;
8488 struct got_repository *repo = NULL;
8489 struct got_worktree *worktree = NULL;
8490 char *cwd = NULL, *repo_path = NULL;
8491 int ch;
8492 struct tog_view *view;
8493 int *pack_fds = NULL;
8495 while ((ch = getopt(argc, argv, "r:")) != -1) {
8496 switch (ch) {
8497 case 'r':
8498 repo_path = realpath(optarg, NULL);
8499 if (repo_path == NULL)
8500 return got_error_from_errno2("realpath",
8501 optarg);
8502 break;
8503 default:
8504 usage_ref();
8505 /* NOTREACHED */
8509 argc -= optind;
8510 argv += optind;
8512 if (argc > 1)
8513 usage_ref();
8515 error = got_repo_pack_fds_open(&pack_fds);
8516 if (error != NULL)
8517 goto done;
8519 if (repo_path == NULL) {
8520 cwd = getcwd(NULL, 0);
8521 if (cwd == NULL)
8522 return got_error_from_errno("getcwd");
8523 error = got_worktree_open(&worktree, cwd);
8524 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8525 goto done;
8526 if (worktree)
8527 repo_path =
8528 strdup(got_worktree_get_repo_path(worktree));
8529 else
8530 repo_path = strdup(cwd);
8531 if (repo_path == NULL) {
8532 error = got_error_from_errno("strdup");
8533 goto done;
8537 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8538 if (error != NULL)
8539 goto done;
8541 init_curses();
8543 error = apply_unveil(got_repo_get_path(repo), NULL);
8544 if (error)
8545 goto done;
8547 error = tog_load_refs(repo, 0);
8548 if (error)
8549 goto done;
8551 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8552 if (view == NULL) {
8553 error = got_error_from_errno("view_open");
8554 goto done;
8557 error = open_ref_view(view, repo);
8558 if (error)
8559 goto done;
8561 if (worktree) {
8562 /* Release work tree lock. */
8563 got_worktree_close(worktree);
8564 worktree = NULL;
8566 error = view_loop(view);
8567 done:
8568 free(repo_path);
8569 free(cwd);
8570 if (repo) {
8571 const struct got_error *close_err = got_repo_close(repo);
8572 if (close_err)
8573 error = close_err;
8575 if (pack_fds) {
8576 const struct got_error *pack_err =
8577 got_repo_pack_fds_close(pack_fds);
8578 if (error == NULL)
8579 error = pack_err;
8581 tog_free_refs();
8582 return error;
8585 static const struct got_error*
8586 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8587 const char *str)
8589 size_t len;
8591 if (win == NULL)
8592 win = stdscr;
8594 len = strlen(str);
8595 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8597 if (focus)
8598 wstandout(win);
8599 if (mvwprintw(win, y, x, "%s", str) == ERR)
8600 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8601 if (focus)
8602 wstandend(win);
8604 return NULL;
8607 static const struct got_error *
8608 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8610 off_t *p;
8612 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8613 if (p == NULL) {
8614 free(*line_offsets);
8615 *line_offsets = NULL;
8616 return got_error_from_errno("reallocarray");
8619 *line_offsets = p;
8620 (*line_offsets)[*nlines] = off;
8621 ++(*nlines);
8622 return NULL;
8625 static const struct got_error *
8626 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8628 *ret = 0;
8630 for (;n > 0; --n, ++km) {
8631 char *t0, *t, *k;
8632 size_t len = 1;
8634 if (km->keys == NULL)
8635 continue;
8637 t = t0 = strdup(km->keys);
8638 if (t0 == NULL)
8639 return got_error_from_errno("strdup");
8641 len += strlen(t);
8642 while ((k = strsep(&t, " ")) != NULL)
8643 len += strlen(k) > 1 ? 2 : 0;
8644 free(t0);
8645 *ret = MAX(*ret, len);
8648 return NULL;
8652 * Write keymap section headers, keys, and key info in km to f.
8653 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8654 * wrap control and symbolic keys in guillemets, else use <>.
8656 static const struct got_error *
8657 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8659 int n, len = width;
8661 if (km->keys) {
8662 static const char *u8_glyph[] = {
8663 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8664 "\xe2\x80\xba" /* U+203A (utf8 >) */
8666 char *t0, *t, *k;
8667 int cs, s, first = 1;
8669 cs = got_locale_is_utf8();
8671 t = t0 = strdup(km->keys);
8672 if (t0 == NULL)
8673 return got_error_from_errno("strdup");
8675 len = strlen(km->keys);
8676 while ((k = strsep(&t, " ")) != NULL) {
8677 s = strlen(k) > 1; /* control or symbolic key */
8678 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8679 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8680 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8681 if (n < 0) {
8682 free(t0);
8683 return got_error_from_errno("fprintf");
8685 first = 0;
8686 len += s ? 2 : 0;
8687 *off += n;
8689 free(t0);
8691 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8692 if (n < 0)
8693 return got_error_from_errno("fprintf");
8694 *off += n;
8696 return NULL;
8699 static const struct got_error *
8700 format_help(struct tog_help_view_state *s)
8702 const struct got_error *err = NULL;
8703 off_t off = 0;
8704 int i, max, n, show = s->all;
8705 static const struct tog_key_map km[] = {
8706 #define KEYMAP_(info, type) { NULL, (info), type }
8707 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8708 GENERATE_HELP
8709 #undef KEYMAP_
8710 #undef KEY_
8713 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8714 if (err)
8715 return err;
8717 n = nitems(km);
8718 err = max_key_str(&max, km, n);
8719 if (err)
8720 return err;
8722 for (i = 0; i < n; ++i) {
8723 if (km[i].keys == NULL) {
8724 show = s->all;
8725 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8726 km[i].type == s->type || s->all)
8727 show = 1;
8729 if (show) {
8730 err = format_help_line(&off, s->f, &km[i], max);
8731 if (err)
8732 return err;
8733 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8734 if (err)
8735 return err;
8738 fputc('\n', s->f);
8739 ++off;
8740 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8741 return err;
8744 static const struct got_error *
8745 create_help(struct tog_help_view_state *s)
8747 FILE *f;
8748 const struct got_error *err;
8750 free(s->line_offsets);
8751 s->line_offsets = NULL;
8752 s->nlines = 0;
8754 f = got_opentemp();
8755 if (f == NULL)
8756 return got_error_from_errno("got_opentemp");
8757 s->f = f;
8759 err = format_help(s);
8760 if (err)
8761 return err;
8763 if (s->f && fflush(s->f) != 0)
8764 return got_error_from_errno("fflush");
8766 return NULL;
8769 static const struct got_error *
8770 search_start_help_view(struct tog_view *view)
8772 view->state.help.matched_line = 0;
8773 return NULL;
8776 static void
8777 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8778 size_t *nlines, int **first, int **last, int **match, int **selected)
8780 struct tog_help_view_state *s = &view->state.help;
8782 *f = s->f;
8783 *nlines = s->nlines;
8784 *line_offsets = s->line_offsets;
8785 *match = &s->matched_line;
8786 *first = &s->first_displayed_line;
8787 *last = &s->last_displayed_line;
8788 *selected = &s->selected_line;
8791 static const struct got_error *
8792 show_help_view(struct tog_view *view)
8794 struct tog_help_view_state *s = &view->state.help;
8795 const struct got_error *err;
8796 regmatch_t *regmatch = &view->regmatch;
8797 wchar_t *wline;
8798 char *line;
8799 ssize_t linelen;
8800 size_t linesz = 0;
8801 int width, nprinted = 0, rc = 0;
8802 int eos = view->nlines;
8804 if (view_is_hsplit_top(view))
8805 --eos; /* account for border */
8807 s->lineno = 0;
8808 rewind(s->f);
8809 werase(view->window);
8811 if (view->gline > s->nlines - 1)
8812 view->gline = s->nlines - 1;
8814 err = win_draw_center(view->window, 0, 0, view->ncols,
8815 view_needs_focus_indication(view),
8816 "tog help (press q to return to tog)");
8817 if (err)
8818 return err;
8819 if (eos <= 1)
8820 return NULL;
8821 waddstr(view->window, "\n\n");
8822 eos -= 2;
8824 s->eof = 0;
8825 view->maxx = 0;
8826 line = NULL;
8827 while (eos > 0 && nprinted < eos) {
8828 attr_t attr = 0;
8830 linelen = getline(&line, &linesz, s->f);
8831 if (linelen == -1) {
8832 if (!feof(s->f)) {
8833 free(line);
8834 return got_ferror(s->f, GOT_ERR_IO);
8836 s->eof = 1;
8837 break;
8839 if (++s->lineno < s->first_displayed_line)
8840 continue;
8841 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8842 continue;
8843 if (s->lineno == view->hiline)
8844 attr = A_STANDOUT;
8846 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8847 view->x ? 1 : 0);
8848 if (err) {
8849 free(line);
8850 return err;
8852 view->maxx = MAX(view->maxx, width);
8853 free(wline);
8854 wline = NULL;
8856 if (attr)
8857 wattron(view->window, attr);
8858 if (s->first_displayed_line + nprinted == s->matched_line &&
8859 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8860 err = add_matched_line(&width, line, view->ncols - 1, 0,
8861 view->window, view->x, regmatch);
8862 if (err) {
8863 free(line);
8864 return err;
8866 } else {
8867 int skip;
8869 err = format_line(&wline, &width, &skip, line,
8870 view->x, view->ncols, 0, view->x ? 1 : 0);
8871 if (err) {
8872 free(line);
8873 return err;
8875 waddwstr(view->window, &wline[skip]);
8876 free(wline);
8877 wline = NULL;
8879 if (s->lineno == view->hiline) {
8880 while (width++ < view->ncols)
8881 waddch(view->window, ' ');
8882 } else {
8883 if (width < view->ncols)
8884 waddch(view->window, '\n');
8886 if (attr)
8887 wattroff(view->window, attr);
8888 if (++nprinted == 1)
8889 s->first_displayed_line = s->lineno;
8891 free(line);
8892 if (nprinted > 0)
8893 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8894 else
8895 s->last_displayed_line = s->first_displayed_line;
8897 view_border(view);
8899 if (s->eof) {
8900 rc = waddnstr(view->window,
8901 "See the tog(1) manual page for full documentation",
8902 view->ncols - 1);
8903 if (rc == ERR)
8904 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8905 } else {
8906 wmove(view->window, view->nlines - 1, 0);
8907 wclrtoeol(view->window);
8908 wstandout(view->window);
8909 rc = waddnstr(view->window, "scroll down for more...",
8910 view->ncols - 1);
8911 if (rc == ERR)
8912 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8913 if (getcurx(view->window) < view->ncols - 6) {
8914 rc = wprintw(view->window, "[%.0f%%]",
8915 100.00 * s->last_displayed_line / s->nlines);
8916 if (rc == ERR)
8917 return got_error_msg(GOT_ERR_IO, "wprintw");
8919 wstandend(view->window);
8922 return NULL;
8925 static const struct got_error *
8926 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8928 struct tog_help_view_state *s = &view->state.help;
8929 const struct got_error *err = NULL;
8930 char *line = NULL;
8931 ssize_t linelen;
8932 size_t linesz = 0;
8933 int eos, nscroll;
8935 eos = nscroll = view->nlines;
8936 if (view_is_hsplit_top(view))
8937 --eos; /* border */
8939 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8941 switch (ch) {
8942 case '0':
8943 case '$':
8944 case KEY_RIGHT:
8945 case 'l':
8946 case KEY_LEFT:
8947 case 'h':
8948 horizontal_scroll_input(view, ch);
8949 break;
8950 case 'g':
8951 case KEY_HOME:
8952 s->first_displayed_line = 1;
8953 view->count = 0;
8954 break;
8955 case 'G':
8956 case KEY_END:
8957 view->count = 0;
8958 if (s->eof)
8959 break;
8960 s->first_displayed_line = (s->nlines - eos) + 3;
8961 s->eof = 1;
8962 break;
8963 case 'k':
8964 case KEY_UP:
8965 if (s->first_displayed_line > 1)
8966 --s->first_displayed_line;
8967 else
8968 view->count = 0;
8969 break;
8970 case CTRL('u'):
8971 case 'u':
8972 nscroll /= 2;
8973 /* FALL THROUGH */
8974 case KEY_PPAGE:
8975 case CTRL('b'):
8976 case 'b':
8977 if (s->first_displayed_line == 1) {
8978 view->count = 0;
8979 break;
8981 while (--nscroll > 0 && s->first_displayed_line > 1)
8982 s->first_displayed_line--;
8983 break;
8984 case 'j':
8985 case KEY_DOWN:
8986 case CTRL('n'):
8987 if (!s->eof)
8988 ++s->first_displayed_line;
8989 else
8990 view->count = 0;
8991 break;
8992 case CTRL('d'):
8993 case 'd':
8994 nscroll /= 2;
8995 /* FALL THROUGH */
8996 case KEY_NPAGE:
8997 case CTRL('f'):
8998 case 'f':
8999 case ' ':
9000 if (s->eof) {
9001 view->count = 0;
9002 break;
9004 while (!s->eof && --nscroll > 0) {
9005 linelen = getline(&line, &linesz, s->f);
9006 s->first_displayed_line++;
9007 if (linelen == -1) {
9008 if (feof(s->f))
9009 s->eof = 1;
9010 else
9011 err = got_ferror(s->f, GOT_ERR_IO);
9012 break;
9015 free(line);
9016 break;
9017 default:
9018 view->count = 0;
9019 break;
9022 return err;
9025 static const struct got_error *
9026 close_help_view(struct tog_view *view)
9028 struct tog_help_view_state *s = &view->state.help;
9030 free(s->line_offsets);
9031 s->line_offsets = NULL;
9032 if (fclose(s->f) == EOF)
9033 return got_error_from_errno("fclose");
9035 return NULL;
9038 static const struct got_error *
9039 reset_help_view(struct tog_view *view)
9041 struct tog_help_view_state *s = &view->state.help;
9044 if (s->f && fclose(s->f) == EOF)
9045 return got_error_from_errno("fclose");
9047 wclear(view->window);
9048 view->count = 0;
9049 view->x = 0;
9050 s->all = !s->all;
9051 s->first_displayed_line = 1;
9052 s->last_displayed_line = view->nlines;
9053 s->matched_line = 0;
9055 return create_help(s);
9058 static const struct got_error *
9059 open_help_view(struct tog_view *view, struct tog_view *parent)
9061 const struct got_error *err = NULL;
9062 struct tog_help_view_state *s = &view->state.help;
9064 s->type = (enum tog_keymap_type)parent->type;
9065 s->first_displayed_line = 1;
9066 s->last_displayed_line = view->nlines;
9067 s->selected_line = 1;
9069 view->show = show_help_view;
9070 view->input = input_help_view;
9071 view->reset = reset_help_view;
9072 view->close = close_help_view;
9073 view->search_start = search_start_help_view;
9074 view->search_setup = search_setup_help_view;
9075 view->search_next = search_next_view_match;
9077 err = create_help(s);
9078 return err;
9081 static const struct got_error *
9082 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9083 enum tog_view_type request, int y, int x)
9085 const struct got_error *err = NULL;
9087 *new_view = NULL;
9089 switch (request) {
9090 case TOG_VIEW_DIFF:
9091 if (view->type == TOG_VIEW_LOG) {
9092 struct tog_log_view_state *s = &view->state.log;
9094 err = open_diff_view_for_commit(new_view, y, x,
9095 s->selected_entry->commit, s->selected_entry->id,
9096 view, s->repo);
9097 } else
9098 return got_error_msg(GOT_ERR_NOT_IMPL,
9099 "parent/child view pair not supported");
9100 break;
9101 case TOG_VIEW_BLAME:
9102 if (view->type == TOG_VIEW_TREE) {
9103 struct tog_tree_view_state *s = &view->state.tree;
9105 err = blame_tree_entry(new_view, y, x,
9106 s->selected_entry, &s->parents, s->commit_id,
9107 s->repo);
9108 } else
9109 return got_error_msg(GOT_ERR_NOT_IMPL,
9110 "parent/child view pair not supported");
9111 break;
9112 case TOG_VIEW_LOG:
9113 if (view->type == TOG_VIEW_BLAME)
9114 err = log_annotated_line(new_view, y, x,
9115 view->state.blame.repo, view->state.blame.id_to_log);
9116 else if (view->type == TOG_VIEW_TREE)
9117 err = log_selected_tree_entry(new_view, y, x,
9118 &view->state.tree);
9119 else if (view->type == TOG_VIEW_REF)
9120 err = log_ref_entry(new_view, y, x,
9121 view->state.ref.selected_entry,
9122 view->state.ref.repo);
9123 else
9124 return got_error_msg(GOT_ERR_NOT_IMPL,
9125 "parent/child view pair not supported");
9126 break;
9127 case TOG_VIEW_TREE:
9128 if (view->type == TOG_VIEW_LOG)
9129 err = browse_commit_tree(new_view, y, x,
9130 view->state.log.selected_entry,
9131 view->state.log.in_repo_path,
9132 view->state.log.head_ref_name,
9133 view->state.log.repo);
9134 else if (view->type == TOG_VIEW_REF)
9135 err = browse_ref_tree(new_view, y, x,
9136 view->state.ref.selected_entry,
9137 view->state.ref.repo);
9138 else
9139 return got_error_msg(GOT_ERR_NOT_IMPL,
9140 "parent/child view pair not supported");
9141 break;
9142 case TOG_VIEW_REF:
9143 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9144 if (*new_view == NULL)
9145 return got_error_from_errno("view_open");
9146 if (view->type == TOG_VIEW_LOG)
9147 err = open_ref_view(*new_view, view->state.log.repo);
9148 else if (view->type == TOG_VIEW_TREE)
9149 err = open_ref_view(*new_view, view->state.tree.repo);
9150 else
9151 err = got_error_msg(GOT_ERR_NOT_IMPL,
9152 "parent/child view pair not supported");
9153 if (err)
9154 view_close(*new_view);
9155 break;
9156 case TOG_VIEW_HELP:
9157 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9158 if (*new_view == NULL)
9159 return got_error_from_errno("view_open");
9160 err = open_help_view(*new_view, view);
9161 if (err)
9162 view_close(*new_view);
9163 break;
9164 default:
9165 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9168 return err;
9172 * If view was scrolled down to move the selected line into view when opening a
9173 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9175 static void
9176 offset_selection_up(struct tog_view *view)
9178 switch (view->type) {
9179 case TOG_VIEW_BLAME: {
9180 struct tog_blame_view_state *s = &view->state.blame;
9181 if (s->first_displayed_line == 1) {
9182 s->selected_line = MAX(s->selected_line - view->offset,
9183 1);
9184 break;
9186 if (s->first_displayed_line > view->offset)
9187 s->first_displayed_line -= view->offset;
9188 else
9189 s->first_displayed_line = 1;
9190 s->selected_line += view->offset;
9191 break;
9193 case TOG_VIEW_LOG:
9194 log_scroll_up(&view->state.log, view->offset);
9195 view->state.log.selected += view->offset;
9196 break;
9197 case TOG_VIEW_REF:
9198 ref_scroll_up(&view->state.ref, view->offset);
9199 view->state.ref.selected += view->offset;
9200 break;
9201 case TOG_VIEW_TREE:
9202 tree_scroll_up(&view->state.tree, view->offset);
9203 view->state.tree.selected += view->offset;
9204 break;
9205 default:
9206 break;
9209 view->offset = 0;
9213 * If the selected line is in the section of screen covered by the bottom split,
9214 * scroll down offset lines to move it into view and index its new position.
9216 static const struct got_error *
9217 offset_selection_down(struct tog_view *view)
9219 const struct got_error *err = NULL;
9220 const struct got_error *(*scrolld)(struct tog_view *, int);
9221 int *selected = NULL;
9222 int header, offset;
9224 switch (view->type) {
9225 case TOG_VIEW_BLAME: {
9226 struct tog_blame_view_state *s = &view->state.blame;
9227 header = 3;
9228 scrolld = NULL;
9229 if (s->selected_line > view->nlines - header) {
9230 offset = abs(view->nlines - s->selected_line - header);
9231 s->first_displayed_line += offset;
9232 s->selected_line -= offset;
9233 view->offset = offset;
9235 break;
9237 case TOG_VIEW_LOG: {
9238 struct tog_log_view_state *s = &view->state.log;
9239 scrolld = &log_scroll_down;
9240 header = view_is_parent_view(view) ? 3 : 2;
9241 selected = &s->selected;
9242 break;
9244 case TOG_VIEW_REF: {
9245 struct tog_ref_view_state *s = &view->state.ref;
9246 scrolld = &ref_scroll_down;
9247 header = 3;
9248 selected = &s->selected;
9249 break;
9251 case TOG_VIEW_TREE: {
9252 struct tog_tree_view_state *s = &view->state.tree;
9253 scrolld = &tree_scroll_down;
9254 header = 5;
9255 selected = &s->selected;
9256 break;
9258 default:
9259 selected = NULL;
9260 scrolld = NULL;
9261 header = 0;
9262 break;
9265 if (selected && *selected > view->nlines - header) {
9266 offset = abs(view->nlines - *selected - header);
9267 view->offset = offset;
9268 if (scrolld && offset) {
9269 err = scrolld(view, offset);
9270 *selected -= offset;
9274 return err;
9277 static void
9278 list_commands(FILE *fp)
9280 size_t i;
9282 fprintf(fp, "commands:");
9283 for (i = 0; i < nitems(tog_commands); i++) {
9284 const struct tog_cmd *cmd = &tog_commands[i];
9285 fprintf(fp, " %s", cmd->name);
9287 fputc('\n', fp);
9290 __dead static void
9291 usage(int hflag, int status)
9293 FILE *fp = (status == 0) ? stdout : stderr;
9295 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9296 getprogname());
9297 if (hflag) {
9298 fprintf(fp, "lazy usage: %s path\n", getprogname());
9299 list_commands(fp);
9301 exit(status);
9304 static char **
9305 make_argv(int argc, ...)
9307 va_list ap;
9308 char **argv;
9309 int i;
9311 va_start(ap, argc);
9313 argv = calloc(argc, sizeof(char *));
9314 if (argv == NULL)
9315 err(1, "calloc");
9316 for (i = 0; i < argc; i++) {
9317 argv[i] = strdup(va_arg(ap, char *));
9318 if (argv[i] == NULL)
9319 err(1, "strdup");
9322 va_end(ap);
9323 return argv;
9327 * Try to convert 'tog path' into a 'tog log path' command.
9328 * The user could simply have mistyped the command rather than knowingly
9329 * provided a path. So check whether argv[0] can in fact be resolved
9330 * to a path in the HEAD commit and print a special error if not.
9331 * This hack is for mpi@ <3
9333 static const struct got_error *
9334 tog_log_with_path(int argc, char *argv[])
9336 const struct got_error *error = NULL, *close_err;
9337 const struct tog_cmd *cmd = NULL;
9338 struct got_repository *repo = NULL;
9339 struct got_worktree *worktree = NULL;
9340 struct got_object_id *commit_id = NULL, *id = NULL;
9341 struct got_commit_object *commit = NULL;
9342 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9343 char *commit_id_str = NULL, **cmd_argv = NULL;
9344 int *pack_fds = NULL;
9346 cwd = getcwd(NULL, 0);
9347 if (cwd == NULL)
9348 return got_error_from_errno("getcwd");
9350 error = got_repo_pack_fds_open(&pack_fds);
9351 if (error != NULL)
9352 goto done;
9354 error = got_worktree_open(&worktree, cwd);
9355 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9356 goto done;
9358 if (worktree)
9359 repo_path = strdup(got_worktree_get_repo_path(worktree));
9360 else
9361 repo_path = strdup(cwd);
9362 if (repo_path == NULL) {
9363 error = got_error_from_errno("strdup");
9364 goto done;
9367 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9368 if (error != NULL)
9369 goto done;
9371 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9372 repo, worktree);
9373 if (error)
9374 goto done;
9376 error = tog_load_refs(repo, 0);
9377 if (error)
9378 goto done;
9379 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9380 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9381 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9382 if (error)
9383 goto done;
9385 if (worktree) {
9386 got_worktree_close(worktree);
9387 worktree = NULL;
9390 error = got_object_open_as_commit(&commit, repo, commit_id);
9391 if (error)
9392 goto done;
9394 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9395 if (error) {
9396 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9397 goto done;
9398 fprintf(stderr, "%s: '%s' is no known command or path\n",
9399 getprogname(), argv[0]);
9400 usage(1, 1);
9401 /* not reached */
9404 error = got_object_id_str(&commit_id_str, commit_id);
9405 if (error)
9406 goto done;
9408 cmd = &tog_commands[0]; /* log */
9409 argc = 4;
9410 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9411 error = cmd->cmd_main(argc, cmd_argv);
9412 done:
9413 if (repo) {
9414 close_err = got_repo_close(repo);
9415 if (error == NULL)
9416 error = close_err;
9418 if (commit)
9419 got_object_commit_close(commit);
9420 if (worktree)
9421 got_worktree_close(worktree);
9422 if (pack_fds) {
9423 const struct got_error *pack_err =
9424 got_repo_pack_fds_close(pack_fds);
9425 if (error == NULL)
9426 error = pack_err;
9428 free(id);
9429 free(commit_id_str);
9430 free(commit_id);
9431 free(cwd);
9432 free(repo_path);
9433 free(in_repo_path);
9434 if (cmd_argv) {
9435 int i;
9436 for (i = 0; i < argc; i++)
9437 free(cmd_argv[i]);
9438 free(cmd_argv);
9440 tog_free_refs();
9441 return error;
9444 int
9445 main(int argc, char *argv[])
9447 const struct got_error *error = NULL;
9448 const struct tog_cmd *cmd = NULL;
9449 int ch, hflag = 0, Vflag = 0;
9450 char **cmd_argv = NULL;
9451 static const struct option longopts[] = {
9452 { "version", no_argument, NULL, 'V' },
9453 { NULL, 0, NULL, 0}
9455 char *diff_algo_str = NULL;
9457 if (!isatty(STDIN_FILENO))
9458 errx(1, "standard input is not a tty");
9460 setlocale(LC_CTYPE, "");
9462 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9463 switch (ch) {
9464 case 'h':
9465 hflag = 1;
9466 break;
9467 case 'V':
9468 Vflag = 1;
9469 break;
9470 default:
9471 usage(hflag, 1);
9472 /* NOTREACHED */
9476 argc -= optind;
9477 argv += optind;
9478 optind = 1;
9479 optreset = 1;
9481 if (Vflag) {
9482 got_version_print_str();
9483 return 0;
9486 #ifndef PROFILE
9487 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9488 NULL) == -1)
9489 err(1, "pledge");
9490 #endif
9492 if (argc == 0) {
9493 if (hflag)
9494 usage(hflag, 0);
9495 /* Build an argument vector which runs a default command. */
9496 cmd = &tog_commands[0];
9497 argc = 1;
9498 cmd_argv = make_argv(argc, cmd->name);
9499 } else {
9500 size_t i;
9502 /* Did the user specify a command? */
9503 for (i = 0; i < nitems(tog_commands); i++) {
9504 if (strncmp(tog_commands[i].name, argv[0],
9505 strlen(argv[0])) == 0) {
9506 cmd = &tog_commands[i];
9507 break;
9512 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9513 if (diff_algo_str) {
9514 if (strcasecmp(diff_algo_str, "patience") == 0)
9515 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9516 if (strcasecmp(diff_algo_str, "myers") == 0)
9517 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9520 if (cmd == NULL) {
9521 if (argc != 1)
9522 usage(0, 1);
9523 /* No command specified; try log with a path */
9524 error = tog_log_with_path(argc, argv);
9525 } else {
9526 if (hflag)
9527 cmd->cmd_usage();
9528 else
9529 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9532 endwin();
9533 if (cmd_argv) {
9534 int i;
9535 for (i = 0; i < argc; i++)
9536 free(cmd_argv[i]);
9537 free(cmd_argv);
9540 if (error && error->code != GOT_ERR_CANCELLED &&
9541 error->code != GOT_ERR_EOF &&
9542 error->code != GOT_ERR_PRIVSEP_EXIT &&
9543 error->code != GOT_ERR_PRIVSEP_PIPE &&
9544 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9545 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9546 return 0;