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 <sha2.h>
30 #include <signal.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <getopt.h>
35 #include <string.h>
36 #include <err.h>
37 #include <unistd.h>
38 #include <limits.h>
39 #include <wchar.h>
40 #include <time.h>
41 #include <pthread.h>
42 #include <libgen.h>
43 #include <regex.h>
44 #include <sched.h>
46 #include "got_compat.h"
48 #include "got_version.h"
49 #include "got_error.h"
50 #include "got_object.h"
51 #include "got_reference.h"
52 #include "got_repository.h"
53 #include "got_diff.h"
54 #include "got_opentemp.h"
55 #include "got_utf8.h"
56 #include "got_cancel.h"
57 #include "got_commit_graph.h"
58 #include "got_blame.h"
59 #include "got_privsep.h"
60 #include "got_path.h"
61 #include "got_worktree.h"
63 #ifndef MIN
64 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
65 #endif
67 #ifndef MAX
68 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
69 #endif
71 #ifndef CTRL
72 #define CTRL(x) ((x) & 0x1f)
73 #endif
75 #ifndef nitems
76 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
77 #endif
79 struct tog_cmd {
80 const char *name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 };
85 __dead static void usage(int, int);
86 __dead static void usage_log(void);
87 __dead static void usage_diff(void);
88 __dead static void usage_blame(void);
89 __dead static void usage_tree(void);
90 __dead static void usage_ref(void);
92 static const struct got_error* cmd_log(int, char *[]);
93 static const struct got_error* cmd_diff(int, char *[]);
94 static const struct got_error* cmd_blame(int, char *[]);
95 static const struct got_error* cmd_tree(int, char *[]);
96 static const struct got_error* cmd_ref(int, char *[]);
98 static const struct tog_cmd tog_commands[] = {
99 { "log", cmd_log, usage_log },
100 { "diff", cmd_diff, usage_diff },
101 { "blame", cmd_blame, usage_blame },
102 { "tree", cmd_tree, usage_tree },
103 { "ref", cmd_ref, usage_ref },
104 };
106 enum tog_view_type {
107 TOG_VIEW_DIFF,
108 TOG_VIEW_LOG,
109 TOG_VIEW_BLAME,
110 TOG_VIEW_TREE,
111 TOG_VIEW_REF,
112 TOG_VIEW_HELP
113 };
115 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
116 enum tog_keymap_type {
117 TOG_KEYMAP_KEYS = -2,
118 TOG_KEYMAP_GLOBAL,
119 TOG_KEYMAP_DIFF,
120 TOG_KEYMAP_LOG,
121 TOG_KEYMAP_BLAME,
122 TOG_KEYMAP_TREE,
123 TOG_KEYMAP_REF,
124 TOG_KEYMAP_HELP
125 };
127 enum tog_view_mode {
128 TOG_VIEW_SPLIT_NONE,
129 TOG_VIEW_SPLIT_VERT,
130 TOG_VIEW_SPLIT_HRZN
131 };
133 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
135 #define TOG_EOF_STRING "(END)"
137 struct commit_queue_entry {
138 TAILQ_ENTRY(commit_queue_entry) entry;
139 struct got_object_id *id;
140 struct got_commit_object *commit;
141 int idx;
142 };
143 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
144 struct commit_queue {
145 int ncommits;
146 struct commit_queue_head head;
147 };
149 struct tog_color {
150 STAILQ_ENTRY(tog_color) entry;
151 regex_t regex;
152 short colorpair;
153 };
154 STAILQ_HEAD(tog_colors, tog_color);
156 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
157 static struct got_reflist_object_id_map *tog_refs_idmap;
158 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
160 static const struct got_error *
161 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
162 struct got_reference* re2)
164 const char *name1 = got_ref_get_name(re1);
165 const char *name2 = got_ref_get_name(re2);
166 int isbackup1, isbackup2;
168 /* Sort backup refs towards the bottom of the list. */
169 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
170 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
171 if (!isbackup1 && isbackup2) {
172 *cmp = -1;
173 return NULL;
174 } else if (isbackup1 && !isbackup2) {
175 *cmp = 1;
176 return NULL;
179 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
180 return NULL;
183 static const struct got_error *
184 tog_load_refs(struct got_repository *repo, int sort_by_date)
186 const struct got_error *err;
188 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
189 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
190 repo);
191 if (err)
192 return err;
194 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
195 repo);
198 static void
199 tog_free_refs(void)
201 if (tog_refs_idmap) {
202 got_reflist_object_id_map_free(tog_refs_idmap);
203 tog_refs_idmap = NULL;
205 got_ref_list_free(&tog_refs);
208 static const struct got_error *
209 add_color(struct tog_colors *colors, const char *pattern,
210 int idx, short color)
212 const struct got_error *err = NULL;
213 struct tog_color *tc;
214 int regerr = 0;
216 if (idx < 1 || idx > COLOR_PAIRS - 1)
217 return NULL;
219 init_pair(idx, color, -1);
221 tc = calloc(1, sizeof(*tc));
222 if (tc == NULL)
223 return got_error_from_errno("calloc");
224 regerr = regcomp(&tc->regex, pattern,
225 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
226 if (regerr) {
227 static char regerr_msg[512];
228 static char err_msg[512];
229 regerror(regerr, &tc->regex, regerr_msg,
230 sizeof(regerr_msg));
231 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
232 regerr_msg);
233 err = got_error_msg(GOT_ERR_REGEX, err_msg);
234 free(tc);
235 return err;
237 tc->colorpair = idx;
238 STAILQ_INSERT_HEAD(colors, tc, entry);
239 return NULL;
242 static void
243 free_colors(struct tog_colors *colors)
245 struct tog_color *tc;
247 while (!STAILQ_EMPTY(colors)) {
248 tc = STAILQ_FIRST(colors);
249 STAILQ_REMOVE_HEAD(colors, entry);
250 regfree(&tc->regex);
251 free(tc);
255 static struct tog_color *
256 get_color(struct tog_colors *colors, int colorpair)
258 struct tog_color *tc = NULL;
260 STAILQ_FOREACH(tc, colors, entry) {
261 if (tc->colorpair == colorpair)
262 return tc;
265 return NULL;
268 static int
269 default_color_value(const char *envvar)
271 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
272 return COLOR_MAGENTA;
273 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
274 return COLOR_CYAN;
275 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
276 return COLOR_YELLOW;
277 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
278 return COLOR_GREEN;
279 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
280 return COLOR_MAGENTA;
281 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
282 return COLOR_MAGENTA;
283 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
284 return COLOR_CYAN;
285 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
286 return COLOR_GREEN;
287 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
288 return COLOR_GREEN;
289 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
290 return COLOR_CYAN;
291 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
292 return COLOR_YELLOW;
293 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
294 return COLOR_GREEN;
295 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
296 return COLOR_MAGENTA;
297 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
298 return COLOR_YELLOW;
299 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
300 return COLOR_CYAN;
302 return -1;
305 static int
306 get_color_value(const char *envvar)
308 const char *val = getenv(envvar);
310 if (val == NULL)
311 return default_color_value(envvar);
313 if (strcasecmp(val, "black") == 0)
314 return COLOR_BLACK;
315 if (strcasecmp(val, "red") == 0)
316 return COLOR_RED;
317 if (strcasecmp(val, "green") == 0)
318 return COLOR_GREEN;
319 if (strcasecmp(val, "yellow") == 0)
320 return COLOR_YELLOW;
321 if (strcasecmp(val, "blue") == 0)
322 return COLOR_BLUE;
323 if (strcasecmp(val, "magenta") == 0)
324 return COLOR_MAGENTA;
325 if (strcasecmp(val, "cyan") == 0)
326 return COLOR_CYAN;
327 if (strcasecmp(val, "white") == 0)
328 return COLOR_WHITE;
329 if (strcasecmp(val, "default") == 0)
330 return -1;
332 return default_color_value(envvar);
335 struct tog_diff_view_state {
336 struct got_object_id *id1, *id2;
337 const char *label1, *label2;
338 FILE *f, *f1, *f2;
339 int fd1, fd2;
340 int lineno;
341 int first_displayed_line;
342 int last_displayed_line;
343 int eof;
344 int diff_context;
345 int ignore_whitespace;
346 int force_text_diff;
347 struct got_repository *repo;
348 struct got_diff_line *lines;
349 size_t nlines;
350 int matched_line;
351 int selected_line;
353 /* passed from log or blame view; may be NULL */
354 struct tog_view *parent_view;
355 };
357 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
358 static volatile sig_atomic_t tog_thread_error;
360 struct tog_log_thread_args {
361 pthread_cond_t need_commits;
362 pthread_cond_t commit_loaded;
363 int commits_needed;
364 int load_all;
365 struct got_commit_graph *graph;
366 struct commit_queue *real_commits;
367 const char *in_repo_path;
368 struct got_object_id *start_id;
369 struct got_repository *repo;
370 int *pack_fds;
371 int log_complete;
372 sig_atomic_t *quit;
373 struct commit_queue_entry **first_displayed_entry;
374 struct commit_queue_entry **selected_entry;
375 int *searching;
376 int *search_next_done;
377 regex_t *regex;
378 int *limiting;
379 int limit_match;
380 regex_t *limit_regex;
381 struct commit_queue *limit_commits;
382 };
384 struct tog_log_view_state {
385 struct commit_queue *commits;
386 struct commit_queue_entry *first_displayed_entry;
387 struct commit_queue_entry *last_displayed_entry;
388 struct commit_queue_entry *selected_entry;
389 struct commit_queue real_commits;
390 int selected;
391 char *in_repo_path;
392 char *head_ref_name;
393 int log_branches;
394 struct got_repository *repo;
395 struct got_object_id *start_id;
396 sig_atomic_t quit;
397 pthread_t thread;
398 struct tog_log_thread_args thread_args;
399 struct commit_queue_entry *matched_entry;
400 struct commit_queue_entry *search_entry;
401 struct tog_colors colors;
402 int use_committer;
403 int limit_view;
404 regex_t limit_regex;
405 struct commit_queue limit_commits;
406 };
408 #define TOG_COLOR_DIFF_MINUS 1
409 #define TOG_COLOR_DIFF_PLUS 2
410 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
411 #define TOG_COLOR_DIFF_META 4
412 #define TOG_COLOR_TREE_SUBMODULE 5
413 #define TOG_COLOR_TREE_SYMLINK 6
414 #define TOG_COLOR_TREE_DIRECTORY 7
415 #define TOG_COLOR_TREE_EXECUTABLE 8
416 #define TOG_COLOR_COMMIT 9
417 #define TOG_COLOR_AUTHOR 10
418 #define TOG_COLOR_DATE 11
419 #define TOG_COLOR_REFS_HEADS 12
420 #define TOG_COLOR_REFS_TAGS 13
421 #define TOG_COLOR_REFS_REMOTES 14
422 #define TOG_COLOR_REFS_BACKUP 15
424 struct tog_blame_cb_args {
425 struct tog_blame_line *lines; /* one per line */
426 int nlines;
428 struct tog_view *view;
429 struct got_object_id *commit_id;
430 int *quit;
431 };
433 struct tog_blame_thread_args {
434 const char *path;
435 struct got_repository *repo;
436 struct tog_blame_cb_args *cb_args;
437 int *complete;
438 got_cancel_cb cancel_cb;
439 void *cancel_arg;
440 };
442 struct tog_blame {
443 FILE *f;
444 off_t filesize;
445 struct tog_blame_line *lines;
446 int nlines;
447 off_t *line_offsets;
448 pthread_t thread;
449 struct tog_blame_thread_args thread_args;
450 struct tog_blame_cb_args cb_args;
451 const char *path;
452 int *pack_fds;
453 };
455 struct tog_blame_view_state {
456 int first_displayed_line;
457 int last_displayed_line;
458 int selected_line;
459 int last_diffed_line;
460 int blame_complete;
461 int eof;
462 int done;
463 struct got_object_id_queue blamed_commits;
464 struct got_object_qid *blamed_commit;
465 char *path;
466 struct got_repository *repo;
467 struct got_object_id *commit_id;
468 struct got_object_id *id_to_log;
469 struct tog_blame blame;
470 int matched_line;
471 struct tog_colors colors;
472 };
474 struct tog_parent_tree {
475 TAILQ_ENTRY(tog_parent_tree) entry;
476 struct got_tree_object *tree;
477 struct got_tree_entry *first_displayed_entry;
478 struct got_tree_entry *selected_entry;
479 int selected;
480 };
482 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
484 struct tog_tree_view_state {
485 char *tree_label;
486 struct got_object_id *commit_id;/* commit which this tree belongs to */
487 struct got_tree_object *root; /* the commit's root tree entry */
488 struct got_tree_object *tree; /* currently displayed (sub-)tree */
489 struct got_tree_entry *first_displayed_entry;
490 struct got_tree_entry *last_displayed_entry;
491 struct got_tree_entry *selected_entry;
492 int ndisplayed, selected, show_ids;
493 struct tog_parent_trees parents; /* parent trees of current sub-tree */
494 char *head_ref_name;
495 struct got_repository *repo;
496 struct got_tree_entry *matched_entry;
497 struct tog_colors colors;
498 };
500 struct tog_reflist_entry {
501 TAILQ_ENTRY(tog_reflist_entry) entry;
502 struct got_reference *ref;
503 int idx;
504 };
506 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
508 struct tog_ref_view_state {
509 struct tog_reflist_head refs;
510 struct tog_reflist_entry *first_displayed_entry;
511 struct tog_reflist_entry *last_displayed_entry;
512 struct tog_reflist_entry *selected_entry;
513 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
514 struct got_repository *repo;
515 struct tog_reflist_entry *matched_entry;
516 struct tog_colors colors;
517 };
519 struct tog_help_view_state {
520 FILE *f;
521 off_t *line_offsets;
522 size_t nlines;
523 int lineno;
524 int first_displayed_line;
525 int last_displayed_line;
526 int eof;
527 int matched_line;
528 int selected_line;
529 int all;
530 enum tog_keymap_type type;
531 };
533 #define GENERATE_HELP \
534 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
535 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
536 KEY_("k C-p Up", "Move cursor or page up one line"), \
537 KEY_("j C-n Down", "Move cursor or page down one line"), \
538 KEY_("C-b b PgUp", "Scroll the view up one page"), \
539 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
540 KEY_("C-u u", "Scroll the view up one half page"), \
541 KEY_("C-d d", "Scroll the view down one half page"), \
542 KEY_("g", "Go to line N (default: first line)"), \
543 KEY_("Home =", "Go to the first line"), \
544 KEY_("G", "Go to line N (default: last line)"), \
545 KEY_("End *", "Go to the last line"), \
546 KEY_("l Right", "Scroll the view right"), \
547 KEY_("h Left", "Scroll the view left"), \
548 KEY_("$", "Scroll view to the rightmost position"), \
549 KEY_("0", "Scroll view to the leftmost position"), \
550 KEY_("-", "Decrease size of the focussed split"), \
551 KEY_("+", "Increase size of the focussed split"), \
552 KEY_("Tab", "Switch focus between views"), \
553 KEY_("F", "Toggle fullscreen mode"), \
554 KEY_("/", "Open prompt to enter search term"), \
555 KEY_("n", "Find next line/token matching the current search term"), \
556 KEY_("N", "Find previous line/token matching the current search term"),\
557 KEY_("q", "Quit the focussed view; Quit help screen"), \
558 KEY_("Q", "Quit tog"), \
560 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
561 KEY_("< ,", "Move cursor up one commit"), \
562 KEY_("> .", "Move cursor down one commit"), \
563 KEY_("Enter", "Open diff view of the selected commit"), \
564 KEY_("B", "Reload the log view and toggle display of merged commits"), \
565 KEY_("R", "Open ref view of all repository references"), \
566 KEY_("T", "Display tree view of the repository from the selected" \
567 " commit"), \
568 KEY_("@", "Toggle between displaying author and committer name"), \
569 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
570 KEY_("C-g Backspace", "Cancel current search or log operation"), \
571 KEY_("C-l", "Reload the log view with new commits in the repository"), \
573 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
574 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
575 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
576 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
577 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
578 " data"), \
579 KEY_("(", "Go to the previous file in the diff"), \
580 KEY_(")", "Go to the next file in the diff"), \
581 KEY_("{", "Go to the previous hunk in the diff"), \
582 KEY_("}", "Go to the next hunk in the diff"), \
583 KEY_("[", "Decrease the number of context lines"), \
584 KEY_("]", "Increase the number of context lines"), \
585 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
587 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
588 KEY_("Enter", "Display diff view of the selected line's commit"), \
589 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
590 KEY_("L", "Open log view for the currently selected annotated line"), \
591 KEY_("C", "Reload view with the previously blamed commit"), \
592 KEY_("c", "Reload view with the version of the file found in the" \
593 " selected line's commit"), \
594 KEY_("p", "Reload view with the version of the file found in the" \
595 " selected line's parent commit"), \
597 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
598 KEY_("Enter", "Enter selected directory or open blame view of the" \
599 " selected file"), \
600 KEY_("L", "Open log view for the selected entry"), \
601 KEY_("R", "Open ref view of all repository references"), \
602 KEY_("i", "Show object IDs for all tree entries"), \
603 KEY_("Backspace", "Return to the parent directory"), \
605 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
606 KEY_("Enter", "Display log view of the selected reference"), \
607 KEY_("T", "Display tree view of the selected reference"), \
608 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
609 KEY_("m", "Toggle display of last modified date for each reference"), \
610 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
611 KEY_("C-l", "Reload view with all repository references")
613 struct tog_key_map {
614 const char *keys;
615 const char *info;
616 enum tog_keymap_type type;
617 };
619 /*
620 * We implement two types of views: parent views and child views.
622 * The 'Tab' key switches focus between a parent view and its child view.
623 * Child views are shown side-by-side to their parent view, provided
624 * there is enough screen estate.
626 * When a new view is opened from within a parent view, this new view
627 * becomes a child view of the parent view, replacing any existing child.
629 * When a new view is opened from within a child view, this new view
630 * becomes a parent view which will obscure the views below until the
631 * user quits the new parent view by typing 'q'.
633 * This list of views contains parent views only.
634 * Child views are only pointed to by their parent view.
635 */
636 TAILQ_HEAD(tog_view_list_head, tog_view);
638 struct tog_view {
639 TAILQ_ENTRY(tog_view) entry;
640 WINDOW *window;
641 PANEL *panel;
642 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
643 int resized_y, resized_x; /* begin_y/x based on user resizing */
644 int maxx, x; /* max column and current start column */
645 int lines, cols; /* copies of LINES and COLS */
646 int nscrolled, offset; /* lines scrolled and hsplit line offset */
647 int gline, hiline; /* navigate to and highlight this nG line */
648 int ch, count; /* current keymap and count prefix */
649 int resized; /* set when in a resize event */
650 int focussed; /* Only set on one parent or child view at a time. */
651 int dying;
652 struct tog_view *parent;
653 struct tog_view *child;
655 /*
656 * This flag is initially set on parent views when a new child view
657 * is created. It gets toggled when the 'Tab' key switches focus
658 * between parent and child.
659 * The flag indicates whether focus should be passed on to our child
660 * view if this parent view gets picked for focus after another parent
661 * view was closed. This prevents child views from losing focus in such
662 * situations.
663 */
664 int focus_child;
666 enum tog_view_mode mode;
667 /* type-specific state */
668 enum tog_view_type type;
669 union {
670 struct tog_diff_view_state diff;
671 struct tog_log_view_state log;
672 struct tog_blame_view_state blame;
673 struct tog_tree_view_state tree;
674 struct tog_ref_view_state ref;
675 struct tog_help_view_state help;
676 } state;
678 const struct got_error *(*show)(struct tog_view *);
679 const struct got_error *(*input)(struct tog_view **,
680 struct tog_view *, int);
681 const struct got_error *(*reset)(struct tog_view *);
682 const struct got_error *(*resize)(struct tog_view *, int);
683 const struct got_error *(*close)(struct tog_view *);
685 const struct got_error *(*search_start)(struct tog_view *);
686 const struct got_error *(*search_next)(struct tog_view *);
687 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
688 int **, int **, int **, int **);
689 int search_started;
690 int searching;
691 #define TOG_SEARCH_FORWARD 1
692 #define TOG_SEARCH_BACKWARD 2
693 int search_next_done;
694 #define TOG_SEARCH_HAVE_MORE 1
695 #define TOG_SEARCH_NO_MORE 2
696 #define TOG_SEARCH_HAVE_NONE 3
697 regex_t regex;
698 regmatch_t regmatch;
699 const char *action;
700 };
702 static const struct got_error *open_diff_view(struct tog_view *,
703 struct got_object_id *, struct got_object_id *,
704 const char *, const char *, int, int, int, struct tog_view *,
705 struct got_repository *);
706 static const struct got_error *show_diff_view(struct tog_view *);
707 static const struct got_error *input_diff_view(struct tog_view **,
708 struct tog_view *, int);
709 static const struct got_error *reset_diff_view(struct tog_view *);
710 static const struct got_error* close_diff_view(struct tog_view *);
711 static const struct got_error *search_start_diff_view(struct tog_view *);
712 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
713 size_t *, int **, int **, int **, int **);
714 static const struct got_error *search_next_view_match(struct tog_view *);
716 static const struct got_error *open_log_view(struct tog_view *,
717 struct got_object_id *, struct got_repository *,
718 const char *, const char *, int);
719 static const struct got_error * show_log_view(struct tog_view *);
720 static const struct got_error *input_log_view(struct tog_view **,
721 struct tog_view *, int);
722 static const struct got_error *resize_log_view(struct tog_view *, int);
723 static const struct got_error *close_log_view(struct tog_view *);
724 static const struct got_error *search_start_log_view(struct tog_view *);
725 static const struct got_error *search_next_log_view(struct tog_view *);
727 static const struct got_error *open_blame_view(struct tog_view *, char *,
728 struct got_object_id *, struct got_repository *);
729 static const struct got_error *show_blame_view(struct tog_view *);
730 static const struct got_error *input_blame_view(struct tog_view **,
731 struct tog_view *, int);
732 static const struct got_error *reset_blame_view(struct tog_view *);
733 static const struct got_error *close_blame_view(struct tog_view *);
734 static const struct got_error *search_start_blame_view(struct tog_view *);
735 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
736 size_t *, int **, int **, int **, int **);
738 static const struct got_error *open_tree_view(struct tog_view *,
739 struct got_object_id *, const char *, struct got_repository *);
740 static const struct got_error *show_tree_view(struct tog_view *);
741 static const struct got_error *input_tree_view(struct tog_view **,
742 struct tog_view *, int);
743 static const struct got_error *close_tree_view(struct tog_view *);
744 static const struct got_error *search_start_tree_view(struct tog_view *);
745 static const struct got_error *search_next_tree_view(struct tog_view *);
747 static const struct got_error *open_ref_view(struct tog_view *,
748 struct got_repository *);
749 static const struct got_error *show_ref_view(struct tog_view *);
750 static const struct got_error *input_ref_view(struct tog_view **,
751 struct tog_view *, int);
752 static const struct got_error *close_ref_view(struct tog_view *);
753 static const struct got_error *search_start_ref_view(struct tog_view *);
754 static const struct got_error *search_next_ref_view(struct tog_view *);
756 static const struct got_error *open_help_view(struct tog_view *,
757 struct tog_view *);
758 static const struct got_error *show_help_view(struct tog_view *);
759 static const struct got_error *input_help_view(struct tog_view **,
760 struct tog_view *, int);
761 static const struct got_error *reset_help_view(struct tog_view *);
762 static const struct got_error* close_help_view(struct tog_view *);
763 static const struct got_error *search_start_help_view(struct tog_view *);
764 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
765 size_t *, int **, int **, int **, int **);
767 static volatile sig_atomic_t tog_sigwinch_received;
768 static volatile sig_atomic_t tog_sigpipe_received;
769 static volatile sig_atomic_t tog_sigcont_received;
770 static volatile sig_atomic_t tog_sigint_received;
771 static volatile sig_atomic_t tog_sigterm_received;
773 static void
774 tog_sigwinch(int signo)
776 tog_sigwinch_received = 1;
779 static void
780 tog_sigpipe(int signo)
782 tog_sigpipe_received = 1;
785 static void
786 tog_sigcont(int signo)
788 tog_sigcont_received = 1;
791 static void
792 tog_sigint(int signo)
794 tog_sigint_received = 1;
797 static void
798 tog_sigterm(int signo)
800 tog_sigterm_received = 1;
803 static int
804 tog_fatal_signal_received(void)
806 return (tog_sigpipe_received ||
807 tog_sigint_received || tog_sigterm_received);
810 static const struct got_error *
811 view_close(struct tog_view *view)
813 const struct got_error *err = NULL, *child_err = NULL;
815 if (view->child) {
816 child_err = view_close(view->child);
817 view->child = NULL;
819 if (view->close)
820 err = view->close(view);
821 if (view->panel)
822 del_panel(view->panel);
823 if (view->window)
824 delwin(view->window);
825 free(view);
826 return err ? err : child_err;
829 static struct tog_view *
830 view_open(int nlines, int ncols, int begin_y, int begin_x,
831 enum tog_view_type type)
833 struct tog_view *view = calloc(1, sizeof(*view));
835 if (view == NULL)
836 return NULL;
838 view->type = type;
839 view->lines = LINES;
840 view->cols = COLS;
841 view->nlines = nlines ? nlines : LINES - begin_y;
842 view->ncols = ncols ? ncols : COLS - begin_x;
843 view->begin_y = begin_y;
844 view->begin_x = begin_x;
845 view->window = newwin(nlines, ncols, begin_y, begin_x);
846 if (view->window == NULL) {
847 view_close(view);
848 return NULL;
850 view->panel = new_panel(view->window);
851 if (view->panel == NULL ||
852 set_panel_userptr(view->panel, view) != OK) {
853 view_close(view);
854 return NULL;
857 keypad(view->window, TRUE);
858 return view;
861 static int
862 view_split_begin_x(int begin_x)
864 if (begin_x > 0 || COLS < 120)
865 return 0;
866 return (COLS - MAX(COLS / 2, 80));
869 /* XXX Stub till we decide what to do. */
870 static int
871 view_split_begin_y(int lines)
873 return lines * HSPLIT_SCALE;
876 static const struct got_error *view_resize(struct tog_view *);
878 static const struct got_error *
879 view_splitscreen(struct tog_view *view)
881 const struct got_error *err = NULL;
883 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
884 if (view->resized_y && view->resized_y < view->lines)
885 view->begin_y = view->resized_y;
886 else
887 view->begin_y = view_split_begin_y(view->nlines);
888 view->begin_x = 0;
889 } else if (!view->resized) {
890 if (view->resized_x && view->resized_x < view->cols - 1 &&
891 view->cols > 119)
892 view->begin_x = view->resized_x;
893 else
894 view->begin_x = view_split_begin_x(0);
895 view->begin_y = 0;
897 view->nlines = LINES - view->begin_y;
898 view->ncols = COLS - view->begin_x;
899 view->lines = LINES;
900 view->cols = COLS;
901 err = view_resize(view);
902 if (err)
903 return err;
905 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
906 view->parent->nlines = view->begin_y;
908 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
909 return got_error_from_errno("mvwin");
911 return NULL;
914 static const struct got_error *
915 view_fullscreen(struct tog_view *view)
917 const struct got_error *err = NULL;
919 view->begin_x = 0;
920 view->begin_y = view->resized ? view->begin_y : 0;
921 view->nlines = view->resized ? view->nlines : LINES;
922 view->ncols = COLS;
923 view->lines = LINES;
924 view->cols = COLS;
925 err = view_resize(view);
926 if (err)
927 return err;
929 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
930 return got_error_from_errno("mvwin");
932 return NULL;
935 static int
936 view_is_parent_view(struct tog_view *view)
938 return view->parent == NULL;
941 static int
942 view_is_splitscreen(struct tog_view *view)
944 return view->begin_x > 0 || view->begin_y > 0;
947 static int
948 view_is_fullscreen(struct tog_view *view)
950 return view->nlines == LINES && view->ncols == COLS;
953 static int
954 view_is_hsplit_top(struct tog_view *view)
956 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
957 view_is_splitscreen(view->child);
960 static void
961 view_border(struct tog_view *view)
963 PANEL *panel;
964 const struct tog_view *view_above;
966 if (view->parent)
967 return view_border(view->parent);
969 panel = panel_above(view->panel);
970 if (panel == NULL)
971 return;
973 view_above = panel_userptr(panel);
974 if (view->mode == TOG_VIEW_SPLIT_HRZN)
975 mvwhline(view->window, view_above->begin_y - 1,
976 view->begin_x, got_locale_is_utf8() ?
977 ACS_HLINE : '-', view->ncols);
978 else
979 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
980 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
983 static const struct got_error *view_init_hsplit(struct tog_view *, int);
984 static const struct got_error *request_log_commits(struct tog_view *);
985 static const struct got_error *offset_selection_down(struct tog_view *);
986 static void offset_selection_up(struct tog_view *);
987 static void view_get_split(struct tog_view *, int *, int *);
989 static const struct got_error *
990 view_resize(struct tog_view *view)
992 const struct got_error *err = NULL;
993 int dif, nlines, ncols;
995 dif = LINES - view->lines; /* line difference */
997 if (view->lines > LINES)
998 nlines = view->nlines - (view->lines - LINES);
999 else
1000 nlines = view->nlines + (LINES - view->lines);
1001 if (view->cols > COLS)
1002 ncols = view->ncols - (view->cols - COLS);
1003 else
1004 ncols = view->ncols + (COLS - view->cols);
1006 if (view->child) {
1007 int hs = view->child->begin_y;
1009 if (!view_is_fullscreen(view))
1010 view->child->begin_x = view_split_begin_x(view->begin_x);
1011 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1012 view->child->begin_x == 0) {
1013 ncols = COLS;
1015 view_fullscreen(view->child);
1016 if (view->child->focussed)
1017 show_panel(view->child->panel);
1018 else
1019 show_panel(view->panel);
1020 } else {
1021 ncols = view->child->begin_x;
1023 view_splitscreen(view->child);
1024 show_panel(view->child->panel);
1027 * XXX This is ugly and needs to be moved into the above
1028 * logic but "works" for now and my attempts at moving it
1029 * break either 'tab' or 'F' key maps in horizontal splits.
1031 if (hs) {
1032 err = view_splitscreen(view->child);
1033 if (err)
1034 return err;
1035 if (dif < 0) { /* top split decreased */
1036 err = offset_selection_down(view);
1037 if (err)
1038 return err;
1040 view_border(view);
1041 update_panels();
1042 doupdate();
1043 show_panel(view->child->panel);
1044 nlines = view->nlines;
1046 } else if (view->parent == NULL)
1047 ncols = COLS;
1049 if (view->resize && dif > 0) {
1050 err = view->resize(view, dif);
1051 if (err)
1052 return err;
1055 if (wresize(view->window, nlines, ncols) == ERR)
1056 return got_error_from_errno("wresize");
1057 if (replace_panel(view->panel, view->window) == ERR)
1058 return got_error_from_errno("replace_panel");
1059 wclear(view->window);
1061 view->nlines = nlines;
1062 view->ncols = ncols;
1063 view->lines = LINES;
1064 view->cols = COLS;
1066 return NULL;
1069 static const struct got_error *
1070 resize_log_view(struct tog_view *view, int increase)
1072 struct tog_log_view_state *s = &view->state.log;
1073 const struct got_error *err = NULL;
1074 int n = 0;
1076 if (s->selected_entry)
1077 n = s->selected_entry->idx + view->lines - s->selected;
1080 * Request commits to account for the increased
1081 * height so we have enough to populate the view.
1083 if (s->commits->ncommits < n) {
1084 view->nscrolled = n - s->commits->ncommits + increase + 1;
1085 err = request_log_commits(view);
1088 return err;
1091 static void
1092 view_adjust_offset(struct tog_view *view, int n)
1094 if (n == 0)
1095 return;
1097 if (view->parent && view->parent->offset) {
1098 if (view->parent->offset + n >= 0)
1099 view->parent->offset += n;
1100 else
1101 view->parent->offset = 0;
1102 } else if (view->offset) {
1103 if (view->offset - n >= 0)
1104 view->offset -= n;
1105 else
1106 view->offset = 0;
1110 static const struct got_error *
1111 view_resize_split(struct tog_view *view, int resize)
1113 const struct got_error *err = NULL;
1114 struct tog_view *v = NULL;
1116 if (view->parent)
1117 v = view->parent;
1118 else
1119 v = view;
1121 if (!v->child || !view_is_splitscreen(v->child))
1122 return NULL;
1124 v->resized = v->child->resized = resize; /* lock for resize event */
1126 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1127 if (v->child->resized_y)
1128 v->child->begin_y = v->child->resized_y;
1129 if (view->parent)
1130 v->child->begin_y -= resize;
1131 else
1132 v->child->begin_y += resize;
1133 if (v->child->begin_y < 3) {
1134 view->count = 0;
1135 v->child->begin_y = 3;
1136 } else if (v->child->begin_y > LINES - 1) {
1137 view->count = 0;
1138 v->child->begin_y = LINES - 1;
1140 v->ncols = COLS;
1141 v->child->ncols = COLS;
1142 view_adjust_offset(view, resize);
1143 err = view_init_hsplit(v, v->child->begin_y);
1144 if (err)
1145 return err;
1146 v->child->resized_y = v->child->begin_y;
1147 } else {
1148 if (v->child->resized_x)
1149 v->child->begin_x = v->child->resized_x;
1150 if (view->parent)
1151 v->child->begin_x -= resize;
1152 else
1153 v->child->begin_x += resize;
1154 if (v->child->begin_x < 11) {
1155 view->count = 0;
1156 v->child->begin_x = 11;
1157 } else if (v->child->begin_x > COLS - 1) {
1158 view->count = 0;
1159 v->child->begin_x = COLS - 1;
1161 v->child->resized_x = v->child->begin_x;
1164 v->child->mode = v->mode;
1165 v->child->nlines = v->lines - v->child->begin_y;
1166 v->child->ncols = v->cols - v->child->begin_x;
1167 v->focus_child = 1;
1169 err = view_fullscreen(v);
1170 if (err)
1171 return err;
1172 err = view_splitscreen(v->child);
1173 if (err)
1174 return err;
1176 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1177 err = offset_selection_down(v->child);
1178 if (err)
1179 return err;
1182 if (v->resize)
1183 err = v->resize(v, 0);
1184 else if (v->child->resize)
1185 err = v->child->resize(v->child, 0);
1187 v->resized = v->child->resized = 0;
1189 return err;
1192 static void
1193 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1195 struct tog_view *v = src->child ? src->child : src;
1197 dst->resized_x = v->resized_x;
1198 dst->resized_y = v->resized_y;
1201 static const struct got_error *
1202 view_close_child(struct tog_view *view)
1204 const struct got_error *err = NULL;
1206 if (view->child == NULL)
1207 return NULL;
1209 err = view_close(view->child);
1210 view->child = NULL;
1211 return err;
1214 static const struct got_error *
1215 view_set_child(struct tog_view *view, struct tog_view *child)
1217 const struct got_error *err = NULL;
1219 view->child = child;
1220 child->parent = view;
1222 err = view_resize(view);
1223 if (err)
1224 return err;
1226 if (view->child->resized_x || view->child->resized_y)
1227 err = view_resize_split(view, 0);
1229 return err;
1232 static const struct got_error *view_dispatch_request(struct tog_view **,
1233 struct tog_view *, enum tog_view_type, int, int);
1235 static const struct got_error *
1236 view_request_new(struct tog_view **requested, struct tog_view *view,
1237 enum tog_view_type request)
1239 struct tog_view *new_view = NULL;
1240 const struct got_error *err;
1241 int y = 0, x = 0;
1243 *requested = NULL;
1245 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1246 view_get_split(view, &y, &x);
1248 err = view_dispatch_request(&new_view, view, request, y, x);
1249 if (err)
1250 return err;
1252 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1253 request != TOG_VIEW_HELP) {
1254 err = view_init_hsplit(view, y);
1255 if (err)
1256 return err;
1259 view->focussed = 0;
1260 new_view->focussed = 1;
1261 new_view->mode = view->mode;
1262 new_view->nlines = request == TOG_VIEW_HELP ?
1263 view->lines : view->lines - y;
1265 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1266 view_transfer_size(new_view, view);
1267 err = view_close_child(view);
1268 if (err)
1269 return err;
1270 err = view_set_child(view, new_view);
1271 if (err)
1272 return err;
1273 view->focus_child = 1;
1274 } else
1275 *requested = new_view;
1277 return NULL;
1280 static void
1281 tog_resizeterm(void)
1283 int cols, lines;
1284 struct winsize size;
1286 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1287 cols = 80; /* Default */
1288 lines = 24;
1289 } else {
1290 cols = size.ws_col;
1291 lines = size.ws_row;
1293 resize_term(lines, cols);
1296 static const struct got_error *
1297 view_search_start(struct tog_view *view, int fast_refresh)
1299 const struct got_error *err = NULL;
1300 struct tog_view *v = view;
1301 char pattern[1024];
1302 int ret;
1304 if (view->search_started) {
1305 regfree(&view->regex);
1306 view->searching = 0;
1307 memset(&view->regmatch, 0, sizeof(view->regmatch));
1309 view->search_started = 0;
1311 if (view->nlines < 1)
1312 return NULL;
1314 if (view_is_hsplit_top(view))
1315 v = view->child;
1316 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1317 v = view->parent;
1319 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1320 wclrtoeol(v->window);
1322 nodelay(v->window, FALSE); /* block for search term input */
1323 nocbreak();
1324 echo();
1325 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1326 wrefresh(v->window);
1327 cbreak();
1328 noecho();
1329 nodelay(v->window, TRUE);
1330 if (!fast_refresh)
1331 halfdelay(10);
1332 if (ret == ERR)
1333 return NULL;
1335 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1336 err = view->search_start(view);
1337 if (err) {
1338 regfree(&view->regex);
1339 return err;
1341 view->search_started = 1;
1342 view->searching = TOG_SEARCH_FORWARD;
1343 view->search_next_done = 0;
1344 view->search_next(view);
1347 return NULL;
1350 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1351 static const struct got_error *
1352 switch_split(struct tog_view *view)
1354 const struct got_error *err = NULL;
1355 struct tog_view *v = NULL;
1357 if (view->parent)
1358 v = view->parent;
1359 else
1360 v = view;
1362 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1363 v->mode = TOG_VIEW_SPLIT_VERT;
1364 else
1365 v->mode = TOG_VIEW_SPLIT_HRZN;
1367 if (!v->child)
1368 return NULL;
1369 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1370 v->mode = TOG_VIEW_SPLIT_NONE;
1372 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1373 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1374 v->child->begin_y = v->child->resized_y;
1375 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1376 v->child->begin_x = v->child->resized_x;
1379 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1380 v->ncols = COLS;
1381 v->child->ncols = COLS;
1382 v->child->nscrolled = LINES - v->child->nlines;
1384 err = view_init_hsplit(v, v->child->begin_y);
1385 if (err)
1386 return err;
1388 v->child->mode = v->mode;
1389 v->child->nlines = v->lines - v->child->begin_y;
1390 v->focus_child = 1;
1392 err = view_fullscreen(v);
1393 if (err)
1394 return err;
1395 err = view_splitscreen(v->child);
1396 if (err)
1397 return err;
1399 if (v->mode == TOG_VIEW_SPLIT_NONE)
1400 v->mode = TOG_VIEW_SPLIT_VERT;
1401 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1402 err = offset_selection_down(v);
1403 if (err)
1404 return err;
1405 err = offset_selection_down(v->child);
1406 if (err)
1407 return err;
1408 } else {
1409 offset_selection_up(v);
1410 offset_selection_up(v->child);
1412 if (v->resize)
1413 err = v->resize(v, 0);
1414 else if (v->child->resize)
1415 err = v->child->resize(v->child, 0);
1417 return err;
1421 * Compute view->count from numeric input. Assign total to view->count and
1422 * return first non-numeric key entered.
1424 static int
1425 get_compound_key(struct tog_view *view, int c)
1427 struct tog_view *v = view;
1428 int x, n = 0;
1430 if (view_is_hsplit_top(view))
1431 v = view->child;
1432 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1433 v = view->parent;
1435 view->count = 0;
1436 cbreak(); /* block for input */
1437 nodelay(view->window, FALSE);
1438 wmove(v->window, v->nlines - 1, 0);
1439 wclrtoeol(v->window);
1440 waddch(v->window, ':');
1442 do {
1443 x = getcurx(v->window);
1444 if (x != ERR && x < view->ncols) {
1445 waddch(v->window, c);
1446 wrefresh(v->window);
1450 * Don't overflow. Max valid request should be the greatest
1451 * between the longest and total lines; cap at 10 million.
1453 if (n >= 9999999)
1454 n = 9999999;
1455 else
1456 n = n * 10 + (c - '0');
1457 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1459 if (c == 'G' || c == 'g') { /* nG key map */
1460 view->gline = view->hiline = n;
1461 n = 0;
1462 c = 0;
1465 /* Massage excessive or inapplicable values at the input handler. */
1466 view->count = n;
1468 return c;
1471 static void
1472 action_report(struct tog_view *view)
1474 struct tog_view *v = view;
1476 if (view_is_hsplit_top(view))
1477 v = view->child;
1478 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1479 v = view->parent;
1481 wmove(v->window, v->nlines - 1, 0);
1482 wclrtoeol(v->window);
1483 wprintw(v->window, ":%s", view->action);
1484 wrefresh(v->window);
1487 * Clear action status report. Only clear in blame view
1488 * once annotating is complete, otherwise it's too fast.
1490 if (view->type == TOG_VIEW_BLAME) {
1491 if (view->state.blame.blame_complete)
1492 view->action = NULL;
1493 } else
1494 view->action = NULL;
1497 static const struct got_error *
1498 view_input(struct tog_view **new, int *done, struct tog_view *view,
1499 struct tog_view_list_head *views, int fast_refresh)
1501 const struct got_error *err = NULL;
1502 struct tog_view *v;
1503 int ch, errcode;
1505 *new = NULL;
1507 if (view->action)
1508 action_report(view);
1510 /* Clear "no matches" indicator. */
1511 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1512 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1513 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1514 view->count = 0;
1517 if (view->searching && !view->search_next_done) {
1518 errcode = pthread_mutex_unlock(&tog_mutex);
1519 if (errcode)
1520 return got_error_set_errno(errcode,
1521 "pthread_mutex_unlock");
1522 sched_yield();
1523 errcode = pthread_mutex_lock(&tog_mutex);
1524 if (errcode)
1525 return got_error_set_errno(errcode,
1526 "pthread_mutex_lock");
1527 view->search_next(view);
1528 return NULL;
1531 /* Allow threads to make progress while we are waiting for input. */
1532 errcode = pthread_mutex_unlock(&tog_mutex);
1533 if (errcode)
1534 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1535 /* If we have an unfinished count, let C-g or backspace abort. */
1536 if (view->count && --view->count) {
1537 cbreak();
1538 nodelay(view->window, TRUE);
1539 ch = wgetch(view->window);
1540 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1541 view->count = 0;
1542 else
1543 ch = view->ch;
1544 } else {
1545 ch = wgetch(view->window);
1546 if (ch >= '1' && ch <= '9')
1547 view->ch = ch = get_compound_key(view, ch);
1549 if (view->hiline && ch != ERR && ch != 0)
1550 view->hiline = 0; /* key pressed, clear line highlight */
1551 nodelay(view->window, TRUE);
1552 errcode = pthread_mutex_lock(&tog_mutex);
1553 if (errcode)
1554 return got_error_set_errno(errcode, "pthread_mutex_lock");
1556 if (tog_sigwinch_received || tog_sigcont_received) {
1557 tog_resizeterm();
1558 tog_sigwinch_received = 0;
1559 tog_sigcont_received = 0;
1560 TAILQ_FOREACH(v, views, entry) {
1561 err = view_resize(v);
1562 if (err)
1563 return err;
1564 err = v->input(new, v, KEY_RESIZE);
1565 if (err)
1566 return err;
1567 if (v->child) {
1568 err = view_resize(v->child);
1569 if (err)
1570 return err;
1571 err = v->child->input(new, v->child,
1572 KEY_RESIZE);
1573 if (err)
1574 return err;
1575 if (v->child->resized_x || v->child->resized_y) {
1576 err = view_resize_split(v, 0);
1577 if (err)
1578 return err;
1584 switch (ch) {
1585 case '?':
1586 case 'H':
1587 case KEY_F(1):
1588 if (view->type == TOG_VIEW_HELP)
1589 err = view->reset(view);
1590 else
1591 err = view_request_new(new, view, TOG_VIEW_HELP);
1592 break;
1593 case '\t':
1594 view->count = 0;
1595 if (view->child) {
1596 view->focussed = 0;
1597 view->child->focussed = 1;
1598 view->focus_child = 1;
1599 } else if (view->parent) {
1600 view->focussed = 0;
1601 view->parent->focussed = 1;
1602 view->parent->focus_child = 0;
1603 if (!view_is_splitscreen(view)) {
1604 if (view->parent->resize) {
1605 err = view->parent->resize(view->parent,
1606 0);
1607 if (err)
1608 return err;
1610 offset_selection_up(view->parent);
1611 err = view_fullscreen(view->parent);
1612 if (err)
1613 return err;
1616 break;
1617 case 'q':
1618 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1619 if (view->parent->resize) {
1620 /* might need more commits to fill fullscreen */
1621 err = view->parent->resize(view->parent, 0);
1622 if (err)
1623 break;
1625 offset_selection_up(view->parent);
1627 err = view->input(new, view, ch);
1628 view->dying = 1;
1629 break;
1630 case 'Q':
1631 *done = 1;
1632 break;
1633 case 'F':
1634 view->count = 0;
1635 if (view_is_parent_view(view)) {
1636 if (view->child == NULL)
1637 break;
1638 if (view_is_splitscreen(view->child)) {
1639 view->focussed = 0;
1640 view->child->focussed = 1;
1641 err = view_fullscreen(view->child);
1642 } else {
1643 err = view_splitscreen(view->child);
1644 if (!err)
1645 err = view_resize_split(view, 0);
1647 if (err)
1648 break;
1649 err = view->child->input(new, view->child,
1650 KEY_RESIZE);
1651 } else {
1652 if (view_is_splitscreen(view)) {
1653 view->parent->focussed = 0;
1654 view->focussed = 1;
1655 err = view_fullscreen(view);
1656 } else {
1657 err = view_splitscreen(view);
1658 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1659 err = view_resize(view->parent);
1660 if (!err)
1661 err = view_resize_split(view, 0);
1663 if (err)
1664 break;
1665 err = view->input(new, view, KEY_RESIZE);
1667 if (err)
1668 break;
1669 if (view->resize) {
1670 err = view->resize(view, 0);
1671 if (err)
1672 break;
1674 if (view->parent)
1675 err = offset_selection_down(view->parent);
1676 if (!err)
1677 err = offset_selection_down(view);
1678 break;
1679 case 'S':
1680 view->count = 0;
1681 err = switch_split(view);
1682 break;
1683 case '-':
1684 err = view_resize_split(view, -1);
1685 break;
1686 case '+':
1687 err = view_resize_split(view, 1);
1688 break;
1689 case KEY_RESIZE:
1690 break;
1691 case '/':
1692 view->count = 0;
1693 if (view->search_start)
1694 view_search_start(view, fast_refresh);
1695 else
1696 err = view->input(new, view, ch);
1697 break;
1698 case 'N':
1699 case 'n':
1700 if (view->search_started && view->search_next) {
1701 view->searching = (ch == 'n' ?
1702 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1703 view->search_next_done = 0;
1704 view->search_next(view);
1705 } else
1706 err = view->input(new, view, ch);
1707 break;
1708 case 'A':
1709 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1710 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1711 view->action = "Patience diff algorithm";
1712 } else {
1713 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1714 view->action = "Myers diff algorithm";
1716 TAILQ_FOREACH(v, views, entry) {
1717 if (v->reset) {
1718 err = v->reset(v);
1719 if (err)
1720 return err;
1722 if (v->child && v->child->reset) {
1723 err = v->child->reset(v->child);
1724 if (err)
1725 return err;
1728 break;
1729 default:
1730 err = view->input(new, view, ch);
1731 break;
1734 return err;
1737 static int
1738 view_needs_focus_indication(struct tog_view *view)
1740 if (view_is_parent_view(view)) {
1741 if (view->child == NULL || view->child->focussed)
1742 return 0;
1743 if (!view_is_splitscreen(view->child))
1744 return 0;
1745 } else if (!view_is_splitscreen(view))
1746 return 0;
1748 return view->focussed;
1751 static const struct got_error *
1752 view_loop(struct tog_view *view)
1754 const struct got_error *err = NULL;
1755 struct tog_view_list_head views;
1756 struct tog_view *new_view;
1757 char *mode;
1758 int fast_refresh = 10;
1759 int done = 0, errcode;
1761 mode = getenv("TOG_VIEW_SPLIT_MODE");
1762 if (!mode || !(*mode == 'h' || *mode == 'H'))
1763 view->mode = TOG_VIEW_SPLIT_VERT;
1764 else
1765 view->mode = TOG_VIEW_SPLIT_HRZN;
1767 errcode = pthread_mutex_lock(&tog_mutex);
1768 if (errcode)
1769 return got_error_set_errno(errcode, "pthread_mutex_lock");
1771 TAILQ_INIT(&views);
1772 TAILQ_INSERT_HEAD(&views, view, entry);
1774 view->focussed = 1;
1775 err = view->show(view);
1776 if (err)
1777 return err;
1778 update_panels();
1779 doupdate();
1780 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1781 !tog_fatal_signal_received()) {
1782 /* Refresh fast during initialization, then become slower. */
1783 if (fast_refresh && --fast_refresh == 0)
1784 halfdelay(10); /* switch to once per second */
1786 err = view_input(&new_view, &done, view, &views, fast_refresh);
1787 if (err)
1788 break;
1790 if (view->dying && view == TAILQ_FIRST(&views) &&
1791 TAILQ_NEXT(view, entry) == NULL)
1792 done = 1;
1793 if (done) {
1794 struct tog_view *v;
1797 * When we quit, scroll the screen up a single line
1798 * so we don't lose any information.
1800 TAILQ_FOREACH(v, &views, entry) {
1801 wmove(v->window, 0, 0);
1802 wdeleteln(v->window);
1803 wnoutrefresh(v->window);
1804 if (v->child && !view_is_fullscreen(v)) {
1805 wmove(v->child->window, 0, 0);
1806 wdeleteln(v->child->window);
1807 wnoutrefresh(v->child->window);
1810 doupdate();
1813 if (view->dying) {
1814 struct tog_view *v, *prev = NULL;
1816 if (view_is_parent_view(view))
1817 prev = TAILQ_PREV(view, tog_view_list_head,
1818 entry);
1819 else if (view->parent)
1820 prev = view->parent;
1822 if (view->parent) {
1823 view->parent->child = NULL;
1824 view->parent->focus_child = 0;
1825 /* Restore fullscreen line height. */
1826 view->parent->nlines = view->parent->lines;
1827 err = view_resize(view->parent);
1828 if (err)
1829 break;
1830 /* Make resized splits persist. */
1831 view_transfer_size(view->parent, view);
1832 } else
1833 TAILQ_REMOVE(&views, view, entry);
1835 err = view_close(view);
1836 if (err)
1837 goto done;
1839 view = NULL;
1840 TAILQ_FOREACH(v, &views, entry) {
1841 if (v->focussed)
1842 break;
1844 if (view == NULL && new_view == NULL) {
1845 /* No view has focus. Try to pick one. */
1846 if (prev)
1847 view = prev;
1848 else if (!TAILQ_EMPTY(&views)) {
1849 view = TAILQ_LAST(&views,
1850 tog_view_list_head);
1852 if (view) {
1853 if (view->focus_child) {
1854 view->child->focussed = 1;
1855 view = view->child;
1856 } else
1857 view->focussed = 1;
1861 if (new_view) {
1862 struct tog_view *v, *t;
1863 /* Only allow one parent view per type. */
1864 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1865 if (v->type != new_view->type)
1866 continue;
1867 TAILQ_REMOVE(&views, v, entry);
1868 err = view_close(v);
1869 if (err)
1870 goto done;
1871 break;
1873 TAILQ_INSERT_TAIL(&views, new_view, entry);
1874 view = new_view;
1876 if (view && !done) {
1877 if (view_is_parent_view(view)) {
1878 if (view->child && view->child->focussed)
1879 view = view->child;
1880 } else {
1881 if (view->parent && view->parent->focussed)
1882 view = view->parent;
1884 show_panel(view->panel);
1885 if (view->child && view_is_splitscreen(view->child))
1886 show_panel(view->child->panel);
1887 if (view->parent && view_is_splitscreen(view)) {
1888 err = view->parent->show(view->parent);
1889 if (err)
1890 goto done;
1892 err = view->show(view);
1893 if (err)
1894 goto done;
1895 if (view->child) {
1896 err = view->child->show(view->child);
1897 if (err)
1898 goto done;
1900 update_panels();
1901 doupdate();
1904 done:
1905 while (!TAILQ_EMPTY(&views)) {
1906 const struct got_error *close_err;
1907 view = TAILQ_FIRST(&views);
1908 TAILQ_REMOVE(&views, view, entry);
1909 close_err = view_close(view);
1910 if (close_err && err == NULL)
1911 err = close_err;
1914 errcode = pthread_mutex_unlock(&tog_mutex);
1915 if (errcode && err == NULL)
1916 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1918 return err;
1921 __dead static void
1922 usage_log(void)
1924 endwin();
1925 fprintf(stderr,
1926 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1927 getprogname());
1928 exit(1);
1931 /* Create newly allocated wide-character string equivalent to a byte string. */
1932 static const struct got_error *
1933 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1935 char *vis = NULL;
1936 const struct got_error *err = NULL;
1938 *ws = NULL;
1939 *wlen = mbstowcs(NULL, s, 0);
1940 if (*wlen == (size_t)-1) {
1941 int vislen;
1942 if (errno != EILSEQ)
1943 return got_error_from_errno("mbstowcs");
1945 /* byte string invalid in current encoding; try to "fix" it */
1946 err = got_mbsavis(&vis, &vislen, s);
1947 if (err)
1948 return err;
1949 *wlen = mbstowcs(NULL, vis, 0);
1950 if (*wlen == (size_t)-1) {
1951 err = got_error_from_errno("mbstowcs"); /* give up */
1952 goto done;
1956 *ws = calloc(*wlen + 1, sizeof(**ws));
1957 if (*ws == NULL) {
1958 err = got_error_from_errno("calloc");
1959 goto done;
1962 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1963 err = got_error_from_errno("mbstowcs");
1964 done:
1965 free(vis);
1966 if (err) {
1967 free(*ws);
1968 *ws = NULL;
1969 *wlen = 0;
1971 return err;
1974 static const struct got_error *
1975 expand_tab(char **ptr, const char *src)
1977 char *dst;
1978 size_t len, n, idx = 0, sz = 0;
1980 *ptr = NULL;
1981 n = len = strlen(src);
1982 dst = malloc(n + 1);
1983 if (dst == NULL)
1984 return got_error_from_errno("malloc");
1986 while (idx < len && src[idx]) {
1987 const char c = src[idx];
1989 if (c == '\t') {
1990 size_t nb = TABSIZE - sz % TABSIZE;
1991 char *p;
1993 p = realloc(dst, n + nb);
1994 if (p == NULL) {
1995 free(dst);
1996 return got_error_from_errno("realloc");
1999 dst = p;
2000 n += nb;
2001 memset(dst + sz, ' ', nb);
2002 sz += nb;
2003 } else
2004 dst[sz++] = src[idx];
2005 ++idx;
2008 dst[sz] = '\0';
2009 *ptr = dst;
2010 return NULL;
2014 * Advance at most n columns from wline starting at offset off.
2015 * Return the index to the first character after the span operation.
2016 * Return the combined column width of all spanned wide character in
2017 * *rcol.
2019 static int
2020 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2022 int width, i, cols = 0;
2024 if (n == 0) {
2025 *rcol = cols;
2026 return off;
2029 for (i = off; wline[i] != L'\0'; ++i) {
2030 if (wline[i] == L'\t')
2031 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2032 else
2033 width = wcwidth(wline[i]);
2035 if (width == -1) {
2036 width = 1;
2037 wline[i] = L'.';
2040 if (cols + width > n)
2041 break;
2042 cols += width;
2045 *rcol = cols;
2046 return i;
2050 * Format a line for display, ensuring that it won't overflow a width limit.
2051 * With scrolling, the width returned refers to the scrolled version of the
2052 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2054 static const struct got_error *
2055 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2056 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2058 const struct got_error *err = NULL;
2059 int cols;
2060 wchar_t *wline = NULL;
2061 char *exstr = NULL;
2062 size_t wlen;
2063 int i, scrollx;
2065 *wlinep = NULL;
2066 *widthp = 0;
2068 if (expand) {
2069 err = expand_tab(&exstr, line);
2070 if (err)
2071 return err;
2074 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2075 free(exstr);
2076 if (err)
2077 return err;
2079 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2081 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2082 wline[wlen - 1] = L'\0';
2083 wlen--;
2085 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2086 wline[wlen - 1] = L'\0';
2087 wlen--;
2090 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2091 wline[i] = L'\0';
2093 if (widthp)
2094 *widthp = cols;
2095 if (scrollxp)
2096 *scrollxp = scrollx;
2097 if (err)
2098 free(wline);
2099 else
2100 *wlinep = wline;
2101 return err;
2104 static const struct got_error*
2105 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2106 struct got_object_id *id, struct got_repository *repo)
2108 static const struct got_error *err = NULL;
2109 struct got_reflist_entry *re;
2110 char *s;
2111 const char *name;
2113 *refs_str = NULL;
2115 TAILQ_FOREACH(re, refs, entry) {
2116 struct got_tag_object *tag = NULL;
2117 struct got_object_id *ref_id;
2118 int cmp;
2120 name = got_ref_get_name(re->ref);
2121 if (strcmp(name, GOT_REF_HEAD) == 0)
2122 continue;
2123 if (strncmp(name, "refs/", 5) == 0)
2124 name += 5;
2125 if (strncmp(name, "got/", 4) == 0 &&
2126 strncmp(name, "got/backup/", 11) != 0)
2127 continue;
2128 if (strncmp(name, "heads/", 6) == 0)
2129 name += 6;
2130 if (strncmp(name, "remotes/", 8) == 0) {
2131 name += 8;
2132 s = strstr(name, "/" GOT_REF_HEAD);
2133 if (s != NULL && s[strlen(s)] == '\0')
2134 continue;
2136 err = got_ref_resolve(&ref_id, repo, re->ref);
2137 if (err)
2138 break;
2139 if (strncmp(name, "tags/", 5) == 0) {
2140 err = got_object_open_as_tag(&tag, repo, ref_id);
2141 if (err) {
2142 if (err->code != GOT_ERR_OBJ_TYPE) {
2143 free(ref_id);
2144 break;
2146 /* Ref points at something other than a tag. */
2147 err = NULL;
2148 tag = NULL;
2151 cmp = got_object_id_cmp(tag ?
2152 got_object_tag_get_object_id(tag) : ref_id, id);
2153 free(ref_id);
2154 if (tag)
2155 got_object_tag_close(tag);
2156 if (cmp != 0)
2157 continue;
2158 s = *refs_str;
2159 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2160 s ? ", " : "", name) == -1) {
2161 err = got_error_from_errno("asprintf");
2162 free(s);
2163 *refs_str = NULL;
2164 break;
2166 free(s);
2169 return err;
2172 static const struct got_error *
2173 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2174 int col_tab_align)
2176 char *smallerthan;
2178 smallerthan = strchr(author, '<');
2179 if (smallerthan && smallerthan[1] != '\0')
2180 author = smallerthan + 1;
2181 author[strcspn(author, "@>")] = '\0';
2182 return format_line(wauthor, author_width, NULL, author, 0, limit,
2183 col_tab_align, 0);
2186 static const struct got_error *
2187 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2188 struct got_object_id *id, const size_t date_display_cols,
2189 int author_display_cols)
2191 struct tog_log_view_state *s = &view->state.log;
2192 const struct got_error *err = NULL;
2193 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2194 char *logmsg0 = NULL, *logmsg = NULL;
2195 char *author = NULL;
2196 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2197 int author_width, logmsg_width;
2198 char *newline, *line = NULL;
2199 int col, limit, scrollx;
2200 const int avail = view->ncols;
2201 struct tm tm;
2202 time_t committer_time;
2203 struct tog_color *tc;
2205 committer_time = got_object_commit_get_committer_time(commit);
2206 if (gmtime_r(&committer_time, &tm) == NULL)
2207 return got_error_from_errno("gmtime_r");
2208 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2209 return got_error(GOT_ERR_NO_SPACE);
2211 if (avail <= date_display_cols)
2212 limit = MIN(sizeof(datebuf) - 1, avail);
2213 else
2214 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2215 tc = get_color(&s->colors, TOG_COLOR_DATE);
2216 if (tc)
2217 wattr_on(view->window,
2218 COLOR_PAIR(tc->colorpair), NULL);
2219 waddnstr(view->window, datebuf, limit);
2220 if (tc)
2221 wattr_off(view->window,
2222 COLOR_PAIR(tc->colorpair), NULL);
2223 col = limit;
2224 if (col > avail)
2225 goto done;
2227 if (avail >= 120) {
2228 char *id_str;
2229 err = got_object_id_str(&id_str, id);
2230 if (err)
2231 goto done;
2232 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2233 if (tc)
2234 wattr_on(view->window,
2235 COLOR_PAIR(tc->colorpair), NULL);
2236 wprintw(view->window, "%.8s ", id_str);
2237 if (tc)
2238 wattr_off(view->window,
2239 COLOR_PAIR(tc->colorpair), NULL);
2240 free(id_str);
2241 col += 9;
2242 if (col > avail)
2243 goto done;
2246 if (s->use_committer)
2247 author = strdup(got_object_commit_get_committer(commit));
2248 else
2249 author = strdup(got_object_commit_get_author(commit));
2250 if (author == NULL) {
2251 err = got_error_from_errno("strdup");
2252 goto done;
2254 err = format_author(&wauthor, &author_width, author, avail - col, col);
2255 if (err)
2256 goto done;
2257 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2258 if (tc)
2259 wattr_on(view->window,
2260 COLOR_PAIR(tc->colorpair), NULL);
2261 waddwstr(view->window, wauthor);
2262 col += author_width;
2263 while (col < avail && author_width < author_display_cols + 2) {
2264 waddch(view->window, ' ');
2265 col++;
2266 author_width++;
2268 if (tc)
2269 wattr_off(view->window,
2270 COLOR_PAIR(tc->colorpair), NULL);
2271 if (col > avail)
2272 goto done;
2274 err = got_object_commit_get_logmsg(&logmsg0, commit);
2275 if (err)
2276 goto done;
2277 logmsg = logmsg0;
2278 while (*logmsg == '\n')
2279 logmsg++;
2280 newline = strchr(logmsg, '\n');
2281 if (newline)
2282 *newline = '\0';
2283 limit = avail - col;
2284 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2285 limit--; /* for the border */
2286 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2287 limit, col, 1);
2288 if (err)
2289 goto done;
2290 waddwstr(view->window, &wlogmsg[scrollx]);
2291 col += MAX(logmsg_width, 0);
2292 while (col < avail) {
2293 waddch(view->window, ' ');
2294 col++;
2296 done:
2297 free(logmsg0);
2298 free(wlogmsg);
2299 free(author);
2300 free(wauthor);
2301 free(line);
2302 return err;
2305 static struct commit_queue_entry *
2306 alloc_commit_queue_entry(struct got_commit_object *commit,
2307 struct got_object_id *id)
2309 struct commit_queue_entry *entry;
2310 struct got_object_id *dup;
2312 entry = calloc(1, sizeof(*entry));
2313 if (entry == NULL)
2314 return NULL;
2316 dup = got_object_id_dup(id);
2317 if (dup == NULL) {
2318 free(entry);
2319 return NULL;
2322 entry->id = dup;
2323 entry->commit = commit;
2324 return entry;
2327 static void
2328 pop_commit(struct commit_queue *commits)
2330 struct commit_queue_entry *entry;
2332 entry = TAILQ_FIRST(&commits->head);
2333 TAILQ_REMOVE(&commits->head, entry, entry);
2334 got_object_commit_close(entry->commit);
2335 commits->ncommits--;
2336 free(entry->id);
2337 free(entry);
2340 static void
2341 free_commits(struct commit_queue *commits)
2343 while (!TAILQ_EMPTY(&commits->head))
2344 pop_commit(commits);
2347 static const struct got_error *
2348 match_commit(int *have_match, struct got_object_id *id,
2349 struct got_commit_object *commit, regex_t *regex)
2351 const struct got_error *err = NULL;
2352 regmatch_t regmatch;
2353 char *id_str = NULL, *logmsg = NULL;
2355 *have_match = 0;
2357 err = got_object_id_str(&id_str, id);
2358 if (err)
2359 return err;
2361 err = got_object_commit_get_logmsg(&logmsg, commit);
2362 if (err)
2363 goto done;
2365 if (regexec(regex, got_object_commit_get_author(commit), 1,
2366 &regmatch, 0) == 0 ||
2367 regexec(regex, got_object_commit_get_committer(commit), 1,
2368 &regmatch, 0) == 0 ||
2369 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2370 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2371 *have_match = 1;
2372 done:
2373 free(id_str);
2374 free(logmsg);
2375 return err;
2378 static const struct got_error *
2379 queue_commits(struct tog_log_thread_args *a)
2381 const struct got_error *err = NULL;
2384 * We keep all commits open throughout the lifetime of the log
2385 * view in order to avoid having to re-fetch commits from disk
2386 * while updating the display.
2388 do {
2389 struct got_object_id id;
2390 struct got_commit_object *commit;
2391 struct commit_queue_entry *entry;
2392 int limit_match = 0;
2393 int errcode;
2395 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2396 NULL, NULL);
2397 if (err)
2398 break;
2400 err = got_object_open_as_commit(&commit, a->repo, &id);
2401 if (err)
2402 break;
2403 entry = alloc_commit_queue_entry(commit, &id);
2404 if (entry == NULL) {
2405 err = got_error_from_errno("alloc_commit_queue_entry");
2406 break;
2409 errcode = pthread_mutex_lock(&tog_mutex);
2410 if (errcode) {
2411 err = got_error_set_errno(errcode,
2412 "pthread_mutex_lock");
2413 break;
2416 entry->idx = a->real_commits->ncommits;
2417 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2418 a->real_commits->ncommits++;
2420 if (*a->limiting) {
2421 err = match_commit(&limit_match, &id, commit,
2422 a->limit_regex);
2423 if (err)
2424 break;
2426 if (limit_match) {
2427 struct commit_queue_entry *matched;
2429 matched = alloc_commit_queue_entry(
2430 entry->commit, entry->id);
2431 if (matched == NULL) {
2432 err = got_error_from_errno(
2433 "alloc_commit_queue_entry");
2434 break;
2436 matched->commit = entry->commit;
2437 got_object_commit_retain(entry->commit);
2439 matched->idx = a->limit_commits->ncommits;
2440 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2441 matched, entry);
2442 a->limit_commits->ncommits++;
2446 * This is how we signal log_thread() that we
2447 * have found a match, and that it should be
2448 * counted as a new entry for the view.
2450 a->limit_match = limit_match;
2453 if (*a->searching == TOG_SEARCH_FORWARD &&
2454 !*a->search_next_done) {
2455 int have_match;
2456 err = match_commit(&have_match, &id, commit, a->regex);
2457 if (err)
2458 break;
2460 if (*a->limiting) {
2461 if (limit_match && have_match)
2462 *a->search_next_done =
2463 TOG_SEARCH_HAVE_MORE;
2464 } else if (have_match)
2465 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2468 errcode = pthread_mutex_unlock(&tog_mutex);
2469 if (errcode && err == NULL)
2470 err = got_error_set_errno(errcode,
2471 "pthread_mutex_unlock");
2472 if (err)
2473 break;
2474 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2476 return err;
2479 static void
2480 select_commit(struct tog_log_view_state *s)
2482 struct commit_queue_entry *entry;
2483 int ncommits = 0;
2485 entry = s->first_displayed_entry;
2486 while (entry) {
2487 if (ncommits == s->selected) {
2488 s->selected_entry = entry;
2489 break;
2491 entry = TAILQ_NEXT(entry, entry);
2492 ncommits++;
2496 static const struct got_error *
2497 draw_commits(struct tog_view *view)
2499 const struct got_error *err = NULL;
2500 struct tog_log_view_state *s = &view->state.log;
2501 struct commit_queue_entry *entry = s->selected_entry;
2502 int limit = view->nlines;
2503 int width;
2504 int ncommits, author_cols = 4;
2505 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2506 char *refs_str = NULL;
2507 wchar_t *wline;
2508 struct tog_color *tc;
2509 static const size_t date_display_cols = 12;
2511 if (view_is_hsplit_top(view))
2512 --limit; /* account for border */
2514 if (s->selected_entry &&
2515 !(view->searching && view->search_next_done == 0)) {
2516 struct got_reflist_head *refs;
2517 err = got_object_id_str(&id_str, s->selected_entry->id);
2518 if (err)
2519 return err;
2520 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2521 s->selected_entry->id);
2522 if (refs) {
2523 err = build_refs_str(&refs_str, refs,
2524 s->selected_entry->id, s->repo);
2525 if (err)
2526 goto done;
2530 if (s->thread_args.commits_needed == 0)
2531 halfdelay(10); /* disable fast refresh */
2533 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2534 if (asprintf(&ncommits_str, " [%d/%d] %s",
2535 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2536 (view->searching && !view->search_next_done) ?
2537 "searching..." : "loading...") == -1) {
2538 err = got_error_from_errno("asprintf");
2539 goto done;
2541 } else {
2542 const char *search_str = NULL;
2543 const char *limit_str = NULL;
2545 if (view->searching) {
2546 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2547 search_str = "no more matches";
2548 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2549 search_str = "no matches found";
2550 else if (!view->search_next_done)
2551 search_str = "searching...";
2554 if (s->limit_view && s->commits->ncommits == 0)
2555 limit_str = "no matches found";
2557 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2558 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2559 search_str ? search_str : (refs_str ? refs_str : ""),
2560 limit_str ? limit_str : "") == -1) {
2561 err = got_error_from_errno("asprintf");
2562 goto done;
2566 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2567 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2568 "........................................",
2569 s->in_repo_path, ncommits_str) == -1) {
2570 err = got_error_from_errno("asprintf");
2571 header = NULL;
2572 goto done;
2574 } else if (asprintf(&header, "commit %s%s",
2575 id_str ? id_str : "........................................",
2576 ncommits_str) == -1) {
2577 err = got_error_from_errno("asprintf");
2578 header = NULL;
2579 goto done;
2581 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2582 if (err)
2583 goto done;
2585 werase(view->window);
2587 if (view_needs_focus_indication(view))
2588 wstandout(view->window);
2589 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2590 if (tc)
2591 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2592 waddwstr(view->window, wline);
2593 while (width < view->ncols) {
2594 waddch(view->window, ' ');
2595 width++;
2597 if (tc)
2598 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2599 if (view_needs_focus_indication(view))
2600 wstandend(view->window);
2601 free(wline);
2602 if (limit <= 1)
2603 goto done;
2605 /* Grow author column size if necessary, and set view->maxx. */
2606 entry = s->first_displayed_entry;
2607 ncommits = 0;
2608 view->maxx = 0;
2609 while (entry) {
2610 struct got_commit_object *c = entry->commit;
2611 char *author, *eol, *msg, *msg0;
2612 wchar_t *wauthor, *wmsg;
2613 int width;
2614 if (ncommits >= limit - 1)
2615 break;
2616 if (s->use_committer)
2617 author = strdup(got_object_commit_get_committer(c));
2618 else
2619 author = strdup(got_object_commit_get_author(c));
2620 if (author == NULL) {
2621 err = got_error_from_errno("strdup");
2622 goto done;
2624 err = format_author(&wauthor, &width, author, COLS,
2625 date_display_cols);
2626 if (author_cols < width)
2627 author_cols = width;
2628 free(wauthor);
2629 free(author);
2630 if (err)
2631 goto done;
2632 err = got_object_commit_get_logmsg(&msg0, c);
2633 if (err)
2634 goto done;
2635 msg = msg0;
2636 while (*msg == '\n')
2637 ++msg;
2638 if ((eol = strchr(msg, '\n')))
2639 *eol = '\0';
2640 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2641 date_display_cols + author_cols, 0);
2642 if (err)
2643 goto done;
2644 view->maxx = MAX(view->maxx, width);
2645 free(msg0);
2646 free(wmsg);
2647 ncommits++;
2648 entry = TAILQ_NEXT(entry, entry);
2651 entry = s->first_displayed_entry;
2652 s->last_displayed_entry = s->first_displayed_entry;
2653 ncommits = 0;
2654 while (entry) {
2655 if (ncommits >= limit - 1)
2656 break;
2657 if (ncommits == s->selected)
2658 wstandout(view->window);
2659 err = draw_commit(view, entry->commit, entry->id,
2660 date_display_cols, author_cols);
2661 if (ncommits == s->selected)
2662 wstandend(view->window);
2663 if (err)
2664 goto done;
2665 ncommits++;
2666 s->last_displayed_entry = entry;
2667 entry = TAILQ_NEXT(entry, entry);
2670 view_border(view);
2671 done:
2672 free(id_str);
2673 free(refs_str);
2674 free(ncommits_str);
2675 free(header);
2676 return err;
2679 static void
2680 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2682 struct commit_queue_entry *entry;
2683 int nscrolled = 0;
2685 entry = TAILQ_FIRST(&s->commits->head);
2686 if (s->first_displayed_entry == entry)
2687 return;
2689 entry = s->first_displayed_entry;
2690 while (entry && nscrolled < maxscroll) {
2691 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2692 if (entry) {
2693 s->first_displayed_entry = entry;
2694 nscrolled++;
2699 static const struct got_error *
2700 trigger_log_thread(struct tog_view *view, int wait)
2702 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2703 int errcode;
2705 halfdelay(1); /* fast refresh while loading commits */
2707 while (!ta->log_complete && !tog_thread_error &&
2708 (ta->commits_needed > 0 || ta->load_all)) {
2709 /* Wake the log thread. */
2710 errcode = pthread_cond_signal(&ta->need_commits);
2711 if (errcode)
2712 return got_error_set_errno(errcode,
2713 "pthread_cond_signal");
2716 * The mutex will be released while the view loop waits
2717 * in wgetch(), at which time the log thread will run.
2719 if (!wait)
2720 break;
2722 /* Display progress update in log view. */
2723 show_log_view(view);
2724 update_panels();
2725 doupdate();
2727 /* Wait right here while next commit is being loaded. */
2728 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2729 if (errcode)
2730 return got_error_set_errno(errcode,
2731 "pthread_cond_wait");
2733 /* Display progress update in log view. */
2734 show_log_view(view);
2735 update_panels();
2736 doupdate();
2739 return NULL;
2742 static const struct got_error *
2743 request_log_commits(struct tog_view *view)
2745 struct tog_log_view_state *state = &view->state.log;
2746 const struct got_error *err = NULL;
2748 if (state->thread_args.log_complete)
2749 return NULL;
2751 state->thread_args.commits_needed += view->nscrolled;
2752 err = trigger_log_thread(view, 1);
2753 view->nscrolled = 0;
2755 return err;
2758 static const struct got_error *
2759 log_scroll_down(struct tog_view *view, int maxscroll)
2761 struct tog_log_view_state *s = &view->state.log;
2762 const struct got_error *err = NULL;
2763 struct commit_queue_entry *pentry;
2764 int nscrolled = 0, ncommits_needed;
2766 if (s->last_displayed_entry == NULL)
2767 return NULL;
2769 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2770 if (s->commits->ncommits < ncommits_needed &&
2771 !s->thread_args.log_complete) {
2773 * Ask the log thread for required amount of commits.
2775 s->thread_args.commits_needed +=
2776 ncommits_needed - s->commits->ncommits;
2777 err = trigger_log_thread(view, 1);
2778 if (err)
2779 return err;
2782 do {
2783 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2784 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2785 break;
2787 s->last_displayed_entry = pentry ?
2788 pentry : s->last_displayed_entry;
2790 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2791 if (pentry == NULL)
2792 break;
2793 s->first_displayed_entry = pentry;
2794 } while (++nscrolled < maxscroll);
2796 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2797 view->nscrolled += nscrolled;
2798 else
2799 view->nscrolled = 0;
2801 return err;
2804 static const struct got_error *
2805 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2806 struct got_commit_object *commit, struct got_object_id *commit_id,
2807 struct tog_view *log_view, struct got_repository *repo)
2809 const struct got_error *err;
2810 struct got_object_qid *parent_id;
2811 struct tog_view *diff_view;
2813 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2814 if (diff_view == NULL)
2815 return got_error_from_errno("view_open");
2817 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2818 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2819 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2820 if (err == NULL)
2821 *new_view = diff_view;
2822 return err;
2825 static const struct got_error *
2826 tree_view_visit_subtree(struct tog_tree_view_state *s,
2827 struct got_tree_object *subtree)
2829 struct tog_parent_tree *parent;
2831 parent = calloc(1, sizeof(*parent));
2832 if (parent == NULL)
2833 return got_error_from_errno("calloc");
2835 parent->tree = s->tree;
2836 parent->first_displayed_entry = s->first_displayed_entry;
2837 parent->selected_entry = s->selected_entry;
2838 parent->selected = s->selected;
2839 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2840 s->tree = subtree;
2841 s->selected = 0;
2842 s->first_displayed_entry = NULL;
2843 return NULL;
2846 static const struct got_error *
2847 tree_view_walk_path(struct tog_tree_view_state *s,
2848 struct got_commit_object *commit, const char *path)
2850 const struct got_error *err = NULL;
2851 struct got_tree_object *tree = NULL;
2852 const char *p;
2853 char *slash, *subpath = NULL;
2855 /* Walk the path and open corresponding tree objects. */
2856 p = path;
2857 while (*p) {
2858 struct got_tree_entry *te;
2859 struct got_object_id *tree_id;
2860 char *te_name;
2862 while (p[0] == '/')
2863 p++;
2865 /* Ensure the correct subtree entry is selected. */
2866 slash = strchr(p, '/');
2867 if (slash == NULL)
2868 te_name = strdup(p);
2869 else
2870 te_name = strndup(p, slash - p);
2871 if (te_name == NULL) {
2872 err = got_error_from_errno("strndup");
2873 break;
2875 te = got_object_tree_find_entry(s->tree, te_name);
2876 if (te == NULL) {
2877 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2878 free(te_name);
2879 break;
2881 free(te_name);
2882 s->first_displayed_entry = s->selected_entry = te;
2884 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2885 break; /* jump to this file's entry */
2887 slash = strchr(p, '/');
2888 if (slash)
2889 subpath = strndup(path, slash - path);
2890 else
2891 subpath = strdup(path);
2892 if (subpath == NULL) {
2893 err = got_error_from_errno("strdup");
2894 break;
2897 err = got_object_id_by_path(&tree_id, s->repo, commit,
2898 subpath);
2899 if (err)
2900 break;
2902 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2903 free(tree_id);
2904 if (err)
2905 break;
2907 err = tree_view_visit_subtree(s, tree);
2908 if (err) {
2909 got_object_tree_close(tree);
2910 break;
2912 if (slash == NULL)
2913 break;
2914 free(subpath);
2915 subpath = NULL;
2916 p = slash;
2919 free(subpath);
2920 return err;
2923 static const struct got_error *
2924 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2925 struct commit_queue_entry *entry, const char *path,
2926 const char *head_ref_name, struct got_repository *repo)
2928 const struct got_error *err = NULL;
2929 struct tog_tree_view_state *s;
2930 struct tog_view *tree_view;
2932 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2933 if (tree_view == NULL)
2934 return got_error_from_errno("view_open");
2936 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2937 if (err)
2938 return err;
2939 s = &tree_view->state.tree;
2941 *new_view = tree_view;
2943 if (got_path_is_root_dir(path))
2944 return NULL;
2946 return tree_view_walk_path(s, entry->commit, path);
2949 static const struct got_error *
2950 block_signals_used_by_main_thread(void)
2952 sigset_t sigset;
2953 int errcode;
2955 if (sigemptyset(&sigset) == -1)
2956 return got_error_from_errno("sigemptyset");
2958 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2959 if (sigaddset(&sigset, SIGWINCH) == -1)
2960 return got_error_from_errno("sigaddset");
2961 if (sigaddset(&sigset, SIGCONT) == -1)
2962 return got_error_from_errno("sigaddset");
2963 if (sigaddset(&sigset, SIGINT) == -1)
2964 return got_error_from_errno("sigaddset");
2965 if (sigaddset(&sigset, SIGTERM) == -1)
2966 return got_error_from_errno("sigaddset");
2968 /* ncurses handles SIGTSTP */
2969 if (sigaddset(&sigset, SIGTSTP) == -1)
2970 return got_error_from_errno("sigaddset");
2972 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2973 if (errcode)
2974 return got_error_set_errno(errcode, "pthread_sigmask");
2976 return NULL;
2979 static void *
2980 log_thread(void *arg)
2982 const struct got_error *err = NULL;
2983 int errcode = 0;
2984 struct tog_log_thread_args *a = arg;
2985 int done = 0;
2988 * Sync startup with main thread such that we begin our
2989 * work once view_input() has released the mutex.
2991 errcode = pthread_mutex_lock(&tog_mutex);
2992 if (errcode) {
2993 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2994 return (void *)err;
2997 err = block_signals_used_by_main_thread();
2998 if (err) {
2999 pthread_mutex_unlock(&tog_mutex);
3000 goto done;
3003 while (!done && !err && !tog_fatal_signal_received()) {
3004 errcode = pthread_mutex_unlock(&tog_mutex);
3005 if (errcode) {
3006 err = got_error_set_errno(errcode,
3007 "pthread_mutex_unlock");
3008 goto done;
3010 err = queue_commits(a);
3011 if (err) {
3012 if (err->code != GOT_ERR_ITER_COMPLETED)
3013 goto done;
3014 err = NULL;
3015 done = 1;
3016 } else if (a->commits_needed > 0 && !a->load_all) {
3017 if (*a->limiting) {
3018 if (a->limit_match)
3019 a->commits_needed--;
3020 } else
3021 a->commits_needed--;
3024 errcode = pthread_mutex_lock(&tog_mutex);
3025 if (errcode) {
3026 err = got_error_set_errno(errcode,
3027 "pthread_mutex_lock");
3028 goto done;
3029 } else if (*a->quit)
3030 done = 1;
3031 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3032 *a->first_displayed_entry =
3033 TAILQ_FIRST(&a->limit_commits->head);
3034 *a->selected_entry = *a->first_displayed_entry;
3035 } else if (*a->first_displayed_entry == NULL) {
3036 *a->first_displayed_entry =
3037 TAILQ_FIRST(&a->real_commits->head);
3038 *a->selected_entry = *a->first_displayed_entry;
3041 errcode = pthread_cond_signal(&a->commit_loaded);
3042 if (errcode) {
3043 err = got_error_set_errno(errcode,
3044 "pthread_cond_signal");
3045 pthread_mutex_unlock(&tog_mutex);
3046 goto done;
3049 if (done)
3050 a->commits_needed = 0;
3051 else {
3052 if (a->commits_needed == 0 && !a->load_all) {
3053 errcode = pthread_cond_wait(&a->need_commits,
3054 &tog_mutex);
3055 if (errcode) {
3056 err = got_error_set_errno(errcode,
3057 "pthread_cond_wait");
3058 pthread_mutex_unlock(&tog_mutex);
3059 goto done;
3061 if (*a->quit)
3062 done = 1;
3066 a->log_complete = 1;
3067 errcode = pthread_mutex_unlock(&tog_mutex);
3068 if (errcode)
3069 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3070 done:
3071 if (err) {
3072 tog_thread_error = 1;
3073 pthread_cond_signal(&a->commit_loaded);
3075 return (void *)err;
3078 static const struct got_error *
3079 stop_log_thread(struct tog_log_view_state *s)
3081 const struct got_error *err = NULL, *thread_err = NULL;
3082 int errcode;
3084 if (s->thread) {
3085 s->quit = 1;
3086 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3087 if (errcode)
3088 return got_error_set_errno(errcode,
3089 "pthread_cond_signal");
3090 errcode = pthread_mutex_unlock(&tog_mutex);
3091 if (errcode)
3092 return got_error_set_errno(errcode,
3093 "pthread_mutex_unlock");
3094 errcode = pthread_join(s->thread, (void **)&thread_err);
3095 if (errcode)
3096 return got_error_set_errno(errcode, "pthread_join");
3097 errcode = pthread_mutex_lock(&tog_mutex);
3098 if (errcode)
3099 return got_error_set_errno(errcode,
3100 "pthread_mutex_lock");
3101 s->thread = 0; //NULL;
3104 if (s->thread_args.repo) {
3105 err = got_repo_close(s->thread_args.repo);
3106 s->thread_args.repo = NULL;
3109 if (s->thread_args.pack_fds) {
3110 const struct got_error *pack_err =
3111 got_repo_pack_fds_close(s->thread_args.pack_fds);
3112 if (err == NULL)
3113 err = pack_err;
3114 s->thread_args.pack_fds = NULL;
3117 if (s->thread_args.graph) {
3118 got_commit_graph_close(s->thread_args.graph);
3119 s->thread_args.graph = NULL;
3122 return err ? err : thread_err;
3125 static const struct got_error *
3126 close_log_view(struct tog_view *view)
3128 const struct got_error *err = NULL;
3129 struct tog_log_view_state *s = &view->state.log;
3130 int errcode;
3132 err = stop_log_thread(s);
3134 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3135 if (errcode && err == NULL)
3136 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3138 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3139 if (errcode && err == NULL)
3140 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3142 free_commits(&s->limit_commits);
3143 free_commits(&s->real_commits);
3144 free(s->in_repo_path);
3145 s->in_repo_path = NULL;
3146 free(s->start_id);
3147 s->start_id = NULL;
3148 free(s->head_ref_name);
3149 s->head_ref_name = NULL;
3150 return err;
3154 * We use two queues to implement the limit feature: first consists of
3155 * commits matching the current limit_regex; second is the real queue
3156 * of all known commits (real_commits). When the user starts limiting,
3157 * we swap queues such that all movement and displaying functionality
3158 * works with very slight change.
3160 static const struct got_error *
3161 limit_log_view(struct tog_view *view)
3163 struct tog_log_view_state *s = &view->state.log;
3164 struct commit_queue_entry *entry;
3165 struct tog_view *v = view;
3166 const struct got_error *err = NULL;
3167 char pattern[1024];
3168 int ret;
3170 if (view_is_hsplit_top(view))
3171 v = view->child;
3172 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3173 v = view->parent;
3175 /* Get the pattern */
3176 wmove(v->window, v->nlines - 1, 0);
3177 wclrtoeol(v->window);
3178 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3179 nodelay(v->window, FALSE);
3180 nocbreak();
3181 echo();
3182 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3183 cbreak();
3184 noecho();
3185 nodelay(v->window, TRUE);
3186 if (ret == ERR)
3187 return NULL;
3189 if (*pattern == '\0') {
3191 * Safety measure for the situation where the user
3192 * resets limit without previously limiting anything.
3194 if (!s->limit_view)
3195 return NULL;
3198 * User could have pressed Ctrl+L, which refreshed the
3199 * commit queues, it means we can't save previously
3200 * (before limit took place) displayed entries,
3201 * because they would point to already free'ed memory,
3202 * so we are forced to always select first entry of
3203 * the queue.
3205 s->commits = &s->real_commits;
3206 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3207 s->selected_entry = s->first_displayed_entry;
3208 s->selected = 0;
3209 s->limit_view = 0;
3211 return NULL;
3214 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3215 return NULL;
3217 s->limit_view = 1;
3219 /* Clear the screen while loading limit view */
3220 s->first_displayed_entry = NULL;
3221 s->last_displayed_entry = NULL;
3222 s->selected_entry = NULL;
3223 s->commits = &s->limit_commits;
3225 /* Prepare limit queue for new search */
3226 free_commits(&s->limit_commits);
3227 s->limit_commits.ncommits = 0;
3229 /* First process commits, which are in queue already */
3230 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3231 int have_match = 0;
3233 err = match_commit(&have_match, entry->id,
3234 entry->commit, &s->limit_regex);
3235 if (err)
3236 return err;
3238 if (have_match) {
3239 struct commit_queue_entry *matched;
3241 matched = alloc_commit_queue_entry(entry->commit,
3242 entry->id);
3243 if (matched == NULL) {
3244 err = got_error_from_errno(
3245 "alloc_commit_queue_entry");
3246 break;
3248 matched->commit = entry->commit;
3249 got_object_commit_retain(entry->commit);
3251 matched->idx = s->limit_commits.ncommits;
3252 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3253 matched, entry);
3254 s->limit_commits.ncommits++;
3258 /* Second process all the commits, until we fill the screen */
3259 if (s->limit_commits.ncommits < view->nlines - 1 &&
3260 !s->thread_args.log_complete) {
3261 s->thread_args.commits_needed +=
3262 view->nlines - s->limit_commits.ncommits - 1;
3263 err = trigger_log_thread(view, 1);
3264 if (err)
3265 return err;
3268 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3269 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3270 s->selected = 0;
3272 return NULL;
3275 static const struct got_error *
3276 search_start_log_view(struct tog_view *view)
3278 struct tog_log_view_state *s = &view->state.log;
3280 s->matched_entry = NULL;
3281 s->search_entry = NULL;
3282 return NULL;
3285 static const struct got_error *
3286 search_next_log_view(struct tog_view *view)
3288 const struct got_error *err = NULL;
3289 struct tog_log_view_state *s = &view->state.log;
3290 struct commit_queue_entry *entry;
3292 /* Display progress update in log view. */
3293 show_log_view(view);
3294 update_panels();
3295 doupdate();
3297 if (s->search_entry) {
3298 int errcode, ch;
3299 errcode = pthread_mutex_unlock(&tog_mutex);
3300 if (errcode)
3301 return got_error_set_errno(errcode,
3302 "pthread_mutex_unlock");
3303 ch = wgetch(view->window);
3304 errcode = pthread_mutex_lock(&tog_mutex);
3305 if (errcode)
3306 return got_error_set_errno(errcode,
3307 "pthread_mutex_lock");
3308 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3309 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3310 return NULL;
3312 if (view->searching == TOG_SEARCH_FORWARD)
3313 entry = TAILQ_NEXT(s->search_entry, entry);
3314 else
3315 entry = TAILQ_PREV(s->search_entry,
3316 commit_queue_head, entry);
3317 } else if (s->matched_entry) {
3319 * If the user has moved the cursor after we hit a match,
3320 * the position from where we should continue searching
3321 * might have changed.
3323 if (view->searching == TOG_SEARCH_FORWARD)
3324 entry = TAILQ_NEXT(s->selected_entry, entry);
3325 else
3326 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3327 entry);
3328 } else {
3329 entry = s->selected_entry;
3332 while (1) {
3333 int have_match = 0;
3335 if (entry == NULL) {
3336 if (s->thread_args.log_complete ||
3337 view->searching == TOG_SEARCH_BACKWARD) {
3338 view->search_next_done =
3339 (s->matched_entry == NULL ?
3340 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3341 s->search_entry = NULL;
3342 return NULL;
3345 * Poke the log thread for more commits and return,
3346 * allowing the main loop to make progress. Search
3347 * will resume at s->search_entry once we come back.
3349 s->thread_args.commits_needed++;
3350 return trigger_log_thread(view, 0);
3353 err = match_commit(&have_match, entry->id, entry->commit,
3354 &view->regex);
3355 if (err)
3356 break;
3357 if (have_match) {
3358 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3359 s->matched_entry = entry;
3360 break;
3363 s->search_entry = entry;
3364 if (view->searching == TOG_SEARCH_FORWARD)
3365 entry = TAILQ_NEXT(entry, entry);
3366 else
3367 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3370 if (s->matched_entry) {
3371 int cur = s->selected_entry->idx;
3372 while (cur < s->matched_entry->idx) {
3373 err = input_log_view(NULL, view, KEY_DOWN);
3374 if (err)
3375 return err;
3376 cur++;
3378 while (cur > s->matched_entry->idx) {
3379 err = input_log_view(NULL, view, KEY_UP);
3380 if (err)
3381 return err;
3382 cur--;
3386 s->search_entry = NULL;
3388 return NULL;
3391 static const struct got_error *
3392 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3393 struct got_repository *repo, const char *head_ref_name,
3394 const char *in_repo_path, int log_branches)
3396 const struct got_error *err = NULL;
3397 struct tog_log_view_state *s = &view->state.log;
3398 struct got_repository *thread_repo = NULL;
3399 struct got_commit_graph *thread_graph = NULL;
3400 int errcode;
3402 if (in_repo_path != s->in_repo_path) {
3403 free(s->in_repo_path);
3404 s->in_repo_path = strdup(in_repo_path);
3405 if (s->in_repo_path == NULL)
3406 return got_error_from_errno("strdup");
3409 /* The commit queue only contains commits being displayed. */
3410 TAILQ_INIT(&s->real_commits.head);
3411 s->real_commits.ncommits = 0;
3412 s->commits = &s->real_commits;
3414 TAILQ_INIT(&s->limit_commits.head);
3415 s->limit_view = 0;
3416 s->limit_commits.ncommits = 0;
3418 s->repo = repo;
3419 if (head_ref_name) {
3420 s->head_ref_name = strdup(head_ref_name);
3421 if (s->head_ref_name == NULL) {
3422 err = got_error_from_errno("strdup");
3423 goto done;
3426 s->start_id = got_object_id_dup(start_id);
3427 if (s->start_id == NULL) {
3428 err = got_error_from_errno("got_object_id_dup");
3429 goto done;
3431 s->log_branches = log_branches;
3432 s->use_committer = 1;
3434 STAILQ_INIT(&s->colors);
3435 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3436 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3437 get_color_value("TOG_COLOR_COMMIT"));
3438 if (err)
3439 goto done;
3440 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3441 get_color_value("TOG_COLOR_AUTHOR"));
3442 if (err) {
3443 free_colors(&s->colors);
3444 goto done;
3446 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3447 get_color_value("TOG_COLOR_DATE"));
3448 if (err) {
3449 free_colors(&s->colors);
3450 goto done;
3454 view->show = show_log_view;
3455 view->input = input_log_view;
3456 view->resize = resize_log_view;
3457 view->close = close_log_view;
3458 view->search_start = search_start_log_view;
3459 view->search_next = search_next_log_view;
3461 if (s->thread_args.pack_fds == NULL) {
3462 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3463 if (err)
3464 goto done;
3466 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3467 s->thread_args.pack_fds);
3468 if (err)
3469 goto done;
3470 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3471 !s->log_branches);
3472 if (err)
3473 goto done;
3474 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3475 s->repo, NULL, NULL);
3476 if (err)
3477 goto done;
3479 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3480 if (errcode) {
3481 err = got_error_set_errno(errcode, "pthread_cond_init");
3482 goto done;
3484 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3485 if (errcode) {
3486 err = got_error_set_errno(errcode, "pthread_cond_init");
3487 goto done;
3490 s->thread_args.commits_needed = view->nlines;
3491 s->thread_args.graph = thread_graph;
3492 s->thread_args.real_commits = &s->real_commits;
3493 s->thread_args.limit_commits = &s->limit_commits;
3494 s->thread_args.in_repo_path = s->in_repo_path;
3495 s->thread_args.start_id = s->start_id;
3496 s->thread_args.repo = thread_repo;
3497 s->thread_args.log_complete = 0;
3498 s->thread_args.quit = &s->quit;
3499 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3500 s->thread_args.selected_entry = &s->selected_entry;
3501 s->thread_args.searching = &view->searching;
3502 s->thread_args.search_next_done = &view->search_next_done;
3503 s->thread_args.regex = &view->regex;
3504 s->thread_args.limiting = &s->limit_view;
3505 s->thread_args.limit_regex = &s->limit_regex;
3506 s->thread_args.limit_commits = &s->limit_commits;
3507 done:
3508 if (err)
3509 close_log_view(view);
3510 return err;
3513 static const struct got_error *
3514 show_log_view(struct tog_view *view)
3516 const struct got_error *err;
3517 struct tog_log_view_state *s = &view->state.log;
3519 if (s->thread == 0) { //NULL) {
3520 int errcode = pthread_create(&s->thread, NULL, log_thread,
3521 &s->thread_args);
3522 if (errcode)
3523 return got_error_set_errno(errcode, "pthread_create");
3524 if (s->thread_args.commits_needed > 0) {
3525 err = trigger_log_thread(view, 1);
3526 if (err)
3527 return err;
3531 return draw_commits(view);
3534 static void
3535 log_move_cursor_up(struct tog_view *view, int page, int home)
3537 struct tog_log_view_state *s = &view->state.log;
3539 if (s->first_displayed_entry == NULL)
3540 return;
3541 if (s->selected_entry->idx == 0)
3542 view->count = 0;
3544 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3545 || home)
3546 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3548 if (!page && !home && s->selected > 0)
3549 --s->selected;
3550 else
3551 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3553 select_commit(s);
3554 return;
3557 static const struct got_error *
3558 log_move_cursor_down(struct tog_view *view, int page)
3560 struct tog_log_view_state *s = &view->state.log;
3561 const struct got_error *err = NULL;
3562 int eos = view->nlines - 2;
3564 if (s->first_displayed_entry == NULL)
3565 return NULL;
3567 if (s->thread_args.log_complete &&
3568 s->selected_entry->idx >= s->commits->ncommits - 1)
3569 return NULL;
3571 if (view_is_hsplit_top(view))
3572 --eos; /* border consumes the last line */
3574 if (!page) {
3575 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3576 ++s->selected;
3577 else
3578 err = log_scroll_down(view, 1);
3579 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3580 struct commit_queue_entry *entry;
3581 int n;
3583 s->selected = 0;
3584 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3585 s->last_displayed_entry = entry;
3586 for (n = 0; n <= eos; n++) {
3587 if (entry == NULL)
3588 break;
3589 s->first_displayed_entry = entry;
3590 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3592 if (n > 0)
3593 s->selected = n - 1;
3594 } else {
3595 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3596 s->thread_args.log_complete)
3597 s->selected += MIN(page,
3598 s->commits->ncommits - s->selected_entry->idx - 1);
3599 else
3600 err = log_scroll_down(view, page);
3602 if (err)
3603 return err;
3606 * We might necessarily overshoot in horizontal
3607 * splits; if so, select the last displayed commit.
3609 if (s->first_displayed_entry && s->last_displayed_entry) {
3610 s->selected = MIN(s->selected,
3611 s->last_displayed_entry->idx -
3612 s->first_displayed_entry->idx);
3615 select_commit(s);
3617 if (s->thread_args.log_complete &&
3618 s->selected_entry->idx == s->commits->ncommits - 1)
3619 view->count = 0;
3621 return NULL;
3624 static void
3625 view_get_split(struct tog_view *view, int *y, int *x)
3627 *x = 0;
3628 *y = 0;
3630 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3631 if (view->child && view->child->resized_y)
3632 *y = view->child->resized_y;
3633 else if (view->resized_y)
3634 *y = view->resized_y;
3635 else
3636 *y = view_split_begin_y(view->lines);
3637 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3638 if (view->child && view->child->resized_x)
3639 *x = view->child->resized_x;
3640 else if (view->resized_x)
3641 *x = view->resized_x;
3642 else
3643 *x = view_split_begin_x(view->begin_x);
3647 /* Split view horizontally at y and offset view->state->selected line. */
3648 static const struct got_error *
3649 view_init_hsplit(struct tog_view *view, int y)
3651 const struct got_error *err = NULL;
3653 view->nlines = y;
3654 view->ncols = COLS;
3655 err = view_resize(view);
3656 if (err)
3657 return err;
3659 err = offset_selection_down(view);
3661 return err;
3664 static const struct got_error *
3665 log_goto_line(struct tog_view *view, int nlines)
3667 const struct got_error *err = NULL;
3668 struct tog_log_view_state *s = &view->state.log;
3669 int g, idx = s->selected_entry->idx;
3671 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3672 return NULL;
3674 g = view->gline;
3675 view->gline = 0;
3677 if (g >= s->first_displayed_entry->idx + 1 &&
3678 g <= s->last_displayed_entry->idx + 1 &&
3679 g - s->first_displayed_entry->idx - 1 < nlines) {
3680 s->selected = g - s->first_displayed_entry->idx - 1;
3681 select_commit(s);
3682 return NULL;
3685 if (idx + 1 < g) {
3686 err = log_move_cursor_down(view, g - idx - 1);
3687 if (!err && g > s->selected_entry->idx + 1)
3688 err = log_move_cursor_down(view,
3689 g - s->first_displayed_entry->idx - 1);
3690 if (err)
3691 return err;
3692 } else if (idx + 1 > g)
3693 log_move_cursor_up(view, idx - g + 1, 0);
3695 if (g < nlines && s->first_displayed_entry->idx == 0)
3696 s->selected = g - 1;
3698 select_commit(s);
3699 return NULL;
3703 static void
3704 horizontal_scroll_input(struct tog_view *view, int ch)
3707 switch (ch) {
3708 case KEY_LEFT:
3709 case 'h':
3710 view->x -= MIN(view->x, 2);
3711 if (view->x <= 0)
3712 view->count = 0;
3713 break;
3714 case KEY_RIGHT:
3715 case 'l':
3716 if (view->x + view->ncols / 2 < view->maxx)
3717 view->x += 2;
3718 else
3719 view->count = 0;
3720 break;
3721 case '0':
3722 view->x = 0;
3723 break;
3724 case '$':
3725 view->x = MAX(view->maxx - view->ncols / 2, 0);
3726 view->count = 0;
3727 break;
3728 default:
3729 break;
3733 static const struct got_error *
3734 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3736 const struct got_error *err = NULL;
3737 struct tog_log_view_state *s = &view->state.log;
3738 int eos, nscroll;
3740 if (s->thread_args.load_all) {
3741 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3742 s->thread_args.load_all = 0;
3743 else if (s->thread_args.log_complete) {
3744 err = log_move_cursor_down(view, s->commits->ncommits);
3745 s->thread_args.load_all = 0;
3747 if (err)
3748 return err;
3751 eos = nscroll = view->nlines - 1;
3752 if (view_is_hsplit_top(view))
3753 --eos; /* border */
3755 if (view->gline)
3756 return log_goto_line(view, eos);
3758 switch (ch) {
3759 case '&':
3760 err = limit_log_view(view);
3761 break;
3762 case 'q':
3763 s->quit = 1;
3764 break;
3765 case '0':
3766 case '$':
3767 case KEY_RIGHT:
3768 case 'l':
3769 case KEY_LEFT:
3770 case 'h':
3771 horizontal_scroll_input(view, ch);
3772 break;
3773 case 'k':
3774 case KEY_UP:
3775 case '<':
3776 case ',':
3777 case CTRL('p'):
3778 log_move_cursor_up(view, 0, 0);
3779 break;
3780 case 'g':
3781 case '=':
3782 case KEY_HOME:
3783 log_move_cursor_up(view, 0, 1);
3784 view->count = 0;
3785 break;
3786 case CTRL('u'):
3787 case 'u':
3788 nscroll /= 2;
3789 /* FALL THROUGH */
3790 case KEY_PPAGE:
3791 case CTRL('b'):
3792 case 'b':
3793 log_move_cursor_up(view, nscroll, 0);
3794 break;
3795 case 'j':
3796 case KEY_DOWN:
3797 case '>':
3798 case '.':
3799 case CTRL('n'):
3800 err = log_move_cursor_down(view, 0);
3801 break;
3802 case '@':
3803 s->use_committer = !s->use_committer;
3804 view->action = s->use_committer ?
3805 "show committer" : "show commit author";
3806 break;
3807 case 'G':
3808 case '*':
3809 case KEY_END: {
3810 /* We don't know yet how many commits, so we're forced to
3811 * traverse them all. */
3812 view->count = 0;
3813 s->thread_args.load_all = 1;
3814 if (!s->thread_args.log_complete)
3815 return trigger_log_thread(view, 0);
3816 err = log_move_cursor_down(view, s->commits->ncommits);
3817 s->thread_args.load_all = 0;
3818 break;
3820 case CTRL('d'):
3821 case 'd':
3822 nscroll /= 2;
3823 /* FALL THROUGH */
3824 case KEY_NPAGE:
3825 case CTRL('f'):
3826 case 'f':
3827 case ' ':
3828 err = log_move_cursor_down(view, nscroll);
3829 break;
3830 case KEY_RESIZE:
3831 if (s->selected > view->nlines - 2)
3832 s->selected = view->nlines - 2;
3833 if (s->selected > s->commits->ncommits - 1)
3834 s->selected = s->commits->ncommits - 1;
3835 select_commit(s);
3836 if (s->commits->ncommits < view->nlines - 1 &&
3837 !s->thread_args.log_complete) {
3838 s->thread_args.commits_needed += (view->nlines - 1) -
3839 s->commits->ncommits;
3840 err = trigger_log_thread(view, 1);
3842 break;
3843 case KEY_ENTER:
3844 case '\r':
3845 view->count = 0;
3846 if (s->selected_entry == NULL)
3847 break;
3848 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3849 break;
3850 case 'T':
3851 view->count = 0;
3852 if (s->selected_entry == NULL)
3853 break;
3854 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3855 break;
3856 case KEY_BACKSPACE:
3857 case CTRL('l'):
3858 case 'B':
3859 view->count = 0;
3860 if (ch == KEY_BACKSPACE &&
3861 got_path_is_root_dir(s->in_repo_path))
3862 break;
3863 err = stop_log_thread(s);
3864 if (err)
3865 return err;
3866 if (ch == KEY_BACKSPACE) {
3867 char *parent_path;
3868 err = got_path_dirname(&parent_path, s->in_repo_path);
3869 if (err)
3870 return err;
3871 free(s->in_repo_path);
3872 s->in_repo_path = parent_path;
3873 s->thread_args.in_repo_path = s->in_repo_path;
3874 } else if (ch == CTRL('l')) {
3875 struct got_object_id *start_id;
3876 err = got_repo_match_object_id(&start_id, NULL,
3877 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3878 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3879 if (err) {
3880 if (s->head_ref_name == NULL ||
3881 err->code != GOT_ERR_NOT_REF)
3882 return err;
3883 /* Try to cope with deleted references. */
3884 free(s->head_ref_name);
3885 s->head_ref_name = NULL;
3886 err = got_repo_match_object_id(&start_id,
3887 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
3888 &tog_refs, s->repo);
3889 if (err)
3890 return err;
3892 free(s->start_id);
3893 s->start_id = start_id;
3894 s->thread_args.start_id = s->start_id;
3895 } else /* 'B' */
3896 s->log_branches = !s->log_branches;
3898 if (s->thread_args.pack_fds == NULL) {
3899 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3900 if (err)
3901 return err;
3903 err = got_repo_open(&s->thread_args.repo,
3904 got_repo_get_path(s->repo), NULL,
3905 s->thread_args.pack_fds);
3906 if (err)
3907 return err;
3908 tog_free_refs();
3909 err = tog_load_refs(s->repo, 0);
3910 if (err)
3911 return err;
3912 err = got_commit_graph_open(&s->thread_args.graph,
3913 s->in_repo_path, !s->log_branches);
3914 if (err)
3915 return err;
3916 err = got_commit_graph_iter_start(s->thread_args.graph,
3917 s->start_id, s->repo, NULL, NULL);
3918 if (err)
3919 return err;
3920 free_commits(&s->real_commits);
3921 free_commits(&s->limit_commits);
3922 s->first_displayed_entry = NULL;
3923 s->last_displayed_entry = NULL;
3924 s->selected_entry = NULL;
3925 s->selected = 0;
3926 s->thread_args.log_complete = 0;
3927 s->quit = 0;
3928 s->thread_args.commits_needed = view->lines;
3929 s->matched_entry = NULL;
3930 s->search_entry = NULL;
3931 view->offset = 0;
3932 break;
3933 case 'R':
3934 view->count = 0;
3935 err = view_request_new(new_view, view, TOG_VIEW_REF);
3936 break;
3937 default:
3938 view->count = 0;
3939 break;
3942 return err;
3945 static const struct got_error *
3946 apply_unveil(const char *repo_path, const char *worktree_path)
3948 const struct got_error *error;
3950 #ifdef PROFILE
3951 if (unveil("gmon.out", "rwc") != 0)
3952 return got_error_from_errno2("unveil", "gmon.out");
3953 #endif
3954 if (repo_path && unveil(repo_path, "r") != 0)
3955 return got_error_from_errno2("unveil", repo_path);
3957 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3958 return got_error_from_errno2("unveil", worktree_path);
3960 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3961 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3963 error = got_privsep_unveil_exec_helpers();
3964 if (error != NULL)
3965 return error;
3967 if (unveil(NULL, NULL) != 0)
3968 return got_error_from_errno("unveil");
3970 return NULL;
3973 static void
3974 init_curses(void)
3977 * Override default signal handlers before starting ncurses.
3978 * This should prevent ncurses from installing its own
3979 * broken cleanup() signal handler.
3981 signal(SIGWINCH, tog_sigwinch);
3982 signal(SIGPIPE, tog_sigpipe);
3983 signal(SIGCONT, tog_sigcont);
3984 signal(SIGINT, tog_sigint);
3985 signal(SIGTERM, tog_sigterm);
3987 initscr();
3988 cbreak();
3989 halfdelay(1); /* Do fast refresh while initial view is loading. */
3990 noecho();
3991 nonl();
3992 intrflush(stdscr, FALSE);
3993 keypad(stdscr, TRUE);
3994 curs_set(0);
3995 if (getenv("TOG_COLORS") != NULL) {
3996 start_color();
3997 use_default_colors();
4001 static const struct got_error *
4002 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4003 struct got_repository *repo, struct got_worktree *worktree)
4005 const struct got_error *err = NULL;
4007 if (argc == 0) {
4008 *in_repo_path = strdup("/");
4009 if (*in_repo_path == NULL)
4010 return got_error_from_errno("strdup");
4011 return NULL;
4014 if (worktree) {
4015 const char *prefix = got_worktree_get_path_prefix(worktree);
4016 char *p;
4018 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4019 if (err)
4020 return err;
4021 if (asprintf(in_repo_path, "%s%s%s", prefix,
4022 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4023 p) == -1) {
4024 err = got_error_from_errno("asprintf");
4025 *in_repo_path = NULL;
4027 free(p);
4028 } else
4029 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4031 return err;
4034 static const struct got_error *
4035 cmd_log(int argc, char *argv[])
4037 const struct got_error *error;
4038 struct got_repository *repo = NULL;
4039 struct got_worktree *worktree = NULL;
4040 struct got_object_id *start_id = NULL;
4041 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4042 char *start_commit = NULL, *label = NULL;
4043 struct got_reference *ref = NULL;
4044 const char *head_ref_name = NULL;
4045 int ch, log_branches = 0;
4046 struct tog_view *view;
4047 int *pack_fds = NULL;
4049 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4050 switch (ch) {
4051 case 'b':
4052 log_branches = 1;
4053 break;
4054 case 'c':
4055 start_commit = optarg;
4056 break;
4057 case 'r':
4058 repo_path = realpath(optarg, NULL);
4059 if (repo_path == NULL)
4060 return got_error_from_errno2("realpath",
4061 optarg);
4062 break;
4063 default:
4064 usage_log();
4065 /* NOTREACHED */
4069 argc -= optind;
4070 argv += optind;
4072 if (argc > 1)
4073 usage_log();
4075 error = got_repo_pack_fds_open(&pack_fds);
4076 if (error != NULL)
4077 goto done;
4079 if (repo_path == NULL) {
4080 cwd = getcwd(NULL, 0);
4081 if (cwd == NULL)
4082 return got_error_from_errno("getcwd");
4083 error = got_worktree_open(&worktree, cwd);
4084 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4085 goto done;
4086 if (worktree)
4087 repo_path =
4088 strdup(got_worktree_get_repo_path(worktree));
4089 else
4090 repo_path = strdup(cwd);
4091 if (repo_path == NULL) {
4092 error = got_error_from_errno("strdup");
4093 goto done;
4097 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4098 if (error != NULL)
4099 goto done;
4101 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4102 repo, worktree);
4103 if (error)
4104 goto done;
4106 init_curses();
4108 error = apply_unveil(got_repo_get_path(repo),
4109 worktree ? got_worktree_get_root_path(worktree) : NULL);
4110 if (error)
4111 goto done;
4113 /* already loaded by tog_log_with_path()? */
4114 if (TAILQ_EMPTY(&tog_refs)) {
4115 error = tog_load_refs(repo, 0);
4116 if (error)
4117 goto done;
4120 if (start_commit == NULL) {
4121 error = got_repo_match_object_id(&start_id, &label,
4122 worktree ? got_worktree_get_head_ref_name(worktree) :
4123 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4124 if (error)
4125 goto done;
4126 head_ref_name = label;
4127 } else {
4128 error = got_ref_open(&ref, repo, start_commit, 0);
4129 if (error == NULL)
4130 head_ref_name = got_ref_get_name(ref);
4131 else if (error->code != GOT_ERR_NOT_REF)
4132 goto done;
4133 error = got_repo_match_object_id(&start_id, NULL,
4134 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4135 if (error)
4136 goto done;
4139 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4140 if (view == NULL) {
4141 error = got_error_from_errno("view_open");
4142 goto done;
4144 error = open_log_view(view, start_id, repo, head_ref_name,
4145 in_repo_path, log_branches);
4146 if (error)
4147 goto done;
4148 if (worktree) {
4149 /* Release work tree lock. */
4150 got_worktree_close(worktree);
4151 worktree = NULL;
4153 error = view_loop(view);
4154 done:
4155 free(in_repo_path);
4156 free(repo_path);
4157 free(cwd);
4158 free(start_id);
4159 free(label);
4160 if (ref)
4161 got_ref_close(ref);
4162 if (repo) {
4163 const struct got_error *close_err = got_repo_close(repo);
4164 if (error == NULL)
4165 error = close_err;
4167 if (worktree)
4168 got_worktree_close(worktree);
4169 if (pack_fds) {
4170 const struct got_error *pack_err =
4171 got_repo_pack_fds_close(pack_fds);
4172 if (error == NULL)
4173 error = pack_err;
4175 tog_free_refs();
4176 return error;
4179 __dead static void
4180 usage_diff(void)
4182 endwin();
4183 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4184 "object1 object2\n", getprogname());
4185 exit(1);
4188 static int
4189 match_line(const char *line, regex_t *regex, size_t nmatch,
4190 regmatch_t *regmatch)
4192 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4195 static struct tog_color *
4196 match_color(struct tog_colors *colors, const char *line)
4198 struct tog_color *tc = NULL;
4200 STAILQ_FOREACH(tc, colors, entry) {
4201 if (match_line(line, &tc->regex, 0, NULL))
4202 return tc;
4205 return NULL;
4208 static const struct got_error *
4209 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4210 WINDOW *window, int skipcol, regmatch_t *regmatch)
4212 const struct got_error *err = NULL;
4213 char *exstr = NULL;
4214 wchar_t *wline = NULL;
4215 int rme, rms, n, width, scrollx;
4216 int width0 = 0, width1 = 0, width2 = 0;
4217 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4219 *wtotal = 0;
4221 rms = regmatch->rm_so;
4222 rme = regmatch->rm_eo;
4224 err = expand_tab(&exstr, line);
4225 if (err)
4226 return err;
4228 /* Split the line into 3 segments, according to match offsets. */
4229 seg0 = strndup(exstr, rms);
4230 if (seg0 == NULL) {
4231 err = got_error_from_errno("strndup");
4232 goto done;
4234 seg1 = strndup(exstr + rms, rme - rms);
4235 if (seg1 == NULL) {
4236 err = got_error_from_errno("strndup");
4237 goto done;
4239 seg2 = strdup(exstr + rme);
4240 if (seg2 == NULL) {
4241 err = got_error_from_errno("strndup");
4242 goto done;
4245 /* draw up to matched token if we haven't scrolled past it */
4246 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4247 col_tab_align, 1);
4248 if (err)
4249 goto done;
4250 n = MAX(width0 - skipcol, 0);
4251 if (n) {
4252 free(wline);
4253 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4254 wlimit, col_tab_align, 1);
4255 if (err)
4256 goto done;
4257 waddwstr(window, &wline[scrollx]);
4258 wlimit -= width;
4259 *wtotal += width;
4262 if (wlimit > 0) {
4263 int i = 0, w = 0;
4264 size_t wlen;
4266 free(wline);
4267 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4268 col_tab_align, 1);
4269 if (err)
4270 goto done;
4271 wlen = wcslen(wline);
4272 while (i < wlen) {
4273 width = wcwidth(wline[i]);
4274 if (width == -1) {
4275 /* should not happen, tabs are expanded */
4276 err = got_error(GOT_ERR_RANGE);
4277 goto done;
4279 if (width0 + w + width > skipcol)
4280 break;
4281 w += width;
4282 i++;
4284 /* draw (visible part of) matched token (if scrolled into it) */
4285 if (width1 - w > 0) {
4286 wattron(window, A_STANDOUT);
4287 waddwstr(window, &wline[i]);
4288 wattroff(window, A_STANDOUT);
4289 wlimit -= (width1 - w);
4290 *wtotal += (width1 - w);
4294 if (wlimit > 0) { /* draw rest of line */
4295 free(wline);
4296 if (skipcol > width0 + width1) {
4297 err = format_line(&wline, &width2, &scrollx, seg2,
4298 skipcol - (width0 + width1), wlimit,
4299 col_tab_align, 1);
4300 if (err)
4301 goto done;
4302 waddwstr(window, &wline[scrollx]);
4303 } else {
4304 err = format_line(&wline, &width2, NULL, seg2, 0,
4305 wlimit, col_tab_align, 1);
4306 if (err)
4307 goto done;
4308 waddwstr(window, wline);
4310 *wtotal += width2;
4312 done:
4313 free(wline);
4314 free(exstr);
4315 free(seg0);
4316 free(seg1);
4317 free(seg2);
4318 return err;
4321 static int
4322 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4324 FILE *f = NULL;
4325 int *eof, *first, *selected;
4327 if (view->type == TOG_VIEW_DIFF) {
4328 struct tog_diff_view_state *s = &view->state.diff;
4330 first = &s->first_displayed_line;
4331 selected = first;
4332 eof = &s->eof;
4333 f = s->f;
4334 } else if (view->type == TOG_VIEW_HELP) {
4335 struct tog_help_view_state *s = &view->state.help;
4337 first = &s->first_displayed_line;
4338 selected = first;
4339 eof = &s->eof;
4340 f = s->f;
4341 } else if (view->type == TOG_VIEW_BLAME) {
4342 struct tog_blame_view_state *s = &view->state.blame;
4344 first = &s->first_displayed_line;
4345 selected = &s->selected_line;
4346 eof = &s->eof;
4347 f = s->blame.f;
4348 } else
4349 return 0;
4351 /* Center gline in the middle of the page like vi(1). */
4352 if (*lineno < view->gline - (view->nlines - 3) / 2)
4353 return 0;
4354 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4355 rewind(f);
4356 *eof = 0;
4357 *first = 1;
4358 *lineno = 0;
4359 *nprinted = 0;
4360 return 0;
4363 *selected = view->gline <= (view->nlines - 3) / 2 ?
4364 view->gline : (view->nlines - 3) / 2 + 1;
4365 view->gline = 0;
4367 return 1;
4370 static const struct got_error *
4371 draw_file(struct tog_view *view, const char *header)
4373 struct tog_diff_view_state *s = &view->state.diff;
4374 regmatch_t *regmatch = &view->regmatch;
4375 const struct got_error *err;
4376 int nprinted = 0;
4377 char *line;
4378 size_t linesize = 0;
4379 ssize_t linelen;
4380 wchar_t *wline;
4381 int width;
4382 int max_lines = view->nlines;
4383 int nlines = s->nlines;
4384 off_t line_offset;
4386 s->lineno = s->first_displayed_line - 1;
4387 line_offset = s->lines[s->first_displayed_line - 1].offset;
4388 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4389 return got_error_from_errno("fseek");
4391 werase(view->window);
4393 if (view->gline > s->nlines - 1)
4394 view->gline = s->nlines - 1;
4396 if (header) {
4397 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4398 1 : view->gline - (view->nlines - 3) / 2 :
4399 s->lineno + s->selected_line;
4401 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4402 return got_error_from_errno("asprintf");
4403 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4404 0, 0);
4405 free(line);
4406 if (err)
4407 return err;
4409 if (view_needs_focus_indication(view))
4410 wstandout(view->window);
4411 waddwstr(view->window, wline);
4412 free(wline);
4413 wline = NULL;
4414 while (width++ < view->ncols)
4415 waddch(view->window, ' ');
4416 if (view_needs_focus_indication(view))
4417 wstandend(view->window);
4419 if (max_lines <= 1)
4420 return NULL;
4421 max_lines--;
4424 s->eof = 0;
4425 view->maxx = 0;
4426 line = NULL;
4427 while (max_lines > 0 && nprinted < max_lines) {
4428 enum got_diff_line_type linetype;
4429 attr_t attr = 0;
4431 linelen = getline(&line, &linesize, s->f);
4432 if (linelen == -1) {
4433 if (feof(s->f)) {
4434 s->eof = 1;
4435 break;
4437 free(line);
4438 return got_ferror(s->f, GOT_ERR_IO);
4441 if (++s->lineno < s->first_displayed_line)
4442 continue;
4443 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4444 continue;
4445 if (s->lineno == view->hiline)
4446 attr = A_STANDOUT;
4448 /* Set view->maxx based on full line length. */
4449 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4450 view->x ? 1 : 0);
4451 if (err) {
4452 free(line);
4453 return err;
4455 view->maxx = MAX(view->maxx, width);
4456 free(wline);
4457 wline = NULL;
4459 linetype = s->lines[s->lineno].type;
4460 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4461 linetype < GOT_DIFF_LINE_CONTEXT)
4462 attr |= COLOR_PAIR(linetype);
4463 if (attr)
4464 wattron(view->window, attr);
4465 if (s->first_displayed_line + nprinted == s->matched_line &&
4466 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4467 err = add_matched_line(&width, line, view->ncols, 0,
4468 view->window, view->x, regmatch);
4469 if (err) {
4470 free(line);
4471 return err;
4473 } else {
4474 int skip;
4475 err = format_line(&wline, &width, &skip, line,
4476 view->x, view->ncols, 0, view->x ? 1 : 0);
4477 if (err) {
4478 free(line);
4479 return err;
4481 waddwstr(view->window, &wline[skip]);
4482 free(wline);
4483 wline = NULL;
4485 if (s->lineno == view->hiline) {
4486 /* highlight full gline length */
4487 while (width++ < view->ncols)
4488 waddch(view->window, ' ');
4489 } else {
4490 if (width <= view->ncols - 1)
4491 waddch(view->window, '\n');
4493 if (attr)
4494 wattroff(view->window, attr);
4495 if (++nprinted == 1)
4496 s->first_displayed_line = s->lineno;
4498 free(line);
4499 if (nprinted >= 1)
4500 s->last_displayed_line = s->first_displayed_line +
4501 (nprinted - 1);
4502 else
4503 s->last_displayed_line = s->first_displayed_line;
4505 view_border(view);
4507 if (s->eof) {
4508 while (nprinted < view->nlines) {
4509 waddch(view->window, '\n');
4510 nprinted++;
4513 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4514 view->ncols, 0, 0);
4515 if (err) {
4516 return err;
4519 wstandout(view->window);
4520 waddwstr(view->window, wline);
4521 free(wline);
4522 wline = NULL;
4523 wstandend(view->window);
4526 return NULL;
4529 static char *
4530 get_datestr(time_t *time, char *datebuf)
4532 struct tm mytm, *tm;
4533 char *p, *s;
4535 tm = gmtime_r(time, &mytm);
4536 if (tm == NULL)
4537 return NULL;
4538 s = asctime_r(tm, datebuf);
4539 if (s == NULL)
4540 return NULL;
4541 p = strchr(s, '\n');
4542 if (p)
4543 *p = '\0';
4544 return s;
4547 static const struct got_error *
4548 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4549 off_t off, uint8_t type)
4551 struct got_diff_line *p;
4553 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4554 if (p == NULL)
4555 return got_error_from_errno("reallocarray");
4556 *lines = p;
4557 (*lines)[*nlines].offset = off;
4558 (*lines)[*nlines].type = type;
4559 (*nlines)++;
4561 return NULL;
4564 static const struct got_error *
4565 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4566 struct got_diff_line *s_lines, size_t s_nlines)
4568 struct got_diff_line *p;
4569 char buf[BUFSIZ];
4570 size_t i, r;
4572 if (fseeko(src, 0L, SEEK_SET) == -1)
4573 return got_error_from_errno("fseeko");
4575 for (;;) {
4576 r = fread(buf, 1, sizeof(buf), src);
4577 if (r == 0) {
4578 if (ferror(src))
4579 return got_error_from_errno("fread");
4580 if (feof(src))
4581 break;
4583 if (fwrite(buf, 1, r, dst) != r)
4584 return got_ferror(dst, GOT_ERR_IO);
4587 if (s_nlines == 0 && *d_nlines == 0)
4588 return NULL;
4591 * If commit info was in dst, increment line offsets
4592 * of the appended diff content, but skip s_lines[0]
4593 * because offset zero is already in *d_lines.
4595 if (*d_nlines > 0) {
4596 for (i = 1; i < s_nlines; ++i)
4597 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4599 if (s_nlines > 0) {
4600 --s_nlines;
4601 ++s_lines;
4605 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4606 if (p == NULL) {
4607 /* d_lines is freed in close_diff_view() */
4608 return got_error_from_errno("reallocarray");
4611 *d_lines = p;
4613 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4614 *d_nlines += s_nlines;
4616 return NULL;
4619 static const struct got_error *
4620 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4621 struct got_object_id *commit_id, struct got_reflist_head *refs,
4622 struct got_repository *repo, int ignore_ws, int force_text_diff,
4623 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4625 const struct got_error *err = NULL;
4626 char datebuf[26], *datestr;
4627 struct got_commit_object *commit;
4628 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4629 time_t committer_time;
4630 const char *author, *committer;
4631 char *refs_str = NULL;
4632 struct got_pathlist_entry *pe;
4633 off_t outoff = 0;
4634 int n;
4636 if (refs) {
4637 err = build_refs_str(&refs_str, refs, commit_id, repo);
4638 if (err)
4639 return err;
4642 err = got_object_open_as_commit(&commit, repo, commit_id);
4643 if (err)
4644 return err;
4646 err = got_object_id_str(&id_str, commit_id);
4647 if (err) {
4648 err = got_error_from_errno("got_object_id_str");
4649 goto done;
4652 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4653 if (err)
4654 goto done;
4656 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4657 refs_str ? refs_str : "", refs_str ? ")" : "");
4658 if (n < 0) {
4659 err = got_error_from_errno("fprintf");
4660 goto done;
4662 outoff += n;
4663 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4664 if (err)
4665 goto done;
4667 n = fprintf(outfile, "from: %s\n",
4668 got_object_commit_get_author(commit));
4669 if (n < 0) {
4670 err = got_error_from_errno("fprintf");
4671 goto done;
4673 outoff += n;
4674 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4675 if (err)
4676 goto done;
4678 author = got_object_commit_get_author(commit);
4679 committer = got_object_commit_get_committer(commit);
4680 if (strcmp(author, committer) != 0) {
4681 n = fprintf(outfile, "via: %s\n", committer);
4682 if (n < 0) {
4683 err = got_error_from_errno("fprintf");
4684 goto done;
4686 outoff += n;
4687 err = add_line_metadata(lines, nlines, outoff,
4688 GOT_DIFF_LINE_AUTHOR);
4689 if (err)
4690 goto done;
4692 committer_time = got_object_commit_get_committer_time(commit);
4693 datestr = get_datestr(&committer_time, datebuf);
4694 if (datestr) {
4695 n = fprintf(outfile, "date: %s UTC\n", datestr);
4696 if (n < 0) {
4697 err = got_error_from_errno("fprintf");
4698 goto done;
4700 outoff += n;
4701 err = add_line_metadata(lines, nlines, outoff,
4702 GOT_DIFF_LINE_DATE);
4703 if (err)
4704 goto done;
4706 if (got_object_commit_get_nparents(commit) > 1) {
4707 const struct got_object_id_queue *parent_ids;
4708 struct got_object_qid *qid;
4709 int pn = 1;
4710 parent_ids = got_object_commit_get_parent_ids(commit);
4711 STAILQ_FOREACH(qid, parent_ids, entry) {
4712 err = got_object_id_str(&id_str, &qid->id);
4713 if (err)
4714 goto done;
4715 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4716 if (n < 0) {
4717 err = got_error_from_errno("fprintf");
4718 goto done;
4720 outoff += n;
4721 err = add_line_metadata(lines, nlines, outoff,
4722 GOT_DIFF_LINE_META);
4723 if (err)
4724 goto done;
4725 free(id_str);
4726 id_str = NULL;
4730 err = got_object_commit_get_logmsg(&logmsg, commit);
4731 if (err)
4732 goto done;
4733 s = logmsg;
4734 while ((line = strsep(&s, "\n")) != NULL) {
4735 n = fprintf(outfile, "%s\n", line);
4736 if (n < 0) {
4737 err = got_error_from_errno("fprintf");
4738 goto done;
4740 outoff += n;
4741 err = add_line_metadata(lines, nlines, outoff,
4742 GOT_DIFF_LINE_LOGMSG);
4743 if (err)
4744 goto done;
4747 TAILQ_FOREACH(pe, dsa->paths, entry) {
4748 struct got_diff_changed_path *cp = pe->data;
4749 int pad = dsa->max_path_len - pe->path_len + 1;
4751 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4752 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4753 dsa->rm_cols + 1, cp->rm);
4754 if (n < 0) {
4755 err = got_error_from_errno("fprintf");
4756 goto done;
4758 outoff += n;
4759 err = add_line_metadata(lines, nlines, outoff,
4760 GOT_DIFF_LINE_CHANGES);
4761 if (err)
4762 goto done;
4765 fputc('\n', outfile);
4766 outoff++;
4767 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4768 if (err)
4769 goto done;
4771 n = fprintf(outfile,
4772 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4773 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4774 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4775 if (n < 0) {
4776 err = got_error_from_errno("fprintf");
4777 goto done;
4779 outoff += n;
4780 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4781 if (err)
4782 goto done;
4784 fputc('\n', outfile);
4785 outoff++;
4786 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4787 done:
4788 free(id_str);
4789 free(logmsg);
4790 free(refs_str);
4791 got_object_commit_close(commit);
4792 if (err) {
4793 free(*lines);
4794 *lines = NULL;
4795 *nlines = 0;
4797 return err;
4800 static const struct got_error *
4801 create_diff(struct tog_diff_view_state *s)
4803 const struct got_error *err = NULL;
4804 FILE *f = NULL, *tmp_diff_file = NULL;
4805 int obj_type;
4806 struct got_diff_line *lines = NULL;
4807 struct got_pathlist_head changed_paths;
4809 TAILQ_INIT(&changed_paths);
4811 free(s->lines);
4812 s->lines = malloc(sizeof(*s->lines));
4813 if (s->lines == NULL)
4814 return got_error_from_errno("malloc");
4815 s->nlines = 0;
4817 f = got_opentemp();
4818 if (f == NULL) {
4819 err = got_error_from_errno("got_opentemp");
4820 goto done;
4822 tmp_diff_file = got_opentemp();
4823 if (tmp_diff_file == NULL) {
4824 err = got_error_from_errno("got_opentemp");
4825 goto done;
4827 if (s->f && fclose(s->f) == EOF) {
4828 err = got_error_from_errno("fclose");
4829 goto done;
4831 s->f = f;
4833 if (s->id1)
4834 err = got_object_get_type(&obj_type, s->repo, s->id1);
4835 else
4836 err = got_object_get_type(&obj_type, s->repo, s->id2);
4837 if (err)
4838 goto done;
4840 switch (obj_type) {
4841 case GOT_OBJ_TYPE_BLOB:
4842 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4843 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4844 s->label1, s->label2, tog_diff_algo, s->diff_context,
4845 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
4846 s->f);
4847 break;
4848 case GOT_OBJ_TYPE_TREE:
4849 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4850 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4851 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4852 s->force_text_diff, NULL, s->repo, s->f);
4853 break;
4854 case GOT_OBJ_TYPE_COMMIT: {
4855 const struct got_object_id_queue *parent_ids;
4856 struct got_object_qid *pid;
4857 struct got_commit_object *commit2;
4858 struct got_reflist_head *refs;
4859 size_t nlines = 0;
4860 struct got_diffstat_cb_arg dsa = {
4861 0, 0, 0, 0, 0, 0,
4862 &changed_paths,
4863 s->ignore_whitespace,
4864 s->force_text_diff,
4865 tog_diff_algo
4868 lines = malloc(sizeof(*lines));
4869 if (lines == NULL) {
4870 err = got_error_from_errno("malloc");
4871 goto done;
4874 /* build diff first in tmp file then append to commit info */
4875 err = got_diff_objects_as_commits(&lines, &nlines,
4876 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4877 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4878 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
4879 if (err)
4880 break;
4882 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4883 if (err)
4884 goto done;
4885 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4886 /* Show commit info if we're diffing to a parent/root commit. */
4887 if (s->id1 == NULL) {
4888 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4889 refs, s->repo, s->ignore_whitespace,
4890 s->force_text_diff, &dsa, s->f);
4891 if (err)
4892 goto done;
4893 } else {
4894 parent_ids = got_object_commit_get_parent_ids(commit2);
4895 STAILQ_FOREACH(pid, parent_ids, entry) {
4896 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4897 err = write_commit_info(&s->lines,
4898 &s->nlines, s->id2, refs, s->repo,
4899 s->ignore_whitespace,
4900 s->force_text_diff, &dsa, s->f);
4901 if (err)
4902 goto done;
4903 break;
4907 got_object_commit_close(commit2);
4909 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
4910 lines, nlines);
4911 break;
4913 default:
4914 err = got_error(GOT_ERR_OBJ_TYPE);
4915 break;
4917 done:
4918 free(lines);
4919 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4920 if (s->f && fflush(s->f) != 0 && err == NULL)
4921 err = got_error_from_errno("fflush");
4922 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
4923 err = got_error_from_errno("fclose");
4924 return err;
4927 static void
4928 diff_view_indicate_progress(struct tog_view *view)
4930 mvwaddstr(view->window, 0, 0, "diffing...");
4931 update_panels();
4932 doupdate();
4935 static const struct got_error *
4936 search_start_diff_view(struct tog_view *view)
4938 struct tog_diff_view_state *s = &view->state.diff;
4940 s->matched_line = 0;
4941 return NULL;
4944 static void
4945 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4946 size_t *nlines, int **first, int **last, int **match, int **selected)
4948 struct tog_diff_view_state *s = &view->state.diff;
4950 *f = s->f;
4951 *nlines = s->nlines;
4952 *line_offsets = NULL;
4953 *match = &s->matched_line;
4954 *first = &s->first_displayed_line;
4955 *last = &s->last_displayed_line;
4956 *selected = &s->selected_line;
4959 static const struct got_error *
4960 search_next_view_match(struct tog_view *view)
4962 const struct got_error *err = NULL;
4963 FILE *f;
4964 int lineno;
4965 char *line = NULL;
4966 size_t linesize = 0;
4967 ssize_t linelen;
4968 off_t *line_offsets;
4969 size_t nlines = 0;
4970 int *first, *last, *match, *selected;
4972 if (!view->search_setup)
4973 return got_error_msg(GOT_ERR_NOT_IMPL,
4974 "view search not supported");
4975 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4976 &match, &selected);
4978 if (!view->searching) {
4979 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4980 return NULL;
4983 if (*match) {
4984 if (view->searching == TOG_SEARCH_FORWARD)
4985 lineno = *match + 1;
4986 else
4987 lineno = *match - 1;
4988 } else
4989 lineno = *first - 1 + *selected;
4991 while (1) {
4992 off_t offset;
4994 if (lineno <= 0 || lineno > nlines) {
4995 if (*match == 0) {
4996 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4997 break;
5000 if (view->searching == TOG_SEARCH_FORWARD)
5001 lineno = 1;
5002 else
5003 lineno = nlines;
5006 offset = view->type == TOG_VIEW_DIFF ?
5007 view->state.diff.lines[lineno - 1].offset :
5008 line_offsets[lineno - 1];
5009 if (fseeko(f, offset, SEEK_SET) != 0) {
5010 free(line);
5011 return got_error_from_errno("fseeko");
5013 linelen = getline(&line, &linesize, f);
5014 if (linelen != -1) {
5015 char *exstr;
5016 err = expand_tab(&exstr, line);
5017 if (err)
5018 break;
5019 if (match_line(exstr, &view->regex, 1,
5020 &view->regmatch)) {
5021 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5022 *match = lineno;
5023 free(exstr);
5024 break;
5026 free(exstr);
5028 if (view->searching == TOG_SEARCH_FORWARD)
5029 lineno++;
5030 else
5031 lineno--;
5033 free(line);
5035 if (*match) {
5036 *first = *match;
5037 *selected = 1;
5040 return err;
5043 static const struct got_error *
5044 close_diff_view(struct tog_view *view)
5046 const struct got_error *err = NULL;
5047 struct tog_diff_view_state *s = &view->state.diff;
5049 free(s->id1);
5050 s->id1 = NULL;
5051 free(s->id2);
5052 s->id2 = NULL;
5053 if (s->f && fclose(s->f) == EOF)
5054 err = got_error_from_errno("fclose");
5055 s->f = NULL;
5056 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5057 err = got_error_from_errno("fclose");
5058 s->f1 = NULL;
5059 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5060 err = got_error_from_errno("fclose");
5061 s->f2 = NULL;
5062 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5063 err = got_error_from_errno("close");
5064 s->fd1 = -1;
5065 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5066 err = got_error_from_errno("close");
5067 s->fd2 = -1;
5068 free(s->lines);
5069 s->lines = NULL;
5070 s->nlines = 0;
5071 return err;
5074 static const struct got_error *
5075 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5076 struct got_object_id *id2, const char *label1, const char *label2,
5077 int diff_context, int ignore_whitespace, int force_text_diff,
5078 struct tog_view *parent_view, struct got_repository *repo)
5080 const struct got_error *err;
5081 struct tog_diff_view_state *s = &view->state.diff;
5083 memset(s, 0, sizeof(*s));
5084 s->fd1 = -1;
5085 s->fd2 = -1;
5087 if (id1 != NULL && id2 != NULL) {
5088 int type1, type2;
5089 err = got_object_get_type(&type1, repo, id1);
5090 if (err)
5091 return err;
5092 err = got_object_get_type(&type2, repo, id2);
5093 if (err)
5094 return err;
5096 if (type1 != type2)
5097 return got_error(GOT_ERR_OBJ_TYPE);
5099 s->first_displayed_line = 1;
5100 s->last_displayed_line = view->nlines;
5101 s->selected_line = 1;
5102 s->repo = repo;
5103 s->id1 = id1;
5104 s->id2 = id2;
5105 s->label1 = label1;
5106 s->label2 = label2;
5108 if (id1) {
5109 s->id1 = got_object_id_dup(id1);
5110 if (s->id1 == NULL)
5111 return got_error_from_errno("got_object_id_dup");
5112 } else
5113 s->id1 = NULL;
5115 s->id2 = got_object_id_dup(id2);
5116 if (s->id2 == NULL) {
5117 err = got_error_from_errno("got_object_id_dup");
5118 goto done;
5121 s->f1 = got_opentemp();
5122 if (s->f1 == NULL) {
5123 err = got_error_from_errno("got_opentemp");
5124 goto done;
5127 s->f2 = got_opentemp();
5128 if (s->f2 == NULL) {
5129 err = got_error_from_errno("got_opentemp");
5130 goto done;
5133 s->fd1 = got_opentempfd();
5134 if (s->fd1 == -1) {
5135 err = got_error_from_errno("got_opentempfd");
5136 goto done;
5139 s->fd2 = got_opentempfd();
5140 if (s->fd2 == -1) {
5141 err = got_error_from_errno("got_opentempfd");
5142 goto done;
5145 s->diff_context = diff_context;
5146 s->ignore_whitespace = ignore_whitespace;
5147 s->force_text_diff = force_text_diff;
5148 s->parent_view = parent_view;
5149 s->repo = repo;
5151 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5152 int rc;
5154 rc = init_pair(GOT_DIFF_LINE_MINUS,
5155 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5156 if (rc != ERR)
5157 rc = init_pair(GOT_DIFF_LINE_PLUS,
5158 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5159 if (rc != ERR)
5160 rc = init_pair(GOT_DIFF_LINE_HUNK,
5161 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5162 if (rc != ERR)
5163 rc = init_pair(GOT_DIFF_LINE_META,
5164 get_color_value("TOG_COLOR_DIFF_META"), -1);
5165 if (rc != ERR)
5166 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5167 get_color_value("TOG_COLOR_DIFF_META"), -1);
5168 if (rc != ERR)
5169 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5170 get_color_value("TOG_COLOR_DIFF_META"), -1);
5171 if (rc != ERR)
5172 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5173 get_color_value("TOG_COLOR_DIFF_META"), -1);
5174 if (rc != ERR)
5175 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5176 get_color_value("TOG_COLOR_AUTHOR"), -1);
5177 if (rc != ERR)
5178 rc = init_pair(GOT_DIFF_LINE_DATE,
5179 get_color_value("TOG_COLOR_DATE"), -1);
5180 if (rc == ERR) {
5181 err = got_error(GOT_ERR_RANGE);
5182 goto done;
5186 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5187 view_is_splitscreen(view))
5188 show_log_view(parent_view); /* draw border */
5189 diff_view_indicate_progress(view);
5191 err = create_diff(s);
5193 view->show = show_diff_view;
5194 view->input = input_diff_view;
5195 view->reset = reset_diff_view;
5196 view->close = close_diff_view;
5197 view->search_start = search_start_diff_view;
5198 view->search_setup = search_setup_diff_view;
5199 view->search_next = search_next_view_match;
5200 done:
5201 if (err)
5202 close_diff_view(view);
5203 return err;
5206 static const struct got_error *
5207 show_diff_view(struct tog_view *view)
5209 const struct got_error *err;
5210 struct tog_diff_view_state *s = &view->state.diff;
5211 char *id_str1 = NULL, *id_str2, *header;
5212 const char *label1, *label2;
5214 if (s->id1) {
5215 err = got_object_id_str(&id_str1, s->id1);
5216 if (err)
5217 return err;
5218 label1 = s->label1 ? s->label1 : id_str1;
5219 } else
5220 label1 = "/dev/null";
5222 err = got_object_id_str(&id_str2, s->id2);
5223 if (err)
5224 return err;
5225 label2 = s->label2 ? s->label2 : id_str2;
5227 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5228 err = got_error_from_errno("asprintf");
5229 free(id_str1);
5230 free(id_str2);
5231 return err;
5233 free(id_str1);
5234 free(id_str2);
5236 err = draw_file(view, header);
5237 free(header);
5238 return err;
5241 static const struct got_error *
5242 set_selected_commit(struct tog_diff_view_state *s,
5243 struct commit_queue_entry *entry)
5245 const struct got_error *err;
5246 const struct got_object_id_queue *parent_ids;
5247 struct got_commit_object *selected_commit;
5248 struct got_object_qid *pid;
5250 free(s->id2);
5251 s->id2 = got_object_id_dup(entry->id);
5252 if (s->id2 == NULL)
5253 return got_error_from_errno("got_object_id_dup");
5255 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5256 if (err)
5257 return err;
5258 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5259 free(s->id1);
5260 pid = STAILQ_FIRST(parent_ids);
5261 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5262 got_object_commit_close(selected_commit);
5263 return NULL;
5266 static const struct got_error *
5267 reset_diff_view(struct tog_view *view)
5269 struct tog_diff_view_state *s = &view->state.diff;
5271 view->count = 0;
5272 wclear(view->window);
5273 s->first_displayed_line = 1;
5274 s->last_displayed_line = view->nlines;
5275 s->matched_line = 0;
5276 diff_view_indicate_progress(view);
5277 return create_diff(s);
5280 static void
5281 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5283 int start, i;
5285 i = start = s->first_displayed_line - 1;
5287 while (s->lines[i].type != type) {
5288 if (i == 0)
5289 i = s->nlines - 1;
5290 if (--i == start)
5291 return; /* do nothing, requested type not in file */
5294 s->selected_line = 1;
5295 s->first_displayed_line = i;
5298 static void
5299 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5301 int start, i;
5303 i = start = s->first_displayed_line + 1;
5305 while (s->lines[i].type != type) {
5306 if (i == s->nlines - 1)
5307 i = 0;
5308 if (++i == start)
5309 return; /* do nothing, requested type not in file */
5312 s->selected_line = 1;
5313 s->first_displayed_line = i;
5316 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5317 int, int, int);
5318 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5319 int, int);
5321 static const struct got_error *
5322 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5324 const struct got_error *err = NULL;
5325 struct tog_diff_view_state *s = &view->state.diff;
5326 struct tog_log_view_state *ls;
5327 struct commit_queue_entry *old_selected_entry;
5328 char *line = NULL;
5329 size_t linesize = 0;
5330 ssize_t linelen;
5331 int i, nscroll = view->nlines - 1, up = 0;
5333 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5335 switch (ch) {
5336 case '0':
5337 case '$':
5338 case KEY_RIGHT:
5339 case 'l':
5340 case KEY_LEFT:
5341 case 'h':
5342 horizontal_scroll_input(view, ch);
5343 break;
5344 case 'a':
5345 case 'w':
5346 if (ch == 'a') {
5347 s->force_text_diff = !s->force_text_diff;
5348 view->action = s->force_text_diff ?
5349 "force ASCII text enabled" :
5350 "force ASCII text disabled";
5352 else if (ch == 'w') {
5353 s->ignore_whitespace = !s->ignore_whitespace;
5354 view->action = s->ignore_whitespace ?
5355 "ignore whitespace enabled" :
5356 "ignore whitespace disabled";
5358 err = reset_diff_view(view);
5359 break;
5360 case 'g':
5361 case KEY_HOME:
5362 s->first_displayed_line = 1;
5363 view->count = 0;
5364 break;
5365 case 'G':
5366 case KEY_END:
5367 view->count = 0;
5368 if (s->eof)
5369 break;
5371 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5372 s->eof = 1;
5373 break;
5374 case 'k':
5375 case KEY_UP:
5376 case CTRL('p'):
5377 if (s->first_displayed_line > 1)
5378 s->first_displayed_line--;
5379 else
5380 view->count = 0;
5381 break;
5382 case CTRL('u'):
5383 case 'u':
5384 nscroll /= 2;
5385 /* FALL THROUGH */
5386 case KEY_PPAGE:
5387 case CTRL('b'):
5388 case 'b':
5389 if (s->first_displayed_line == 1) {
5390 view->count = 0;
5391 break;
5393 i = 0;
5394 while (i++ < nscroll && s->first_displayed_line > 1)
5395 s->first_displayed_line--;
5396 break;
5397 case 'j':
5398 case KEY_DOWN:
5399 case CTRL('n'):
5400 if (!s->eof)
5401 s->first_displayed_line++;
5402 else
5403 view->count = 0;
5404 break;
5405 case CTRL('d'):
5406 case 'd':
5407 nscroll /= 2;
5408 /* FALL THROUGH */
5409 case KEY_NPAGE:
5410 case CTRL('f'):
5411 case 'f':
5412 case ' ':
5413 if (s->eof) {
5414 view->count = 0;
5415 break;
5417 i = 0;
5418 while (!s->eof && i++ < nscroll) {
5419 linelen = getline(&line, &linesize, s->f);
5420 s->first_displayed_line++;
5421 if (linelen == -1) {
5422 if (feof(s->f)) {
5423 s->eof = 1;
5424 } else
5425 err = got_ferror(s->f, GOT_ERR_IO);
5426 break;
5429 free(line);
5430 break;
5431 case '(':
5432 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5433 break;
5434 case ')':
5435 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5436 break;
5437 case '{':
5438 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5439 break;
5440 case '}':
5441 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5442 break;
5443 case '[':
5444 if (s->diff_context > 0) {
5445 s->diff_context--;
5446 s->matched_line = 0;
5447 diff_view_indicate_progress(view);
5448 err = create_diff(s);
5449 if (s->first_displayed_line + view->nlines - 1 >
5450 s->nlines) {
5451 s->first_displayed_line = 1;
5452 s->last_displayed_line = view->nlines;
5454 } else
5455 view->count = 0;
5456 break;
5457 case ']':
5458 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5459 s->diff_context++;
5460 s->matched_line = 0;
5461 diff_view_indicate_progress(view);
5462 err = create_diff(s);
5463 } else
5464 view->count = 0;
5465 break;
5466 case '<':
5467 case ',':
5468 case 'K':
5469 up = 1;
5470 /* FALL THROUGH */
5471 case '>':
5472 case '.':
5473 case 'J':
5474 if (s->parent_view == NULL) {
5475 view->count = 0;
5476 break;
5478 s->parent_view->count = view->count;
5480 if (s->parent_view->type == TOG_VIEW_LOG) {
5481 ls = &s->parent_view->state.log;
5482 old_selected_entry = ls->selected_entry;
5484 err = input_log_view(NULL, s->parent_view,
5485 up ? KEY_UP : KEY_DOWN);
5486 if (err)
5487 break;
5488 view->count = s->parent_view->count;
5490 if (old_selected_entry == ls->selected_entry)
5491 break;
5493 err = set_selected_commit(s, ls->selected_entry);
5494 if (err)
5495 break;
5496 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5497 struct tog_blame_view_state *bs;
5498 struct got_object_id *id, *prev_id;
5500 bs = &s->parent_view->state.blame;
5501 prev_id = get_annotation_for_line(bs->blame.lines,
5502 bs->blame.nlines, bs->last_diffed_line);
5504 err = input_blame_view(&view, s->parent_view,
5505 up ? KEY_UP : KEY_DOWN);
5506 if (err)
5507 break;
5508 view->count = s->parent_view->count;
5510 if (prev_id == NULL)
5511 break;
5512 id = get_selected_commit_id(bs->blame.lines,
5513 bs->blame.nlines, bs->first_displayed_line,
5514 bs->selected_line);
5515 if (id == NULL)
5516 break;
5518 if (!got_object_id_cmp(prev_id, id))
5519 break;
5521 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5522 if (err)
5523 break;
5525 s->first_displayed_line = 1;
5526 s->last_displayed_line = view->nlines;
5527 s->matched_line = 0;
5528 view->x = 0;
5530 diff_view_indicate_progress(view);
5531 err = create_diff(s);
5532 break;
5533 default:
5534 view->count = 0;
5535 break;
5538 return err;
5541 static const struct got_error *
5542 cmd_diff(int argc, char *argv[])
5544 const struct got_error *error = NULL;
5545 struct got_repository *repo = NULL;
5546 struct got_worktree *worktree = NULL;
5547 struct got_object_id *id1 = NULL, *id2 = NULL;
5548 char *repo_path = NULL, *cwd = NULL;
5549 char *id_str1 = NULL, *id_str2 = NULL;
5550 char *label1 = NULL, *label2 = NULL;
5551 int diff_context = 3, ignore_whitespace = 0;
5552 int ch, force_text_diff = 0;
5553 const char *errstr;
5554 struct tog_view *view;
5555 int *pack_fds = NULL;
5557 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5558 switch (ch) {
5559 case 'a':
5560 force_text_diff = 1;
5561 break;
5562 case 'C':
5563 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5564 &errstr);
5565 if (errstr != NULL)
5566 errx(1, "number of context lines is %s: %s",
5567 errstr, errstr);
5568 break;
5569 case 'r':
5570 repo_path = realpath(optarg, NULL);
5571 if (repo_path == NULL)
5572 return got_error_from_errno2("realpath",
5573 optarg);
5574 got_path_strip_trailing_slashes(repo_path);
5575 break;
5576 case 'w':
5577 ignore_whitespace = 1;
5578 break;
5579 default:
5580 usage_diff();
5581 /* NOTREACHED */
5585 argc -= optind;
5586 argv += optind;
5588 if (argc == 0) {
5589 usage_diff(); /* TODO show local worktree changes */
5590 } else if (argc == 2) {
5591 id_str1 = argv[0];
5592 id_str2 = argv[1];
5593 } else
5594 usage_diff();
5596 error = got_repo_pack_fds_open(&pack_fds);
5597 if (error)
5598 goto done;
5600 if (repo_path == NULL) {
5601 cwd = getcwd(NULL, 0);
5602 if (cwd == NULL)
5603 return got_error_from_errno("getcwd");
5604 error = got_worktree_open(&worktree, cwd);
5605 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5606 goto done;
5607 if (worktree)
5608 repo_path =
5609 strdup(got_worktree_get_repo_path(worktree));
5610 else
5611 repo_path = strdup(cwd);
5612 if (repo_path == NULL) {
5613 error = got_error_from_errno("strdup");
5614 goto done;
5618 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5619 if (error)
5620 goto done;
5622 init_curses();
5624 error = apply_unveil(got_repo_get_path(repo), NULL);
5625 if (error)
5626 goto done;
5628 error = tog_load_refs(repo, 0);
5629 if (error)
5630 goto done;
5632 error = got_repo_match_object_id(&id1, &label1, id_str1,
5633 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5634 if (error)
5635 goto done;
5637 error = got_repo_match_object_id(&id2, &label2, id_str2,
5638 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5639 if (error)
5640 goto done;
5642 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5643 if (view == NULL) {
5644 error = got_error_from_errno("view_open");
5645 goto done;
5647 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5648 ignore_whitespace, force_text_diff, NULL, repo);
5649 if (error)
5650 goto done;
5651 error = view_loop(view);
5652 done:
5653 free(label1);
5654 free(label2);
5655 free(repo_path);
5656 free(cwd);
5657 if (repo) {
5658 const struct got_error *close_err = got_repo_close(repo);
5659 if (error == NULL)
5660 error = close_err;
5662 if (worktree)
5663 got_worktree_close(worktree);
5664 if (pack_fds) {
5665 const struct got_error *pack_err =
5666 got_repo_pack_fds_close(pack_fds);
5667 if (error == NULL)
5668 error = pack_err;
5670 tog_free_refs();
5671 return error;
5674 __dead static void
5675 usage_blame(void)
5677 endwin();
5678 fprintf(stderr,
5679 "usage: %s blame [-c commit] [-r repository-path] path\n",
5680 getprogname());
5681 exit(1);
5684 struct tog_blame_line {
5685 int annotated;
5686 struct got_object_id *id;
5689 static const struct got_error *
5690 draw_blame(struct tog_view *view)
5692 struct tog_blame_view_state *s = &view->state.blame;
5693 struct tog_blame *blame = &s->blame;
5694 regmatch_t *regmatch = &view->regmatch;
5695 const struct got_error *err;
5696 int lineno = 0, nprinted = 0;
5697 char *line = NULL;
5698 size_t linesize = 0;
5699 ssize_t linelen;
5700 wchar_t *wline;
5701 int width;
5702 struct tog_blame_line *blame_line;
5703 struct got_object_id *prev_id = NULL;
5704 char *id_str;
5705 struct tog_color *tc;
5707 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5708 if (err)
5709 return err;
5711 rewind(blame->f);
5712 werase(view->window);
5714 if (asprintf(&line, "commit %s", id_str) == -1) {
5715 err = got_error_from_errno("asprintf");
5716 free(id_str);
5717 return err;
5720 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5721 free(line);
5722 line = NULL;
5723 if (err)
5724 return err;
5725 if (view_needs_focus_indication(view))
5726 wstandout(view->window);
5727 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5728 if (tc)
5729 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5730 waddwstr(view->window, wline);
5731 while (width++ < view->ncols)
5732 waddch(view->window, ' ');
5733 if (tc)
5734 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5735 if (view_needs_focus_indication(view))
5736 wstandend(view->window);
5737 free(wline);
5738 wline = NULL;
5740 if (view->gline > blame->nlines)
5741 view->gline = blame->nlines;
5743 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5744 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5745 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5746 free(id_str);
5747 return got_error_from_errno("asprintf");
5749 free(id_str);
5750 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5751 free(line);
5752 line = NULL;
5753 if (err)
5754 return err;
5755 waddwstr(view->window, wline);
5756 free(wline);
5757 wline = NULL;
5758 if (width < view->ncols - 1)
5759 waddch(view->window, '\n');
5761 s->eof = 0;
5762 view->maxx = 0;
5763 while (nprinted < view->nlines - 2) {
5764 linelen = getline(&line, &linesize, blame->f);
5765 if (linelen == -1) {
5766 if (feof(blame->f)) {
5767 s->eof = 1;
5768 break;
5770 free(line);
5771 return got_ferror(blame->f, GOT_ERR_IO);
5773 if (++lineno < s->first_displayed_line)
5774 continue;
5775 if (view->gline && !gotoline(view, &lineno, &nprinted))
5776 continue;
5778 /* Set view->maxx based on full line length. */
5779 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5780 if (err) {
5781 free(line);
5782 return err;
5784 free(wline);
5785 wline = NULL;
5786 view->maxx = MAX(view->maxx, width);
5788 if (nprinted == s->selected_line - 1)
5789 wstandout(view->window);
5791 if (blame->nlines > 0) {
5792 blame_line = &blame->lines[lineno - 1];
5793 if (blame_line->annotated && prev_id &&
5794 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5795 !(nprinted == s->selected_line - 1)) {
5796 waddstr(view->window, " ");
5797 } else if (blame_line->annotated) {
5798 char *id_str;
5799 err = got_object_id_str(&id_str,
5800 blame_line->id);
5801 if (err) {
5802 free(line);
5803 return err;
5805 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5806 if (tc)
5807 wattr_on(view->window,
5808 COLOR_PAIR(tc->colorpair), NULL);
5809 wprintw(view->window, "%.8s", id_str);
5810 if (tc)
5811 wattr_off(view->window,
5812 COLOR_PAIR(tc->colorpair), NULL);
5813 free(id_str);
5814 prev_id = blame_line->id;
5815 } else {
5816 waddstr(view->window, "........");
5817 prev_id = NULL;
5819 } else {
5820 waddstr(view->window, "........");
5821 prev_id = NULL;
5824 if (nprinted == s->selected_line - 1)
5825 wstandend(view->window);
5826 waddstr(view->window, " ");
5828 if (view->ncols <= 9) {
5829 width = 9;
5830 } else if (s->first_displayed_line + nprinted ==
5831 s->matched_line &&
5832 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5833 err = add_matched_line(&width, line, view->ncols - 9, 9,
5834 view->window, view->x, regmatch);
5835 if (err) {
5836 free(line);
5837 return err;
5839 width += 9;
5840 } else {
5841 int skip;
5842 err = format_line(&wline, &width, &skip, line,
5843 view->x, view->ncols - 9, 9, 1);
5844 if (err) {
5845 free(line);
5846 return err;
5848 waddwstr(view->window, &wline[skip]);
5849 width += 9;
5850 free(wline);
5851 wline = NULL;
5854 if (width <= view->ncols - 1)
5855 waddch(view->window, '\n');
5856 if (++nprinted == 1)
5857 s->first_displayed_line = lineno;
5859 free(line);
5860 s->last_displayed_line = lineno;
5862 view_border(view);
5864 return NULL;
5867 static const struct got_error *
5868 blame_cb(void *arg, int nlines, int lineno,
5869 struct got_commit_object *commit, struct got_object_id *id)
5871 const struct got_error *err = NULL;
5872 struct tog_blame_cb_args *a = arg;
5873 struct tog_blame_line *line;
5874 int errcode;
5876 if (nlines != a->nlines ||
5877 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5878 return got_error(GOT_ERR_RANGE);
5880 errcode = pthread_mutex_lock(&tog_mutex);
5881 if (errcode)
5882 return got_error_set_errno(errcode, "pthread_mutex_lock");
5884 if (*a->quit) { /* user has quit the blame view */
5885 err = got_error(GOT_ERR_ITER_COMPLETED);
5886 goto done;
5889 if (lineno == -1)
5890 goto done; /* no change in this commit */
5892 line = &a->lines[lineno - 1];
5893 if (line->annotated)
5894 goto done;
5896 line->id = got_object_id_dup(id);
5897 if (line->id == NULL) {
5898 err = got_error_from_errno("got_object_id_dup");
5899 goto done;
5901 line->annotated = 1;
5902 done:
5903 errcode = pthread_mutex_unlock(&tog_mutex);
5904 if (errcode)
5905 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5906 return err;
5909 static void *
5910 blame_thread(void *arg)
5912 const struct got_error *err, *close_err;
5913 struct tog_blame_thread_args *ta = arg;
5914 struct tog_blame_cb_args *a = ta->cb_args;
5915 int errcode, fd1 = -1, fd2 = -1;
5916 FILE *f1 = NULL, *f2 = NULL;
5918 fd1 = got_opentempfd();
5919 if (fd1 == -1)
5920 return (void *)got_error_from_errno("got_opentempfd");
5922 fd2 = got_opentempfd();
5923 if (fd2 == -1) {
5924 err = got_error_from_errno("got_opentempfd");
5925 goto done;
5928 f1 = got_opentemp();
5929 if (f1 == NULL) {
5930 err = (void *)got_error_from_errno("got_opentemp");
5931 goto done;
5933 f2 = got_opentemp();
5934 if (f2 == NULL) {
5935 err = (void *)got_error_from_errno("got_opentemp");
5936 goto done;
5939 err = block_signals_used_by_main_thread();
5940 if (err)
5941 goto done;
5943 err = got_blame(ta->path, a->commit_id, ta->repo,
5944 tog_diff_algo, blame_cb, ta->cb_args,
5945 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5946 if (err && err->code == GOT_ERR_CANCELLED)
5947 err = NULL;
5949 errcode = pthread_mutex_lock(&tog_mutex);
5950 if (errcode) {
5951 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5952 goto done;
5955 close_err = got_repo_close(ta->repo);
5956 if (err == NULL)
5957 err = close_err;
5958 ta->repo = NULL;
5959 *ta->complete = 1;
5961 errcode = pthread_mutex_unlock(&tog_mutex);
5962 if (errcode && err == NULL)
5963 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5965 done:
5966 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5967 err = got_error_from_errno("close");
5968 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5969 err = got_error_from_errno("close");
5970 if (f1 && fclose(f1) == EOF && err == NULL)
5971 err = got_error_from_errno("fclose");
5972 if (f2 && fclose(f2) == EOF && err == NULL)
5973 err = got_error_from_errno("fclose");
5975 return (void *)err;
5978 static struct got_object_id *
5979 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5980 int first_displayed_line, int selected_line)
5982 struct tog_blame_line *line;
5984 if (nlines <= 0)
5985 return NULL;
5987 line = &lines[first_displayed_line - 1 + selected_line - 1];
5988 if (!line->annotated)
5989 return NULL;
5991 return line->id;
5994 static struct got_object_id *
5995 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5996 int lineno)
5998 struct tog_blame_line *line;
6000 if (nlines <= 0 || lineno >= nlines)
6001 return NULL;
6003 line = &lines[lineno - 1];
6004 if (!line->annotated)
6005 return NULL;
6007 return line->id;
6010 static const struct got_error *
6011 stop_blame(struct tog_blame *blame)
6013 const struct got_error *err = NULL;
6014 int i;
6016 if (blame->thread) {
6017 int errcode;
6018 errcode = pthread_mutex_unlock(&tog_mutex);
6019 if (errcode)
6020 return got_error_set_errno(errcode,
6021 "pthread_mutex_unlock");
6022 errcode = pthread_join(blame->thread, (void **)&err);
6023 if (errcode)
6024 return got_error_set_errno(errcode, "pthread_join");
6025 errcode = pthread_mutex_lock(&tog_mutex);
6026 if (errcode)
6027 return got_error_set_errno(errcode,
6028 "pthread_mutex_lock");
6029 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6030 err = NULL;
6031 blame->thread = 0; //NULL;
6033 if (blame->thread_args.repo) {
6034 const struct got_error *close_err;
6035 close_err = got_repo_close(blame->thread_args.repo);
6036 if (err == NULL)
6037 err = close_err;
6038 blame->thread_args.repo = NULL;
6040 if (blame->f) {
6041 if (fclose(blame->f) == EOF && err == NULL)
6042 err = got_error_from_errno("fclose");
6043 blame->f = NULL;
6045 if (blame->lines) {
6046 for (i = 0; i < blame->nlines; i++)
6047 free(blame->lines[i].id);
6048 free(blame->lines);
6049 blame->lines = NULL;
6051 free(blame->cb_args.commit_id);
6052 blame->cb_args.commit_id = NULL;
6053 if (blame->pack_fds) {
6054 const struct got_error *pack_err =
6055 got_repo_pack_fds_close(blame->pack_fds);
6056 if (err == NULL)
6057 err = pack_err;
6058 blame->pack_fds = NULL;
6060 return err;
6063 static const struct got_error *
6064 cancel_blame_view(void *arg)
6066 const struct got_error *err = NULL;
6067 int *done = arg;
6068 int errcode;
6070 errcode = pthread_mutex_lock(&tog_mutex);
6071 if (errcode)
6072 return got_error_set_errno(errcode,
6073 "pthread_mutex_unlock");
6075 if (*done)
6076 err = got_error(GOT_ERR_CANCELLED);
6078 errcode = pthread_mutex_unlock(&tog_mutex);
6079 if (errcode)
6080 return got_error_set_errno(errcode,
6081 "pthread_mutex_lock");
6083 return err;
6086 static const struct got_error *
6087 run_blame(struct tog_view *view)
6089 struct tog_blame_view_state *s = &view->state.blame;
6090 struct tog_blame *blame = &s->blame;
6091 const struct got_error *err = NULL;
6092 struct got_commit_object *commit = NULL;
6093 struct got_blob_object *blob = NULL;
6094 struct got_repository *thread_repo = NULL;
6095 struct got_object_id *obj_id = NULL;
6096 int obj_type, fd = -1;
6097 int *pack_fds = NULL;
6099 err = got_object_open_as_commit(&commit, s->repo,
6100 &s->blamed_commit->id);
6101 if (err)
6102 return err;
6104 fd = got_opentempfd();
6105 if (fd == -1) {
6106 err = got_error_from_errno("got_opentempfd");
6107 goto done;
6110 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6111 if (err)
6112 goto done;
6114 err = got_object_get_type(&obj_type, s->repo, obj_id);
6115 if (err)
6116 goto done;
6118 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6119 err = got_error(GOT_ERR_OBJ_TYPE);
6120 goto done;
6123 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6124 if (err)
6125 goto done;
6126 blame->f = got_opentemp();
6127 if (blame->f == NULL) {
6128 err = got_error_from_errno("got_opentemp");
6129 goto done;
6131 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6132 &blame->line_offsets, blame->f, blob);
6133 if (err)
6134 goto done;
6135 if (blame->nlines == 0) {
6136 s->blame_complete = 1;
6137 goto done;
6140 /* Don't include \n at EOF in the blame line count. */
6141 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6142 blame->nlines--;
6144 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6145 if (blame->lines == NULL) {
6146 err = got_error_from_errno("calloc");
6147 goto done;
6150 err = got_repo_pack_fds_open(&pack_fds);
6151 if (err)
6152 goto done;
6153 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6154 pack_fds);
6155 if (err)
6156 goto done;
6158 blame->pack_fds = pack_fds;
6159 blame->cb_args.view = view;
6160 blame->cb_args.lines = blame->lines;
6161 blame->cb_args.nlines = blame->nlines;
6162 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6163 if (blame->cb_args.commit_id == NULL) {
6164 err = got_error_from_errno("got_object_id_dup");
6165 goto done;
6167 blame->cb_args.quit = &s->done;
6169 blame->thread_args.path = s->path;
6170 blame->thread_args.repo = thread_repo;
6171 blame->thread_args.cb_args = &blame->cb_args;
6172 blame->thread_args.complete = &s->blame_complete;
6173 blame->thread_args.cancel_cb = cancel_blame_view;
6174 blame->thread_args.cancel_arg = &s->done;
6175 s->blame_complete = 0;
6177 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6178 s->first_displayed_line = 1;
6179 s->last_displayed_line = view->nlines;
6180 s->selected_line = 1;
6182 s->matched_line = 0;
6184 done:
6185 if (commit)
6186 got_object_commit_close(commit);
6187 if (fd != -1 && close(fd) == -1 && err == NULL)
6188 err = got_error_from_errno("close");
6189 if (blob)
6190 got_object_blob_close(blob);
6191 free(obj_id);
6192 if (err)
6193 stop_blame(blame);
6194 return err;
6197 static const struct got_error *
6198 open_blame_view(struct tog_view *view, char *path,
6199 struct got_object_id *commit_id, struct got_repository *repo)
6201 const struct got_error *err = NULL;
6202 struct tog_blame_view_state *s = &view->state.blame;
6204 STAILQ_INIT(&s->blamed_commits);
6206 s->path = strdup(path);
6207 if (s->path == NULL)
6208 return got_error_from_errno("strdup");
6210 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6211 if (err) {
6212 free(s->path);
6213 return err;
6216 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6217 s->first_displayed_line = 1;
6218 s->last_displayed_line = view->nlines;
6219 s->selected_line = 1;
6220 s->blame_complete = 0;
6221 s->repo = repo;
6222 s->commit_id = commit_id;
6223 memset(&s->blame, 0, sizeof(s->blame));
6225 STAILQ_INIT(&s->colors);
6226 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6227 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6228 get_color_value("TOG_COLOR_COMMIT"));
6229 if (err)
6230 return err;
6233 view->show = show_blame_view;
6234 view->input = input_blame_view;
6235 view->reset = reset_blame_view;
6236 view->close = close_blame_view;
6237 view->search_start = search_start_blame_view;
6238 view->search_setup = search_setup_blame_view;
6239 view->search_next = search_next_view_match;
6241 return run_blame(view);
6244 static const struct got_error *
6245 close_blame_view(struct tog_view *view)
6247 const struct got_error *err = NULL;
6248 struct tog_blame_view_state *s = &view->state.blame;
6250 if (s->blame.thread)
6251 err = stop_blame(&s->blame);
6253 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6254 struct got_object_qid *blamed_commit;
6255 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6256 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6257 got_object_qid_free(blamed_commit);
6260 free(s->path);
6261 free_colors(&s->colors);
6262 return err;
6265 static const struct got_error *
6266 search_start_blame_view(struct tog_view *view)
6268 struct tog_blame_view_state *s = &view->state.blame;
6270 s->matched_line = 0;
6271 return NULL;
6274 static void
6275 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6276 size_t *nlines, int **first, int **last, int **match, int **selected)
6278 struct tog_blame_view_state *s = &view->state.blame;
6280 *f = s->blame.f;
6281 *nlines = s->blame.nlines;
6282 *line_offsets = s->blame.line_offsets;
6283 *match = &s->matched_line;
6284 *first = &s->first_displayed_line;
6285 *last = &s->last_displayed_line;
6286 *selected = &s->selected_line;
6289 static const struct got_error *
6290 show_blame_view(struct tog_view *view)
6292 const struct got_error *err = NULL;
6293 struct tog_blame_view_state *s = &view->state.blame;
6294 int errcode;
6296 if (s->blame.thread == 0 && !s->blame_complete) {
6297 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6298 &s->blame.thread_args);
6299 if (errcode)
6300 return got_error_set_errno(errcode, "pthread_create");
6302 halfdelay(1); /* fast refresh while annotating */
6305 if (s->blame_complete)
6306 halfdelay(10); /* disable fast refresh */
6308 err = draw_blame(view);
6310 view_border(view);
6311 return err;
6314 static const struct got_error *
6315 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6316 struct got_repository *repo, struct got_object_id *id)
6318 struct tog_view *log_view;
6319 const struct got_error *err = NULL;
6321 *new_view = NULL;
6323 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6324 if (log_view == NULL)
6325 return got_error_from_errno("view_open");
6327 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6328 if (err)
6329 view_close(log_view);
6330 else
6331 *new_view = log_view;
6333 return err;
6336 static const struct got_error *
6337 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6339 const struct got_error *err = NULL, *thread_err = NULL;
6340 struct tog_view *diff_view;
6341 struct tog_blame_view_state *s = &view->state.blame;
6342 int eos, nscroll, begin_y = 0, begin_x = 0;
6344 eos = nscroll = view->nlines - 2;
6345 if (view_is_hsplit_top(view))
6346 --eos; /* border */
6348 switch (ch) {
6349 case '0':
6350 case '$':
6351 case KEY_RIGHT:
6352 case 'l':
6353 case KEY_LEFT:
6354 case 'h':
6355 horizontal_scroll_input(view, ch);
6356 break;
6357 case 'q':
6358 s->done = 1;
6359 break;
6360 case 'g':
6361 case KEY_HOME:
6362 s->selected_line = 1;
6363 s->first_displayed_line = 1;
6364 view->count = 0;
6365 break;
6366 case 'G':
6367 case KEY_END:
6368 if (s->blame.nlines < eos) {
6369 s->selected_line = s->blame.nlines;
6370 s->first_displayed_line = 1;
6371 } else {
6372 s->selected_line = eos;
6373 s->first_displayed_line = s->blame.nlines - (eos - 1);
6375 view->count = 0;
6376 break;
6377 case 'k':
6378 case KEY_UP:
6379 case CTRL('p'):
6380 if (s->selected_line > 1)
6381 s->selected_line--;
6382 else if (s->selected_line == 1 &&
6383 s->first_displayed_line > 1)
6384 s->first_displayed_line--;
6385 else
6386 view->count = 0;
6387 break;
6388 case CTRL('u'):
6389 case 'u':
6390 nscroll /= 2;
6391 /* FALL THROUGH */
6392 case KEY_PPAGE:
6393 case CTRL('b'):
6394 case 'b':
6395 if (s->first_displayed_line == 1) {
6396 if (view->count > 1)
6397 nscroll += nscroll;
6398 s->selected_line = MAX(1, s->selected_line - nscroll);
6399 view->count = 0;
6400 break;
6402 if (s->first_displayed_line > nscroll)
6403 s->first_displayed_line -= nscroll;
6404 else
6405 s->first_displayed_line = 1;
6406 break;
6407 case 'j':
6408 case KEY_DOWN:
6409 case CTRL('n'):
6410 if (s->selected_line < eos && s->first_displayed_line +
6411 s->selected_line <= s->blame.nlines)
6412 s->selected_line++;
6413 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6414 s->first_displayed_line++;
6415 else
6416 view->count = 0;
6417 break;
6418 case 'c':
6419 case 'p': {
6420 struct got_object_id *id = NULL;
6422 view->count = 0;
6423 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6424 s->first_displayed_line, s->selected_line);
6425 if (id == NULL)
6426 break;
6427 if (ch == 'p') {
6428 struct got_commit_object *commit, *pcommit;
6429 struct got_object_qid *pid;
6430 struct got_object_id *blob_id = NULL;
6431 int obj_type;
6432 err = got_object_open_as_commit(&commit,
6433 s->repo, id);
6434 if (err)
6435 break;
6436 pid = STAILQ_FIRST(
6437 got_object_commit_get_parent_ids(commit));
6438 if (pid == NULL) {
6439 got_object_commit_close(commit);
6440 break;
6442 /* Check if path history ends here. */
6443 err = got_object_open_as_commit(&pcommit,
6444 s->repo, &pid->id);
6445 if (err)
6446 break;
6447 err = got_object_id_by_path(&blob_id, s->repo,
6448 pcommit, s->path);
6449 got_object_commit_close(pcommit);
6450 if (err) {
6451 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6452 err = NULL;
6453 got_object_commit_close(commit);
6454 break;
6456 err = got_object_get_type(&obj_type, s->repo,
6457 blob_id);
6458 free(blob_id);
6459 /* Can't blame non-blob type objects. */
6460 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6461 got_object_commit_close(commit);
6462 break;
6464 err = got_object_qid_alloc(&s->blamed_commit,
6465 &pid->id);
6466 got_object_commit_close(commit);
6467 } else {
6468 if (got_object_id_cmp(id,
6469 &s->blamed_commit->id) == 0)
6470 break;
6471 err = got_object_qid_alloc(&s->blamed_commit,
6472 id);
6474 if (err)
6475 break;
6476 s->done = 1;
6477 thread_err = stop_blame(&s->blame);
6478 s->done = 0;
6479 if (thread_err)
6480 break;
6481 STAILQ_INSERT_HEAD(&s->blamed_commits,
6482 s->blamed_commit, entry);
6483 err = run_blame(view);
6484 if (err)
6485 break;
6486 break;
6488 case 'C': {
6489 struct got_object_qid *first;
6491 view->count = 0;
6492 first = STAILQ_FIRST(&s->blamed_commits);
6493 if (!got_object_id_cmp(&first->id, s->commit_id))
6494 break;
6495 s->done = 1;
6496 thread_err = stop_blame(&s->blame);
6497 s->done = 0;
6498 if (thread_err)
6499 break;
6500 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6501 got_object_qid_free(s->blamed_commit);
6502 s->blamed_commit =
6503 STAILQ_FIRST(&s->blamed_commits);
6504 err = run_blame(view);
6505 if (err)
6506 break;
6507 break;
6509 case 'L':
6510 view->count = 0;
6511 s->id_to_log = get_selected_commit_id(s->blame.lines,
6512 s->blame.nlines, s->first_displayed_line, s->selected_line);
6513 if (s->id_to_log)
6514 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6515 break;
6516 case KEY_ENTER:
6517 case '\r': {
6518 struct got_object_id *id = NULL;
6519 struct got_object_qid *pid;
6520 struct got_commit_object *commit = NULL;
6522 view->count = 0;
6523 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6524 s->first_displayed_line, s->selected_line);
6525 if (id == NULL)
6526 break;
6527 err = got_object_open_as_commit(&commit, s->repo, id);
6528 if (err)
6529 break;
6530 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6531 if (*new_view) {
6532 /* traversed from diff view, release diff resources */
6533 err = close_diff_view(*new_view);
6534 if (err)
6535 break;
6536 diff_view = *new_view;
6537 } else {
6538 if (view_is_parent_view(view))
6539 view_get_split(view, &begin_y, &begin_x);
6541 diff_view = view_open(0, 0, begin_y, begin_x,
6542 TOG_VIEW_DIFF);
6543 if (diff_view == NULL) {
6544 got_object_commit_close(commit);
6545 err = got_error_from_errno("view_open");
6546 break;
6549 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6550 id, NULL, NULL, 3, 0, 0, view, s->repo);
6551 got_object_commit_close(commit);
6552 if (err) {
6553 view_close(diff_view);
6554 break;
6556 s->last_diffed_line = s->first_displayed_line - 1 +
6557 s->selected_line;
6558 if (*new_view)
6559 break; /* still open from active diff view */
6560 if (view_is_parent_view(view) &&
6561 view->mode == TOG_VIEW_SPLIT_HRZN) {
6562 err = view_init_hsplit(view, begin_y);
6563 if (err)
6564 break;
6567 view->focussed = 0;
6568 diff_view->focussed = 1;
6569 diff_view->mode = view->mode;
6570 diff_view->nlines = view->lines - begin_y;
6571 if (view_is_parent_view(view)) {
6572 view_transfer_size(diff_view, view);
6573 err = view_close_child(view);
6574 if (err)
6575 break;
6576 err = view_set_child(view, diff_view);
6577 if (err)
6578 break;
6579 view->focus_child = 1;
6580 } else
6581 *new_view = diff_view;
6582 if (err)
6583 break;
6584 break;
6586 case CTRL('d'):
6587 case 'd':
6588 nscroll /= 2;
6589 /* FALL THROUGH */
6590 case KEY_NPAGE:
6591 case CTRL('f'):
6592 case 'f':
6593 case ' ':
6594 if (s->last_displayed_line >= s->blame.nlines &&
6595 s->selected_line >= MIN(s->blame.nlines,
6596 view->nlines - 2)) {
6597 view->count = 0;
6598 break;
6600 if (s->last_displayed_line >= s->blame.nlines &&
6601 s->selected_line < view->nlines - 2) {
6602 s->selected_line +=
6603 MIN(nscroll, s->last_displayed_line -
6604 s->first_displayed_line - s->selected_line + 1);
6606 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6607 s->first_displayed_line += nscroll;
6608 else
6609 s->first_displayed_line =
6610 s->blame.nlines - (view->nlines - 3);
6611 break;
6612 case KEY_RESIZE:
6613 if (s->selected_line > view->nlines - 2) {
6614 s->selected_line = MIN(s->blame.nlines,
6615 view->nlines - 2);
6617 break;
6618 default:
6619 view->count = 0;
6620 break;
6622 return thread_err ? thread_err : err;
6625 static const struct got_error *
6626 reset_blame_view(struct tog_view *view)
6628 const struct got_error *err;
6629 struct tog_blame_view_state *s = &view->state.blame;
6631 view->count = 0;
6632 s->done = 1;
6633 err = stop_blame(&s->blame);
6634 s->done = 0;
6635 if (err)
6636 return err;
6637 return run_blame(view);
6640 static const struct got_error *
6641 cmd_blame(int argc, char *argv[])
6643 const struct got_error *error;
6644 struct got_repository *repo = NULL;
6645 struct got_worktree *worktree = NULL;
6646 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6647 char *link_target = NULL;
6648 struct got_object_id *commit_id = NULL;
6649 struct got_commit_object *commit = NULL;
6650 char *commit_id_str = NULL;
6651 int ch;
6652 struct tog_view *view;
6653 int *pack_fds = NULL;
6655 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6656 switch (ch) {
6657 case 'c':
6658 commit_id_str = optarg;
6659 break;
6660 case 'r':
6661 repo_path = realpath(optarg, NULL);
6662 if (repo_path == NULL)
6663 return got_error_from_errno2("realpath",
6664 optarg);
6665 break;
6666 default:
6667 usage_blame();
6668 /* NOTREACHED */
6672 argc -= optind;
6673 argv += optind;
6675 if (argc != 1)
6676 usage_blame();
6678 error = got_repo_pack_fds_open(&pack_fds);
6679 if (error != NULL)
6680 goto done;
6682 if (repo_path == NULL) {
6683 cwd = getcwd(NULL, 0);
6684 if (cwd == NULL)
6685 return got_error_from_errno("getcwd");
6686 error = got_worktree_open(&worktree, cwd);
6687 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6688 goto done;
6689 if (worktree)
6690 repo_path =
6691 strdup(got_worktree_get_repo_path(worktree));
6692 else
6693 repo_path = strdup(cwd);
6694 if (repo_path == NULL) {
6695 error = got_error_from_errno("strdup");
6696 goto done;
6700 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6701 if (error != NULL)
6702 goto done;
6704 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6705 worktree);
6706 if (error)
6707 goto done;
6709 init_curses();
6711 error = apply_unveil(got_repo_get_path(repo), NULL);
6712 if (error)
6713 goto done;
6715 error = tog_load_refs(repo, 0);
6716 if (error)
6717 goto done;
6719 if (commit_id_str == NULL) {
6720 struct got_reference *head_ref;
6721 error = got_ref_open(&head_ref, repo, worktree ?
6722 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6723 if (error != NULL)
6724 goto done;
6725 error = got_ref_resolve(&commit_id, repo, head_ref);
6726 got_ref_close(head_ref);
6727 } else {
6728 error = got_repo_match_object_id(&commit_id, NULL,
6729 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6731 if (error != NULL)
6732 goto done;
6734 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6735 if (view == NULL) {
6736 error = got_error_from_errno("view_open");
6737 goto done;
6740 error = got_object_open_as_commit(&commit, repo, commit_id);
6741 if (error)
6742 goto done;
6744 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6745 commit, repo);
6746 if (error)
6747 goto done;
6749 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6750 commit_id, repo);
6751 if (error)
6752 goto done;
6753 if (worktree) {
6754 /* Release work tree lock. */
6755 got_worktree_close(worktree);
6756 worktree = NULL;
6758 error = view_loop(view);
6759 done:
6760 free(repo_path);
6761 free(in_repo_path);
6762 free(link_target);
6763 free(cwd);
6764 free(commit_id);
6765 if (commit)
6766 got_object_commit_close(commit);
6767 if (worktree)
6768 got_worktree_close(worktree);
6769 if (repo) {
6770 const struct got_error *close_err = got_repo_close(repo);
6771 if (error == NULL)
6772 error = close_err;
6774 if (pack_fds) {
6775 const struct got_error *pack_err =
6776 got_repo_pack_fds_close(pack_fds);
6777 if (error == NULL)
6778 error = pack_err;
6780 tog_free_refs();
6781 return error;
6784 static const struct got_error *
6785 draw_tree_entries(struct tog_view *view, const char *parent_path)
6787 struct tog_tree_view_state *s = &view->state.tree;
6788 const struct got_error *err = NULL;
6789 struct got_tree_entry *te;
6790 wchar_t *wline;
6791 char *index = NULL;
6792 struct tog_color *tc;
6793 int width, n, nentries, scrollx, i = 1;
6794 int limit = view->nlines;
6796 s->ndisplayed = 0;
6797 if (view_is_hsplit_top(view))
6798 --limit; /* border */
6800 werase(view->window);
6802 if (limit == 0)
6803 return NULL;
6805 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6806 0, 0);
6807 if (err)
6808 return err;
6809 if (view_needs_focus_indication(view))
6810 wstandout(view->window);
6811 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6812 if (tc)
6813 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6814 waddwstr(view->window, wline);
6815 free(wline);
6816 wline = NULL;
6817 while (width++ < view->ncols)
6818 waddch(view->window, ' ');
6819 if (tc)
6820 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6821 if (view_needs_focus_indication(view))
6822 wstandend(view->window);
6823 if (--limit <= 0)
6824 return NULL;
6826 i += s->selected;
6827 if (s->first_displayed_entry) {
6828 i += got_tree_entry_get_index(s->first_displayed_entry);
6829 if (s->tree != s->root)
6830 ++i; /* account for ".." entry */
6832 nentries = got_object_tree_get_nentries(s->tree);
6833 if (asprintf(&index, "[%d/%d] %s",
6834 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6835 return got_error_from_errno("asprintf");
6836 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6837 free(index);
6838 if (err)
6839 return err;
6840 waddwstr(view->window, wline);
6841 free(wline);
6842 wline = NULL;
6843 if (width < view->ncols - 1)
6844 waddch(view->window, '\n');
6845 if (--limit <= 0)
6846 return NULL;
6847 waddch(view->window, '\n');
6848 if (--limit <= 0)
6849 return NULL;
6851 if (s->first_displayed_entry == NULL) {
6852 te = got_object_tree_get_first_entry(s->tree);
6853 if (s->selected == 0) {
6854 if (view->focussed)
6855 wstandout(view->window);
6856 s->selected_entry = NULL;
6858 waddstr(view->window, " ..\n"); /* parent directory */
6859 if (s->selected == 0 && view->focussed)
6860 wstandend(view->window);
6861 s->ndisplayed++;
6862 if (--limit <= 0)
6863 return NULL;
6864 n = 1;
6865 } else {
6866 n = 0;
6867 te = s->first_displayed_entry;
6870 view->maxx = 0;
6871 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6872 char *line = NULL, *id_str = NULL, *link_target = NULL;
6873 const char *modestr = "";
6874 mode_t mode;
6876 te = got_object_tree_get_entry(s->tree, i);
6877 mode = got_tree_entry_get_mode(te);
6879 if (s->show_ids) {
6880 err = got_object_id_str(&id_str,
6881 got_tree_entry_get_id(te));
6882 if (err)
6883 return got_error_from_errno(
6884 "got_object_id_str");
6886 if (got_object_tree_entry_is_submodule(te))
6887 modestr = "$";
6888 else if (S_ISLNK(mode)) {
6889 int i;
6891 err = got_tree_entry_get_symlink_target(&link_target,
6892 te, s->repo);
6893 if (err) {
6894 free(id_str);
6895 return err;
6897 for (i = 0; i < strlen(link_target); i++) {
6898 if (!isprint((unsigned char)link_target[i]))
6899 link_target[i] = '?';
6901 modestr = "@";
6903 else if (S_ISDIR(mode))
6904 modestr = "/";
6905 else if (mode & S_IXUSR)
6906 modestr = "*";
6907 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6908 got_tree_entry_get_name(te), modestr,
6909 link_target ? " -> ": "",
6910 link_target ? link_target : "") == -1) {
6911 free(id_str);
6912 free(link_target);
6913 return got_error_from_errno("asprintf");
6915 free(id_str);
6916 free(link_target);
6918 /* use full line width to determine view->maxx */
6919 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
6920 if (err) {
6921 free(line);
6922 break;
6924 view->maxx = MAX(view->maxx, width);
6925 free(wline);
6926 wline = NULL;
6928 err = format_line(&wline, &width, &scrollx, line, view->x,
6929 view->ncols, 0, 0);
6930 if (err) {
6931 free(line);
6932 break;
6934 if (n == s->selected) {
6935 if (view->focussed)
6936 wstandout(view->window);
6937 s->selected_entry = te;
6939 tc = match_color(&s->colors, line);
6940 if (tc)
6941 wattr_on(view->window,
6942 COLOR_PAIR(tc->colorpair), NULL);
6943 waddwstr(view->window, &wline[scrollx]);
6944 if (tc)
6945 wattr_off(view->window,
6946 COLOR_PAIR(tc->colorpair), NULL);
6947 if (width < view->ncols)
6948 waddch(view->window, '\n');
6949 if (n == s->selected && view->focussed)
6950 wstandend(view->window);
6951 free(line);
6952 free(wline);
6953 wline = NULL;
6954 n++;
6955 s->ndisplayed++;
6956 s->last_displayed_entry = te;
6957 if (--limit <= 0)
6958 break;
6961 return err;
6964 static void
6965 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6967 struct got_tree_entry *te;
6968 int isroot = s->tree == s->root;
6969 int i = 0;
6971 if (s->first_displayed_entry == NULL)
6972 return;
6974 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6975 while (i++ < maxscroll) {
6976 if (te == NULL) {
6977 if (!isroot)
6978 s->first_displayed_entry = NULL;
6979 break;
6981 s->first_displayed_entry = te;
6982 te = got_tree_entry_get_prev(s->tree, te);
6986 static const struct got_error *
6987 tree_scroll_down(struct tog_view *view, int maxscroll)
6989 struct tog_tree_view_state *s = &view->state.tree;
6990 struct got_tree_entry *next, *last;
6991 int n = 0;
6993 if (s->first_displayed_entry)
6994 next = got_tree_entry_get_next(s->tree,
6995 s->first_displayed_entry);
6996 else
6997 next = got_object_tree_get_first_entry(s->tree);
6999 last = s->last_displayed_entry;
7000 while (next && n++ < maxscroll) {
7001 if (last) {
7002 s->last_displayed_entry = last;
7003 last = got_tree_entry_get_next(s->tree, last);
7005 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7006 s->first_displayed_entry = next;
7007 next = got_tree_entry_get_next(s->tree, next);
7011 return NULL;
7014 static const struct got_error *
7015 tree_entry_path(char **path, struct tog_parent_trees *parents,
7016 struct got_tree_entry *te)
7018 const struct got_error *err = NULL;
7019 struct tog_parent_tree *pt;
7020 size_t len = 2; /* for leading slash and NUL */
7022 TAILQ_FOREACH(pt, parents, entry)
7023 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7024 + 1 /* slash */;
7025 if (te)
7026 len += strlen(got_tree_entry_get_name(te));
7028 *path = calloc(1, len);
7029 if (path == NULL)
7030 return got_error_from_errno("calloc");
7032 (*path)[0] = '/';
7033 pt = TAILQ_LAST(parents, tog_parent_trees);
7034 while (pt) {
7035 const char *name = got_tree_entry_get_name(pt->selected_entry);
7036 if (strlcat(*path, name, len) >= len) {
7037 err = got_error(GOT_ERR_NO_SPACE);
7038 goto done;
7040 if (strlcat(*path, "/", len) >= len) {
7041 err = got_error(GOT_ERR_NO_SPACE);
7042 goto done;
7044 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7046 if (te) {
7047 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7048 err = got_error(GOT_ERR_NO_SPACE);
7049 goto done;
7052 done:
7053 if (err) {
7054 free(*path);
7055 *path = NULL;
7057 return err;
7060 static const struct got_error *
7061 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7062 struct got_tree_entry *te, struct tog_parent_trees *parents,
7063 struct got_object_id *commit_id, struct got_repository *repo)
7065 const struct got_error *err = NULL;
7066 char *path;
7067 struct tog_view *blame_view;
7069 *new_view = NULL;
7071 err = tree_entry_path(&path, parents, te);
7072 if (err)
7073 return err;
7075 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7076 if (blame_view == NULL) {
7077 err = got_error_from_errno("view_open");
7078 goto done;
7081 err = open_blame_view(blame_view, path, commit_id, repo);
7082 if (err) {
7083 if (err->code == GOT_ERR_CANCELLED)
7084 err = NULL;
7085 view_close(blame_view);
7086 } else
7087 *new_view = blame_view;
7088 done:
7089 free(path);
7090 return err;
7093 static const struct got_error *
7094 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7095 struct tog_tree_view_state *s)
7097 struct tog_view *log_view;
7098 const struct got_error *err = NULL;
7099 char *path;
7101 *new_view = NULL;
7103 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7104 if (log_view == NULL)
7105 return got_error_from_errno("view_open");
7107 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7108 if (err)
7109 return err;
7111 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7112 path, 0);
7113 if (err)
7114 view_close(log_view);
7115 else
7116 *new_view = log_view;
7117 free(path);
7118 return err;
7121 static const struct got_error *
7122 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7123 const char *head_ref_name, struct got_repository *repo)
7125 const struct got_error *err = NULL;
7126 char *commit_id_str = NULL;
7127 struct tog_tree_view_state *s = &view->state.tree;
7128 struct got_commit_object *commit = NULL;
7130 TAILQ_INIT(&s->parents);
7131 STAILQ_INIT(&s->colors);
7133 s->commit_id = got_object_id_dup(commit_id);
7134 if (s->commit_id == NULL)
7135 return got_error_from_errno("got_object_id_dup");
7137 err = got_object_open_as_commit(&commit, repo, commit_id);
7138 if (err)
7139 goto done;
7142 * The root is opened here and will be closed when the view is closed.
7143 * Any visited subtrees and their path-wise parents are opened and
7144 * closed on demand.
7146 err = got_object_open_as_tree(&s->root, repo,
7147 got_object_commit_get_tree_id(commit));
7148 if (err)
7149 goto done;
7150 s->tree = s->root;
7152 err = got_object_id_str(&commit_id_str, commit_id);
7153 if (err != NULL)
7154 goto done;
7156 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7157 err = got_error_from_errno("asprintf");
7158 goto done;
7161 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7162 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7163 if (head_ref_name) {
7164 s->head_ref_name = strdup(head_ref_name);
7165 if (s->head_ref_name == NULL) {
7166 err = got_error_from_errno("strdup");
7167 goto done;
7170 s->repo = repo;
7172 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7173 err = add_color(&s->colors, "\\$$",
7174 TOG_COLOR_TREE_SUBMODULE,
7175 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7176 if (err)
7177 goto done;
7178 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7179 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7180 if (err)
7181 goto done;
7182 err = add_color(&s->colors, "/$",
7183 TOG_COLOR_TREE_DIRECTORY,
7184 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7185 if (err)
7186 goto done;
7188 err = add_color(&s->colors, "\\*$",
7189 TOG_COLOR_TREE_EXECUTABLE,
7190 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7191 if (err)
7192 goto done;
7194 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7195 get_color_value("TOG_COLOR_COMMIT"));
7196 if (err)
7197 goto done;
7200 view->show = show_tree_view;
7201 view->input = input_tree_view;
7202 view->close = close_tree_view;
7203 view->search_start = search_start_tree_view;
7204 view->search_next = search_next_tree_view;
7205 done:
7206 free(commit_id_str);
7207 if (commit)
7208 got_object_commit_close(commit);
7209 if (err)
7210 close_tree_view(view);
7211 return err;
7214 static const struct got_error *
7215 close_tree_view(struct tog_view *view)
7217 struct tog_tree_view_state *s = &view->state.tree;
7219 free_colors(&s->colors);
7220 free(s->tree_label);
7221 s->tree_label = NULL;
7222 free(s->commit_id);
7223 s->commit_id = NULL;
7224 free(s->head_ref_name);
7225 s->head_ref_name = NULL;
7226 while (!TAILQ_EMPTY(&s->parents)) {
7227 struct tog_parent_tree *parent;
7228 parent = TAILQ_FIRST(&s->parents);
7229 TAILQ_REMOVE(&s->parents, parent, entry);
7230 if (parent->tree != s->root)
7231 got_object_tree_close(parent->tree);
7232 free(parent);
7235 if (s->tree != NULL && s->tree != s->root)
7236 got_object_tree_close(s->tree);
7237 if (s->root)
7238 got_object_tree_close(s->root);
7239 return NULL;
7242 static const struct got_error *
7243 search_start_tree_view(struct tog_view *view)
7245 struct tog_tree_view_state *s = &view->state.tree;
7247 s->matched_entry = NULL;
7248 return NULL;
7251 static int
7252 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7254 regmatch_t regmatch;
7256 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7257 0) == 0;
7260 static const struct got_error *
7261 search_next_tree_view(struct tog_view *view)
7263 struct tog_tree_view_state *s = &view->state.tree;
7264 struct got_tree_entry *te = NULL;
7266 if (!view->searching) {
7267 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7268 return NULL;
7271 if (s->matched_entry) {
7272 if (view->searching == TOG_SEARCH_FORWARD) {
7273 if (s->selected_entry)
7274 te = got_tree_entry_get_next(s->tree,
7275 s->selected_entry);
7276 else
7277 te = got_object_tree_get_first_entry(s->tree);
7278 } else {
7279 if (s->selected_entry == NULL)
7280 te = got_object_tree_get_last_entry(s->tree);
7281 else
7282 te = got_tree_entry_get_prev(s->tree,
7283 s->selected_entry);
7285 } else {
7286 if (s->selected_entry)
7287 te = s->selected_entry;
7288 else 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 while (1) {
7295 if (te == NULL) {
7296 if (s->matched_entry == NULL) {
7297 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7298 return NULL;
7300 if (view->searching == TOG_SEARCH_FORWARD)
7301 te = got_object_tree_get_first_entry(s->tree);
7302 else
7303 te = got_object_tree_get_last_entry(s->tree);
7306 if (match_tree_entry(te, &view->regex)) {
7307 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7308 s->matched_entry = te;
7309 break;
7312 if (view->searching == TOG_SEARCH_FORWARD)
7313 te = got_tree_entry_get_next(s->tree, te);
7314 else
7315 te = got_tree_entry_get_prev(s->tree, te);
7318 if (s->matched_entry) {
7319 s->first_displayed_entry = s->matched_entry;
7320 s->selected = 0;
7323 return NULL;
7326 static const struct got_error *
7327 show_tree_view(struct tog_view *view)
7329 const struct got_error *err = NULL;
7330 struct tog_tree_view_state *s = &view->state.tree;
7331 char *parent_path;
7333 err = tree_entry_path(&parent_path, &s->parents, NULL);
7334 if (err)
7335 return err;
7337 err = draw_tree_entries(view, parent_path);
7338 free(parent_path);
7340 view_border(view);
7341 return err;
7344 static const struct got_error *
7345 tree_goto_line(struct tog_view *view, int nlines)
7347 const struct got_error *err = NULL;
7348 struct tog_tree_view_state *s = &view->state.tree;
7349 struct got_tree_entry **fte, **lte, **ste;
7350 int g, last, first = 1, i = 1;
7351 int root = s->tree == s->root;
7352 int off = root ? 1 : 2;
7354 g = view->gline;
7355 view->gline = 0;
7357 if (g == 0)
7358 g = 1;
7359 else if (g > got_object_tree_get_nentries(s->tree))
7360 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7362 fte = &s->first_displayed_entry;
7363 lte = &s->last_displayed_entry;
7364 ste = &s->selected_entry;
7366 if (*fte != NULL) {
7367 first = got_tree_entry_get_index(*fte);
7368 first += off; /* account for ".." */
7370 last = got_tree_entry_get_index(*lte);
7371 last += off;
7373 if (g >= first && g <= last && g - first < nlines) {
7374 s->selected = g - first;
7375 return NULL; /* gline is on the current page */
7378 if (*ste != NULL) {
7379 i = got_tree_entry_get_index(*ste);
7380 i += off;
7383 if (i < g) {
7384 err = tree_scroll_down(view, g - i);
7385 if (err)
7386 return err;
7387 if (got_tree_entry_get_index(*lte) >=
7388 got_object_tree_get_nentries(s->tree) - 1 &&
7389 first + s->selected < g &&
7390 s->selected < s->ndisplayed - 1) {
7391 first = got_tree_entry_get_index(*fte);
7392 first += off;
7393 s->selected = g - first;
7395 } else if (i > g)
7396 tree_scroll_up(s, i - g);
7398 if (g < nlines &&
7399 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7400 s->selected = g - 1;
7402 return NULL;
7405 static const struct got_error *
7406 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7408 const struct got_error *err = NULL;
7409 struct tog_tree_view_state *s = &view->state.tree;
7410 struct got_tree_entry *te;
7411 int n, nscroll = view->nlines - 3;
7413 if (view->gline)
7414 return tree_goto_line(view, nscroll);
7416 switch (ch) {
7417 case '0':
7418 case '$':
7419 case KEY_RIGHT:
7420 case 'l':
7421 case KEY_LEFT:
7422 case 'h':
7423 horizontal_scroll_input(view, ch);
7424 break;
7425 case 'i':
7426 s->show_ids = !s->show_ids;
7427 view->count = 0;
7428 break;
7429 case 'L':
7430 view->count = 0;
7431 if (!s->selected_entry)
7432 break;
7433 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7434 break;
7435 case 'R':
7436 view->count = 0;
7437 err = view_request_new(new_view, view, TOG_VIEW_REF);
7438 break;
7439 case 'g':
7440 case '=':
7441 case KEY_HOME:
7442 s->selected = 0;
7443 view->count = 0;
7444 if (s->tree == s->root)
7445 s->first_displayed_entry =
7446 got_object_tree_get_first_entry(s->tree);
7447 else
7448 s->first_displayed_entry = NULL;
7449 break;
7450 case 'G':
7451 case '*':
7452 case KEY_END: {
7453 int eos = view->nlines - 3;
7455 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7456 --eos; /* border */
7457 s->selected = 0;
7458 view->count = 0;
7459 te = got_object_tree_get_last_entry(s->tree);
7460 for (n = 0; n < eos; n++) {
7461 if (te == NULL) {
7462 if (s->tree != s->root) {
7463 s->first_displayed_entry = NULL;
7464 n++;
7466 break;
7468 s->first_displayed_entry = te;
7469 te = got_tree_entry_get_prev(s->tree, te);
7471 if (n > 0)
7472 s->selected = n - 1;
7473 break;
7475 case 'k':
7476 case KEY_UP:
7477 case CTRL('p'):
7478 if (s->selected > 0) {
7479 s->selected--;
7480 break;
7482 tree_scroll_up(s, 1);
7483 if (s->selected_entry == NULL ||
7484 (s->tree == s->root && s->selected_entry ==
7485 got_object_tree_get_first_entry(s->tree)))
7486 view->count = 0;
7487 break;
7488 case CTRL('u'):
7489 case 'u':
7490 nscroll /= 2;
7491 /* FALL THROUGH */
7492 case KEY_PPAGE:
7493 case CTRL('b'):
7494 case 'b':
7495 if (s->tree == s->root) {
7496 if (got_object_tree_get_first_entry(s->tree) ==
7497 s->first_displayed_entry)
7498 s->selected -= MIN(s->selected, nscroll);
7499 } else {
7500 if (s->first_displayed_entry == NULL)
7501 s->selected -= MIN(s->selected, nscroll);
7503 tree_scroll_up(s, MAX(0, nscroll));
7504 if (s->selected_entry == NULL ||
7505 (s->tree == s->root && s->selected_entry ==
7506 got_object_tree_get_first_entry(s->tree)))
7507 view->count = 0;
7508 break;
7509 case 'j':
7510 case KEY_DOWN:
7511 case CTRL('n'):
7512 if (s->selected < s->ndisplayed - 1) {
7513 s->selected++;
7514 break;
7516 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7517 == NULL) {
7518 /* can't scroll any further */
7519 view->count = 0;
7520 break;
7522 tree_scroll_down(view, 1);
7523 break;
7524 case CTRL('d'):
7525 case 'd':
7526 nscroll /= 2;
7527 /* FALL THROUGH */
7528 case KEY_NPAGE:
7529 case CTRL('f'):
7530 case 'f':
7531 case ' ':
7532 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7533 == NULL) {
7534 /* can't scroll any further; move cursor down */
7535 if (s->selected < s->ndisplayed - 1)
7536 s->selected += MIN(nscroll,
7537 s->ndisplayed - s->selected - 1);
7538 else
7539 view->count = 0;
7540 break;
7542 tree_scroll_down(view, nscroll);
7543 break;
7544 case KEY_ENTER:
7545 case '\r':
7546 case KEY_BACKSPACE:
7547 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7548 struct tog_parent_tree *parent;
7549 /* user selected '..' */
7550 if (s->tree == s->root) {
7551 view->count = 0;
7552 break;
7554 parent = TAILQ_FIRST(&s->parents);
7555 TAILQ_REMOVE(&s->parents, parent,
7556 entry);
7557 got_object_tree_close(s->tree);
7558 s->tree = parent->tree;
7559 s->first_displayed_entry =
7560 parent->first_displayed_entry;
7561 s->selected_entry =
7562 parent->selected_entry;
7563 s->selected = parent->selected;
7564 if (s->selected > view->nlines - 3) {
7565 err = offset_selection_down(view);
7566 if (err)
7567 break;
7569 free(parent);
7570 } else if (S_ISDIR(got_tree_entry_get_mode(
7571 s->selected_entry))) {
7572 struct got_tree_object *subtree;
7573 view->count = 0;
7574 err = got_object_open_as_tree(&subtree, s->repo,
7575 got_tree_entry_get_id(s->selected_entry));
7576 if (err)
7577 break;
7578 err = tree_view_visit_subtree(s, subtree);
7579 if (err) {
7580 got_object_tree_close(subtree);
7581 break;
7583 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7584 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7585 break;
7586 case KEY_RESIZE:
7587 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7588 s->selected = view->nlines - 4;
7589 view->count = 0;
7590 break;
7591 default:
7592 view->count = 0;
7593 break;
7596 return err;
7599 __dead static void
7600 usage_tree(void)
7602 endwin();
7603 fprintf(stderr,
7604 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7605 getprogname());
7606 exit(1);
7609 static const struct got_error *
7610 cmd_tree(int argc, char *argv[])
7612 const struct got_error *error;
7613 struct got_repository *repo = NULL;
7614 struct got_worktree *worktree = NULL;
7615 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7616 struct got_object_id *commit_id = NULL;
7617 struct got_commit_object *commit = NULL;
7618 const char *commit_id_arg = NULL;
7619 char *label = NULL;
7620 struct got_reference *ref = NULL;
7621 const char *head_ref_name = NULL;
7622 int ch;
7623 struct tog_view *view;
7624 int *pack_fds = NULL;
7626 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7627 switch (ch) {
7628 case 'c':
7629 commit_id_arg = optarg;
7630 break;
7631 case 'r':
7632 repo_path = realpath(optarg, NULL);
7633 if (repo_path == NULL)
7634 return got_error_from_errno2("realpath",
7635 optarg);
7636 break;
7637 default:
7638 usage_tree();
7639 /* NOTREACHED */
7643 argc -= optind;
7644 argv += optind;
7646 if (argc > 1)
7647 usage_tree();
7649 error = got_repo_pack_fds_open(&pack_fds);
7650 if (error != NULL)
7651 goto done;
7653 if (repo_path == NULL) {
7654 cwd = getcwd(NULL, 0);
7655 if (cwd == NULL)
7656 return got_error_from_errno("getcwd");
7657 error = got_worktree_open(&worktree, cwd);
7658 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7659 goto done;
7660 if (worktree)
7661 repo_path =
7662 strdup(got_worktree_get_repo_path(worktree));
7663 else
7664 repo_path = strdup(cwd);
7665 if (repo_path == NULL) {
7666 error = got_error_from_errno("strdup");
7667 goto done;
7671 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7672 if (error != NULL)
7673 goto done;
7675 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7676 repo, worktree);
7677 if (error)
7678 goto done;
7680 init_curses();
7682 error = apply_unveil(got_repo_get_path(repo), NULL);
7683 if (error)
7684 goto done;
7686 error = tog_load_refs(repo, 0);
7687 if (error)
7688 goto done;
7690 if (commit_id_arg == NULL) {
7691 error = got_repo_match_object_id(&commit_id, &label,
7692 worktree ? got_worktree_get_head_ref_name(worktree) :
7693 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7694 if (error)
7695 goto done;
7696 head_ref_name = label;
7697 } else {
7698 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7699 if (error == NULL)
7700 head_ref_name = got_ref_get_name(ref);
7701 else if (error->code != GOT_ERR_NOT_REF)
7702 goto done;
7703 error = got_repo_match_object_id(&commit_id, NULL,
7704 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7705 if (error)
7706 goto done;
7709 error = got_object_open_as_commit(&commit, repo, commit_id);
7710 if (error)
7711 goto done;
7713 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7714 if (view == NULL) {
7715 error = got_error_from_errno("view_open");
7716 goto done;
7718 error = open_tree_view(view, commit_id, head_ref_name, repo);
7719 if (error)
7720 goto done;
7721 if (!got_path_is_root_dir(in_repo_path)) {
7722 error = tree_view_walk_path(&view->state.tree, commit,
7723 in_repo_path);
7724 if (error)
7725 goto done;
7728 if (worktree) {
7729 /* Release work tree lock. */
7730 got_worktree_close(worktree);
7731 worktree = NULL;
7733 error = view_loop(view);
7734 done:
7735 free(repo_path);
7736 free(cwd);
7737 free(commit_id);
7738 free(label);
7739 if (ref)
7740 got_ref_close(ref);
7741 if (repo) {
7742 const struct got_error *close_err = got_repo_close(repo);
7743 if (error == NULL)
7744 error = close_err;
7746 if (pack_fds) {
7747 const struct got_error *pack_err =
7748 got_repo_pack_fds_close(pack_fds);
7749 if (error == NULL)
7750 error = pack_err;
7752 tog_free_refs();
7753 return error;
7756 static const struct got_error *
7757 ref_view_load_refs(struct tog_ref_view_state *s)
7759 struct got_reflist_entry *sre;
7760 struct tog_reflist_entry *re;
7762 s->nrefs = 0;
7763 TAILQ_FOREACH(sre, &tog_refs, entry) {
7764 if (strncmp(got_ref_get_name(sre->ref),
7765 "refs/got/", 9) == 0 &&
7766 strncmp(got_ref_get_name(sre->ref),
7767 "refs/got/backup/", 16) != 0)
7768 continue;
7770 re = malloc(sizeof(*re));
7771 if (re == NULL)
7772 return got_error_from_errno("malloc");
7774 re->ref = got_ref_dup(sre->ref);
7775 if (re->ref == NULL)
7776 return got_error_from_errno("got_ref_dup");
7777 re->idx = s->nrefs++;
7778 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7781 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7782 return NULL;
7785 static void
7786 ref_view_free_refs(struct tog_ref_view_state *s)
7788 struct tog_reflist_entry *re;
7790 while (!TAILQ_EMPTY(&s->refs)) {
7791 re = TAILQ_FIRST(&s->refs);
7792 TAILQ_REMOVE(&s->refs, re, entry);
7793 got_ref_close(re->ref);
7794 free(re);
7798 static const struct got_error *
7799 open_ref_view(struct tog_view *view, struct got_repository *repo)
7801 const struct got_error *err = NULL;
7802 struct tog_ref_view_state *s = &view->state.ref;
7804 s->selected_entry = 0;
7805 s->repo = repo;
7807 TAILQ_INIT(&s->refs);
7808 STAILQ_INIT(&s->colors);
7810 err = ref_view_load_refs(s);
7811 if (err)
7812 return err;
7814 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7815 err = add_color(&s->colors, "^refs/heads/",
7816 TOG_COLOR_REFS_HEADS,
7817 get_color_value("TOG_COLOR_REFS_HEADS"));
7818 if (err)
7819 goto done;
7821 err = add_color(&s->colors, "^refs/tags/",
7822 TOG_COLOR_REFS_TAGS,
7823 get_color_value("TOG_COLOR_REFS_TAGS"));
7824 if (err)
7825 goto done;
7827 err = add_color(&s->colors, "^refs/remotes/",
7828 TOG_COLOR_REFS_REMOTES,
7829 get_color_value("TOG_COLOR_REFS_REMOTES"));
7830 if (err)
7831 goto done;
7833 err = add_color(&s->colors, "^refs/got/backup/",
7834 TOG_COLOR_REFS_BACKUP,
7835 get_color_value("TOG_COLOR_REFS_BACKUP"));
7836 if (err)
7837 goto done;
7840 view->show = show_ref_view;
7841 view->input = input_ref_view;
7842 view->close = close_ref_view;
7843 view->search_start = search_start_ref_view;
7844 view->search_next = search_next_ref_view;
7845 done:
7846 if (err)
7847 free_colors(&s->colors);
7848 return err;
7851 static const struct got_error *
7852 close_ref_view(struct tog_view *view)
7854 struct tog_ref_view_state *s = &view->state.ref;
7856 ref_view_free_refs(s);
7857 free_colors(&s->colors);
7859 return NULL;
7862 static const struct got_error *
7863 resolve_reflist_entry(struct got_object_id **commit_id,
7864 struct tog_reflist_entry *re, struct got_repository *repo)
7866 const struct got_error *err = NULL;
7867 struct got_object_id *obj_id;
7868 struct got_tag_object *tag = NULL;
7869 int obj_type;
7871 *commit_id = NULL;
7873 err = got_ref_resolve(&obj_id, repo, re->ref);
7874 if (err)
7875 return err;
7877 err = got_object_get_type(&obj_type, repo, obj_id);
7878 if (err)
7879 goto done;
7881 switch (obj_type) {
7882 case GOT_OBJ_TYPE_COMMIT:
7883 *commit_id = obj_id;
7884 break;
7885 case GOT_OBJ_TYPE_TAG:
7886 err = got_object_open_as_tag(&tag, repo, obj_id);
7887 if (err)
7888 goto done;
7889 free(obj_id);
7890 err = got_object_get_type(&obj_type, repo,
7891 got_object_tag_get_object_id(tag));
7892 if (err)
7893 goto done;
7894 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7895 err = got_error(GOT_ERR_OBJ_TYPE);
7896 goto done;
7898 *commit_id = got_object_id_dup(
7899 got_object_tag_get_object_id(tag));
7900 if (*commit_id == NULL) {
7901 err = got_error_from_errno("got_object_id_dup");
7902 goto done;
7904 break;
7905 default:
7906 err = got_error(GOT_ERR_OBJ_TYPE);
7907 break;
7910 done:
7911 if (tag)
7912 got_object_tag_close(tag);
7913 if (err) {
7914 free(*commit_id);
7915 *commit_id = NULL;
7917 return err;
7920 static const struct got_error *
7921 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7922 struct tog_reflist_entry *re, struct got_repository *repo)
7924 struct tog_view *log_view;
7925 const struct got_error *err = NULL;
7926 struct got_object_id *commit_id = NULL;
7928 *new_view = NULL;
7930 err = resolve_reflist_entry(&commit_id, re, repo);
7931 if (err) {
7932 if (err->code != GOT_ERR_OBJ_TYPE)
7933 return err;
7934 else
7935 return NULL;
7938 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7939 if (log_view == NULL) {
7940 err = got_error_from_errno("view_open");
7941 goto done;
7944 err = open_log_view(log_view, commit_id, repo,
7945 got_ref_get_name(re->ref), "", 0);
7946 done:
7947 if (err)
7948 view_close(log_view);
7949 else
7950 *new_view = log_view;
7951 free(commit_id);
7952 return err;
7955 static void
7956 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7958 struct tog_reflist_entry *re;
7959 int i = 0;
7961 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7962 return;
7964 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7965 while (i++ < maxscroll) {
7966 if (re == NULL)
7967 break;
7968 s->first_displayed_entry = re;
7969 re = TAILQ_PREV(re, tog_reflist_head, entry);
7973 static const struct got_error *
7974 ref_scroll_down(struct tog_view *view, int maxscroll)
7976 struct tog_ref_view_state *s = &view->state.ref;
7977 struct tog_reflist_entry *next, *last;
7978 int n = 0;
7980 if (s->first_displayed_entry)
7981 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7982 else
7983 next = TAILQ_FIRST(&s->refs);
7985 last = s->last_displayed_entry;
7986 while (next && n++ < maxscroll) {
7987 if (last) {
7988 s->last_displayed_entry = last;
7989 last = TAILQ_NEXT(last, entry);
7991 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7992 s->first_displayed_entry = next;
7993 next = TAILQ_NEXT(next, entry);
7997 return NULL;
8000 static const struct got_error *
8001 search_start_ref_view(struct tog_view *view)
8003 struct tog_ref_view_state *s = &view->state.ref;
8005 s->matched_entry = NULL;
8006 return NULL;
8009 static int
8010 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8012 regmatch_t regmatch;
8014 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8015 0) == 0;
8018 static const struct got_error *
8019 search_next_ref_view(struct tog_view *view)
8021 struct tog_ref_view_state *s = &view->state.ref;
8022 struct tog_reflist_entry *re = NULL;
8024 if (!view->searching) {
8025 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8026 return NULL;
8029 if (s->matched_entry) {
8030 if (view->searching == TOG_SEARCH_FORWARD) {
8031 if (s->selected_entry)
8032 re = TAILQ_NEXT(s->selected_entry, entry);
8033 else
8034 re = TAILQ_PREV(s->selected_entry,
8035 tog_reflist_head, entry);
8036 } else {
8037 if (s->selected_entry == NULL)
8038 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8039 else
8040 re = TAILQ_PREV(s->selected_entry,
8041 tog_reflist_head, entry);
8043 } else {
8044 if (s->selected_entry)
8045 re = s->selected_entry;
8046 else if (view->searching == TOG_SEARCH_FORWARD)
8047 re = TAILQ_FIRST(&s->refs);
8048 else
8049 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8052 while (1) {
8053 if (re == NULL) {
8054 if (s->matched_entry == NULL) {
8055 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8056 return NULL;
8058 if (view->searching == TOG_SEARCH_FORWARD)
8059 re = TAILQ_FIRST(&s->refs);
8060 else
8061 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8064 if (match_reflist_entry(re, &view->regex)) {
8065 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8066 s->matched_entry = re;
8067 break;
8070 if (view->searching == TOG_SEARCH_FORWARD)
8071 re = TAILQ_NEXT(re, entry);
8072 else
8073 re = TAILQ_PREV(re, tog_reflist_head, entry);
8076 if (s->matched_entry) {
8077 s->first_displayed_entry = s->matched_entry;
8078 s->selected = 0;
8081 return NULL;
8084 static const struct got_error *
8085 show_ref_view(struct tog_view *view)
8087 const struct got_error *err = NULL;
8088 struct tog_ref_view_state *s = &view->state.ref;
8089 struct tog_reflist_entry *re;
8090 char *line = NULL;
8091 wchar_t *wline;
8092 struct tog_color *tc;
8093 int width, n, scrollx;
8094 int limit = view->nlines;
8096 werase(view->window);
8098 s->ndisplayed = 0;
8099 if (view_is_hsplit_top(view))
8100 --limit; /* border */
8102 if (limit == 0)
8103 return NULL;
8105 re = s->first_displayed_entry;
8107 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8108 s->nrefs) == -1)
8109 return got_error_from_errno("asprintf");
8111 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8112 if (err) {
8113 free(line);
8114 return err;
8116 if (view_needs_focus_indication(view))
8117 wstandout(view->window);
8118 waddwstr(view->window, wline);
8119 while (width++ < view->ncols)
8120 waddch(view->window, ' ');
8121 if (view_needs_focus_indication(view))
8122 wstandend(view->window);
8123 free(wline);
8124 wline = NULL;
8125 free(line);
8126 line = NULL;
8127 if (--limit <= 0)
8128 return NULL;
8130 n = 0;
8131 view->maxx = 0;
8132 while (re && limit > 0) {
8133 char *line = NULL;
8134 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8136 if (s->show_date) {
8137 struct got_commit_object *ci;
8138 struct got_tag_object *tag;
8139 struct got_object_id *id;
8140 struct tm tm;
8141 time_t t;
8143 err = got_ref_resolve(&id, s->repo, re->ref);
8144 if (err)
8145 return err;
8146 err = got_object_open_as_tag(&tag, s->repo, id);
8147 if (err) {
8148 if (err->code != GOT_ERR_OBJ_TYPE) {
8149 free(id);
8150 return err;
8152 err = got_object_open_as_commit(&ci, s->repo,
8153 id);
8154 if (err) {
8155 free(id);
8156 return err;
8158 t = got_object_commit_get_committer_time(ci);
8159 got_object_commit_close(ci);
8160 } else {
8161 t = got_object_tag_get_tagger_time(tag);
8162 got_object_tag_close(tag);
8164 free(id);
8165 if (gmtime_r(&t, &tm) == NULL)
8166 return got_error_from_errno("gmtime_r");
8167 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8168 return got_error(GOT_ERR_NO_SPACE);
8170 if (got_ref_is_symbolic(re->ref)) {
8171 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8172 ymd : "", got_ref_get_name(re->ref),
8173 got_ref_get_symref_target(re->ref)) == -1)
8174 return got_error_from_errno("asprintf");
8175 } else if (s->show_ids) {
8176 struct got_object_id *id;
8177 char *id_str;
8178 err = got_ref_resolve(&id, s->repo, re->ref);
8179 if (err)
8180 return err;
8181 err = got_object_id_str(&id_str, id);
8182 if (err) {
8183 free(id);
8184 return err;
8186 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8187 got_ref_get_name(re->ref), id_str) == -1) {
8188 err = got_error_from_errno("asprintf");
8189 free(id);
8190 free(id_str);
8191 return err;
8193 free(id);
8194 free(id_str);
8195 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8196 got_ref_get_name(re->ref)) == -1)
8197 return got_error_from_errno("asprintf");
8199 /* use full line width to determine view->maxx */
8200 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8201 if (err) {
8202 free(line);
8203 return err;
8205 view->maxx = MAX(view->maxx, width);
8206 free(wline);
8207 wline = NULL;
8209 err = format_line(&wline, &width, &scrollx, line, view->x,
8210 view->ncols, 0, 0);
8211 if (err) {
8212 free(line);
8213 return err;
8215 if (n == s->selected) {
8216 if (view->focussed)
8217 wstandout(view->window);
8218 s->selected_entry = re;
8220 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8221 if (tc)
8222 wattr_on(view->window,
8223 COLOR_PAIR(tc->colorpair), NULL);
8224 waddwstr(view->window, &wline[scrollx]);
8225 if (tc)
8226 wattr_off(view->window,
8227 COLOR_PAIR(tc->colorpair), NULL);
8228 if (width < view->ncols)
8229 waddch(view->window, '\n');
8230 if (n == s->selected && view->focussed)
8231 wstandend(view->window);
8232 free(line);
8233 free(wline);
8234 wline = NULL;
8235 n++;
8236 s->ndisplayed++;
8237 s->last_displayed_entry = re;
8239 limit--;
8240 re = TAILQ_NEXT(re, entry);
8243 view_border(view);
8244 return err;
8247 static const struct got_error *
8248 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8249 struct tog_reflist_entry *re, struct got_repository *repo)
8251 const struct got_error *err = NULL;
8252 struct got_object_id *commit_id = NULL;
8253 struct tog_view *tree_view;
8255 *new_view = NULL;
8257 err = resolve_reflist_entry(&commit_id, re, repo);
8258 if (err) {
8259 if (err->code != GOT_ERR_OBJ_TYPE)
8260 return err;
8261 else
8262 return NULL;
8266 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8267 if (tree_view == NULL) {
8268 err = got_error_from_errno("view_open");
8269 goto done;
8272 err = open_tree_view(tree_view, commit_id,
8273 got_ref_get_name(re->ref), repo);
8274 if (err)
8275 goto done;
8277 *new_view = tree_view;
8278 done:
8279 free(commit_id);
8280 return err;
8283 static const struct got_error *
8284 ref_goto_line(struct tog_view *view, int nlines)
8286 const struct got_error *err = NULL;
8287 struct tog_ref_view_state *s = &view->state.ref;
8288 int g, idx = s->selected_entry->idx;
8290 g = view->gline;
8291 view->gline = 0;
8293 if (g == 0)
8294 g = 1;
8295 else if (g > s->nrefs)
8296 g = s->nrefs;
8298 if (g >= s->first_displayed_entry->idx + 1 &&
8299 g <= s->last_displayed_entry->idx + 1 &&
8300 g - s->first_displayed_entry->idx - 1 < nlines) {
8301 s->selected = g - s->first_displayed_entry->idx - 1;
8302 return NULL;
8305 if (idx + 1 < g) {
8306 err = ref_scroll_down(view, g - idx - 1);
8307 if (err)
8308 return err;
8309 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8310 s->first_displayed_entry->idx + s->selected < g &&
8311 s->selected < s->ndisplayed - 1)
8312 s->selected = g - s->first_displayed_entry->idx - 1;
8313 } else if (idx + 1 > g)
8314 ref_scroll_up(s, idx - g + 1);
8316 if (g < nlines && s->first_displayed_entry->idx == 0)
8317 s->selected = g - 1;
8319 return NULL;
8323 static const struct got_error *
8324 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8326 const struct got_error *err = NULL;
8327 struct tog_ref_view_state *s = &view->state.ref;
8328 struct tog_reflist_entry *re;
8329 int n, nscroll = view->nlines - 1;
8331 if (view->gline)
8332 return ref_goto_line(view, nscroll);
8334 switch (ch) {
8335 case '0':
8336 case '$':
8337 case KEY_RIGHT:
8338 case 'l':
8339 case KEY_LEFT:
8340 case 'h':
8341 horizontal_scroll_input(view, ch);
8342 break;
8343 case 'i':
8344 s->show_ids = !s->show_ids;
8345 view->count = 0;
8346 break;
8347 case 'm':
8348 s->show_date = !s->show_date;
8349 view->count = 0;
8350 break;
8351 case 'o':
8352 s->sort_by_date = !s->sort_by_date;
8353 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8354 view->count = 0;
8355 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8356 got_ref_cmp_by_commit_timestamp_descending :
8357 tog_ref_cmp_by_name, s->repo);
8358 if (err)
8359 break;
8360 got_reflist_object_id_map_free(tog_refs_idmap);
8361 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8362 &tog_refs, s->repo);
8363 if (err)
8364 break;
8365 ref_view_free_refs(s);
8366 err = ref_view_load_refs(s);
8367 break;
8368 case KEY_ENTER:
8369 case '\r':
8370 view->count = 0;
8371 if (!s->selected_entry)
8372 break;
8373 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8374 break;
8375 case 'T':
8376 view->count = 0;
8377 if (!s->selected_entry)
8378 break;
8379 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8380 break;
8381 case 'g':
8382 case '=':
8383 case KEY_HOME:
8384 s->selected = 0;
8385 view->count = 0;
8386 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8387 break;
8388 case 'G':
8389 case '*':
8390 case KEY_END: {
8391 int eos = view->nlines - 1;
8393 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8394 --eos; /* border */
8395 s->selected = 0;
8396 view->count = 0;
8397 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8398 for (n = 0; n < eos; n++) {
8399 if (re == NULL)
8400 break;
8401 s->first_displayed_entry = re;
8402 re = TAILQ_PREV(re, tog_reflist_head, entry);
8404 if (n > 0)
8405 s->selected = n - 1;
8406 break;
8408 case 'k':
8409 case KEY_UP:
8410 case CTRL('p'):
8411 if (s->selected > 0) {
8412 s->selected--;
8413 break;
8415 ref_scroll_up(s, 1);
8416 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8417 view->count = 0;
8418 break;
8419 case CTRL('u'):
8420 case 'u':
8421 nscroll /= 2;
8422 /* FALL THROUGH */
8423 case KEY_PPAGE:
8424 case CTRL('b'):
8425 case 'b':
8426 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8427 s->selected -= MIN(nscroll, s->selected);
8428 ref_scroll_up(s, MAX(0, nscroll));
8429 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8430 view->count = 0;
8431 break;
8432 case 'j':
8433 case KEY_DOWN:
8434 case CTRL('n'):
8435 if (s->selected < s->ndisplayed - 1) {
8436 s->selected++;
8437 break;
8439 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8440 /* can't scroll any further */
8441 view->count = 0;
8442 break;
8444 ref_scroll_down(view, 1);
8445 break;
8446 case CTRL('d'):
8447 case 'd':
8448 nscroll /= 2;
8449 /* FALL THROUGH */
8450 case KEY_NPAGE:
8451 case CTRL('f'):
8452 case 'f':
8453 case ' ':
8454 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8455 /* can't scroll any further; move cursor down */
8456 if (s->selected < s->ndisplayed - 1)
8457 s->selected += MIN(nscroll,
8458 s->ndisplayed - s->selected - 1);
8459 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8460 s->selected += s->ndisplayed - s->selected - 1;
8461 view->count = 0;
8462 break;
8464 ref_scroll_down(view, nscroll);
8465 break;
8466 case CTRL('l'):
8467 view->count = 0;
8468 tog_free_refs();
8469 err = tog_load_refs(s->repo, s->sort_by_date);
8470 if (err)
8471 break;
8472 ref_view_free_refs(s);
8473 err = ref_view_load_refs(s);
8474 break;
8475 case KEY_RESIZE:
8476 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8477 s->selected = view->nlines - 2;
8478 break;
8479 default:
8480 view->count = 0;
8481 break;
8484 return err;
8487 __dead static void
8488 usage_ref(void)
8490 endwin();
8491 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8492 getprogname());
8493 exit(1);
8496 static const struct got_error *
8497 cmd_ref(int argc, char *argv[])
8499 const struct got_error *error;
8500 struct got_repository *repo = NULL;
8501 struct got_worktree *worktree = NULL;
8502 char *cwd = NULL, *repo_path = NULL;
8503 int ch;
8504 struct tog_view *view;
8505 int *pack_fds = NULL;
8507 while ((ch = getopt(argc, argv, "r:")) != -1) {
8508 switch (ch) {
8509 case 'r':
8510 repo_path = realpath(optarg, NULL);
8511 if (repo_path == NULL)
8512 return got_error_from_errno2("realpath",
8513 optarg);
8514 break;
8515 default:
8516 usage_ref();
8517 /* NOTREACHED */
8521 argc -= optind;
8522 argv += optind;
8524 if (argc > 1)
8525 usage_ref();
8527 error = got_repo_pack_fds_open(&pack_fds);
8528 if (error != NULL)
8529 goto done;
8531 if (repo_path == NULL) {
8532 cwd = getcwd(NULL, 0);
8533 if (cwd == NULL)
8534 return got_error_from_errno("getcwd");
8535 error = got_worktree_open(&worktree, cwd);
8536 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8537 goto done;
8538 if (worktree)
8539 repo_path =
8540 strdup(got_worktree_get_repo_path(worktree));
8541 else
8542 repo_path = strdup(cwd);
8543 if (repo_path == NULL) {
8544 error = got_error_from_errno("strdup");
8545 goto done;
8549 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8550 if (error != NULL)
8551 goto done;
8553 init_curses();
8555 error = apply_unveil(got_repo_get_path(repo), NULL);
8556 if (error)
8557 goto done;
8559 error = tog_load_refs(repo, 0);
8560 if (error)
8561 goto done;
8563 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8564 if (view == NULL) {
8565 error = got_error_from_errno("view_open");
8566 goto done;
8569 error = open_ref_view(view, repo);
8570 if (error)
8571 goto done;
8573 if (worktree) {
8574 /* Release work tree lock. */
8575 got_worktree_close(worktree);
8576 worktree = NULL;
8578 error = view_loop(view);
8579 done:
8580 free(repo_path);
8581 free(cwd);
8582 if (repo) {
8583 const struct got_error *close_err = got_repo_close(repo);
8584 if (close_err)
8585 error = close_err;
8587 if (pack_fds) {
8588 const struct got_error *pack_err =
8589 got_repo_pack_fds_close(pack_fds);
8590 if (error == NULL)
8591 error = pack_err;
8593 tog_free_refs();
8594 return error;
8597 static const struct got_error*
8598 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8599 const char *str)
8601 size_t len;
8603 if (win == NULL)
8604 win = stdscr;
8606 len = strlen(str);
8607 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8609 if (focus)
8610 wstandout(win);
8611 if (mvwprintw(win, y, x, "%s", str) == ERR)
8612 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8613 if (focus)
8614 wstandend(win);
8616 return NULL;
8619 static const struct got_error *
8620 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8622 off_t *p;
8624 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8625 if (p == NULL) {
8626 free(*line_offsets);
8627 *line_offsets = NULL;
8628 return got_error_from_errno("reallocarray");
8631 *line_offsets = p;
8632 (*line_offsets)[*nlines] = off;
8633 ++(*nlines);
8634 return NULL;
8637 static const struct got_error *
8638 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8640 *ret = 0;
8642 for (;n > 0; --n, ++km) {
8643 char *t0, *t, *k;
8644 size_t len = 1;
8646 if (km->keys == NULL)
8647 continue;
8649 t = t0 = strdup(km->keys);
8650 if (t0 == NULL)
8651 return got_error_from_errno("strdup");
8653 len += strlen(t);
8654 while ((k = strsep(&t, " ")) != NULL)
8655 len += strlen(k) > 1 ? 2 : 0;
8656 free(t0);
8657 *ret = MAX(*ret, len);
8660 return NULL;
8664 * Write keymap section headers, keys, and key info in km to f.
8665 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8666 * wrap control and symbolic keys in guillemets, else use <>.
8668 static const struct got_error *
8669 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8671 int n, len = width;
8673 if (km->keys) {
8674 static const char *u8_glyph[] = {
8675 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8676 "\xe2\x80\xba" /* U+203A (utf8 >) */
8678 char *t0, *t, *k;
8679 int cs, s, first = 1;
8681 cs = got_locale_is_utf8();
8683 t = t0 = strdup(km->keys);
8684 if (t0 == NULL)
8685 return got_error_from_errno("strdup");
8687 len = strlen(km->keys);
8688 while ((k = strsep(&t, " ")) != NULL) {
8689 s = strlen(k) > 1; /* control or symbolic key */
8690 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8691 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8692 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8693 if (n < 0) {
8694 free(t0);
8695 return got_error_from_errno("fprintf");
8697 first = 0;
8698 len += s ? 2 : 0;
8699 *off += n;
8701 free(t0);
8703 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8704 if (n < 0)
8705 return got_error_from_errno("fprintf");
8706 *off += n;
8708 return NULL;
8711 static const struct got_error *
8712 format_help(struct tog_help_view_state *s)
8714 const struct got_error *err = NULL;
8715 off_t off = 0;
8716 int i, max, n, show = s->all;
8717 static const struct tog_key_map km[] = {
8718 #define KEYMAP_(info, type) { NULL, (info), type }
8719 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8720 GENERATE_HELP
8721 #undef KEYMAP_
8722 #undef KEY_
8725 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8726 if (err)
8727 return err;
8729 n = nitems(km);
8730 err = max_key_str(&max, km, n);
8731 if (err)
8732 return err;
8734 for (i = 0; i < n; ++i) {
8735 if (km[i].keys == NULL) {
8736 show = s->all;
8737 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8738 km[i].type == s->type || s->all)
8739 show = 1;
8741 if (show) {
8742 err = format_help_line(&off, s->f, &km[i], max);
8743 if (err)
8744 return err;
8745 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8746 if (err)
8747 return err;
8750 fputc('\n', s->f);
8751 ++off;
8752 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8753 return err;
8756 static const struct got_error *
8757 create_help(struct tog_help_view_state *s)
8759 FILE *f;
8760 const struct got_error *err;
8762 free(s->line_offsets);
8763 s->line_offsets = NULL;
8764 s->nlines = 0;
8766 f = got_opentemp();
8767 if (f == NULL)
8768 return got_error_from_errno("got_opentemp");
8769 s->f = f;
8771 err = format_help(s);
8772 if (err)
8773 return err;
8775 if (s->f && fflush(s->f) != 0)
8776 return got_error_from_errno("fflush");
8778 return NULL;
8781 static const struct got_error *
8782 search_start_help_view(struct tog_view *view)
8784 view->state.help.matched_line = 0;
8785 return NULL;
8788 static void
8789 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8790 size_t *nlines, int **first, int **last, int **match, int **selected)
8792 struct tog_help_view_state *s = &view->state.help;
8794 *f = s->f;
8795 *nlines = s->nlines;
8796 *line_offsets = s->line_offsets;
8797 *match = &s->matched_line;
8798 *first = &s->first_displayed_line;
8799 *last = &s->last_displayed_line;
8800 *selected = &s->selected_line;
8803 static const struct got_error *
8804 show_help_view(struct tog_view *view)
8806 struct tog_help_view_state *s = &view->state.help;
8807 const struct got_error *err;
8808 regmatch_t *regmatch = &view->regmatch;
8809 wchar_t *wline;
8810 char *line;
8811 ssize_t linelen;
8812 size_t linesz = 0;
8813 int width, nprinted = 0, rc = 0;
8814 int eos = view->nlines;
8816 if (view_is_hsplit_top(view))
8817 --eos; /* account for border */
8819 s->lineno = 0;
8820 rewind(s->f);
8821 werase(view->window);
8823 if (view->gline > s->nlines - 1)
8824 view->gline = s->nlines - 1;
8826 err = win_draw_center(view->window, 0, 0, view->ncols,
8827 view_needs_focus_indication(view),
8828 "tog help (press q to return to tog)");
8829 if (err)
8830 return err;
8831 if (eos <= 1)
8832 return NULL;
8833 waddstr(view->window, "\n\n");
8834 eos -= 2;
8836 s->eof = 0;
8837 view->maxx = 0;
8838 line = NULL;
8839 while (eos > 0 && nprinted < eos) {
8840 attr_t attr = 0;
8842 linelen = getline(&line, &linesz, s->f);
8843 if (linelen == -1) {
8844 if (!feof(s->f)) {
8845 free(line);
8846 return got_ferror(s->f, GOT_ERR_IO);
8848 s->eof = 1;
8849 break;
8851 if (++s->lineno < s->first_displayed_line)
8852 continue;
8853 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8854 continue;
8855 if (s->lineno == view->hiline)
8856 attr = A_STANDOUT;
8858 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8859 view->x ? 1 : 0);
8860 if (err) {
8861 free(line);
8862 return err;
8864 view->maxx = MAX(view->maxx, width);
8865 free(wline);
8866 wline = NULL;
8868 if (attr)
8869 wattron(view->window, attr);
8870 if (s->first_displayed_line + nprinted == s->matched_line &&
8871 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8872 err = add_matched_line(&width, line, view->ncols - 1, 0,
8873 view->window, view->x, regmatch);
8874 if (err) {
8875 free(line);
8876 return err;
8878 } else {
8879 int skip;
8881 err = format_line(&wline, &width, &skip, line,
8882 view->x, view->ncols, 0, view->x ? 1 : 0);
8883 if (err) {
8884 free(line);
8885 return err;
8887 waddwstr(view->window, &wline[skip]);
8888 free(wline);
8889 wline = NULL;
8891 if (s->lineno == view->hiline) {
8892 while (width++ < view->ncols)
8893 waddch(view->window, ' ');
8894 } else {
8895 if (width < view->ncols)
8896 waddch(view->window, '\n');
8898 if (attr)
8899 wattroff(view->window, attr);
8900 if (++nprinted == 1)
8901 s->first_displayed_line = s->lineno;
8903 free(line);
8904 if (nprinted > 0)
8905 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8906 else
8907 s->last_displayed_line = s->first_displayed_line;
8909 view_border(view);
8911 if (s->eof) {
8912 rc = waddnstr(view->window,
8913 "See the tog(1) manual page for full documentation",
8914 view->ncols - 1);
8915 if (rc == ERR)
8916 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8917 } else {
8918 wmove(view->window, view->nlines - 1, 0);
8919 wclrtoeol(view->window);
8920 wstandout(view->window);
8921 rc = waddnstr(view->window, "scroll down for more...",
8922 view->ncols - 1);
8923 if (rc == ERR)
8924 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8925 if (getcurx(view->window) < view->ncols - 6) {
8926 rc = wprintw(view->window, "[%.0f%%]",
8927 100.00 * s->last_displayed_line / s->nlines);
8928 if (rc == ERR)
8929 return got_error_msg(GOT_ERR_IO, "wprintw");
8931 wstandend(view->window);
8934 return NULL;
8937 static const struct got_error *
8938 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8940 struct tog_help_view_state *s = &view->state.help;
8941 const struct got_error *err = NULL;
8942 char *line = NULL;
8943 ssize_t linelen;
8944 size_t linesz = 0;
8945 int eos, nscroll;
8947 eos = nscroll = view->nlines;
8948 if (view_is_hsplit_top(view))
8949 --eos; /* border */
8951 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8953 switch (ch) {
8954 case '0':
8955 case '$':
8956 case KEY_RIGHT:
8957 case 'l':
8958 case KEY_LEFT:
8959 case 'h':
8960 horizontal_scroll_input(view, ch);
8961 break;
8962 case 'g':
8963 case KEY_HOME:
8964 s->first_displayed_line = 1;
8965 view->count = 0;
8966 break;
8967 case 'G':
8968 case KEY_END:
8969 view->count = 0;
8970 if (s->eof)
8971 break;
8972 s->first_displayed_line = (s->nlines - eos) + 3;
8973 s->eof = 1;
8974 break;
8975 case 'k':
8976 case KEY_UP:
8977 if (s->first_displayed_line > 1)
8978 --s->first_displayed_line;
8979 else
8980 view->count = 0;
8981 break;
8982 case CTRL('u'):
8983 case 'u':
8984 nscroll /= 2;
8985 /* FALL THROUGH */
8986 case KEY_PPAGE:
8987 case CTRL('b'):
8988 case 'b':
8989 if (s->first_displayed_line == 1) {
8990 view->count = 0;
8991 break;
8993 while (--nscroll > 0 && s->first_displayed_line > 1)
8994 s->first_displayed_line--;
8995 break;
8996 case 'j':
8997 case KEY_DOWN:
8998 case CTRL('n'):
8999 if (!s->eof)
9000 ++s->first_displayed_line;
9001 else
9002 view->count = 0;
9003 break;
9004 case CTRL('d'):
9005 case 'd':
9006 nscroll /= 2;
9007 /* FALL THROUGH */
9008 case KEY_NPAGE:
9009 case CTRL('f'):
9010 case 'f':
9011 case ' ':
9012 if (s->eof) {
9013 view->count = 0;
9014 break;
9016 while (!s->eof && --nscroll > 0) {
9017 linelen = getline(&line, &linesz, s->f);
9018 s->first_displayed_line++;
9019 if (linelen == -1) {
9020 if (feof(s->f))
9021 s->eof = 1;
9022 else
9023 err = got_ferror(s->f, GOT_ERR_IO);
9024 break;
9027 free(line);
9028 break;
9029 default:
9030 view->count = 0;
9031 break;
9034 return err;
9037 static const struct got_error *
9038 close_help_view(struct tog_view *view)
9040 struct tog_help_view_state *s = &view->state.help;
9042 free(s->line_offsets);
9043 s->line_offsets = NULL;
9044 if (fclose(s->f) == EOF)
9045 return got_error_from_errno("fclose");
9047 return NULL;
9050 static const struct got_error *
9051 reset_help_view(struct tog_view *view)
9053 struct tog_help_view_state *s = &view->state.help;
9056 if (s->f && fclose(s->f) == EOF)
9057 return got_error_from_errno("fclose");
9059 wclear(view->window);
9060 view->count = 0;
9061 view->x = 0;
9062 s->all = !s->all;
9063 s->first_displayed_line = 1;
9064 s->last_displayed_line = view->nlines;
9065 s->matched_line = 0;
9067 return create_help(s);
9070 static const struct got_error *
9071 open_help_view(struct tog_view *view, struct tog_view *parent)
9073 const struct got_error *err = NULL;
9074 struct tog_help_view_state *s = &view->state.help;
9076 s->type = (enum tog_keymap_type)parent->type;
9077 s->first_displayed_line = 1;
9078 s->last_displayed_line = view->nlines;
9079 s->selected_line = 1;
9081 view->show = show_help_view;
9082 view->input = input_help_view;
9083 view->reset = reset_help_view;
9084 view->close = close_help_view;
9085 view->search_start = search_start_help_view;
9086 view->search_setup = search_setup_help_view;
9087 view->search_next = search_next_view_match;
9089 err = create_help(s);
9090 return err;
9093 static const struct got_error *
9094 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9095 enum tog_view_type request, int y, int x)
9097 const struct got_error *err = NULL;
9099 *new_view = NULL;
9101 switch (request) {
9102 case TOG_VIEW_DIFF:
9103 if (view->type == TOG_VIEW_LOG) {
9104 struct tog_log_view_state *s = &view->state.log;
9106 err = open_diff_view_for_commit(new_view, y, x,
9107 s->selected_entry->commit, s->selected_entry->id,
9108 view, s->repo);
9109 } else
9110 return got_error_msg(GOT_ERR_NOT_IMPL,
9111 "parent/child view pair not supported");
9112 break;
9113 case TOG_VIEW_BLAME:
9114 if (view->type == TOG_VIEW_TREE) {
9115 struct tog_tree_view_state *s = &view->state.tree;
9117 err = blame_tree_entry(new_view, y, x,
9118 s->selected_entry, &s->parents, s->commit_id,
9119 s->repo);
9120 } else
9121 return got_error_msg(GOT_ERR_NOT_IMPL,
9122 "parent/child view pair not supported");
9123 break;
9124 case TOG_VIEW_LOG:
9125 if (view->type == TOG_VIEW_BLAME)
9126 err = log_annotated_line(new_view, y, x,
9127 view->state.blame.repo, view->state.blame.id_to_log);
9128 else if (view->type == TOG_VIEW_TREE)
9129 err = log_selected_tree_entry(new_view, y, x,
9130 &view->state.tree);
9131 else if (view->type == TOG_VIEW_REF)
9132 err = log_ref_entry(new_view, y, x,
9133 view->state.ref.selected_entry,
9134 view->state.ref.repo);
9135 else
9136 return got_error_msg(GOT_ERR_NOT_IMPL,
9137 "parent/child view pair not supported");
9138 break;
9139 case TOG_VIEW_TREE:
9140 if (view->type == TOG_VIEW_LOG)
9141 err = browse_commit_tree(new_view, y, x,
9142 view->state.log.selected_entry,
9143 view->state.log.in_repo_path,
9144 view->state.log.head_ref_name,
9145 view->state.log.repo);
9146 else if (view->type == TOG_VIEW_REF)
9147 err = browse_ref_tree(new_view, y, x,
9148 view->state.ref.selected_entry,
9149 view->state.ref.repo);
9150 else
9151 return got_error_msg(GOT_ERR_NOT_IMPL,
9152 "parent/child view pair not supported");
9153 break;
9154 case TOG_VIEW_REF:
9155 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9156 if (*new_view == NULL)
9157 return got_error_from_errno("view_open");
9158 if (view->type == TOG_VIEW_LOG)
9159 err = open_ref_view(*new_view, view->state.log.repo);
9160 else if (view->type == TOG_VIEW_TREE)
9161 err = open_ref_view(*new_view, view->state.tree.repo);
9162 else
9163 err = got_error_msg(GOT_ERR_NOT_IMPL,
9164 "parent/child view pair not supported");
9165 if (err)
9166 view_close(*new_view);
9167 break;
9168 case TOG_VIEW_HELP:
9169 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9170 if (*new_view == NULL)
9171 return got_error_from_errno("view_open");
9172 err = open_help_view(*new_view, view);
9173 if (err)
9174 view_close(*new_view);
9175 break;
9176 default:
9177 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9180 return err;
9184 * If view was scrolled down to move the selected line into view when opening a
9185 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9187 static void
9188 offset_selection_up(struct tog_view *view)
9190 switch (view->type) {
9191 case TOG_VIEW_BLAME: {
9192 struct tog_blame_view_state *s = &view->state.blame;
9193 if (s->first_displayed_line == 1) {
9194 s->selected_line = MAX(s->selected_line - view->offset,
9195 1);
9196 break;
9198 if (s->first_displayed_line > view->offset)
9199 s->first_displayed_line -= view->offset;
9200 else
9201 s->first_displayed_line = 1;
9202 s->selected_line += view->offset;
9203 break;
9205 case TOG_VIEW_LOG:
9206 log_scroll_up(&view->state.log, view->offset);
9207 view->state.log.selected += view->offset;
9208 break;
9209 case TOG_VIEW_REF:
9210 ref_scroll_up(&view->state.ref, view->offset);
9211 view->state.ref.selected += view->offset;
9212 break;
9213 case TOG_VIEW_TREE:
9214 tree_scroll_up(&view->state.tree, view->offset);
9215 view->state.tree.selected += view->offset;
9216 break;
9217 default:
9218 break;
9221 view->offset = 0;
9225 * If the selected line is in the section of screen covered by the bottom split,
9226 * scroll down offset lines to move it into view and index its new position.
9228 static const struct got_error *
9229 offset_selection_down(struct tog_view *view)
9231 const struct got_error *err = NULL;
9232 const struct got_error *(*scrolld)(struct tog_view *, int);
9233 int *selected = NULL;
9234 int header, offset;
9236 switch (view->type) {
9237 case TOG_VIEW_BLAME: {
9238 struct tog_blame_view_state *s = &view->state.blame;
9239 header = 3;
9240 scrolld = NULL;
9241 if (s->selected_line > view->nlines - header) {
9242 offset = abs(view->nlines - s->selected_line - header);
9243 s->first_displayed_line += offset;
9244 s->selected_line -= offset;
9245 view->offset = offset;
9247 break;
9249 case TOG_VIEW_LOG: {
9250 struct tog_log_view_state *s = &view->state.log;
9251 scrolld = &log_scroll_down;
9252 header = view_is_parent_view(view) ? 3 : 2;
9253 selected = &s->selected;
9254 break;
9256 case TOG_VIEW_REF: {
9257 struct tog_ref_view_state *s = &view->state.ref;
9258 scrolld = &ref_scroll_down;
9259 header = 3;
9260 selected = &s->selected;
9261 break;
9263 case TOG_VIEW_TREE: {
9264 struct tog_tree_view_state *s = &view->state.tree;
9265 scrolld = &tree_scroll_down;
9266 header = 5;
9267 selected = &s->selected;
9268 break;
9270 default:
9271 selected = NULL;
9272 scrolld = NULL;
9273 header = 0;
9274 break;
9277 if (selected && *selected > view->nlines - header) {
9278 offset = abs(view->nlines - *selected - header);
9279 view->offset = offset;
9280 if (scrolld && offset) {
9281 err = scrolld(view, offset);
9282 *selected -= offset;
9286 return err;
9289 static void
9290 list_commands(FILE *fp)
9292 size_t i;
9294 fprintf(fp, "commands:");
9295 for (i = 0; i < nitems(tog_commands); i++) {
9296 const struct tog_cmd *cmd = &tog_commands[i];
9297 fprintf(fp, " %s", cmd->name);
9299 fputc('\n', fp);
9302 __dead static void
9303 usage(int hflag, int status)
9305 FILE *fp = (status == 0) ? stdout : stderr;
9307 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9308 getprogname());
9309 if (hflag) {
9310 fprintf(fp, "lazy usage: %s path\n", getprogname());
9311 list_commands(fp);
9313 exit(status);
9316 static char **
9317 make_argv(int argc, ...)
9319 va_list ap;
9320 char **argv;
9321 int i;
9323 va_start(ap, argc);
9325 argv = calloc(argc, sizeof(char *));
9326 if (argv == NULL)
9327 err(1, "calloc");
9328 for (i = 0; i < argc; i++) {
9329 argv[i] = strdup(va_arg(ap, char *));
9330 if (argv[i] == NULL)
9331 err(1, "strdup");
9334 va_end(ap);
9335 return argv;
9339 * Try to convert 'tog path' into a 'tog log path' command.
9340 * The user could simply have mistyped the command rather than knowingly
9341 * provided a path. So check whether argv[0] can in fact be resolved
9342 * to a path in the HEAD commit and print a special error if not.
9343 * This hack is for mpi@ <3
9345 static const struct got_error *
9346 tog_log_with_path(int argc, char *argv[])
9348 const struct got_error *error = NULL, *close_err;
9349 const struct tog_cmd *cmd = NULL;
9350 struct got_repository *repo = NULL;
9351 struct got_worktree *worktree = NULL;
9352 struct got_object_id *commit_id = NULL, *id = NULL;
9353 struct got_commit_object *commit = NULL;
9354 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9355 char *commit_id_str = NULL, **cmd_argv = NULL;
9356 int *pack_fds = NULL;
9358 cwd = getcwd(NULL, 0);
9359 if (cwd == NULL)
9360 return got_error_from_errno("getcwd");
9362 error = got_repo_pack_fds_open(&pack_fds);
9363 if (error != NULL)
9364 goto done;
9366 error = got_worktree_open(&worktree, cwd);
9367 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9368 goto done;
9370 if (worktree)
9371 repo_path = strdup(got_worktree_get_repo_path(worktree));
9372 else
9373 repo_path = strdup(cwd);
9374 if (repo_path == NULL) {
9375 error = got_error_from_errno("strdup");
9376 goto done;
9379 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9380 if (error != NULL)
9381 goto done;
9383 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9384 repo, worktree);
9385 if (error)
9386 goto done;
9388 error = tog_load_refs(repo, 0);
9389 if (error)
9390 goto done;
9391 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9392 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9393 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9394 if (error)
9395 goto done;
9397 if (worktree) {
9398 got_worktree_close(worktree);
9399 worktree = NULL;
9402 error = got_object_open_as_commit(&commit, repo, commit_id);
9403 if (error)
9404 goto done;
9406 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9407 if (error) {
9408 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9409 goto done;
9410 fprintf(stderr, "%s: '%s' is no known command or path\n",
9411 getprogname(), argv[0]);
9412 usage(1, 1);
9413 /* not reached */
9416 error = got_object_id_str(&commit_id_str, commit_id);
9417 if (error)
9418 goto done;
9420 cmd = &tog_commands[0]; /* log */
9421 argc = 4;
9422 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9423 error = cmd->cmd_main(argc, cmd_argv);
9424 done:
9425 if (repo) {
9426 close_err = got_repo_close(repo);
9427 if (error == NULL)
9428 error = close_err;
9430 if (commit)
9431 got_object_commit_close(commit);
9432 if (worktree)
9433 got_worktree_close(worktree);
9434 if (pack_fds) {
9435 const struct got_error *pack_err =
9436 got_repo_pack_fds_close(pack_fds);
9437 if (error == NULL)
9438 error = pack_err;
9440 free(id);
9441 free(commit_id_str);
9442 free(commit_id);
9443 free(cwd);
9444 free(repo_path);
9445 free(in_repo_path);
9446 if (cmd_argv) {
9447 int i;
9448 for (i = 0; i < argc; i++)
9449 free(cmd_argv[i]);
9450 free(cmd_argv);
9452 tog_free_refs();
9453 return error;
9456 int
9457 main(int argc, char *argv[])
9459 const struct got_error *error = NULL;
9460 const struct tog_cmd *cmd = NULL;
9461 int ch, hflag = 0, Vflag = 0;
9462 char **cmd_argv = NULL;
9463 static const struct option longopts[] = {
9464 { "version", no_argument, NULL, 'V' },
9465 { NULL, 0, NULL, 0}
9467 char *diff_algo_str = NULL;
9469 setlocale(LC_CTYPE, "");
9471 #ifndef PROFILE
9472 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9473 NULL) == -1)
9474 err(1, "pledge");
9475 #endif
9477 if (!isatty(STDIN_FILENO))
9478 errx(1, "standard input is not a tty");
9480 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9481 switch (ch) {
9482 case 'h':
9483 hflag = 1;
9484 break;
9485 case 'V':
9486 Vflag = 1;
9487 break;
9488 default:
9489 usage(hflag, 1);
9490 /* NOTREACHED */
9494 argc -= optind;
9495 argv += optind;
9496 optind = 1;
9497 optreset = 1;
9499 if (Vflag) {
9500 got_version_print_str();
9501 return 0;
9504 if (argc == 0) {
9505 if (hflag)
9506 usage(hflag, 0);
9507 /* Build an argument vector which runs a default command. */
9508 cmd = &tog_commands[0];
9509 argc = 1;
9510 cmd_argv = make_argv(argc, cmd->name);
9511 } else {
9512 size_t i;
9514 /* Did the user specify a command? */
9515 for (i = 0; i < nitems(tog_commands); i++) {
9516 if (strncmp(tog_commands[i].name, argv[0],
9517 strlen(argv[0])) == 0) {
9518 cmd = &tog_commands[i];
9519 break;
9524 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9525 if (diff_algo_str) {
9526 if (strcasecmp(diff_algo_str, "patience") == 0)
9527 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9528 if (strcasecmp(diff_algo_str, "myers") == 0)
9529 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9532 if (cmd == NULL) {
9533 if (argc != 1)
9534 usage(0, 1);
9535 /* No command specified; try log with a path */
9536 error = tog_log_with_path(argc, argv);
9537 } else {
9538 if (hflag)
9539 cmd->cmd_usage();
9540 else
9541 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9544 endwin();
9545 if (cmd_argv) {
9546 int i;
9547 for (i = 0; i < argc; i++)
9548 free(cmd_argv[i]);
9549 free(cmd_argv);
9552 if (error && error->code != GOT_ERR_CANCELLED &&
9553 error->code != GOT_ERR_EOF &&
9554 error->code != GOT_ERR_PRIVSEP_EXIT &&
9555 error->code != GOT_ERR_PRIVSEP_PIPE &&
9556 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9557 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9558 return 0;