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 "got_compat.h"
19 #include <sys/queue.h>
20 #include <sys/stat.h>
21 #include <sys/ioctl.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #if defined(__FreeBSD__) || defined(__APPLE__)
26 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
27 #endif
28 #include <curses.h>
29 #include <panel.h>
30 #include <locale.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <getopt.h>
36 #include <string.h>
37 #include <err.h>
38 #include <unistd.h>
39 #include <limits.h>
40 #include <wchar.h>
41 #include <time.h>
42 #include <pthread.h>
43 #include <libgen.h>
44 #include <regex.h>
45 #include <sched.h>
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 TOG_VIEW_HELP
112 };
114 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
115 enum tog_keymap_type {
116 TOG_KEYMAP_KEYS = -2,
117 TOG_KEYMAP_GLOBAL,
118 TOG_KEYMAP_DIFF,
119 TOG_KEYMAP_LOG,
120 TOG_KEYMAP_BLAME,
121 TOG_KEYMAP_TREE,
122 TOG_KEYMAP_REF,
123 TOG_KEYMAP_HELP
124 };
126 enum tog_view_mode {
127 TOG_VIEW_SPLIT_NONE,
128 TOG_VIEW_SPLIT_VERT,
129 TOG_VIEW_SPLIT_HRZN
130 };
132 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
134 #define TOG_EOF_STRING "(END)"
136 struct commit_queue_entry {
137 TAILQ_ENTRY(commit_queue_entry) entry;
138 struct got_object_id *id;
139 struct got_commit_object *commit;
140 int idx;
141 };
142 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
143 struct commit_queue {
144 int ncommits;
145 struct commit_queue_head head;
146 };
148 struct tog_color {
149 STAILQ_ENTRY(tog_color) entry;
150 regex_t regex;
151 short colorpair;
152 };
153 STAILQ_HEAD(tog_colors, tog_color);
155 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
156 static struct got_reflist_object_id_map *tog_refs_idmap;
157 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
159 static const struct got_error *
160 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
161 struct got_reference* re2)
163 const char *name1 = got_ref_get_name(re1);
164 const char *name2 = got_ref_get_name(re2);
165 int isbackup1, isbackup2;
167 /* Sort backup refs towards the bottom of the list. */
168 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
169 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
170 if (!isbackup1 && isbackup2) {
171 *cmp = -1;
172 return NULL;
173 } else if (isbackup1 && !isbackup2) {
174 *cmp = 1;
175 return NULL;
178 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
179 return NULL;
182 static const struct got_error *
183 tog_load_refs(struct got_repository *repo, int sort_by_date)
185 const struct got_error *err;
187 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
188 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
189 repo);
190 if (err)
191 return err;
193 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
194 repo);
197 static void
198 tog_free_refs(void)
200 if (tog_refs_idmap) {
201 got_reflist_object_id_map_free(tog_refs_idmap);
202 tog_refs_idmap = NULL;
204 got_ref_list_free(&tog_refs);
207 static const struct got_error *
208 add_color(struct tog_colors *colors, const char *pattern,
209 int idx, short color)
211 const struct got_error *err = NULL;
212 struct tog_color *tc;
213 int regerr = 0;
215 if (idx < 1 || idx > COLOR_PAIRS - 1)
216 return NULL;
218 init_pair(idx, color, -1);
220 tc = calloc(1, sizeof(*tc));
221 if (tc == NULL)
222 return got_error_from_errno("calloc");
223 regerr = regcomp(&tc->regex, pattern,
224 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
225 if (regerr) {
226 static char regerr_msg[512];
227 static char err_msg[512];
228 regerror(regerr, &tc->regex, regerr_msg,
229 sizeof(regerr_msg));
230 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
231 regerr_msg);
232 err = got_error_msg(GOT_ERR_REGEX, err_msg);
233 free(tc);
234 return err;
236 tc->colorpair = idx;
237 STAILQ_INSERT_HEAD(colors, tc, entry);
238 return NULL;
241 static void
242 free_colors(struct tog_colors *colors)
244 struct tog_color *tc;
246 while (!STAILQ_EMPTY(colors)) {
247 tc = STAILQ_FIRST(colors);
248 STAILQ_REMOVE_HEAD(colors, entry);
249 regfree(&tc->regex);
250 free(tc);
254 static struct tog_color *
255 get_color(struct tog_colors *colors, int colorpair)
257 struct tog_color *tc = NULL;
259 STAILQ_FOREACH(tc, colors, entry) {
260 if (tc->colorpair == colorpair)
261 return tc;
264 return NULL;
267 static int
268 default_color_value(const char *envvar)
270 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
271 return COLOR_MAGENTA;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
273 return COLOR_CYAN;
274 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
275 return COLOR_YELLOW;
276 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
277 return COLOR_GREEN;
278 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
279 return COLOR_MAGENTA;
280 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
283 return COLOR_CYAN;
284 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
285 return COLOR_GREEN;
286 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
287 return COLOR_GREEN;
288 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
289 return COLOR_CYAN;
290 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
291 return COLOR_YELLOW;
292 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
293 return COLOR_GREEN;
294 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
295 return COLOR_MAGENTA;
296 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
297 return COLOR_YELLOW;
298 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
299 return COLOR_CYAN;
301 return -1;
304 static int
305 get_color_value(const char *envvar)
307 const char *val = getenv(envvar);
309 if (val == NULL)
310 return default_color_value(envvar);
312 if (strcasecmp(val, "black") == 0)
313 return COLOR_BLACK;
314 if (strcasecmp(val, "red") == 0)
315 return COLOR_RED;
316 if (strcasecmp(val, "green") == 0)
317 return COLOR_GREEN;
318 if (strcasecmp(val, "yellow") == 0)
319 return COLOR_YELLOW;
320 if (strcasecmp(val, "blue") == 0)
321 return COLOR_BLUE;
322 if (strcasecmp(val, "magenta") == 0)
323 return COLOR_MAGENTA;
324 if (strcasecmp(val, "cyan") == 0)
325 return COLOR_CYAN;
326 if (strcasecmp(val, "white") == 0)
327 return COLOR_WHITE;
328 if (strcasecmp(val, "default") == 0)
329 return -1;
331 return default_color_value(envvar);
334 struct tog_diff_view_state {
335 struct got_object_id *id1, *id2;
336 const char *label1, *label2;
337 FILE *f, *f1, *f2;
338 int fd1, fd2;
339 int lineno;
340 int first_displayed_line;
341 int last_displayed_line;
342 int eof;
343 int diff_context;
344 int ignore_whitespace;
345 int force_text_diff;
346 struct got_repository *repo;
347 struct got_diff_line *lines;
348 size_t nlines;
349 int matched_line;
350 int selected_line;
352 /* passed from log or blame view; may be NULL */
353 struct tog_view *parent_view;
354 };
356 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
357 static volatile sig_atomic_t tog_thread_error;
359 struct tog_log_thread_args {
360 pthread_cond_t need_commits;
361 pthread_cond_t commit_loaded;
362 int commits_needed;
363 int load_all;
364 struct got_commit_graph *graph;
365 struct commit_queue *real_commits;
366 const char *in_repo_path;
367 struct got_object_id *start_id;
368 struct got_repository *repo;
369 int *pack_fds;
370 int log_complete;
371 sig_atomic_t *quit;
372 struct commit_queue_entry **first_displayed_entry;
373 struct commit_queue_entry **selected_entry;
374 int *searching;
375 int *search_next_done;
376 regex_t *regex;
377 int *limiting;
378 int limit_match;
379 regex_t *limit_regex;
380 struct commit_queue *limit_commits;
381 };
383 struct tog_log_view_state {
384 struct commit_queue *commits;
385 struct commit_queue_entry *first_displayed_entry;
386 struct commit_queue_entry *last_displayed_entry;
387 struct commit_queue_entry *selected_entry;
388 struct commit_queue real_commits;
389 int selected;
390 char *in_repo_path;
391 char *head_ref_name;
392 int log_branches;
393 struct got_repository *repo;
394 struct got_object_id *start_id;
395 sig_atomic_t quit;
396 pthread_t thread;
397 struct tog_log_thread_args thread_args;
398 struct commit_queue_entry *matched_entry;
399 struct commit_queue_entry *search_entry;
400 struct tog_colors colors;
401 int use_committer;
402 int limit_view;
403 regex_t limit_regex;
404 struct commit_queue limit_commits;
405 };
407 #define TOG_COLOR_DIFF_MINUS 1
408 #define TOG_COLOR_DIFF_PLUS 2
409 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
410 #define TOG_COLOR_DIFF_META 4
411 #define TOG_COLOR_TREE_SUBMODULE 5
412 #define TOG_COLOR_TREE_SYMLINK 6
413 #define TOG_COLOR_TREE_DIRECTORY 7
414 #define TOG_COLOR_TREE_EXECUTABLE 8
415 #define TOG_COLOR_COMMIT 9
416 #define TOG_COLOR_AUTHOR 10
417 #define TOG_COLOR_DATE 11
418 #define TOG_COLOR_REFS_HEADS 12
419 #define TOG_COLOR_REFS_TAGS 13
420 #define TOG_COLOR_REFS_REMOTES 14
421 #define TOG_COLOR_REFS_BACKUP 15
423 struct tog_blame_cb_args {
424 struct tog_blame_line *lines; /* one per line */
425 int nlines;
427 struct tog_view *view;
428 struct got_object_id *commit_id;
429 int *quit;
430 };
432 struct tog_blame_thread_args {
433 const char *path;
434 struct got_repository *repo;
435 struct tog_blame_cb_args *cb_args;
436 int *complete;
437 got_cancel_cb cancel_cb;
438 void *cancel_arg;
439 };
441 struct tog_blame {
442 FILE *f;
443 off_t filesize;
444 struct tog_blame_line *lines;
445 int nlines;
446 off_t *line_offsets;
447 pthread_t thread;
448 struct tog_blame_thread_args thread_args;
449 struct tog_blame_cb_args cb_args;
450 const char *path;
451 int *pack_fds;
452 };
454 struct tog_blame_view_state {
455 int first_displayed_line;
456 int last_displayed_line;
457 int selected_line;
458 int last_diffed_line;
459 int blame_complete;
460 int eof;
461 int done;
462 struct got_object_id_queue blamed_commits;
463 struct got_object_qid *blamed_commit;
464 char *path;
465 struct got_repository *repo;
466 struct got_object_id *commit_id;
467 struct got_object_id *id_to_log;
468 struct tog_blame blame;
469 int matched_line;
470 struct tog_colors colors;
471 };
473 struct tog_parent_tree {
474 TAILQ_ENTRY(tog_parent_tree) entry;
475 struct got_tree_object *tree;
476 struct got_tree_entry *first_displayed_entry;
477 struct got_tree_entry *selected_entry;
478 int selected;
479 };
481 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
483 struct tog_tree_view_state {
484 char *tree_label;
485 struct got_object_id *commit_id;/* commit which this tree belongs to */
486 struct got_tree_object *root; /* the commit's root tree entry */
487 struct got_tree_object *tree; /* currently displayed (sub-)tree */
488 struct got_tree_entry *first_displayed_entry;
489 struct got_tree_entry *last_displayed_entry;
490 struct got_tree_entry *selected_entry;
491 int ndisplayed, selected, show_ids;
492 struct tog_parent_trees parents; /* parent trees of current sub-tree */
493 char *head_ref_name;
494 struct got_repository *repo;
495 struct got_tree_entry *matched_entry;
496 struct tog_colors colors;
497 };
499 struct tog_reflist_entry {
500 TAILQ_ENTRY(tog_reflist_entry) entry;
501 struct got_reference *ref;
502 int idx;
503 };
505 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
507 struct tog_ref_view_state {
508 struct tog_reflist_head refs;
509 struct tog_reflist_entry *first_displayed_entry;
510 struct tog_reflist_entry *last_displayed_entry;
511 struct tog_reflist_entry *selected_entry;
512 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
513 struct got_repository *repo;
514 struct tog_reflist_entry *matched_entry;
515 struct tog_colors colors;
516 };
518 struct tog_help_view_state {
519 FILE *f;
520 off_t *line_offsets;
521 size_t nlines;
522 int lineno;
523 int first_displayed_line;
524 int last_displayed_line;
525 int eof;
526 int matched_line;
527 int selected_line;
528 int all;
529 enum tog_keymap_type type;
530 };
532 #define GENERATE_HELP \
533 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
534 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
535 KEY_("k C-p Up", "Move cursor or page up one line"), \
536 KEY_("j C-n Down", "Move cursor or page down one line"), \
537 KEY_("C-b b PgUp", "Scroll the view up one page"), \
538 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
539 KEY_("C-u u", "Scroll the view up one half page"), \
540 KEY_("C-d d", "Scroll the view down one half page"), \
541 KEY_("g", "Go to line N (default: first line)"), \
542 KEY_("Home =", "Go to the first line"), \
543 KEY_("G", "Go to line N (default: last line)"), \
544 KEY_("End *", "Go to the last line"), \
545 KEY_("l Right", "Scroll the view right"), \
546 KEY_("h Left", "Scroll the view left"), \
547 KEY_("$", "Scroll view to the rightmost position"), \
548 KEY_("0", "Scroll view to the leftmost position"), \
549 KEY_("-", "Decrease size of the focussed split"), \
550 KEY_("+", "Increase size of the focussed split"), \
551 KEY_("Tab", "Switch focus between views"), \
552 KEY_("F", "Toggle fullscreen mode"), \
553 KEY_("/", "Open prompt to enter search term"), \
554 KEY_("n", "Find next line/token matching the current search term"), \
555 KEY_("N", "Find previous line/token matching the current search term"),\
556 KEY_("q", "Quit the focussed view; Quit help screen"), \
557 KEY_("Q", "Quit tog"), \
559 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
560 KEY_("< ,", "Move cursor up one commit"), \
561 KEY_("> .", "Move cursor down one commit"), \
562 KEY_("Enter", "Open diff view of the selected commit"), \
563 KEY_("B", "Reload the log view and toggle display of merged commits"), \
564 KEY_("R", "Open ref view of all repository references"), \
565 KEY_("T", "Display tree view of the repository from the selected" \
566 " commit"), \
567 KEY_("@", "Toggle between displaying author and committer name"), \
568 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
569 KEY_("C-g Backspace", "Cancel current search or log operation"), \
570 KEY_("C-l", "Reload the log view with new commits in the repository"), \
572 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
573 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
574 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
575 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
576 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
577 " data"), \
578 KEY_("(", "Go to the previous file in the diff"), \
579 KEY_(")", "Go to the next file in the diff"), \
580 KEY_("{", "Go to the previous hunk in the diff"), \
581 KEY_("}", "Go to the next hunk in the diff"), \
582 KEY_("[", "Decrease the number of context lines"), \
583 KEY_("]", "Increase the number of context lines"), \
584 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
586 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
587 KEY_("Enter", "Display diff view of the selected line's commit"), \
588 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
589 KEY_("L", "Open log view for the currently selected annotated line"), \
590 KEY_("C", "Reload view with the previously blamed commit"), \
591 KEY_("c", "Reload view with the version of the file found in the" \
592 " selected line's commit"), \
593 KEY_("p", "Reload view with the version of the file found in the" \
594 " selected line's parent commit"), \
596 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
597 KEY_("Enter", "Enter selected directory or open blame view of the" \
598 " selected file"), \
599 KEY_("L", "Open log view for the selected entry"), \
600 KEY_("R", "Open ref view of all repository references"), \
601 KEY_("i", "Show object IDs for all tree entries"), \
602 KEY_("Backspace", "Return to the parent directory"), \
604 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
605 KEY_("Enter", "Display log view of the selected reference"), \
606 KEY_("T", "Display tree view of the selected reference"), \
607 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
608 KEY_("m", "Toggle display of last modified date for each reference"), \
609 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
610 KEY_("C-l", "Reload view with all repository references")
612 struct tog_key_map {
613 const char *keys;
614 const char *info;
615 enum tog_keymap_type type;
616 };
618 /*
619 * We implement two types of views: parent views and child views.
621 * The 'Tab' key switches focus between a parent view and its child view.
622 * Child views are shown side-by-side to their parent view, provided
623 * there is enough screen estate.
625 * When a new view is opened from within a parent view, this new view
626 * becomes a child view of the parent view, replacing any existing child.
628 * When a new view is opened from within a child view, this new view
629 * becomes a parent view which will obscure the views below until the
630 * user quits the new parent view by typing 'q'.
632 * This list of views contains parent views only.
633 * Child views are only pointed to by their parent view.
634 */
635 TAILQ_HEAD(tog_view_list_head, tog_view);
637 struct tog_view {
638 TAILQ_ENTRY(tog_view) entry;
639 WINDOW *window;
640 PANEL *panel;
641 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
642 int resized_y, resized_x; /* begin_y/x based on user resizing */
643 int maxx, x; /* max column and current start column */
644 int lines, cols; /* copies of LINES and COLS */
645 int nscrolled, offset; /* lines scrolled and hsplit line offset */
646 int gline, hiline; /* navigate to and highlight this nG line */
647 int ch, count; /* current keymap and count prefix */
648 int resized; /* set when in a resize event */
649 int focussed; /* Only set on one parent or child view at a time. */
650 int dying;
651 struct tog_view *parent;
652 struct tog_view *child;
654 /*
655 * This flag is initially set on parent views when a new child view
656 * is created. It gets toggled when the 'Tab' key switches focus
657 * between parent and child.
658 * The flag indicates whether focus should be passed on to our child
659 * view if this parent view gets picked for focus after another parent
660 * view was closed. This prevents child views from losing focus in such
661 * situations.
662 */
663 int focus_child;
665 enum tog_view_mode mode;
666 /* type-specific state */
667 enum tog_view_type type;
668 union {
669 struct tog_diff_view_state diff;
670 struct tog_log_view_state log;
671 struct tog_blame_view_state blame;
672 struct tog_tree_view_state tree;
673 struct tog_ref_view_state ref;
674 struct tog_help_view_state help;
675 } state;
677 const struct got_error *(*show)(struct tog_view *);
678 const struct got_error *(*input)(struct tog_view **,
679 struct tog_view *, int);
680 const struct got_error *(*reset)(struct tog_view *);
681 const struct got_error *(*resize)(struct tog_view *, int);
682 const struct got_error *(*close)(struct tog_view *);
684 const struct got_error *(*search_start)(struct tog_view *);
685 const struct got_error *(*search_next)(struct tog_view *);
686 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
687 int **, int **, int **, int **);
688 int search_started;
689 int searching;
690 #define TOG_SEARCH_FORWARD 1
691 #define TOG_SEARCH_BACKWARD 2
692 int search_next_done;
693 #define TOG_SEARCH_HAVE_MORE 1
694 #define TOG_SEARCH_NO_MORE 2
695 #define TOG_SEARCH_HAVE_NONE 3
696 regex_t regex;
697 regmatch_t regmatch;
698 const char *action;
699 };
701 static const struct got_error *open_diff_view(struct tog_view *,
702 struct got_object_id *, struct got_object_id *,
703 const char *, const char *, int, int, int, struct tog_view *,
704 struct got_repository *);
705 static const struct got_error *show_diff_view(struct tog_view *);
706 static const struct got_error *input_diff_view(struct tog_view **,
707 struct tog_view *, int);
708 static const struct got_error *reset_diff_view(struct tog_view *);
709 static const struct got_error* close_diff_view(struct tog_view *);
710 static const struct got_error *search_start_diff_view(struct tog_view *);
711 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
712 size_t *, int **, int **, int **, int **);
713 static const struct got_error *search_next_view_match(struct tog_view *);
715 static const struct got_error *open_log_view(struct tog_view *,
716 struct got_object_id *, struct got_repository *,
717 const char *, const char *, int);
718 static const struct got_error * show_log_view(struct tog_view *);
719 static const struct got_error *input_log_view(struct tog_view **,
720 struct tog_view *, int);
721 static const struct got_error *resize_log_view(struct tog_view *, int);
722 static const struct got_error *close_log_view(struct tog_view *);
723 static const struct got_error *search_start_log_view(struct tog_view *);
724 static const struct got_error *search_next_log_view(struct tog_view *);
726 static const struct got_error *open_blame_view(struct tog_view *, char *,
727 struct got_object_id *, struct got_repository *);
728 static const struct got_error *show_blame_view(struct tog_view *);
729 static const struct got_error *input_blame_view(struct tog_view **,
730 struct tog_view *, int);
731 static const struct got_error *reset_blame_view(struct tog_view *);
732 static const struct got_error *close_blame_view(struct tog_view *);
733 static const struct got_error *search_start_blame_view(struct tog_view *);
734 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
735 size_t *, int **, int **, int **, int **);
737 static const struct got_error *open_tree_view(struct tog_view *,
738 struct got_object_id *, const char *, struct got_repository *);
739 static const struct got_error *show_tree_view(struct tog_view *);
740 static const struct got_error *input_tree_view(struct tog_view **,
741 struct tog_view *, int);
742 static const struct got_error *close_tree_view(struct tog_view *);
743 static const struct got_error *search_start_tree_view(struct tog_view *);
744 static const struct got_error *search_next_tree_view(struct tog_view *);
746 static const struct got_error *open_ref_view(struct tog_view *,
747 struct got_repository *);
748 static const struct got_error *show_ref_view(struct tog_view *);
749 static const struct got_error *input_ref_view(struct tog_view **,
750 struct tog_view *, int);
751 static const struct got_error *close_ref_view(struct tog_view *);
752 static const struct got_error *search_start_ref_view(struct tog_view *);
753 static const struct got_error *search_next_ref_view(struct tog_view *);
755 static const struct got_error *open_help_view(struct tog_view *,
756 struct tog_view *);
757 static const struct got_error *show_help_view(struct tog_view *);
758 static const struct got_error *input_help_view(struct tog_view **,
759 struct tog_view *, int);
760 static const struct got_error *reset_help_view(struct tog_view *);
761 static const struct got_error* close_help_view(struct tog_view *);
762 static const struct got_error *search_start_help_view(struct tog_view *);
763 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
764 size_t *, int **, int **, int **, int **);
766 static volatile sig_atomic_t tog_sigwinch_received;
767 static volatile sig_atomic_t tog_sigpipe_received;
768 static volatile sig_atomic_t tog_sigcont_received;
769 static volatile sig_atomic_t tog_sigint_received;
770 static volatile sig_atomic_t tog_sigterm_received;
772 static void
773 tog_sigwinch(int signo)
775 tog_sigwinch_received = 1;
778 static void
779 tog_sigpipe(int signo)
781 tog_sigpipe_received = 1;
784 static void
785 tog_sigcont(int signo)
787 tog_sigcont_received = 1;
790 static void
791 tog_sigint(int signo)
793 tog_sigint_received = 1;
796 static void
797 tog_sigterm(int signo)
799 tog_sigterm_received = 1;
802 static int
803 tog_fatal_signal_received(void)
805 return (tog_sigpipe_received ||
806 tog_sigint_received || tog_sigterm_received);
809 static const struct got_error *
810 view_close(struct tog_view *view)
812 const struct got_error *err = NULL, *child_err = NULL;
814 if (view->child) {
815 child_err = view_close(view->child);
816 view->child = NULL;
818 if (view->close)
819 err = view->close(view);
820 if (view->panel)
821 del_panel(view->panel);
822 if (view->window)
823 delwin(view->window);
824 free(view);
825 return err ? err : child_err;
828 static struct tog_view *
829 view_open(int nlines, int ncols, int begin_y, int begin_x,
830 enum tog_view_type type)
832 struct tog_view *view = calloc(1, sizeof(*view));
834 if (view == NULL)
835 return NULL;
837 view->type = type;
838 view->lines = LINES;
839 view->cols = COLS;
840 view->nlines = nlines ? nlines : LINES - begin_y;
841 view->ncols = ncols ? ncols : COLS - begin_x;
842 view->begin_y = begin_y;
843 view->begin_x = begin_x;
844 view->window = newwin(nlines, ncols, begin_y, begin_x);
845 if (view->window == NULL) {
846 view_close(view);
847 return NULL;
849 view->panel = new_panel(view->window);
850 if (view->panel == NULL ||
851 set_panel_userptr(view->panel, view) != OK) {
852 view_close(view);
853 return NULL;
856 keypad(view->window, TRUE);
857 return view;
860 static int
861 view_split_begin_x(int begin_x)
863 if (begin_x > 0 || COLS < 120)
864 return 0;
865 return (COLS - MAX(COLS / 2, 80));
868 /* XXX Stub till we decide what to do. */
869 static int
870 view_split_begin_y(int lines)
872 return lines * HSPLIT_SCALE;
875 static const struct got_error *view_resize(struct tog_view *);
877 static const struct got_error *
878 view_splitscreen(struct tog_view *view)
880 const struct got_error *err = NULL;
882 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
883 if (view->resized_y && view->resized_y < view->lines)
884 view->begin_y = view->resized_y;
885 else
886 view->begin_y = view_split_begin_y(view->nlines);
887 view->begin_x = 0;
888 } else if (!view->resized) {
889 if (view->resized_x && view->resized_x < view->cols - 1 &&
890 view->cols > 119)
891 view->begin_x = view->resized_x;
892 else
893 view->begin_x = view_split_begin_x(0);
894 view->begin_y = 0;
896 view->nlines = LINES - view->begin_y;
897 view->ncols = COLS - view->begin_x;
898 view->lines = LINES;
899 view->cols = COLS;
900 err = view_resize(view);
901 if (err)
902 return err;
904 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
905 view->parent->nlines = view->begin_y;
907 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
908 return got_error_from_errno("mvwin");
910 return NULL;
913 static const struct got_error *
914 view_fullscreen(struct tog_view *view)
916 const struct got_error *err = NULL;
918 view->begin_x = 0;
919 view->begin_y = view->resized ? view->begin_y : 0;
920 view->nlines = view->resized ? view->nlines : LINES;
921 view->ncols = COLS;
922 view->lines = LINES;
923 view->cols = COLS;
924 err = view_resize(view);
925 if (err)
926 return err;
928 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
929 return got_error_from_errno("mvwin");
931 return NULL;
934 static int
935 view_is_parent_view(struct tog_view *view)
937 return view->parent == NULL;
940 static int
941 view_is_splitscreen(struct tog_view *view)
943 return view->begin_x > 0 || view->begin_y > 0;
946 static int
947 view_is_fullscreen(struct tog_view *view)
949 return view->nlines == LINES && view->ncols == COLS;
952 static int
953 view_is_hsplit_top(struct tog_view *view)
955 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
956 view_is_splitscreen(view->child);
959 static void
960 view_border(struct tog_view *view)
962 PANEL *panel;
963 const struct tog_view *view_above;
965 if (view->parent)
966 return view_border(view->parent);
968 panel = panel_above(view->panel);
969 if (panel == NULL)
970 return;
972 view_above = panel_userptr(panel);
973 if (view->mode == TOG_VIEW_SPLIT_HRZN)
974 mvwhline(view->window, view_above->begin_y - 1,
975 view->begin_x, got_locale_is_utf8() ?
976 ACS_HLINE : '-', view->ncols);
977 else
978 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
979 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
982 static const struct got_error *view_init_hsplit(struct tog_view *, int);
983 static const struct got_error *request_log_commits(struct tog_view *);
984 static const struct got_error *offset_selection_down(struct tog_view *);
985 static void offset_selection_up(struct tog_view *);
986 static void view_get_split(struct tog_view *, int *, int *);
988 static const struct got_error *
989 view_resize(struct tog_view *view)
991 const struct got_error *err = NULL;
992 int dif, nlines, ncols;
994 dif = LINES - view->lines; /* line difference */
996 if (view->lines > LINES)
997 nlines = view->nlines - (view->lines - LINES);
998 else
999 nlines = view->nlines + (LINES - view->lines);
1000 if (view->cols > COLS)
1001 ncols = view->ncols - (view->cols - COLS);
1002 else
1003 ncols = view->ncols + (COLS - view->cols);
1005 if (view->child) {
1006 int hs = view->child->begin_y;
1008 if (!view_is_fullscreen(view))
1009 view->child->begin_x = view_split_begin_x(view->begin_x);
1010 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1011 view->child->begin_x == 0) {
1012 ncols = COLS;
1014 view_fullscreen(view->child);
1015 if (view->child->focussed)
1016 show_panel(view->child->panel);
1017 else
1018 show_panel(view->panel);
1019 } else {
1020 ncols = view->child->begin_x;
1022 view_splitscreen(view->child);
1023 show_panel(view->child->panel);
1026 * XXX This is ugly and needs to be moved into the above
1027 * logic but "works" for now and my attempts at moving it
1028 * break either 'tab' or 'F' key maps in horizontal splits.
1030 if (hs) {
1031 err = view_splitscreen(view->child);
1032 if (err)
1033 return err;
1034 if (dif < 0) { /* top split decreased */
1035 err = offset_selection_down(view);
1036 if (err)
1037 return err;
1039 view_border(view);
1040 update_panels();
1041 doupdate();
1042 show_panel(view->child->panel);
1043 nlines = view->nlines;
1045 } else if (view->parent == NULL)
1046 ncols = COLS;
1048 if (view->resize && dif > 0) {
1049 err = view->resize(view, dif);
1050 if (err)
1051 return err;
1054 if (wresize(view->window, nlines, ncols) == ERR)
1055 return got_error_from_errno("wresize");
1056 if (replace_panel(view->panel, view->window) == ERR)
1057 return got_error_from_errno("replace_panel");
1058 wclear(view->window);
1060 view->nlines = nlines;
1061 view->ncols = ncols;
1062 view->lines = LINES;
1063 view->cols = COLS;
1065 return NULL;
1068 static const struct got_error *
1069 resize_log_view(struct tog_view *view, int increase)
1071 struct tog_log_view_state *s = &view->state.log;
1072 const struct got_error *err = NULL;
1073 int n = 0;
1075 if (s->selected_entry)
1076 n = s->selected_entry->idx + view->lines - s->selected;
1079 * Request commits to account for the increased
1080 * height so we have enough to populate the view.
1082 if (s->commits->ncommits < n) {
1083 view->nscrolled = n - s->commits->ncommits + increase + 1;
1084 err = request_log_commits(view);
1087 return err;
1090 static void
1091 view_adjust_offset(struct tog_view *view, int n)
1093 if (n == 0)
1094 return;
1096 if (view->parent && view->parent->offset) {
1097 if (view->parent->offset + n >= 0)
1098 view->parent->offset += n;
1099 else
1100 view->parent->offset = 0;
1101 } else if (view->offset) {
1102 if (view->offset - n >= 0)
1103 view->offset -= n;
1104 else
1105 view->offset = 0;
1109 static const struct got_error *
1110 view_resize_split(struct tog_view *view, int resize)
1112 const struct got_error *err = NULL;
1113 struct tog_view *v = NULL;
1115 if (view->parent)
1116 v = view->parent;
1117 else
1118 v = view;
1120 if (!v->child || !view_is_splitscreen(v->child))
1121 return NULL;
1123 v->resized = v->child->resized = resize; /* lock for resize event */
1125 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1126 if (v->child->resized_y)
1127 v->child->begin_y = v->child->resized_y;
1128 if (view->parent)
1129 v->child->begin_y -= resize;
1130 else
1131 v->child->begin_y += resize;
1132 if (v->child->begin_y < 3) {
1133 view->count = 0;
1134 v->child->begin_y = 3;
1135 } else if (v->child->begin_y > LINES - 1) {
1136 view->count = 0;
1137 v->child->begin_y = LINES - 1;
1139 v->ncols = COLS;
1140 v->child->ncols = COLS;
1141 view_adjust_offset(view, resize);
1142 err = view_init_hsplit(v, v->child->begin_y);
1143 if (err)
1144 return err;
1145 v->child->resized_y = v->child->begin_y;
1146 } else {
1147 if (v->child->resized_x)
1148 v->child->begin_x = v->child->resized_x;
1149 if (view->parent)
1150 v->child->begin_x -= resize;
1151 else
1152 v->child->begin_x += resize;
1153 if (v->child->begin_x < 11) {
1154 view->count = 0;
1155 v->child->begin_x = 11;
1156 } else if (v->child->begin_x > COLS - 1) {
1157 view->count = 0;
1158 v->child->begin_x = COLS - 1;
1160 v->child->resized_x = v->child->begin_x;
1163 v->child->mode = v->mode;
1164 v->child->nlines = v->lines - v->child->begin_y;
1165 v->child->ncols = v->cols - v->child->begin_x;
1166 v->focus_child = 1;
1168 err = view_fullscreen(v);
1169 if (err)
1170 return err;
1171 err = view_splitscreen(v->child);
1172 if (err)
1173 return err;
1175 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1176 err = offset_selection_down(v->child);
1177 if (err)
1178 return err;
1181 if (v->resize)
1182 err = v->resize(v, 0);
1183 else if (v->child->resize)
1184 err = v->child->resize(v->child, 0);
1186 v->resized = v->child->resized = 0;
1188 return err;
1191 static void
1192 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1194 struct tog_view *v = src->child ? src->child : src;
1196 dst->resized_x = v->resized_x;
1197 dst->resized_y = v->resized_y;
1200 static const struct got_error *
1201 view_close_child(struct tog_view *view)
1203 const struct got_error *err = NULL;
1205 if (view->child == NULL)
1206 return NULL;
1208 err = view_close(view->child);
1209 view->child = NULL;
1210 return err;
1213 static const struct got_error *
1214 view_set_child(struct tog_view *view, struct tog_view *child)
1216 const struct got_error *err = NULL;
1218 view->child = child;
1219 child->parent = view;
1221 err = view_resize(view);
1222 if (err)
1223 return err;
1225 if (view->child->resized_x || view->child->resized_y)
1226 err = view_resize_split(view, 0);
1228 return err;
1231 static const struct got_error *view_dispatch_request(struct tog_view **,
1232 struct tog_view *, enum tog_view_type, int, int);
1234 static const struct got_error *
1235 view_request_new(struct tog_view **requested, struct tog_view *view,
1236 enum tog_view_type request)
1238 struct tog_view *new_view = NULL;
1239 const struct got_error *err;
1240 int y = 0, x = 0;
1242 *requested = NULL;
1244 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1245 view_get_split(view, &y, &x);
1247 err = view_dispatch_request(&new_view, view, request, y, x);
1248 if (err)
1249 return err;
1251 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1252 request != TOG_VIEW_HELP) {
1253 err = view_init_hsplit(view, y);
1254 if (err)
1255 return err;
1258 view->focussed = 0;
1259 new_view->focussed = 1;
1260 new_view->mode = view->mode;
1261 new_view->nlines = request == TOG_VIEW_HELP ?
1262 view->lines : view->lines - y;
1264 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1265 view_transfer_size(new_view, view);
1266 err = view_close_child(view);
1267 if (err)
1268 return err;
1269 err = view_set_child(view, new_view);
1270 if (err)
1271 return err;
1272 view->focus_child = 1;
1273 } else
1274 *requested = new_view;
1276 return NULL;
1279 static void
1280 tog_resizeterm(void)
1282 int cols, lines;
1283 struct winsize size;
1285 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1286 cols = 80; /* Default */
1287 lines = 24;
1288 } else {
1289 cols = size.ws_col;
1290 lines = size.ws_row;
1292 resize_term(lines, cols);
1295 static const struct got_error *
1296 view_search_start(struct tog_view *view, int fast_refresh)
1298 const struct got_error *err = NULL;
1299 struct tog_view *v = view;
1300 char pattern[1024];
1301 int ret;
1303 if (view->search_started) {
1304 regfree(&view->regex);
1305 view->searching = 0;
1306 memset(&view->regmatch, 0, sizeof(view->regmatch));
1308 view->search_started = 0;
1310 if (view->nlines < 1)
1311 return NULL;
1313 if (view_is_hsplit_top(view))
1314 v = view->child;
1315 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1316 v = view->parent;
1318 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1319 wclrtoeol(v->window);
1321 nodelay(v->window, FALSE); /* block for search term input */
1322 nocbreak();
1323 echo();
1324 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1325 wrefresh(v->window);
1326 cbreak();
1327 noecho();
1328 nodelay(v->window, TRUE);
1329 if (!fast_refresh)
1330 halfdelay(10);
1331 if (ret == ERR)
1332 return NULL;
1334 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1335 err = view->search_start(view);
1336 if (err) {
1337 regfree(&view->regex);
1338 return err;
1340 view->search_started = 1;
1341 view->searching = TOG_SEARCH_FORWARD;
1342 view->search_next_done = 0;
1343 view->search_next(view);
1346 return NULL;
1349 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1350 static const struct got_error *
1351 switch_split(struct tog_view *view)
1353 const struct got_error *err = NULL;
1354 struct tog_view *v = NULL;
1356 if (view->parent)
1357 v = view->parent;
1358 else
1359 v = view;
1361 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1362 v->mode = TOG_VIEW_SPLIT_VERT;
1363 else
1364 v->mode = TOG_VIEW_SPLIT_HRZN;
1366 if (!v->child)
1367 return NULL;
1368 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1369 v->mode = TOG_VIEW_SPLIT_NONE;
1371 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1372 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1373 v->child->begin_y = v->child->resized_y;
1374 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1375 v->child->begin_x = v->child->resized_x;
1378 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1379 v->ncols = COLS;
1380 v->child->ncols = COLS;
1381 v->child->nscrolled = LINES - v->child->nlines;
1383 err = view_init_hsplit(v, v->child->begin_y);
1384 if (err)
1385 return err;
1387 v->child->mode = v->mode;
1388 v->child->nlines = v->lines - v->child->begin_y;
1389 v->focus_child = 1;
1391 err = view_fullscreen(v);
1392 if (err)
1393 return err;
1394 err = view_splitscreen(v->child);
1395 if (err)
1396 return err;
1398 if (v->mode == TOG_VIEW_SPLIT_NONE)
1399 v->mode = TOG_VIEW_SPLIT_VERT;
1400 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1401 err = offset_selection_down(v);
1402 if (err)
1403 return err;
1404 err = offset_selection_down(v->child);
1405 if (err)
1406 return err;
1407 } else {
1408 offset_selection_up(v);
1409 offset_selection_up(v->child);
1411 if (v->resize)
1412 err = v->resize(v, 0);
1413 else if (v->child->resize)
1414 err = v->child->resize(v->child, 0);
1416 return err;
1420 * Compute view->count from numeric input. Assign total to view->count and
1421 * return first non-numeric key entered.
1423 static int
1424 get_compound_key(struct tog_view *view, int c)
1426 struct tog_view *v = view;
1427 int x, n = 0;
1429 if (view_is_hsplit_top(view))
1430 v = view->child;
1431 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1432 v = view->parent;
1434 view->count = 0;
1435 cbreak(); /* block for input */
1436 nodelay(view->window, FALSE);
1437 wmove(v->window, v->nlines - 1, 0);
1438 wclrtoeol(v->window);
1439 waddch(v->window, ':');
1441 do {
1442 x = getcurx(v->window);
1443 if (x != ERR && x < view->ncols) {
1444 waddch(v->window, c);
1445 wrefresh(v->window);
1449 * Don't overflow. Max valid request should be the greatest
1450 * between the longest and total lines; cap at 10 million.
1452 if (n >= 9999999)
1453 n = 9999999;
1454 else
1455 n = n * 10 + (c - '0');
1456 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1458 if (c == 'G' || c == 'g') { /* nG key map */
1459 view->gline = view->hiline = n;
1460 n = 0;
1461 c = 0;
1464 /* Massage excessive or inapplicable values at the input handler. */
1465 view->count = n;
1467 return c;
1470 static void
1471 action_report(struct tog_view *view)
1473 struct tog_view *v = view;
1475 if (view_is_hsplit_top(view))
1476 v = view->child;
1477 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1478 v = view->parent;
1480 wmove(v->window, v->nlines - 1, 0);
1481 wclrtoeol(v->window);
1482 wprintw(v->window, ":%s", view->action);
1483 wrefresh(v->window);
1486 * Clear action status report. Only clear in blame view
1487 * once annotating is complete, otherwise it's too fast.
1489 if (view->type == TOG_VIEW_BLAME) {
1490 if (view->state.blame.blame_complete)
1491 view->action = NULL;
1492 } else
1493 view->action = NULL;
1496 static const struct got_error *
1497 view_input(struct tog_view **new, int *done, struct tog_view *view,
1498 struct tog_view_list_head *views, int fast_refresh)
1500 const struct got_error *err = NULL;
1501 struct tog_view *v;
1502 int ch, errcode;
1504 *new = NULL;
1506 if (view->action)
1507 action_report(view);
1509 /* Clear "no matches" indicator. */
1510 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1511 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1512 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1513 view->count = 0;
1516 if (view->searching && !view->search_next_done) {
1517 errcode = pthread_mutex_unlock(&tog_mutex);
1518 if (errcode)
1519 return got_error_set_errno(errcode,
1520 "pthread_mutex_unlock");
1521 sched_yield();
1522 errcode = pthread_mutex_lock(&tog_mutex);
1523 if (errcode)
1524 return got_error_set_errno(errcode,
1525 "pthread_mutex_lock");
1526 view->search_next(view);
1527 return NULL;
1530 /* Allow threads to make progress while we are waiting for input. */
1531 errcode = pthread_mutex_unlock(&tog_mutex);
1532 if (errcode)
1533 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1534 /* If we have an unfinished count, let C-g or backspace abort. */
1535 if (view->count && --view->count) {
1536 cbreak();
1537 nodelay(view->window, TRUE);
1538 ch = wgetch(view->window);
1539 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1540 view->count = 0;
1541 else
1542 ch = view->ch;
1543 } else {
1544 ch = wgetch(view->window);
1545 if (ch >= '1' && ch <= '9')
1546 view->ch = ch = get_compound_key(view, ch);
1548 if (view->hiline && ch != ERR && ch != 0)
1549 view->hiline = 0; /* key pressed, clear line highlight */
1550 nodelay(view->window, TRUE);
1551 errcode = pthread_mutex_lock(&tog_mutex);
1552 if (errcode)
1553 return got_error_set_errno(errcode, "pthread_mutex_lock");
1555 if (tog_sigwinch_received || tog_sigcont_received) {
1556 tog_resizeterm();
1557 tog_sigwinch_received = 0;
1558 tog_sigcont_received = 0;
1559 TAILQ_FOREACH(v, views, entry) {
1560 err = view_resize(v);
1561 if (err)
1562 return err;
1563 err = v->input(new, v, KEY_RESIZE);
1564 if (err)
1565 return err;
1566 if (v->child) {
1567 err = view_resize(v->child);
1568 if (err)
1569 return err;
1570 err = v->child->input(new, v->child,
1571 KEY_RESIZE);
1572 if (err)
1573 return err;
1574 if (v->child->resized_x || v->child->resized_y) {
1575 err = view_resize_split(v, 0);
1576 if (err)
1577 return err;
1583 switch (ch) {
1584 case '?':
1585 case 'H':
1586 case KEY_F(1):
1587 if (view->type == TOG_VIEW_HELP)
1588 err = view->reset(view);
1589 else
1590 err = view_request_new(new, view, TOG_VIEW_HELP);
1591 break;
1592 case '\t':
1593 view->count = 0;
1594 if (view->child) {
1595 view->focussed = 0;
1596 view->child->focussed = 1;
1597 view->focus_child = 1;
1598 } else if (view->parent) {
1599 view->focussed = 0;
1600 view->parent->focussed = 1;
1601 view->parent->focus_child = 0;
1602 if (!view_is_splitscreen(view)) {
1603 if (view->parent->resize) {
1604 err = view->parent->resize(view->parent,
1605 0);
1606 if (err)
1607 return err;
1609 offset_selection_up(view->parent);
1610 err = view_fullscreen(view->parent);
1611 if (err)
1612 return err;
1615 break;
1616 case 'q':
1617 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1618 if (view->parent->resize) {
1619 /* might need more commits to fill fullscreen */
1620 err = view->parent->resize(view->parent, 0);
1621 if (err)
1622 break;
1624 offset_selection_up(view->parent);
1626 err = view->input(new, view, ch);
1627 view->dying = 1;
1628 break;
1629 case 'Q':
1630 *done = 1;
1631 break;
1632 case 'F':
1633 view->count = 0;
1634 if (view_is_parent_view(view)) {
1635 if (view->child == NULL)
1636 break;
1637 if (view_is_splitscreen(view->child)) {
1638 view->focussed = 0;
1639 view->child->focussed = 1;
1640 err = view_fullscreen(view->child);
1641 } else {
1642 err = view_splitscreen(view->child);
1643 if (!err)
1644 err = view_resize_split(view, 0);
1646 if (err)
1647 break;
1648 err = view->child->input(new, view->child,
1649 KEY_RESIZE);
1650 } else {
1651 if (view_is_splitscreen(view)) {
1652 view->parent->focussed = 0;
1653 view->focussed = 1;
1654 err = view_fullscreen(view);
1655 } else {
1656 err = view_splitscreen(view);
1657 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1658 err = view_resize(view->parent);
1659 if (!err)
1660 err = view_resize_split(view, 0);
1662 if (err)
1663 break;
1664 err = view->input(new, view, KEY_RESIZE);
1666 if (err)
1667 break;
1668 if (view->resize) {
1669 err = view->resize(view, 0);
1670 if (err)
1671 break;
1673 if (view->parent)
1674 err = offset_selection_down(view->parent);
1675 if (!err)
1676 err = offset_selection_down(view);
1677 break;
1678 case 'S':
1679 view->count = 0;
1680 err = switch_split(view);
1681 break;
1682 case '-':
1683 err = view_resize_split(view, -1);
1684 break;
1685 case '+':
1686 err = view_resize_split(view, 1);
1687 break;
1688 case KEY_RESIZE:
1689 break;
1690 case '/':
1691 view->count = 0;
1692 if (view->search_start)
1693 view_search_start(view, fast_refresh);
1694 else
1695 err = view->input(new, view, ch);
1696 break;
1697 case 'N':
1698 case 'n':
1699 if (view->search_started && view->search_next) {
1700 view->searching = (ch == 'n' ?
1701 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1702 view->search_next_done = 0;
1703 view->search_next(view);
1704 } else
1705 err = view->input(new, view, ch);
1706 break;
1707 case 'A':
1708 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1709 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1710 view->action = "Patience diff algorithm";
1711 } else {
1712 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1713 view->action = "Myers diff algorithm";
1715 TAILQ_FOREACH(v, views, entry) {
1716 if (v->reset) {
1717 err = v->reset(v);
1718 if (err)
1719 return err;
1721 if (v->child && v->child->reset) {
1722 err = v->child->reset(v->child);
1723 if (err)
1724 return err;
1727 break;
1728 default:
1729 err = view->input(new, view, ch);
1730 break;
1733 return err;
1736 static int
1737 view_needs_focus_indication(struct tog_view *view)
1739 if (view_is_parent_view(view)) {
1740 if (view->child == NULL || view->child->focussed)
1741 return 0;
1742 if (!view_is_splitscreen(view->child))
1743 return 0;
1744 } else if (!view_is_splitscreen(view))
1745 return 0;
1747 return view->focussed;
1750 static const struct got_error *
1751 view_loop(struct tog_view *view)
1753 const struct got_error *err = NULL;
1754 struct tog_view_list_head views;
1755 struct tog_view *new_view;
1756 char *mode;
1757 int fast_refresh = 10;
1758 int done = 0, errcode;
1760 mode = getenv("TOG_VIEW_SPLIT_MODE");
1761 if (!mode || !(*mode == 'h' || *mode == 'H'))
1762 view->mode = TOG_VIEW_SPLIT_VERT;
1763 else
1764 view->mode = TOG_VIEW_SPLIT_HRZN;
1766 errcode = pthread_mutex_lock(&tog_mutex);
1767 if (errcode)
1768 return got_error_set_errno(errcode, "pthread_mutex_lock");
1770 TAILQ_INIT(&views);
1771 TAILQ_INSERT_HEAD(&views, view, entry);
1773 view->focussed = 1;
1774 err = view->show(view);
1775 if (err)
1776 return err;
1777 update_panels();
1778 doupdate();
1779 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1780 !tog_fatal_signal_received()) {
1781 /* Refresh fast during initialization, then become slower. */
1782 if (fast_refresh && --fast_refresh == 0)
1783 halfdelay(10); /* switch to once per second */
1785 err = view_input(&new_view, &done, view, &views, fast_refresh);
1786 if (err)
1787 break;
1789 if (view->dying && view == TAILQ_FIRST(&views) &&
1790 TAILQ_NEXT(view, entry) == NULL)
1791 done = 1;
1792 if (done) {
1793 struct tog_view *v;
1796 * When we quit, scroll the screen up a single line
1797 * so we don't lose any information.
1799 TAILQ_FOREACH(v, &views, entry) {
1800 wmove(v->window, 0, 0);
1801 wdeleteln(v->window);
1802 wnoutrefresh(v->window);
1803 if (v->child && !view_is_fullscreen(v)) {
1804 wmove(v->child->window, 0, 0);
1805 wdeleteln(v->child->window);
1806 wnoutrefresh(v->child->window);
1809 doupdate();
1812 if (view->dying) {
1813 struct tog_view *v, *prev = NULL;
1815 if (view_is_parent_view(view))
1816 prev = TAILQ_PREV(view, tog_view_list_head,
1817 entry);
1818 else if (view->parent)
1819 prev = view->parent;
1821 if (view->parent) {
1822 view->parent->child = NULL;
1823 view->parent->focus_child = 0;
1824 /* Restore fullscreen line height. */
1825 view->parent->nlines = view->parent->lines;
1826 err = view_resize(view->parent);
1827 if (err)
1828 break;
1829 /* Make resized splits persist. */
1830 view_transfer_size(view->parent, view);
1831 } else
1832 TAILQ_REMOVE(&views, view, entry);
1834 err = view_close(view);
1835 if (err)
1836 goto done;
1838 view = NULL;
1839 TAILQ_FOREACH(v, &views, entry) {
1840 if (v->focussed)
1841 break;
1843 if (view == NULL && new_view == NULL) {
1844 /* No view has focus. Try to pick one. */
1845 if (prev)
1846 view = prev;
1847 else if (!TAILQ_EMPTY(&views)) {
1848 view = TAILQ_LAST(&views,
1849 tog_view_list_head);
1851 if (view) {
1852 if (view->focus_child) {
1853 view->child->focussed = 1;
1854 view = view->child;
1855 } else
1856 view->focussed = 1;
1860 if (new_view) {
1861 struct tog_view *v, *t;
1862 /* Only allow one parent view per type. */
1863 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1864 if (v->type != new_view->type)
1865 continue;
1866 TAILQ_REMOVE(&views, v, entry);
1867 err = view_close(v);
1868 if (err)
1869 goto done;
1870 break;
1872 TAILQ_INSERT_TAIL(&views, new_view, entry);
1873 view = new_view;
1875 if (view && !done) {
1876 if (view_is_parent_view(view)) {
1877 if (view->child && view->child->focussed)
1878 view = view->child;
1879 } else {
1880 if (view->parent && view->parent->focussed)
1881 view = view->parent;
1883 show_panel(view->panel);
1884 if (view->child && view_is_splitscreen(view->child))
1885 show_panel(view->child->panel);
1886 if (view->parent && view_is_splitscreen(view)) {
1887 err = view->parent->show(view->parent);
1888 if (err)
1889 goto done;
1891 err = view->show(view);
1892 if (err)
1893 goto done;
1894 if (view->child) {
1895 err = view->child->show(view->child);
1896 if (err)
1897 goto done;
1899 update_panels();
1900 doupdate();
1903 done:
1904 while (!TAILQ_EMPTY(&views)) {
1905 const struct got_error *close_err;
1906 view = TAILQ_FIRST(&views);
1907 TAILQ_REMOVE(&views, view, entry);
1908 close_err = view_close(view);
1909 if (close_err && err == NULL)
1910 err = close_err;
1913 errcode = pthread_mutex_unlock(&tog_mutex);
1914 if (errcode && err == NULL)
1915 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1917 return err;
1920 __dead static void
1921 usage_log(void)
1923 endwin();
1924 fprintf(stderr,
1925 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1926 getprogname());
1927 exit(1);
1930 /* Create newly allocated wide-character string equivalent to a byte string. */
1931 static const struct got_error *
1932 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1934 char *vis = NULL;
1935 const struct got_error *err = NULL;
1937 *ws = NULL;
1938 *wlen = mbstowcs(NULL, s, 0);
1939 if (*wlen == (size_t)-1) {
1940 int vislen;
1941 if (errno != EILSEQ)
1942 return got_error_from_errno("mbstowcs");
1944 /* byte string invalid in current encoding; try to "fix" it */
1945 err = got_mbsavis(&vis, &vislen, s);
1946 if (err)
1947 return err;
1948 *wlen = mbstowcs(NULL, vis, 0);
1949 if (*wlen == (size_t)-1) {
1950 err = got_error_from_errno("mbstowcs"); /* give up */
1951 goto done;
1955 *ws = calloc(*wlen + 1, sizeof(**ws));
1956 if (*ws == NULL) {
1957 err = got_error_from_errno("calloc");
1958 goto done;
1961 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1962 err = got_error_from_errno("mbstowcs");
1963 done:
1964 free(vis);
1965 if (err) {
1966 free(*ws);
1967 *ws = NULL;
1968 *wlen = 0;
1970 return err;
1973 static const struct got_error *
1974 expand_tab(char **ptr, const char *src)
1976 char *dst;
1977 size_t len, n, idx = 0, sz = 0;
1979 *ptr = NULL;
1980 n = len = strlen(src);
1981 dst = malloc(n + 1);
1982 if (dst == NULL)
1983 return got_error_from_errno("malloc");
1985 while (idx < len && src[idx]) {
1986 const char c = src[idx];
1988 if (c == '\t') {
1989 size_t nb = TABSIZE - sz % TABSIZE;
1990 char *p;
1992 p = realloc(dst, n + nb);
1993 if (p == NULL) {
1994 free(dst);
1995 return got_error_from_errno("realloc");
1998 dst = p;
1999 n += nb;
2000 memset(dst + sz, ' ', nb);
2001 sz += nb;
2002 } else
2003 dst[sz++] = src[idx];
2004 ++idx;
2007 dst[sz] = '\0';
2008 *ptr = dst;
2009 return NULL;
2013 * Advance at most n columns from wline starting at offset off.
2014 * Return the index to the first character after the span operation.
2015 * Return the combined column width of all spanned wide character in
2016 * *rcol.
2018 static int
2019 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2021 int width, i, cols = 0;
2023 if (n == 0) {
2024 *rcol = cols;
2025 return off;
2028 for (i = off; wline[i] != L'\0'; ++i) {
2029 if (wline[i] == L'\t')
2030 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2031 else
2032 width = wcwidth(wline[i]);
2034 if (width == -1) {
2035 width = 1;
2036 wline[i] = L'.';
2039 if (cols + width > n)
2040 break;
2041 cols += width;
2044 *rcol = cols;
2045 return i;
2049 * Format a line for display, ensuring that it won't overflow a width limit.
2050 * With scrolling, the width returned refers to the scrolled version of the
2051 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2053 static const struct got_error *
2054 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2055 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2057 const struct got_error *err = NULL;
2058 int cols;
2059 wchar_t *wline = NULL;
2060 char *exstr = NULL;
2061 size_t wlen;
2062 int i, scrollx;
2064 *wlinep = NULL;
2065 *widthp = 0;
2067 if (expand) {
2068 err = expand_tab(&exstr, line);
2069 if (err)
2070 return err;
2073 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2074 free(exstr);
2075 if (err)
2076 return err;
2078 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2080 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2081 wline[wlen - 1] = L'\0';
2082 wlen--;
2084 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2085 wline[wlen - 1] = L'\0';
2086 wlen--;
2089 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2090 wline[i] = L'\0';
2092 if (widthp)
2093 *widthp = cols;
2094 if (scrollxp)
2095 *scrollxp = scrollx;
2096 if (err)
2097 free(wline);
2098 else
2099 *wlinep = wline;
2100 return err;
2103 static const struct got_error*
2104 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2105 struct got_object_id *id, struct got_repository *repo)
2107 static const struct got_error *err = NULL;
2108 struct got_reflist_entry *re;
2109 char *s;
2110 const char *name;
2112 *refs_str = NULL;
2114 TAILQ_FOREACH(re, refs, entry) {
2115 struct got_tag_object *tag = NULL;
2116 struct got_object_id *ref_id;
2117 int cmp;
2119 name = got_ref_get_name(re->ref);
2120 if (strcmp(name, GOT_REF_HEAD) == 0)
2121 continue;
2122 if (strncmp(name, "refs/", 5) == 0)
2123 name += 5;
2124 if (strncmp(name, "got/", 4) == 0 &&
2125 strncmp(name, "got/backup/", 11) != 0)
2126 continue;
2127 if (strncmp(name, "heads/", 6) == 0)
2128 name += 6;
2129 if (strncmp(name, "remotes/", 8) == 0) {
2130 name += 8;
2131 s = strstr(name, "/" GOT_REF_HEAD);
2132 if (s != NULL && s[strlen(s)] == '\0')
2133 continue;
2135 err = got_ref_resolve(&ref_id, repo, re->ref);
2136 if (err)
2137 break;
2138 if (strncmp(name, "tags/", 5) == 0) {
2139 err = got_object_open_as_tag(&tag, repo, ref_id);
2140 if (err) {
2141 if (err->code != GOT_ERR_OBJ_TYPE) {
2142 free(ref_id);
2143 break;
2145 /* Ref points at something other than a tag. */
2146 err = NULL;
2147 tag = NULL;
2150 cmp = got_object_id_cmp(tag ?
2151 got_object_tag_get_object_id(tag) : ref_id, id);
2152 free(ref_id);
2153 if (tag)
2154 got_object_tag_close(tag);
2155 if (cmp != 0)
2156 continue;
2157 s = *refs_str;
2158 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2159 s ? ", " : "", name) == -1) {
2160 err = got_error_from_errno("asprintf");
2161 free(s);
2162 *refs_str = NULL;
2163 break;
2165 free(s);
2168 return err;
2171 static const struct got_error *
2172 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2173 int col_tab_align)
2175 char *smallerthan;
2177 smallerthan = strchr(author, '<');
2178 if (smallerthan && smallerthan[1] != '\0')
2179 author = smallerthan + 1;
2180 author[strcspn(author, "@>")] = '\0';
2181 return format_line(wauthor, author_width, NULL, author, 0, limit,
2182 col_tab_align, 0);
2185 static const struct got_error *
2186 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2187 struct got_object_id *id, const size_t date_display_cols,
2188 int author_display_cols)
2190 struct tog_log_view_state *s = &view->state.log;
2191 const struct got_error *err = NULL;
2192 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2193 char *logmsg0 = NULL, *logmsg = NULL;
2194 char *author = NULL;
2195 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2196 int author_width, logmsg_width;
2197 char *newline, *line = NULL;
2198 int col, limit, scrollx;
2199 const int avail = view->ncols;
2200 struct tm tm;
2201 time_t committer_time;
2202 struct tog_color *tc;
2204 committer_time = got_object_commit_get_committer_time(commit);
2205 if (gmtime_r(&committer_time, &tm) == NULL)
2206 return got_error_from_errno("gmtime_r");
2207 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2208 return got_error(GOT_ERR_NO_SPACE);
2210 if (avail <= date_display_cols)
2211 limit = MIN(sizeof(datebuf) - 1, avail);
2212 else
2213 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2214 tc = get_color(&s->colors, TOG_COLOR_DATE);
2215 if (tc)
2216 wattr_on(view->window,
2217 COLOR_PAIR(tc->colorpair), NULL);
2218 waddnstr(view->window, datebuf, limit);
2219 if (tc)
2220 wattr_off(view->window,
2221 COLOR_PAIR(tc->colorpair), NULL);
2222 col = limit;
2223 if (col > avail)
2224 goto done;
2226 if (avail >= 120) {
2227 char *id_str;
2228 err = got_object_id_str(&id_str, id);
2229 if (err)
2230 goto done;
2231 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2232 if (tc)
2233 wattr_on(view->window,
2234 COLOR_PAIR(tc->colorpair), NULL);
2235 wprintw(view->window, "%.8s ", id_str);
2236 if (tc)
2237 wattr_off(view->window,
2238 COLOR_PAIR(tc->colorpair), NULL);
2239 free(id_str);
2240 col += 9;
2241 if (col > avail)
2242 goto done;
2245 if (s->use_committer)
2246 author = strdup(got_object_commit_get_committer(commit));
2247 else
2248 author = strdup(got_object_commit_get_author(commit));
2249 if (author == NULL) {
2250 err = got_error_from_errno("strdup");
2251 goto done;
2253 err = format_author(&wauthor, &author_width, author, avail - col, col);
2254 if (err)
2255 goto done;
2256 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2257 if (tc)
2258 wattr_on(view->window,
2259 COLOR_PAIR(tc->colorpair), NULL);
2260 waddwstr(view->window, wauthor);
2261 col += author_width;
2262 while (col < avail && author_width < author_display_cols + 2) {
2263 waddch(view->window, ' ');
2264 col++;
2265 author_width++;
2267 if (tc)
2268 wattr_off(view->window,
2269 COLOR_PAIR(tc->colorpair), NULL);
2270 if (col > avail)
2271 goto done;
2273 err = got_object_commit_get_logmsg(&logmsg0, commit);
2274 if (err)
2275 goto done;
2276 logmsg = logmsg0;
2277 while (*logmsg == '\n')
2278 logmsg++;
2279 newline = strchr(logmsg, '\n');
2280 if (newline)
2281 *newline = '\0';
2282 limit = avail - col;
2283 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2284 limit--; /* for the border */
2285 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2286 limit, col, 1);
2287 if (err)
2288 goto done;
2289 waddwstr(view->window, &wlogmsg[scrollx]);
2290 col += MAX(logmsg_width, 0);
2291 while (col < avail) {
2292 waddch(view->window, ' ');
2293 col++;
2295 done:
2296 free(logmsg0);
2297 free(wlogmsg);
2298 free(author);
2299 free(wauthor);
2300 free(line);
2301 return err;
2304 static struct commit_queue_entry *
2305 alloc_commit_queue_entry(struct got_commit_object *commit,
2306 struct got_object_id *id)
2308 struct commit_queue_entry *entry;
2309 struct got_object_id *dup;
2311 entry = calloc(1, sizeof(*entry));
2312 if (entry == NULL)
2313 return NULL;
2315 dup = got_object_id_dup(id);
2316 if (dup == NULL) {
2317 free(entry);
2318 return NULL;
2321 entry->id = dup;
2322 entry->commit = commit;
2323 return entry;
2326 static void
2327 pop_commit(struct commit_queue *commits)
2329 struct commit_queue_entry *entry;
2331 entry = TAILQ_FIRST(&commits->head);
2332 TAILQ_REMOVE(&commits->head, entry, entry);
2333 got_object_commit_close(entry->commit);
2334 commits->ncommits--;
2335 free(entry->id);
2336 free(entry);
2339 static void
2340 free_commits(struct commit_queue *commits)
2342 while (!TAILQ_EMPTY(&commits->head))
2343 pop_commit(commits);
2346 static const struct got_error *
2347 match_commit(int *have_match, struct got_object_id *id,
2348 struct got_commit_object *commit, regex_t *regex)
2350 const struct got_error *err = NULL;
2351 regmatch_t regmatch;
2352 char *id_str = NULL, *logmsg = NULL;
2354 *have_match = 0;
2356 err = got_object_id_str(&id_str, id);
2357 if (err)
2358 return err;
2360 err = got_object_commit_get_logmsg(&logmsg, commit);
2361 if (err)
2362 goto done;
2364 if (regexec(regex, got_object_commit_get_author(commit), 1,
2365 &regmatch, 0) == 0 ||
2366 regexec(regex, got_object_commit_get_committer(commit), 1,
2367 &regmatch, 0) == 0 ||
2368 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2369 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2370 *have_match = 1;
2371 done:
2372 free(id_str);
2373 free(logmsg);
2374 return err;
2377 static const struct got_error *
2378 queue_commits(struct tog_log_thread_args *a)
2380 const struct got_error *err = NULL;
2383 * We keep all commits open throughout the lifetime of the log
2384 * view in order to avoid having to re-fetch commits from disk
2385 * while updating the display.
2387 do {
2388 struct got_object_id id;
2389 struct got_commit_object *commit;
2390 struct commit_queue_entry *entry;
2391 int limit_match = 0;
2392 int errcode;
2394 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2395 NULL, NULL);
2396 if (err)
2397 break;
2399 err = got_object_open_as_commit(&commit, a->repo, &id);
2400 if (err)
2401 break;
2402 entry = alloc_commit_queue_entry(commit, &id);
2403 if (entry == NULL) {
2404 err = got_error_from_errno("alloc_commit_queue_entry");
2405 break;
2408 errcode = pthread_mutex_lock(&tog_mutex);
2409 if (errcode) {
2410 err = got_error_set_errno(errcode,
2411 "pthread_mutex_lock");
2412 break;
2415 entry->idx = a->real_commits->ncommits;
2416 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2417 a->real_commits->ncommits++;
2419 if (*a->limiting) {
2420 err = match_commit(&limit_match, &id, commit,
2421 a->limit_regex);
2422 if (err)
2423 break;
2425 if (limit_match) {
2426 struct commit_queue_entry *matched;
2428 matched = alloc_commit_queue_entry(
2429 entry->commit, entry->id);
2430 if (matched == NULL) {
2431 err = got_error_from_errno(
2432 "alloc_commit_queue_entry");
2433 break;
2435 matched->commit = entry->commit;
2436 got_object_commit_retain(entry->commit);
2438 matched->idx = a->limit_commits->ncommits;
2439 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2440 matched, entry);
2441 a->limit_commits->ncommits++;
2445 * This is how we signal log_thread() that we
2446 * have found a match, and that it should be
2447 * counted as a new entry for the view.
2449 a->limit_match = limit_match;
2452 if (*a->searching == TOG_SEARCH_FORWARD &&
2453 !*a->search_next_done) {
2454 int have_match;
2455 err = match_commit(&have_match, &id, commit, a->regex);
2456 if (err)
2457 break;
2459 if (*a->limiting) {
2460 if (limit_match && have_match)
2461 *a->search_next_done =
2462 TOG_SEARCH_HAVE_MORE;
2463 } else if (have_match)
2464 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2467 errcode = pthread_mutex_unlock(&tog_mutex);
2468 if (errcode && err == NULL)
2469 err = got_error_set_errno(errcode,
2470 "pthread_mutex_unlock");
2471 if (err)
2472 break;
2473 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2475 return err;
2478 static void
2479 select_commit(struct tog_log_view_state *s)
2481 struct commit_queue_entry *entry;
2482 int ncommits = 0;
2484 entry = s->first_displayed_entry;
2485 while (entry) {
2486 if (ncommits == s->selected) {
2487 s->selected_entry = entry;
2488 break;
2490 entry = TAILQ_NEXT(entry, entry);
2491 ncommits++;
2495 static const struct got_error *
2496 draw_commits(struct tog_view *view)
2498 const struct got_error *err = NULL;
2499 struct tog_log_view_state *s = &view->state.log;
2500 struct commit_queue_entry *entry = s->selected_entry;
2501 int limit = view->nlines;
2502 int width;
2503 int ncommits, author_cols = 4;
2504 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2505 char *refs_str = NULL;
2506 wchar_t *wline;
2507 struct tog_color *tc;
2508 static const size_t date_display_cols = 12;
2510 if (view_is_hsplit_top(view))
2511 --limit; /* account for border */
2513 if (s->selected_entry &&
2514 !(view->searching && view->search_next_done == 0)) {
2515 struct got_reflist_head *refs;
2516 err = got_object_id_str(&id_str, s->selected_entry->id);
2517 if (err)
2518 return err;
2519 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2520 s->selected_entry->id);
2521 if (refs) {
2522 err = build_refs_str(&refs_str, refs,
2523 s->selected_entry->id, s->repo);
2524 if (err)
2525 goto done;
2529 if (s->thread_args.commits_needed == 0)
2530 halfdelay(10); /* disable fast refresh */
2532 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2533 if (asprintf(&ncommits_str, " [%d/%d] %s",
2534 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2535 (view->searching && !view->search_next_done) ?
2536 "searching..." : "loading...") == -1) {
2537 err = got_error_from_errno("asprintf");
2538 goto done;
2540 } else {
2541 const char *search_str = NULL;
2542 const char *limit_str = NULL;
2544 if (view->searching) {
2545 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2546 search_str = "no more matches";
2547 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2548 search_str = "no matches found";
2549 else if (!view->search_next_done)
2550 search_str = "searching...";
2553 if (s->limit_view && s->commits->ncommits == 0)
2554 limit_str = "no matches found";
2556 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2557 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2558 search_str ? search_str : (refs_str ? refs_str : ""),
2559 limit_str ? limit_str : "") == -1) {
2560 err = got_error_from_errno("asprintf");
2561 goto done;
2565 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2566 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2567 "........................................",
2568 s->in_repo_path, ncommits_str) == -1) {
2569 err = got_error_from_errno("asprintf");
2570 header = NULL;
2571 goto done;
2573 } else if (asprintf(&header, "commit %s%s",
2574 id_str ? id_str : "........................................",
2575 ncommits_str) == -1) {
2576 err = got_error_from_errno("asprintf");
2577 header = NULL;
2578 goto done;
2580 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2581 if (err)
2582 goto done;
2584 werase(view->window);
2586 if (view_needs_focus_indication(view))
2587 wstandout(view->window);
2588 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2589 if (tc)
2590 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2591 waddwstr(view->window, wline);
2592 while (width < view->ncols) {
2593 waddch(view->window, ' ');
2594 width++;
2596 if (tc)
2597 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2598 if (view_needs_focus_indication(view))
2599 wstandend(view->window);
2600 free(wline);
2601 if (limit <= 1)
2602 goto done;
2604 /* Grow author column size if necessary, and set view->maxx. */
2605 entry = s->first_displayed_entry;
2606 ncommits = 0;
2607 view->maxx = 0;
2608 while (entry) {
2609 struct got_commit_object *c = entry->commit;
2610 char *author, *eol, *msg, *msg0;
2611 wchar_t *wauthor, *wmsg;
2612 int width;
2613 if (ncommits >= limit - 1)
2614 break;
2615 if (s->use_committer)
2616 author = strdup(got_object_commit_get_committer(c));
2617 else
2618 author = strdup(got_object_commit_get_author(c));
2619 if (author == NULL) {
2620 err = got_error_from_errno("strdup");
2621 goto done;
2623 err = format_author(&wauthor, &width, author, COLS,
2624 date_display_cols);
2625 if (author_cols < width)
2626 author_cols = width;
2627 free(wauthor);
2628 free(author);
2629 if (err)
2630 goto done;
2631 err = got_object_commit_get_logmsg(&msg0, c);
2632 if (err)
2633 goto done;
2634 msg = msg0;
2635 while (*msg == '\n')
2636 ++msg;
2637 if ((eol = strchr(msg, '\n')))
2638 *eol = '\0';
2639 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2640 date_display_cols + author_cols, 0);
2641 if (err)
2642 goto done;
2643 view->maxx = MAX(view->maxx, width);
2644 free(msg0);
2645 free(wmsg);
2646 ncommits++;
2647 entry = TAILQ_NEXT(entry, entry);
2650 entry = s->first_displayed_entry;
2651 s->last_displayed_entry = s->first_displayed_entry;
2652 ncommits = 0;
2653 while (entry) {
2654 if (ncommits >= limit - 1)
2655 break;
2656 if (ncommits == s->selected)
2657 wstandout(view->window);
2658 err = draw_commit(view, entry->commit, entry->id,
2659 date_display_cols, author_cols);
2660 if (ncommits == s->selected)
2661 wstandend(view->window);
2662 if (err)
2663 goto done;
2664 ncommits++;
2665 s->last_displayed_entry = entry;
2666 entry = TAILQ_NEXT(entry, entry);
2669 view_border(view);
2670 done:
2671 free(id_str);
2672 free(refs_str);
2673 free(ncommits_str);
2674 free(header);
2675 return err;
2678 static void
2679 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2681 struct commit_queue_entry *entry;
2682 int nscrolled = 0;
2684 entry = TAILQ_FIRST(&s->commits->head);
2685 if (s->first_displayed_entry == entry)
2686 return;
2688 entry = s->first_displayed_entry;
2689 while (entry && nscrolled < maxscroll) {
2690 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2691 if (entry) {
2692 s->first_displayed_entry = entry;
2693 nscrolled++;
2698 static const struct got_error *
2699 trigger_log_thread(struct tog_view *view, int wait)
2701 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2702 int errcode;
2704 halfdelay(1); /* fast refresh while loading commits */
2706 while (!ta->log_complete && !tog_thread_error &&
2707 (ta->commits_needed > 0 || ta->load_all)) {
2708 /* Wake the log thread. */
2709 errcode = pthread_cond_signal(&ta->need_commits);
2710 if (errcode)
2711 return got_error_set_errno(errcode,
2712 "pthread_cond_signal");
2715 * The mutex will be released while the view loop waits
2716 * in wgetch(), at which time the log thread will run.
2718 if (!wait)
2719 break;
2721 /* Display progress update in log view. */
2722 show_log_view(view);
2723 update_panels();
2724 doupdate();
2726 /* Wait right here while next commit is being loaded. */
2727 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2728 if (errcode)
2729 return got_error_set_errno(errcode,
2730 "pthread_cond_wait");
2732 /* Display progress update in log view. */
2733 show_log_view(view);
2734 update_panels();
2735 doupdate();
2738 return NULL;
2741 static const struct got_error *
2742 request_log_commits(struct tog_view *view)
2744 struct tog_log_view_state *state = &view->state.log;
2745 const struct got_error *err = NULL;
2747 if (state->thread_args.log_complete)
2748 return NULL;
2750 state->thread_args.commits_needed += view->nscrolled;
2751 err = trigger_log_thread(view, 1);
2752 view->nscrolled = 0;
2754 return err;
2757 static const struct got_error *
2758 log_scroll_down(struct tog_view *view, int maxscroll)
2760 struct tog_log_view_state *s = &view->state.log;
2761 const struct got_error *err = NULL;
2762 struct commit_queue_entry *pentry;
2763 int nscrolled = 0, ncommits_needed;
2765 if (s->last_displayed_entry == NULL)
2766 return NULL;
2768 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2769 if (s->commits->ncommits < ncommits_needed &&
2770 !s->thread_args.log_complete) {
2772 * Ask the log thread for required amount of commits.
2774 s->thread_args.commits_needed +=
2775 ncommits_needed - s->commits->ncommits;
2776 err = trigger_log_thread(view, 1);
2777 if (err)
2778 return err;
2781 do {
2782 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2783 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2784 break;
2786 s->last_displayed_entry = pentry ?
2787 pentry : s->last_displayed_entry;
2789 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2790 if (pentry == NULL)
2791 break;
2792 s->first_displayed_entry = pentry;
2793 } while (++nscrolled < maxscroll);
2795 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2796 view->nscrolled += nscrolled;
2797 else
2798 view->nscrolled = 0;
2800 return err;
2803 static const struct got_error *
2804 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2805 struct got_commit_object *commit, struct got_object_id *commit_id,
2806 struct tog_view *log_view, struct got_repository *repo)
2808 const struct got_error *err;
2809 struct got_object_qid *parent_id;
2810 struct tog_view *diff_view;
2812 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2813 if (diff_view == NULL)
2814 return got_error_from_errno("view_open");
2816 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2817 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2818 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2819 if (err == NULL)
2820 *new_view = diff_view;
2821 return err;
2824 static const struct got_error *
2825 tree_view_visit_subtree(struct tog_tree_view_state *s,
2826 struct got_tree_object *subtree)
2828 struct tog_parent_tree *parent;
2830 parent = calloc(1, sizeof(*parent));
2831 if (parent == NULL)
2832 return got_error_from_errno("calloc");
2834 parent->tree = s->tree;
2835 parent->first_displayed_entry = s->first_displayed_entry;
2836 parent->selected_entry = s->selected_entry;
2837 parent->selected = s->selected;
2838 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2839 s->tree = subtree;
2840 s->selected = 0;
2841 s->first_displayed_entry = NULL;
2842 return NULL;
2845 static const struct got_error *
2846 tree_view_walk_path(struct tog_tree_view_state *s,
2847 struct got_commit_object *commit, const char *path)
2849 const struct got_error *err = NULL;
2850 struct got_tree_object *tree = NULL;
2851 const char *p;
2852 char *slash, *subpath = NULL;
2854 /* Walk the path and open corresponding tree objects. */
2855 p = path;
2856 while (*p) {
2857 struct got_tree_entry *te;
2858 struct got_object_id *tree_id;
2859 char *te_name;
2861 while (p[0] == '/')
2862 p++;
2864 /* Ensure the correct subtree entry is selected. */
2865 slash = strchr(p, '/');
2866 if (slash == NULL)
2867 te_name = strdup(p);
2868 else
2869 te_name = strndup(p, slash - p);
2870 if (te_name == NULL) {
2871 err = got_error_from_errno("strndup");
2872 break;
2874 te = got_object_tree_find_entry(s->tree, te_name);
2875 if (te == NULL) {
2876 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2877 free(te_name);
2878 break;
2880 free(te_name);
2881 s->first_displayed_entry = s->selected_entry = te;
2883 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2884 break; /* jump to this file's entry */
2886 slash = strchr(p, '/');
2887 if (slash)
2888 subpath = strndup(path, slash - path);
2889 else
2890 subpath = strdup(path);
2891 if (subpath == NULL) {
2892 err = got_error_from_errno("strdup");
2893 break;
2896 err = got_object_id_by_path(&tree_id, s->repo, commit,
2897 subpath);
2898 if (err)
2899 break;
2901 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2902 free(tree_id);
2903 if (err)
2904 break;
2906 err = tree_view_visit_subtree(s, tree);
2907 if (err) {
2908 got_object_tree_close(tree);
2909 break;
2911 if (slash == NULL)
2912 break;
2913 free(subpath);
2914 subpath = NULL;
2915 p = slash;
2918 free(subpath);
2919 return err;
2922 static const struct got_error *
2923 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2924 struct commit_queue_entry *entry, const char *path,
2925 const char *head_ref_name, struct got_repository *repo)
2927 const struct got_error *err = NULL;
2928 struct tog_tree_view_state *s;
2929 struct tog_view *tree_view;
2931 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2932 if (tree_view == NULL)
2933 return got_error_from_errno("view_open");
2935 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2936 if (err)
2937 return err;
2938 s = &tree_view->state.tree;
2940 *new_view = tree_view;
2942 if (got_path_is_root_dir(path))
2943 return NULL;
2945 return tree_view_walk_path(s, entry->commit, path);
2948 static const struct got_error *
2949 block_signals_used_by_main_thread(void)
2951 sigset_t sigset;
2952 int errcode;
2954 if (sigemptyset(&sigset) == -1)
2955 return got_error_from_errno("sigemptyset");
2957 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2958 if (sigaddset(&sigset, SIGWINCH) == -1)
2959 return got_error_from_errno("sigaddset");
2960 if (sigaddset(&sigset, SIGCONT) == -1)
2961 return got_error_from_errno("sigaddset");
2962 if (sigaddset(&sigset, SIGINT) == -1)
2963 return got_error_from_errno("sigaddset");
2964 if (sigaddset(&sigset, SIGTERM) == -1)
2965 return got_error_from_errno("sigaddset");
2967 /* ncurses handles SIGTSTP */
2968 if (sigaddset(&sigset, SIGTSTP) == -1)
2969 return got_error_from_errno("sigaddset");
2971 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2972 if (errcode)
2973 return got_error_set_errno(errcode, "pthread_sigmask");
2975 return NULL;
2978 static void *
2979 log_thread(void *arg)
2981 const struct got_error *err = NULL;
2982 int errcode = 0;
2983 struct tog_log_thread_args *a = arg;
2984 int done = 0;
2987 * Sync startup with main thread such that we begin our
2988 * work once view_input() has released the mutex.
2990 errcode = pthread_mutex_lock(&tog_mutex);
2991 if (errcode) {
2992 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2993 return (void *)err;
2996 err = block_signals_used_by_main_thread();
2997 if (err) {
2998 pthread_mutex_unlock(&tog_mutex);
2999 goto done;
3002 while (!done && !err && !tog_fatal_signal_received()) {
3003 errcode = pthread_mutex_unlock(&tog_mutex);
3004 if (errcode) {
3005 err = got_error_set_errno(errcode,
3006 "pthread_mutex_unlock");
3007 goto done;
3009 err = queue_commits(a);
3010 if (err) {
3011 if (err->code != GOT_ERR_ITER_COMPLETED)
3012 goto done;
3013 err = NULL;
3014 done = 1;
3015 } else if (a->commits_needed > 0 && !a->load_all) {
3016 if (*a->limiting) {
3017 if (a->limit_match)
3018 a->commits_needed--;
3019 } else
3020 a->commits_needed--;
3023 errcode = pthread_mutex_lock(&tog_mutex);
3024 if (errcode) {
3025 err = got_error_set_errno(errcode,
3026 "pthread_mutex_lock");
3027 goto done;
3028 } else if (*a->quit)
3029 done = 1;
3030 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3031 *a->first_displayed_entry =
3032 TAILQ_FIRST(&a->limit_commits->head);
3033 *a->selected_entry = *a->first_displayed_entry;
3034 } else if (*a->first_displayed_entry == NULL) {
3035 *a->first_displayed_entry =
3036 TAILQ_FIRST(&a->real_commits->head);
3037 *a->selected_entry = *a->first_displayed_entry;
3040 errcode = pthread_cond_signal(&a->commit_loaded);
3041 if (errcode) {
3042 err = got_error_set_errno(errcode,
3043 "pthread_cond_signal");
3044 pthread_mutex_unlock(&tog_mutex);
3045 goto done;
3048 if (done)
3049 a->commits_needed = 0;
3050 else {
3051 if (a->commits_needed == 0 && !a->load_all) {
3052 errcode = pthread_cond_wait(&a->need_commits,
3053 &tog_mutex);
3054 if (errcode) {
3055 err = got_error_set_errno(errcode,
3056 "pthread_cond_wait");
3057 pthread_mutex_unlock(&tog_mutex);
3058 goto done;
3060 if (*a->quit)
3061 done = 1;
3065 a->log_complete = 1;
3066 errcode = pthread_mutex_unlock(&tog_mutex);
3067 if (errcode)
3068 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3069 done:
3070 if (err) {
3071 tog_thread_error = 1;
3072 pthread_cond_signal(&a->commit_loaded);
3074 return (void *)err;
3077 static const struct got_error *
3078 stop_log_thread(struct tog_log_view_state *s)
3080 const struct got_error *err = NULL, *thread_err = NULL;
3081 int errcode;
3083 if (s->thread) {
3084 s->quit = 1;
3085 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3086 if (errcode)
3087 return got_error_set_errno(errcode,
3088 "pthread_cond_signal");
3089 errcode = pthread_mutex_unlock(&tog_mutex);
3090 if (errcode)
3091 return got_error_set_errno(errcode,
3092 "pthread_mutex_unlock");
3093 errcode = pthread_join(s->thread, (void **)&thread_err);
3094 if (errcode)
3095 return got_error_set_errno(errcode, "pthread_join");
3096 errcode = pthread_mutex_lock(&tog_mutex);
3097 if (errcode)
3098 return got_error_set_errno(errcode,
3099 "pthread_mutex_lock");
3100 s->thread = 0; //NULL;
3103 if (s->thread_args.repo) {
3104 err = got_repo_close(s->thread_args.repo);
3105 s->thread_args.repo = NULL;
3108 if (s->thread_args.pack_fds) {
3109 const struct got_error *pack_err =
3110 got_repo_pack_fds_close(s->thread_args.pack_fds);
3111 if (err == NULL)
3112 err = pack_err;
3113 s->thread_args.pack_fds = NULL;
3116 if (s->thread_args.graph) {
3117 got_commit_graph_close(s->thread_args.graph);
3118 s->thread_args.graph = NULL;
3121 return err ? err : thread_err;
3124 static const struct got_error *
3125 close_log_view(struct tog_view *view)
3127 const struct got_error *err = NULL;
3128 struct tog_log_view_state *s = &view->state.log;
3129 int errcode;
3131 err = stop_log_thread(s);
3133 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3134 if (errcode && err == NULL)
3135 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3137 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3138 if (errcode && err == NULL)
3139 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3141 free_commits(&s->limit_commits);
3142 free_commits(&s->real_commits);
3143 free(s->in_repo_path);
3144 s->in_repo_path = NULL;
3145 free(s->start_id);
3146 s->start_id = NULL;
3147 free(s->head_ref_name);
3148 s->head_ref_name = NULL;
3149 return err;
3153 * We use two queues to implement the limit feature: first consists of
3154 * commits matching the current limit_regex; second is the real queue
3155 * of all known commits (real_commits). When the user starts limiting,
3156 * we swap queues such that all movement and displaying functionality
3157 * works with very slight change.
3159 static const struct got_error *
3160 limit_log_view(struct tog_view *view)
3162 struct tog_log_view_state *s = &view->state.log;
3163 struct commit_queue_entry *entry;
3164 struct tog_view *v = view;
3165 const struct got_error *err = NULL;
3166 char pattern[1024];
3167 int ret;
3169 if (view_is_hsplit_top(view))
3170 v = view->child;
3171 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3172 v = view->parent;
3174 /* Get the pattern */
3175 wmove(v->window, v->nlines - 1, 0);
3176 wclrtoeol(v->window);
3177 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3178 nodelay(v->window, FALSE);
3179 nocbreak();
3180 echo();
3181 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3182 cbreak();
3183 noecho();
3184 nodelay(v->window, TRUE);
3185 if (ret == ERR)
3186 return NULL;
3188 if (*pattern == '\0') {
3190 * Safety measure for the situation where the user
3191 * resets limit without previously limiting anything.
3193 if (!s->limit_view)
3194 return NULL;
3197 * User could have pressed Ctrl+L, which refreshed the
3198 * commit queues, it means we can't save previously
3199 * (before limit took place) displayed entries,
3200 * because they would point to already free'ed memory,
3201 * so we are forced to always select first entry of
3202 * the queue.
3204 s->commits = &s->real_commits;
3205 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3206 s->selected_entry = s->first_displayed_entry;
3207 s->selected = 0;
3208 s->limit_view = 0;
3210 return NULL;
3213 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3214 return NULL;
3216 s->limit_view = 1;
3218 /* Clear the screen while loading limit view */
3219 s->first_displayed_entry = NULL;
3220 s->last_displayed_entry = NULL;
3221 s->selected_entry = NULL;
3222 s->commits = &s->limit_commits;
3224 /* Prepare limit queue for new search */
3225 free_commits(&s->limit_commits);
3226 s->limit_commits.ncommits = 0;
3228 /* First process commits, which are in queue already */
3229 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3230 int have_match = 0;
3232 err = match_commit(&have_match, entry->id,
3233 entry->commit, &s->limit_regex);
3234 if (err)
3235 return err;
3237 if (have_match) {
3238 struct commit_queue_entry *matched;
3240 matched = alloc_commit_queue_entry(entry->commit,
3241 entry->id);
3242 if (matched == NULL) {
3243 err = got_error_from_errno(
3244 "alloc_commit_queue_entry");
3245 break;
3247 matched->commit = entry->commit;
3248 got_object_commit_retain(entry->commit);
3250 matched->idx = s->limit_commits.ncommits;
3251 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3252 matched, entry);
3253 s->limit_commits.ncommits++;
3257 /* Second process all the commits, until we fill the screen */
3258 if (s->limit_commits.ncommits < view->nlines - 1 &&
3259 !s->thread_args.log_complete) {
3260 s->thread_args.commits_needed +=
3261 view->nlines - s->limit_commits.ncommits - 1;
3262 err = trigger_log_thread(view, 1);
3263 if (err)
3264 return err;
3267 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3268 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3269 s->selected = 0;
3271 return NULL;
3274 static const struct got_error *
3275 search_start_log_view(struct tog_view *view)
3277 struct tog_log_view_state *s = &view->state.log;
3279 s->matched_entry = NULL;
3280 s->search_entry = NULL;
3281 return NULL;
3284 static const struct got_error *
3285 search_next_log_view(struct tog_view *view)
3287 const struct got_error *err = NULL;
3288 struct tog_log_view_state *s = &view->state.log;
3289 struct commit_queue_entry *entry;
3291 /* Display progress update in log view. */
3292 show_log_view(view);
3293 update_panels();
3294 doupdate();
3296 if (s->search_entry) {
3297 int errcode, ch;
3298 errcode = pthread_mutex_unlock(&tog_mutex);
3299 if (errcode)
3300 return got_error_set_errno(errcode,
3301 "pthread_mutex_unlock");
3302 ch = wgetch(view->window);
3303 errcode = pthread_mutex_lock(&tog_mutex);
3304 if (errcode)
3305 return got_error_set_errno(errcode,
3306 "pthread_mutex_lock");
3307 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3308 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3309 return NULL;
3311 if (view->searching == TOG_SEARCH_FORWARD)
3312 entry = TAILQ_NEXT(s->search_entry, entry);
3313 else
3314 entry = TAILQ_PREV(s->search_entry,
3315 commit_queue_head, entry);
3316 } else if (s->matched_entry) {
3318 * If the user has moved the cursor after we hit a match,
3319 * the position from where we should continue searching
3320 * might have changed.
3322 if (view->searching == TOG_SEARCH_FORWARD)
3323 entry = TAILQ_NEXT(s->selected_entry, entry);
3324 else
3325 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3326 entry);
3327 } else {
3328 entry = s->selected_entry;
3331 while (1) {
3332 int have_match = 0;
3334 if (entry == NULL) {
3335 if (s->thread_args.log_complete ||
3336 view->searching == TOG_SEARCH_BACKWARD) {
3337 view->search_next_done =
3338 (s->matched_entry == NULL ?
3339 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3340 s->search_entry = NULL;
3341 return NULL;
3344 * Poke the log thread for more commits and return,
3345 * allowing the main loop to make progress. Search
3346 * will resume at s->search_entry once we come back.
3348 s->thread_args.commits_needed++;
3349 return trigger_log_thread(view, 0);
3352 err = match_commit(&have_match, entry->id, entry->commit,
3353 &view->regex);
3354 if (err)
3355 break;
3356 if (have_match) {
3357 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3358 s->matched_entry = entry;
3359 break;
3362 s->search_entry = entry;
3363 if (view->searching == TOG_SEARCH_FORWARD)
3364 entry = TAILQ_NEXT(entry, entry);
3365 else
3366 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3369 if (s->matched_entry) {
3370 int cur = s->selected_entry->idx;
3371 while (cur < s->matched_entry->idx) {
3372 err = input_log_view(NULL, view, KEY_DOWN);
3373 if (err)
3374 return err;
3375 cur++;
3377 while (cur > s->matched_entry->idx) {
3378 err = input_log_view(NULL, view, KEY_UP);
3379 if (err)
3380 return err;
3381 cur--;
3385 s->search_entry = NULL;
3387 return NULL;
3390 static const struct got_error *
3391 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3392 struct got_repository *repo, const char *head_ref_name,
3393 const char *in_repo_path, int log_branches)
3395 const struct got_error *err = NULL;
3396 struct tog_log_view_state *s = &view->state.log;
3397 struct got_repository *thread_repo = NULL;
3398 struct got_commit_graph *thread_graph = NULL;
3399 int errcode;
3401 if (in_repo_path != s->in_repo_path) {
3402 free(s->in_repo_path);
3403 s->in_repo_path = strdup(in_repo_path);
3404 if (s->in_repo_path == NULL)
3405 return got_error_from_errno("strdup");
3408 /* The commit queue only contains commits being displayed. */
3409 TAILQ_INIT(&s->real_commits.head);
3410 s->real_commits.ncommits = 0;
3411 s->commits = &s->real_commits;
3413 TAILQ_INIT(&s->limit_commits.head);
3414 s->limit_view = 0;
3415 s->limit_commits.ncommits = 0;
3417 s->repo = repo;
3418 if (head_ref_name) {
3419 s->head_ref_name = strdup(head_ref_name);
3420 if (s->head_ref_name == NULL) {
3421 err = got_error_from_errno("strdup");
3422 goto done;
3425 s->start_id = got_object_id_dup(start_id);
3426 if (s->start_id == NULL) {
3427 err = got_error_from_errno("got_object_id_dup");
3428 goto done;
3430 s->log_branches = log_branches;
3431 s->use_committer = 1;
3433 STAILQ_INIT(&s->colors);
3434 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3435 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3436 get_color_value("TOG_COLOR_COMMIT"));
3437 if (err)
3438 goto done;
3439 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3440 get_color_value("TOG_COLOR_AUTHOR"));
3441 if (err) {
3442 free_colors(&s->colors);
3443 goto done;
3445 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3446 get_color_value("TOG_COLOR_DATE"));
3447 if (err) {
3448 free_colors(&s->colors);
3449 goto done;
3453 view->show = show_log_view;
3454 view->input = input_log_view;
3455 view->resize = resize_log_view;
3456 view->close = close_log_view;
3457 view->search_start = search_start_log_view;
3458 view->search_next = search_next_log_view;
3460 if (s->thread_args.pack_fds == NULL) {
3461 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3462 if (err)
3463 goto done;
3465 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3466 s->thread_args.pack_fds);
3467 if (err)
3468 goto done;
3469 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3470 !s->log_branches);
3471 if (err)
3472 goto done;
3473 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3474 s->repo, NULL, NULL);
3475 if (err)
3476 goto done;
3478 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3479 if (errcode) {
3480 err = got_error_set_errno(errcode, "pthread_cond_init");
3481 goto done;
3483 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3484 if (errcode) {
3485 err = got_error_set_errno(errcode, "pthread_cond_init");
3486 goto done;
3489 s->thread_args.commits_needed = view->nlines;
3490 s->thread_args.graph = thread_graph;
3491 s->thread_args.real_commits = &s->real_commits;
3492 s->thread_args.limit_commits = &s->limit_commits;
3493 s->thread_args.in_repo_path = s->in_repo_path;
3494 s->thread_args.start_id = s->start_id;
3495 s->thread_args.repo = thread_repo;
3496 s->thread_args.log_complete = 0;
3497 s->thread_args.quit = &s->quit;
3498 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3499 s->thread_args.selected_entry = &s->selected_entry;
3500 s->thread_args.searching = &view->searching;
3501 s->thread_args.search_next_done = &view->search_next_done;
3502 s->thread_args.regex = &view->regex;
3503 s->thread_args.limiting = &s->limit_view;
3504 s->thread_args.limit_regex = &s->limit_regex;
3505 s->thread_args.limit_commits = &s->limit_commits;
3506 done:
3507 if (err)
3508 close_log_view(view);
3509 return err;
3512 static const struct got_error *
3513 show_log_view(struct tog_view *view)
3515 const struct got_error *err;
3516 struct tog_log_view_state *s = &view->state.log;
3518 if (s->thread == 0) { //NULL) {
3519 int errcode = pthread_create(&s->thread, NULL, log_thread,
3520 &s->thread_args);
3521 if (errcode)
3522 return got_error_set_errno(errcode, "pthread_create");
3523 if (s->thread_args.commits_needed > 0) {
3524 err = trigger_log_thread(view, 1);
3525 if (err)
3526 return err;
3530 return draw_commits(view);
3533 static void
3534 log_move_cursor_up(struct tog_view *view, int page, int home)
3536 struct tog_log_view_state *s = &view->state.log;
3538 if (s->first_displayed_entry == NULL)
3539 return;
3540 if (s->selected_entry->idx == 0)
3541 view->count = 0;
3543 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3544 || home)
3545 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3547 if (!page && !home && s->selected > 0)
3548 --s->selected;
3549 else
3550 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3552 select_commit(s);
3553 return;
3556 static const struct got_error *
3557 log_move_cursor_down(struct tog_view *view, int page)
3559 struct tog_log_view_state *s = &view->state.log;
3560 const struct got_error *err = NULL;
3561 int eos = view->nlines - 2;
3563 if (s->first_displayed_entry == NULL)
3564 return NULL;
3566 if (s->thread_args.log_complete &&
3567 s->selected_entry->idx >= s->commits->ncommits - 1)
3568 return NULL;
3570 if (view_is_hsplit_top(view))
3571 --eos; /* border consumes the last line */
3573 if (!page) {
3574 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3575 ++s->selected;
3576 else
3577 err = log_scroll_down(view, 1);
3578 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3579 struct commit_queue_entry *entry;
3580 int n;
3582 s->selected = 0;
3583 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3584 s->last_displayed_entry = entry;
3585 for (n = 0; n <= eos; n++) {
3586 if (entry == NULL)
3587 break;
3588 s->first_displayed_entry = entry;
3589 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3591 if (n > 0)
3592 s->selected = n - 1;
3593 } else {
3594 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3595 s->thread_args.log_complete)
3596 s->selected += MIN(page,
3597 s->commits->ncommits - s->selected_entry->idx - 1);
3598 else
3599 err = log_scroll_down(view, page);
3601 if (err)
3602 return err;
3605 * We might necessarily overshoot in horizontal
3606 * splits; if so, select the last displayed commit.
3608 if (s->first_displayed_entry && s->last_displayed_entry) {
3609 s->selected = MIN(s->selected,
3610 s->last_displayed_entry->idx -
3611 s->first_displayed_entry->idx);
3614 select_commit(s);
3616 if (s->thread_args.log_complete &&
3617 s->selected_entry->idx == s->commits->ncommits - 1)
3618 view->count = 0;
3620 return NULL;
3623 static void
3624 view_get_split(struct tog_view *view, int *y, int *x)
3626 *x = 0;
3627 *y = 0;
3629 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3630 if (view->child && view->child->resized_y)
3631 *y = view->child->resized_y;
3632 else if (view->resized_y)
3633 *y = view->resized_y;
3634 else
3635 *y = view_split_begin_y(view->lines);
3636 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3637 if (view->child && view->child->resized_x)
3638 *x = view->child->resized_x;
3639 else if (view->resized_x)
3640 *x = view->resized_x;
3641 else
3642 *x = view_split_begin_x(view->begin_x);
3646 /* Split view horizontally at y and offset view->state->selected line. */
3647 static const struct got_error *
3648 view_init_hsplit(struct tog_view *view, int y)
3650 const struct got_error *err = NULL;
3652 view->nlines = y;
3653 view->ncols = COLS;
3654 err = view_resize(view);
3655 if (err)
3656 return err;
3658 err = offset_selection_down(view);
3660 return err;
3663 static const struct got_error *
3664 log_goto_line(struct tog_view *view, int nlines)
3666 const struct got_error *err = NULL;
3667 struct tog_log_view_state *s = &view->state.log;
3668 int g, idx = s->selected_entry->idx;
3670 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3671 return NULL;
3673 g = view->gline;
3674 view->gline = 0;
3676 if (g >= s->first_displayed_entry->idx + 1 &&
3677 g <= s->last_displayed_entry->idx + 1 &&
3678 g - s->first_displayed_entry->idx - 1 < nlines) {
3679 s->selected = g - s->first_displayed_entry->idx - 1;
3680 select_commit(s);
3681 return NULL;
3684 if (idx + 1 < g) {
3685 err = log_move_cursor_down(view, g - idx - 1);
3686 if (!err && g > s->selected_entry->idx + 1)
3687 err = log_move_cursor_down(view,
3688 g - s->first_displayed_entry->idx - 1);
3689 if (err)
3690 return err;
3691 } else if (idx + 1 > g)
3692 log_move_cursor_up(view, idx - g + 1, 0);
3694 if (g < nlines && s->first_displayed_entry->idx == 0)
3695 s->selected = g - 1;
3697 select_commit(s);
3698 return NULL;
3702 static void
3703 horizontal_scroll_input(struct tog_view *view, int ch)
3706 switch (ch) {
3707 case KEY_LEFT:
3708 case 'h':
3709 view->x -= MIN(view->x, 2);
3710 if (view->x <= 0)
3711 view->count = 0;
3712 break;
3713 case KEY_RIGHT:
3714 case 'l':
3715 if (view->x + view->ncols / 2 < view->maxx)
3716 view->x += 2;
3717 else
3718 view->count = 0;
3719 break;
3720 case '0':
3721 view->x = 0;
3722 break;
3723 case '$':
3724 view->x = MAX(view->maxx - view->ncols / 2, 0);
3725 view->count = 0;
3726 break;
3727 default:
3728 break;
3732 static const struct got_error *
3733 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3735 const struct got_error *err = NULL;
3736 struct tog_log_view_state *s = &view->state.log;
3737 int eos, nscroll;
3739 if (s->thread_args.load_all) {
3740 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3741 s->thread_args.load_all = 0;
3742 else if (s->thread_args.log_complete) {
3743 err = log_move_cursor_down(view, s->commits->ncommits);
3744 s->thread_args.load_all = 0;
3746 if (err)
3747 return err;
3750 eos = nscroll = view->nlines - 1;
3751 if (view_is_hsplit_top(view))
3752 --eos; /* border */
3754 if (view->gline)
3755 return log_goto_line(view, eos);
3757 switch (ch) {
3758 case '&':
3759 err = limit_log_view(view);
3760 break;
3761 case 'q':
3762 s->quit = 1;
3763 break;
3764 case '0':
3765 case '$':
3766 case KEY_RIGHT:
3767 case 'l':
3768 case KEY_LEFT:
3769 case 'h':
3770 horizontal_scroll_input(view, ch);
3771 break;
3772 case 'k':
3773 case KEY_UP:
3774 case '<':
3775 case ',':
3776 case CTRL('p'):
3777 log_move_cursor_up(view, 0, 0);
3778 break;
3779 case 'g':
3780 case '=':
3781 case KEY_HOME:
3782 log_move_cursor_up(view, 0, 1);
3783 view->count = 0;
3784 break;
3785 case CTRL('u'):
3786 case 'u':
3787 nscroll /= 2;
3788 /* FALL THROUGH */
3789 case KEY_PPAGE:
3790 case CTRL('b'):
3791 case 'b':
3792 log_move_cursor_up(view, nscroll, 0);
3793 break;
3794 case 'j':
3795 case KEY_DOWN:
3796 case '>':
3797 case '.':
3798 case CTRL('n'):
3799 err = log_move_cursor_down(view, 0);
3800 break;
3801 case '@':
3802 s->use_committer = !s->use_committer;
3803 view->action = s->use_committer ?
3804 "show committer" : "show commit author";
3805 break;
3806 case 'G':
3807 case '*':
3808 case KEY_END: {
3809 /* We don't know yet how many commits, so we're forced to
3810 * traverse them all. */
3811 view->count = 0;
3812 s->thread_args.load_all = 1;
3813 if (!s->thread_args.log_complete)
3814 return trigger_log_thread(view, 0);
3815 err = log_move_cursor_down(view, s->commits->ncommits);
3816 s->thread_args.load_all = 0;
3817 break;
3819 case CTRL('d'):
3820 case 'd':
3821 nscroll /= 2;
3822 /* FALL THROUGH */
3823 case KEY_NPAGE:
3824 case CTRL('f'):
3825 case 'f':
3826 case ' ':
3827 err = log_move_cursor_down(view, nscroll);
3828 break;
3829 case KEY_RESIZE:
3830 if (s->selected > view->nlines - 2)
3831 s->selected = view->nlines - 2;
3832 if (s->selected > s->commits->ncommits - 1)
3833 s->selected = s->commits->ncommits - 1;
3834 select_commit(s);
3835 if (s->commits->ncommits < view->nlines - 1 &&
3836 !s->thread_args.log_complete) {
3837 s->thread_args.commits_needed += (view->nlines - 1) -
3838 s->commits->ncommits;
3839 err = trigger_log_thread(view, 1);
3841 break;
3842 case KEY_ENTER:
3843 case '\r':
3844 view->count = 0;
3845 if (s->selected_entry == NULL)
3846 break;
3847 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3848 break;
3849 case 'T':
3850 view->count = 0;
3851 if (s->selected_entry == NULL)
3852 break;
3853 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3854 break;
3855 case KEY_BACKSPACE:
3856 case CTRL('l'):
3857 case 'B':
3858 view->count = 0;
3859 if (ch == KEY_BACKSPACE &&
3860 got_path_is_root_dir(s->in_repo_path))
3861 break;
3862 err = stop_log_thread(s);
3863 if (err)
3864 return err;
3865 if (ch == KEY_BACKSPACE) {
3866 char *parent_path;
3867 err = got_path_dirname(&parent_path, s->in_repo_path);
3868 if (err)
3869 return err;
3870 free(s->in_repo_path);
3871 s->in_repo_path = parent_path;
3872 s->thread_args.in_repo_path = s->in_repo_path;
3873 } else if (ch == CTRL('l')) {
3874 struct got_object_id *start_id;
3875 err = got_repo_match_object_id(&start_id, NULL,
3876 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3877 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3878 if (err) {
3879 if (s->head_ref_name == NULL ||
3880 err->code != GOT_ERR_NOT_REF)
3881 return err;
3882 /* Try to cope with deleted references. */
3883 free(s->head_ref_name);
3884 s->head_ref_name = NULL;
3885 err = got_repo_match_object_id(&start_id,
3886 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
3887 &tog_refs, s->repo);
3888 if (err)
3889 return err;
3891 free(s->start_id);
3892 s->start_id = start_id;
3893 s->thread_args.start_id = s->start_id;
3894 } else /* 'B' */
3895 s->log_branches = !s->log_branches;
3897 if (s->thread_args.pack_fds == NULL) {
3898 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3899 if (err)
3900 return err;
3902 err = got_repo_open(&s->thread_args.repo,
3903 got_repo_get_path(s->repo), NULL,
3904 s->thread_args.pack_fds);
3905 if (err)
3906 return err;
3907 tog_free_refs();
3908 err = tog_load_refs(s->repo, 0);
3909 if (err)
3910 return err;
3911 err = got_commit_graph_open(&s->thread_args.graph,
3912 s->in_repo_path, !s->log_branches);
3913 if (err)
3914 return err;
3915 err = got_commit_graph_iter_start(s->thread_args.graph,
3916 s->start_id, s->repo, NULL, NULL);
3917 if (err)
3918 return err;
3919 free_commits(&s->real_commits);
3920 free_commits(&s->limit_commits);
3921 s->first_displayed_entry = NULL;
3922 s->last_displayed_entry = NULL;
3923 s->selected_entry = NULL;
3924 s->selected = 0;
3925 s->thread_args.log_complete = 0;
3926 s->quit = 0;
3927 s->thread_args.commits_needed = view->lines;
3928 s->matched_entry = NULL;
3929 s->search_entry = NULL;
3930 view->offset = 0;
3931 break;
3932 case 'R':
3933 view->count = 0;
3934 err = view_request_new(new_view, view, TOG_VIEW_REF);
3935 break;
3936 default:
3937 view->count = 0;
3938 break;
3941 return err;
3944 static const struct got_error *
3945 apply_unveil(const char *repo_path, const char *worktree_path)
3947 const struct got_error *error;
3949 #ifdef PROFILE
3950 if (unveil("gmon.out", "rwc") != 0)
3951 return got_error_from_errno2("unveil", "gmon.out");
3952 #endif
3953 if (repo_path && unveil(repo_path, "r") != 0)
3954 return got_error_from_errno2("unveil", repo_path);
3956 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3957 return got_error_from_errno2("unveil", worktree_path);
3959 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3960 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3962 error = got_privsep_unveil_exec_helpers();
3963 if (error != NULL)
3964 return error;
3966 if (unveil(NULL, NULL) != 0)
3967 return got_error_from_errno("unveil");
3969 return NULL;
3972 static void
3973 init_curses(void)
3976 * Override default signal handlers before starting ncurses.
3977 * This should prevent ncurses from installing its own
3978 * broken cleanup() signal handler.
3980 signal(SIGWINCH, tog_sigwinch);
3981 signal(SIGPIPE, tog_sigpipe);
3982 signal(SIGCONT, tog_sigcont);
3983 signal(SIGINT, tog_sigint);
3984 signal(SIGTERM, tog_sigterm);
3986 initscr();
3987 cbreak();
3988 halfdelay(1); /* Do fast refresh while initial view is loading. */
3989 noecho();
3990 nonl();
3991 intrflush(stdscr, FALSE);
3992 keypad(stdscr, TRUE);
3993 curs_set(0);
3994 if (getenv("TOG_COLORS") != NULL) {
3995 start_color();
3996 use_default_colors();
4000 static const struct got_error *
4001 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4002 struct got_repository *repo, struct got_worktree *worktree)
4004 const struct got_error *err = NULL;
4006 if (argc == 0) {
4007 *in_repo_path = strdup("/");
4008 if (*in_repo_path == NULL)
4009 return got_error_from_errno("strdup");
4010 return NULL;
4013 if (worktree) {
4014 const char *prefix = got_worktree_get_path_prefix(worktree);
4015 char *p;
4017 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4018 if (err)
4019 return err;
4020 if (asprintf(in_repo_path, "%s%s%s", prefix,
4021 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4022 p) == -1) {
4023 err = got_error_from_errno("asprintf");
4024 *in_repo_path = NULL;
4026 free(p);
4027 } else
4028 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4030 return err;
4033 static const struct got_error *
4034 cmd_log(int argc, char *argv[])
4036 const struct got_error *error;
4037 struct got_repository *repo = NULL;
4038 struct got_worktree *worktree = NULL;
4039 struct got_object_id *start_id = NULL;
4040 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4041 char *start_commit = NULL, *label = NULL;
4042 struct got_reference *ref = NULL;
4043 const char *head_ref_name = NULL;
4044 int ch, log_branches = 0;
4045 struct tog_view *view;
4046 int *pack_fds = NULL;
4048 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4049 switch (ch) {
4050 case 'b':
4051 log_branches = 1;
4052 break;
4053 case 'c':
4054 start_commit = optarg;
4055 break;
4056 case 'r':
4057 repo_path = realpath(optarg, NULL);
4058 if (repo_path == NULL)
4059 return got_error_from_errno2("realpath",
4060 optarg);
4061 break;
4062 default:
4063 usage_log();
4064 /* NOTREACHED */
4068 argc -= optind;
4069 argv += optind;
4071 if (argc > 1)
4072 usage_log();
4074 error = got_repo_pack_fds_open(&pack_fds);
4075 if (error != NULL)
4076 goto done;
4078 if (repo_path == NULL) {
4079 cwd = getcwd(NULL, 0);
4080 if (cwd == NULL)
4081 return got_error_from_errno("getcwd");
4082 error = got_worktree_open(&worktree, cwd);
4083 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4084 goto done;
4085 if (worktree)
4086 repo_path =
4087 strdup(got_worktree_get_repo_path(worktree));
4088 else
4089 repo_path = strdup(cwd);
4090 if (repo_path == NULL) {
4091 error = got_error_from_errno("strdup");
4092 goto done;
4096 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4097 if (error != NULL)
4098 goto done;
4100 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4101 repo, worktree);
4102 if (error)
4103 goto done;
4105 init_curses();
4107 error = apply_unveil(got_repo_get_path(repo),
4108 worktree ? got_worktree_get_root_path(worktree) : NULL);
4109 if (error)
4110 goto done;
4112 /* already loaded by tog_log_with_path()? */
4113 if (TAILQ_EMPTY(&tog_refs)) {
4114 error = tog_load_refs(repo, 0);
4115 if (error)
4116 goto done;
4119 if (start_commit == NULL) {
4120 error = got_repo_match_object_id(&start_id, &label,
4121 worktree ? got_worktree_get_head_ref_name(worktree) :
4122 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4123 if (error)
4124 goto done;
4125 head_ref_name = label;
4126 } else {
4127 error = got_ref_open(&ref, repo, start_commit, 0);
4128 if (error == NULL)
4129 head_ref_name = got_ref_get_name(ref);
4130 else if (error->code != GOT_ERR_NOT_REF)
4131 goto done;
4132 error = got_repo_match_object_id(&start_id, NULL,
4133 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4134 if (error)
4135 goto done;
4138 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4139 if (view == NULL) {
4140 error = got_error_from_errno("view_open");
4141 goto done;
4143 error = open_log_view(view, start_id, repo, head_ref_name,
4144 in_repo_path, log_branches);
4145 if (error)
4146 goto done;
4147 if (worktree) {
4148 /* Release work tree lock. */
4149 got_worktree_close(worktree);
4150 worktree = NULL;
4152 error = view_loop(view);
4153 done:
4154 free(in_repo_path);
4155 free(repo_path);
4156 free(cwd);
4157 free(start_id);
4158 free(label);
4159 if (ref)
4160 got_ref_close(ref);
4161 if (repo) {
4162 const struct got_error *close_err = got_repo_close(repo);
4163 if (error == NULL)
4164 error = close_err;
4166 if (worktree)
4167 got_worktree_close(worktree);
4168 if (pack_fds) {
4169 const struct got_error *pack_err =
4170 got_repo_pack_fds_close(pack_fds);
4171 if (error == NULL)
4172 error = pack_err;
4174 tog_free_refs();
4175 return error;
4178 __dead static void
4179 usage_diff(void)
4181 endwin();
4182 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4183 "object1 object2\n", getprogname());
4184 exit(1);
4187 static int
4188 match_line(const char *line, regex_t *regex, size_t nmatch,
4189 regmatch_t *regmatch)
4191 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4194 static struct tog_color *
4195 match_color(struct tog_colors *colors, const char *line)
4197 struct tog_color *tc = NULL;
4199 STAILQ_FOREACH(tc, colors, entry) {
4200 if (match_line(line, &tc->regex, 0, NULL))
4201 return tc;
4204 return NULL;
4207 static const struct got_error *
4208 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4209 WINDOW *window, int skipcol, regmatch_t *regmatch)
4211 const struct got_error *err = NULL;
4212 char *exstr = NULL;
4213 wchar_t *wline = NULL;
4214 int rme, rms, n, width, scrollx;
4215 int width0 = 0, width1 = 0, width2 = 0;
4216 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4218 *wtotal = 0;
4220 rms = regmatch->rm_so;
4221 rme = regmatch->rm_eo;
4223 err = expand_tab(&exstr, line);
4224 if (err)
4225 return err;
4227 /* Split the line into 3 segments, according to match offsets. */
4228 seg0 = strndup(exstr, rms);
4229 if (seg0 == NULL) {
4230 err = got_error_from_errno("strndup");
4231 goto done;
4233 seg1 = strndup(exstr + rms, rme - rms);
4234 if (seg1 == NULL) {
4235 err = got_error_from_errno("strndup");
4236 goto done;
4238 seg2 = strdup(exstr + rme);
4239 if (seg2 == NULL) {
4240 err = got_error_from_errno("strndup");
4241 goto done;
4244 /* draw up to matched token if we haven't scrolled past it */
4245 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4246 col_tab_align, 1);
4247 if (err)
4248 goto done;
4249 n = MAX(width0 - skipcol, 0);
4250 if (n) {
4251 free(wline);
4252 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4253 wlimit, col_tab_align, 1);
4254 if (err)
4255 goto done;
4256 waddwstr(window, &wline[scrollx]);
4257 wlimit -= width;
4258 *wtotal += width;
4261 if (wlimit > 0) {
4262 int i = 0, w = 0;
4263 size_t wlen;
4265 free(wline);
4266 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4267 col_tab_align, 1);
4268 if (err)
4269 goto done;
4270 wlen = wcslen(wline);
4271 while (i < wlen) {
4272 width = wcwidth(wline[i]);
4273 if (width == -1) {
4274 /* should not happen, tabs are expanded */
4275 err = got_error(GOT_ERR_RANGE);
4276 goto done;
4278 if (width0 + w + width > skipcol)
4279 break;
4280 w += width;
4281 i++;
4283 /* draw (visible part of) matched token (if scrolled into it) */
4284 if (width1 - w > 0) {
4285 wattron(window, A_STANDOUT);
4286 waddwstr(window, &wline[i]);
4287 wattroff(window, A_STANDOUT);
4288 wlimit -= (width1 - w);
4289 *wtotal += (width1 - w);
4293 if (wlimit > 0) { /* draw rest of line */
4294 free(wline);
4295 if (skipcol > width0 + width1) {
4296 err = format_line(&wline, &width2, &scrollx, seg2,
4297 skipcol - (width0 + width1), wlimit,
4298 col_tab_align, 1);
4299 if (err)
4300 goto done;
4301 waddwstr(window, &wline[scrollx]);
4302 } else {
4303 err = format_line(&wline, &width2, NULL, seg2, 0,
4304 wlimit, col_tab_align, 1);
4305 if (err)
4306 goto done;
4307 waddwstr(window, wline);
4309 *wtotal += width2;
4311 done:
4312 free(wline);
4313 free(exstr);
4314 free(seg0);
4315 free(seg1);
4316 free(seg2);
4317 return err;
4320 static int
4321 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4323 FILE *f = NULL;
4324 int *eof, *first, *selected;
4326 if (view->type == TOG_VIEW_DIFF) {
4327 struct tog_diff_view_state *s = &view->state.diff;
4329 first = &s->first_displayed_line;
4330 selected = first;
4331 eof = &s->eof;
4332 f = s->f;
4333 } else if (view->type == TOG_VIEW_HELP) {
4334 struct tog_help_view_state *s = &view->state.help;
4336 first = &s->first_displayed_line;
4337 selected = first;
4338 eof = &s->eof;
4339 f = s->f;
4340 } else if (view->type == TOG_VIEW_BLAME) {
4341 struct tog_blame_view_state *s = &view->state.blame;
4343 first = &s->first_displayed_line;
4344 selected = &s->selected_line;
4345 eof = &s->eof;
4346 f = s->blame.f;
4347 } else
4348 return 0;
4350 /* Center gline in the middle of the page like vi(1). */
4351 if (*lineno < view->gline - (view->nlines - 3) / 2)
4352 return 0;
4353 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4354 rewind(f);
4355 *eof = 0;
4356 *first = 1;
4357 *lineno = 0;
4358 *nprinted = 0;
4359 return 0;
4362 *selected = view->gline <= (view->nlines - 3) / 2 ?
4363 view->gline : (view->nlines - 3) / 2 + 1;
4364 view->gline = 0;
4366 return 1;
4369 static const struct got_error *
4370 draw_file(struct tog_view *view, const char *header)
4372 struct tog_diff_view_state *s = &view->state.diff;
4373 regmatch_t *regmatch = &view->regmatch;
4374 const struct got_error *err;
4375 int nprinted = 0;
4376 char *line;
4377 size_t linesize = 0;
4378 ssize_t linelen;
4379 wchar_t *wline;
4380 int width;
4381 int max_lines = view->nlines;
4382 int nlines = s->nlines;
4383 off_t line_offset;
4385 s->lineno = s->first_displayed_line - 1;
4386 line_offset = s->lines[s->first_displayed_line - 1].offset;
4387 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4388 return got_error_from_errno("fseek");
4390 werase(view->window);
4392 if (view->gline > s->nlines - 1)
4393 view->gline = s->nlines - 1;
4395 if (header) {
4396 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4397 1 : view->gline - (view->nlines - 3) / 2 :
4398 s->lineno + s->selected_line;
4400 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4401 return got_error_from_errno("asprintf");
4402 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4403 0, 0);
4404 free(line);
4405 if (err)
4406 return err;
4408 if (view_needs_focus_indication(view))
4409 wstandout(view->window);
4410 waddwstr(view->window, wline);
4411 free(wline);
4412 wline = NULL;
4413 while (width++ < view->ncols)
4414 waddch(view->window, ' ');
4415 if (view_needs_focus_indication(view))
4416 wstandend(view->window);
4418 if (max_lines <= 1)
4419 return NULL;
4420 max_lines--;
4423 s->eof = 0;
4424 view->maxx = 0;
4425 line = NULL;
4426 while (max_lines > 0 && nprinted < max_lines) {
4427 enum got_diff_line_type linetype;
4428 attr_t attr = 0;
4430 linelen = getline(&line, &linesize, s->f);
4431 if (linelen == -1) {
4432 if (feof(s->f)) {
4433 s->eof = 1;
4434 break;
4436 free(line);
4437 return got_ferror(s->f, GOT_ERR_IO);
4440 if (++s->lineno < s->first_displayed_line)
4441 continue;
4442 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4443 continue;
4444 if (s->lineno == view->hiline)
4445 attr = A_STANDOUT;
4447 /* Set view->maxx based on full line length. */
4448 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4449 view->x ? 1 : 0);
4450 if (err) {
4451 free(line);
4452 return err;
4454 view->maxx = MAX(view->maxx, width);
4455 free(wline);
4456 wline = NULL;
4458 linetype = s->lines[s->lineno].type;
4459 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4460 linetype < GOT_DIFF_LINE_CONTEXT)
4461 attr |= COLOR_PAIR(linetype);
4462 if (attr)
4463 wattron(view->window, attr);
4464 if (s->first_displayed_line + nprinted == s->matched_line &&
4465 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4466 err = add_matched_line(&width, line, view->ncols, 0,
4467 view->window, view->x, regmatch);
4468 if (err) {
4469 free(line);
4470 return err;
4472 } else {
4473 int skip;
4474 err = format_line(&wline, &width, &skip, line,
4475 view->x, view->ncols, 0, view->x ? 1 : 0);
4476 if (err) {
4477 free(line);
4478 return err;
4480 waddwstr(view->window, &wline[skip]);
4481 free(wline);
4482 wline = NULL;
4484 if (s->lineno == view->hiline) {
4485 /* highlight full gline length */
4486 while (width++ < view->ncols)
4487 waddch(view->window, ' ');
4488 } else {
4489 if (width <= view->ncols - 1)
4490 waddch(view->window, '\n');
4492 if (attr)
4493 wattroff(view->window, attr);
4494 if (++nprinted == 1)
4495 s->first_displayed_line = s->lineno;
4497 free(line);
4498 if (nprinted >= 1)
4499 s->last_displayed_line = s->first_displayed_line +
4500 (nprinted - 1);
4501 else
4502 s->last_displayed_line = s->first_displayed_line;
4504 view_border(view);
4506 if (s->eof) {
4507 while (nprinted < view->nlines) {
4508 waddch(view->window, '\n');
4509 nprinted++;
4512 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4513 view->ncols, 0, 0);
4514 if (err) {
4515 return err;
4518 wstandout(view->window);
4519 waddwstr(view->window, wline);
4520 free(wline);
4521 wline = NULL;
4522 wstandend(view->window);
4525 return NULL;
4528 static char *
4529 get_datestr(time_t *time, char *datebuf)
4531 struct tm mytm, *tm;
4532 char *p, *s;
4534 tm = gmtime_r(time, &mytm);
4535 if (tm == NULL)
4536 return NULL;
4537 s = asctime_r(tm, datebuf);
4538 if (s == NULL)
4539 return NULL;
4540 p = strchr(s, '\n');
4541 if (p)
4542 *p = '\0';
4543 return s;
4546 static const struct got_error *
4547 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4548 off_t off, uint8_t type)
4550 struct got_diff_line *p;
4552 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4553 if (p == NULL)
4554 return got_error_from_errno("reallocarray");
4555 *lines = p;
4556 (*lines)[*nlines].offset = off;
4557 (*lines)[*nlines].type = type;
4558 (*nlines)++;
4560 return NULL;
4563 static const struct got_error *
4564 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4565 struct got_diff_line *s_lines, size_t s_nlines)
4567 struct got_diff_line *p;
4568 char buf[BUFSIZ];
4569 size_t i, r;
4571 if (fseeko(src, 0L, SEEK_SET) == -1)
4572 return got_error_from_errno("fseeko");
4574 for (;;) {
4575 r = fread(buf, 1, sizeof(buf), src);
4576 if (r == 0) {
4577 if (ferror(src))
4578 return got_error_from_errno("fread");
4579 if (feof(src))
4580 break;
4582 if (fwrite(buf, 1, r, dst) != r)
4583 return got_ferror(dst, GOT_ERR_IO);
4586 if (s_nlines == 0 && *d_nlines == 0)
4587 return NULL;
4590 * If commit info was in dst, increment line offsets
4591 * of the appended diff content, but skip s_lines[0]
4592 * because offset zero is already in *d_lines.
4594 if (*d_nlines > 0) {
4595 for (i = 1; i < s_nlines; ++i)
4596 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4598 if (s_nlines > 0) {
4599 --s_nlines;
4600 ++s_lines;
4604 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4605 if (p == NULL) {
4606 /* d_lines is freed in close_diff_view() */
4607 return got_error_from_errno("reallocarray");
4610 *d_lines = p;
4612 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4613 *d_nlines += s_nlines;
4615 return NULL;
4618 static const struct got_error *
4619 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4620 struct got_object_id *commit_id, struct got_reflist_head *refs,
4621 struct got_repository *repo, int ignore_ws, int force_text_diff,
4622 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4624 const struct got_error *err = NULL;
4625 char datebuf[26], *datestr;
4626 struct got_commit_object *commit;
4627 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4628 time_t committer_time;
4629 const char *author, *committer;
4630 char *refs_str = NULL;
4631 struct got_pathlist_entry *pe;
4632 off_t outoff = 0;
4633 int n;
4635 if (refs) {
4636 err = build_refs_str(&refs_str, refs, commit_id, repo);
4637 if (err)
4638 return err;
4641 err = got_object_open_as_commit(&commit, repo, commit_id);
4642 if (err)
4643 return err;
4645 err = got_object_id_str(&id_str, commit_id);
4646 if (err) {
4647 err = got_error_from_errno("got_object_id_str");
4648 goto done;
4651 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4652 if (err)
4653 goto done;
4655 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4656 refs_str ? refs_str : "", refs_str ? ")" : "");
4657 if (n < 0) {
4658 err = got_error_from_errno("fprintf");
4659 goto done;
4661 outoff += n;
4662 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4663 if (err)
4664 goto done;
4666 n = fprintf(outfile, "from: %s\n",
4667 got_object_commit_get_author(commit));
4668 if (n < 0) {
4669 err = got_error_from_errno("fprintf");
4670 goto done;
4672 outoff += n;
4673 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4674 if (err)
4675 goto done;
4677 author = got_object_commit_get_author(commit);
4678 committer = got_object_commit_get_committer(commit);
4679 if (strcmp(author, committer) != 0) {
4680 n = fprintf(outfile, "via: %s\n", committer);
4681 if (n < 0) {
4682 err = got_error_from_errno("fprintf");
4683 goto done;
4685 outoff += n;
4686 err = add_line_metadata(lines, nlines, outoff,
4687 GOT_DIFF_LINE_AUTHOR);
4688 if (err)
4689 goto done;
4691 committer_time = got_object_commit_get_committer_time(commit);
4692 datestr = get_datestr(&committer_time, datebuf);
4693 if (datestr) {
4694 n = fprintf(outfile, "date: %s UTC\n", datestr);
4695 if (n < 0) {
4696 err = got_error_from_errno("fprintf");
4697 goto done;
4699 outoff += n;
4700 err = add_line_metadata(lines, nlines, outoff,
4701 GOT_DIFF_LINE_DATE);
4702 if (err)
4703 goto done;
4705 if (got_object_commit_get_nparents(commit) > 1) {
4706 const struct got_object_id_queue *parent_ids;
4707 struct got_object_qid *qid;
4708 int pn = 1;
4709 parent_ids = got_object_commit_get_parent_ids(commit);
4710 STAILQ_FOREACH(qid, parent_ids, entry) {
4711 err = got_object_id_str(&id_str, &qid->id);
4712 if (err)
4713 goto done;
4714 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4715 if (n < 0) {
4716 err = got_error_from_errno("fprintf");
4717 goto done;
4719 outoff += n;
4720 err = add_line_metadata(lines, nlines, outoff,
4721 GOT_DIFF_LINE_META);
4722 if (err)
4723 goto done;
4724 free(id_str);
4725 id_str = NULL;
4729 err = got_object_commit_get_logmsg(&logmsg, commit);
4730 if (err)
4731 goto done;
4732 s = logmsg;
4733 while ((line = strsep(&s, "\n")) != NULL) {
4734 n = fprintf(outfile, "%s\n", line);
4735 if (n < 0) {
4736 err = got_error_from_errno("fprintf");
4737 goto done;
4739 outoff += n;
4740 err = add_line_metadata(lines, nlines, outoff,
4741 GOT_DIFF_LINE_LOGMSG);
4742 if (err)
4743 goto done;
4746 TAILQ_FOREACH(pe, dsa->paths, entry) {
4747 struct got_diff_changed_path *cp = pe->data;
4748 int pad = dsa->max_path_len - pe->path_len + 1;
4750 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4751 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4752 dsa->rm_cols + 1, cp->rm);
4753 if (n < 0) {
4754 err = got_error_from_errno("fprintf");
4755 goto done;
4757 outoff += n;
4758 err = add_line_metadata(lines, nlines, outoff,
4759 GOT_DIFF_LINE_CHANGES);
4760 if (err)
4761 goto done;
4764 fputc('\n', outfile);
4765 outoff++;
4766 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4767 if (err)
4768 goto done;
4770 n = fprintf(outfile,
4771 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4772 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4773 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4774 if (n < 0) {
4775 err = got_error_from_errno("fprintf");
4776 goto done;
4778 outoff += n;
4779 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4780 if (err)
4781 goto done;
4783 fputc('\n', outfile);
4784 outoff++;
4785 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4786 done:
4787 free(id_str);
4788 free(logmsg);
4789 free(refs_str);
4790 got_object_commit_close(commit);
4791 if (err) {
4792 free(*lines);
4793 *lines = NULL;
4794 *nlines = 0;
4796 return err;
4799 static const struct got_error *
4800 create_diff(struct tog_diff_view_state *s)
4802 const struct got_error *err = NULL;
4803 FILE *f = NULL, *tmp_diff_file = NULL;
4804 int obj_type;
4805 struct got_diff_line *lines = NULL;
4806 struct got_pathlist_head changed_paths;
4808 TAILQ_INIT(&changed_paths);
4810 free(s->lines);
4811 s->lines = malloc(sizeof(*s->lines));
4812 if (s->lines == NULL)
4813 return got_error_from_errno("malloc");
4814 s->nlines = 0;
4816 f = got_opentemp();
4817 if (f == NULL) {
4818 err = got_error_from_errno("got_opentemp");
4819 goto done;
4821 tmp_diff_file = got_opentemp();
4822 if (tmp_diff_file == NULL) {
4823 err = got_error_from_errno("got_opentemp");
4824 goto done;
4826 if (s->f && fclose(s->f) == EOF) {
4827 err = got_error_from_errno("fclose");
4828 goto done;
4830 s->f = f;
4832 if (s->id1)
4833 err = got_object_get_type(&obj_type, s->repo, s->id1);
4834 else
4835 err = got_object_get_type(&obj_type, s->repo, s->id2);
4836 if (err)
4837 goto done;
4839 switch (obj_type) {
4840 case GOT_OBJ_TYPE_BLOB:
4841 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4842 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4843 s->label1, s->label2, tog_diff_algo, s->diff_context,
4844 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
4845 s->f);
4846 break;
4847 case GOT_OBJ_TYPE_TREE:
4848 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4849 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4850 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4851 s->force_text_diff, NULL, s->repo, s->f);
4852 break;
4853 case GOT_OBJ_TYPE_COMMIT: {
4854 const struct got_object_id_queue *parent_ids;
4855 struct got_object_qid *pid;
4856 struct got_commit_object *commit2;
4857 struct got_reflist_head *refs;
4858 size_t nlines = 0;
4859 struct got_diffstat_cb_arg dsa = {
4860 0, 0, 0, 0, 0, 0,
4861 &changed_paths,
4862 s->ignore_whitespace,
4863 s->force_text_diff,
4864 tog_diff_algo
4867 lines = malloc(sizeof(*lines));
4868 if (lines == NULL) {
4869 err = got_error_from_errno("malloc");
4870 goto done;
4873 /* build diff first in tmp file then append to commit info */
4874 err = got_diff_objects_as_commits(&lines, &nlines,
4875 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4876 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4877 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
4878 if (err)
4879 break;
4881 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4882 if (err)
4883 goto done;
4884 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4885 /* Show commit info if we're diffing to a parent/root commit. */
4886 if (s->id1 == NULL) {
4887 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4888 refs, s->repo, s->ignore_whitespace,
4889 s->force_text_diff, &dsa, s->f);
4890 if (err)
4891 goto done;
4892 } else {
4893 parent_ids = got_object_commit_get_parent_ids(commit2);
4894 STAILQ_FOREACH(pid, parent_ids, entry) {
4895 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4896 err = write_commit_info(&s->lines,
4897 &s->nlines, s->id2, refs, s->repo,
4898 s->ignore_whitespace,
4899 s->force_text_diff, &dsa, s->f);
4900 if (err)
4901 goto done;
4902 break;
4906 got_object_commit_close(commit2);
4908 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
4909 lines, nlines);
4910 break;
4912 default:
4913 err = got_error(GOT_ERR_OBJ_TYPE);
4914 break;
4916 done:
4917 free(lines);
4918 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4919 if (s->f && fflush(s->f) != 0 && err == NULL)
4920 err = got_error_from_errno("fflush");
4921 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
4922 err = got_error_from_errno("fclose");
4923 return err;
4926 static void
4927 diff_view_indicate_progress(struct tog_view *view)
4929 mvwaddstr(view->window, 0, 0, "diffing...");
4930 update_panels();
4931 doupdate();
4934 static const struct got_error *
4935 search_start_diff_view(struct tog_view *view)
4937 struct tog_diff_view_state *s = &view->state.diff;
4939 s->matched_line = 0;
4940 return NULL;
4943 static void
4944 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4945 size_t *nlines, int **first, int **last, int **match, int **selected)
4947 struct tog_diff_view_state *s = &view->state.diff;
4949 *f = s->f;
4950 *nlines = s->nlines;
4951 *line_offsets = NULL;
4952 *match = &s->matched_line;
4953 *first = &s->first_displayed_line;
4954 *last = &s->last_displayed_line;
4955 *selected = &s->selected_line;
4958 static const struct got_error *
4959 search_next_view_match(struct tog_view *view)
4961 const struct got_error *err = NULL;
4962 FILE *f;
4963 int lineno;
4964 char *line = NULL;
4965 size_t linesize = 0;
4966 ssize_t linelen;
4967 off_t *line_offsets;
4968 size_t nlines = 0;
4969 int *first, *last, *match, *selected;
4971 if (!view->search_setup)
4972 return got_error_msg(GOT_ERR_NOT_IMPL,
4973 "view search not supported");
4974 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4975 &match, &selected);
4977 if (!view->searching) {
4978 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4979 return NULL;
4982 if (*match) {
4983 if (view->searching == TOG_SEARCH_FORWARD)
4984 lineno = *match + 1;
4985 else
4986 lineno = *match - 1;
4987 } else
4988 lineno = *first - 1 + *selected;
4990 while (1) {
4991 off_t offset;
4993 if (lineno <= 0 || lineno > nlines) {
4994 if (*match == 0) {
4995 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4996 break;
4999 if (view->searching == TOG_SEARCH_FORWARD)
5000 lineno = 1;
5001 else
5002 lineno = nlines;
5005 offset = view->type == TOG_VIEW_DIFF ?
5006 view->state.diff.lines[lineno - 1].offset :
5007 line_offsets[lineno - 1];
5008 if (fseeko(f, offset, SEEK_SET) != 0) {
5009 free(line);
5010 return got_error_from_errno("fseeko");
5012 linelen = getline(&line, &linesize, f);
5013 if (linelen != -1) {
5014 char *exstr;
5015 err = expand_tab(&exstr, line);
5016 if (err)
5017 break;
5018 if (match_line(exstr, &view->regex, 1,
5019 &view->regmatch)) {
5020 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5021 *match = lineno;
5022 free(exstr);
5023 break;
5025 free(exstr);
5027 if (view->searching == TOG_SEARCH_FORWARD)
5028 lineno++;
5029 else
5030 lineno--;
5032 free(line);
5034 if (*match) {
5035 *first = *match;
5036 *selected = 1;
5039 return err;
5042 static const struct got_error *
5043 close_diff_view(struct tog_view *view)
5045 const struct got_error *err = NULL;
5046 struct tog_diff_view_state *s = &view->state.diff;
5048 free(s->id1);
5049 s->id1 = NULL;
5050 free(s->id2);
5051 s->id2 = NULL;
5052 if (s->f && fclose(s->f) == EOF)
5053 err = got_error_from_errno("fclose");
5054 s->f = NULL;
5055 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5056 err = got_error_from_errno("fclose");
5057 s->f1 = NULL;
5058 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5059 err = got_error_from_errno("fclose");
5060 s->f2 = NULL;
5061 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5062 err = got_error_from_errno("close");
5063 s->fd1 = -1;
5064 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5065 err = got_error_from_errno("close");
5066 s->fd2 = -1;
5067 free(s->lines);
5068 s->lines = NULL;
5069 s->nlines = 0;
5070 return err;
5073 static const struct got_error *
5074 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5075 struct got_object_id *id2, const char *label1, const char *label2,
5076 int diff_context, int ignore_whitespace, int force_text_diff,
5077 struct tog_view *parent_view, struct got_repository *repo)
5079 const struct got_error *err;
5080 struct tog_diff_view_state *s = &view->state.diff;
5082 memset(s, 0, sizeof(*s));
5083 s->fd1 = -1;
5084 s->fd2 = -1;
5086 if (id1 != NULL && id2 != NULL) {
5087 int type1, type2;
5088 err = got_object_get_type(&type1, repo, id1);
5089 if (err)
5090 return err;
5091 err = got_object_get_type(&type2, repo, id2);
5092 if (err)
5093 return err;
5095 if (type1 != type2)
5096 return got_error(GOT_ERR_OBJ_TYPE);
5098 s->first_displayed_line = 1;
5099 s->last_displayed_line = view->nlines;
5100 s->selected_line = 1;
5101 s->repo = repo;
5102 s->id1 = id1;
5103 s->id2 = id2;
5104 s->label1 = label1;
5105 s->label2 = label2;
5107 if (id1) {
5108 s->id1 = got_object_id_dup(id1);
5109 if (s->id1 == NULL)
5110 return got_error_from_errno("got_object_id_dup");
5111 } else
5112 s->id1 = NULL;
5114 s->id2 = got_object_id_dup(id2);
5115 if (s->id2 == NULL) {
5116 err = got_error_from_errno("got_object_id_dup");
5117 goto done;
5120 s->f1 = got_opentemp();
5121 if (s->f1 == NULL) {
5122 err = got_error_from_errno("got_opentemp");
5123 goto done;
5126 s->f2 = got_opentemp();
5127 if (s->f2 == NULL) {
5128 err = got_error_from_errno("got_opentemp");
5129 goto done;
5132 s->fd1 = got_opentempfd();
5133 if (s->fd1 == -1) {
5134 err = got_error_from_errno("got_opentempfd");
5135 goto done;
5138 s->fd2 = got_opentempfd();
5139 if (s->fd2 == -1) {
5140 err = got_error_from_errno("got_opentempfd");
5141 goto done;
5144 s->diff_context = diff_context;
5145 s->ignore_whitespace = ignore_whitespace;
5146 s->force_text_diff = force_text_diff;
5147 s->parent_view = parent_view;
5148 s->repo = repo;
5150 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5151 int rc;
5153 rc = init_pair(GOT_DIFF_LINE_MINUS,
5154 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5155 if (rc != ERR)
5156 rc = init_pair(GOT_DIFF_LINE_PLUS,
5157 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5158 if (rc != ERR)
5159 rc = init_pair(GOT_DIFF_LINE_HUNK,
5160 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5161 if (rc != ERR)
5162 rc = init_pair(GOT_DIFF_LINE_META,
5163 get_color_value("TOG_COLOR_DIFF_META"), -1);
5164 if (rc != ERR)
5165 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5166 get_color_value("TOG_COLOR_DIFF_META"), -1);
5167 if (rc != ERR)
5168 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5169 get_color_value("TOG_COLOR_DIFF_META"), -1);
5170 if (rc != ERR)
5171 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5172 get_color_value("TOG_COLOR_DIFF_META"), -1);
5173 if (rc != ERR)
5174 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5175 get_color_value("TOG_COLOR_AUTHOR"), -1);
5176 if (rc != ERR)
5177 rc = init_pair(GOT_DIFF_LINE_DATE,
5178 get_color_value("TOG_COLOR_DATE"), -1);
5179 if (rc == ERR) {
5180 err = got_error(GOT_ERR_RANGE);
5181 goto done;
5185 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5186 view_is_splitscreen(view))
5187 show_log_view(parent_view); /* draw border */
5188 diff_view_indicate_progress(view);
5190 err = create_diff(s);
5192 view->show = show_diff_view;
5193 view->input = input_diff_view;
5194 view->reset = reset_diff_view;
5195 view->close = close_diff_view;
5196 view->search_start = search_start_diff_view;
5197 view->search_setup = search_setup_diff_view;
5198 view->search_next = search_next_view_match;
5199 done:
5200 if (err)
5201 close_diff_view(view);
5202 return err;
5205 static const struct got_error *
5206 show_diff_view(struct tog_view *view)
5208 const struct got_error *err;
5209 struct tog_diff_view_state *s = &view->state.diff;
5210 char *id_str1 = NULL, *id_str2, *header;
5211 const char *label1, *label2;
5213 if (s->id1) {
5214 err = got_object_id_str(&id_str1, s->id1);
5215 if (err)
5216 return err;
5217 label1 = s->label1 ? s->label1 : id_str1;
5218 } else
5219 label1 = "/dev/null";
5221 err = got_object_id_str(&id_str2, s->id2);
5222 if (err)
5223 return err;
5224 label2 = s->label2 ? s->label2 : id_str2;
5226 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5227 err = got_error_from_errno("asprintf");
5228 free(id_str1);
5229 free(id_str2);
5230 return err;
5232 free(id_str1);
5233 free(id_str2);
5235 err = draw_file(view, header);
5236 free(header);
5237 return err;
5240 static const struct got_error *
5241 set_selected_commit(struct tog_diff_view_state *s,
5242 struct commit_queue_entry *entry)
5244 const struct got_error *err;
5245 const struct got_object_id_queue *parent_ids;
5246 struct got_commit_object *selected_commit;
5247 struct got_object_qid *pid;
5249 free(s->id2);
5250 s->id2 = got_object_id_dup(entry->id);
5251 if (s->id2 == NULL)
5252 return got_error_from_errno("got_object_id_dup");
5254 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5255 if (err)
5256 return err;
5257 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5258 free(s->id1);
5259 pid = STAILQ_FIRST(parent_ids);
5260 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5261 got_object_commit_close(selected_commit);
5262 return NULL;
5265 static const struct got_error *
5266 reset_diff_view(struct tog_view *view)
5268 struct tog_diff_view_state *s = &view->state.diff;
5270 view->count = 0;
5271 wclear(view->window);
5272 s->first_displayed_line = 1;
5273 s->last_displayed_line = view->nlines;
5274 s->matched_line = 0;
5275 diff_view_indicate_progress(view);
5276 return create_diff(s);
5279 static void
5280 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5282 int start, i;
5284 i = start = s->first_displayed_line - 1;
5286 while (s->lines[i].type != type) {
5287 if (i == 0)
5288 i = s->nlines - 1;
5289 if (--i == start)
5290 return; /* do nothing, requested type not in file */
5293 s->selected_line = 1;
5294 s->first_displayed_line = i;
5297 static void
5298 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5300 int start, i;
5302 i = start = s->first_displayed_line + 1;
5304 while (s->lines[i].type != type) {
5305 if (i == s->nlines - 1)
5306 i = 0;
5307 if (++i == start)
5308 return; /* do nothing, requested type not in file */
5311 s->selected_line = 1;
5312 s->first_displayed_line = i;
5315 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5316 int, int, int);
5317 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5318 int, int);
5320 static const struct got_error *
5321 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5323 const struct got_error *err = NULL;
5324 struct tog_diff_view_state *s = &view->state.diff;
5325 struct tog_log_view_state *ls;
5326 struct commit_queue_entry *old_selected_entry;
5327 char *line = NULL;
5328 size_t linesize = 0;
5329 ssize_t linelen;
5330 int i, nscroll = view->nlines - 1, up = 0;
5332 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5334 switch (ch) {
5335 case '0':
5336 case '$':
5337 case KEY_RIGHT:
5338 case 'l':
5339 case KEY_LEFT:
5340 case 'h':
5341 horizontal_scroll_input(view, ch);
5342 break;
5343 case 'a':
5344 case 'w':
5345 if (ch == 'a') {
5346 s->force_text_diff = !s->force_text_diff;
5347 view->action = s->force_text_diff ?
5348 "force ASCII text enabled" :
5349 "force ASCII text disabled";
5351 else if (ch == 'w') {
5352 s->ignore_whitespace = !s->ignore_whitespace;
5353 view->action = s->ignore_whitespace ?
5354 "ignore whitespace enabled" :
5355 "ignore whitespace disabled";
5357 err = reset_diff_view(view);
5358 break;
5359 case 'g':
5360 case KEY_HOME:
5361 s->first_displayed_line = 1;
5362 view->count = 0;
5363 break;
5364 case 'G':
5365 case KEY_END:
5366 view->count = 0;
5367 if (s->eof)
5368 break;
5370 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5371 s->eof = 1;
5372 break;
5373 case 'k':
5374 case KEY_UP:
5375 case CTRL('p'):
5376 if (s->first_displayed_line > 1)
5377 s->first_displayed_line--;
5378 else
5379 view->count = 0;
5380 break;
5381 case CTRL('u'):
5382 case 'u':
5383 nscroll /= 2;
5384 /* FALL THROUGH */
5385 case KEY_PPAGE:
5386 case CTRL('b'):
5387 case 'b':
5388 if (s->first_displayed_line == 1) {
5389 view->count = 0;
5390 break;
5392 i = 0;
5393 while (i++ < nscroll && s->first_displayed_line > 1)
5394 s->first_displayed_line--;
5395 break;
5396 case 'j':
5397 case KEY_DOWN:
5398 case CTRL('n'):
5399 if (!s->eof)
5400 s->first_displayed_line++;
5401 else
5402 view->count = 0;
5403 break;
5404 case CTRL('d'):
5405 case 'd':
5406 nscroll /= 2;
5407 /* FALL THROUGH */
5408 case KEY_NPAGE:
5409 case CTRL('f'):
5410 case 'f':
5411 case ' ':
5412 if (s->eof) {
5413 view->count = 0;
5414 break;
5416 i = 0;
5417 while (!s->eof && i++ < nscroll) {
5418 linelen = getline(&line, &linesize, s->f);
5419 s->first_displayed_line++;
5420 if (linelen == -1) {
5421 if (feof(s->f)) {
5422 s->eof = 1;
5423 } else
5424 err = got_ferror(s->f, GOT_ERR_IO);
5425 break;
5428 free(line);
5429 break;
5430 case '(':
5431 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5432 break;
5433 case ')':
5434 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5435 break;
5436 case '{':
5437 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5438 break;
5439 case '}':
5440 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5441 break;
5442 case '[':
5443 if (s->diff_context > 0) {
5444 s->diff_context--;
5445 s->matched_line = 0;
5446 diff_view_indicate_progress(view);
5447 err = create_diff(s);
5448 if (s->first_displayed_line + view->nlines - 1 >
5449 s->nlines) {
5450 s->first_displayed_line = 1;
5451 s->last_displayed_line = view->nlines;
5453 } else
5454 view->count = 0;
5455 break;
5456 case ']':
5457 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5458 s->diff_context++;
5459 s->matched_line = 0;
5460 diff_view_indicate_progress(view);
5461 err = create_diff(s);
5462 } else
5463 view->count = 0;
5464 break;
5465 case '<':
5466 case ',':
5467 case 'K':
5468 up = 1;
5469 /* FALL THROUGH */
5470 case '>':
5471 case '.':
5472 case 'J':
5473 if (s->parent_view == NULL) {
5474 view->count = 0;
5475 break;
5477 s->parent_view->count = view->count;
5479 if (s->parent_view->type == TOG_VIEW_LOG) {
5480 ls = &s->parent_view->state.log;
5481 old_selected_entry = ls->selected_entry;
5483 err = input_log_view(NULL, s->parent_view,
5484 up ? KEY_UP : KEY_DOWN);
5485 if (err)
5486 break;
5487 view->count = s->parent_view->count;
5489 if (old_selected_entry == ls->selected_entry)
5490 break;
5492 err = set_selected_commit(s, ls->selected_entry);
5493 if (err)
5494 break;
5495 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5496 struct tog_blame_view_state *bs;
5497 struct got_object_id *id, *prev_id;
5499 bs = &s->parent_view->state.blame;
5500 prev_id = get_annotation_for_line(bs->blame.lines,
5501 bs->blame.nlines, bs->last_diffed_line);
5503 err = input_blame_view(&view, s->parent_view,
5504 up ? KEY_UP : KEY_DOWN);
5505 if (err)
5506 break;
5507 view->count = s->parent_view->count;
5509 if (prev_id == NULL)
5510 break;
5511 id = get_selected_commit_id(bs->blame.lines,
5512 bs->blame.nlines, bs->first_displayed_line,
5513 bs->selected_line);
5514 if (id == NULL)
5515 break;
5517 if (!got_object_id_cmp(prev_id, id))
5518 break;
5520 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5521 if (err)
5522 break;
5524 s->first_displayed_line = 1;
5525 s->last_displayed_line = view->nlines;
5526 s->matched_line = 0;
5527 view->x = 0;
5529 diff_view_indicate_progress(view);
5530 err = create_diff(s);
5531 break;
5532 default:
5533 view->count = 0;
5534 break;
5537 return err;
5540 static const struct got_error *
5541 cmd_diff(int argc, char *argv[])
5543 const struct got_error *error = NULL;
5544 struct got_repository *repo = NULL;
5545 struct got_worktree *worktree = NULL;
5546 struct got_object_id *id1 = NULL, *id2 = NULL;
5547 char *repo_path = NULL, *cwd = NULL;
5548 char *id_str1 = NULL, *id_str2 = NULL;
5549 char *label1 = NULL, *label2 = NULL;
5550 int diff_context = 3, ignore_whitespace = 0;
5551 int ch, force_text_diff = 0;
5552 const char *errstr;
5553 struct tog_view *view;
5554 int *pack_fds = NULL;
5556 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5557 switch (ch) {
5558 case 'a':
5559 force_text_diff = 1;
5560 break;
5561 case 'C':
5562 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5563 &errstr);
5564 if (errstr != NULL)
5565 errx(1, "number of context lines is %s: %s",
5566 errstr, errstr);
5567 break;
5568 case 'r':
5569 repo_path = realpath(optarg, NULL);
5570 if (repo_path == NULL)
5571 return got_error_from_errno2("realpath",
5572 optarg);
5573 got_path_strip_trailing_slashes(repo_path);
5574 break;
5575 case 'w':
5576 ignore_whitespace = 1;
5577 break;
5578 default:
5579 usage_diff();
5580 /* NOTREACHED */
5584 argc -= optind;
5585 argv += optind;
5587 if (argc == 0) {
5588 usage_diff(); /* TODO show local worktree changes */
5589 } else if (argc == 2) {
5590 id_str1 = argv[0];
5591 id_str2 = argv[1];
5592 } else
5593 usage_diff();
5595 error = got_repo_pack_fds_open(&pack_fds);
5596 if (error)
5597 goto done;
5599 if (repo_path == NULL) {
5600 cwd = getcwd(NULL, 0);
5601 if (cwd == NULL)
5602 return got_error_from_errno("getcwd");
5603 error = got_worktree_open(&worktree, cwd);
5604 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5605 goto done;
5606 if (worktree)
5607 repo_path =
5608 strdup(got_worktree_get_repo_path(worktree));
5609 else
5610 repo_path = strdup(cwd);
5611 if (repo_path == NULL) {
5612 error = got_error_from_errno("strdup");
5613 goto done;
5617 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5618 if (error)
5619 goto done;
5621 init_curses();
5623 error = apply_unveil(got_repo_get_path(repo), NULL);
5624 if (error)
5625 goto done;
5627 error = tog_load_refs(repo, 0);
5628 if (error)
5629 goto done;
5631 error = got_repo_match_object_id(&id1, &label1, id_str1,
5632 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5633 if (error)
5634 goto done;
5636 error = got_repo_match_object_id(&id2, &label2, id_str2,
5637 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5638 if (error)
5639 goto done;
5641 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5642 if (view == NULL) {
5643 error = got_error_from_errno("view_open");
5644 goto done;
5646 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5647 ignore_whitespace, force_text_diff, NULL, repo);
5648 if (error)
5649 goto done;
5650 error = view_loop(view);
5651 done:
5652 free(label1);
5653 free(label2);
5654 free(repo_path);
5655 free(cwd);
5656 if (repo) {
5657 const struct got_error *close_err = got_repo_close(repo);
5658 if (error == NULL)
5659 error = close_err;
5661 if (worktree)
5662 got_worktree_close(worktree);
5663 if (pack_fds) {
5664 const struct got_error *pack_err =
5665 got_repo_pack_fds_close(pack_fds);
5666 if (error == NULL)
5667 error = pack_err;
5669 tog_free_refs();
5670 return error;
5673 __dead static void
5674 usage_blame(void)
5676 endwin();
5677 fprintf(stderr,
5678 "usage: %s blame [-c commit] [-r repository-path] path\n",
5679 getprogname());
5680 exit(1);
5683 struct tog_blame_line {
5684 int annotated;
5685 struct got_object_id *id;
5688 static const struct got_error *
5689 draw_blame(struct tog_view *view)
5691 struct tog_blame_view_state *s = &view->state.blame;
5692 struct tog_blame *blame = &s->blame;
5693 regmatch_t *regmatch = &view->regmatch;
5694 const struct got_error *err;
5695 int lineno = 0, nprinted = 0;
5696 char *line = NULL;
5697 size_t linesize = 0;
5698 ssize_t linelen;
5699 wchar_t *wline;
5700 int width;
5701 struct tog_blame_line *blame_line;
5702 struct got_object_id *prev_id = NULL;
5703 char *id_str;
5704 struct tog_color *tc;
5706 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5707 if (err)
5708 return err;
5710 rewind(blame->f);
5711 werase(view->window);
5713 if (asprintf(&line, "commit %s", id_str) == -1) {
5714 err = got_error_from_errno("asprintf");
5715 free(id_str);
5716 return err;
5719 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5720 free(line);
5721 line = NULL;
5722 if (err)
5723 return err;
5724 if (view_needs_focus_indication(view))
5725 wstandout(view->window);
5726 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5727 if (tc)
5728 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5729 waddwstr(view->window, wline);
5730 while (width++ < view->ncols)
5731 waddch(view->window, ' ');
5732 if (tc)
5733 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5734 if (view_needs_focus_indication(view))
5735 wstandend(view->window);
5736 free(wline);
5737 wline = NULL;
5739 if (view->gline > blame->nlines)
5740 view->gline = blame->nlines;
5742 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5743 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5744 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5745 free(id_str);
5746 return got_error_from_errno("asprintf");
5748 free(id_str);
5749 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5750 free(line);
5751 line = NULL;
5752 if (err)
5753 return err;
5754 waddwstr(view->window, wline);
5755 free(wline);
5756 wline = NULL;
5757 if (width < view->ncols - 1)
5758 waddch(view->window, '\n');
5760 s->eof = 0;
5761 view->maxx = 0;
5762 while (nprinted < view->nlines - 2) {
5763 linelen = getline(&line, &linesize, blame->f);
5764 if (linelen == -1) {
5765 if (feof(blame->f)) {
5766 s->eof = 1;
5767 break;
5769 free(line);
5770 return got_ferror(blame->f, GOT_ERR_IO);
5772 if (++lineno < s->first_displayed_line)
5773 continue;
5774 if (view->gline && !gotoline(view, &lineno, &nprinted))
5775 continue;
5777 /* Set view->maxx based on full line length. */
5778 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5779 if (err) {
5780 free(line);
5781 return err;
5783 free(wline);
5784 wline = NULL;
5785 view->maxx = MAX(view->maxx, width);
5787 if (nprinted == s->selected_line - 1)
5788 wstandout(view->window);
5790 if (blame->nlines > 0) {
5791 blame_line = &blame->lines[lineno - 1];
5792 if (blame_line->annotated && prev_id &&
5793 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5794 !(nprinted == s->selected_line - 1)) {
5795 waddstr(view->window, " ");
5796 } else if (blame_line->annotated) {
5797 char *id_str;
5798 err = got_object_id_str(&id_str,
5799 blame_line->id);
5800 if (err) {
5801 free(line);
5802 return err;
5804 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5805 if (tc)
5806 wattr_on(view->window,
5807 COLOR_PAIR(tc->colorpair), NULL);
5808 wprintw(view->window, "%.8s", id_str);
5809 if (tc)
5810 wattr_off(view->window,
5811 COLOR_PAIR(tc->colorpair), NULL);
5812 free(id_str);
5813 prev_id = blame_line->id;
5814 } else {
5815 waddstr(view->window, "........");
5816 prev_id = NULL;
5818 } else {
5819 waddstr(view->window, "........");
5820 prev_id = NULL;
5823 if (nprinted == s->selected_line - 1)
5824 wstandend(view->window);
5825 waddstr(view->window, " ");
5827 if (view->ncols <= 9) {
5828 width = 9;
5829 } else if (s->first_displayed_line + nprinted ==
5830 s->matched_line &&
5831 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5832 err = add_matched_line(&width, line, view->ncols - 9, 9,
5833 view->window, view->x, regmatch);
5834 if (err) {
5835 free(line);
5836 return err;
5838 width += 9;
5839 } else {
5840 int skip;
5841 err = format_line(&wline, &width, &skip, line,
5842 view->x, view->ncols - 9, 9, 1);
5843 if (err) {
5844 free(line);
5845 return err;
5847 waddwstr(view->window, &wline[skip]);
5848 width += 9;
5849 free(wline);
5850 wline = NULL;
5853 if (width <= view->ncols - 1)
5854 waddch(view->window, '\n');
5855 if (++nprinted == 1)
5856 s->first_displayed_line = lineno;
5858 free(line);
5859 s->last_displayed_line = lineno;
5861 view_border(view);
5863 return NULL;
5866 static const struct got_error *
5867 blame_cb(void *arg, int nlines, int lineno,
5868 struct got_commit_object *commit, struct got_object_id *id)
5870 const struct got_error *err = NULL;
5871 struct tog_blame_cb_args *a = arg;
5872 struct tog_blame_line *line;
5873 int errcode;
5875 if (nlines != a->nlines ||
5876 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5877 return got_error(GOT_ERR_RANGE);
5879 errcode = pthread_mutex_lock(&tog_mutex);
5880 if (errcode)
5881 return got_error_set_errno(errcode, "pthread_mutex_lock");
5883 if (*a->quit) { /* user has quit the blame view */
5884 err = got_error(GOT_ERR_ITER_COMPLETED);
5885 goto done;
5888 if (lineno == -1)
5889 goto done; /* no change in this commit */
5891 line = &a->lines[lineno - 1];
5892 if (line->annotated)
5893 goto done;
5895 line->id = got_object_id_dup(id);
5896 if (line->id == NULL) {
5897 err = got_error_from_errno("got_object_id_dup");
5898 goto done;
5900 line->annotated = 1;
5901 done:
5902 errcode = pthread_mutex_unlock(&tog_mutex);
5903 if (errcode)
5904 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5905 return err;
5908 static void *
5909 blame_thread(void *arg)
5911 const struct got_error *err, *close_err;
5912 struct tog_blame_thread_args *ta = arg;
5913 struct tog_blame_cb_args *a = ta->cb_args;
5914 int errcode, fd1 = -1, fd2 = -1;
5915 FILE *f1 = NULL, *f2 = NULL;
5917 fd1 = got_opentempfd();
5918 if (fd1 == -1)
5919 return (void *)got_error_from_errno("got_opentempfd");
5921 fd2 = got_opentempfd();
5922 if (fd2 == -1) {
5923 err = got_error_from_errno("got_opentempfd");
5924 goto done;
5927 f1 = got_opentemp();
5928 if (f1 == NULL) {
5929 err = (void *)got_error_from_errno("got_opentemp");
5930 goto done;
5932 f2 = got_opentemp();
5933 if (f2 == NULL) {
5934 err = (void *)got_error_from_errno("got_opentemp");
5935 goto done;
5938 err = block_signals_used_by_main_thread();
5939 if (err)
5940 goto done;
5942 err = got_blame(ta->path, a->commit_id, ta->repo,
5943 tog_diff_algo, blame_cb, ta->cb_args,
5944 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5945 if (err && err->code == GOT_ERR_CANCELLED)
5946 err = NULL;
5948 errcode = pthread_mutex_lock(&tog_mutex);
5949 if (errcode) {
5950 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5951 goto done;
5954 close_err = got_repo_close(ta->repo);
5955 if (err == NULL)
5956 err = close_err;
5957 ta->repo = NULL;
5958 *ta->complete = 1;
5960 errcode = pthread_mutex_unlock(&tog_mutex);
5961 if (errcode && err == NULL)
5962 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5964 done:
5965 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5966 err = got_error_from_errno("close");
5967 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5968 err = got_error_from_errno("close");
5969 if (f1 && fclose(f1) == EOF && err == NULL)
5970 err = got_error_from_errno("fclose");
5971 if (f2 && fclose(f2) == EOF && err == NULL)
5972 err = got_error_from_errno("fclose");
5974 return (void *)err;
5977 static struct got_object_id *
5978 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5979 int first_displayed_line, int selected_line)
5981 struct tog_blame_line *line;
5983 if (nlines <= 0)
5984 return NULL;
5986 line = &lines[first_displayed_line - 1 + selected_line - 1];
5987 if (!line->annotated)
5988 return NULL;
5990 return line->id;
5993 static struct got_object_id *
5994 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5995 int lineno)
5997 struct tog_blame_line *line;
5999 if (nlines <= 0 || lineno >= nlines)
6000 return NULL;
6002 line = &lines[lineno - 1];
6003 if (!line->annotated)
6004 return NULL;
6006 return line->id;
6009 static const struct got_error *
6010 stop_blame(struct tog_blame *blame)
6012 const struct got_error *err = NULL;
6013 int i;
6015 if (blame->thread) {
6016 int errcode;
6017 errcode = pthread_mutex_unlock(&tog_mutex);
6018 if (errcode)
6019 return got_error_set_errno(errcode,
6020 "pthread_mutex_unlock");
6021 errcode = pthread_join(blame->thread, (void **)&err);
6022 if (errcode)
6023 return got_error_set_errno(errcode, "pthread_join");
6024 errcode = pthread_mutex_lock(&tog_mutex);
6025 if (errcode)
6026 return got_error_set_errno(errcode,
6027 "pthread_mutex_lock");
6028 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6029 err = NULL;
6030 blame->thread = 0; //NULL;
6032 if (blame->thread_args.repo) {
6033 const struct got_error *close_err;
6034 close_err = got_repo_close(blame->thread_args.repo);
6035 if (err == NULL)
6036 err = close_err;
6037 blame->thread_args.repo = NULL;
6039 if (blame->f) {
6040 if (fclose(blame->f) == EOF && err == NULL)
6041 err = got_error_from_errno("fclose");
6042 blame->f = NULL;
6044 if (blame->lines) {
6045 for (i = 0; i < blame->nlines; i++)
6046 free(blame->lines[i].id);
6047 free(blame->lines);
6048 blame->lines = NULL;
6050 free(blame->cb_args.commit_id);
6051 blame->cb_args.commit_id = NULL;
6052 if (blame->pack_fds) {
6053 const struct got_error *pack_err =
6054 got_repo_pack_fds_close(blame->pack_fds);
6055 if (err == NULL)
6056 err = pack_err;
6057 blame->pack_fds = NULL;
6059 return err;
6062 static const struct got_error *
6063 cancel_blame_view(void *arg)
6065 const struct got_error *err = NULL;
6066 int *done = arg;
6067 int errcode;
6069 errcode = pthread_mutex_lock(&tog_mutex);
6070 if (errcode)
6071 return got_error_set_errno(errcode,
6072 "pthread_mutex_unlock");
6074 if (*done)
6075 err = got_error(GOT_ERR_CANCELLED);
6077 errcode = pthread_mutex_unlock(&tog_mutex);
6078 if (errcode)
6079 return got_error_set_errno(errcode,
6080 "pthread_mutex_lock");
6082 return err;
6085 static const struct got_error *
6086 run_blame(struct tog_view *view)
6088 struct tog_blame_view_state *s = &view->state.blame;
6089 struct tog_blame *blame = &s->blame;
6090 const struct got_error *err = NULL;
6091 struct got_commit_object *commit = NULL;
6092 struct got_blob_object *blob = NULL;
6093 struct got_repository *thread_repo = NULL;
6094 struct got_object_id *obj_id = NULL;
6095 int obj_type, fd = -1;
6096 int *pack_fds = NULL;
6098 err = got_object_open_as_commit(&commit, s->repo,
6099 &s->blamed_commit->id);
6100 if (err)
6101 return err;
6103 fd = got_opentempfd();
6104 if (fd == -1) {
6105 err = got_error_from_errno("got_opentempfd");
6106 goto done;
6109 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6110 if (err)
6111 goto done;
6113 err = got_object_get_type(&obj_type, s->repo, obj_id);
6114 if (err)
6115 goto done;
6117 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6118 err = got_error(GOT_ERR_OBJ_TYPE);
6119 goto done;
6122 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6123 if (err)
6124 goto done;
6125 blame->f = got_opentemp();
6126 if (blame->f == NULL) {
6127 err = got_error_from_errno("got_opentemp");
6128 goto done;
6130 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6131 &blame->line_offsets, blame->f, blob);
6132 if (err)
6133 goto done;
6134 if (blame->nlines == 0) {
6135 s->blame_complete = 1;
6136 goto done;
6139 /* Don't include \n at EOF in the blame line count. */
6140 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6141 blame->nlines--;
6143 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6144 if (blame->lines == NULL) {
6145 err = got_error_from_errno("calloc");
6146 goto done;
6149 err = got_repo_pack_fds_open(&pack_fds);
6150 if (err)
6151 goto done;
6152 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6153 pack_fds);
6154 if (err)
6155 goto done;
6157 blame->pack_fds = pack_fds;
6158 blame->cb_args.view = view;
6159 blame->cb_args.lines = blame->lines;
6160 blame->cb_args.nlines = blame->nlines;
6161 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6162 if (blame->cb_args.commit_id == NULL) {
6163 err = got_error_from_errno("got_object_id_dup");
6164 goto done;
6166 blame->cb_args.quit = &s->done;
6168 blame->thread_args.path = s->path;
6169 blame->thread_args.repo = thread_repo;
6170 blame->thread_args.cb_args = &blame->cb_args;
6171 blame->thread_args.complete = &s->blame_complete;
6172 blame->thread_args.cancel_cb = cancel_blame_view;
6173 blame->thread_args.cancel_arg = &s->done;
6174 s->blame_complete = 0;
6176 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6177 s->first_displayed_line = 1;
6178 s->last_displayed_line = view->nlines;
6179 s->selected_line = 1;
6181 s->matched_line = 0;
6183 done:
6184 if (commit)
6185 got_object_commit_close(commit);
6186 if (fd != -1 && close(fd) == -1 && err == NULL)
6187 err = got_error_from_errno("close");
6188 if (blob)
6189 got_object_blob_close(blob);
6190 free(obj_id);
6191 if (err)
6192 stop_blame(blame);
6193 return err;
6196 static const struct got_error *
6197 open_blame_view(struct tog_view *view, char *path,
6198 struct got_object_id *commit_id, struct got_repository *repo)
6200 const struct got_error *err = NULL;
6201 struct tog_blame_view_state *s = &view->state.blame;
6203 STAILQ_INIT(&s->blamed_commits);
6205 s->path = strdup(path);
6206 if (s->path == NULL)
6207 return got_error_from_errno("strdup");
6209 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6210 if (err) {
6211 free(s->path);
6212 return err;
6215 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6216 s->first_displayed_line = 1;
6217 s->last_displayed_line = view->nlines;
6218 s->selected_line = 1;
6219 s->blame_complete = 0;
6220 s->repo = repo;
6221 s->commit_id = commit_id;
6222 memset(&s->blame, 0, sizeof(s->blame));
6224 STAILQ_INIT(&s->colors);
6225 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6226 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6227 get_color_value("TOG_COLOR_COMMIT"));
6228 if (err)
6229 return err;
6232 view->show = show_blame_view;
6233 view->input = input_blame_view;
6234 view->reset = reset_blame_view;
6235 view->close = close_blame_view;
6236 view->search_start = search_start_blame_view;
6237 view->search_setup = search_setup_blame_view;
6238 view->search_next = search_next_view_match;
6240 return run_blame(view);
6243 static const struct got_error *
6244 close_blame_view(struct tog_view *view)
6246 const struct got_error *err = NULL;
6247 struct tog_blame_view_state *s = &view->state.blame;
6249 if (s->blame.thread)
6250 err = stop_blame(&s->blame);
6252 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6253 struct got_object_qid *blamed_commit;
6254 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6255 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6256 got_object_qid_free(blamed_commit);
6259 free(s->path);
6260 free_colors(&s->colors);
6261 return err;
6264 static const struct got_error *
6265 search_start_blame_view(struct tog_view *view)
6267 struct tog_blame_view_state *s = &view->state.blame;
6269 s->matched_line = 0;
6270 return NULL;
6273 static void
6274 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6275 size_t *nlines, int **first, int **last, int **match, int **selected)
6277 struct tog_blame_view_state *s = &view->state.blame;
6279 *f = s->blame.f;
6280 *nlines = s->blame.nlines;
6281 *line_offsets = s->blame.line_offsets;
6282 *match = &s->matched_line;
6283 *first = &s->first_displayed_line;
6284 *last = &s->last_displayed_line;
6285 *selected = &s->selected_line;
6288 static const struct got_error *
6289 show_blame_view(struct tog_view *view)
6291 const struct got_error *err = NULL;
6292 struct tog_blame_view_state *s = &view->state.blame;
6293 int errcode;
6295 if (s->blame.thread == 0 && !s->blame_complete) {
6296 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6297 &s->blame.thread_args);
6298 if (errcode)
6299 return got_error_set_errno(errcode, "pthread_create");
6301 halfdelay(1); /* fast refresh while annotating */
6304 if (s->blame_complete)
6305 halfdelay(10); /* disable fast refresh */
6307 err = draw_blame(view);
6309 view_border(view);
6310 return err;
6313 static const struct got_error *
6314 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6315 struct got_repository *repo, struct got_object_id *id)
6317 struct tog_view *log_view;
6318 const struct got_error *err = NULL;
6320 *new_view = NULL;
6322 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6323 if (log_view == NULL)
6324 return got_error_from_errno("view_open");
6326 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6327 if (err)
6328 view_close(log_view);
6329 else
6330 *new_view = log_view;
6332 return err;
6335 static const struct got_error *
6336 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6338 const struct got_error *err = NULL, *thread_err = NULL;
6339 struct tog_view *diff_view;
6340 struct tog_blame_view_state *s = &view->state.blame;
6341 int eos, nscroll, begin_y = 0, begin_x = 0;
6343 eos = nscroll = view->nlines - 2;
6344 if (view_is_hsplit_top(view))
6345 --eos; /* border */
6347 switch (ch) {
6348 case '0':
6349 case '$':
6350 case KEY_RIGHT:
6351 case 'l':
6352 case KEY_LEFT:
6353 case 'h':
6354 horizontal_scroll_input(view, ch);
6355 break;
6356 case 'q':
6357 s->done = 1;
6358 break;
6359 case 'g':
6360 case KEY_HOME:
6361 s->selected_line = 1;
6362 s->first_displayed_line = 1;
6363 view->count = 0;
6364 break;
6365 case 'G':
6366 case KEY_END:
6367 if (s->blame.nlines < eos) {
6368 s->selected_line = s->blame.nlines;
6369 s->first_displayed_line = 1;
6370 } else {
6371 s->selected_line = eos;
6372 s->first_displayed_line = s->blame.nlines - (eos - 1);
6374 view->count = 0;
6375 break;
6376 case 'k':
6377 case KEY_UP:
6378 case CTRL('p'):
6379 if (s->selected_line > 1)
6380 s->selected_line--;
6381 else if (s->selected_line == 1 &&
6382 s->first_displayed_line > 1)
6383 s->first_displayed_line--;
6384 else
6385 view->count = 0;
6386 break;
6387 case CTRL('u'):
6388 case 'u':
6389 nscroll /= 2;
6390 /* FALL THROUGH */
6391 case KEY_PPAGE:
6392 case CTRL('b'):
6393 case 'b':
6394 if (s->first_displayed_line == 1) {
6395 if (view->count > 1)
6396 nscroll += nscroll;
6397 s->selected_line = MAX(1, s->selected_line - nscroll);
6398 view->count = 0;
6399 break;
6401 if (s->first_displayed_line > nscroll)
6402 s->first_displayed_line -= nscroll;
6403 else
6404 s->first_displayed_line = 1;
6405 break;
6406 case 'j':
6407 case KEY_DOWN:
6408 case CTRL('n'):
6409 if (s->selected_line < eos && s->first_displayed_line +
6410 s->selected_line <= s->blame.nlines)
6411 s->selected_line++;
6412 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6413 s->first_displayed_line++;
6414 else
6415 view->count = 0;
6416 break;
6417 case 'c':
6418 case 'p': {
6419 struct got_object_id *id = NULL;
6421 view->count = 0;
6422 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6423 s->first_displayed_line, s->selected_line);
6424 if (id == NULL)
6425 break;
6426 if (ch == 'p') {
6427 struct got_commit_object *commit, *pcommit;
6428 struct got_object_qid *pid;
6429 struct got_object_id *blob_id = NULL;
6430 int obj_type;
6431 err = got_object_open_as_commit(&commit,
6432 s->repo, id);
6433 if (err)
6434 break;
6435 pid = STAILQ_FIRST(
6436 got_object_commit_get_parent_ids(commit));
6437 if (pid == NULL) {
6438 got_object_commit_close(commit);
6439 break;
6441 /* Check if path history ends here. */
6442 err = got_object_open_as_commit(&pcommit,
6443 s->repo, &pid->id);
6444 if (err)
6445 break;
6446 err = got_object_id_by_path(&blob_id, s->repo,
6447 pcommit, s->path);
6448 got_object_commit_close(pcommit);
6449 if (err) {
6450 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6451 err = NULL;
6452 got_object_commit_close(commit);
6453 break;
6455 err = got_object_get_type(&obj_type, s->repo,
6456 blob_id);
6457 free(blob_id);
6458 /* Can't blame non-blob type objects. */
6459 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6460 got_object_commit_close(commit);
6461 break;
6463 err = got_object_qid_alloc(&s->blamed_commit,
6464 &pid->id);
6465 got_object_commit_close(commit);
6466 } else {
6467 if (got_object_id_cmp(id,
6468 &s->blamed_commit->id) == 0)
6469 break;
6470 err = got_object_qid_alloc(&s->blamed_commit,
6471 id);
6473 if (err)
6474 break;
6475 s->done = 1;
6476 thread_err = stop_blame(&s->blame);
6477 s->done = 0;
6478 if (thread_err)
6479 break;
6480 STAILQ_INSERT_HEAD(&s->blamed_commits,
6481 s->blamed_commit, entry);
6482 err = run_blame(view);
6483 if (err)
6484 break;
6485 break;
6487 case 'C': {
6488 struct got_object_qid *first;
6490 view->count = 0;
6491 first = STAILQ_FIRST(&s->blamed_commits);
6492 if (!got_object_id_cmp(&first->id, s->commit_id))
6493 break;
6494 s->done = 1;
6495 thread_err = stop_blame(&s->blame);
6496 s->done = 0;
6497 if (thread_err)
6498 break;
6499 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6500 got_object_qid_free(s->blamed_commit);
6501 s->blamed_commit =
6502 STAILQ_FIRST(&s->blamed_commits);
6503 err = run_blame(view);
6504 if (err)
6505 break;
6506 break;
6508 case 'L':
6509 view->count = 0;
6510 s->id_to_log = get_selected_commit_id(s->blame.lines,
6511 s->blame.nlines, s->first_displayed_line, s->selected_line);
6512 if (s->id_to_log)
6513 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6514 break;
6515 case KEY_ENTER:
6516 case '\r': {
6517 struct got_object_id *id = NULL;
6518 struct got_object_qid *pid;
6519 struct got_commit_object *commit = NULL;
6521 view->count = 0;
6522 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6523 s->first_displayed_line, s->selected_line);
6524 if (id == NULL)
6525 break;
6526 err = got_object_open_as_commit(&commit, s->repo, id);
6527 if (err)
6528 break;
6529 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6530 if (*new_view) {
6531 /* traversed from diff view, release diff resources */
6532 err = close_diff_view(*new_view);
6533 if (err)
6534 break;
6535 diff_view = *new_view;
6536 } else {
6537 if (view_is_parent_view(view))
6538 view_get_split(view, &begin_y, &begin_x);
6540 diff_view = view_open(0, 0, begin_y, begin_x,
6541 TOG_VIEW_DIFF);
6542 if (diff_view == NULL) {
6543 got_object_commit_close(commit);
6544 err = got_error_from_errno("view_open");
6545 break;
6548 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6549 id, NULL, NULL, 3, 0, 0, view, s->repo);
6550 got_object_commit_close(commit);
6551 if (err) {
6552 view_close(diff_view);
6553 break;
6555 s->last_diffed_line = s->first_displayed_line - 1 +
6556 s->selected_line;
6557 if (*new_view)
6558 break; /* still open from active diff view */
6559 if (view_is_parent_view(view) &&
6560 view->mode == TOG_VIEW_SPLIT_HRZN) {
6561 err = view_init_hsplit(view, begin_y);
6562 if (err)
6563 break;
6566 view->focussed = 0;
6567 diff_view->focussed = 1;
6568 diff_view->mode = view->mode;
6569 diff_view->nlines = view->lines - begin_y;
6570 if (view_is_parent_view(view)) {
6571 view_transfer_size(diff_view, view);
6572 err = view_close_child(view);
6573 if (err)
6574 break;
6575 err = view_set_child(view, diff_view);
6576 if (err)
6577 break;
6578 view->focus_child = 1;
6579 } else
6580 *new_view = diff_view;
6581 if (err)
6582 break;
6583 break;
6585 case CTRL('d'):
6586 case 'd':
6587 nscroll /= 2;
6588 /* FALL THROUGH */
6589 case KEY_NPAGE:
6590 case CTRL('f'):
6591 case 'f':
6592 case ' ':
6593 if (s->last_displayed_line >= s->blame.nlines &&
6594 s->selected_line >= MIN(s->blame.nlines,
6595 view->nlines - 2)) {
6596 view->count = 0;
6597 break;
6599 if (s->last_displayed_line >= s->blame.nlines &&
6600 s->selected_line < view->nlines - 2) {
6601 s->selected_line +=
6602 MIN(nscroll, s->last_displayed_line -
6603 s->first_displayed_line - s->selected_line + 1);
6605 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6606 s->first_displayed_line += nscroll;
6607 else
6608 s->first_displayed_line =
6609 s->blame.nlines - (view->nlines - 3);
6610 break;
6611 case KEY_RESIZE:
6612 if (s->selected_line > view->nlines - 2) {
6613 s->selected_line = MIN(s->blame.nlines,
6614 view->nlines - 2);
6616 break;
6617 default:
6618 view->count = 0;
6619 break;
6621 return thread_err ? thread_err : err;
6624 static const struct got_error *
6625 reset_blame_view(struct tog_view *view)
6627 const struct got_error *err;
6628 struct tog_blame_view_state *s = &view->state.blame;
6630 view->count = 0;
6631 s->done = 1;
6632 err = stop_blame(&s->blame);
6633 s->done = 0;
6634 if (err)
6635 return err;
6636 return run_blame(view);
6639 static const struct got_error *
6640 cmd_blame(int argc, char *argv[])
6642 const struct got_error *error;
6643 struct got_repository *repo = NULL;
6644 struct got_worktree *worktree = NULL;
6645 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6646 char *link_target = NULL;
6647 struct got_object_id *commit_id = NULL;
6648 struct got_commit_object *commit = NULL;
6649 char *commit_id_str = NULL;
6650 int ch;
6651 struct tog_view *view;
6652 int *pack_fds = NULL;
6654 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6655 switch (ch) {
6656 case 'c':
6657 commit_id_str = optarg;
6658 break;
6659 case 'r':
6660 repo_path = realpath(optarg, NULL);
6661 if (repo_path == NULL)
6662 return got_error_from_errno2("realpath",
6663 optarg);
6664 break;
6665 default:
6666 usage_blame();
6667 /* NOTREACHED */
6671 argc -= optind;
6672 argv += optind;
6674 if (argc != 1)
6675 usage_blame();
6677 error = got_repo_pack_fds_open(&pack_fds);
6678 if (error != NULL)
6679 goto done;
6681 if (repo_path == NULL) {
6682 cwd = getcwd(NULL, 0);
6683 if (cwd == NULL)
6684 return got_error_from_errno("getcwd");
6685 error = got_worktree_open(&worktree, cwd);
6686 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6687 goto done;
6688 if (worktree)
6689 repo_path =
6690 strdup(got_worktree_get_repo_path(worktree));
6691 else
6692 repo_path = strdup(cwd);
6693 if (repo_path == NULL) {
6694 error = got_error_from_errno("strdup");
6695 goto done;
6699 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6700 if (error != NULL)
6701 goto done;
6703 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6704 worktree);
6705 if (error)
6706 goto done;
6708 init_curses();
6710 error = apply_unveil(got_repo_get_path(repo), NULL);
6711 if (error)
6712 goto done;
6714 error = tog_load_refs(repo, 0);
6715 if (error)
6716 goto done;
6718 if (commit_id_str == NULL) {
6719 struct got_reference *head_ref;
6720 error = got_ref_open(&head_ref, repo, worktree ?
6721 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6722 if (error != NULL)
6723 goto done;
6724 error = got_ref_resolve(&commit_id, repo, head_ref);
6725 got_ref_close(head_ref);
6726 } else {
6727 error = got_repo_match_object_id(&commit_id, NULL,
6728 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6730 if (error != NULL)
6731 goto done;
6733 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6734 if (view == NULL) {
6735 error = got_error_from_errno("view_open");
6736 goto done;
6739 error = got_object_open_as_commit(&commit, repo, commit_id);
6740 if (error)
6741 goto done;
6743 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6744 commit, repo);
6745 if (error)
6746 goto done;
6748 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6749 commit_id, repo);
6750 if (error)
6751 goto done;
6752 if (worktree) {
6753 /* Release work tree lock. */
6754 got_worktree_close(worktree);
6755 worktree = NULL;
6757 error = view_loop(view);
6758 done:
6759 free(repo_path);
6760 free(in_repo_path);
6761 free(link_target);
6762 free(cwd);
6763 free(commit_id);
6764 if (commit)
6765 got_object_commit_close(commit);
6766 if (worktree)
6767 got_worktree_close(worktree);
6768 if (repo) {
6769 const struct got_error *close_err = got_repo_close(repo);
6770 if (error == NULL)
6771 error = close_err;
6773 if (pack_fds) {
6774 const struct got_error *pack_err =
6775 got_repo_pack_fds_close(pack_fds);
6776 if (error == NULL)
6777 error = pack_err;
6779 tog_free_refs();
6780 return error;
6783 static const struct got_error *
6784 draw_tree_entries(struct tog_view *view, const char *parent_path)
6786 struct tog_tree_view_state *s = &view->state.tree;
6787 const struct got_error *err = NULL;
6788 struct got_tree_entry *te;
6789 wchar_t *wline;
6790 char *index = NULL;
6791 struct tog_color *tc;
6792 int width, n, nentries, scrollx, i = 1;
6793 int limit = view->nlines;
6795 s->ndisplayed = 0;
6796 if (view_is_hsplit_top(view))
6797 --limit; /* border */
6799 werase(view->window);
6801 if (limit == 0)
6802 return NULL;
6804 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6805 0, 0);
6806 if (err)
6807 return err;
6808 if (view_needs_focus_indication(view))
6809 wstandout(view->window);
6810 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6811 if (tc)
6812 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6813 waddwstr(view->window, wline);
6814 free(wline);
6815 wline = NULL;
6816 while (width++ < view->ncols)
6817 waddch(view->window, ' ');
6818 if (tc)
6819 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6820 if (view_needs_focus_indication(view))
6821 wstandend(view->window);
6822 if (--limit <= 0)
6823 return NULL;
6825 i += s->selected;
6826 if (s->first_displayed_entry) {
6827 i += got_tree_entry_get_index(s->first_displayed_entry);
6828 if (s->tree != s->root)
6829 ++i; /* account for ".." entry */
6831 nentries = got_object_tree_get_nentries(s->tree);
6832 if (asprintf(&index, "[%d/%d] %s",
6833 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6834 return got_error_from_errno("asprintf");
6835 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6836 free(index);
6837 if (err)
6838 return err;
6839 waddwstr(view->window, wline);
6840 free(wline);
6841 wline = NULL;
6842 if (width < view->ncols - 1)
6843 waddch(view->window, '\n');
6844 if (--limit <= 0)
6845 return NULL;
6846 waddch(view->window, '\n');
6847 if (--limit <= 0)
6848 return NULL;
6850 if (s->first_displayed_entry == NULL) {
6851 te = got_object_tree_get_first_entry(s->tree);
6852 if (s->selected == 0) {
6853 if (view->focussed)
6854 wstandout(view->window);
6855 s->selected_entry = NULL;
6857 waddstr(view->window, " ..\n"); /* parent directory */
6858 if (s->selected == 0 && view->focussed)
6859 wstandend(view->window);
6860 s->ndisplayed++;
6861 if (--limit <= 0)
6862 return NULL;
6863 n = 1;
6864 } else {
6865 n = 0;
6866 te = s->first_displayed_entry;
6869 view->maxx = 0;
6870 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6871 char *line = NULL, *id_str = NULL, *link_target = NULL;
6872 const char *modestr = "";
6873 mode_t mode;
6875 te = got_object_tree_get_entry(s->tree, i);
6876 mode = got_tree_entry_get_mode(te);
6878 if (s->show_ids) {
6879 err = got_object_id_str(&id_str,
6880 got_tree_entry_get_id(te));
6881 if (err)
6882 return got_error_from_errno(
6883 "got_object_id_str");
6885 if (got_object_tree_entry_is_submodule(te))
6886 modestr = "$";
6887 else if (S_ISLNK(mode)) {
6888 int i;
6890 err = got_tree_entry_get_symlink_target(&link_target,
6891 te, s->repo);
6892 if (err) {
6893 free(id_str);
6894 return err;
6896 for (i = 0; i < strlen(link_target); i++) {
6897 if (!isprint((unsigned char)link_target[i]))
6898 link_target[i] = '?';
6900 modestr = "@";
6902 else if (S_ISDIR(mode))
6903 modestr = "/";
6904 else if (mode & S_IXUSR)
6905 modestr = "*";
6906 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6907 got_tree_entry_get_name(te), modestr,
6908 link_target ? " -> ": "",
6909 link_target ? link_target : "") == -1) {
6910 free(id_str);
6911 free(link_target);
6912 return got_error_from_errno("asprintf");
6914 free(id_str);
6915 free(link_target);
6917 /* use full line width to determine view->maxx */
6918 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
6919 if (err) {
6920 free(line);
6921 break;
6923 view->maxx = MAX(view->maxx, width);
6924 free(wline);
6925 wline = NULL;
6927 err = format_line(&wline, &width, &scrollx, line, view->x,
6928 view->ncols, 0, 0);
6929 if (err) {
6930 free(line);
6931 break;
6933 if (n == s->selected) {
6934 if (view->focussed)
6935 wstandout(view->window);
6936 s->selected_entry = te;
6938 tc = match_color(&s->colors, line);
6939 if (tc)
6940 wattr_on(view->window,
6941 COLOR_PAIR(tc->colorpair), NULL);
6942 waddwstr(view->window, &wline[scrollx]);
6943 if (tc)
6944 wattr_off(view->window,
6945 COLOR_PAIR(tc->colorpair), NULL);
6946 if (width < view->ncols)
6947 waddch(view->window, '\n');
6948 if (n == s->selected && view->focussed)
6949 wstandend(view->window);
6950 free(line);
6951 free(wline);
6952 wline = NULL;
6953 n++;
6954 s->ndisplayed++;
6955 s->last_displayed_entry = te;
6956 if (--limit <= 0)
6957 break;
6960 return err;
6963 static void
6964 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6966 struct got_tree_entry *te;
6967 int isroot = s->tree == s->root;
6968 int i = 0;
6970 if (s->first_displayed_entry == NULL)
6971 return;
6973 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6974 while (i++ < maxscroll) {
6975 if (te == NULL) {
6976 if (!isroot)
6977 s->first_displayed_entry = NULL;
6978 break;
6980 s->first_displayed_entry = te;
6981 te = got_tree_entry_get_prev(s->tree, te);
6985 static const struct got_error *
6986 tree_scroll_down(struct tog_view *view, int maxscroll)
6988 struct tog_tree_view_state *s = &view->state.tree;
6989 struct got_tree_entry *next, *last;
6990 int n = 0;
6992 if (s->first_displayed_entry)
6993 next = got_tree_entry_get_next(s->tree,
6994 s->first_displayed_entry);
6995 else
6996 next = got_object_tree_get_first_entry(s->tree);
6998 last = s->last_displayed_entry;
6999 while (next && n++ < maxscroll) {
7000 if (last) {
7001 s->last_displayed_entry = last;
7002 last = got_tree_entry_get_next(s->tree, last);
7004 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7005 s->first_displayed_entry = next;
7006 next = got_tree_entry_get_next(s->tree, next);
7010 return NULL;
7013 static const struct got_error *
7014 tree_entry_path(char **path, struct tog_parent_trees *parents,
7015 struct got_tree_entry *te)
7017 const struct got_error *err = NULL;
7018 struct tog_parent_tree *pt;
7019 size_t len = 2; /* for leading slash and NUL */
7021 TAILQ_FOREACH(pt, parents, entry)
7022 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7023 + 1 /* slash */;
7024 if (te)
7025 len += strlen(got_tree_entry_get_name(te));
7027 *path = calloc(1, len);
7028 if (path == NULL)
7029 return got_error_from_errno("calloc");
7031 (*path)[0] = '/';
7032 pt = TAILQ_LAST(parents, tog_parent_trees);
7033 while (pt) {
7034 const char *name = got_tree_entry_get_name(pt->selected_entry);
7035 if (strlcat(*path, name, len) >= len) {
7036 err = got_error(GOT_ERR_NO_SPACE);
7037 goto done;
7039 if (strlcat(*path, "/", len) >= len) {
7040 err = got_error(GOT_ERR_NO_SPACE);
7041 goto done;
7043 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7045 if (te) {
7046 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7047 err = got_error(GOT_ERR_NO_SPACE);
7048 goto done;
7051 done:
7052 if (err) {
7053 free(*path);
7054 *path = NULL;
7056 return err;
7059 static const struct got_error *
7060 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7061 struct got_tree_entry *te, struct tog_parent_trees *parents,
7062 struct got_object_id *commit_id, struct got_repository *repo)
7064 const struct got_error *err = NULL;
7065 char *path;
7066 struct tog_view *blame_view;
7068 *new_view = NULL;
7070 err = tree_entry_path(&path, parents, te);
7071 if (err)
7072 return err;
7074 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7075 if (blame_view == NULL) {
7076 err = got_error_from_errno("view_open");
7077 goto done;
7080 err = open_blame_view(blame_view, path, commit_id, repo);
7081 if (err) {
7082 if (err->code == GOT_ERR_CANCELLED)
7083 err = NULL;
7084 view_close(blame_view);
7085 } else
7086 *new_view = blame_view;
7087 done:
7088 free(path);
7089 return err;
7092 static const struct got_error *
7093 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7094 struct tog_tree_view_state *s)
7096 struct tog_view *log_view;
7097 const struct got_error *err = NULL;
7098 char *path;
7100 *new_view = NULL;
7102 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7103 if (log_view == NULL)
7104 return got_error_from_errno("view_open");
7106 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7107 if (err)
7108 return err;
7110 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7111 path, 0);
7112 if (err)
7113 view_close(log_view);
7114 else
7115 *new_view = log_view;
7116 free(path);
7117 return err;
7120 static const struct got_error *
7121 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7122 const char *head_ref_name, struct got_repository *repo)
7124 const struct got_error *err = NULL;
7125 char *commit_id_str = NULL;
7126 struct tog_tree_view_state *s = &view->state.tree;
7127 struct got_commit_object *commit = NULL;
7129 TAILQ_INIT(&s->parents);
7130 STAILQ_INIT(&s->colors);
7132 s->commit_id = got_object_id_dup(commit_id);
7133 if (s->commit_id == NULL)
7134 return got_error_from_errno("got_object_id_dup");
7136 err = got_object_open_as_commit(&commit, repo, commit_id);
7137 if (err)
7138 goto done;
7141 * The root is opened here and will be closed when the view is closed.
7142 * Any visited subtrees and their path-wise parents are opened and
7143 * closed on demand.
7145 err = got_object_open_as_tree(&s->root, repo,
7146 got_object_commit_get_tree_id(commit));
7147 if (err)
7148 goto done;
7149 s->tree = s->root;
7151 err = got_object_id_str(&commit_id_str, commit_id);
7152 if (err != NULL)
7153 goto done;
7155 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7156 err = got_error_from_errno("asprintf");
7157 goto done;
7160 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7161 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7162 if (head_ref_name) {
7163 s->head_ref_name = strdup(head_ref_name);
7164 if (s->head_ref_name == NULL) {
7165 err = got_error_from_errno("strdup");
7166 goto done;
7169 s->repo = repo;
7171 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7172 err = add_color(&s->colors, "\\$$",
7173 TOG_COLOR_TREE_SUBMODULE,
7174 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7175 if (err)
7176 goto done;
7177 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7178 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7179 if (err)
7180 goto done;
7181 err = add_color(&s->colors, "/$",
7182 TOG_COLOR_TREE_DIRECTORY,
7183 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7184 if (err)
7185 goto done;
7187 err = add_color(&s->colors, "\\*$",
7188 TOG_COLOR_TREE_EXECUTABLE,
7189 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7190 if (err)
7191 goto done;
7193 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7194 get_color_value("TOG_COLOR_COMMIT"));
7195 if (err)
7196 goto done;
7199 view->show = show_tree_view;
7200 view->input = input_tree_view;
7201 view->close = close_tree_view;
7202 view->search_start = search_start_tree_view;
7203 view->search_next = search_next_tree_view;
7204 done:
7205 free(commit_id_str);
7206 if (commit)
7207 got_object_commit_close(commit);
7208 if (err)
7209 close_tree_view(view);
7210 return err;
7213 static const struct got_error *
7214 close_tree_view(struct tog_view *view)
7216 struct tog_tree_view_state *s = &view->state.tree;
7218 free_colors(&s->colors);
7219 free(s->tree_label);
7220 s->tree_label = NULL;
7221 free(s->commit_id);
7222 s->commit_id = NULL;
7223 free(s->head_ref_name);
7224 s->head_ref_name = NULL;
7225 while (!TAILQ_EMPTY(&s->parents)) {
7226 struct tog_parent_tree *parent;
7227 parent = TAILQ_FIRST(&s->parents);
7228 TAILQ_REMOVE(&s->parents, parent, entry);
7229 if (parent->tree != s->root)
7230 got_object_tree_close(parent->tree);
7231 free(parent);
7234 if (s->tree != NULL && s->tree != s->root)
7235 got_object_tree_close(s->tree);
7236 if (s->root)
7237 got_object_tree_close(s->root);
7238 return NULL;
7241 static const struct got_error *
7242 search_start_tree_view(struct tog_view *view)
7244 struct tog_tree_view_state *s = &view->state.tree;
7246 s->matched_entry = NULL;
7247 return NULL;
7250 static int
7251 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7253 regmatch_t regmatch;
7255 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7256 0) == 0;
7259 static const struct got_error *
7260 search_next_tree_view(struct tog_view *view)
7262 struct tog_tree_view_state *s = &view->state.tree;
7263 struct got_tree_entry *te = NULL;
7265 if (!view->searching) {
7266 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7267 return NULL;
7270 if (s->matched_entry) {
7271 if (view->searching == TOG_SEARCH_FORWARD) {
7272 if (s->selected_entry)
7273 te = got_tree_entry_get_next(s->tree,
7274 s->selected_entry);
7275 else
7276 te = got_object_tree_get_first_entry(s->tree);
7277 } else {
7278 if (s->selected_entry == NULL)
7279 te = got_object_tree_get_last_entry(s->tree);
7280 else
7281 te = got_tree_entry_get_prev(s->tree,
7282 s->selected_entry);
7284 } else {
7285 if (s->selected_entry)
7286 te = s->selected_entry;
7287 else if (view->searching == TOG_SEARCH_FORWARD)
7288 te = got_object_tree_get_first_entry(s->tree);
7289 else
7290 te = got_object_tree_get_last_entry(s->tree);
7293 while (1) {
7294 if (te == NULL) {
7295 if (s->matched_entry == NULL) {
7296 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7297 return NULL;
7299 if (view->searching == TOG_SEARCH_FORWARD)
7300 te = got_object_tree_get_first_entry(s->tree);
7301 else
7302 te = got_object_tree_get_last_entry(s->tree);
7305 if (match_tree_entry(te, &view->regex)) {
7306 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7307 s->matched_entry = te;
7308 break;
7311 if (view->searching == TOG_SEARCH_FORWARD)
7312 te = got_tree_entry_get_next(s->tree, te);
7313 else
7314 te = got_tree_entry_get_prev(s->tree, te);
7317 if (s->matched_entry) {
7318 s->first_displayed_entry = s->matched_entry;
7319 s->selected = 0;
7322 return NULL;
7325 static const struct got_error *
7326 show_tree_view(struct tog_view *view)
7328 const struct got_error *err = NULL;
7329 struct tog_tree_view_state *s = &view->state.tree;
7330 char *parent_path;
7332 err = tree_entry_path(&parent_path, &s->parents, NULL);
7333 if (err)
7334 return err;
7336 err = draw_tree_entries(view, parent_path);
7337 free(parent_path);
7339 view_border(view);
7340 return err;
7343 static const struct got_error *
7344 tree_goto_line(struct tog_view *view, int nlines)
7346 const struct got_error *err = NULL;
7347 struct tog_tree_view_state *s = &view->state.tree;
7348 struct got_tree_entry **fte, **lte, **ste;
7349 int g, last, first = 1, i = 1;
7350 int root = s->tree == s->root;
7351 int off = root ? 1 : 2;
7353 g = view->gline;
7354 view->gline = 0;
7356 if (g == 0)
7357 g = 1;
7358 else if (g > got_object_tree_get_nentries(s->tree))
7359 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7361 fte = &s->first_displayed_entry;
7362 lte = &s->last_displayed_entry;
7363 ste = &s->selected_entry;
7365 if (*fte != NULL) {
7366 first = got_tree_entry_get_index(*fte);
7367 first += off; /* account for ".." */
7369 last = got_tree_entry_get_index(*lte);
7370 last += off;
7372 if (g >= first && g <= last && g - first < nlines) {
7373 s->selected = g - first;
7374 return NULL; /* gline is on the current page */
7377 if (*ste != NULL) {
7378 i = got_tree_entry_get_index(*ste);
7379 i += off;
7382 if (i < g) {
7383 err = tree_scroll_down(view, g - i);
7384 if (err)
7385 return err;
7386 if (got_tree_entry_get_index(*lte) >=
7387 got_object_tree_get_nentries(s->tree) - 1 &&
7388 first + s->selected < g &&
7389 s->selected < s->ndisplayed - 1) {
7390 first = got_tree_entry_get_index(*fte);
7391 first += off;
7392 s->selected = g - first;
7394 } else if (i > g)
7395 tree_scroll_up(s, i - g);
7397 if (g < nlines &&
7398 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7399 s->selected = g - 1;
7401 return NULL;
7404 static const struct got_error *
7405 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7407 const struct got_error *err = NULL;
7408 struct tog_tree_view_state *s = &view->state.tree;
7409 struct got_tree_entry *te;
7410 int n, nscroll = view->nlines - 3;
7412 if (view->gline)
7413 return tree_goto_line(view, nscroll);
7415 switch (ch) {
7416 case '0':
7417 case '$':
7418 case KEY_RIGHT:
7419 case 'l':
7420 case KEY_LEFT:
7421 case 'h':
7422 horizontal_scroll_input(view, ch);
7423 break;
7424 case 'i':
7425 s->show_ids = !s->show_ids;
7426 view->count = 0;
7427 break;
7428 case 'L':
7429 view->count = 0;
7430 if (!s->selected_entry)
7431 break;
7432 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7433 break;
7434 case 'R':
7435 view->count = 0;
7436 err = view_request_new(new_view, view, TOG_VIEW_REF);
7437 break;
7438 case 'g':
7439 case '=':
7440 case KEY_HOME:
7441 s->selected = 0;
7442 view->count = 0;
7443 if (s->tree == s->root)
7444 s->first_displayed_entry =
7445 got_object_tree_get_first_entry(s->tree);
7446 else
7447 s->first_displayed_entry = NULL;
7448 break;
7449 case 'G':
7450 case '*':
7451 case KEY_END: {
7452 int eos = view->nlines - 3;
7454 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7455 --eos; /* border */
7456 s->selected = 0;
7457 view->count = 0;
7458 te = got_object_tree_get_last_entry(s->tree);
7459 for (n = 0; n < eos; n++) {
7460 if (te == NULL) {
7461 if (s->tree != s->root) {
7462 s->first_displayed_entry = NULL;
7463 n++;
7465 break;
7467 s->first_displayed_entry = te;
7468 te = got_tree_entry_get_prev(s->tree, te);
7470 if (n > 0)
7471 s->selected = n - 1;
7472 break;
7474 case 'k':
7475 case KEY_UP:
7476 case CTRL('p'):
7477 if (s->selected > 0) {
7478 s->selected--;
7479 break;
7481 tree_scroll_up(s, 1);
7482 if (s->selected_entry == NULL ||
7483 (s->tree == s->root && s->selected_entry ==
7484 got_object_tree_get_first_entry(s->tree)))
7485 view->count = 0;
7486 break;
7487 case CTRL('u'):
7488 case 'u':
7489 nscroll /= 2;
7490 /* FALL THROUGH */
7491 case KEY_PPAGE:
7492 case CTRL('b'):
7493 case 'b':
7494 if (s->tree == s->root) {
7495 if (got_object_tree_get_first_entry(s->tree) ==
7496 s->first_displayed_entry)
7497 s->selected -= MIN(s->selected, nscroll);
7498 } else {
7499 if (s->first_displayed_entry == NULL)
7500 s->selected -= MIN(s->selected, nscroll);
7502 tree_scroll_up(s, MAX(0, nscroll));
7503 if (s->selected_entry == NULL ||
7504 (s->tree == s->root && s->selected_entry ==
7505 got_object_tree_get_first_entry(s->tree)))
7506 view->count = 0;
7507 break;
7508 case 'j':
7509 case KEY_DOWN:
7510 case CTRL('n'):
7511 if (s->selected < s->ndisplayed - 1) {
7512 s->selected++;
7513 break;
7515 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7516 == NULL) {
7517 /* can't scroll any further */
7518 view->count = 0;
7519 break;
7521 tree_scroll_down(view, 1);
7522 break;
7523 case CTRL('d'):
7524 case 'd':
7525 nscroll /= 2;
7526 /* FALL THROUGH */
7527 case KEY_NPAGE:
7528 case CTRL('f'):
7529 case 'f':
7530 case ' ':
7531 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7532 == NULL) {
7533 /* can't scroll any further; move cursor down */
7534 if (s->selected < s->ndisplayed - 1)
7535 s->selected += MIN(nscroll,
7536 s->ndisplayed - s->selected - 1);
7537 else
7538 view->count = 0;
7539 break;
7541 tree_scroll_down(view, nscroll);
7542 break;
7543 case KEY_ENTER:
7544 case '\r':
7545 case KEY_BACKSPACE:
7546 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7547 struct tog_parent_tree *parent;
7548 /* user selected '..' */
7549 if (s->tree == s->root) {
7550 view->count = 0;
7551 break;
7553 parent = TAILQ_FIRST(&s->parents);
7554 TAILQ_REMOVE(&s->parents, parent,
7555 entry);
7556 got_object_tree_close(s->tree);
7557 s->tree = parent->tree;
7558 s->first_displayed_entry =
7559 parent->first_displayed_entry;
7560 s->selected_entry =
7561 parent->selected_entry;
7562 s->selected = parent->selected;
7563 if (s->selected > view->nlines - 3) {
7564 err = offset_selection_down(view);
7565 if (err)
7566 break;
7568 free(parent);
7569 } else if (S_ISDIR(got_tree_entry_get_mode(
7570 s->selected_entry))) {
7571 struct got_tree_object *subtree;
7572 view->count = 0;
7573 err = got_object_open_as_tree(&subtree, s->repo,
7574 got_tree_entry_get_id(s->selected_entry));
7575 if (err)
7576 break;
7577 err = tree_view_visit_subtree(s, subtree);
7578 if (err) {
7579 got_object_tree_close(subtree);
7580 break;
7582 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7583 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7584 break;
7585 case KEY_RESIZE:
7586 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7587 s->selected = view->nlines - 4;
7588 view->count = 0;
7589 break;
7590 default:
7591 view->count = 0;
7592 break;
7595 return err;
7598 __dead static void
7599 usage_tree(void)
7601 endwin();
7602 fprintf(stderr,
7603 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7604 getprogname());
7605 exit(1);
7608 static const struct got_error *
7609 cmd_tree(int argc, char *argv[])
7611 const struct got_error *error;
7612 struct got_repository *repo = NULL;
7613 struct got_worktree *worktree = NULL;
7614 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7615 struct got_object_id *commit_id = NULL;
7616 struct got_commit_object *commit = NULL;
7617 const char *commit_id_arg = NULL;
7618 char *label = NULL;
7619 struct got_reference *ref = NULL;
7620 const char *head_ref_name = NULL;
7621 int ch;
7622 struct tog_view *view;
7623 int *pack_fds = NULL;
7625 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7626 switch (ch) {
7627 case 'c':
7628 commit_id_arg = optarg;
7629 break;
7630 case 'r':
7631 repo_path = realpath(optarg, NULL);
7632 if (repo_path == NULL)
7633 return got_error_from_errno2("realpath",
7634 optarg);
7635 break;
7636 default:
7637 usage_tree();
7638 /* NOTREACHED */
7642 argc -= optind;
7643 argv += optind;
7645 if (argc > 1)
7646 usage_tree();
7648 error = got_repo_pack_fds_open(&pack_fds);
7649 if (error != NULL)
7650 goto done;
7652 if (repo_path == NULL) {
7653 cwd = getcwd(NULL, 0);
7654 if (cwd == NULL)
7655 return got_error_from_errno("getcwd");
7656 error = got_worktree_open(&worktree, cwd);
7657 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7658 goto done;
7659 if (worktree)
7660 repo_path =
7661 strdup(got_worktree_get_repo_path(worktree));
7662 else
7663 repo_path = strdup(cwd);
7664 if (repo_path == NULL) {
7665 error = got_error_from_errno("strdup");
7666 goto done;
7670 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7671 if (error != NULL)
7672 goto done;
7674 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7675 repo, worktree);
7676 if (error)
7677 goto done;
7679 init_curses();
7681 error = apply_unveil(got_repo_get_path(repo), NULL);
7682 if (error)
7683 goto done;
7685 error = tog_load_refs(repo, 0);
7686 if (error)
7687 goto done;
7689 if (commit_id_arg == NULL) {
7690 error = got_repo_match_object_id(&commit_id, &label,
7691 worktree ? got_worktree_get_head_ref_name(worktree) :
7692 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7693 if (error)
7694 goto done;
7695 head_ref_name = label;
7696 } else {
7697 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7698 if (error == NULL)
7699 head_ref_name = got_ref_get_name(ref);
7700 else if (error->code != GOT_ERR_NOT_REF)
7701 goto done;
7702 error = got_repo_match_object_id(&commit_id, NULL,
7703 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7704 if (error)
7705 goto done;
7708 error = got_object_open_as_commit(&commit, repo, commit_id);
7709 if (error)
7710 goto done;
7712 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7713 if (view == NULL) {
7714 error = got_error_from_errno("view_open");
7715 goto done;
7717 error = open_tree_view(view, commit_id, head_ref_name, repo);
7718 if (error)
7719 goto done;
7720 if (!got_path_is_root_dir(in_repo_path)) {
7721 error = tree_view_walk_path(&view->state.tree, commit,
7722 in_repo_path);
7723 if (error)
7724 goto done;
7727 if (worktree) {
7728 /* Release work tree lock. */
7729 got_worktree_close(worktree);
7730 worktree = NULL;
7732 error = view_loop(view);
7733 done:
7734 free(repo_path);
7735 free(cwd);
7736 free(commit_id);
7737 free(label);
7738 if (ref)
7739 got_ref_close(ref);
7740 if (repo) {
7741 const struct got_error *close_err = got_repo_close(repo);
7742 if (error == NULL)
7743 error = close_err;
7745 if (pack_fds) {
7746 const struct got_error *pack_err =
7747 got_repo_pack_fds_close(pack_fds);
7748 if (error == NULL)
7749 error = pack_err;
7751 tog_free_refs();
7752 return error;
7755 static const struct got_error *
7756 ref_view_load_refs(struct tog_ref_view_state *s)
7758 struct got_reflist_entry *sre;
7759 struct tog_reflist_entry *re;
7761 s->nrefs = 0;
7762 TAILQ_FOREACH(sre, &tog_refs, entry) {
7763 if (strncmp(got_ref_get_name(sre->ref),
7764 "refs/got/", 9) == 0 &&
7765 strncmp(got_ref_get_name(sre->ref),
7766 "refs/got/backup/", 16) != 0)
7767 continue;
7769 re = malloc(sizeof(*re));
7770 if (re == NULL)
7771 return got_error_from_errno("malloc");
7773 re->ref = got_ref_dup(sre->ref);
7774 if (re->ref == NULL)
7775 return got_error_from_errno("got_ref_dup");
7776 re->idx = s->nrefs++;
7777 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7780 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7781 return NULL;
7784 static void
7785 ref_view_free_refs(struct tog_ref_view_state *s)
7787 struct tog_reflist_entry *re;
7789 while (!TAILQ_EMPTY(&s->refs)) {
7790 re = TAILQ_FIRST(&s->refs);
7791 TAILQ_REMOVE(&s->refs, re, entry);
7792 got_ref_close(re->ref);
7793 free(re);
7797 static const struct got_error *
7798 open_ref_view(struct tog_view *view, struct got_repository *repo)
7800 const struct got_error *err = NULL;
7801 struct tog_ref_view_state *s = &view->state.ref;
7803 s->selected_entry = 0;
7804 s->repo = repo;
7806 TAILQ_INIT(&s->refs);
7807 STAILQ_INIT(&s->colors);
7809 err = ref_view_load_refs(s);
7810 if (err)
7811 return err;
7813 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7814 err = add_color(&s->colors, "^refs/heads/",
7815 TOG_COLOR_REFS_HEADS,
7816 get_color_value("TOG_COLOR_REFS_HEADS"));
7817 if (err)
7818 goto done;
7820 err = add_color(&s->colors, "^refs/tags/",
7821 TOG_COLOR_REFS_TAGS,
7822 get_color_value("TOG_COLOR_REFS_TAGS"));
7823 if (err)
7824 goto done;
7826 err = add_color(&s->colors, "^refs/remotes/",
7827 TOG_COLOR_REFS_REMOTES,
7828 get_color_value("TOG_COLOR_REFS_REMOTES"));
7829 if (err)
7830 goto done;
7832 err = add_color(&s->colors, "^refs/got/backup/",
7833 TOG_COLOR_REFS_BACKUP,
7834 get_color_value("TOG_COLOR_REFS_BACKUP"));
7835 if (err)
7836 goto done;
7839 view->show = show_ref_view;
7840 view->input = input_ref_view;
7841 view->close = close_ref_view;
7842 view->search_start = search_start_ref_view;
7843 view->search_next = search_next_ref_view;
7844 done:
7845 if (err)
7846 free_colors(&s->colors);
7847 return err;
7850 static const struct got_error *
7851 close_ref_view(struct tog_view *view)
7853 struct tog_ref_view_state *s = &view->state.ref;
7855 ref_view_free_refs(s);
7856 free_colors(&s->colors);
7858 return NULL;
7861 static const struct got_error *
7862 resolve_reflist_entry(struct got_object_id **commit_id,
7863 struct tog_reflist_entry *re, struct got_repository *repo)
7865 const struct got_error *err = NULL;
7866 struct got_object_id *obj_id;
7867 struct got_tag_object *tag = NULL;
7868 int obj_type;
7870 *commit_id = NULL;
7872 err = got_ref_resolve(&obj_id, repo, re->ref);
7873 if (err)
7874 return err;
7876 err = got_object_get_type(&obj_type, repo, obj_id);
7877 if (err)
7878 goto done;
7880 switch (obj_type) {
7881 case GOT_OBJ_TYPE_COMMIT:
7882 *commit_id = obj_id;
7883 break;
7884 case GOT_OBJ_TYPE_TAG:
7885 err = got_object_open_as_tag(&tag, repo, obj_id);
7886 if (err)
7887 goto done;
7888 free(obj_id);
7889 err = got_object_get_type(&obj_type, repo,
7890 got_object_tag_get_object_id(tag));
7891 if (err)
7892 goto done;
7893 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7894 err = got_error(GOT_ERR_OBJ_TYPE);
7895 goto done;
7897 *commit_id = got_object_id_dup(
7898 got_object_tag_get_object_id(tag));
7899 if (*commit_id == NULL) {
7900 err = got_error_from_errno("got_object_id_dup");
7901 goto done;
7903 break;
7904 default:
7905 err = got_error(GOT_ERR_OBJ_TYPE);
7906 break;
7909 done:
7910 if (tag)
7911 got_object_tag_close(tag);
7912 if (err) {
7913 free(*commit_id);
7914 *commit_id = NULL;
7916 return err;
7919 static const struct got_error *
7920 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7921 struct tog_reflist_entry *re, struct got_repository *repo)
7923 struct tog_view *log_view;
7924 const struct got_error *err = NULL;
7925 struct got_object_id *commit_id = NULL;
7927 *new_view = NULL;
7929 err = resolve_reflist_entry(&commit_id, re, repo);
7930 if (err) {
7931 if (err->code != GOT_ERR_OBJ_TYPE)
7932 return err;
7933 else
7934 return NULL;
7937 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7938 if (log_view == NULL) {
7939 err = got_error_from_errno("view_open");
7940 goto done;
7943 err = open_log_view(log_view, commit_id, repo,
7944 got_ref_get_name(re->ref), "", 0);
7945 done:
7946 if (err)
7947 view_close(log_view);
7948 else
7949 *new_view = log_view;
7950 free(commit_id);
7951 return err;
7954 static void
7955 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7957 struct tog_reflist_entry *re;
7958 int i = 0;
7960 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7961 return;
7963 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7964 while (i++ < maxscroll) {
7965 if (re == NULL)
7966 break;
7967 s->first_displayed_entry = re;
7968 re = TAILQ_PREV(re, tog_reflist_head, entry);
7972 static const struct got_error *
7973 ref_scroll_down(struct tog_view *view, int maxscroll)
7975 struct tog_ref_view_state *s = &view->state.ref;
7976 struct tog_reflist_entry *next, *last;
7977 int n = 0;
7979 if (s->first_displayed_entry)
7980 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7981 else
7982 next = TAILQ_FIRST(&s->refs);
7984 last = s->last_displayed_entry;
7985 while (next && n++ < maxscroll) {
7986 if (last) {
7987 s->last_displayed_entry = last;
7988 last = TAILQ_NEXT(last, entry);
7990 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7991 s->first_displayed_entry = next;
7992 next = TAILQ_NEXT(next, entry);
7996 return NULL;
7999 static const struct got_error *
8000 search_start_ref_view(struct tog_view *view)
8002 struct tog_ref_view_state *s = &view->state.ref;
8004 s->matched_entry = NULL;
8005 return NULL;
8008 static int
8009 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8011 regmatch_t regmatch;
8013 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8014 0) == 0;
8017 static const struct got_error *
8018 search_next_ref_view(struct tog_view *view)
8020 struct tog_ref_view_state *s = &view->state.ref;
8021 struct tog_reflist_entry *re = NULL;
8023 if (!view->searching) {
8024 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8025 return NULL;
8028 if (s->matched_entry) {
8029 if (view->searching == TOG_SEARCH_FORWARD) {
8030 if (s->selected_entry)
8031 re = TAILQ_NEXT(s->selected_entry, entry);
8032 else
8033 re = TAILQ_PREV(s->selected_entry,
8034 tog_reflist_head, entry);
8035 } else {
8036 if (s->selected_entry == NULL)
8037 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8038 else
8039 re = TAILQ_PREV(s->selected_entry,
8040 tog_reflist_head, entry);
8042 } else {
8043 if (s->selected_entry)
8044 re = s->selected_entry;
8045 else if (view->searching == TOG_SEARCH_FORWARD)
8046 re = TAILQ_FIRST(&s->refs);
8047 else
8048 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8051 while (1) {
8052 if (re == NULL) {
8053 if (s->matched_entry == NULL) {
8054 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8055 return NULL;
8057 if (view->searching == TOG_SEARCH_FORWARD)
8058 re = TAILQ_FIRST(&s->refs);
8059 else
8060 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8063 if (match_reflist_entry(re, &view->regex)) {
8064 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8065 s->matched_entry = re;
8066 break;
8069 if (view->searching == TOG_SEARCH_FORWARD)
8070 re = TAILQ_NEXT(re, entry);
8071 else
8072 re = TAILQ_PREV(re, tog_reflist_head, entry);
8075 if (s->matched_entry) {
8076 s->first_displayed_entry = s->matched_entry;
8077 s->selected = 0;
8080 return NULL;
8083 static const struct got_error *
8084 show_ref_view(struct tog_view *view)
8086 const struct got_error *err = NULL;
8087 struct tog_ref_view_state *s = &view->state.ref;
8088 struct tog_reflist_entry *re;
8089 char *line = NULL;
8090 wchar_t *wline;
8091 struct tog_color *tc;
8092 int width, n, scrollx;
8093 int limit = view->nlines;
8095 werase(view->window);
8097 s->ndisplayed = 0;
8098 if (view_is_hsplit_top(view))
8099 --limit; /* border */
8101 if (limit == 0)
8102 return NULL;
8104 re = s->first_displayed_entry;
8106 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8107 s->nrefs) == -1)
8108 return got_error_from_errno("asprintf");
8110 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8111 if (err) {
8112 free(line);
8113 return err;
8115 if (view_needs_focus_indication(view))
8116 wstandout(view->window);
8117 waddwstr(view->window, wline);
8118 while (width++ < view->ncols)
8119 waddch(view->window, ' ');
8120 if (view_needs_focus_indication(view))
8121 wstandend(view->window);
8122 free(wline);
8123 wline = NULL;
8124 free(line);
8125 line = NULL;
8126 if (--limit <= 0)
8127 return NULL;
8129 n = 0;
8130 view->maxx = 0;
8131 while (re && limit > 0) {
8132 char *line = NULL;
8133 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8135 if (s->show_date) {
8136 struct got_commit_object *ci;
8137 struct got_tag_object *tag;
8138 struct got_object_id *id;
8139 struct tm tm;
8140 time_t t;
8142 err = got_ref_resolve(&id, s->repo, re->ref);
8143 if (err)
8144 return err;
8145 err = got_object_open_as_tag(&tag, s->repo, id);
8146 if (err) {
8147 if (err->code != GOT_ERR_OBJ_TYPE) {
8148 free(id);
8149 return err;
8151 err = got_object_open_as_commit(&ci, s->repo,
8152 id);
8153 if (err) {
8154 free(id);
8155 return err;
8157 t = got_object_commit_get_committer_time(ci);
8158 got_object_commit_close(ci);
8159 } else {
8160 t = got_object_tag_get_tagger_time(tag);
8161 got_object_tag_close(tag);
8163 free(id);
8164 if (gmtime_r(&t, &tm) == NULL)
8165 return got_error_from_errno("gmtime_r");
8166 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8167 return got_error(GOT_ERR_NO_SPACE);
8169 if (got_ref_is_symbolic(re->ref)) {
8170 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8171 ymd : "", got_ref_get_name(re->ref),
8172 got_ref_get_symref_target(re->ref)) == -1)
8173 return got_error_from_errno("asprintf");
8174 } else if (s->show_ids) {
8175 struct got_object_id *id;
8176 char *id_str;
8177 err = got_ref_resolve(&id, s->repo, re->ref);
8178 if (err)
8179 return err;
8180 err = got_object_id_str(&id_str, id);
8181 if (err) {
8182 free(id);
8183 return err;
8185 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8186 got_ref_get_name(re->ref), id_str) == -1) {
8187 err = got_error_from_errno("asprintf");
8188 free(id);
8189 free(id_str);
8190 return err;
8192 free(id);
8193 free(id_str);
8194 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8195 got_ref_get_name(re->ref)) == -1)
8196 return got_error_from_errno("asprintf");
8198 /* use full line width to determine view->maxx */
8199 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8200 if (err) {
8201 free(line);
8202 return err;
8204 view->maxx = MAX(view->maxx, width);
8205 free(wline);
8206 wline = NULL;
8208 err = format_line(&wline, &width, &scrollx, line, view->x,
8209 view->ncols, 0, 0);
8210 if (err) {
8211 free(line);
8212 return err;
8214 if (n == s->selected) {
8215 if (view->focussed)
8216 wstandout(view->window);
8217 s->selected_entry = re;
8219 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8220 if (tc)
8221 wattr_on(view->window,
8222 COLOR_PAIR(tc->colorpair), NULL);
8223 waddwstr(view->window, &wline[scrollx]);
8224 if (tc)
8225 wattr_off(view->window,
8226 COLOR_PAIR(tc->colorpair), NULL);
8227 if (width < view->ncols)
8228 waddch(view->window, '\n');
8229 if (n == s->selected && view->focussed)
8230 wstandend(view->window);
8231 free(line);
8232 free(wline);
8233 wline = NULL;
8234 n++;
8235 s->ndisplayed++;
8236 s->last_displayed_entry = re;
8238 limit--;
8239 re = TAILQ_NEXT(re, entry);
8242 view_border(view);
8243 return err;
8246 static const struct got_error *
8247 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8248 struct tog_reflist_entry *re, struct got_repository *repo)
8250 const struct got_error *err = NULL;
8251 struct got_object_id *commit_id = NULL;
8252 struct tog_view *tree_view;
8254 *new_view = NULL;
8256 err = resolve_reflist_entry(&commit_id, re, repo);
8257 if (err) {
8258 if (err->code != GOT_ERR_OBJ_TYPE)
8259 return err;
8260 else
8261 return NULL;
8265 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8266 if (tree_view == NULL) {
8267 err = got_error_from_errno("view_open");
8268 goto done;
8271 err = open_tree_view(tree_view, commit_id,
8272 got_ref_get_name(re->ref), repo);
8273 if (err)
8274 goto done;
8276 *new_view = tree_view;
8277 done:
8278 free(commit_id);
8279 return err;
8282 static const struct got_error *
8283 ref_goto_line(struct tog_view *view, int nlines)
8285 const struct got_error *err = NULL;
8286 struct tog_ref_view_state *s = &view->state.ref;
8287 int g, idx = s->selected_entry->idx;
8289 g = view->gline;
8290 view->gline = 0;
8292 if (g == 0)
8293 g = 1;
8294 else if (g > s->nrefs)
8295 g = s->nrefs;
8297 if (g >= s->first_displayed_entry->idx + 1 &&
8298 g <= s->last_displayed_entry->idx + 1 &&
8299 g - s->first_displayed_entry->idx - 1 < nlines) {
8300 s->selected = g - s->first_displayed_entry->idx - 1;
8301 return NULL;
8304 if (idx + 1 < g) {
8305 err = ref_scroll_down(view, g - idx - 1);
8306 if (err)
8307 return err;
8308 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8309 s->first_displayed_entry->idx + s->selected < g &&
8310 s->selected < s->ndisplayed - 1)
8311 s->selected = g - s->first_displayed_entry->idx - 1;
8312 } else if (idx + 1 > g)
8313 ref_scroll_up(s, idx - g + 1);
8315 if (g < nlines && s->first_displayed_entry->idx == 0)
8316 s->selected = g - 1;
8318 return NULL;
8322 static const struct got_error *
8323 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8325 const struct got_error *err = NULL;
8326 struct tog_ref_view_state *s = &view->state.ref;
8327 struct tog_reflist_entry *re;
8328 int n, nscroll = view->nlines - 1;
8330 if (view->gline)
8331 return ref_goto_line(view, nscroll);
8333 switch (ch) {
8334 case '0':
8335 case '$':
8336 case KEY_RIGHT:
8337 case 'l':
8338 case KEY_LEFT:
8339 case 'h':
8340 horizontal_scroll_input(view, ch);
8341 break;
8342 case 'i':
8343 s->show_ids = !s->show_ids;
8344 view->count = 0;
8345 break;
8346 case 'm':
8347 s->show_date = !s->show_date;
8348 view->count = 0;
8349 break;
8350 case 'o':
8351 s->sort_by_date = !s->sort_by_date;
8352 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8353 view->count = 0;
8354 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8355 got_ref_cmp_by_commit_timestamp_descending :
8356 tog_ref_cmp_by_name, s->repo);
8357 if (err)
8358 break;
8359 got_reflist_object_id_map_free(tog_refs_idmap);
8360 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8361 &tog_refs, s->repo);
8362 if (err)
8363 break;
8364 ref_view_free_refs(s);
8365 err = ref_view_load_refs(s);
8366 break;
8367 case KEY_ENTER:
8368 case '\r':
8369 view->count = 0;
8370 if (!s->selected_entry)
8371 break;
8372 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8373 break;
8374 case 'T':
8375 view->count = 0;
8376 if (!s->selected_entry)
8377 break;
8378 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8379 break;
8380 case 'g':
8381 case '=':
8382 case KEY_HOME:
8383 s->selected = 0;
8384 view->count = 0;
8385 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8386 break;
8387 case 'G':
8388 case '*':
8389 case KEY_END: {
8390 int eos = view->nlines - 1;
8392 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8393 --eos; /* border */
8394 s->selected = 0;
8395 view->count = 0;
8396 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8397 for (n = 0; n < eos; n++) {
8398 if (re == NULL)
8399 break;
8400 s->first_displayed_entry = re;
8401 re = TAILQ_PREV(re, tog_reflist_head, entry);
8403 if (n > 0)
8404 s->selected = n - 1;
8405 break;
8407 case 'k':
8408 case KEY_UP:
8409 case CTRL('p'):
8410 if (s->selected > 0) {
8411 s->selected--;
8412 break;
8414 ref_scroll_up(s, 1);
8415 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8416 view->count = 0;
8417 break;
8418 case CTRL('u'):
8419 case 'u':
8420 nscroll /= 2;
8421 /* FALL THROUGH */
8422 case KEY_PPAGE:
8423 case CTRL('b'):
8424 case 'b':
8425 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8426 s->selected -= MIN(nscroll, s->selected);
8427 ref_scroll_up(s, MAX(0, nscroll));
8428 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8429 view->count = 0;
8430 break;
8431 case 'j':
8432 case KEY_DOWN:
8433 case CTRL('n'):
8434 if (s->selected < s->ndisplayed - 1) {
8435 s->selected++;
8436 break;
8438 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8439 /* can't scroll any further */
8440 view->count = 0;
8441 break;
8443 ref_scroll_down(view, 1);
8444 break;
8445 case CTRL('d'):
8446 case 'd':
8447 nscroll /= 2;
8448 /* FALL THROUGH */
8449 case KEY_NPAGE:
8450 case CTRL('f'):
8451 case 'f':
8452 case ' ':
8453 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8454 /* can't scroll any further; move cursor down */
8455 if (s->selected < s->ndisplayed - 1)
8456 s->selected += MIN(nscroll,
8457 s->ndisplayed - s->selected - 1);
8458 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8459 s->selected += s->ndisplayed - s->selected - 1;
8460 view->count = 0;
8461 break;
8463 ref_scroll_down(view, nscroll);
8464 break;
8465 case CTRL('l'):
8466 view->count = 0;
8467 tog_free_refs();
8468 err = tog_load_refs(s->repo, s->sort_by_date);
8469 if (err)
8470 break;
8471 ref_view_free_refs(s);
8472 err = ref_view_load_refs(s);
8473 break;
8474 case KEY_RESIZE:
8475 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8476 s->selected = view->nlines - 2;
8477 break;
8478 default:
8479 view->count = 0;
8480 break;
8483 return err;
8486 __dead static void
8487 usage_ref(void)
8489 endwin();
8490 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8491 getprogname());
8492 exit(1);
8495 static const struct got_error *
8496 cmd_ref(int argc, char *argv[])
8498 const struct got_error *error;
8499 struct got_repository *repo = NULL;
8500 struct got_worktree *worktree = NULL;
8501 char *cwd = NULL, *repo_path = NULL;
8502 int ch;
8503 struct tog_view *view;
8504 int *pack_fds = NULL;
8506 while ((ch = getopt(argc, argv, "r:")) != -1) {
8507 switch (ch) {
8508 case 'r':
8509 repo_path = realpath(optarg, NULL);
8510 if (repo_path == NULL)
8511 return got_error_from_errno2("realpath",
8512 optarg);
8513 break;
8514 default:
8515 usage_ref();
8516 /* NOTREACHED */
8520 argc -= optind;
8521 argv += optind;
8523 if (argc > 1)
8524 usage_ref();
8526 error = got_repo_pack_fds_open(&pack_fds);
8527 if (error != NULL)
8528 goto done;
8530 if (repo_path == NULL) {
8531 cwd = getcwd(NULL, 0);
8532 if (cwd == NULL)
8533 return got_error_from_errno("getcwd");
8534 error = got_worktree_open(&worktree, cwd);
8535 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8536 goto done;
8537 if (worktree)
8538 repo_path =
8539 strdup(got_worktree_get_repo_path(worktree));
8540 else
8541 repo_path = strdup(cwd);
8542 if (repo_path == NULL) {
8543 error = got_error_from_errno("strdup");
8544 goto done;
8548 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8549 if (error != NULL)
8550 goto done;
8552 init_curses();
8554 error = apply_unveil(got_repo_get_path(repo), NULL);
8555 if (error)
8556 goto done;
8558 error = tog_load_refs(repo, 0);
8559 if (error)
8560 goto done;
8562 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8563 if (view == NULL) {
8564 error = got_error_from_errno("view_open");
8565 goto done;
8568 error = open_ref_view(view, repo);
8569 if (error)
8570 goto done;
8572 if (worktree) {
8573 /* Release work tree lock. */
8574 got_worktree_close(worktree);
8575 worktree = NULL;
8577 error = view_loop(view);
8578 done:
8579 free(repo_path);
8580 free(cwd);
8581 if (repo) {
8582 const struct got_error *close_err = got_repo_close(repo);
8583 if (close_err)
8584 error = close_err;
8586 if (pack_fds) {
8587 const struct got_error *pack_err =
8588 got_repo_pack_fds_close(pack_fds);
8589 if (error == NULL)
8590 error = pack_err;
8592 tog_free_refs();
8593 return error;
8596 static const struct got_error*
8597 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8598 const char *str)
8600 size_t len;
8602 if (win == NULL)
8603 win = stdscr;
8605 len = strlen(str);
8606 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8608 if (focus)
8609 wstandout(win);
8610 if (mvwprintw(win, y, x, "%s", str) == ERR)
8611 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8612 if (focus)
8613 wstandend(win);
8615 return NULL;
8618 static const struct got_error *
8619 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8621 off_t *p;
8623 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8624 if (p == NULL) {
8625 free(*line_offsets);
8626 *line_offsets = NULL;
8627 return got_error_from_errno("reallocarray");
8630 *line_offsets = p;
8631 (*line_offsets)[*nlines] = off;
8632 ++(*nlines);
8633 return NULL;
8636 static const struct got_error *
8637 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8639 *ret = 0;
8641 for (;n > 0; --n, ++km) {
8642 char *t0, *t, *k;
8643 size_t len = 1;
8645 if (km->keys == NULL)
8646 continue;
8648 t = t0 = strdup(km->keys);
8649 if (t0 == NULL)
8650 return got_error_from_errno("strdup");
8652 len += strlen(t);
8653 while ((k = strsep(&t, " ")) != NULL)
8654 len += strlen(k) > 1 ? 2 : 0;
8655 free(t0);
8656 *ret = MAX(*ret, len);
8659 return NULL;
8663 * Write keymap section headers, keys, and key info in km to f.
8664 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8665 * wrap control and symbolic keys in guillemets, else use <>.
8667 static const struct got_error *
8668 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8670 int n, len = width;
8672 if (km->keys) {
8673 static const char *u8_glyph[] = {
8674 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8675 "\xe2\x80\xba" /* U+203A (utf8 >) */
8677 char *t0, *t, *k;
8678 int cs, s, first = 1;
8680 cs = got_locale_is_utf8();
8682 t = t0 = strdup(km->keys);
8683 if (t0 == NULL)
8684 return got_error_from_errno("strdup");
8686 len = strlen(km->keys);
8687 while ((k = strsep(&t, " ")) != NULL) {
8688 s = strlen(k) > 1; /* control or symbolic key */
8689 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8690 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8691 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8692 if (n < 0) {
8693 free(t0);
8694 return got_error_from_errno("fprintf");
8696 first = 0;
8697 len += s ? 2 : 0;
8698 *off += n;
8700 free(t0);
8702 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8703 if (n < 0)
8704 return got_error_from_errno("fprintf");
8705 *off += n;
8707 return NULL;
8710 static const struct got_error *
8711 format_help(struct tog_help_view_state *s)
8713 const struct got_error *err = NULL;
8714 off_t off = 0;
8715 int i, max, n, show = s->all;
8716 static const struct tog_key_map km[] = {
8717 #define KEYMAP_(info, type) { NULL, (info), type }
8718 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8719 GENERATE_HELP
8720 #undef KEYMAP_
8721 #undef KEY_
8724 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8725 if (err)
8726 return err;
8728 n = nitems(km);
8729 err = max_key_str(&max, km, n);
8730 if (err)
8731 return err;
8733 for (i = 0; i < n; ++i) {
8734 if (km[i].keys == NULL) {
8735 show = s->all;
8736 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8737 km[i].type == s->type || s->all)
8738 show = 1;
8740 if (show) {
8741 err = format_help_line(&off, s->f, &km[i], max);
8742 if (err)
8743 return err;
8744 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8745 if (err)
8746 return err;
8749 fputc('\n', s->f);
8750 ++off;
8751 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8752 return err;
8755 static const struct got_error *
8756 create_help(struct tog_help_view_state *s)
8758 FILE *f;
8759 const struct got_error *err;
8761 free(s->line_offsets);
8762 s->line_offsets = NULL;
8763 s->nlines = 0;
8765 f = got_opentemp();
8766 if (f == NULL)
8767 return got_error_from_errno("got_opentemp");
8768 s->f = f;
8770 err = format_help(s);
8771 if (err)
8772 return err;
8774 if (s->f && fflush(s->f) != 0)
8775 return got_error_from_errno("fflush");
8777 return NULL;
8780 static const struct got_error *
8781 search_start_help_view(struct tog_view *view)
8783 view->state.help.matched_line = 0;
8784 return NULL;
8787 static void
8788 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8789 size_t *nlines, int **first, int **last, int **match, int **selected)
8791 struct tog_help_view_state *s = &view->state.help;
8793 *f = s->f;
8794 *nlines = s->nlines;
8795 *line_offsets = s->line_offsets;
8796 *match = &s->matched_line;
8797 *first = &s->first_displayed_line;
8798 *last = &s->last_displayed_line;
8799 *selected = &s->selected_line;
8802 static const struct got_error *
8803 show_help_view(struct tog_view *view)
8805 struct tog_help_view_state *s = &view->state.help;
8806 const struct got_error *err;
8807 regmatch_t *regmatch = &view->regmatch;
8808 wchar_t *wline;
8809 char *line;
8810 ssize_t linelen;
8811 size_t linesz = 0;
8812 int width, nprinted = 0, rc = 0;
8813 int eos = view->nlines;
8815 if (view_is_hsplit_top(view))
8816 --eos; /* account for border */
8818 s->lineno = 0;
8819 rewind(s->f);
8820 werase(view->window);
8822 if (view->gline > s->nlines - 1)
8823 view->gline = s->nlines - 1;
8825 err = win_draw_center(view->window, 0, 0, view->ncols,
8826 view_needs_focus_indication(view),
8827 "tog help (press q to return to tog)");
8828 if (err)
8829 return err;
8830 if (eos <= 1)
8831 return NULL;
8832 waddstr(view->window, "\n\n");
8833 eos -= 2;
8835 s->eof = 0;
8836 view->maxx = 0;
8837 line = NULL;
8838 while (eos > 0 && nprinted < eos) {
8839 attr_t attr = 0;
8841 linelen = getline(&line, &linesz, s->f);
8842 if (linelen == -1) {
8843 if (!feof(s->f)) {
8844 free(line);
8845 return got_ferror(s->f, GOT_ERR_IO);
8847 s->eof = 1;
8848 break;
8850 if (++s->lineno < s->first_displayed_line)
8851 continue;
8852 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8853 continue;
8854 if (s->lineno == view->hiline)
8855 attr = A_STANDOUT;
8857 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8858 view->x ? 1 : 0);
8859 if (err) {
8860 free(line);
8861 return err;
8863 view->maxx = MAX(view->maxx, width);
8864 free(wline);
8865 wline = NULL;
8867 if (attr)
8868 wattron(view->window, attr);
8869 if (s->first_displayed_line + nprinted == s->matched_line &&
8870 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8871 err = add_matched_line(&width, line, view->ncols - 1, 0,
8872 view->window, view->x, regmatch);
8873 if (err) {
8874 free(line);
8875 return err;
8877 } else {
8878 int skip;
8880 err = format_line(&wline, &width, &skip, line,
8881 view->x, view->ncols, 0, view->x ? 1 : 0);
8882 if (err) {
8883 free(line);
8884 return err;
8886 waddwstr(view->window, &wline[skip]);
8887 free(wline);
8888 wline = NULL;
8890 if (s->lineno == view->hiline) {
8891 while (width++ < view->ncols)
8892 waddch(view->window, ' ');
8893 } else {
8894 if (width < view->ncols)
8895 waddch(view->window, '\n');
8897 if (attr)
8898 wattroff(view->window, attr);
8899 if (++nprinted == 1)
8900 s->first_displayed_line = s->lineno;
8902 free(line);
8903 if (nprinted > 0)
8904 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8905 else
8906 s->last_displayed_line = s->first_displayed_line;
8908 view_border(view);
8910 if (s->eof) {
8911 rc = waddnstr(view->window,
8912 "See the tog(1) manual page for full documentation",
8913 view->ncols - 1);
8914 if (rc == ERR)
8915 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8916 } else {
8917 wmove(view->window, view->nlines - 1, 0);
8918 wclrtoeol(view->window);
8919 wstandout(view->window);
8920 rc = waddnstr(view->window, "scroll down for more...",
8921 view->ncols - 1);
8922 if (rc == ERR)
8923 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8924 if (getcurx(view->window) < view->ncols - 6) {
8925 rc = wprintw(view->window, "[%.0f%%]",
8926 100.00 * s->last_displayed_line / s->nlines);
8927 if (rc == ERR)
8928 return got_error_msg(GOT_ERR_IO, "wprintw");
8930 wstandend(view->window);
8933 return NULL;
8936 static const struct got_error *
8937 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8939 struct tog_help_view_state *s = &view->state.help;
8940 const struct got_error *err = NULL;
8941 char *line = NULL;
8942 ssize_t linelen;
8943 size_t linesz = 0;
8944 int eos, nscroll;
8946 eos = nscroll = view->nlines;
8947 if (view_is_hsplit_top(view))
8948 --eos; /* border */
8950 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8952 switch (ch) {
8953 case '0':
8954 case '$':
8955 case KEY_RIGHT:
8956 case 'l':
8957 case KEY_LEFT:
8958 case 'h':
8959 horizontal_scroll_input(view, ch);
8960 break;
8961 case 'g':
8962 case KEY_HOME:
8963 s->first_displayed_line = 1;
8964 view->count = 0;
8965 break;
8966 case 'G':
8967 case KEY_END:
8968 view->count = 0;
8969 if (s->eof)
8970 break;
8971 s->first_displayed_line = (s->nlines - eos) + 3;
8972 s->eof = 1;
8973 break;
8974 case 'k':
8975 case KEY_UP:
8976 if (s->first_displayed_line > 1)
8977 --s->first_displayed_line;
8978 else
8979 view->count = 0;
8980 break;
8981 case CTRL('u'):
8982 case 'u':
8983 nscroll /= 2;
8984 /* FALL THROUGH */
8985 case KEY_PPAGE:
8986 case CTRL('b'):
8987 case 'b':
8988 if (s->first_displayed_line == 1) {
8989 view->count = 0;
8990 break;
8992 while (--nscroll > 0 && s->first_displayed_line > 1)
8993 s->first_displayed_line--;
8994 break;
8995 case 'j':
8996 case KEY_DOWN:
8997 case CTRL('n'):
8998 if (!s->eof)
8999 ++s->first_displayed_line;
9000 else
9001 view->count = 0;
9002 break;
9003 case CTRL('d'):
9004 case 'd':
9005 nscroll /= 2;
9006 /* FALL THROUGH */
9007 case KEY_NPAGE:
9008 case CTRL('f'):
9009 case 'f':
9010 case ' ':
9011 if (s->eof) {
9012 view->count = 0;
9013 break;
9015 while (!s->eof && --nscroll > 0) {
9016 linelen = getline(&line, &linesz, s->f);
9017 s->first_displayed_line++;
9018 if (linelen == -1) {
9019 if (feof(s->f))
9020 s->eof = 1;
9021 else
9022 err = got_ferror(s->f, GOT_ERR_IO);
9023 break;
9026 free(line);
9027 break;
9028 default:
9029 view->count = 0;
9030 break;
9033 return err;
9036 static const struct got_error *
9037 close_help_view(struct tog_view *view)
9039 struct tog_help_view_state *s = &view->state.help;
9041 free(s->line_offsets);
9042 s->line_offsets = NULL;
9043 if (fclose(s->f) == EOF)
9044 return got_error_from_errno("fclose");
9046 return NULL;
9049 static const struct got_error *
9050 reset_help_view(struct tog_view *view)
9052 struct tog_help_view_state *s = &view->state.help;
9055 if (s->f && fclose(s->f) == EOF)
9056 return got_error_from_errno("fclose");
9058 wclear(view->window);
9059 view->count = 0;
9060 view->x = 0;
9061 s->all = !s->all;
9062 s->first_displayed_line = 1;
9063 s->last_displayed_line = view->nlines;
9064 s->matched_line = 0;
9066 return create_help(s);
9069 static const struct got_error *
9070 open_help_view(struct tog_view *view, struct tog_view *parent)
9072 const struct got_error *err = NULL;
9073 struct tog_help_view_state *s = &view->state.help;
9075 s->type = (enum tog_keymap_type)parent->type;
9076 s->first_displayed_line = 1;
9077 s->last_displayed_line = view->nlines;
9078 s->selected_line = 1;
9080 view->show = show_help_view;
9081 view->input = input_help_view;
9082 view->reset = reset_help_view;
9083 view->close = close_help_view;
9084 view->search_start = search_start_help_view;
9085 view->search_setup = search_setup_help_view;
9086 view->search_next = search_next_view_match;
9088 err = create_help(s);
9089 return err;
9092 static const struct got_error *
9093 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9094 enum tog_view_type request, int y, int x)
9096 const struct got_error *err = NULL;
9098 *new_view = NULL;
9100 switch (request) {
9101 case TOG_VIEW_DIFF:
9102 if (view->type == TOG_VIEW_LOG) {
9103 struct tog_log_view_state *s = &view->state.log;
9105 err = open_diff_view_for_commit(new_view, y, x,
9106 s->selected_entry->commit, s->selected_entry->id,
9107 view, s->repo);
9108 } else
9109 return got_error_msg(GOT_ERR_NOT_IMPL,
9110 "parent/child view pair not supported");
9111 break;
9112 case TOG_VIEW_BLAME:
9113 if (view->type == TOG_VIEW_TREE) {
9114 struct tog_tree_view_state *s = &view->state.tree;
9116 err = blame_tree_entry(new_view, y, x,
9117 s->selected_entry, &s->parents, s->commit_id,
9118 s->repo);
9119 } else
9120 return got_error_msg(GOT_ERR_NOT_IMPL,
9121 "parent/child view pair not supported");
9122 break;
9123 case TOG_VIEW_LOG:
9124 if (view->type == TOG_VIEW_BLAME)
9125 err = log_annotated_line(new_view, y, x,
9126 view->state.blame.repo, view->state.blame.id_to_log);
9127 else if (view->type == TOG_VIEW_TREE)
9128 err = log_selected_tree_entry(new_view, y, x,
9129 &view->state.tree);
9130 else if (view->type == TOG_VIEW_REF)
9131 err = log_ref_entry(new_view, y, x,
9132 view->state.ref.selected_entry,
9133 view->state.ref.repo);
9134 else
9135 return got_error_msg(GOT_ERR_NOT_IMPL,
9136 "parent/child view pair not supported");
9137 break;
9138 case TOG_VIEW_TREE:
9139 if (view->type == TOG_VIEW_LOG)
9140 err = browse_commit_tree(new_view, y, x,
9141 view->state.log.selected_entry,
9142 view->state.log.in_repo_path,
9143 view->state.log.head_ref_name,
9144 view->state.log.repo);
9145 else if (view->type == TOG_VIEW_REF)
9146 err = browse_ref_tree(new_view, y, x,
9147 view->state.ref.selected_entry,
9148 view->state.ref.repo);
9149 else
9150 return got_error_msg(GOT_ERR_NOT_IMPL,
9151 "parent/child view pair not supported");
9152 break;
9153 case TOG_VIEW_REF:
9154 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9155 if (*new_view == NULL)
9156 return got_error_from_errno("view_open");
9157 if (view->type == TOG_VIEW_LOG)
9158 err = open_ref_view(*new_view, view->state.log.repo);
9159 else if (view->type == TOG_VIEW_TREE)
9160 err = open_ref_view(*new_view, view->state.tree.repo);
9161 else
9162 err = got_error_msg(GOT_ERR_NOT_IMPL,
9163 "parent/child view pair not supported");
9164 if (err)
9165 view_close(*new_view);
9166 break;
9167 case TOG_VIEW_HELP:
9168 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9169 if (*new_view == NULL)
9170 return got_error_from_errno("view_open");
9171 err = open_help_view(*new_view, view);
9172 if (err)
9173 view_close(*new_view);
9174 break;
9175 default:
9176 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9179 return err;
9183 * If view was scrolled down to move the selected line into view when opening a
9184 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9186 static void
9187 offset_selection_up(struct tog_view *view)
9189 switch (view->type) {
9190 case TOG_VIEW_BLAME: {
9191 struct tog_blame_view_state *s = &view->state.blame;
9192 if (s->first_displayed_line == 1) {
9193 s->selected_line = MAX(s->selected_line - view->offset,
9194 1);
9195 break;
9197 if (s->first_displayed_line > view->offset)
9198 s->first_displayed_line -= view->offset;
9199 else
9200 s->first_displayed_line = 1;
9201 s->selected_line += view->offset;
9202 break;
9204 case TOG_VIEW_LOG:
9205 log_scroll_up(&view->state.log, view->offset);
9206 view->state.log.selected += view->offset;
9207 break;
9208 case TOG_VIEW_REF:
9209 ref_scroll_up(&view->state.ref, view->offset);
9210 view->state.ref.selected += view->offset;
9211 break;
9212 case TOG_VIEW_TREE:
9213 tree_scroll_up(&view->state.tree, view->offset);
9214 view->state.tree.selected += view->offset;
9215 break;
9216 default:
9217 break;
9220 view->offset = 0;
9224 * If the selected line is in the section of screen covered by the bottom split,
9225 * scroll down offset lines to move it into view and index its new position.
9227 static const struct got_error *
9228 offset_selection_down(struct tog_view *view)
9230 const struct got_error *err = NULL;
9231 const struct got_error *(*scrolld)(struct tog_view *, int);
9232 int *selected = NULL;
9233 int header, offset;
9235 switch (view->type) {
9236 case TOG_VIEW_BLAME: {
9237 struct tog_blame_view_state *s = &view->state.blame;
9238 header = 3;
9239 scrolld = NULL;
9240 if (s->selected_line > view->nlines - header) {
9241 offset = abs(view->nlines - s->selected_line - header);
9242 s->first_displayed_line += offset;
9243 s->selected_line -= offset;
9244 view->offset = offset;
9246 break;
9248 case TOG_VIEW_LOG: {
9249 struct tog_log_view_state *s = &view->state.log;
9250 scrolld = &log_scroll_down;
9251 header = view_is_parent_view(view) ? 3 : 2;
9252 selected = &s->selected;
9253 break;
9255 case TOG_VIEW_REF: {
9256 struct tog_ref_view_state *s = &view->state.ref;
9257 scrolld = &ref_scroll_down;
9258 header = 3;
9259 selected = &s->selected;
9260 break;
9262 case TOG_VIEW_TREE: {
9263 struct tog_tree_view_state *s = &view->state.tree;
9264 scrolld = &tree_scroll_down;
9265 header = 5;
9266 selected = &s->selected;
9267 break;
9269 default:
9270 selected = NULL;
9271 scrolld = NULL;
9272 header = 0;
9273 break;
9276 if (selected && *selected > view->nlines - header) {
9277 offset = abs(view->nlines - *selected - header);
9278 view->offset = offset;
9279 if (scrolld && offset) {
9280 err = scrolld(view, offset);
9281 *selected -= offset;
9285 return err;
9288 static void
9289 list_commands(FILE *fp)
9291 size_t i;
9293 fprintf(fp, "commands:");
9294 for (i = 0; i < nitems(tog_commands); i++) {
9295 const struct tog_cmd *cmd = &tog_commands[i];
9296 fprintf(fp, " %s", cmd->name);
9298 fputc('\n', fp);
9301 __dead static void
9302 usage(int hflag, int status)
9304 FILE *fp = (status == 0) ? stdout : stderr;
9306 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9307 getprogname());
9308 if (hflag) {
9309 fprintf(fp, "lazy usage: %s path\n", getprogname());
9310 list_commands(fp);
9312 exit(status);
9315 static char **
9316 make_argv(int argc, ...)
9318 va_list ap;
9319 char **argv;
9320 int i;
9322 va_start(ap, argc);
9324 argv = calloc(argc, sizeof(char *));
9325 if (argv == NULL)
9326 err(1, "calloc");
9327 for (i = 0; i < argc; i++) {
9328 argv[i] = strdup(va_arg(ap, char *));
9329 if (argv[i] == NULL)
9330 err(1, "strdup");
9333 va_end(ap);
9334 return argv;
9338 * Try to convert 'tog path' into a 'tog log path' command.
9339 * The user could simply have mistyped the command rather than knowingly
9340 * provided a path. So check whether argv[0] can in fact be resolved
9341 * to a path in the HEAD commit and print a special error if not.
9342 * This hack is for mpi@ <3
9344 static const struct got_error *
9345 tog_log_with_path(int argc, char *argv[])
9347 const struct got_error *error = NULL, *close_err;
9348 const struct tog_cmd *cmd = NULL;
9349 struct got_repository *repo = NULL;
9350 struct got_worktree *worktree = NULL;
9351 struct got_object_id *commit_id = NULL, *id = NULL;
9352 struct got_commit_object *commit = NULL;
9353 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9354 char *commit_id_str = NULL, **cmd_argv = NULL;
9355 int *pack_fds = NULL;
9357 cwd = getcwd(NULL, 0);
9358 if (cwd == NULL)
9359 return got_error_from_errno("getcwd");
9361 error = got_repo_pack_fds_open(&pack_fds);
9362 if (error != NULL)
9363 goto done;
9365 error = got_worktree_open(&worktree, cwd);
9366 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9367 goto done;
9369 if (worktree)
9370 repo_path = strdup(got_worktree_get_repo_path(worktree));
9371 else
9372 repo_path = strdup(cwd);
9373 if (repo_path == NULL) {
9374 error = got_error_from_errno("strdup");
9375 goto done;
9378 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9379 if (error != NULL)
9380 goto done;
9382 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9383 repo, worktree);
9384 if (error)
9385 goto done;
9387 error = tog_load_refs(repo, 0);
9388 if (error)
9389 goto done;
9390 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9391 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9392 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9393 if (error)
9394 goto done;
9396 if (worktree) {
9397 got_worktree_close(worktree);
9398 worktree = NULL;
9401 error = got_object_open_as_commit(&commit, repo, commit_id);
9402 if (error)
9403 goto done;
9405 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9406 if (error) {
9407 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9408 goto done;
9409 fprintf(stderr, "%s: '%s' is no known command or path\n",
9410 getprogname(), argv[0]);
9411 usage(1, 1);
9412 /* not reached */
9415 error = got_object_id_str(&commit_id_str, commit_id);
9416 if (error)
9417 goto done;
9419 cmd = &tog_commands[0]; /* log */
9420 argc = 4;
9421 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9422 error = cmd->cmd_main(argc, cmd_argv);
9423 done:
9424 if (repo) {
9425 close_err = got_repo_close(repo);
9426 if (error == NULL)
9427 error = close_err;
9429 if (commit)
9430 got_object_commit_close(commit);
9431 if (worktree)
9432 got_worktree_close(worktree);
9433 if (pack_fds) {
9434 const struct got_error *pack_err =
9435 got_repo_pack_fds_close(pack_fds);
9436 if (error == NULL)
9437 error = pack_err;
9439 free(id);
9440 free(commit_id_str);
9441 free(commit_id);
9442 free(cwd);
9443 free(repo_path);
9444 free(in_repo_path);
9445 if (cmd_argv) {
9446 int i;
9447 for (i = 0; i < argc; i++)
9448 free(cmd_argv[i]);
9449 free(cmd_argv);
9451 tog_free_refs();
9452 return error;
9455 int
9456 main(int argc, char *argv[])
9458 const struct got_error *error = NULL;
9459 const struct tog_cmd *cmd = NULL;
9460 int ch, hflag = 0, Vflag = 0;
9461 char **cmd_argv = NULL;
9462 static const struct option longopts[] = {
9463 { "version", no_argument, NULL, 'V' },
9464 { NULL, 0, NULL, 0}
9466 char *diff_algo_str = NULL;
9468 setlocale(LC_CTYPE, "");
9470 #ifndef PROFILE
9471 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9472 NULL) == -1)
9473 err(1, "pledge");
9474 #endif
9476 if (!isatty(STDIN_FILENO))
9477 errx(1, "standard input is not a tty");
9479 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9480 switch (ch) {
9481 case 'h':
9482 hflag = 1;
9483 break;
9484 case 'V':
9485 Vflag = 1;
9486 break;
9487 default:
9488 usage(hflag, 1);
9489 /* NOTREACHED */
9493 argc -= optind;
9494 argv += optind;
9495 optind = 1;
9496 optreset = 1;
9498 if (Vflag) {
9499 got_version_print_str();
9500 return 0;
9503 if (argc == 0) {
9504 if (hflag)
9505 usage(hflag, 0);
9506 /* Build an argument vector which runs a default command. */
9507 cmd = &tog_commands[0];
9508 argc = 1;
9509 cmd_argv = make_argv(argc, cmd->name);
9510 } else {
9511 size_t i;
9513 /* Did the user specify a command? */
9514 for (i = 0; i < nitems(tog_commands); i++) {
9515 if (strncmp(tog_commands[i].name, argv[0],
9516 strlen(argv[0])) == 0) {
9517 cmd = &tog_commands[i];
9518 break;
9523 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9524 if (diff_algo_str) {
9525 if (strcasecmp(diff_algo_str, "patience") == 0)
9526 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9527 if (strcasecmp(diff_algo_str, "myers") == 0)
9528 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9531 if (cmd == NULL) {
9532 if (argc != 1)
9533 usage(0, 1);
9534 /* No command specified; try log with a path */
9535 error = tog_log_with_path(argc, argv);
9536 } else {
9537 if (hflag)
9538 cmd->cmd_usage();
9539 else
9540 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9543 endwin();
9544 if (cmd_argv) {
9545 int i;
9546 for (i = 0; i < argc; i++)
9547 free(cmd_argv[i]);
9548 free(cmd_argv);
9551 if (error && error->code != GOT_ERR_CANCELLED &&
9552 error->code != GOT_ERR_EOF &&
9553 error->code != GOT_ERR_PRIVSEP_EXIT &&
9554 error->code != GOT_ERR_PRIVSEP_PIPE &&
9555 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9556 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9557 return 0;