Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <sha2.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_diff.h"
51 #include "got_opentemp.h"
52 #include "got_utf8.h"
53 #include "got_cancel.h"
54 #include "got_commit_graph.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_path.h"
58 #include "got_worktree.h"
60 #ifndef MIN
61 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
62 #endif
64 #ifndef MAX
65 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
66 #endif
68 #define CTRL(x) ((x) & 0x1f)
70 #ifndef nitems
71 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
72 #endif
74 struct tog_cmd {
75 const char *name;
76 const struct got_error *(*cmd_main)(int, char *[]);
77 void (*cmd_usage)(void);
78 };
80 __dead static void usage(int, int);
81 __dead static void usage_log(void);
82 __dead static void usage_diff(void);
83 __dead static void usage_blame(void);
84 __dead static void usage_tree(void);
85 __dead static void usage_ref(void);
87 static const struct got_error* cmd_log(int, char *[]);
88 static const struct got_error* cmd_diff(int, char *[]);
89 static const struct got_error* cmd_blame(int, char *[]);
90 static const struct got_error* cmd_tree(int, char *[]);
91 static const struct got_error* cmd_ref(int, char *[]);
93 static const struct tog_cmd tog_commands[] = {
94 { "log", cmd_log, usage_log },
95 { "diff", cmd_diff, usage_diff },
96 { "blame", cmd_blame, usage_blame },
97 { "tree", cmd_tree, usage_tree },
98 { "ref", cmd_ref, usage_ref },
99 };
101 enum tog_view_type {
102 TOG_VIEW_DIFF,
103 TOG_VIEW_LOG,
104 TOG_VIEW_BLAME,
105 TOG_VIEW_TREE,
106 TOG_VIEW_REF,
107 TOG_VIEW_HELP
108 };
110 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
111 enum tog_keymap_type {
112 TOG_KEYMAP_KEYS = -2,
113 TOG_KEYMAP_GLOBAL,
114 TOG_KEYMAP_DIFF,
115 TOG_KEYMAP_LOG,
116 TOG_KEYMAP_BLAME,
117 TOG_KEYMAP_TREE,
118 TOG_KEYMAP_REF,
119 TOG_KEYMAP_HELP
120 };
122 enum tog_view_mode {
123 TOG_VIEW_SPLIT_NONE,
124 TOG_VIEW_SPLIT_VERT,
125 TOG_VIEW_SPLIT_HRZN
126 };
128 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
130 #define TOG_EOF_STRING "(END)"
132 struct commit_queue_entry {
133 TAILQ_ENTRY(commit_queue_entry) entry;
134 struct got_object_id *id;
135 struct got_commit_object *commit;
136 int idx;
137 };
138 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
139 struct commit_queue {
140 int ncommits;
141 struct commit_queue_head head;
142 };
144 struct tog_color {
145 STAILQ_ENTRY(tog_color) entry;
146 regex_t regex;
147 short colorpair;
148 };
149 STAILQ_HEAD(tog_colors, tog_color);
151 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
152 static struct got_reflist_object_id_map *tog_refs_idmap;
153 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
155 static const struct got_error *
156 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
157 struct got_reference* re2)
159 const char *name1 = got_ref_get_name(re1);
160 const char *name2 = got_ref_get_name(re2);
161 int isbackup1, isbackup2;
163 /* Sort backup refs towards the bottom of the list. */
164 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
165 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
166 if (!isbackup1 && isbackup2) {
167 *cmp = -1;
168 return NULL;
169 } else if (isbackup1 && !isbackup2) {
170 *cmp = 1;
171 return NULL;
174 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
175 return NULL;
178 static const struct got_error *
179 tog_load_refs(struct got_repository *repo, int sort_by_date)
181 const struct got_error *err;
183 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
184 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
185 repo);
186 if (err)
187 return err;
189 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
190 repo);
193 static void
194 tog_free_refs(void)
196 if (tog_refs_idmap) {
197 got_reflist_object_id_map_free(tog_refs_idmap);
198 tog_refs_idmap = NULL;
200 got_ref_list_free(&tog_refs);
203 static const struct got_error *
204 add_color(struct tog_colors *colors, const char *pattern,
205 int idx, short color)
207 const struct got_error *err = NULL;
208 struct tog_color *tc;
209 int regerr = 0;
211 if (idx < 1 || idx > COLOR_PAIRS - 1)
212 return NULL;
214 init_pair(idx, color, -1);
216 tc = calloc(1, sizeof(*tc));
217 if (tc == NULL)
218 return got_error_from_errno("calloc");
219 regerr = regcomp(&tc->regex, pattern,
220 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
221 if (regerr) {
222 static char regerr_msg[512];
223 static char err_msg[512];
224 regerror(regerr, &tc->regex, regerr_msg,
225 sizeof(regerr_msg));
226 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
227 regerr_msg);
228 err = got_error_msg(GOT_ERR_REGEX, err_msg);
229 free(tc);
230 return err;
232 tc->colorpair = idx;
233 STAILQ_INSERT_HEAD(colors, tc, entry);
234 return NULL;
237 static void
238 free_colors(struct tog_colors *colors)
240 struct tog_color *tc;
242 while (!STAILQ_EMPTY(colors)) {
243 tc = STAILQ_FIRST(colors);
244 STAILQ_REMOVE_HEAD(colors, entry);
245 regfree(&tc->regex);
246 free(tc);
250 static struct tog_color *
251 get_color(struct tog_colors *colors, int colorpair)
253 struct tog_color *tc = NULL;
255 STAILQ_FOREACH(tc, colors, entry) {
256 if (tc->colorpair == colorpair)
257 return tc;
260 return NULL;
263 static int
264 default_color_value(const char *envvar)
266 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
267 return COLOR_MAGENTA;
268 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
269 return COLOR_CYAN;
270 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
271 return COLOR_YELLOW;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
273 return COLOR_GREEN;
274 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
275 return COLOR_MAGENTA;
276 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
279 return COLOR_CYAN;
280 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
281 return COLOR_GREEN;
282 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
283 return COLOR_GREEN;
284 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
285 return COLOR_CYAN;
286 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
287 return COLOR_YELLOW;
288 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
289 return COLOR_GREEN;
290 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
291 return COLOR_MAGENTA;
292 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
293 return COLOR_YELLOW;
294 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
295 return COLOR_CYAN;
297 return -1;
300 static int
301 get_color_value(const char *envvar)
303 const char *val = getenv(envvar);
305 if (val == NULL)
306 return default_color_value(envvar);
308 if (strcasecmp(val, "black") == 0)
309 return COLOR_BLACK;
310 if (strcasecmp(val, "red") == 0)
311 return COLOR_RED;
312 if (strcasecmp(val, "green") == 0)
313 return COLOR_GREEN;
314 if (strcasecmp(val, "yellow") == 0)
315 return COLOR_YELLOW;
316 if (strcasecmp(val, "blue") == 0)
317 return COLOR_BLUE;
318 if (strcasecmp(val, "magenta") == 0)
319 return COLOR_MAGENTA;
320 if (strcasecmp(val, "cyan") == 0)
321 return COLOR_CYAN;
322 if (strcasecmp(val, "white") == 0)
323 return COLOR_WHITE;
324 if (strcasecmp(val, "default") == 0)
325 return -1;
327 return default_color_value(envvar);
330 struct tog_diff_view_state {
331 struct got_object_id *id1, *id2;
332 const char *label1, *label2;
333 FILE *f, *f1, *f2;
334 int fd1, fd2;
335 int lineno;
336 int first_displayed_line;
337 int last_displayed_line;
338 int eof;
339 int diff_context;
340 int ignore_whitespace;
341 int force_text_diff;
342 struct got_repository *repo;
343 struct got_diff_line *lines;
344 size_t nlines;
345 int matched_line;
346 int selected_line;
348 /* passed from log or blame view; may be NULL */
349 struct tog_view *parent_view;
350 };
352 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
353 static volatile sig_atomic_t tog_thread_error;
355 struct tog_log_thread_args {
356 pthread_cond_t need_commits;
357 pthread_cond_t commit_loaded;
358 int commits_needed;
359 int load_all;
360 struct got_commit_graph *graph;
361 struct commit_queue *real_commits;
362 const char *in_repo_path;
363 struct got_object_id *start_id;
364 struct got_repository *repo;
365 int *pack_fds;
366 int log_complete;
367 sig_atomic_t *quit;
368 struct commit_queue_entry **first_displayed_entry;
369 struct commit_queue_entry **selected_entry;
370 int *searching;
371 int *search_next_done;
372 regex_t *regex;
373 int *limiting;
374 int limit_match;
375 regex_t *limit_regex;
376 struct commit_queue *limit_commits;
377 };
379 struct tog_log_view_state {
380 struct commit_queue *commits;
381 struct commit_queue_entry *first_displayed_entry;
382 struct commit_queue_entry *last_displayed_entry;
383 struct commit_queue_entry *selected_entry;
384 struct commit_queue real_commits;
385 int selected;
386 char *in_repo_path;
387 char *head_ref_name;
388 int log_branches;
389 struct got_repository *repo;
390 struct got_object_id *start_id;
391 sig_atomic_t quit;
392 pthread_t thread;
393 struct tog_log_thread_args thread_args;
394 struct commit_queue_entry *matched_entry;
395 struct commit_queue_entry *search_entry;
396 struct tog_colors colors;
397 int use_committer;
398 int limit_view;
399 regex_t limit_regex;
400 struct commit_queue limit_commits;
401 };
403 #define TOG_COLOR_DIFF_MINUS 1
404 #define TOG_COLOR_DIFF_PLUS 2
405 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
406 #define TOG_COLOR_DIFF_META 4
407 #define TOG_COLOR_TREE_SUBMODULE 5
408 #define TOG_COLOR_TREE_SYMLINK 6
409 #define TOG_COLOR_TREE_DIRECTORY 7
410 #define TOG_COLOR_TREE_EXECUTABLE 8
411 #define TOG_COLOR_COMMIT 9
412 #define TOG_COLOR_AUTHOR 10
413 #define TOG_COLOR_DATE 11
414 #define TOG_COLOR_REFS_HEADS 12
415 #define TOG_COLOR_REFS_TAGS 13
416 #define TOG_COLOR_REFS_REMOTES 14
417 #define TOG_COLOR_REFS_BACKUP 15
419 struct tog_blame_cb_args {
420 struct tog_blame_line *lines; /* one per line */
421 int nlines;
423 struct tog_view *view;
424 struct got_object_id *commit_id;
425 int *quit;
426 };
428 struct tog_blame_thread_args {
429 const char *path;
430 struct got_repository *repo;
431 struct tog_blame_cb_args *cb_args;
432 int *complete;
433 got_cancel_cb cancel_cb;
434 void *cancel_arg;
435 };
437 struct tog_blame {
438 FILE *f;
439 off_t filesize;
440 struct tog_blame_line *lines;
441 int nlines;
442 off_t *line_offsets;
443 pthread_t thread;
444 struct tog_blame_thread_args thread_args;
445 struct tog_blame_cb_args cb_args;
446 const char *path;
447 int *pack_fds;
448 };
450 struct tog_blame_view_state {
451 int first_displayed_line;
452 int last_displayed_line;
453 int selected_line;
454 int last_diffed_line;
455 int blame_complete;
456 int eof;
457 int done;
458 struct got_object_id_queue blamed_commits;
459 struct got_object_qid *blamed_commit;
460 char *path;
461 struct got_repository *repo;
462 struct got_object_id *commit_id;
463 struct got_object_id *id_to_log;
464 struct tog_blame blame;
465 int matched_line;
466 struct tog_colors colors;
467 };
469 struct tog_parent_tree {
470 TAILQ_ENTRY(tog_parent_tree) entry;
471 struct got_tree_object *tree;
472 struct got_tree_entry *first_displayed_entry;
473 struct got_tree_entry *selected_entry;
474 int selected;
475 };
477 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
479 struct tog_tree_view_state {
480 char *tree_label;
481 struct got_object_id *commit_id;/* commit which this tree belongs to */
482 struct got_tree_object *root; /* the commit's root tree entry */
483 struct got_tree_object *tree; /* currently displayed (sub-)tree */
484 struct got_tree_entry *first_displayed_entry;
485 struct got_tree_entry *last_displayed_entry;
486 struct got_tree_entry *selected_entry;
487 int ndisplayed, selected, show_ids;
488 struct tog_parent_trees parents; /* parent trees of current sub-tree */
489 char *head_ref_name;
490 struct got_repository *repo;
491 struct got_tree_entry *matched_entry;
492 struct tog_colors colors;
493 };
495 struct tog_reflist_entry {
496 TAILQ_ENTRY(tog_reflist_entry) entry;
497 struct got_reference *ref;
498 int idx;
499 };
501 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
503 struct tog_ref_view_state {
504 struct tog_reflist_head refs;
505 struct tog_reflist_entry *first_displayed_entry;
506 struct tog_reflist_entry *last_displayed_entry;
507 struct tog_reflist_entry *selected_entry;
508 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
509 struct got_repository *repo;
510 struct tog_reflist_entry *matched_entry;
511 struct tog_colors colors;
512 };
514 struct tog_help_view_state {
515 FILE *f;
516 off_t *line_offsets;
517 size_t nlines;
518 int lineno;
519 int first_displayed_line;
520 int last_displayed_line;
521 int eof;
522 int matched_line;
523 int selected_line;
524 int all;
525 enum tog_keymap_type type;
526 };
528 #define GENERATE_HELP \
529 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
530 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
531 KEY_("k C-p Up", "Move cursor or page up one line"), \
532 KEY_("j C-n Down", "Move cursor or page down one line"), \
533 KEY_("C-b b PgUp", "Scroll the view up one page"), \
534 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
535 KEY_("C-u u", "Scroll the view up one half page"), \
536 KEY_("C-d d", "Scroll the view down one half page"), \
537 KEY_("g", "Go to line N (default: first line)"), \
538 KEY_("Home =", "Go to the first line"), \
539 KEY_("G", "Go to line N (default: last line)"), \
540 KEY_("End *", "Go to the last line"), \
541 KEY_("l Right", "Scroll the view right"), \
542 KEY_("h Left", "Scroll the view left"), \
543 KEY_("$", "Scroll view to the rightmost position"), \
544 KEY_("0", "Scroll view to the leftmost position"), \
545 KEY_("-", "Decrease size of the focussed split"), \
546 KEY_("+", "Increase size of the focussed split"), \
547 KEY_("Tab", "Switch focus between views"), \
548 KEY_("F", "Toggle fullscreen mode"), \
549 KEY_("/", "Open prompt to enter search term"), \
550 KEY_("n", "Find next line/token matching the current search term"), \
551 KEY_("N", "Find previous line/token matching the current search term"),\
552 KEY_("q", "Quit the focussed view; Quit help screen"), \
553 KEY_("Q", "Quit tog"), \
555 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
556 KEY_("< ,", "Move cursor up one commit"), \
557 KEY_("> .", "Move cursor down one commit"), \
558 KEY_("Enter", "Open diff view of the selected commit"), \
559 KEY_("B", "Reload the log view and toggle display of merged commits"), \
560 KEY_("R", "Open ref view of all repository references"), \
561 KEY_("T", "Display tree view of the repository from the selected" \
562 " commit"), \
563 KEY_("@", "Toggle between displaying author and committer name"), \
564 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
565 KEY_("C-g Backspace", "Cancel current search or log operation"), \
566 KEY_("C-l", "Reload the log view with new commits in the repository"), \
568 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
569 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
570 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
571 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
572 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
573 " data"), \
574 KEY_("(", "Go to the previous file in the diff"), \
575 KEY_(")", "Go to the next file in the diff"), \
576 KEY_("{", "Go to the previous hunk in the diff"), \
577 KEY_("}", "Go to the next hunk in the diff"), \
578 KEY_("[", "Decrease the number of context lines"), \
579 KEY_("]", "Increase the number of context lines"), \
580 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
582 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
583 KEY_("Enter", "Display diff view of the selected line's commit"), \
584 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
585 KEY_("L", "Open log view for the currently selected annotated line"), \
586 KEY_("C", "Reload view with the previously blamed commit"), \
587 KEY_("c", "Reload view with the version of the file found in the" \
588 " selected line's commit"), \
589 KEY_("p", "Reload view with the version of the file found in the" \
590 " selected line's parent commit"), \
592 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
593 KEY_("Enter", "Enter selected directory or open blame view of the" \
594 " selected file"), \
595 KEY_("L", "Open log view for the selected entry"), \
596 KEY_("R", "Open ref view of all repository references"), \
597 KEY_("i", "Show object IDs for all tree entries"), \
598 KEY_("Backspace", "Return to the parent directory"), \
600 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
601 KEY_("Enter", "Display log view of the selected reference"), \
602 KEY_("T", "Display tree view of the selected reference"), \
603 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
604 KEY_("m", "Toggle display of last modified date for each reference"), \
605 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
606 KEY_("C-l", "Reload view with all repository references")
608 struct tog_key_map {
609 const char *keys;
610 const char *info;
611 enum tog_keymap_type type;
612 };
614 /*
615 * We implement two types of views: parent views and child views.
617 * The 'Tab' key switches focus between a parent view and its child view.
618 * Child views are shown side-by-side to their parent view, provided
619 * there is enough screen estate.
621 * When a new view is opened from within a parent view, this new view
622 * becomes a child view of the parent view, replacing any existing child.
624 * When a new view is opened from within a child view, this new view
625 * becomes a parent view which will obscure the views below until the
626 * user quits the new parent view by typing 'q'.
628 * This list of views contains parent views only.
629 * Child views are only pointed to by their parent view.
630 */
631 TAILQ_HEAD(tog_view_list_head, tog_view);
633 struct tog_view {
634 TAILQ_ENTRY(tog_view) entry;
635 WINDOW *window;
636 PANEL *panel;
637 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
638 int resized_y, resized_x; /* begin_y/x based on user resizing */
639 int maxx, x; /* max column and current start column */
640 int lines, cols; /* copies of LINES and COLS */
641 int nscrolled, offset; /* lines scrolled and hsplit line offset */
642 int gline, hiline; /* navigate to and highlight this nG line */
643 int ch, count; /* current keymap and count prefix */
644 int resized; /* set when in a resize event */
645 int focussed; /* Only set on one parent or child view at a time. */
646 int dying;
647 struct tog_view *parent;
648 struct tog_view *child;
650 /*
651 * This flag is initially set on parent views when a new child view
652 * is created. It gets toggled when the 'Tab' key switches focus
653 * between parent and child.
654 * The flag indicates whether focus should be passed on to our child
655 * view if this parent view gets picked for focus after another parent
656 * view was closed. This prevents child views from losing focus in such
657 * situations.
658 */
659 int focus_child;
661 enum tog_view_mode mode;
662 /* type-specific state */
663 enum tog_view_type type;
664 union {
665 struct tog_diff_view_state diff;
666 struct tog_log_view_state log;
667 struct tog_blame_view_state blame;
668 struct tog_tree_view_state tree;
669 struct tog_ref_view_state ref;
670 struct tog_help_view_state help;
671 } state;
673 const struct got_error *(*show)(struct tog_view *);
674 const struct got_error *(*input)(struct tog_view **,
675 struct tog_view *, int);
676 const struct got_error *(*reset)(struct tog_view *);
677 const struct got_error *(*resize)(struct tog_view *, int);
678 const struct got_error *(*close)(struct tog_view *);
680 const struct got_error *(*search_start)(struct tog_view *);
681 const struct got_error *(*search_next)(struct tog_view *);
682 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
683 int **, int **, int **, int **);
684 int search_started;
685 int searching;
686 #define TOG_SEARCH_FORWARD 1
687 #define TOG_SEARCH_BACKWARD 2
688 int search_next_done;
689 #define TOG_SEARCH_HAVE_MORE 1
690 #define TOG_SEARCH_NO_MORE 2
691 #define TOG_SEARCH_HAVE_NONE 3
692 regex_t regex;
693 regmatch_t regmatch;
694 const char *action;
695 };
697 static const struct got_error *open_diff_view(struct tog_view *,
698 struct got_object_id *, struct got_object_id *,
699 const char *, const char *, int, int, int, struct tog_view *,
700 struct got_repository *);
701 static const struct got_error *show_diff_view(struct tog_view *);
702 static const struct got_error *input_diff_view(struct tog_view **,
703 struct tog_view *, int);
704 static const struct got_error *reset_diff_view(struct tog_view *);
705 static const struct got_error* close_diff_view(struct tog_view *);
706 static const struct got_error *search_start_diff_view(struct tog_view *);
707 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
708 size_t *, int **, int **, int **, int **);
709 static const struct got_error *search_next_view_match(struct tog_view *);
711 static const struct got_error *open_log_view(struct tog_view *,
712 struct got_object_id *, struct got_repository *,
713 const char *, const char *, int);
714 static const struct got_error * show_log_view(struct tog_view *);
715 static const struct got_error *input_log_view(struct tog_view **,
716 struct tog_view *, int);
717 static const struct got_error *resize_log_view(struct tog_view *, int);
718 static const struct got_error *close_log_view(struct tog_view *);
719 static const struct got_error *search_start_log_view(struct tog_view *);
720 static const struct got_error *search_next_log_view(struct tog_view *);
722 static const struct got_error *open_blame_view(struct tog_view *, char *,
723 struct got_object_id *, struct got_repository *);
724 static const struct got_error *show_blame_view(struct tog_view *);
725 static const struct got_error *input_blame_view(struct tog_view **,
726 struct tog_view *, int);
727 static const struct got_error *reset_blame_view(struct tog_view *);
728 static const struct got_error *close_blame_view(struct tog_view *);
729 static const struct got_error *search_start_blame_view(struct tog_view *);
730 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
731 size_t *, int **, int **, int **, int **);
733 static const struct got_error *open_tree_view(struct tog_view *,
734 struct got_object_id *, const char *, struct got_repository *);
735 static const struct got_error *show_tree_view(struct tog_view *);
736 static const struct got_error *input_tree_view(struct tog_view **,
737 struct tog_view *, int);
738 static const struct got_error *close_tree_view(struct tog_view *);
739 static const struct got_error *search_start_tree_view(struct tog_view *);
740 static const struct got_error *search_next_tree_view(struct tog_view *);
742 static const struct got_error *open_ref_view(struct tog_view *,
743 struct got_repository *);
744 static const struct got_error *show_ref_view(struct tog_view *);
745 static const struct got_error *input_ref_view(struct tog_view **,
746 struct tog_view *, int);
747 static const struct got_error *close_ref_view(struct tog_view *);
748 static const struct got_error *search_start_ref_view(struct tog_view *);
749 static const struct got_error *search_next_ref_view(struct tog_view *);
751 static const struct got_error *open_help_view(struct tog_view *,
752 struct tog_view *);
753 static const struct got_error *show_help_view(struct tog_view *);
754 static const struct got_error *input_help_view(struct tog_view **,
755 struct tog_view *, int);
756 static const struct got_error *reset_help_view(struct tog_view *);
757 static const struct got_error* close_help_view(struct tog_view *);
758 static const struct got_error *search_start_help_view(struct tog_view *);
759 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
760 size_t *, int **, int **, int **, int **);
762 static volatile sig_atomic_t tog_sigwinch_received;
763 static volatile sig_atomic_t tog_sigpipe_received;
764 static volatile sig_atomic_t tog_sigcont_received;
765 static volatile sig_atomic_t tog_sigint_received;
766 static volatile sig_atomic_t tog_sigterm_received;
768 static void
769 tog_sigwinch(int signo)
771 tog_sigwinch_received = 1;
774 static void
775 tog_sigpipe(int signo)
777 tog_sigpipe_received = 1;
780 static void
781 tog_sigcont(int signo)
783 tog_sigcont_received = 1;
786 static void
787 tog_sigint(int signo)
789 tog_sigint_received = 1;
792 static void
793 tog_sigterm(int signo)
795 tog_sigterm_received = 1;
798 static int
799 tog_fatal_signal_received(void)
801 return (tog_sigpipe_received ||
802 tog_sigint_received || tog_sigterm_received);
805 static const struct got_error *
806 view_close(struct tog_view *view)
808 const struct got_error *err = NULL, *child_err = NULL;
810 if (view->child) {
811 child_err = view_close(view->child);
812 view->child = NULL;
814 if (view->close)
815 err = view->close(view);
816 if (view->panel)
817 del_panel(view->panel);
818 if (view->window)
819 delwin(view->window);
820 free(view);
821 return err ? err : child_err;
824 static struct tog_view *
825 view_open(int nlines, int ncols, int begin_y, int begin_x,
826 enum tog_view_type type)
828 struct tog_view *view = calloc(1, sizeof(*view));
830 if (view == NULL)
831 return NULL;
833 view->type = type;
834 view->lines = LINES;
835 view->cols = COLS;
836 view->nlines = nlines ? nlines : LINES - begin_y;
837 view->ncols = ncols ? ncols : COLS - begin_x;
838 view->begin_y = begin_y;
839 view->begin_x = begin_x;
840 view->window = newwin(nlines, ncols, begin_y, begin_x);
841 if (view->window == NULL) {
842 view_close(view);
843 return NULL;
845 view->panel = new_panel(view->window);
846 if (view->panel == NULL ||
847 set_panel_userptr(view->panel, view) != OK) {
848 view_close(view);
849 return NULL;
852 keypad(view->window, TRUE);
853 return view;
856 static int
857 view_split_begin_x(int begin_x)
859 if (begin_x > 0 || COLS < 120)
860 return 0;
861 return (COLS - MAX(COLS / 2, 80));
864 /* XXX Stub till we decide what to do. */
865 static int
866 view_split_begin_y(int lines)
868 return lines * HSPLIT_SCALE;
871 static const struct got_error *view_resize(struct tog_view *);
873 static const struct got_error *
874 view_splitscreen(struct tog_view *view)
876 const struct got_error *err = NULL;
878 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
879 if (view->resized_y && view->resized_y < view->lines)
880 view->begin_y = view->resized_y;
881 else
882 view->begin_y = view_split_begin_y(view->nlines);
883 view->begin_x = 0;
884 } else if (!view->resized) {
885 if (view->resized_x && view->resized_x < view->cols - 1 &&
886 view->cols > 119)
887 view->begin_x = view->resized_x;
888 else
889 view->begin_x = view_split_begin_x(0);
890 view->begin_y = 0;
892 view->nlines = LINES - view->begin_y;
893 view->ncols = COLS - view->begin_x;
894 view->lines = LINES;
895 view->cols = COLS;
896 err = view_resize(view);
897 if (err)
898 return err;
900 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
901 view->parent->nlines = view->begin_y;
903 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
904 return got_error_from_errno("mvwin");
906 return NULL;
909 static const struct got_error *
910 view_fullscreen(struct tog_view *view)
912 const struct got_error *err = NULL;
914 view->begin_x = 0;
915 view->begin_y = view->resized ? view->begin_y : 0;
916 view->nlines = view->resized ? view->nlines : LINES;
917 view->ncols = COLS;
918 view->lines = LINES;
919 view->cols = COLS;
920 err = view_resize(view);
921 if (err)
922 return err;
924 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
925 return got_error_from_errno("mvwin");
927 return NULL;
930 static int
931 view_is_parent_view(struct tog_view *view)
933 return view->parent == NULL;
936 static int
937 view_is_splitscreen(struct tog_view *view)
939 return view->begin_x > 0 || view->begin_y > 0;
942 static int
943 view_is_fullscreen(struct tog_view *view)
945 return view->nlines == LINES && view->ncols == COLS;
948 static int
949 view_is_hsplit_top(struct tog_view *view)
951 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
952 view_is_splitscreen(view->child);
955 static void
956 view_border(struct tog_view *view)
958 PANEL *panel;
959 const struct tog_view *view_above;
961 if (view->parent)
962 return view_border(view->parent);
964 panel = panel_above(view->panel);
965 if (panel == NULL)
966 return;
968 view_above = panel_userptr(panel);
969 if (view->mode == TOG_VIEW_SPLIT_HRZN)
970 mvwhline(view->window, view_above->begin_y - 1,
971 view->begin_x, got_locale_is_utf8() ?
972 ACS_HLINE : '-', view->ncols);
973 else
974 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
975 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
978 static const struct got_error *view_init_hsplit(struct tog_view *, int);
979 static const struct got_error *request_log_commits(struct tog_view *);
980 static const struct got_error *offset_selection_down(struct tog_view *);
981 static void offset_selection_up(struct tog_view *);
982 static void view_get_split(struct tog_view *, int *, int *);
984 static const struct got_error *
985 view_resize(struct tog_view *view)
987 const struct got_error *err = NULL;
988 int dif, nlines, ncols;
990 dif = LINES - view->lines; /* line difference */
992 if (view->lines > LINES)
993 nlines = view->nlines - (view->lines - LINES);
994 else
995 nlines = view->nlines + (LINES - view->lines);
996 if (view->cols > COLS)
997 ncols = view->ncols - (view->cols - COLS);
998 else
999 ncols = view->ncols + (COLS - view->cols);
1001 if (view->child) {
1002 int hs = view->child->begin_y;
1004 if (!view_is_fullscreen(view))
1005 view->child->begin_x = view_split_begin_x(view->begin_x);
1006 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1007 view->child->begin_x == 0) {
1008 ncols = COLS;
1010 view_fullscreen(view->child);
1011 if (view->child->focussed)
1012 show_panel(view->child->panel);
1013 else
1014 show_panel(view->panel);
1015 } else {
1016 ncols = view->child->begin_x;
1018 view_splitscreen(view->child);
1019 show_panel(view->child->panel);
1022 * XXX This is ugly and needs to be moved into the above
1023 * logic but "works" for now and my attempts at moving it
1024 * break either 'tab' or 'F' key maps in horizontal splits.
1026 if (hs) {
1027 err = view_splitscreen(view->child);
1028 if (err)
1029 return err;
1030 if (dif < 0) { /* top split decreased */
1031 err = offset_selection_down(view);
1032 if (err)
1033 return err;
1035 view_border(view);
1036 update_panels();
1037 doupdate();
1038 show_panel(view->child->panel);
1039 nlines = view->nlines;
1041 } else if (view->parent == NULL)
1042 ncols = COLS;
1044 if (view->resize && dif > 0) {
1045 err = view->resize(view, dif);
1046 if (err)
1047 return err;
1050 if (wresize(view->window, nlines, ncols) == ERR)
1051 return got_error_from_errno("wresize");
1052 if (replace_panel(view->panel, view->window) == ERR)
1053 return got_error_from_errno("replace_panel");
1054 wclear(view->window);
1056 view->nlines = nlines;
1057 view->ncols = ncols;
1058 view->lines = LINES;
1059 view->cols = COLS;
1061 return NULL;
1064 static const struct got_error *
1065 resize_log_view(struct tog_view *view, int increase)
1067 struct tog_log_view_state *s = &view->state.log;
1068 const struct got_error *err = NULL;
1069 int n = 0;
1071 if (s->selected_entry)
1072 n = s->selected_entry->idx + view->lines - s->selected;
1075 * Request commits to account for the increased
1076 * height so we have enough to populate the view.
1078 if (s->commits->ncommits < n) {
1079 view->nscrolled = n - s->commits->ncommits + increase + 1;
1080 err = request_log_commits(view);
1083 return err;
1086 static void
1087 view_adjust_offset(struct tog_view *view, int n)
1089 if (n == 0)
1090 return;
1092 if (view->parent && view->parent->offset) {
1093 if (view->parent->offset + n >= 0)
1094 view->parent->offset += n;
1095 else
1096 view->parent->offset = 0;
1097 } else if (view->offset) {
1098 if (view->offset - n >= 0)
1099 view->offset -= n;
1100 else
1101 view->offset = 0;
1105 static const struct got_error *
1106 view_resize_split(struct tog_view *view, int resize)
1108 const struct got_error *err = NULL;
1109 struct tog_view *v = NULL;
1111 if (view->parent)
1112 v = view->parent;
1113 else
1114 v = view;
1116 if (!v->child || !view_is_splitscreen(v->child))
1117 return NULL;
1119 v->resized = v->child->resized = resize; /* lock for resize event */
1121 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1122 if (v->child->resized_y)
1123 v->child->begin_y = v->child->resized_y;
1124 if (view->parent)
1125 v->child->begin_y -= resize;
1126 else
1127 v->child->begin_y += resize;
1128 if (v->child->begin_y < 3) {
1129 view->count = 0;
1130 v->child->begin_y = 3;
1131 } else if (v->child->begin_y > LINES - 1) {
1132 view->count = 0;
1133 v->child->begin_y = LINES - 1;
1135 v->ncols = COLS;
1136 v->child->ncols = COLS;
1137 view_adjust_offset(view, resize);
1138 err = view_init_hsplit(v, v->child->begin_y);
1139 if (err)
1140 return err;
1141 v->child->resized_y = v->child->begin_y;
1142 } else {
1143 if (v->child->resized_x)
1144 v->child->begin_x = v->child->resized_x;
1145 if (view->parent)
1146 v->child->begin_x -= resize;
1147 else
1148 v->child->begin_x += resize;
1149 if (v->child->begin_x < 11) {
1150 view->count = 0;
1151 v->child->begin_x = 11;
1152 } else if (v->child->begin_x > COLS - 1) {
1153 view->count = 0;
1154 v->child->begin_x = COLS - 1;
1156 v->child->resized_x = v->child->begin_x;
1159 v->child->mode = v->mode;
1160 v->child->nlines = v->lines - v->child->begin_y;
1161 v->child->ncols = v->cols - v->child->begin_x;
1162 v->focus_child = 1;
1164 err = view_fullscreen(v);
1165 if (err)
1166 return err;
1167 err = view_splitscreen(v->child);
1168 if (err)
1169 return err;
1171 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1172 err = offset_selection_down(v->child);
1173 if (err)
1174 return err;
1177 if (v->resize)
1178 err = v->resize(v, 0);
1179 else if (v->child->resize)
1180 err = v->child->resize(v->child, 0);
1182 v->resized = v->child->resized = 0;
1184 return err;
1187 static void
1188 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1190 struct tog_view *v = src->child ? src->child : src;
1192 dst->resized_x = v->resized_x;
1193 dst->resized_y = v->resized_y;
1196 static const struct got_error *
1197 view_close_child(struct tog_view *view)
1199 const struct got_error *err = NULL;
1201 if (view->child == NULL)
1202 return NULL;
1204 err = view_close(view->child);
1205 view->child = NULL;
1206 return err;
1209 static const struct got_error *
1210 view_set_child(struct tog_view *view, struct tog_view *child)
1212 const struct got_error *err = NULL;
1214 view->child = child;
1215 child->parent = view;
1217 err = view_resize(view);
1218 if (err)
1219 return err;
1221 if (view->child->resized_x || view->child->resized_y)
1222 err = view_resize_split(view, 0);
1224 return err;
1227 static const struct got_error *view_dispatch_request(struct tog_view **,
1228 struct tog_view *, enum tog_view_type, int, int);
1230 static const struct got_error *
1231 view_request_new(struct tog_view **requested, struct tog_view *view,
1232 enum tog_view_type request)
1234 struct tog_view *new_view = NULL;
1235 const struct got_error *err;
1236 int y = 0, x = 0;
1238 *requested = NULL;
1240 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1241 view_get_split(view, &y, &x);
1243 err = view_dispatch_request(&new_view, view, request, y, x);
1244 if (err)
1245 return err;
1247 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1248 request != TOG_VIEW_HELP) {
1249 err = view_init_hsplit(view, y);
1250 if (err)
1251 return err;
1254 view->focussed = 0;
1255 new_view->focussed = 1;
1256 new_view->mode = view->mode;
1257 new_view->nlines = request == TOG_VIEW_HELP ?
1258 view->lines : view->lines - y;
1260 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1261 view_transfer_size(new_view, view);
1262 err = view_close_child(view);
1263 if (err)
1264 return err;
1265 err = view_set_child(view, new_view);
1266 if (err)
1267 return err;
1268 view->focus_child = 1;
1269 } else
1270 *requested = new_view;
1272 return NULL;
1275 static void
1276 tog_resizeterm(void)
1278 int cols, lines;
1279 struct winsize size;
1281 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1282 cols = 80; /* Default */
1283 lines = 24;
1284 } else {
1285 cols = size.ws_col;
1286 lines = size.ws_row;
1288 resize_term(lines, cols);
1291 static const struct got_error *
1292 view_search_start(struct tog_view *view)
1294 const struct got_error *err = NULL;
1295 struct tog_view *v = view;
1296 char pattern[1024];
1297 int ret;
1299 if (view->search_started) {
1300 regfree(&view->regex);
1301 view->searching = 0;
1302 memset(&view->regmatch, 0, sizeof(view->regmatch));
1304 view->search_started = 0;
1306 if (view->nlines < 1)
1307 return NULL;
1309 if (view_is_hsplit_top(view))
1310 v = view->child;
1311 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1312 v = view->parent;
1314 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1315 wclrtoeol(v->window);
1317 nodelay(v->window, FALSE); /* block for search term input */
1318 nocbreak();
1319 echo();
1320 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1321 wrefresh(v->window);
1322 cbreak();
1323 noecho();
1324 nodelay(v->window, TRUE);
1325 if (ret == ERR)
1326 return NULL;
1328 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1329 err = view->search_start(view);
1330 if (err) {
1331 regfree(&view->regex);
1332 return err;
1334 view->search_started = 1;
1335 view->searching = TOG_SEARCH_FORWARD;
1336 view->search_next_done = 0;
1337 view->search_next(view);
1340 return NULL;
1343 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1344 static const struct got_error *
1345 switch_split(struct tog_view *view)
1347 const struct got_error *err = NULL;
1348 struct tog_view *v = NULL;
1350 if (view->parent)
1351 v = view->parent;
1352 else
1353 v = view;
1355 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1356 v->mode = TOG_VIEW_SPLIT_VERT;
1357 else
1358 v->mode = TOG_VIEW_SPLIT_HRZN;
1360 if (!v->child)
1361 return NULL;
1362 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1363 v->mode = TOG_VIEW_SPLIT_NONE;
1365 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1366 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1367 v->child->begin_y = v->child->resized_y;
1368 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1369 v->child->begin_x = v->child->resized_x;
1372 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1373 v->ncols = COLS;
1374 v->child->ncols = COLS;
1375 v->child->nscrolled = LINES - v->child->nlines;
1377 err = view_init_hsplit(v, v->child->begin_y);
1378 if (err)
1379 return err;
1381 v->child->mode = v->mode;
1382 v->child->nlines = v->lines - v->child->begin_y;
1383 v->focus_child = 1;
1385 err = view_fullscreen(v);
1386 if (err)
1387 return err;
1388 err = view_splitscreen(v->child);
1389 if (err)
1390 return err;
1392 if (v->mode == TOG_VIEW_SPLIT_NONE)
1393 v->mode = TOG_VIEW_SPLIT_VERT;
1394 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1395 err = offset_selection_down(v);
1396 if (err)
1397 return err;
1398 err = offset_selection_down(v->child);
1399 if (err)
1400 return err;
1401 } else {
1402 offset_selection_up(v);
1403 offset_selection_up(v->child);
1405 if (v->resize)
1406 err = v->resize(v, 0);
1407 else if (v->child->resize)
1408 err = v->child->resize(v->child, 0);
1410 return err;
1414 * Compute view->count from numeric input. Assign total to view->count and
1415 * return first non-numeric key entered.
1417 static int
1418 get_compound_key(struct tog_view *view, int c)
1420 struct tog_view *v = view;
1421 int x, n = 0;
1423 if (view_is_hsplit_top(view))
1424 v = view->child;
1425 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1426 v = view->parent;
1428 view->count = 0;
1429 cbreak(); /* block for input */
1430 nodelay(view->window, FALSE);
1431 wmove(v->window, v->nlines - 1, 0);
1432 wclrtoeol(v->window);
1433 waddch(v->window, ':');
1435 do {
1436 x = getcurx(v->window);
1437 if (x != ERR && x < view->ncols) {
1438 waddch(v->window, c);
1439 wrefresh(v->window);
1443 * Don't overflow. Max valid request should be the greatest
1444 * between the longest and total lines; cap at 10 million.
1446 if (n >= 9999999)
1447 n = 9999999;
1448 else
1449 n = n * 10 + (c - '0');
1450 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1452 if (c == 'G' || c == 'g') { /* nG key map */
1453 view->gline = view->hiline = n;
1454 n = 0;
1455 c = 0;
1458 /* Massage excessive or inapplicable values at the input handler. */
1459 view->count = n;
1461 return c;
1464 static void
1465 action_report(struct tog_view *view)
1467 struct tog_view *v = view;
1469 if (view_is_hsplit_top(view))
1470 v = view->child;
1471 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1472 v = view->parent;
1474 wmove(v->window, v->nlines - 1, 0);
1475 wclrtoeol(v->window);
1476 wprintw(v->window, ":%s", view->action);
1477 wrefresh(v->window);
1480 * Clear action status report. Only clear in blame view
1481 * once annotating is complete, otherwise it's too fast.
1483 if (view->type == TOG_VIEW_BLAME) {
1484 if (view->state.blame.blame_complete)
1485 view->action = NULL;
1486 } else
1487 view->action = NULL;
1490 static const struct got_error *
1491 view_input(struct tog_view **new, int *done, struct tog_view *view,
1492 struct tog_view_list_head *views)
1494 const struct got_error *err = NULL;
1495 struct tog_view *v;
1496 int ch, errcode;
1498 *new = NULL;
1500 if (view->action)
1501 action_report(view);
1503 /* Clear "no matches" indicator. */
1504 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1505 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1506 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1507 view->count = 0;
1510 if (view->searching && !view->search_next_done) {
1511 errcode = pthread_mutex_unlock(&tog_mutex);
1512 if (errcode)
1513 return got_error_set_errno(errcode,
1514 "pthread_mutex_unlock");
1515 sched_yield();
1516 errcode = pthread_mutex_lock(&tog_mutex);
1517 if (errcode)
1518 return got_error_set_errno(errcode,
1519 "pthread_mutex_lock");
1520 view->search_next(view);
1521 return NULL;
1524 /* Allow threads to make progress while we are waiting for input. */
1525 errcode = pthread_mutex_unlock(&tog_mutex);
1526 if (errcode)
1527 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1528 /* If we have an unfinished count, let C-g or backspace abort. */
1529 if (view->count && --view->count) {
1530 cbreak();
1531 nodelay(view->window, TRUE);
1532 ch = wgetch(view->window);
1533 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1534 view->count = 0;
1535 else
1536 ch = view->ch;
1537 } else {
1538 ch = wgetch(view->window);
1539 if (ch >= '1' && ch <= '9')
1540 view->ch = ch = get_compound_key(view, ch);
1542 if (view->hiline && ch != ERR && ch != 0)
1543 view->hiline = 0; /* key pressed, clear line highlight */
1544 nodelay(view->window, TRUE);
1545 errcode = pthread_mutex_lock(&tog_mutex);
1546 if (errcode)
1547 return got_error_set_errno(errcode, "pthread_mutex_lock");
1549 if (tog_sigwinch_received || tog_sigcont_received) {
1550 tog_resizeterm();
1551 tog_sigwinch_received = 0;
1552 tog_sigcont_received = 0;
1553 TAILQ_FOREACH(v, views, entry) {
1554 err = view_resize(v);
1555 if (err)
1556 return err;
1557 err = v->input(new, v, KEY_RESIZE);
1558 if (err)
1559 return err;
1560 if (v->child) {
1561 err = view_resize(v->child);
1562 if (err)
1563 return err;
1564 err = v->child->input(new, v->child,
1565 KEY_RESIZE);
1566 if (err)
1567 return err;
1568 if (v->child->resized_x || v->child->resized_y) {
1569 err = view_resize_split(v, 0);
1570 if (err)
1571 return err;
1577 switch (ch) {
1578 case '?':
1579 case 'H':
1580 case KEY_F(1):
1581 if (view->type == TOG_VIEW_HELP)
1582 err = view->reset(view);
1583 else
1584 err = view_request_new(new, view, TOG_VIEW_HELP);
1585 break;
1586 case '\t':
1587 view->count = 0;
1588 if (view->child) {
1589 view->focussed = 0;
1590 view->child->focussed = 1;
1591 view->focus_child = 1;
1592 } else if (view->parent) {
1593 view->focussed = 0;
1594 view->parent->focussed = 1;
1595 view->parent->focus_child = 0;
1596 if (!view_is_splitscreen(view)) {
1597 if (view->parent->resize) {
1598 err = view->parent->resize(view->parent,
1599 0);
1600 if (err)
1601 return err;
1603 offset_selection_up(view->parent);
1604 err = view_fullscreen(view->parent);
1605 if (err)
1606 return err;
1609 break;
1610 case 'q':
1611 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1612 if (view->parent->resize) {
1613 /* might need more commits to fill fullscreen */
1614 err = view->parent->resize(view->parent, 0);
1615 if (err)
1616 break;
1618 offset_selection_up(view->parent);
1620 err = view->input(new, view, ch);
1621 view->dying = 1;
1622 break;
1623 case 'Q':
1624 *done = 1;
1625 break;
1626 case 'F':
1627 view->count = 0;
1628 if (view_is_parent_view(view)) {
1629 if (view->child == NULL)
1630 break;
1631 if (view_is_splitscreen(view->child)) {
1632 view->focussed = 0;
1633 view->child->focussed = 1;
1634 err = view_fullscreen(view->child);
1635 } else {
1636 err = view_splitscreen(view->child);
1637 if (!err)
1638 err = view_resize_split(view, 0);
1640 if (err)
1641 break;
1642 err = view->child->input(new, view->child,
1643 KEY_RESIZE);
1644 } else {
1645 if (view_is_splitscreen(view)) {
1646 view->parent->focussed = 0;
1647 view->focussed = 1;
1648 err = view_fullscreen(view);
1649 } else {
1650 err = view_splitscreen(view);
1651 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1652 err = view_resize(view->parent);
1653 if (!err)
1654 err = view_resize_split(view, 0);
1656 if (err)
1657 break;
1658 err = view->input(new, view, KEY_RESIZE);
1660 if (err)
1661 break;
1662 if (view->resize) {
1663 err = view->resize(view, 0);
1664 if (err)
1665 break;
1667 if (view->parent)
1668 err = offset_selection_down(view->parent);
1669 if (!err)
1670 err = offset_selection_down(view);
1671 break;
1672 case 'S':
1673 view->count = 0;
1674 err = switch_split(view);
1675 break;
1676 case '-':
1677 err = view_resize_split(view, -1);
1678 break;
1679 case '+':
1680 err = view_resize_split(view, 1);
1681 break;
1682 case KEY_RESIZE:
1683 break;
1684 case '/':
1685 view->count = 0;
1686 if (view->search_start)
1687 view_search_start(view);
1688 else
1689 err = view->input(new, view, ch);
1690 break;
1691 case 'N':
1692 case 'n':
1693 if (view->search_started && view->search_next) {
1694 view->searching = (ch == 'n' ?
1695 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1696 view->search_next_done = 0;
1697 view->search_next(view);
1698 } else
1699 err = view->input(new, view, ch);
1700 break;
1701 case 'A':
1702 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1703 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1704 view->action = "Patience diff algorithm";
1705 } else {
1706 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1707 view->action = "Myers diff algorithm";
1709 TAILQ_FOREACH(v, views, entry) {
1710 if (v->reset) {
1711 err = v->reset(v);
1712 if (err)
1713 return err;
1715 if (v->child && v->child->reset) {
1716 err = v->child->reset(v->child);
1717 if (err)
1718 return err;
1721 break;
1722 default:
1723 err = view->input(new, view, ch);
1724 break;
1727 return err;
1730 static int
1731 view_needs_focus_indication(struct tog_view *view)
1733 if (view_is_parent_view(view)) {
1734 if (view->child == NULL || view->child->focussed)
1735 return 0;
1736 if (!view_is_splitscreen(view->child))
1737 return 0;
1738 } else if (!view_is_splitscreen(view))
1739 return 0;
1741 return view->focussed;
1744 static const struct got_error *
1745 view_loop(struct tog_view *view)
1747 const struct got_error *err = NULL;
1748 struct tog_view_list_head views;
1749 struct tog_view *new_view;
1750 char *mode;
1751 int fast_refresh = 10;
1752 int done = 0, errcode;
1754 mode = getenv("TOG_VIEW_SPLIT_MODE");
1755 if (!mode || !(*mode == 'h' || *mode == 'H'))
1756 view->mode = TOG_VIEW_SPLIT_VERT;
1757 else
1758 view->mode = TOG_VIEW_SPLIT_HRZN;
1760 errcode = pthread_mutex_lock(&tog_mutex);
1761 if (errcode)
1762 return got_error_set_errno(errcode, "pthread_mutex_lock");
1764 TAILQ_INIT(&views);
1765 TAILQ_INSERT_HEAD(&views, view, entry);
1767 view->focussed = 1;
1768 err = view->show(view);
1769 if (err)
1770 return err;
1771 update_panels();
1772 doupdate();
1773 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1774 !tog_fatal_signal_received()) {
1775 /* Refresh fast during initialization, then become slower. */
1776 if (fast_refresh && --fast_refresh == 0)
1777 halfdelay(10); /* switch to once per second */
1779 err = view_input(&new_view, &done, view, &views);
1780 if (err)
1781 break;
1783 if (view->dying && view == TAILQ_FIRST(&views) &&
1784 TAILQ_NEXT(view, entry) == NULL)
1785 done = 1;
1786 if (done) {
1787 struct tog_view *v;
1790 * When we quit, scroll the screen up a single line
1791 * so we don't lose any information.
1793 TAILQ_FOREACH(v, &views, entry) {
1794 wmove(v->window, 0, 0);
1795 wdeleteln(v->window);
1796 wnoutrefresh(v->window);
1797 if (v->child && !view_is_fullscreen(v)) {
1798 wmove(v->child->window, 0, 0);
1799 wdeleteln(v->child->window);
1800 wnoutrefresh(v->child->window);
1803 doupdate();
1806 if (view->dying) {
1807 struct tog_view *v, *prev = NULL;
1809 if (view_is_parent_view(view))
1810 prev = TAILQ_PREV(view, tog_view_list_head,
1811 entry);
1812 else if (view->parent)
1813 prev = view->parent;
1815 if (view->parent) {
1816 view->parent->child = NULL;
1817 view->parent->focus_child = 0;
1818 /* Restore fullscreen line height. */
1819 view->parent->nlines = view->parent->lines;
1820 err = view_resize(view->parent);
1821 if (err)
1822 break;
1823 /* Make resized splits persist. */
1824 view_transfer_size(view->parent, view);
1825 } else
1826 TAILQ_REMOVE(&views, view, entry);
1828 err = view_close(view);
1829 if (err)
1830 goto done;
1832 view = NULL;
1833 TAILQ_FOREACH(v, &views, entry) {
1834 if (v->focussed)
1835 break;
1837 if (view == NULL && new_view == NULL) {
1838 /* No view has focus. Try to pick one. */
1839 if (prev)
1840 view = prev;
1841 else if (!TAILQ_EMPTY(&views)) {
1842 view = TAILQ_LAST(&views,
1843 tog_view_list_head);
1845 if (view) {
1846 if (view->focus_child) {
1847 view->child->focussed = 1;
1848 view = view->child;
1849 } else
1850 view->focussed = 1;
1854 if (new_view) {
1855 struct tog_view *v, *t;
1856 /* Only allow one parent view per type. */
1857 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1858 if (v->type != new_view->type)
1859 continue;
1860 TAILQ_REMOVE(&views, v, entry);
1861 err = view_close(v);
1862 if (err)
1863 goto done;
1864 break;
1866 TAILQ_INSERT_TAIL(&views, new_view, entry);
1867 view = new_view;
1869 if (view && !done) {
1870 if (view_is_parent_view(view)) {
1871 if (view->child && view->child->focussed)
1872 view = view->child;
1873 } else {
1874 if (view->parent && view->parent->focussed)
1875 view = view->parent;
1877 show_panel(view->panel);
1878 if (view->child && view_is_splitscreen(view->child))
1879 show_panel(view->child->panel);
1880 if (view->parent && view_is_splitscreen(view)) {
1881 err = view->parent->show(view->parent);
1882 if (err)
1883 goto done;
1885 err = view->show(view);
1886 if (err)
1887 goto done;
1888 if (view->child) {
1889 err = view->child->show(view->child);
1890 if (err)
1891 goto done;
1893 update_panels();
1894 doupdate();
1897 done:
1898 while (!TAILQ_EMPTY(&views)) {
1899 const struct got_error *close_err;
1900 view = TAILQ_FIRST(&views);
1901 TAILQ_REMOVE(&views, view, entry);
1902 close_err = view_close(view);
1903 if (close_err && err == NULL)
1904 err = close_err;
1907 errcode = pthread_mutex_unlock(&tog_mutex);
1908 if (errcode && err == NULL)
1909 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1911 return err;
1914 __dead static void
1915 usage_log(void)
1917 endwin();
1918 fprintf(stderr,
1919 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1920 getprogname());
1921 exit(1);
1924 /* Create newly allocated wide-character string equivalent to a byte string. */
1925 static const struct got_error *
1926 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1928 char *vis = NULL;
1929 const struct got_error *err = NULL;
1931 *ws = NULL;
1932 *wlen = mbstowcs(NULL, s, 0);
1933 if (*wlen == (size_t)-1) {
1934 int vislen;
1935 if (errno != EILSEQ)
1936 return got_error_from_errno("mbstowcs");
1938 /* byte string invalid in current encoding; try to "fix" it */
1939 err = got_mbsavis(&vis, &vislen, s);
1940 if (err)
1941 return err;
1942 *wlen = mbstowcs(NULL, vis, 0);
1943 if (*wlen == (size_t)-1) {
1944 err = got_error_from_errno("mbstowcs"); /* give up */
1945 goto done;
1949 *ws = calloc(*wlen + 1, sizeof(**ws));
1950 if (*ws == NULL) {
1951 err = got_error_from_errno("calloc");
1952 goto done;
1955 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1956 err = got_error_from_errno("mbstowcs");
1957 done:
1958 free(vis);
1959 if (err) {
1960 free(*ws);
1961 *ws = NULL;
1962 *wlen = 0;
1964 return err;
1967 static const struct got_error *
1968 expand_tab(char **ptr, const char *src)
1970 char *dst;
1971 size_t len, n, idx = 0, sz = 0;
1973 *ptr = NULL;
1974 n = len = strlen(src);
1975 dst = malloc(n + 1);
1976 if (dst == NULL)
1977 return got_error_from_errno("malloc");
1979 while (idx < len && src[idx]) {
1980 const char c = src[idx];
1982 if (c == '\t') {
1983 size_t nb = TABSIZE - sz % TABSIZE;
1984 char *p;
1986 p = realloc(dst, n + nb);
1987 if (p == NULL) {
1988 free(dst);
1989 return got_error_from_errno("realloc");
1992 dst = p;
1993 n += nb;
1994 memset(dst + sz, ' ', nb);
1995 sz += nb;
1996 } else
1997 dst[sz++] = src[idx];
1998 ++idx;
2001 dst[sz] = '\0';
2002 *ptr = dst;
2003 return NULL;
2007 * Advance at most n columns from wline starting at offset off.
2008 * Return the index to the first character after the span operation.
2009 * Return the combined column width of all spanned wide character in
2010 * *rcol.
2012 static int
2013 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2015 int width, i, cols = 0;
2017 if (n == 0) {
2018 *rcol = cols;
2019 return off;
2022 for (i = off; wline[i] != L'\0'; ++i) {
2023 if (wline[i] == L'\t')
2024 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2025 else
2026 width = wcwidth(wline[i]);
2028 if (width == -1) {
2029 width = 1;
2030 wline[i] = L'.';
2033 if (cols + width > n)
2034 break;
2035 cols += width;
2038 *rcol = cols;
2039 return i;
2043 * Format a line for display, ensuring that it won't overflow a width limit.
2044 * With scrolling, the width returned refers to the scrolled version of the
2045 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2047 static const struct got_error *
2048 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2049 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2051 const struct got_error *err = NULL;
2052 int cols;
2053 wchar_t *wline = NULL;
2054 char *exstr = NULL;
2055 size_t wlen;
2056 int i, scrollx;
2058 *wlinep = NULL;
2059 *widthp = 0;
2061 if (expand) {
2062 err = expand_tab(&exstr, line);
2063 if (err)
2064 return err;
2067 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2068 free(exstr);
2069 if (err)
2070 return err;
2072 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2074 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2075 wline[wlen - 1] = L'\0';
2076 wlen--;
2078 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2079 wline[wlen - 1] = L'\0';
2080 wlen--;
2083 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2084 wline[i] = L'\0';
2086 if (widthp)
2087 *widthp = cols;
2088 if (scrollxp)
2089 *scrollxp = scrollx;
2090 if (err)
2091 free(wline);
2092 else
2093 *wlinep = wline;
2094 return err;
2097 static const struct got_error*
2098 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2099 struct got_object_id *id, struct got_repository *repo)
2101 static const struct got_error *err = NULL;
2102 struct got_reflist_entry *re;
2103 char *s;
2104 const char *name;
2106 *refs_str = NULL;
2108 TAILQ_FOREACH(re, refs, entry) {
2109 struct got_tag_object *tag = NULL;
2110 struct got_object_id *ref_id;
2111 int cmp;
2113 name = got_ref_get_name(re->ref);
2114 if (strcmp(name, GOT_REF_HEAD) == 0)
2115 continue;
2116 if (strncmp(name, "refs/", 5) == 0)
2117 name += 5;
2118 if (strncmp(name, "got/", 4) == 0 &&
2119 strncmp(name, "got/backup/", 11) != 0)
2120 continue;
2121 if (strncmp(name, "heads/", 6) == 0)
2122 name += 6;
2123 if (strncmp(name, "remotes/", 8) == 0) {
2124 name += 8;
2125 s = strstr(name, "/" GOT_REF_HEAD);
2126 if (s != NULL && s[strlen(s)] == '\0')
2127 continue;
2129 err = got_ref_resolve(&ref_id, repo, re->ref);
2130 if (err)
2131 break;
2132 if (strncmp(name, "tags/", 5) == 0) {
2133 err = got_object_open_as_tag(&tag, repo, ref_id);
2134 if (err) {
2135 if (err->code != GOT_ERR_OBJ_TYPE) {
2136 free(ref_id);
2137 break;
2139 /* Ref points at something other than a tag. */
2140 err = NULL;
2141 tag = NULL;
2144 cmp = got_object_id_cmp(tag ?
2145 got_object_tag_get_object_id(tag) : ref_id, id);
2146 free(ref_id);
2147 if (tag)
2148 got_object_tag_close(tag);
2149 if (cmp != 0)
2150 continue;
2151 s = *refs_str;
2152 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2153 s ? ", " : "", name) == -1) {
2154 err = got_error_from_errno("asprintf");
2155 free(s);
2156 *refs_str = NULL;
2157 break;
2159 free(s);
2162 return err;
2165 static const struct got_error *
2166 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2167 int col_tab_align)
2169 char *smallerthan;
2171 smallerthan = strchr(author, '<');
2172 if (smallerthan && smallerthan[1] != '\0')
2173 author = smallerthan + 1;
2174 author[strcspn(author, "@>")] = '\0';
2175 return format_line(wauthor, author_width, NULL, author, 0, limit,
2176 col_tab_align, 0);
2179 static const struct got_error *
2180 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2181 struct got_object_id *id, const size_t date_display_cols,
2182 int author_display_cols)
2184 struct tog_log_view_state *s = &view->state.log;
2185 const struct got_error *err = NULL;
2186 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2187 char *logmsg0 = NULL, *logmsg = NULL;
2188 char *author = NULL;
2189 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2190 int author_width, logmsg_width;
2191 char *newline, *line = NULL;
2192 int col, limit, scrollx;
2193 const int avail = view->ncols;
2194 struct tm tm;
2195 time_t committer_time;
2196 struct tog_color *tc;
2198 committer_time = got_object_commit_get_committer_time(commit);
2199 if (gmtime_r(&committer_time, &tm) == NULL)
2200 return got_error_from_errno("gmtime_r");
2201 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2202 return got_error(GOT_ERR_NO_SPACE);
2204 if (avail <= date_display_cols)
2205 limit = MIN(sizeof(datebuf) - 1, avail);
2206 else
2207 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2208 tc = get_color(&s->colors, TOG_COLOR_DATE);
2209 if (tc)
2210 wattr_on(view->window,
2211 COLOR_PAIR(tc->colorpair), NULL);
2212 waddnstr(view->window, datebuf, limit);
2213 if (tc)
2214 wattr_off(view->window,
2215 COLOR_PAIR(tc->colorpair), NULL);
2216 col = limit;
2217 if (col > avail)
2218 goto done;
2220 if (avail >= 120) {
2221 char *id_str;
2222 err = got_object_id_str(&id_str, id);
2223 if (err)
2224 goto done;
2225 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2226 if (tc)
2227 wattr_on(view->window,
2228 COLOR_PAIR(tc->colorpair), NULL);
2229 wprintw(view->window, "%.8s ", id_str);
2230 if (tc)
2231 wattr_off(view->window,
2232 COLOR_PAIR(tc->colorpair), NULL);
2233 free(id_str);
2234 col += 9;
2235 if (col > avail)
2236 goto done;
2239 if (s->use_committer)
2240 author = strdup(got_object_commit_get_committer(commit));
2241 else
2242 author = strdup(got_object_commit_get_author(commit));
2243 if (author == NULL) {
2244 err = got_error_from_errno("strdup");
2245 goto done;
2247 err = format_author(&wauthor, &author_width, author, avail - col, col);
2248 if (err)
2249 goto done;
2250 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2251 if (tc)
2252 wattr_on(view->window,
2253 COLOR_PAIR(tc->colorpair), NULL);
2254 waddwstr(view->window, wauthor);
2255 col += author_width;
2256 while (col < avail && author_width < author_display_cols + 2) {
2257 waddch(view->window, ' ');
2258 col++;
2259 author_width++;
2261 if (tc)
2262 wattr_off(view->window,
2263 COLOR_PAIR(tc->colorpair), NULL);
2264 if (col > avail)
2265 goto done;
2267 err = got_object_commit_get_logmsg(&logmsg0, commit);
2268 if (err)
2269 goto done;
2270 logmsg = logmsg0;
2271 while (*logmsg == '\n')
2272 logmsg++;
2273 newline = strchr(logmsg, '\n');
2274 if (newline)
2275 *newline = '\0';
2276 limit = avail - col;
2277 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2278 limit--; /* for the border */
2279 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2280 limit, col, 1);
2281 if (err)
2282 goto done;
2283 waddwstr(view->window, &wlogmsg[scrollx]);
2284 col += MAX(logmsg_width, 0);
2285 while (col < avail) {
2286 waddch(view->window, ' ');
2287 col++;
2289 done:
2290 free(logmsg0);
2291 free(wlogmsg);
2292 free(author);
2293 free(wauthor);
2294 free(line);
2295 return err;
2298 static struct commit_queue_entry *
2299 alloc_commit_queue_entry(struct got_commit_object *commit,
2300 struct got_object_id *id)
2302 struct commit_queue_entry *entry;
2303 struct got_object_id *dup;
2305 entry = calloc(1, sizeof(*entry));
2306 if (entry == NULL)
2307 return NULL;
2309 dup = got_object_id_dup(id);
2310 if (dup == NULL) {
2311 free(entry);
2312 return NULL;
2315 entry->id = dup;
2316 entry->commit = commit;
2317 return entry;
2320 static void
2321 pop_commit(struct commit_queue *commits)
2323 struct commit_queue_entry *entry;
2325 entry = TAILQ_FIRST(&commits->head);
2326 TAILQ_REMOVE(&commits->head, entry, entry);
2327 got_object_commit_close(entry->commit);
2328 commits->ncommits--;
2329 free(entry->id);
2330 free(entry);
2333 static void
2334 free_commits(struct commit_queue *commits)
2336 while (!TAILQ_EMPTY(&commits->head))
2337 pop_commit(commits);
2340 static const struct got_error *
2341 match_commit(int *have_match, struct got_object_id *id,
2342 struct got_commit_object *commit, regex_t *regex)
2344 const struct got_error *err = NULL;
2345 regmatch_t regmatch;
2346 char *id_str = NULL, *logmsg = NULL;
2348 *have_match = 0;
2350 err = got_object_id_str(&id_str, id);
2351 if (err)
2352 return err;
2354 err = got_object_commit_get_logmsg(&logmsg, commit);
2355 if (err)
2356 goto done;
2358 if (regexec(regex, got_object_commit_get_author(commit), 1,
2359 &regmatch, 0) == 0 ||
2360 regexec(regex, got_object_commit_get_committer(commit), 1,
2361 &regmatch, 0) == 0 ||
2362 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2363 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2364 *have_match = 1;
2365 done:
2366 free(id_str);
2367 free(logmsg);
2368 return err;
2371 static const struct got_error *
2372 queue_commits(struct tog_log_thread_args *a)
2374 const struct got_error *err = NULL;
2377 * We keep all commits open throughout the lifetime of the log
2378 * view in order to avoid having to re-fetch commits from disk
2379 * while updating the display.
2381 do {
2382 struct got_object_id id;
2383 struct got_commit_object *commit;
2384 struct commit_queue_entry *entry;
2385 int limit_match = 0;
2386 int errcode;
2388 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2389 NULL, NULL);
2390 if (err)
2391 break;
2393 err = got_object_open_as_commit(&commit, a->repo, &id);
2394 if (err)
2395 break;
2396 entry = alloc_commit_queue_entry(commit, &id);
2397 if (entry == NULL) {
2398 err = got_error_from_errno("alloc_commit_queue_entry");
2399 break;
2402 errcode = pthread_mutex_lock(&tog_mutex);
2403 if (errcode) {
2404 err = got_error_set_errno(errcode,
2405 "pthread_mutex_lock");
2406 break;
2409 entry->idx = a->real_commits->ncommits;
2410 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2411 a->real_commits->ncommits++;
2413 if (*a->limiting) {
2414 err = match_commit(&limit_match, &id, commit,
2415 a->limit_regex);
2416 if (err)
2417 break;
2419 if (limit_match) {
2420 struct commit_queue_entry *matched;
2422 matched = alloc_commit_queue_entry(
2423 entry->commit, entry->id);
2424 if (matched == NULL) {
2425 err = got_error_from_errno(
2426 "alloc_commit_queue_entry");
2427 break;
2429 matched->commit = entry->commit;
2430 got_object_commit_retain(entry->commit);
2432 matched->idx = a->limit_commits->ncommits;
2433 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2434 matched, entry);
2435 a->limit_commits->ncommits++;
2439 * This is how we signal log_thread() that we
2440 * have found a match, and that it should be
2441 * counted as a new entry for the view.
2443 a->limit_match = limit_match;
2446 if (*a->searching == TOG_SEARCH_FORWARD &&
2447 !*a->search_next_done) {
2448 int have_match;
2449 err = match_commit(&have_match, &id, commit, a->regex);
2450 if (err)
2451 break;
2453 if (*a->limiting) {
2454 if (limit_match && have_match)
2455 *a->search_next_done =
2456 TOG_SEARCH_HAVE_MORE;
2457 } else if (have_match)
2458 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2461 errcode = pthread_mutex_unlock(&tog_mutex);
2462 if (errcode && err == NULL)
2463 err = got_error_set_errno(errcode,
2464 "pthread_mutex_unlock");
2465 if (err)
2466 break;
2467 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2469 return err;
2472 static void
2473 select_commit(struct tog_log_view_state *s)
2475 struct commit_queue_entry *entry;
2476 int ncommits = 0;
2478 entry = s->first_displayed_entry;
2479 while (entry) {
2480 if (ncommits == s->selected) {
2481 s->selected_entry = entry;
2482 break;
2484 entry = TAILQ_NEXT(entry, entry);
2485 ncommits++;
2489 static const struct got_error *
2490 draw_commits(struct tog_view *view)
2492 const struct got_error *err = NULL;
2493 struct tog_log_view_state *s = &view->state.log;
2494 struct commit_queue_entry *entry = s->selected_entry;
2495 int limit = view->nlines;
2496 int width;
2497 int ncommits, author_cols = 4;
2498 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2499 char *refs_str = NULL;
2500 wchar_t *wline;
2501 struct tog_color *tc;
2502 static const size_t date_display_cols = 12;
2504 if (view_is_hsplit_top(view))
2505 --limit; /* account for border */
2507 if (s->selected_entry &&
2508 !(view->searching && view->search_next_done == 0)) {
2509 struct got_reflist_head *refs;
2510 err = got_object_id_str(&id_str, s->selected_entry->id);
2511 if (err)
2512 return err;
2513 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2514 s->selected_entry->id);
2515 if (refs) {
2516 err = build_refs_str(&refs_str, refs,
2517 s->selected_entry->id, s->repo);
2518 if (err)
2519 goto done;
2523 if (s->thread_args.commits_needed == 0)
2524 halfdelay(10); /* disable fast refresh */
2526 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2527 if (asprintf(&ncommits_str, " [%d/%d] %s",
2528 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2529 (view->searching && !view->search_next_done) ?
2530 "searching..." : "loading...") == -1) {
2531 err = got_error_from_errno("asprintf");
2532 goto done;
2534 } else {
2535 const char *search_str = NULL;
2536 const char *limit_str = NULL;
2538 if (view->searching) {
2539 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2540 search_str = "no more matches";
2541 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2542 search_str = "no matches found";
2543 else if (!view->search_next_done)
2544 search_str = "searching...";
2547 if (s->limit_view && s->commits->ncommits == 0)
2548 limit_str = "no matches found";
2550 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2551 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2552 search_str ? search_str : (refs_str ? refs_str : ""),
2553 limit_str ? limit_str : "") == -1) {
2554 err = got_error_from_errno("asprintf");
2555 goto done;
2559 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2560 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2561 "........................................",
2562 s->in_repo_path, ncommits_str) == -1) {
2563 err = got_error_from_errno("asprintf");
2564 header = NULL;
2565 goto done;
2567 } else if (asprintf(&header, "commit %s%s",
2568 id_str ? id_str : "........................................",
2569 ncommits_str) == -1) {
2570 err = got_error_from_errno("asprintf");
2571 header = NULL;
2572 goto done;
2574 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2575 if (err)
2576 goto done;
2578 werase(view->window);
2580 if (view_needs_focus_indication(view))
2581 wstandout(view->window);
2582 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2583 if (tc)
2584 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2585 waddwstr(view->window, wline);
2586 while (width < view->ncols) {
2587 waddch(view->window, ' ');
2588 width++;
2590 if (tc)
2591 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2592 if (view_needs_focus_indication(view))
2593 wstandend(view->window);
2594 free(wline);
2595 if (limit <= 1)
2596 goto done;
2598 /* Grow author column size if necessary, and set view->maxx. */
2599 entry = s->first_displayed_entry;
2600 ncommits = 0;
2601 view->maxx = 0;
2602 while (entry) {
2603 struct got_commit_object *c = entry->commit;
2604 char *author, *eol, *msg, *msg0;
2605 wchar_t *wauthor, *wmsg;
2606 int width;
2607 if (ncommits >= limit - 1)
2608 break;
2609 if (s->use_committer)
2610 author = strdup(got_object_commit_get_committer(c));
2611 else
2612 author = strdup(got_object_commit_get_author(c));
2613 if (author == NULL) {
2614 err = got_error_from_errno("strdup");
2615 goto done;
2617 err = format_author(&wauthor, &width, author, COLS,
2618 date_display_cols);
2619 if (author_cols < width)
2620 author_cols = width;
2621 free(wauthor);
2622 free(author);
2623 if (err)
2624 goto done;
2625 err = got_object_commit_get_logmsg(&msg0, c);
2626 if (err)
2627 goto done;
2628 msg = msg0;
2629 while (*msg == '\n')
2630 ++msg;
2631 if ((eol = strchr(msg, '\n')))
2632 *eol = '\0';
2633 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2634 date_display_cols + author_cols, 0);
2635 if (err)
2636 goto done;
2637 view->maxx = MAX(view->maxx, width);
2638 free(msg0);
2639 free(wmsg);
2640 ncommits++;
2641 entry = TAILQ_NEXT(entry, entry);
2644 entry = s->first_displayed_entry;
2645 s->last_displayed_entry = s->first_displayed_entry;
2646 ncommits = 0;
2647 while (entry) {
2648 if (ncommits >= limit - 1)
2649 break;
2650 if (ncommits == s->selected)
2651 wstandout(view->window);
2652 err = draw_commit(view, entry->commit, entry->id,
2653 date_display_cols, author_cols);
2654 if (ncommits == s->selected)
2655 wstandend(view->window);
2656 if (err)
2657 goto done;
2658 ncommits++;
2659 s->last_displayed_entry = entry;
2660 entry = TAILQ_NEXT(entry, entry);
2663 view_border(view);
2664 done:
2665 free(id_str);
2666 free(refs_str);
2667 free(ncommits_str);
2668 free(header);
2669 return err;
2672 static void
2673 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2675 struct commit_queue_entry *entry;
2676 int nscrolled = 0;
2678 entry = TAILQ_FIRST(&s->commits->head);
2679 if (s->first_displayed_entry == entry)
2680 return;
2682 entry = s->first_displayed_entry;
2683 while (entry && nscrolled < maxscroll) {
2684 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2685 if (entry) {
2686 s->first_displayed_entry = entry;
2687 nscrolled++;
2692 static const struct got_error *
2693 trigger_log_thread(struct tog_view *view, int wait)
2695 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2696 int errcode;
2698 halfdelay(1); /* fast refresh while loading commits */
2700 while (!ta->log_complete && !tog_thread_error &&
2701 (ta->commits_needed > 0 || ta->load_all)) {
2702 /* Wake the log thread. */
2703 errcode = pthread_cond_signal(&ta->need_commits);
2704 if (errcode)
2705 return got_error_set_errno(errcode,
2706 "pthread_cond_signal");
2709 * The mutex will be released while the view loop waits
2710 * in wgetch(), at which time the log thread will run.
2712 if (!wait)
2713 break;
2715 /* Display progress update in log view. */
2716 show_log_view(view);
2717 update_panels();
2718 doupdate();
2720 /* Wait right here while next commit is being loaded. */
2721 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2722 if (errcode)
2723 return got_error_set_errno(errcode,
2724 "pthread_cond_wait");
2726 /* Display progress update in log view. */
2727 show_log_view(view);
2728 update_panels();
2729 doupdate();
2732 return NULL;
2735 static const struct got_error *
2736 request_log_commits(struct tog_view *view)
2738 struct tog_log_view_state *state = &view->state.log;
2739 const struct got_error *err = NULL;
2741 if (state->thread_args.log_complete)
2742 return NULL;
2744 state->thread_args.commits_needed += view->nscrolled;
2745 err = trigger_log_thread(view, 1);
2746 view->nscrolled = 0;
2748 return err;
2751 static const struct got_error *
2752 log_scroll_down(struct tog_view *view, int maxscroll)
2754 struct tog_log_view_state *s = &view->state.log;
2755 const struct got_error *err = NULL;
2756 struct commit_queue_entry *pentry;
2757 int nscrolled = 0, ncommits_needed;
2759 if (s->last_displayed_entry == NULL)
2760 return NULL;
2762 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2763 if (s->commits->ncommits < ncommits_needed &&
2764 !s->thread_args.log_complete) {
2766 * Ask the log thread for required amount of commits.
2768 s->thread_args.commits_needed +=
2769 ncommits_needed - s->commits->ncommits;
2770 err = trigger_log_thread(view, 1);
2771 if (err)
2772 return err;
2775 do {
2776 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2777 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2778 break;
2780 s->last_displayed_entry = pentry ?
2781 pentry : s->last_displayed_entry;
2783 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2784 if (pentry == NULL)
2785 break;
2786 s->first_displayed_entry = pentry;
2787 } while (++nscrolled < maxscroll);
2789 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2790 view->nscrolled += nscrolled;
2791 else
2792 view->nscrolled = 0;
2794 return err;
2797 static const struct got_error *
2798 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2799 struct got_commit_object *commit, struct got_object_id *commit_id,
2800 struct tog_view *log_view, struct got_repository *repo)
2802 const struct got_error *err;
2803 struct got_object_qid *parent_id;
2804 struct tog_view *diff_view;
2806 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2807 if (diff_view == NULL)
2808 return got_error_from_errno("view_open");
2810 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2811 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2812 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2813 if (err == NULL)
2814 *new_view = diff_view;
2815 return err;
2818 static const struct got_error *
2819 tree_view_visit_subtree(struct tog_tree_view_state *s,
2820 struct got_tree_object *subtree)
2822 struct tog_parent_tree *parent;
2824 parent = calloc(1, sizeof(*parent));
2825 if (parent == NULL)
2826 return got_error_from_errno("calloc");
2828 parent->tree = s->tree;
2829 parent->first_displayed_entry = s->first_displayed_entry;
2830 parent->selected_entry = s->selected_entry;
2831 parent->selected = s->selected;
2832 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2833 s->tree = subtree;
2834 s->selected = 0;
2835 s->first_displayed_entry = NULL;
2836 return NULL;
2839 static const struct got_error *
2840 tree_view_walk_path(struct tog_tree_view_state *s,
2841 struct got_commit_object *commit, const char *path)
2843 const struct got_error *err = NULL;
2844 struct got_tree_object *tree = NULL;
2845 const char *p;
2846 char *slash, *subpath = NULL;
2848 /* Walk the path and open corresponding tree objects. */
2849 p = path;
2850 while (*p) {
2851 struct got_tree_entry *te;
2852 struct got_object_id *tree_id;
2853 char *te_name;
2855 while (p[0] == '/')
2856 p++;
2858 /* Ensure the correct subtree entry is selected. */
2859 slash = strchr(p, '/');
2860 if (slash == NULL)
2861 te_name = strdup(p);
2862 else
2863 te_name = strndup(p, slash - p);
2864 if (te_name == NULL) {
2865 err = got_error_from_errno("strndup");
2866 break;
2868 te = got_object_tree_find_entry(s->tree, te_name);
2869 if (te == NULL) {
2870 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2871 free(te_name);
2872 break;
2874 free(te_name);
2875 s->first_displayed_entry = s->selected_entry = te;
2877 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2878 break; /* jump to this file's entry */
2880 slash = strchr(p, '/');
2881 if (slash)
2882 subpath = strndup(path, slash - path);
2883 else
2884 subpath = strdup(path);
2885 if (subpath == NULL) {
2886 err = got_error_from_errno("strdup");
2887 break;
2890 err = got_object_id_by_path(&tree_id, s->repo, commit,
2891 subpath);
2892 if (err)
2893 break;
2895 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2896 free(tree_id);
2897 if (err)
2898 break;
2900 err = tree_view_visit_subtree(s, tree);
2901 if (err) {
2902 got_object_tree_close(tree);
2903 break;
2905 if (slash == NULL)
2906 break;
2907 free(subpath);
2908 subpath = NULL;
2909 p = slash;
2912 free(subpath);
2913 return err;
2916 static const struct got_error *
2917 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2918 struct commit_queue_entry *entry, const char *path,
2919 const char *head_ref_name, struct got_repository *repo)
2921 const struct got_error *err = NULL;
2922 struct tog_tree_view_state *s;
2923 struct tog_view *tree_view;
2925 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2926 if (tree_view == NULL)
2927 return got_error_from_errno("view_open");
2929 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2930 if (err)
2931 return err;
2932 s = &tree_view->state.tree;
2934 *new_view = tree_view;
2936 if (got_path_is_root_dir(path))
2937 return NULL;
2939 return tree_view_walk_path(s, entry->commit, path);
2942 static const struct got_error *
2943 block_signals_used_by_main_thread(void)
2945 sigset_t sigset;
2946 int errcode;
2948 if (sigemptyset(&sigset) == -1)
2949 return got_error_from_errno("sigemptyset");
2951 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2952 if (sigaddset(&sigset, SIGWINCH) == -1)
2953 return got_error_from_errno("sigaddset");
2954 if (sigaddset(&sigset, SIGCONT) == -1)
2955 return got_error_from_errno("sigaddset");
2956 if (sigaddset(&sigset, SIGINT) == -1)
2957 return got_error_from_errno("sigaddset");
2958 if (sigaddset(&sigset, SIGTERM) == -1)
2959 return got_error_from_errno("sigaddset");
2961 /* ncurses handles SIGTSTP */
2962 if (sigaddset(&sigset, SIGTSTP) == -1)
2963 return got_error_from_errno("sigaddset");
2965 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2966 if (errcode)
2967 return got_error_set_errno(errcode, "pthread_sigmask");
2969 return NULL;
2972 static void *
2973 log_thread(void *arg)
2975 const struct got_error *err = NULL;
2976 int errcode = 0;
2977 struct tog_log_thread_args *a = arg;
2978 int done = 0;
2981 * Sync startup with main thread such that we begin our
2982 * work once view_input() has released the mutex.
2984 errcode = pthread_mutex_lock(&tog_mutex);
2985 if (errcode) {
2986 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2987 return (void *)err;
2990 err = block_signals_used_by_main_thread();
2991 if (err) {
2992 pthread_mutex_unlock(&tog_mutex);
2993 goto done;
2996 while (!done && !err && !tog_fatal_signal_received()) {
2997 errcode = pthread_mutex_unlock(&tog_mutex);
2998 if (errcode) {
2999 err = got_error_set_errno(errcode,
3000 "pthread_mutex_unlock");
3001 goto done;
3003 err = queue_commits(a);
3004 if (err) {
3005 if (err->code != GOT_ERR_ITER_COMPLETED)
3006 goto done;
3007 err = NULL;
3008 done = 1;
3009 } else if (a->commits_needed > 0 && !a->load_all) {
3010 if (*a->limiting) {
3011 if (a->limit_match)
3012 a->commits_needed--;
3013 } else
3014 a->commits_needed--;
3017 errcode = pthread_mutex_lock(&tog_mutex);
3018 if (errcode) {
3019 err = got_error_set_errno(errcode,
3020 "pthread_mutex_lock");
3021 goto done;
3022 } else if (*a->quit)
3023 done = 1;
3024 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3025 *a->first_displayed_entry =
3026 TAILQ_FIRST(&a->limit_commits->head);
3027 *a->selected_entry = *a->first_displayed_entry;
3028 } else if (*a->first_displayed_entry == NULL) {
3029 *a->first_displayed_entry =
3030 TAILQ_FIRST(&a->real_commits->head);
3031 *a->selected_entry = *a->first_displayed_entry;
3034 errcode = pthread_cond_signal(&a->commit_loaded);
3035 if (errcode) {
3036 err = got_error_set_errno(errcode,
3037 "pthread_cond_signal");
3038 pthread_mutex_unlock(&tog_mutex);
3039 goto done;
3042 if (done)
3043 a->commits_needed = 0;
3044 else {
3045 if (a->commits_needed == 0 && !a->load_all) {
3046 errcode = pthread_cond_wait(&a->need_commits,
3047 &tog_mutex);
3048 if (errcode) {
3049 err = got_error_set_errno(errcode,
3050 "pthread_cond_wait");
3051 pthread_mutex_unlock(&tog_mutex);
3052 goto done;
3054 if (*a->quit)
3055 done = 1;
3059 a->log_complete = 1;
3060 errcode = pthread_mutex_unlock(&tog_mutex);
3061 if (errcode)
3062 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3063 done:
3064 if (err) {
3065 tog_thread_error = 1;
3066 pthread_cond_signal(&a->commit_loaded);
3068 return (void *)err;
3071 static const struct got_error *
3072 stop_log_thread(struct tog_log_view_state *s)
3074 const struct got_error *err = NULL, *thread_err = NULL;
3075 int errcode;
3077 if (s->thread) {
3078 s->quit = 1;
3079 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3080 if (errcode)
3081 return got_error_set_errno(errcode,
3082 "pthread_cond_signal");
3083 errcode = pthread_mutex_unlock(&tog_mutex);
3084 if (errcode)
3085 return got_error_set_errno(errcode,
3086 "pthread_mutex_unlock");
3087 errcode = pthread_join(s->thread, (void **)&thread_err);
3088 if (errcode)
3089 return got_error_set_errno(errcode, "pthread_join");
3090 errcode = pthread_mutex_lock(&tog_mutex);
3091 if (errcode)
3092 return got_error_set_errno(errcode,
3093 "pthread_mutex_lock");
3094 s->thread = NULL;
3097 if (s->thread_args.repo) {
3098 err = got_repo_close(s->thread_args.repo);
3099 s->thread_args.repo = NULL;
3102 if (s->thread_args.pack_fds) {
3103 const struct got_error *pack_err =
3104 got_repo_pack_fds_close(s->thread_args.pack_fds);
3105 if (err == NULL)
3106 err = pack_err;
3107 s->thread_args.pack_fds = NULL;
3110 if (s->thread_args.graph) {
3111 got_commit_graph_close(s->thread_args.graph);
3112 s->thread_args.graph = NULL;
3115 return err ? err : thread_err;
3118 static const struct got_error *
3119 close_log_view(struct tog_view *view)
3121 const struct got_error *err = NULL;
3122 struct tog_log_view_state *s = &view->state.log;
3123 int errcode;
3125 err = stop_log_thread(s);
3127 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3128 if (errcode && err == NULL)
3129 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3131 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3132 if (errcode && err == NULL)
3133 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3135 free_commits(&s->limit_commits);
3136 free_commits(&s->real_commits);
3137 free(s->in_repo_path);
3138 s->in_repo_path = NULL;
3139 free(s->start_id);
3140 s->start_id = NULL;
3141 free(s->head_ref_name);
3142 s->head_ref_name = NULL;
3143 return err;
3147 * We use two queues to implement the limit feature: first consists of
3148 * commits matching the current limit_regex; second is the real queue
3149 * of all known commits (real_commits). When the user starts limiting,
3150 * we swap queues such that all movement and displaying functionality
3151 * works with very slight change.
3153 static const struct got_error *
3154 limit_log_view(struct tog_view *view)
3156 struct tog_log_view_state *s = &view->state.log;
3157 struct commit_queue_entry *entry;
3158 struct tog_view *v = view;
3159 const struct got_error *err = NULL;
3160 char pattern[1024];
3161 int ret;
3163 if (view_is_hsplit_top(view))
3164 v = view->child;
3165 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3166 v = view->parent;
3168 /* Get the pattern */
3169 wmove(v->window, v->nlines - 1, 0);
3170 wclrtoeol(v->window);
3171 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3172 nodelay(v->window, FALSE);
3173 nocbreak();
3174 echo();
3175 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3176 cbreak();
3177 noecho();
3178 nodelay(v->window, TRUE);
3179 if (ret == ERR)
3180 return NULL;
3182 if (*pattern == '\0') {
3184 * Safety measure for the situation where the user
3185 * resets limit without previously limiting anything.
3187 if (!s->limit_view)
3188 return NULL;
3191 * User could have pressed Ctrl+L, which refreshed the
3192 * commit queues, it means we can't save previously
3193 * (before limit took place) displayed entries,
3194 * because they would point to already free'ed memory,
3195 * so we are forced to always select first entry of
3196 * the queue.
3198 s->commits = &s->real_commits;
3199 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3200 s->selected_entry = s->first_displayed_entry;
3201 s->selected = 0;
3202 s->limit_view = 0;
3204 return NULL;
3207 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3208 return NULL;
3210 s->limit_view = 1;
3212 /* Clear the screen while loading limit view */
3213 s->first_displayed_entry = NULL;
3214 s->last_displayed_entry = NULL;
3215 s->selected_entry = NULL;
3216 s->commits = &s->limit_commits;
3218 /* Prepare limit queue for new search */
3219 free_commits(&s->limit_commits);
3220 s->limit_commits.ncommits = 0;
3222 /* First process commits, which are in queue already */
3223 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3224 int have_match = 0;
3226 err = match_commit(&have_match, entry->id,
3227 entry->commit, &s->limit_regex);
3228 if (err)
3229 return err;
3231 if (have_match) {
3232 struct commit_queue_entry *matched;
3234 matched = alloc_commit_queue_entry(entry->commit,
3235 entry->id);
3236 if (matched == NULL) {
3237 err = got_error_from_errno(
3238 "alloc_commit_queue_entry");
3239 break;
3241 matched->commit = entry->commit;
3242 got_object_commit_retain(entry->commit);
3244 matched->idx = s->limit_commits.ncommits;
3245 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3246 matched, entry);
3247 s->limit_commits.ncommits++;
3251 /* Second process all the commits, until we fill the screen */
3252 if (s->limit_commits.ncommits < view->nlines - 1 &&
3253 !s->thread_args.log_complete) {
3254 s->thread_args.commits_needed +=
3255 view->nlines - s->limit_commits.ncommits - 1;
3256 err = trigger_log_thread(view, 1);
3257 if (err)
3258 return err;
3261 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3262 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3263 s->selected = 0;
3265 return NULL;
3268 static const struct got_error *
3269 search_start_log_view(struct tog_view *view)
3271 struct tog_log_view_state *s = &view->state.log;
3273 s->matched_entry = NULL;
3274 s->search_entry = NULL;
3275 return NULL;
3278 static const struct got_error *
3279 search_next_log_view(struct tog_view *view)
3281 const struct got_error *err = NULL;
3282 struct tog_log_view_state *s = &view->state.log;
3283 struct commit_queue_entry *entry;
3285 /* Display progress update in log view. */
3286 show_log_view(view);
3287 update_panels();
3288 doupdate();
3290 if (s->search_entry) {
3291 int errcode, ch;
3292 errcode = pthread_mutex_unlock(&tog_mutex);
3293 if (errcode)
3294 return got_error_set_errno(errcode,
3295 "pthread_mutex_unlock");
3296 ch = wgetch(view->window);
3297 errcode = pthread_mutex_lock(&tog_mutex);
3298 if (errcode)
3299 return got_error_set_errno(errcode,
3300 "pthread_mutex_lock");
3301 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3302 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3303 return NULL;
3305 if (view->searching == TOG_SEARCH_FORWARD)
3306 entry = TAILQ_NEXT(s->search_entry, entry);
3307 else
3308 entry = TAILQ_PREV(s->search_entry,
3309 commit_queue_head, entry);
3310 } else if (s->matched_entry) {
3312 * If the user has moved the cursor after we hit a match,
3313 * the position from where we should continue searching
3314 * might have changed.
3316 if (view->searching == TOG_SEARCH_FORWARD)
3317 entry = TAILQ_NEXT(s->selected_entry, entry);
3318 else
3319 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3320 entry);
3321 } else {
3322 entry = s->selected_entry;
3325 while (1) {
3326 int have_match = 0;
3328 if (entry == NULL) {
3329 if (s->thread_args.log_complete ||
3330 view->searching == TOG_SEARCH_BACKWARD) {
3331 view->search_next_done =
3332 (s->matched_entry == NULL ?
3333 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3334 s->search_entry = NULL;
3335 return NULL;
3338 * Poke the log thread for more commits and return,
3339 * allowing the main loop to make progress. Search
3340 * will resume at s->search_entry once we come back.
3342 s->thread_args.commits_needed++;
3343 return trigger_log_thread(view, 0);
3346 err = match_commit(&have_match, entry->id, entry->commit,
3347 &view->regex);
3348 if (err)
3349 break;
3350 if (have_match) {
3351 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3352 s->matched_entry = entry;
3353 break;
3356 s->search_entry = entry;
3357 if (view->searching == TOG_SEARCH_FORWARD)
3358 entry = TAILQ_NEXT(entry, entry);
3359 else
3360 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3363 if (s->matched_entry) {
3364 int cur = s->selected_entry->idx;
3365 while (cur < s->matched_entry->idx) {
3366 err = input_log_view(NULL, view, KEY_DOWN);
3367 if (err)
3368 return err;
3369 cur++;
3371 while (cur > s->matched_entry->idx) {
3372 err = input_log_view(NULL, view, KEY_UP);
3373 if (err)
3374 return err;
3375 cur--;
3379 s->search_entry = NULL;
3381 return NULL;
3384 static const struct got_error *
3385 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3386 struct got_repository *repo, const char *head_ref_name,
3387 const char *in_repo_path, int log_branches)
3389 const struct got_error *err = NULL;
3390 struct tog_log_view_state *s = &view->state.log;
3391 struct got_repository *thread_repo = NULL;
3392 struct got_commit_graph *thread_graph = NULL;
3393 int errcode;
3395 if (in_repo_path != s->in_repo_path) {
3396 free(s->in_repo_path);
3397 s->in_repo_path = strdup(in_repo_path);
3398 if (s->in_repo_path == NULL)
3399 return got_error_from_errno("strdup");
3402 /* The commit queue only contains commits being displayed. */
3403 TAILQ_INIT(&s->real_commits.head);
3404 s->real_commits.ncommits = 0;
3405 s->commits = &s->real_commits;
3407 TAILQ_INIT(&s->limit_commits.head);
3408 s->limit_view = 0;
3409 s->limit_commits.ncommits = 0;
3411 s->repo = repo;
3412 if (head_ref_name) {
3413 s->head_ref_name = strdup(head_ref_name);
3414 if (s->head_ref_name == NULL) {
3415 err = got_error_from_errno("strdup");
3416 goto done;
3419 s->start_id = got_object_id_dup(start_id);
3420 if (s->start_id == NULL) {
3421 err = got_error_from_errno("got_object_id_dup");
3422 goto done;
3424 s->log_branches = log_branches;
3425 s->use_committer = 1;
3427 STAILQ_INIT(&s->colors);
3428 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3429 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3430 get_color_value("TOG_COLOR_COMMIT"));
3431 if (err)
3432 goto done;
3433 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3434 get_color_value("TOG_COLOR_AUTHOR"));
3435 if (err) {
3436 free_colors(&s->colors);
3437 goto done;
3439 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3440 get_color_value("TOG_COLOR_DATE"));
3441 if (err) {
3442 free_colors(&s->colors);
3443 goto done;
3447 view->show = show_log_view;
3448 view->input = input_log_view;
3449 view->resize = resize_log_view;
3450 view->close = close_log_view;
3451 view->search_start = search_start_log_view;
3452 view->search_next = search_next_log_view;
3454 if (s->thread_args.pack_fds == NULL) {
3455 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3456 if (err)
3457 goto done;
3459 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3460 s->thread_args.pack_fds);
3461 if (err)
3462 goto done;
3463 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3464 !s->log_branches);
3465 if (err)
3466 goto done;
3467 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3468 s->repo, NULL, NULL);
3469 if (err)
3470 goto done;
3472 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3473 if (errcode) {
3474 err = got_error_set_errno(errcode, "pthread_cond_init");
3475 goto done;
3477 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3478 if (errcode) {
3479 err = got_error_set_errno(errcode, "pthread_cond_init");
3480 goto done;
3483 s->thread_args.commits_needed = view->nlines;
3484 s->thread_args.graph = thread_graph;
3485 s->thread_args.real_commits = &s->real_commits;
3486 s->thread_args.limit_commits = &s->limit_commits;
3487 s->thread_args.in_repo_path = s->in_repo_path;
3488 s->thread_args.start_id = s->start_id;
3489 s->thread_args.repo = thread_repo;
3490 s->thread_args.log_complete = 0;
3491 s->thread_args.quit = &s->quit;
3492 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3493 s->thread_args.selected_entry = &s->selected_entry;
3494 s->thread_args.searching = &view->searching;
3495 s->thread_args.search_next_done = &view->search_next_done;
3496 s->thread_args.regex = &view->regex;
3497 s->thread_args.limiting = &s->limit_view;
3498 s->thread_args.limit_regex = &s->limit_regex;
3499 s->thread_args.limit_commits = &s->limit_commits;
3500 done:
3501 if (err)
3502 close_log_view(view);
3503 return err;
3506 static const struct got_error *
3507 show_log_view(struct tog_view *view)
3509 const struct got_error *err;
3510 struct tog_log_view_state *s = &view->state.log;
3512 if (s->thread == NULL) {
3513 int errcode = pthread_create(&s->thread, NULL, log_thread,
3514 &s->thread_args);
3515 if (errcode)
3516 return got_error_set_errno(errcode, "pthread_create");
3517 if (s->thread_args.commits_needed > 0) {
3518 err = trigger_log_thread(view, 1);
3519 if (err)
3520 return err;
3524 return draw_commits(view);
3527 static void
3528 log_move_cursor_up(struct tog_view *view, int page, int home)
3530 struct tog_log_view_state *s = &view->state.log;
3532 if (s->first_displayed_entry == NULL)
3533 return;
3534 if (s->selected_entry->idx == 0)
3535 view->count = 0;
3537 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3538 || home)
3539 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3541 if (!page && !home && s->selected > 0)
3542 --s->selected;
3543 else
3544 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3546 select_commit(s);
3547 return;
3550 static const struct got_error *
3551 log_move_cursor_down(struct tog_view *view, int page)
3553 struct tog_log_view_state *s = &view->state.log;
3554 const struct got_error *err = NULL;
3555 int eos = view->nlines - 2;
3557 if (s->first_displayed_entry == NULL)
3558 return NULL;
3560 if (s->thread_args.log_complete &&
3561 s->selected_entry->idx >= s->commits->ncommits - 1)
3562 return NULL;
3564 if (view_is_hsplit_top(view))
3565 --eos; /* border consumes the last line */
3567 if (!page) {
3568 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3569 ++s->selected;
3570 else
3571 err = log_scroll_down(view, 1);
3572 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3573 struct commit_queue_entry *entry;
3574 int n;
3576 s->selected = 0;
3577 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3578 s->last_displayed_entry = entry;
3579 for (n = 0; n <= eos; n++) {
3580 if (entry == NULL)
3581 break;
3582 s->first_displayed_entry = entry;
3583 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3585 if (n > 0)
3586 s->selected = n - 1;
3587 } else {
3588 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3589 s->thread_args.log_complete)
3590 s->selected += MIN(page,
3591 s->commits->ncommits - s->selected_entry->idx - 1);
3592 else
3593 err = log_scroll_down(view, page);
3595 if (err)
3596 return err;
3599 * We might necessarily overshoot in horizontal
3600 * splits; if so, select the last displayed commit.
3602 if (s->first_displayed_entry && s->last_displayed_entry) {
3603 s->selected = MIN(s->selected,
3604 s->last_displayed_entry->idx -
3605 s->first_displayed_entry->idx);
3608 select_commit(s);
3610 if (s->thread_args.log_complete &&
3611 s->selected_entry->idx == s->commits->ncommits - 1)
3612 view->count = 0;
3614 return NULL;
3617 static void
3618 view_get_split(struct tog_view *view, int *y, int *x)
3620 *x = 0;
3621 *y = 0;
3623 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3624 if (view->child && view->child->resized_y)
3625 *y = view->child->resized_y;
3626 else if (view->resized_y)
3627 *y = view->resized_y;
3628 else
3629 *y = view_split_begin_y(view->lines);
3630 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3631 if (view->child && view->child->resized_x)
3632 *x = view->child->resized_x;
3633 else if (view->resized_x)
3634 *x = view->resized_x;
3635 else
3636 *x = view_split_begin_x(view->begin_x);
3640 /* Split view horizontally at y and offset view->state->selected line. */
3641 static const struct got_error *
3642 view_init_hsplit(struct tog_view *view, int y)
3644 const struct got_error *err = NULL;
3646 view->nlines = y;
3647 view->ncols = COLS;
3648 err = view_resize(view);
3649 if (err)
3650 return err;
3652 err = offset_selection_down(view);
3654 return err;
3657 static const struct got_error *
3658 log_goto_line(struct tog_view *view, int nlines)
3660 const struct got_error *err = NULL;
3661 struct tog_log_view_state *s = &view->state.log;
3662 int g, idx = s->selected_entry->idx;
3664 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3665 return NULL;
3667 g = view->gline;
3668 view->gline = 0;
3670 if (g >= s->first_displayed_entry->idx + 1 &&
3671 g <= s->last_displayed_entry->idx + 1 &&
3672 g - s->first_displayed_entry->idx - 1 < nlines) {
3673 s->selected = g - s->first_displayed_entry->idx - 1;
3674 select_commit(s);
3675 return NULL;
3678 if (idx + 1 < g) {
3679 err = log_move_cursor_down(view, g - idx - 1);
3680 if (!err && g > s->selected_entry->idx + 1)
3681 err = log_move_cursor_down(view,
3682 g - s->first_displayed_entry->idx - 1);
3683 if (err)
3684 return err;
3685 } else if (idx + 1 > g)
3686 log_move_cursor_up(view, idx - g + 1, 0);
3688 if (g < nlines && s->first_displayed_entry->idx == 0)
3689 s->selected = g - 1;
3691 select_commit(s);
3692 return NULL;
3696 static void
3697 horizontal_scroll_input(struct tog_view *view, int ch)
3700 switch (ch) {
3701 case KEY_LEFT:
3702 case 'h':
3703 view->x -= MIN(view->x, 2);
3704 if (view->x <= 0)
3705 view->count = 0;
3706 break;
3707 case KEY_RIGHT:
3708 case 'l':
3709 if (view->x + view->ncols / 2 < view->maxx)
3710 view->x += 2;
3711 else
3712 view->count = 0;
3713 break;
3714 case '0':
3715 view->x = 0;
3716 break;
3717 case '$':
3718 view->x = MAX(view->maxx - view->ncols / 2, 0);
3719 view->count = 0;
3720 break;
3721 default:
3722 break;
3726 static const struct got_error *
3727 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3729 const struct got_error *err = NULL;
3730 struct tog_log_view_state *s = &view->state.log;
3731 int eos, nscroll;
3733 if (s->thread_args.load_all) {
3734 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3735 s->thread_args.load_all = 0;
3736 else if (s->thread_args.log_complete) {
3737 err = log_move_cursor_down(view, s->commits->ncommits);
3738 s->thread_args.load_all = 0;
3740 if (err)
3741 return err;
3744 eos = nscroll = view->nlines - 1;
3745 if (view_is_hsplit_top(view))
3746 --eos; /* border */
3748 if (view->gline)
3749 return log_goto_line(view, eos);
3751 switch (ch) {
3752 case '&':
3753 err = limit_log_view(view);
3754 break;
3755 case 'q':
3756 s->quit = 1;
3757 break;
3758 case '0':
3759 case '$':
3760 case KEY_RIGHT:
3761 case 'l':
3762 case KEY_LEFT:
3763 case 'h':
3764 horizontal_scroll_input(view, ch);
3765 break;
3766 case 'k':
3767 case KEY_UP:
3768 case '<':
3769 case ',':
3770 case CTRL('p'):
3771 log_move_cursor_up(view, 0, 0);
3772 break;
3773 case 'g':
3774 case '=':
3775 case KEY_HOME:
3776 log_move_cursor_up(view, 0, 1);
3777 view->count = 0;
3778 break;
3779 case CTRL('u'):
3780 case 'u':
3781 nscroll /= 2;
3782 /* FALL THROUGH */
3783 case KEY_PPAGE:
3784 case CTRL('b'):
3785 case 'b':
3786 log_move_cursor_up(view, nscroll, 0);
3787 break;
3788 case 'j':
3789 case KEY_DOWN:
3790 case '>':
3791 case '.':
3792 case CTRL('n'):
3793 err = log_move_cursor_down(view, 0);
3794 break;
3795 case '@':
3796 s->use_committer = !s->use_committer;
3797 view->action = s->use_committer ?
3798 "show committer" : "show commit author";
3799 break;
3800 case 'G':
3801 case '*':
3802 case KEY_END: {
3803 /* We don't know yet how many commits, so we're forced to
3804 * traverse them all. */
3805 view->count = 0;
3806 s->thread_args.load_all = 1;
3807 if (!s->thread_args.log_complete)
3808 return trigger_log_thread(view, 0);
3809 err = log_move_cursor_down(view, s->commits->ncommits);
3810 s->thread_args.load_all = 0;
3811 break;
3813 case CTRL('d'):
3814 case 'd':
3815 nscroll /= 2;
3816 /* FALL THROUGH */
3817 case KEY_NPAGE:
3818 case CTRL('f'):
3819 case 'f':
3820 case ' ':
3821 err = log_move_cursor_down(view, nscroll);
3822 break;
3823 case KEY_RESIZE:
3824 if (s->selected > view->nlines - 2)
3825 s->selected = view->nlines - 2;
3826 if (s->selected > s->commits->ncommits - 1)
3827 s->selected = s->commits->ncommits - 1;
3828 select_commit(s);
3829 if (s->commits->ncommits < view->nlines - 1 &&
3830 !s->thread_args.log_complete) {
3831 s->thread_args.commits_needed += (view->nlines - 1) -
3832 s->commits->ncommits;
3833 err = trigger_log_thread(view, 1);
3835 break;
3836 case KEY_ENTER:
3837 case '\r':
3838 view->count = 0;
3839 if (s->selected_entry == NULL)
3840 break;
3841 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3842 break;
3843 case 'T':
3844 view->count = 0;
3845 if (s->selected_entry == NULL)
3846 break;
3847 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3848 break;
3849 case KEY_BACKSPACE:
3850 case CTRL('l'):
3851 case 'B':
3852 view->count = 0;
3853 if (ch == KEY_BACKSPACE &&
3854 got_path_is_root_dir(s->in_repo_path))
3855 break;
3856 err = stop_log_thread(s);
3857 if (err)
3858 return err;
3859 if (ch == KEY_BACKSPACE) {
3860 char *parent_path;
3861 err = got_path_dirname(&parent_path, s->in_repo_path);
3862 if (err)
3863 return err;
3864 free(s->in_repo_path);
3865 s->in_repo_path = parent_path;
3866 s->thread_args.in_repo_path = s->in_repo_path;
3867 } else if (ch == CTRL('l')) {
3868 struct got_object_id *start_id;
3869 err = got_repo_match_object_id(&start_id, NULL,
3870 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3871 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3872 if (err) {
3873 if (s->head_ref_name == NULL ||
3874 err->code != GOT_ERR_NOT_REF)
3875 return err;
3876 /* Try to cope with deleted references. */
3877 free(s->head_ref_name);
3878 s->head_ref_name = NULL;
3879 err = got_repo_match_object_id(&start_id,
3880 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
3881 &tog_refs, s->repo);
3882 if (err)
3883 return err;
3885 free(s->start_id);
3886 s->start_id = start_id;
3887 s->thread_args.start_id = s->start_id;
3888 } else /* 'B' */
3889 s->log_branches = !s->log_branches;
3891 if (s->thread_args.pack_fds == NULL) {
3892 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3893 if (err)
3894 return err;
3896 err = got_repo_open(&s->thread_args.repo,
3897 got_repo_get_path(s->repo), NULL,
3898 s->thread_args.pack_fds);
3899 if (err)
3900 return err;
3901 tog_free_refs();
3902 err = tog_load_refs(s->repo, 0);
3903 if (err)
3904 return err;
3905 err = got_commit_graph_open(&s->thread_args.graph,
3906 s->in_repo_path, !s->log_branches);
3907 if (err)
3908 return err;
3909 err = got_commit_graph_iter_start(s->thread_args.graph,
3910 s->start_id, s->repo, NULL, NULL);
3911 if (err)
3912 return err;
3913 free_commits(&s->real_commits);
3914 free_commits(&s->limit_commits);
3915 s->first_displayed_entry = NULL;
3916 s->last_displayed_entry = NULL;
3917 s->selected_entry = NULL;
3918 s->selected = 0;
3919 s->thread_args.log_complete = 0;
3920 s->quit = 0;
3921 s->thread_args.commits_needed = view->lines;
3922 s->matched_entry = NULL;
3923 s->search_entry = NULL;
3924 view->offset = 0;
3925 break;
3926 case 'R':
3927 view->count = 0;
3928 err = view_request_new(new_view, view, TOG_VIEW_REF);
3929 break;
3930 default:
3931 view->count = 0;
3932 break;
3935 return err;
3938 static const struct got_error *
3939 apply_unveil(const char *repo_path, const char *worktree_path)
3941 const struct got_error *error;
3943 #ifdef PROFILE
3944 if (unveil("gmon.out", "rwc") != 0)
3945 return got_error_from_errno2("unveil", "gmon.out");
3946 #endif
3947 if (repo_path && unveil(repo_path, "r") != 0)
3948 return got_error_from_errno2("unveil", repo_path);
3950 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3951 return got_error_from_errno2("unveil", worktree_path);
3953 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3954 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3956 error = got_privsep_unveil_exec_helpers();
3957 if (error != NULL)
3958 return error;
3960 if (unveil(NULL, NULL) != 0)
3961 return got_error_from_errno("unveil");
3963 return NULL;
3966 static void
3967 init_curses(void)
3970 * Override default signal handlers before starting ncurses.
3971 * This should prevent ncurses from installing its own
3972 * broken cleanup() signal handler.
3974 signal(SIGWINCH, tog_sigwinch);
3975 signal(SIGPIPE, tog_sigpipe);
3976 signal(SIGCONT, tog_sigcont);
3977 signal(SIGINT, tog_sigint);
3978 signal(SIGTERM, tog_sigterm);
3980 initscr();
3981 cbreak();
3982 halfdelay(1); /* Do fast refresh while initial view is loading. */
3983 noecho();
3984 nonl();
3985 intrflush(stdscr, FALSE);
3986 keypad(stdscr, TRUE);
3987 curs_set(0);
3988 if (getenv("TOG_COLORS") != NULL) {
3989 start_color();
3990 use_default_colors();
3994 static const struct got_error *
3995 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3996 struct got_repository *repo, struct got_worktree *worktree)
3998 const struct got_error *err = NULL;
4000 if (argc == 0) {
4001 *in_repo_path = strdup("/");
4002 if (*in_repo_path == NULL)
4003 return got_error_from_errno("strdup");
4004 return NULL;
4007 if (worktree) {
4008 const char *prefix = got_worktree_get_path_prefix(worktree);
4009 char *p;
4011 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4012 if (err)
4013 return err;
4014 if (asprintf(in_repo_path, "%s%s%s", prefix,
4015 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4016 p) == -1) {
4017 err = got_error_from_errno("asprintf");
4018 *in_repo_path = NULL;
4020 free(p);
4021 } else
4022 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4024 return err;
4027 static const struct got_error *
4028 cmd_log(int argc, char *argv[])
4030 const struct got_error *error;
4031 struct got_repository *repo = NULL;
4032 struct got_worktree *worktree = NULL;
4033 struct got_object_id *start_id = NULL;
4034 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4035 char *start_commit = NULL, *label = NULL;
4036 struct got_reference *ref = NULL;
4037 const char *head_ref_name = NULL;
4038 int ch, log_branches = 0;
4039 struct tog_view *view;
4040 int *pack_fds = NULL;
4042 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4043 switch (ch) {
4044 case 'b':
4045 log_branches = 1;
4046 break;
4047 case 'c':
4048 start_commit = optarg;
4049 break;
4050 case 'r':
4051 repo_path = realpath(optarg, NULL);
4052 if (repo_path == NULL)
4053 return got_error_from_errno2("realpath",
4054 optarg);
4055 break;
4056 default:
4057 usage_log();
4058 /* NOTREACHED */
4062 argc -= optind;
4063 argv += optind;
4065 if (argc > 1)
4066 usage_log();
4068 error = got_repo_pack_fds_open(&pack_fds);
4069 if (error != NULL)
4070 goto done;
4072 if (repo_path == NULL) {
4073 cwd = getcwd(NULL, 0);
4074 if (cwd == NULL)
4075 return got_error_from_errno("getcwd");
4076 error = got_worktree_open(&worktree, cwd);
4077 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4078 goto done;
4079 if (worktree)
4080 repo_path =
4081 strdup(got_worktree_get_repo_path(worktree));
4082 else
4083 repo_path = strdup(cwd);
4084 if (repo_path == NULL) {
4085 error = got_error_from_errno("strdup");
4086 goto done;
4090 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4091 if (error != NULL)
4092 goto done;
4094 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4095 repo, worktree);
4096 if (error)
4097 goto done;
4099 init_curses();
4101 error = apply_unveil(got_repo_get_path(repo),
4102 worktree ? got_worktree_get_root_path(worktree) : NULL);
4103 if (error)
4104 goto done;
4106 /* already loaded by tog_log_with_path()? */
4107 if (TAILQ_EMPTY(&tog_refs)) {
4108 error = tog_load_refs(repo, 0);
4109 if (error)
4110 goto done;
4113 if (start_commit == NULL) {
4114 error = got_repo_match_object_id(&start_id, &label,
4115 worktree ? got_worktree_get_head_ref_name(worktree) :
4116 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4117 if (error)
4118 goto done;
4119 head_ref_name = label;
4120 } else {
4121 error = got_ref_open(&ref, repo, start_commit, 0);
4122 if (error == NULL)
4123 head_ref_name = got_ref_get_name(ref);
4124 else if (error->code != GOT_ERR_NOT_REF)
4125 goto done;
4126 error = got_repo_match_object_id(&start_id, NULL,
4127 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4128 if (error)
4129 goto done;
4132 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4133 if (view == NULL) {
4134 error = got_error_from_errno("view_open");
4135 goto done;
4137 error = open_log_view(view, start_id, repo, head_ref_name,
4138 in_repo_path, log_branches);
4139 if (error)
4140 goto done;
4141 if (worktree) {
4142 /* Release work tree lock. */
4143 got_worktree_close(worktree);
4144 worktree = NULL;
4146 error = view_loop(view);
4147 done:
4148 free(in_repo_path);
4149 free(repo_path);
4150 free(cwd);
4151 free(start_id);
4152 free(label);
4153 if (ref)
4154 got_ref_close(ref);
4155 if (repo) {
4156 const struct got_error *close_err = got_repo_close(repo);
4157 if (error == NULL)
4158 error = close_err;
4160 if (worktree)
4161 got_worktree_close(worktree);
4162 if (pack_fds) {
4163 const struct got_error *pack_err =
4164 got_repo_pack_fds_close(pack_fds);
4165 if (error == NULL)
4166 error = pack_err;
4168 tog_free_refs();
4169 return error;
4172 __dead static void
4173 usage_diff(void)
4175 endwin();
4176 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4177 "object1 object2\n", getprogname());
4178 exit(1);
4181 static int
4182 match_line(const char *line, regex_t *regex, size_t nmatch,
4183 regmatch_t *regmatch)
4185 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4188 static struct tog_color *
4189 match_color(struct tog_colors *colors, const char *line)
4191 struct tog_color *tc = NULL;
4193 STAILQ_FOREACH(tc, colors, entry) {
4194 if (match_line(line, &tc->regex, 0, NULL))
4195 return tc;
4198 return NULL;
4201 static const struct got_error *
4202 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4203 WINDOW *window, int skipcol, regmatch_t *regmatch)
4205 const struct got_error *err = NULL;
4206 char *exstr = NULL;
4207 wchar_t *wline = NULL;
4208 int rme, rms, n, width, scrollx;
4209 int width0 = 0, width1 = 0, width2 = 0;
4210 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4212 *wtotal = 0;
4214 rms = regmatch->rm_so;
4215 rme = regmatch->rm_eo;
4217 err = expand_tab(&exstr, line);
4218 if (err)
4219 return err;
4221 /* Split the line into 3 segments, according to match offsets. */
4222 seg0 = strndup(exstr, rms);
4223 if (seg0 == NULL) {
4224 err = got_error_from_errno("strndup");
4225 goto done;
4227 seg1 = strndup(exstr + rms, rme - rms);
4228 if (seg1 == NULL) {
4229 err = got_error_from_errno("strndup");
4230 goto done;
4232 seg2 = strdup(exstr + rme);
4233 if (seg2 == NULL) {
4234 err = got_error_from_errno("strndup");
4235 goto done;
4238 /* draw up to matched token if we haven't scrolled past it */
4239 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4240 col_tab_align, 1);
4241 if (err)
4242 goto done;
4243 n = MAX(width0 - skipcol, 0);
4244 if (n) {
4245 free(wline);
4246 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4247 wlimit, col_tab_align, 1);
4248 if (err)
4249 goto done;
4250 waddwstr(window, &wline[scrollx]);
4251 wlimit -= width;
4252 *wtotal += width;
4255 if (wlimit > 0) {
4256 int i = 0, w = 0;
4257 size_t wlen;
4259 free(wline);
4260 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4261 col_tab_align, 1);
4262 if (err)
4263 goto done;
4264 wlen = wcslen(wline);
4265 while (i < wlen) {
4266 width = wcwidth(wline[i]);
4267 if (width == -1) {
4268 /* should not happen, tabs are expanded */
4269 err = got_error(GOT_ERR_RANGE);
4270 goto done;
4272 if (width0 + w + width > skipcol)
4273 break;
4274 w += width;
4275 i++;
4277 /* draw (visible part of) matched token (if scrolled into it) */
4278 if (width1 - w > 0) {
4279 wattron(window, A_STANDOUT);
4280 waddwstr(window, &wline[i]);
4281 wattroff(window, A_STANDOUT);
4282 wlimit -= (width1 - w);
4283 *wtotal += (width1 - w);
4287 if (wlimit > 0) { /* draw rest of line */
4288 free(wline);
4289 if (skipcol > width0 + width1) {
4290 err = format_line(&wline, &width2, &scrollx, seg2,
4291 skipcol - (width0 + width1), wlimit,
4292 col_tab_align, 1);
4293 if (err)
4294 goto done;
4295 waddwstr(window, &wline[scrollx]);
4296 } else {
4297 err = format_line(&wline, &width2, NULL, seg2, 0,
4298 wlimit, col_tab_align, 1);
4299 if (err)
4300 goto done;
4301 waddwstr(window, wline);
4303 *wtotal += width2;
4305 done:
4306 free(wline);
4307 free(exstr);
4308 free(seg0);
4309 free(seg1);
4310 free(seg2);
4311 return err;
4314 static int
4315 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4317 FILE *f = NULL;
4318 int *eof, *first, *selected;
4320 if (view->type == TOG_VIEW_DIFF) {
4321 struct tog_diff_view_state *s = &view->state.diff;
4323 first = &s->first_displayed_line;
4324 selected = first;
4325 eof = &s->eof;
4326 f = s->f;
4327 } else if (view->type == TOG_VIEW_HELP) {
4328 struct tog_help_view_state *s = &view->state.help;
4330 first = &s->first_displayed_line;
4331 selected = first;
4332 eof = &s->eof;
4333 f = s->f;
4334 } else if (view->type == TOG_VIEW_BLAME) {
4335 struct tog_blame_view_state *s = &view->state.blame;
4337 first = &s->first_displayed_line;
4338 selected = &s->selected_line;
4339 eof = &s->eof;
4340 f = s->blame.f;
4341 } else
4342 return 0;
4344 /* Center gline in the middle of the page like vi(1). */
4345 if (*lineno < view->gline - (view->nlines - 3) / 2)
4346 return 0;
4347 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4348 rewind(f);
4349 *eof = 0;
4350 *first = 1;
4351 *lineno = 0;
4352 *nprinted = 0;
4353 return 0;
4356 *selected = view->gline <= (view->nlines - 3) / 2 ?
4357 view->gline : (view->nlines - 3) / 2 + 1;
4358 view->gline = 0;
4360 return 1;
4363 static const struct got_error *
4364 draw_file(struct tog_view *view, const char *header)
4366 struct tog_diff_view_state *s = &view->state.diff;
4367 regmatch_t *regmatch = &view->regmatch;
4368 const struct got_error *err;
4369 int nprinted = 0;
4370 char *line;
4371 size_t linesize = 0;
4372 ssize_t linelen;
4373 wchar_t *wline;
4374 int width;
4375 int max_lines = view->nlines;
4376 int nlines = s->nlines;
4377 off_t line_offset;
4379 s->lineno = s->first_displayed_line - 1;
4380 line_offset = s->lines[s->first_displayed_line - 1].offset;
4381 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4382 return got_error_from_errno("fseek");
4384 werase(view->window);
4386 if (view->gline > s->nlines - 1)
4387 view->gline = s->nlines - 1;
4389 if (header) {
4390 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4391 1 : view->gline - (view->nlines - 3) / 2 :
4392 s->lineno + s->selected_line;
4394 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4395 return got_error_from_errno("asprintf");
4396 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4397 0, 0);
4398 free(line);
4399 if (err)
4400 return err;
4402 if (view_needs_focus_indication(view))
4403 wstandout(view->window);
4404 waddwstr(view->window, wline);
4405 free(wline);
4406 wline = NULL;
4407 while (width++ < view->ncols)
4408 waddch(view->window, ' ');
4409 if (view_needs_focus_indication(view))
4410 wstandend(view->window);
4412 if (max_lines <= 1)
4413 return NULL;
4414 max_lines--;
4417 s->eof = 0;
4418 view->maxx = 0;
4419 line = NULL;
4420 while (max_lines > 0 && nprinted < max_lines) {
4421 enum got_diff_line_type linetype;
4422 attr_t attr = 0;
4424 linelen = getline(&line, &linesize, s->f);
4425 if (linelen == -1) {
4426 if (feof(s->f)) {
4427 s->eof = 1;
4428 break;
4430 free(line);
4431 return got_ferror(s->f, GOT_ERR_IO);
4434 if (++s->lineno < s->first_displayed_line)
4435 continue;
4436 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4437 continue;
4438 if (s->lineno == view->hiline)
4439 attr = A_STANDOUT;
4441 /* Set view->maxx based on full line length. */
4442 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4443 view->x ? 1 : 0);
4444 if (err) {
4445 free(line);
4446 return err;
4448 view->maxx = MAX(view->maxx, width);
4449 free(wline);
4450 wline = NULL;
4452 linetype = s->lines[s->lineno].type;
4453 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4454 linetype < GOT_DIFF_LINE_CONTEXT)
4455 attr |= COLOR_PAIR(linetype);
4456 if (attr)
4457 wattron(view->window, attr);
4458 if (s->first_displayed_line + nprinted == s->matched_line &&
4459 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4460 err = add_matched_line(&width, line, view->ncols, 0,
4461 view->window, view->x, regmatch);
4462 if (err) {
4463 free(line);
4464 return err;
4466 } else {
4467 int skip;
4468 err = format_line(&wline, &width, &skip, line,
4469 view->x, view->ncols, 0, view->x ? 1 : 0);
4470 if (err) {
4471 free(line);
4472 return err;
4474 waddwstr(view->window, &wline[skip]);
4475 free(wline);
4476 wline = NULL;
4478 if (s->lineno == view->hiline) {
4479 /* highlight full gline length */
4480 while (width++ < view->ncols)
4481 waddch(view->window, ' ');
4482 } else {
4483 if (width <= view->ncols - 1)
4484 waddch(view->window, '\n');
4486 if (attr)
4487 wattroff(view->window, attr);
4488 if (++nprinted == 1)
4489 s->first_displayed_line = s->lineno;
4491 free(line);
4492 if (nprinted >= 1)
4493 s->last_displayed_line = s->first_displayed_line +
4494 (nprinted - 1);
4495 else
4496 s->last_displayed_line = s->first_displayed_line;
4498 view_border(view);
4500 if (s->eof) {
4501 while (nprinted < view->nlines) {
4502 waddch(view->window, '\n');
4503 nprinted++;
4506 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4507 view->ncols, 0, 0);
4508 if (err) {
4509 return err;
4512 wstandout(view->window);
4513 waddwstr(view->window, wline);
4514 free(wline);
4515 wline = NULL;
4516 wstandend(view->window);
4519 return NULL;
4522 static char *
4523 get_datestr(time_t *time, char *datebuf)
4525 struct tm mytm, *tm;
4526 char *p, *s;
4528 tm = gmtime_r(time, &mytm);
4529 if (tm == NULL)
4530 return NULL;
4531 s = asctime_r(tm, datebuf);
4532 if (s == NULL)
4533 return NULL;
4534 p = strchr(s, '\n');
4535 if (p)
4536 *p = '\0';
4537 return s;
4540 static const struct got_error *
4541 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4542 off_t off, uint8_t type)
4544 struct got_diff_line *p;
4546 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4547 if (p == NULL)
4548 return got_error_from_errno("reallocarray");
4549 *lines = p;
4550 (*lines)[*nlines].offset = off;
4551 (*lines)[*nlines].type = type;
4552 (*nlines)++;
4554 return NULL;
4557 static const struct got_error *
4558 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4559 struct got_diff_line *s_lines, size_t s_nlines)
4561 struct got_diff_line *p;
4562 char buf[BUFSIZ];
4563 size_t i, r;
4565 if (fseeko(src, 0L, SEEK_SET) == -1)
4566 return got_error_from_errno("fseeko");
4568 for (;;) {
4569 r = fread(buf, 1, sizeof(buf), src);
4570 if (r == 0) {
4571 if (ferror(src))
4572 return got_error_from_errno("fread");
4573 if (feof(src))
4574 break;
4576 if (fwrite(buf, 1, r, dst) != r)
4577 return got_ferror(dst, GOT_ERR_IO);
4581 * The diff driver initialises the first line at offset zero when the
4582 * array isn't prepopulated, skip it; we already have it in *d_lines.
4584 for (i = 1; i < s_nlines; ++i)
4585 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4587 --s_nlines;
4589 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4590 if (p == NULL) {
4591 /* d_lines is freed in close_diff_view() */
4592 return got_error_from_errno("reallocarray");
4595 *d_lines = p;
4597 memcpy(*d_lines + *d_nlines, s_lines + 1, s_nlines * sizeof(*s_lines));
4598 *d_nlines += s_nlines;
4600 return NULL;
4603 static const struct got_error *
4604 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4605 struct got_object_id *commit_id, struct got_reflist_head *refs,
4606 struct got_repository *repo, int ignore_ws, int force_text_diff,
4607 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4609 const struct got_error *err = NULL;
4610 char datebuf[26], *datestr;
4611 struct got_commit_object *commit;
4612 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4613 time_t committer_time;
4614 const char *author, *committer;
4615 char *refs_str = NULL;
4616 struct got_pathlist_entry *pe;
4617 off_t outoff = 0;
4618 int n;
4620 if (refs) {
4621 err = build_refs_str(&refs_str, refs, commit_id, repo);
4622 if (err)
4623 return err;
4626 err = got_object_open_as_commit(&commit, repo, commit_id);
4627 if (err)
4628 return err;
4630 err = got_object_id_str(&id_str, commit_id);
4631 if (err) {
4632 err = got_error_from_errno("got_object_id_str");
4633 goto done;
4636 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4637 if (err)
4638 goto done;
4640 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4641 refs_str ? refs_str : "", refs_str ? ")" : "");
4642 if (n < 0) {
4643 err = got_error_from_errno("fprintf");
4644 goto done;
4646 outoff += n;
4647 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4648 if (err)
4649 goto done;
4651 n = fprintf(outfile, "from: %s\n",
4652 got_object_commit_get_author(commit));
4653 if (n < 0) {
4654 err = got_error_from_errno("fprintf");
4655 goto done;
4657 outoff += n;
4658 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4659 if (err)
4660 goto done;
4662 author = got_object_commit_get_author(commit);
4663 committer = got_object_commit_get_committer(commit);
4664 if (strcmp(author, committer) != 0) {
4665 n = fprintf(outfile, "via: %s\n", committer);
4666 if (n < 0) {
4667 err = got_error_from_errno("fprintf");
4668 goto done;
4670 outoff += n;
4671 err = add_line_metadata(lines, nlines, outoff,
4672 GOT_DIFF_LINE_AUTHOR);
4673 if (err)
4674 goto done;
4676 committer_time = got_object_commit_get_committer_time(commit);
4677 datestr = get_datestr(&committer_time, datebuf);
4678 if (datestr) {
4679 n = fprintf(outfile, "date: %s UTC\n", datestr);
4680 if (n < 0) {
4681 err = got_error_from_errno("fprintf");
4682 goto done;
4684 outoff += n;
4685 err = add_line_metadata(lines, nlines, outoff,
4686 GOT_DIFF_LINE_DATE);
4687 if (err)
4688 goto done;
4690 if (got_object_commit_get_nparents(commit) > 1) {
4691 const struct got_object_id_queue *parent_ids;
4692 struct got_object_qid *qid;
4693 int pn = 1;
4694 parent_ids = got_object_commit_get_parent_ids(commit);
4695 STAILQ_FOREACH(qid, parent_ids, entry) {
4696 err = got_object_id_str(&id_str, &qid->id);
4697 if (err)
4698 goto done;
4699 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4700 if (n < 0) {
4701 err = got_error_from_errno("fprintf");
4702 goto done;
4704 outoff += n;
4705 err = add_line_metadata(lines, nlines, outoff,
4706 GOT_DIFF_LINE_META);
4707 if (err)
4708 goto done;
4709 free(id_str);
4710 id_str = NULL;
4714 err = got_object_commit_get_logmsg(&logmsg, commit);
4715 if (err)
4716 goto done;
4717 s = logmsg;
4718 while ((line = strsep(&s, "\n")) != NULL) {
4719 n = fprintf(outfile, "%s\n", line);
4720 if (n < 0) {
4721 err = got_error_from_errno("fprintf");
4722 goto done;
4724 outoff += n;
4725 err = add_line_metadata(lines, nlines, outoff,
4726 GOT_DIFF_LINE_LOGMSG);
4727 if (err)
4728 goto done;
4731 TAILQ_FOREACH(pe, dsa->paths, entry) {
4732 struct got_diff_changed_path *cp = pe->data;
4733 int pad = dsa->max_path_len - pe->path_len + 1;
4735 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4736 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4737 dsa->rm_cols + 1, cp->rm);
4738 if (n < 0) {
4739 err = got_error_from_errno("fprintf");
4740 goto done;
4742 outoff += n;
4743 err = add_line_metadata(lines, nlines, outoff,
4744 GOT_DIFF_LINE_CHANGES);
4745 if (err)
4746 goto done;
4749 fputc('\n', outfile);
4750 outoff++;
4751 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4752 if (err)
4753 goto done;
4755 n = fprintf(outfile,
4756 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4757 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4758 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4759 if (n < 0) {
4760 err = got_error_from_errno("fprintf");
4761 goto done;
4763 outoff += n;
4764 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4765 if (err)
4766 goto done;
4768 fputc('\n', outfile);
4769 outoff++;
4770 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4771 done:
4772 free(id_str);
4773 free(logmsg);
4774 free(refs_str);
4775 got_object_commit_close(commit);
4776 if (err) {
4777 free(*lines);
4778 *lines = NULL;
4779 *nlines = 0;
4781 return err;
4784 static const struct got_error *
4785 create_diff(struct tog_diff_view_state *s)
4787 const struct got_error *err = NULL;
4788 FILE *f = NULL, *tmp_diff_file = NULL;
4789 int obj_type;
4790 struct got_diff_line *lines = NULL;
4791 struct got_pathlist_head changed_paths;
4793 TAILQ_INIT(&changed_paths);
4795 free(s->lines);
4796 s->lines = malloc(sizeof(*s->lines));
4797 if (s->lines == NULL)
4798 return got_error_from_errno("malloc");
4799 s->nlines = 0;
4801 f = got_opentemp();
4802 if (f == NULL) {
4803 err = got_error_from_errno("got_opentemp");
4804 goto done;
4806 tmp_diff_file = got_opentemp();
4807 if (tmp_diff_file == NULL) {
4808 err = got_error_from_errno("got_opentemp");
4809 goto done;
4811 if (s->f && fclose(s->f) == EOF) {
4812 err = got_error_from_errno("fclose");
4813 goto done;
4815 s->f = f;
4817 if (s->id1)
4818 err = got_object_get_type(&obj_type, s->repo, s->id1);
4819 else
4820 err = got_object_get_type(&obj_type, s->repo, s->id2);
4821 if (err)
4822 goto done;
4824 switch (obj_type) {
4825 case GOT_OBJ_TYPE_BLOB:
4826 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4827 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4828 s->label1, s->label2, tog_diff_algo, s->diff_context,
4829 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
4830 s->f);
4831 break;
4832 case GOT_OBJ_TYPE_TREE:
4833 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4834 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4835 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4836 s->force_text_diff, NULL, s->repo, s->f);
4837 break;
4838 case GOT_OBJ_TYPE_COMMIT: {
4839 const struct got_object_id_queue *parent_ids;
4840 struct got_object_qid *pid;
4841 struct got_commit_object *commit2;
4842 struct got_reflist_head *refs;
4843 size_t nlines = 0;
4844 struct got_diffstat_cb_arg dsa = {
4845 0, 0, 0, 0, 0, 0,
4846 &changed_paths,
4847 s->ignore_whitespace,
4848 s->force_text_diff,
4849 tog_diff_algo
4852 lines = malloc(sizeof(*lines));
4853 if (lines == NULL) {
4854 err = got_error_from_errno("malloc");
4855 goto done;
4858 /* build diff first in tmp file then append to commit info */
4859 err = got_diff_objects_as_commits(&lines, &nlines,
4860 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4861 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4862 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
4863 if (err)
4864 break;
4866 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4867 if (err)
4868 goto done;
4869 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4870 /* Show commit info if we're diffing to a parent/root commit. */
4871 if (s->id1 == NULL) {
4872 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4873 refs, s->repo, s->ignore_whitespace,
4874 s->force_text_diff, &dsa, s->f);
4875 if (err)
4876 goto done;
4877 } else {
4878 parent_ids = got_object_commit_get_parent_ids(commit2);
4879 STAILQ_FOREACH(pid, parent_ids, entry) {
4880 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4881 err = write_commit_info(&s->lines,
4882 &s->nlines, s->id2, refs, s->repo,
4883 s->ignore_whitespace,
4884 s->force_text_diff, &dsa, s->f);
4885 if (err)
4886 goto done;
4887 break;
4891 got_object_commit_close(commit2);
4893 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
4894 lines, nlines);
4895 break;
4897 default:
4898 err = got_error(GOT_ERR_OBJ_TYPE);
4899 break;
4901 done:
4902 free(lines);
4903 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4904 if (s->f && fflush(s->f) != 0 && err == NULL)
4905 err = got_error_from_errno("fflush");
4906 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
4907 err = got_error_from_errno("fclose");
4908 return err;
4911 static void
4912 diff_view_indicate_progress(struct tog_view *view)
4914 mvwaddstr(view->window, 0, 0, "diffing...");
4915 update_panels();
4916 doupdate();
4919 static const struct got_error *
4920 search_start_diff_view(struct tog_view *view)
4922 struct tog_diff_view_state *s = &view->state.diff;
4924 s->matched_line = 0;
4925 return NULL;
4928 static void
4929 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4930 size_t *nlines, int **first, int **last, int **match, int **selected)
4932 struct tog_diff_view_state *s = &view->state.diff;
4934 *f = s->f;
4935 *nlines = s->nlines;
4936 *line_offsets = NULL;
4937 *match = &s->matched_line;
4938 *first = &s->first_displayed_line;
4939 *last = &s->last_displayed_line;
4940 *selected = &s->selected_line;
4943 static const struct got_error *
4944 search_next_view_match(struct tog_view *view)
4946 const struct got_error *err = NULL;
4947 FILE *f;
4948 int lineno;
4949 char *line = NULL;
4950 size_t linesize = 0;
4951 ssize_t linelen;
4952 off_t *line_offsets;
4953 size_t nlines = 0;
4954 int *first, *last, *match, *selected;
4956 if (!view->search_setup)
4957 return got_error_msg(GOT_ERR_NOT_IMPL,
4958 "view search not supported");
4959 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4960 &match, &selected);
4962 if (!view->searching) {
4963 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4964 return NULL;
4967 if (*match) {
4968 if (view->searching == TOG_SEARCH_FORWARD)
4969 lineno = *match + 1;
4970 else
4971 lineno = *match - 1;
4972 } else
4973 lineno = *first - 1 + *selected;
4975 while (1) {
4976 off_t offset;
4978 if (lineno <= 0 || lineno > nlines) {
4979 if (*match == 0) {
4980 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4981 break;
4984 if (view->searching == TOG_SEARCH_FORWARD)
4985 lineno = 1;
4986 else
4987 lineno = nlines;
4990 offset = view->type == TOG_VIEW_DIFF ?
4991 view->state.diff.lines[lineno - 1].offset :
4992 line_offsets[lineno - 1];
4993 if (fseeko(f, offset, SEEK_SET) != 0) {
4994 free(line);
4995 return got_error_from_errno("fseeko");
4997 linelen = getline(&line, &linesize, f);
4998 if (linelen != -1) {
4999 char *exstr;
5000 err = expand_tab(&exstr, line);
5001 if (err)
5002 break;
5003 if (match_line(exstr, &view->regex, 1,
5004 &view->regmatch)) {
5005 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5006 *match = lineno;
5007 free(exstr);
5008 break;
5010 free(exstr);
5012 if (view->searching == TOG_SEARCH_FORWARD)
5013 lineno++;
5014 else
5015 lineno--;
5017 free(line);
5019 if (*match) {
5020 *first = *match;
5021 *selected = 1;
5024 return err;
5027 static const struct got_error *
5028 close_diff_view(struct tog_view *view)
5030 const struct got_error *err = NULL;
5031 struct tog_diff_view_state *s = &view->state.diff;
5033 free(s->id1);
5034 s->id1 = NULL;
5035 free(s->id2);
5036 s->id2 = NULL;
5037 if (s->f && fclose(s->f) == EOF)
5038 err = got_error_from_errno("fclose");
5039 s->f = NULL;
5040 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5041 err = got_error_from_errno("fclose");
5042 s->f1 = NULL;
5043 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5044 err = got_error_from_errno("fclose");
5045 s->f2 = NULL;
5046 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5047 err = got_error_from_errno("close");
5048 s->fd1 = -1;
5049 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5050 err = got_error_from_errno("close");
5051 s->fd2 = -1;
5052 free(s->lines);
5053 s->lines = NULL;
5054 s->nlines = 0;
5055 return err;
5058 static const struct got_error *
5059 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5060 struct got_object_id *id2, const char *label1, const char *label2,
5061 int diff_context, int ignore_whitespace, int force_text_diff,
5062 struct tog_view *parent_view, struct got_repository *repo)
5064 const struct got_error *err;
5065 struct tog_diff_view_state *s = &view->state.diff;
5067 memset(s, 0, sizeof(*s));
5068 s->fd1 = -1;
5069 s->fd2 = -1;
5071 if (id1 != NULL && id2 != NULL) {
5072 int type1, type2;
5073 err = got_object_get_type(&type1, repo, id1);
5074 if (err)
5075 return err;
5076 err = got_object_get_type(&type2, repo, id2);
5077 if (err)
5078 return err;
5080 if (type1 != type2)
5081 return got_error(GOT_ERR_OBJ_TYPE);
5083 s->first_displayed_line = 1;
5084 s->last_displayed_line = view->nlines;
5085 s->selected_line = 1;
5086 s->repo = repo;
5087 s->id1 = id1;
5088 s->id2 = id2;
5089 s->label1 = label1;
5090 s->label2 = label2;
5092 if (id1) {
5093 s->id1 = got_object_id_dup(id1);
5094 if (s->id1 == NULL)
5095 return got_error_from_errno("got_object_id_dup");
5096 } else
5097 s->id1 = NULL;
5099 s->id2 = got_object_id_dup(id2);
5100 if (s->id2 == NULL) {
5101 err = got_error_from_errno("got_object_id_dup");
5102 goto done;
5105 s->f1 = got_opentemp();
5106 if (s->f1 == NULL) {
5107 err = got_error_from_errno("got_opentemp");
5108 goto done;
5111 s->f2 = got_opentemp();
5112 if (s->f2 == NULL) {
5113 err = got_error_from_errno("got_opentemp");
5114 goto done;
5117 s->fd1 = got_opentempfd();
5118 if (s->fd1 == -1) {
5119 err = got_error_from_errno("got_opentempfd");
5120 goto done;
5123 s->fd2 = got_opentempfd();
5124 if (s->fd2 == -1) {
5125 err = got_error_from_errno("got_opentempfd");
5126 goto done;
5129 s->diff_context = diff_context;
5130 s->ignore_whitespace = ignore_whitespace;
5131 s->force_text_diff = force_text_diff;
5132 s->parent_view = parent_view;
5133 s->repo = repo;
5135 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5136 int rc;
5138 rc = init_pair(GOT_DIFF_LINE_MINUS,
5139 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5140 if (rc != ERR)
5141 rc = init_pair(GOT_DIFF_LINE_PLUS,
5142 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5143 if (rc != ERR)
5144 rc = init_pair(GOT_DIFF_LINE_HUNK,
5145 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5146 if (rc != ERR)
5147 rc = init_pair(GOT_DIFF_LINE_META,
5148 get_color_value("TOG_COLOR_DIFF_META"), -1);
5149 if (rc != ERR)
5150 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5151 get_color_value("TOG_COLOR_DIFF_META"), -1);
5152 if (rc != ERR)
5153 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5154 get_color_value("TOG_COLOR_DIFF_META"), -1);
5155 if (rc != ERR)
5156 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5157 get_color_value("TOG_COLOR_DIFF_META"), -1);
5158 if (rc != ERR)
5159 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5160 get_color_value("TOG_COLOR_AUTHOR"), -1);
5161 if (rc != ERR)
5162 rc = init_pair(GOT_DIFF_LINE_DATE,
5163 get_color_value("TOG_COLOR_DATE"), -1);
5164 if (rc == ERR) {
5165 err = got_error(GOT_ERR_RANGE);
5166 goto done;
5170 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5171 view_is_splitscreen(view))
5172 show_log_view(parent_view); /* draw border */
5173 diff_view_indicate_progress(view);
5175 err = create_diff(s);
5177 view->show = show_diff_view;
5178 view->input = input_diff_view;
5179 view->reset = reset_diff_view;
5180 view->close = close_diff_view;
5181 view->search_start = search_start_diff_view;
5182 view->search_setup = search_setup_diff_view;
5183 view->search_next = search_next_view_match;
5184 done:
5185 if (err)
5186 close_diff_view(view);
5187 return err;
5190 static const struct got_error *
5191 show_diff_view(struct tog_view *view)
5193 const struct got_error *err;
5194 struct tog_diff_view_state *s = &view->state.diff;
5195 char *id_str1 = NULL, *id_str2, *header;
5196 const char *label1, *label2;
5198 if (s->id1) {
5199 err = got_object_id_str(&id_str1, s->id1);
5200 if (err)
5201 return err;
5202 label1 = s->label1 ? s->label1 : id_str1;
5203 } else
5204 label1 = "/dev/null";
5206 err = got_object_id_str(&id_str2, s->id2);
5207 if (err)
5208 return err;
5209 label2 = s->label2 ? s->label2 : id_str2;
5211 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5212 err = got_error_from_errno("asprintf");
5213 free(id_str1);
5214 free(id_str2);
5215 return err;
5217 free(id_str1);
5218 free(id_str2);
5220 err = draw_file(view, header);
5221 free(header);
5222 return err;
5225 static const struct got_error *
5226 set_selected_commit(struct tog_diff_view_state *s,
5227 struct commit_queue_entry *entry)
5229 const struct got_error *err;
5230 const struct got_object_id_queue *parent_ids;
5231 struct got_commit_object *selected_commit;
5232 struct got_object_qid *pid;
5234 free(s->id2);
5235 s->id2 = got_object_id_dup(entry->id);
5236 if (s->id2 == NULL)
5237 return got_error_from_errno("got_object_id_dup");
5239 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5240 if (err)
5241 return err;
5242 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5243 free(s->id1);
5244 pid = STAILQ_FIRST(parent_ids);
5245 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5246 got_object_commit_close(selected_commit);
5247 return NULL;
5250 static const struct got_error *
5251 reset_diff_view(struct tog_view *view)
5253 struct tog_diff_view_state *s = &view->state.diff;
5255 view->count = 0;
5256 wclear(view->window);
5257 s->first_displayed_line = 1;
5258 s->last_displayed_line = view->nlines;
5259 s->matched_line = 0;
5260 diff_view_indicate_progress(view);
5261 return create_diff(s);
5264 static void
5265 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5267 int start, i;
5269 i = start = s->first_displayed_line - 1;
5271 while (s->lines[i].type != type) {
5272 if (i == 0)
5273 i = s->nlines - 1;
5274 if (--i == start)
5275 return; /* do nothing, requested type not in file */
5278 s->selected_line = 1;
5279 s->first_displayed_line = i;
5282 static void
5283 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5285 int start, i;
5287 i = start = s->first_displayed_line + 1;
5289 while (s->lines[i].type != type) {
5290 if (i == s->nlines - 1)
5291 i = 0;
5292 if (++i == start)
5293 return; /* do nothing, requested type not in file */
5296 s->selected_line = 1;
5297 s->first_displayed_line = i;
5300 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5301 int, int, int);
5302 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5303 int, int);
5305 static const struct got_error *
5306 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5308 const struct got_error *err = NULL;
5309 struct tog_diff_view_state *s = &view->state.diff;
5310 struct tog_log_view_state *ls;
5311 struct commit_queue_entry *old_selected_entry;
5312 char *line = NULL;
5313 size_t linesize = 0;
5314 ssize_t linelen;
5315 int i, nscroll = view->nlines - 1, up = 0;
5317 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5319 switch (ch) {
5320 case '0':
5321 case '$':
5322 case KEY_RIGHT:
5323 case 'l':
5324 case KEY_LEFT:
5325 case 'h':
5326 horizontal_scroll_input(view, ch);
5327 break;
5328 case 'a':
5329 case 'w':
5330 if (ch == 'a') {
5331 s->force_text_diff = !s->force_text_diff;
5332 view->action = s->force_text_diff ?
5333 "force ASCII text enabled" :
5334 "force ASCII text disabled";
5336 else if (ch == 'w') {
5337 s->ignore_whitespace = !s->ignore_whitespace;
5338 view->action = s->ignore_whitespace ?
5339 "ignore whitespace enabled" :
5340 "ignore whitespace disabled";
5342 err = reset_diff_view(view);
5343 break;
5344 case 'g':
5345 case KEY_HOME:
5346 s->first_displayed_line = 1;
5347 view->count = 0;
5348 break;
5349 case 'G':
5350 case KEY_END:
5351 view->count = 0;
5352 if (s->eof)
5353 break;
5355 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5356 s->eof = 1;
5357 break;
5358 case 'k':
5359 case KEY_UP:
5360 case CTRL('p'):
5361 if (s->first_displayed_line > 1)
5362 s->first_displayed_line--;
5363 else
5364 view->count = 0;
5365 break;
5366 case CTRL('u'):
5367 case 'u':
5368 nscroll /= 2;
5369 /* FALL THROUGH */
5370 case KEY_PPAGE:
5371 case CTRL('b'):
5372 case 'b':
5373 if (s->first_displayed_line == 1) {
5374 view->count = 0;
5375 break;
5377 i = 0;
5378 while (i++ < nscroll && s->first_displayed_line > 1)
5379 s->first_displayed_line--;
5380 break;
5381 case 'j':
5382 case KEY_DOWN:
5383 case CTRL('n'):
5384 if (!s->eof)
5385 s->first_displayed_line++;
5386 else
5387 view->count = 0;
5388 break;
5389 case CTRL('d'):
5390 case 'd':
5391 nscroll /= 2;
5392 /* FALL THROUGH */
5393 case KEY_NPAGE:
5394 case CTRL('f'):
5395 case 'f':
5396 case ' ':
5397 if (s->eof) {
5398 view->count = 0;
5399 break;
5401 i = 0;
5402 while (!s->eof && i++ < nscroll) {
5403 linelen = getline(&line, &linesize, s->f);
5404 s->first_displayed_line++;
5405 if (linelen == -1) {
5406 if (feof(s->f)) {
5407 s->eof = 1;
5408 } else
5409 err = got_ferror(s->f, GOT_ERR_IO);
5410 break;
5413 free(line);
5414 break;
5415 case '(':
5416 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5417 break;
5418 case ')':
5419 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5420 break;
5421 case '{':
5422 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5423 break;
5424 case '}':
5425 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5426 break;
5427 case '[':
5428 if (s->diff_context > 0) {
5429 s->diff_context--;
5430 s->matched_line = 0;
5431 diff_view_indicate_progress(view);
5432 err = create_diff(s);
5433 if (s->first_displayed_line + view->nlines - 1 >
5434 s->nlines) {
5435 s->first_displayed_line = 1;
5436 s->last_displayed_line = view->nlines;
5438 } else
5439 view->count = 0;
5440 break;
5441 case ']':
5442 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5443 s->diff_context++;
5444 s->matched_line = 0;
5445 diff_view_indicate_progress(view);
5446 err = create_diff(s);
5447 } else
5448 view->count = 0;
5449 break;
5450 case '<':
5451 case ',':
5452 case 'K':
5453 up = 1;
5454 /* FALL THROUGH */
5455 case '>':
5456 case '.':
5457 case 'J':
5458 if (s->parent_view == NULL) {
5459 view->count = 0;
5460 break;
5462 s->parent_view->count = view->count;
5464 if (s->parent_view->type == TOG_VIEW_LOG) {
5465 ls = &s->parent_view->state.log;
5466 old_selected_entry = ls->selected_entry;
5468 err = input_log_view(NULL, s->parent_view,
5469 up ? KEY_UP : KEY_DOWN);
5470 if (err)
5471 break;
5472 view->count = s->parent_view->count;
5474 if (old_selected_entry == ls->selected_entry)
5475 break;
5477 err = set_selected_commit(s, ls->selected_entry);
5478 if (err)
5479 break;
5480 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5481 struct tog_blame_view_state *bs;
5482 struct got_object_id *id, *prev_id;
5484 bs = &s->parent_view->state.blame;
5485 prev_id = get_annotation_for_line(bs->blame.lines,
5486 bs->blame.nlines, bs->last_diffed_line);
5488 err = input_blame_view(&view, s->parent_view,
5489 up ? KEY_UP : KEY_DOWN);
5490 if (err)
5491 break;
5492 view->count = s->parent_view->count;
5494 if (prev_id == NULL)
5495 break;
5496 id = get_selected_commit_id(bs->blame.lines,
5497 bs->blame.nlines, bs->first_displayed_line,
5498 bs->selected_line);
5499 if (id == NULL)
5500 break;
5502 if (!got_object_id_cmp(prev_id, id))
5503 break;
5505 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5506 if (err)
5507 break;
5509 s->first_displayed_line = 1;
5510 s->last_displayed_line = view->nlines;
5511 s->matched_line = 0;
5512 view->x = 0;
5514 diff_view_indicate_progress(view);
5515 err = create_diff(s);
5516 break;
5517 default:
5518 view->count = 0;
5519 break;
5522 return err;
5525 static const struct got_error *
5526 cmd_diff(int argc, char *argv[])
5528 const struct got_error *error = NULL;
5529 struct got_repository *repo = NULL;
5530 struct got_worktree *worktree = NULL;
5531 struct got_object_id *id1 = NULL, *id2 = NULL;
5532 char *repo_path = NULL, *cwd = NULL;
5533 char *id_str1 = NULL, *id_str2 = NULL;
5534 char *label1 = NULL, *label2 = NULL;
5535 int diff_context = 3, ignore_whitespace = 0;
5536 int ch, force_text_diff = 0;
5537 const char *errstr;
5538 struct tog_view *view;
5539 int *pack_fds = NULL;
5541 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5542 switch (ch) {
5543 case 'a':
5544 force_text_diff = 1;
5545 break;
5546 case 'C':
5547 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5548 &errstr);
5549 if (errstr != NULL)
5550 errx(1, "number of context lines is %s: %s",
5551 errstr, errstr);
5552 break;
5553 case 'r':
5554 repo_path = realpath(optarg, NULL);
5555 if (repo_path == NULL)
5556 return got_error_from_errno2("realpath",
5557 optarg);
5558 got_path_strip_trailing_slashes(repo_path);
5559 break;
5560 case 'w':
5561 ignore_whitespace = 1;
5562 break;
5563 default:
5564 usage_diff();
5565 /* NOTREACHED */
5569 argc -= optind;
5570 argv += optind;
5572 if (argc == 0) {
5573 usage_diff(); /* TODO show local worktree changes */
5574 } else if (argc == 2) {
5575 id_str1 = argv[0];
5576 id_str2 = argv[1];
5577 } else
5578 usage_diff();
5580 error = got_repo_pack_fds_open(&pack_fds);
5581 if (error)
5582 goto done;
5584 if (repo_path == NULL) {
5585 cwd = getcwd(NULL, 0);
5586 if (cwd == NULL)
5587 return got_error_from_errno("getcwd");
5588 error = got_worktree_open(&worktree, cwd);
5589 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5590 goto done;
5591 if (worktree)
5592 repo_path =
5593 strdup(got_worktree_get_repo_path(worktree));
5594 else
5595 repo_path = strdup(cwd);
5596 if (repo_path == NULL) {
5597 error = got_error_from_errno("strdup");
5598 goto done;
5602 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5603 if (error)
5604 goto done;
5606 init_curses();
5608 error = apply_unveil(got_repo_get_path(repo), NULL);
5609 if (error)
5610 goto done;
5612 error = tog_load_refs(repo, 0);
5613 if (error)
5614 goto done;
5616 error = got_repo_match_object_id(&id1, &label1, id_str1,
5617 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5618 if (error)
5619 goto done;
5621 error = got_repo_match_object_id(&id2, &label2, id_str2,
5622 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5623 if (error)
5624 goto done;
5626 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5627 if (view == NULL) {
5628 error = got_error_from_errno("view_open");
5629 goto done;
5631 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5632 ignore_whitespace, force_text_diff, NULL, repo);
5633 if (error)
5634 goto done;
5635 error = view_loop(view);
5636 done:
5637 free(label1);
5638 free(label2);
5639 free(repo_path);
5640 free(cwd);
5641 if (repo) {
5642 const struct got_error *close_err = got_repo_close(repo);
5643 if (error == NULL)
5644 error = close_err;
5646 if (worktree)
5647 got_worktree_close(worktree);
5648 if (pack_fds) {
5649 const struct got_error *pack_err =
5650 got_repo_pack_fds_close(pack_fds);
5651 if (error == NULL)
5652 error = pack_err;
5654 tog_free_refs();
5655 return error;
5658 __dead static void
5659 usage_blame(void)
5661 endwin();
5662 fprintf(stderr,
5663 "usage: %s blame [-c commit] [-r repository-path] path\n",
5664 getprogname());
5665 exit(1);
5668 struct tog_blame_line {
5669 int annotated;
5670 struct got_object_id *id;
5673 static const struct got_error *
5674 draw_blame(struct tog_view *view)
5676 struct tog_blame_view_state *s = &view->state.blame;
5677 struct tog_blame *blame = &s->blame;
5678 regmatch_t *regmatch = &view->regmatch;
5679 const struct got_error *err;
5680 int lineno = 0, nprinted = 0;
5681 char *line = NULL;
5682 size_t linesize = 0;
5683 ssize_t linelen;
5684 wchar_t *wline;
5685 int width;
5686 struct tog_blame_line *blame_line;
5687 struct got_object_id *prev_id = NULL;
5688 char *id_str;
5689 struct tog_color *tc;
5691 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5692 if (err)
5693 return err;
5695 rewind(blame->f);
5696 werase(view->window);
5698 if (asprintf(&line, "commit %s", id_str) == -1) {
5699 err = got_error_from_errno("asprintf");
5700 free(id_str);
5701 return err;
5704 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5705 free(line);
5706 line = NULL;
5707 if (err)
5708 return err;
5709 if (view_needs_focus_indication(view))
5710 wstandout(view->window);
5711 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5712 if (tc)
5713 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5714 waddwstr(view->window, wline);
5715 while (width++ < view->ncols)
5716 waddch(view->window, ' ');
5717 if (tc)
5718 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5719 if (view_needs_focus_indication(view))
5720 wstandend(view->window);
5721 free(wline);
5722 wline = NULL;
5724 if (view->gline > blame->nlines)
5725 view->gline = blame->nlines;
5727 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5728 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5729 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5730 free(id_str);
5731 return got_error_from_errno("asprintf");
5733 free(id_str);
5734 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5735 free(line);
5736 line = NULL;
5737 if (err)
5738 return err;
5739 waddwstr(view->window, wline);
5740 free(wline);
5741 wline = NULL;
5742 if (width < view->ncols - 1)
5743 waddch(view->window, '\n');
5745 s->eof = 0;
5746 view->maxx = 0;
5747 while (nprinted < view->nlines - 2) {
5748 linelen = getline(&line, &linesize, blame->f);
5749 if (linelen == -1) {
5750 if (feof(blame->f)) {
5751 s->eof = 1;
5752 break;
5754 free(line);
5755 return got_ferror(blame->f, GOT_ERR_IO);
5757 if (++lineno < s->first_displayed_line)
5758 continue;
5759 if (view->gline && !gotoline(view, &lineno, &nprinted))
5760 continue;
5762 /* Set view->maxx based on full line length. */
5763 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5764 if (err) {
5765 free(line);
5766 return err;
5768 free(wline);
5769 wline = NULL;
5770 view->maxx = MAX(view->maxx, width);
5772 if (nprinted == s->selected_line - 1)
5773 wstandout(view->window);
5775 if (blame->nlines > 0) {
5776 blame_line = &blame->lines[lineno - 1];
5777 if (blame_line->annotated && prev_id &&
5778 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5779 !(nprinted == s->selected_line - 1)) {
5780 waddstr(view->window, " ");
5781 } else if (blame_line->annotated) {
5782 char *id_str;
5783 err = got_object_id_str(&id_str,
5784 blame_line->id);
5785 if (err) {
5786 free(line);
5787 return err;
5789 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5790 if (tc)
5791 wattr_on(view->window,
5792 COLOR_PAIR(tc->colorpair), NULL);
5793 wprintw(view->window, "%.8s", id_str);
5794 if (tc)
5795 wattr_off(view->window,
5796 COLOR_PAIR(tc->colorpair), NULL);
5797 free(id_str);
5798 prev_id = blame_line->id;
5799 } else {
5800 waddstr(view->window, "........");
5801 prev_id = NULL;
5803 } else {
5804 waddstr(view->window, "........");
5805 prev_id = NULL;
5808 if (nprinted == s->selected_line - 1)
5809 wstandend(view->window);
5810 waddstr(view->window, " ");
5812 if (view->ncols <= 9) {
5813 width = 9;
5814 } else if (s->first_displayed_line + nprinted ==
5815 s->matched_line &&
5816 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5817 err = add_matched_line(&width, line, view->ncols - 9, 9,
5818 view->window, view->x, regmatch);
5819 if (err) {
5820 free(line);
5821 return err;
5823 width += 9;
5824 } else {
5825 int skip;
5826 err = format_line(&wline, &width, &skip, line,
5827 view->x, view->ncols - 9, 9, 1);
5828 if (err) {
5829 free(line);
5830 return err;
5832 waddwstr(view->window, &wline[skip]);
5833 width += 9;
5834 free(wline);
5835 wline = NULL;
5838 if (width <= view->ncols - 1)
5839 waddch(view->window, '\n');
5840 if (++nprinted == 1)
5841 s->first_displayed_line = lineno;
5843 free(line);
5844 s->last_displayed_line = lineno;
5846 view_border(view);
5848 return NULL;
5851 static const struct got_error *
5852 blame_cb(void *arg, int nlines, int lineno,
5853 struct got_commit_object *commit, struct got_object_id *id)
5855 const struct got_error *err = NULL;
5856 struct tog_blame_cb_args *a = arg;
5857 struct tog_blame_line *line;
5858 int errcode;
5860 if (nlines != a->nlines ||
5861 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5862 return got_error(GOT_ERR_RANGE);
5864 errcode = pthread_mutex_lock(&tog_mutex);
5865 if (errcode)
5866 return got_error_set_errno(errcode, "pthread_mutex_lock");
5868 if (*a->quit) { /* user has quit the blame view */
5869 err = got_error(GOT_ERR_ITER_COMPLETED);
5870 goto done;
5873 if (lineno == -1)
5874 goto done; /* no change in this commit */
5876 line = &a->lines[lineno - 1];
5877 if (line->annotated)
5878 goto done;
5880 line->id = got_object_id_dup(id);
5881 if (line->id == NULL) {
5882 err = got_error_from_errno("got_object_id_dup");
5883 goto done;
5885 line->annotated = 1;
5886 done:
5887 errcode = pthread_mutex_unlock(&tog_mutex);
5888 if (errcode)
5889 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5890 return err;
5893 static void *
5894 blame_thread(void *arg)
5896 const struct got_error *err, *close_err;
5897 struct tog_blame_thread_args *ta = arg;
5898 struct tog_blame_cb_args *a = ta->cb_args;
5899 int errcode, fd1 = -1, fd2 = -1;
5900 FILE *f1 = NULL, *f2 = NULL;
5902 fd1 = got_opentempfd();
5903 if (fd1 == -1)
5904 return (void *)got_error_from_errno("got_opentempfd");
5906 fd2 = got_opentempfd();
5907 if (fd2 == -1) {
5908 err = got_error_from_errno("got_opentempfd");
5909 goto done;
5912 f1 = got_opentemp();
5913 if (f1 == NULL) {
5914 err = (void *)got_error_from_errno("got_opentemp");
5915 goto done;
5917 f2 = got_opentemp();
5918 if (f2 == NULL) {
5919 err = (void *)got_error_from_errno("got_opentemp");
5920 goto done;
5923 err = block_signals_used_by_main_thread();
5924 if (err)
5925 goto done;
5927 err = got_blame(ta->path, a->commit_id, ta->repo,
5928 tog_diff_algo, blame_cb, ta->cb_args,
5929 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5930 if (err && err->code == GOT_ERR_CANCELLED)
5931 err = NULL;
5933 errcode = pthread_mutex_lock(&tog_mutex);
5934 if (errcode) {
5935 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5936 goto done;
5939 close_err = got_repo_close(ta->repo);
5940 if (err == NULL)
5941 err = close_err;
5942 ta->repo = NULL;
5943 *ta->complete = 1;
5945 errcode = pthread_mutex_unlock(&tog_mutex);
5946 if (errcode && err == NULL)
5947 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5949 done:
5950 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5951 err = got_error_from_errno("close");
5952 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5953 err = got_error_from_errno("close");
5954 if (f1 && fclose(f1) == EOF && err == NULL)
5955 err = got_error_from_errno("fclose");
5956 if (f2 && fclose(f2) == EOF && err == NULL)
5957 err = got_error_from_errno("fclose");
5959 return (void *)err;
5962 static struct got_object_id *
5963 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5964 int first_displayed_line, int selected_line)
5966 struct tog_blame_line *line;
5968 if (nlines <= 0)
5969 return NULL;
5971 line = &lines[first_displayed_line - 1 + selected_line - 1];
5972 if (!line->annotated)
5973 return NULL;
5975 return line->id;
5978 static struct got_object_id *
5979 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5980 int lineno)
5982 struct tog_blame_line *line;
5984 if (nlines <= 0 || lineno >= nlines)
5985 return NULL;
5987 line = &lines[lineno - 1];
5988 if (!line->annotated)
5989 return NULL;
5991 return line->id;
5994 static const struct got_error *
5995 stop_blame(struct tog_blame *blame)
5997 const struct got_error *err = NULL;
5998 int i;
6000 if (blame->thread) {
6001 int errcode;
6002 errcode = pthread_mutex_unlock(&tog_mutex);
6003 if (errcode)
6004 return got_error_set_errno(errcode,
6005 "pthread_mutex_unlock");
6006 errcode = pthread_join(blame->thread, (void **)&err);
6007 if (errcode)
6008 return got_error_set_errno(errcode, "pthread_join");
6009 errcode = pthread_mutex_lock(&tog_mutex);
6010 if (errcode)
6011 return got_error_set_errno(errcode,
6012 "pthread_mutex_lock");
6013 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6014 err = NULL;
6015 blame->thread = NULL;
6017 if (blame->thread_args.repo) {
6018 const struct got_error *close_err;
6019 close_err = got_repo_close(blame->thread_args.repo);
6020 if (err == NULL)
6021 err = close_err;
6022 blame->thread_args.repo = NULL;
6024 if (blame->f) {
6025 if (fclose(blame->f) == EOF && err == NULL)
6026 err = got_error_from_errno("fclose");
6027 blame->f = NULL;
6029 if (blame->lines) {
6030 for (i = 0; i < blame->nlines; i++)
6031 free(blame->lines[i].id);
6032 free(blame->lines);
6033 blame->lines = NULL;
6035 free(blame->cb_args.commit_id);
6036 blame->cb_args.commit_id = NULL;
6037 if (blame->pack_fds) {
6038 const struct got_error *pack_err =
6039 got_repo_pack_fds_close(blame->pack_fds);
6040 if (err == NULL)
6041 err = pack_err;
6042 blame->pack_fds = NULL;
6044 return err;
6047 static const struct got_error *
6048 cancel_blame_view(void *arg)
6050 const struct got_error *err = NULL;
6051 int *done = arg;
6052 int errcode;
6054 errcode = pthread_mutex_lock(&tog_mutex);
6055 if (errcode)
6056 return got_error_set_errno(errcode,
6057 "pthread_mutex_unlock");
6059 if (*done)
6060 err = got_error(GOT_ERR_CANCELLED);
6062 errcode = pthread_mutex_unlock(&tog_mutex);
6063 if (errcode)
6064 return got_error_set_errno(errcode,
6065 "pthread_mutex_lock");
6067 return err;
6070 static const struct got_error *
6071 run_blame(struct tog_view *view)
6073 struct tog_blame_view_state *s = &view->state.blame;
6074 struct tog_blame *blame = &s->blame;
6075 const struct got_error *err = NULL;
6076 struct got_commit_object *commit = NULL;
6077 struct got_blob_object *blob = NULL;
6078 struct got_repository *thread_repo = NULL;
6079 struct got_object_id *obj_id = NULL;
6080 int obj_type, fd = -1;
6081 int *pack_fds = NULL;
6083 err = got_object_open_as_commit(&commit, s->repo,
6084 &s->blamed_commit->id);
6085 if (err)
6086 return err;
6088 fd = got_opentempfd();
6089 if (fd == -1) {
6090 err = got_error_from_errno("got_opentempfd");
6091 goto done;
6094 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6095 if (err)
6096 goto done;
6098 err = got_object_get_type(&obj_type, s->repo, obj_id);
6099 if (err)
6100 goto done;
6102 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6103 err = got_error(GOT_ERR_OBJ_TYPE);
6104 goto done;
6107 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6108 if (err)
6109 goto done;
6110 blame->f = got_opentemp();
6111 if (blame->f == NULL) {
6112 err = got_error_from_errno("got_opentemp");
6113 goto done;
6115 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6116 &blame->line_offsets, blame->f, blob);
6117 if (err)
6118 goto done;
6119 if (blame->nlines == 0) {
6120 s->blame_complete = 1;
6121 goto done;
6124 /* Don't include \n at EOF in the blame line count. */
6125 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6126 blame->nlines--;
6128 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6129 if (blame->lines == NULL) {
6130 err = got_error_from_errno("calloc");
6131 goto done;
6134 err = got_repo_pack_fds_open(&pack_fds);
6135 if (err)
6136 goto done;
6137 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6138 pack_fds);
6139 if (err)
6140 goto done;
6142 blame->pack_fds = pack_fds;
6143 blame->cb_args.view = view;
6144 blame->cb_args.lines = blame->lines;
6145 blame->cb_args.nlines = blame->nlines;
6146 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6147 if (blame->cb_args.commit_id == NULL) {
6148 err = got_error_from_errno("got_object_id_dup");
6149 goto done;
6151 blame->cb_args.quit = &s->done;
6153 blame->thread_args.path = s->path;
6154 blame->thread_args.repo = thread_repo;
6155 blame->thread_args.cb_args = &blame->cb_args;
6156 blame->thread_args.complete = &s->blame_complete;
6157 blame->thread_args.cancel_cb = cancel_blame_view;
6158 blame->thread_args.cancel_arg = &s->done;
6159 s->blame_complete = 0;
6161 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6162 s->first_displayed_line = 1;
6163 s->last_displayed_line = view->nlines;
6164 s->selected_line = 1;
6166 s->matched_line = 0;
6168 done:
6169 if (commit)
6170 got_object_commit_close(commit);
6171 if (fd != -1 && close(fd) == -1 && err == NULL)
6172 err = got_error_from_errno("close");
6173 if (blob)
6174 got_object_blob_close(blob);
6175 free(obj_id);
6176 if (err)
6177 stop_blame(blame);
6178 return err;
6181 static const struct got_error *
6182 open_blame_view(struct tog_view *view, char *path,
6183 struct got_object_id *commit_id, struct got_repository *repo)
6185 const struct got_error *err = NULL;
6186 struct tog_blame_view_state *s = &view->state.blame;
6188 STAILQ_INIT(&s->blamed_commits);
6190 s->path = strdup(path);
6191 if (s->path == NULL)
6192 return got_error_from_errno("strdup");
6194 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6195 if (err) {
6196 free(s->path);
6197 return err;
6200 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6201 s->first_displayed_line = 1;
6202 s->last_displayed_line = view->nlines;
6203 s->selected_line = 1;
6204 s->blame_complete = 0;
6205 s->repo = repo;
6206 s->commit_id = commit_id;
6207 memset(&s->blame, 0, sizeof(s->blame));
6209 STAILQ_INIT(&s->colors);
6210 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6211 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6212 get_color_value("TOG_COLOR_COMMIT"));
6213 if (err)
6214 return err;
6217 view->show = show_blame_view;
6218 view->input = input_blame_view;
6219 view->reset = reset_blame_view;
6220 view->close = close_blame_view;
6221 view->search_start = search_start_blame_view;
6222 view->search_setup = search_setup_blame_view;
6223 view->search_next = search_next_view_match;
6225 return run_blame(view);
6228 static const struct got_error *
6229 close_blame_view(struct tog_view *view)
6231 const struct got_error *err = NULL;
6232 struct tog_blame_view_state *s = &view->state.blame;
6234 if (s->blame.thread)
6235 err = stop_blame(&s->blame);
6237 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6238 struct got_object_qid *blamed_commit;
6239 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6240 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6241 got_object_qid_free(blamed_commit);
6244 free(s->path);
6245 free_colors(&s->colors);
6246 return err;
6249 static const struct got_error *
6250 search_start_blame_view(struct tog_view *view)
6252 struct tog_blame_view_state *s = &view->state.blame;
6254 s->matched_line = 0;
6255 return NULL;
6258 static void
6259 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6260 size_t *nlines, int **first, int **last, int **match, int **selected)
6262 struct tog_blame_view_state *s = &view->state.blame;
6264 *f = s->blame.f;
6265 *nlines = s->blame.nlines;
6266 *line_offsets = s->blame.line_offsets;
6267 *match = &s->matched_line;
6268 *first = &s->first_displayed_line;
6269 *last = &s->last_displayed_line;
6270 *selected = &s->selected_line;
6273 static const struct got_error *
6274 show_blame_view(struct tog_view *view)
6276 const struct got_error *err = NULL;
6277 struct tog_blame_view_state *s = &view->state.blame;
6278 int errcode;
6280 if (s->blame.thread == NULL && !s->blame_complete) {
6281 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6282 &s->blame.thread_args);
6283 if (errcode)
6284 return got_error_set_errno(errcode, "pthread_create");
6286 halfdelay(1); /* fast refresh while annotating */
6289 if (s->blame_complete)
6290 halfdelay(10); /* disable fast refresh */
6292 err = draw_blame(view);
6294 view_border(view);
6295 return err;
6298 static const struct got_error *
6299 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6300 struct got_repository *repo, struct got_object_id *id)
6302 struct tog_view *log_view;
6303 const struct got_error *err = NULL;
6305 *new_view = NULL;
6307 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6308 if (log_view == NULL)
6309 return got_error_from_errno("view_open");
6311 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6312 if (err)
6313 view_close(log_view);
6314 else
6315 *new_view = log_view;
6317 return err;
6320 static const struct got_error *
6321 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6323 const struct got_error *err = NULL, *thread_err = NULL;
6324 struct tog_view *diff_view;
6325 struct tog_blame_view_state *s = &view->state.blame;
6326 int eos, nscroll, begin_y = 0, begin_x = 0;
6328 eos = nscroll = view->nlines - 2;
6329 if (view_is_hsplit_top(view))
6330 --eos; /* border */
6332 switch (ch) {
6333 case '0':
6334 case '$':
6335 case KEY_RIGHT:
6336 case 'l':
6337 case KEY_LEFT:
6338 case 'h':
6339 horizontal_scroll_input(view, ch);
6340 break;
6341 case 'q':
6342 s->done = 1;
6343 break;
6344 case 'g':
6345 case KEY_HOME:
6346 s->selected_line = 1;
6347 s->first_displayed_line = 1;
6348 view->count = 0;
6349 break;
6350 case 'G':
6351 case KEY_END:
6352 if (s->blame.nlines < eos) {
6353 s->selected_line = s->blame.nlines;
6354 s->first_displayed_line = 1;
6355 } else {
6356 s->selected_line = eos;
6357 s->first_displayed_line = s->blame.nlines - (eos - 1);
6359 view->count = 0;
6360 break;
6361 case 'k':
6362 case KEY_UP:
6363 case CTRL('p'):
6364 if (s->selected_line > 1)
6365 s->selected_line--;
6366 else if (s->selected_line == 1 &&
6367 s->first_displayed_line > 1)
6368 s->first_displayed_line--;
6369 else
6370 view->count = 0;
6371 break;
6372 case CTRL('u'):
6373 case 'u':
6374 nscroll /= 2;
6375 /* FALL THROUGH */
6376 case KEY_PPAGE:
6377 case CTRL('b'):
6378 case 'b':
6379 if (s->first_displayed_line == 1) {
6380 if (view->count > 1)
6381 nscroll += nscroll;
6382 s->selected_line = MAX(1, s->selected_line - nscroll);
6383 view->count = 0;
6384 break;
6386 if (s->first_displayed_line > nscroll)
6387 s->first_displayed_line -= nscroll;
6388 else
6389 s->first_displayed_line = 1;
6390 break;
6391 case 'j':
6392 case KEY_DOWN:
6393 case CTRL('n'):
6394 if (s->selected_line < eos && s->first_displayed_line +
6395 s->selected_line <= s->blame.nlines)
6396 s->selected_line++;
6397 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6398 s->first_displayed_line++;
6399 else
6400 view->count = 0;
6401 break;
6402 case 'c':
6403 case 'p': {
6404 struct got_object_id *id = NULL;
6406 view->count = 0;
6407 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6408 s->first_displayed_line, s->selected_line);
6409 if (id == NULL)
6410 break;
6411 if (ch == 'p') {
6412 struct got_commit_object *commit, *pcommit;
6413 struct got_object_qid *pid;
6414 struct got_object_id *blob_id = NULL;
6415 int obj_type;
6416 err = got_object_open_as_commit(&commit,
6417 s->repo, id);
6418 if (err)
6419 break;
6420 pid = STAILQ_FIRST(
6421 got_object_commit_get_parent_ids(commit));
6422 if (pid == NULL) {
6423 got_object_commit_close(commit);
6424 break;
6426 /* Check if path history ends here. */
6427 err = got_object_open_as_commit(&pcommit,
6428 s->repo, &pid->id);
6429 if (err)
6430 break;
6431 err = got_object_id_by_path(&blob_id, s->repo,
6432 pcommit, s->path);
6433 got_object_commit_close(pcommit);
6434 if (err) {
6435 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6436 err = NULL;
6437 got_object_commit_close(commit);
6438 break;
6440 err = got_object_get_type(&obj_type, s->repo,
6441 blob_id);
6442 free(blob_id);
6443 /* Can't blame non-blob type objects. */
6444 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6445 got_object_commit_close(commit);
6446 break;
6448 err = got_object_qid_alloc(&s->blamed_commit,
6449 &pid->id);
6450 got_object_commit_close(commit);
6451 } else {
6452 if (got_object_id_cmp(id,
6453 &s->blamed_commit->id) == 0)
6454 break;
6455 err = got_object_qid_alloc(&s->blamed_commit,
6456 id);
6458 if (err)
6459 break;
6460 s->done = 1;
6461 thread_err = stop_blame(&s->blame);
6462 s->done = 0;
6463 if (thread_err)
6464 break;
6465 STAILQ_INSERT_HEAD(&s->blamed_commits,
6466 s->blamed_commit, entry);
6467 err = run_blame(view);
6468 if (err)
6469 break;
6470 break;
6472 case 'C': {
6473 struct got_object_qid *first;
6475 view->count = 0;
6476 first = STAILQ_FIRST(&s->blamed_commits);
6477 if (!got_object_id_cmp(&first->id, s->commit_id))
6478 break;
6479 s->done = 1;
6480 thread_err = stop_blame(&s->blame);
6481 s->done = 0;
6482 if (thread_err)
6483 break;
6484 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6485 got_object_qid_free(s->blamed_commit);
6486 s->blamed_commit =
6487 STAILQ_FIRST(&s->blamed_commits);
6488 err = run_blame(view);
6489 if (err)
6490 break;
6491 break;
6493 case 'L':
6494 view->count = 0;
6495 s->id_to_log = get_selected_commit_id(s->blame.lines,
6496 s->blame.nlines, s->first_displayed_line, s->selected_line);
6497 if (s->id_to_log)
6498 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6499 break;
6500 case KEY_ENTER:
6501 case '\r': {
6502 struct got_object_id *id = NULL;
6503 struct got_object_qid *pid;
6504 struct got_commit_object *commit = NULL;
6506 view->count = 0;
6507 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6508 s->first_displayed_line, s->selected_line);
6509 if (id == NULL)
6510 break;
6511 err = got_object_open_as_commit(&commit, s->repo, id);
6512 if (err)
6513 break;
6514 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6515 if (*new_view) {
6516 /* traversed from diff view, release diff resources */
6517 err = close_diff_view(*new_view);
6518 if (err)
6519 break;
6520 diff_view = *new_view;
6521 } else {
6522 if (view_is_parent_view(view))
6523 view_get_split(view, &begin_y, &begin_x);
6525 diff_view = view_open(0, 0, begin_y, begin_x,
6526 TOG_VIEW_DIFF);
6527 if (diff_view == NULL) {
6528 got_object_commit_close(commit);
6529 err = got_error_from_errno("view_open");
6530 break;
6533 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6534 id, NULL, NULL, 3, 0, 0, view, s->repo);
6535 got_object_commit_close(commit);
6536 if (err) {
6537 view_close(diff_view);
6538 break;
6540 s->last_diffed_line = s->first_displayed_line - 1 +
6541 s->selected_line;
6542 if (*new_view)
6543 break; /* still open from active diff view */
6544 if (view_is_parent_view(view) &&
6545 view->mode == TOG_VIEW_SPLIT_HRZN) {
6546 err = view_init_hsplit(view, begin_y);
6547 if (err)
6548 break;
6551 view->focussed = 0;
6552 diff_view->focussed = 1;
6553 diff_view->mode = view->mode;
6554 diff_view->nlines = view->lines - begin_y;
6555 if (view_is_parent_view(view)) {
6556 view_transfer_size(diff_view, view);
6557 err = view_close_child(view);
6558 if (err)
6559 break;
6560 err = view_set_child(view, diff_view);
6561 if (err)
6562 break;
6563 view->focus_child = 1;
6564 } else
6565 *new_view = diff_view;
6566 if (err)
6567 break;
6568 break;
6570 case CTRL('d'):
6571 case 'd':
6572 nscroll /= 2;
6573 /* FALL THROUGH */
6574 case KEY_NPAGE:
6575 case CTRL('f'):
6576 case 'f':
6577 case ' ':
6578 if (s->last_displayed_line >= s->blame.nlines &&
6579 s->selected_line >= MIN(s->blame.nlines,
6580 view->nlines - 2)) {
6581 view->count = 0;
6582 break;
6584 if (s->last_displayed_line >= s->blame.nlines &&
6585 s->selected_line < view->nlines - 2) {
6586 s->selected_line +=
6587 MIN(nscroll, s->last_displayed_line -
6588 s->first_displayed_line - s->selected_line + 1);
6590 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6591 s->first_displayed_line += nscroll;
6592 else
6593 s->first_displayed_line =
6594 s->blame.nlines - (view->nlines - 3);
6595 break;
6596 case KEY_RESIZE:
6597 if (s->selected_line > view->nlines - 2) {
6598 s->selected_line = MIN(s->blame.nlines,
6599 view->nlines - 2);
6601 break;
6602 default:
6603 view->count = 0;
6604 break;
6606 return thread_err ? thread_err : err;
6609 static const struct got_error *
6610 reset_blame_view(struct tog_view *view)
6612 const struct got_error *err;
6613 struct tog_blame_view_state *s = &view->state.blame;
6615 view->count = 0;
6616 s->done = 1;
6617 err = stop_blame(&s->blame);
6618 s->done = 0;
6619 if (err)
6620 return err;
6621 return run_blame(view);
6624 static const struct got_error *
6625 cmd_blame(int argc, char *argv[])
6627 const struct got_error *error;
6628 struct got_repository *repo = NULL;
6629 struct got_worktree *worktree = NULL;
6630 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6631 char *link_target = NULL;
6632 struct got_object_id *commit_id = NULL;
6633 struct got_commit_object *commit = NULL;
6634 char *commit_id_str = NULL;
6635 int ch;
6636 struct tog_view *view;
6637 int *pack_fds = NULL;
6639 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6640 switch (ch) {
6641 case 'c':
6642 commit_id_str = optarg;
6643 break;
6644 case 'r':
6645 repo_path = realpath(optarg, NULL);
6646 if (repo_path == NULL)
6647 return got_error_from_errno2("realpath",
6648 optarg);
6649 break;
6650 default:
6651 usage_blame();
6652 /* NOTREACHED */
6656 argc -= optind;
6657 argv += optind;
6659 if (argc != 1)
6660 usage_blame();
6662 error = got_repo_pack_fds_open(&pack_fds);
6663 if (error != NULL)
6664 goto done;
6666 if (repo_path == NULL) {
6667 cwd = getcwd(NULL, 0);
6668 if (cwd == NULL)
6669 return got_error_from_errno("getcwd");
6670 error = got_worktree_open(&worktree, cwd);
6671 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6672 goto done;
6673 if (worktree)
6674 repo_path =
6675 strdup(got_worktree_get_repo_path(worktree));
6676 else
6677 repo_path = strdup(cwd);
6678 if (repo_path == NULL) {
6679 error = got_error_from_errno("strdup");
6680 goto done;
6684 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6685 if (error != NULL)
6686 goto done;
6688 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6689 worktree);
6690 if (error)
6691 goto done;
6693 init_curses();
6695 error = apply_unveil(got_repo_get_path(repo), NULL);
6696 if (error)
6697 goto done;
6699 error = tog_load_refs(repo, 0);
6700 if (error)
6701 goto done;
6703 if (commit_id_str == NULL) {
6704 struct got_reference *head_ref;
6705 error = got_ref_open(&head_ref, repo, worktree ?
6706 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6707 if (error != NULL)
6708 goto done;
6709 error = got_ref_resolve(&commit_id, repo, head_ref);
6710 got_ref_close(head_ref);
6711 } else {
6712 error = got_repo_match_object_id(&commit_id, NULL,
6713 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6715 if (error != NULL)
6716 goto done;
6718 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6719 if (view == NULL) {
6720 error = got_error_from_errno("view_open");
6721 goto done;
6724 error = got_object_open_as_commit(&commit, repo, commit_id);
6725 if (error)
6726 goto done;
6728 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6729 commit, repo);
6730 if (error)
6731 goto done;
6733 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6734 commit_id, repo);
6735 if (error)
6736 goto done;
6737 if (worktree) {
6738 /* Release work tree lock. */
6739 got_worktree_close(worktree);
6740 worktree = NULL;
6742 error = view_loop(view);
6743 done:
6744 free(repo_path);
6745 free(in_repo_path);
6746 free(link_target);
6747 free(cwd);
6748 free(commit_id);
6749 if (commit)
6750 got_object_commit_close(commit);
6751 if (worktree)
6752 got_worktree_close(worktree);
6753 if (repo) {
6754 const struct got_error *close_err = got_repo_close(repo);
6755 if (error == NULL)
6756 error = close_err;
6758 if (pack_fds) {
6759 const struct got_error *pack_err =
6760 got_repo_pack_fds_close(pack_fds);
6761 if (error == NULL)
6762 error = pack_err;
6764 tog_free_refs();
6765 return error;
6768 static const struct got_error *
6769 draw_tree_entries(struct tog_view *view, const char *parent_path)
6771 struct tog_tree_view_state *s = &view->state.tree;
6772 const struct got_error *err = NULL;
6773 struct got_tree_entry *te;
6774 wchar_t *wline;
6775 char *index = NULL;
6776 struct tog_color *tc;
6777 int width, n, nentries, scrollx, i = 1;
6778 int limit = view->nlines;
6780 s->ndisplayed = 0;
6781 if (view_is_hsplit_top(view))
6782 --limit; /* border */
6784 werase(view->window);
6786 if (limit == 0)
6787 return NULL;
6789 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6790 0, 0);
6791 if (err)
6792 return err;
6793 if (view_needs_focus_indication(view))
6794 wstandout(view->window);
6795 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6796 if (tc)
6797 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6798 waddwstr(view->window, wline);
6799 free(wline);
6800 wline = NULL;
6801 while (width++ < view->ncols)
6802 waddch(view->window, ' ');
6803 if (tc)
6804 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6805 if (view_needs_focus_indication(view))
6806 wstandend(view->window);
6807 if (--limit <= 0)
6808 return NULL;
6810 i += s->selected;
6811 if (s->first_displayed_entry) {
6812 i += got_tree_entry_get_index(s->first_displayed_entry);
6813 if (s->tree != s->root)
6814 ++i; /* account for ".." entry */
6816 nentries = got_object_tree_get_nentries(s->tree);
6817 if (asprintf(&index, "[%d/%d] %s",
6818 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6819 return got_error_from_errno("asprintf");
6820 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6821 free(index);
6822 if (err)
6823 return err;
6824 waddwstr(view->window, wline);
6825 free(wline);
6826 wline = NULL;
6827 if (width < view->ncols - 1)
6828 waddch(view->window, '\n');
6829 if (--limit <= 0)
6830 return NULL;
6831 waddch(view->window, '\n');
6832 if (--limit <= 0)
6833 return NULL;
6835 if (s->first_displayed_entry == NULL) {
6836 te = got_object_tree_get_first_entry(s->tree);
6837 if (s->selected == 0) {
6838 if (view->focussed)
6839 wstandout(view->window);
6840 s->selected_entry = NULL;
6842 waddstr(view->window, " ..\n"); /* parent directory */
6843 if (s->selected == 0 && view->focussed)
6844 wstandend(view->window);
6845 s->ndisplayed++;
6846 if (--limit <= 0)
6847 return NULL;
6848 n = 1;
6849 } else {
6850 n = 0;
6851 te = s->first_displayed_entry;
6854 view->maxx = 0;
6855 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6856 char *line = NULL, *id_str = NULL, *link_target = NULL;
6857 const char *modestr = "";
6858 mode_t mode;
6860 te = got_object_tree_get_entry(s->tree, i);
6861 mode = got_tree_entry_get_mode(te);
6863 if (s->show_ids) {
6864 err = got_object_id_str(&id_str,
6865 got_tree_entry_get_id(te));
6866 if (err)
6867 return got_error_from_errno(
6868 "got_object_id_str");
6870 if (got_object_tree_entry_is_submodule(te))
6871 modestr = "$";
6872 else if (S_ISLNK(mode)) {
6873 int i;
6875 err = got_tree_entry_get_symlink_target(&link_target,
6876 te, s->repo);
6877 if (err) {
6878 free(id_str);
6879 return err;
6881 for (i = 0; i < strlen(link_target); i++) {
6882 if (!isprint((unsigned char)link_target[i]))
6883 link_target[i] = '?';
6885 modestr = "@";
6887 else if (S_ISDIR(mode))
6888 modestr = "/";
6889 else if (mode & S_IXUSR)
6890 modestr = "*";
6891 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6892 got_tree_entry_get_name(te), modestr,
6893 link_target ? " -> ": "",
6894 link_target ? link_target : "") == -1) {
6895 free(id_str);
6896 free(link_target);
6897 return got_error_from_errno("asprintf");
6899 free(id_str);
6900 free(link_target);
6902 /* use full line width to determine view->maxx */
6903 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
6904 if (err) {
6905 free(line);
6906 break;
6908 view->maxx = MAX(view->maxx, width);
6909 free(wline);
6910 wline = NULL;
6912 err = format_line(&wline, &width, &scrollx, line, view->x,
6913 view->ncols, 0, 0);
6914 if (err) {
6915 free(line);
6916 break;
6918 if (n == s->selected) {
6919 if (view->focussed)
6920 wstandout(view->window);
6921 s->selected_entry = te;
6923 tc = match_color(&s->colors, line);
6924 if (tc)
6925 wattr_on(view->window,
6926 COLOR_PAIR(tc->colorpair), NULL);
6927 waddwstr(view->window, &wline[scrollx]);
6928 if (tc)
6929 wattr_off(view->window,
6930 COLOR_PAIR(tc->colorpair), NULL);
6931 if (width < view->ncols)
6932 waddch(view->window, '\n');
6933 if (n == s->selected && view->focussed)
6934 wstandend(view->window);
6935 free(line);
6936 free(wline);
6937 wline = NULL;
6938 n++;
6939 s->ndisplayed++;
6940 s->last_displayed_entry = te;
6941 if (--limit <= 0)
6942 break;
6945 return err;
6948 static void
6949 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6951 struct got_tree_entry *te;
6952 int isroot = s->tree == s->root;
6953 int i = 0;
6955 if (s->first_displayed_entry == NULL)
6956 return;
6958 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6959 while (i++ < maxscroll) {
6960 if (te == NULL) {
6961 if (!isroot)
6962 s->first_displayed_entry = NULL;
6963 break;
6965 s->first_displayed_entry = te;
6966 te = got_tree_entry_get_prev(s->tree, te);
6970 static const struct got_error *
6971 tree_scroll_down(struct tog_view *view, int maxscroll)
6973 struct tog_tree_view_state *s = &view->state.tree;
6974 struct got_tree_entry *next, *last;
6975 int n = 0;
6977 if (s->first_displayed_entry)
6978 next = got_tree_entry_get_next(s->tree,
6979 s->first_displayed_entry);
6980 else
6981 next = got_object_tree_get_first_entry(s->tree);
6983 last = s->last_displayed_entry;
6984 while (next && n++ < maxscroll) {
6985 if (last) {
6986 s->last_displayed_entry = last;
6987 last = got_tree_entry_get_next(s->tree, last);
6989 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6990 s->first_displayed_entry = next;
6991 next = got_tree_entry_get_next(s->tree, next);
6995 return NULL;
6998 static const struct got_error *
6999 tree_entry_path(char **path, struct tog_parent_trees *parents,
7000 struct got_tree_entry *te)
7002 const struct got_error *err = NULL;
7003 struct tog_parent_tree *pt;
7004 size_t len = 2; /* for leading slash and NUL */
7006 TAILQ_FOREACH(pt, parents, entry)
7007 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7008 + 1 /* slash */;
7009 if (te)
7010 len += strlen(got_tree_entry_get_name(te));
7012 *path = calloc(1, len);
7013 if (path == NULL)
7014 return got_error_from_errno("calloc");
7016 (*path)[0] = '/';
7017 pt = TAILQ_LAST(parents, tog_parent_trees);
7018 while (pt) {
7019 const char *name = got_tree_entry_get_name(pt->selected_entry);
7020 if (strlcat(*path, name, len) >= len) {
7021 err = got_error(GOT_ERR_NO_SPACE);
7022 goto done;
7024 if (strlcat(*path, "/", len) >= len) {
7025 err = got_error(GOT_ERR_NO_SPACE);
7026 goto done;
7028 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7030 if (te) {
7031 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7032 err = got_error(GOT_ERR_NO_SPACE);
7033 goto done;
7036 done:
7037 if (err) {
7038 free(*path);
7039 *path = NULL;
7041 return err;
7044 static const struct got_error *
7045 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7046 struct got_tree_entry *te, struct tog_parent_trees *parents,
7047 struct got_object_id *commit_id, struct got_repository *repo)
7049 const struct got_error *err = NULL;
7050 char *path;
7051 struct tog_view *blame_view;
7053 *new_view = NULL;
7055 err = tree_entry_path(&path, parents, te);
7056 if (err)
7057 return err;
7059 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7060 if (blame_view == NULL) {
7061 err = got_error_from_errno("view_open");
7062 goto done;
7065 err = open_blame_view(blame_view, path, commit_id, repo);
7066 if (err) {
7067 if (err->code == GOT_ERR_CANCELLED)
7068 err = NULL;
7069 view_close(blame_view);
7070 } else
7071 *new_view = blame_view;
7072 done:
7073 free(path);
7074 return err;
7077 static const struct got_error *
7078 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7079 struct tog_tree_view_state *s)
7081 struct tog_view *log_view;
7082 const struct got_error *err = NULL;
7083 char *path;
7085 *new_view = NULL;
7087 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7088 if (log_view == NULL)
7089 return got_error_from_errno("view_open");
7091 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7092 if (err)
7093 return err;
7095 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7096 path, 0);
7097 if (err)
7098 view_close(log_view);
7099 else
7100 *new_view = log_view;
7101 free(path);
7102 return err;
7105 static const struct got_error *
7106 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7107 const char *head_ref_name, struct got_repository *repo)
7109 const struct got_error *err = NULL;
7110 char *commit_id_str = NULL;
7111 struct tog_tree_view_state *s = &view->state.tree;
7112 struct got_commit_object *commit = NULL;
7114 TAILQ_INIT(&s->parents);
7115 STAILQ_INIT(&s->colors);
7117 s->commit_id = got_object_id_dup(commit_id);
7118 if (s->commit_id == NULL)
7119 return got_error_from_errno("got_object_id_dup");
7121 err = got_object_open_as_commit(&commit, repo, commit_id);
7122 if (err)
7123 goto done;
7126 * The root is opened here and will be closed when the view is closed.
7127 * Any visited subtrees and their path-wise parents are opened and
7128 * closed on demand.
7130 err = got_object_open_as_tree(&s->root, repo,
7131 got_object_commit_get_tree_id(commit));
7132 if (err)
7133 goto done;
7134 s->tree = s->root;
7136 err = got_object_id_str(&commit_id_str, commit_id);
7137 if (err != NULL)
7138 goto done;
7140 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7141 err = got_error_from_errno("asprintf");
7142 goto done;
7145 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7146 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7147 if (head_ref_name) {
7148 s->head_ref_name = strdup(head_ref_name);
7149 if (s->head_ref_name == NULL) {
7150 err = got_error_from_errno("strdup");
7151 goto done;
7154 s->repo = repo;
7156 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7157 err = add_color(&s->colors, "\\$$",
7158 TOG_COLOR_TREE_SUBMODULE,
7159 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7160 if (err)
7161 goto done;
7162 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7163 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7164 if (err)
7165 goto done;
7166 err = add_color(&s->colors, "/$",
7167 TOG_COLOR_TREE_DIRECTORY,
7168 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7169 if (err)
7170 goto done;
7172 err = add_color(&s->colors, "\\*$",
7173 TOG_COLOR_TREE_EXECUTABLE,
7174 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7175 if (err)
7176 goto done;
7178 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7179 get_color_value("TOG_COLOR_COMMIT"));
7180 if (err)
7181 goto done;
7184 view->show = show_tree_view;
7185 view->input = input_tree_view;
7186 view->close = close_tree_view;
7187 view->search_start = search_start_tree_view;
7188 view->search_next = search_next_tree_view;
7189 done:
7190 free(commit_id_str);
7191 if (commit)
7192 got_object_commit_close(commit);
7193 if (err)
7194 close_tree_view(view);
7195 return err;
7198 static const struct got_error *
7199 close_tree_view(struct tog_view *view)
7201 struct tog_tree_view_state *s = &view->state.tree;
7203 free_colors(&s->colors);
7204 free(s->tree_label);
7205 s->tree_label = NULL;
7206 free(s->commit_id);
7207 s->commit_id = NULL;
7208 free(s->head_ref_name);
7209 s->head_ref_name = NULL;
7210 while (!TAILQ_EMPTY(&s->parents)) {
7211 struct tog_parent_tree *parent;
7212 parent = TAILQ_FIRST(&s->parents);
7213 TAILQ_REMOVE(&s->parents, parent, entry);
7214 if (parent->tree != s->root)
7215 got_object_tree_close(parent->tree);
7216 free(parent);
7219 if (s->tree != NULL && s->tree != s->root)
7220 got_object_tree_close(s->tree);
7221 if (s->root)
7222 got_object_tree_close(s->root);
7223 return NULL;
7226 static const struct got_error *
7227 search_start_tree_view(struct tog_view *view)
7229 struct tog_tree_view_state *s = &view->state.tree;
7231 s->matched_entry = NULL;
7232 return NULL;
7235 static int
7236 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7238 regmatch_t regmatch;
7240 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7241 0) == 0;
7244 static const struct got_error *
7245 search_next_tree_view(struct tog_view *view)
7247 struct tog_tree_view_state *s = &view->state.tree;
7248 struct got_tree_entry *te = NULL;
7250 if (!view->searching) {
7251 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7252 return NULL;
7255 if (s->matched_entry) {
7256 if (view->searching == TOG_SEARCH_FORWARD) {
7257 if (s->selected_entry)
7258 te = got_tree_entry_get_next(s->tree,
7259 s->selected_entry);
7260 else
7261 te = got_object_tree_get_first_entry(s->tree);
7262 } else {
7263 if (s->selected_entry == NULL)
7264 te = got_object_tree_get_last_entry(s->tree);
7265 else
7266 te = got_tree_entry_get_prev(s->tree,
7267 s->selected_entry);
7269 } else {
7270 if (s->selected_entry)
7271 te = s->selected_entry;
7272 else if (view->searching == TOG_SEARCH_FORWARD)
7273 te = got_object_tree_get_first_entry(s->tree);
7274 else
7275 te = got_object_tree_get_last_entry(s->tree);
7278 while (1) {
7279 if (te == NULL) {
7280 if (s->matched_entry == NULL) {
7281 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7282 return NULL;
7284 if (view->searching == TOG_SEARCH_FORWARD)
7285 te = got_object_tree_get_first_entry(s->tree);
7286 else
7287 te = got_object_tree_get_last_entry(s->tree);
7290 if (match_tree_entry(te, &view->regex)) {
7291 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7292 s->matched_entry = te;
7293 break;
7296 if (view->searching == TOG_SEARCH_FORWARD)
7297 te = got_tree_entry_get_next(s->tree, te);
7298 else
7299 te = got_tree_entry_get_prev(s->tree, te);
7302 if (s->matched_entry) {
7303 s->first_displayed_entry = s->matched_entry;
7304 s->selected = 0;
7307 return NULL;
7310 static const struct got_error *
7311 show_tree_view(struct tog_view *view)
7313 const struct got_error *err = NULL;
7314 struct tog_tree_view_state *s = &view->state.tree;
7315 char *parent_path;
7317 err = tree_entry_path(&parent_path, &s->parents, NULL);
7318 if (err)
7319 return err;
7321 err = draw_tree_entries(view, parent_path);
7322 free(parent_path);
7324 view_border(view);
7325 return err;
7328 static const struct got_error *
7329 tree_goto_line(struct tog_view *view, int nlines)
7331 const struct got_error *err = NULL;
7332 struct tog_tree_view_state *s = &view->state.tree;
7333 struct got_tree_entry **fte, **lte, **ste;
7334 int g, last, first = 1, i = 1;
7335 int root = s->tree == s->root;
7336 int off = root ? 1 : 2;
7338 g = view->gline;
7339 view->gline = 0;
7341 if (g == 0)
7342 g = 1;
7343 else if (g > got_object_tree_get_nentries(s->tree))
7344 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7346 fte = &s->first_displayed_entry;
7347 lte = &s->last_displayed_entry;
7348 ste = &s->selected_entry;
7350 if (*fte != NULL) {
7351 first = got_tree_entry_get_index(*fte);
7352 first += off; /* account for ".." */
7354 last = got_tree_entry_get_index(*lte);
7355 last += off;
7357 if (g >= first && g <= last && g - first < nlines) {
7358 s->selected = g - first;
7359 return NULL; /* gline is on the current page */
7362 if (*ste != NULL) {
7363 i = got_tree_entry_get_index(*ste);
7364 i += off;
7367 if (i < g) {
7368 err = tree_scroll_down(view, g - i);
7369 if (err)
7370 return err;
7371 if (got_tree_entry_get_index(*lte) >=
7372 got_object_tree_get_nentries(s->tree) - 1 &&
7373 first + s->selected < g &&
7374 s->selected < s->ndisplayed - 1) {
7375 first = got_tree_entry_get_index(*fte);
7376 first += off;
7377 s->selected = g - first;
7379 } else if (i > g)
7380 tree_scroll_up(s, i - g);
7382 if (g < nlines &&
7383 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7384 s->selected = g - 1;
7386 return NULL;
7389 static const struct got_error *
7390 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7392 const struct got_error *err = NULL;
7393 struct tog_tree_view_state *s = &view->state.tree;
7394 struct got_tree_entry *te;
7395 int n, nscroll = view->nlines - 3;
7397 if (view->gline)
7398 return tree_goto_line(view, nscroll);
7400 switch (ch) {
7401 case '0':
7402 case '$':
7403 case KEY_RIGHT:
7404 case 'l':
7405 case KEY_LEFT:
7406 case 'h':
7407 horizontal_scroll_input(view, ch);
7408 break;
7409 case 'i':
7410 s->show_ids = !s->show_ids;
7411 view->count = 0;
7412 break;
7413 case 'L':
7414 view->count = 0;
7415 if (!s->selected_entry)
7416 break;
7417 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7418 break;
7419 case 'R':
7420 view->count = 0;
7421 err = view_request_new(new_view, view, TOG_VIEW_REF);
7422 break;
7423 case 'g':
7424 case '=':
7425 case KEY_HOME:
7426 s->selected = 0;
7427 view->count = 0;
7428 if (s->tree == s->root)
7429 s->first_displayed_entry =
7430 got_object_tree_get_first_entry(s->tree);
7431 else
7432 s->first_displayed_entry = NULL;
7433 break;
7434 case 'G':
7435 case '*':
7436 case KEY_END: {
7437 int eos = view->nlines - 3;
7439 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7440 --eos; /* border */
7441 s->selected = 0;
7442 view->count = 0;
7443 te = got_object_tree_get_last_entry(s->tree);
7444 for (n = 0; n < eos; n++) {
7445 if (te == NULL) {
7446 if (s->tree != s->root) {
7447 s->first_displayed_entry = NULL;
7448 n++;
7450 break;
7452 s->first_displayed_entry = te;
7453 te = got_tree_entry_get_prev(s->tree, te);
7455 if (n > 0)
7456 s->selected = n - 1;
7457 break;
7459 case 'k':
7460 case KEY_UP:
7461 case CTRL('p'):
7462 if (s->selected > 0) {
7463 s->selected--;
7464 break;
7466 tree_scroll_up(s, 1);
7467 if (s->selected_entry == NULL ||
7468 (s->tree == s->root && s->selected_entry ==
7469 got_object_tree_get_first_entry(s->tree)))
7470 view->count = 0;
7471 break;
7472 case CTRL('u'):
7473 case 'u':
7474 nscroll /= 2;
7475 /* FALL THROUGH */
7476 case KEY_PPAGE:
7477 case CTRL('b'):
7478 case 'b':
7479 if (s->tree == s->root) {
7480 if (got_object_tree_get_first_entry(s->tree) ==
7481 s->first_displayed_entry)
7482 s->selected -= MIN(s->selected, nscroll);
7483 } else {
7484 if (s->first_displayed_entry == NULL)
7485 s->selected -= MIN(s->selected, nscroll);
7487 tree_scroll_up(s, MAX(0, nscroll));
7488 if (s->selected_entry == NULL ||
7489 (s->tree == s->root && s->selected_entry ==
7490 got_object_tree_get_first_entry(s->tree)))
7491 view->count = 0;
7492 break;
7493 case 'j':
7494 case KEY_DOWN:
7495 case CTRL('n'):
7496 if (s->selected < s->ndisplayed - 1) {
7497 s->selected++;
7498 break;
7500 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7501 == NULL) {
7502 /* can't scroll any further */
7503 view->count = 0;
7504 break;
7506 tree_scroll_down(view, 1);
7507 break;
7508 case CTRL('d'):
7509 case 'd':
7510 nscroll /= 2;
7511 /* FALL THROUGH */
7512 case KEY_NPAGE:
7513 case CTRL('f'):
7514 case 'f':
7515 case ' ':
7516 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7517 == NULL) {
7518 /* can't scroll any further; move cursor down */
7519 if (s->selected < s->ndisplayed - 1)
7520 s->selected += MIN(nscroll,
7521 s->ndisplayed - s->selected - 1);
7522 else
7523 view->count = 0;
7524 break;
7526 tree_scroll_down(view, nscroll);
7527 break;
7528 case KEY_ENTER:
7529 case '\r':
7530 case KEY_BACKSPACE:
7531 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7532 struct tog_parent_tree *parent;
7533 /* user selected '..' */
7534 if (s->tree == s->root) {
7535 view->count = 0;
7536 break;
7538 parent = TAILQ_FIRST(&s->parents);
7539 TAILQ_REMOVE(&s->parents, parent,
7540 entry);
7541 got_object_tree_close(s->tree);
7542 s->tree = parent->tree;
7543 s->first_displayed_entry =
7544 parent->first_displayed_entry;
7545 s->selected_entry =
7546 parent->selected_entry;
7547 s->selected = parent->selected;
7548 if (s->selected > view->nlines - 3) {
7549 err = offset_selection_down(view);
7550 if (err)
7551 break;
7553 free(parent);
7554 } else if (S_ISDIR(got_tree_entry_get_mode(
7555 s->selected_entry))) {
7556 struct got_tree_object *subtree;
7557 view->count = 0;
7558 err = got_object_open_as_tree(&subtree, s->repo,
7559 got_tree_entry_get_id(s->selected_entry));
7560 if (err)
7561 break;
7562 err = tree_view_visit_subtree(s, subtree);
7563 if (err) {
7564 got_object_tree_close(subtree);
7565 break;
7567 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7568 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7569 break;
7570 case KEY_RESIZE:
7571 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7572 s->selected = view->nlines - 4;
7573 view->count = 0;
7574 break;
7575 default:
7576 view->count = 0;
7577 break;
7580 return err;
7583 __dead static void
7584 usage_tree(void)
7586 endwin();
7587 fprintf(stderr,
7588 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7589 getprogname());
7590 exit(1);
7593 static const struct got_error *
7594 cmd_tree(int argc, char *argv[])
7596 const struct got_error *error;
7597 struct got_repository *repo = NULL;
7598 struct got_worktree *worktree = NULL;
7599 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7600 struct got_object_id *commit_id = NULL;
7601 struct got_commit_object *commit = NULL;
7602 const char *commit_id_arg = NULL;
7603 char *label = NULL;
7604 struct got_reference *ref = NULL;
7605 const char *head_ref_name = NULL;
7606 int ch;
7607 struct tog_view *view;
7608 int *pack_fds = NULL;
7610 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7611 switch (ch) {
7612 case 'c':
7613 commit_id_arg = optarg;
7614 break;
7615 case 'r':
7616 repo_path = realpath(optarg, NULL);
7617 if (repo_path == NULL)
7618 return got_error_from_errno2("realpath",
7619 optarg);
7620 break;
7621 default:
7622 usage_tree();
7623 /* NOTREACHED */
7627 argc -= optind;
7628 argv += optind;
7630 if (argc > 1)
7631 usage_tree();
7633 error = got_repo_pack_fds_open(&pack_fds);
7634 if (error != NULL)
7635 goto done;
7637 if (repo_path == NULL) {
7638 cwd = getcwd(NULL, 0);
7639 if (cwd == NULL)
7640 return got_error_from_errno("getcwd");
7641 error = got_worktree_open(&worktree, cwd);
7642 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7643 goto done;
7644 if (worktree)
7645 repo_path =
7646 strdup(got_worktree_get_repo_path(worktree));
7647 else
7648 repo_path = strdup(cwd);
7649 if (repo_path == NULL) {
7650 error = got_error_from_errno("strdup");
7651 goto done;
7655 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7656 if (error != NULL)
7657 goto done;
7659 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7660 repo, worktree);
7661 if (error)
7662 goto done;
7664 init_curses();
7666 error = apply_unveil(got_repo_get_path(repo), NULL);
7667 if (error)
7668 goto done;
7670 error = tog_load_refs(repo, 0);
7671 if (error)
7672 goto done;
7674 if (commit_id_arg == NULL) {
7675 error = got_repo_match_object_id(&commit_id, &label,
7676 worktree ? got_worktree_get_head_ref_name(worktree) :
7677 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7678 if (error)
7679 goto done;
7680 head_ref_name = label;
7681 } else {
7682 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7683 if (error == NULL)
7684 head_ref_name = got_ref_get_name(ref);
7685 else if (error->code != GOT_ERR_NOT_REF)
7686 goto done;
7687 error = got_repo_match_object_id(&commit_id, NULL,
7688 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7689 if (error)
7690 goto done;
7693 error = got_object_open_as_commit(&commit, repo, commit_id);
7694 if (error)
7695 goto done;
7697 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7698 if (view == NULL) {
7699 error = got_error_from_errno("view_open");
7700 goto done;
7702 error = open_tree_view(view, commit_id, head_ref_name, repo);
7703 if (error)
7704 goto done;
7705 if (!got_path_is_root_dir(in_repo_path)) {
7706 error = tree_view_walk_path(&view->state.tree, commit,
7707 in_repo_path);
7708 if (error)
7709 goto done;
7712 if (worktree) {
7713 /* Release work tree lock. */
7714 got_worktree_close(worktree);
7715 worktree = NULL;
7717 error = view_loop(view);
7718 done:
7719 free(repo_path);
7720 free(cwd);
7721 free(commit_id);
7722 free(label);
7723 if (ref)
7724 got_ref_close(ref);
7725 if (repo) {
7726 const struct got_error *close_err = got_repo_close(repo);
7727 if (error == NULL)
7728 error = close_err;
7730 if (pack_fds) {
7731 const struct got_error *pack_err =
7732 got_repo_pack_fds_close(pack_fds);
7733 if (error == NULL)
7734 error = pack_err;
7736 tog_free_refs();
7737 return error;
7740 static const struct got_error *
7741 ref_view_load_refs(struct tog_ref_view_state *s)
7743 struct got_reflist_entry *sre;
7744 struct tog_reflist_entry *re;
7746 s->nrefs = 0;
7747 TAILQ_FOREACH(sre, &tog_refs, entry) {
7748 if (strncmp(got_ref_get_name(sre->ref),
7749 "refs/got/", 9) == 0 &&
7750 strncmp(got_ref_get_name(sre->ref),
7751 "refs/got/backup/", 16) != 0)
7752 continue;
7754 re = malloc(sizeof(*re));
7755 if (re == NULL)
7756 return got_error_from_errno("malloc");
7758 re->ref = got_ref_dup(sre->ref);
7759 if (re->ref == NULL)
7760 return got_error_from_errno("got_ref_dup");
7761 re->idx = s->nrefs++;
7762 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7765 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7766 return NULL;
7769 static void
7770 ref_view_free_refs(struct tog_ref_view_state *s)
7772 struct tog_reflist_entry *re;
7774 while (!TAILQ_EMPTY(&s->refs)) {
7775 re = TAILQ_FIRST(&s->refs);
7776 TAILQ_REMOVE(&s->refs, re, entry);
7777 got_ref_close(re->ref);
7778 free(re);
7782 static const struct got_error *
7783 open_ref_view(struct tog_view *view, struct got_repository *repo)
7785 const struct got_error *err = NULL;
7786 struct tog_ref_view_state *s = &view->state.ref;
7788 s->selected_entry = 0;
7789 s->repo = repo;
7791 TAILQ_INIT(&s->refs);
7792 STAILQ_INIT(&s->colors);
7794 err = ref_view_load_refs(s);
7795 if (err)
7796 return err;
7798 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7799 err = add_color(&s->colors, "^refs/heads/",
7800 TOG_COLOR_REFS_HEADS,
7801 get_color_value("TOG_COLOR_REFS_HEADS"));
7802 if (err)
7803 goto done;
7805 err = add_color(&s->colors, "^refs/tags/",
7806 TOG_COLOR_REFS_TAGS,
7807 get_color_value("TOG_COLOR_REFS_TAGS"));
7808 if (err)
7809 goto done;
7811 err = add_color(&s->colors, "^refs/remotes/",
7812 TOG_COLOR_REFS_REMOTES,
7813 get_color_value("TOG_COLOR_REFS_REMOTES"));
7814 if (err)
7815 goto done;
7817 err = add_color(&s->colors, "^refs/got/backup/",
7818 TOG_COLOR_REFS_BACKUP,
7819 get_color_value("TOG_COLOR_REFS_BACKUP"));
7820 if (err)
7821 goto done;
7824 view->show = show_ref_view;
7825 view->input = input_ref_view;
7826 view->close = close_ref_view;
7827 view->search_start = search_start_ref_view;
7828 view->search_next = search_next_ref_view;
7829 done:
7830 if (err)
7831 free_colors(&s->colors);
7832 return err;
7835 static const struct got_error *
7836 close_ref_view(struct tog_view *view)
7838 struct tog_ref_view_state *s = &view->state.ref;
7840 ref_view_free_refs(s);
7841 free_colors(&s->colors);
7843 return NULL;
7846 static const struct got_error *
7847 resolve_reflist_entry(struct got_object_id **commit_id,
7848 struct tog_reflist_entry *re, struct got_repository *repo)
7850 const struct got_error *err = NULL;
7851 struct got_object_id *obj_id;
7852 struct got_tag_object *tag = NULL;
7853 int obj_type;
7855 *commit_id = NULL;
7857 err = got_ref_resolve(&obj_id, repo, re->ref);
7858 if (err)
7859 return err;
7861 err = got_object_get_type(&obj_type, repo, obj_id);
7862 if (err)
7863 goto done;
7865 switch (obj_type) {
7866 case GOT_OBJ_TYPE_COMMIT:
7867 *commit_id = obj_id;
7868 break;
7869 case GOT_OBJ_TYPE_TAG:
7870 err = got_object_open_as_tag(&tag, repo, obj_id);
7871 if (err)
7872 goto done;
7873 free(obj_id);
7874 err = got_object_get_type(&obj_type, repo,
7875 got_object_tag_get_object_id(tag));
7876 if (err)
7877 goto done;
7878 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7879 err = got_error(GOT_ERR_OBJ_TYPE);
7880 goto done;
7882 *commit_id = got_object_id_dup(
7883 got_object_tag_get_object_id(tag));
7884 if (*commit_id == NULL) {
7885 err = got_error_from_errno("got_object_id_dup");
7886 goto done;
7888 break;
7889 default:
7890 err = got_error(GOT_ERR_OBJ_TYPE);
7891 break;
7894 done:
7895 if (tag)
7896 got_object_tag_close(tag);
7897 if (err) {
7898 free(*commit_id);
7899 *commit_id = NULL;
7901 return err;
7904 static const struct got_error *
7905 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7906 struct tog_reflist_entry *re, struct got_repository *repo)
7908 struct tog_view *log_view;
7909 const struct got_error *err = NULL;
7910 struct got_object_id *commit_id = NULL;
7912 *new_view = NULL;
7914 err = resolve_reflist_entry(&commit_id, re, repo);
7915 if (err) {
7916 if (err->code != GOT_ERR_OBJ_TYPE)
7917 return err;
7918 else
7919 return NULL;
7922 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7923 if (log_view == NULL) {
7924 err = got_error_from_errno("view_open");
7925 goto done;
7928 err = open_log_view(log_view, commit_id, repo,
7929 got_ref_get_name(re->ref), "", 0);
7930 done:
7931 if (err)
7932 view_close(log_view);
7933 else
7934 *new_view = log_view;
7935 free(commit_id);
7936 return err;
7939 static void
7940 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7942 struct tog_reflist_entry *re;
7943 int i = 0;
7945 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7946 return;
7948 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7949 while (i++ < maxscroll) {
7950 if (re == NULL)
7951 break;
7952 s->first_displayed_entry = re;
7953 re = TAILQ_PREV(re, tog_reflist_head, entry);
7957 static const struct got_error *
7958 ref_scroll_down(struct tog_view *view, int maxscroll)
7960 struct tog_ref_view_state *s = &view->state.ref;
7961 struct tog_reflist_entry *next, *last;
7962 int n = 0;
7964 if (s->first_displayed_entry)
7965 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7966 else
7967 next = TAILQ_FIRST(&s->refs);
7969 last = s->last_displayed_entry;
7970 while (next && n++ < maxscroll) {
7971 if (last) {
7972 s->last_displayed_entry = last;
7973 last = TAILQ_NEXT(last, entry);
7975 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7976 s->first_displayed_entry = next;
7977 next = TAILQ_NEXT(next, entry);
7981 return NULL;
7984 static const struct got_error *
7985 search_start_ref_view(struct tog_view *view)
7987 struct tog_ref_view_state *s = &view->state.ref;
7989 s->matched_entry = NULL;
7990 return NULL;
7993 static int
7994 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7996 regmatch_t regmatch;
7998 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7999 0) == 0;
8002 static const struct got_error *
8003 search_next_ref_view(struct tog_view *view)
8005 struct tog_ref_view_state *s = &view->state.ref;
8006 struct tog_reflist_entry *re = NULL;
8008 if (!view->searching) {
8009 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8010 return NULL;
8013 if (s->matched_entry) {
8014 if (view->searching == TOG_SEARCH_FORWARD) {
8015 if (s->selected_entry)
8016 re = TAILQ_NEXT(s->selected_entry, entry);
8017 else
8018 re = TAILQ_PREV(s->selected_entry,
8019 tog_reflist_head, entry);
8020 } else {
8021 if (s->selected_entry == NULL)
8022 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8023 else
8024 re = TAILQ_PREV(s->selected_entry,
8025 tog_reflist_head, entry);
8027 } else {
8028 if (s->selected_entry)
8029 re = s->selected_entry;
8030 else if (view->searching == TOG_SEARCH_FORWARD)
8031 re = TAILQ_FIRST(&s->refs);
8032 else
8033 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8036 while (1) {
8037 if (re == NULL) {
8038 if (s->matched_entry == NULL) {
8039 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8040 return NULL;
8042 if (view->searching == TOG_SEARCH_FORWARD)
8043 re = TAILQ_FIRST(&s->refs);
8044 else
8045 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8048 if (match_reflist_entry(re, &view->regex)) {
8049 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8050 s->matched_entry = re;
8051 break;
8054 if (view->searching == TOG_SEARCH_FORWARD)
8055 re = TAILQ_NEXT(re, entry);
8056 else
8057 re = TAILQ_PREV(re, tog_reflist_head, entry);
8060 if (s->matched_entry) {
8061 s->first_displayed_entry = s->matched_entry;
8062 s->selected = 0;
8065 return NULL;
8068 static const struct got_error *
8069 show_ref_view(struct tog_view *view)
8071 const struct got_error *err = NULL;
8072 struct tog_ref_view_state *s = &view->state.ref;
8073 struct tog_reflist_entry *re;
8074 char *line = NULL;
8075 wchar_t *wline;
8076 struct tog_color *tc;
8077 int width, n, scrollx;
8078 int limit = view->nlines;
8080 werase(view->window);
8082 s->ndisplayed = 0;
8083 if (view_is_hsplit_top(view))
8084 --limit; /* border */
8086 if (limit == 0)
8087 return NULL;
8089 re = s->first_displayed_entry;
8091 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8092 s->nrefs) == -1)
8093 return got_error_from_errno("asprintf");
8095 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8096 if (err) {
8097 free(line);
8098 return err;
8100 if (view_needs_focus_indication(view))
8101 wstandout(view->window);
8102 waddwstr(view->window, wline);
8103 while (width++ < view->ncols)
8104 waddch(view->window, ' ');
8105 if (view_needs_focus_indication(view))
8106 wstandend(view->window);
8107 free(wline);
8108 wline = NULL;
8109 free(line);
8110 line = NULL;
8111 if (--limit <= 0)
8112 return NULL;
8114 n = 0;
8115 view->maxx = 0;
8116 while (re && limit > 0) {
8117 char *line = NULL;
8118 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8120 if (s->show_date) {
8121 struct got_commit_object *ci;
8122 struct got_tag_object *tag;
8123 struct got_object_id *id;
8124 struct tm tm;
8125 time_t t;
8127 err = got_ref_resolve(&id, s->repo, re->ref);
8128 if (err)
8129 return err;
8130 err = got_object_open_as_tag(&tag, s->repo, id);
8131 if (err) {
8132 if (err->code != GOT_ERR_OBJ_TYPE) {
8133 free(id);
8134 return err;
8136 err = got_object_open_as_commit(&ci, s->repo,
8137 id);
8138 if (err) {
8139 free(id);
8140 return err;
8142 t = got_object_commit_get_committer_time(ci);
8143 got_object_commit_close(ci);
8144 } else {
8145 t = got_object_tag_get_tagger_time(tag);
8146 got_object_tag_close(tag);
8148 free(id);
8149 if (gmtime_r(&t, &tm) == NULL)
8150 return got_error_from_errno("gmtime_r");
8151 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8152 return got_error(GOT_ERR_NO_SPACE);
8154 if (got_ref_is_symbolic(re->ref)) {
8155 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8156 ymd : "", got_ref_get_name(re->ref),
8157 got_ref_get_symref_target(re->ref)) == -1)
8158 return got_error_from_errno("asprintf");
8159 } else if (s->show_ids) {
8160 struct got_object_id *id;
8161 char *id_str;
8162 err = got_ref_resolve(&id, s->repo, re->ref);
8163 if (err)
8164 return err;
8165 err = got_object_id_str(&id_str, id);
8166 if (err) {
8167 free(id);
8168 return err;
8170 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8171 got_ref_get_name(re->ref), id_str) == -1) {
8172 err = got_error_from_errno("asprintf");
8173 free(id);
8174 free(id_str);
8175 return err;
8177 free(id);
8178 free(id_str);
8179 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8180 got_ref_get_name(re->ref)) == -1)
8181 return got_error_from_errno("asprintf");
8183 /* use full line width to determine view->maxx */
8184 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8185 if (err) {
8186 free(line);
8187 return err;
8189 view->maxx = MAX(view->maxx, width);
8190 free(wline);
8191 wline = NULL;
8193 err = format_line(&wline, &width, &scrollx, line, view->x,
8194 view->ncols, 0, 0);
8195 if (err) {
8196 free(line);
8197 return err;
8199 if (n == s->selected) {
8200 if (view->focussed)
8201 wstandout(view->window);
8202 s->selected_entry = re;
8204 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8205 if (tc)
8206 wattr_on(view->window,
8207 COLOR_PAIR(tc->colorpair), NULL);
8208 waddwstr(view->window, &wline[scrollx]);
8209 if (tc)
8210 wattr_off(view->window,
8211 COLOR_PAIR(tc->colorpair), NULL);
8212 if (width < view->ncols)
8213 waddch(view->window, '\n');
8214 if (n == s->selected && view->focussed)
8215 wstandend(view->window);
8216 free(line);
8217 free(wline);
8218 wline = NULL;
8219 n++;
8220 s->ndisplayed++;
8221 s->last_displayed_entry = re;
8223 limit--;
8224 re = TAILQ_NEXT(re, entry);
8227 view_border(view);
8228 return err;
8231 static const struct got_error *
8232 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8233 struct tog_reflist_entry *re, struct got_repository *repo)
8235 const struct got_error *err = NULL;
8236 struct got_object_id *commit_id = NULL;
8237 struct tog_view *tree_view;
8239 *new_view = NULL;
8241 err = resolve_reflist_entry(&commit_id, re, repo);
8242 if (err) {
8243 if (err->code != GOT_ERR_OBJ_TYPE)
8244 return err;
8245 else
8246 return NULL;
8250 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8251 if (tree_view == NULL) {
8252 err = got_error_from_errno("view_open");
8253 goto done;
8256 err = open_tree_view(tree_view, commit_id,
8257 got_ref_get_name(re->ref), repo);
8258 if (err)
8259 goto done;
8261 *new_view = tree_view;
8262 done:
8263 free(commit_id);
8264 return err;
8267 static const struct got_error *
8268 ref_goto_line(struct tog_view *view, int nlines)
8270 const struct got_error *err = NULL;
8271 struct tog_ref_view_state *s = &view->state.ref;
8272 int g, idx = s->selected_entry->idx;
8274 g = view->gline;
8275 view->gline = 0;
8277 if (g == 0)
8278 g = 1;
8279 else if (g > s->nrefs)
8280 g = s->nrefs;
8282 if (g >= s->first_displayed_entry->idx + 1 &&
8283 g <= s->last_displayed_entry->idx + 1 &&
8284 g - s->first_displayed_entry->idx - 1 < nlines) {
8285 s->selected = g - s->first_displayed_entry->idx - 1;
8286 return NULL;
8289 if (idx + 1 < g) {
8290 err = ref_scroll_down(view, g - idx - 1);
8291 if (err)
8292 return err;
8293 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8294 s->first_displayed_entry->idx + s->selected < g &&
8295 s->selected < s->ndisplayed - 1)
8296 s->selected = g - s->first_displayed_entry->idx - 1;
8297 } else if (idx + 1 > g)
8298 ref_scroll_up(s, idx - g + 1);
8300 if (g < nlines && s->first_displayed_entry->idx == 0)
8301 s->selected = g - 1;
8303 return NULL;
8307 static const struct got_error *
8308 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8310 const struct got_error *err = NULL;
8311 struct tog_ref_view_state *s = &view->state.ref;
8312 struct tog_reflist_entry *re;
8313 int n, nscroll = view->nlines - 1;
8315 if (view->gline)
8316 return ref_goto_line(view, nscroll);
8318 switch (ch) {
8319 case '0':
8320 case '$':
8321 case KEY_RIGHT:
8322 case 'l':
8323 case KEY_LEFT:
8324 case 'h':
8325 horizontal_scroll_input(view, ch);
8326 break;
8327 case 'i':
8328 s->show_ids = !s->show_ids;
8329 view->count = 0;
8330 break;
8331 case 'm':
8332 s->show_date = !s->show_date;
8333 view->count = 0;
8334 break;
8335 case 'o':
8336 s->sort_by_date = !s->sort_by_date;
8337 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8338 view->count = 0;
8339 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8340 got_ref_cmp_by_commit_timestamp_descending :
8341 tog_ref_cmp_by_name, s->repo);
8342 if (err)
8343 break;
8344 got_reflist_object_id_map_free(tog_refs_idmap);
8345 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8346 &tog_refs, s->repo);
8347 if (err)
8348 break;
8349 ref_view_free_refs(s);
8350 err = ref_view_load_refs(s);
8351 break;
8352 case KEY_ENTER:
8353 case '\r':
8354 view->count = 0;
8355 if (!s->selected_entry)
8356 break;
8357 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8358 break;
8359 case 'T':
8360 view->count = 0;
8361 if (!s->selected_entry)
8362 break;
8363 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8364 break;
8365 case 'g':
8366 case '=':
8367 case KEY_HOME:
8368 s->selected = 0;
8369 view->count = 0;
8370 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8371 break;
8372 case 'G':
8373 case '*':
8374 case KEY_END: {
8375 int eos = view->nlines - 1;
8377 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8378 --eos; /* border */
8379 s->selected = 0;
8380 view->count = 0;
8381 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8382 for (n = 0; n < eos; n++) {
8383 if (re == NULL)
8384 break;
8385 s->first_displayed_entry = re;
8386 re = TAILQ_PREV(re, tog_reflist_head, entry);
8388 if (n > 0)
8389 s->selected = n - 1;
8390 break;
8392 case 'k':
8393 case KEY_UP:
8394 case CTRL('p'):
8395 if (s->selected > 0) {
8396 s->selected--;
8397 break;
8399 ref_scroll_up(s, 1);
8400 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8401 view->count = 0;
8402 break;
8403 case CTRL('u'):
8404 case 'u':
8405 nscroll /= 2;
8406 /* FALL THROUGH */
8407 case KEY_PPAGE:
8408 case CTRL('b'):
8409 case 'b':
8410 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8411 s->selected -= MIN(nscroll, s->selected);
8412 ref_scroll_up(s, MAX(0, nscroll));
8413 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8414 view->count = 0;
8415 break;
8416 case 'j':
8417 case KEY_DOWN:
8418 case CTRL('n'):
8419 if (s->selected < s->ndisplayed - 1) {
8420 s->selected++;
8421 break;
8423 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8424 /* can't scroll any further */
8425 view->count = 0;
8426 break;
8428 ref_scroll_down(view, 1);
8429 break;
8430 case CTRL('d'):
8431 case 'd':
8432 nscroll /= 2;
8433 /* FALL THROUGH */
8434 case KEY_NPAGE:
8435 case CTRL('f'):
8436 case 'f':
8437 case ' ':
8438 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8439 /* can't scroll any further; move cursor down */
8440 if (s->selected < s->ndisplayed - 1)
8441 s->selected += MIN(nscroll,
8442 s->ndisplayed - s->selected - 1);
8443 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8444 s->selected += s->ndisplayed - s->selected - 1;
8445 view->count = 0;
8446 break;
8448 ref_scroll_down(view, nscroll);
8449 break;
8450 case CTRL('l'):
8451 view->count = 0;
8452 tog_free_refs();
8453 err = tog_load_refs(s->repo, s->sort_by_date);
8454 if (err)
8455 break;
8456 ref_view_free_refs(s);
8457 err = ref_view_load_refs(s);
8458 break;
8459 case KEY_RESIZE:
8460 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8461 s->selected = view->nlines - 2;
8462 break;
8463 default:
8464 view->count = 0;
8465 break;
8468 return err;
8471 __dead static void
8472 usage_ref(void)
8474 endwin();
8475 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8476 getprogname());
8477 exit(1);
8480 static const struct got_error *
8481 cmd_ref(int argc, char *argv[])
8483 const struct got_error *error;
8484 struct got_repository *repo = NULL;
8485 struct got_worktree *worktree = NULL;
8486 char *cwd = NULL, *repo_path = NULL;
8487 int ch;
8488 struct tog_view *view;
8489 int *pack_fds = NULL;
8491 while ((ch = getopt(argc, argv, "r:")) != -1) {
8492 switch (ch) {
8493 case 'r':
8494 repo_path = realpath(optarg, NULL);
8495 if (repo_path == NULL)
8496 return got_error_from_errno2("realpath",
8497 optarg);
8498 break;
8499 default:
8500 usage_ref();
8501 /* NOTREACHED */
8505 argc -= optind;
8506 argv += optind;
8508 if (argc > 1)
8509 usage_ref();
8511 error = got_repo_pack_fds_open(&pack_fds);
8512 if (error != NULL)
8513 goto done;
8515 if (repo_path == NULL) {
8516 cwd = getcwd(NULL, 0);
8517 if (cwd == NULL)
8518 return got_error_from_errno("getcwd");
8519 error = got_worktree_open(&worktree, cwd);
8520 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8521 goto done;
8522 if (worktree)
8523 repo_path =
8524 strdup(got_worktree_get_repo_path(worktree));
8525 else
8526 repo_path = strdup(cwd);
8527 if (repo_path == NULL) {
8528 error = got_error_from_errno("strdup");
8529 goto done;
8533 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8534 if (error != NULL)
8535 goto done;
8537 init_curses();
8539 error = apply_unveil(got_repo_get_path(repo), NULL);
8540 if (error)
8541 goto done;
8543 error = tog_load_refs(repo, 0);
8544 if (error)
8545 goto done;
8547 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8548 if (view == NULL) {
8549 error = got_error_from_errno("view_open");
8550 goto done;
8553 error = open_ref_view(view, repo);
8554 if (error)
8555 goto done;
8557 if (worktree) {
8558 /* Release work tree lock. */
8559 got_worktree_close(worktree);
8560 worktree = NULL;
8562 error = view_loop(view);
8563 done:
8564 free(repo_path);
8565 free(cwd);
8566 if (repo) {
8567 const struct got_error *close_err = got_repo_close(repo);
8568 if (close_err)
8569 error = close_err;
8571 if (pack_fds) {
8572 const struct got_error *pack_err =
8573 got_repo_pack_fds_close(pack_fds);
8574 if (error == NULL)
8575 error = pack_err;
8577 tog_free_refs();
8578 return error;
8581 static const struct got_error*
8582 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8583 const char *str)
8585 size_t len;
8587 if (win == NULL)
8588 win = stdscr;
8590 len = strlen(str);
8591 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8593 if (focus)
8594 wstandout(win);
8595 if (mvwprintw(win, y, x, "%s", str) == ERR)
8596 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8597 if (focus)
8598 wstandend(win);
8600 return NULL;
8603 static const struct got_error *
8604 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8606 off_t *p;
8608 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8609 if (p == NULL) {
8610 free(*line_offsets);
8611 *line_offsets = NULL;
8612 return got_error_from_errno("reallocarray");
8615 *line_offsets = p;
8616 (*line_offsets)[*nlines] = off;
8617 ++(*nlines);
8618 return NULL;
8621 static const struct got_error *
8622 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8624 *ret = 0;
8626 for (;n > 0; --n, ++km) {
8627 char *t0, *t, *k;
8628 size_t len = 1;
8630 if (km->keys == NULL)
8631 continue;
8633 t = t0 = strdup(km->keys);
8634 if (t0 == NULL)
8635 return got_error_from_errno("strdup");
8637 len += strlen(t);
8638 while ((k = strsep(&t, " ")) != NULL)
8639 len += strlen(k) > 1 ? 2 : 0;
8640 free(t0);
8641 *ret = MAX(*ret, len);
8644 return NULL;
8648 * Write keymap section headers, keys, and key info in km to f.
8649 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8650 * wrap control and symbolic keys in guillemets, else use <>.
8652 static const struct got_error *
8653 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8655 int n, len = width;
8657 if (km->keys) {
8658 static const char *u8_glyph[] = {
8659 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8660 "\xe2\x80\xba" /* U+203A (utf8 >) */
8662 char *t0, *t, *k;
8663 int cs, s, first = 1;
8665 cs = got_locale_is_utf8();
8667 t = t0 = strdup(km->keys);
8668 if (t0 == NULL)
8669 return got_error_from_errno("strdup");
8671 len = strlen(km->keys);
8672 while ((k = strsep(&t, " ")) != NULL) {
8673 s = strlen(k) > 1; /* control or symbolic key */
8674 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8675 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8676 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8677 if (n < 0) {
8678 free(t0);
8679 return got_error_from_errno("fprintf");
8681 first = 0;
8682 len += s ? 2 : 0;
8683 *off += n;
8685 free(t0);
8687 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8688 if (n < 0)
8689 return got_error_from_errno("fprintf");
8690 *off += n;
8692 return NULL;
8695 static const struct got_error *
8696 format_help(struct tog_help_view_state *s)
8698 const struct got_error *err = NULL;
8699 off_t off = 0;
8700 int i, max, n, show = s->all;
8701 static const struct tog_key_map km[] = {
8702 #define KEYMAP_(info, type) { NULL, (info), type }
8703 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8704 GENERATE_HELP
8705 #undef KEYMAP_
8706 #undef KEY_
8709 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8710 if (err)
8711 return err;
8713 n = nitems(km);
8714 err = max_key_str(&max, km, n);
8715 if (err)
8716 return err;
8718 for (i = 0; i < n; ++i) {
8719 if (km[i].keys == NULL) {
8720 show = s->all;
8721 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8722 km[i].type == s->type || s->all)
8723 show = 1;
8725 if (show) {
8726 err = format_help_line(&off, s->f, &km[i], max);
8727 if (err)
8728 return err;
8729 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8730 if (err)
8731 return err;
8734 fputc('\n', s->f);
8735 ++off;
8736 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8737 return err;
8740 static const struct got_error *
8741 create_help(struct tog_help_view_state *s)
8743 FILE *f;
8744 const struct got_error *err;
8746 free(s->line_offsets);
8747 s->line_offsets = NULL;
8748 s->nlines = 0;
8750 f = got_opentemp();
8751 if (f == NULL)
8752 return got_error_from_errno("got_opentemp");
8753 s->f = f;
8755 err = format_help(s);
8756 if (err)
8757 return err;
8759 if (s->f && fflush(s->f) != 0)
8760 return got_error_from_errno("fflush");
8762 return NULL;
8765 static const struct got_error *
8766 search_start_help_view(struct tog_view *view)
8768 view->state.help.matched_line = 0;
8769 return NULL;
8772 static void
8773 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8774 size_t *nlines, int **first, int **last, int **match, int **selected)
8776 struct tog_help_view_state *s = &view->state.help;
8778 *f = s->f;
8779 *nlines = s->nlines;
8780 *line_offsets = s->line_offsets;
8781 *match = &s->matched_line;
8782 *first = &s->first_displayed_line;
8783 *last = &s->last_displayed_line;
8784 *selected = &s->selected_line;
8787 static const struct got_error *
8788 show_help_view(struct tog_view *view)
8790 struct tog_help_view_state *s = &view->state.help;
8791 const struct got_error *err;
8792 regmatch_t *regmatch = &view->regmatch;
8793 wchar_t *wline;
8794 char *line;
8795 ssize_t linelen;
8796 size_t linesz = 0;
8797 int width, nprinted = 0, rc = 0;
8798 int eos = view->nlines;
8800 if (view_is_hsplit_top(view))
8801 --eos; /* account for border */
8803 s->lineno = 0;
8804 rewind(s->f);
8805 werase(view->window);
8807 if (view->gline > s->nlines - 1)
8808 view->gline = s->nlines - 1;
8810 err = win_draw_center(view->window, 0, 0, view->ncols,
8811 view_needs_focus_indication(view),
8812 "tog help (press q to return to tog)");
8813 if (err)
8814 return err;
8815 if (eos <= 1)
8816 return NULL;
8817 waddstr(view->window, "\n\n");
8818 eos -= 2;
8820 s->eof = 0;
8821 view->maxx = 0;
8822 line = NULL;
8823 while (eos > 0 && nprinted < eos) {
8824 attr_t attr = 0;
8826 linelen = getline(&line, &linesz, s->f);
8827 if (linelen == -1) {
8828 if (!feof(s->f)) {
8829 free(line);
8830 return got_ferror(s->f, GOT_ERR_IO);
8832 s->eof = 1;
8833 break;
8835 if (++s->lineno < s->first_displayed_line)
8836 continue;
8837 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8838 continue;
8839 if (s->lineno == view->hiline)
8840 attr = A_STANDOUT;
8842 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8843 view->x ? 1 : 0);
8844 if (err) {
8845 free(line);
8846 return err;
8848 view->maxx = MAX(view->maxx, width);
8849 free(wline);
8850 wline = NULL;
8852 if (attr)
8853 wattron(view->window, attr);
8854 if (s->first_displayed_line + nprinted == s->matched_line &&
8855 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8856 err = add_matched_line(&width, line, view->ncols - 1, 0,
8857 view->window, view->x, regmatch);
8858 if (err) {
8859 free(line);
8860 return err;
8862 } else {
8863 int skip;
8865 err = format_line(&wline, &width, &skip, line,
8866 view->x, view->ncols, 0, view->x ? 1 : 0);
8867 if (err) {
8868 free(line);
8869 return err;
8871 waddwstr(view->window, &wline[skip]);
8872 free(wline);
8873 wline = NULL;
8875 if (s->lineno == view->hiline) {
8876 while (width++ < view->ncols)
8877 waddch(view->window, ' ');
8878 } else {
8879 if (width < view->ncols)
8880 waddch(view->window, '\n');
8882 if (attr)
8883 wattroff(view->window, attr);
8884 if (++nprinted == 1)
8885 s->first_displayed_line = s->lineno;
8887 free(line);
8888 if (nprinted > 0)
8889 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8890 else
8891 s->last_displayed_line = s->first_displayed_line;
8893 view_border(view);
8895 if (s->eof) {
8896 rc = waddnstr(view->window,
8897 "See the tog(1) manual page for full documentation",
8898 view->ncols - 1);
8899 if (rc == ERR)
8900 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8901 } else {
8902 wmove(view->window, view->nlines - 1, 0);
8903 wclrtoeol(view->window);
8904 wstandout(view->window);
8905 rc = waddnstr(view->window, "scroll down for more...",
8906 view->ncols - 1);
8907 if (rc == ERR)
8908 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8909 if (getcurx(view->window) < view->ncols - 6) {
8910 rc = wprintw(view->window, "[%.0f%%]",
8911 100.00 * s->last_displayed_line / s->nlines);
8912 if (rc == ERR)
8913 return got_error_msg(GOT_ERR_IO, "wprintw");
8915 wstandend(view->window);
8918 return NULL;
8921 static const struct got_error *
8922 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8924 struct tog_help_view_state *s = &view->state.help;
8925 const struct got_error *err = NULL;
8926 char *line = NULL;
8927 ssize_t linelen;
8928 size_t linesz = 0;
8929 int eos, nscroll;
8931 eos = nscroll = view->nlines;
8932 if (view_is_hsplit_top(view))
8933 --eos; /* border */
8935 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8937 switch (ch) {
8938 case '0':
8939 case '$':
8940 case KEY_RIGHT:
8941 case 'l':
8942 case KEY_LEFT:
8943 case 'h':
8944 horizontal_scroll_input(view, ch);
8945 break;
8946 case 'g':
8947 case KEY_HOME:
8948 s->first_displayed_line = 1;
8949 view->count = 0;
8950 break;
8951 case 'G':
8952 case KEY_END:
8953 view->count = 0;
8954 if (s->eof)
8955 break;
8956 s->first_displayed_line = (s->nlines - eos) + 3;
8957 s->eof = 1;
8958 break;
8959 case 'k':
8960 case KEY_UP:
8961 if (s->first_displayed_line > 1)
8962 --s->first_displayed_line;
8963 else
8964 view->count = 0;
8965 break;
8966 case CTRL('u'):
8967 case 'u':
8968 nscroll /= 2;
8969 /* FALL THROUGH */
8970 case KEY_PPAGE:
8971 case CTRL('b'):
8972 case 'b':
8973 if (s->first_displayed_line == 1) {
8974 view->count = 0;
8975 break;
8977 while (--nscroll > 0 && s->first_displayed_line > 1)
8978 s->first_displayed_line--;
8979 break;
8980 case 'j':
8981 case KEY_DOWN:
8982 case CTRL('n'):
8983 if (!s->eof)
8984 ++s->first_displayed_line;
8985 else
8986 view->count = 0;
8987 break;
8988 case CTRL('d'):
8989 case 'd':
8990 nscroll /= 2;
8991 /* FALL THROUGH */
8992 case KEY_NPAGE:
8993 case CTRL('f'):
8994 case 'f':
8995 case ' ':
8996 if (s->eof) {
8997 view->count = 0;
8998 break;
9000 while (!s->eof && --nscroll > 0) {
9001 linelen = getline(&line, &linesz, s->f);
9002 s->first_displayed_line++;
9003 if (linelen == -1) {
9004 if (feof(s->f))
9005 s->eof = 1;
9006 else
9007 err = got_ferror(s->f, GOT_ERR_IO);
9008 break;
9011 free(line);
9012 break;
9013 default:
9014 view->count = 0;
9015 break;
9018 return err;
9021 static const struct got_error *
9022 close_help_view(struct tog_view *view)
9024 struct tog_help_view_state *s = &view->state.help;
9026 free(s->line_offsets);
9027 s->line_offsets = NULL;
9028 if (fclose(s->f) == EOF)
9029 return got_error_from_errno("fclose");
9031 return NULL;
9034 static const struct got_error *
9035 reset_help_view(struct tog_view *view)
9037 struct tog_help_view_state *s = &view->state.help;
9040 if (s->f && fclose(s->f) == EOF)
9041 return got_error_from_errno("fclose");
9043 wclear(view->window);
9044 view->count = 0;
9045 view->x = 0;
9046 s->all = !s->all;
9047 s->first_displayed_line = 1;
9048 s->last_displayed_line = view->nlines;
9049 s->matched_line = 0;
9051 return create_help(s);
9054 static const struct got_error *
9055 open_help_view(struct tog_view *view, struct tog_view *parent)
9057 const struct got_error *err = NULL;
9058 struct tog_help_view_state *s = &view->state.help;
9060 s->type = (enum tog_keymap_type)parent->type;
9061 s->first_displayed_line = 1;
9062 s->last_displayed_line = view->nlines;
9063 s->selected_line = 1;
9065 view->show = show_help_view;
9066 view->input = input_help_view;
9067 view->reset = reset_help_view;
9068 view->close = close_help_view;
9069 view->search_start = search_start_help_view;
9070 view->search_setup = search_setup_help_view;
9071 view->search_next = search_next_view_match;
9073 err = create_help(s);
9074 return err;
9077 static const struct got_error *
9078 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9079 enum tog_view_type request, int y, int x)
9081 const struct got_error *err = NULL;
9083 *new_view = NULL;
9085 switch (request) {
9086 case TOG_VIEW_DIFF:
9087 if (view->type == TOG_VIEW_LOG) {
9088 struct tog_log_view_state *s = &view->state.log;
9090 err = open_diff_view_for_commit(new_view, y, x,
9091 s->selected_entry->commit, s->selected_entry->id,
9092 view, s->repo);
9093 } else
9094 return got_error_msg(GOT_ERR_NOT_IMPL,
9095 "parent/child view pair not supported");
9096 break;
9097 case TOG_VIEW_BLAME:
9098 if (view->type == TOG_VIEW_TREE) {
9099 struct tog_tree_view_state *s = &view->state.tree;
9101 err = blame_tree_entry(new_view, y, x,
9102 s->selected_entry, &s->parents, s->commit_id,
9103 s->repo);
9104 } else
9105 return got_error_msg(GOT_ERR_NOT_IMPL,
9106 "parent/child view pair not supported");
9107 break;
9108 case TOG_VIEW_LOG:
9109 if (view->type == TOG_VIEW_BLAME)
9110 err = log_annotated_line(new_view, y, x,
9111 view->state.blame.repo, view->state.blame.id_to_log);
9112 else if (view->type == TOG_VIEW_TREE)
9113 err = log_selected_tree_entry(new_view, y, x,
9114 &view->state.tree);
9115 else if (view->type == TOG_VIEW_REF)
9116 err = log_ref_entry(new_view, y, x,
9117 view->state.ref.selected_entry,
9118 view->state.ref.repo);
9119 else
9120 return got_error_msg(GOT_ERR_NOT_IMPL,
9121 "parent/child view pair not supported");
9122 break;
9123 case TOG_VIEW_TREE:
9124 if (view->type == TOG_VIEW_LOG)
9125 err = browse_commit_tree(new_view, y, x,
9126 view->state.log.selected_entry,
9127 view->state.log.in_repo_path,
9128 view->state.log.head_ref_name,
9129 view->state.log.repo);
9130 else if (view->type == TOG_VIEW_REF)
9131 err = browse_ref_tree(new_view, y, x,
9132 view->state.ref.selected_entry,
9133 view->state.ref.repo);
9134 else
9135 return got_error_msg(GOT_ERR_NOT_IMPL,
9136 "parent/child view pair not supported");
9137 break;
9138 case TOG_VIEW_REF:
9139 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9140 if (*new_view == NULL)
9141 return got_error_from_errno("view_open");
9142 if (view->type == TOG_VIEW_LOG)
9143 err = open_ref_view(*new_view, view->state.log.repo);
9144 else if (view->type == TOG_VIEW_TREE)
9145 err = open_ref_view(*new_view, view->state.tree.repo);
9146 else
9147 err = got_error_msg(GOT_ERR_NOT_IMPL,
9148 "parent/child view pair not supported");
9149 if (err)
9150 view_close(*new_view);
9151 break;
9152 case TOG_VIEW_HELP:
9153 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9154 if (*new_view == NULL)
9155 return got_error_from_errno("view_open");
9156 err = open_help_view(*new_view, view);
9157 if (err)
9158 view_close(*new_view);
9159 break;
9160 default:
9161 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9164 return err;
9168 * If view was scrolled down to move the selected line into view when opening a
9169 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9171 static void
9172 offset_selection_up(struct tog_view *view)
9174 switch (view->type) {
9175 case TOG_VIEW_BLAME: {
9176 struct tog_blame_view_state *s = &view->state.blame;
9177 if (s->first_displayed_line == 1) {
9178 s->selected_line = MAX(s->selected_line - view->offset,
9179 1);
9180 break;
9182 if (s->first_displayed_line > view->offset)
9183 s->first_displayed_line -= view->offset;
9184 else
9185 s->first_displayed_line = 1;
9186 s->selected_line += view->offset;
9187 break;
9189 case TOG_VIEW_LOG:
9190 log_scroll_up(&view->state.log, view->offset);
9191 view->state.log.selected += view->offset;
9192 break;
9193 case TOG_VIEW_REF:
9194 ref_scroll_up(&view->state.ref, view->offset);
9195 view->state.ref.selected += view->offset;
9196 break;
9197 case TOG_VIEW_TREE:
9198 tree_scroll_up(&view->state.tree, view->offset);
9199 view->state.tree.selected += view->offset;
9200 break;
9201 default:
9202 break;
9205 view->offset = 0;
9209 * If the selected line is in the section of screen covered by the bottom split,
9210 * scroll down offset lines to move it into view and index its new position.
9212 static const struct got_error *
9213 offset_selection_down(struct tog_view *view)
9215 const struct got_error *err = NULL;
9216 const struct got_error *(*scrolld)(struct tog_view *, int);
9217 int *selected = NULL;
9218 int header, offset;
9220 switch (view->type) {
9221 case TOG_VIEW_BLAME: {
9222 struct tog_blame_view_state *s = &view->state.blame;
9223 header = 3;
9224 scrolld = NULL;
9225 if (s->selected_line > view->nlines - header) {
9226 offset = abs(view->nlines - s->selected_line - header);
9227 s->first_displayed_line += offset;
9228 s->selected_line -= offset;
9229 view->offset = offset;
9231 break;
9233 case TOG_VIEW_LOG: {
9234 struct tog_log_view_state *s = &view->state.log;
9235 scrolld = &log_scroll_down;
9236 header = view_is_parent_view(view) ? 3 : 2;
9237 selected = &s->selected;
9238 break;
9240 case TOG_VIEW_REF: {
9241 struct tog_ref_view_state *s = &view->state.ref;
9242 scrolld = &ref_scroll_down;
9243 header = 3;
9244 selected = &s->selected;
9245 break;
9247 case TOG_VIEW_TREE: {
9248 struct tog_tree_view_state *s = &view->state.tree;
9249 scrolld = &tree_scroll_down;
9250 header = 5;
9251 selected = &s->selected;
9252 break;
9254 default:
9255 selected = NULL;
9256 scrolld = NULL;
9257 header = 0;
9258 break;
9261 if (selected && *selected > view->nlines - header) {
9262 offset = abs(view->nlines - *selected - header);
9263 view->offset = offset;
9264 if (scrolld && offset) {
9265 err = scrolld(view, offset);
9266 *selected -= offset;
9270 return err;
9273 static void
9274 list_commands(FILE *fp)
9276 size_t i;
9278 fprintf(fp, "commands:");
9279 for (i = 0; i < nitems(tog_commands); i++) {
9280 const struct tog_cmd *cmd = &tog_commands[i];
9281 fprintf(fp, " %s", cmd->name);
9283 fputc('\n', fp);
9286 __dead static void
9287 usage(int hflag, int status)
9289 FILE *fp = (status == 0) ? stdout : stderr;
9291 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9292 getprogname());
9293 if (hflag) {
9294 fprintf(fp, "lazy usage: %s path\n", getprogname());
9295 list_commands(fp);
9297 exit(status);
9300 static char **
9301 make_argv(int argc, ...)
9303 va_list ap;
9304 char **argv;
9305 int i;
9307 va_start(ap, argc);
9309 argv = calloc(argc, sizeof(char *));
9310 if (argv == NULL)
9311 err(1, "calloc");
9312 for (i = 0; i < argc; i++) {
9313 argv[i] = strdup(va_arg(ap, char *));
9314 if (argv[i] == NULL)
9315 err(1, "strdup");
9318 va_end(ap);
9319 return argv;
9323 * Try to convert 'tog path' into a 'tog log path' command.
9324 * The user could simply have mistyped the command rather than knowingly
9325 * provided a path. So check whether argv[0] can in fact be resolved
9326 * to a path in the HEAD commit and print a special error if not.
9327 * This hack is for mpi@ <3
9329 static const struct got_error *
9330 tog_log_with_path(int argc, char *argv[])
9332 const struct got_error *error = NULL, *close_err;
9333 const struct tog_cmd *cmd = NULL;
9334 struct got_repository *repo = NULL;
9335 struct got_worktree *worktree = NULL;
9336 struct got_object_id *commit_id = NULL, *id = NULL;
9337 struct got_commit_object *commit = NULL;
9338 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9339 char *commit_id_str = NULL, **cmd_argv = NULL;
9340 int *pack_fds = NULL;
9342 cwd = getcwd(NULL, 0);
9343 if (cwd == NULL)
9344 return got_error_from_errno("getcwd");
9346 error = got_repo_pack_fds_open(&pack_fds);
9347 if (error != NULL)
9348 goto done;
9350 error = got_worktree_open(&worktree, cwd);
9351 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9352 goto done;
9354 if (worktree)
9355 repo_path = strdup(got_worktree_get_repo_path(worktree));
9356 else
9357 repo_path = strdup(cwd);
9358 if (repo_path == NULL) {
9359 error = got_error_from_errno("strdup");
9360 goto done;
9363 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9364 if (error != NULL)
9365 goto done;
9367 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9368 repo, worktree);
9369 if (error)
9370 goto done;
9372 error = tog_load_refs(repo, 0);
9373 if (error)
9374 goto done;
9375 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9376 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9377 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9378 if (error)
9379 goto done;
9381 if (worktree) {
9382 got_worktree_close(worktree);
9383 worktree = NULL;
9386 error = got_object_open_as_commit(&commit, repo, commit_id);
9387 if (error)
9388 goto done;
9390 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9391 if (error) {
9392 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9393 goto done;
9394 fprintf(stderr, "%s: '%s' is no known command or path\n",
9395 getprogname(), argv[0]);
9396 usage(1, 1);
9397 /* not reached */
9400 error = got_object_id_str(&commit_id_str, commit_id);
9401 if (error)
9402 goto done;
9404 cmd = &tog_commands[0]; /* log */
9405 argc = 4;
9406 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9407 error = cmd->cmd_main(argc, cmd_argv);
9408 done:
9409 if (repo) {
9410 close_err = got_repo_close(repo);
9411 if (error == NULL)
9412 error = close_err;
9414 if (commit)
9415 got_object_commit_close(commit);
9416 if (worktree)
9417 got_worktree_close(worktree);
9418 if (pack_fds) {
9419 const struct got_error *pack_err =
9420 got_repo_pack_fds_close(pack_fds);
9421 if (error == NULL)
9422 error = pack_err;
9424 free(id);
9425 free(commit_id_str);
9426 free(commit_id);
9427 free(cwd);
9428 free(repo_path);
9429 free(in_repo_path);
9430 if (cmd_argv) {
9431 int i;
9432 for (i = 0; i < argc; i++)
9433 free(cmd_argv[i]);
9434 free(cmd_argv);
9436 tog_free_refs();
9437 return error;
9440 int
9441 main(int argc, char *argv[])
9443 const struct got_error *error = NULL;
9444 const struct tog_cmd *cmd = NULL;
9445 int ch, hflag = 0, Vflag = 0;
9446 char **cmd_argv = NULL;
9447 static const struct option longopts[] = {
9448 { "version", no_argument, NULL, 'V' },
9449 { NULL, 0, NULL, 0}
9451 char *diff_algo_str = NULL;
9453 if (!isatty(STDIN_FILENO))
9454 errx(1, "standard input is not a tty");
9456 setlocale(LC_CTYPE, "");
9458 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9459 switch (ch) {
9460 case 'h':
9461 hflag = 1;
9462 break;
9463 case 'V':
9464 Vflag = 1;
9465 break;
9466 default:
9467 usage(hflag, 1);
9468 /* NOTREACHED */
9472 argc -= optind;
9473 argv += optind;
9474 optind = 1;
9475 optreset = 1;
9477 if (Vflag) {
9478 got_version_print_str();
9479 return 0;
9482 #ifndef PROFILE
9483 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9484 NULL) == -1)
9485 err(1, "pledge");
9486 #endif
9488 if (argc == 0) {
9489 if (hflag)
9490 usage(hflag, 0);
9491 /* Build an argument vector which runs a default command. */
9492 cmd = &tog_commands[0];
9493 argc = 1;
9494 cmd_argv = make_argv(argc, cmd->name);
9495 } else {
9496 size_t i;
9498 /* Did the user specify a command? */
9499 for (i = 0; i < nitems(tog_commands); i++) {
9500 if (strncmp(tog_commands[i].name, argv[0],
9501 strlen(argv[0])) == 0) {
9502 cmd = &tog_commands[i];
9503 break;
9508 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9509 if (diff_algo_str) {
9510 if (strcasecmp(diff_algo_str, "patience") == 0)
9511 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9512 if (strcasecmp(diff_algo_str, "myers") == 0)
9513 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9516 if (cmd == NULL) {
9517 if (argc != 1)
9518 usage(0, 1);
9519 /* No command specified; try log with a path */
9520 error = tog_log_with_path(argc, argv);
9521 } else {
9522 if (hflag)
9523 cmd->cmd_usage();
9524 else
9525 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9528 endwin();
9529 if (cmd_argv) {
9530 int i;
9531 for (i = 0; i < argc; i++)
9532 free(cmd_argv[i]);
9533 free(cmd_argv);
9536 if (error && error->code != GOT_ERR_CANCELLED &&
9537 error->code != GOT_ERR_EOF &&
9538 error->code != GOT_ERR_PRIVSEP_EXIT &&
9539 error->code != GOT_ERR_PRIVSEP_PIPE &&
9540 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9541 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9542 return 0;