Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #if defined(__FreeBSD__) || defined(__APPLE__)
24 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
25 #endif
26 #include <curses.h>
27 #include <panel.h>
28 #include <locale.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_compat.h"
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 TOG_VIEW_HELP
112 };
114 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
115 enum tog_keymap_type {
116 TOG_KEYMAP_KEYS = -2,
117 TOG_KEYMAP_GLOBAL,
118 TOG_KEYMAP_DIFF,
119 TOG_KEYMAP_LOG,
120 TOG_KEYMAP_BLAME,
121 TOG_KEYMAP_TREE,
122 TOG_KEYMAP_REF,
123 TOG_KEYMAP_HELP
124 };
126 enum tog_view_mode {
127 TOG_VIEW_SPLIT_NONE,
128 TOG_VIEW_SPLIT_VERT,
129 TOG_VIEW_SPLIT_HRZN
130 };
132 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
134 #define TOG_EOF_STRING "(END)"
136 struct commit_queue_entry {
137 TAILQ_ENTRY(commit_queue_entry) entry;
138 struct got_object_id *id;
139 struct got_commit_object *commit;
140 int idx;
141 };
142 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
143 struct commit_queue {
144 int ncommits;
145 struct commit_queue_head head;
146 };
148 struct tog_color {
149 STAILQ_ENTRY(tog_color) entry;
150 regex_t regex;
151 short colorpair;
152 };
153 STAILQ_HEAD(tog_colors, tog_color);
155 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
156 static struct got_reflist_object_id_map *tog_refs_idmap;
157 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
159 static const struct got_error *
160 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
161 struct got_reference* re2)
163 const char *name1 = got_ref_get_name(re1);
164 const char *name2 = got_ref_get_name(re2);
165 int isbackup1, isbackup2;
167 /* Sort backup refs towards the bottom of the list. */
168 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
169 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
170 if (!isbackup1 && isbackup2) {
171 *cmp = -1;
172 return NULL;
173 } else if (isbackup1 && !isbackup2) {
174 *cmp = 1;
175 return NULL;
178 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
179 return NULL;
182 static const struct got_error *
183 tog_load_refs(struct got_repository *repo, int sort_by_date)
185 const struct got_error *err;
187 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
188 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
189 repo);
190 if (err)
191 return err;
193 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
194 repo);
197 static void
198 tog_free_refs(void)
200 if (tog_refs_idmap) {
201 got_reflist_object_id_map_free(tog_refs_idmap);
202 tog_refs_idmap = NULL;
204 got_ref_list_free(&tog_refs);
207 static const struct got_error *
208 add_color(struct tog_colors *colors, const char *pattern,
209 int idx, short color)
211 const struct got_error *err = NULL;
212 struct tog_color *tc;
213 int regerr = 0;
215 if (idx < 1 || idx > COLOR_PAIRS - 1)
216 return NULL;
218 init_pair(idx, color, -1);
220 tc = calloc(1, sizeof(*tc));
221 if (tc == NULL)
222 return got_error_from_errno("calloc");
223 regerr = regcomp(&tc->regex, pattern,
224 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
225 if (regerr) {
226 static char regerr_msg[512];
227 static char err_msg[512];
228 regerror(regerr, &tc->regex, regerr_msg,
229 sizeof(regerr_msg));
230 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
231 regerr_msg);
232 err = got_error_msg(GOT_ERR_REGEX, err_msg);
233 free(tc);
234 return err;
236 tc->colorpair = idx;
237 STAILQ_INSERT_HEAD(colors, tc, entry);
238 return NULL;
241 static void
242 free_colors(struct tog_colors *colors)
244 struct tog_color *tc;
246 while (!STAILQ_EMPTY(colors)) {
247 tc = STAILQ_FIRST(colors);
248 STAILQ_REMOVE_HEAD(colors, entry);
249 regfree(&tc->regex);
250 free(tc);
254 static struct tog_color *
255 get_color(struct tog_colors *colors, int colorpair)
257 struct tog_color *tc = NULL;
259 STAILQ_FOREACH(tc, colors, entry) {
260 if (tc->colorpair == colorpair)
261 return tc;
264 return NULL;
267 static int
268 default_color_value(const char *envvar)
270 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
271 return COLOR_MAGENTA;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
273 return COLOR_CYAN;
274 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
275 return COLOR_YELLOW;
276 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
277 return COLOR_GREEN;
278 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
279 return COLOR_MAGENTA;
280 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
283 return COLOR_CYAN;
284 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
285 return COLOR_GREEN;
286 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
287 return COLOR_GREEN;
288 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
289 return COLOR_CYAN;
290 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
291 return COLOR_YELLOW;
292 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
293 return COLOR_GREEN;
294 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
295 return COLOR_MAGENTA;
296 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
297 return COLOR_YELLOW;
298 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
299 return COLOR_CYAN;
301 return -1;
304 static int
305 get_color_value(const char *envvar)
307 const char *val = getenv(envvar);
309 if (val == NULL)
310 return default_color_value(envvar);
312 if (strcasecmp(val, "black") == 0)
313 return COLOR_BLACK;
314 if (strcasecmp(val, "red") == 0)
315 return COLOR_RED;
316 if (strcasecmp(val, "green") == 0)
317 return COLOR_GREEN;
318 if (strcasecmp(val, "yellow") == 0)
319 return COLOR_YELLOW;
320 if (strcasecmp(val, "blue") == 0)
321 return COLOR_BLUE;
322 if (strcasecmp(val, "magenta") == 0)
323 return COLOR_MAGENTA;
324 if (strcasecmp(val, "cyan") == 0)
325 return COLOR_CYAN;
326 if (strcasecmp(val, "white") == 0)
327 return COLOR_WHITE;
328 if (strcasecmp(val, "default") == 0)
329 return -1;
331 return default_color_value(envvar);
334 struct tog_diff_view_state {
335 struct got_object_id *id1, *id2;
336 const char *label1, *label2;
337 FILE *f, *f1, *f2;
338 int fd1, fd2;
339 int lineno;
340 int first_displayed_line;
341 int last_displayed_line;
342 int eof;
343 int diff_context;
344 int ignore_whitespace;
345 int force_text_diff;
346 struct got_repository *repo;
347 struct got_diff_line *lines;
348 size_t nlines;
349 int matched_line;
350 int selected_line;
352 /* passed from log or blame view; may be NULL */
353 struct tog_view *parent_view;
354 };
356 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
357 static volatile sig_atomic_t tog_thread_error;
359 struct tog_log_thread_args {
360 pthread_cond_t need_commits;
361 pthread_cond_t commit_loaded;
362 int commits_needed;
363 int load_all;
364 struct got_commit_graph *graph;
365 struct commit_queue *real_commits;
366 const char *in_repo_path;
367 struct got_object_id *start_id;
368 struct got_repository *repo;
369 int *pack_fds;
370 int log_complete;
371 sig_atomic_t *quit;
372 struct commit_queue_entry **first_displayed_entry;
373 struct commit_queue_entry **selected_entry;
374 int *searching;
375 int *search_next_done;
376 regex_t *regex;
377 int *limiting;
378 int limit_match;
379 regex_t *limit_regex;
380 struct commit_queue *limit_commits;
381 };
383 struct tog_log_view_state {
384 struct commit_queue *commits;
385 struct commit_queue_entry *first_displayed_entry;
386 struct commit_queue_entry *last_displayed_entry;
387 struct commit_queue_entry *selected_entry;
388 struct commit_queue real_commits;
389 int selected;
390 char *in_repo_path;
391 char *head_ref_name;
392 int log_branches;
393 struct got_repository *repo;
394 struct got_object_id *start_id;
395 sig_atomic_t quit;
396 pthread_t thread;
397 struct tog_log_thread_args thread_args;
398 struct commit_queue_entry *matched_entry;
399 struct commit_queue_entry *search_entry;
400 struct tog_colors colors;
401 int use_committer;
402 int limit_view;
403 regex_t limit_regex;
404 struct commit_queue limit_commits;
405 };
407 #define TOG_COLOR_DIFF_MINUS 1
408 #define TOG_COLOR_DIFF_PLUS 2
409 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
410 #define TOG_COLOR_DIFF_META 4
411 #define TOG_COLOR_TREE_SUBMODULE 5
412 #define TOG_COLOR_TREE_SYMLINK 6
413 #define TOG_COLOR_TREE_DIRECTORY 7
414 #define TOG_COLOR_TREE_EXECUTABLE 8
415 #define TOG_COLOR_COMMIT 9
416 #define TOG_COLOR_AUTHOR 10
417 #define TOG_COLOR_DATE 11
418 #define TOG_COLOR_REFS_HEADS 12
419 #define TOG_COLOR_REFS_TAGS 13
420 #define TOG_COLOR_REFS_REMOTES 14
421 #define TOG_COLOR_REFS_BACKUP 15
423 struct tog_blame_cb_args {
424 struct tog_blame_line *lines; /* one per line */
425 int nlines;
427 struct tog_view *view;
428 struct got_object_id *commit_id;
429 int *quit;
430 };
432 struct tog_blame_thread_args {
433 const char *path;
434 struct got_repository *repo;
435 struct tog_blame_cb_args *cb_args;
436 int *complete;
437 got_cancel_cb cancel_cb;
438 void *cancel_arg;
439 };
441 struct tog_blame {
442 FILE *f;
443 off_t filesize;
444 struct tog_blame_line *lines;
445 int nlines;
446 off_t *line_offsets;
447 pthread_t thread;
448 struct tog_blame_thread_args thread_args;
449 struct tog_blame_cb_args cb_args;
450 const char *path;
451 int *pack_fds;
452 };
454 struct tog_blame_view_state {
455 int first_displayed_line;
456 int last_displayed_line;
457 int selected_line;
458 int last_diffed_line;
459 int blame_complete;
460 int eof;
461 int done;
462 struct got_object_id_queue blamed_commits;
463 struct got_object_qid *blamed_commit;
464 char *path;
465 struct got_repository *repo;
466 struct got_object_id *commit_id;
467 struct got_object_id *id_to_log;
468 struct tog_blame blame;
469 int matched_line;
470 struct tog_colors colors;
471 };
473 struct tog_parent_tree {
474 TAILQ_ENTRY(tog_parent_tree) entry;
475 struct got_tree_object *tree;
476 struct got_tree_entry *first_displayed_entry;
477 struct got_tree_entry *selected_entry;
478 int selected;
479 };
481 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
483 struct tog_tree_view_state {
484 char *tree_label;
485 struct got_object_id *commit_id;/* commit which this tree belongs to */
486 struct got_tree_object *root; /* the commit's root tree entry */
487 struct got_tree_object *tree; /* currently displayed (sub-)tree */
488 struct got_tree_entry *first_displayed_entry;
489 struct got_tree_entry *last_displayed_entry;
490 struct got_tree_entry *selected_entry;
491 int ndisplayed, selected, show_ids;
492 struct tog_parent_trees parents; /* parent trees of current sub-tree */
493 char *head_ref_name;
494 struct got_repository *repo;
495 struct got_tree_entry *matched_entry;
496 struct tog_colors colors;
497 };
499 struct tog_reflist_entry {
500 TAILQ_ENTRY(tog_reflist_entry) entry;
501 struct got_reference *ref;
502 int idx;
503 };
505 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
507 struct tog_ref_view_state {
508 struct tog_reflist_head refs;
509 struct tog_reflist_entry *first_displayed_entry;
510 struct tog_reflist_entry *last_displayed_entry;
511 struct tog_reflist_entry *selected_entry;
512 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
513 struct got_repository *repo;
514 struct tog_reflist_entry *matched_entry;
515 struct tog_colors colors;
516 };
518 struct tog_help_view_state {
519 FILE *f;
520 off_t *line_offsets;
521 size_t nlines;
522 int lineno;
523 int first_displayed_line;
524 int last_displayed_line;
525 int eof;
526 int matched_line;
527 int selected_line;
528 int all;
529 enum tog_keymap_type type;
530 };
532 #define GENERATE_HELP \
533 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
534 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
535 KEY_("k C-p Up", "Move cursor or page up one line"), \
536 KEY_("j C-n Down", "Move cursor or page down one line"), \
537 KEY_("C-b b PgUp", "Scroll the view up one page"), \
538 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
539 KEY_("C-u u", "Scroll the view up one half page"), \
540 KEY_("C-d d", "Scroll the view down one half page"), \
541 KEY_("g", "Go to line N (default: first line)"), \
542 KEY_("Home =", "Go to the first line"), \
543 KEY_("G", "Go to line N (default: last line)"), \
544 KEY_("End *", "Go to the last line"), \
545 KEY_("l Right", "Scroll the view right"), \
546 KEY_("h Left", "Scroll the view left"), \
547 KEY_("$", "Scroll view to the rightmost position"), \
548 KEY_("0", "Scroll view to the leftmost position"), \
549 KEY_("-", "Decrease size of the focussed split"), \
550 KEY_("+", "Increase size of the focussed split"), \
551 KEY_("Tab", "Switch focus between views"), \
552 KEY_("F", "Toggle fullscreen mode"), \
553 KEY_("/", "Open prompt to enter search term"), \
554 KEY_("n", "Find next line/token matching the current search term"), \
555 KEY_("N", "Find previous line/token matching the current search term"),\
556 KEY_("q", "Quit the focussed view; Quit help screen"), \
557 KEY_("Q", "Quit tog"), \
559 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
560 KEY_("< ,", "Move cursor up one commit"), \
561 KEY_("> .", "Move cursor down one commit"), \
562 KEY_("Enter", "Open diff view of the selected commit"), \
563 KEY_("B", "Reload the log view and toggle display of merged commits"), \
564 KEY_("R", "Open ref view of all repository references"), \
565 KEY_("T", "Display tree view of the repository from the selected" \
566 " commit"), \
567 KEY_("@", "Toggle between displaying author and committer name"), \
568 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
569 KEY_("C-g Backspace", "Cancel current search or log operation"), \
570 KEY_("C-l", "Reload the log view with new commits in the repository"), \
572 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
573 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
574 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
575 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
576 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
577 " data"), \
578 KEY_("(", "Go to the previous file in the diff"), \
579 KEY_(")", "Go to the next file in the diff"), \
580 KEY_("{", "Go to the previous hunk in the diff"), \
581 KEY_("}", "Go to the next hunk in the diff"), \
582 KEY_("[", "Decrease the number of context lines"), \
583 KEY_("]", "Increase the number of context lines"), \
584 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
586 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
587 KEY_("Enter", "Display diff view of the selected line's commit"), \
588 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
589 KEY_("L", "Open log view for the currently selected annotated line"), \
590 KEY_("C", "Reload view with the previously blamed commit"), \
591 KEY_("c", "Reload view with the version of the file found in the" \
592 " selected line's commit"), \
593 KEY_("p", "Reload view with the version of the file found in the" \
594 " selected line's parent commit"), \
596 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
597 KEY_("Enter", "Enter selected directory or open blame view of the" \
598 " selected file"), \
599 KEY_("L", "Open log view for the selected entry"), \
600 KEY_("R", "Open ref view of all repository references"), \
601 KEY_("i", "Show object IDs for all tree entries"), \
602 KEY_("Backspace", "Return to the parent directory"), \
604 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
605 KEY_("Enter", "Display log view of the selected reference"), \
606 KEY_("T", "Display tree view of the selected reference"), \
607 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
608 KEY_("m", "Toggle display of last modified date for each reference"), \
609 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
610 KEY_("C-l", "Reload view with all repository references")
612 struct tog_key_map {
613 const char *keys;
614 const char *info;
615 enum tog_keymap_type type;
616 };
618 /*
619 * We implement two types of views: parent views and child views.
621 * The 'Tab' key switches focus between a parent view and its child view.
622 * Child views are shown side-by-side to their parent view, provided
623 * there is enough screen estate.
625 * When a new view is opened from within a parent view, this new view
626 * becomes a child view of the parent view, replacing any existing child.
628 * When a new view is opened from within a child view, this new view
629 * becomes a parent view which will obscure the views below until the
630 * user quits the new parent view by typing 'q'.
632 * This list of views contains parent views only.
633 * Child views are only pointed to by their parent view.
634 */
635 TAILQ_HEAD(tog_view_list_head, tog_view);
637 struct tog_view {
638 TAILQ_ENTRY(tog_view) entry;
639 WINDOW *window;
640 PANEL *panel;
641 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
642 int resized_y, resized_x; /* begin_y/x based on user resizing */
643 int maxx, x; /* max column and current start column */
644 int lines, cols; /* copies of LINES and COLS */
645 int nscrolled, offset; /* lines scrolled and hsplit line offset */
646 int gline, hiline; /* navigate to and highlight this nG line */
647 int ch, count; /* current keymap and count prefix */
648 int resized; /* set when in a resize event */
649 int focussed; /* Only set on one parent or child view at a time. */
650 int dying;
651 struct tog_view *parent;
652 struct tog_view *child;
654 /*
655 * This flag is initially set on parent views when a new child view
656 * is created. It gets toggled when the 'Tab' key switches focus
657 * between parent and child.
658 * The flag indicates whether focus should be passed on to our child
659 * view if this parent view gets picked for focus after another parent
660 * view was closed. This prevents child views from losing focus in such
661 * situations.
662 */
663 int focus_child;
665 enum tog_view_mode mode;
666 /* type-specific state */
667 enum tog_view_type type;
668 union {
669 struct tog_diff_view_state diff;
670 struct tog_log_view_state log;
671 struct tog_blame_view_state blame;
672 struct tog_tree_view_state tree;
673 struct tog_ref_view_state ref;
674 struct tog_help_view_state help;
675 } state;
677 const struct got_error *(*show)(struct tog_view *);
678 const struct got_error *(*input)(struct tog_view **,
679 struct tog_view *, int);
680 const struct got_error *(*reset)(struct tog_view *);
681 const struct got_error *(*resize)(struct tog_view *, int);
682 const struct got_error *(*close)(struct tog_view *);
684 const struct got_error *(*search_start)(struct tog_view *);
685 const struct got_error *(*search_next)(struct tog_view *);
686 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
687 int **, int **, int **, int **);
688 int search_started;
689 int searching;
690 #define TOG_SEARCH_FORWARD 1
691 #define TOG_SEARCH_BACKWARD 2
692 int search_next_done;
693 #define TOG_SEARCH_HAVE_MORE 1
694 #define TOG_SEARCH_NO_MORE 2
695 #define TOG_SEARCH_HAVE_NONE 3
696 regex_t regex;
697 regmatch_t regmatch;
698 };
700 static const struct got_error *open_diff_view(struct tog_view *,
701 struct got_object_id *, struct got_object_id *,
702 const char *, const char *, int, int, int, struct tog_view *,
703 struct got_repository *);
704 static const struct got_error *show_diff_view(struct tog_view *);
705 static const struct got_error *input_diff_view(struct tog_view **,
706 struct tog_view *, int);
707 static const struct got_error *reset_diff_view(struct tog_view *);
708 static const struct got_error* close_diff_view(struct tog_view *);
709 static const struct got_error *search_start_diff_view(struct tog_view *);
710 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
711 size_t *, int **, int **, int **, int **);
712 static const struct got_error *search_next_view_match(struct tog_view *);
714 static const struct got_error *open_log_view(struct tog_view *,
715 struct got_object_id *, struct got_repository *,
716 const char *, const char *, int);
717 static const struct got_error * show_log_view(struct tog_view *);
718 static const struct got_error *input_log_view(struct tog_view **,
719 struct tog_view *, int);
720 static const struct got_error *resize_log_view(struct tog_view *, int);
721 static const struct got_error *close_log_view(struct tog_view *);
722 static const struct got_error *search_start_log_view(struct tog_view *);
723 static const struct got_error *search_next_log_view(struct tog_view *);
725 static const struct got_error *open_blame_view(struct tog_view *, char *,
726 struct got_object_id *, struct got_repository *);
727 static const struct got_error *show_blame_view(struct tog_view *);
728 static const struct got_error *input_blame_view(struct tog_view **,
729 struct tog_view *, int);
730 static const struct got_error *reset_blame_view(struct tog_view *);
731 static const struct got_error *close_blame_view(struct tog_view *);
732 static const struct got_error *search_start_blame_view(struct tog_view *);
733 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
734 size_t *, int **, int **, int **, int **);
736 static const struct got_error *open_tree_view(struct tog_view *,
737 struct got_object_id *, const char *, struct got_repository *);
738 static const struct got_error *show_tree_view(struct tog_view *);
739 static const struct got_error *input_tree_view(struct tog_view **,
740 struct tog_view *, int);
741 static const struct got_error *close_tree_view(struct tog_view *);
742 static const struct got_error *search_start_tree_view(struct tog_view *);
743 static const struct got_error *search_next_tree_view(struct tog_view *);
745 static const struct got_error *open_ref_view(struct tog_view *,
746 struct got_repository *);
747 static const struct got_error *show_ref_view(struct tog_view *);
748 static const struct got_error *input_ref_view(struct tog_view **,
749 struct tog_view *, int);
750 static const struct got_error *close_ref_view(struct tog_view *);
751 static const struct got_error *search_start_ref_view(struct tog_view *);
752 static const struct got_error *search_next_ref_view(struct tog_view *);
754 static const struct got_error *open_help_view(struct tog_view *,
755 struct tog_view *);
756 static const struct got_error *show_help_view(struct tog_view *);
757 static const struct got_error *input_help_view(struct tog_view **,
758 struct tog_view *, int);
759 static const struct got_error *reset_help_view(struct tog_view *);
760 static const struct got_error* close_help_view(struct tog_view *);
761 static const struct got_error *search_start_help_view(struct tog_view *);
762 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
763 size_t *, int **, int **, int **, int **);
765 static volatile sig_atomic_t tog_sigwinch_received;
766 static volatile sig_atomic_t tog_sigpipe_received;
767 static volatile sig_atomic_t tog_sigcont_received;
768 static volatile sig_atomic_t tog_sigint_received;
769 static volatile sig_atomic_t tog_sigterm_received;
771 static void
772 tog_sigwinch(int signo)
774 tog_sigwinch_received = 1;
777 static void
778 tog_sigpipe(int signo)
780 tog_sigpipe_received = 1;
783 static void
784 tog_sigcont(int signo)
786 tog_sigcont_received = 1;
789 static void
790 tog_sigint(int signo)
792 tog_sigint_received = 1;
795 static void
796 tog_sigterm(int signo)
798 tog_sigterm_received = 1;
801 static int
802 tog_fatal_signal_received(void)
804 return (tog_sigpipe_received ||
805 tog_sigint_received || tog_sigterm_received);
808 static const struct got_error *
809 view_close(struct tog_view *view)
811 const struct got_error *err = NULL, *child_err = NULL;
813 if (view->child) {
814 child_err = view_close(view->child);
815 view->child = NULL;
817 if (view->close)
818 err = view->close(view);
819 if (view->panel)
820 del_panel(view->panel);
821 if (view->window)
822 delwin(view->window);
823 free(view);
824 return err ? err : child_err;
827 static struct tog_view *
828 view_open(int nlines, int ncols, int begin_y, int begin_x,
829 enum tog_view_type type)
831 struct tog_view *view = calloc(1, sizeof(*view));
833 if (view == NULL)
834 return NULL;
836 view->type = type;
837 view->lines = LINES;
838 view->cols = COLS;
839 view->nlines = nlines ? nlines : LINES - begin_y;
840 view->ncols = ncols ? ncols : COLS - begin_x;
841 view->begin_y = begin_y;
842 view->begin_x = begin_x;
843 view->window = newwin(nlines, ncols, begin_y, begin_x);
844 if (view->window == NULL) {
845 view_close(view);
846 return NULL;
848 view->panel = new_panel(view->window);
849 if (view->panel == NULL ||
850 set_panel_userptr(view->panel, view) != OK) {
851 view_close(view);
852 return NULL;
855 keypad(view->window, TRUE);
856 return view;
859 static int
860 view_split_begin_x(int begin_x)
862 if (begin_x > 0 || COLS < 120)
863 return 0;
864 return (COLS - MAX(COLS / 2, 80));
867 /* XXX Stub till we decide what to do. */
868 static int
869 view_split_begin_y(int lines)
871 return lines * HSPLIT_SCALE;
874 static const struct got_error *view_resize(struct tog_view *);
876 static const struct got_error *
877 view_splitscreen(struct tog_view *view)
879 const struct got_error *err = NULL;
881 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
882 if (view->resized_y && view->resized_y < view->lines)
883 view->begin_y = view->resized_y;
884 else
885 view->begin_y = view_split_begin_y(view->nlines);
886 view->begin_x = 0;
887 } else if (!view->resized) {
888 if (view->resized_x && view->resized_x < view->cols - 1 &&
889 view->cols > 119)
890 view->begin_x = view->resized_x;
891 else
892 view->begin_x = view_split_begin_x(0);
893 view->begin_y = 0;
895 view->nlines = LINES - view->begin_y;
896 view->ncols = COLS - view->begin_x;
897 view->lines = LINES;
898 view->cols = COLS;
899 err = view_resize(view);
900 if (err)
901 return err;
903 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
904 view->parent->nlines = view->begin_y;
906 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
907 return got_error_from_errno("mvwin");
909 return NULL;
912 static const struct got_error *
913 view_fullscreen(struct tog_view *view)
915 const struct got_error *err = NULL;
917 view->begin_x = 0;
918 view->begin_y = view->resized ? view->begin_y : 0;
919 view->nlines = view->resized ? view->nlines : LINES;
920 view->ncols = COLS;
921 view->lines = LINES;
922 view->cols = COLS;
923 err = view_resize(view);
924 if (err)
925 return err;
927 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
928 return got_error_from_errno("mvwin");
930 return NULL;
933 static int
934 view_is_parent_view(struct tog_view *view)
936 return view->parent == NULL;
939 static int
940 view_is_splitscreen(struct tog_view *view)
942 return view->begin_x > 0 || view->begin_y > 0;
945 static int
946 view_is_fullscreen(struct tog_view *view)
948 return view->nlines == LINES && view->ncols == COLS;
951 static int
952 view_is_hsplit_top(struct tog_view *view)
954 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
955 view_is_splitscreen(view->child);
958 static void
959 view_border(struct tog_view *view)
961 PANEL *panel;
962 const struct tog_view *view_above;
964 if (view->parent)
965 return view_border(view->parent);
967 panel = panel_above(view->panel);
968 if (panel == NULL)
969 return;
971 view_above = panel_userptr(panel);
972 if (view->mode == TOG_VIEW_SPLIT_HRZN)
973 mvwhline(view->window, view_above->begin_y - 1,
974 view->begin_x, got_locale_is_utf8() ?
975 ACS_HLINE : '-', view->ncols);
976 else
977 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
978 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
981 static const struct got_error *view_init_hsplit(struct tog_view *, int);
982 static const struct got_error *request_log_commits(struct tog_view *);
983 static const struct got_error *offset_selection_down(struct tog_view *);
984 static void offset_selection_up(struct tog_view *);
985 static void view_get_split(struct tog_view *, int *, int *);
987 static const struct got_error *
988 view_resize(struct tog_view *view)
990 const struct got_error *err = NULL;
991 int dif, nlines, ncols;
993 dif = LINES - view->lines; /* line difference */
995 if (view->lines > LINES)
996 nlines = view->nlines - (view->lines - LINES);
997 else
998 nlines = view->nlines + (LINES - view->lines);
999 if (view->cols > COLS)
1000 ncols = view->ncols - (view->cols - COLS);
1001 else
1002 ncols = view->ncols + (COLS - view->cols);
1004 if (view->child) {
1005 int hs = view->child->begin_y;
1007 if (!view_is_fullscreen(view))
1008 view->child->begin_x = view_split_begin_x(view->begin_x);
1009 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1010 view->child->begin_x == 0) {
1011 ncols = COLS;
1013 view_fullscreen(view->child);
1014 if (view->child->focussed)
1015 show_panel(view->child->panel);
1016 else
1017 show_panel(view->panel);
1018 } else {
1019 ncols = view->child->begin_x;
1021 view_splitscreen(view->child);
1022 show_panel(view->child->panel);
1025 * XXX This is ugly and needs to be moved into the above
1026 * logic but "works" for now and my attempts at moving it
1027 * break either 'tab' or 'F' key maps in horizontal splits.
1029 if (hs) {
1030 err = view_splitscreen(view->child);
1031 if (err)
1032 return err;
1033 if (dif < 0) { /* top split decreased */
1034 err = offset_selection_down(view);
1035 if (err)
1036 return err;
1038 view_border(view);
1039 update_panels();
1040 doupdate();
1041 show_panel(view->child->panel);
1042 nlines = view->nlines;
1044 } else if (view->parent == NULL)
1045 ncols = COLS;
1047 if (view->resize && dif > 0) {
1048 err = view->resize(view, dif);
1049 if (err)
1050 return err;
1053 if (wresize(view->window, nlines, ncols) == ERR)
1054 return got_error_from_errno("wresize");
1055 if (replace_panel(view->panel, view->window) == ERR)
1056 return got_error_from_errno("replace_panel");
1057 wclear(view->window);
1059 view->nlines = nlines;
1060 view->ncols = ncols;
1061 view->lines = LINES;
1062 view->cols = COLS;
1064 return NULL;
1067 static const struct got_error *
1068 resize_log_view(struct tog_view *view, int increase)
1070 struct tog_log_view_state *s = &view->state.log;
1071 const struct got_error *err = NULL;
1072 int n = 0;
1074 if (s->selected_entry)
1075 n = s->selected_entry->idx + view->lines - s->selected;
1078 * Request commits to account for the increased
1079 * height so we have enough to populate the view.
1081 if (s->commits->ncommits < n) {
1082 view->nscrolled = n - s->commits->ncommits + increase + 1;
1083 err = request_log_commits(view);
1086 return err;
1089 static void
1090 view_adjust_offset(struct tog_view *view, int n)
1092 if (n == 0)
1093 return;
1095 if (view->parent && view->parent->offset) {
1096 if (view->parent->offset + n >= 0)
1097 view->parent->offset += n;
1098 else
1099 view->parent->offset = 0;
1100 } else if (view->offset) {
1101 if (view->offset - n >= 0)
1102 view->offset -= n;
1103 else
1104 view->offset = 0;
1108 static const struct got_error *
1109 view_resize_split(struct tog_view *view, int resize)
1111 const struct got_error *err = NULL;
1112 struct tog_view *v = NULL;
1114 if (view->parent)
1115 v = view->parent;
1116 else
1117 v = view;
1119 if (!v->child || !view_is_splitscreen(v->child))
1120 return NULL;
1122 v->resized = v->child->resized = resize; /* lock for resize event */
1124 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1125 if (v->child->resized_y)
1126 v->child->begin_y = v->child->resized_y;
1127 if (view->parent)
1128 v->child->begin_y -= resize;
1129 else
1130 v->child->begin_y += resize;
1131 if (v->child->begin_y < 3) {
1132 view->count = 0;
1133 v->child->begin_y = 3;
1134 } else if (v->child->begin_y > LINES - 1) {
1135 view->count = 0;
1136 v->child->begin_y = LINES - 1;
1138 v->ncols = COLS;
1139 v->child->ncols = COLS;
1140 view_adjust_offset(view, resize);
1141 err = view_init_hsplit(v, v->child->begin_y);
1142 if (err)
1143 return err;
1144 v->child->resized_y = v->child->begin_y;
1145 } else {
1146 if (v->child->resized_x)
1147 v->child->begin_x = v->child->resized_x;
1148 if (view->parent)
1149 v->child->begin_x -= resize;
1150 else
1151 v->child->begin_x += resize;
1152 if (v->child->begin_x < 11) {
1153 view->count = 0;
1154 v->child->begin_x = 11;
1155 } else if (v->child->begin_x > COLS - 1) {
1156 view->count = 0;
1157 v->child->begin_x = COLS - 1;
1159 v->child->resized_x = v->child->begin_x;
1162 v->child->mode = v->mode;
1163 v->child->nlines = v->lines - v->child->begin_y;
1164 v->child->ncols = v->cols - v->child->begin_x;
1165 v->focus_child = 1;
1167 err = view_fullscreen(v);
1168 if (err)
1169 return err;
1170 err = view_splitscreen(v->child);
1171 if (err)
1172 return err;
1174 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1175 err = offset_selection_down(v->child);
1176 if (err)
1177 return err;
1180 if (v->resize)
1181 err = v->resize(v, 0);
1182 else if (v->child->resize)
1183 err = v->child->resize(v->child, 0);
1185 v->resized = v->child->resized = 0;
1187 return err;
1190 static void
1191 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1193 struct tog_view *v = src->child ? src->child : src;
1195 dst->resized_x = v->resized_x;
1196 dst->resized_y = v->resized_y;
1199 static const struct got_error *
1200 view_close_child(struct tog_view *view)
1202 const struct got_error *err = NULL;
1204 if (view->child == NULL)
1205 return NULL;
1207 err = view_close(view->child);
1208 view->child = NULL;
1209 return err;
1212 static const struct got_error *
1213 view_set_child(struct tog_view *view, struct tog_view *child)
1215 const struct got_error *err = NULL;
1217 view->child = child;
1218 child->parent = view;
1220 err = view_resize(view);
1221 if (err)
1222 return err;
1224 if (view->child->resized_x || view->child->resized_y)
1225 err = view_resize_split(view, 0);
1227 return err;
1230 static const struct got_error *view_dispatch_request(struct tog_view **,
1231 struct tog_view *, enum tog_view_type, int, int);
1233 static const struct got_error *
1234 view_request_new(struct tog_view **requested, struct tog_view *view,
1235 enum tog_view_type request)
1237 struct tog_view *new_view = NULL;
1238 const struct got_error *err;
1239 int y = 0, x = 0;
1241 *requested = NULL;
1243 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1244 view_get_split(view, &y, &x);
1246 err = view_dispatch_request(&new_view, view, request, y, x);
1247 if (err)
1248 return err;
1250 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1251 request != TOG_VIEW_HELP) {
1252 err = view_init_hsplit(view, y);
1253 if (err)
1254 return err;
1257 view->focussed = 0;
1258 new_view->focussed = 1;
1259 new_view->mode = view->mode;
1260 new_view->nlines = request == TOG_VIEW_HELP ?
1261 view->lines : view->lines - y;
1263 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1264 view_transfer_size(new_view, view);
1265 err = view_close_child(view);
1266 if (err)
1267 return err;
1268 err = view_set_child(view, new_view);
1269 if (err)
1270 return err;
1271 view->focus_child = 1;
1272 } else
1273 *requested = new_view;
1275 return NULL;
1278 static void
1279 tog_resizeterm(void)
1281 int cols, lines;
1282 struct winsize size;
1284 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1285 cols = 80; /* Default */
1286 lines = 24;
1287 } else {
1288 cols = size.ws_col;
1289 lines = size.ws_row;
1291 resize_term(lines, cols);
1294 static const struct got_error *
1295 view_search_start(struct tog_view *view)
1297 const struct got_error *err = NULL;
1298 struct tog_view *v = view;
1299 char pattern[1024];
1300 int ret;
1302 if (view->search_started) {
1303 regfree(&view->regex);
1304 view->searching = 0;
1305 memset(&view->regmatch, 0, sizeof(view->regmatch));
1307 view->search_started = 0;
1309 if (view->nlines < 1)
1310 return NULL;
1312 if (view_is_hsplit_top(view))
1313 v = view->child;
1314 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1315 v = view->parent;
1317 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1318 wclrtoeol(v->window);
1320 nodelay(v->window, FALSE); /* block for search term input */
1321 nocbreak();
1322 echo();
1323 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1324 wrefresh(v->window);
1325 cbreak();
1326 noecho();
1327 nodelay(v->window, TRUE);
1328 if (ret == ERR)
1329 return NULL;
1331 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1332 err = view->search_start(view);
1333 if (err) {
1334 regfree(&view->regex);
1335 return err;
1337 view->search_started = 1;
1338 view->searching = TOG_SEARCH_FORWARD;
1339 view->search_next_done = 0;
1340 view->search_next(view);
1343 return NULL;
1346 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1347 static const struct got_error *
1348 switch_split(struct tog_view *view)
1350 const struct got_error *err = NULL;
1351 struct tog_view *v = NULL;
1353 if (view->parent)
1354 v = view->parent;
1355 else
1356 v = view;
1358 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1359 v->mode = TOG_VIEW_SPLIT_VERT;
1360 else
1361 v->mode = TOG_VIEW_SPLIT_HRZN;
1363 if (!v->child)
1364 return NULL;
1365 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1366 v->mode = TOG_VIEW_SPLIT_NONE;
1368 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1369 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1370 v->child->begin_y = v->child->resized_y;
1371 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1372 v->child->begin_x = v->child->resized_x;
1375 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1376 v->ncols = COLS;
1377 v->child->ncols = COLS;
1378 v->child->nscrolled = LINES - v->child->nlines;
1380 err = view_init_hsplit(v, v->child->begin_y);
1381 if (err)
1382 return err;
1384 v->child->mode = v->mode;
1385 v->child->nlines = v->lines - v->child->begin_y;
1386 v->focus_child = 1;
1388 err = view_fullscreen(v);
1389 if (err)
1390 return err;
1391 err = view_splitscreen(v->child);
1392 if (err)
1393 return err;
1395 if (v->mode == TOG_VIEW_SPLIT_NONE)
1396 v->mode = TOG_VIEW_SPLIT_VERT;
1397 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1398 err = offset_selection_down(v);
1399 if (err)
1400 return err;
1401 err = offset_selection_down(v->child);
1402 if (err)
1403 return err;
1404 } else {
1405 offset_selection_up(v);
1406 offset_selection_up(v->child);
1408 if (v->resize)
1409 err = v->resize(v, 0);
1410 else if (v->child->resize)
1411 err = v->child->resize(v->child, 0);
1413 return err;
1417 * Compute view->count from numeric input. Assign total to view->count and
1418 * return first non-numeric key entered.
1420 static int
1421 get_compound_key(struct tog_view *view, int c)
1423 struct tog_view *v = view;
1424 int x, n = 0;
1426 if (view_is_hsplit_top(view))
1427 v = view->child;
1428 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1429 v = view->parent;
1431 view->count = 0;
1432 cbreak(); /* block for input */
1433 nodelay(view->window, FALSE);
1434 wmove(v->window, v->nlines - 1, 0);
1435 wclrtoeol(v->window);
1436 waddch(v->window, ':');
1438 do {
1439 x = getcurx(v->window);
1440 if (x != ERR && x < view->ncols) {
1441 waddch(v->window, c);
1442 wrefresh(v->window);
1446 * Don't overflow. Max valid request should be the greatest
1447 * between the longest and total lines; cap at 10 million.
1449 if (n >= 9999999)
1450 n = 9999999;
1451 else
1452 n = n * 10 + (c - '0');
1453 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1455 if (c == 'G' || c == 'g') { /* nG key map */
1456 view->gline = view->hiline = n;
1457 n = 0;
1458 c = 0;
1461 /* Massage excessive or inapplicable values at the input handler. */
1462 view->count = n;
1464 return c;
1467 static const struct got_error *
1468 view_input(struct tog_view **new, int *done, struct tog_view *view,
1469 struct tog_view_list_head *views)
1471 const struct got_error *err = NULL;
1472 struct tog_view *v;
1473 int ch, errcode;
1475 *new = NULL;
1477 /* Clear "no matches" indicator. */
1478 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1479 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1480 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1481 view->count = 0;
1484 if (view->searching && !view->search_next_done) {
1485 errcode = pthread_mutex_unlock(&tog_mutex);
1486 if (errcode)
1487 return got_error_set_errno(errcode,
1488 "pthread_mutex_unlock");
1489 sched_yield();
1490 errcode = pthread_mutex_lock(&tog_mutex);
1491 if (errcode)
1492 return got_error_set_errno(errcode,
1493 "pthread_mutex_lock");
1494 view->search_next(view);
1495 return NULL;
1498 /* Allow threads to make progress while we are waiting for input. */
1499 errcode = pthread_mutex_unlock(&tog_mutex);
1500 if (errcode)
1501 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1502 /* If we have an unfinished count, let C-g or backspace abort. */
1503 if (view->count && --view->count) {
1504 cbreak();
1505 nodelay(view->window, TRUE);
1506 ch = wgetch(view->window);
1507 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1508 view->count = 0;
1509 else
1510 ch = view->ch;
1511 } else {
1512 ch = wgetch(view->window);
1513 if (ch >= '1' && ch <= '9')
1514 view->ch = ch = get_compound_key(view, ch);
1516 if (view->hiline && ch != ERR && ch != 0)
1517 view->hiline = 0; /* key pressed, clear line highlight */
1518 nodelay(view->window, TRUE);
1519 errcode = pthread_mutex_lock(&tog_mutex);
1520 if (errcode)
1521 return got_error_set_errno(errcode, "pthread_mutex_lock");
1523 if (tog_sigwinch_received || tog_sigcont_received) {
1524 tog_resizeterm();
1525 tog_sigwinch_received = 0;
1526 tog_sigcont_received = 0;
1527 TAILQ_FOREACH(v, views, entry) {
1528 err = view_resize(v);
1529 if (err)
1530 return err;
1531 err = v->input(new, v, KEY_RESIZE);
1532 if (err)
1533 return err;
1534 if (v->child) {
1535 err = view_resize(v->child);
1536 if (err)
1537 return err;
1538 err = v->child->input(new, v->child,
1539 KEY_RESIZE);
1540 if (err)
1541 return err;
1542 if (v->child->resized_x || v->child->resized_y) {
1543 err = view_resize_split(v, 0);
1544 if (err)
1545 return err;
1551 switch (ch) {
1552 case '?':
1553 case 'H':
1554 case KEY_F(1):
1555 if (view->type == TOG_VIEW_HELP)
1556 err = view->reset(view);
1557 else
1558 err = view_request_new(new, view, TOG_VIEW_HELP);
1559 break;
1560 case '\t':
1561 view->count = 0;
1562 if (view->child) {
1563 view->focussed = 0;
1564 view->child->focussed = 1;
1565 view->focus_child = 1;
1566 } else if (view->parent) {
1567 view->focussed = 0;
1568 view->parent->focussed = 1;
1569 view->parent->focus_child = 0;
1570 if (!view_is_splitscreen(view)) {
1571 if (view->parent->resize) {
1572 err = view->parent->resize(view->parent,
1573 0);
1574 if (err)
1575 return err;
1577 offset_selection_up(view->parent);
1578 err = view_fullscreen(view->parent);
1579 if (err)
1580 return err;
1583 break;
1584 case 'q':
1585 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1586 if (view->parent->resize) {
1587 /* might need more commits to fill fullscreen */
1588 err = view->parent->resize(view->parent, 0);
1589 if (err)
1590 break;
1592 offset_selection_up(view->parent);
1594 err = view->input(new, view, ch);
1595 view->dying = 1;
1596 break;
1597 case 'Q':
1598 *done = 1;
1599 break;
1600 case 'F':
1601 view->count = 0;
1602 if (view_is_parent_view(view)) {
1603 if (view->child == NULL)
1604 break;
1605 if (view_is_splitscreen(view->child)) {
1606 view->focussed = 0;
1607 view->child->focussed = 1;
1608 err = view_fullscreen(view->child);
1609 } else {
1610 err = view_splitscreen(view->child);
1611 if (!err)
1612 err = view_resize_split(view, 0);
1614 if (err)
1615 break;
1616 err = view->child->input(new, view->child,
1617 KEY_RESIZE);
1618 } else {
1619 if (view_is_splitscreen(view)) {
1620 view->parent->focussed = 0;
1621 view->focussed = 1;
1622 err = view_fullscreen(view);
1623 } else {
1624 err = view_splitscreen(view);
1625 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1626 err = view_resize(view->parent);
1627 if (!err)
1628 err = view_resize_split(view, 0);
1630 if (err)
1631 break;
1632 err = view->input(new, view, KEY_RESIZE);
1634 if (err)
1635 break;
1636 if (view->resize) {
1637 err = view->resize(view, 0);
1638 if (err)
1639 break;
1641 if (view->parent)
1642 err = offset_selection_down(view->parent);
1643 if (!err)
1644 err = offset_selection_down(view);
1645 break;
1646 case 'S':
1647 view->count = 0;
1648 err = switch_split(view);
1649 break;
1650 case '-':
1651 err = view_resize_split(view, -1);
1652 break;
1653 case '+':
1654 err = view_resize_split(view, 1);
1655 break;
1656 case KEY_RESIZE:
1657 break;
1658 case '/':
1659 view->count = 0;
1660 if (view->search_start)
1661 view_search_start(view);
1662 else
1663 err = view->input(new, view, ch);
1664 break;
1665 case 'N':
1666 case 'n':
1667 if (view->search_started && view->search_next) {
1668 view->searching = (ch == 'n' ?
1669 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1670 view->search_next_done = 0;
1671 view->search_next(view);
1672 } else
1673 err = view->input(new, view, ch);
1674 break;
1675 case 'A':
1676 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1677 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1678 else
1679 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1680 TAILQ_FOREACH(v, views, entry) {
1681 if (v->reset) {
1682 err = v->reset(v);
1683 if (err)
1684 return err;
1686 if (v->child && v->child->reset) {
1687 err = v->child->reset(v->child);
1688 if (err)
1689 return err;
1692 break;
1693 default:
1694 err = view->input(new, view, ch);
1695 break;
1698 return err;
1701 static int
1702 view_needs_focus_indication(struct tog_view *view)
1704 if (view_is_parent_view(view)) {
1705 if (view->child == NULL || view->child->focussed)
1706 return 0;
1707 if (!view_is_splitscreen(view->child))
1708 return 0;
1709 } else if (!view_is_splitscreen(view))
1710 return 0;
1712 return view->focussed;
1715 static const struct got_error *
1716 view_loop(struct tog_view *view)
1718 const struct got_error *err = NULL;
1719 struct tog_view_list_head views;
1720 struct tog_view *new_view;
1721 char *mode;
1722 int fast_refresh = 10;
1723 int done = 0, errcode;
1725 mode = getenv("TOG_VIEW_SPLIT_MODE");
1726 if (!mode || !(*mode == 'h' || *mode == 'H'))
1727 view->mode = TOG_VIEW_SPLIT_VERT;
1728 else
1729 view->mode = TOG_VIEW_SPLIT_HRZN;
1731 errcode = pthread_mutex_lock(&tog_mutex);
1732 if (errcode)
1733 return got_error_set_errno(errcode, "pthread_mutex_lock");
1735 TAILQ_INIT(&views);
1736 TAILQ_INSERT_HEAD(&views, view, entry);
1738 view->focussed = 1;
1739 err = view->show(view);
1740 if (err)
1741 return err;
1742 update_panels();
1743 doupdate();
1744 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1745 !tog_fatal_signal_received()) {
1746 /* Refresh fast during initialization, then become slower. */
1747 if (fast_refresh && fast_refresh-- == 0)
1748 halfdelay(10); /* switch to once per second */
1750 err = view_input(&new_view, &done, view, &views);
1751 if (err)
1752 break;
1753 if (view->dying) {
1754 struct tog_view *v, *prev = NULL;
1756 if (view_is_parent_view(view))
1757 prev = TAILQ_PREV(view, tog_view_list_head,
1758 entry);
1759 else if (view->parent)
1760 prev = view->parent;
1762 if (view->parent) {
1763 view->parent->child = NULL;
1764 view->parent->focus_child = 0;
1765 /* Restore fullscreen line height. */
1766 view->parent->nlines = view->parent->lines;
1767 err = view_resize(view->parent);
1768 if (err)
1769 break;
1770 /* Make resized splits persist. */
1771 view_transfer_size(view->parent, view);
1772 } else
1773 TAILQ_REMOVE(&views, view, entry);
1775 err = view_close(view);
1776 if (err)
1777 goto done;
1779 view = NULL;
1780 TAILQ_FOREACH(v, &views, entry) {
1781 if (v->focussed)
1782 break;
1784 if (view == NULL && new_view == NULL) {
1785 /* No view has focus. Try to pick one. */
1786 if (prev)
1787 view = prev;
1788 else if (!TAILQ_EMPTY(&views)) {
1789 view = TAILQ_LAST(&views,
1790 tog_view_list_head);
1792 if (view) {
1793 if (view->focus_child) {
1794 view->child->focussed = 1;
1795 view = view->child;
1796 } else
1797 view->focussed = 1;
1801 if (new_view) {
1802 struct tog_view *v, *t;
1803 /* Only allow one parent view per type. */
1804 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1805 if (v->type != new_view->type)
1806 continue;
1807 TAILQ_REMOVE(&views, v, entry);
1808 err = view_close(v);
1809 if (err)
1810 goto done;
1811 break;
1813 TAILQ_INSERT_TAIL(&views, new_view, entry);
1814 view = new_view;
1816 if (view) {
1817 if (view_is_parent_view(view)) {
1818 if (view->child && view->child->focussed)
1819 view = view->child;
1820 } else {
1821 if (view->parent && view->parent->focussed)
1822 view = view->parent;
1824 show_panel(view->panel);
1825 if (view->child && view_is_splitscreen(view->child))
1826 show_panel(view->child->panel);
1827 if (view->parent && view_is_splitscreen(view)) {
1828 err = view->parent->show(view->parent);
1829 if (err)
1830 goto done;
1832 err = view->show(view);
1833 if (err)
1834 goto done;
1835 if (view->child) {
1836 err = view->child->show(view->child);
1837 if (err)
1838 goto done;
1840 update_panels();
1841 doupdate();
1844 done:
1845 while (!TAILQ_EMPTY(&views)) {
1846 const struct got_error *close_err;
1847 view = TAILQ_FIRST(&views);
1848 TAILQ_REMOVE(&views, view, entry);
1849 close_err = view_close(view);
1850 if (close_err && err == NULL)
1851 err = close_err;
1854 errcode = pthread_mutex_unlock(&tog_mutex);
1855 if (errcode && err == NULL)
1856 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1858 return err;
1861 __dead static void
1862 usage_log(void)
1864 endwin();
1865 fprintf(stderr,
1866 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1867 getprogname());
1868 exit(1);
1871 /* Create newly allocated wide-character string equivalent to a byte string. */
1872 static const struct got_error *
1873 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1875 char *vis = NULL;
1876 const struct got_error *err = NULL;
1878 *ws = NULL;
1879 *wlen = mbstowcs(NULL, s, 0);
1880 if (*wlen == (size_t)-1) {
1881 int vislen;
1882 if (errno != EILSEQ)
1883 return got_error_from_errno("mbstowcs");
1885 /* byte string invalid in current encoding; try to "fix" it */
1886 err = got_mbsavis(&vis, &vislen, s);
1887 if (err)
1888 return err;
1889 *wlen = mbstowcs(NULL, vis, 0);
1890 if (*wlen == (size_t)-1) {
1891 err = got_error_from_errno("mbstowcs"); /* give up */
1892 goto done;
1896 *ws = calloc(*wlen + 1, sizeof(**ws));
1897 if (*ws == NULL) {
1898 err = got_error_from_errno("calloc");
1899 goto done;
1902 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1903 err = got_error_from_errno("mbstowcs");
1904 done:
1905 free(vis);
1906 if (err) {
1907 free(*ws);
1908 *ws = NULL;
1909 *wlen = 0;
1911 return err;
1914 static const struct got_error *
1915 expand_tab(char **ptr, const char *src)
1917 char *dst;
1918 size_t len, n, idx = 0, sz = 0;
1920 *ptr = NULL;
1921 n = len = strlen(src);
1922 dst = malloc(n + 1);
1923 if (dst == NULL)
1924 return got_error_from_errno("malloc");
1926 while (idx < len && src[idx]) {
1927 const char c = src[idx];
1929 if (c == '\t') {
1930 size_t nb = TABSIZE - sz % TABSIZE;
1931 char *p;
1933 p = realloc(dst, n + nb);
1934 if (p == NULL) {
1935 free(dst);
1936 return got_error_from_errno("realloc");
1939 dst = p;
1940 n += nb;
1941 memset(dst + sz, ' ', nb);
1942 sz += nb;
1943 } else
1944 dst[sz++] = src[idx];
1945 ++idx;
1948 dst[sz] = '\0';
1949 *ptr = dst;
1950 return NULL;
1954 * Advance at most n columns from wline starting at offset off.
1955 * Return the index to the first character after the span operation.
1956 * Return the combined column width of all spanned wide character in
1957 * *rcol.
1959 static int
1960 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1962 int width, i, cols = 0;
1964 if (n == 0) {
1965 *rcol = cols;
1966 return off;
1969 for (i = off; wline[i] != L'\0'; ++i) {
1970 if (wline[i] == L'\t')
1971 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1972 else
1973 width = wcwidth(wline[i]);
1975 if (width == -1) {
1976 width = 1;
1977 wline[i] = L'.';
1980 if (cols + width > n)
1981 break;
1982 cols += width;
1985 *rcol = cols;
1986 return i;
1990 * Format a line for display, ensuring that it won't overflow a width limit.
1991 * With scrolling, the width returned refers to the scrolled version of the
1992 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1994 static const struct got_error *
1995 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1996 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1998 const struct got_error *err = NULL;
1999 int cols;
2000 wchar_t *wline = NULL;
2001 char *exstr = NULL;
2002 size_t wlen;
2003 int i, scrollx;
2005 *wlinep = NULL;
2006 *widthp = 0;
2008 if (expand) {
2009 err = expand_tab(&exstr, line);
2010 if (err)
2011 return err;
2014 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2015 free(exstr);
2016 if (err)
2017 return err;
2019 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2021 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2022 wline[wlen - 1] = L'\0';
2023 wlen--;
2025 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2026 wline[wlen - 1] = L'\0';
2027 wlen--;
2030 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2031 wline[i] = L'\0';
2033 if (widthp)
2034 *widthp = cols;
2035 if (scrollxp)
2036 *scrollxp = scrollx;
2037 if (err)
2038 free(wline);
2039 else
2040 *wlinep = wline;
2041 return err;
2044 static const struct got_error*
2045 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2046 struct got_object_id *id, struct got_repository *repo)
2048 static const struct got_error *err = NULL;
2049 struct got_reflist_entry *re;
2050 char *s;
2051 const char *name;
2053 *refs_str = NULL;
2055 TAILQ_FOREACH(re, refs, entry) {
2056 struct got_tag_object *tag = NULL;
2057 struct got_object_id *ref_id;
2058 int cmp;
2060 name = got_ref_get_name(re->ref);
2061 if (strcmp(name, GOT_REF_HEAD) == 0)
2062 continue;
2063 if (strncmp(name, "refs/", 5) == 0)
2064 name += 5;
2065 if (strncmp(name, "got/", 4) == 0 &&
2066 strncmp(name, "got/backup/", 11) != 0)
2067 continue;
2068 if (strncmp(name, "heads/", 6) == 0)
2069 name += 6;
2070 if (strncmp(name, "remotes/", 8) == 0) {
2071 name += 8;
2072 s = strstr(name, "/" GOT_REF_HEAD);
2073 if (s != NULL && s[strlen(s)] == '\0')
2074 continue;
2076 err = got_ref_resolve(&ref_id, repo, re->ref);
2077 if (err)
2078 break;
2079 if (strncmp(name, "tags/", 5) == 0) {
2080 err = got_object_open_as_tag(&tag, repo, ref_id);
2081 if (err) {
2082 if (err->code != GOT_ERR_OBJ_TYPE) {
2083 free(ref_id);
2084 break;
2086 /* Ref points at something other than a tag. */
2087 err = NULL;
2088 tag = NULL;
2091 cmp = got_object_id_cmp(tag ?
2092 got_object_tag_get_object_id(tag) : ref_id, id);
2093 free(ref_id);
2094 if (tag)
2095 got_object_tag_close(tag);
2096 if (cmp != 0)
2097 continue;
2098 s = *refs_str;
2099 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2100 s ? ", " : "", name) == -1) {
2101 err = got_error_from_errno("asprintf");
2102 free(s);
2103 *refs_str = NULL;
2104 break;
2106 free(s);
2109 return err;
2112 static const struct got_error *
2113 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2114 int col_tab_align)
2116 char *smallerthan;
2118 smallerthan = strchr(author, '<');
2119 if (smallerthan && smallerthan[1] != '\0')
2120 author = smallerthan + 1;
2121 author[strcspn(author, "@>")] = '\0';
2122 return format_line(wauthor, author_width, NULL, author, 0, limit,
2123 col_tab_align, 0);
2126 static const struct got_error *
2127 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2128 struct got_object_id *id, const size_t date_display_cols,
2129 int author_display_cols)
2131 struct tog_log_view_state *s = &view->state.log;
2132 const struct got_error *err = NULL;
2133 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2134 char *logmsg0 = NULL, *logmsg = NULL;
2135 char *author = NULL;
2136 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2137 int author_width, logmsg_width;
2138 char *newline, *line = NULL;
2139 int col, limit, scrollx;
2140 const int avail = view->ncols;
2141 struct tm tm;
2142 time_t committer_time;
2143 struct tog_color *tc;
2145 committer_time = got_object_commit_get_committer_time(commit);
2146 if (gmtime_r(&committer_time, &tm) == NULL)
2147 return got_error_from_errno("gmtime_r");
2148 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2149 return got_error(GOT_ERR_NO_SPACE);
2151 if (avail <= date_display_cols)
2152 limit = MIN(sizeof(datebuf) - 1, avail);
2153 else
2154 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2155 tc = get_color(&s->colors, TOG_COLOR_DATE);
2156 if (tc)
2157 wattr_on(view->window,
2158 COLOR_PAIR(tc->colorpair), NULL);
2159 waddnstr(view->window, datebuf, limit);
2160 if (tc)
2161 wattr_off(view->window,
2162 COLOR_PAIR(tc->colorpair), NULL);
2163 col = limit;
2164 if (col > avail)
2165 goto done;
2167 if (avail >= 120) {
2168 char *id_str;
2169 err = got_object_id_str(&id_str, id);
2170 if (err)
2171 goto done;
2172 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2173 if (tc)
2174 wattr_on(view->window,
2175 COLOR_PAIR(tc->colorpair), NULL);
2176 wprintw(view->window, "%.8s ", id_str);
2177 if (tc)
2178 wattr_off(view->window,
2179 COLOR_PAIR(tc->colorpair), NULL);
2180 free(id_str);
2181 col += 9;
2182 if (col > avail)
2183 goto done;
2186 if (s->use_committer)
2187 author = strdup(got_object_commit_get_committer(commit));
2188 else
2189 author = strdup(got_object_commit_get_author(commit));
2190 if (author == NULL) {
2191 err = got_error_from_errno("strdup");
2192 goto done;
2194 err = format_author(&wauthor, &author_width, author, avail - col, col);
2195 if (err)
2196 goto done;
2197 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2198 if (tc)
2199 wattr_on(view->window,
2200 COLOR_PAIR(tc->colorpair), NULL);
2201 waddwstr(view->window, wauthor);
2202 col += author_width;
2203 while (col < avail && author_width < author_display_cols + 2) {
2204 waddch(view->window, ' ');
2205 col++;
2206 author_width++;
2208 if (tc)
2209 wattr_off(view->window,
2210 COLOR_PAIR(tc->colorpair), NULL);
2211 if (col > avail)
2212 goto done;
2214 err = got_object_commit_get_logmsg(&logmsg0, commit);
2215 if (err)
2216 goto done;
2217 logmsg = logmsg0;
2218 while (*logmsg == '\n')
2219 logmsg++;
2220 newline = strchr(logmsg, '\n');
2221 if (newline)
2222 *newline = '\0';
2223 limit = avail - col;
2224 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2225 limit--; /* for the border */
2226 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2227 limit, col, 1);
2228 if (err)
2229 goto done;
2230 waddwstr(view->window, &wlogmsg[scrollx]);
2231 col += MAX(logmsg_width, 0);
2232 while (col < avail) {
2233 waddch(view->window, ' ');
2234 col++;
2236 done:
2237 free(logmsg0);
2238 free(wlogmsg);
2239 free(author);
2240 free(wauthor);
2241 free(line);
2242 return err;
2245 static struct commit_queue_entry *
2246 alloc_commit_queue_entry(struct got_commit_object *commit,
2247 struct got_object_id *id)
2249 struct commit_queue_entry *entry;
2250 struct got_object_id *dup;
2252 entry = calloc(1, sizeof(*entry));
2253 if (entry == NULL)
2254 return NULL;
2256 dup = got_object_id_dup(id);
2257 if (dup == NULL) {
2258 free(entry);
2259 return NULL;
2262 entry->id = dup;
2263 entry->commit = commit;
2264 return entry;
2267 static void
2268 pop_commit(struct commit_queue *commits)
2270 struct commit_queue_entry *entry;
2272 entry = TAILQ_FIRST(&commits->head);
2273 TAILQ_REMOVE(&commits->head, entry, entry);
2274 got_object_commit_close(entry->commit);
2275 commits->ncommits--;
2276 free(entry->id);
2277 free(entry);
2280 static void
2281 free_commits(struct commit_queue *commits)
2283 while (!TAILQ_EMPTY(&commits->head))
2284 pop_commit(commits);
2287 static const struct got_error *
2288 match_commit(int *have_match, struct got_object_id *id,
2289 struct got_commit_object *commit, regex_t *regex)
2291 const struct got_error *err = NULL;
2292 regmatch_t regmatch;
2293 char *id_str = NULL, *logmsg = NULL;
2295 *have_match = 0;
2297 err = got_object_id_str(&id_str, id);
2298 if (err)
2299 return err;
2301 err = got_object_commit_get_logmsg(&logmsg, commit);
2302 if (err)
2303 goto done;
2305 if (regexec(regex, got_object_commit_get_author(commit), 1,
2306 &regmatch, 0) == 0 ||
2307 regexec(regex, got_object_commit_get_committer(commit), 1,
2308 &regmatch, 0) == 0 ||
2309 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2310 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2311 *have_match = 1;
2312 done:
2313 free(id_str);
2314 free(logmsg);
2315 return err;
2318 static const struct got_error *
2319 queue_commits(struct tog_log_thread_args *a)
2321 const struct got_error *err = NULL;
2324 * We keep all commits open throughout the lifetime of the log
2325 * view in order to avoid having to re-fetch commits from disk
2326 * while updating the display.
2328 do {
2329 struct got_object_id id;
2330 struct got_commit_object *commit;
2331 struct commit_queue_entry *entry;
2332 int limit_match = 0;
2333 int errcode;
2335 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2336 NULL, NULL);
2337 if (err)
2338 break;
2340 err = got_object_open_as_commit(&commit, a->repo, &id);
2341 if (err)
2342 break;
2343 entry = alloc_commit_queue_entry(commit, &id);
2344 if (entry == NULL) {
2345 err = got_error_from_errno("alloc_commit_queue_entry");
2346 break;
2349 errcode = pthread_mutex_lock(&tog_mutex);
2350 if (errcode) {
2351 err = got_error_set_errno(errcode,
2352 "pthread_mutex_lock");
2353 break;
2356 entry->idx = a->real_commits->ncommits;
2357 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2358 a->real_commits->ncommits++;
2360 if (*a->limiting) {
2361 err = match_commit(&limit_match, &id, commit,
2362 a->limit_regex);
2363 if (err)
2364 break;
2366 if (limit_match) {
2367 struct commit_queue_entry *matched;
2369 matched = alloc_commit_queue_entry(
2370 entry->commit, entry->id);
2371 if (matched == NULL) {
2372 err = got_error_from_errno(
2373 "alloc_commit_queue_entry");
2374 break;
2376 matched->commit = entry->commit;
2377 got_object_commit_retain(entry->commit);
2379 matched->idx = a->limit_commits->ncommits;
2380 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2381 matched, entry);
2382 a->limit_commits->ncommits++;
2386 * This is how we signal log_thread() that we
2387 * have found a match, and that it should be
2388 * counted as a new entry for the view.
2390 a->limit_match = limit_match;
2393 if (*a->searching == TOG_SEARCH_FORWARD &&
2394 !*a->search_next_done) {
2395 int have_match;
2396 err = match_commit(&have_match, &id, commit, a->regex);
2397 if (err)
2398 break;
2400 if (*a->limiting) {
2401 if (limit_match && have_match)
2402 *a->search_next_done =
2403 TOG_SEARCH_HAVE_MORE;
2404 } else if (have_match)
2405 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2408 errcode = pthread_mutex_unlock(&tog_mutex);
2409 if (errcode && err == NULL)
2410 err = got_error_set_errno(errcode,
2411 "pthread_mutex_unlock");
2412 if (err)
2413 break;
2414 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2416 return err;
2419 static void
2420 select_commit(struct tog_log_view_state *s)
2422 struct commit_queue_entry *entry;
2423 int ncommits = 0;
2425 entry = s->first_displayed_entry;
2426 while (entry) {
2427 if (ncommits == s->selected) {
2428 s->selected_entry = entry;
2429 break;
2431 entry = TAILQ_NEXT(entry, entry);
2432 ncommits++;
2436 static const struct got_error *
2437 draw_commits(struct tog_view *view)
2439 const struct got_error *err = NULL;
2440 struct tog_log_view_state *s = &view->state.log;
2441 struct commit_queue_entry *entry = s->selected_entry;
2442 int limit = view->nlines;
2443 int width;
2444 int ncommits, author_cols = 4;
2445 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2446 char *refs_str = NULL;
2447 wchar_t *wline;
2448 struct tog_color *tc;
2449 static const size_t date_display_cols = 12;
2451 if (view_is_hsplit_top(view))
2452 --limit; /* account for border */
2454 if (s->selected_entry &&
2455 !(view->searching && view->search_next_done == 0)) {
2456 struct got_reflist_head *refs;
2457 err = got_object_id_str(&id_str, s->selected_entry->id);
2458 if (err)
2459 return err;
2460 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2461 s->selected_entry->id);
2462 if (refs) {
2463 err = build_refs_str(&refs_str, refs,
2464 s->selected_entry->id, s->repo);
2465 if (err)
2466 goto done;
2470 if (s->thread_args.commits_needed == 0)
2471 halfdelay(10); /* disable fast refresh */
2473 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2474 if (asprintf(&ncommits_str, " [%d/%d] %s",
2475 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2476 (view->searching && !view->search_next_done) ?
2477 "searching..." : "loading...") == -1) {
2478 err = got_error_from_errno("asprintf");
2479 goto done;
2481 } else {
2482 const char *search_str = NULL;
2483 const char *limit_str = NULL;
2485 if (view->searching) {
2486 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2487 search_str = "no more matches";
2488 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2489 search_str = "no matches found";
2490 else if (!view->search_next_done)
2491 search_str = "searching...";
2494 if (s->limit_view && s->commits->ncommits == 0)
2495 limit_str = "no matches found";
2497 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2498 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2499 search_str ? search_str : (refs_str ? refs_str : ""),
2500 limit_str ? limit_str : "") == -1) {
2501 err = got_error_from_errno("asprintf");
2502 goto done;
2506 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2507 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2508 "........................................",
2509 s->in_repo_path, ncommits_str) == -1) {
2510 err = got_error_from_errno("asprintf");
2511 header = NULL;
2512 goto done;
2514 } else if (asprintf(&header, "commit %s%s",
2515 id_str ? id_str : "........................................",
2516 ncommits_str) == -1) {
2517 err = got_error_from_errno("asprintf");
2518 header = NULL;
2519 goto done;
2521 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2522 if (err)
2523 goto done;
2525 werase(view->window);
2527 if (view_needs_focus_indication(view))
2528 wstandout(view->window);
2529 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2530 if (tc)
2531 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2532 waddwstr(view->window, wline);
2533 while (width < view->ncols) {
2534 waddch(view->window, ' ');
2535 width++;
2537 if (tc)
2538 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2539 if (view_needs_focus_indication(view))
2540 wstandend(view->window);
2541 free(wline);
2542 if (limit <= 1)
2543 goto done;
2545 /* Grow author column size if necessary, and set view->maxx. */
2546 entry = s->first_displayed_entry;
2547 ncommits = 0;
2548 view->maxx = 0;
2549 while (entry) {
2550 struct got_commit_object *c = entry->commit;
2551 char *author, *eol, *msg, *msg0;
2552 wchar_t *wauthor, *wmsg;
2553 int width;
2554 if (ncommits >= limit - 1)
2555 break;
2556 if (s->use_committer)
2557 author = strdup(got_object_commit_get_committer(c));
2558 else
2559 author = strdup(got_object_commit_get_author(c));
2560 if (author == NULL) {
2561 err = got_error_from_errno("strdup");
2562 goto done;
2564 err = format_author(&wauthor, &width, author, COLS,
2565 date_display_cols);
2566 if (author_cols < width)
2567 author_cols = width;
2568 free(wauthor);
2569 free(author);
2570 if (err)
2571 goto done;
2572 err = got_object_commit_get_logmsg(&msg0, c);
2573 if (err)
2574 goto done;
2575 msg = msg0;
2576 while (*msg == '\n')
2577 ++msg;
2578 if ((eol = strchr(msg, '\n')))
2579 *eol = '\0';
2580 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2581 date_display_cols + author_cols, 0);
2582 if (err)
2583 goto done;
2584 view->maxx = MAX(view->maxx, width);
2585 free(msg0);
2586 free(wmsg);
2587 ncommits++;
2588 entry = TAILQ_NEXT(entry, entry);
2591 entry = s->first_displayed_entry;
2592 s->last_displayed_entry = s->first_displayed_entry;
2593 ncommits = 0;
2594 while (entry) {
2595 if (ncommits >= limit - 1)
2596 break;
2597 if (ncommits == s->selected)
2598 wstandout(view->window);
2599 err = draw_commit(view, entry->commit, entry->id,
2600 date_display_cols, author_cols);
2601 if (ncommits == s->selected)
2602 wstandend(view->window);
2603 if (err)
2604 goto done;
2605 ncommits++;
2606 s->last_displayed_entry = entry;
2607 entry = TAILQ_NEXT(entry, entry);
2610 view_border(view);
2611 done:
2612 free(id_str);
2613 free(refs_str);
2614 free(ncommits_str);
2615 free(header);
2616 return err;
2619 static void
2620 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2622 struct commit_queue_entry *entry;
2623 int nscrolled = 0;
2625 entry = TAILQ_FIRST(&s->commits->head);
2626 if (s->first_displayed_entry == entry)
2627 return;
2629 entry = s->first_displayed_entry;
2630 while (entry && nscrolled < maxscroll) {
2631 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2632 if (entry) {
2633 s->first_displayed_entry = entry;
2634 nscrolled++;
2639 static const struct got_error *
2640 trigger_log_thread(struct tog_view *view, int wait)
2642 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2643 int errcode;
2645 halfdelay(1); /* fast refresh while loading commits */
2647 while (!ta->log_complete && !tog_thread_error &&
2648 (ta->commits_needed > 0 || ta->load_all)) {
2649 /* Wake the log thread. */
2650 errcode = pthread_cond_signal(&ta->need_commits);
2651 if (errcode)
2652 return got_error_set_errno(errcode,
2653 "pthread_cond_signal");
2656 * The mutex will be released while the view loop waits
2657 * in wgetch(), at which time the log thread will run.
2659 if (!wait)
2660 break;
2662 /* Display progress update in log view. */
2663 show_log_view(view);
2664 update_panels();
2665 doupdate();
2667 /* Wait right here while next commit is being loaded. */
2668 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2669 if (errcode)
2670 return got_error_set_errno(errcode,
2671 "pthread_cond_wait");
2673 /* Display progress update in log view. */
2674 show_log_view(view);
2675 update_panels();
2676 doupdate();
2679 return NULL;
2682 static const struct got_error *
2683 request_log_commits(struct tog_view *view)
2685 struct tog_log_view_state *state = &view->state.log;
2686 const struct got_error *err = NULL;
2688 if (state->thread_args.log_complete)
2689 return NULL;
2691 state->thread_args.commits_needed += view->nscrolled;
2692 err = trigger_log_thread(view, 1);
2693 view->nscrolled = 0;
2695 return err;
2698 static const struct got_error *
2699 log_scroll_down(struct tog_view *view, int maxscroll)
2701 struct tog_log_view_state *s = &view->state.log;
2702 const struct got_error *err = NULL;
2703 struct commit_queue_entry *pentry;
2704 int nscrolled = 0, ncommits_needed;
2706 if (s->last_displayed_entry == NULL)
2707 return NULL;
2709 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2710 if (s->commits->ncommits < ncommits_needed &&
2711 !s->thread_args.log_complete) {
2713 * Ask the log thread for required amount of commits.
2715 s->thread_args.commits_needed +=
2716 ncommits_needed - s->commits->ncommits;
2717 err = trigger_log_thread(view, 1);
2718 if (err)
2719 return err;
2722 do {
2723 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2724 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2725 break;
2727 s->last_displayed_entry = pentry ?
2728 pentry : s->last_displayed_entry;
2730 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2731 if (pentry == NULL)
2732 break;
2733 s->first_displayed_entry = pentry;
2734 } while (++nscrolled < maxscroll);
2736 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2737 view->nscrolled += nscrolled;
2738 else
2739 view->nscrolled = 0;
2741 return err;
2744 static const struct got_error *
2745 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2746 struct got_commit_object *commit, struct got_object_id *commit_id,
2747 struct tog_view *log_view, struct got_repository *repo)
2749 const struct got_error *err;
2750 struct got_object_qid *parent_id;
2751 struct tog_view *diff_view;
2753 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2754 if (diff_view == NULL)
2755 return got_error_from_errno("view_open");
2757 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2758 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2759 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2760 if (err == NULL)
2761 *new_view = diff_view;
2762 return err;
2765 static const struct got_error *
2766 tree_view_visit_subtree(struct tog_tree_view_state *s,
2767 struct got_tree_object *subtree)
2769 struct tog_parent_tree *parent;
2771 parent = calloc(1, sizeof(*parent));
2772 if (parent == NULL)
2773 return got_error_from_errno("calloc");
2775 parent->tree = s->tree;
2776 parent->first_displayed_entry = s->first_displayed_entry;
2777 parent->selected_entry = s->selected_entry;
2778 parent->selected = s->selected;
2779 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2780 s->tree = subtree;
2781 s->selected = 0;
2782 s->first_displayed_entry = NULL;
2783 return NULL;
2786 static const struct got_error *
2787 tree_view_walk_path(struct tog_tree_view_state *s,
2788 struct got_commit_object *commit, const char *path)
2790 const struct got_error *err = NULL;
2791 struct got_tree_object *tree = NULL;
2792 const char *p;
2793 char *slash, *subpath = NULL;
2795 /* Walk the path and open corresponding tree objects. */
2796 p = path;
2797 while (*p) {
2798 struct got_tree_entry *te;
2799 struct got_object_id *tree_id;
2800 char *te_name;
2802 while (p[0] == '/')
2803 p++;
2805 /* Ensure the correct subtree entry is selected. */
2806 slash = strchr(p, '/');
2807 if (slash == NULL)
2808 te_name = strdup(p);
2809 else
2810 te_name = strndup(p, slash - p);
2811 if (te_name == NULL) {
2812 err = got_error_from_errno("strndup");
2813 break;
2815 te = got_object_tree_find_entry(s->tree, te_name);
2816 if (te == NULL) {
2817 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2818 free(te_name);
2819 break;
2821 free(te_name);
2822 s->first_displayed_entry = s->selected_entry = te;
2824 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2825 break; /* jump to this file's entry */
2827 slash = strchr(p, '/');
2828 if (slash)
2829 subpath = strndup(path, slash - path);
2830 else
2831 subpath = strdup(path);
2832 if (subpath == NULL) {
2833 err = got_error_from_errno("strdup");
2834 break;
2837 err = got_object_id_by_path(&tree_id, s->repo, commit,
2838 subpath);
2839 if (err)
2840 break;
2842 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2843 free(tree_id);
2844 if (err)
2845 break;
2847 err = tree_view_visit_subtree(s, tree);
2848 if (err) {
2849 got_object_tree_close(tree);
2850 break;
2852 if (slash == NULL)
2853 break;
2854 free(subpath);
2855 subpath = NULL;
2856 p = slash;
2859 free(subpath);
2860 return err;
2863 static const struct got_error *
2864 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2865 struct commit_queue_entry *entry, const char *path,
2866 const char *head_ref_name, struct got_repository *repo)
2868 const struct got_error *err = NULL;
2869 struct tog_tree_view_state *s;
2870 struct tog_view *tree_view;
2872 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2873 if (tree_view == NULL)
2874 return got_error_from_errno("view_open");
2876 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2877 if (err)
2878 return err;
2879 s = &tree_view->state.tree;
2881 *new_view = tree_view;
2883 if (got_path_is_root_dir(path))
2884 return NULL;
2886 return tree_view_walk_path(s, entry->commit, path);
2889 static const struct got_error *
2890 block_signals_used_by_main_thread(void)
2892 sigset_t sigset;
2893 int errcode;
2895 if (sigemptyset(&sigset) == -1)
2896 return got_error_from_errno("sigemptyset");
2898 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2899 if (sigaddset(&sigset, SIGWINCH) == -1)
2900 return got_error_from_errno("sigaddset");
2901 if (sigaddset(&sigset, SIGCONT) == -1)
2902 return got_error_from_errno("sigaddset");
2903 if (sigaddset(&sigset, SIGINT) == -1)
2904 return got_error_from_errno("sigaddset");
2905 if (sigaddset(&sigset, SIGTERM) == -1)
2906 return got_error_from_errno("sigaddset");
2908 /* ncurses handles SIGTSTP */
2909 if (sigaddset(&sigset, SIGTSTP) == -1)
2910 return got_error_from_errno("sigaddset");
2912 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2913 if (errcode)
2914 return got_error_set_errno(errcode, "pthread_sigmask");
2916 return NULL;
2919 static void *
2920 log_thread(void *arg)
2922 const struct got_error *err = NULL;
2923 int errcode = 0;
2924 struct tog_log_thread_args *a = arg;
2925 int done = 0;
2928 * Sync startup with main thread such that we begin our
2929 * work once view_input() has released the mutex.
2931 errcode = pthread_mutex_lock(&tog_mutex);
2932 if (errcode) {
2933 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2934 return (void *)err;
2937 err = block_signals_used_by_main_thread();
2938 if (err) {
2939 pthread_mutex_unlock(&tog_mutex);
2940 goto done;
2943 while (!done && !err && !tog_fatal_signal_received()) {
2944 errcode = pthread_mutex_unlock(&tog_mutex);
2945 if (errcode) {
2946 err = got_error_set_errno(errcode,
2947 "pthread_mutex_unlock");
2948 goto done;
2950 err = queue_commits(a);
2951 if (err) {
2952 if (err->code != GOT_ERR_ITER_COMPLETED)
2953 goto done;
2954 err = NULL;
2955 done = 1;
2956 } else if (a->commits_needed > 0 && !a->load_all) {
2957 if (*a->limiting) {
2958 if (a->limit_match)
2959 a->commits_needed--;
2960 } else
2961 a->commits_needed--;
2964 errcode = pthread_mutex_lock(&tog_mutex);
2965 if (errcode) {
2966 err = got_error_set_errno(errcode,
2967 "pthread_mutex_lock");
2968 goto done;
2969 } else if (*a->quit)
2970 done = 1;
2971 else if (*a->limiting && *a->first_displayed_entry == NULL) {
2972 *a->first_displayed_entry =
2973 TAILQ_FIRST(&a->limit_commits->head);
2974 *a->selected_entry = *a->first_displayed_entry;
2975 } else if (*a->first_displayed_entry == NULL) {
2976 *a->first_displayed_entry =
2977 TAILQ_FIRST(&a->real_commits->head);
2978 *a->selected_entry = *a->first_displayed_entry;
2981 errcode = pthread_cond_signal(&a->commit_loaded);
2982 if (errcode) {
2983 err = got_error_set_errno(errcode,
2984 "pthread_cond_signal");
2985 pthread_mutex_unlock(&tog_mutex);
2986 goto done;
2989 if (done)
2990 a->commits_needed = 0;
2991 else {
2992 if (a->commits_needed == 0 && !a->load_all) {
2993 errcode = pthread_cond_wait(&a->need_commits,
2994 &tog_mutex);
2995 if (errcode) {
2996 err = got_error_set_errno(errcode,
2997 "pthread_cond_wait");
2998 pthread_mutex_unlock(&tog_mutex);
2999 goto done;
3001 if (*a->quit)
3002 done = 1;
3006 a->log_complete = 1;
3007 errcode = pthread_mutex_unlock(&tog_mutex);
3008 if (errcode)
3009 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3010 done:
3011 if (err) {
3012 tog_thread_error = 1;
3013 pthread_cond_signal(&a->commit_loaded);
3015 return (void *)err;
3018 static const struct got_error *
3019 stop_log_thread(struct tog_log_view_state *s)
3021 const struct got_error *err = NULL, *thread_err = NULL;
3022 int errcode;
3024 if (s->thread) {
3025 s->quit = 1;
3026 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3027 if (errcode)
3028 return got_error_set_errno(errcode,
3029 "pthread_cond_signal");
3030 errcode = pthread_mutex_unlock(&tog_mutex);
3031 if (errcode)
3032 return got_error_set_errno(errcode,
3033 "pthread_mutex_unlock");
3034 errcode = pthread_join(s->thread, (void **)&thread_err);
3035 if (errcode)
3036 return got_error_set_errno(errcode, "pthread_join");
3037 errcode = pthread_mutex_lock(&tog_mutex);
3038 if (errcode)
3039 return got_error_set_errno(errcode,
3040 "pthread_mutex_lock");
3041 s->thread = 0; //NULL;
3044 if (s->thread_args.repo) {
3045 err = got_repo_close(s->thread_args.repo);
3046 s->thread_args.repo = NULL;
3049 if (s->thread_args.pack_fds) {
3050 const struct got_error *pack_err =
3051 got_repo_pack_fds_close(s->thread_args.pack_fds);
3052 if (err == NULL)
3053 err = pack_err;
3054 s->thread_args.pack_fds = NULL;
3057 if (s->thread_args.graph) {
3058 got_commit_graph_close(s->thread_args.graph);
3059 s->thread_args.graph = NULL;
3062 return err ? err : thread_err;
3065 static const struct got_error *
3066 close_log_view(struct tog_view *view)
3068 const struct got_error *err = NULL;
3069 struct tog_log_view_state *s = &view->state.log;
3070 int errcode;
3072 err = stop_log_thread(s);
3074 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3075 if (errcode && err == NULL)
3076 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3078 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3079 if (errcode && err == NULL)
3080 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3082 free_commits(&s->limit_commits);
3083 free_commits(&s->real_commits);
3084 free(s->in_repo_path);
3085 s->in_repo_path = NULL;
3086 free(s->start_id);
3087 s->start_id = NULL;
3088 free(s->head_ref_name);
3089 s->head_ref_name = NULL;
3090 return err;
3094 * We use two queues to implement the limit feature: first consists of
3095 * commits matching the current limit_regex; second is the real queue
3096 * of all known commits (real_commits). When the user starts limiting,
3097 * we swap queues such that all movement and displaying functionality
3098 * works with very slight change.
3100 static const struct got_error *
3101 limit_log_view(struct tog_view *view)
3103 struct tog_log_view_state *s = &view->state.log;
3104 struct commit_queue_entry *entry;
3105 struct tog_view *v = view;
3106 const struct got_error *err = NULL;
3107 char pattern[1024];
3108 int ret;
3110 if (view_is_hsplit_top(view))
3111 v = view->child;
3112 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3113 v = view->parent;
3115 /* Get the pattern */
3116 wmove(v->window, v->nlines - 1, 0);
3117 wclrtoeol(v->window);
3118 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3119 nodelay(v->window, FALSE);
3120 nocbreak();
3121 echo();
3122 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3123 cbreak();
3124 noecho();
3125 nodelay(v->window, TRUE);
3126 if (ret == ERR)
3127 return NULL;
3129 if (*pattern == '\0') {
3131 * Safety measure for the situation where the user
3132 * resets limit without previously limiting anything.
3134 if (!s->limit_view)
3135 return NULL;
3138 * User could have pressed Ctrl+L, which refreshed the
3139 * commit queues, it means we can't save previously
3140 * (before limit took place) displayed entries,
3141 * because they would point to already free'ed memory,
3142 * so we are forced to always select first entry of
3143 * the queue.
3145 s->commits = &s->real_commits;
3146 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3147 s->selected_entry = s->first_displayed_entry;
3148 s->selected = 0;
3149 s->limit_view = 0;
3151 return NULL;
3154 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3155 return NULL;
3157 s->limit_view = 1;
3159 /* Clear the screen while loading limit view */
3160 s->first_displayed_entry = NULL;
3161 s->last_displayed_entry = NULL;
3162 s->selected_entry = NULL;
3163 s->commits = &s->limit_commits;
3165 /* Prepare limit queue for new search */
3166 free_commits(&s->limit_commits);
3167 s->limit_commits.ncommits = 0;
3169 /* First process commits, which are in queue already */
3170 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3171 int have_match = 0;
3173 err = match_commit(&have_match, entry->id,
3174 entry->commit, &s->limit_regex);
3175 if (err)
3176 return err;
3178 if (have_match) {
3179 struct commit_queue_entry *matched;
3181 matched = alloc_commit_queue_entry(entry->commit,
3182 entry->id);
3183 if (matched == NULL) {
3184 err = got_error_from_errno(
3185 "alloc_commit_queue_entry");
3186 break;
3188 matched->commit = entry->commit;
3189 got_object_commit_retain(entry->commit);
3191 matched->idx = s->limit_commits.ncommits;
3192 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3193 matched, entry);
3194 s->limit_commits.ncommits++;
3198 /* Second process all the commits, until we fill the screen */
3199 if (s->limit_commits.ncommits < view->nlines - 1 &&
3200 !s->thread_args.log_complete) {
3201 s->thread_args.commits_needed +=
3202 view->nlines - s->limit_commits.ncommits - 1;
3203 err = trigger_log_thread(view, 1);
3204 if (err)
3205 return err;
3208 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3209 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3210 s->selected = 0;
3212 return NULL;
3215 static const struct got_error *
3216 search_start_log_view(struct tog_view *view)
3218 struct tog_log_view_state *s = &view->state.log;
3220 s->matched_entry = NULL;
3221 s->search_entry = NULL;
3222 return NULL;
3225 static const struct got_error *
3226 search_next_log_view(struct tog_view *view)
3228 const struct got_error *err = NULL;
3229 struct tog_log_view_state *s = &view->state.log;
3230 struct commit_queue_entry *entry;
3232 /* Display progress update in log view. */
3233 show_log_view(view);
3234 update_panels();
3235 doupdate();
3237 if (s->search_entry) {
3238 int errcode, ch;
3239 errcode = pthread_mutex_unlock(&tog_mutex);
3240 if (errcode)
3241 return got_error_set_errno(errcode,
3242 "pthread_mutex_unlock");
3243 ch = wgetch(view->window);
3244 errcode = pthread_mutex_lock(&tog_mutex);
3245 if (errcode)
3246 return got_error_set_errno(errcode,
3247 "pthread_mutex_lock");
3248 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3249 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3250 return NULL;
3252 if (view->searching == TOG_SEARCH_FORWARD)
3253 entry = TAILQ_NEXT(s->search_entry, entry);
3254 else
3255 entry = TAILQ_PREV(s->search_entry,
3256 commit_queue_head, entry);
3257 } else if (s->matched_entry) {
3259 * If the user has moved the cursor after we hit a match,
3260 * the position from where we should continue searching
3261 * might have changed.
3263 if (view->searching == TOG_SEARCH_FORWARD)
3264 entry = TAILQ_NEXT(s->selected_entry, entry);
3265 else
3266 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3267 entry);
3268 } else {
3269 entry = s->selected_entry;
3272 while (1) {
3273 int have_match = 0;
3275 if (entry == NULL) {
3276 if (s->thread_args.log_complete ||
3277 view->searching == TOG_SEARCH_BACKWARD) {
3278 view->search_next_done =
3279 (s->matched_entry == NULL ?
3280 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3281 s->search_entry = NULL;
3282 return NULL;
3285 * Poke the log thread for more commits and return,
3286 * allowing the main loop to make progress. Search
3287 * will resume at s->search_entry once we come back.
3289 s->thread_args.commits_needed++;
3290 return trigger_log_thread(view, 0);
3293 err = match_commit(&have_match, entry->id, entry->commit,
3294 &view->regex);
3295 if (err)
3296 break;
3297 if (have_match) {
3298 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3299 s->matched_entry = entry;
3300 break;
3303 s->search_entry = entry;
3304 if (view->searching == TOG_SEARCH_FORWARD)
3305 entry = TAILQ_NEXT(entry, entry);
3306 else
3307 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3310 if (s->matched_entry) {
3311 int cur = s->selected_entry->idx;
3312 while (cur < s->matched_entry->idx) {
3313 err = input_log_view(NULL, view, KEY_DOWN);
3314 if (err)
3315 return err;
3316 cur++;
3318 while (cur > s->matched_entry->idx) {
3319 err = input_log_view(NULL, view, KEY_UP);
3320 if (err)
3321 return err;
3322 cur--;
3326 s->search_entry = NULL;
3328 return NULL;
3331 static const struct got_error *
3332 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3333 struct got_repository *repo, const char *head_ref_name,
3334 const char *in_repo_path, int log_branches)
3336 const struct got_error *err = NULL;
3337 struct tog_log_view_state *s = &view->state.log;
3338 struct got_repository *thread_repo = NULL;
3339 struct got_commit_graph *thread_graph = NULL;
3340 int errcode;
3342 if (in_repo_path != s->in_repo_path) {
3343 free(s->in_repo_path);
3344 s->in_repo_path = strdup(in_repo_path);
3345 if (s->in_repo_path == NULL)
3346 return got_error_from_errno("strdup");
3349 /* The commit queue only contains commits being displayed. */
3350 TAILQ_INIT(&s->real_commits.head);
3351 s->real_commits.ncommits = 0;
3352 s->commits = &s->real_commits;
3354 TAILQ_INIT(&s->limit_commits.head);
3355 s->limit_view = 0;
3356 s->limit_commits.ncommits = 0;
3358 s->repo = repo;
3359 if (head_ref_name) {
3360 s->head_ref_name = strdup(head_ref_name);
3361 if (s->head_ref_name == NULL) {
3362 err = got_error_from_errno("strdup");
3363 goto done;
3366 s->start_id = got_object_id_dup(start_id);
3367 if (s->start_id == NULL) {
3368 err = got_error_from_errno("got_object_id_dup");
3369 goto done;
3371 s->log_branches = log_branches;
3372 s->use_committer = 1;
3374 STAILQ_INIT(&s->colors);
3375 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3376 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3377 get_color_value("TOG_COLOR_COMMIT"));
3378 if (err)
3379 goto done;
3380 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3381 get_color_value("TOG_COLOR_AUTHOR"));
3382 if (err) {
3383 free_colors(&s->colors);
3384 goto done;
3386 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3387 get_color_value("TOG_COLOR_DATE"));
3388 if (err) {
3389 free_colors(&s->colors);
3390 goto done;
3394 view->show = show_log_view;
3395 view->input = input_log_view;
3396 view->resize = resize_log_view;
3397 view->close = close_log_view;
3398 view->search_start = search_start_log_view;
3399 view->search_next = search_next_log_view;
3401 if (s->thread_args.pack_fds == NULL) {
3402 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3403 if (err)
3404 goto done;
3406 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3407 s->thread_args.pack_fds);
3408 if (err)
3409 goto done;
3410 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3411 !s->log_branches);
3412 if (err)
3413 goto done;
3414 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3415 s->repo, NULL, NULL);
3416 if (err)
3417 goto done;
3419 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3420 if (errcode) {
3421 err = got_error_set_errno(errcode, "pthread_cond_init");
3422 goto done;
3424 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3425 if (errcode) {
3426 err = got_error_set_errno(errcode, "pthread_cond_init");
3427 goto done;
3430 s->thread_args.commits_needed = view->nlines;
3431 s->thread_args.graph = thread_graph;
3432 s->thread_args.real_commits = &s->real_commits;
3433 s->thread_args.limit_commits = &s->limit_commits;
3434 s->thread_args.in_repo_path = s->in_repo_path;
3435 s->thread_args.start_id = s->start_id;
3436 s->thread_args.repo = thread_repo;
3437 s->thread_args.log_complete = 0;
3438 s->thread_args.quit = &s->quit;
3439 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3440 s->thread_args.selected_entry = &s->selected_entry;
3441 s->thread_args.searching = &view->searching;
3442 s->thread_args.search_next_done = &view->search_next_done;
3443 s->thread_args.regex = &view->regex;
3444 s->thread_args.limiting = &s->limit_view;
3445 s->thread_args.limit_regex = &s->limit_regex;
3446 s->thread_args.limit_commits = &s->limit_commits;
3447 done:
3448 if (err)
3449 close_log_view(view);
3450 return err;
3453 static const struct got_error *
3454 show_log_view(struct tog_view *view)
3456 const struct got_error *err;
3457 struct tog_log_view_state *s = &view->state.log;
3459 if (s->thread == 0) { //NULL) {
3460 int errcode = pthread_create(&s->thread, NULL, log_thread,
3461 &s->thread_args);
3462 if (errcode)
3463 return got_error_set_errno(errcode, "pthread_create");
3464 if (s->thread_args.commits_needed > 0) {
3465 err = trigger_log_thread(view, 1);
3466 if (err)
3467 return err;
3471 return draw_commits(view);
3474 static void
3475 log_move_cursor_up(struct tog_view *view, int page, int home)
3477 struct tog_log_view_state *s = &view->state.log;
3479 if (s->first_displayed_entry == NULL)
3480 return;
3481 if (s->selected_entry->idx == 0)
3482 view->count = 0;
3484 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3485 || home)
3486 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3488 if (!page && !home && s->selected > 0)
3489 --s->selected;
3490 else
3491 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3493 select_commit(s);
3494 return;
3497 static const struct got_error *
3498 log_move_cursor_down(struct tog_view *view, int page)
3500 struct tog_log_view_state *s = &view->state.log;
3501 const struct got_error *err = NULL;
3502 int eos = view->nlines - 2;
3504 if (s->first_displayed_entry == NULL)
3505 return NULL;
3507 if (s->thread_args.log_complete &&
3508 s->selected_entry->idx >= s->commits->ncommits - 1)
3509 return NULL;
3511 if (view_is_hsplit_top(view))
3512 --eos; /* border consumes the last line */
3514 if (!page) {
3515 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3516 ++s->selected;
3517 else
3518 err = log_scroll_down(view, 1);
3519 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3520 struct commit_queue_entry *entry;
3521 int n;
3523 s->selected = 0;
3524 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3525 s->last_displayed_entry = entry;
3526 for (n = 0; n <= eos; n++) {
3527 if (entry == NULL)
3528 break;
3529 s->first_displayed_entry = entry;
3530 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3532 if (n > 0)
3533 s->selected = n - 1;
3534 } else {
3535 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3536 s->thread_args.log_complete)
3537 s->selected += MIN(page,
3538 s->commits->ncommits - s->selected_entry->idx - 1);
3539 else
3540 err = log_scroll_down(view, page);
3542 if (err)
3543 return err;
3546 * We might necessarily overshoot in horizontal
3547 * splits; if so, select the last displayed commit.
3549 if (s->first_displayed_entry && s->last_displayed_entry) {
3550 s->selected = MIN(s->selected,
3551 s->last_displayed_entry->idx -
3552 s->first_displayed_entry->idx);
3555 select_commit(s);
3557 if (s->thread_args.log_complete &&
3558 s->selected_entry->idx == s->commits->ncommits - 1)
3559 view->count = 0;
3561 return NULL;
3564 static void
3565 view_get_split(struct tog_view *view, int *y, int *x)
3567 *x = 0;
3568 *y = 0;
3570 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3571 if (view->child && view->child->resized_y)
3572 *y = view->child->resized_y;
3573 else if (view->resized_y)
3574 *y = view->resized_y;
3575 else
3576 *y = view_split_begin_y(view->lines);
3577 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3578 if (view->child && view->child->resized_x)
3579 *x = view->child->resized_x;
3580 else if (view->resized_x)
3581 *x = view->resized_x;
3582 else
3583 *x = view_split_begin_x(view->begin_x);
3587 /* Split view horizontally at y and offset view->state->selected line. */
3588 static const struct got_error *
3589 view_init_hsplit(struct tog_view *view, int y)
3591 const struct got_error *err = NULL;
3593 view->nlines = y;
3594 view->ncols = COLS;
3595 err = view_resize(view);
3596 if (err)
3597 return err;
3599 err = offset_selection_down(view);
3601 return err;
3604 static const struct got_error *
3605 log_goto_line(struct tog_view *view, int nlines)
3607 const struct got_error *err = NULL;
3608 struct tog_log_view_state *s = &view->state.log;
3609 int g, idx = s->selected_entry->idx;
3611 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3612 return NULL;
3614 g = view->gline;
3615 view->gline = 0;
3617 if (g >= s->first_displayed_entry->idx + 1 &&
3618 g <= s->last_displayed_entry->idx + 1 &&
3619 g - s->first_displayed_entry->idx - 1 < nlines) {
3620 s->selected = g - s->first_displayed_entry->idx - 1;
3621 select_commit(s);
3622 return NULL;
3625 if (idx + 1 < g) {
3626 err = log_move_cursor_down(view, g - idx - 1);
3627 if (!err && g > s->selected_entry->idx + 1)
3628 err = log_move_cursor_down(view,
3629 g - s->first_displayed_entry->idx - 1);
3630 if (err)
3631 return err;
3632 } else if (idx + 1 > g)
3633 log_move_cursor_up(view, idx - g + 1, 0);
3635 if (g < nlines && s->first_displayed_entry->idx == 0)
3636 s->selected = g - 1;
3638 select_commit(s);
3639 return NULL;
3643 static const struct got_error *
3644 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3646 const struct got_error *err = NULL;
3647 struct tog_log_view_state *s = &view->state.log;
3648 int eos, nscroll;
3650 if (s->thread_args.load_all) {
3651 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3652 s->thread_args.load_all = 0;
3653 else if (s->thread_args.log_complete) {
3654 err = log_move_cursor_down(view, s->commits->ncommits);
3655 s->thread_args.load_all = 0;
3657 if (err)
3658 return err;
3661 eos = nscroll = view->nlines - 1;
3662 if (view_is_hsplit_top(view))
3663 --eos; /* border */
3665 if (view->gline)
3666 return log_goto_line(view, eos);
3668 switch (ch) {
3669 case '&':
3670 err = limit_log_view(view);
3671 break;
3672 case 'q':
3673 s->quit = 1;
3674 break;
3675 case '0':
3676 view->x = 0;
3677 break;
3678 case '$':
3679 view->x = MAX(view->maxx - view->ncols / 2, 0);
3680 view->count = 0;
3681 break;
3682 case KEY_RIGHT:
3683 case 'l':
3684 if (view->x + view->ncols / 2 < view->maxx)
3685 view->x += 2; /* move two columns right */
3686 else
3687 view->count = 0;
3688 break;
3689 case KEY_LEFT:
3690 case 'h':
3691 view->x -= MIN(view->x, 2); /* move two columns back */
3692 if (view->x <= 0)
3693 view->count = 0;
3694 break;
3695 case 'k':
3696 case KEY_UP:
3697 case '<':
3698 case ',':
3699 case CTRL('p'):
3700 log_move_cursor_up(view, 0, 0);
3701 break;
3702 case 'g':
3703 case '=':
3704 case KEY_HOME:
3705 log_move_cursor_up(view, 0, 1);
3706 view->count = 0;
3707 break;
3708 case CTRL('u'):
3709 case 'u':
3710 nscroll /= 2;
3711 /* FALL THROUGH */
3712 case KEY_PPAGE:
3713 case CTRL('b'):
3714 case 'b':
3715 log_move_cursor_up(view, nscroll, 0);
3716 break;
3717 case 'j':
3718 case KEY_DOWN:
3719 case '>':
3720 case '.':
3721 case CTRL('n'):
3722 err = log_move_cursor_down(view, 0);
3723 break;
3724 case '@':
3725 s->use_committer = !s->use_committer;
3726 break;
3727 case 'G':
3728 case '*':
3729 case KEY_END: {
3730 /* We don't know yet how many commits, so we're forced to
3731 * traverse them all. */
3732 view->count = 0;
3733 s->thread_args.load_all = 1;
3734 if (!s->thread_args.log_complete)
3735 return trigger_log_thread(view, 0);
3736 err = log_move_cursor_down(view, s->commits->ncommits);
3737 s->thread_args.load_all = 0;
3738 break;
3740 case CTRL('d'):
3741 case 'd':
3742 nscroll /= 2;
3743 /* FALL THROUGH */
3744 case KEY_NPAGE:
3745 case CTRL('f'):
3746 case 'f':
3747 case ' ':
3748 err = log_move_cursor_down(view, nscroll);
3749 break;
3750 case KEY_RESIZE:
3751 if (s->selected > view->nlines - 2)
3752 s->selected = view->nlines - 2;
3753 if (s->selected > s->commits->ncommits - 1)
3754 s->selected = s->commits->ncommits - 1;
3755 select_commit(s);
3756 if (s->commits->ncommits < view->nlines - 1 &&
3757 !s->thread_args.log_complete) {
3758 s->thread_args.commits_needed += (view->nlines - 1) -
3759 s->commits->ncommits;
3760 err = trigger_log_thread(view, 1);
3762 break;
3763 case KEY_ENTER:
3764 case '\r':
3765 view->count = 0;
3766 if (s->selected_entry == NULL)
3767 break;
3768 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3769 break;
3770 case 'T':
3771 view->count = 0;
3772 if (s->selected_entry == NULL)
3773 break;
3774 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3775 break;
3776 case KEY_BACKSPACE:
3777 case CTRL('l'):
3778 case 'B':
3779 view->count = 0;
3780 if (ch == KEY_BACKSPACE &&
3781 got_path_is_root_dir(s->in_repo_path))
3782 break;
3783 err = stop_log_thread(s);
3784 if (err)
3785 return err;
3786 if (ch == KEY_BACKSPACE) {
3787 char *parent_path;
3788 err = got_path_dirname(&parent_path, s->in_repo_path);
3789 if (err)
3790 return err;
3791 free(s->in_repo_path);
3792 s->in_repo_path = parent_path;
3793 s->thread_args.in_repo_path = s->in_repo_path;
3794 } else if (ch == CTRL('l')) {
3795 struct got_object_id *start_id;
3796 err = got_repo_match_object_id(&start_id, NULL,
3797 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3798 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3799 if (err) {
3800 if (s->head_ref_name == NULL ||
3801 err->code != GOT_ERR_NOT_REF)
3802 return err;
3803 /* Try to cope with deleted references. */
3804 free(s->head_ref_name);
3805 s->head_ref_name = NULL;
3806 err = got_repo_match_object_id(&start_id,
3807 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
3808 &tog_refs, s->repo);
3809 if (err)
3810 return err;
3812 free(s->start_id);
3813 s->start_id = start_id;
3814 s->thread_args.start_id = s->start_id;
3815 } else /* 'B' */
3816 s->log_branches = !s->log_branches;
3818 if (s->thread_args.pack_fds == NULL) {
3819 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3820 if (err)
3821 return err;
3823 err = got_repo_open(&s->thread_args.repo,
3824 got_repo_get_path(s->repo), NULL,
3825 s->thread_args.pack_fds);
3826 if (err)
3827 return err;
3828 tog_free_refs();
3829 err = tog_load_refs(s->repo, 0);
3830 if (err)
3831 return err;
3832 err = got_commit_graph_open(&s->thread_args.graph,
3833 s->in_repo_path, !s->log_branches);
3834 if (err)
3835 return err;
3836 err = got_commit_graph_iter_start(s->thread_args.graph,
3837 s->start_id, s->repo, NULL, NULL);
3838 if (err)
3839 return err;
3840 free_commits(&s->real_commits);
3841 free_commits(&s->limit_commits);
3842 s->first_displayed_entry = NULL;
3843 s->last_displayed_entry = NULL;
3844 s->selected_entry = NULL;
3845 s->selected = 0;
3846 s->thread_args.log_complete = 0;
3847 s->quit = 0;
3848 s->thread_args.commits_needed = view->lines;
3849 s->matched_entry = NULL;
3850 s->search_entry = NULL;
3851 view->offset = 0;
3852 break;
3853 case 'R':
3854 view->count = 0;
3855 err = view_request_new(new_view, view, TOG_VIEW_REF);
3856 break;
3857 default:
3858 view->count = 0;
3859 break;
3862 return err;
3865 static const struct got_error *
3866 apply_unveil(const char *repo_path, const char *worktree_path)
3868 const struct got_error *error;
3870 #ifdef PROFILE
3871 if (unveil("gmon.out", "rwc") != 0)
3872 return got_error_from_errno2("unveil", "gmon.out");
3873 #endif
3874 if (repo_path && unveil(repo_path, "r") != 0)
3875 return got_error_from_errno2("unveil", repo_path);
3877 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3878 return got_error_from_errno2("unveil", worktree_path);
3880 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3881 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3883 error = got_privsep_unveil_exec_helpers();
3884 if (error != NULL)
3885 return error;
3887 if (unveil(NULL, NULL) != 0)
3888 return got_error_from_errno("unveil");
3890 return NULL;
3893 static void
3894 init_curses(void)
3897 * Override default signal handlers before starting ncurses.
3898 * This should prevent ncurses from installing its own
3899 * broken cleanup() signal handler.
3901 signal(SIGWINCH, tog_sigwinch);
3902 signal(SIGPIPE, tog_sigpipe);
3903 signal(SIGCONT, tog_sigcont);
3904 signal(SIGINT, tog_sigint);
3905 signal(SIGTERM, tog_sigterm);
3907 initscr();
3908 cbreak();
3909 halfdelay(1); /* Do fast refresh while initial view is loading. */
3910 noecho();
3911 nonl();
3912 intrflush(stdscr, FALSE);
3913 keypad(stdscr, TRUE);
3914 curs_set(0);
3915 if (getenv("TOG_COLORS") != NULL) {
3916 start_color();
3917 use_default_colors();
3921 static const struct got_error *
3922 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3923 struct got_repository *repo, struct got_worktree *worktree)
3925 const struct got_error *err = NULL;
3927 if (argc == 0) {
3928 *in_repo_path = strdup("/");
3929 if (*in_repo_path == NULL)
3930 return got_error_from_errno("strdup");
3931 return NULL;
3934 if (worktree) {
3935 const char *prefix = got_worktree_get_path_prefix(worktree);
3936 char *p;
3938 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3939 if (err)
3940 return err;
3941 if (asprintf(in_repo_path, "%s%s%s", prefix,
3942 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3943 p) == -1) {
3944 err = got_error_from_errno("asprintf");
3945 *in_repo_path = NULL;
3947 free(p);
3948 } else
3949 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3951 return err;
3954 static const struct got_error *
3955 cmd_log(int argc, char *argv[])
3957 const struct got_error *error;
3958 struct got_repository *repo = NULL;
3959 struct got_worktree *worktree = NULL;
3960 struct got_object_id *start_id = NULL;
3961 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3962 char *start_commit = NULL, *label = NULL;
3963 struct got_reference *ref = NULL;
3964 const char *head_ref_name = NULL;
3965 int ch, log_branches = 0;
3966 struct tog_view *view;
3967 int *pack_fds = NULL;
3969 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3970 switch (ch) {
3971 case 'b':
3972 log_branches = 1;
3973 break;
3974 case 'c':
3975 start_commit = optarg;
3976 break;
3977 case 'r':
3978 repo_path = realpath(optarg, NULL);
3979 if (repo_path == NULL)
3980 return got_error_from_errno2("realpath",
3981 optarg);
3982 break;
3983 default:
3984 usage_log();
3985 /* NOTREACHED */
3989 argc -= optind;
3990 argv += optind;
3992 if (argc > 1)
3993 usage_log();
3995 error = got_repo_pack_fds_open(&pack_fds);
3996 if (error != NULL)
3997 goto done;
3999 if (repo_path == NULL) {
4000 cwd = getcwd(NULL, 0);
4001 if (cwd == NULL)
4002 return got_error_from_errno("getcwd");
4003 error = got_worktree_open(&worktree, cwd);
4004 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4005 goto done;
4006 if (worktree)
4007 repo_path =
4008 strdup(got_worktree_get_repo_path(worktree));
4009 else
4010 repo_path = strdup(cwd);
4011 if (repo_path == NULL) {
4012 error = got_error_from_errno("strdup");
4013 goto done;
4017 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4018 if (error != NULL)
4019 goto done;
4021 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4022 repo, worktree);
4023 if (error)
4024 goto done;
4026 init_curses();
4028 error = apply_unveil(got_repo_get_path(repo),
4029 worktree ? got_worktree_get_root_path(worktree) : NULL);
4030 if (error)
4031 goto done;
4033 /* already loaded by tog_log_with_path()? */
4034 if (TAILQ_EMPTY(&tog_refs)) {
4035 error = tog_load_refs(repo, 0);
4036 if (error)
4037 goto done;
4040 if (start_commit == NULL) {
4041 error = got_repo_match_object_id(&start_id, &label,
4042 worktree ? got_worktree_get_head_ref_name(worktree) :
4043 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4044 if (error)
4045 goto done;
4046 head_ref_name = label;
4047 } else {
4048 error = got_ref_open(&ref, repo, start_commit, 0);
4049 if (error == NULL)
4050 head_ref_name = got_ref_get_name(ref);
4051 else if (error->code != GOT_ERR_NOT_REF)
4052 goto done;
4053 error = got_repo_match_object_id(&start_id, NULL,
4054 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4055 if (error)
4056 goto done;
4059 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4060 if (view == NULL) {
4061 error = got_error_from_errno("view_open");
4062 goto done;
4064 error = open_log_view(view, start_id, repo, head_ref_name,
4065 in_repo_path, log_branches);
4066 if (error)
4067 goto done;
4068 if (worktree) {
4069 /* Release work tree lock. */
4070 got_worktree_close(worktree);
4071 worktree = NULL;
4073 error = view_loop(view);
4074 done:
4075 free(in_repo_path);
4076 free(repo_path);
4077 free(cwd);
4078 free(start_id);
4079 free(label);
4080 if (ref)
4081 got_ref_close(ref);
4082 if (repo) {
4083 const struct got_error *close_err = got_repo_close(repo);
4084 if (error == NULL)
4085 error = close_err;
4087 if (worktree)
4088 got_worktree_close(worktree);
4089 if (pack_fds) {
4090 const struct got_error *pack_err =
4091 got_repo_pack_fds_close(pack_fds);
4092 if (error == NULL)
4093 error = pack_err;
4095 tog_free_refs();
4096 return error;
4099 __dead static void
4100 usage_diff(void)
4102 endwin();
4103 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4104 "object1 object2\n", getprogname());
4105 exit(1);
4108 static int
4109 match_line(const char *line, regex_t *regex, size_t nmatch,
4110 regmatch_t *regmatch)
4112 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4115 static struct tog_color *
4116 match_color(struct tog_colors *colors, const char *line)
4118 struct tog_color *tc = NULL;
4120 STAILQ_FOREACH(tc, colors, entry) {
4121 if (match_line(line, &tc->regex, 0, NULL))
4122 return tc;
4125 return NULL;
4128 static const struct got_error *
4129 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4130 WINDOW *window, int skipcol, regmatch_t *regmatch)
4132 const struct got_error *err = NULL;
4133 char *exstr = NULL;
4134 wchar_t *wline = NULL;
4135 int rme, rms, n, width, scrollx;
4136 int width0 = 0, width1 = 0, width2 = 0;
4137 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4139 *wtotal = 0;
4141 rms = regmatch->rm_so;
4142 rme = regmatch->rm_eo;
4144 err = expand_tab(&exstr, line);
4145 if (err)
4146 return err;
4148 /* Split the line into 3 segments, according to match offsets. */
4149 seg0 = strndup(exstr, rms);
4150 if (seg0 == NULL) {
4151 err = got_error_from_errno("strndup");
4152 goto done;
4154 seg1 = strndup(exstr + rms, rme - rms);
4155 if (seg1 == NULL) {
4156 err = got_error_from_errno("strndup");
4157 goto done;
4159 seg2 = strdup(exstr + rme);
4160 if (seg2 == NULL) {
4161 err = got_error_from_errno("strndup");
4162 goto done;
4165 /* draw up to matched token if we haven't scrolled past it */
4166 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4167 col_tab_align, 1);
4168 if (err)
4169 goto done;
4170 n = MAX(width0 - skipcol, 0);
4171 if (n) {
4172 free(wline);
4173 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4174 wlimit, col_tab_align, 1);
4175 if (err)
4176 goto done;
4177 waddwstr(window, &wline[scrollx]);
4178 wlimit -= width;
4179 *wtotal += width;
4182 if (wlimit > 0) {
4183 int i = 0, w = 0;
4184 size_t wlen;
4186 free(wline);
4187 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4188 col_tab_align, 1);
4189 if (err)
4190 goto done;
4191 wlen = wcslen(wline);
4192 while (i < wlen) {
4193 width = wcwidth(wline[i]);
4194 if (width == -1) {
4195 /* should not happen, tabs are expanded */
4196 err = got_error(GOT_ERR_RANGE);
4197 goto done;
4199 if (width0 + w + width > skipcol)
4200 break;
4201 w += width;
4202 i++;
4204 /* draw (visible part of) matched token (if scrolled into it) */
4205 if (width1 - w > 0) {
4206 wattron(window, A_STANDOUT);
4207 waddwstr(window, &wline[i]);
4208 wattroff(window, A_STANDOUT);
4209 wlimit -= (width1 - w);
4210 *wtotal += (width1 - w);
4214 if (wlimit > 0) { /* draw rest of line */
4215 free(wline);
4216 if (skipcol > width0 + width1) {
4217 err = format_line(&wline, &width2, &scrollx, seg2,
4218 skipcol - (width0 + width1), wlimit,
4219 col_tab_align, 1);
4220 if (err)
4221 goto done;
4222 waddwstr(window, &wline[scrollx]);
4223 } else {
4224 err = format_line(&wline, &width2, NULL, seg2, 0,
4225 wlimit, col_tab_align, 1);
4226 if (err)
4227 goto done;
4228 waddwstr(window, wline);
4230 *wtotal += width2;
4232 done:
4233 free(wline);
4234 free(exstr);
4235 free(seg0);
4236 free(seg1);
4237 free(seg2);
4238 return err;
4241 static int
4242 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4244 FILE *f = NULL;
4245 int *eof, *first, *selected;
4247 if (view->type == TOG_VIEW_DIFF) {
4248 struct tog_diff_view_state *s = &view->state.diff;
4250 first = &s->first_displayed_line;
4251 selected = first;
4252 eof = &s->eof;
4253 f = s->f;
4254 } else if (view->type == TOG_VIEW_HELP) {
4255 struct tog_help_view_state *s = &view->state.help;
4257 first = &s->first_displayed_line;
4258 selected = first;
4259 eof = &s->eof;
4260 f = s->f;
4261 } else if (view->type == TOG_VIEW_BLAME) {
4262 struct tog_blame_view_state *s = &view->state.blame;
4264 first = &s->first_displayed_line;
4265 selected = &s->selected_line;
4266 eof = &s->eof;
4267 f = s->blame.f;
4268 } else
4269 return 0;
4271 /* Center gline in the middle of the page like vi(1). */
4272 if (*lineno < view->gline - (view->nlines - 3) / 2)
4273 return 0;
4274 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4275 rewind(f);
4276 *eof = 0;
4277 *first = 1;
4278 *lineno = 0;
4279 *nprinted = 0;
4280 return 0;
4283 *selected = view->gline <= (view->nlines - 3) / 2 ?
4284 view->gline : (view->nlines - 3) / 2 + 1;
4285 view->gline = 0;
4287 return 1;
4290 static const struct got_error *
4291 draw_file(struct tog_view *view, const char *header)
4293 struct tog_diff_view_state *s = &view->state.diff;
4294 regmatch_t *regmatch = &view->regmatch;
4295 const struct got_error *err;
4296 int nprinted = 0;
4297 char *line;
4298 size_t linesize = 0;
4299 ssize_t linelen;
4300 wchar_t *wline;
4301 int width;
4302 int max_lines = view->nlines;
4303 int nlines = s->nlines;
4304 off_t line_offset;
4306 s->lineno = s->first_displayed_line - 1;
4307 line_offset = s->lines[s->first_displayed_line - 1].offset;
4308 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4309 return got_error_from_errno("fseek");
4311 werase(view->window);
4313 if (view->gline > s->nlines - 1)
4314 view->gline = s->nlines - 1;
4316 if (header) {
4317 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4318 1 : view->gline - (view->nlines - 3) / 2 :
4319 s->lineno + s->selected_line;
4321 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4322 return got_error_from_errno("asprintf");
4323 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4324 0, 0);
4325 free(line);
4326 if (err)
4327 return err;
4329 if (view_needs_focus_indication(view))
4330 wstandout(view->window);
4331 waddwstr(view->window, wline);
4332 free(wline);
4333 wline = NULL;
4334 while (width++ < view->ncols)
4335 waddch(view->window, ' ');
4336 if (view_needs_focus_indication(view))
4337 wstandend(view->window);
4339 if (max_lines <= 1)
4340 return NULL;
4341 max_lines--;
4344 s->eof = 0;
4345 view->maxx = 0;
4346 line = NULL;
4347 while (max_lines > 0 && nprinted < max_lines) {
4348 enum got_diff_line_type linetype;
4349 attr_t attr = 0;
4351 linelen = getline(&line, &linesize, s->f);
4352 if (linelen == -1) {
4353 if (feof(s->f)) {
4354 s->eof = 1;
4355 break;
4357 free(line);
4358 return got_ferror(s->f, GOT_ERR_IO);
4361 if (++s->lineno < s->first_displayed_line)
4362 continue;
4363 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4364 continue;
4365 if (s->lineno == view->hiline)
4366 attr = A_STANDOUT;
4368 /* Set view->maxx based on full line length. */
4369 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4370 view->x ? 1 : 0);
4371 if (err) {
4372 free(line);
4373 return err;
4375 view->maxx = MAX(view->maxx, width);
4376 free(wline);
4377 wline = NULL;
4379 linetype = s->lines[s->lineno].type;
4380 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4381 linetype < GOT_DIFF_LINE_CONTEXT)
4382 attr |= COLOR_PAIR(linetype);
4383 if (attr)
4384 wattron(view->window, attr);
4385 if (s->first_displayed_line + nprinted == s->matched_line &&
4386 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4387 err = add_matched_line(&width, line, view->ncols, 0,
4388 view->window, view->x, regmatch);
4389 if (err) {
4390 free(line);
4391 return err;
4393 } else {
4394 int skip;
4395 err = format_line(&wline, &width, &skip, line,
4396 view->x, view->ncols, 0, view->x ? 1 : 0);
4397 if (err) {
4398 free(line);
4399 return err;
4401 waddwstr(view->window, &wline[skip]);
4402 free(wline);
4403 wline = NULL;
4405 if (s->lineno == view->hiline) {
4406 /* highlight full gline length */
4407 while (width++ < view->ncols)
4408 waddch(view->window, ' ');
4409 } else {
4410 if (width <= view->ncols - 1)
4411 waddch(view->window, '\n');
4413 if (attr)
4414 wattroff(view->window, attr);
4415 if (++nprinted == 1)
4416 s->first_displayed_line = s->lineno;
4418 free(line);
4419 if (nprinted >= 1)
4420 s->last_displayed_line = s->first_displayed_line +
4421 (nprinted - 1);
4422 else
4423 s->last_displayed_line = s->first_displayed_line;
4425 view_border(view);
4427 if (s->eof) {
4428 while (nprinted < view->nlines) {
4429 waddch(view->window, '\n');
4430 nprinted++;
4433 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4434 view->ncols, 0, 0);
4435 if (err) {
4436 return err;
4439 wstandout(view->window);
4440 waddwstr(view->window, wline);
4441 free(wline);
4442 wline = NULL;
4443 wstandend(view->window);
4446 return NULL;
4449 static char *
4450 get_datestr(time_t *time, char *datebuf)
4452 struct tm mytm, *tm;
4453 char *p, *s;
4455 tm = gmtime_r(time, &mytm);
4456 if (tm == NULL)
4457 return NULL;
4458 s = asctime_r(tm, datebuf);
4459 if (s == NULL)
4460 return NULL;
4461 p = strchr(s, '\n');
4462 if (p)
4463 *p = '\0';
4464 return s;
4467 static const struct got_error *
4468 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4469 off_t off, uint8_t type)
4471 struct got_diff_line *p;
4473 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4474 if (p == NULL)
4475 return got_error_from_errno("reallocarray");
4476 *lines = p;
4477 (*lines)[*nlines].offset = off;
4478 (*lines)[*nlines].type = type;
4479 (*nlines)++;
4481 return NULL;
4484 static const struct got_error *
4485 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4486 struct got_diff_line *s_lines, size_t s_nlines)
4488 struct got_diff_line *p;
4489 char buf[BUFSIZ];
4490 size_t i, r;
4492 if (fseeko(src, 0L, SEEK_SET) == -1)
4493 return got_error_from_errno("fseeko");
4495 for (;;) {
4496 r = fread(buf, 1, sizeof(buf), src);
4497 if (r == 0) {
4498 if (ferror(src))
4499 return got_error_from_errno("fread");
4500 if (feof(src))
4501 break;
4503 if (fwrite(buf, 1, r, dst) != r)
4504 return got_ferror(dst, GOT_ERR_IO);
4508 * The diff driver initialises the first line at offset zero when the
4509 * array isn't prepopulated, skip it; we already have it in *d_lines.
4511 for (i = 1; i < s_nlines; ++i)
4512 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4514 --s_nlines;
4516 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4517 if (p == NULL) {
4518 /* d_lines is freed in close_diff_view() */
4519 return got_error_from_errno("reallocarray");
4522 *d_lines = p;
4524 memcpy(*d_lines + *d_nlines, s_lines + 1, s_nlines * sizeof(*s_lines));
4525 *d_nlines += s_nlines;
4527 return NULL;
4530 static const struct got_error *
4531 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4532 struct got_object_id *commit_id, struct got_reflist_head *refs,
4533 struct got_repository *repo, int ignore_ws, int force_text_diff,
4534 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4536 const struct got_error *err = NULL;
4537 char datebuf[26], *datestr;
4538 struct got_commit_object *commit;
4539 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4540 time_t committer_time;
4541 const char *author, *committer;
4542 char *refs_str = NULL;
4543 struct got_pathlist_entry *pe;
4544 off_t outoff = 0;
4545 int n;
4547 if (refs) {
4548 err = build_refs_str(&refs_str, refs, commit_id, repo);
4549 if (err)
4550 return err;
4553 err = got_object_open_as_commit(&commit, repo, commit_id);
4554 if (err)
4555 return err;
4557 err = got_object_id_str(&id_str, commit_id);
4558 if (err) {
4559 err = got_error_from_errno("got_object_id_str");
4560 goto done;
4563 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4564 if (err)
4565 goto done;
4567 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4568 refs_str ? refs_str : "", refs_str ? ")" : "");
4569 if (n < 0) {
4570 err = got_error_from_errno("fprintf");
4571 goto done;
4573 outoff += n;
4574 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4575 if (err)
4576 goto done;
4578 n = fprintf(outfile, "from: %s\n",
4579 got_object_commit_get_author(commit));
4580 if (n < 0) {
4581 err = got_error_from_errno("fprintf");
4582 goto done;
4584 outoff += n;
4585 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4586 if (err)
4587 goto done;
4589 author = got_object_commit_get_author(commit);
4590 committer = got_object_commit_get_committer(commit);
4591 if (strcmp(author, committer) != 0) {
4592 n = fprintf(outfile, "via: %s\n", committer);
4593 if (n < 0) {
4594 err = got_error_from_errno("fprintf");
4595 goto done;
4597 outoff += n;
4598 err = add_line_metadata(lines, nlines, outoff,
4599 GOT_DIFF_LINE_AUTHOR);
4600 if (err)
4601 goto done;
4603 committer_time = got_object_commit_get_committer_time(commit);
4604 datestr = get_datestr(&committer_time, datebuf);
4605 if (datestr) {
4606 n = fprintf(outfile, "date: %s UTC\n", datestr);
4607 if (n < 0) {
4608 err = got_error_from_errno("fprintf");
4609 goto done;
4611 outoff += n;
4612 err = add_line_metadata(lines, nlines, outoff,
4613 GOT_DIFF_LINE_DATE);
4614 if (err)
4615 goto done;
4617 if (got_object_commit_get_nparents(commit) > 1) {
4618 const struct got_object_id_queue *parent_ids;
4619 struct got_object_qid *qid;
4620 int pn = 1;
4621 parent_ids = got_object_commit_get_parent_ids(commit);
4622 STAILQ_FOREACH(qid, parent_ids, entry) {
4623 err = got_object_id_str(&id_str, &qid->id);
4624 if (err)
4625 goto done;
4626 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4627 if (n < 0) {
4628 err = got_error_from_errno("fprintf");
4629 goto done;
4631 outoff += n;
4632 err = add_line_metadata(lines, nlines, outoff,
4633 GOT_DIFF_LINE_META);
4634 if (err)
4635 goto done;
4636 free(id_str);
4637 id_str = NULL;
4641 err = got_object_commit_get_logmsg(&logmsg, commit);
4642 if (err)
4643 goto done;
4644 s = logmsg;
4645 while ((line = strsep(&s, "\n")) != NULL) {
4646 n = fprintf(outfile, "%s\n", line);
4647 if (n < 0) {
4648 err = got_error_from_errno("fprintf");
4649 goto done;
4651 outoff += n;
4652 err = add_line_metadata(lines, nlines, outoff,
4653 GOT_DIFF_LINE_LOGMSG);
4654 if (err)
4655 goto done;
4658 TAILQ_FOREACH(pe, dsa->paths, entry) {
4659 struct got_diff_changed_path *cp = pe->data;
4660 int pad = dsa->max_path_len - pe->path_len + 1;
4662 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4663 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4664 dsa->rm_cols + 1, cp->rm);
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_CHANGES);
4672 if (err)
4673 goto done;
4676 fputc('\n', outfile);
4677 outoff++;
4678 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4679 if (err)
4680 goto done;
4682 n = fprintf(outfile,
4683 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4684 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4685 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4686 if (n < 0) {
4687 err = got_error_from_errno("fprintf");
4688 goto done;
4690 outoff += n;
4691 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4692 if (err)
4693 goto done;
4695 fputc('\n', outfile);
4696 outoff++;
4697 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4698 done:
4699 free(id_str);
4700 free(logmsg);
4701 free(refs_str);
4702 got_object_commit_close(commit);
4703 if (err) {
4704 free(*lines);
4705 *lines = NULL;
4706 *nlines = 0;
4708 return err;
4711 static const struct got_error *
4712 create_diff(struct tog_diff_view_state *s)
4714 const struct got_error *err = NULL;
4715 FILE *f = NULL, *tmp_diff_file = NULL;
4716 int obj_type;
4717 struct got_diff_line *lines = NULL;
4718 struct got_pathlist_head changed_paths;
4720 TAILQ_INIT(&changed_paths);
4722 free(s->lines);
4723 s->lines = malloc(sizeof(*s->lines));
4724 if (s->lines == NULL)
4725 return got_error_from_errno("malloc");
4726 s->nlines = 0;
4728 f = got_opentemp();
4729 if (f == NULL) {
4730 err = got_error_from_errno("got_opentemp");
4731 goto done;
4733 tmp_diff_file = got_opentemp();
4734 if (tmp_diff_file == NULL) {
4735 err = got_error_from_errno("got_opentemp");
4736 goto done;
4738 if (s->f && fclose(s->f) == EOF) {
4739 err = got_error_from_errno("fclose");
4740 goto done;
4742 s->f = f;
4744 if (s->id1)
4745 err = got_object_get_type(&obj_type, s->repo, s->id1);
4746 else
4747 err = got_object_get_type(&obj_type, s->repo, s->id2);
4748 if (err)
4749 goto done;
4751 switch (obj_type) {
4752 case GOT_OBJ_TYPE_BLOB:
4753 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4754 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4755 s->label1, s->label2, tog_diff_algo, s->diff_context,
4756 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
4757 s->f);
4758 break;
4759 case GOT_OBJ_TYPE_TREE:
4760 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4761 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4762 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4763 s->force_text_diff, NULL, s->repo, s->f);
4764 break;
4765 case GOT_OBJ_TYPE_COMMIT: {
4766 const struct got_object_id_queue *parent_ids;
4767 struct got_object_qid *pid;
4768 struct got_commit_object *commit2;
4769 struct got_reflist_head *refs;
4770 size_t nlines = 0;
4771 struct got_diffstat_cb_arg dsa = {
4772 0, 0, 0, 0, 0, 0,
4773 &changed_paths,
4774 s->ignore_whitespace,
4775 s->force_text_diff,
4776 tog_diff_algo
4779 lines = malloc(sizeof(*lines));
4780 if (lines == NULL) {
4781 err = got_error_from_errno("malloc");
4782 goto done;
4785 /* build diff first in tmp file then append to commit info */
4786 err = got_diff_objects_as_commits(&lines, &nlines,
4787 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4788 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4789 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
4790 if (err)
4791 break;
4793 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4794 if (err)
4795 goto done;
4796 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4797 /* Show commit info if we're diffing to a parent/root commit. */
4798 if (s->id1 == NULL) {
4799 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4800 refs, s->repo, s->ignore_whitespace,
4801 s->force_text_diff, &dsa, s->f);
4802 if (err)
4803 goto done;
4804 } else {
4805 parent_ids = got_object_commit_get_parent_ids(commit2);
4806 STAILQ_FOREACH(pid, parent_ids, entry) {
4807 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4808 err = write_commit_info(&s->lines,
4809 &s->nlines, s->id2, refs, s->repo,
4810 s->ignore_whitespace,
4811 s->force_text_diff, &dsa, s->f);
4812 if (err)
4813 goto done;
4814 break;
4818 got_object_commit_close(commit2);
4820 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
4821 lines, nlines);
4822 break;
4824 default:
4825 err = got_error(GOT_ERR_OBJ_TYPE);
4826 break;
4828 done:
4829 free(lines);
4830 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4831 if (s->f && fflush(s->f) != 0 && err == NULL)
4832 err = got_error_from_errno("fflush");
4833 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
4834 err = got_error_from_errno("fclose");
4835 return err;
4838 static void
4839 diff_view_indicate_progress(struct tog_view *view)
4841 mvwaddstr(view->window, 0, 0, "diffing...");
4842 update_panels();
4843 doupdate();
4846 static const struct got_error *
4847 search_start_diff_view(struct tog_view *view)
4849 struct tog_diff_view_state *s = &view->state.diff;
4851 s->matched_line = 0;
4852 return NULL;
4855 static void
4856 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4857 size_t *nlines, int **first, int **last, int **match, int **selected)
4859 struct tog_diff_view_state *s = &view->state.diff;
4861 *f = s->f;
4862 *nlines = s->nlines;
4863 *line_offsets = NULL;
4864 *match = &s->matched_line;
4865 *first = &s->first_displayed_line;
4866 *last = &s->last_displayed_line;
4867 *selected = &s->selected_line;
4870 static const struct got_error *
4871 search_next_view_match(struct tog_view *view)
4873 const struct got_error *err = NULL;
4874 FILE *f;
4875 int lineno;
4876 char *line = NULL;
4877 size_t linesize = 0;
4878 ssize_t linelen;
4879 off_t *line_offsets;
4880 size_t nlines = 0;
4881 int *first, *last, *match, *selected;
4883 if (!view->search_setup)
4884 return got_error_msg(GOT_ERR_NOT_IMPL,
4885 "view search not supported");
4886 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4887 &match, &selected);
4889 if (!view->searching) {
4890 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4891 return NULL;
4894 if (*match) {
4895 if (view->searching == TOG_SEARCH_FORWARD)
4896 lineno = *match + 1;
4897 else
4898 lineno = *match - 1;
4899 } else
4900 lineno = *first - 1 + *selected;
4902 while (1) {
4903 off_t offset;
4905 if (lineno <= 0 || lineno > nlines) {
4906 if (*match == 0) {
4907 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4908 break;
4911 if (view->searching == TOG_SEARCH_FORWARD)
4912 lineno = 1;
4913 else
4914 lineno = nlines;
4917 offset = view->type == TOG_VIEW_DIFF ?
4918 view->state.diff.lines[lineno - 1].offset :
4919 line_offsets[lineno - 1];
4920 if (fseeko(f, offset, SEEK_SET) != 0) {
4921 free(line);
4922 return got_error_from_errno("fseeko");
4924 linelen = getline(&line, &linesize, f);
4925 if (linelen != -1) {
4926 char *exstr;
4927 err = expand_tab(&exstr, line);
4928 if (err)
4929 break;
4930 if (match_line(exstr, &view->regex, 1,
4931 &view->regmatch)) {
4932 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4933 *match = lineno;
4934 free(exstr);
4935 break;
4937 free(exstr);
4939 if (view->searching == TOG_SEARCH_FORWARD)
4940 lineno++;
4941 else
4942 lineno--;
4944 free(line);
4946 if (*match) {
4947 *first = *match;
4948 *selected = 1;
4951 return err;
4954 static const struct got_error *
4955 close_diff_view(struct tog_view *view)
4957 const struct got_error *err = NULL;
4958 struct tog_diff_view_state *s = &view->state.diff;
4960 free(s->id1);
4961 s->id1 = NULL;
4962 free(s->id2);
4963 s->id2 = NULL;
4964 if (s->f && fclose(s->f) == EOF)
4965 err = got_error_from_errno("fclose");
4966 s->f = NULL;
4967 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4968 err = got_error_from_errno("fclose");
4969 s->f1 = NULL;
4970 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4971 err = got_error_from_errno("fclose");
4972 s->f2 = NULL;
4973 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4974 err = got_error_from_errno("close");
4975 s->fd1 = -1;
4976 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4977 err = got_error_from_errno("close");
4978 s->fd2 = -1;
4979 free(s->lines);
4980 s->lines = NULL;
4981 s->nlines = 0;
4982 return err;
4985 static const struct got_error *
4986 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4987 struct got_object_id *id2, const char *label1, const char *label2,
4988 int diff_context, int ignore_whitespace, int force_text_diff,
4989 struct tog_view *parent_view, struct got_repository *repo)
4991 const struct got_error *err;
4992 struct tog_diff_view_state *s = &view->state.diff;
4994 memset(s, 0, sizeof(*s));
4995 s->fd1 = -1;
4996 s->fd2 = -1;
4998 if (id1 != NULL && id2 != NULL) {
4999 int type1, type2;
5000 err = got_object_get_type(&type1, repo, id1);
5001 if (err)
5002 return err;
5003 err = got_object_get_type(&type2, repo, id2);
5004 if (err)
5005 return err;
5007 if (type1 != type2)
5008 return got_error(GOT_ERR_OBJ_TYPE);
5010 s->first_displayed_line = 1;
5011 s->last_displayed_line = view->nlines;
5012 s->selected_line = 1;
5013 s->repo = repo;
5014 s->id1 = id1;
5015 s->id2 = id2;
5016 s->label1 = label1;
5017 s->label2 = label2;
5019 if (id1) {
5020 s->id1 = got_object_id_dup(id1);
5021 if (s->id1 == NULL)
5022 return got_error_from_errno("got_object_id_dup");
5023 } else
5024 s->id1 = NULL;
5026 s->id2 = got_object_id_dup(id2);
5027 if (s->id2 == NULL) {
5028 err = got_error_from_errno("got_object_id_dup");
5029 goto done;
5032 s->f1 = got_opentemp();
5033 if (s->f1 == NULL) {
5034 err = got_error_from_errno("got_opentemp");
5035 goto done;
5038 s->f2 = got_opentemp();
5039 if (s->f2 == NULL) {
5040 err = got_error_from_errno("got_opentemp");
5041 goto done;
5044 s->fd1 = got_opentempfd();
5045 if (s->fd1 == -1) {
5046 err = got_error_from_errno("got_opentempfd");
5047 goto done;
5050 s->fd2 = got_opentempfd();
5051 if (s->fd2 == -1) {
5052 err = got_error_from_errno("got_opentempfd");
5053 goto done;
5056 s->diff_context = diff_context;
5057 s->ignore_whitespace = ignore_whitespace;
5058 s->force_text_diff = force_text_diff;
5059 s->parent_view = parent_view;
5060 s->repo = repo;
5062 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5063 int rc;
5065 rc = init_pair(GOT_DIFF_LINE_MINUS,
5066 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5067 if (rc != ERR)
5068 rc = init_pair(GOT_DIFF_LINE_PLUS,
5069 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5070 if (rc != ERR)
5071 rc = init_pair(GOT_DIFF_LINE_HUNK,
5072 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5073 if (rc != ERR)
5074 rc = init_pair(GOT_DIFF_LINE_META,
5075 get_color_value("TOG_COLOR_DIFF_META"), -1);
5076 if (rc != ERR)
5077 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5078 get_color_value("TOG_COLOR_DIFF_META"), -1);
5079 if (rc != ERR)
5080 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5081 get_color_value("TOG_COLOR_DIFF_META"), -1);
5082 if (rc != ERR)
5083 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5084 get_color_value("TOG_COLOR_DIFF_META"), -1);
5085 if (rc != ERR)
5086 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5087 get_color_value("TOG_COLOR_AUTHOR"), -1);
5088 if (rc != ERR)
5089 rc = init_pair(GOT_DIFF_LINE_DATE,
5090 get_color_value("TOG_COLOR_DATE"), -1);
5091 if (rc == ERR) {
5092 err = got_error(GOT_ERR_RANGE);
5093 goto done;
5097 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5098 view_is_splitscreen(view))
5099 show_log_view(parent_view); /* draw border */
5100 diff_view_indicate_progress(view);
5102 err = create_diff(s);
5104 view->show = show_diff_view;
5105 view->input = input_diff_view;
5106 view->reset = reset_diff_view;
5107 view->close = close_diff_view;
5108 view->search_start = search_start_diff_view;
5109 view->search_setup = search_setup_diff_view;
5110 view->search_next = search_next_view_match;
5111 done:
5112 if (err)
5113 close_diff_view(view);
5114 return err;
5117 static const struct got_error *
5118 show_diff_view(struct tog_view *view)
5120 const struct got_error *err;
5121 struct tog_diff_view_state *s = &view->state.diff;
5122 char *id_str1 = NULL, *id_str2, *header;
5123 const char *label1, *label2;
5125 if (s->id1) {
5126 err = got_object_id_str(&id_str1, s->id1);
5127 if (err)
5128 return err;
5129 label1 = s->label1 ? s->label1 : id_str1;
5130 } else
5131 label1 = "/dev/null";
5133 err = got_object_id_str(&id_str2, s->id2);
5134 if (err)
5135 return err;
5136 label2 = s->label2 ? s->label2 : id_str2;
5138 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5139 err = got_error_from_errno("asprintf");
5140 free(id_str1);
5141 free(id_str2);
5142 return err;
5144 free(id_str1);
5145 free(id_str2);
5147 err = draw_file(view, header);
5148 free(header);
5149 return err;
5152 static const struct got_error *
5153 set_selected_commit(struct tog_diff_view_state *s,
5154 struct commit_queue_entry *entry)
5156 const struct got_error *err;
5157 const struct got_object_id_queue *parent_ids;
5158 struct got_commit_object *selected_commit;
5159 struct got_object_qid *pid;
5161 free(s->id2);
5162 s->id2 = got_object_id_dup(entry->id);
5163 if (s->id2 == NULL)
5164 return got_error_from_errno("got_object_id_dup");
5166 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5167 if (err)
5168 return err;
5169 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5170 free(s->id1);
5171 pid = STAILQ_FIRST(parent_ids);
5172 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5173 got_object_commit_close(selected_commit);
5174 return NULL;
5177 static const struct got_error *
5178 reset_diff_view(struct tog_view *view)
5180 struct tog_diff_view_state *s = &view->state.diff;
5182 view->count = 0;
5183 wclear(view->window);
5184 s->first_displayed_line = 1;
5185 s->last_displayed_line = view->nlines;
5186 s->matched_line = 0;
5187 diff_view_indicate_progress(view);
5188 return create_diff(s);
5191 static void
5192 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5194 int start, i;
5196 i = start = s->first_displayed_line - 1;
5198 while (s->lines[i].type != type) {
5199 if (i == 0)
5200 i = s->nlines - 1;
5201 if (--i == start)
5202 return; /* do nothing, requested type not in file */
5205 s->selected_line = 1;
5206 s->first_displayed_line = i;
5209 static void
5210 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5212 int start, i;
5214 i = start = s->first_displayed_line + 1;
5216 while (s->lines[i].type != type) {
5217 if (i == s->nlines - 1)
5218 i = 0;
5219 if (++i == start)
5220 return; /* do nothing, requested type not in file */
5223 s->selected_line = 1;
5224 s->first_displayed_line = i;
5227 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5228 int, int, int);
5229 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5230 int, int);
5232 static const struct got_error *
5233 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5235 const struct got_error *err = NULL;
5236 struct tog_diff_view_state *s = &view->state.diff;
5237 struct tog_log_view_state *ls;
5238 struct commit_queue_entry *old_selected_entry;
5239 char *line = NULL;
5240 size_t linesize = 0;
5241 ssize_t linelen;
5242 int i, nscroll = view->nlines - 1, up = 0;
5244 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5246 switch (ch) {
5247 case '0':
5248 view->x = 0;
5249 break;
5250 case '$':
5251 view->x = MAX(view->maxx - view->ncols / 3, 0);
5252 view->count = 0;
5253 break;
5254 case KEY_RIGHT:
5255 case 'l':
5256 if (view->x + view->ncols / 3 < view->maxx)
5257 view->x += 2; /* move two columns right */
5258 else
5259 view->count = 0;
5260 break;
5261 case KEY_LEFT:
5262 case 'h':
5263 view->x -= MIN(view->x, 2); /* move two columns back */
5264 if (view->x <= 0)
5265 view->count = 0;
5266 break;
5267 case 'a':
5268 case 'w':
5269 if (ch == 'a')
5270 s->force_text_diff = !s->force_text_diff;
5271 else if (ch == 'w')
5272 s->ignore_whitespace = !s->ignore_whitespace;
5273 err = reset_diff_view(view);
5274 break;
5275 case 'g':
5276 case KEY_HOME:
5277 s->first_displayed_line = 1;
5278 view->count = 0;
5279 break;
5280 case 'G':
5281 case KEY_END:
5282 view->count = 0;
5283 if (s->eof)
5284 break;
5286 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5287 s->eof = 1;
5288 break;
5289 case 'k':
5290 case KEY_UP:
5291 case CTRL('p'):
5292 if (s->first_displayed_line > 1)
5293 s->first_displayed_line--;
5294 else
5295 view->count = 0;
5296 break;
5297 case CTRL('u'):
5298 case 'u':
5299 nscroll /= 2;
5300 /* FALL THROUGH */
5301 case KEY_PPAGE:
5302 case CTRL('b'):
5303 case 'b':
5304 if (s->first_displayed_line == 1) {
5305 view->count = 0;
5306 break;
5308 i = 0;
5309 while (i++ < nscroll && s->first_displayed_line > 1)
5310 s->first_displayed_line--;
5311 break;
5312 case 'j':
5313 case KEY_DOWN:
5314 case CTRL('n'):
5315 if (!s->eof)
5316 s->first_displayed_line++;
5317 else
5318 view->count = 0;
5319 break;
5320 case CTRL('d'):
5321 case 'd':
5322 nscroll /= 2;
5323 /* FALL THROUGH */
5324 case KEY_NPAGE:
5325 case CTRL('f'):
5326 case 'f':
5327 case ' ':
5328 if (s->eof) {
5329 view->count = 0;
5330 break;
5332 i = 0;
5333 while (!s->eof && i++ < nscroll) {
5334 linelen = getline(&line, &linesize, s->f);
5335 s->first_displayed_line++;
5336 if (linelen == -1) {
5337 if (feof(s->f)) {
5338 s->eof = 1;
5339 } else
5340 err = got_ferror(s->f, GOT_ERR_IO);
5341 break;
5344 free(line);
5345 break;
5346 case '(':
5347 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5348 break;
5349 case ')':
5350 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5351 break;
5352 case '{':
5353 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5354 break;
5355 case '}':
5356 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5357 break;
5358 case '[':
5359 if (s->diff_context > 0) {
5360 s->diff_context--;
5361 s->matched_line = 0;
5362 diff_view_indicate_progress(view);
5363 err = create_diff(s);
5364 if (s->first_displayed_line + view->nlines - 1 >
5365 s->nlines) {
5366 s->first_displayed_line = 1;
5367 s->last_displayed_line = view->nlines;
5369 } else
5370 view->count = 0;
5371 break;
5372 case ']':
5373 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5374 s->diff_context++;
5375 s->matched_line = 0;
5376 diff_view_indicate_progress(view);
5377 err = create_diff(s);
5378 } else
5379 view->count = 0;
5380 break;
5381 case '<':
5382 case ',':
5383 case 'K':
5384 up = 1;
5385 /* FALL THROUGH */
5386 case '>':
5387 case '.':
5388 case 'J':
5389 if (s->parent_view == NULL) {
5390 view->count = 0;
5391 break;
5393 s->parent_view->count = view->count;
5395 if (s->parent_view->type == TOG_VIEW_LOG) {
5396 ls = &s->parent_view->state.log;
5397 old_selected_entry = ls->selected_entry;
5399 err = input_log_view(NULL, s->parent_view,
5400 up ? KEY_UP : KEY_DOWN);
5401 if (err)
5402 break;
5403 view->count = s->parent_view->count;
5405 if (old_selected_entry == ls->selected_entry)
5406 break;
5408 err = set_selected_commit(s, ls->selected_entry);
5409 if (err)
5410 break;
5411 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5412 struct tog_blame_view_state *bs;
5413 struct got_object_id *id, *prev_id;
5415 bs = &s->parent_view->state.blame;
5416 prev_id = get_annotation_for_line(bs->blame.lines,
5417 bs->blame.nlines, bs->last_diffed_line);
5419 err = input_blame_view(&view, s->parent_view,
5420 up ? KEY_UP : KEY_DOWN);
5421 if (err)
5422 break;
5423 view->count = s->parent_view->count;
5425 if (prev_id == NULL)
5426 break;
5427 id = get_selected_commit_id(bs->blame.lines,
5428 bs->blame.nlines, bs->first_displayed_line,
5429 bs->selected_line);
5430 if (id == NULL)
5431 break;
5433 if (!got_object_id_cmp(prev_id, id))
5434 break;
5436 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5437 if (err)
5438 break;
5440 s->first_displayed_line = 1;
5441 s->last_displayed_line = view->nlines;
5442 s->matched_line = 0;
5443 view->x = 0;
5445 diff_view_indicate_progress(view);
5446 err = create_diff(s);
5447 break;
5448 default:
5449 view->count = 0;
5450 break;
5453 return err;
5456 static const struct got_error *
5457 cmd_diff(int argc, char *argv[])
5459 const struct got_error *error = NULL;
5460 struct got_repository *repo = NULL;
5461 struct got_worktree *worktree = NULL;
5462 struct got_object_id *id1 = NULL, *id2 = NULL;
5463 char *repo_path = NULL, *cwd = NULL;
5464 char *id_str1 = NULL, *id_str2 = NULL;
5465 char *label1 = NULL, *label2 = NULL;
5466 int diff_context = 3, ignore_whitespace = 0;
5467 int ch, force_text_diff = 0;
5468 const char *errstr;
5469 struct tog_view *view;
5470 int *pack_fds = NULL;
5472 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5473 switch (ch) {
5474 case 'a':
5475 force_text_diff = 1;
5476 break;
5477 case 'C':
5478 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5479 &errstr);
5480 if (errstr != NULL)
5481 errx(1, "number of context lines is %s: %s",
5482 errstr, errstr);
5483 break;
5484 case 'r':
5485 repo_path = realpath(optarg, NULL);
5486 if (repo_path == NULL)
5487 return got_error_from_errno2("realpath",
5488 optarg);
5489 got_path_strip_trailing_slashes(repo_path);
5490 break;
5491 case 'w':
5492 ignore_whitespace = 1;
5493 break;
5494 default:
5495 usage_diff();
5496 /* NOTREACHED */
5500 argc -= optind;
5501 argv += optind;
5503 if (argc == 0) {
5504 usage_diff(); /* TODO show local worktree changes */
5505 } else if (argc == 2) {
5506 id_str1 = argv[0];
5507 id_str2 = argv[1];
5508 } else
5509 usage_diff();
5511 error = got_repo_pack_fds_open(&pack_fds);
5512 if (error)
5513 goto done;
5515 if (repo_path == NULL) {
5516 cwd = getcwd(NULL, 0);
5517 if (cwd == NULL)
5518 return got_error_from_errno("getcwd");
5519 error = got_worktree_open(&worktree, cwd);
5520 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5521 goto done;
5522 if (worktree)
5523 repo_path =
5524 strdup(got_worktree_get_repo_path(worktree));
5525 else
5526 repo_path = strdup(cwd);
5527 if (repo_path == NULL) {
5528 error = got_error_from_errno("strdup");
5529 goto done;
5533 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5534 if (error)
5535 goto done;
5537 init_curses();
5539 error = apply_unveil(got_repo_get_path(repo), NULL);
5540 if (error)
5541 goto done;
5543 error = tog_load_refs(repo, 0);
5544 if (error)
5545 goto done;
5547 error = got_repo_match_object_id(&id1, &label1, id_str1,
5548 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5549 if (error)
5550 goto done;
5552 error = got_repo_match_object_id(&id2, &label2, id_str2,
5553 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5554 if (error)
5555 goto done;
5557 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5558 if (view == NULL) {
5559 error = got_error_from_errno("view_open");
5560 goto done;
5562 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5563 ignore_whitespace, force_text_diff, NULL, repo);
5564 if (error)
5565 goto done;
5566 error = view_loop(view);
5567 done:
5568 free(label1);
5569 free(label2);
5570 free(repo_path);
5571 free(cwd);
5572 if (repo) {
5573 const struct got_error *close_err = got_repo_close(repo);
5574 if (error == NULL)
5575 error = close_err;
5577 if (worktree)
5578 got_worktree_close(worktree);
5579 if (pack_fds) {
5580 const struct got_error *pack_err =
5581 got_repo_pack_fds_close(pack_fds);
5582 if (error == NULL)
5583 error = pack_err;
5585 tog_free_refs();
5586 return error;
5589 __dead static void
5590 usage_blame(void)
5592 endwin();
5593 fprintf(stderr,
5594 "usage: %s blame [-c commit] [-r repository-path] path\n",
5595 getprogname());
5596 exit(1);
5599 struct tog_blame_line {
5600 int annotated;
5601 struct got_object_id *id;
5604 static const struct got_error *
5605 draw_blame(struct tog_view *view)
5607 struct tog_blame_view_state *s = &view->state.blame;
5608 struct tog_blame *blame = &s->blame;
5609 regmatch_t *regmatch = &view->regmatch;
5610 const struct got_error *err;
5611 int lineno = 0, nprinted = 0;
5612 char *line = NULL;
5613 size_t linesize = 0;
5614 ssize_t linelen;
5615 wchar_t *wline;
5616 int width;
5617 struct tog_blame_line *blame_line;
5618 struct got_object_id *prev_id = NULL;
5619 char *id_str;
5620 struct tog_color *tc;
5622 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5623 if (err)
5624 return err;
5626 rewind(blame->f);
5627 werase(view->window);
5629 if (asprintf(&line, "commit %s", id_str) == -1) {
5630 err = got_error_from_errno("asprintf");
5631 free(id_str);
5632 return err;
5635 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5636 free(line);
5637 line = NULL;
5638 if (err)
5639 return err;
5640 if (view_needs_focus_indication(view))
5641 wstandout(view->window);
5642 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5643 if (tc)
5644 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5645 waddwstr(view->window, wline);
5646 while (width++ < view->ncols)
5647 waddch(view->window, ' ');
5648 if (tc)
5649 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5650 if (view_needs_focus_indication(view))
5651 wstandend(view->window);
5652 free(wline);
5653 wline = NULL;
5655 if (view->gline > blame->nlines)
5656 view->gline = blame->nlines;
5658 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5659 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5660 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5661 free(id_str);
5662 return got_error_from_errno("asprintf");
5664 free(id_str);
5665 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5666 free(line);
5667 line = NULL;
5668 if (err)
5669 return err;
5670 waddwstr(view->window, wline);
5671 free(wline);
5672 wline = NULL;
5673 if (width < view->ncols - 1)
5674 waddch(view->window, '\n');
5676 s->eof = 0;
5677 view->maxx = 0;
5678 while (nprinted < view->nlines - 2) {
5679 linelen = getline(&line, &linesize, blame->f);
5680 if (linelen == -1) {
5681 if (feof(blame->f)) {
5682 s->eof = 1;
5683 break;
5685 free(line);
5686 return got_ferror(blame->f, GOT_ERR_IO);
5688 if (++lineno < s->first_displayed_line)
5689 continue;
5690 if (view->gline && !gotoline(view, &lineno, &nprinted))
5691 continue;
5693 /* Set view->maxx based on full line length. */
5694 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5695 if (err) {
5696 free(line);
5697 return err;
5699 free(wline);
5700 wline = NULL;
5701 view->maxx = MAX(view->maxx, width);
5703 if (nprinted == s->selected_line - 1)
5704 wstandout(view->window);
5706 if (blame->nlines > 0) {
5707 blame_line = &blame->lines[lineno - 1];
5708 if (blame_line->annotated && prev_id &&
5709 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5710 !(nprinted == s->selected_line - 1)) {
5711 waddstr(view->window, " ");
5712 } else if (blame_line->annotated) {
5713 char *id_str;
5714 err = got_object_id_str(&id_str,
5715 blame_line->id);
5716 if (err) {
5717 free(line);
5718 return err;
5720 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5721 if (tc)
5722 wattr_on(view->window,
5723 COLOR_PAIR(tc->colorpair), NULL);
5724 wprintw(view->window, "%.8s", id_str);
5725 if (tc)
5726 wattr_off(view->window,
5727 COLOR_PAIR(tc->colorpair), NULL);
5728 free(id_str);
5729 prev_id = blame_line->id;
5730 } else {
5731 waddstr(view->window, "........");
5732 prev_id = NULL;
5734 } else {
5735 waddstr(view->window, "........");
5736 prev_id = NULL;
5739 if (nprinted == s->selected_line - 1)
5740 wstandend(view->window);
5741 waddstr(view->window, " ");
5743 if (view->ncols <= 9) {
5744 width = 9;
5745 } else if (s->first_displayed_line + nprinted ==
5746 s->matched_line &&
5747 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5748 err = add_matched_line(&width, line, view->ncols - 9, 9,
5749 view->window, view->x, regmatch);
5750 if (err) {
5751 free(line);
5752 return err;
5754 width += 9;
5755 } else {
5756 int skip;
5757 err = format_line(&wline, &width, &skip, line,
5758 view->x, view->ncols - 9, 9, 1);
5759 if (err) {
5760 free(line);
5761 return err;
5763 waddwstr(view->window, &wline[skip]);
5764 width += 9;
5765 free(wline);
5766 wline = NULL;
5769 if (width <= view->ncols - 1)
5770 waddch(view->window, '\n');
5771 if (++nprinted == 1)
5772 s->first_displayed_line = lineno;
5774 free(line);
5775 s->last_displayed_line = lineno;
5777 view_border(view);
5779 return NULL;
5782 static const struct got_error *
5783 blame_cb(void *arg, int nlines, int lineno,
5784 struct got_commit_object *commit, struct got_object_id *id)
5786 const struct got_error *err = NULL;
5787 struct tog_blame_cb_args *a = arg;
5788 struct tog_blame_line *line;
5789 int errcode;
5791 if (nlines != a->nlines ||
5792 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5793 return got_error(GOT_ERR_RANGE);
5795 errcode = pthread_mutex_lock(&tog_mutex);
5796 if (errcode)
5797 return got_error_set_errno(errcode, "pthread_mutex_lock");
5799 if (*a->quit) { /* user has quit the blame view */
5800 err = got_error(GOT_ERR_ITER_COMPLETED);
5801 goto done;
5804 if (lineno == -1)
5805 goto done; /* no change in this commit */
5807 line = &a->lines[lineno - 1];
5808 if (line->annotated)
5809 goto done;
5811 line->id = got_object_id_dup(id);
5812 if (line->id == NULL) {
5813 err = got_error_from_errno("got_object_id_dup");
5814 goto done;
5816 line->annotated = 1;
5817 done:
5818 errcode = pthread_mutex_unlock(&tog_mutex);
5819 if (errcode)
5820 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5821 return err;
5824 static void *
5825 blame_thread(void *arg)
5827 const struct got_error *err, *close_err;
5828 struct tog_blame_thread_args *ta = arg;
5829 struct tog_blame_cb_args *a = ta->cb_args;
5830 int errcode, fd1 = -1, fd2 = -1;
5831 FILE *f1 = NULL, *f2 = NULL;
5833 fd1 = got_opentempfd();
5834 if (fd1 == -1)
5835 return (void *)got_error_from_errno("got_opentempfd");
5837 fd2 = got_opentempfd();
5838 if (fd2 == -1) {
5839 err = got_error_from_errno("got_opentempfd");
5840 goto done;
5843 f1 = got_opentemp();
5844 if (f1 == NULL) {
5845 err = (void *)got_error_from_errno("got_opentemp");
5846 goto done;
5848 f2 = got_opentemp();
5849 if (f2 == NULL) {
5850 err = (void *)got_error_from_errno("got_opentemp");
5851 goto done;
5854 err = block_signals_used_by_main_thread();
5855 if (err)
5856 goto done;
5858 err = got_blame(ta->path, a->commit_id, ta->repo,
5859 tog_diff_algo, blame_cb, ta->cb_args,
5860 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5861 if (err && err->code == GOT_ERR_CANCELLED)
5862 err = NULL;
5864 errcode = pthread_mutex_lock(&tog_mutex);
5865 if (errcode) {
5866 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5867 goto done;
5870 close_err = got_repo_close(ta->repo);
5871 if (err == NULL)
5872 err = close_err;
5873 ta->repo = NULL;
5874 *ta->complete = 1;
5876 errcode = pthread_mutex_unlock(&tog_mutex);
5877 if (errcode && err == NULL)
5878 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5880 done:
5881 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5882 err = got_error_from_errno("close");
5883 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5884 err = got_error_from_errno("close");
5885 if (f1 && fclose(f1) == EOF && err == NULL)
5886 err = got_error_from_errno("fclose");
5887 if (f2 && fclose(f2) == EOF && err == NULL)
5888 err = got_error_from_errno("fclose");
5890 return (void *)err;
5893 static struct got_object_id *
5894 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5895 int first_displayed_line, int selected_line)
5897 struct tog_blame_line *line;
5899 if (nlines <= 0)
5900 return NULL;
5902 line = &lines[first_displayed_line - 1 + selected_line - 1];
5903 if (!line->annotated)
5904 return NULL;
5906 return line->id;
5909 static struct got_object_id *
5910 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5911 int lineno)
5913 struct tog_blame_line *line;
5915 if (nlines <= 0 || lineno >= nlines)
5916 return NULL;
5918 line = &lines[lineno - 1];
5919 if (!line->annotated)
5920 return NULL;
5922 return line->id;
5925 static const struct got_error *
5926 stop_blame(struct tog_blame *blame)
5928 const struct got_error *err = NULL;
5929 int i;
5931 if (blame->thread) {
5932 int errcode;
5933 errcode = pthread_mutex_unlock(&tog_mutex);
5934 if (errcode)
5935 return got_error_set_errno(errcode,
5936 "pthread_mutex_unlock");
5937 errcode = pthread_join(blame->thread, (void **)&err);
5938 if (errcode)
5939 return got_error_set_errno(errcode, "pthread_join");
5940 errcode = pthread_mutex_lock(&tog_mutex);
5941 if (errcode)
5942 return got_error_set_errno(errcode,
5943 "pthread_mutex_lock");
5944 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5945 err = NULL;
5946 blame->thread = 0; //NULL;
5948 if (blame->thread_args.repo) {
5949 const struct got_error *close_err;
5950 close_err = got_repo_close(blame->thread_args.repo);
5951 if (err == NULL)
5952 err = close_err;
5953 blame->thread_args.repo = NULL;
5955 if (blame->f) {
5956 if (fclose(blame->f) == EOF && err == NULL)
5957 err = got_error_from_errno("fclose");
5958 blame->f = NULL;
5960 if (blame->lines) {
5961 for (i = 0; i < blame->nlines; i++)
5962 free(blame->lines[i].id);
5963 free(blame->lines);
5964 blame->lines = NULL;
5966 free(blame->cb_args.commit_id);
5967 blame->cb_args.commit_id = NULL;
5968 if (blame->pack_fds) {
5969 const struct got_error *pack_err =
5970 got_repo_pack_fds_close(blame->pack_fds);
5971 if (err == NULL)
5972 err = pack_err;
5973 blame->pack_fds = NULL;
5975 return err;
5978 static const struct got_error *
5979 cancel_blame_view(void *arg)
5981 const struct got_error *err = NULL;
5982 int *done = arg;
5983 int errcode;
5985 errcode = pthread_mutex_lock(&tog_mutex);
5986 if (errcode)
5987 return got_error_set_errno(errcode,
5988 "pthread_mutex_unlock");
5990 if (*done)
5991 err = got_error(GOT_ERR_CANCELLED);
5993 errcode = pthread_mutex_unlock(&tog_mutex);
5994 if (errcode)
5995 return got_error_set_errno(errcode,
5996 "pthread_mutex_lock");
5998 return err;
6001 static const struct got_error *
6002 run_blame(struct tog_view *view)
6004 struct tog_blame_view_state *s = &view->state.blame;
6005 struct tog_blame *blame = &s->blame;
6006 const struct got_error *err = NULL;
6007 struct got_commit_object *commit = NULL;
6008 struct got_blob_object *blob = NULL;
6009 struct got_repository *thread_repo = NULL;
6010 struct got_object_id *obj_id = NULL;
6011 int obj_type, fd = -1;
6012 int *pack_fds = NULL;
6014 err = got_object_open_as_commit(&commit, s->repo,
6015 &s->blamed_commit->id);
6016 if (err)
6017 return err;
6019 fd = got_opentempfd();
6020 if (fd == -1) {
6021 err = got_error_from_errno("got_opentempfd");
6022 goto done;
6025 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6026 if (err)
6027 goto done;
6029 err = got_object_get_type(&obj_type, s->repo, obj_id);
6030 if (err)
6031 goto done;
6033 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6034 err = got_error(GOT_ERR_OBJ_TYPE);
6035 goto done;
6038 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6039 if (err)
6040 goto done;
6041 blame->f = got_opentemp();
6042 if (blame->f == NULL) {
6043 err = got_error_from_errno("got_opentemp");
6044 goto done;
6046 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6047 &blame->line_offsets, blame->f, blob);
6048 if (err)
6049 goto done;
6050 if (blame->nlines == 0) {
6051 s->blame_complete = 1;
6052 goto done;
6055 /* Don't include \n at EOF in the blame line count. */
6056 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6057 blame->nlines--;
6059 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6060 if (blame->lines == NULL) {
6061 err = got_error_from_errno("calloc");
6062 goto done;
6065 err = got_repo_pack_fds_open(&pack_fds);
6066 if (err)
6067 goto done;
6068 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6069 pack_fds);
6070 if (err)
6071 goto done;
6073 blame->pack_fds = pack_fds;
6074 blame->cb_args.view = view;
6075 blame->cb_args.lines = blame->lines;
6076 blame->cb_args.nlines = blame->nlines;
6077 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6078 if (blame->cb_args.commit_id == NULL) {
6079 err = got_error_from_errno("got_object_id_dup");
6080 goto done;
6082 blame->cb_args.quit = &s->done;
6084 blame->thread_args.path = s->path;
6085 blame->thread_args.repo = thread_repo;
6086 blame->thread_args.cb_args = &blame->cb_args;
6087 blame->thread_args.complete = &s->blame_complete;
6088 blame->thread_args.cancel_cb = cancel_blame_view;
6089 blame->thread_args.cancel_arg = &s->done;
6090 s->blame_complete = 0;
6092 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6093 s->first_displayed_line = 1;
6094 s->last_displayed_line = view->nlines;
6095 s->selected_line = 1;
6097 s->matched_line = 0;
6099 done:
6100 if (commit)
6101 got_object_commit_close(commit);
6102 if (fd != -1 && close(fd) == -1 && err == NULL)
6103 err = got_error_from_errno("close");
6104 if (blob)
6105 got_object_blob_close(blob);
6106 free(obj_id);
6107 if (err)
6108 stop_blame(blame);
6109 return err;
6112 static const struct got_error *
6113 open_blame_view(struct tog_view *view, char *path,
6114 struct got_object_id *commit_id, struct got_repository *repo)
6116 const struct got_error *err = NULL;
6117 struct tog_blame_view_state *s = &view->state.blame;
6119 STAILQ_INIT(&s->blamed_commits);
6121 s->path = strdup(path);
6122 if (s->path == NULL)
6123 return got_error_from_errno("strdup");
6125 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6126 if (err) {
6127 free(s->path);
6128 return err;
6131 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6132 s->first_displayed_line = 1;
6133 s->last_displayed_line = view->nlines;
6134 s->selected_line = 1;
6135 s->blame_complete = 0;
6136 s->repo = repo;
6137 s->commit_id = commit_id;
6138 memset(&s->blame, 0, sizeof(s->blame));
6140 STAILQ_INIT(&s->colors);
6141 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6142 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6143 get_color_value("TOG_COLOR_COMMIT"));
6144 if (err)
6145 return err;
6148 view->show = show_blame_view;
6149 view->input = input_blame_view;
6150 view->reset = reset_blame_view;
6151 view->close = close_blame_view;
6152 view->search_start = search_start_blame_view;
6153 view->search_setup = search_setup_blame_view;
6154 view->search_next = search_next_view_match;
6156 return run_blame(view);
6159 static const struct got_error *
6160 close_blame_view(struct tog_view *view)
6162 const struct got_error *err = NULL;
6163 struct tog_blame_view_state *s = &view->state.blame;
6165 if (s->blame.thread)
6166 err = stop_blame(&s->blame);
6168 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6169 struct got_object_qid *blamed_commit;
6170 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6171 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6172 got_object_qid_free(blamed_commit);
6175 free(s->path);
6176 free_colors(&s->colors);
6177 return err;
6180 static const struct got_error *
6181 search_start_blame_view(struct tog_view *view)
6183 struct tog_blame_view_state *s = &view->state.blame;
6185 s->matched_line = 0;
6186 return NULL;
6189 static void
6190 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6191 size_t *nlines, int **first, int **last, int **match, int **selected)
6193 struct tog_blame_view_state *s = &view->state.blame;
6195 *f = s->blame.f;
6196 *nlines = s->blame.nlines;
6197 *line_offsets = s->blame.line_offsets;
6198 *match = &s->matched_line;
6199 *first = &s->first_displayed_line;
6200 *last = &s->last_displayed_line;
6201 *selected = &s->selected_line;
6204 static const struct got_error *
6205 show_blame_view(struct tog_view *view)
6207 const struct got_error *err = NULL;
6208 struct tog_blame_view_state *s = &view->state.blame;
6209 int errcode;
6211 if (s->blame.thread == 0 && !s->blame_complete) {
6212 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6213 &s->blame.thread_args);
6214 if (errcode)
6215 return got_error_set_errno(errcode, "pthread_create");
6217 halfdelay(1); /* fast refresh while annotating */
6220 if (s->blame_complete)
6221 halfdelay(10); /* disable fast refresh */
6223 err = draw_blame(view);
6225 view_border(view);
6226 return err;
6229 static const struct got_error *
6230 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6231 struct got_repository *repo, struct got_object_id *id)
6233 struct tog_view *log_view;
6234 const struct got_error *err = NULL;
6236 *new_view = NULL;
6238 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6239 if (log_view == NULL)
6240 return got_error_from_errno("view_open");
6242 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6243 if (err)
6244 view_close(log_view);
6245 else
6246 *new_view = log_view;
6248 return err;
6251 static const struct got_error *
6252 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6254 const struct got_error *err = NULL, *thread_err = NULL;
6255 struct tog_view *diff_view;
6256 struct tog_blame_view_state *s = &view->state.blame;
6257 int eos, nscroll, begin_y = 0, begin_x = 0;
6259 eos = nscroll = view->nlines - 2;
6260 if (view_is_hsplit_top(view))
6261 --eos; /* border */
6263 switch (ch) {
6264 case '0':
6265 view->x = 0;
6266 break;
6267 case '$':
6268 view->x = MAX(view->maxx - view->ncols / 3, 0);
6269 view->count = 0;
6270 break;
6271 case KEY_RIGHT:
6272 case 'l':
6273 if (view->x + view->ncols / 3 < view->maxx)
6274 view->x += 2; /* move two columns right */
6275 else
6276 view->count = 0;
6277 break;
6278 case KEY_LEFT:
6279 case 'h':
6280 view->x -= MIN(view->x, 2); /* move two columns back */
6281 if (view->x <= 0)
6282 view->count = 0;
6283 break;
6284 case 'q':
6285 s->done = 1;
6286 break;
6287 case 'g':
6288 case KEY_HOME:
6289 s->selected_line = 1;
6290 s->first_displayed_line = 1;
6291 view->count = 0;
6292 break;
6293 case 'G':
6294 case KEY_END:
6295 if (s->blame.nlines < eos) {
6296 s->selected_line = s->blame.nlines;
6297 s->first_displayed_line = 1;
6298 } else {
6299 s->selected_line = eos;
6300 s->first_displayed_line = s->blame.nlines - (eos - 1);
6302 view->count = 0;
6303 break;
6304 case 'k':
6305 case KEY_UP:
6306 case CTRL('p'):
6307 if (s->selected_line > 1)
6308 s->selected_line--;
6309 else if (s->selected_line == 1 &&
6310 s->first_displayed_line > 1)
6311 s->first_displayed_line--;
6312 else
6313 view->count = 0;
6314 break;
6315 case CTRL('u'):
6316 case 'u':
6317 nscroll /= 2;
6318 /* FALL THROUGH */
6319 case KEY_PPAGE:
6320 case CTRL('b'):
6321 case 'b':
6322 if (s->first_displayed_line == 1) {
6323 if (view->count > 1)
6324 nscroll += nscroll;
6325 s->selected_line = MAX(1, s->selected_line - nscroll);
6326 view->count = 0;
6327 break;
6329 if (s->first_displayed_line > nscroll)
6330 s->first_displayed_line -= nscroll;
6331 else
6332 s->first_displayed_line = 1;
6333 break;
6334 case 'j':
6335 case KEY_DOWN:
6336 case CTRL('n'):
6337 if (s->selected_line < eos && s->first_displayed_line +
6338 s->selected_line <= s->blame.nlines)
6339 s->selected_line++;
6340 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6341 s->first_displayed_line++;
6342 else
6343 view->count = 0;
6344 break;
6345 case 'c':
6346 case 'p': {
6347 struct got_object_id *id = NULL;
6349 view->count = 0;
6350 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6351 s->first_displayed_line, s->selected_line);
6352 if (id == NULL)
6353 break;
6354 if (ch == 'p') {
6355 struct got_commit_object *commit, *pcommit;
6356 struct got_object_qid *pid;
6357 struct got_object_id *blob_id = NULL;
6358 int obj_type;
6359 err = got_object_open_as_commit(&commit,
6360 s->repo, id);
6361 if (err)
6362 break;
6363 pid = STAILQ_FIRST(
6364 got_object_commit_get_parent_ids(commit));
6365 if (pid == NULL) {
6366 got_object_commit_close(commit);
6367 break;
6369 /* Check if path history ends here. */
6370 err = got_object_open_as_commit(&pcommit,
6371 s->repo, &pid->id);
6372 if (err)
6373 break;
6374 err = got_object_id_by_path(&blob_id, s->repo,
6375 pcommit, s->path);
6376 got_object_commit_close(pcommit);
6377 if (err) {
6378 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6379 err = NULL;
6380 got_object_commit_close(commit);
6381 break;
6383 err = got_object_get_type(&obj_type, s->repo,
6384 blob_id);
6385 free(blob_id);
6386 /* Can't blame non-blob type objects. */
6387 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6388 got_object_commit_close(commit);
6389 break;
6391 err = got_object_qid_alloc(&s->blamed_commit,
6392 &pid->id);
6393 got_object_commit_close(commit);
6394 } else {
6395 if (got_object_id_cmp(id,
6396 &s->blamed_commit->id) == 0)
6397 break;
6398 err = got_object_qid_alloc(&s->blamed_commit,
6399 id);
6401 if (err)
6402 break;
6403 s->done = 1;
6404 thread_err = stop_blame(&s->blame);
6405 s->done = 0;
6406 if (thread_err)
6407 break;
6408 STAILQ_INSERT_HEAD(&s->blamed_commits,
6409 s->blamed_commit, entry);
6410 err = run_blame(view);
6411 if (err)
6412 break;
6413 break;
6415 case 'C': {
6416 struct got_object_qid *first;
6418 view->count = 0;
6419 first = STAILQ_FIRST(&s->blamed_commits);
6420 if (!got_object_id_cmp(&first->id, s->commit_id))
6421 break;
6422 s->done = 1;
6423 thread_err = stop_blame(&s->blame);
6424 s->done = 0;
6425 if (thread_err)
6426 break;
6427 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6428 got_object_qid_free(s->blamed_commit);
6429 s->blamed_commit =
6430 STAILQ_FIRST(&s->blamed_commits);
6431 err = run_blame(view);
6432 if (err)
6433 break;
6434 break;
6436 case 'L':
6437 view->count = 0;
6438 s->id_to_log = get_selected_commit_id(s->blame.lines,
6439 s->blame.nlines, s->first_displayed_line, s->selected_line);
6440 if (s->id_to_log)
6441 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6442 break;
6443 case KEY_ENTER:
6444 case '\r': {
6445 struct got_object_id *id = NULL;
6446 struct got_object_qid *pid;
6447 struct got_commit_object *commit = NULL;
6449 view->count = 0;
6450 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6451 s->first_displayed_line, s->selected_line);
6452 if (id == NULL)
6453 break;
6454 err = got_object_open_as_commit(&commit, s->repo, id);
6455 if (err)
6456 break;
6457 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6458 if (*new_view) {
6459 /* traversed from diff view, release diff resources */
6460 err = close_diff_view(*new_view);
6461 if (err)
6462 break;
6463 diff_view = *new_view;
6464 } else {
6465 if (view_is_parent_view(view))
6466 view_get_split(view, &begin_y, &begin_x);
6468 diff_view = view_open(0, 0, begin_y, begin_x,
6469 TOG_VIEW_DIFF);
6470 if (diff_view == NULL) {
6471 got_object_commit_close(commit);
6472 err = got_error_from_errno("view_open");
6473 break;
6476 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6477 id, NULL, NULL, 3, 0, 0, view, s->repo);
6478 got_object_commit_close(commit);
6479 if (err) {
6480 view_close(diff_view);
6481 break;
6483 s->last_diffed_line = s->first_displayed_line - 1 +
6484 s->selected_line;
6485 if (*new_view)
6486 break; /* still open from active diff view */
6487 if (view_is_parent_view(view) &&
6488 view->mode == TOG_VIEW_SPLIT_HRZN) {
6489 err = view_init_hsplit(view, begin_y);
6490 if (err)
6491 break;
6494 view->focussed = 0;
6495 diff_view->focussed = 1;
6496 diff_view->mode = view->mode;
6497 diff_view->nlines = view->lines - begin_y;
6498 if (view_is_parent_view(view)) {
6499 view_transfer_size(diff_view, view);
6500 err = view_close_child(view);
6501 if (err)
6502 break;
6503 err = view_set_child(view, diff_view);
6504 if (err)
6505 break;
6506 view->focus_child = 1;
6507 } else
6508 *new_view = diff_view;
6509 if (err)
6510 break;
6511 break;
6513 case CTRL('d'):
6514 case 'd':
6515 nscroll /= 2;
6516 /* FALL THROUGH */
6517 case KEY_NPAGE:
6518 case CTRL('f'):
6519 case 'f':
6520 case ' ':
6521 if (s->last_displayed_line >= s->blame.nlines &&
6522 s->selected_line >= MIN(s->blame.nlines,
6523 view->nlines - 2)) {
6524 view->count = 0;
6525 break;
6527 if (s->last_displayed_line >= s->blame.nlines &&
6528 s->selected_line < view->nlines - 2) {
6529 s->selected_line +=
6530 MIN(nscroll, s->last_displayed_line -
6531 s->first_displayed_line - s->selected_line + 1);
6533 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6534 s->first_displayed_line += nscroll;
6535 else
6536 s->first_displayed_line =
6537 s->blame.nlines - (view->nlines - 3);
6538 break;
6539 case KEY_RESIZE:
6540 if (s->selected_line > view->nlines - 2) {
6541 s->selected_line = MIN(s->blame.nlines,
6542 view->nlines - 2);
6544 break;
6545 default:
6546 view->count = 0;
6547 break;
6549 return thread_err ? thread_err : err;
6552 static const struct got_error *
6553 reset_blame_view(struct tog_view *view)
6555 const struct got_error *err;
6556 struct tog_blame_view_state *s = &view->state.blame;
6558 view->count = 0;
6559 s->done = 1;
6560 err = stop_blame(&s->blame);
6561 s->done = 0;
6562 if (err)
6563 return err;
6564 return run_blame(view);
6567 static const struct got_error *
6568 cmd_blame(int argc, char *argv[])
6570 const struct got_error *error;
6571 struct got_repository *repo = NULL;
6572 struct got_worktree *worktree = NULL;
6573 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6574 char *link_target = NULL;
6575 struct got_object_id *commit_id = NULL;
6576 struct got_commit_object *commit = NULL;
6577 char *commit_id_str = NULL;
6578 int ch;
6579 struct tog_view *view;
6580 int *pack_fds = NULL;
6582 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6583 switch (ch) {
6584 case 'c':
6585 commit_id_str = optarg;
6586 break;
6587 case 'r':
6588 repo_path = realpath(optarg, NULL);
6589 if (repo_path == NULL)
6590 return got_error_from_errno2("realpath",
6591 optarg);
6592 break;
6593 default:
6594 usage_blame();
6595 /* NOTREACHED */
6599 argc -= optind;
6600 argv += optind;
6602 if (argc != 1)
6603 usage_blame();
6605 error = got_repo_pack_fds_open(&pack_fds);
6606 if (error != NULL)
6607 goto done;
6609 if (repo_path == NULL) {
6610 cwd = getcwd(NULL, 0);
6611 if (cwd == NULL)
6612 return got_error_from_errno("getcwd");
6613 error = got_worktree_open(&worktree, cwd);
6614 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6615 goto done;
6616 if (worktree)
6617 repo_path =
6618 strdup(got_worktree_get_repo_path(worktree));
6619 else
6620 repo_path = strdup(cwd);
6621 if (repo_path == NULL) {
6622 error = got_error_from_errno("strdup");
6623 goto done;
6627 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6628 if (error != NULL)
6629 goto done;
6631 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6632 worktree);
6633 if (error)
6634 goto done;
6636 init_curses();
6638 error = apply_unveil(got_repo_get_path(repo), NULL);
6639 if (error)
6640 goto done;
6642 error = tog_load_refs(repo, 0);
6643 if (error)
6644 goto done;
6646 if (commit_id_str == NULL) {
6647 struct got_reference *head_ref;
6648 error = got_ref_open(&head_ref, repo, worktree ?
6649 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6650 if (error != NULL)
6651 goto done;
6652 error = got_ref_resolve(&commit_id, repo, head_ref);
6653 got_ref_close(head_ref);
6654 } else {
6655 error = got_repo_match_object_id(&commit_id, NULL,
6656 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6658 if (error != NULL)
6659 goto done;
6661 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6662 if (view == NULL) {
6663 error = got_error_from_errno("view_open");
6664 goto done;
6667 error = got_object_open_as_commit(&commit, repo, commit_id);
6668 if (error)
6669 goto done;
6671 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6672 commit, repo);
6673 if (error)
6674 goto done;
6676 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6677 commit_id, repo);
6678 if (error)
6679 goto done;
6680 if (worktree) {
6681 /* Release work tree lock. */
6682 got_worktree_close(worktree);
6683 worktree = NULL;
6685 error = view_loop(view);
6686 done:
6687 free(repo_path);
6688 free(in_repo_path);
6689 free(link_target);
6690 free(cwd);
6691 free(commit_id);
6692 if (commit)
6693 got_object_commit_close(commit);
6694 if (worktree)
6695 got_worktree_close(worktree);
6696 if (repo) {
6697 const struct got_error *close_err = got_repo_close(repo);
6698 if (error == NULL)
6699 error = close_err;
6701 if (pack_fds) {
6702 const struct got_error *pack_err =
6703 got_repo_pack_fds_close(pack_fds);
6704 if (error == NULL)
6705 error = pack_err;
6707 tog_free_refs();
6708 return error;
6711 static const struct got_error *
6712 draw_tree_entries(struct tog_view *view, const char *parent_path)
6714 struct tog_tree_view_state *s = &view->state.tree;
6715 const struct got_error *err = NULL;
6716 struct got_tree_entry *te;
6717 wchar_t *wline;
6718 char *index = NULL;
6719 struct tog_color *tc;
6720 int width, n, nentries, i = 1;
6721 int limit = view->nlines;
6723 s->ndisplayed = 0;
6724 if (view_is_hsplit_top(view))
6725 --limit; /* border */
6727 werase(view->window);
6729 if (limit == 0)
6730 return NULL;
6732 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6733 0, 0);
6734 if (err)
6735 return err;
6736 if (view_needs_focus_indication(view))
6737 wstandout(view->window);
6738 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6739 if (tc)
6740 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6741 waddwstr(view->window, wline);
6742 free(wline);
6743 wline = NULL;
6744 while (width++ < view->ncols)
6745 waddch(view->window, ' ');
6746 if (tc)
6747 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6748 if (view_needs_focus_indication(view))
6749 wstandend(view->window);
6750 if (--limit <= 0)
6751 return NULL;
6753 i += s->selected;
6754 if (s->first_displayed_entry) {
6755 i += got_tree_entry_get_index(s->first_displayed_entry);
6756 if (s->tree != s->root)
6757 ++i; /* account for ".." entry */
6759 nentries = got_object_tree_get_nentries(s->tree);
6760 if (asprintf(&index, "[%d/%d] %s",
6761 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6762 return got_error_from_errno("asprintf");
6763 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6764 free(index);
6765 if (err)
6766 return err;
6767 waddwstr(view->window, wline);
6768 free(wline);
6769 wline = NULL;
6770 if (width < view->ncols - 1)
6771 waddch(view->window, '\n');
6772 if (--limit <= 0)
6773 return NULL;
6774 waddch(view->window, '\n');
6775 if (--limit <= 0)
6776 return NULL;
6778 if (s->first_displayed_entry == NULL) {
6779 te = got_object_tree_get_first_entry(s->tree);
6780 if (s->selected == 0) {
6781 if (view->focussed)
6782 wstandout(view->window);
6783 s->selected_entry = NULL;
6785 waddstr(view->window, " ..\n"); /* parent directory */
6786 if (s->selected == 0 && view->focussed)
6787 wstandend(view->window);
6788 s->ndisplayed++;
6789 if (--limit <= 0)
6790 return NULL;
6791 n = 1;
6792 } else {
6793 n = 0;
6794 te = s->first_displayed_entry;
6797 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6798 char *line = NULL, *id_str = NULL, *link_target = NULL;
6799 const char *modestr = "";
6800 mode_t mode;
6802 te = got_object_tree_get_entry(s->tree, i);
6803 mode = got_tree_entry_get_mode(te);
6805 if (s->show_ids) {
6806 err = got_object_id_str(&id_str,
6807 got_tree_entry_get_id(te));
6808 if (err)
6809 return got_error_from_errno(
6810 "got_object_id_str");
6812 if (got_object_tree_entry_is_submodule(te))
6813 modestr = "$";
6814 else if (S_ISLNK(mode)) {
6815 int i;
6817 err = got_tree_entry_get_symlink_target(&link_target,
6818 te, s->repo);
6819 if (err) {
6820 free(id_str);
6821 return err;
6823 for (i = 0; i < strlen(link_target); i++) {
6824 if (!isprint((unsigned char)link_target[i]))
6825 link_target[i] = '?';
6827 modestr = "@";
6829 else if (S_ISDIR(mode))
6830 modestr = "/";
6831 else if (mode & S_IXUSR)
6832 modestr = "*";
6833 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6834 got_tree_entry_get_name(te), modestr,
6835 link_target ? " -> ": "",
6836 link_target ? link_target : "") == -1) {
6837 free(id_str);
6838 free(link_target);
6839 return got_error_from_errno("asprintf");
6841 free(id_str);
6842 free(link_target);
6843 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6844 0, 0);
6845 if (err) {
6846 free(line);
6847 break;
6849 if (n == s->selected) {
6850 if (view->focussed)
6851 wstandout(view->window);
6852 s->selected_entry = te;
6854 tc = match_color(&s->colors, line);
6855 if (tc)
6856 wattr_on(view->window,
6857 COLOR_PAIR(tc->colorpair), NULL);
6858 waddwstr(view->window, wline);
6859 if (tc)
6860 wattr_off(view->window,
6861 COLOR_PAIR(tc->colorpair), NULL);
6862 if (width < view->ncols - 1)
6863 waddch(view->window, '\n');
6864 if (n == s->selected && view->focussed)
6865 wstandend(view->window);
6866 free(line);
6867 free(wline);
6868 wline = NULL;
6869 n++;
6870 s->ndisplayed++;
6871 s->last_displayed_entry = te;
6872 if (--limit <= 0)
6873 break;
6876 return err;
6879 static void
6880 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6882 struct got_tree_entry *te;
6883 int isroot = s->tree == s->root;
6884 int i = 0;
6886 if (s->first_displayed_entry == NULL)
6887 return;
6889 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6890 while (i++ < maxscroll) {
6891 if (te == NULL) {
6892 if (!isroot)
6893 s->first_displayed_entry = NULL;
6894 break;
6896 s->first_displayed_entry = te;
6897 te = got_tree_entry_get_prev(s->tree, te);
6901 static const struct got_error *
6902 tree_scroll_down(struct tog_view *view, int maxscroll)
6904 struct tog_tree_view_state *s = &view->state.tree;
6905 struct got_tree_entry *next, *last;
6906 int n = 0;
6908 if (s->first_displayed_entry)
6909 next = got_tree_entry_get_next(s->tree,
6910 s->first_displayed_entry);
6911 else
6912 next = got_object_tree_get_first_entry(s->tree);
6914 last = s->last_displayed_entry;
6915 while (next && n++ < maxscroll) {
6916 if (last) {
6917 s->last_displayed_entry = last;
6918 last = got_tree_entry_get_next(s->tree, last);
6920 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6921 s->first_displayed_entry = next;
6922 next = got_tree_entry_get_next(s->tree, next);
6926 return NULL;
6929 static const struct got_error *
6930 tree_entry_path(char **path, struct tog_parent_trees *parents,
6931 struct got_tree_entry *te)
6933 const struct got_error *err = NULL;
6934 struct tog_parent_tree *pt;
6935 size_t len = 2; /* for leading slash and NUL */
6937 TAILQ_FOREACH(pt, parents, entry)
6938 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6939 + 1 /* slash */;
6940 if (te)
6941 len += strlen(got_tree_entry_get_name(te));
6943 *path = calloc(1, len);
6944 if (path == NULL)
6945 return got_error_from_errno("calloc");
6947 (*path)[0] = '/';
6948 pt = TAILQ_LAST(parents, tog_parent_trees);
6949 while (pt) {
6950 const char *name = got_tree_entry_get_name(pt->selected_entry);
6951 if (strlcat(*path, name, len) >= len) {
6952 err = got_error(GOT_ERR_NO_SPACE);
6953 goto done;
6955 if (strlcat(*path, "/", len) >= len) {
6956 err = got_error(GOT_ERR_NO_SPACE);
6957 goto done;
6959 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6961 if (te) {
6962 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6963 err = got_error(GOT_ERR_NO_SPACE);
6964 goto done;
6967 done:
6968 if (err) {
6969 free(*path);
6970 *path = NULL;
6972 return err;
6975 static const struct got_error *
6976 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6977 struct got_tree_entry *te, struct tog_parent_trees *parents,
6978 struct got_object_id *commit_id, struct got_repository *repo)
6980 const struct got_error *err = NULL;
6981 char *path;
6982 struct tog_view *blame_view;
6984 *new_view = NULL;
6986 err = tree_entry_path(&path, parents, te);
6987 if (err)
6988 return err;
6990 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6991 if (blame_view == NULL) {
6992 err = got_error_from_errno("view_open");
6993 goto done;
6996 err = open_blame_view(blame_view, path, commit_id, repo);
6997 if (err) {
6998 if (err->code == GOT_ERR_CANCELLED)
6999 err = NULL;
7000 view_close(blame_view);
7001 } else
7002 *new_view = blame_view;
7003 done:
7004 free(path);
7005 return err;
7008 static const struct got_error *
7009 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7010 struct tog_tree_view_state *s)
7012 struct tog_view *log_view;
7013 const struct got_error *err = NULL;
7014 char *path;
7016 *new_view = NULL;
7018 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7019 if (log_view == NULL)
7020 return got_error_from_errno("view_open");
7022 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7023 if (err)
7024 return err;
7026 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7027 path, 0);
7028 if (err)
7029 view_close(log_view);
7030 else
7031 *new_view = log_view;
7032 free(path);
7033 return err;
7036 static const struct got_error *
7037 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7038 const char *head_ref_name, struct got_repository *repo)
7040 const struct got_error *err = NULL;
7041 char *commit_id_str = NULL;
7042 struct tog_tree_view_state *s = &view->state.tree;
7043 struct got_commit_object *commit = NULL;
7045 TAILQ_INIT(&s->parents);
7046 STAILQ_INIT(&s->colors);
7048 s->commit_id = got_object_id_dup(commit_id);
7049 if (s->commit_id == NULL)
7050 return got_error_from_errno("got_object_id_dup");
7052 err = got_object_open_as_commit(&commit, repo, commit_id);
7053 if (err)
7054 goto done;
7057 * The root is opened here and will be closed when the view is closed.
7058 * Any visited subtrees and their path-wise parents are opened and
7059 * closed on demand.
7061 err = got_object_open_as_tree(&s->root, repo,
7062 got_object_commit_get_tree_id(commit));
7063 if (err)
7064 goto done;
7065 s->tree = s->root;
7067 err = got_object_id_str(&commit_id_str, commit_id);
7068 if (err != NULL)
7069 goto done;
7071 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7072 err = got_error_from_errno("asprintf");
7073 goto done;
7076 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7077 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7078 if (head_ref_name) {
7079 s->head_ref_name = strdup(head_ref_name);
7080 if (s->head_ref_name == NULL) {
7081 err = got_error_from_errno("strdup");
7082 goto done;
7085 s->repo = repo;
7087 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7088 err = add_color(&s->colors, "\\$$",
7089 TOG_COLOR_TREE_SUBMODULE,
7090 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7091 if (err)
7092 goto done;
7093 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7094 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7095 if (err)
7096 goto done;
7097 err = add_color(&s->colors, "/$",
7098 TOG_COLOR_TREE_DIRECTORY,
7099 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7100 if (err)
7101 goto done;
7103 err = add_color(&s->colors, "\\*$",
7104 TOG_COLOR_TREE_EXECUTABLE,
7105 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7106 if (err)
7107 goto done;
7109 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7110 get_color_value("TOG_COLOR_COMMIT"));
7111 if (err)
7112 goto done;
7115 view->show = show_tree_view;
7116 view->input = input_tree_view;
7117 view->close = close_tree_view;
7118 view->search_start = search_start_tree_view;
7119 view->search_next = search_next_tree_view;
7120 done:
7121 free(commit_id_str);
7122 if (commit)
7123 got_object_commit_close(commit);
7124 if (err)
7125 close_tree_view(view);
7126 return err;
7129 static const struct got_error *
7130 close_tree_view(struct tog_view *view)
7132 struct tog_tree_view_state *s = &view->state.tree;
7134 free_colors(&s->colors);
7135 free(s->tree_label);
7136 s->tree_label = NULL;
7137 free(s->commit_id);
7138 s->commit_id = NULL;
7139 free(s->head_ref_name);
7140 s->head_ref_name = NULL;
7141 while (!TAILQ_EMPTY(&s->parents)) {
7142 struct tog_parent_tree *parent;
7143 parent = TAILQ_FIRST(&s->parents);
7144 TAILQ_REMOVE(&s->parents, parent, entry);
7145 if (parent->tree != s->root)
7146 got_object_tree_close(parent->tree);
7147 free(parent);
7150 if (s->tree != NULL && s->tree != s->root)
7151 got_object_tree_close(s->tree);
7152 if (s->root)
7153 got_object_tree_close(s->root);
7154 return NULL;
7157 static const struct got_error *
7158 search_start_tree_view(struct tog_view *view)
7160 struct tog_tree_view_state *s = &view->state.tree;
7162 s->matched_entry = NULL;
7163 return NULL;
7166 static int
7167 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7169 regmatch_t regmatch;
7171 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7172 0) == 0;
7175 static const struct got_error *
7176 search_next_tree_view(struct tog_view *view)
7178 struct tog_tree_view_state *s = &view->state.tree;
7179 struct got_tree_entry *te = NULL;
7181 if (!view->searching) {
7182 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7183 return NULL;
7186 if (s->matched_entry) {
7187 if (view->searching == TOG_SEARCH_FORWARD) {
7188 if (s->selected_entry)
7189 te = got_tree_entry_get_next(s->tree,
7190 s->selected_entry);
7191 else
7192 te = got_object_tree_get_first_entry(s->tree);
7193 } else {
7194 if (s->selected_entry == NULL)
7195 te = got_object_tree_get_last_entry(s->tree);
7196 else
7197 te = got_tree_entry_get_prev(s->tree,
7198 s->selected_entry);
7200 } else {
7201 if (s->selected_entry)
7202 te = s->selected_entry;
7203 else if (view->searching == TOG_SEARCH_FORWARD)
7204 te = got_object_tree_get_first_entry(s->tree);
7205 else
7206 te = got_object_tree_get_last_entry(s->tree);
7209 while (1) {
7210 if (te == NULL) {
7211 if (s->matched_entry == NULL) {
7212 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7213 return NULL;
7215 if (view->searching == TOG_SEARCH_FORWARD)
7216 te = got_object_tree_get_first_entry(s->tree);
7217 else
7218 te = got_object_tree_get_last_entry(s->tree);
7221 if (match_tree_entry(te, &view->regex)) {
7222 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7223 s->matched_entry = te;
7224 break;
7227 if (view->searching == TOG_SEARCH_FORWARD)
7228 te = got_tree_entry_get_next(s->tree, te);
7229 else
7230 te = got_tree_entry_get_prev(s->tree, te);
7233 if (s->matched_entry) {
7234 s->first_displayed_entry = s->matched_entry;
7235 s->selected = 0;
7238 return NULL;
7241 static const struct got_error *
7242 show_tree_view(struct tog_view *view)
7244 const struct got_error *err = NULL;
7245 struct tog_tree_view_state *s = &view->state.tree;
7246 char *parent_path;
7248 err = tree_entry_path(&parent_path, &s->parents, NULL);
7249 if (err)
7250 return err;
7252 err = draw_tree_entries(view, parent_path);
7253 free(parent_path);
7255 view_border(view);
7256 return err;
7259 static const struct got_error *
7260 tree_goto_line(struct tog_view *view, int nlines)
7262 const struct got_error *err = NULL;
7263 struct tog_tree_view_state *s = &view->state.tree;
7264 struct got_tree_entry **fte, **lte, **ste;
7265 int g, last, first = 1, i = 1;
7266 int root = s->tree == s->root;
7267 int off = root ? 1 : 2;
7269 g = view->gline;
7270 view->gline = 0;
7272 if (g == 0)
7273 g = 1;
7274 else if (g > got_object_tree_get_nentries(s->tree))
7275 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7277 fte = &s->first_displayed_entry;
7278 lte = &s->last_displayed_entry;
7279 ste = &s->selected_entry;
7281 if (*fte != NULL) {
7282 first = got_tree_entry_get_index(*fte);
7283 first += off; /* account for ".." */
7285 last = got_tree_entry_get_index(*lte);
7286 last += off;
7288 if (g >= first && g <= last && g - first < nlines) {
7289 s->selected = g - first;
7290 return NULL; /* gline is on the current page */
7293 if (*ste != NULL) {
7294 i = got_tree_entry_get_index(*ste);
7295 i += off;
7298 if (i < g) {
7299 err = tree_scroll_down(view, g - i);
7300 if (err)
7301 return err;
7302 if (got_tree_entry_get_index(*lte) >=
7303 got_object_tree_get_nentries(s->tree) - 1 &&
7304 first + s->selected < g &&
7305 s->selected < s->ndisplayed - 1) {
7306 first = got_tree_entry_get_index(*fte);
7307 first += off;
7308 s->selected = g - first;
7310 } else if (i > g)
7311 tree_scroll_up(s, i - g);
7313 if (g < nlines &&
7314 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7315 s->selected = g - 1;
7317 return NULL;
7320 static const struct got_error *
7321 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7323 const struct got_error *err = NULL;
7324 struct tog_tree_view_state *s = &view->state.tree;
7325 struct got_tree_entry *te;
7326 int n, nscroll = view->nlines - 3;
7328 if (view->gline)
7329 return tree_goto_line(view, nscroll);
7331 switch (ch) {
7332 case 'i':
7333 s->show_ids = !s->show_ids;
7334 view->count = 0;
7335 break;
7336 case 'L':
7337 view->count = 0;
7338 if (!s->selected_entry)
7339 break;
7340 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7341 break;
7342 case 'R':
7343 view->count = 0;
7344 err = view_request_new(new_view, view, TOG_VIEW_REF);
7345 break;
7346 case 'g':
7347 case '=':
7348 case KEY_HOME:
7349 s->selected = 0;
7350 view->count = 0;
7351 if (s->tree == s->root)
7352 s->first_displayed_entry =
7353 got_object_tree_get_first_entry(s->tree);
7354 else
7355 s->first_displayed_entry = NULL;
7356 break;
7357 case 'G':
7358 case '*':
7359 case KEY_END: {
7360 int eos = view->nlines - 3;
7362 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7363 --eos; /* border */
7364 s->selected = 0;
7365 view->count = 0;
7366 te = got_object_tree_get_last_entry(s->tree);
7367 for (n = 0; n < eos; n++) {
7368 if (te == NULL) {
7369 if (s->tree != s->root) {
7370 s->first_displayed_entry = NULL;
7371 n++;
7373 break;
7375 s->first_displayed_entry = te;
7376 te = got_tree_entry_get_prev(s->tree, te);
7378 if (n > 0)
7379 s->selected = n - 1;
7380 break;
7382 case 'k':
7383 case KEY_UP:
7384 case CTRL('p'):
7385 if (s->selected > 0) {
7386 s->selected--;
7387 break;
7389 tree_scroll_up(s, 1);
7390 if (s->selected_entry == NULL ||
7391 (s->tree == s->root && s->selected_entry ==
7392 got_object_tree_get_first_entry(s->tree)))
7393 view->count = 0;
7394 break;
7395 case CTRL('u'):
7396 case 'u':
7397 nscroll /= 2;
7398 /* FALL THROUGH */
7399 case KEY_PPAGE:
7400 case CTRL('b'):
7401 case 'b':
7402 if (s->tree == s->root) {
7403 if (got_object_tree_get_first_entry(s->tree) ==
7404 s->first_displayed_entry)
7405 s->selected -= MIN(s->selected, nscroll);
7406 } else {
7407 if (s->first_displayed_entry == NULL)
7408 s->selected -= MIN(s->selected, nscroll);
7410 tree_scroll_up(s, MAX(0, nscroll));
7411 if (s->selected_entry == NULL ||
7412 (s->tree == s->root && s->selected_entry ==
7413 got_object_tree_get_first_entry(s->tree)))
7414 view->count = 0;
7415 break;
7416 case 'j':
7417 case KEY_DOWN:
7418 case CTRL('n'):
7419 if (s->selected < s->ndisplayed - 1) {
7420 s->selected++;
7421 break;
7423 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7424 == NULL) {
7425 /* can't scroll any further */
7426 view->count = 0;
7427 break;
7429 tree_scroll_down(view, 1);
7430 break;
7431 case CTRL('d'):
7432 case 'd':
7433 nscroll /= 2;
7434 /* FALL THROUGH */
7435 case KEY_NPAGE:
7436 case CTRL('f'):
7437 case 'f':
7438 case ' ':
7439 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7440 == NULL) {
7441 /* can't scroll any further; move cursor down */
7442 if (s->selected < s->ndisplayed - 1)
7443 s->selected += MIN(nscroll,
7444 s->ndisplayed - s->selected - 1);
7445 else
7446 view->count = 0;
7447 break;
7449 tree_scroll_down(view, nscroll);
7450 break;
7451 case KEY_ENTER:
7452 case '\r':
7453 case KEY_BACKSPACE:
7454 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7455 struct tog_parent_tree *parent;
7456 /* user selected '..' */
7457 if (s->tree == s->root) {
7458 view->count = 0;
7459 break;
7461 parent = TAILQ_FIRST(&s->parents);
7462 TAILQ_REMOVE(&s->parents, parent,
7463 entry);
7464 got_object_tree_close(s->tree);
7465 s->tree = parent->tree;
7466 s->first_displayed_entry =
7467 parent->first_displayed_entry;
7468 s->selected_entry =
7469 parent->selected_entry;
7470 s->selected = parent->selected;
7471 if (s->selected > view->nlines - 3) {
7472 err = offset_selection_down(view);
7473 if (err)
7474 break;
7476 free(parent);
7477 } else if (S_ISDIR(got_tree_entry_get_mode(
7478 s->selected_entry))) {
7479 struct got_tree_object *subtree;
7480 view->count = 0;
7481 err = got_object_open_as_tree(&subtree, s->repo,
7482 got_tree_entry_get_id(s->selected_entry));
7483 if (err)
7484 break;
7485 err = tree_view_visit_subtree(s, subtree);
7486 if (err) {
7487 got_object_tree_close(subtree);
7488 break;
7490 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7491 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7492 break;
7493 case KEY_RESIZE:
7494 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7495 s->selected = view->nlines - 4;
7496 view->count = 0;
7497 break;
7498 default:
7499 view->count = 0;
7500 break;
7503 return err;
7506 __dead static void
7507 usage_tree(void)
7509 endwin();
7510 fprintf(stderr,
7511 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7512 getprogname());
7513 exit(1);
7516 static const struct got_error *
7517 cmd_tree(int argc, char *argv[])
7519 const struct got_error *error;
7520 struct got_repository *repo = NULL;
7521 struct got_worktree *worktree = NULL;
7522 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7523 struct got_object_id *commit_id = NULL;
7524 struct got_commit_object *commit = NULL;
7525 const char *commit_id_arg = NULL;
7526 char *label = NULL;
7527 struct got_reference *ref = NULL;
7528 const char *head_ref_name = NULL;
7529 int ch;
7530 struct tog_view *view;
7531 int *pack_fds = NULL;
7533 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7534 switch (ch) {
7535 case 'c':
7536 commit_id_arg = optarg;
7537 break;
7538 case 'r':
7539 repo_path = realpath(optarg, NULL);
7540 if (repo_path == NULL)
7541 return got_error_from_errno2("realpath",
7542 optarg);
7543 break;
7544 default:
7545 usage_tree();
7546 /* NOTREACHED */
7550 argc -= optind;
7551 argv += optind;
7553 if (argc > 1)
7554 usage_tree();
7556 error = got_repo_pack_fds_open(&pack_fds);
7557 if (error != NULL)
7558 goto done;
7560 if (repo_path == NULL) {
7561 cwd = getcwd(NULL, 0);
7562 if (cwd == NULL)
7563 return got_error_from_errno("getcwd");
7564 error = got_worktree_open(&worktree, cwd);
7565 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7566 goto done;
7567 if (worktree)
7568 repo_path =
7569 strdup(got_worktree_get_repo_path(worktree));
7570 else
7571 repo_path = strdup(cwd);
7572 if (repo_path == NULL) {
7573 error = got_error_from_errno("strdup");
7574 goto done;
7578 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7579 if (error != NULL)
7580 goto done;
7582 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7583 repo, worktree);
7584 if (error)
7585 goto done;
7587 init_curses();
7589 error = apply_unveil(got_repo_get_path(repo), NULL);
7590 if (error)
7591 goto done;
7593 error = tog_load_refs(repo, 0);
7594 if (error)
7595 goto done;
7597 if (commit_id_arg == NULL) {
7598 error = got_repo_match_object_id(&commit_id, &label,
7599 worktree ? got_worktree_get_head_ref_name(worktree) :
7600 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7601 if (error)
7602 goto done;
7603 head_ref_name = label;
7604 } else {
7605 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7606 if (error == NULL)
7607 head_ref_name = got_ref_get_name(ref);
7608 else if (error->code != GOT_ERR_NOT_REF)
7609 goto done;
7610 error = got_repo_match_object_id(&commit_id, NULL,
7611 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7612 if (error)
7613 goto done;
7616 error = got_object_open_as_commit(&commit, repo, commit_id);
7617 if (error)
7618 goto done;
7620 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7621 if (view == NULL) {
7622 error = got_error_from_errno("view_open");
7623 goto done;
7625 error = open_tree_view(view, commit_id, head_ref_name, repo);
7626 if (error)
7627 goto done;
7628 if (!got_path_is_root_dir(in_repo_path)) {
7629 error = tree_view_walk_path(&view->state.tree, commit,
7630 in_repo_path);
7631 if (error)
7632 goto done;
7635 if (worktree) {
7636 /* Release work tree lock. */
7637 got_worktree_close(worktree);
7638 worktree = NULL;
7640 error = view_loop(view);
7641 done:
7642 free(repo_path);
7643 free(cwd);
7644 free(commit_id);
7645 free(label);
7646 if (ref)
7647 got_ref_close(ref);
7648 if (repo) {
7649 const struct got_error *close_err = got_repo_close(repo);
7650 if (error == NULL)
7651 error = close_err;
7653 if (pack_fds) {
7654 const struct got_error *pack_err =
7655 got_repo_pack_fds_close(pack_fds);
7656 if (error == NULL)
7657 error = pack_err;
7659 tog_free_refs();
7660 return error;
7663 static const struct got_error *
7664 ref_view_load_refs(struct tog_ref_view_state *s)
7666 struct got_reflist_entry *sre;
7667 struct tog_reflist_entry *re;
7669 s->nrefs = 0;
7670 TAILQ_FOREACH(sre, &tog_refs, entry) {
7671 if (strncmp(got_ref_get_name(sre->ref),
7672 "refs/got/", 9) == 0 &&
7673 strncmp(got_ref_get_name(sre->ref),
7674 "refs/got/backup/", 16) != 0)
7675 continue;
7677 re = malloc(sizeof(*re));
7678 if (re == NULL)
7679 return got_error_from_errno("malloc");
7681 re->ref = got_ref_dup(sre->ref);
7682 if (re->ref == NULL)
7683 return got_error_from_errno("got_ref_dup");
7684 re->idx = s->nrefs++;
7685 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7688 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7689 return NULL;
7692 static void
7693 ref_view_free_refs(struct tog_ref_view_state *s)
7695 struct tog_reflist_entry *re;
7697 while (!TAILQ_EMPTY(&s->refs)) {
7698 re = TAILQ_FIRST(&s->refs);
7699 TAILQ_REMOVE(&s->refs, re, entry);
7700 got_ref_close(re->ref);
7701 free(re);
7705 static const struct got_error *
7706 open_ref_view(struct tog_view *view, struct got_repository *repo)
7708 const struct got_error *err = NULL;
7709 struct tog_ref_view_state *s = &view->state.ref;
7711 s->selected_entry = 0;
7712 s->repo = repo;
7714 TAILQ_INIT(&s->refs);
7715 STAILQ_INIT(&s->colors);
7717 err = ref_view_load_refs(s);
7718 if (err)
7719 return err;
7721 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7722 err = add_color(&s->colors, "^refs/heads/",
7723 TOG_COLOR_REFS_HEADS,
7724 get_color_value("TOG_COLOR_REFS_HEADS"));
7725 if (err)
7726 goto done;
7728 err = add_color(&s->colors, "^refs/tags/",
7729 TOG_COLOR_REFS_TAGS,
7730 get_color_value("TOG_COLOR_REFS_TAGS"));
7731 if (err)
7732 goto done;
7734 err = add_color(&s->colors, "^refs/remotes/",
7735 TOG_COLOR_REFS_REMOTES,
7736 get_color_value("TOG_COLOR_REFS_REMOTES"));
7737 if (err)
7738 goto done;
7740 err = add_color(&s->colors, "^refs/got/backup/",
7741 TOG_COLOR_REFS_BACKUP,
7742 get_color_value("TOG_COLOR_REFS_BACKUP"));
7743 if (err)
7744 goto done;
7747 view->show = show_ref_view;
7748 view->input = input_ref_view;
7749 view->close = close_ref_view;
7750 view->search_start = search_start_ref_view;
7751 view->search_next = search_next_ref_view;
7752 done:
7753 if (err)
7754 free_colors(&s->colors);
7755 return err;
7758 static const struct got_error *
7759 close_ref_view(struct tog_view *view)
7761 struct tog_ref_view_state *s = &view->state.ref;
7763 ref_view_free_refs(s);
7764 free_colors(&s->colors);
7766 return NULL;
7769 static const struct got_error *
7770 resolve_reflist_entry(struct got_object_id **commit_id,
7771 struct tog_reflist_entry *re, struct got_repository *repo)
7773 const struct got_error *err = NULL;
7774 struct got_object_id *obj_id;
7775 struct got_tag_object *tag = NULL;
7776 int obj_type;
7778 *commit_id = NULL;
7780 err = got_ref_resolve(&obj_id, repo, re->ref);
7781 if (err)
7782 return err;
7784 err = got_object_get_type(&obj_type, repo, obj_id);
7785 if (err)
7786 goto done;
7788 switch (obj_type) {
7789 case GOT_OBJ_TYPE_COMMIT:
7790 *commit_id = obj_id;
7791 break;
7792 case GOT_OBJ_TYPE_TAG:
7793 err = got_object_open_as_tag(&tag, repo, obj_id);
7794 if (err)
7795 goto done;
7796 free(obj_id);
7797 err = got_object_get_type(&obj_type, repo,
7798 got_object_tag_get_object_id(tag));
7799 if (err)
7800 goto done;
7801 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7802 err = got_error(GOT_ERR_OBJ_TYPE);
7803 goto done;
7805 *commit_id = got_object_id_dup(
7806 got_object_tag_get_object_id(tag));
7807 if (*commit_id == NULL) {
7808 err = got_error_from_errno("got_object_id_dup");
7809 goto done;
7811 break;
7812 default:
7813 err = got_error(GOT_ERR_OBJ_TYPE);
7814 break;
7817 done:
7818 if (tag)
7819 got_object_tag_close(tag);
7820 if (err) {
7821 free(*commit_id);
7822 *commit_id = NULL;
7824 return err;
7827 static const struct got_error *
7828 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7829 struct tog_reflist_entry *re, struct got_repository *repo)
7831 struct tog_view *log_view;
7832 const struct got_error *err = NULL;
7833 struct got_object_id *commit_id = NULL;
7835 *new_view = NULL;
7837 err = resolve_reflist_entry(&commit_id, re, repo);
7838 if (err) {
7839 if (err->code != GOT_ERR_OBJ_TYPE)
7840 return err;
7841 else
7842 return NULL;
7845 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7846 if (log_view == NULL) {
7847 err = got_error_from_errno("view_open");
7848 goto done;
7851 err = open_log_view(log_view, commit_id, repo,
7852 got_ref_get_name(re->ref), "", 0);
7853 done:
7854 if (err)
7855 view_close(log_view);
7856 else
7857 *new_view = log_view;
7858 free(commit_id);
7859 return err;
7862 static void
7863 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7865 struct tog_reflist_entry *re;
7866 int i = 0;
7868 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7869 return;
7871 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7872 while (i++ < maxscroll) {
7873 if (re == NULL)
7874 break;
7875 s->first_displayed_entry = re;
7876 re = TAILQ_PREV(re, tog_reflist_head, entry);
7880 static const struct got_error *
7881 ref_scroll_down(struct tog_view *view, int maxscroll)
7883 struct tog_ref_view_state *s = &view->state.ref;
7884 struct tog_reflist_entry *next, *last;
7885 int n = 0;
7887 if (s->first_displayed_entry)
7888 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7889 else
7890 next = TAILQ_FIRST(&s->refs);
7892 last = s->last_displayed_entry;
7893 while (next && n++ < maxscroll) {
7894 if (last) {
7895 s->last_displayed_entry = last;
7896 last = TAILQ_NEXT(last, entry);
7898 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7899 s->first_displayed_entry = next;
7900 next = TAILQ_NEXT(next, entry);
7904 return NULL;
7907 static const struct got_error *
7908 search_start_ref_view(struct tog_view *view)
7910 struct tog_ref_view_state *s = &view->state.ref;
7912 s->matched_entry = NULL;
7913 return NULL;
7916 static int
7917 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7919 regmatch_t regmatch;
7921 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7922 0) == 0;
7925 static const struct got_error *
7926 search_next_ref_view(struct tog_view *view)
7928 struct tog_ref_view_state *s = &view->state.ref;
7929 struct tog_reflist_entry *re = NULL;
7931 if (!view->searching) {
7932 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7933 return NULL;
7936 if (s->matched_entry) {
7937 if (view->searching == TOG_SEARCH_FORWARD) {
7938 if (s->selected_entry)
7939 re = TAILQ_NEXT(s->selected_entry, entry);
7940 else
7941 re = TAILQ_PREV(s->selected_entry,
7942 tog_reflist_head, entry);
7943 } else {
7944 if (s->selected_entry == NULL)
7945 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7946 else
7947 re = TAILQ_PREV(s->selected_entry,
7948 tog_reflist_head, entry);
7950 } else {
7951 if (s->selected_entry)
7952 re = s->selected_entry;
7953 else if (view->searching == TOG_SEARCH_FORWARD)
7954 re = TAILQ_FIRST(&s->refs);
7955 else
7956 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7959 while (1) {
7960 if (re == NULL) {
7961 if (s->matched_entry == NULL) {
7962 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7963 return NULL;
7965 if (view->searching == TOG_SEARCH_FORWARD)
7966 re = TAILQ_FIRST(&s->refs);
7967 else
7968 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7971 if (match_reflist_entry(re, &view->regex)) {
7972 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7973 s->matched_entry = re;
7974 break;
7977 if (view->searching == TOG_SEARCH_FORWARD)
7978 re = TAILQ_NEXT(re, entry);
7979 else
7980 re = TAILQ_PREV(re, tog_reflist_head, entry);
7983 if (s->matched_entry) {
7984 s->first_displayed_entry = s->matched_entry;
7985 s->selected = 0;
7988 return NULL;
7991 static const struct got_error *
7992 show_ref_view(struct tog_view *view)
7994 const struct got_error *err = NULL;
7995 struct tog_ref_view_state *s = &view->state.ref;
7996 struct tog_reflist_entry *re;
7997 char *line = NULL;
7998 wchar_t *wline;
7999 struct tog_color *tc;
8000 int width, n;
8001 int limit = view->nlines;
8003 werase(view->window);
8005 s->ndisplayed = 0;
8006 if (view_is_hsplit_top(view))
8007 --limit; /* border */
8009 if (limit == 0)
8010 return NULL;
8012 re = s->first_displayed_entry;
8014 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8015 s->nrefs) == -1)
8016 return got_error_from_errno("asprintf");
8018 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8019 if (err) {
8020 free(line);
8021 return err;
8023 if (view_needs_focus_indication(view))
8024 wstandout(view->window);
8025 waddwstr(view->window, wline);
8026 while (width++ < view->ncols)
8027 waddch(view->window, ' ');
8028 if (view_needs_focus_indication(view))
8029 wstandend(view->window);
8030 free(wline);
8031 wline = NULL;
8032 free(line);
8033 line = NULL;
8034 if (--limit <= 0)
8035 return NULL;
8037 n = 0;
8038 while (re && limit > 0) {
8039 char *line = NULL;
8040 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8042 if (s->show_date) {
8043 struct got_commit_object *ci;
8044 struct got_tag_object *tag;
8045 struct got_object_id *id;
8046 struct tm tm;
8047 time_t t;
8049 err = got_ref_resolve(&id, s->repo, re->ref);
8050 if (err)
8051 return err;
8052 err = got_object_open_as_tag(&tag, s->repo, id);
8053 if (err) {
8054 if (err->code != GOT_ERR_OBJ_TYPE) {
8055 free(id);
8056 return err;
8058 err = got_object_open_as_commit(&ci, s->repo,
8059 id);
8060 if (err) {
8061 free(id);
8062 return err;
8064 t = got_object_commit_get_committer_time(ci);
8065 got_object_commit_close(ci);
8066 } else {
8067 t = got_object_tag_get_tagger_time(tag);
8068 got_object_tag_close(tag);
8070 free(id);
8071 if (gmtime_r(&t, &tm) == NULL)
8072 return got_error_from_errno("gmtime_r");
8073 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8074 return got_error(GOT_ERR_NO_SPACE);
8076 if (got_ref_is_symbolic(re->ref)) {
8077 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8078 ymd : "", got_ref_get_name(re->ref),
8079 got_ref_get_symref_target(re->ref)) == -1)
8080 return got_error_from_errno("asprintf");
8081 } else if (s->show_ids) {
8082 struct got_object_id *id;
8083 char *id_str;
8084 err = got_ref_resolve(&id, s->repo, re->ref);
8085 if (err)
8086 return err;
8087 err = got_object_id_str(&id_str, id);
8088 if (err) {
8089 free(id);
8090 return err;
8092 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8093 got_ref_get_name(re->ref), id_str) == -1) {
8094 err = got_error_from_errno("asprintf");
8095 free(id);
8096 free(id_str);
8097 return err;
8099 free(id);
8100 free(id_str);
8101 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8102 got_ref_get_name(re->ref)) == -1)
8103 return got_error_from_errno("asprintf");
8105 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
8106 0, 0);
8107 if (err) {
8108 free(line);
8109 return err;
8111 if (n == s->selected) {
8112 if (view->focussed)
8113 wstandout(view->window);
8114 s->selected_entry = re;
8116 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8117 if (tc)
8118 wattr_on(view->window,
8119 COLOR_PAIR(tc->colorpair), NULL);
8120 waddwstr(view->window, wline);
8121 if (tc)
8122 wattr_off(view->window,
8123 COLOR_PAIR(tc->colorpair), NULL);
8124 if (width < view->ncols - 1)
8125 waddch(view->window, '\n');
8126 if (n == s->selected && view->focussed)
8127 wstandend(view->window);
8128 free(line);
8129 free(wline);
8130 wline = NULL;
8131 n++;
8132 s->ndisplayed++;
8133 s->last_displayed_entry = re;
8135 limit--;
8136 re = TAILQ_NEXT(re, entry);
8139 view_border(view);
8140 return err;
8143 static const struct got_error *
8144 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8145 struct tog_reflist_entry *re, struct got_repository *repo)
8147 const struct got_error *err = NULL;
8148 struct got_object_id *commit_id = NULL;
8149 struct tog_view *tree_view;
8151 *new_view = NULL;
8153 err = resolve_reflist_entry(&commit_id, re, repo);
8154 if (err) {
8155 if (err->code != GOT_ERR_OBJ_TYPE)
8156 return err;
8157 else
8158 return NULL;
8162 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8163 if (tree_view == NULL) {
8164 err = got_error_from_errno("view_open");
8165 goto done;
8168 err = open_tree_view(tree_view, commit_id,
8169 got_ref_get_name(re->ref), repo);
8170 if (err)
8171 goto done;
8173 *new_view = tree_view;
8174 done:
8175 free(commit_id);
8176 return err;
8179 static const struct got_error *
8180 ref_goto_line(struct tog_view *view, int nlines)
8182 const struct got_error *err = NULL;
8183 struct tog_ref_view_state *s = &view->state.ref;
8184 int g, idx = s->selected_entry->idx;
8186 g = view->gline;
8187 view->gline = 0;
8189 if (g == 0)
8190 g = 1;
8191 else if (g > s->nrefs)
8192 g = s->nrefs;
8194 if (g >= s->first_displayed_entry->idx + 1 &&
8195 g <= s->last_displayed_entry->idx + 1 &&
8196 g - s->first_displayed_entry->idx - 1 < nlines) {
8197 s->selected = g - s->first_displayed_entry->idx - 1;
8198 return NULL;
8201 if (idx + 1 < g) {
8202 err = ref_scroll_down(view, g - idx - 1);
8203 if (err)
8204 return err;
8205 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8206 s->first_displayed_entry->idx + s->selected < g &&
8207 s->selected < s->ndisplayed - 1)
8208 s->selected = g - s->first_displayed_entry->idx - 1;
8209 } else if (idx + 1 > g)
8210 ref_scroll_up(s, idx - g + 1);
8212 if (g < nlines && s->first_displayed_entry->idx == 0)
8213 s->selected = g - 1;
8215 return NULL;
8219 static const struct got_error *
8220 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8222 const struct got_error *err = NULL;
8223 struct tog_ref_view_state *s = &view->state.ref;
8224 struct tog_reflist_entry *re;
8225 int n, nscroll = view->nlines - 1;
8227 if (view->gline)
8228 return ref_goto_line(view, nscroll);
8230 switch (ch) {
8231 case 'i':
8232 s->show_ids = !s->show_ids;
8233 view->count = 0;
8234 break;
8235 case 'm':
8236 s->show_date = !s->show_date;
8237 view->count = 0;
8238 break;
8239 case 'o':
8240 s->sort_by_date = !s->sort_by_date;
8241 view->count = 0;
8242 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8243 got_ref_cmp_by_commit_timestamp_descending :
8244 tog_ref_cmp_by_name, s->repo);
8245 if (err)
8246 break;
8247 got_reflist_object_id_map_free(tog_refs_idmap);
8248 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8249 &tog_refs, s->repo);
8250 if (err)
8251 break;
8252 ref_view_free_refs(s);
8253 err = ref_view_load_refs(s);
8254 break;
8255 case KEY_ENTER:
8256 case '\r':
8257 view->count = 0;
8258 if (!s->selected_entry)
8259 break;
8260 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8261 break;
8262 case 'T':
8263 view->count = 0;
8264 if (!s->selected_entry)
8265 break;
8266 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8267 break;
8268 case 'g':
8269 case '=':
8270 case KEY_HOME:
8271 s->selected = 0;
8272 view->count = 0;
8273 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8274 break;
8275 case 'G':
8276 case '*':
8277 case KEY_END: {
8278 int eos = view->nlines - 1;
8280 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8281 --eos; /* border */
8282 s->selected = 0;
8283 view->count = 0;
8284 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8285 for (n = 0; n < eos; n++) {
8286 if (re == NULL)
8287 break;
8288 s->first_displayed_entry = re;
8289 re = TAILQ_PREV(re, tog_reflist_head, entry);
8291 if (n > 0)
8292 s->selected = n - 1;
8293 break;
8295 case 'k':
8296 case KEY_UP:
8297 case CTRL('p'):
8298 if (s->selected > 0) {
8299 s->selected--;
8300 break;
8302 ref_scroll_up(s, 1);
8303 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8304 view->count = 0;
8305 break;
8306 case CTRL('u'):
8307 case 'u':
8308 nscroll /= 2;
8309 /* FALL THROUGH */
8310 case KEY_PPAGE:
8311 case CTRL('b'):
8312 case 'b':
8313 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8314 s->selected -= MIN(nscroll, s->selected);
8315 ref_scroll_up(s, MAX(0, nscroll));
8316 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8317 view->count = 0;
8318 break;
8319 case 'j':
8320 case KEY_DOWN:
8321 case CTRL('n'):
8322 if (s->selected < s->ndisplayed - 1) {
8323 s->selected++;
8324 break;
8326 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8327 /* can't scroll any further */
8328 view->count = 0;
8329 break;
8331 ref_scroll_down(view, 1);
8332 break;
8333 case CTRL('d'):
8334 case 'd':
8335 nscroll /= 2;
8336 /* FALL THROUGH */
8337 case KEY_NPAGE:
8338 case CTRL('f'):
8339 case 'f':
8340 case ' ':
8341 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8342 /* can't scroll any further; move cursor down */
8343 if (s->selected < s->ndisplayed - 1)
8344 s->selected += MIN(nscroll,
8345 s->ndisplayed - s->selected - 1);
8346 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8347 s->selected += s->ndisplayed - s->selected - 1;
8348 view->count = 0;
8349 break;
8351 ref_scroll_down(view, nscroll);
8352 break;
8353 case CTRL('l'):
8354 view->count = 0;
8355 tog_free_refs();
8356 err = tog_load_refs(s->repo, s->sort_by_date);
8357 if (err)
8358 break;
8359 ref_view_free_refs(s);
8360 err = ref_view_load_refs(s);
8361 break;
8362 case KEY_RESIZE:
8363 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8364 s->selected = view->nlines - 2;
8365 break;
8366 default:
8367 view->count = 0;
8368 break;
8371 return err;
8374 __dead static void
8375 usage_ref(void)
8377 endwin();
8378 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8379 getprogname());
8380 exit(1);
8383 static const struct got_error *
8384 cmd_ref(int argc, char *argv[])
8386 const struct got_error *error;
8387 struct got_repository *repo = NULL;
8388 struct got_worktree *worktree = NULL;
8389 char *cwd = NULL, *repo_path = NULL;
8390 int ch;
8391 struct tog_view *view;
8392 int *pack_fds = NULL;
8394 while ((ch = getopt(argc, argv, "r:")) != -1) {
8395 switch (ch) {
8396 case 'r':
8397 repo_path = realpath(optarg, NULL);
8398 if (repo_path == NULL)
8399 return got_error_from_errno2("realpath",
8400 optarg);
8401 break;
8402 default:
8403 usage_ref();
8404 /* NOTREACHED */
8408 argc -= optind;
8409 argv += optind;
8411 if (argc > 1)
8412 usage_ref();
8414 error = got_repo_pack_fds_open(&pack_fds);
8415 if (error != NULL)
8416 goto done;
8418 if (repo_path == NULL) {
8419 cwd = getcwd(NULL, 0);
8420 if (cwd == NULL)
8421 return got_error_from_errno("getcwd");
8422 error = got_worktree_open(&worktree, cwd);
8423 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8424 goto done;
8425 if (worktree)
8426 repo_path =
8427 strdup(got_worktree_get_repo_path(worktree));
8428 else
8429 repo_path = strdup(cwd);
8430 if (repo_path == NULL) {
8431 error = got_error_from_errno("strdup");
8432 goto done;
8436 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8437 if (error != NULL)
8438 goto done;
8440 init_curses();
8442 error = apply_unveil(got_repo_get_path(repo), NULL);
8443 if (error)
8444 goto done;
8446 error = tog_load_refs(repo, 0);
8447 if (error)
8448 goto done;
8450 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8451 if (view == NULL) {
8452 error = got_error_from_errno("view_open");
8453 goto done;
8456 error = open_ref_view(view, repo);
8457 if (error)
8458 goto done;
8460 if (worktree) {
8461 /* Release work tree lock. */
8462 got_worktree_close(worktree);
8463 worktree = NULL;
8465 error = view_loop(view);
8466 done:
8467 free(repo_path);
8468 free(cwd);
8469 if (repo) {
8470 const struct got_error *close_err = got_repo_close(repo);
8471 if (close_err)
8472 error = close_err;
8474 if (pack_fds) {
8475 const struct got_error *pack_err =
8476 got_repo_pack_fds_close(pack_fds);
8477 if (error == NULL)
8478 error = pack_err;
8480 tog_free_refs();
8481 return error;
8484 static const struct got_error*
8485 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8486 const char *str)
8488 size_t len;
8490 if (win == NULL)
8491 win = stdscr;
8493 len = strlen(str);
8494 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8496 if (focus)
8497 wstandout(win);
8498 if (mvwprintw(win, y, x, "%s", str) == ERR)
8499 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8500 if (focus)
8501 wstandend(win);
8503 return NULL;
8506 static const struct got_error *
8507 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8509 off_t *p;
8511 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8512 if (p == NULL) {
8513 free(*line_offsets);
8514 *line_offsets = NULL;
8515 return got_error_from_errno("reallocarray");
8518 *line_offsets = p;
8519 (*line_offsets)[*nlines] = off;
8520 ++(*nlines);
8521 return NULL;
8524 static const struct got_error *
8525 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8527 *ret = 0;
8529 for (;n > 0; --n, ++km) {
8530 char *t0, *t, *k;
8531 size_t len = 1;
8533 if (km->keys == NULL)
8534 continue;
8536 t = t0 = strdup(km->keys);
8537 if (t0 == NULL)
8538 return got_error_from_errno("strdup");
8540 len += strlen(t);
8541 while ((k = strsep(&t, " ")) != NULL)
8542 len += strlen(k) > 1 ? 2 : 0;
8543 free(t0);
8544 *ret = MAX(*ret, len);
8547 return NULL;
8551 * Write keymap section headers, keys, and key info in km to f.
8552 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8553 * wrap control and symbolic keys in guillemets, else use <>.
8555 static const struct got_error *
8556 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8558 int n, len = width;
8560 if (km->keys) {
8561 static const char *u8_glyph[] = {
8562 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8563 "\xe2\x80\xba" /* U+203A (utf8 >) */
8565 char *t0, *t, *k;
8566 int cs, s, first = 1;
8568 cs = got_locale_is_utf8();
8570 t = t0 = strdup(km->keys);
8571 if (t0 == NULL)
8572 return got_error_from_errno("strdup");
8574 len = strlen(km->keys);
8575 while ((k = strsep(&t, " ")) != NULL) {
8576 s = strlen(k) > 1; /* control or symbolic key */
8577 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8578 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8579 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8580 if (n < 0) {
8581 free(t0);
8582 return got_error_from_errno("fprintf");
8584 first = 0;
8585 len += s ? 2 : 0;
8586 *off += n;
8588 free(t0);
8590 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8591 if (n < 0)
8592 return got_error_from_errno("fprintf");
8593 *off += n;
8595 return NULL;
8598 static const struct got_error *
8599 format_help(struct tog_help_view_state *s)
8601 const struct got_error *err = NULL;
8602 off_t off = 0;
8603 int i, max, n, show = s->all;
8604 static const struct tog_key_map km[] = {
8605 #define KEYMAP_(info, type) { NULL, (info), type }
8606 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8607 GENERATE_HELP
8608 #undef KEYMAP_
8609 #undef KEY_
8612 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8613 if (err)
8614 return err;
8616 n = nitems(km);
8617 err = max_key_str(&max, km, n);
8618 if (err)
8619 return err;
8621 for (i = 0; i < n; ++i) {
8622 if (km[i].keys == NULL) {
8623 show = s->all;
8624 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8625 km[i].type == s->type || s->all)
8626 show = 1;
8628 if (show) {
8629 err = format_help_line(&off, s->f, &km[i], max);
8630 if (err)
8631 return err;
8632 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8633 if (err)
8634 return err;
8637 fputc('\n', s->f);
8638 ++off;
8639 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8640 return err;
8643 static const struct got_error *
8644 create_help(struct tog_help_view_state *s)
8646 FILE *f;
8647 const struct got_error *err;
8649 free(s->line_offsets);
8650 s->line_offsets = NULL;
8651 s->nlines = 0;
8653 f = got_opentemp();
8654 if (f == NULL)
8655 return got_error_from_errno("got_opentemp");
8656 s->f = f;
8658 err = format_help(s);
8659 if (err)
8660 return err;
8662 if (s->f && fflush(s->f) != 0)
8663 return got_error_from_errno("fflush");
8665 return NULL;
8668 static const struct got_error *
8669 search_start_help_view(struct tog_view *view)
8671 view->state.help.matched_line = 0;
8672 return NULL;
8675 static void
8676 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8677 size_t *nlines, int **first, int **last, int **match, int **selected)
8679 struct tog_help_view_state *s = &view->state.help;
8681 *f = s->f;
8682 *nlines = s->nlines;
8683 *line_offsets = s->line_offsets;
8684 *match = &s->matched_line;
8685 *first = &s->first_displayed_line;
8686 *last = &s->last_displayed_line;
8687 *selected = &s->selected_line;
8690 static const struct got_error *
8691 show_help_view(struct tog_view *view)
8693 struct tog_help_view_state *s = &view->state.help;
8694 const struct got_error *err;
8695 regmatch_t *regmatch = &view->regmatch;
8696 wchar_t *wline;
8697 char *line;
8698 ssize_t linelen;
8699 size_t linesz = 0;
8700 int width, nprinted = 0, rc = 0;
8701 int eos = view->nlines;
8703 if (view_is_hsplit_top(view))
8704 --eos; /* account for border */
8706 s->lineno = 0;
8707 rewind(s->f);
8708 werase(view->window);
8710 if (view->gline > s->nlines - 1)
8711 view->gline = s->nlines - 1;
8713 err = win_draw_center(view->window, 0, 0, view->ncols,
8714 view_needs_focus_indication(view),
8715 "tog help (press q to return to tog)");
8716 if (err)
8717 return err;
8718 if (eos <= 1)
8719 return NULL;
8720 waddstr(view->window, "\n\n");
8721 eos -= 2;
8723 s->eof = 0;
8724 view->maxx = 0;
8725 line = NULL;
8726 while (eos > 0 && nprinted < eos) {
8727 attr_t attr = 0;
8729 linelen = getline(&line, &linesz, s->f);
8730 if (linelen == -1) {
8731 if (!feof(s->f)) {
8732 free(line);
8733 return got_ferror(s->f, GOT_ERR_IO);
8735 s->eof = 1;
8736 break;
8738 if (++s->lineno < s->first_displayed_line)
8739 continue;
8740 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8741 continue;
8742 if (s->lineno == view->hiline)
8743 attr = A_STANDOUT;
8745 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8746 view->x ? 1 : 0);
8747 if (err) {
8748 free(line);
8749 return err;
8751 view->maxx = MAX(view->maxx, width);
8752 free(wline);
8753 wline = NULL;
8755 if (attr)
8756 wattron(view->window, attr);
8757 if (s->first_displayed_line + nprinted == s->matched_line &&
8758 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8759 err = add_matched_line(&width, line, view->ncols - 1, 0,
8760 view->window, view->x, regmatch);
8761 if (err) {
8762 free(line);
8763 return err;
8765 } else {
8766 int skip;
8768 err = format_line(&wline, &width, &skip, line,
8769 view->x, view->ncols - 1, 0, view->x ? 1 : 0);
8770 if (err) {
8771 free(line);
8772 return err;
8774 rc = waddwstr(view->window, &wline[skip]);
8775 free(wline);
8776 wline = NULL;
8777 if (rc == ERR)
8778 return got_error_msg(GOT_ERR_IO, "waddwstr");
8780 if (s->lineno == view->hiline) {
8781 while (width++ < view->ncols)
8782 waddch(view->window, ' ');
8783 } else {
8784 if (width <= view->ncols)
8785 waddch(view->window, '\n');
8787 if (attr)
8788 wattroff(view->window, attr);
8789 if (++nprinted == 1)
8790 s->first_displayed_line = s->lineno;
8792 free(line);
8793 if (nprinted > 0)
8794 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8795 else
8796 s->last_displayed_line = s->first_displayed_line;
8798 view_border(view);
8800 if (s->eof) {
8801 rc = waddnstr(view->window,
8802 "See the tog(1) manual page for full documentation",
8803 view->ncols - 1);
8804 if (rc == ERR)
8805 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8806 } else {
8807 wmove(view->window, view->nlines - 1, 0);
8808 wclrtoeol(view->window);
8809 wstandout(view->window);
8810 rc = waddnstr(view->window, "scroll down for more...",
8811 view->ncols - 1);
8812 if (rc == ERR)
8813 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8814 if (getcurx(view->window) < view->ncols - 6) {
8815 rc = wprintw(view->window, "[%.0f%%]",
8816 100.00 * s->last_displayed_line / s->nlines);
8817 if (rc == ERR)
8818 return got_error_msg(GOT_ERR_IO, "wprintw");
8820 wstandend(view->window);
8823 return NULL;
8826 static const struct got_error *
8827 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8829 struct tog_help_view_state *s = &view->state.help;
8830 const struct got_error *err = NULL;
8831 char *line = NULL;
8832 ssize_t linelen;
8833 size_t linesz = 0;
8834 int eos, nscroll;
8836 eos = nscroll = view->nlines;
8837 if (view_is_hsplit_top(view))
8838 --eos; /* border */
8840 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8842 switch (ch) {
8843 case '0':
8844 view->x = 0;
8845 break;
8846 case '$':
8847 view->x = MAX(view->maxx - view->ncols / 3, 0);
8848 view->count = 0;
8849 break;
8850 case KEY_RIGHT:
8851 case 'l':
8852 if (view->x + view->ncols / 3 < view->maxx)
8853 view->x += 2;
8854 else
8855 view->count = 0;
8856 break;
8857 case KEY_LEFT:
8858 case 'h':
8859 view->x -= MIN(view->x, 2);
8860 if (view->x <= 0)
8861 view->count = 0;
8862 break;
8863 case 'g':
8864 case KEY_HOME:
8865 s->first_displayed_line = 1;
8866 view->count = 0;
8867 break;
8868 case 'G':
8869 case KEY_END:
8870 view->count = 0;
8871 if (s->eof)
8872 break;
8873 s->first_displayed_line = (s->nlines - eos) + 3;
8874 s->eof = 1;
8875 break;
8876 case 'k':
8877 case KEY_UP:
8878 if (s->first_displayed_line > 1)
8879 --s->first_displayed_line;
8880 else
8881 view->count = 0;
8882 break;
8883 case CTRL('u'):
8884 case 'u':
8885 nscroll /= 2;
8886 /* FALL THROUGH */
8887 case KEY_PPAGE:
8888 case CTRL('b'):
8889 case 'b':
8890 if (s->first_displayed_line == 1) {
8891 view->count = 0;
8892 break;
8894 while (--nscroll > 0 && s->first_displayed_line > 1)
8895 s->first_displayed_line--;
8896 break;
8897 case 'j':
8898 case KEY_DOWN:
8899 case CTRL('n'):
8900 if (!s->eof)
8901 ++s->first_displayed_line;
8902 else
8903 view->count = 0;
8904 break;
8905 case CTRL('d'):
8906 case 'd':
8907 nscroll /= 2;
8908 /* FALL THROUGH */
8909 case KEY_NPAGE:
8910 case CTRL('f'):
8911 case 'f':
8912 case ' ':
8913 if (s->eof) {
8914 view->count = 0;
8915 break;
8917 while (!s->eof && --nscroll > 0) {
8918 linelen = getline(&line, &linesz, s->f);
8919 s->first_displayed_line++;
8920 if (linelen == -1) {
8921 if (feof(s->f))
8922 s->eof = 1;
8923 else
8924 err = got_ferror(s->f, GOT_ERR_IO);
8925 break;
8928 free(line);
8929 break;
8930 default:
8931 view->count = 0;
8932 break;
8935 return err;
8938 static const struct got_error *
8939 close_help_view(struct tog_view *view)
8941 struct tog_help_view_state *s = &view->state.help;
8943 free(s->line_offsets);
8944 s->line_offsets = NULL;
8945 if (fclose(s->f) == EOF)
8946 return got_error_from_errno("fclose");
8948 return NULL;
8951 static const struct got_error *
8952 reset_help_view(struct tog_view *view)
8954 struct tog_help_view_state *s = &view->state.help;
8957 if (s->f && fclose(s->f) == EOF)
8958 return got_error_from_errno("fclose");
8960 wclear(view->window);
8961 view->count = 0;
8962 view->x = 0;
8963 s->all = !s->all;
8964 s->first_displayed_line = 1;
8965 s->last_displayed_line = view->nlines;
8966 s->matched_line = 0;
8968 return create_help(s);
8971 static const struct got_error *
8972 open_help_view(struct tog_view *view, struct tog_view *parent)
8974 const struct got_error *err = NULL;
8975 struct tog_help_view_state *s = &view->state.help;
8977 s->type = (enum tog_keymap_type)parent->type;
8978 s->first_displayed_line = 1;
8979 s->last_displayed_line = view->nlines;
8980 s->selected_line = 1;
8982 view->show = show_help_view;
8983 view->input = input_help_view;
8984 view->reset = reset_help_view;
8985 view->close = close_help_view;
8986 view->search_start = search_start_help_view;
8987 view->search_setup = search_setup_help_view;
8988 view->search_next = search_next_view_match;
8990 err = create_help(s);
8991 return err;
8994 static const struct got_error *
8995 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8996 enum tog_view_type request, int y, int x)
8998 const struct got_error *err = NULL;
9000 *new_view = NULL;
9002 switch (request) {
9003 case TOG_VIEW_DIFF:
9004 if (view->type == TOG_VIEW_LOG) {
9005 struct tog_log_view_state *s = &view->state.log;
9007 err = open_diff_view_for_commit(new_view, y, x,
9008 s->selected_entry->commit, s->selected_entry->id,
9009 view, s->repo);
9010 } else
9011 return got_error_msg(GOT_ERR_NOT_IMPL,
9012 "parent/child view pair not supported");
9013 break;
9014 case TOG_VIEW_BLAME:
9015 if (view->type == TOG_VIEW_TREE) {
9016 struct tog_tree_view_state *s = &view->state.tree;
9018 err = blame_tree_entry(new_view, y, x,
9019 s->selected_entry, &s->parents, s->commit_id,
9020 s->repo);
9021 } else
9022 return got_error_msg(GOT_ERR_NOT_IMPL,
9023 "parent/child view pair not supported");
9024 break;
9025 case TOG_VIEW_LOG:
9026 if (view->type == TOG_VIEW_BLAME)
9027 err = log_annotated_line(new_view, y, x,
9028 view->state.blame.repo, view->state.blame.id_to_log);
9029 else if (view->type == TOG_VIEW_TREE)
9030 err = log_selected_tree_entry(new_view, y, x,
9031 &view->state.tree);
9032 else if (view->type == TOG_VIEW_REF)
9033 err = log_ref_entry(new_view, y, x,
9034 view->state.ref.selected_entry,
9035 view->state.ref.repo);
9036 else
9037 return got_error_msg(GOT_ERR_NOT_IMPL,
9038 "parent/child view pair not supported");
9039 break;
9040 case TOG_VIEW_TREE:
9041 if (view->type == TOG_VIEW_LOG)
9042 err = browse_commit_tree(new_view, y, x,
9043 view->state.log.selected_entry,
9044 view->state.log.in_repo_path,
9045 view->state.log.head_ref_name,
9046 view->state.log.repo);
9047 else if (view->type == TOG_VIEW_REF)
9048 err = browse_ref_tree(new_view, y, x,
9049 view->state.ref.selected_entry,
9050 view->state.ref.repo);
9051 else
9052 return got_error_msg(GOT_ERR_NOT_IMPL,
9053 "parent/child view pair not supported");
9054 break;
9055 case TOG_VIEW_REF:
9056 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9057 if (*new_view == NULL)
9058 return got_error_from_errno("view_open");
9059 if (view->type == TOG_VIEW_LOG)
9060 err = open_ref_view(*new_view, view->state.log.repo);
9061 else if (view->type == TOG_VIEW_TREE)
9062 err = open_ref_view(*new_view, view->state.tree.repo);
9063 else
9064 err = got_error_msg(GOT_ERR_NOT_IMPL,
9065 "parent/child view pair not supported");
9066 if (err)
9067 view_close(*new_view);
9068 break;
9069 case TOG_VIEW_HELP:
9070 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9071 if (*new_view == NULL)
9072 return got_error_from_errno("view_open");
9073 err = open_help_view(*new_view, view);
9074 if (err)
9075 view_close(*new_view);
9076 break;
9077 default:
9078 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9081 return err;
9085 * If view was scrolled down to move the selected line into view when opening a
9086 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9088 static void
9089 offset_selection_up(struct tog_view *view)
9091 switch (view->type) {
9092 case TOG_VIEW_BLAME: {
9093 struct tog_blame_view_state *s = &view->state.blame;
9094 if (s->first_displayed_line == 1) {
9095 s->selected_line = MAX(s->selected_line - view->offset,
9096 1);
9097 break;
9099 if (s->first_displayed_line > view->offset)
9100 s->first_displayed_line -= view->offset;
9101 else
9102 s->first_displayed_line = 1;
9103 s->selected_line += view->offset;
9104 break;
9106 case TOG_VIEW_LOG:
9107 log_scroll_up(&view->state.log, view->offset);
9108 view->state.log.selected += view->offset;
9109 break;
9110 case TOG_VIEW_REF:
9111 ref_scroll_up(&view->state.ref, view->offset);
9112 view->state.ref.selected += view->offset;
9113 break;
9114 case TOG_VIEW_TREE:
9115 tree_scroll_up(&view->state.tree, view->offset);
9116 view->state.tree.selected += view->offset;
9117 break;
9118 default:
9119 break;
9122 view->offset = 0;
9126 * If the selected line is in the section of screen covered by the bottom split,
9127 * scroll down offset lines to move it into view and index its new position.
9129 static const struct got_error *
9130 offset_selection_down(struct tog_view *view)
9132 const struct got_error *err = NULL;
9133 const struct got_error *(*scrolld)(struct tog_view *, int);
9134 int *selected = NULL;
9135 int header, offset;
9137 switch (view->type) {
9138 case TOG_VIEW_BLAME: {
9139 struct tog_blame_view_state *s = &view->state.blame;
9140 header = 3;
9141 scrolld = NULL;
9142 if (s->selected_line > view->nlines - header) {
9143 offset = abs(view->nlines - s->selected_line - header);
9144 s->first_displayed_line += offset;
9145 s->selected_line -= offset;
9146 view->offset = offset;
9148 break;
9150 case TOG_VIEW_LOG: {
9151 struct tog_log_view_state *s = &view->state.log;
9152 scrolld = &log_scroll_down;
9153 header = view_is_parent_view(view) ? 3 : 2;
9154 selected = &s->selected;
9155 break;
9157 case TOG_VIEW_REF: {
9158 struct tog_ref_view_state *s = &view->state.ref;
9159 scrolld = &ref_scroll_down;
9160 header = 3;
9161 selected = &s->selected;
9162 break;
9164 case TOG_VIEW_TREE: {
9165 struct tog_tree_view_state *s = &view->state.tree;
9166 scrolld = &tree_scroll_down;
9167 header = 5;
9168 selected = &s->selected;
9169 break;
9171 default:
9172 selected = NULL;
9173 scrolld = NULL;
9174 header = 0;
9175 break;
9178 if (selected && *selected > view->nlines - header) {
9179 offset = abs(view->nlines - *selected - header);
9180 view->offset = offset;
9181 if (scrolld && offset) {
9182 err = scrolld(view, offset);
9183 *selected -= offset;
9187 return err;
9190 static void
9191 list_commands(FILE *fp)
9193 size_t i;
9195 fprintf(fp, "commands:");
9196 for (i = 0; i < nitems(tog_commands); i++) {
9197 const struct tog_cmd *cmd = &tog_commands[i];
9198 fprintf(fp, " %s", cmd->name);
9200 fputc('\n', fp);
9203 __dead static void
9204 usage(int hflag, int status)
9206 FILE *fp = (status == 0) ? stdout : stderr;
9208 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9209 getprogname());
9210 if (hflag) {
9211 fprintf(fp, "lazy usage: %s path\n", getprogname());
9212 list_commands(fp);
9214 exit(status);
9217 static char **
9218 make_argv(int argc, ...)
9220 va_list ap;
9221 char **argv;
9222 int i;
9224 va_start(ap, argc);
9226 argv = calloc(argc, sizeof(char *));
9227 if (argv == NULL)
9228 err(1, "calloc");
9229 for (i = 0; i < argc; i++) {
9230 argv[i] = strdup(va_arg(ap, char *));
9231 if (argv[i] == NULL)
9232 err(1, "strdup");
9235 va_end(ap);
9236 return argv;
9240 * Try to convert 'tog path' into a 'tog log path' command.
9241 * The user could simply have mistyped the command rather than knowingly
9242 * provided a path. So check whether argv[0] can in fact be resolved
9243 * to a path in the HEAD commit and print a special error if not.
9244 * This hack is for mpi@ <3
9246 static const struct got_error *
9247 tog_log_with_path(int argc, char *argv[])
9249 const struct got_error *error = NULL, *close_err;
9250 const struct tog_cmd *cmd = NULL;
9251 struct got_repository *repo = NULL;
9252 struct got_worktree *worktree = NULL;
9253 struct got_object_id *commit_id = NULL, *id = NULL;
9254 struct got_commit_object *commit = NULL;
9255 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9256 char *commit_id_str = NULL, **cmd_argv = NULL;
9257 int *pack_fds = NULL;
9259 cwd = getcwd(NULL, 0);
9260 if (cwd == NULL)
9261 return got_error_from_errno("getcwd");
9263 error = got_repo_pack_fds_open(&pack_fds);
9264 if (error != NULL)
9265 goto done;
9267 error = got_worktree_open(&worktree, cwd);
9268 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9269 goto done;
9271 if (worktree)
9272 repo_path = strdup(got_worktree_get_repo_path(worktree));
9273 else
9274 repo_path = strdup(cwd);
9275 if (repo_path == NULL) {
9276 error = got_error_from_errno("strdup");
9277 goto done;
9280 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9281 if (error != NULL)
9282 goto done;
9284 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9285 repo, worktree);
9286 if (error)
9287 goto done;
9289 error = tog_load_refs(repo, 0);
9290 if (error)
9291 goto done;
9292 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9293 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9294 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9295 if (error)
9296 goto done;
9298 if (worktree) {
9299 got_worktree_close(worktree);
9300 worktree = NULL;
9303 error = got_object_open_as_commit(&commit, repo, commit_id);
9304 if (error)
9305 goto done;
9307 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9308 if (error) {
9309 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9310 goto done;
9311 fprintf(stderr, "%s: '%s' is no known command or path\n",
9312 getprogname(), argv[0]);
9313 usage(1, 1);
9314 /* not reached */
9317 error = got_object_id_str(&commit_id_str, commit_id);
9318 if (error)
9319 goto done;
9321 cmd = &tog_commands[0]; /* log */
9322 argc = 4;
9323 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9324 error = cmd->cmd_main(argc, cmd_argv);
9325 done:
9326 if (repo) {
9327 close_err = got_repo_close(repo);
9328 if (error == NULL)
9329 error = close_err;
9331 if (commit)
9332 got_object_commit_close(commit);
9333 if (worktree)
9334 got_worktree_close(worktree);
9335 if (pack_fds) {
9336 const struct got_error *pack_err =
9337 got_repo_pack_fds_close(pack_fds);
9338 if (error == NULL)
9339 error = pack_err;
9341 free(id);
9342 free(commit_id_str);
9343 free(commit_id);
9344 free(cwd);
9345 free(repo_path);
9346 free(in_repo_path);
9347 if (cmd_argv) {
9348 int i;
9349 for (i = 0; i < argc; i++)
9350 free(cmd_argv[i]);
9351 free(cmd_argv);
9353 tog_free_refs();
9354 return error;
9357 int
9358 main(int argc, char *argv[])
9360 const struct got_error *error = NULL;
9361 const struct tog_cmd *cmd = NULL;
9362 int ch, hflag = 0, Vflag = 0;
9363 char **cmd_argv = NULL;
9364 static const struct option longopts[] = {
9365 { "version", no_argument, NULL, 'V' },
9366 { NULL, 0, NULL, 0}
9368 char *diff_algo_str = NULL;
9370 if (!isatty(STDIN_FILENO))
9371 errx(1, "standard input is not a tty");
9373 setlocale(LC_CTYPE, "");
9375 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9376 switch (ch) {
9377 case 'h':
9378 hflag = 1;
9379 break;
9380 case 'V':
9381 Vflag = 1;
9382 break;
9383 default:
9384 usage(hflag, 1);
9385 /* NOTREACHED */
9389 argc -= optind;
9390 argv += optind;
9391 optind = 1;
9392 optreset = 1;
9394 if (Vflag) {
9395 got_version_print_str();
9396 return 0;
9399 #ifndef PROFILE
9400 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9401 NULL) == -1)
9402 err(1, "pledge");
9403 #endif
9405 if (argc == 0) {
9406 if (hflag)
9407 usage(hflag, 0);
9408 /* Build an argument vector which runs a default command. */
9409 cmd = &tog_commands[0];
9410 argc = 1;
9411 cmd_argv = make_argv(argc, cmd->name);
9412 } else {
9413 size_t i;
9415 /* Did the user specify a command? */
9416 for (i = 0; i < nitems(tog_commands); i++) {
9417 if (strncmp(tog_commands[i].name, argv[0],
9418 strlen(argv[0])) == 0) {
9419 cmd = &tog_commands[i];
9420 break;
9425 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9426 if (diff_algo_str) {
9427 if (strcasecmp(diff_algo_str, "patience") == 0)
9428 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9429 if (strcasecmp(diff_algo_str, "myers") == 0)
9430 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9433 if (cmd == NULL) {
9434 if (argc != 1)
9435 usage(0, 1);
9436 /* No command specified; try log with a path */
9437 error = tog_log_with_path(argc, argv);
9438 } else {
9439 if (hflag)
9440 cmd->cmd_usage();
9441 else
9442 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9445 endwin();
9446 putchar('\n');
9447 if (cmd_argv) {
9448 int i;
9449 for (i = 0; i < argc; i++)
9450 free(cmd_argv[i]);
9451 free(cmd_argv);
9454 if (error && error->code != GOT_ERR_CANCELLED &&
9455 error->code != GOT_ERR_EOF &&
9456 error->code != GOT_ERR_PRIVSEP_EXIT &&
9457 error->code != GOT_ERR_PRIVSEP_PIPE &&
9458 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9459 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9460 return 0;