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 <signal.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <getopt.h>
33 #include <string.h>
34 #include <err.h>
35 #include <unistd.h>
36 #include <limits.h>
37 #include <wchar.h>
38 #include <time.h>
39 #include <pthread.h>
40 #include <libgen.h>
41 #include <regex.h>
42 #include <sched.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_diff.h"
50 #include "got_opentemp.h"
51 #include "got_utf8.h"
52 #include "got_cancel.h"
53 #include "got_commit_graph.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_path.h"
57 #include "got_worktree.h"
59 #ifndef MIN
60 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
61 #endif
63 #ifndef MAX
64 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
65 #endif
67 #define CTRL(x) ((x) & 0x1f)
69 #ifndef nitems
70 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
71 #endif
73 struct tog_cmd {
74 const char *name;
75 const struct got_error *(*cmd_main)(int, char *[]);
76 void (*cmd_usage)(void);
77 };
79 __dead static void usage(int, int);
80 __dead static void usage_log(void);
81 __dead static void usage_diff(void);
82 __dead static void usage_blame(void);
83 __dead static void usage_tree(void);
84 __dead static void usage_ref(void);
86 static const struct got_error* cmd_log(int, char *[]);
87 static const struct got_error* cmd_diff(int, char *[]);
88 static const struct got_error* cmd_blame(int, char *[]);
89 static const struct got_error* cmd_tree(int, char *[]);
90 static const struct got_error* cmd_ref(int, char *[]);
92 static const struct tog_cmd tog_commands[] = {
93 { "log", cmd_log, usage_log },
94 { "diff", cmd_diff, usage_diff },
95 { "blame", cmd_blame, usage_blame },
96 { "tree", cmd_tree, usage_tree },
97 { "ref", cmd_ref, usage_ref },
98 };
100 enum tog_view_type {
101 TOG_VIEW_DIFF,
102 TOG_VIEW_LOG,
103 TOG_VIEW_BLAME,
104 TOG_VIEW_TREE,
105 TOG_VIEW_REF,
106 TOG_VIEW_HELP
107 };
109 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
110 enum tog_keymap_type {
111 TOG_KEYMAP_KEYS = -2,
112 TOG_KEYMAP_GLOBAL,
113 TOG_KEYMAP_DIFF,
114 TOG_KEYMAP_LOG,
115 TOG_KEYMAP_BLAME,
116 TOG_KEYMAP_TREE,
117 TOG_KEYMAP_REF,
118 TOG_KEYMAP_HELP
119 };
121 enum tog_view_mode {
122 TOG_VIEW_SPLIT_NONE,
123 TOG_VIEW_SPLIT_VERT,
124 TOG_VIEW_SPLIT_HRZN
125 };
127 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
129 #define TOG_EOF_STRING "(END)"
131 struct commit_queue_entry {
132 TAILQ_ENTRY(commit_queue_entry) entry;
133 struct got_object_id *id;
134 struct got_commit_object *commit;
135 int idx;
136 };
137 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
138 struct commit_queue {
139 int ncommits;
140 struct commit_queue_head head;
141 };
143 struct tog_color {
144 STAILQ_ENTRY(tog_color) entry;
145 regex_t regex;
146 short colorpair;
147 };
148 STAILQ_HEAD(tog_colors, tog_color);
150 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
151 static struct got_reflist_object_id_map *tog_refs_idmap;
152 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
154 static const struct got_error *
155 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
156 struct got_reference* re2)
158 const char *name1 = got_ref_get_name(re1);
159 const char *name2 = got_ref_get_name(re2);
160 int isbackup1, isbackup2;
162 /* Sort backup refs towards the bottom of the list. */
163 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
164 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
165 if (!isbackup1 && isbackup2) {
166 *cmp = -1;
167 return NULL;
168 } else if (isbackup1 && !isbackup2) {
169 *cmp = 1;
170 return NULL;
173 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
174 return NULL;
177 static const struct got_error *
178 tog_load_refs(struct got_repository *repo, int sort_by_date)
180 const struct got_error *err;
182 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
183 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
184 repo);
185 if (err)
186 return err;
188 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
189 repo);
192 static void
193 tog_free_refs(void)
195 if (tog_refs_idmap) {
196 got_reflist_object_id_map_free(tog_refs_idmap);
197 tog_refs_idmap = NULL;
199 got_ref_list_free(&tog_refs);
202 static const struct got_error *
203 add_color(struct tog_colors *colors, const char *pattern,
204 int idx, short color)
206 const struct got_error *err = NULL;
207 struct tog_color *tc;
208 int regerr = 0;
210 if (idx < 1 || idx > COLOR_PAIRS - 1)
211 return NULL;
213 init_pair(idx, color, -1);
215 tc = calloc(1, sizeof(*tc));
216 if (tc == NULL)
217 return got_error_from_errno("calloc");
218 regerr = regcomp(&tc->regex, pattern,
219 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
220 if (regerr) {
221 static char regerr_msg[512];
222 static char err_msg[512];
223 regerror(regerr, &tc->regex, regerr_msg,
224 sizeof(regerr_msg));
225 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
226 regerr_msg);
227 err = got_error_msg(GOT_ERR_REGEX, err_msg);
228 free(tc);
229 return err;
231 tc->colorpair = idx;
232 STAILQ_INSERT_HEAD(colors, tc, entry);
233 return NULL;
236 static void
237 free_colors(struct tog_colors *colors)
239 struct tog_color *tc;
241 while (!STAILQ_EMPTY(colors)) {
242 tc = STAILQ_FIRST(colors);
243 STAILQ_REMOVE_HEAD(colors, entry);
244 regfree(&tc->regex);
245 free(tc);
249 static struct tog_color *
250 get_color(struct tog_colors *colors, int colorpair)
252 struct tog_color *tc = NULL;
254 STAILQ_FOREACH(tc, colors, entry) {
255 if (tc->colorpair == colorpair)
256 return tc;
259 return NULL;
262 static int
263 default_color_value(const char *envvar)
265 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
266 return COLOR_MAGENTA;
267 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
268 return COLOR_CYAN;
269 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
270 return COLOR_YELLOW;
271 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
272 return COLOR_GREEN;
273 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
274 return COLOR_MAGENTA;
275 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
276 return COLOR_MAGENTA;
277 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
278 return COLOR_CYAN;
279 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
280 return COLOR_GREEN;
281 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
282 return COLOR_GREEN;
283 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
284 return COLOR_CYAN;
285 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
286 return COLOR_YELLOW;
287 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
288 return COLOR_GREEN;
289 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
290 return COLOR_MAGENTA;
291 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
292 return COLOR_YELLOW;
293 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
294 return COLOR_CYAN;
296 return -1;
299 static int
300 get_color_value(const char *envvar)
302 const char *val = getenv(envvar);
304 if (val == NULL)
305 return default_color_value(envvar);
307 if (strcasecmp(val, "black") == 0)
308 return COLOR_BLACK;
309 if (strcasecmp(val, "red") == 0)
310 return COLOR_RED;
311 if (strcasecmp(val, "green") == 0)
312 return COLOR_GREEN;
313 if (strcasecmp(val, "yellow") == 0)
314 return COLOR_YELLOW;
315 if (strcasecmp(val, "blue") == 0)
316 return COLOR_BLUE;
317 if (strcasecmp(val, "magenta") == 0)
318 return COLOR_MAGENTA;
319 if (strcasecmp(val, "cyan") == 0)
320 return COLOR_CYAN;
321 if (strcasecmp(val, "white") == 0)
322 return COLOR_WHITE;
323 if (strcasecmp(val, "default") == 0)
324 return -1;
326 return default_color_value(envvar);
329 struct tog_diff_view_state {
330 struct got_object_id *id1, *id2;
331 const char *label1, *label2;
332 FILE *f, *f1, *f2;
333 int fd1, fd2;
334 int lineno;
335 int first_displayed_line;
336 int last_displayed_line;
337 int eof;
338 int diff_context;
339 int ignore_whitespace;
340 int force_text_diff;
341 struct got_repository *repo;
342 struct got_diff_line *lines;
343 size_t nlines;
344 int matched_line;
345 int selected_line;
347 /* passed from log or blame view; may be NULL */
348 struct tog_view *parent_view;
349 };
351 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
352 static volatile sig_atomic_t tog_thread_error;
354 struct tog_log_thread_args {
355 pthread_cond_t need_commits;
356 pthread_cond_t commit_loaded;
357 int commits_needed;
358 int load_all;
359 struct got_commit_graph *graph;
360 struct commit_queue *real_commits;
361 const char *in_repo_path;
362 struct got_object_id *start_id;
363 struct got_repository *repo;
364 int *pack_fds;
365 int log_complete;
366 sig_atomic_t *quit;
367 struct commit_queue_entry **first_displayed_entry;
368 struct commit_queue_entry **selected_entry;
369 int *searching;
370 int *search_next_done;
371 regex_t *regex;
372 int *limiting;
373 int limit_match;
374 regex_t *limit_regex;
375 struct commit_queue *limit_commits;
376 };
378 struct tog_log_view_state {
379 struct commit_queue *commits;
380 struct commit_queue_entry *first_displayed_entry;
381 struct commit_queue_entry *last_displayed_entry;
382 struct commit_queue_entry *selected_entry;
383 struct commit_queue real_commits;
384 int selected;
385 char *in_repo_path;
386 char *head_ref_name;
387 int log_branches;
388 struct got_repository *repo;
389 struct got_object_id *start_id;
390 sig_atomic_t quit;
391 pthread_t thread;
392 struct tog_log_thread_args thread_args;
393 struct commit_queue_entry *matched_entry;
394 struct commit_queue_entry *search_entry;
395 struct tog_colors colors;
396 int use_committer;
397 int limit_view;
398 regex_t limit_regex;
399 struct commit_queue limit_commits;
400 };
402 #define TOG_COLOR_DIFF_MINUS 1
403 #define TOG_COLOR_DIFF_PLUS 2
404 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
405 #define TOG_COLOR_DIFF_META 4
406 #define TOG_COLOR_TREE_SUBMODULE 5
407 #define TOG_COLOR_TREE_SYMLINK 6
408 #define TOG_COLOR_TREE_DIRECTORY 7
409 #define TOG_COLOR_TREE_EXECUTABLE 8
410 #define TOG_COLOR_COMMIT 9
411 #define TOG_COLOR_AUTHOR 10
412 #define TOG_COLOR_DATE 11
413 #define TOG_COLOR_REFS_HEADS 12
414 #define TOG_COLOR_REFS_TAGS 13
415 #define TOG_COLOR_REFS_REMOTES 14
416 #define TOG_COLOR_REFS_BACKUP 15
418 struct tog_blame_cb_args {
419 struct tog_blame_line *lines; /* one per line */
420 int nlines;
422 struct tog_view *view;
423 struct got_object_id *commit_id;
424 int *quit;
425 };
427 struct tog_blame_thread_args {
428 const char *path;
429 struct got_repository *repo;
430 struct tog_blame_cb_args *cb_args;
431 int *complete;
432 got_cancel_cb cancel_cb;
433 void *cancel_arg;
434 };
436 struct tog_blame {
437 FILE *f;
438 off_t filesize;
439 struct tog_blame_line *lines;
440 int nlines;
441 off_t *line_offsets;
442 pthread_t thread;
443 struct tog_blame_thread_args thread_args;
444 struct tog_blame_cb_args cb_args;
445 const char *path;
446 int *pack_fds;
447 };
449 struct tog_blame_view_state {
450 int first_displayed_line;
451 int last_displayed_line;
452 int selected_line;
453 int last_diffed_line;
454 int blame_complete;
455 int eof;
456 int done;
457 struct got_object_id_queue blamed_commits;
458 struct got_object_qid *blamed_commit;
459 char *path;
460 struct got_repository *repo;
461 struct got_object_id *commit_id;
462 struct got_object_id *id_to_log;
463 struct tog_blame blame;
464 int matched_line;
465 struct tog_colors colors;
466 };
468 struct tog_parent_tree {
469 TAILQ_ENTRY(tog_parent_tree) entry;
470 struct got_tree_object *tree;
471 struct got_tree_entry *first_displayed_entry;
472 struct got_tree_entry *selected_entry;
473 int selected;
474 };
476 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
478 struct tog_tree_view_state {
479 char *tree_label;
480 struct got_object_id *commit_id;/* commit which this tree belongs to */
481 struct got_tree_object *root; /* the commit's root tree entry */
482 struct got_tree_object *tree; /* currently displayed (sub-)tree */
483 struct got_tree_entry *first_displayed_entry;
484 struct got_tree_entry *last_displayed_entry;
485 struct got_tree_entry *selected_entry;
486 int ndisplayed, selected, show_ids;
487 struct tog_parent_trees parents; /* parent trees of current sub-tree */
488 char *head_ref_name;
489 struct got_repository *repo;
490 struct got_tree_entry *matched_entry;
491 struct tog_colors colors;
492 };
494 struct tog_reflist_entry {
495 TAILQ_ENTRY(tog_reflist_entry) entry;
496 struct got_reference *ref;
497 int idx;
498 };
500 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
502 struct tog_ref_view_state {
503 struct tog_reflist_head refs;
504 struct tog_reflist_entry *first_displayed_entry;
505 struct tog_reflist_entry *last_displayed_entry;
506 struct tog_reflist_entry *selected_entry;
507 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
508 struct got_repository *repo;
509 struct tog_reflist_entry *matched_entry;
510 struct tog_colors colors;
511 };
513 struct tog_help_view_state {
514 FILE *f;
515 off_t *line_offsets;
516 size_t nlines;
517 int lineno;
518 int first_displayed_line;
519 int last_displayed_line;
520 int eof;
521 int matched_line;
522 int selected_line;
523 int all;
524 enum tog_keymap_type type;
525 };
527 #define GENERATE_HELP \
528 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
529 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
530 KEY_("k C-p Up", "Move cursor or page up one line"), \
531 KEY_("j C-n Down", "Move cursor or page down one line"), \
532 KEY_("C-b b PgUp", "Scroll the view up one page"), \
533 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
534 KEY_("C-u u", "Scroll the view up one half page"), \
535 KEY_("C-d d", "Scroll the view down one half page"), \
536 KEY_("g", "Go to line N (default: first line)"), \
537 KEY_("Home =", "Go to the first line"), \
538 KEY_("G", "Go to line N (default: last line)"), \
539 KEY_("End *", "Go to the last line"), \
540 KEY_("l Right", "Scroll the view right"), \
541 KEY_("h Left", "Scroll the view left"), \
542 KEY_("$", "Scroll view to the rightmost position"), \
543 KEY_("0", "Scroll view to the leftmost position"), \
544 KEY_("-", "Decrease size of the focussed split"), \
545 KEY_("+", "Increase size of the focussed split"), \
546 KEY_("Tab", "Switch focus between views"), \
547 KEY_("F", "Toggle fullscreen mode"), \
548 KEY_("/", "Open prompt to enter search term"), \
549 KEY_("n", "Find next line/token matching the current search term"), \
550 KEY_("N", "Find previous line/token matching the current search term"),\
551 KEY_("q", "Quit the focussed view; Quit help screen"), \
552 KEY_("Q", "Quit tog"), \
554 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
555 KEY_("< ,", "Move cursor up one commit"), \
556 KEY_("> .", "Move cursor down one commit"), \
557 KEY_("Enter", "Open diff view of the selected commit"), \
558 KEY_("B", "Reload the log view and toggle display of merged commits"), \
559 KEY_("R", "Open ref view of all repository references"), \
560 KEY_("T", "Display tree view of the repository from the selected" \
561 " commit"), \
562 KEY_("@", "Toggle between displaying author and committer name"), \
563 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
564 KEY_("C-g Backspace", "Cancel current search or log operation"), \
565 KEY_("C-l", "Reload the log view with new commits in the repository"), \
567 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
568 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
569 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
570 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
571 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
572 " data"), \
573 KEY_("(", "Go to the previous file in the diff"), \
574 KEY_(")", "Go to the next file in the diff"), \
575 KEY_("{", "Go to the previous hunk in the diff"), \
576 KEY_("}", "Go to the next hunk in the diff"), \
577 KEY_("[", "Decrease the number of context lines"), \
578 KEY_("]", "Increase the number of context lines"), \
579 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
581 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
582 KEY_("Enter", "Display diff view of the selected line's commit"), \
583 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
584 KEY_("L", "Open log view for the currently selected annotated line"), \
585 KEY_("C", "Reload view with the previously blamed commit"), \
586 KEY_("c", "Reload view with the version of the file found in the" \
587 " selected line's commit"), \
588 KEY_("p", "Reload view with the version of the file found in the" \
589 " selected line's parent commit"), \
591 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
592 KEY_("Enter", "Enter selected directory or open blame view of the" \
593 " selected file"), \
594 KEY_("L", "Open log view for the selected entry"), \
595 KEY_("R", "Open ref view of all repository references"), \
596 KEY_("i", "Show object IDs for all tree entries"), \
597 KEY_("Backspace", "Return to the parent directory"), \
599 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
600 KEY_("Enter", "Display log view of the selected reference"), \
601 KEY_("T", "Display tree view of the selected reference"), \
602 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
603 KEY_("m", "Toggle display of last modified date for each reference"), \
604 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
605 KEY_("C-l", "Reload view with all repository references")
607 struct tog_key_map {
608 const char *keys;
609 const char *info;
610 enum tog_keymap_type type;
611 };
613 /*
614 * We implement two types of views: parent views and child views.
616 * The 'Tab' key switches focus between a parent view and its child view.
617 * Child views are shown side-by-side to their parent view, provided
618 * there is enough screen estate.
620 * When a new view is opened from within a parent view, this new view
621 * becomes a child view of the parent view, replacing any existing child.
623 * When a new view is opened from within a child view, this new view
624 * becomes a parent view which will obscure the views below until the
625 * user quits the new parent view by typing 'q'.
627 * This list of views contains parent views only.
628 * Child views are only pointed to by their parent view.
629 */
630 TAILQ_HEAD(tog_view_list_head, tog_view);
632 struct tog_view {
633 TAILQ_ENTRY(tog_view) entry;
634 WINDOW *window;
635 PANEL *panel;
636 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
637 int resized_y, resized_x; /* begin_y/x based on user resizing */
638 int maxx, x; /* max column and current start column */
639 int lines, cols; /* copies of LINES and COLS */
640 int nscrolled, offset; /* lines scrolled and hsplit line offset */
641 int gline, hiline; /* navigate to and highlight this nG line */
642 int ch, count; /* current keymap and count prefix */
643 int resized; /* set when in a resize event */
644 int focussed; /* Only set on one parent or child view at a time. */
645 int dying;
646 struct tog_view *parent;
647 struct tog_view *child;
649 /*
650 * This flag is initially set on parent views when a new child view
651 * is created. It gets toggled when the 'Tab' key switches focus
652 * between parent and child.
653 * The flag indicates whether focus should be passed on to our child
654 * view if this parent view gets picked for focus after another parent
655 * view was closed. This prevents child views from losing focus in such
656 * situations.
657 */
658 int focus_child;
660 enum tog_view_mode mode;
661 /* type-specific state */
662 enum tog_view_type type;
663 union {
664 struct tog_diff_view_state diff;
665 struct tog_log_view_state log;
666 struct tog_blame_view_state blame;
667 struct tog_tree_view_state tree;
668 struct tog_ref_view_state ref;
669 struct tog_help_view_state help;
670 } state;
672 const struct got_error *(*show)(struct tog_view *);
673 const struct got_error *(*input)(struct tog_view **,
674 struct tog_view *, int);
675 const struct got_error *(*reset)(struct tog_view *);
676 const struct got_error *(*resize)(struct tog_view *, int);
677 const struct got_error *(*close)(struct tog_view *);
679 const struct got_error *(*search_start)(struct tog_view *);
680 const struct got_error *(*search_next)(struct tog_view *);
681 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
682 int **, int **, int **, int **);
683 int search_started;
684 int searching;
685 #define TOG_SEARCH_FORWARD 1
686 #define TOG_SEARCH_BACKWARD 2
687 int search_next_done;
688 #define TOG_SEARCH_HAVE_MORE 1
689 #define TOG_SEARCH_NO_MORE 2
690 #define TOG_SEARCH_HAVE_NONE 3
691 regex_t regex;
692 regmatch_t regmatch;
693 const char *action;
694 };
696 static const struct got_error *open_diff_view(struct tog_view *,
697 struct got_object_id *, struct got_object_id *,
698 const char *, const char *, int, int, int, struct tog_view *,
699 struct got_repository *);
700 static const struct got_error *show_diff_view(struct tog_view *);
701 static const struct got_error *input_diff_view(struct tog_view **,
702 struct tog_view *, int);
703 static const struct got_error *reset_diff_view(struct tog_view *);
704 static const struct got_error* close_diff_view(struct tog_view *);
705 static const struct got_error *search_start_diff_view(struct tog_view *);
706 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
707 size_t *, int **, int **, int **, int **);
708 static const struct got_error *search_next_view_match(struct tog_view *);
710 static const struct got_error *open_log_view(struct tog_view *,
711 struct got_object_id *, struct got_repository *,
712 const char *, const char *, int);
713 static const struct got_error * show_log_view(struct tog_view *);
714 static const struct got_error *input_log_view(struct tog_view **,
715 struct tog_view *, int);
716 static const struct got_error *resize_log_view(struct tog_view *, int);
717 static const struct got_error *close_log_view(struct tog_view *);
718 static const struct got_error *search_start_log_view(struct tog_view *);
719 static const struct got_error *search_next_log_view(struct tog_view *);
721 static const struct got_error *open_blame_view(struct tog_view *, char *,
722 struct got_object_id *, struct got_repository *);
723 static const struct got_error *show_blame_view(struct tog_view *);
724 static const struct got_error *input_blame_view(struct tog_view **,
725 struct tog_view *, int);
726 static const struct got_error *reset_blame_view(struct tog_view *);
727 static const struct got_error *close_blame_view(struct tog_view *);
728 static const struct got_error *search_start_blame_view(struct tog_view *);
729 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
730 size_t *, int **, int **, int **, int **);
732 static const struct got_error *open_tree_view(struct tog_view *,
733 struct got_object_id *, const char *, struct got_repository *);
734 static const struct got_error *show_tree_view(struct tog_view *);
735 static const struct got_error *input_tree_view(struct tog_view **,
736 struct tog_view *, int);
737 static const struct got_error *close_tree_view(struct tog_view *);
738 static const struct got_error *search_start_tree_view(struct tog_view *);
739 static const struct got_error *search_next_tree_view(struct tog_view *);
741 static const struct got_error *open_ref_view(struct tog_view *,
742 struct got_repository *);
743 static const struct got_error *show_ref_view(struct tog_view *);
744 static const struct got_error *input_ref_view(struct tog_view **,
745 struct tog_view *, int);
746 static const struct got_error *close_ref_view(struct tog_view *);
747 static const struct got_error *search_start_ref_view(struct tog_view *);
748 static const struct got_error *search_next_ref_view(struct tog_view *);
750 static const struct got_error *open_help_view(struct tog_view *,
751 struct tog_view *);
752 static const struct got_error *show_help_view(struct tog_view *);
753 static const struct got_error *input_help_view(struct tog_view **,
754 struct tog_view *, int);
755 static const struct got_error *reset_help_view(struct tog_view *);
756 static const struct got_error* close_help_view(struct tog_view *);
757 static const struct got_error *search_start_help_view(struct tog_view *);
758 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
759 size_t *, int **, int **, int **, int **);
761 static volatile sig_atomic_t tog_sigwinch_received;
762 static volatile sig_atomic_t tog_sigpipe_received;
763 static volatile sig_atomic_t tog_sigcont_received;
764 static volatile sig_atomic_t tog_sigint_received;
765 static volatile sig_atomic_t tog_sigterm_received;
767 static void
768 tog_sigwinch(int signo)
770 tog_sigwinch_received = 1;
773 static void
774 tog_sigpipe(int signo)
776 tog_sigpipe_received = 1;
779 static void
780 tog_sigcont(int signo)
782 tog_sigcont_received = 1;
785 static void
786 tog_sigint(int signo)
788 tog_sigint_received = 1;
791 static void
792 tog_sigterm(int signo)
794 tog_sigterm_received = 1;
797 static int
798 tog_fatal_signal_received(void)
800 return (tog_sigpipe_received ||
801 tog_sigint_received || tog_sigterm_received);
804 static const struct got_error *
805 view_close(struct tog_view *view)
807 const struct got_error *err = NULL, *child_err = NULL;
809 if (view->child) {
810 child_err = view_close(view->child);
811 view->child = NULL;
813 if (view->close)
814 err = view->close(view);
815 if (view->panel)
816 del_panel(view->panel);
817 if (view->window)
818 delwin(view->window);
819 free(view);
820 return err ? err : child_err;
823 static struct tog_view *
824 view_open(int nlines, int ncols, int begin_y, int begin_x,
825 enum tog_view_type type)
827 struct tog_view *view = calloc(1, sizeof(*view));
829 if (view == NULL)
830 return NULL;
832 view->type = type;
833 view->lines = LINES;
834 view->cols = COLS;
835 view->nlines = nlines ? nlines : LINES - begin_y;
836 view->ncols = ncols ? ncols : COLS - begin_x;
837 view->begin_y = begin_y;
838 view->begin_x = begin_x;
839 view->window = newwin(nlines, ncols, begin_y, begin_x);
840 if (view->window == NULL) {
841 view_close(view);
842 return NULL;
844 view->panel = new_panel(view->window);
845 if (view->panel == NULL ||
846 set_panel_userptr(view->panel, view) != OK) {
847 view_close(view);
848 return NULL;
851 keypad(view->window, TRUE);
852 return view;
855 static int
856 view_split_begin_x(int begin_x)
858 if (begin_x > 0 || COLS < 120)
859 return 0;
860 return (COLS - MAX(COLS / 2, 80));
863 /* XXX Stub till we decide what to do. */
864 static int
865 view_split_begin_y(int lines)
867 return lines * HSPLIT_SCALE;
870 static const struct got_error *view_resize(struct tog_view *);
872 static const struct got_error *
873 view_splitscreen(struct tog_view *view)
875 const struct got_error *err = NULL;
877 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
878 if (view->resized_y && view->resized_y < view->lines)
879 view->begin_y = view->resized_y;
880 else
881 view->begin_y = view_split_begin_y(view->nlines);
882 view->begin_x = 0;
883 } else if (!view->resized) {
884 if (view->resized_x && view->resized_x < view->cols - 1 &&
885 view->cols > 119)
886 view->begin_x = view->resized_x;
887 else
888 view->begin_x = view_split_begin_x(0);
889 view->begin_y = 0;
891 view->nlines = LINES - view->begin_y;
892 view->ncols = COLS - view->begin_x;
893 view->lines = LINES;
894 view->cols = COLS;
895 err = view_resize(view);
896 if (err)
897 return err;
899 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
900 view->parent->nlines = view->begin_y;
902 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
903 return got_error_from_errno("mvwin");
905 return NULL;
908 static const struct got_error *
909 view_fullscreen(struct tog_view *view)
911 const struct got_error *err = NULL;
913 view->begin_x = 0;
914 view->begin_y = view->resized ? view->begin_y : 0;
915 view->nlines = view->resized ? view->nlines : LINES;
916 view->ncols = COLS;
917 view->lines = LINES;
918 view->cols = COLS;
919 err = view_resize(view);
920 if (err)
921 return err;
923 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
924 return got_error_from_errno("mvwin");
926 return NULL;
929 static int
930 view_is_parent_view(struct tog_view *view)
932 return view->parent == NULL;
935 static int
936 view_is_splitscreen(struct tog_view *view)
938 return view->begin_x > 0 || view->begin_y > 0;
941 static int
942 view_is_fullscreen(struct tog_view *view)
944 return view->nlines == LINES && view->ncols == COLS;
947 static int
948 view_is_hsplit_top(struct tog_view *view)
950 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
951 view_is_splitscreen(view->child);
954 static void
955 view_border(struct tog_view *view)
957 PANEL *panel;
958 const struct tog_view *view_above;
960 if (view->parent)
961 return view_border(view->parent);
963 panel = panel_above(view->panel);
964 if (panel == NULL)
965 return;
967 view_above = panel_userptr(panel);
968 if (view->mode == TOG_VIEW_SPLIT_HRZN)
969 mvwhline(view->window, view_above->begin_y - 1,
970 view->begin_x, got_locale_is_utf8() ?
971 ACS_HLINE : '-', view->ncols);
972 else
973 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
974 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
977 static const struct got_error *view_init_hsplit(struct tog_view *, int);
978 static const struct got_error *request_log_commits(struct tog_view *);
979 static const struct got_error *offset_selection_down(struct tog_view *);
980 static void offset_selection_up(struct tog_view *);
981 static void view_get_split(struct tog_view *, int *, int *);
983 static const struct got_error *
984 view_resize(struct tog_view *view)
986 const struct got_error *err = NULL;
987 int dif, nlines, ncols;
989 dif = LINES - view->lines; /* line difference */
991 if (view->lines > LINES)
992 nlines = view->nlines - (view->lines - LINES);
993 else
994 nlines = view->nlines + (LINES - view->lines);
995 if (view->cols > COLS)
996 ncols = view->ncols - (view->cols - COLS);
997 else
998 ncols = view->ncols + (COLS - view->cols);
1000 if (view->child) {
1001 int hs = view->child->begin_y;
1003 if (!view_is_fullscreen(view))
1004 view->child->begin_x = view_split_begin_x(view->begin_x);
1005 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1006 view->child->begin_x == 0) {
1007 ncols = COLS;
1009 view_fullscreen(view->child);
1010 if (view->child->focussed)
1011 show_panel(view->child->panel);
1012 else
1013 show_panel(view->panel);
1014 } else {
1015 ncols = view->child->begin_x;
1017 view_splitscreen(view->child);
1018 show_panel(view->child->panel);
1021 * XXX This is ugly and needs to be moved into the above
1022 * logic but "works" for now and my attempts at moving it
1023 * break either 'tab' or 'F' key maps in horizontal splits.
1025 if (hs) {
1026 err = view_splitscreen(view->child);
1027 if (err)
1028 return err;
1029 if (dif < 0) { /* top split decreased */
1030 err = offset_selection_down(view);
1031 if (err)
1032 return err;
1034 view_border(view);
1035 update_panels();
1036 doupdate();
1037 show_panel(view->child->panel);
1038 nlines = view->nlines;
1040 } else if (view->parent == NULL)
1041 ncols = COLS;
1043 if (view->resize && dif > 0) {
1044 err = view->resize(view, dif);
1045 if (err)
1046 return err;
1049 if (wresize(view->window, nlines, ncols) == ERR)
1050 return got_error_from_errno("wresize");
1051 if (replace_panel(view->panel, view->window) == ERR)
1052 return got_error_from_errno("replace_panel");
1053 wclear(view->window);
1055 view->nlines = nlines;
1056 view->ncols = ncols;
1057 view->lines = LINES;
1058 view->cols = COLS;
1060 return NULL;
1063 static const struct got_error *
1064 resize_log_view(struct tog_view *view, int increase)
1066 struct tog_log_view_state *s = &view->state.log;
1067 const struct got_error *err = NULL;
1068 int n = 0;
1070 if (s->selected_entry)
1071 n = s->selected_entry->idx + view->lines - s->selected;
1074 * Request commits to account for the increased
1075 * height so we have enough to populate the view.
1077 if (s->commits->ncommits < n) {
1078 view->nscrolled = n - s->commits->ncommits + increase + 1;
1079 err = request_log_commits(view);
1082 return err;
1085 static void
1086 view_adjust_offset(struct tog_view *view, int n)
1088 if (n == 0)
1089 return;
1091 if (view->parent && view->parent->offset) {
1092 if (view->parent->offset + n >= 0)
1093 view->parent->offset += n;
1094 else
1095 view->parent->offset = 0;
1096 } else if (view->offset) {
1097 if (view->offset - n >= 0)
1098 view->offset -= n;
1099 else
1100 view->offset = 0;
1104 static const struct got_error *
1105 view_resize_split(struct tog_view *view, int resize)
1107 const struct got_error *err = NULL;
1108 struct tog_view *v = NULL;
1110 if (view->parent)
1111 v = view->parent;
1112 else
1113 v = view;
1115 if (!v->child || !view_is_splitscreen(v->child))
1116 return NULL;
1118 v->resized = v->child->resized = resize; /* lock for resize event */
1120 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1121 if (v->child->resized_y)
1122 v->child->begin_y = v->child->resized_y;
1123 if (view->parent)
1124 v->child->begin_y -= resize;
1125 else
1126 v->child->begin_y += resize;
1127 if (v->child->begin_y < 3) {
1128 view->count = 0;
1129 v->child->begin_y = 3;
1130 } else if (v->child->begin_y > LINES - 1) {
1131 view->count = 0;
1132 v->child->begin_y = LINES - 1;
1134 v->ncols = COLS;
1135 v->child->ncols = COLS;
1136 view_adjust_offset(view, resize);
1137 err = view_init_hsplit(v, v->child->begin_y);
1138 if (err)
1139 return err;
1140 v->child->resized_y = v->child->begin_y;
1141 } else {
1142 if (v->child->resized_x)
1143 v->child->begin_x = v->child->resized_x;
1144 if (view->parent)
1145 v->child->begin_x -= resize;
1146 else
1147 v->child->begin_x += resize;
1148 if (v->child->begin_x < 11) {
1149 view->count = 0;
1150 v->child->begin_x = 11;
1151 } else if (v->child->begin_x > COLS - 1) {
1152 view->count = 0;
1153 v->child->begin_x = COLS - 1;
1155 v->child->resized_x = v->child->begin_x;
1158 v->child->mode = v->mode;
1159 v->child->nlines = v->lines - v->child->begin_y;
1160 v->child->ncols = v->cols - v->child->begin_x;
1161 v->focus_child = 1;
1163 err = view_fullscreen(v);
1164 if (err)
1165 return err;
1166 err = view_splitscreen(v->child);
1167 if (err)
1168 return err;
1170 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1171 err = offset_selection_down(v->child);
1172 if (err)
1173 return err;
1176 if (v->resize)
1177 err = v->resize(v, 0);
1178 else if (v->child->resize)
1179 err = v->child->resize(v->child, 0);
1181 v->resized = v->child->resized = 0;
1183 return err;
1186 static void
1187 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1189 struct tog_view *v = src->child ? src->child : src;
1191 dst->resized_x = v->resized_x;
1192 dst->resized_y = v->resized_y;
1195 static const struct got_error *
1196 view_close_child(struct tog_view *view)
1198 const struct got_error *err = NULL;
1200 if (view->child == NULL)
1201 return NULL;
1203 err = view_close(view->child);
1204 view->child = NULL;
1205 return err;
1208 static const struct got_error *
1209 view_set_child(struct tog_view *view, struct tog_view *child)
1211 const struct got_error *err = NULL;
1213 view->child = child;
1214 child->parent = view;
1216 err = view_resize(view);
1217 if (err)
1218 return err;
1220 if (view->child->resized_x || view->child->resized_y)
1221 err = view_resize_split(view, 0);
1223 return err;
1226 static const struct got_error *view_dispatch_request(struct tog_view **,
1227 struct tog_view *, enum tog_view_type, int, int);
1229 static const struct got_error *
1230 view_request_new(struct tog_view **requested, struct tog_view *view,
1231 enum tog_view_type request)
1233 struct tog_view *new_view = NULL;
1234 const struct got_error *err;
1235 int y = 0, x = 0;
1237 *requested = NULL;
1239 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1240 view_get_split(view, &y, &x);
1242 err = view_dispatch_request(&new_view, view, request, y, x);
1243 if (err)
1244 return err;
1246 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1247 request != TOG_VIEW_HELP) {
1248 err = view_init_hsplit(view, y);
1249 if (err)
1250 return err;
1253 view->focussed = 0;
1254 new_view->focussed = 1;
1255 new_view->mode = view->mode;
1256 new_view->nlines = request == TOG_VIEW_HELP ?
1257 view->lines : view->lines - y;
1259 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1260 view_transfer_size(new_view, view);
1261 err = view_close_child(view);
1262 if (err)
1263 return err;
1264 err = view_set_child(view, new_view);
1265 if (err)
1266 return err;
1267 view->focus_child = 1;
1268 } else
1269 *requested = new_view;
1271 return NULL;
1274 static void
1275 tog_resizeterm(void)
1277 int cols, lines;
1278 struct winsize size;
1280 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1281 cols = 80; /* Default */
1282 lines = 24;
1283 } else {
1284 cols = size.ws_col;
1285 lines = size.ws_row;
1287 resize_term(lines, cols);
1290 static const struct got_error *
1291 view_search_start(struct tog_view *view)
1293 const struct got_error *err = NULL;
1294 struct tog_view *v = view;
1295 char pattern[1024];
1296 int ret;
1298 if (view->search_started) {
1299 regfree(&view->regex);
1300 view->searching = 0;
1301 memset(&view->regmatch, 0, sizeof(view->regmatch));
1303 view->search_started = 0;
1305 if (view->nlines < 1)
1306 return NULL;
1308 if (view_is_hsplit_top(view))
1309 v = view->child;
1310 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1311 v = view->parent;
1313 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1314 wclrtoeol(v->window);
1316 nodelay(v->window, FALSE); /* block for search term input */
1317 nocbreak();
1318 echo();
1319 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1320 wrefresh(v->window);
1321 cbreak();
1322 noecho();
1323 nodelay(v->window, TRUE);
1324 if (ret == ERR)
1325 return NULL;
1327 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1328 err = view->search_start(view);
1329 if (err) {
1330 regfree(&view->regex);
1331 return err;
1333 view->search_started = 1;
1334 view->searching = TOG_SEARCH_FORWARD;
1335 view->search_next_done = 0;
1336 view->search_next(view);
1339 return NULL;
1342 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1343 static const struct got_error *
1344 switch_split(struct tog_view *view)
1346 const struct got_error *err = NULL;
1347 struct tog_view *v = NULL;
1349 if (view->parent)
1350 v = view->parent;
1351 else
1352 v = view;
1354 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1355 v->mode = TOG_VIEW_SPLIT_VERT;
1356 else
1357 v->mode = TOG_VIEW_SPLIT_HRZN;
1359 if (!v->child)
1360 return NULL;
1361 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1362 v->mode = TOG_VIEW_SPLIT_NONE;
1364 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1365 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1366 v->child->begin_y = v->child->resized_y;
1367 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1368 v->child->begin_x = v->child->resized_x;
1371 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1372 v->ncols = COLS;
1373 v->child->ncols = COLS;
1374 v->child->nscrolled = LINES - v->child->nlines;
1376 err = view_init_hsplit(v, v->child->begin_y);
1377 if (err)
1378 return err;
1380 v->child->mode = v->mode;
1381 v->child->nlines = v->lines - v->child->begin_y;
1382 v->focus_child = 1;
1384 err = view_fullscreen(v);
1385 if (err)
1386 return err;
1387 err = view_splitscreen(v->child);
1388 if (err)
1389 return err;
1391 if (v->mode == TOG_VIEW_SPLIT_NONE)
1392 v->mode = TOG_VIEW_SPLIT_VERT;
1393 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1394 err = offset_selection_down(v);
1395 if (err)
1396 return err;
1397 err = offset_selection_down(v->child);
1398 if (err)
1399 return err;
1400 } else {
1401 offset_selection_up(v);
1402 offset_selection_up(v->child);
1404 if (v->resize)
1405 err = v->resize(v, 0);
1406 else if (v->child->resize)
1407 err = v->child->resize(v->child, 0);
1409 return err;
1413 * Compute view->count from numeric input. Assign total to view->count and
1414 * return first non-numeric key entered.
1416 static int
1417 get_compound_key(struct tog_view *view, int c)
1419 struct tog_view *v = view;
1420 int x, n = 0;
1422 if (view_is_hsplit_top(view))
1423 v = view->child;
1424 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1425 v = view->parent;
1427 view->count = 0;
1428 cbreak(); /* block for input */
1429 nodelay(view->window, FALSE);
1430 wmove(v->window, v->nlines - 1, 0);
1431 wclrtoeol(v->window);
1432 waddch(v->window, ':');
1434 do {
1435 x = getcurx(v->window);
1436 if (x != ERR && x < view->ncols) {
1437 waddch(v->window, c);
1438 wrefresh(v->window);
1442 * Don't overflow. Max valid request should be the greatest
1443 * between the longest and total lines; cap at 10 million.
1445 if (n >= 9999999)
1446 n = 9999999;
1447 else
1448 n = n * 10 + (c - '0');
1449 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1451 if (c == 'G' || c == 'g') { /* nG key map */
1452 view->gline = view->hiline = n;
1453 n = 0;
1454 c = 0;
1457 /* Massage excessive or inapplicable values at the input handler. */
1458 view->count = n;
1460 return c;
1463 static void
1464 action_report(struct tog_view *view)
1466 struct tog_view *v = view;
1468 if (view_is_hsplit_top(view))
1469 v = view->child;
1470 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1471 v = view->parent;
1473 wmove(v->window, v->nlines - 1, 0);
1474 wclrtoeol(v->window);
1475 wprintw(v->window, ":%s", view->action);
1476 wrefresh(v->window);
1479 * Clear action status report. Only clear in blame view
1480 * once annotating is complete, otherwise it's too fast.
1482 if (view->type == TOG_VIEW_BLAME) {
1483 if (view->state.blame.blame_complete)
1484 view->action = NULL;
1485 } else
1486 view->action = NULL;
1489 static const struct got_error *
1490 view_input(struct tog_view **new, int *done, struct tog_view *view,
1491 struct tog_view_list_head *views)
1493 const struct got_error *err = NULL;
1494 struct tog_view *v;
1495 int ch, errcode;
1497 *new = NULL;
1499 if (view->action)
1500 action_report(view);
1502 /* Clear "no matches" indicator. */
1503 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1504 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1505 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1506 view->count = 0;
1509 if (view->searching && !view->search_next_done) {
1510 errcode = pthread_mutex_unlock(&tog_mutex);
1511 if (errcode)
1512 return got_error_set_errno(errcode,
1513 "pthread_mutex_unlock");
1514 sched_yield();
1515 errcode = pthread_mutex_lock(&tog_mutex);
1516 if (errcode)
1517 return got_error_set_errno(errcode,
1518 "pthread_mutex_lock");
1519 view->search_next(view);
1520 return NULL;
1523 /* Allow threads to make progress while we are waiting for input. */
1524 errcode = pthread_mutex_unlock(&tog_mutex);
1525 if (errcode)
1526 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1527 /* If we have an unfinished count, let C-g or backspace abort. */
1528 if (view->count && --view->count) {
1529 cbreak();
1530 nodelay(view->window, TRUE);
1531 ch = wgetch(view->window);
1532 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1533 view->count = 0;
1534 else
1535 ch = view->ch;
1536 } else {
1537 ch = wgetch(view->window);
1538 if (ch >= '1' && ch <= '9')
1539 view->ch = ch = get_compound_key(view, ch);
1541 if (view->hiline && ch != ERR && ch != 0)
1542 view->hiline = 0; /* key pressed, clear line highlight */
1543 nodelay(view->window, TRUE);
1544 errcode = pthread_mutex_lock(&tog_mutex);
1545 if (errcode)
1546 return got_error_set_errno(errcode, "pthread_mutex_lock");
1548 if (tog_sigwinch_received || tog_sigcont_received) {
1549 tog_resizeterm();
1550 tog_sigwinch_received = 0;
1551 tog_sigcont_received = 0;
1552 TAILQ_FOREACH(v, views, entry) {
1553 err = view_resize(v);
1554 if (err)
1555 return err;
1556 err = v->input(new, v, KEY_RESIZE);
1557 if (err)
1558 return err;
1559 if (v->child) {
1560 err = view_resize(v->child);
1561 if (err)
1562 return err;
1563 err = v->child->input(new, v->child,
1564 KEY_RESIZE);
1565 if (err)
1566 return err;
1567 if (v->child->resized_x || v->child->resized_y) {
1568 err = view_resize_split(v, 0);
1569 if (err)
1570 return err;
1576 switch (ch) {
1577 case '?':
1578 case 'H':
1579 case KEY_F(1):
1580 if (view->type == TOG_VIEW_HELP)
1581 err = view->reset(view);
1582 else
1583 err = view_request_new(new, view, TOG_VIEW_HELP);
1584 break;
1585 case '\t':
1586 view->count = 0;
1587 if (view->child) {
1588 view->focussed = 0;
1589 view->child->focussed = 1;
1590 view->focus_child = 1;
1591 } else if (view->parent) {
1592 view->focussed = 0;
1593 view->parent->focussed = 1;
1594 view->parent->focus_child = 0;
1595 if (!view_is_splitscreen(view)) {
1596 if (view->parent->resize) {
1597 err = view->parent->resize(view->parent,
1598 0);
1599 if (err)
1600 return err;
1602 offset_selection_up(view->parent);
1603 err = view_fullscreen(view->parent);
1604 if (err)
1605 return err;
1608 break;
1609 case 'q':
1610 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1611 if (view->parent->resize) {
1612 /* might need more commits to fill fullscreen */
1613 err = view->parent->resize(view->parent, 0);
1614 if (err)
1615 break;
1617 offset_selection_up(view->parent);
1619 err = view->input(new, view, ch);
1620 view->dying = 1;
1621 break;
1622 case 'Q':
1623 *done = 1;
1624 break;
1625 case 'F':
1626 view->count = 0;
1627 if (view_is_parent_view(view)) {
1628 if (view->child == NULL)
1629 break;
1630 if (view_is_splitscreen(view->child)) {
1631 view->focussed = 0;
1632 view->child->focussed = 1;
1633 err = view_fullscreen(view->child);
1634 } else {
1635 err = view_splitscreen(view->child);
1636 if (!err)
1637 err = view_resize_split(view, 0);
1639 if (err)
1640 break;
1641 err = view->child->input(new, view->child,
1642 KEY_RESIZE);
1643 } else {
1644 if (view_is_splitscreen(view)) {
1645 view->parent->focussed = 0;
1646 view->focussed = 1;
1647 err = view_fullscreen(view);
1648 } else {
1649 err = view_splitscreen(view);
1650 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1651 err = view_resize(view->parent);
1652 if (!err)
1653 err = view_resize_split(view, 0);
1655 if (err)
1656 break;
1657 err = view->input(new, view, KEY_RESIZE);
1659 if (err)
1660 break;
1661 if (view->resize) {
1662 err = view->resize(view, 0);
1663 if (err)
1664 break;
1666 if (view->parent)
1667 err = offset_selection_down(view->parent);
1668 if (!err)
1669 err = offset_selection_down(view);
1670 break;
1671 case 'S':
1672 view->count = 0;
1673 err = switch_split(view);
1674 break;
1675 case '-':
1676 err = view_resize_split(view, -1);
1677 break;
1678 case '+':
1679 err = view_resize_split(view, 1);
1680 break;
1681 case KEY_RESIZE:
1682 break;
1683 case '/':
1684 view->count = 0;
1685 if (view->search_start)
1686 view_search_start(view);
1687 else
1688 err = view->input(new, view, ch);
1689 break;
1690 case 'N':
1691 case 'n':
1692 if (view->search_started && view->search_next) {
1693 view->searching = (ch == 'n' ?
1694 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1695 view->search_next_done = 0;
1696 view->search_next(view);
1697 } else
1698 err = view->input(new, view, ch);
1699 break;
1700 case 'A':
1701 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1702 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1703 view->action = "Patience diff algorithm";
1704 } else {
1705 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1706 view->action = "Myers diff algorithm";
1708 TAILQ_FOREACH(v, views, entry) {
1709 if (v->reset) {
1710 err = v->reset(v);
1711 if (err)
1712 return err;
1714 if (v->child && v->child->reset) {
1715 err = v->child->reset(v->child);
1716 if (err)
1717 return err;
1720 break;
1721 default:
1722 err = view->input(new, view, ch);
1723 break;
1726 return err;
1729 static int
1730 view_needs_focus_indication(struct tog_view *view)
1732 if (view_is_parent_view(view)) {
1733 if (view->child == NULL || view->child->focussed)
1734 return 0;
1735 if (!view_is_splitscreen(view->child))
1736 return 0;
1737 } else if (!view_is_splitscreen(view))
1738 return 0;
1740 return view->focussed;
1743 static const struct got_error *
1744 view_loop(struct tog_view *view)
1746 const struct got_error *err = NULL;
1747 struct tog_view_list_head views;
1748 struct tog_view *new_view;
1749 char *mode;
1750 int fast_refresh = 10;
1751 int done = 0, errcode;
1753 mode = getenv("TOG_VIEW_SPLIT_MODE");
1754 if (!mode || !(*mode == 'h' || *mode == 'H'))
1755 view->mode = TOG_VIEW_SPLIT_VERT;
1756 else
1757 view->mode = TOG_VIEW_SPLIT_HRZN;
1759 errcode = pthread_mutex_lock(&tog_mutex);
1760 if (errcode)
1761 return got_error_set_errno(errcode, "pthread_mutex_lock");
1763 TAILQ_INIT(&views);
1764 TAILQ_INSERT_HEAD(&views, view, entry);
1766 view->focussed = 1;
1767 err = view->show(view);
1768 if (err)
1769 return err;
1770 update_panels();
1771 doupdate();
1772 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1773 !tog_fatal_signal_received()) {
1774 /* Refresh fast during initialization, then become slower. */
1775 if (fast_refresh && --fast_refresh == 0)
1776 halfdelay(10); /* switch to once per second */
1778 err = view_input(&new_view, &done, view, &views);
1779 if (err)
1780 break;
1782 if (view->dying && view == TAILQ_FIRST(&views) &&
1783 TAILQ_NEXT(view, entry) == NULL)
1784 done = 1;
1785 if (done) {
1786 struct tog_view *v;
1789 * When we quit, scroll the screen up a single line
1790 * so we don't lose any information.
1792 TAILQ_FOREACH(v, &views, entry) {
1793 wmove(v->window, 0, 0);
1794 wdeleteln(v->window);
1795 wnoutrefresh(v->window);
1796 if (v->child && !view_is_fullscreen(v)) {
1797 wmove(v->child->window, 0, 0);
1798 wdeleteln(v->child->window);
1799 wnoutrefresh(v->child->window);
1802 doupdate();
1805 if (view->dying) {
1806 struct tog_view *v, *prev = NULL;
1808 if (view_is_parent_view(view))
1809 prev = TAILQ_PREV(view, tog_view_list_head,
1810 entry);
1811 else if (view->parent)
1812 prev = view->parent;
1814 if (view->parent) {
1815 view->parent->child = NULL;
1816 view->parent->focus_child = 0;
1817 /* Restore fullscreen line height. */
1818 view->parent->nlines = view->parent->lines;
1819 err = view_resize(view->parent);
1820 if (err)
1821 break;
1822 /* Make resized splits persist. */
1823 view_transfer_size(view->parent, view);
1824 } else
1825 TAILQ_REMOVE(&views, view, entry);
1827 err = view_close(view);
1828 if (err)
1829 goto done;
1831 view = NULL;
1832 TAILQ_FOREACH(v, &views, entry) {
1833 if (v->focussed)
1834 break;
1836 if (view == NULL && new_view == NULL) {
1837 /* No view has focus. Try to pick one. */
1838 if (prev)
1839 view = prev;
1840 else if (!TAILQ_EMPTY(&views)) {
1841 view = TAILQ_LAST(&views,
1842 tog_view_list_head);
1844 if (view) {
1845 if (view->focus_child) {
1846 view->child->focussed = 1;
1847 view = view->child;
1848 } else
1849 view->focussed = 1;
1853 if (new_view) {
1854 struct tog_view *v, *t;
1855 /* Only allow one parent view per type. */
1856 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1857 if (v->type != new_view->type)
1858 continue;
1859 TAILQ_REMOVE(&views, v, entry);
1860 err = view_close(v);
1861 if (err)
1862 goto done;
1863 break;
1865 TAILQ_INSERT_TAIL(&views, new_view, entry);
1866 view = new_view;
1868 if (view && !done) {
1869 if (view_is_parent_view(view)) {
1870 if (view->child && view->child->focussed)
1871 view = view->child;
1872 } else {
1873 if (view->parent && view->parent->focussed)
1874 view = view->parent;
1876 show_panel(view->panel);
1877 if (view->child && view_is_splitscreen(view->child))
1878 show_panel(view->child->panel);
1879 if (view->parent && view_is_splitscreen(view)) {
1880 err = view->parent->show(view->parent);
1881 if (err)
1882 goto done;
1884 err = view->show(view);
1885 if (err)
1886 goto done;
1887 if (view->child) {
1888 err = view->child->show(view->child);
1889 if (err)
1890 goto done;
1892 update_panels();
1893 doupdate();
1896 done:
1897 while (!TAILQ_EMPTY(&views)) {
1898 const struct got_error *close_err;
1899 view = TAILQ_FIRST(&views);
1900 TAILQ_REMOVE(&views, view, entry);
1901 close_err = view_close(view);
1902 if (close_err && err == NULL)
1903 err = close_err;
1906 errcode = pthread_mutex_unlock(&tog_mutex);
1907 if (errcode && err == NULL)
1908 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1910 return err;
1913 __dead static void
1914 usage_log(void)
1916 endwin();
1917 fprintf(stderr,
1918 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1919 getprogname());
1920 exit(1);
1923 /* Create newly allocated wide-character string equivalent to a byte string. */
1924 static const struct got_error *
1925 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1927 char *vis = NULL;
1928 const struct got_error *err = NULL;
1930 *ws = NULL;
1931 *wlen = mbstowcs(NULL, s, 0);
1932 if (*wlen == (size_t)-1) {
1933 int vislen;
1934 if (errno != EILSEQ)
1935 return got_error_from_errno("mbstowcs");
1937 /* byte string invalid in current encoding; try to "fix" it */
1938 err = got_mbsavis(&vis, &vislen, s);
1939 if (err)
1940 return err;
1941 *wlen = mbstowcs(NULL, vis, 0);
1942 if (*wlen == (size_t)-1) {
1943 err = got_error_from_errno("mbstowcs"); /* give up */
1944 goto done;
1948 *ws = calloc(*wlen + 1, sizeof(**ws));
1949 if (*ws == NULL) {
1950 err = got_error_from_errno("calloc");
1951 goto done;
1954 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1955 err = got_error_from_errno("mbstowcs");
1956 done:
1957 free(vis);
1958 if (err) {
1959 free(*ws);
1960 *ws = NULL;
1961 *wlen = 0;
1963 return err;
1966 static const struct got_error *
1967 expand_tab(char **ptr, const char *src)
1969 char *dst;
1970 size_t len, n, idx = 0, sz = 0;
1972 *ptr = NULL;
1973 n = len = strlen(src);
1974 dst = malloc(n + 1);
1975 if (dst == NULL)
1976 return got_error_from_errno("malloc");
1978 while (idx < len && src[idx]) {
1979 const char c = src[idx];
1981 if (c == '\t') {
1982 size_t nb = TABSIZE - sz % TABSIZE;
1983 char *p;
1985 p = realloc(dst, n + nb);
1986 if (p == NULL) {
1987 free(dst);
1988 return got_error_from_errno("realloc");
1991 dst = p;
1992 n += nb;
1993 memset(dst + sz, ' ', nb);
1994 sz += nb;
1995 } else
1996 dst[sz++] = src[idx];
1997 ++idx;
2000 dst[sz] = '\0';
2001 *ptr = dst;
2002 return NULL;
2006 * Advance at most n columns from wline starting at offset off.
2007 * Return the index to the first character after the span operation.
2008 * Return the combined column width of all spanned wide character in
2009 * *rcol.
2011 static int
2012 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2014 int width, i, cols = 0;
2016 if (n == 0) {
2017 *rcol = cols;
2018 return off;
2021 for (i = off; wline[i] != L'\0'; ++i) {
2022 if (wline[i] == L'\t')
2023 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2024 else
2025 width = wcwidth(wline[i]);
2027 if (width == -1) {
2028 width = 1;
2029 wline[i] = L'.';
2032 if (cols + width > n)
2033 break;
2034 cols += width;
2037 *rcol = cols;
2038 return i;
2042 * Format a line for display, ensuring that it won't overflow a width limit.
2043 * With scrolling, the width returned refers to the scrolled version of the
2044 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2046 static const struct got_error *
2047 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2048 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2050 const struct got_error *err = NULL;
2051 int cols;
2052 wchar_t *wline = NULL;
2053 char *exstr = NULL;
2054 size_t wlen;
2055 int i, scrollx;
2057 *wlinep = NULL;
2058 *widthp = 0;
2060 if (expand) {
2061 err = expand_tab(&exstr, line);
2062 if (err)
2063 return err;
2066 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2067 free(exstr);
2068 if (err)
2069 return err;
2071 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2073 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2074 wline[wlen - 1] = L'\0';
2075 wlen--;
2077 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2078 wline[wlen - 1] = L'\0';
2079 wlen--;
2082 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2083 wline[i] = L'\0';
2085 if (widthp)
2086 *widthp = cols;
2087 if (scrollxp)
2088 *scrollxp = scrollx;
2089 if (err)
2090 free(wline);
2091 else
2092 *wlinep = wline;
2093 return err;
2096 static const struct got_error*
2097 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2098 struct got_object_id *id, struct got_repository *repo)
2100 static const struct got_error *err = NULL;
2101 struct got_reflist_entry *re;
2102 char *s;
2103 const char *name;
2105 *refs_str = NULL;
2107 TAILQ_FOREACH(re, refs, entry) {
2108 struct got_tag_object *tag = NULL;
2109 struct got_object_id *ref_id;
2110 int cmp;
2112 name = got_ref_get_name(re->ref);
2113 if (strcmp(name, GOT_REF_HEAD) == 0)
2114 continue;
2115 if (strncmp(name, "refs/", 5) == 0)
2116 name += 5;
2117 if (strncmp(name, "got/", 4) == 0 &&
2118 strncmp(name, "got/backup/", 11) != 0)
2119 continue;
2120 if (strncmp(name, "heads/", 6) == 0)
2121 name += 6;
2122 if (strncmp(name, "remotes/", 8) == 0) {
2123 name += 8;
2124 s = strstr(name, "/" GOT_REF_HEAD);
2125 if (s != NULL && s[strlen(s)] == '\0')
2126 continue;
2128 err = got_ref_resolve(&ref_id, repo, re->ref);
2129 if (err)
2130 break;
2131 if (strncmp(name, "tags/", 5) == 0) {
2132 err = got_object_open_as_tag(&tag, repo, ref_id);
2133 if (err) {
2134 if (err->code != GOT_ERR_OBJ_TYPE) {
2135 free(ref_id);
2136 break;
2138 /* Ref points at something other than a tag. */
2139 err = NULL;
2140 tag = NULL;
2143 cmp = got_object_id_cmp(tag ?
2144 got_object_tag_get_object_id(tag) : ref_id, id);
2145 free(ref_id);
2146 if (tag)
2147 got_object_tag_close(tag);
2148 if (cmp != 0)
2149 continue;
2150 s = *refs_str;
2151 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2152 s ? ", " : "", name) == -1) {
2153 err = got_error_from_errno("asprintf");
2154 free(s);
2155 *refs_str = NULL;
2156 break;
2158 free(s);
2161 return err;
2164 static const struct got_error *
2165 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2166 int col_tab_align)
2168 char *smallerthan;
2170 smallerthan = strchr(author, '<');
2171 if (smallerthan && smallerthan[1] != '\0')
2172 author = smallerthan + 1;
2173 author[strcspn(author, "@>")] = '\0';
2174 return format_line(wauthor, author_width, NULL, author, 0, limit,
2175 col_tab_align, 0);
2178 static const struct got_error *
2179 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2180 struct got_object_id *id, const size_t date_display_cols,
2181 int author_display_cols)
2183 struct tog_log_view_state *s = &view->state.log;
2184 const struct got_error *err = NULL;
2185 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2186 char *logmsg0 = NULL, *logmsg = NULL;
2187 char *author = NULL;
2188 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2189 int author_width, logmsg_width;
2190 char *newline, *line = NULL;
2191 int col, limit, scrollx;
2192 const int avail = view->ncols;
2193 struct tm tm;
2194 time_t committer_time;
2195 struct tog_color *tc;
2197 committer_time = got_object_commit_get_committer_time(commit);
2198 if (gmtime_r(&committer_time, &tm) == NULL)
2199 return got_error_from_errno("gmtime_r");
2200 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2201 return got_error(GOT_ERR_NO_SPACE);
2203 if (avail <= date_display_cols)
2204 limit = MIN(sizeof(datebuf) - 1, avail);
2205 else
2206 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2207 tc = get_color(&s->colors, TOG_COLOR_DATE);
2208 if (tc)
2209 wattr_on(view->window,
2210 COLOR_PAIR(tc->colorpair), NULL);
2211 waddnstr(view->window, datebuf, limit);
2212 if (tc)
2213 wattr_off(view->window,
2214 COLOR_PAIR(tc->colorpair), NULL);
2215 col = limit;
2216 if (col > avail)
2217 goto done;
2219 if (avail >= 120) {
2220 char *id_str;
2221 err = got_object_id_str(&id_str, id);
2222 if (err)
2223 goto done;
2224 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2225 if (tc)
2226 wattr_on(view->window,
2227 COLOR_PAIR(tc->colorpair), NULL);
2228 wprintw(view->window, "%.8s ", id_str);
2229 if (tc)
2230 wattr_off(view->window,
2231 COLOR_PAIR(tc->colorpair), NULL);
2232 free(id_str);
2233 col += 9;
2234 if (col > avail)
2235 goto done;
2238 if (s->use_committer)
2239 author = strdup(got_object_commit_get_committer(commit));
2240 else
2241 author = strdup(got_object_commit_get_author(commit));
2242 if (author == NULL) {
2243 err = got_error_from_errno("strdup");
2244 goto done;
2246 err = format_author(&wauthor, &author_width, author, avail - col, col);
2247 if (err)
2248 goto done;
2249 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2250 if (tc)
2251 wattr_on(view->window,
2252 COLOR_PAIR(tc->colorpair), NULL);
2253 waddwstr(view->window, wauthor);
2254 col += author_width;
2255 while (col < avail && author_width < author_display_cols + 2) {
2256 waddch(view->window, ' ');
2257 col++;
2258 author_width++;
2260 if (tc)
2261 wattr_off(view->window,
2262 COLOR_PAIR(tc->colorpair), NULL);
2263 if (col > avail)
2264 goto done;
2266 err = got_object_commit_get_logmsg(&logmsg0, commit);
2267 if (err)
2268 goto done;
2269 logmsg = logmsg0;
2270 while (*logmsg == '\n')
2271 logmsg++;
2272 newline = strchr(logmsg, '\n');
2273 if (newline)
2274 *newline = '\0';
2275 limit = avail - col;
2276 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2277 limit--; /* for the border */
2278 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2279 limit, col, 1);
2280 if (err)
2281 goto done;
2282 waddwstr(view->window, &wlogmsg[scrollx]);
2283 col += MAX(logmsg_width, 0);
2284 while (col < avail) {
2285 waddch(view->window, ' ');
2286 col++;
2288 done:
2289 free(logmsg0);
2290 free(wlogmsg);
2291 free(author);
2292 free(wauthor);
2293 free(line);
2294 return err;
2297 static struct commit_queue_entry *
2298 alloc_commit_queue_entry(struct got_commit_object *commit,
2299 struct got_object_id *id)
2301 struct commit_queue_entry *entry;
2302 struct got_object_id *dup;
2304 entry = calloc(1, sizeof(*entry));
2305 if (entry == NULL)
2306 return NULL;
2308 dup = got_object_id_dup(id);
2309 if (dup == NULL) {
2310 free(entry);
2311 return NULL;
2314 entry->id = dup;
2315 entry->commit = commit;
2316 return entry;
2319 static void
2320 pop_commit(struct commit_queue *commits)
2322 struct commit_queue_entry *entry;
2324 entry = TAILQ_FIRST(&commits->head);
2325 TAILQ_REMOVE(&commits->head, entry, entry);
2326 got_object_commit_close(entry->commit);
2327 commits->ncommits--;
2328 free(entry->id);
2329 free(entry);
2332 static void
2333 free_commits(struct commit_queue *commits)
2335 while (!TAILQ_EMPTY(&commits->head))
2336 pop_commit(commits);
2339 static const struct got_error *
2340 match_commit(int *have_match, struct got_object_id *id,
2341 struct got_commit_object *commit, regex_t *regex)
2343 const struct got_error *err = NULL;
2344 regmatch_t regmatch;
2345 char *id_str = NULL, *logmsg = NULL;
2347 *have_match = 0;
2349 err = got_object_id_str(&id_str, id);
2350 if (err)
2351 return err;
2353 err = got_object_commit_get_logmsg(&logmsg, commit);
2354 if (err)
2355 goto done;
2357 if (regexec(regex, got_object_commit_get_author(commit), 1,
2358 &regmatch, 0) == 0 ||
2359 regexec(regex, got_object_commit_get_committer(commit), 1,
2360 &regmatch, 0) == 0 ||
2361 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2362 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2363 *have_match = 1;
2364 done:
2365 free(id_str);
2366 free(logmsg);
2367 return err;
2370 static const struct got_error *
2371 queue_commits(struct tog_log_thread_args *a)
2373 const struct got_error *err = NULL;
2376 * We keep all commits open throughout the lifetime of the log
2377 * view in order to avoid having to re-fetch commits from disk
2378 * while updating the display.
2380 do {
2381 struct got_object_id id;
2382 struct got_commit_object *commit;
2383 struct commit_queue_entry *entry;
2384 int limit_match = 0;
2385 int errcode;
2387 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2388 NULL, NULL);
2389 if (err)
2390 break;
2392 err = got_object_open_as_commit(&commit, a->repo, &id);
2393 if (err)
2394 break;
2395 entry = alloc_commit_queue_entry(commit, &id);
2396 if (entry == NULL) {
2397 err = got_error_from_errno("alloc_commit_queue_entry");
2398 break;
2401 errcode = pthread_mutex_lock(&tog_mutex);
2402 if (errcode) {
2403 err = got_error_set_errno(errcode,
2404 "pthread_mutex_lock");
2405 break;
2408 entry->idx = a->real_commits->ncommits;
2409 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2410 a->real_commits->ncommits++;
2412 if (*a->limiting) {
2413 err = match_commit(&limit_match, &id, commit,
2414 a->limit_regex);
2415 if (err)
2416 break;
2418 if (limit_match) {
2419 struct commit_queue_entry *matched;
2421 matched = alloc_commit_queue_entry(
2422 entry->commit, entry->id);
2423 if (matched == NULL) {
2424 err = got_error_from_errno(
2425 "alloc_commit_queue_entry");
2426 break;
2428 matched->commit = entry->commit;
2429 got_object_commit_retain(entry->commit);
2431 matched->idx = a->limit_commits->ncommits;
2432 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2433 matched, entry);
2434 a->limit_commits->ncommits++;
2438 * This is how we signal log_thread() that we
2439 * have found a match, and that it should be
2440 * counted as a new entry for the view.
2442 a->limit_match = limit_match;
2445 if (*a->searching == TOG_SEARCH_FORWARD &&
2446 !*a->search_next_done) {
2447 int have_match;
2448 err = match_commit(&have_match, &id, commit, a->regex);
2449 if (err)
2450 break;
2452 if (*a->limiting) {
2453 if (limit_match && have_match)
2454 *a->search_next_done =
2455 TOG_SEARCH_HAVE_MORE;
2456 } else if (have_match)
2457 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2460 errcode = pthread_mutex_unlock(&tog_mutex);
2461 if (errcode && err == NULL)
2462 err = got_error_set_errno(errcode,
2463 "pthread_mutex_unlock");
2464 if (err)
2465 break;
2466 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2468 return err;
2471 static void
2472 select_commit(struct tog_log_view_state *s)
2474 struct commit_queue_entry *entry;
2475 int ncommits = 0;
2477 entry = s->first_displayed_entry;
2478 while (entry) {
2479 if (ncommits == s->selected) {
2480 s->selected_entry = entry;
2481 break;
2483 entry = TAILQ_NEXT(entry, entry);
2484 ncommits++;
2488 static const struct got_error *
2489 draw_commits(struct tog_view *view)
2491 const struct got_error *err = NULL;
2492 struct tog_log_view_state *s = &view->state.log;
2493 struct commit_queue_entry *entry = s->selected_entry;
2494 int limit = view->nlines;
2495 int width;
2496 int ncommits, author_cols = 4;
2497 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2498 char *refs_str = NULL;
2499 wchar_t *wline;
2500 struct tog_color *tc;
2501 static const size_t date_display_cols = 12;
2503 if (view_is_hsplit_top(view))
2504 --limit; /* account for border */
2506 if (s->selected_entry &&
2507 !(view->searching && view->search_next_done == 0)) {
2508 struct got_reflist_head *refs;
2509 err = got_object_id_str(&id_str, s->selected_entry->id);
2510 if (err)
2511 return err;
2512 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2513 s->selected_entry->id);
2514 if (refs) {
2515 err = build_refs_str(&refs_str, refs,
2516 s->selected_entry->id, s->repo);
2517 if (err)
2518 goto done;
2522 if (s->thread_args.commits_needed == 0)
2523 halfdelay(10); /* disable fast refresh */
2525 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2526 if (asprintf(&ncommits_str, " [%d/%d] %s",
2527 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2528 (view->searching && !view->search_next_done) ?
2529 "searching..." : "loading...") == -1) {
2530 err = got_error_from_errno("asprintf");
2531 goto done;
2533 } else {
2534 const char *search_str = NULL;
2535 const char *limit_str = NULL;
2537 if (view->searching) {
2538 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2539 search_str = "no more matches";
2540 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2541 search_str = "no matches found";
2542 else if (!view->search_next_done)
2543 search_str = "searching...";
2546 if (s->limit_view && s->commits->ncommits == 0)
2547 limit_str = "no matches found";
2549 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2550 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2551 search_str ? search_str : (refs_str ? refs_str : ""),
2552 limit_str ? limit_str : "") == -1) {
2553 err = got_error_from_errno("asprintf");
2554 goto done;
2558 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2559 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2560 "........................................",
2561 s->in_repo_path, ncommits_str) == -1) {
2562 err = got_error_from_errno("asprintf");
2563 header = NULL;
2564 goto done;
2566 } else if (asprintf(&header, "commit %s%s",
2567 id_str ? id_str : "........................................",
2568 ncommits_str) == -1) {
2569 err = got_error_from_errno("asprintf");
2570 header = NULL;
2571 goto done;
2573 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2574 if (err)
2575 goto done;
2577 werase(view->window);
2579 if (view_needs_focus_indication(view))
2580 wstandout(view->window);
2581 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2582 if (tc)
2583 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2584 waddwstr(view->window, wline);
2585 while (width < view->ncols) {
2586 waddch(view->window, ' ');
2587 width++;
2589 if (tc)
2590 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2591 if (view_needs_focus_indication(view))
2592 wstandend(view->window);
2593 free(wline);
2594 if (limit <= 1)
2595 goto done;
2597 /* Grow author column size if necessary, and set view->maxx. */
2598 entry = s->first_displayed_entry;
2599 ncommits = 0;
2600 view->maxx = 0;
2601 while (entry) {
2602 struct got_commit_object *c = entry->commit;
2603 char *author, *eol, *msg, *msg0;
2604 wchar_t *wauthor, *wmsg;
2605 int width;
2606 if (ncommits >= limit - 1)
2607 break;
2608 if (s->use_committer)
2609 author = strdup(got_object_commit_get_committer(c));
2610 else
2611 author = strdup(got_object_commit_get_author(c));
2612 if (author == NULL) {
2613 err = got_error_from_errno("strdup");
2614 goto done;
2616 err = format_author(&wauthor, &width, author, COLS,
2617 date_display_cols);
2618 if (author_cols < width)
2619 author_cols = width;
2620 free(wauthor);
2621 free(author);
2622 if (err)
2623 goto done;
2624 err = got_object_commit_get_logmsg(&msg0, c);
2625 if (err)
2626 goto done;
2627 msg = msg0;
2628 while (*msg == '\n')
2629 ++msg;
2630 if ((eol = strchr(msg, '\n')))
2631 *eol = '\0';
2632 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2633 date_display_cols + author_cols, 0);
2634 if (err)
2635 goto done;
2636 view->maxx = MAX(view->maxx, width);
2637 free(msg0);
2638 free(wmsg);
2639 ncommits++;
2640 entry = TAILQ_NEXT(entry, entry);
2643 entry = s->first_displayed_entry;
2644 s->last_displayed_entry = s->first_displayed_entry;
2645 ncommits = 0;
2646 while (entry) {
2647 if (ncommits >= limit - 1)
2648 break;
2649 if (ncommits == s->selected)
2650 wstandout(view->window);
2651 err = draw_commit(view, entry->commit, entry->id,
2652 date_display_cols, author_cols);
2653 if (ncommits == s->selected)
2654 wstandend(view->window);
2655 if (err)
2656 goto done;
2657 ncommits++;
2658 s->last_displayed_entry = entry;
2659 entry = TAILQ_NEXT(entry, entry);
2662 view_border(view);
2663 done:
2664 free(id_str);
2665 free(refs_str);
2666 free(ncommits_str);
2667 free(header);
2668 return err;
2671 static void
2672 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2674 struct commit_queue_entry *entry;
2675 int nscrolled = 0;
2677 entry = TAILQ_FIRST(&s->commits->head);
2678 if (s->first_displayed_entry == entry)
2679 return;
2681 entry = s->first_displayed_entry;
2682 while (entry && nscrolled < maxscroll) {
2683 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2684 if (entry) {
2685 s->first_displayed_entry = entry;
2686 nscrolled++;
2691 static const struct got_error *
2692 trigger_log_thread(struct tog_view *view, int wait)
2694 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2695 int errcode;
2697 halfdelay(1); /* fast refresh while loading commits */
2699 while (!ta->log_complete && !tog_thread_error &&
2700 (ta->commits_needed > 0 || ta->load_all)) {
2701 /* Wake the log thread. */
2702 errcode = pthread_cond_signal(&ta->need_commits);
2703 if (errcode)
2704 return got_error_set_errno(errcode,
2705 "pthread_cond_signal");
2708 * The mutex will be released while the view loop waits
2709 * in wgetch(), at which time the log thread will run.
2711 if (!wait)
2712 break;
2714 /* Display progress update in log view. */
2715 show_log_view(view);
2716 update_panels();
2717 doupdate();
2719 /* Wait right here while next commit is being loaded. */
2720 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2721 if (errcode)
2722 return got_error_set_errno(errcode,
2723 "pthread_cond_wait");
2725 /* Display progress update in log view. */
2726 show_log_view(view);
2727 update_panels();
2728 doupdate();
2731 return NULL;
2734 static const struct got_error *
2735 request_log_commits(struct tog_view *view)
2737 struct tog_log_view_state *state = &view->state.log;
2738 const struct got_error *err = NULL;
2740 if (state->thread_args.log_complete)
2741 return NULL;
2743 state->thread_args.commits_needed += view->nscrolled;
2744 err = trigger_log_thread(view, 1);
2745 view->nscrolled = 0;
2747 return err;
2750 static const struct got_error *
2751 log_scroll_down(struct tog_view *view, int maxscroll)
2753 struct tog_log_view_state *s = &view->state.log;
2754 const struct got_error *err = NULL;
2755 struct commit_queue_entry *pentry;
2756 int nscrolled = 0, ncommits_needed;
2758 if (s->last_displayed_entry == NULL)
2759 return NULL;
2761 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2762 if (s->commits->ncommits < ncommits_needed &&
2763 !s->thread_args.log_complete) {
2765 * Ask the log thread for required amount of commits.
2767 s->thread_args.commits_needed +=
2768 ncommits_needed - s->commits->ncommits;
2769 err = trigger_log_thread(view, 1);
2770 if (err)
2771 return err;
2774 do {
2775 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2776 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2777 break;
2779 s->last_displayed_entry = pentry ?
2780 pentry : s->last_displayed_entry;
2782 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2783 if (pentry == NULL)
2784 break;
2785 s->first_displayed_entry = pentry;
2786 } while (++nscrolled < maxscroll);
2788 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2789 view->nscrolled += nscrolled;
2790 else
2791 view->nscrolled = 0;
2793 return err;
2796 static const struct got_error *
2797 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2798 struct got_commit_object *commit, struct got_object_id *commit_id,
2799 struct tog_view *log_view, struct got_repository *repo)
2801 const struct got_error *err;
2802 struct got_object_qid *parent_id;
2803 struct tog_view *diff_view;
2805 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2806 if (diff_view == NULL)
2807 return got_error_from_errno("view_open");
2809 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2810 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2811 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2812 if (err == NULL)
2813 *new_view = diff_view;
2814 return err;
2817 static const struct got_error *
2818 tree_view_visit_subtree(struct tog_tree_view_state *s,
2819 struct got_tree_object *subtree)
2821 struct tog_parent_tree *parent;
2823 parent = calloc(1, sizeof(*parent));
2824 if (parent == NULL)
2825 return got_error_from_errno("calloc");
2827 parent->tree = s->tree;
2828 parent->first_displayed_entry = s->first_displayed_entry;
2829 parent->selected_entry = s->selected_entry;
2830 parent->selected = s->selected;
2831 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2832 s->tree = subtree;
2833 s->selected = 0;
2834 s->first_displayed_entry = NULL;
2835 return NULL;
2838 static const struct got_error *
2839 tree_view_walk_path(struct tog_tree_view_state *s,
2840 struct got_commit_object *commit, const char *path)
2842 const struct got_error *err = NULL;
2843 struct got_tree_object *tree = NULL;
2844 const char *p;
2845 char *slash, *subpath = NULL;
2847 /* Walk the path and open corresponding tree objects. */
2848 p = path;
2849 while (*p) {
2850 struct got_tree_entry *te;
2851 struct got_object_id *tree_id;
2852 char *te_name;
2854 while (p[0] == '/')
2855 p++;
2857 /* Ensure the correct subtree entry is selected. */
2858 slash = strchr(p, '/');
2859 if (slash == NULL)
2860 te_name = strdup(p);
2861 else
2862 te_name = strndup(p, slash - p);
2863 if (te_name == NULL) {
2864 err = got_error_from_errno("strndup");
2865 break;
2867 te = got_object_tree_find_entry(s->tree, te_name);
2868 if (te == NULL) {
2869 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2870 free(te_name);
2871 break;
2873 free(te_name);
2874 s->first_displayed_entry = s->selected_entry = te;
2876 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2877 break; /* jump to this file's entry */
2879 slash = strchr(p, '/');
2880 if (slash)
2881 subpath = strndup(path, slash - path);
2882 else
2883 subpath = strdup(path);
2884 if (subpath == NULL) {
2885 err = got_error_from_errno("strdup");
2886 break;
2889 err = got_object_id_by_path(&tree_id, s->repo, commit,
2890 subpath);
2891 if (err)
2892 break;
2894 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2895 free(tree_id);
2896 if (err)
2897 break;
2899 err = tree_view_visit_subtree(s, tree);
2900 if (err) {
2901 got_object_tree_close(tree);
2902 break;
2904 if (slash == NULL)
2905 break;
2906 free(subpath);
2907 subpath = NULL;
2908 p = slash;
2911 free(subpath);
2912 return err;
2915 static const struct got_error *
2916 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2917 struct commit_queue_entry *entry, const char *path,
2918 const char *head_ref_name, struct got_repository *repo)
2920 const struct got_error *err = NULL;
2921 struct tog_tree_view_state *s;
2922 struct tog_view *tree_view;
2924 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2925 if (tree_view == NULL)
2926 return got_error_from_errno("view_open");
2928 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2929 if (err)
2930 return err;
2931 s = &tree_view->state.tree;
2933 *new_view = tree_view;
2935 if (got_path_is_root_dir(path))
2936 return NULL;
2938 return tree_view_walk_path(s, entry->commit, path);
2941 static const struct got_error *
2942 block_signals_used_by_main_thread(void)
2944 sigset_t sigset;
2945 int errcode;
2947 if (sigemptyset(&sigset) == -1)
2948 return got_error_from_errno("sigemptyset");
2950 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2951 if (sigaddset(&sigset, SIGWINCH) == -1)
2952 return got_error_from_errno("sigaddset");
2953 if (sigaddset(&sigset, SIGCONT) == -1)
2954 return got_error_from_errno("sigaddset");
2955 if (sigaddset(&sigset, SIGINT) == -1)
2956 return got_error_from_errno("sigaddset");
2957 if (sigaddset(&sigset, SIGTERM) == -1)
2958 return got_error_from_errno("sigaddset");
2960 /* ncurses handles SIGTSTP */
2961 if (sigaddset(&sigset, SIGTSTP) == -1)
2962 return got_error_from_errno("sigaddset");
2964 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2965 if (errcode)
2966 return got_error_set_errno(errcode, "pthread_sigmask");
2968 return NULL;
2971 static void *
2972 log_thread(void *arg)
2974 const struct got_error *err = NULL;
2975 int errcode = 0;
2976 struct tog_log_thread_args *a = arg;
2977 int done = 0;
2980 * Sync startup with main thread such that we begin our
2981 * work once view_input() has released the mutex.
2983 errcode = pthread_mutex_lock(&tog_mutex);
2984 if (errcode) {
2985 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2986 return (void *)err;
2989 err = block_signals_used_by_main_thread();
2990 if (err) {
2991 pthread_mutex_unlock(&tog_mutex);
2992 goto done;
2995 while (!done && !err && !tog_fatal_signal_received()) {
2996 errcode = pthread_mutex_unlock(&tog_mutex);
2997 if (errcode) {
2998 err = got_error_set_errno(errcode,
2999 "pthread_mutex_unlock");
3000 goto done;
3002 err = queue_commits(a);
3003 if (err) {
3004 if (err->code != GOT_ERR_ITER_COMPLETED)
3005 goto done;
3006 err = NULL;
3007 done = 1;
3008 } else if (a->commits_needed > 0 && !a->load_all) {
3009 if (*a->limiting) {
3010 if (a->limit_match)
3011 a->commits_needed--;
3012 } else
3013 a->commits_needed--;
3016 errcode = pthread_mutex_lock(&tog_mutex);
3017 if (errcode) {
3018 err = got_error_set_errno(errcode,
3019 "pthread_mutex_lock");
3020 goto done;
3021 } else if (*a->quit)
3022 done = 1;
3023 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3024 *a->first_displayed_entry =
3025 TAILQ_FIRST(&a->limit_commits->head);
3026 *a->selected_entry = *a->first_displayed_entry;
3027 } else if (*a->first_displayed_entry == NULL) {
3028 *a->first_displayed_entry =
3029 TAILQ_FIRST(&a->real_commits->head);
3030 *a->selected_entry = *a->first_displayed_entry;
3033 errcode = pthread_cond_signal(&a->commit_loaded);
3034 if (errcode) {
3035 err = got_error_set_errno(errcode,
3036 "pthread_cond_signal");
3037 pthread_mutex_unlock(&tog_mutex);
3038 goto done;
3041 if (done)
3042 a->commits_needed = 0;
3043 else {
3044 if (a->commits_needed == 0 && !a->load_all) {
3045 errcode = pthread_cond_wait(&a->need_commits,
3046 &tog_mutex);
3047 if (errcode) {
3048 err = got_error_set_errno(errcode,
3049 "pthread_cond_wait");
3050 pthread_mutex_unlock(&tog_mutex);
3051 goto done;
3053 if (*a->quit)
3054 done = 1;
3058 a->log_complete = 1;
3059 errcode = pthread_mutex_unlock(&tog_mutex);
3060 if (errcode)
3061 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3062 done:
3063 if (err) {
3064 tog_thread_error = 1;
3065 pthread_cond_signal(&a->commit_loaded);
3067 return (void *)err;
3070 static const struct got_error *
3071 stop_log_thread(struct tog_log_view_state *s)
3073 const struct got_error *err = NULL, *thread_err = NULL;
3074 int errcode;
3076 if (s->thread) {
3077 s->quit = 1;
3078 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3079 if (errcode)
3080 return got_error_set_errno(errcode,
3081 "pthread_cond_signal");
3082 errcode = pthread_mutex_unlock(&tog_mutex);
3083 if (errcode)
3084 return got_error_set_errno(errcode,
3085 "pthread_mutex_unlock");
3086 errcode = pthread_join(s->thread, (void **)&thread_err);
3087 if (errcode)
3088 return got_error_set_errno(errcode, "pthread_join");
3089 errcode = pthread_mutex_lock(&tog_mutex);
3090 if (errcode)
3091 return got_error_set_errno(errcode,
3092 "pthread_mutex_lock");
3093 s->thread = NULL;
3096 if (s->thread_args.repo) {
3097 err = got_repo_close(s->thread_args.repo);
3098 s->thread_args.repo = NULL;
3101 if (s->thread_args.pack_fds) {
3102 const struct got_error *pack_err =
3103 got_repo_pack_fds_close(s->thread_args.pack_fds);
3104 if (err == NULL)
3105 err = pack_err;
3106 s->thread_args.pack_fds = NULL;
3109 if (s->thread_args.graph) {
3110 got_commit_graph_close(s->thread_args.graph);
3111 s->thread_args.graph = NULL;
3114 return err ? err : thread_err;
3117 static const struct got_error *
3118 close_log_view(struct tog_view *view)
3120 const struct got_error *err = NULL;
3121 struct tog_log_view_state *s = &view->state.log;
3122 int errcode;
3124 err = stop_log_thread(s);
3126 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3127 if (errcode && err == NULL)
3128 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3130 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3131 if (errcode && err == NULL)
3132 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3134 free_commits(&s->limit_commits);
3135 free_commits(&s->real_commits);
3136 free(s->in_repo_path);
3137 s->in_repo_path = NULL;
3138 free(s->start_id);
3139 s->start_id = NULL;
3140 free(s->head_ref_name);
3141 s->head_ref_name = NULL;
3142 return err;
3146 * We use two queues to implement the limit feature: first consists of
3147 * commits matching the current limit_regex; second is the real queue
3148 * of all known commits (real_commits). When the user starts limiting,
3149 * we swap queues such that all movement and displaying functionality
3150 * works with very slight change.
3152 static const struct got_error *
3153 limit_log_view(struct tog_view *view)
3155 struct tog_log_view_state *s = &view->state.log;
3156 struct commit_queue_entry *entry;
3157 struct tog_view *v = view;
3158 const struct got_error *err = NULL;
3159 char pattern[1024];
3160 int ret;
3162 if (view_is_hsplit_top(view))
3163 v = view->child;
3164 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3165 v = view->parent;
3167 /* Get the pattern */
3168 wmove(v->window, v->nlines - 1, 0);
3169 wclrtoeol(v->window);
3170 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3171 nodelay(v->window, FALSE);
3172 nocbreak();
3173 echo();
3174 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3175 cbreak();
3176 noecho();
3177 nodelay(v->window, TRUE);
3178 if (ret == ERR)
3179 return NULL;
3181 if (*pattern == '\0') {
3183 * Safety measure for the situation where the user
3184 * resets limit without previously limiting anything.
3186 if (!s->limit_view)
3187 return NULL;
3190 * User could have pressed Ctrl+L, which refreshed the
3191 * commit queues, it means we can't save previously
3192 * (before limit took place) displayed entries,
3193 * because they would point to already free'ed memory,
3194 * so we are forced to always select first entry of
3195 * the queue.
3197 s->commits = &s->real_commits;
3198 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3199 s->selected_entry = s->first_displayed_entry;
3200 s->selected = 0;
3201 s->limit_view = 0;
3203 return NULL;
3206 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3207 return NULL;
3209 s->limit_view = 1;
3211 /* Clear the screen while loading limit view */
3212 s->first_displayed_entry = NULL;
3213 s->last_displayed_entry = NULL;
3214 s->selected_entry = NULL;
3215 s->commits = &s->limit_commits;
3217 /* Prepare limit queue for new search */
3218 free_commits(&s->limit_commits);
3219 s->limit_commits.ncommits = 0;
3221 /* First process commits, which are in queue already */
3222 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3223 int have_match = 0;
3225 err = match_commit(&have_match, entry->id,
3226 entry->commit, &s->limit_regex);
3227 if (err)
3228 return err;
3230 if (have_match) {
3231 struct commit_queue_entry *matched;
3233 matched = alloc_commit_queue_entry(entry->commit,
3234 entry->id);
3235 if (matched == NULL) {
3236 err = got_error_from_errno(
3237 "alloc_commit_queue_entry");
3238 break;
3240 matched->commit = entry->commit;
3241 got_object_commit_retain(entry->commit);
3243 matched->idx = s->limit_commits.ncommits;
3244 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3245 matched, entry);
3246 s->limit_commits.ncommits++;
3250 /* Second process all the commits, until we fill the screen */
3251 if (s->limit_commits.ncommits < view->nlines - 1 &&
3252 !s->thread_args.log_complete) {
3253 s->thread_args.commits_needed +=
3254 view->nlines - s->limit_commits.ncommits - 1;
3255 err = trigger_log_thread(view, 1);
3256 if (err)
3257 return err;
3260 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3261 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3262 s->selected = 0;
3264 return NULL;
3267 static const struct got_error *
3268 search_start_log_view(struct tog_view *view)
3270 struct tog_log_view_state *s = &view->state.log;
3272 s->matched_entry = NULL;
3273 s->search_entry = NULL;
3274 return NULL;
3277 static const struct got_error *
3278 search_next_log_view(struct tog_view *view)
3280 const struct got_error *err = NULL;
3281 struct tog_log_view_state *s = &view->state.log;
3282 struct commit_queue_entry *entry;
3284 /* Display progress update in log view. */
3285 show_log_view(view);
3286 update_panels();
3287 doupdate();
3289 if (s->search_entry) {
3290 int errcode, ch;
3291 errcode = pthread_mutex_unlock(&tog_mutex);
3292 if (errcode)
3293 return got_error_set_errno(errcode,
3294 "pthread_mutex_unlock");
3295 ch = wgetch(view->window);
3296 errcode = pthread_mutex_lock(&tog_mutex);
3297 if (errcode)
3298 return got_error_set_errno(errcode,
3299 "pthread_mutex_lock");
3300 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3301 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3302 return NULL;
3304 if (view->searching == TOG_SEARCH_FORWARD)
3305 entry = TAILQ_NEXT(s->search_entry, entry);
3306 else
3307 entry = TAILQ_PREV(s->search_entry,
3308 commit_queue_head, entry);
3309 } else if (s->matched_entry) {
3311 * If the user has moved the cursor after we hit a match,
3312 * the position from where we should continue searching
3313 * might have changed.
3315 if (view->searching == TOG_SEARCH_FORWARD)
3316 entry = TAILQ_NEXT(s->selected_entry, entry);
3317 else
3318 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3319 entry);
3320 } else {
3321 entry = s->selected_entry;
3324 while (1) {
3325 int have_match = 0;
3327 if (entry == NULL) {
3328 if (s->thread_args.log_complete ||
3329 view->searching == TOG_SEARCH_BACKWARD) {
3330 view->search_next_done =
3331 (s->matched_entry == NULL ?
3332 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3333 s->search_entry = NULL;
3334 return NULL;
3337 * Poke the log thread for more commits and return,
3338 * allowing the main loop to make progress. Search
3339 * will resume at s->search_entry once we come back.
3341 s->thread_args.commits_needed++;
3342 return trigger_log_thread(view, 0);
3345 err = match_commit(&have_match, entry->id, entry->commit,
3346 &view->regex);
3347 if (err)
3348 break;
3349 if (have_match) {
3350 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3351 s->matched_entry = entry;
3352 break;
3355 s->search_entry = entry;
3356 if (view->searching == TOG_SEARCH_FORWARD)
3357 entry = TAILQ_NEXT(entry, entry);
3358 else
3359 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3362 if (s->matched_entry) {
3363 int cur = s->selected_entry->idx;
3364 while (cur < s->matched_entry->idx) {
3365 err = input_log_view(NULL, view, KEY_DOWN);
3366 if (err)
3367 return err;
3368 cur++;
3370 while (cur > s->matched_entry->idx) {
3371 err = input_log_view(NULL, view, KEY_UP);
3372 if (err)
3373 return err;
3374 cur--;
3378 s->search_entry = NULL;
3380 return NULL;
3383 static const struct got_error *
3384 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3385 struct got_repository *repo, const char *head_ref_name,
3386 const char *in_repo_path, int log_branches)
3388 const struct got_error *err = NULL;
3389 struct tog_log_view_state *s = &view->state.log;
3390 struct got_repository *thread_repo = NULL;
3391 struct got_commit_graph *thread_graph = NULL;
3392 int errcode;
3394 if (in_repo_path != s->in_repo_path) {
3395 free(s->in_repo_path);
3396 s->in_repo_path = strdup(in_repo_path);
3397 if (s->in_repo_path == NULL)
3398 return got_error_from_errno("strdup");
3401 /* The commit queue only contains commits being displayed. */
3402 TAILQ_INIT(&s->real_commits.head);
3403 s->real_commits.ncommits = 0;
3404 s->commits = &s->real_commits;
3406 TAILQ_INIT(&s->limit_commits.head);
3407 s->limit_view = 0;
3408 s->limit_commits.ncommits = 0;
3410 s->repo = repo;
3411 if (head_ref_name) {
3412 s->head_ref_name = strdup(head_ref_name);
3413 if (s->head_ref_name == NULL) {
3414 err = got_error_from_errno("strdup");
3415 goto done;
3418 s->start_id = got_object_id_dup(start_id);
3419 if (s->start_id == NULL) {
3420 err = got_error_from_errno("got_object_id_dup");
3421 goto done;
3423 s->log_branches = log_branches;
3424 s->use_committer = 1;
3426 STAILQ_INIT(&s->colors);
3427 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3428 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3429 get_color_value("TOG_COLOR_COMMIT"));
3430 if (err)
3431 goto done;
3432 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3433 get_color_value("TOG_COLOR_AUTHOR"));
3434 if (err) {
3435 free_colors(&s->colors);
3436 goto done;
3438 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3439 get_color_value("TOG_COLOR_DATE"));
3440 if (err) {
3441 free_colors(&s->colors);
3442 goto done;
3446 view->show = show_log_view;
3447 view->input = input_log_view;
3448 view->resize = resize_log_view;
3449 view->close = close_log_view;
3450 view->search_start = search_start_log_view;
3451 view->search_next = search_next_log_view;
3453 if (s->thread_args.pack_fds == NULL) {
3454 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3455 if (err)
3456 goto done;
3458 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3459 s->thread_args.pack_fds);
3460 if (err)
3461 goto done;
3462 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3463 !s->log_branches);
3464 if (err)
3465 goto done;
3466 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3467 s->repo, NULL, NULL);
3468 if (err)
3469 goto done;
3471 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3472 if (errcode) {
3473 err = got_error_set_errno(errcode, "pthread_cond_init");
3474 goto done;
3476 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3477 if (errcode) {
3478 err = got_error_set_errno(errcode, "pthread_cond_init");
3479 goto done;
3482 s->thread_args.commits_needed = view->nlines;
3483 s->thread_args.graph = thread_graph;
3484 s->thread_args.real_commits = &s->real_commits;
3485 s->thread_args.limit_commits = &s->limit_commits;
3486 s->thread_args.in_repo_path = s->in_repo_path;
3487 s->thread_args.start_id = s->start_id;
3488 s->thread_args.repo = thread_repo;
3489 s->thread_args.log_complete = 0;
3490 s->thread_args.quit = &s->quit;
3491 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3492 s->thread_args.selected_entry = &s->selected_entry;
3493 s->thread_args.searching = &view->searching;
3494 s->thread_args.search_next_done = &view->search_next_done;
3495 s->thread_args.regex = &view->regex;
3496 s->thread_args.limiting = &s->limit_view;
3497 s->thread_args.limit_regex = &s->limit_regex;
3498 s->thread_args.limit_commits = &s->limit_commits;
3499 done:
3500 if (err)
3501 close_log_view(view);
3502 return err;
3505 static const struct got_error *
3506 show_log_view(struct tog_view *view)
3508 const struct got_error *err;
3509 struct tog_log_view_state *s = &view->state.log;
3511 if (s->thread == NULL) {
3512 int errcode = pthread_create(&s->thread, NULL, log_thread,
3513 &s->thread_args);
3514 if (errcode)
3515 return got_error_set_errno(errcode, "pthread_create");
3516 if (s->thread_args.commits_needed > 0) {
3517 err = trigger_log_thread(view, 1);
3518 if (err)
3519 return err;
3523 return draw_commits(view);
3526 static void
3527 log_move_cursor_up(struct tog_view *view, int page, int home)
3529 struct tog_log_view_state *s = &view->state.log;
3531 if (s->first_displayed_entry == NULL)
3532 return;
3533 if (s->selected_entry->idx == 0)
3534 view->count = 0;
3536 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3537 || home)
3538 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3540 if (!page && !home && s->selected > 0)
3541 --s->selected;
3542 else
3543 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3545 select_commit(s);
3546 return;
3549 static const struct got_error *
3550 log_move_cursor_down(struct tog_view *view, int page)
3552 struct tog_log_view_state *s = &view->state.log;
3553 const struct got_error *err = NULL;
3554 int eos = view->nlines - 2;
3556 if (s->first_displayed_entry == NULL)
3557 return NULL;
3559 if (s->thread_args.log_complete &&
3560 s->selected_entry->idx >= s->commits->ncommits - 1)
3561 return NULL;
3563 if (view_is_hsplit_top(view))
3564 --eos; /* border consumes the last line */
3566 if (!page) {
3567 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3568 ++s->selected;
3569 else
3570 err = log_scroll_down(view, 1);
3571 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3572 struct commit_queue_entry *entry;
3573 int n;
3575 s->selected = 0;
3576 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3577 s->last_displayed_entry = entry;
3578 for (n = 0; n <= eos; n++) {
3579 if (entry == NULL)
3580 break;
3581 s->first_displayed_entry = entry;
3582 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3584 if (n > 0)
3585 s->selected = n - 1;
3586 } else {
3587 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3588 s->thread_args.log_complete)
3589 s->selected += MIN(page,
3590 s->commits->ncommits - s->selected_entry->idx - 1);
3591 else
3592 err = log_scroll_down(view, page);
3594 if (err)
3595 return err;
3598 * We might necessarily overshoot in horizontal
3599 * splits; if so, select the last displayed commit.
3601 if (s->first_displayed_entry && s->last_displayed_entry) {
3602 s->selected = MIN(s->selected,
3603 s->last_displayed_entry->idx -
3604 s->first_displayed_entry->idx);
3607 select_commit(s);
3609 if (s->thread_args.log_complete &&
3610 s->selected_entry->idx == s->commits->ncommits - 1)
3611 view->count = 0;
3613 return NULL;
3616 static void
3617 view_get_split(struct tog_view *view, int *y, int *x)
3619 *x = 0;
3620 *y = 0;
3622 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3623 if (view->child && view->child->resized_y)
3624 *y = view->child->resized_y;
3625 else if (view->resized_y)
3626 *y = view->resized_y;
3627 else
3628 *y = view_split_begin_y(view->lines);
3629 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3630 if (view->child && view->child->resized_x)
3631 *x = view->child->resized_x;
3632 else if (view->resized_x)
3633 *x = view->resized_x;
3634 else
3635 *x = view_split_begin_x(view->begin_x);
3639 /* Split view horizontally at y and offset view->state->selected line. */
3640 static const struct got_error *
3641 view_init_hsplit(struct tog_view *view, int y)
3643 const struct got_error *err = NULL;
3645 view->nlines = y;
3646 view->ncols = COLS;
3647 err = view_resize(view);
3648 if (err)
3649 return err;
3651 err = offset_selection_down(view);
3653 return err;
3656 static const struct got_error *
3657 log_goto_line(struct tog_view *view, int nlines)
3659 const struct got_error *err = NULL;
3660 struct tog_log_view_state *s = &view->state.log;
3661 int g, idx = s->selected_entry->idx;
3663 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3664 return NULL;
3666 g = view->gline;
3667 view->gline = 0;
3669 if (g >= s->first_displayed_entry->idx + 1 &&
3670 g <= s->last_displayed_entry->idx + 1 &&
3671 g - s->first_displayed_entry->idx - 1 < nlines) {
3672 s->selected = g - s->first_displayed_entry->idx - 1;
3673 select_commit(s);
3674 return NULL;
3677 if (idx + 1 < g) {
3678 err = log_move_cursor_down(view, g - idx - 1);
3679 if (!err && g > s->selected_entry->idx + 1)
3680 err = log_move_cursor_down(view,
3681 g - s->first_displayed_entry->idx - 1);
3682 if (err)
3683 return err;
3684 } else if (idx + 1 > g)
3685 log_move_cursor_up(view, idx - g + 1, 0);
3687 if (g < nlines && s->first_displayed_entry->idx == 0)
3688 s->selected = g - 1;
3690 select_commit(s);
3691 return NULL;
3695 static void
3696 horizontal_scroll_input(struct tog_view *view, int ch)
3699 switch (ch) {
3700 case KEY_LEFT:
3701 case 'h':
3702 view->x -= MIN(view->x, 2);
3703 if (view->x <= 0)
3704 view->count = 0;
3705 break;
3706 case KEY_RIGHT:
3707 case 'l':
3708 if (view->x + view->ncols / 2 < view->maxx)
3709 view->x += 2;
3710 else
3711 view->count = 0;
3712 break;
3713 case '0':
3714 view->x = 0;
3715 break;
3716 case '$':
3717 view->x = MAX(view->maxx - view->ncols / 2, 0);
3718 view->count = 0;
3719 break;
3720 default:
3721 break;
3725 static const struct got_error *
3726 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3728 const struct got_error *err = NULL;
3729 struct tog_log_view_state *s = &view->state.log;
3730 int eos, nscroll;
3732 if (s->thread_args.load_all) {
3733 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3734 s->thread_args.load_all = 0;
3735 else if (s->thread_args.log_complete) {
3736 err = log_move_cursor_down(view, s->commits->ncommits);
3737 s->thread_args.load_all = 0;
3739 if (err)
3740 return err;
3743 eos = nscroll = view->nlines - 1;
3744 if (view_is_hsplit_top(view))
3745 --eos; /* border */
3747 if (view->gline)
3748 return log_goto_line(view, eos);
3750 switch (ch) {
3751 case '&':
3752 err = limit_log_view(view);
3753 break;
3754 case 'q':
3755 s->quit = 1;
3756 break;
3757 case '0':
3758 case '$':
3759 case KEY_RIGHT:
3760 case 'l':
3761 case KEY_LEFT:
3762 case 'h':
3763 horizontal_scroll_input(view, ch);
3764 break;
3765 case 'k':
3766 case KEY_UP:
3767 case '<':
3768 case ',':
3769 case CTRL('p'):
3770 log_move_cursor_up(view, 0, 0);
3771 break;
3772 case 'g':
3773 case '=':
3774 case KEY_HOME:
3775 log_move_cursor_up(view, 0, 1);
3776 view->count = 0;
3777 break;
3778 case CTRL('u'):
3779 case 'u':
3780 nscroll /= 2;
3781 /* FALL THROUGH */
3782 case KEY_PPAGE:
3783 case CTRL('b'):
3784 case 'b':
3785 log_move_cursor_up(view, nscroll, 0);
3786 break;
3787 case 'j':
3788 case KEY_DOWN:
3789 case '>':
3790 case '.':
3791 case CTRL('n'):
3792 err = log_move_cursor_down(view, 0);
3793 break;
3794 case '@':
3795 s->use_committer = !s->use_committer;
3796 view->action = s->use_committer ?
3797 "show committer" : "show commit author";
3798 break;
3799 case 'G':
3800 case '*':
3801 case KEY_END: {
3802 /* We don't know yet how many commits, so we're forced to
3803 * traverse them all. */
3804 view->count = 0;
3805 s->thread_args.load_all = 1;
3806 if (!s->thread_args.log_complete)
3807 return trigger_log_thread(view, 0);
3808 err = log_move_cursor_down(view, s->commits->ncommits);
3809 s->thread_args.load_all = 0;
3810 break;
3812 case CTRL('d'):
3813 case 'd':
3814 nscroll /= 2;
3815 /* FALL THROUGH */
3816 case KEY_NPAGE:
3817 case CTRL('f'):
3818 case 'f':
3819 case ' ':
3820 err = log_move_cursor_down(view, nscroll);
3821 break;
3822 case KEY_RESIZE:
3823 if (s->selected > view->nlines - 2)
3824 s->selected = view->nlines - 2;
3825 if (s->selected > s->commits->ncommits - 1)
3826 s->selected = s->commits->ncommits - 1;
3827 select_commit(s);
3828 if (s->commits->ncommits < view->nlines - 1 &&
3829 !s->thread_args.log_complete) {
3830 s->thread_args.commits_needed += (view->nlines - 1) -
3831 s->commits->ncommits;
3832 err = trigger_log_thread(view, 1);
3834 break;
3835 case KEY_ENTER:
3836 case '\r':
3837 view->count = 0;
3838 if (s->selected_entry == NULL)
3839 break;
3840 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3841 break;
3842 case 'T':
3843 view->count = 0;
3844 if (s->selected_entry == NULL)
3845 break;
3846 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3847 break;
3848 case KEY_BACKSPACE:
3849 case CTRL('l'):
3850 case 'B':
3851 view->count = 0;
3852 if (ch == KEY_BACKSPACE &&
3853 got_path_is_root_dir(s->in_repo_path))
3854 break;
3855 err = stop_log_thread(s);
3856 if (err)
3857 return err;
3858 if (ch == KEY_BACKSPACE) {
3859 char *parent_path;
3860 err = got_path_dirname(&parent_path, s->in_repo_path);
3861 if (err)
3862 return err;
3863 free(s->in_repo_path);
3864 s->in_repo_path = parent_path;
3865 s->thread_args.in_repo_path = s->in_repo_path;
3866 } else if (ch == CTRL('l')) {
3867 struct got_object_id *start_id;
3868 err = got_repo_match_object_id(&start_id, NULL,
3869 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3870 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3871 if (err) {
3872 if (s->head_ref_name == NULL ||
3873 err->code != GOT_ERR_NOT_REF)
3874 return err;
3875 /* Try to cope with deleted references. */
3876 free(s->head_ref_name);
3877 s->head_ref_name = NULL;
3878 err = got_repo_match_object_id(&start_id,
3879 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
3880 &tog_refs, s->repo);
3881 if (err)
3882 return err;
3884 free(s->start_id);
3885 s->start_id = start_id;
3886 s->thread_args.start_id = s->start_id;
3887 } else /* 'B' */
3888 s->log_branches = !s->log_branches;
3890 if (s->thread_args.pack_fds == NULL) {
3891 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3892 if (err)
3893 return err;
3895 err = got_repo_open(&s->thread_args.repo,
3896 got_repo_get_path(s->repo), NULL,
3897 s->thread_args.pack_fds);
3898 if (err)
3899 return err;
3900 tog_free_refs();
3901 err = tog_load_refs(s->repo, 0);
3902 if (err)
3903 return err;
3904 err = got_commit_graph_open(&s->thread_args.graph,
3905 s->in_repo_path, !s->log_branches);
3906 if (err)
3907 return err;
3908 err = got_commit_graph_iter_start(s->thread_args.graph,
3909 s->start_id, s->repo, NULL, NULL);
3910 if (err)
3911 return err;
3912 free_commits(&s->real_commits);
3913 free_commits(&s->limit_commits);
3914 s->first_displayed_entry = NULL;
3915 s->last_displayed_entry = NULL;
3916 s->selected_entry = NULL;
3917 s->selected = 0;
3918 s->thread_args.log_complete = 0;
3919 s->quit = 0;
3920 s->thread_args.commits_needed = view->lines;
3921 s->matched_entry = NULL;
3922 s->search_entry = NULL;
3923 view->offset = 0;
3924 break;
3925 case 'R':
3926 view->count = 0;
3927 err = view_request_new(new_view, view, TOG_VIEW_REF);
3928 break;
3929 default:
3930 view->count = 0;
3931 break;
3934 return err;
3937 static const struct got_error *
3938 apply_unveil(const char *repo_path, const char *worktree_path)
3940 const struct got_error *error;
3942 #ifdef PROFILE
3943 if (unveil("gmon.out", "rwc") != 0)
3944 return got_error_from_errno2("unveil", "gmon.out");
3945 #endif
3946 if (repo_path && unveil(repo_path, "r") != 0)
3947 return got_error_from_errno2("unveil", repo_path);
3949 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3950 return got_error_from_errno2("unveil", worktree_path);
3952 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3953 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3955 error = got_privsep_unveil_exec_helpers();
3956 if (error != NULL)
3957 return error;
3959 if (unveil(NULL, NULL) != 0)
3960 return got_error_from_errno("unveil");
3962 return NULL;
3965 static void
3966 init_curses(void)
3969 * Override default signal handlers before starting ncurses.
3970 * This should prevent ncurses from installing its own
3971 * broken cleanup() signal handler.
3973 signal(SIGWINCH, tog_sigwinch);
3974 signal(SIGPIPE, tog_sigpipe);
3975 signal(SIGCONT, tog_sigcont);
3976 signal(SIGINT, tog_sigint);
3977 signal(SIGTERM, tog_sigterm);
3979 initscr();
3980 cbreak();
3981 halfdelay(1); /* Do fast refresh while initial view is loading. */
3982 noecho();
3983 nonl();
3984 intrflush(stdscr, FALSE);
3985 keypad(stdscr, TRUE);
3986 curs_set(0);
3987 if (getenv("TOG_COLORS") != NULL) {
3988 start_color();
3989 use_default_colors();
3993 static const struct got_error *
3994 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3995 struct got_repository *repo, struct got_worktree *worktree)
3997 const struct got_error *err = NULL;
3999 if (argc == 0) {
4000 *in_repo_path = strdup("/");
4001 if (*in_repo_path == NULL)
4002 return got_error_from_errno("strdup");
4003 return NULL;
4006 if (worktree) {
4007 const char *prefix = got_worktree_get_path_prefix(worktree);
4008 char *p;
4010 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4011 if (err)
4012 return err;
4013 if (asprintf(in_repo_path, "%s%s%s", prefix,
4014 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4015 p) == -1) {
4016 err = got_error_from_errno("asprintf");
4017 *in_repo_path = NULL;
4019 free(p);
4020 } else
4021 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4023 return err;
4026 static const struct got_error *
4027 cmd_log(int argc, char *argv[])
4029 const struct got_error *error;
4030 struct got_repository *repo = NULL;
4031 struct got_worktree *worktree = NULL;
4032 struct got_object_id *start_id = NULL;
4033 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4034 char *start_commit = NULL, *label = NULL;
4035 struct got_reference *ref = NULL;
4036 const char *head_ref_name = NULL;
4037 int ch, log_branches = 0;
4038 struct tog_view *view;
4039 int *pack_fds = NULL;
4041 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4042 switch (ch) {
4043 case 'b':
4044 log_branches = 1;
4045 break;
4046 case 'c':
4047 start_commit = optarg;
4048 break;
4049 case 'r':
4050 repo_path = realpath(optarg, NULL);
4051 if (repo_path == NULL)
4052 return got_error_from_errno2("realpath",
4053 optarg);
4054 break;
4055 default:
4056 usage_log();
4057 /* NOTREACHED */
4061 argc -= optind;
4062 argv += optind;
4064 if (argc > 1)
4065 usage_log();
4067 error = got_repo_pack_fds_open(&pack_fds);
4068 if (error != NULL)
4069 goto done;
4071 if (repo_path == NULL) {
4072 cwd = getcwd(NULL, 0);
4073 if (cwd == NULL)
4074 return got_error_from_errno("getcwd");
4075 error = got_worktree_open(&worktree, cwd);
4076 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4077 goto done;
4078 if (worktree)
4079 repo_path =
4080 strdup(got_worktree_get_repo_path(worktree));
4081 else
4082 repo_path = strdup(cwd);
4083 if (repo_path == NULL) {
4084 error = got_error_from_errno("strdup");
4085 goto done;
4089 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4090 if (error != NULL)
4091 goto done;
4093 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4094 repo, worktree);
4095 if (error)
4096 goto done;
4098 init_curses();
4100 error = apply_unveil(got_repo_get_path(repo),
4101 worktree ? got_worktree_get_root_path(worktree) : NULL);
4102 if (error)
4103 goto done;
4105 /* already loaded by tog_log_with_path()? */
4106 if (TAILQ_EMPTY(&tog_refs)) {
4107 error = tog_load_refs(repo, 0);
4108 if (error)
4109 goto done;
4112 if (start_commit == NULL) {
4113 error = got_repo_match_object_id(&start_id, &label,
4114 worktree ? got_worktree_get_head_ref_name(worktree) :
4115 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4116 if (error)
4117 goto done;
4118 head_ref_name = label;
4119 } else {
4120 error = got_ref_open(&ref, repo, start_commit, 0);
4121 if (error == NULL)
4122 head_ref_name = got_ref_get_name(ref);
4123 else if (error->code != GOT_ERR_NOT_REF)
4124 goto done;
4125 error = got_repo_match_object_id(&start_id, NULL,
4126 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4127 if (error)
4128 goto done;
4131 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4132 if (view == NULL) {
4133 error = got_error_from_errno("view_open");
4134 goto done;
4136 error = open_log_view(view, start_id, repo, head_ref_name,
4137 in_repo_path, log_branches);
4138 if (error)
4139 goto done;
4140 if (worktree) {
4141 /* Release work tree lock. */
4142 got_worktree_close(worktree);
4143 worktree = NULL;
4145 error = view_loop(view);
4146 done:
4147 free(in_repo_path);
4148 free(repo_path);
4149 free(cwd);
4150 free(start_id);
4151 free(label);
4152 if (ref)
4153 got_ref_close(ref);
4154 if (repo) {
4155 const struct got_error *close_err = got_repo_close(repo);
4156 if (error == NULL)
4157 error = close_err;
4159 if (worktree)
4160 got_worktree_close(worktree);
4161 if (pack_fds) {
4162 const struct got_error *pack_err =
4163 got_repo_pack_fds_close(pack_fds);
4164 if (error == NULL)
4165 error = pack_err;
4167 tog_free_refs();
4168 return error;
4171 __dead static void
4172 usage_diff(void)
4174 endwin();
4175 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4176 "object1 object2\n", getprogname());
4177 exit(1);
4180 static int
4181 match_line(const char *line, regex_t *regex, size_t nmatch,
4182 regmatch_t *regmatch)
4184 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4187 static struct tog_color *
4188 match_color(struct tog_colors *colors, const char *line)
4190 struct tog_color *tc = NULL;
4192 STAILQ_FOREACH(tc, colors, entry) {
4193 if (match_line(line, &tc->regex, 0, NULL))
4194 return tc;
4197 return NULL;
4200 static const struct got_error *
4201 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4202 WINDOW *window, int skipcol, regmatch_t *regmatch)
4204 const struct got_error *err = NULL;
4205 char *exstr = NULL;
4206 wchar_t *wline = NULL;
4207 int rme, rms, n, width, scrollx;
4208 int width0 = 0, width1 = 0, width2 = 0;
4209 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4211 *wtotal = 0;
4213 rms = regmatch->rm_so;
4214 rme = regmatch->rm_eo;
4216 err = expand_tab(&exstr, line);
4217 if (err)
4218 return err;
4220 /* Split the line into 3 segments, according to match offsets. */
4221 seg0 = strndup(exstr, rms);
4222 if (seg0 == NULL) {
4223 err = got_error_from_errno("strndup");
4224 goto done;
4226 seg1 = strndup(exstr + rms, rme - rms);
4227 if (seg1 == NULL) {
4228 err = got_error_from_errno("strndup");
4229 goto done;
4231 seg2 = strdup(exstr + rme);
4232 if (seg2 == NULL) {
4233 err = got_error_from_errno("strndup");
4234 goto done;
4237 /* draw up to matched token if we haven't scrolled past it */
4238 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4239 col_tab_align, 1);
4240 if (err)
4241 goto done;
4242 n = MAX(width0 - skipcol, 0);
4243 if (n) {
4244 free(wline);
4245 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4246 wlimit, col_tab_align, 1);
4247 if (err)
4248 goto done;
4249 waddwstr(window, &wline[scrollx]);
4250 wlimit -= width;
4251 *wtotal += width;
4254 if (wlimit > 0) {
4255 int i = 0, w = 0;
4256 size_t wlen;
4258 free(wline);
4259 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4260 col_tab_align, 1);
4261 if (err)
4262 goto done;
4263 wlen = wcslen(wline);
4264 while (i < wlen) {
4265 width = wcwidth(wline[i]);
4266 if (width == -1) {
4267 /* should not happen, tabs are expanded */
4268 err = got_error(GOT_ERR_RANGE);
4269 goto done;
4271 if (width0 + w + width > skipcol)
4272 break;
4273 w += width;
4274 i++;
4276 /* draw (visible part of) matched token (if scrolled into it) */
4277 if (width1 - w > 0) {
4278 wattron(window, A_STANDOUT);
4279 waddwstr(window, &wline[i]);
4280 wattroff(window, A_STANDOUT);
4281 wlimit -= (width1 - w);
4282 *wtotal += (width1 - w);
4286 if (wlimit > 0) { /* draw rest of line */
4287 free(wline);
4288 if (skipcol > width0 + width1) {
4289 err = format_line(&wline, &width2, &scrollx, seg2,
4290 skipcol - (width0 + width1), wlimit,
4291 col_tab_align, 1);
4292 if (err)
4293 goto done;
4294 waddwstr(window, &wline[scrollx]);
4295 } else {
4296 err = format_line(&wline, &width2, NULL, seg2, 0,
4297 wlimit, col_tab_align, 1);
4298 if (err)
4299 goto done;
4300 waddwstr(window, wline);
4302 *wtotal += width2;
4304 done:
4305 free(wline);
4306 free(exstr);
4307 free(seg0);
4308 free(seg1);
4309 free(seg2);
4310 return err;
4313 static int
4314 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4316 FILE *f = NULL;
4317 int *eof, *first, *selected;
4319 if (view->type == TOG_VIEW_DIFF) {
4320 struct tog_diff_view_state *s = &view->state.diff;
4322 first = &s->first_displayed_line;
4323 selected = first;
4324 eof = &s->eof;
4325 f = s->f;
4326 } else if (view->type == TOG_VIEW_HELP) {
4327 struct tog_help_view_state *s = &view->state.help;
4329 first = &s->first_displayed_line;
4330 selected = first;
4331 eof = &s->eof;
4332 f = s->f;
4333 } else if (view->type == TOG_VIEW_BLAME) {
4334 struct tog_blame_view_state *s = &view->state.blame;
4336 first = &s->first_displayed_line;
4337 selected = &s->selected_line;
4338 eof = &s->eof;
4339 f = s->blame.f;
4340 } else
4341 return 0;
4343 /* Center gline in the middle of the page like vi(1). */
4344 if (*lineno < view->gline - (view->nlines - 3) / 2)
4345 return 0;
4346 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4347 rewind(f);
4348 *eof = 0;
4349 *first = 1;
4350 *lineno = 0;
4351 *nprinted = 0;
4352 return 0;
4355 *selected = view->gline <= (view->nlines - 3) / 2 ?
4356 view->gline : (view->nlines - 3) / 2 + 1;
4357 view->gline = 0;
4359 return 1;
4362 static const struct got_error *
4363 draw_file(struct tog_view *view, const char *header)
4365 struct tog_diff_view_state *s = &view->state.diff;
4366 regmatch_t *regmatch = &view->regmatch;
4367 const struct got_error *err;
4368 int nprinted = 0;
4369 char *line;
4370 size_t linesize = 0;
4371 ssize_t linelen;
4372 wchar_t *wline;
4373 int width;
4374 int max_lines = view->nlines;
4375 int nlines = s->nlines;
4376 off_t line_offset;
4378 s->lineno = s->first_displayed_line - 1;
4379 line_offset = s->lines[s->first_displayed_line - 1].offset;
4380 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4381 return got_error_from_errno("fseek");
4383 werase(view->window);
4385 if (view->gline > s->nlines - 1)
4386 view->gline = s->nlines - 1;
4388 if (header) {
4389 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4390 1 : view->gline - (view->nlines - 3) / 2 :
4391 s->lineno + s->selected_line;
4393 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4394 return got_error_from_errno("asprintf");
4395 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4396 0, 0);
4397 free(line);
4398 if (err)
4399 return err;
4401 if (view_needs_focus_indication(view))
4402 wstandout(view->window);
4403 waddwstr(view->window, wline);
4404 free(wline);
4405 wline = NULL;
4406 while (width++ < view->ncols)
4407 waddch(view->window, ' ');
4408 if (view_needs_focus_indication(view))
4409 wstandend(view->window);
4411 if (max_lines <= 1)
4412 return NULL;
4413 max_lines--;
4416 s->eof = 0;
4417 view->maxx = 0;
4418 line = NULL;
4419 while (max_lines > 0 && nprinted < max_lines) {
4420 enum got_diff_line_type linetype;
4421 attr_t attr = 0;
4423 linelen = getline(&line, &linesize, s->f);
4424 if (linelen == -1) {
4425 if (feof(s->f)) {
4426 s->eof = 1;
4427 break;
4429 free(line);
4430 return got_ferror(s->f, GOT_ERR_IO);
4433 if (++s->lineno < s->first_displayed_line)
4434 continue;
4435 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4436 continue;
4437 if (s->lineno == view->hiline)
4438 attr = A_STANDOUT;
4440 /* Set view->maxx based on full line length. */
4441 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4442 view->x ? 1 : 0);
4443 if (err) {
4444 free(line);
4445 return err;
4447 view->maxx = MAX(view->maxx, width);
4448 free(wline);
4449 wline = NULL;
4451 linetype = s->lines[s->lineno].type;
4452 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4453 linetype < GOT_DIFF_LINE_CONTEXT)
4454 attr |= COLOR_PAIR(linetype);
4455 if (attr)
4456 wattron(view->window, attr);
4457 if (s->first_displayed_line + nprinted == s->matched_line &&
4458 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4459 err = add_matched_line(&width, line, view->ncols, 0,
4460 view->window, view->x, regmatch);
4461 if (err) {
4462 free(line);
4463 return err;
4465 } else {
4466 int skip;
4467 err = format_line(&wline, &width, &skip, line,
4468 view->x, view->ncols, 0, view->x ? 1 : 0);
4469 if (err) {
4470 free(line);
4471 return err;
4473 waddwstr(view->window, &wline[skip]);
4474 free(wline);
4475 wline = NULL;
4477 if (s->lineno == view->hiline) {
4478 /* highlight full gline length */
4479 while (width++ < view->ncols)
4480 waddch(view->window, ' ');
4481 } else {
4482 if (width <= view->ncols - 1)
4483 waddch(view->window, '\n');
4485 if (attr)
4486 wattroff(view->window, attr);
4487 if (++nprinted == 1)
4488 s->first_displayed_line = s->lineno;
4490 free(line);
4491 if (nprinted >= 1)
4492 s->last_displayed_line = s->first_displayed_line +
4493 (nprinted - 1);
4494 else
4495 s->last_displayed_line = s->first_displayed_line;
4497 view_border(view);
4499 if (s->eof) {
4500 while (nprinted < view->nlines) {
4501 waddch(view->window, '\n');
4502 nprinted++;
4505 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4506 view->ncols, 0, 0);
4507 if (err) {
4508 return err;
4511 wstandout(view->window);
4512 waddwstr(view->window, wline);
4513 free(wline);
4514 wline = NULL;
4515 wstandend(view->window);
4518 return NULL;
4521 static char *
4522 get_datestr(time_t *time, char *datebuf)
4524 struct tm mytm, *tm;
4525 char *p, *s;
4527 tm = gmtime_r(time, &mytm);
4528 if (tm == NULL)
4529 return NULL;
4530 s = asctime_r(tm, datebuf);
4531 if (s == NULL)
4532 return NULL;
4533 p = strchr(s, '\n');
4534 if (p)
4535 *p = '\0';
4536 return s;
4539 static const struct got_error *
4540 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4541 off_t off, uint8_t type)
4543 struct got_diff_line *p;
4545 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4546 if (p == NULL)
4547 return got_error_from_errno("reallocarray");
4548 *lines = p;
4549 (*lines)[*nlines].offset = off;
4550 (*lines)[*nlines].type = type;
4551 (*nlines)++;
4553 return NULL;
4556 static const struct got_error *
4557 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4558 struct got_diff_line *s_lines, size_t s_nlines)
4560 struct got_diff_line *p;
4561 char buf[BUFSIZ];
4562 size_t i, r;
4564 if (fseeko(src, 0L, SEEK_SET) == -1)
4565 return got_error_from_errno("fseeko");
4567 for (;;) {
4568 r = fread(buf, 1, sizeof(buf), src);
4569 if (r == 0) {
4570 if (ferror(src))
4571 return got_error_from_errno("fread");
4572 if (feof(src))
4573 break;
4575 if (fwrite(buf, 1, r, dst) != r)
4576 return got_ferror(dst, GOT_ERR_IO);
4580 * The diff driver initialises the first line at offset zero when the
4581 * array isn't prepopulated, skip it; we already have it in *d_lines.
4583 for (i = 1; i < s_nlines; ++i)
4584 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4586 --s_nlines;
4588 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4589 if (p == NULL) {
4590 /* d_lines is freed in close_diff_view() */
4591 return got_error_from_errno("reallocarray");
4594 *d_lines = p;
4596 memcpy(*d_lines + *d_nlines, s_lines + 1, s_nlines * sizeof(*s_lines));
4597 *d_nlines += s_nlines;
4599 return NULL;
4602 static const struct got_error *
4603 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4604 struct got_object_id *commit_id, struct got_reflist_head *refs,
4605 struct got_repository *repo, int ignore_ws, int force_text_diff,
4606 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4608 const struct got_error *err = NULL;
4609 char datebuf[26], *datestr;
4610 struct got_commit_object *commit;
4611 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4612 time_t committer_time;
4613 const char *author, *committer;
4614 char *refs_str = NULL;
4615 struct got_pathlist_entry *pe;
4616 off_t outoff = 0;
4617 int n;
4619 if (refs) {
4620 err = build_refs_str(&refs_str, refs, commit_id, repo);
4621 if (err)
4622 return err;
4625 err = got_object_open_as_commit(&commit, repo, commit_id);
4626 if (err)
4627 return err;
4629 err = got_object_id_str(&id_str, commit_id);
4630 if (err) {
4631 err = got_error_from_errno("got_object_id_str");
4632 goto done;
4635 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4636 if (err)
4637 goto done;
4639 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4640 refs_str ? refs_str : "", refs_str ? ")" : "");
4641 if (n < 0) {
4642 err = got_error_from_errno("fprintf");
4643 goto done;
4645 outoff += n;
4646 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4647 if (err)
4648 goto done;
4650 n = fprintf(outfile, "from: %s\n",
4651 got_object_commit_get_author(commit));
4652 if (n < 0) {
4653 err = got_error_from_errno("fprintf");
4654 goto done;
4656 outoff += n;
4657 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4658 if (err)
4659 goto done;
4661 author = got_object_commit_get_author(commit);
4662 committer = got_object_commit_get_committer(commit);
4663 if (strcmp(author, committer) != 0) {
4664 n = fprintf(outfile, "via: %s\n", committer);
4665 if (n < 0) {
4666 err = got_error_from_errno("fprintf");
4667 goto done;
4669 outoff += n;
4670 err = add_line_metadata(lines, nlines, outoff,
4671 GOT_DIFF_LINE_AUTHOR);
4672 if (err)
4673 goto done;
4675 committer_time = got_object_commit_get_committer_time(commit);
4676 datestr = get_datestr(&committer_time, datebuf);
4677 if (datestr) {
4678 n = fprintf(outfile, "date: %s UTC\n", datestr);
4679 if (n < 0) {
4680 err = got_error_from_errno("fprintf");
4681 goto done;
4683 outoff += n;
4684 err = add_line_metadata(lines, nlines, outoff,
4685 GOT_DIFF_LINE_DATE);
4686 if (err)
4687 goto done;
4689 if (got_object_commit_get_nparents(commit) > 1) {
4690 const struct got_object_id_queue *parent_ids;
4691 struct got_object_qid *qid;
4692 int pn = 1;
4693 parent_ids = got_object_commit_get_parent_ids(commit);
4694 STAILQ_FOREACH(qid, parent_ids, entry) {
4695 err = got_object_id_str(&id_str, &qid->id);
4696 if (err)
4697 goto done;
4698 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4699 if (n < 0) {
4700 err = got_error_from_errno("fprintf");
4701 goto done;
4703 outoff += n;
4704 err = add_line_metadata(lines, nlines, outoff,
4705 GOT_DIFF_LINE_META);
4706 if (err)
4707 goto done;
4708 free(id_str);
4709 id_str = NULL;
4713 err = got_object_commit_get_logmsg(&logmsg, commit);
4714 if (err)
4715 goto done;
4716 s = logmsg;
4717 while ((line = strsep(&s, "\n")) != NULL) {
4718 n = fprintf(outfile, "%s\n", line);
4719 if (n < 0) {
4720 err = got_error_from_errno("fprintf");
4721 goto done;
4723 outoff += n;
4724 err = add_line_metadata(lines, nlines, outoff,
4725 GOT_DIFF_LINE_LOGMSG);
4726 if (err)
4727 goto done;
4730 TAILQ_FOREACH(pe, dsa->paths, entry) {
4731 struct got_diff_changed_path *cp = pe->data;
4732 int pad = dsa->max_path_len - pe->path_len + 1;
4734 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4735 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4736 dsa->rm_cols + 1, cp->rm);
4737 if (n < 0) {
4738 err = got_error_from_errno("fprintf");
4739 goto done;
4741 outoff += n;
4742 err = add_line_metadata(lines, nlines, outoff,
4743 GOT_DIFF_LINE_CHANGES);
4744 if (err)
4745 goto done;
4748 fputc('\n', outfile);
4749 outoff++;
4750 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4751 if (err)
4752 goto done;
4754 n = fprintf(outfile,
4755 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4756 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4757 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4758 if (n < 0) {
4759 err = got_error_from_errno("fprintf");
4760 goto done;
4762 outoff += n;
4763 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4764 if (err)
4765 goto done;
4767 fputc('\n', outfile);
4768 outoff++;
4769 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4770 done:
4771 free(id_str);
4772 free(logmsg);
4773 free(refs_str);
4774 got_object_commit_close(commit);
4775 if (err) {
4776 free(*lines);
4777 *lines = NULL;
4778 *nlines = 0;
4780 return err;
4783 static const struct got_error *
4784 create_diff(struct tog_diff_view_state *s)
4786 const struct got_error *err = NULL;
4787 FILE *f = NULL, *tmp_diff_file = NULL;
4788 int obj_type;
4789 struct got_diff_line *lines = NULL;
4790 struct got_pathlist_head changed_paths;
4792 TAILQ_INIT(&changed_paths);
4794 free(s->lines);
4795 s->lines = malloc(sizeof(*s->lines));
4796 if (s->lines == NULL)
4797 return got_error_from_errno("malloc");
4798 s->nlines = 0;
4800 f = got_opentemp();
4801 if (f == NULL) {
4802 err = got_error_from_errno("got_opentemp");
4803 goto done;
4805 tmp_diff_file = got_opentemp();
4806 if (tmp_diff_file == NULL) {
4807 err = got_error_from_errno("got_opentemp");
4808 goto done;
4810 if (s->f && fclose(s->f) == EOF) {
4811 err = got_error_from_errno("fclose");
4812 goto done;
4814 s->f = f;
4816 if (s->id1)
4817 err = got_object_get_type(&obj_type, s->repo, s->id1);
4818 else
4819 err = got_object_get_type(&obj_type, s->repo, s->id2);
4820 if (err)
4821 goto done;
4823 switch (obj_type) {
4824 case GOT_OBJ_TYPE_BLOB:
4825 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4826 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4827 s->label1, s->label2, tog_diff_algo, s->diff_context,
4828 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
4829 s->f);
4830 break;
4831 case GOT_OBJ_TYPE_TREE:
4832 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4833 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4834 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4835 s->force_text_diff, NULL, s->repo, s->f);
4836 break;
4837 case GOT_OBJ_TYPE_COMMIT: {
4838 const struct got_object_id_queue *parent_ids;
4839 struct got_object_qid *pid;
4840 struct got_commit_object *commit2;
4841 struct got_reflist_head *refs;
4842 size_t nlines = 0;
4843 struct got_diffstat_cb_arg dsa = {
4844 0, 0, 0, 0, 0, 0,
4845 &changed_paths,
4846 s->ignore_whitespace,
4847 s->force_text_diff,
4848 tog_diff_algo
4851 lines = malloc(sizeof(*lines));
4852 if (lines == NULL) {
4853 err = got_error_from_errno("malloc");
4854 goto done;
4857 /* build diff first in tmp file then append to commit info */
4858 err = got_diff_objects_as_commits(&lines, &nlines,
4859 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4860 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4861 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
4862 if (err)
4863 break;
4865 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4866 if (err)
4867 goto done;
4868 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4869 /* Show commit info if we're diffing to a parent/root commit. */
4870 if (s->id1 == NULL) {
4871 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4872 refs, s->repo, s->ignore_whitespace,
4873 s->force_text_diff, &dsa, s->f);
4874 if (err)
4875 goto done;
4876 } else {
4877 parent_ids = got_object_commit_get_parent_ids(commit2);
4878 STAILQ_FOREACH(pid, parent_ids, entry) {
4879 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4880 err = write_commit_info(&s->lines,
4881 &s->nlines, s->id2, refs, s->repo,
4882 s->ignore_whitespace,
4883 s->force_text_diff, &dsa, s->f);
4884 if (err)
4885 goto done;
4886 break;
4890 got_object_commit_close(commit2);
4892 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
4893 lines, nlines);
4894 break;
4896 default:
4897 err = got_error(GOT_ERR_OBJ_TYPE);
4898 break;
4900 done:
4901 free(lines);
4902 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4903 if (s->f && fflush(s->f) != 0 && err == NULL)
4904 err = got_error_from_errno("fflush");
4905 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
4906 err = got_error_from_errno("fclose");
4907 return err;
4910 static void
4911 diff_view_indicate_progress(struct tog_view *view)
4913 mvwaddstr(view->window, 0, 0, "diffing...");
4914 update_panels();
4915 doupdate();
4918 static const struct got_error *
4919 search_start_diff_view(struct tog_view *view)
4921 struct tog_diff_view_state *s = &view->state.diff;
4923 s->matched_line = 0;
4924 return NULL;
4927 static void
4928 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4929 size_t *nlines, int **first, int **last, int **match, int **selected)
4931 struct tog_diff_view_state *s = &view->state.diff;
4933 *f = s->f;
4934 *nlines = s->nlines;
4935 *line_offsets = NULL;
4936 *match = &s->matched_line;
4937 *first = &s->first_displayed_line;
4938 *last = &s->last_displayed_line;
4939 *selected = &s->selected_line;
4942 static const struct got_error *
4943 search_next_view_match(struct tog_view *view)
4945 const struct got_error *err = NULL;
4946 FILE *f;
4947 int lineno;
4948 char *line = NULL;
4949 size_t linesize = 0;
4950 ssize_t linelen;
4951 off_t *line_offsets;
4952 size_t nlines = 0;
4953 int *first, *last, *match, *selected;
4955 if (!view->search_setup)
4956 return got_error_msg(GOT_ERR_NOT_IMPL,
4957 "view search not supported");
4958 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4959 &match, &selected);
4961 if (!view->searching) {
4962 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4963 return NULL;
4966 if (*match) {
4967 if (view->searching == TOG_SEARCH_FORWARD)
4968 lineno = *match + 1;
4969 else
4970 lineno = *match - 1;
4971 } else
4972 lineno = *first - 1 + *selected;
4974 while (1) {
4975 off_t offset;
4977 if (lineno <= 0 || lineno > nlines) {
4978 if (*match == 0) {
4979 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4980 break;
4983 if (view->searching == TOG_SEARCH_FORWARD)
4984 lineno = 1;
4985 else
4986 lineno = nlines;
4989 offset = view->type == TOG_VIEW_DIFF ?
4990 view->state.diff.lines[lineno - 1].offset :
4991 line_offsets[lineno - 1];
4992 if (fseeko(f, offset, SEEK_SET) != 0) {
4993 free(line);
4994 return got_error_from_errno("fseeko");
4996 linelen = getline(&line, &linesize, f);
4997 if (linelen != -1) {
4998 char *exstr;
4999 err = expand_tab(&exstr, line);
5000 if (err)
5001 break;
5002 if (match_line(exstr, &view->regex, 1,
5003 &view->regmatch)) {
5004 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5005 *match = lineno;
5006 free(exstr);
5007 break;
5009 free(exstr);
5011 if (view->searching == TOG_SEARCH_FORWARD)
5012 lineno++;
5013 else
5014 lineno--;
5016 free(line);
5018 if (*match) {
5019 *first = *match;
5020 *selected = 1;
5023 return err;
5026 static const struct got_error *
5027 close_diff_view(struct tog_view *view)
5029 const struct got_error *err = NULL;
5030 struct tog_diff_view_state *s = &view->state.diff;
5032 free(s->id1);
5033 s->id1 = NULL;
5034 free(s->id2);
5035 s->id2 = NULL;
5036 if (s->f && fclose(s->f) == EOF)
5037 err = got_error_from_errno("fclose");
5038 s->f = NULL;
5039 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5040 err = got_error_from_errno("fclose");
5041 s->f1 = NULL;
5042 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5043 err = got_error_from_errno("fclose");
5044 s->f2 = NULL;
5045 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5046 err = got_error_from_errno("close");
5047 s->fd1 = -1;
5048 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5049 err = got_error_from_errno("close");
5050 s->fd2 = -1;
5051 free(s->lines);
5052 s->lines = NULL;
5053 s->nlines = 0;
5054 return err;
5057 static const struct got_error *
5058 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5059 struct got_object_id *id2, const char *label1, const char *label2,
5060 int diff_context, int ignore_whitespace, int force_text_diff,
5061 struct tog_view *parent_view, struct got_repository *repo)
5063 const struct got_error *err;
5064 struct tog_diff_view_state *s = &view->state.diff;
5066 memset(s, 0, sizeof(*s));
5067 s->fd1 = -1;
5068 s->fd2 = -1;
5070 if (id1 != NULL && id2 != NULL) {
5071 int type1, type2;
5072 err = got_object_get_type(&type1, repo, id1);
5073 if (err)
5074 return err;
5075 err = got_object_get_type(&type2, repo, id2);
5076 if (err)
5077 return err;
5079 if (type1 != type2)
5080 return got_error(GOT_ERR_OBJ_TYPE);
5082 s->first_displayed_line = 1;
5083 s->last_displayed_line = view->nlines;
5084 s->selected_line = 1;
5085 s->repo = repo;
5086 s->id1 = id1;
5087 s->id2 = id2;
5088 s->label1 = label1;
5089 s->label2 = label2;
5091 if (id1) {
5092 s->id1 = got_object_id_dup(id1);
5093 if (s->id1 == NULL)
5094 return got_error_from_errno("got_object_id_dup");
5095 } else
5096 s->id1 = NULL;
5098 s->id2 = got_object_id_dup(id2);
5099 if (s->id2 == NULL) {
5100 err = got_error_from_errno("got_object_id_dup");
5101 goto done;
5104 s->f1 = got_opentemp();
5105 if (s->f1 == NULL) {
5106 err = got_error_from_errno("got_opentemp");
5107 goto done;
5110 s->f2 = got_opentemp();
5111 if (s->f2 == NULL) {
5112 err = got_error_from_errno("got_opentemp");
5113 goto done;
5116 s->fd1 = got_opentempfd();
5117 if (s->fd1 == -1) {
5118 err = got_error_from_errno("got_opentempfd");
5119 goto done;
5122 s->fd2 = got_opentempfd();
5123 if (s->fd2 == -1) {
5124 err = got_error_from_errno("got_opentempfd");
5125 goto done;
5128 s->diff_context = diff_context;
5129 s->ignore_whitespace = ignore_whitespace;
5130 s->force_text_diff = force_text_diff;
5131 s->parent_view = parent_view;
5132 s->repo = repo;
5134 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5135 int rc;
5137 rc = init_pair(GOT_DIFF_LINE_MINUS,
5138 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5139 if (rc != ERR)
5140 rc = init_pair(GOT_DIFF_LINE_PLUS,
5141 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5142 if (rc != ERR)
5143 rc = init_pair(GOT_DIFF_LINE_HUNK,
5144 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5145 if (rc != ERR)
5146 rc = init_pair(GOT_DIFF_LINE_META,
5147 get_color_value("TOG_COLOR_DIFF_META"), -1);
5148 if (rc != ERR)
5149 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5150 get_color_value("TOG_COLOR_DIFF_META"), -1);
5151 if (rc != ERR)
5152 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5153 get_color_value("TOG_COLOR_DIFF_META"), -1);
5154 if (rc != ERR)
5155 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5156 get_color_value("TOG_COLOR_DIFF_META"), -1);
5157 if (rc != ERR)
5158 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5159 get_color_value("TOG_COLOR_AUTHOR"), -1);
5160 if (rc != ERR)
5161 rc = init_pair(GOT_DIFF_LINE_DATE,
5162 get_color_value("TOG_COLOR_DATE"), -1);
5163 if (rc == ERR) {
5164 err = got_error(GOT_ERR_RANGE);
5165 goto done;
5169 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5170 view_is_splitscreen(view))
5171 show_log_view(parent_view); /* draw border */
5172 diff_view_indicate_progress(view);
5174 err = create_diff(s);
5176 view->show = show_diff_view;
5177 view->input = input_diff_view;
5178 view->reset = reset_diff_view;
5179 view->close = close_diff_view;
5180 view->search_start = search_start_diff_view;
5181 view->search_setup = search_setup_diff_view;
5182 view->search_next = search_next_view_match;
5183 done:
5184 if (err)
5185 close_diff_view(view);
5186 return err;
5189 static const struct got_error *
5190 show_diff_view(struct tog_view *view)
5192 const struct got_error *err;
5193 struct tog_diff_view_state *s = &view->state.diff;
5194 char *id_str1 = NULL, *id_str2, *header;
5195 const char *label1, *label2;
5197 if (s->id1) {
5198 err = got_object_id_str(&id_str1, s->id1);
5199 if (err)
5200 return err;
5201 label1 = s->label1 ? s->label1 : id_str1;
5202 } else
5203 label1 = "/dev/null";
5205 err = got_object_id_str(&id_str2, s->id2);
5206 if (err)
5207 return err;
5208 label2 = s->label2 ? s->label2 : id_str2;
5210 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5211 err = got_error_from_errno("asprintf");
5212 free(id_str1);
5213 free(id_str2);
5214 return err;
5216 free(id_str1);
5217 free(id_str2);
5219 err = draw_file(view, header);
5220 free(header);
5221 return err;
5224 static const struct got_error *
5225 set_selected_commit(struct tog_diff_view_state *s,
5226 struct commit_queue_entry *entry)
5228 const struct got_error *err;
5229 const struct got_object_id_queue *parent_ids;
5230 struct got_commit_object *selected_commit;
5231 struct got_object_qid *pid;
5233 free(s->id2);
5234 s->id2 = got_object_id_dup(entry->id);
5235 if (s->id2 == NULL)
5236 return got_error_from_errno("got_object_id_dup");
5238 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5239 if (err)
5240 return err;
5241 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5242 free(s->id1);
5243 pid = STAILQ_FIRST(parent_ids);
5244 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5245 got_object_commit_close(selected_commit);
5246 return NULL;
5249 static const struct got_error *
5250 reset_diff_view(struct tog_view *view)
5252 struct tog_diff_view_state *s = &view->state.diff;
5254 view->count = 0;
5255 wclear(view->window);
5256 s->first_displayed_line = 1;
5257 s->last_displayed_line = view->nlines;
5258 s->matched_line = 0;
5259 diff_view_indicate_progress(view);
5260 return create_diff(s);
5263 static void
5264 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5266 int start, i;
5268 i = start = s->first_displayed_line - 1;
5270 while (s->lines[i].type != type) {
5271 if (i == 0)
5272 i = s->nlines - 1;
5273 if (--i == start)
5274 return; /* do nothing, requested type not in file */
5277 s->selected_line = 1;
5278 s->first_displayed_line = i;
5281 static void
5282 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5284 int start, i;
5286 i = start = s->first_displayed_line + 1;
5288 while (s->lines[i].type != type) {
5289 if (i == s->nlines - 1)
5290 i = 0;
5291 if (++i == start)
5292 return; /* do nothing, requested type not in file */
5295 s->selected_line = 1;
5296 s->first_displayed_line = i;
5299 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5300 int, int, int);
5301 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5302 int, int);
5304 static const struct got_error *
5305 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5307 const struct got_error *err = NULL;
5308 struct tog_diff_view_state *s = &view->state.diff;
5309 struct tog_log_view_state *ls;
5310 struct commit_queue_entry *old_selected_entry;
5311 char *line = NULL;
5312 size_t linesize = 0;
5313 ssize_t linelen;
5314 int i, nscroll = view->nlines - 1, up = 0;
5316 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5318 switch (ch) {
5319 case '0':
5320 case '$':
5321 case KEY_RIGHT:
5322 case 'l':
5323 case KEY_LEFT:
5324 case 'h':
5325 horizontal_scroll_input(view, ch);
5326 break;
5327 case 'a':
5328 case 'w':
5329 if (ch == 'a') {
5330 s->force_text_diff = !s->force_text_diff;
5331 view->action = s->force_text_diff ?
5332 "force ASCII text enabled" :
5333 "force ASCII text disabled";
5335 else if (ch == 'w') {
5336 s->ignore_whitespace = !s->ignore_whitespace;
5337 view->action = s->ignore_whitespace ?
5338 "ignore whitespace enabled" :
5339 "ignore whitespace disabled";
5341 err = reset_diff_view(view);
5342 break;
5343 case 'g':
5344 case KEY_HOME:
5345 s->first_displayed_line = 1;
5346 view->count = 0;
5347 break;
5348 case 'G':
5349 case KEY_END:
5350 view->count = 0;
5351 if (s->eof)
5352 break;
5354 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5355 s->eof = 1;
5356 break;
5357 case 'k':
5358 case KEY_UP:
5359 case CTRL('p'):
5360 if (s->first_displayed_line > 1)
5361 s->first_displayed_line--;
5362 else
5363 view->count = 0;
5364 break;
5365 case CTRL('u'):
5366 case 'u':
5367 nscroll /= 2;
5368 /* FALL THROUGH */
5369 case KEY_PPAGE:
5370 case CTRL('b'):
5371 case 'b':
5372 if (s->first_displayed_line == 1) {
5373 view->count = 0;
5374 break;
5376 i = 0;
5377 while (i++ < nscroll && s->first_displayed_line > 1)
5378 s->first_displayed_line--;
5379 break;
5380 case 'j':
5381 case KEY_DOWN:
5382 case CTRL('n'):
5383 if (!s->eof)
5384 s->first_displayed_line++;
5385 else
5386 view->count = 0;
5387 break;
5388 case CTRL('d'):
5389 case 'd':
5390 nscroll /= 2;
5391 /* FALL THROUGH */
5392 case KEY_NPAGE:
5393 case CTRL('f'):
5394 case 'f':
5395 case ' ':
5396 if (s->eof) {
5397 view->count = 0;
5398 break;
5400 i = 0;
5401 while (!s->eof && i++ < nscroll) {
5402 linelen = getline(&line, &linesize, s->f);
5403 s->first_displayed_line++;
5404 if (linelen == -1) {
5405 if (feof(s->f)) {
5406 s->eof = 1;
5407 } else
5408 err = got_ferror(s->f, GOT_ERR_IO);
5409 break;
5412 free(line);
5413 break;
5414 case '(':
5415 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5416 break;
5417 case ')':
5418 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5419 break;
5420 case '{':
5421 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5422 break;
5423 case '}':
5424 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5425 break;
5426 case '[':
5427 if (s->diff_context > 0) {
5428 s->diff_context--;
5429 s->matched_line = 0;
5430 diff_view_indicate_progress(view);
5431 err = create_diff(s);
5432 if (s->first_displayed_line + view->nlines - 1 >
5433 s->nlines) {
5434 s->first_displayed_line = 1;
5435 s->last_displayed_line = view->nlines;
5437 } else
5438 view->count = 0;
5439 break;
5440 case ']':
5441 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5442 s->diff_context++;
5443 s->matched_line = 0;
5444 diff_view_indicate_progress(view);
5445 err = create_diff(s);
5446 } else
5447 view->count = 0;
5448 break;
5449 case '<':
5450 case ',':
5451 case 'K':
5452 up = 1;
5453 /* FALL THROUGH */
5454 case '>':
5455 case '.':
5456 case 'J':
5457 if (s->parent_view == NULL) {
5458 view->count = 0;
5459 break;
5461 s->parent_view->count = view->count;
5463 if (s->parent_view->type == TOG_VIEW_LOG) {
5464 ls = &s->parent_view->state.log;
5465 old_selected_entry = ls->selected_entry;
5467 err = input_log_view(NULL, s->parent_view,
5468 up ? KEY_UP : KEY_DOWN);
5469 if (err)
5470 break;
5471 view->count = s->parent_view->count;
5473 if (old_selected_entry == ls->selected_entry)
5474 break;
5476 err = set_selected_commit(s, ls->selected_entry);
5477 if (err)
5478 break;
5479 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5480 struct tog_blame_view_state *bs;
5481 struct got_object_id *id, *prev_id;
5483 bs = &s->parent_view->state.blame;
5484 prev_id = get_annotation_for_line(bs->blame.lines,
5485 bs->blame.nlines, bs->last_diffed_line);
5487 err = input_blame_view(&view, s->parent_view,
5488 up ? KEY_UP : KEY_DOWN);
5489 if (err)
5490 break;
5491 view->count = s->parent_view->count;
5493 if (prev_id == NULL)
5494 break;
5495 id = get_selected_commit_id(bs->blame.lines,
5496 bs->blame.nlines, bs->first_displayed_line,
5497 bs->selected_line);
5498 if (id == NULL)
5499 break;
5501 if (!got_object_id_cmp(prev_id, id))
5502 break;
5504 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5505 if (err)
5506 break;
5508 s->first_displayed_line = 1;
5509 s->last_displayed_line = view->nlines;
5510 s->matched_line = 0;
5511 view->x = 0;
5513 diff_view_indicate_progress(view);
5514 err = create_diff(s);
5515 break;
5516 default:
5517 view->count = 0;
5518 break;
5521 return err;
5524 static const struct got_error *
5525 cmd_diff(int argc, char *argv[])
5527 const struct got_error *error = NULL;
5528 struct got_repository *repo = NULL;
5529 struct got_worktree *worktree = NULL;
5530 struct got_object_id *id1 = NULL, *id2 = NULL;
5531 char *repo_path = NULL, *cwd = NULL;
5532 char *id_str1 = NULL, *id_str2 = NULL;
5533 char *label1 = NULL, *label2 = NULL;
5534 int diff_context = 3, ignore_whitespace = 0;
5535 int ch, force_text_diff = 0;
5536 const char *errstr;
5537 struct tog_view *view;
5538 int *pack_fds = NULL;
5540 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5541 switch (ch) {
5542 case 'a':
5543 force_text_diff = 1;
5544 break;
5545 case 'C':
5546 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5547 &errstr);
5548 if (errstr != NULL)
5549 errx(1, "number of context lines is %s: %s",
5550 errstr, errstr);
5551 break;
5552 case 'r':
5553 repo_path = realpath(optarg, NULL);
5554 if (repo_path == NULL)
5555 return got_error_from_errno2("realpath",
5556 optarg);
5557 got_path_strip_trailing_slashes(repo_path);
5558 break;
5559 case 'w':
5560 ignore_whitespace = 1;
5561 break;
5562 default:
5563 usage_diff();
5564 /* NOTREACHED */
5568 argc -= optind;
5569 argv += optind;
5571 if (argc == 0) {
5572 usage_diff(); /* TODO show local worktree changes */
5573 } else if (argc == 2) {
5574 id_str1 = argv[0];
5575 id_str2 = argv[1];
5576 } else
5577 usage_diff();
5579 error = got_repo_pack_fds_open(&pack_fds);
5580 if (error)
5581 goto done;
5583 if (repo_path == NULL) {
5584 cwd = getcwd(NULL, 0);
5585 if (cwd == NULL)
5586 return got_error_from_errno("getcwd");
5587 error = got_worktree_open(&worktree, cwd);
5588 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5589 goto done;
5590 if (worktree)
5591 repo_path =
5592 strdup(got_worktree_get_repo_path(worktree));
5593 else
5594 repo_path = strdup(cwd);
5595 if (repo_path == NULL) {
5596 error = got_error_from_errno("strdup");
5597 goto done;
5601 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5602 if (error)
5603 goto done;
5605 init_curses();
5607 error = apply_unveil(got_repo_get_path(repo), NULL);
5608 if (error)
5609 goto done;
5611 error = tog_load_refs(repo, 0);
5612 if (error)
5613 goto done;
5615 error = got_repo_match_object_id(&id1, &label1, id_str1,
5616 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5617 if (error)
5618 goto done;
5620 error = got_repo_match_object_id(&id2, &label2, id_str2,
5621 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5622 if (error)
5623 goto done;
5625 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5626 if (view == NULL) {
5627 error = got_error_from_errno("view_open");
5628 goto done;
5630 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5631 ignore_whitespace, force_text_diff, NULL, repo);
5632 if (error)
5633 goto done;
5634 error = view_loop(view);
5635 done:
5636 free(label1);
5637 free(label2);
5638 free(repo_path);
5639 free(cwd);
5640 if (repo) {
5641 const struct got_error *close_err = got_repo_close(repo);
5642 if (error == NULL)
5643 error = close_err;
5645 if (worktree)
5646 got_worktree_close(worktree);
5647 if (pack_fds) {
5648 const struct got_error *pack_err =
5649 got_repo_pack_fds_close(pack_fds);
5650 if (error == NULL)
5651 error = pack_err;
5653 tog_free_refs();
5654 return error;
5657 __dead static void
5658 usage_blame(void)
5660 endwin();
5661 fprintf(stderr,
5662 "usage: %s blame [-c commit] [-r repository-path] path\n",
5663 getprogname());
5664 exit(1);
5667 struct tog_blame_line {
5668 int annotated;
5669 struct got_object_id *id;
5672 static const struct got_error *
5673 draw_blame(struct tog_view *view)
5675 struct tog_blame_view_state *s = &view->state.blame;
5676 struct tog_blame *blame = &s->blame;
5677 regmatch_t *regmatch = &view->regmatch;
5678 const struct got_error *err;
5679 int lineno = 0, nprinted = 0;
5680 char *line = NULL;
5681 size_t linesize = 0;
5682 ssize_t linelen;
5683 wchar_t *wline;
5684 int width;
5685 struct tog_blame_line *blame_line;
5686 struct got_object_id *prev_id = NULL;
5687 char *id_str;
5688 struct tog_color *tc;
5690 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5691 if (err)
5692 return err;
5694 rewind(blame->f);
5695 werase(view->window);
5697 if (asprintf(&line, "commit %s", id_str) == -1) {
5698 err = got_error_from_errno("asprintf");
5699 free(id_str);
5700 return err;
5703 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5704 free(line);
5705 line = NULL;
5706 if (err)
5707 return err;
5708 if (view_needs_focus_indication(view))
5709 wstandout(view->window);
5710 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5711 if (tc)
5712 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5713 waddwstr(view->window, wline);
5714 while (width++ < view->ncols)
5715 waddch(view->window, ' ');
5716 if (tc)
5717 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5718 if (view_needs_focus_indication(view))
5719 wstandend(view->window);
5720 free(wline);
5721 wline = NULL;
5723 if (view->gline > blame->nlines)
5724 view->gline = blame->nlines;
5726 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5727 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5728 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5729 free(id_str);
5730 return got_error_from_errno("asprintf");
5732 free(id_str);
5733 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5734 free(line);
5735 line = NULL;
5736 if (err)
5737 return err;
5738 waddwstr(view->window, wline);
5739 free(wline);
5740 wline = NULL;
5741 if (width < view->ncols - 1)
5742 waddch(view->window, '\n');
5744 s->eof = 0;
5745 view->maxx = 0;
5746 while (nprinted < view->nlines - 2) {
5747 linelen = getline(&line, &linesize, blame->f);
5748 if (linelen == -1) {
5749 if (feof(blame->f)) {
5750 s->eof = 1;
5751 break;
5753 free(line);
5754 return got_ferror(blame->f, GOT_ERR_IO);
5756 if (++lineno < s->first_displayed_line)
5757 continue;
5758 if (view->gline && !gotoline(view, &lineno, &nprinted))
5759 continue;
5761 /* Set view->maxx based on full line length. */
5762 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5763 if (err) {
5764 free(line);
5765 return err;
5767 free(wline);
5768 wline = NULL;
5769 view->maxx = MAX(view->maxx, width);
5771 if (nprinted == s->selected_line - 1)
5772 wstandout(view->window);
5774 if (blame->nlines > 0) {
5775 blame_line = &blame->lines[lineno - 1];
5776 if (blame_line->annotated && prev_id &&
5777 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5778 !(nprinted == s->selected_line - 1)) {
5779 waddstr(view->window, " ");
5780 } else if (blame_line->annotated) {
5781 char *id_str;
5782 err = got_object_id_str(&id_str,
5783 blame_line->id);
5784 if (err) {
5785 free(line);
5786 return err;
5788 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5789 if (tc)
5790 wattr_on(view->window,
5791 COLOR_PAIR(tc->colorpair), NULL);
5792 wprintw(view->window, "%.8s", id_str);
5793 if (tc)
5794 wattr_off(view->window,
5795 COLOR_PAIR(tc->colorpair), NULL);
5796 free(id_str);
5797 prev_id = blame_line->id;
5798 } else {
5799 waddstr(view->window, "........");
5800 prev_id = NULL;
5802 } else {
5803 waddstr(view->window, "........");
5804 prev_id = NULL;
5807 if (nprinted == s->selected_line - 1)
5808 wstandend(view->window);
5809 waddstr(view->window, " ");
5811 if (view->ncols <= 9) {
5812 width = 9;
5813 } else if (s->first_displayed_line + nprinted ==
5814 s->matched_line &&
5815 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5816 err = add_matched_line(&width, line, view->ncols - 9, 9,
5817 view->window, view->x, regmatch);
5818 if (err) {
5819 free(line);
5820 return err;
5822 width += 9;
5823 } else {
5824 int skip;
5825 err = format_line(&wline, &width, &skip, line,
5826 view->x, view->ncols - 9, 9, 1);
5827 if (err) {
5828 free(line);
5829 return err;
5831 waddwstr(view->window, &wline[skip]);
5832 width += 9;
5833 free(wline);
5834 wline = NULL;
5837 if (width <= view->ncols - 1)
5838 waddch(view->window, '\n');
5839 if (++nprinted == 1)
5840 s->first_displayed_line = lineno;
5842 free(line);
5843 s->last_displayed_line = lineno;
5845 view_border(view);
5847 return NULL;
5850 static const struct got_error *
5851 blame_cb(void *arg, int nlines, int lineno,
5852 struct got_commit_object *commit, struct got_object_id *id)
5854 const struct got_error *err = NULL;
5855 struct tog_blame_cb_args *a = arg;
5856 struct tog_blame_line *line;
5857 int errcode;
5859 if (nlines != a->nlines ||
5860 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5861 return got_error(GOT_ERR_RANGE);
5863 errcode = pthread_mutex_lock(&tog_mutex);
5864 if (errcode)
5865 return got_error_set_errno(errcode, "pthread_mutex_lock");
5867 if (*a->quit) { /* user has quit the blame view */
5868 err = got_error(GOT_ERR_ITER_COMPLETED);
5869 goto done;
5872 if (lineno == -1)
5873 goto done; /* no change in this commit */
5875 line = &a->lines[lineno - 1];
5876 if (line->annotated)
5877 goto done;
5879 line->id = got_object_id_dup(id);
5880 if (line->id == NULL) {
5881 err = got_error_from_errno("got_object_id_dup");
5882 goto done;
5884 line->annotated = 1;
5885 done:
5886 errcode = pthread_mutex_unlock(&tog_mutex);
5887 if (errcode)
5888 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5889 return err;
5892 static void *
5893 blame_thread(void *arg)
5895 const struct got_error *err, *close_err;
5896 struct tog_blame_thread_args *ta = arg;
5897 struct tog_blame_cb_args *a = ta->cb_args;
5898 int errcode, fd1 = -1, fd2 = -1;
5899 FILE *f1 = NULL, *f2 = NULL;
5901 fd1 = got_opentempfd();
5902 if (fd1 == -1)
5903 return (void *)got_error_from_errno("got_opentempfd");
5905 fd2 = got_opentempfd();
5906 if (fd2 == -1) {
5907 err = got_error_from_errno("got_opentempfd");
5908 goto done;
5911 f1 = got_opentemp();
5912 if (f1 == NULL) {
5913 err = (void *)got_error_from_errno("got_opentemp");
5914 goto done;
5916 f2 = got_opentemp();
5917 if (f2 == NULL) {
5918 err = (void *)got_error_from_errno("got_opentemp");
5919 goto done;
5922 err = block_signals_used_by_main_thread();
5923 if (err)
5924 goto done;
5926 err = got_blame(ta->path, a->commit_id, ta->repo,
5927 tog_diff_algo, blame_cb, ta->cb_args,
5928 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5929 if (err && err->code == GOT_ERR_CANCELLED)
5930 err = NULL;
5932 errcode = pthread_mutex_lock(&tog_mutex);
5933 if (errcode) {
5934 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5935 goto done;
5938 close_err = got_repo_close(ta->repo);
5939 if (err == NULL)
5940 err = close_err;
5941 ta->repo = NULL;
5942 *ta->complete = 1;
5944 errcode = pthread_mutex_unlock(&tog_mutex);
5945 if (errcode && err == NULL)
5946 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5948 done:
5949 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5950 err = got_error_from_errno("close");
5951 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5952 err = got_error_from_errno("close");
5953 if (f1 && fclose(f1) == EOF && err == NULL)
5954 err = got_error_from_errno("fclose");
5955 if (f2 && fclose(f2) == EOF && err == NULL)
5956 err = got_error_from_errno("fclose");
5958 return (void *)err;
5961 static struct got_object_id *
5962 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5963 int first_displayed_line, int selected_line)
5965 struct tog_blame_line *line;
5967 if (nlines <= 0)
5968 return NULL;
5970 line = &lines[first_displayed_line - 1 + selected_line - 1];
5971 if (!line->annotated)
5972 return NULL;
5974 return line->id;
5977 static struct got_object_id *
5978 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5979 int lineno)
5981 struct tog_blame_line *line;
5983 if (nlines <= 0 || lineno >= nlines)
5984 return NULL;
5986 line = &lines[lineno - 1];
5987 if (!line->annotated)
5988 return NULL;
5990 return line->id;
5993 static const struct got_error *
5994 stop_blame(struct tog_blame *blame)
5996 const struct got_error *err = NULL;
5997 int i;
5999 if (blame->thread) {
6000 int errcode;
6001 errcode = pthread_mutex_unlock(&tog_mutex);
6002 if (errcode)
6003 return got_error_set_errno(errcode,
6004 "pthread_mutex_unlock");
6005 errcode = pthread_join(blame->thread, (void **)&err);
6006 if (errcode)
6007 return got_error_set_errno(errcode, "pthread_join");
6008 errcode = pthread_mutex_lock(&tog_mutex);
6009 if (errcode)
6010 return got_error_set_errno(errcode,
6011 "pthread_mutex_lock");
6012 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6013 err = NULL;
6014 blame->thread = NULL;
6016 if (blame->thread_args.repo) {
6017 const struct got_error *close_err;
6018 close_err = got_repo_close(blame->thread_args.repo);
6019 if (err == NULL)
6020 err = close_err;
6021 blame->thread_args.repo = NULL;
6023 if (blame->f) {
6024 if (fclose(blame->f) == EOF && err == NULL)
6025 err = got_error_from_errno("fclose");
6026 blame->f = NULL;
6028 if (blame->lines) {
6029 for (i = 0; i < blame->nlines; i++)
6030 free(blame->lines[i].id);
6031 free(blame->lines);
6032 blame->lines = NULL;
6034 free(blame->cb_args.commit_id);
6035 blame->cb_args.commit_id = NULL;
6036 if (blame->pack_fds) {
6037 const struct got_error *pack_err =
6038 got_repo_pack_fds_close(blame->pack_fds);
6039 if (err == NULL)
6040 err = pack_err;
6041 blame->pack_fds = NULL;
6043 return err;
6046 static const struct got_error *
6047 cancel_blame_view(void *arg)
6049 const struct got_error *err = NULL;
6050 int *done = arg;
6051 int errcode;
6053 errcode = pthread_mutex_lock(&tog_mutex);
6054 if (errcode)
6055 return got_error_set_errno(errcode,
6056 "pthread_mutex_unlock");
6058 if (*done)
6059 err = got_error(GOT_ERR_CANCELLED);
6061 errcode = pthread_mutex_unlock(&tog_mutex);
6062 if (errcode)
6063 return got_error_set_errno(errcode,
6064 "pthread_mutex_lock");
6066 return err;
6069 static const struct got_error *
6070 run_blame(struct tog_view *view)
6072 struct tog_blame_view_state *s = &view->state.blame;
6073 struct tog_blame *blame = &s->blame;
6074 const struct got_error *err = NULL;
6075 struct got_commit_object *commit = NULL;
6076 struct got_blob_object *blob = NULL;
6077 struct got_repository *thread_repo = NULL;
6078 struct got_object_id *obj_id = NULL;
6079 int obj_type, fd = -1;
6080 int *pack_fds = NULL;
6082 err = got_object_open_as_commit(&commit, s->repo,
6083 &s->blamed_commit->id);
6084 if (err)
6085 return err;
6087 fd = got_opentempfd();
6088 if (fd == -1) {
6089 err = got_error_from_errno("got_opentempfd");
6090 goto done;
6093 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6094 if (err)
6095 goto done;
6097 err = got_object_get_type(&obj_type, s->repo, obj_id);
6098 if (err)
6099 goto done;
6101 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6102 err = got_error(GOT_ERR_OBJ_TYPE);
6103 goto done;
6106 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6107 if (err)
6108 goto done;
6109 blame->f = got_opentemp();
6110 if (blame->f == NULL) {
6111 err = got_error_from_errno("got_opentemp");
6112 goto done;
6114 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6115 &blame->line_offsets, blame->f, blob);
6116 if (err)
6117 goto done;
6118 if (blame->nlines == 0) {
6119 s->blame_complete = 1;
6120 goto done;
6123 /* Don't include \n at EOF in the blame line count. */
6124 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6125 blame->nlines--;
6127 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6128 if (blame->lines == NULL) {
6129 err = got_error_from_errno("calloc");
6130 goto done;
6133 err = got_repo_pack_fds_open(&pack_fds);
6134 if (err)
6135 goto done;
6136 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6137 pack_fds);
6138 if (err)
6139 goto done;
6141 blame->pack_fds = pack_fds;
6142 blame->cb_args.view = view;
6143 blame->cb_args.lines = blame->lines;
6144 blame->cb_args.nlines = blame->nlines;
6145 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6146 if (blame->cb_args.commit_id == NULL) {
6147 err = got_error_from_errno("got_object_id_dup");
6148 goto done;
6150 blame->cb_args.quit = &s->done;
6152 blame->thread_args.path = s->path;
6153 blame->thread_args.repo = thread_repo;
6154 blame->thread_args.cb_args = &blame->cb_args;
6155 blame->thread_args.complete = &s->blame_complete;
6156 blame->thread_args.cancel_cb = cancel_blame_view;
6157 blame->thread_args.cancel_arg = &s->done;
6158 s->blame_complete = 0;
6160 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6161 s->first_displayed_line = 1;
6162 s->last_displayed_line = view->nlines;
6163 s->selected_line = 1;
6165 s->matched_line = 0;
6167 done:
6168 if (commit)
6169 got_object_commit_close(commit);
6170 if (fd != -1 && close(fd) == -1 && err == NULL)
6171 err = got_error_from_errno("close");
6172 if (blob)
6173 got_object_blob_close(blob);
6174 free(obj_id);
6175 if (err)
6176 stop_blame(blame);
6177 return err;
6180 static const struct got_error *
6181 open_blame_view(struct tog_view *view, char *path,
6182 struct got_object_id *commit_id, struct got_repository *repo)
6184 const struct got_error *err = NULL;
6185 struct tog_blame_view_state *s = &view->state.blame;
6187 STAILQ_INIT(&s->blamed_commits);
6189 s->path = strdup(path);
6190 if (s->path == NULL)
6191 return got_error_from_errno("strdup");
6193 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6194 if (err) {
6195 free(s->path);
6196 return err;
6199 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6200 s->first_displayed_line = 1;
6201 s->last_displayed_line = view->nlines;
6202 s->selected_line = 1;
6203 s->blame_complete = 0;
6204 s->repo = repo;
6205 s->commit_id = commit_id;
6206 memset(&s->blame, 0, sizeof(s->blame));
6208 STAILQ_INIT(&s->colors);
6209 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6210 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6211 get_color_value("TOG_COLOR_COMMIT"));
6212 if (err)
6213 return err;
6216 view->show = show_blame_view;
6217 view->input = input_blame_view;
6218 view->reset = reset_blame_view;
6219 view->close = close_blame_view;
6220 view->search_start = search_start_blame_view;
6221 view->search_setup = search_setup_blame_view;
6222 view->search_next = search_next_view_match;
6224 return run_blame(view);
6227 static const struct got_error *
6228 close_blame_view(struct tog_view *view)
6230 const struct got_error *err = NULL;
6231 struct tog_blame_view_state *s = &view->state.blame;
6233 if (s->blame.thread)
6234 err = stop_blame(&s->blame);
6236 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6237 struct got_object_qid *blamed_commit;
6238 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6239 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6240 got_object_qid_free(blamed_commit);
6243 free(s->path);
6244 free_colors(&s->colors);
6245 return err;
6248 static const struct got_error *
6249 search_start_blame_view(struct tog_view *view)
6251 struct tog_blame_view_state *s = &view->state.blame;
6253 s->matched_line = 0;
6254 return NULL;
6257 static void
6258 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6259 size_t *nlines, int **first, int **last, int **match, int **selected)
6261 struct tog_blame_view_state *s = &view->state.blame;
6263 *f = s->blame.f;
6264 *nlines = s->blame.nlines;
6265 *line_offsets = s->blame.line_offsets;
6266 *match = &s->matched_line;
6267 *first = &s->first_displayed_line;
6268 *last = &s->last_displayed_line;
6269 *selected = &s->selected_line;
6272 static const struct got_error *
6273 show_blame_view(struct tog_view *view)
6275 const struct got_error *err = NULL;
6276 struct tog_blame_view_state *s = &view->state.blame;
6277 int errcode;
6279 if (s->blame.thread == NULL && !s->blame_complete) {
6280 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6281 &s->blame.thread_args);
6282 if (errcode)
6283 return got_error_set_errno(errcode, "pthread_create");
6285 halfdelay(1); /* fast refresh while annotating */
6288 if (s->blame_complete)
6289 halfdelay(10); /* disable fast refresh */
6291 err = draw_blame(view);
6293 view_border(view);
6294 return err;
6297 static const struct got_error *
6298 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6299 struct got_repository *repo, struct got_object_id *id)
6301 struct tog_view *log_view;
6302 const struct got_error *err = NULL;
6304 *new_view = NULL;
6306 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6307 if (log_view == NULL)
6308 return got_error_from_errno("view_open");
6310 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6311 if (err)
6312 view_close(log_view);
6313 else
6314 *new_view = log_view;
6316 return err;
6319 static const struct got_error *
6320 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6322 const struct got_error *err = NULL, *thread_err = NULL;
6323 struct tog_view *diff_view;
6324 struct tog_blame_view_state *s = &view->state.blame;
6325 int eos, nscroll, begin_y = 0, begin_x = 0;
6327 eos = nscroll = view->nlines - 2;
6328 if (view_is_hsplit_top(view))
6329 --eos; /* border */
6331 switch (ch) {
6332 case '0':
6333 case '$':
6334 case KEY_RIGHT:
6335 case 'l':
6336 case KEY_LEFT:
6337 case 'h':
6338 horizontal_scroll_input(view, ch);
6339 break;
6340 case 'q':
6341 s->done = 1;
6342 break;
6343 case 'g':
6344 case KEY_HOME:
6345 s->selected_line = 1;
6346 s->first_displayed_line = 1;
6347 view->count = 0;
6348 break;
6349 case 'G':
6350 case KEY_END:
6351 if (s->blame.nlines < eos) {
6352 s->selected_line = s->blame.nlines;
6353 s->first_displayed_line = 1;
6354 } else {
6355 s->selected_line = eos;
6356 s->first_displayed_line = s->blame.nlines - (eos - 1);
6358 view->count = 0;
6359 break;
6360 case 'k':
6361 case KEY_UP:
6362 case CTRL('p'):
6363 if (s->selected_line > 1)
6364 s->selected_line--;
6365 else if (s->selected_line == 1 &&
6366 s->first_displayed_line > 1)
6367 s->first_displayed_line--;
6368 else
6369 view->count = 0;
6370 break;
6371 case CTRL('u'):
6372 case 'u':
6373 nscroll /= 2;
6374 /* FALL THROUGH */
6375 case KEY_PPAGE:
6376 case CTRL('b'):
6377 case 'b':
6378 if (s->first_displayed_line == 1) {
6379 if (view->count > 1)
6380 nscroll += nscroll;
6381 s->selected_line = MAX(1, s->selected_line - nscroll);
6382 view->count = 0;
6383 break;
6385 if (s->first_displayed_line > nscroll)
6386 s->first_displayed_line -= nscroll;
6387 else
6388 s->first_displayed_line = 1;
6389 break;
6390 case 'j':
6391 case KEY_DOWN:
6392 case CTRL('n'):
6393 if (s->selected_line < eos && s->first_displayed_line +
6394 s->selected_line <= s->blame.nlines)
6395 s->selected_line++;
6396 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6397 s->first_displayed_line++;
6398 else
6399 view->count = 0;
6400 break;
6401 case 'c':
6402 case 'p': {
6403 struct got_object_id *id = NULL;
6405 view->count = 0;
6406 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6407 s->first_displayed_line, s->selected_line);
6408 if (id == NULL)
6409 break;
6410 if (ch == 'p') {
6411 struct got_commit_object *commit, *pcommit;
6412 struct got_object_qid *pid;
6413 struct got_object_id *blob_id = NULL;
6414 int obj_type;
6415 err = got_object_open_as_commit(&commit,
6416 s->repo, id);
6417 if (err)
6418 break;
6419 pid = STAILQ_FIRST(
6420 got_object_commit_get_parent_ids(commit));
6421 if (pid == NULL) {
6422 got_object_commit_close(commit);
6423 break;
6425 /* Check if path history ends here. */
6426 err = got_object_open_as_commit(&pcommit,
6427 s->repo, &pid->id);
6428 if (err)
6429 break;
6430 err = got_object_id_by_path(&blob_id, s->repo,
6431 pcommit, s->path);
6432 got_object_commit_close(pcommit);
6433 if (err) {
6434 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6435 err = NULL;
6436 got_object_commit_close(commit);
6437 break;
6439 err = got_object_get_type(&obj_type, s->repo,
6440 blob_id);
6441 free(blob_id);
6442 /* Can't blame non-blob type objects. */
6443 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6444 got_object_commit_close(commit);
6445 break;
6447 err = got_object_qid_alloc(&s->blamed_commit,
6448 &pid->id);
6449 got_object_commit_close(commit);
6450 } else {
6451 if (got_object_id_cmp(id,
6452 &s->blamed_commit->id) == 0)
6453 break;
6454 err = got_object_qid_alloc(&s->blamed_commit,
6455 id);
6457 if (err)
6458 break;
6459 s->done = 1;
6460 thread_err = stop_blame(&s->blame);
6461 s->done = 0;
6462 if (thread_err)
6463 break;
6464 STAILQ_INSERT_HEAD(&s->blamed_commits,
6465 s->blamed_commit, entry);
6466 err = run_blame(view);
6467 if (err)
6468 break;
6469 break;
6471 case 'C': {
6472 struct got_object_qid *first;
6474 view->count = 0;
6475 first = STAILQ_FIRST(&s->blamed_commits);
6476 if (!got_object_id_cmp(&first->id, s->commit_id))
6477 break;
6478 s->done = 1;
6479 thread_err = stop_blame(&s->blame);
6480 s->done = 0;
6481 if (thread_err)
6482 break;
6483 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6484 got_object_qid_free(s->blamed_commit);
6485 s->blamed_commit =
6486 STAILQ_FIRST(&s->blamed_commits);
6487 err = run_blame(view);
6488 if (err)
6489 break;
6490 break;
6492 case 'L':
6493 view->count = 0;
6494 s->id_to_log = get_selected_commit_id(s->blame.lines,
6495 s->blame.nlines, s->first_displayed_line, s->selected_line);
6496 if (s->id_to_log)
6497 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6498 break;
6499 case KEY_ENTER:
6500 case '\r': {
6501 struct got_object_id *id = NULL;
6502 struct got_object_qid *pid;
6503 struct got_commit_object *commit = NULL;
6505 view->count = 0;
6506 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6507 s->first_displayed_line, s->selected_line);
6508 if (id == NULL)
6509 break;
6510 err = got_object_open_as_commit(&commit, s->repo, id);
6511 if (err)
6512 break;
6513 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6514 if (*new_view) {
6515 /* traversed from diff view, release diff resources */
6516 err = close_diff_view(*new_view);
6517 if (err)
6518 break;
6519 diff_view = *new_view;
6520 } else {
6521 if (view_is_parent_view(view))
6522 view_get_split(view, &begin_y, &begin_x);
6524 diff_view = view_open(0, 0, begin_y, begin_x,
6525 TOG_VIEW_DIFF);
6526 if (diff_view == NULL) {
6527 got_object_commit_close(commit);
6528 err = got_error_from_errno("view_open");
6529 break;
6532 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6533 id, NULL, NULL, 3, 0, 0, view, s->repo);
6534 got_object_commit_close(commit);
6535 if (err) {
6536 view_close(diff_view);
6537 break;
6539 s->last_diffed_line = s->first_displayed_line - 1 +
6540 s->selected_line;
6541 if (*new_view)
6542 break; /* still open from active diff view */
6543 if (view_is_parent_view(view) &&
6544 view->mode == TOG_VIEW_SPLIT_HRZN) {
6545 err = view_init_hsplit(view, begin_y);
6546 if (err)
6547 break;
6550 view->focussed = 0;
6551 diff_view->focussed = 1;
6552 diff_view->mode = view->mode;
6553 diff_view->nlines = view->lines - begin_y;
6554 if (view_is_parent_view(view)) {
6555 view_transfer_size(diff_view, view);
6556 err = view_close_child(view);
6557 if (err)
6558 break;
6559 err = view_set_child(view, diff_view);
6560 if (err)
6561 break;
6562 view->focus_child = 1;
6563 } else
6564 *new_view = diff_view;
6565 if (err)
6566 break;
6567 break;
6569 case CTRL('d'):
6570 case 'd':
6571 nscroll /= 2;
6572 /* FALL THROUGH */
6573 case KEY_NPAGE:
6574 case CTRL('f'):
6575 case 'f':
6576 case ' ':
6577 if (s->last_displayed_line >= s->blame.nlines &&
6578 s->selected_line >= MIN(s->blame.nlines,
6579 view->nlines - 2)) {
6580 view->count = 0;
6581 break;
6583 if (s->last_displayed_line >= s->blame.nlines &&
6584 s->selected_line < view->nlines - 2) {
6585 s->selected_line +=
6586 MIN(nscroll, s->last_displayed_line -
6587 s->first_displayed_line - s->selected_line + 1);
6589 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6590 s->first_displayed_line += nscroll;
6591 else
6592 s->first_displayed_line =
6593 s->blame.nlines - (view->nlines - 3);
6594 break;
6595 case KEY_RESIZE:
6596 if (s->selected_line > view->nlines - 2) {
6597 s->selected_line = MIN(s->blame.nlines,
6598 view->nlines - 2);
6600 break;
6601 default:
6602 view->count = 0;
6603 break;
6605 return thread_err ? thread_err : err;
6608 static const struct got_error *
6609 reset_blame_view(struct tog_view *view)
6611 const struct got_error *err;
6612 struct tog_blame_view_state *s = &view->state.blame;
6614 view->count = 0;
6615 s->done = 1;
6616 err = stop_blame(&s->blame);
6617 s->done = 0;
6618 if (err)
6619 return err;
6620 return run_blame(view);
6623 static const struct got_error *
6624 cmd_blame(int argc, char *argv[])
6626 const struct got_error *error;
6627 struct got_repository *repo = NULL;
6628 struct got_worktree *worktree = NULL;
6629 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6630 char *link_target = NULL;
6631 struct got_object_id *commit_id = NULL;
6632 struct got_commit_object *commit = NULL;
6633 char *commit_id_str = NULL;
6634 int ch;
6635 struct tog_view *view;
6636 int *pack_fds = NULL;
6638 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6639 switch (ch) {
6640 case 'c':
6641 commit_id_str = optarg;
6642 break;
6643 case 'r':
6644 repo_path = realpath(optarg, NULL);
6645 if (repo_path == NULL)
6646 return got_error_from_errno2("realpath",
6647 optarg);
6648 break;
6649 default:
6650 usage_blame();
6651 /* NOTREACHED */
6655 argc -= optind;
6656 argv += optind;
6658 if (argc != 1)
6659 usage_blame();
6661 error = got_repo_pack_fds_open(&pack_fds);
6662 if (error != NULL)
6663 goto done;
6665 if (repo_path == NULL) {
6666 cwd = getcwd(NULL, 0);
6667 if (cwd == NULL)
6668 return got_error_from_errno("getcwd");
6669 error = got_worktree_open(&worktree, cwd);
6670 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6671 goto done;
6672 if (worktree)
6673 repo_path =
6674 strdup(got_worktree_get_repo_path(worktree));
6675 else
6676 repo_path = strdup(cwd);
6677 if (repo_path == NULL) {
6678 error = got_error_from_errno("strdup");
6679 goto done;
6683 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6684 if (error != NULL)
6685 goto done;
6687 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6688 worktree);
6689 if (error)
6690 goto done;
6692 init_curses();
6694 error = apply_unveil(got_repo_get_path(repo), NULL);
6695 if (error)
6696 goto done;
6698 error = tog_load_refs(repo, 0);
6699 if (error)
6700 goto done;
6702 if (commit_id_str == NULL) {
6703 struct got_reference *head_ref;
6704 error = got_ref_open(&head_ref, repo, worktree ?
6705 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6706 if (error != NULL)
6707 goto done;
6708 error = got_ref_resolve(&commit_id, repo, head_ref);
6709 got_ref_close(head_ref);
6710 } else {
6711 error = got_repo_match_object_id(&commit_id, NULL,
6712 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6714 if (error != NULL)
6715 goto done;
6717 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6718 if (view == NULL) {
6719 error = got_error_from_errno("view_open");
6720 goto done;
6723 error = got_object_open_as_commit(&commit, repo, commit_id);
6724 if (error)
6725 goto done;
6727 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6728 commit, repo);
6729 if (error)
6730 goto done;
6732 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6733 commit_id, repo);
6734 if (error)
6735 goto done;
6736 if (worktree) {
6737 /* Release work tree lock. */
6738 got_worktree_close(worktree);
6739 worktree = NULL;
6741 error = view_loop(view);
6742 done:
6743 free(repo_path);
6744 free(in_repo_path);
6745 free(link_target);
6746 free(cwd);
6747 free(commit_id);
6748 if (commit)
6749 got_object_commit_close(commit);
6750 if (worktree)
6751 got_worktree_close(worktree);
6752 if (repo) {
6753 const struct got_error *close_err = got_repo_close(repo);
6754 if (error == NULL)
6755 error = close_err;
6757 if (pack_fds) {
6758 const struct got_error *pack_err =
6759 got_repo_pack_fds_close(pack_fds);
6760 if (error == NULL)
6761 error = pack_err;
6763 tog_free_refs();
6764 return error;
6767 static const struct got_error *
6768 draw_tree_entries(struct tog_view *view, const char *parent_path)
6770 struct tog_tree_view_state *s = &view->state.tree;
6771 const struct got_error *err = NULL;
6772 struct got_tree_entry *te;
6773 wchar_t *wline;
6774 char *index = NULL;
6775 struct tog_color *tc;
6776 int width, n, nentries, scrollx, i = 1;
6777 int limit = view->nlines;
6779 s->ndisplayed = 0;
6780 if (view_is_hsplit_top(view))
6781 --limit; /* border */
6783 werase(view->window);
6785 if (limit == 0)
6786 return NULL;
6788 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6789 0, 0);
6790 if (err)
6791 return err;
6792 if (view_needs_focus_indication(view))
6793 wstandout(view->window);
6794 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6795 if (tc)
6796 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6797 waddwstr(view->window, wline);
6798 free(wline);
6799 wline = NULL;
6800 while (width++ < view->ncols)
6801 waddch(view->window, ' ');
6802 if (tc)
6803 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6804 if (view_needs_focus_indication(view))
6805 wstandend(view->window);
6806 if (--limit <= 0)
6807 return NULL;
6809 i += s->selected;
6810 if (s->first_displayed_entry) {
6811 i += got_tree_entry_get_index(s->first_displayed_entry);
6812 if (s->tree != s->root)
6813 ++i; /* account for ".." entry */
6815 nentries = got_object_tree_get_nentries(s->tree);
6816 if (asprintf(&index, "[%d/%d] %s",
6817 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6818 return got_error_from_errno("asprintf");
6819 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6820 free(index);
6821 if (err)
6822 return err;
6823 waddwstr(view->window, wline);
6824 free(wline);
6825 wline = NULL;
6826 if (width < view->ncols - 1)
6827 waddch(view->window, '\n');
6828 if (--limit <= 0)
6829 return NULL;
6830 waddch(view->window, '\n');
6831 if (--limit <= 0)
6832 return NULL;
6834 if (s->first_displayed_entry == NULL) {
6835 te = got_object_tree_get_first_entry(s->tree);
6836 if (s->selected == 0) {
6837 if (view->focussed)
6838 wstandout(view->window);
6839 s->selected_entry = NULL;
6841 waddstr(view->window, " ..\n"); /* parent directory */
6842 if (s->selected == 0 && view->focussed)
6843 wstandend(view->window);
6844 s->ndisplayed++;
6845 if (--limit <= 0)
6846 return NULL;
6847 n = 1;
6848 } else {
6849 n = 0;
6850 te = s->first_displayed_entry;
6853 view->maxx = 0;
6854 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6855 char *line = NULL, *id_str = NULL, *link_target = NULL;
6856 const char *modestr = "";
6857 mode_t mode;
6859 te = got_object_tree_get_entry(s->tree, i);
6860 mode = got_tree_entry_get_mode(te);
6862 if (s->show_ids) {
6863 err = got_object_id_str(&id_str,
6864 got_tree_entry_get_id(te));
6865 if (err)
6866 return got_error_from_errno(
6867 "got_object_id_str");
6869 if (got_object_tree_entry_is_submodule(te))
6870 modestr = "$";
6871 else if (S_ISLNK(mode)) {
6872 int i;
6874 err = got_tree_entry_get_symlink_target(&link_target,
6875 te, s->repo);
6876 if (err) {
6877 free(id_str);
6878 return err;
6880 for (i = 0; i < strlen(link_target); i++) {
6881 if (!isprint((unsigned char)link_target[i]))
6882 link_target[i] = '?';
6884 modestr = "@";
6886 else if (S_ISDIR(mode))
6887 modestr = "/";
6888 else if (mode & S_IXUSR)
6889 modestr = "*";
6890 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6891 got_tree_entry_get_name(te), modestr,
6892 link_target ? " -> ": "",
6893 link_target ? link_target : "") == -1) {
6894 free(id_str);
6895 free(link_target);
6896 return got_error_from_errno("asprintf");
6898 free(id_str);
6899 free(link_target);
6901 /* use full line width to determine view->maxx */
6902 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
6903 if (err) {
6904 free(line);
6905 break;
6907 view->maxx = MAX(view->maxx, width);
6908 free(wline);
6909 wline = NULL;
6911 err = format_line(&wline, &width, &scrollx, line, view->x,
6912 view->ncols, 0, 0);
6913 if (err) {
6914 free(line);
6915 break;
6917 if (n == s->selected) {
6918 if (view->focussed)
6919 wstandout(view->window);
6920 s->selected_entry = te;
6922 tc = match_color(&s->colors, line);
6923 if (tc)
6924 wattr_on(view->window,
6925 COLOR_PAIR(tc->colorpair), NULL);
6926 waddwstr(view->window, &wline[scrollx]);
6927 if (tc)
6928 wattr_off(view->window,
6929 COLOR_PAIR(tc->colorpair), NULL);
6930 if (width < view->ncols)
6931 waddch(view->window, '\n');
6932 if (n == s->selected && view->focussed)
6933 wstandend(view->window);
6934 free(line);
6935 free(wline);
6936 wline = NULL;
6937 n++;
6938 s->ndisplayed++;
6939 s->last_displayed_entry = te;
6940 if (--limit <= 0)
6941 break;
6944 return err;
6947 static void
6948 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6950 struct got_tree_entry *te;
6951 int isroot = s->tree == s->root;
6952 int i = 0;
6954 if (s->first_displayed_entry == NULL)
6955 return;
6957 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6958 while (i++ < maxscroll) {
6959 if (te == NULL) {
6960 if (!isroot)
6961 s->first_displayed_entry = NULL;
6962 break;
6964 s->first_displayed_entry = te;
6965 te = got_tree_entry_get_prev(s->tree, te);
6969 static const struct got_error *
6970 tree_scroll_down(struct tog_view *view, int maxscroll)
6972 struct tog_tree_view_state *s = &view->state.tree;
6973 struct got_tree_entry *next, *last;
6974 int n = 0;
6976 if (s->first_displayed_entry)
6977 next = got_tree_entry_get_next(s->tree,
6978 s->first_displayed_entry);
6979 else
6980 next = got_object_tree_get_first_entry(s->tree);
6982 last = s->last_displayed_entry;
6983 while (next && n++ < maxscroll) {
6984 if (last) {
6985 s->last_displayed_entry = last;
6986 last = got_tree_entry_get_next(s->tree, last);
6988 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6989 s->first_displayed_entry = next;
6990 next = got_tree_entry_get_next(s->tree, next);
6994 return NULL;
6997 static const struct got_error *
6998 tree_entry_path(char **path, struct tog_parent_trees *parents,
6999 struct got_tree_entry *te)
7001 const struct got_error *err = NULL;
7002 struct tog_parent_tree *pt;
7003 size_t len = 2; /* for leading slash and NUL */
7005 TAILQ_FOREACH(pt, parents, entry)
7006 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7007 + 1 /* slash */;
7008 if (te)
7009 len += strlen(got_tree_entry_get_name(te));
7011 *path = calloc(1, len);
7012 if (path == NULL)
7013 return got_error_from_errno("calloc");
7015 (*path)[0] = '/';
7016 pt = TAILQ_LAST(parents, tog_parent_trees);
7017 while (pt) {
7018 const char *name = got_tree_entry_get_name(pt->selected_entry);
7019 if (strlcat(*path, name, len) >= len) {
7020 err = got_error(GOT_ERR_NO_SPACE);
7021 goto done;
7023 if (strlcat(*path, "/", len) >= len) {
7024 err = got_error(GOT_ERR_NO_SPACE);
7025 goto done;
7027 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7029 if (te) {
7030 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7031 err = got_error(GOT_ERR_NO_SPACE);
7032 goto done;
7035 done:
7036 if (err) {
7037 free(*path);
7038 *path = NULL;
7040 return err;
7043 static const struct got_error *
7044 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7045 struct got_tree_entry *te, struct tog_parent_trees *parents,
7046 struct got_object_id *commit_id, struct got_repository *repo)
7048 const struct got_error *err = NULL;
7049 char *path;
7050 struct tog_view *blame_view;
7052 *new_view = NULL;
7054 err = tree_entry_path(&path, parents, te);
7055 if (err)
7056 return err;
7058 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7059 if (blame_view == NULL) {
7060 err = got_error_from_errno("view_open");
7061 goto done;
7064 err = open_blame_view(blame_view, path, commit_id, repo);
7065 if (err) {
7066 if (err->code == GOT_ERR_CANCELLED)
7067 err = NULL;
7068 view_close(blame_view);
7069 } else
7070 *new_view = blame_view;
7071 done:
7072 free(path);
7073 return err;
7076 static const struct got_error *
7077 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7078 struct tog_tree_view_state *s)
7080 struct tog_view *log_view;
7081 const struct got_error *err = NULL;
7082 char *path;
7084 *new_view = NULL;
7086 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7087 if (log_view == NULL)
7088 return got_error_from_errno("view_open");
7090 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7091 if (err)
7092 return err;
7094 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7095 path, 0);
7096 if (err)
7097 view_close(log_view);
7098 else
7099 *new_view = log_view;
7100 free(path);
7101 return err;
7104 static const struct got_error *
7105 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7106 const char *head_ref_name, struct got_repository *repo)
7108 const struct got_error *err = NULL;
7109 char *commit_id_str = NULL;
7110 struct tog_tree_view_state *s = &view->state.tree;
7111 struct got_commit_object *commit = NULL;
7113 TAILQ_INIT(&s->parents);
7114 STAILQ_INIT(&s->colors);
7116 s->commit_id = got_object_id_dup(commit_id);
7117 if (s->commit_id == NULL)
7118 return got_error_from_errno("got_object_id_dup");
7120 err = got_object_open_as_commit(&commit, repo, commit_id);
7121 if (err)
7122 goto done;
7125 * The root is opened here and will be closed when the view is closed.
7126 * Any visited subtrees and their path-wise parents are opened and
7127 * closed on demand.
7129 err = got_object_open_as_tree(&s->root, repo,
7130 got_object_commit_get_tree_id(commit));
7131 if (err)
7132 goto done;
7133 s->tree = s->root;
7135 err = got_object_id_str(&commit_id_str, commit_id);
7136 if (err != NULL)
7137 goto done;
7139 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7140 err = got_error_from_errno("asprintf");
7141 goto done;
7144 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7145 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7146 if (head_ref_name) {
7147 s->head_ref_name = strdup(head_ref_name);
7148 if (s->head_ref_name == NULL) {
7149 err = got_error_from_errno("strdup");
7150 goto done;
7153 s->repo = repo;
7155 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7156 err = add_color(&s->colors, "\\$$",
7157 TOG_COLOR_TREE_SUBMODULE,
7158 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7159 if (err)
7160 goto done;
7161 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7162 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7163 if (err)
7164 goto done;
7165 err = add_color(&s->colors, "/$",
7166 TOG_COLOR_TREE_DIRECTORY,
7167 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7168 if (err)
7169 goto done;
7171 err = add_color(&s->colors, "\\*$",
7172 TOG_COLOR_TREE_EXECUTABLE,
7173 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7174 if (err)
7175 goto done;
7177 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7178 get_color_value("TOG_COLOR_COMMIT"));
7179 if (err)
7180 goto done;
7183 view->show = show_tree_view;
7184 view->input = input_tree_view;
7185 view->close = close_tree_view;
7186 view->search_start = search_start_tree_view;
7187 view->search_next = search_next_tree_view;
7188 done:
7189 free(commit_id_str);
7190 if (commit)
7191 got_object_commit_close(commit);
7192 if (err)
7193 close_tree_view(view);
7194 return err;
7197 static const struct got_error *
7198 close_tree_view(struct tog_view *view)
7200 struct tog_tree_view_state *s = &view->state.tree;
7202 free_colors(&s->colors);
7203 free(s->tree_label);
7204 s->tree_label = NULL;
7205 free(s->commit_id);
7206 s->commit_id = NULL;
7207 free(s->head_ref_name);
7208 s->head_ref_name = NULL;
7209 while (!TAILQ_EMPTY(&s->parents)) {
7210 struct tog_parent_tree *parent;
7211 parent = TAILQ_FIRST(&s->parents);
7212 TAILQ_REMOVE(&s->parents, parent, entry);
7213 if (parent->tree != s->root)
7214 got_object_tree_close(parent->tree);
7215 free(parent);
7218 if (s->tree != NULL && s->tree != s->root)
7219 got_object_tree_close(s->tree);
7220 if (s->root)
7221 got_object_tree_close(s->root);
7222 return NULL;
7225 static const struct got_error *
7226 search_start_tree_view(struct tog_view *view)
7228 struct tog_tree_view_state *s = &view->state.tree;
7230 s->matched_entry = NULL;
7231 return NULL;
7234 static int
7235 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7237 regmatch_t regmatch;
7239 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7240 0) == 0;
7243 static const struct got_error *
7244 search_next_tree_view(struct tog_view *view)
7246 struct tog_tree_view_state *s = &view->state.tree;
7247 struct got_tree_entry *te = NULL;
7249 if (!view->searching) {
7250 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7251 return NULL;
7254 if (s->matched_entry) {
7255 if (view->searching == TOG_SEARCH_FORWARD) {
7256 if (s->selected_entry)
7257 te = got_tree_entry_get_next(s->tree,
7258 s->selected_entry);
7259 else
7260 te = got_object_tree_get_first_entry(s->tree);
7261 } else {
7262 if (s->selected_entry == NULL)
7263 te = got_object_tree_get_last_entry(s->tree);
7264 else
7265 te = got_tree_entry_get_prev(s->tree,
7266 s->selected_entry);
7268 } else {
7269 if (s->selected_entry)
7270 te = s->selected_entry;
7271 else if (view->searching == TOG_SEARCH_FORWARD)
7272 te = got_object_tree_get_first_entry(s->tree);
7273 else
7274 te = got_object_tree_get_last_entry(s->tree);
7277 while (1) {
7278 if (te == NULL) {
7279 if (s->matched_entry == NULL) {
7280 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7281 return NULL;
7283 if (view->searching == TOG_SEARCH_FORWARD)
7284 te = got_object_tree_get_first_entry(s->tree);
7285 else
7286 te = got_object_tree_get_last_entry(s->tree);
7289 if (match_tree_entry(te, &view->regex)) {
7290 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7291 s->matched_entry = te;
7292 break;
7295 if (view->searching == TOG_SEARCH_FORWARD)
7296 te = got_tree_entry_get_next(s->tree, te);
7297 else
7298 te = got_tree_entry_get_prev(s->tree, te);
7301 if (s->matched_entry) {
7302 s->first_displayed_entry = s->matched_entry;
7303 s->selected = 0;
7306 return NULL;
7309 static const struct got_error *
7310 show_tree_view(struct tog_view *view)
7312 const struct got_error *err = NULL;
7313 struct tog_tree_view_state *s = &view->state.tree;
7314 char *parent_path;
7316 err = tree_entry_path(&parent_path, &s->parents, NULL);
7317 if (err)
7318 return err;
7320 err = draw_tree_entries(view, parent_path);
7321 free(parent_path);
7323 view_border(view);
7324 return err;
7327 static const struct got_error *
7328 tree_goto_line(struct tog_view *view, int nlines)
7330 const struct got_error *err = NULL;
7331 struct tog_tree_view_state *s = &view->state.tree;
7332 struct got_tree_entry **fte, **lte, **ste;
7333 int g, last, first = 1, i = 1;
7334 int root = s->tree == s->root;
7335 int off = root ? 1 : 2;
7337 g = view->gline;
7338 view->gline = 0;
7340 if (g == 0)
7341 g = 1;
7342 else if (g > got_object_tree_get_nentries(s->tree))
7343 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7345 fte = &s->first_displayed_entry;
7346 lte = &s->last_displayed_entry;
7347 ste = &s->selected_entry;
7349 if (*fte != NULL) {
7350 first = got_tree_entry_get_index(*fte);
7351 first += off; /* account for ".." */
7353 last = got_tree_entry_get_index(*lte);
7354 last += off;
7356 if (g >= first && g <= last && g - first < nlines) {
7357 s->selected = g - first;
7358 return NULL; /* gline is on the current page */
7361 if (*ste != NULL) {
7362 i = got_tree_entry_get_index(*ste);
7363 i += off;
7366 if (i < g) {
7367 err = tree_scroll_down(view, g - i);
7368 if (err)
7369 return err;
7370 if (got_tree_entry_get_index(*lte) >=
7371 got_object_tree_get_nentries(s->tree) - 1 &&
7372 first + s->selected < g &&
7373 s->selected < s->ndisplayed - 1) {
7374 first = got_tree_entry_get_index(*fte);
7375 first += off;
7376 s->selected = g - first;
7378 } else if (i > g)
7379 tree_scroll_up(s, i - g);
7381 if (g < nlines &&
7382 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7383 s->selected = g - 1;
7385 return NULL;
7388 static const struct got_error *
7389 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7391 const struct got_error *err = NULL;
7392 struct tog_tree_view_state *s = &view->state.tree;
7393 struct got_tree_entry *te;
7394 int n, nscroll = view->nlines - 3;
7396 if (view->gline)
7397 return tree_goto_line(view, nscroll);
7399 switch (ch) {
7400 case '0':
7401 case '$':
7402 case KEY_RIGHT:
7403 case 'l':
7404 case KEY_LEFT:
7405 case 'h':
7406 horizontal_scroll_input(view, ch);
7407 break;
7408 case 'i':
7409 s->show_ids = !s->show_ids;
7410 view->count = 0;
7411 break;
7412 case 'L':
7413 view->count = 0;
7414 if (!s->selected_entry)
7415 break;
7416 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7417 break;
7418 case 'R':
7419 view->count = 0;
7420 err = view_request_new(new_view, view, TOG_VIEW_REF);
7421 break;
7422 case 'g':
7423 case '=':
7424 case KEY_HOME:
7425 s->selected = 0;
7426 view->count = 0;
7427 if (s->tree == s->root)
7428 s->first_displayed_entry =
7429 got_object_tree_get_first_entry(s->tree);
7430 else
7431 s->first_displayed_entry = NULL;
7432 break;
7433 case 'G':
7434 case '*':
7435 case KEY_END: {
7436 int eos = view->nlines - 3;
7438 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7439 --eos; /* border */
7440 s->selected = 0;
7441 view->count = 0;
7442 te = got_object_tree_get_last_entry(s->tree);
7443 for (n = 0; n < eos; n++) {
7444 if (te == NULL) {
7445 if (s->tree != s->root) {
7446 s->first_displayed_entry = NULL;
7447 n++;
7449 break;
7451 s->first_displayed_entry = te;
7452 te = got_tree_entry_get_prev(s->tree, te);
7454 if (n > 0)
7455 s->selected = n - 1;
7456 break;
7458 case 'k':
7459 case KEY_UP:
7460 case CTRL('p'):
7461 if (s->selected > 0) {
7462 s->selected--;
7463 break;
7465 tree_scroll_up(s, 1);
7466 if (s->selected_entry == NULL ||
7467 (s->tree == s->root && s->selected_entry ==
7468 got_object_tree_get_first_entry(s->tree)))
7469 view->count = 0;
7470 break;
7471 case CTRL('u'):
7472 case 'u':
7473 nscroll /= 2;
7474 /* FALL THROUGH */
7475 case KEY_PPAGE:
7476 case CTRL('b'):
7477 case 'b':
7478 if (s->tree == s->root) {
7479 if (got_object_tree_get_first_entry(s->tree) ==
7480 s->first_displayed_entry)
7481 s->selected -= MIN(s->selected, nscroll);
7482 } else {
7483 if (s->first_displayed_entry == NULL)
7484 s->selected -= MIN(s->selected, nscroll);
7486 tree_scroll_up(s, MAX(0, nscroll));
7487 if (s->selected_entry == NULL ||
7488 (s->tree == s->root && s->selected_entry ==
7489 got_object_tree_get_first_entry(s->tree)))
7490 view->count = 0;
7491 break;
7492 case 'j':
7493 case KEY_DOWN:
7494 case CTRL('n'):
7495 if (s->selected < s->ndisplayed - 1) {
7496 s->selected++;
7497 break;
7499 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7500 == NULL) {
7501 /* can't scroll any further */
7502 view->count = 0;
7503 break;
7505 tree_scroll_down(view, 1);
7506 break;
7507 case CTRL('d'):
7508 case 'd':
7509 nscroll /= 2;
7510 /* FALL THROUGH */
7511 case KEY_NPAGE:
7512 case CTRL('f'):
7513 case 'f':
7514 case ' ':
7515 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7516 == NULL) {
7517 /* can't scroll any further; move cursor down */
7518 if (s->selected < s->ndisplayed - 1)
7519 s->selected += MIN(nscroll,
7520 s->ndisplayed - s->selected - 1);
7521 else
7522 view->count = 0;
7523 break;
7525 tree_scroll_down(view, nscroll);
7526 break;
7527 case KEY_ENTER:
7528 case '\r':
7529 case KEY_BACKSPACE:
7530 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7531 struct tog_parent_tree *parent;
7532 /* user selected '..' */
7533 if (s->tree == s->root) {
7534 view->count = 0;
7535 break;
7537 parent = TAILQ_FIRST(&s->parents);
7538 TAILQ_REMOVE(&s->parents, parent,
7539 entry);
7540 got_object_tree_close(s->tree);
7541 s->tree = parent->tree;
7542 s->first_displayed_entry =
7543 parent->first_displayed_entry;
7544 s->selected_entry =
7545 parent->selected_entry;
7546 s->selected = parent->selected;
7547 if (s->selected > view->nlines - 3) {
7548 err = offset_selection_down(view);
7549 if (err)
7550 break;
7552 free(parent);
7553 } else if (S_ISDIR(got_tree_entry_get_mode(
7554 s->selected_entry))) {
7555 struct got_tree_object *subtree;
7556 view->count = 0;
7557 err = got_object_open_as_tree(&subtree, s->repo,
7558 got_tree_entry_get_id(s->selected_entry));
7559 if (err)
7560 break;
7561 err = tree_view_visit_subtree(s, subtree);
7562 if (err) {
7563 got_object_tree_close(subtree);
7564 break;
7566 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7567 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7568 break;
7569 case KEY_RESIZE:
7570 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7571 s->selected = view->nlines - 4;
7572 view->count = 0;
7573 break;
7574 default:
7575 view->count = 0;
7576 break;
7579 return err;
7582 __dead static void
7583 usage_tree(void)
7585 endwin();
7586 fprintf(stderr,
7587 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7588 getprogname());
7589 exit(1);
7592 static const struct got_error *
7593 cmd_tree(int argc, char *argv[])
7595 const struct got_error *error;
7596 struct got_repository *repo = NULL;
7597 struct got_worktree *worktree = NULL;
7598 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7599 struct got_object_id *commit_id = NULL;
7600 struct got_commit_object *commit = NULL;
7601 const char *commit_id_arg = NULL;
7602 char *label = NULL;
7603 struct got_reference *ref = NULL;
7604 const char *head_ref_name = NULL;
7605 int ch;
7606 struct tog_view *view;
7607 int *pack_fds = NULL;
7609 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7610 switch (ch) {
7611 case 'c':
7612 commit_id_arg = optarg;
7613 break;
7614 case 'r':
7615 repo_path = realpath(optarg, NULL);
7616 if (repo_path == NULL)
7617 return got_error_from_errno2("realpath",
7618 optarg);
7619 break;
7620 default:
7621 usage_tree();
7622 /* NOTREACHED */
7626 argc -= optind;
7627 argv += optind;
7629 if (argc > 1)
7630 usage_tree();
7632 error = got_repo_pack_fds_open(&pack_fds);
7633 if (error != NULL)
7634 goto done;
7636 if (repo_path == NULL) {
7637 cwd = getcwd(NULL, 0);
7638 if (cwd == NULL)
7639 return got_error_from_errno("getcwd");
7640 error = got_worktree_open(&worktree, cwd);
7641 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7642 goto done;
7643 if (worktree)
7644 repo_path =
7645 strdup(got_worktree_get_repo_path(worktree));
7646 else
7647 repo_path = strdup(cwd);
7648 if (repo_path == NULL) {
7649 error = got_error_from_errno("strdup");
7650 goto done;
7654 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7655 if (error != NULL)
7656 goto done;
7658 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7659 repo, worktree);
7660 if (error)
7661 goto done;
7663 init_curses();
7665 error = apply_unveil(got_repo_get_path(repo), NULL);
7666 if (error)
7667 goto done;
7669 error = tog_load_refs(repo, 0);
7670 if (error)
7671 goto done;
7673 if (commit_id_arg == NULL) {
7674 error = got_repo_match_object_id(&commit_id, &label,
7675 worktree ? got_worktree_get_head_ref_name(worktree) :
7676 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7677 if (error)
7678 goto done;
7679 head_ref_name = label;
7680 } else {
7681 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7682 if (error == NULL)
7683 head_ref_name = got_ref_get_name(ref);
7684 else if (error->code != GOT_ERR_NOT_REF)
7685 goto done;
7686 error = got_repo_match_object_id(&commit_id, NULL,
7687 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7688 if (error)
7689 goto done;
7692 error = got_object_open_as_commit(&commit, repo, commit_id);
7693 if (error)
7694 goto done;
7696 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7697 if (view == NULL) {
7698 error = got_error_from_errno("view_open");
7699 goto done;
7701 error = open_tree_view(view, commit_id, head_ref_name, repo);
7702 if (error)
7703 goto done;
7704 if (!got_path_is_root_dir(in_repo_path)) {
7705 error = tree_view_walk_path(&view->state.tree, commit,
7706 in_repo_path);
7707 if (error)
7708 goto done;
7711 if (worktree) {
7712 /* Release work tree lock. */
7713 got_worktree_close(worktree);
7714 worktree = NULL;
7716 error = view_loop(view);
7717 done:
7718 free(repo_path);
7719 free(cwd);
7720 free(commit_id);
7721 free(label);
7722 if (ref)
7723 got_ref_close(ref);
7724 if (repo) {
7725 const struct got_error *close_err = got_repo_close(repo);
7726 if (error == NULL)
7727 error = close_err;
7729 if (pack_fds) {
7730 const struct got_error *pack_err =
7731 got_repo_pack_fds_close(pack_fds);
7732 if (error == NULL)
7733 error = pack_err;
7735 tog_free_refs();
7736 return error;
7739 static const struct got_error *
7740 ref_view_load_refs(struct tog_ref_view_state *s)
7742 struct got_reflist_entry *sre;
7743 struct tog_reflist_entry *re;
7745 s->nrefs = 0;
7746 TAILQ_FOREACH(sre, &tog_refs, entry) {
7747 if (strncmp(got_ref_get_name(sre->ref),
7748 "refs/got/", 9) == 0 &&
7749 strncmp(got_ref_get_name(sre->ref),
7750 "refs/got/backup/", 16) != 0)
7751 continue;
7753 re = malloc(sizeof(*re));
7754 if (re == NULL)
7755 return got_error_from_errno("malloc");
7757 re->ref = got_ref_dup(sre->ref);
7758 if (re->ref == NULL)
7759 return got_error_from_errno("got_ref_dup");
7760 re->idx = s->nrefs++;
7761 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7764 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7765 return NULL;
7768 static void
7769 ref_view_free_refs(struct tog_ref_view_state *s)
7771 struct tog_reflist_entry *re;
7773 while (!TAILQ_EMPTY(&s->refs)) {
7774 re = TAILQ_FIRST(&s->refs);
7775 TAILQ_REMOVE(&s->refs, re, entry);
7776 got_ref_close(re->ref);
7777 free(re);
7781 static const struct got_error *
7782 open_ref_view(struct tog_view *view, struct got_repository *repo)
7784 const struct got_error *err = NULL;
7785 struct tog_ref_view_state *s = &view->state.ref;
7787 s->selected_entry = 0;
7788 s->repo = repo;
7790 TAILQ_INIT(&s->refs);
7791 STAILQ_INIT(&s->colors);
7793 err = ref_view_load_refs(s);
7794 if (err)
7795 return err;
7797 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7798 err = add_color(&s->colors, "^refs/heads/",
7799 TOG_COLOR_REFS_HEADS,
7800 get_color_value("TOG_COLOR_REFS_HEADS"));
7801 if (err)
7802 goto done;
7804 err = add_color(&s->colors, "^refs/tags/",
7805 TOG_COLOR_REFS_TAGS,
7806 get_color_value("TOG_COLOR_REFS_TAGS"));
7807 if (err)
7808 goto done;
7810 err = add_color(&s->colors, "^refs/remotes/",
7811 TOG_COLOR_REFS_REMOTES,
7812 get_color_value("TOG_COLOR_REFS_REMOTES"));
7813 if (err)
7814 goto done;
7816 err = add_color(&s->colors, "^refs/got/backup/",
7817 TOG_COLOR_REFS_BACKUP,
7818 get_color_value("TOG_COLOR_REFS_BACKUP"));
7819 if (err)
7820 goto done;
7823 view->show = show_ref_view;
7824 view->input = input_ref_view;
7825 view->close = close_ref_view;
7826 view->search_start = search_start_ref_view;
7827 view->search_next = search_next_ref_view;
7828 done:
7829 if (err)
7830 free_colors(&s->colors);
7831 return err;
7834 static const struct got_error *
7835 close_ref_view(struct tog_view *view)
7837 struct tog_ref_view_state *s = &view->state.ref;
7839 ref_view_free_refs(s);
7840 free_colors(&s->colors);
7842 return NULL;
7845 static const struct got_error *
7846 resolve_reflist_entry(struct got_object_id **commit_id,
7847 struct tog_reflist_entry *re, struct got_repository *repo)
7849 const struct got_error *err = NULL;
7850 struct got_object_id *obj_id;
7851 struct got_tag_object *tag = NULL;
7852 int obj_type;
7854 *commit_id = NULL;
7856 err = got_ref_resolve(&obj_id, repo, re->ref);
7857 if (err)
7858 return err;
7860 err = got_object_get_type(&obj_type, repo, obj_id);
7861 if (err)
7862 goto done;
7864 switch (obj_type) {
7865 case GOT_OBJ_TYPE_COMMIT:
7866 *commit_id = obj_id;
7867 break;
7868 case GOT_OBJ_TYPE_TAG:
7869 err = got_object_open_as_tag(&tag, repo, obj_id);
7870 if (err)
7871 goto done;
7872 free(obj_id);
7873 err = got_object_get_type(&obj_type, repo,
7874 got_object_tag_get_object_id(tag));
7875 if (err)
7876 goto done;
7877 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7878 err = got_error(GOT_ERR_OBJ_TYPE);
7879 goto done;
7881 *commit_id = got_object_id_dup(
7882 got_object_tag_get_object_id(tag));
7883 if (*commit_id == NULL) {
7884 err = got_error_from_errno("got_object_id_dup");
7885 goto done;
7887 break;
7888 default:
7889 err = got_error(GOT_ERR_OBJ_TYPE);
7890 break;
7893 done:
7894 if (tag)
7895 got_object_tag_close(tag);
7896 if (err) {
7897 free(*commit_id);
7898 *commit_id = NULL;
7900 return err;
7903 static const struct got_error *
7904 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7905 struct tog_reflist_entry *re, struct got_repository *repo)
7907 struct tog_view *log_view;
7908 const struct got_error *err = NULL;
7909 struct got_object_id *commit_id = NULL;
7911 *new_view = NULL;
7913 err = resolve_reflist_entry(&commit_id, re, repo);
7914 if (err) {
7915 if (err->code != GOT_ERR_OBJ_TYPE)
7916 return err;
7917 else
7918 return NULL;
7921 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7922 if (log_view == NULL) {
7923 err = got_error_from_errno("view_open");
7924 goto done;
7927 err = open_log_view(log_view, commit_id, repo,
7928 got_ref_get_name(re->ref), "", 0);
7929 done:
7930 if (err)
7931 view_close(log_view);
7932 else
7933 *new_view = log_view;
7934 free(commit_id);
7935 return err;
7938 static void
7939 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7941 struct tog_reflist_entry *re;
7942 int i = 0;
7944 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7945 return;
7947 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7948 while (i++ < maxscroll) {
7949 if (re == NULL)
7950 break;
7951 s->first_displayed_entry = re;
7952 re = TAILQ_PREV(re, tog_reflist_head, entry);
7956 static const struct got_error *
7957 ref_scroll_down(struct tog_view *view, int maxscroll)
7959 struct tog_ref_view_state *s = &view->state.ref;
7960 struct tog_reflist_entry *next, *last;
7961 int n = 0;
7963 if (s->first_displayed_entry)
7964 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7965 else
7966 next = TAILQ_FIRST(&s->refs);
7968 last = s->last_displayed_entry;
7969 while (next && n++ < maxscroll) {
7970 if (last) {
7971 s->last_displayed_entry = last;
7972 last = TAILQ_NEXT(last, entry);
7974 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7975 s->first_displayed_entry = next;
7976 next = TAILQ_NEXT(next, entry);
7980 return NULL;
7983 static const struct got_error *
7984 search_start_ref_view(struct tog_view *view)
7986 struct tog_ref_view_state *s = &view->state.ref;
7988 s->matched_entry = NULL;
7989 return NULL;
7992 static int
7993 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7995 regmatch_t regmatch;
7997 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7998 0) == 0;
8001 static const struct got_error *
8002 search_next_ref_view(struct tog_view *view)
8004 struct tog_ref_view_state *s = &view->state.ref;
8005 struct tog_reflist_entry *re = NULL;
8007 if (!view->searching) {
8008 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8009 return NULL;
8012 if (s->matched_entry) {
8013 if (view->searching == TOG_SEARCH_FORWARD) {
8014 if (s->selected_entry)
8015 re = TAILQ_NEXT(s->selected_entry, entry);
8016 else
8017 re = TAILQ_PREV(s->selected_entry,
8018 tog_reflist_head, entry);
8019 } else {
8020 if (s->selected_entry == NULL)
8021 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8022 else
8023 re = TAILQ_PREV(s->selected_entry,
8024 tog_reflist_head, entry);
8026 } else {
8027 if (s->selected_entry)
8028 re = s->selected_entry;
8029 else if (view->searching == TOG_SEARCH_FORWARD)
8030 re = TAILQ_FIRST(&s->refs);
8031 else
8032 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8035 while (1) {
8036 if (re == NULL) {
8037 if (s->matched_entry == NULL) {
8038 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8039 return NULL;
8041 if (view->searching == TOG_SEARCH_FORWARD)
8042 re = TAILQ_FIRST(&s->refs);
8043 else
8044 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8047 if (match_reflist_entry(re, &view->regex)) {
8048 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8049 s->matched_entry = re;
8050 break;
8053 if (view->searching == TOG_SEARCH_FORWARD)
8054 re = TAILQ_NEXT(re, entry);
8055 else
8056 re = TAILQ_PREV(re, tog_reflist_head, entry);
8059 if (s->matched_entry) {
8060 s->first_displayed_entry = s->matched_entry;
8061 s->selected = 0;
8064 return NULL;
8067 static const struct got_error *
8068 show_ref_view(struct tog_view *view)
8070 const struct got_error *err = NULL;
8071 struct tog_ref_view_state *s = &view->state.ref;
8072 struct tog_reflist_entry *re;
8073 char *line = NULL;
8074 wchar_t *wline;
8075 struct tog_color *tc;
8076 int width, n, scrollx;
8077 int limit = view->nlines;
8079 werase(view->window);
8081 s->ndisplayed = 0;
8082 if (view_is_hsplit_top(view))
8083 --limit; /* border */
8085 if (limit == 0)
8086 return NULL;
8088 re = s->first_displayed_entry;
8090 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8091 s->nrefs) == -1)
8092 return got_error_from_errno("asprintf");
8094 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8095 if (err) {
8096 free(line);
8097 return err;
8099 if (view_needs_focus_indication(view))
8100 wstandout(view->window);
8101 waddwstr(view->window, wline);
8102 while (width++ < view->ncols)
8103 waddch(view->window, ' ');
8104 if (view_needs_focus_indication(view))
8105 wstandend(view->window);
8106 free(wline);
8107 wline = NULL;
8108 free(line);
8109 line = NULL;
8110 if (--limit <= 0)
8111 return NULL;
8113 n = 0;
8114 view->maxx = 0;
8115 while (re && limit > 0) {
8116 char *line = NULL;
8117 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8119 if (s->show_date) {
8120 struct got_commit_object *ci;
8121 struct got_tag_object *tag;
8122 struct got_object_id *id;
8123 struct tm tm;
8124 time_t t;
8126 err = got_ref_resolve(&id, s->repo, re->ref);
8127 if (err)
8128 return err;
8129 err = got_object_open_as_tag(&tag, s->repo, id);
8130 if (err) {
8131 if (err->code != GOT_ERR_OBJ_TYPE) {
8132 free(id);
8133 return err;
8135 err = got_object_open_as_commit(&ci, s->repo,
8136 id);
8137 if (err) {
8138 free(id);
8139 return err;
8141 t = got_object_commit_get_committer_time(ci);
8142 got_object_commit_close(ci);
8143 } else {
8144 t = got_object_tag_get_tagger_time(tag);
8145 got_object_tag_close(tag);
8147 free(id);
8148 if (gmtime_r(&t, &tm) == NULL)
8149 return got_error_from_errno("gmtime_r");
8150 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8151 return got_error(GOT_ERR_NO_SPACE);
8153 if (got_ref_is_symbolic(re->ref)) {
8154 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8155 ymd : "", got_ref_get_name(re->ref),
8156 got_ref_get_symref_target(re->ref)) == -1)
8157 return got_error_from_errno("asprintf");
8158 } else if (s->show_ids) {
8159 struct got_object_id *id;
8160 char *id_str;
8161 err = got_ref_resolve(&id, s->repo, re->ref);
8162 if (err)
8163 return err;
8164 err = got_object_id_str(&id_str, id);
8165 if (err) {
8166 free(id);
8167 return err;
8169 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8170 got_ref_get_name(re->ref), id_str) == -1) {
8171 err = got_error_from_errno("asprintf");
8172 free(id);
8173 free(id_str);
8174 return err;
8176 free(id);
8177 free(id_str);
8178 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8179 got_ref_get_name(re->ref)) == -1)
8180 return got_error_from_errno("asprintf");
8182 /* use full line width to determine view->maxx */
8183 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8184 if (err) {
8185 free(line);
8186 return err;
8188 view->maxx = MAX(view->maxx, width);
8189 free(wline);
8190 wline = NULL;
8192 err = format_line(&wline, &width, &scrollx, line, view->x,
8193 view->ncols, 0, 0);
8194 if (err) {
8195 free(line);
8196 return err;
8198 if (n == s->selected) {
8199 if (view->focussed)
8200 wstandout(view->window);
8201 s->selected_entry = re;
8203 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8204 if (tc)
8205 wattr_on(view->window,
8206 COLOR_PAIR(tc->colorpair), NULL);
8207 waddwstr(view->window, &wline[scrollx]);
8208 if (tc)
8209 wattr_off(view->window,
8210 COLOR_PAIR(tc->colorpair), NULL);
8211 if (width < view->ncols)
8212 waddch(view->window, '\n');
8213 if (n == s->selected && view->focussed)
8214 wstandend(view->window);
8215 free(line);
8216 free(wline);
8217 wline = NULL;
8218 n++;
8219 s->ndisplayed++;
8220 s->last_displayed_entry = re;
8222 limit--;
8223 re = TAILQ_NEXT(re, entry);
8226 view_border(view);
8227 return err;
8230 static const struct got_error *
8231 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8232 struct tog_reflist_entry *re, struct got_repository *repo)
8234 const struct got_error *err = NULL;
8235 struct got_object_id *commit_id = NULL;
8236 struct tog_view *tree_view;
8238 *new_view = NULL;
8240 err = resolve_reflist_entry(&commit_id, re, repo);
8241 if (err) {
8242 if (err->code != GOT_ERR_OBJ_TYPE)
8243 return err;
8244 else
8245 return NULL;
8249 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8250 if (tree_view == NULL) {
8251 err = got_error_from_errno("view_open");
8252 goto done;
8255 err = open_tree_view(tree_view, commit_id,
8256 got_ref_get_name(re->ref), repo);
8257 if (err)
8258 goto done;
8260 *new_view = tree_view;
8261 done:
8262 free(commit_id);
8263 return err;
8266 static const struct got_error *
8267 ref_goto_line(struct tog_view *view, int nlines)
8269 const struct got_error *err = NULL;
8270 struct tog_ref_view_state *s = &view->state.ref;
8271 int g, idx = s->selected_entry->idx;
8273 g = view->gline;
8274 view->gline = 0;
8276 if (g == 0)
8277 g = 1;
8278 else if (g > s->nrefs)
8279 g = s->nrefs;
8281 if (g >= s->first_displayed_entry->idx + 1 &&
8282 g <= s->last_displayed_entry->idx + 1 &&
8283 g - s->first_displayed_entry->idx - 1 < nlines) {
8284 s->selected = g - s->first_displayed_entry->idx - 1;
8285 return NULL;
8288 if (idx + 1 < g) {
8289 err = ref_scroll_down(view, g - idx - 1);
8290 if (err)
8291 return err;
8292 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8293 s->first_displayed_entry->idx + s->selected < g &&
8294 s->selected < s->ndisplayed - 1)
8295 s->selected = g - s->first_displayed_entry->idx - 1;
8296 } else if (idx + 1 > g)
8297 ref_scroll_up(s, idx - g + 1);
8299 if (g < nlines && s->first_displayed_entry->idx == 0)
8300 s->selected = g - 1;
8302 return NULL;
8306 static const struct got_error *
8307 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8309 const struct got_error *err = NULL;
8310 struct tog_ref_view_state *s = &view->state.ref;
8311 struct tog_reflist_entry *re;
8312 int n, nscroll = view->nlines - 1;
8314 if (view->gline)
8315 return ref_goto_line(view, nscroll);
8317 switch (ch) {
8318 case '0':
8319 case '$':
8320 case KEY_RIGHT:
8321 case 'l':
8322 case KEY_LEFT:
8323 case 'h':
8324 horizontal_scroll_input(view, ch);
8325 break;
8326 case 'i':
8327 s->show_ids = !s->show_ids;
8328 view->count = 0;
8329 break;
8330 case 'm':
8331 s->show_date = !s->show_date;
8332 view->count = 0;
8333 break;
8334 case 'o':
8335 s->sort_by_date = !s->sort_by_date;
8336 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8337 view->count = 0;
8338 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8339 got_ref_cmp_by_commit_timestamp_descending :
8340 tog_ref_cmp_by_name, s->repo);
8341 if (err)
8342 break;
8343 got_reflist_object_id_map_free(tog_refs_idmap);
8344 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8345 &tog_refs, s->repo);
8346 if (err)
8347 break;
8348 ref_view_free_refs(s);
8349 err = ref_view_load_refs(s);
8350 break;
8351 case KEY_ENTER:
8352 case '\r':
8353 view->count = 0;
8354 if (!s->selected_entry)
8355 break;
8356 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8357 break;
8358 case 'T':
8359 view->count = 0;
8360 if (!s->selected_entry)
8361 break;
8362 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8363 break;
8364 case 'g':
8365 case '=':
8366 case KEY_HOME:
8367 s->selected = 0;
8368 view->count = 0;
8369 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8370 break;
8371 case 'G':
8372 case '*':
8373 case KEY_END: {
8374 int eos = view->nlines - 1;
8376 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8377 --eos; /* border */
8378 s->selected = 0;
8379 view->count = 0;
8380 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8381 for (n = 0; n < eos; n++) {
8382 if (re == NULL)
8383 break;
8384 s->first_displayed_entry = re;
8385 re = TAILQ_PREV(re, tog_reflist_head, entry);
8387 if (n > 0)
8388 s->selected = n - 1;
8389 break;
8391 case 'k':
8392 case KEY_UP:
8393 case CTRL('p'):
8394 if (s->selected > 0) {
8395 s->selected--;
8396 break;
8398 ref_scroll_up(s, 1);
8399 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8400 view->count = 0;
8401 break;
8402 case CTRL('u'):
8403 case 'u':
8404 nscroll /= 2;
8405 /* FALL THROUGH */
8406 case KEY_PPAGE:
8407 case CTRL('b'):
8408 case 'b':
8409 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8410 s->selected -= MIN(nscroll, s->selected);
8411 ref_scroll_up(s, MAX(0, nscroll));
8412 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8413 view->count = 0;
8414 break;
8415 case 'j':
8416 case KEY_DOWN:
8417 case CTRL('n'):
8418 if (s->selected < s->ndisplayed - 1) {
8419 s->selected++;
8420 break;
8422 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8423 /* can't scroll any further */
8424 view->count = 0;
8425 break;
8427 ref_scroll_down(view, 1);
8428 break;
8429 case CTRL('d'):
8430 case 'd':
8431 nscroll /= 2;
8432 /* FALL THROUGH */
8433 case KEY_NPAGE:
8434 case CTRL('f'):
8435 case 'f':
8436 case ' ':
8437 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8438 /* can't scroll any further; move cursor down */
8439 if (s->selected < s->ndisplayed - 1)
8440 s->selected += MIN(nscroll,
8441 s->ndisplayed - s->selected - 1);
8442 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8443 s->selected += s->ndisplayed - s->selected - 1;
8444 view->count = 0;
8445 break;
8447 ref_scroll_down(view, nscroll);
8448 break;
8449 case CTRL('l'):
8450 view->count = 0;
8451 tog_free_refs();
8452 err = tog_load_refs(s->repo, s->sort_by_date);
8453 if (err)
8454 break;
8455 ref_view_free_refs(s);
8456 err = ref_view_load_refs(s);
8457 break;
8458 case KEY_RESIZE:
8459 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8460 s->selected = view->nlines - 2;
8461 break;
8462 default:
8463 view->count = 0;
8464 break;
8467 return err;
8470 __dead static void
8471 usage_ref(void)
8473 endwin();
8474 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8475 getprogname());
8476 exit(1);
8479 static const struct got_error *
8480 cmd_ref(int argc, char *argv[])
8482 const struct got_error *error;
8483 struct got_repository *repo = NULL;
8484 struct got_worktree *worktree = NULL;
8485 char *cwd = NULL, *repo_path = NULL;
8486 int ch;
8487 struct tog_view *view;
8488 int *pack_fds = NULL;
8490 while ((ch = getopt(argc, argv, "r:")) != -1) {
8491 switch (ch) {
8492 case 'r':
8493 repo_path = realpath(optarg, NULL);
8494 if (repo_path == NULL)
8495 return got_error_from_errno2("realpath",
8496 optarg);
8497 break;
8498 default:
8499 usage_ref();
8500 /* NOTREACHED */
8504 argc -= optind;
8505 argv += optind;
8507 if (argc > 1)
8508 usage_ref();
8510 error = got_repo_pack_fds_open(&pack_fds);
8511 if (error != NULL)
8512 goto done;
8514 if (repo_path == NULL) {
8515 cwd = getcwd(NULL, 0);
8516 if (cwd == NULL)
8517 return got_error_from_errno("getcwd");
8518 error = got_worktree_open(&worktree, cwd);
8519 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8520 goto done;
8521 if (worktree)
8522 repo_path =
8523 strdup(got_worktree_get_repo_path(worktree));
8524 else
8525 repo_path = strdup(cwd);
8526 if (repo_path == NULL) {
8527 error = got_error_from_errno("strdup");
8528 goto done;
8532 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8533 if (error != NULL)
8534 goto done;
8536 init_curses();
8538 error = apply_unveil(got_repo_get_path(repo), NULL);
8539 if (error)
8540 goto done;
8542 error = tog_load_refs(repo, 0);
8543 if (error)
8544 goto done;
8546 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8547 if (view == NULL) {
8548 error = got_error_from_errno("view_open");
8549 goto done;
8552 error = open_ref_view(view, repo);
8553 if (error)
8554 goto done;
8556 if (worktree) {
8557 /* Release work tree lock. */
8558 got_worktree_close(worktree);
8559 worktree = NULL;
8561 error = view_loop(view);
8562 done:
8563 free(repo_path);
8564 free(cwd);
8565 if (repo) {
8566 const struct got_error *close_err = got_repo_close(repo);
8567 if (close_err)
8568 error = close_err;
8570 if (pack_fds) {
8571 const struct got_error *pack_err =
8572 got_repo_pack_fds_close(pack_fds);
8573 if (error == NULL)
8574 error = pack_err;
8576 tog_free_refs();
8577 return error;
8580 static const struct got_error*
8581 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8582 const char *str)
8584 size_t len;
8586 if (win == NULL)
8587 win = stdscr;
8589 len = strlen(str);
8590 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8592 if (focus)
8593 wstandout(win);
8594 if (mvwprintw(win, y, x, "%s", str) == ERR)
8595 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8596 if (focus)
8597 wstandend(win);
8599 return NULL;
8602 static const struct got_error *
8603 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8605 off_t *p;
8607 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8608 if (p == NULL) {
8609 free(*line_offsets);
8610 *line_offsets = NULL;
8611 return got_error_from_errno("reallocarray");
8614 *line_offsets = p;
8615 (*line_offsets)[*nlines] = off;
8616 ++(*nlines);
8617 return NULL;
8620 static const struct got_error *
8621 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8623 *ret = 0;
8625 for (;n > 0; --n, ++km) {
8626 char *t0, *t, *k;
8627 size_t len = 1;
8629 if (km->keys == NULL)
8630 continue;
8632 t = t0 = strdup(km->keys);
8633 if (t0 == NULL)
8634 return got_error_from_errno("strdup");
8636 len += strlen(t);
8637 while ((k = strsep(&t, " ")) != NULL)
8638 len += strlen(k) > 1 ? 2 : 0;
8639 free(t0);
8640 *ret = MAX(*ret, len);
8643 return NULL;
8647 * Write keymap section headers, keys, and key info in km to f.
8648 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8649 * wrap control and symbolic keys in guillemets, else use <>.
8651 static const struct got_error *
8652 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8654 int n, len = width;
8656 if (km->keys) {
8657 static const char *u8_glyph[] = {
8658 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8659 "\xe2\x80\xba" /* U+203A (utf8 >) */
8661 char *t0, *t, *k;
8662 int cs, s, first = 1;
8664 cs = got_locale_is_utf8();
8666 t = t0 = strdup(km->keys);
8667 if (t0 == NULL)
8668 return got_error_from_errno("strdup");
8670 len = strlen(km->keys);
8671 while ((k = strsep(&t, " ")) != NULL) {
8672 s = strlen(k) > 1; /* control or symbolic key */
8673 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8674 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8675 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8676 if (n < 0) {
8677 free(t0);
8678 return got_error_from_errno("fprintf");
8680 first = 0;
8681 len += s ? 2 : 0;
8682 *off += n;
8684 free(t0);
8686 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8687 if (n < 0)
8688 return got_error_from_errno("fprintf");
8689 *off += n;
8691 return NULL;
8694 static const struct got_error *
8695 format_help(struct tog_help_view_state *s)
8697 const struct got_error *err = NULL;
8698 off_t off = 0;
8699 int i, max, n, show = s->all;
8700 static const struct tog_key_map km[] = {
8701 #define KEYMAP_(info, type) { NULL, (info), type }
8702 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8703 GENERATE_HELP
8704 #undef KEYMAP_
8705 #undef KEY_
8708 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8709 if (err)
8710 return err;
8712 n = nitems(km);
8713 err = max_key_str(&max, km, n);
8714 if (err)
8715 return err;
8717 for (i = 0; i < n; ++i) {
8718 if (km[i].keys == NULL) {
8719 show = s->all;
8720 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8721 km[i].type == s->type || s->all)
8722 show = 1;
8724 if (show) {
8725 err = format_help_line(&off, s->f, &km[i], max);
8726 if (err)
8727 return err;
8728 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8729 if (err)
8730 return err;
8733 fputc('\n', s->f);
8734 ++off;
8735 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8736 return err;
8739 static const struct got_error *
8740 create_help(struct tog_help_view_state *s)
8742 FILE *f;
8743 const struct got_error *err;
8745 free(s->line_offsets);
8746 s->line_offsets = NULL;
8747 s->nlines = 0;
8749 f = got_opentemp();
8750 if (f == NULL)
8751 return got_error_from_errno("got_opentemp");
8752 s->f = f;
8754 err = format_help(s);
8755 if (err)
8756 return err;
8758 if (s->f && fflush(s->f) != 0)
8759 return got_error_from_errno("fflush");
8761 return NULL;
8764 static const struct got_error *
8765 search_start_help_view(struct tog_view *view)
8767 view->state.help.matched_line = 0;
8768 return NULL;
8771 static void
8772 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8773 size_t *nlines, int **first, int **last, int **match, int **selected)
8775 struct tog_help_view_state *s = &view->state.help;
8777 *f = s->f;
8778 *nlines = s->nlines;
8779 *line_offsets = s->line_offsets;
8780 *match = &s->matched_line;
8781 *first = &s->first_displayed_line;
8782 *last = &s->last_displayed_line;
8783 *selected = &s->selected_line;
8786 static const struct got_error *
8787 show_help_view(struct tog_view *view)
8789 struct tog_help_view_state *s = &view->state.help;
8790 const struct got_error *err;
8791 regmatch_t *regmatch = &view->regmatch;
8792 wchar_t *wline;
8793 char *line;
8794 ssize_t linelen;
8795 size_t linesz = 0;
8796 int width, nprinted = 0, rc = 0;
8797 int eos = view->nlines;
8799 if (view_is_hsplit_top(view))
8800 --eos; /* account for border */
8802 s->lineno = 0;
8803 rewind(s->f);
8804 werase(view->window);
8806 if (view->gline > s->nlines - 1)
8807 view->gline = s->nlines - 1;
8809 err = win_draw_center(view->window, 0, 0, view->ncols,
8810 view_needs_focus_indication(view),
8811 "tog help (press q to return to tog)");
8812 if (err)
8813 return err;
8814 if (eos <= 1)
8815 return NULL;
8816 waddstr(view->window, "\n\n");
8817 eos -= 2;
8819 s->eof = 0;
8820 view->maxx = 0;
8821 line = NULL;
8822 while (eos > 0 && nprinted < eos) {
8823 attr_t attr = 0;
8825 linelen = getline(&line, &linesz, s->f);
8826 if (linelen == -1) {
8827 if (!feof(s->f)) {
8828 free(line);
8829 return got_ferror(s->f, GOT_ERR_IO);
8831 s->eof = 1;
8832 break;
8834 if (++s->lineno < s->first_displayed_line)
8835 continue;
8836 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8837 continue;
8838 if (s->lineno == view->hiline)
8839 attr = A_STANDOUT;
8841 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8842 view->x ? 1 : 0);
8843 if (err) {
8844 free(line);
8845 return err;
8847 view->maxx = MAX(view->maxx, width);
8848 free(wline);
8849 wline = NULL;
8851 if (attr)
8852 wattron(view->window, attr);
8853 if (s->first_displayed_line + nprinted == s->matched_line &&
8854 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8855 err = add_matched_line(&width, line, view->ncols - 1, 0,
8856 view->window, view->x, regmatch);
8857 if (err) {
8858 free(line);
8859 return err;
8861 } else {
8862 int skip;
8864 err = format_line(&wline, &width, &skip, line,
8865 view->x, view->ncols, 0, view->x ? 1 : 0);
8866 if (err) {
8867 free(line);
8868 return err;
8870 waddwstr(view->window, &wline[skip]);
8871 free(wline);
8872 wline = NULL;
8874 if (s->lineno == view->hiline) {
8875 while (width++ < view->ncols)
8876 waddch(view->window, ' ');
8877 } else {
8878 if (width < view->ncols)
8879 waddch(view->window, '\n');
8881 if (attr)
8882 wattroff(view->window, attr);
8883 if (++nprinted == 1)
8884 s->first_displayed_line = s->lineno;
8886 free(line);
8887 if (nprinted > 0)
8888 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8889 else
8890 s->last_displayed_line = s->first_displayed_line;
8892 view_border(view);
8894 if (s->eof) {
8895 rc = waddnstr(view->window,
8896 "See the tog(1) manual page for full documentation",
8897 view->ncols - 1);
8898 if (rc == ERR)
8899 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8900 } else {
8901 wmove(view->window, view->nlines - 1, 0);
8902 wclrtoeol(view->window);
8903 wstandout(view->window);
8904 rc = waddnstr(view->window, "scroll down for more...",
8905 view->ncols - 1);
8906 if (rc == ERR)
8907 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8908 if (getcurx(view->window) < view->ncols - 6) {
8909 rc = wprintw(view->window, "[%.0f%%]",
8910 100.00 * s->last_displayed_line / s->nlines);
8911 if (rc == ERR)
8912 return got_error_msg(GOT_ERR_IO, "wprintw");
8914 wstandend(view->window);
8917 return NULL;
8920 static const struct got_error *
8921 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8923 struct tog_help_view_state *s = &view->state.help;
8924 const struct got_error *err = NULL;
8925 char *line = NULL;
8926 ssize_t linelen;
8927 size_t linesz = 0;
8928 int eos, nscroll;
8930 eos = nscroll = view->nlines;
8931 if (view_is_hsplit_top(view))
8932 --eos; /* border */
8934 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8936 switch (ch) {
8937 case '0':
8938 case '$':
8939 case KEY_RIGHT:
8940 case 'l':
8941 case KEY_LEFT:
8942 case 'h':
8943 horizontal_scroll_input(view, ch);
8944 break;
8945 case 'g':
8946 case KEY_HOME:
8947 s->first_displayed_line = 1;
8948 view->count = 0;
8949 break;
8950 case 'G':
8951 case KEY_END:
8952 view->count = 0;
8953 if (s->eof)
8954 break;
8955 s->first_displayed_line = (s->nlines - eos) + 3;
8956 s->eof = 1;
8957 break;
8958 case 'k':
8959 case KEY_UP:
8960 if (s->first_displayed_line > 1)
8961 --s->first_displayed_line;
8962 else
8963 view->count = 0;
8964 break;
8965 case CTRL('u'):
8966 case 'u':
8967 nscroll /= 2;
8968 /* FALL THROUGH */
8969 case KEY_PPAGE:
8970 case CTRL('b'):
8971 case 'b':
8972 if (s->first_displayed_line == 1) {
8973 view->count = 0;
8974 break;
8976 while (--nscroll > 0 && s->first_displayed_line > 1)
8977 s->first_displayed_line--;
8978 break;
8979 case 'j':
8980 case KEY_DOWN:
8981 case CTRL('n'):
8982 if (!s->eof)
8983 ++s->first_displayed_line;
8984 else
8985 view->count = 0;
8986 break;
8987 case CTRL('d'):
8988 case 'd':
8989 nscroll /= 2;
8990 /* FALL THROUGH */
8991 case KEY_NPAGE:
8992 case CTRL('f'):
8993 case 'f':
8994 case ' ':
8995 if (s->eof) {
8996 view->count = 0;
8997 break;
8999 while (!s->eof && --nscroll > 0) {
9000 linelen = getline(&line, &linesz, s->f);
9001 s->first_displayed_line++;
9002 if (linelen == -1) {
9003 if (feof(s->f))
9004 s->eof = 1;
9005 else
9006 err = got_ferror(s->f, GOT_ERR_IO);
9007 break;
9010 free(line);
9011 break;
9012 default:
9013 view->count = 0;
9014 break;
9017 return err;
9020 static const struct got_error *
9021 close_help_view(struct tog_view *view)
9023 struct tog_help_view_state *s = &view->state.help;
9025 free(s->line_offsets);
9026 s->line_offsets = NULL;
9027 if (fclose(s->f) == EOF)
9028 return got_error_from_errno("fclose");
9030 return NULL;
9033 static const struct got_error *
9034 reset_help_view(struct tog_view *view)
9036 struct tog_help_view_state *s = &view->state.help;
9039 if (s->f && fclose(s->f) == EOF)
9040 return got_error_from_errno("fclose");
9042 wclear(view->window);
9043 view->count = 0;
9044 view->x = 0;
9045 s->all = !s->all;
9046 s->first_displayed_line = 1;
9047 s->last_displayed_line = view->nlines;
9048 s->matched_line = 0;
9050 return create_help(s);
9053 static const struct got_error *
9054 open_help_view(struct tog_view *view, struct tog_view *parent)
9056 const struct got_error *err = NULL;
9057 struct tog_help_view_state *s = &view->state.help;
9059 s->type = (enum tog_keymap_type)parent->type;
9060 s->first_displayed_line = 1;
9061 s->last_displayed_line = view->nlines;
9062 s->selected_line = 1;
9064 view->show = show_help_view;
9065 view->input = input_help_view;
9066 view->reset = reset_help_view;
9067 view->close = close_help_view;
9068 view->search_start = search_start_help_view;
9069 view->search_setup = search_setup_help_view;
9070 view->search_next = search_next_view_match;
9072 err = create_help(s);
9073 return err;
9076 static const struct got_error *
9077 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9078 enum tog_view_type request, int y, int x)
9080 const struct got_error *err = NULL;
9082 *new_view = NULL;
9084 switch (request) {
9085 case TOG_VIEW_DIFF:
9086 if (view->type == TOG_VIEW_LOG) {
9087 struct tog_log_view_state *s = &view->state.log;
9089 err = open_diff_view_for_commit(new_view, y, x,
9090 s->selected_entry->commit, s->selected_entry->id,
9091 view, s->repo);
9092 } else
9093 return got_error_msg(GOT_ERR_NOT_IMPL,
9094 "parent/child view pair not supported");
9095 break;
9096 case TOG_VIEW_BLAME:
9097 if (view->type == TOG_VIEW_TREE) {
9098 struct tog_tree_view_state *s = &view->state.tree;
9100 err = blame_tree_entry(new_view, y, x,
9101 s->selected_entry, &s->parents, s->commit_id,
9102 s->repo);
9103 } else
9104 return got_error_msg(GOT_ERR_NOT_IMPL,
9105 "parent/child view pair not supported");
9106 break;
9107 case TOG_VIEW_LOG:
9108 if (view->type == TOG_VIEW_BLAME)
9109 err = log_annotated_line(new_view, y, x,
9110 view->state.blame.repo, view->state.blame.id_to_log);
9111 else if (view->type == TOG_VIEW_TREE)
9112 err = log_selected_tree_entry(new_view, y, x,
9113 &view->state.tree);
9114 else if (view->type == TOG_VIEW_REF)
9115 err = log_ref_entry(new_view, y, x,
9116 view->state.ref.selected_entry,
9117 view->state.ref.repo);
9118 else
9119 return got_error_msg(GOT_ERR_NOT_IMPL,
9120 "parent/child view pair not supported");
9121 break;
9122 case TOG_VIEW_TREE:
9123 if (view->type == TOG_VIEW_LOG)
9124 err = browse_commit_tree(new_view, y, x,
9125 view->state.log.selected_entry,
9126 view->state.log.in_repo_path,
9127 view->state.log.head_ref_name,
9128 view->state.log.repo);
9129 else if (view->type == TOG_VIEW_REF)
9130 err = browse_ref_tree(new_view, y, x,
9131 view->state.ref.selected_entry,
9132 view->state.ref.repo);
9133 else
9134 return got_error_msg(GOT_ERR_NOT_IMPL,
9135 "parent/child view pair not supported");
9136 break;
9137 case TOG_VIEW_REF:
9138 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9139 if (*new_view == NULL)
9140 return got_error_from_errno("view_open");
9141 if (view->type == TOG_VIEW_LOG)
9142 err = open_ref_view(*new_view, view->state.log.repo);
9143 else if (view->type == TOG_VIEW_TREE)
9144 err = open_ref_view(*new_view, view->state.tree.repo);
9145 else
9146 err = got_error_msg(GOT_ERR_NOT_IMPL,
9147 "parent/child view pair not supported");
9148 if (err)
9149 view_close(*new_view);
9150 break;
9151 case TOG_VIEW_HELP:
9152 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9153 if (*new_view == NULL)
9154 return got_error_from_errno("view_open");
9155 err = open_help_view(*new_view, view);
9156 if (err)
9157 view_close(*new_view);
9158 break;
9159 default:
9160 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9163 return err;
9167 * If view was scrolled down to move the selected line into view when opening a
9168 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9170 static void
9171 offset_selection_up(struct tog_view *view)
9173 switch (view->type) {
9174 case TOG_VIEW_BLAME: {
9175 struct tog_blame_view_state *s = &view->state.blame;
9176 if (s->first_displayed_line == 1) {
9177 s->selected_line = MAX(s->selected_line - view->offset,
9178 1);
9179 break;
9181 if (s->first_displayed_line > view->offset)
9182 s->first_displayed_line -= view->offset;
9183 else
9184 s->first_displayed_line = 1;
9185 s->selected_line += view->offset;
9186 break;
9188 case TOG_VIEW_LOG:
9189 log_scroll_up(&view->state.log, view->offset);
9190 view->state.log.selected += view->offset;
9191 break;
9192 case TOG_VIEW_REF:
9193 ref_scroll_up(&view->state.ref, view->offset);
9194 view->state.ref.selected += view->offset;
9195 break;
9196 case TOG_VIEW_TREE:
9197 tree_scroll_up(&view->state.tree, view->offset);
9198 view->state.tree.selected += view->offset;
9199 break;
9200 default:
9201 break;
9204 view->offset = 0;
9208 * If the selected line is in the section of screen covered by the bottom split,
9209 * scroll down offset lines to move it into view and index its new position.
9211 static const struct got_error *
9212 offset_selection_down(struct tog_view *view)
9214 const struct got_error *err = NULL;
9215 const struct got_error *(*scrolld)(struct tog_view *, int);
9216 int *selected = NULL;
9217 int header, offset;
9219 switch (view->type) {
9220 case TOG_VIEW_BLAME: {
9221 struct tog_blame_view_state *s = &view->state.blame;
9222 header = 3;
9223 scrolld = NULL;
9224 if (s->selected_line > view->nlines - header) {
9225 offset = abs(view->nlines - s->selected_line - header);
9226 s->first_displayed_line += offset;
9227 s->selected_line -= offset;
9228 view->offset = offset;
9230 break;
9232 case TOG_VIEW_LOG: {
9233 struct tog_log_view_state *s = &view->state.log;
9234 scrolld = &log_scroll_down;
9235 header = view_is_parent_view(view) ? 3 : 2;
9236 selected = &s->selected;
9237 break;
9239 case TOG_VIEW_REF: {
9240 struct tog_ref_view_state *s = &view->state.ref;
9241 scrolld = &ref_scroll_down;
9242 header = 3;
9243 selected = &s->selected;
9244 break;
9246 case TOG_VIEW_TREE: {
9247 struct tog_tree_view_state *s = &view->state.tree;
9248 scrolld = &tree_scroll_down;
9249 header = 5;
9250 selected = &s->selected;
9251 break;
9253 default:
9254 selected = NULL;
9255 scrolld = NULL;
9256 header = 0;
9257 break;
9260 if (selected && *selected > view->nlines - header) {
9261 offset = abs(view->nlines - *selected - header);
9262 view->offset = offset;
9263 if (scrolld && offset) {
9264 err = scrolld(view, offset);
9265 *selected -= offset;
9269 return err;
9272 static void
9273 list_commands(FILE *fp)
9275 size_t i;
9277 fprintf(fp, "commands:");
9278 for (i = 0; i < nitems(tog_commands); i++) {
9279 const struct tog_cmd *cmd = &tog_commands[i];
9280 fprintf(fp, " %s", cmd->name);
9282 fputc('\n', fp);
9285 __dead static void
9286 usage(int hflag, int status)
9288 FILE *fp = (status == 0) ? stdout : stderr;
9290 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9291 getprogname());
9292 if (hflag) {
9293 fprintf(fp, "lazy usage: %s path\n", getprogname());
9294 list_commands(fp);
9296 exit(status);
9299 static char **
9300 make_argv(int argc, ...)
9302 va_list ap;
9303 char **argv;
9304 int i;
9306 va_start(ap, argc);
9308 argv = calloc(argc, sizeof(char *));
9309 if (argv == NULL)
9310 err(1, "calloc");
9311 for (i = 0; i < argc; i++) {
9312 argv[i] = strdup(va_arg(ap, char *));
9313 if (argv[i] == NULL)
9314 err(1, "strdup");
9317 va_end(ap);
9318 return argv;
9322 * Try to convert 'tog path' into a 'tog log path' command.
9323 * The user could simply have mistyped the command rather than knowingly
9324 * provided a path. So check whether argv[0] can in fact be resolved
9325 * to a path in the HEAD commit and print a special error if not.
9326 * This hack is for mpi@ <3
9328 static const struct got_error *
9329 tog_log_with_path(int argc, char *argv[])
9331 const struct got_error *error = NULL, *close_err;
9332 const struct tog_cmd *cmd = NULL;
9333 struct got_repository *repo = NULL;
9334 struct got_worktree *worktree = NULL;
9335 struct got_object_id *commit_id = NULL, *id = NULL;
9336 struct got_commit_object *commit = NULL;
9337 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9338 char *commit_id_str = NULL, **cmd_argv = NULL;
9339 int *pack_fds = NULL;
9341 cwd = getcwd(NULL, 0);
9342 if (cwd == NULL)
9343 return got_error_from_errno("getcwd");
9345 error = got_repo_pack_fds_open(&pack_fds);
9346 if (error != NULL)
9347 goto done;
9349 error = got_worktree_open(&worktree, cwd);
9350 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9351 goto done;
9353 if (worktree)
9354 repo_path = strdup(got_worktree_get_repo_path(worktree));
9355 else
9356 repo_path = strdup(cwd);
9357 if (repo_path == NULL) {
9358 error = got_error_from_errno("strdup");
9359 goto done;
9362 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9363 if (error != NULL)
9364 goto done;
9366 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9367 repo, worktree);
9368 if (error)
9369 goto done;
9371 error = tog_load_refs(repo, 0);
9372 if (error)
9373 goto done;
9374 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9375 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9376 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9377 if (error)
9378 goto done;
9380 if (worktree) {
9381 got_worktree_close(worktree);
9382 worktree = NULL;
9385 error = got_object_open_as_commit(&commit, repo, commit_id);
9386 if (error)
9387 goto done;
9389 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9390 if (error) {
9391 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9392 goto done;
9393 fprintf(stderr, "%s: '%s' is no known command or path\n",
9394 getprogname(), argv[0]);
9395 usage(1, 1);
9396 /* not reached */
9399 error = got_object_id_str(&commit_id_str, commit_id);
9400 if (error)
9401 goto done;
9403 cmd = &tog_commands[0]; /* log */
9404 argc = 4;
9405 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9406 error = cmd->cmd_main(argc, cmd_argv);
9407 done:
9408 if (repo) {
9409 close_err = got_repo_close(repo);
9410 if (error == NULL)
9411 error = close_err;
9413 if (commit)
9414 got_object_commit_close(commit);
9415 if (worktree)
9416 got_worktree_close(worktree);
9417 if (pack_fds) {
9418 const struct got_error *pack_err =
9419 got_repo_pack_fds_close(pack_fds);
9420 if (error == NULL)
9421 error = pack_err;
9423 free(id);
9424 free(commit_id_str);
9425 free(commit_id);
9426 free(cwd);
9427 free(repo_path);
9428 free(in_repo_path);
9429 if (cmd_argv) {
9430 int i;
9431 for (i = 0; i < argc; i++)
9432 free(cmd_argv[i]);
9433 free(cmd_argv);
9435 tog_free_refs();
9436 return error;
9439 int
9440 main(int argc, char *argv[])
9442 const struct got_error *error = NULL;
9443 const struct tog_cmd *cmd = NULL;
9444 int ch, hflag = 0, Vflag = 0;
9445 char **cmd_argv = NULL;
9446 static const struct option longopts[] = {
9447 { "version", no_argument, NULL, 'V' },
9448 { NULL, 0, NULL, 0}
9450 char *diff_algo_str = NULL;
9452 if (!isatty(STDIN_FILENO))
9453 errx(1, "standard input is not a tty");
9455 setlocale(LC_CTYPE, "");
9457 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9458 switch (ch) {
9459 case 'h':
9460 hflag = 1;
9461 break;
9462 case 'V':
9463 Vflag = 1;
9464 break;
9465 default:
9466 usage(hflag, 1);
9467 /* NOTREACHED */
9471 argc -= optind;
9472 argv += optind;
9473 optind = 1;
9474 optreset = 1;
9476 if (Vflag) {
9477 got_version_print_str();
9478 return 0;
9481 #ifndef PROFILE
9482 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9483 NULL) == -1)
9484 err(1, "pledge");
9485 #endif
9487 if (argc == 0) {
9488 if (hflag)
9489 usage(hflag, 0);
9490 /* Build an argument vector which runs a default command. */
9491 cmd = &tog_commands[0];
9492 argc = 1;
9493 cmd_argv = make_argv(argc, cmd->name);
9494 } else {
9495 size_t i;
9497 /* Did the user specify a command? */
9498 for (i = 0; i < nitems(tog_commands); i++) {
9499 if (strncmp(tog_commands[i].name, argv[0],
9500 strlen(argv[0])) == 0) {
9501 cmd = &tog_commands[i];
9502 break;
9507 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9508 if (diff_algo_str) {
9509 if (strcasecmp(diff_algo_str, "patience") == 0)
9510 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9511 if (strcasecmp(diff_algo_str, "myers") == 0)
9512 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9515 if (cmd == NULL) {
9516 if (argc != 1)
9517 usage(0, 1);
9518 /* No command specified; try log with a path */
9519 error = tog_log_with_path(argc, argv);
9520 } else {
9521 if (hflag)
9522 cmd->cmd_usage();
9523 else
9524 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9527 endwin();
9528 if (cmd_argv) {
9529 int i;
9530 for (i = 0; i < argc; i++)
9531 free(cmd_argv[i]);
9532 free(cmd_argv);
9535 if (error && error->code != GOT_ERR_CANCELLED &&
9536 error->code != GOT_ERR_EOF &&
9537 error->code != GOT_ERR_PRIVSEP_EXIT &&
9538 error->code != GOT_ERR_PRIVSEP_PIPE &&
9539 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9540 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9541 return 0;