Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #if defined(__FreeBSD__) || defined(__APPLE__)
24 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
25 #endif
26 #include <curses.h>
27 #include <panel.h>
28 #include <locale.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_compat.h"
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 TOG_VIEW_HELP
112 };
114 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
115 enum tog_keymap_type {
116 TOG_KEYMAP_KEYS = -2,
117 TOG_KEYMAP_GLOBAL,
118 TOG_KEYMAP_DIFF,
119 TOG_KEYMAP_LOG,
120 TOG_KEYMAP_BLAME,
121 TOG_KEYMAP_TREE,
122 TOG_KEYMAP_REF,
123 TOG_KEYMAP_HELP
124 };
126 enum tog_view_mode {
127 TOG_VIEW_SPLIT_NONE,
128 TOG_VIEW_SPLIT_VERT,
129 TOG_VIEW_SPLIT_HRZN
130 };
132 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
134 #define TOG_EOF_STRING "(END)"
136 struct commit_queue_entry {
137 TAILQ_ENTRY(commit_queue_entry) entry;
138 struct got_object_id *id;
139 struct got_commit_object *commit;
140 int idx;
141 };
142 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
143 struct commit_queue {
144 int ncommits;
145 struct commit_queue_head head;
146 };
148 struct tog_color {
149 STAILQ_ENTRY(tog_color) entry;
150 regex_t regex;
151 short colorpair;
152 };
153 STAILQ_HEAD(tog_colors, tog_color);
155 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
156 static struct got_reflist_object_id_map *tog_refs_idmap;
157 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
159 static const struct got_error *
160 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
161 struct got_reference* re2)
163 const char *name1 = got_ref_get_name(re1);
164 const char *name2 = got_ref_get_name(re2);
165 int isbackup1, isbackup2;
167 /* Sort backup refs towards the bottom of the list. */
168 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
169 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
170 if (!isbackup1 && isbackup2) {
171 *cmp = -1;
172 return NULL;
173 } else if (isbackup1 && !isbackup2) {
174 *cmp = 1;
175 return NULL;
178 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
179 return NULL;
182 static const struct got_error *
183 tog_load_refs(struct got_repository *repo, int sort_by_date)
185 const struct got_error *err;
187 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
188 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
189 repo);
190 if (err)
191 return err;
193 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
194 repo);
197 static void
198 tog_free_refs(void)
200 if (tog_refs_idmap) {
201 got_reflist_object_id_map_free(tog_refs_idmap);
202 tog_refs_idmap = NULL;
204 got_ref_list_free(&tog_refs);
207 static const struct got_error *
208 add_color(struct tog_colors *colors, const char *pattern,
209 int idx, short color)
211 const struct got_error *err = NULL;
212 struct tog_color *tc;
213 int regerr = 0;
215 if (idx < 1 || idx > COLOR_PAIRS - 1)
216 return NULL;
218 init_pair(idx, color, -1);
220 tc = calloc(1, sizeof(*tc));
221 if (tc == NULL)
222 return got_error_from_errno("calloc");
223 regerr = regcomp(&tc->regex, pattern,
224 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
225 if (regerr) {
226 static char regerr_msg[512];
227 static char err_msg[512];
228 regerror(regerr, &tc->regex, regerr_msg,
229 sizeof(regerr_msg));
230 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
231 regerr_msg);
232 err = got_error_msg(GOT_ERR_REGEX, err_msg);
233 free(tc);
234 return err;
236 tc->colorpair = idx;
237 STAILQ_INSERT_HEAD(colors, tc, entry);
238 return NULL;
241 static void
242 free_colors(struct tog_colors *colors)
244 struct tog_color *tc;
246 while (!STAILQ_EMPTY(colors)) {
247 tc = STAILQ_FIRST(colors);
248 STAILQ_REMOVE_HEAD(colors, entry);
249 regfree(&tc->regex);
250 free(tc);
254 static struct tog_color *
255 get_color(struct tog_colors *colors, int colorpair)
257 struct tog_color *tc = NULL;
259 STAILQ_FOREACH(tc, colors, entry) {
260 if (tc->colorpair == colorpair)
261 return tc;
264 return NULL;
267 static int
268 default_color_value(const char *envvar)
270 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
271 return COLOR_MAGENTA;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
273 return COLOR_CYAN;
274 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
275 return COLOR_YELLOW;
276 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
277 return COLOR_GREEN;
278 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
279 return COLOR_MAGENTA;
280 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
283 return COLOR_CYAN;
284 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
285 return COLOR_GREEN;
286 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
287 return COLOR_GREEN;
288 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
289 return COLOR_CYAN;
290 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
291 return COLOR_YELLOW;
292 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
293 return COLOR_GREEN;
294 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
295 return COLOR_MAGENTA;
296 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
297 return COLOR_YELLOW;
298 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
299 return COLOR_CYAN;
301 return -1;
304 static int
305 get_color_value(const char *envvar)
307 const char *val = getenv(envvar);
309 if (val == NULL)
310 return default_color_value(envvar);
312 if (strcasecmp(val, "black") == 0)
313 return COLOR_BLACK;
314 if (strcasecmp(val, "red") == 0)
315 return COLOR_RED;
316 if (strcasecmp(val, "green") == 0)
317 return COLOR_GREEN;
318 if (strcasecmp(val, "yellow") == 0)
319 return COLOR_YELLOW;
320 if (strcasecmp(val, "blue") == 0)
321 return COLOR_BLUE;
322 if (strcasecmp(val, "magenta") == 0)
323 return COLOR_MAGENTA;
324 if (strcasecmp(val, "cyan") == 0)
325 return COLOR_CYAN;
326 if (strcasecmp(val, "white") == 0)
327 return COLOR_WHITE;
328 if (strcasecmp(val, "default") == 0)
329 return -1;
331 return default_color_value(envvar);
334 struct tog_diff_view_state {
335 struct got_object_id *id1, *id2;
336 const char *label1, *label2;
337 FILE *f, *f1, *f2;
338 int fd1, fd2;
339 int lineno;
340 int first_displayed_line;
341 int last_displayed_line;
342 int eof;
343 int diff_context;
344 int ignore_whitespace;
345 int force_text_diff;
346 struct got_repository *repo;
347 struct got_diff_line *lines;
348 size_t nlines;
349 int matched_line;
350 int selected_line;
352 /* passed from log or blame view; may be NULL */
353 struct tog_view *parent_view;
354 };
356 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
357 static volatile sig_atomic_t tog_thread_error;
359 struct tog_log_thread_args {
360 pthread_cond_t need_commits;
361 pthread_cond_t commit_loaded;
362 int commits_needed;
363 int load_all;
364 struct got_commit_graph *graph;
365 struct commit_queue *real_commits;
366 const char *in_repo_path;
367 struct got_object_id *start_id;
368 struct got_repository *repo;
369 int *pack_fds;
370 int log_complete;
371 sig_atomic_t *quit;
372 struct commit_queue_entry **first_displayed_entry;
373 struct commit_queue_entry **selected_entry;
374 int *searching;
375 int *search_next_done;
376 regex_t *regex;
377 int *limiting;
378 int limit_match;
379 regex_t *limit_regex;
380 struct commit_queue *limit_commits;
381 };
383 struct tog_log_view_state {
384 struct commit_queue *commits;
385 struct commit_queue_entry *first_displayed_entry;
386 struct commit_queue_entry *last_displayed_entry;
387 struct commit_queue_entry *selected_entry;
388 struct commit_queue real_commits;
389 int selected;
390 char *in_repo_path;
391 char *head_ref_name;
392 int log_branches;
393 struct got_repository *repo;
394 struct got_object_id *start_id;
395 sig_atomic_t quit;
396 pthread_t thread;
397 struct tog_log_thread_args thread_args;
398 struct commit_queue_entry *matched_entry;
399 struct commit_queue_entry *search_entry;
400 struct tog_colors colors;
401 int use_committer;
402 int limit_view;
403 regex_t limit_regex;
404 struct commit_queue limit_commits;
405 };
407 #define TOG_COLOR_DIFF_MINUS 1
408 #define TOG_COLOR_DIFF_PLUS 2
409 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
410 #define TOG_COLOR_DIFF_META 4
411 #define TOG_COLOR_TREE_SUBMODULE 5
412 #define TOG_COLOR_TREE_SYMLINK 6
413 #define TOG_COLOR_TREE_DIRECTORY 7
414 #define TOG_COLOR_TREE_EXECUTABLE 8
415 #define TOG_COLOR_COMMIT 9
416 #define TOG_COLOR_AUTHOR 10
417 #define TOG_COLOR_DATE 11
418 #define TOG_COLOR_REFS_HEADS 12
419 #define TOG_COLOR_REFS_TAGS 13
420 #define TOG_COLOR_REFS_REMOTES 14
421 #define TOG_COLOR_REFS_BACKUP 15
423 struct tog_blame_cb_args {
424 struct tog_blame_line *lines; /* one per line */
425 int nlines;
427 struct tog_view *view;
428 struct got_object_id *commit_id;
429 int *quit;
430 };
432 struct tog_blame_thread_args {
433 const char *path;
434 struct got_repository *repo;
435 struct tog_blame_cb_args *cb_args;
436 int *complete;
437 got_cancel_cb cancel_cb;
438 void *cancel_arg;
439 };
441 struct tog_blame {
442 FILE *f;
443 off_t filesize;
444 struct tog_blame_line *lines;
445 int nlines;
446 off_t *line_offsets;
447 pthread_t thread;
448 struct tog_blame_thread_args thread_args;
449 struct tog_blame_cb_args cb_args;
450 const char *path;
451 int *pack_fds;
452 };
454 struct tog_blame_view_state {
455 int first_displayed_line;
456 int last_displayed_line;
457 int selected_line;
458 int last_diffed_line;
459 int blame_complete;
460 int eof;
461 int done;
462 struct got_object_id_queue blamed_commits;
463 struct got_object_qid *blamed_commit;
464 char *path;
465 struct got_repository *repo;
466 struct got_object_id *commit_id;
467 struct got_object_id *id_to_log;
468 struct tog_blame blame;
469 int matched_line;
470 struct tog_colors colors;
471 };
473 struct tog_parent_tree {
474 TAILQ_ENTRY(tog_parent_tree) entry;
475 struct got_tree_object *tree;
476 struct got_tree_entry *first_displayed_entry;
477 struct got_tree_entry *selected_entry;
478 int selected;
479 };
481 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
483 struct tog_tree_view_state {
484 char *tree_label;
485 struct got_object_id *commit_id;/* commit which this tree belongs to */
486 struct got_tree_object *root; /* the commit's root tree entry */
487 struct got_tree_object *tree; /* currently displayed (sub-)tree */
488 struct got_tree_entry *first_displayed_entry;
489 struct got_tree_entry *last_displayed_entry;
490 struct got_tree_entry *selected_entry;
491 int ndisplayed, selected, show_ids;
492 struct tog_parent_trees parents; /* parent trees of current sub-tree */
493 char *head_ref_name;
494 struct got_repository *repo;
495 struct got_tree_entry *matched_entry;
496 struct tog_colors colors;
497 };
499 struct tog_reflist_entry {
500 TAILQ_ENTRY(tog_reflist_entry) entry;
501 struct got_reference *ref;
502 int idx;
503 };
505 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
507 struct tog_ref_view_state {
508 struct tog_reflist_head refs;
509 struct tog_reflist_entry *first_displayed_entry;
510 struct tog_reflist_entry *last_displayed_entry;
511 struct tog_reflist_entry *selected_entry;
512 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
513 struct got_repository *repo;
514 struct tog_reflist_entry *matched_entry;
515 struct tog_colors colors;
516 };
518 struct tog_help_view_state {
519 FILE *f;
520 off_t *line_offsets;
521 size_t nlines;
522 int lineno;
523 int first_displayed_line;
524 int last_displayed_line;
525 int eof;
526 int matched_line;
527 int selected_line;
528 int all;
529 enum tog_keymap_type type;
530 };
532 #define GENERATE_HELP \
533 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
534 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
535 KEY_("k C-p Up", "Move cursor or page up one line"), \
536 KEY_("j C-n Down", "Move cursor or page down one line"), \
537 KEY_("C-b b PgUp", "Scroll the view up one page"), \
538 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
539 KEY_("C-u u", "Scroll the view up one half page"), \
540 KEY_("C-d d", "Scroll the view down one half page"), \
541 KEY_("g", "Go to line N (default: first line)"), \
542 KEY_("Home =", "Go to the first line"), \
543 KEY_("G", "Go to line N (default: last line)"), \
544 KEY_("End *", "Go to the last line"), \
545 KEY_("l Right", "Scroll the view right"), \
546 KEY_("h Left", "Scroll the view left"), \
547 KEY_("$", "Scroll view to the rightmost position"), \
548 KEY_("0", "Scroll view to the leftmost position"), \
549 KEY_("-", "Decrease size of the focussed split"), \
550 KEY_("+", "Increase size of the focussed split"), \
551 KEY_("Tab", "Switch focus between views"), \
552 KEY_("F", "Toggle fullscreen mode"), \
553 KEY_("/", "Open prompt to enter search term"), \
554 KEY_("n", "Find next line/token matching the current search term"), \
555 KEY_("N", "Find previous line/token matching the current search term"),\
556 KEY_("q", "Quit the focussed view; Quit help screen"), \
557 KEY_("Q", "Quit tog"), \
559 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
560 KEY_("< ,", "Move cursor up one commit"), \
561 KEY_("> .", "Move cursor down one commit"), \
562 KEY_("Enter", "Open diff view of the selected commit"), \
563 KEY_("B", "Reload the log view and toggle display of merged commits"), \
564 KEY_("R", "Open ref view of all repository references"), \
565 KEY_("T", "Display tree view of the repository from the selected" \
566 " commit"), \
567 KEY_("@", "Toggle between displaying author and committer name"), \
568 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
569 KEY_("C-g Backspace", "Cancel current search or log operation"), \
570 KEY_("C-l", "Reload the log view with new commits in the repository"), \
572 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
573 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
574 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
575 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
576 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
577 " data"), \
578 KEY_("(", "Go to the previous file in the diff"), \
579 KEY_(")", "Go to the next file in the diff"), \
580 KEY_("{", "Go to the previous hunk in the diff"), \
581 KEY_("}", "Go to the next hunk in the diff"), \
582 KEY_("[", "Decrease the number of context lines"), \
583 KEY_("]", "Increase the number of context lines"), \
584 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
586 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
587 KEY_("Enter", "Display diff view of the selected line's commit"), \
588 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
589 KEY_("L", "Open log view for the currently selected annotated line"), \
590 KEY_("C", "Reload view with the previously blamed commit"), \
591 KEY_("c", "Reload view with the version of the file found in the" \
592 " selected line's commit"), \
593 KEY_("p", "Reload view with the version of the file found in the" \
594 " selected line's parent commit"), \
596 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
597 KEY_("Enter", "Enter selected directory or open blame view of the" \
598 " selected file"), \
599 KEY_("L", "Open log view for the selected entry"), \
600 KEY_("R", "Open ref view of all repository references"), \
601 KEY_("i", "Show object IDs for all tree entries"), \
602 KEY_("Backspace", "Return to the parent directory"), \
604 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
605 KEY_("Enter", "Display log view of the selected reference"), \
606 KEY_("T", "Display tree view of the selected reference"), \
607 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
608 KEY_("m", "Toggle display of last modified date for each reference"), \
609 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
610 KEY_("C-l", "Reload view with all repository references")
612 struct tog_key_map {
613 const char *keys;
614 const char *info;
615 enum tog_keymap_type type;
616 };
618 /*
619 * We implement two types of views: parent views and child views.
621 * The 'Tab' key switches focus between a parent view and its child view.
622 * Child views are shown side-by-side to their parent view, provided
623 * there is enough screen estate.
625 * When a new view is opened from within a parent view, this new view
626 * becomes a child view of the parent view, replacing any existing child.
628 * When a new view is opened from within a child view, this new view
629 * becomes a parent view which will obscure the views below until the
630 * user quits the new parent view by typing 'q'.
632 * This list of views contains parent views only.
633 * Child views are only pointed to by their parent view.
634 */
635 TAILQ_HEAD(tog_view_list_head, tog_view);
637 struct tog_view {
638 TAILQ_ENTRY(tog_view) entry;
639 WINDOW *window;
640 PANEL *panel;
641 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
642 int resized_y, resized_x; /* begin_y/x based on user resizing */
643 int maxx, x; /* max column and current start column */
644 int lines, cols; /* copies of LINES and COLS */
645 int nscrolled, offset; /* lines scrolled and hsplit line offset */
646 int gline, hiline; /* navigate to and highlight this nG line */
647 int ch, count; /* current keymap and count prefix */
648 int resized; /* set when in a resize event */
649 int focussed; /* Only set on one parent or child view at a time. */
650 int dying;
651 struct tog_view *parent;
652 struct tog_view *child;
654 /*
655 * This flag is initially set on parent views when a new child view
656 * is created. It gets toggled when the 'Tab' key switches focus
657 * between parent and child.
658 * The flag indicates whether focus should be passed on to our child
659 * view if this parent view gets picked for focus after another parent
660 * view was closed. This prevents child views from losing focus in such
661 * situations.
662 */
663 int focus_child;
665 enum tog_view_mode mode;
666 /* type-specific state */
667 enum tog_view_type type;
668 union {
669 struct tog_diff_view_state diff;
670 struct tog_log_view_state log;
671 struct tog_blame_view_state blame;
672 struct tog_tree_view_state tree;
673 struct tog_ref_view_state ref;
674 struct tog_help_view_state help;
675 } state;
677 const struct got_error *(*show)(struct tog_view *);
678 const struct got_error *(*input)(struct tog_view **,
679 struct tog_view *, int);
680 const struct got_error *(*reset)(struct tog_view *);
681 const struct got_error *(*resize)(struct tog_view *, int);
682 const struct got_error *(*close)(struct tog_view *);
684 const struct got_error *(*search_start)(struct tog_view *);
685 const struct got_error *(*search_next)(struct tog_view *);
686 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
687 int **, int **, int **, int **);
688 int search_started;
689 int searching;
690 #define TOG_SEARCH_FORWARD 1
691 #define TOG_SEARCH_BACKWARD 2
692 int search_next_done;
693 #define TOG_SEARCH_HAVE_MORE 1
694 #define TOG_SEARCH_NO_MORE 2
695 #define TOG_SEARCH_HAVE_NONE 3
696 regex_t regex;
697 regmatch_t regmatch;
698 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)
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 (ret == ERR)
1330 return NULL;
1332 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1333 err = view->search_start(view);
1334 if (err) {
1335 regfree(&view->regex);
1336 return err;
1338 view->search_started = 1;
1339 view->searching = TOG_SEARCH_FORWARD;
1340 view->search_next_done = 0;
1341 view->search_next(view);
1344 return NULL;
1347 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1348 static const struct got_error *
1349 switch_split(struct tog_view *view)
1351 const struct got_error *err = NULL;
1352 struct tog_view *v = NULL;
1354 if (view->parent)
1355 v = view->parent;
1356 else
1357 v = view;
1359 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1360 v->mode = TOG_VIEW_SPLIT_VERT;
1361 else
1362 v->mode = TOG_VIEW_SPLIT_HRZN;
1364 if (!v->child)
1365 return NULL;
1366 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1367 v->mode = TOG_VIEW_SPLIT_NONE;
1369 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1370 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1371 v->child->begin_y = v->child->resized_y;
1372 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1373 v->child->begin_x = v->child->resized_x;
1376 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1377 v->ncols = COLS;
1378 v->child->ncols = COLS;
1379 v->child->nscrolled = LINES - v->child->nlines;
1381 err = view_init_hsplit(v, v->child->begin_y);
1382 if (err)
1383 return err;
1385 v->child->mode = v->mode;
1386 v->child->nlines = v->lines - v->child->begin_y;
1387 v->focus_child = 1;
1389 err = view_fullscreen(v);
1390 if (err)
1391 return err;
1392 err = view_splitscreen(v->child);
1393 if (err)
1394 return err;
1396 if (v->mode == TOG_VIEW_SPLIT_NONE)
1397 v->mode = TOG_VIEW_SPLIT_VERT;
1398 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1399 err = offset_selection_down(v);
1400 if (err)
1401 return err;
1402 err = offset_selection_down(v->child);
1403 if (err)
1404 return err;
1405 } else {
1406 offset_selection_up(v);
1407 offset_selection_up(v->child);
1409 if (v->resize)
1410 err = v->resize(v, 0);
1411 else if (v->child->resize)
1412 err = v->child->resize(v->child, 0);
1414 return err;
1418 * Compute view->count from numeric input. Assign total to view->count and
1419 * return first non-numeric key entered.
1421 static int
1422 get_compound_key(struct tog_view *view, int c)
1424 struct tog_view *v = view;
1425 int x, n = 0;
1427 if (view_is_hsplit_top(view))
1428 v = view->child;
1429 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1430 v = view->parent;
1432 view->count = 0;
1433 cbreak(); /* block for input */
1434 nodelay(view->window, FALSE);
1435 wmove(v->window, v->nlines - 1, 0);
1436 wclrtoeol(v->window);
1437 waddch(v->window, ':');
1439 do {
1440 x = getcurx(v->window);
1441 if (x != ERR && x < view->ncols) {
1442 waddch(v->window, c);
1443 wrefresh(v->window);
1447 * Don't overflow. Max valid request should be the greatest
1448 * between the longest and total lines; cap at 10 million.
1450 if (n >= 9999999)
1451 n = 9999999;
1452 else
1453 n = n * 10 + (c - '0');
1454 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1456 if (c == 'G' || c == 'g') { /* nG key map */
1457 view->gline = view->hiline = n;
1458 n = 0;
1459 c = 0;
1462 /* Massage excessive or inapplicable values at the input handler. */
1463 view->count = n;
1465 return c;
1468 static void
1469 action_report(struct tog_view *view)
1471 struct tog_view *v = view;
1473 if (view_is_hsplit_top(view))
1474 v = view->child;
1475 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1476 v = view->parent;
1478 wmove(v->window, v->nlines - 1, 0);
1479 wclrtoeol(v->window);
1480 wprintw(v->window, ":%s", view->action);
1481 wrefresh(v->window);
1484 * Clear action status report. Only clear in blame view
1485 * once annotating is complete, otherwise it's too fast.
1487 if (view->type == TOG_VIEW_BLAME) {
1488 if (view->state.blame.blame_complete)
1489 view->action = NULL;
1490 } else
1491 view->action = NULL;
1494 static const struct got_error *
1495 view_input(struct tog_view **new, int *done, struct tog_view *view,
1496 struct tog_view_list_head *views)
1498 const struct got_error *err = NULL;
1499 struct tog_view *v;
1500 int ch, errcode;
1502 *new = NULL;
1504 if (view->action)
1505 action_report(view);
1507 /* Clear "no matches" indicator. */
1508 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1509 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1510 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1511 view->count = 0;
1514 if (view->searching && !view->search_next_done) {
1515 errcode = pthread_mutex_unlock(&tog_mutex);
1516 if (errcode)
1517 return got_error_set_errno(errcode,
1518 "pthread_mutex_unlock");
1519 sched_yield();
1520 errcode = pthread_mutex_lock(&tog_mutex);
1521 if (errcode)
1522 return got_error_set_errno(errcode,
1523 "pthread_mutex_lock");
1524 view->search_next(view);
1525 return NULL;
1528 /* Allow threads to make progress while we are waiting for input. */
1529 errcode = pthread_mutex_unlock(&tog_mutex);
1530 if (errcode)
1531 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1532 /* If we have an unfinished count, let C-g or backspace abort. */
1533 if (view->count && --view->count) {
1534 cbreak();
1535 nodelay(view->window, TRUE);
1536 ch = wgetch(view->window);
1537 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1538 view->count = 0;
1539 else
1540 ch = view->ch;
1541 } else {
1542 ch = wgetch(view->window);
1543 if (ch >= '1' && ch <= '9')
1544 view->ch = ch = get_compound_key(view, ch);
1546 if (view->hiline && ch != ERR && ch != 0)
1547 view->hiline = 0; /* key pressed, clear line highlight */
1548 nodelay(view->window, TRUE);
1549 errcode = pthread_mutex_lock(&tog_mutex);
1550 if (errcode)
1551 return got_error_set_errno(errcode, "pthread_mutex_lock");
1553 if (tog_sigwinch_received || tog_sigcont_received) {
1554 tog_resizeterm();
1555 tog_sigwinch_received = 0;
1556 tog_sigcont_received = 0;
1557 TAILQ_FOREACH(v, views, entry) {
1558 err = view_resize(v);
1559 if (err)
1560 return err;
1561 err = v->input(new, v, KEY_RESIZE);
1562 if (err)
1563 return err;
1564 if (v->child) {
1565 err = view_resize(v->child);
1566 if (err)
1567 return err;
1568 err = v->child->input(new, v->child,
1569 KEY_RESIZE);
1570 if (err)
1571 return err;
1572 if (v->child->resized_x || v->child->resized_y) {
1573 err = view_resize_split(v, 0);
1574 if (err)
1575 return err;
1581 switch (ch) {
1582 case '?':
1583 case 'H':
1584 case KEY_F(1):
1585 if (view->type == TOG_VIEW_HELP)
1586 err = view->reset(view);
1587 else
1588 err = view_request_new(new, view, TOG_VIEW_HELP);
1589 break;
1590 case '\t':
1591 view->count = 0;
1592 if (view->child) {
1593 view->focussed = 0;
1594 view->child->focussed = 1;
1595 view->focus_child = 1;
1596 } else if (view->parent) {
1597 view->focussed = 0;
1598 view->parent->focussed = 1;
1599 view->parent->focus_child = 0;
1600 if (!view_is_splitscreen(view)) {
1601 if (view->parent->resize) {
1602 err = view->parent->resize(view->parent,
1603 0);
1604 if (err)
1605 return err;
1607 offset_selection_up(view->parent);
1608 err = view_fullscreen(view->parent);
1609 if (err)
1610 return err;
1613 break;
1614 case 'q':
1615 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1616 if (view->parent->resize) {
1617 /* might need more commits to fill fullscreen */
1618 err = view->parent->resize(view->parent, 0);
1619 if (err)
1620 break;
1622 offset_selection_up(view->parent);
1624 err = view->input(new, view, ch);
1625 view->dying = 1;
1626 break;
1627 case 'Q':
1628 *done = 1;
1629 break;
1630 case 'F':
1631 view->count = 0;
1632 if (view_is_parent_view(view)) {
1633 if (view->child == NULL)
1634 break;
1635 if (view_is_splitscreen(view->child)) {
1636 view->focussed = 0;
1637 view->child->focussed = 1;
1638 err = view_fullscreen(view->child);
1639 } else {
1640 err = view_splitscreen(view->child);
1641 if (!err)
1642 err = view_resize_split(view, 0);
1644 if (err)
1645 break;
1646 err = view->child->input(new, view->child,
1647 KEY_RESIZE);
1648 } else {
1649 if (view_is_splitscreen(view)) {
1650 view->parent->focussed = 0;
1651 view->focussed = 1;
1652 err = view_fullscreen(view);
1653 } else {
1654 err = view_splitscreen(view);
1655 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1656 err = view_resize(view->parent);
1657 if (!err)
1658 err = view_resize_split(view, 0);
1660 if (err)
1661 break;
1662 err = view->input(new, view, KEY_RESIZE);
1664 if (err)
1665 break;
1666 if (view->resize) {
1667 err = view->resize(view, 0);
1668 if (err)
1669 break;
1671 if (view->parent)
1672 err = offset_selection_down(view->parent);
1673 if (!err)
1674 err = offset_selection_down(view);
1675 break;
1676 case 'S':
1677 view->count = 0;
1678 err = switch_split(view);
1679 break;
1680 case '-':
1681 err = view_resize_split(view, -1);
1682 break;
1683 case '+':
1684 err = view_resize_split(view, 1);
1685 break;
1686 case KEY_RESIZE:
1687 break;
1688 case '/':
1689 view->count = 0;
1690 if (view->search_start)
1691 view_search_start(view);
1692 else
1693 err = view->input(new, view, ch);
1694 break;
1695 case 'N':
1696 case 'n':
1697 if (view->search_started && view->search_next) {
1698 view->searching = (ch == 'n' ?
1699 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1700 view->search_next_done = 0;
1701 view->search_next(view);
1702 } else
1703 err = view->input(new, view, ch);
1704 break;
1705 case 'A':
1706 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1707 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1708 view->action = "Patience diff algorithm";
1709 } else {
1710 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1711 view->action = "Myers diff algorithm";
1713 TAILQ_FOREACH(v, views, entry) {
1714 if (v->reset) {
1715 err = v->reset(v);
1716 if (err)
1717 return err;
1719 if (v->child && v->child->reset) {
1720 err = v->child->reset(v->child);
1721 if (err)
1722 return err;
1725 break;
1726 default:
1727 err = view->input(new, view, ch);
1728 break;
1731 return err;
1734 static int
1735 view_needs_focus_indication(struct tog_view *view)
1737 if (view_is_parent_view(view)) {
1738 if (view->child == NULL || view->child->focussed)
1739 return 0;
1740 if (!view_is_splitscreen(view->child))
1741 return 0;
1742 } else if (!view_is_splitscreen(view))
1743 return 0;
1745 return view->focussed;
1748 static const struct got_error *
1749 view_loop(struct tog_view *view)
1751 const struct got_error *err = NULL;
1752 struct tog_view_list_head views;
1753 struct tog_view *new_view;
1754 char *mode;
1755 int fast_refresh = 10;
1756 int done = 0, errcode;
1758 mode = getenv("TOG_VIEW_SPLIT_MODE");
1759 if (!mode || !(*mode == 'h' || *mode == 'H'))
1760 view->mode = TOG_VIEW_SPLIT_VERT;
1761 else
1762 view->mode = TOG_VIEW_SPLIT_HRZN;
1764 errcode = pthread_mutex_lock(&tog_mutex);
1765 if (errcode)
1766 return got_error_set_errno(errcode, "pthread_mutex_lock");
1768 TAILQ_INIT(&views);
1769 TAILQ_INSERT_HEAD(&views, view, entry);
1771 view->focussed = 1;
1772 err = view->show(view);
1773 if (err)
1774 return err;
1775 update_panels();
1776 doupdate();
1777 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1778 !tog_fatal_signal_received()) {
1779 /* Refresh fast during initialization, then become slower. */
1780 if (fast_refresh && --fast_refresh == 0)
1781 halfdelay(10); /* switch to once per second */
1783 err = view_input(&new_view, &done, view, &views);
1784 if (err)
1785 break;
1787 if (view->dying && view == TAILQ_FIRST(&views) &&
1788 TAILQ_NEXT(view, entry) == NULL)
1789 done = 1;
1790 if (done) {
1791 struct tog_view *v;
1794 * When we quit, scroll the screen up a single line
1795 * so we don't lose any information.
1797 TAILQ_FOREACH(v, &views, entry) {
1798 wmove(v->window, 0, 0);
1799 wdeleteln(v->window);
1800 wnoutrefresh(v->window);
1801 if (v->child && !view_is_fullscreen(v)) {
1802 wmove(v->child->window, 0, 0);
1803 wdeleteln(v->child->window);
1804 wnoutrefresh(v->child->window);
1807 doupdate();
1810 if (view->dying) {
1811 struct tog_view *v, *prev = NULL;
1813 if (view_is_parent_view(view))
1814 prev = TAILQ_PREV(view, tog_view_list_head,
1815 entry);
1816 else if (view->parent)
1817 prev = view->parent;
1819 if (view->parent) {
1820 view->parent->child = NULL;
1821 view->parent->focus_child = 0;
1822 /* Restore fullscreen line height. */
1823 view->parent->nlines = view->parent->lines;
1824 err = view_resize(view->parent);
1825 if (err)
1826 break;
1827 /* Make resized splits persist. */
1828 view_transfer_size(view->parent, view);
1829 } else
1830 TAILQ_REMOVE(&views, view, entry);
1832 err = view_close(view);
1833 if (err)
1834 goto done;
1836 view = NULL;
1837 TAILQ_FOREACH(v, &views, entry) {
1838 if (v->focussed)
1839 break;
1841 if (view == NULL && new_view == NULL) {
1842 /* No view has focus. Try to pick one. */
1843 if (prev)
1844 view = prev;
1845 else if (!TAILQ_EMPTY(&views)) {
1846 view = TAILQ_LAST(&views,
1847 tog_view_list_head);
1849 if (view) {
1850 if (view->focus_child) {
1851 view->child->focussed = 1;
1852 view = view->child;
1853 } else
1854 view->focussed = 1;
1858 if (new_view) {
1859 struct tog_view *v, *t;
1860 /* Only allow one parent view per type. */
1861 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1862 if (v->type != new_view->type)
1863 continue;
1864 TAILQ_REMOVE(&views, v, entry);
1865 err = view_close(v);
1866 if (err)
1867 goto done;
1868 break;
1870 TAILQ_INSERT_TAIL(&views, new_view, entry);
1871 view = new_view;
1873 if (view && !done) {
1874 if (view_is_parent_view(view)) {
1875 if (view->child && view->child->focussed)
1876 view = view->child;
1877 } else {
1878 if (view->parent && view->parent->focussed)
1879 view = view->parent;
1881 show_panel(view->panel);
1882 if (view->child && view_is_splitscreen(view->child))
1883 show_panel(view->child->panel);
1884 if (view->parent && view_is_splitscreen(view)) {
1885 err = view->parent->show(view->parent);
1886 if (err)
1887 goto done;
1889 err = view->show(view);
1890 if (err)
1891 goto done;
1892 if (view->child) {
1893 err = view->child->show(view->child);
1894 if (err)
1895 goto done;
1897 update_panels();
1898 doupdate();
1901 done:
1902 while (!TAILQ_EMPTY(&views)) {
1903 const struct got_error *close_err;
1904 view = TAILQ_FIRST(&views);
1905 TAILQ_REMOVE(&views, view, entry);
1906 close_err = view_close(view);
1907 if (close_err && err == NULL)
1908 err = close_err;
1911 errcode = pthread_mutex_unlock(&tog_mutex);
1912 if (errcode && err == NULL)
1913 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1915 return err;
1918 __dead static void
1919 usage_log(void)
1921 endwin();
1922 fprintf(stderr,
1923 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1924 getprogname());
1925 exit(1);
1928 /* Create newly allocated wide-character string equivalent to a byte string. */
1929 static const struct got_error *
1930 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1932 char *vis = NULL;
1933 const struct got_error *err = NULL;
1935 *ws = NULL;
1936 *wlen = mbstowcs(NULL, s, 0);
1937 if (*wlen == (size_t)-1) {
1938 int vislen;
1939 if (errno != EILSEQ)
1940 return got_error_from_errno("mbstowcs");
1942 /* byte string invalid in current encoding; try to "fix" it */
1943 err = got_mbsavis(&vis, &vislen, s);
1944 if (err)
1945 return err;
1946 *wlen = mbstowcs(NULL, vis, 0);
1947 if (*wlen == (size_t)-1) {
1948 err = got_error_from_errno("mbstowcs"); /* give up */
1949 goto done;
1953 *ws = calloc(*wlen + 1, sizeof(**ws));
1954 if (*ws == NULL) {
1955 err = got_error_from_errno("calloc");
1956 goto done;
1959 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1960 err = got_error_from_errno("mbstowcs");
1961 done:
1962 free(vis);
1963 if (err) {
1964 free(*ws);
1965 *ws = NULL;
1966 *wlen = 0;
1968 return err;
1971 static const struct got_error *
1972 expand_tab(char **ptr, const char *src)
1974 char *dst;
1975 size_t len, n, idx = 0, sz = 0;
1977 *ptr = NULL;
1978 n = len = strlen(src);
1979 dst = malloc(n + 1);
1980 if (dst == NULL)
1981 return got_error_from_errno("malloc");
1983 while (idx < len && src[idx]) {
1984 const char c = src[idx];
1986 if (c == '\t') {
1987 size_t nb = TABSIZE - sz % TABSIZE;
1988 char *p;
1990 p = realloc(dst, n + nb);
1991 if (p == NULL) {
1992 free(dst);
1993 return got_error_from_errno("realloc");
1996 dst = p;
1997 n += nb;
1998 memset(dst + sz, ' ', nb);
1999 sz += nb;
2000 } else
2001 dst[sz++] = src[idx];
2002 ++idx;
2005 dst[sz] = '\0';
2006 *ptr = dst;
2007 return NULL;
2011 * Advance at most n columns from wline starting at offset off.
2012 * Return the index to the first character after the span operation.
2013 * Return the combined column width of all spanned wide character in
2014 * *rcol.
2016 static int
2017 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2019 int width, i, cols = 0;
2021 if (n == 0) {
2022 *rcol = cols;
2023 return off;
2026 for (i = off; wline[i] != L'\0'; ++i) {
2027 if (wline[i] == L'\t')
2028 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2029 else
2030 width = wcwidth(wline[i]);
2032 if (width == -1) {
2033 width = 1;
2034 wline[i] = L'.';
2037 if (cols + width > n)
2038 break;
2039 cols += width;
2042 *rcol = cols;
2043 return i;
2047 * Format a line for display, ensuring that it won't overflow a width limit.
2048 * With scrolling, the width returned refers to the scrolled version of the
2049 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2051 static const struct got_error *
2052 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2053 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2055 const struct got_error *err = NULL;
2056 int cols;
2057 wchar_t *wline = NULL;
2058 char *exstr = NULL;
2059 size_t wlen;
2060 int i, scrollx;
2062 *wlinep = NULL;
2063 *widthp = 0;
2065 if (expand) {
2066 err = expand_tab(&exstr, line);
2067 if (err)
2068 return err;
2071 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2072 free(exstr);
2073 if (err)
2074 return err;
2076 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2078 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2079 wline[wlen - 1] = L'\0';
2080 wlen--;
2082 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2083 wline[wlen - 1] = L'\0';
2084 wlen--;
2087 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2088 wline[i] = L'\0';
2090 if (widthp)
2091 *widthp = cols;
2092 if (scrollxp)
2093 *scrollxp = scrollx;
2094 if (err)
2095 free(wline);
2096 else
2097 *wlinep = wline;
2098 return err;
2101 static const struct got_error*
2102 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2103 struct got_object_id *id, struct got_repository *repo)
2105 static const struct got_error *err = NULL;
2106 struct got_reflist_entry *re;
2107 char *s;
2108 const char *name;
2110 *refs_str = NULL;
2112 TAILQ_FOREACH(re, refs, entry) {
2113 struct got_tag_object *tag = NULL;
2114 struct got_object_id *ref_id;
2115 int cmp;
2117 name = got_ref_get_name(re->ref);
2118 if (strcmp(name, GOT_REF_HEAD) == 0)
2119 continue;
2120 if (strncmp(name, "refs/", 5) == 0)
2121 name += 5;
2122 if (strncmp(name, "got/", 4) == 0 &&
2123 strncmp(name, "got/backup/", 11) != 0)
2124 continue;
2125 if (strncmp(name, "heads/", 6) == 0)
2126 name += 6;
2127 if (strncmp(name, "remotes/", 8) == 0) {
2128 name += 8;
2129 s = strstr(name, "/" GOT_REF_HEAD);
2130 if (s != NULL && s[strlen(s)] == '\0')
2131 continue;
2133 err = got_ref_resolve(&ref_id, repo, re->ref);
2134 if (err)
2135 break;
2136 if (strncmp(name, "tags/", 5) == 0) {
2137 err = got_object_open_as_tag(&tag, repo, ref_id);
2138 if (err) {
2139 if (err->code != GOT_ERR_OBJ_TYPE) {
2140 free(ref_id);
2141 break;
2143 /* Ref points at something other than a tag. */
2144 err = NULL;
2145 tag = NULL;
2148 cmp = got_object_id_cmp(tag ?
2149 got_object_tag_get_object_id(tag) : ref_id, id);
2150 free(ref_id);
2151 if (tag)
2152 got_object_tag_close(tag);
2153 if (cmp != 0)
2154 continue;
2155 s = *refs_str;
2156 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2157 s ? ", " : "", name) == -1) {
2158 err = got_error_from_errno("asprintf");
2159 free(s);
2160 *refs_str = NULL;
2161 break;
2163 free(s);
2166 return err;
2169 static const struct got_error *
2170 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2171 int col_tab_align)
2173 char *smallerthan;
2175 smallerthan = strchr(author, '<');
2176 if (smallerthan && smallerthan[1] != '\0')
2177 author = smallerthan + 1;
2178 author[strcspn(author, "@>")] = '\0';
2179 return format_line(wauthor, author_width, NULL, author, 0, limit,
2180 col_tab_align, 0);
2183 static const struct got_error *
2184 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2185 struct got_object_id *id, const size_t date_display_cols,
2186 int author_display_cols)
2188 struct tog_log_view_state *s = &view->state.log;
2189 const struct got_error *err = NULL;
2190 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2191 char *logmsg0 = NULL, *logmsg = NULL;
2192 char *author = NULL;
2193 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2194 int author_width, logmsg_width;
2195 char *newline, *line = NULL;
2196 int col, limit, scrollx;
2197 const int avail = view->ncols;
2198 struct tm tm;
2199 time_t committer_time;
2200 struct tog_color *tc;
2202 committer_time = got_object_commit_get_committer_time(commit);
2203 if (gmtime_r(&committer_time, &tm) == NULL)
2204 return got_error_from_errno("gmtime_r");
2205 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2206 return got_error(GOT_ERR_NO_SPACE);
2208 if (avail <= date_display_cols)
2209 limit = MIN(sizeof(datebuf) - 1, avail);
2210 else
2211 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2212 tc = get_color(&s->colors, TOG_COLOR_DATE);
2213 if (tc)
2214 wattr_on(view->window,
2215 COLOR_PAIR(tc->colorpair), NULL);
2216 waddnstr(view->window, datebuf, limit);
2217 if (tc)
2218 wattr_off(view->window,
2219 COLOR_PAIR(tc->colorpair), NULL);
2220 col = limit;
2221 if (col > avail)
2222 goto done;
2224 if (avail >= 120) {
2225 char *id_str;
2226 err = got_object_id_str(&id_str, id);
2227 if (err)
2228 goto done;
2229 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2230 if (tc)
2231 wattr_on(view->window,
2232 COLOR_PAIR(tc->colorpair), NULL);
2233 wprintw(view->window, "%.8s ", id_str);
2234 if (tc)
2235 wattr_off(view->window,
2236 COLOR_PAIR(tc->colorpair), NULL);
2237 free(id_str);
2238 col += 9;
2239 if (col > avail)
2240 goto done;
2243 if (s->use_committer)
2244 author = strdup(got_object_commit_get_committer(commit));
2245 else
2246 author = strdup(got_object_commit_get_author(commit));
2247 if (author == NULL) {
2248 err = got_error_from_errno("strdup");
2249 goto done;
2251 err = format_author(&wauthor, &author_width, author, avail - col, col);
2252 if (err)
2253 goto done;
2254 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2255 if (tc)
2256 wattr_on(view->window,
2257 COLOR_PAIR(tc->colorpair), NULL);
2258 waddwstr(view->window, wauthor);
2259 col += author_width;
2260 while (col < avail && author_width < author_display_cols + 2) {
2261 waddch(view->window, ' ');
2262 col++;
2263 author_width++;
2265 if (tc)
2266 wattr_off(view->window,
2267 COLOR_PAIR(tc->colorpair), NULL);
2268 if (col > avail)
2269 goto done;
2271 err = got_object_commit_get_logmsg(&logmsg0, commit);
2272 if (err)
2273 goto done;
2274 logmsg = logmsg0;
2275 while (*logmsg == '\n')
2276 logmsg++;
2277 newline = strchr(logmsg, '\n');
2278 if (newline)
2279 *newline = '\0';
2280 limit = avail - col;
2281 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2282 limit--; /* for the border */
2283 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2284 limit, col, 1);
2285 if (err)
2286 goto done;
2287 waddwstr(view->window, &wlogmsg[scrollx]);
2288 col += MAX(logmsg_width, 0);
2289 while (col < avail) {
2290 waddch(view->window, ' ');
2291 col++;
2293 done:
2294 free(logmsg0);
2295 free(wlogmsg);
2296 free(author);
2297 free(wauthor);
2298 free(line);
2299 return err;
2302 static struct commit_queue_entry *
2303 alloc_commit_queue_entry(struct got_commit_object *commit,
2304 struct got_object_id *id)
2306 struct commit_queue_entry *entry;
2307 struct got_object_id *dup;
2309 entry = calloc(1, sizeof(*entry));
2310 if (entry == NULL)
2311 return NULL;
2313 dup = got_object_id_dup(id);
2314 if (dup == NULL) {
2315 free(entry);
2316 return NULL;
2319 entry->id = dup;
2320 entry->commit = commit;
2321 return entry;
2324 static void
2325 pop_commit(struct commit_queue *commits)
2327 struct commit_queue_entry *entry;
2329 entry = TAILQ_FIRST(&commits->head);
2330 TAILQ_REMOVE(&commits->head, entry, entry);
2331 got_object_commit_close(entry->commit);
2332 commits->ncommits--;
2333 free(entry->id);
2334 free(entry);
2337 static void
2338 free_commits(struct commit_queue *commits)
2340 while (!TAILQ_EMPTY(&commits->head))
2341 pop_commit(commits);
2344 static const struct got_error *
2345 match_commit(int *have_match, struct got_object_id *id,
2346 struct got_commit_object *commit, regex_t *regex)
2348 const struct got_error *err = NULL;
2349 regmatch_t regmatch;
2350 char *id_str = NULL, *logmsg = NULL;
2352 *have_match = 0;
2354 err = got_object_id_str(&id_str, id);
2355 if (err)
2356 return err;
2358 err = got_object_commit_get_logmsg(&logmsg, commit);
2359 if (err)
2360 goto done;
2362 if (regexec(regex, got_object_commit_get_author(commit), 1,
2363 &regmatch, 0) == 0 ||
2364 regexec(regex, got_object_commit_get_committer(commit), 1,
2365 &regmatch, 0) == 0 ||
2366 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2367 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2368 *have_match = 1;
2369 done:
2370 free(id_str);
2371 free(logmsg);
2372 return err;
2375 static const struct got_error *
2376 queue_commits(struct tog_log_thread_args *a)
2378 const struct got_error *err = NULL;
2381 * We keep all commits open throughout the lifetime of the log
2382 * view in order to avoid having to re-fetch commits from disk
2383 * while updating the display.
2385 do {
2386 struct got_object_id id;
2387 struct got_commit_object *commit;
2388 struct commit_queue_entry *entry;
2389 int limit_match = 0;
2390 int errcode;
2392 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2393 NULL, NULL);
2394 if (err)
2395 break;
2397 err = got_object_open_as_commit(&commit, a->repo, &id);
2398 if (err)
2399 break;
2400 entry = alloc_commit_queue_entry(commit, &id);
2401 if (entry == NULL) {
2402 err = got_error_from_errno("alloc_commit_queue_entry");
2403 break;
2406 errcode = pthread_mutex_lock(&tog_mutex);
2407 if (errcode) {
2408 err = got_error_set_errno(errcode,
2409 "pthread_mutex_lock");
2410 break;
2413 entry->idx = a->real_commits->ncommits;
2414 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2415 a->real_commits->ncommits++;
2417 if (*a->limiting) {
2418 err = match_commit(&limit_match, &id, commit,
2419 a->limit_regex);
2420 if (err)
2421 break;
2423 if (limit_match) {
2424 struct commit_queue_entry *matched;
2426 matched = alloc_commit_queue_entry(
2427 entry->commit, entry->id);
2428 if (matched == NULL) {
2429 err = got_error_from_errno(
2430 "alloc_commit_queue_entry");
2431 break;
2433 matched->commit = entry->commit;
2434 got_object_commit_retain(entry->commit);
2436 matched->idx = a->limit_commits->ncommits;
2437 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2438 matched, entry);
2439 a->limit_commits->ncommits++;
2443 * This is how we signal log_thread() that we
2444 * have found a match, and that it should be
2445 * counted as a new entry for the view.
2447 a->limit_match = limit_match;
2450 if (*a->searching == TOG_SEARCH_FORWARD &&
2451 !*a->search_next_done) {
2452 int have_match;
2453 err = match_commit(&have_match, &id, commit, a->regex);
2454 if (err)
2455 break;
2457 if (*a->limiting) {
2458 if (limit_match && have_match)
2459 *a->search_next_done =
2460 TOG_SEARCH_HAVE_MORE;
2461 } else if (have_match)
2462 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2465 errcode = pthread_mutex_unlock(&tog_mutex);
2466 if (errcode && err == NULL)
2467 err = got_error_set_errno(errcode,
2468 "pthread_mutex_unlock");
2469 if (err)
2470 break;
2471 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2473 return err;
2476 static void
2477 select_commit(struct tog_log_view_state *s)
2479 struct commit_queue_entry *entry;
2480 int ncommits = 0;
2482 entry = s->first_displayed_entry;
2483 while (entry) {
2484 if (ncommits == s->selected) {
2485 s->selected_entry = entry;
2486 break;
2488 entry = TAILQ_NEXT(entry, entry);
2489 ncommits++;
2493 static const struct got_error *
2494 draw_commits(struct tog_view *view)
2496 const struct got_error *err = NULL;
2497 struct tog_log_view_state *s = &view->state.log;
2498 struct commit_queue_entry *entry = s->selected_entry;
2499 int limit = view->nlines;
2500 int width;
2501 int ncommits, author_cols = 4;
2502 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2503 char *refs_str = NULL;
2504 wchar_t *wline;
2505 struct tog_color *tc;
2506 static const size_t date_display_cols = 12;
2508 if (view_is_hsplit_top(view))
2509 --limit; /* account for border */
2511 if (s->selected_entry &&
2512 !(view->searching && view->search_next_done == 0)) {
2513 struct got_reflist_head *refs;
2514 err = got_object_id_str(&id_str, s->selected_entry->id);
2515 if (err)
2516 return err;
2517 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2518 s->selected_entry->id);
2519 if (refs) {
2520 err = build_refs_str(&refs_str, refs,
2521 s->selected_entry->id, s->repo);
2522 if (err)
2523 goto done;
2527 if (s->thread_args.commits_needed == 0)
2528 halfdelay(10); /* disable fast refresh */
2530 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2531 if (asprintf(&ncommits_str, " [%d/%d] %s",
2532 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2533 (view->searching && !view->search_next_done) ?
2534 "searching..." : "loading...") == -1) {
2535 err = got_error_from_errno("asprintf");
2536 goto done;
2538 } else {
2539 const char *search_str = NULL;
2540 const char *limit_str = NULL;
2542 if (view->searching) {
2543 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2544 search_str = "no more matches";
2545 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2546 search_str = "no matches found";
2547 else if (!view->search_next_done)
2548 search_str = "searching...";
2551 if (s->limit_view && s->commits->ncommits == 0)
2552 limit_str = "no matches found";
2554 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2555 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2556 search_str ? search_str : (refs_str ? refs_str : ""),
2557 limit_str ? limit_str : "") == -1) {
2558 err = got_error_from_errno("asprintf");
2559 goto done;
2563 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2564 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2565 "........................................",
2566 s->in_repo_path, ncommits_str) == -1) {
2567 err = got_error_from_errno("asprintf");
2568 header = NULL;
2569 goto done;
2571 } else if (asprintf(&header, "commit %s%s",
2572 id_str ? id_str : "........................................",
2573 ncommits_str) == -1) {
2574 err = got_error_from_errno("asprintf");
2575 header = NULL;
2576 goto done;
2578 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2579 if (err)
2580 goto done;
2582 werase(view->window);
2584 if (view_needs_focus_indication(view))
2585 wstandout(view->window);
2586 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2587 if (tc)
2588 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2589 waddwstr(view->window, wline);
2590 while (width < view->ncols) {
2591 waddch(view->window, ' ');
2592 width++;
2594 if (tc)
2595 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2596 if (view_needs_focus_indication(view))
2597 wstandend(view->window);
2598 free(wline);
2599 if (limit <= 1)
2600 goto done;
2602 /* Grow author column size if necessary, and set view->maxx. */
2603 entry = s->first_displayed_entry;
2604 ncommits = 0;
2605 view->maxx = 0;
2606 while (entry) {
2607 struct got_commit_object *c = entry->commit;
2608 char *author, *eol, *msg, *msg0;
2609 wchar_t *wauthor, *wmsg;
2610 int width;
2611 if (ncommits >= limit - 1)
2612 break;
2613 if (s->use_committer)
2614 author = strdup(got_object_commit_get_committer(c));
2615 else
2616 author = strdup(got_object_commit_get_author(c));
2617 if (author == NULL) {
2618 err = got_error_from_errno("strdup");
2619 goto done;
2621 err = format_author(&wauthor, &width, author, COLS,
2622 date_display_cols);
2623 if (author_cols < width)
2624 author_cols = width;
2625 free(wauthor);
2626 free(author);
2627 if (err)
2628 goto done;
2629 err = got_object_commit_get_logmsg(&msg0, c);
2630 if (err)
2631 goto done;
2632 msg = msg0;
2633 while (*msg == '\n')
2634 ++msg;
2635 if ((eol = strchr(msg, '\n')))
2636 *eol = '\0';
2637 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2638 date_display_cols + author_cols, 0);
2639 if (err)
2640 goto done;
2641 view->maxx = MAX(view->maxx, width);
2642 free(msg0);
2643 free(wmsg);
2644 ncommits++;
2645 entry = TAILQ_NEXT(entry, entry);
2648 entry = s->first_displayed_entry;
2649 s->last_displayed_entry = s->first_displayed_entry;
2650 ncommits = 0;
2651 while (entry) {
2652 if (ncommits >= limit - 1)
2653 break;
2654 if (ncommits == s->selected)
2655 wstandout(view->window);
2656 err = draw_commit(view, entry->commit, entry->id,
2657 date_display_cols, author_cols);
2658 if (ncommits == s->selected)
2659 wstandend(view->window);
2660 if (err)
2661 goto done;
2662 ncommits++;
2663 s->last_displayed_entry = entry;
2664 entry = TAILQ_NEXT(entry, entry);
2667 view_border(view);
2668 done:
2669 free(id_str);
2670 free(refs_str);
2671 free(ncommits_str);
2672 free(header);
2673 return err;
2676 static void
2677 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2679 struct commit_queue_entry *entry;
2680 int nscrolled = 0;
2682 entry = TAILQ_FIRST(&s->commits->head);
2683 if (s->first_displayed_entry == entry)
2684 return;
2686 entry = s->first_displayed_entry;
2687 while (entry && nscrolled < maxscroll) {
2688 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2689 if (entry) {
2690 s->first_displayed_entry = entry;
2691 nscrolled++;
2696 static const struct got_error *
2697 trigger_log_thread(struct tog_view *view, int wait)
2699 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2700 int errcode;
2702 halfdelay(1); /* fast refresh while loading commits */
2704 while (!ta->log_complete && !tog_thread_error &&
2705 (ta->commits_needed > 0 || ta->load_all)) {
2706 /* Wake the log thread. */
2707 errcode = pthread_cond_signal(&ta->need_commits);
2708 if (errcode)
2709 return got_error_set_errno(errcode,
2710 "pthread_cond_signal");
2713 * The mutex will be released while the view loop waits
2714 * in wgetch(), at which time the log thread will run.
2716 if (!wait)
2717 break;
2719 /* Display progress update in log view. */
2720 show_log_view(view);
2721 update_panels();
2722 doupdate();
2724 /* Wait right here while next commit is being loaded. */
2725 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2726 if (errcode)
2727 return got_error_set_errno(errcode,
2728 "pthread_cond_wait");
2730 /* Display progress update in log view. */
2731 show_log_view(view);
2732 update_panels();
2733 doupdate();
2736 return NULL;
2739 static const struct got_error *
2740 request_log_commits(struct tog_view *view)
2742 struct tog_log_view_state *state = &view->state.log;
2743 const struct got_error *err = NULL;
2745 if (state->thread_args.log_complete)
2746 return NULL;
2748 state->thread_args.commits_needed += view->nscrolled;
2749 err = trigger_log_thread(view, 1);
2750 view->nscrolled = 0;
2752 return err;
2755 static const struct got_error *
2756 log_scroll_down(struct tog_view *view, int maxscroll)
2758 struct tog_log_view_state *s = &view->state.log;
2759 const struct got_error *err = NULL;
2760 struct commit_queue_entry *pentry;
2761 int nscrolled = 0, ncommits_needed;
2763 if (s->last_displayed_entry == NULL)
2764 return NULL;
2766 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2767 if (s->commits->ncommits < ncommits_needed &&
2768 !s->thread_args.log_complete) {
2770 * Ask the log thread for required amount of commits.
2772 s->thread_args.commits_needed +=
2773 ncommits_needed - s->commits->ncommits;
2774 err = trigger_log_thread(view, 1);
2775 if (err)
2776 return err;
2779 do {
2780 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2781 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2782 break;
2784 s->last_displayed_entry = pentry ?
2785 pentry : s->last_displayed_entry;
2787 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2788 if (pentry == NULL)
2789 break;
2790 s->first_displayed_entry = pentry;
2791 } while (++nscrolled < maxscroll);
2793 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2794 view->nscrolled += nscrolled;
2795 else
2796 view->nscrolled = 0;
2798 return err;
2801 static const struct got_error *
2802 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2803 struct got_commit_object *commit, struct got_object_id *commit_id,
2804 struct tog_view *log_view, struct got_repository *repo)
2806 const struct got_error *err;
2807 struct got_object_qid *parent_id;
2808 struct tog_view *diff_view;
2810 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2811 if (diff_view == NULL)
2812 return got_error_from_errno("view_open");
2814 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2815 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2816 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2817 if (err == NULL)
2818 *new_view = diff_view;
2819 return err;
2822 static const struct got_error *
2823 tree_view_visit_subtree(struct tog_tree_view_state *s,
2824 struct got_tree_object *subtree)
2826 struct tog_parent_tree *parent;
2828 parent = calloc(1, sizeof(*parent));
2829 if (parent == NULL)
2830 return got_error_from_errno("calloc");
2832 parent->tree = s->tree;
2833 parent->first_displayed_entry = s->first_displayed_entry;
2834 parent->selected_entry = s->selected_entry;
2835 parent->selected = s->selected;
2836 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2837 s->tree = subtree;
2838 s->selected = 0;
2839 s->first_displayed_entry = NULL;
2840 return NULL;
2843 static const struct got_error *
2844 tree_view_walk_path(struct tog_tree_view_state *s,
2845 struct got_commit_object *commit, const char *path)
2847 const struct got_error *err = NULL;
2848 struct got_tree_object *tree = NULL;
2849 const char *p;
2850 char *slash, *subpath = NULL;
2852 /* Walk the path and open corresponding tree objects. */
2853 p = path;
2854 while (*p) {
2855 struct got_tree_entry *te;
2856 struct got_object_id *tree_id;
2857 char *te_name;
2859 while (p[0] == '/')
2860 p++;
2862 /* Ensure the correct subtree entry is selected. */
2863 slash = strchr(p, '/');
2864 if (slash == NULL)
2865 te_name = strdup(p);
2866 else
2867 te_name = strndup(p, slash - p);
2868 if (te_name == NULL) {
2869 err = got_error_from_errno("strndup");
2870 break;
2872 te = got_object_tree_find_entry(s->tree, te_name);
2873 if (te == NULL) {
2874 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2875 free(te_name);
2876 break;
2878 free(te_name);
2879 s->first_displayed_entry = s->selected_entry = te;
2881 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2882 break; /* jump to this file's entry */
2884 slash = strchr(p, '/');
2885 if (slash)
2886 subpath = strndup(path, slash - path);
2887 else
2888 subpath = strdup(path);
2889 if (subpath == NULL) {
2890 err = got_error_from_errno("strdup");
2891 break;
2894 err = got_object_id_by_path(&tree_id, s->repo, commit,
2895 subpath);
2896 if (err)
2897 break;
2899 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2900 free(tree_id);
2901 if (err)
2902 break;
2904 err = tree_view_visit_subtree(s, tree);
2905 if (err) {
2906 got_object_tree_close(tree);
2907 break;
2909 if (slash == NULL)
2910 break;
2911 free(subpath);
2912 subpath = NULL;
2913 p = slash;
2916 free(subpath);
2917 return err;
2920 static const struct got_error *
2921 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2922 struct commit_queue_entry *entry, const char *path,
2923 const char *head_ref_name, struct got_repository *repo)
2925 const struct got_error *err = NULL;
2926 struct tog_tree_view_state *s;
2927 struct tog_view *tree_view;
2929 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2930 if (tree_view == NULL)
2931 return got_error_from_errno("view_open");
2933 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2934 if (err)
2935 return err;
2936 s = &tree_view->state.tree;
2938 *new_view = tree_view;
2940 if (got_path_is_root_dir(path))
2941 return NULL;
2943 return tree_view_walk_path(s, entry->commit, path);
2946 static const struct got_error *
2947 block_signals_used_by_main_thread(void)
2949 sigset_t sigset;
2950 int errcode;
2952 if (sigemptyset(&sigset) == -1)
2953 return got_error_from_errno("sigemptyset");
2955 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2956 if (sigaddset(&sigset, SIGWINCH) == -1)
2957 return got_error_from_errno("sigaddset");
2958 if (sigaddset(&sigset, SIGCONT) == -1)
2959 return got_error_from_errno("sigaddset");
2960 if (sigaddset(&sigset, SIGINT) == -1)
2961 return got_error_from_errno("sigaddset");
2962 if (sigaddset(&sigset, SIGTERM) == -1)
2963 return got_error_from_errno("sigaddset");
2965 /* ncurses handles SIGTSTP */
2966 if (sigaddset(&sigset, SIGTSTP) == -1)
2967 return got_error_from_errno("sigaddset");
2969 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2970 if (errcode)
2971 return got_error_set_errno(errcode, "pthread_sigmask");
2973 return NULL;
2976 static void *
2977 log_thread(void *arg)
2979 const struct got_error *err = NULL;
2980 int errcode = 0;
2981 struct tog_log_thread_args *a = arg;
2982 int done = 0;
2985 * Sync startup with main thread such that we begin our
2986 * work once view_input() has released the mutex.
2988 errcode = pthread_mutex_lock(&tog_mutex);
2989 if (errcode) {
2990 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2991 return (void *)err;
2994 err = block_signals_used_by_main_thread();
2995 if (err) {
2996 pthread_mutex_unlock(&tog_mutex);
2997 goto done;
3000 while (!done && !err && !tog_fatal_signal_received()) {
3001 errcode = pthread_mutex_unlock(&tog_mutex);
3002 if (errcode) {
3003 err = got_error_set_errno(errcode,
3004 "pthread_mutex_unlock");
3005 goto done;
3007 err = queue_commits(a);
3008 if (err) {
3009 if (err->code != GOT_ERR_ITER_COMPLETED)
3010 goto done;
3011 err = NULL;
3012 done = 1;
3013 } else if (a->commits_needed > 0 && !a->load_all) {
3014 if (*a->limiting) {
3015 if (a->limit_match)
3016 a->commits_needed--;
3017 } else
3018 a->commits_needed--;
3021 errcode = pthread_mutex_lock(&tog_mutex);
3022 if (errcode) {
3023 err = got_error_set_errno(errcode,
3024 "pthread_mutex_lock");
3025 goto done;
3026 } else if (*a->quit)
3027 done = 1;
3028 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3029 *a->first_displayed_entry =
3030 TAILQ_FIRST(&a->limit_commits->head);
3031 *a->selected_entry = *a->first_displayed_entry;
3032 } else if (*a->first_displayed_entry == NULL) {
3033 *a->first_displayed_entry =
3034 TAILQ_FIRST(&a->real_commits->head);
3035 *a->selected_entry = *a->first_displayed_entry;
3038 errcode = pthread_cond_signal(&a->commit_loaded);
3039 if (errcode) {
3040 err = got_error_set_errno(errcode,
3041 "pthread_cond_signal");
3042 pthread_mutex_unlock(&tog_mutex);
3043 goto done;
3046 if (done)
3047 a->commits_needed = 0;
3048 else {
3049 if (a->commits_needed == 0 && !a->load_all) {
3050 errcode = pthread_cond_wait(&a->need_commits,
3051 &tog_mutex);
3052 if (errcode) {
3053 err = got_error_set_errno(errcode,
3054 "pthread_cond_wait");
3055 pthread_mutex_unlock(&tog_mutex);
3056 goto done;
3058 if (*a->quit)
3059 done = 1;
3063 a->log_complete = 1;
3064 errcode = pthread_mutex_unlock(&tog_mutex);
3065 if (errcode)
3066 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3067 done:
3068 if (err) {
3069 tog_thread_error = 1;
3070 pthread_cond_signal(&a->commit_loaded);
3072 return (void *)err;
3075 static const struct got_error *
3076 stop_log_thread(struct tog_log_view_state *s)
3078 const struct got_error *err = NULL, *thread_err = NULL;
3079 int errcode;
3081 if (s->thread) {
3082 s->quit = 1;
3083 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3084 if (errcode)
3085 return got_error_set_errno(errcode,
3086 "pthread_cond_signal");
3087 errcode = pthread_mutex_unlock(&tog_mutex);
3088 if (errcode)
3089 return got_error_set_errno(errcode,
3090 "pthread_mutex_unlock");
3091 errcode = pthread_join(s->thread, (void **)&thread_err);
3092 if (errcode)
3093 return got_error_set_errno(errcode, "pthread_join");
3094 errcode = pthread_mutex_lock(&tog_mutex);
3095 if (errcode)
3096 return got_error_set_errno(errcode,
3097 "pthread_mutex_lock");
3098 s->thread = 0; //NULL;
3101 if (s->thread_args.repo) {
3102 err = got_repo_close(s->thread_args.repo);
3103 s->thread_args.repo = NULL;
3106 if (s->thread_args.pack_fds) {
3107 const struct got_error *pack_err =
3108 got_repo_pack_fds_close(s->thread_args.pack_fds);
3109 if (err == NULL)
3110 err = pack_err;
3111 s->thread_args.pack_fds = NULL;
3114 if (s->thread_args.graph) {
3115 got_commit_graph_close(s->thread_args.graph);
3116 s->thread_args.graph = NULL;
3119 return err ? err : thread_err;
3122 static const struct got_error *
3123 close_log_view(struct tog_view *view)
3125 const struct got_error *err = NULL;
3126 struct tog_log_view_state *s = &view->state.log;
3127 int errcode;
3129 err = stop_log_thread(s);
3131 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3132 if (errcode && err == NULL)
3133 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3135 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3136 if (errcode && err == NULL)
3137 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3139 free_commits(&s->limit_commits);
3140 free_commits(&s->real_commits);
3141 free(s->in_repo_path);
3142 s->in_repo_path = NULL;
3143 free(s->start_id);
3144 s->start_id = NULL;
3145 free(s->head_ref_name);
3146 s->head_ref_name = NULL;
3147 return err;
3151 * We use two queues to implement the limit feature: first consists of
3152 * commits matching the current limit_regex; second is the real queue
3153 * of all known commits (real_commits). When the user starts limiting,
3154 * we swap queues such that all movement and displaying functionality
3155 * works with very slight change.
3157 static const struct got_error *
3158 limit_log_view(struct tog_view *view)
3160 struct tog_log_view_state *s = &view->state.log;
3161 struct commit_queue_entry *entry;
3162 struct tog_view *v = view;
3163 const struct got_error *err = NULL;
3164 char pattern[1024];
3165 int ret;
3167 if (view_is_hsplit_top(view))
3168 v = view->child;
3169 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3170 v = view->parent;
3172 /* Get the pattern */
3173 wmove(v->window, v->nlines - 1, 0);
3174 wclrtoeol(v->window);
3175 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3176 nodelay(v->window, FALSE);
3177 nocbreak();
3178 echo();
3179 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3180 cbreak();
3181 noecho();
3182 nodelay(v->window, TRUE);
3183 if (ret == ERR)
3184 return NULL;
3186 if (*pattern == '\0') {
3188 * Safety measure for the situation where the user
3189 * resets limit without previously limiting anything.
3191 if (!s->limit_view)
3192 return NULL;
3195 * User could have pressed Ctrl+L, which refreshed the
3196 * commit queues, it means we can't save previously
3197 * (before limit took place) displayed entries,
3198 * because they would point to already free'ed memory,
3199 * so we are forced to always select first entry of
3200 * the queue.
3202 s->commits = &s->real_commits;
3203 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3204 s->selected_entry = s->first_displayed_entry;
3205 s->selected = 0;
3206 s->limit_view = 0;
3208 return NULL;
3211 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3212 return NULL;
3214 s->limit_view = 1;
3216 /* Clear the screen while loading limit view */
3217 s->first_displayed_entry = NULL;
3218 s->last_displayed_entry = NULL;
3219 s->selected_entry = NULL;
3220 s->commits = &s->limit_commits;
3222 /* Prepare limit queue for new search */
3223 free_commits(&s->limit_commits);
3224 s->limit_commits.ncommits = 0;
3226 /* First process commits, which are in queue already */
3227 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3228 int have_match = 0;
3230 err = match_commit(&have_match, entry->id,
3231 entry->commit, &s->limit_regex);
3232 if (err)
3233 return err;
3235 if (have_match) {
3236 struct commit_queue_entry *matched;
3238 matched = alloc_commit_queue_entry(entry->commit,
3239 entry->id);
3240 if (matched == NULL) {
3241 err = got_error_from_errno(
3242 "alloc_commit_queue_entry");
3243 break;
3245 matched->commit = entry->commit;
3246 got_object_commit_retain(entry->commit);
3248 matched->idx = s->limit_commits.ncommits;
3249 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3250 matched, entry);
3251 s->limit_commits.ncommits++;
3255 /* Second process all the commits, until we fill the screen */
3256 if (s->limit_commits.ncommits < view->nlines - 1 &&
3257 !s->thread_args.log_complete) {
3258 s->thread_args.commits_needed +=
3259 view->nlines - s->limit_commits.ncommits - 1;
3260 err = trigger_log_thread(view, 1);
3261 if (err)
3262 return err;
3265 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3266 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3267 s->selected = 0;
3269 return NULL;
3272 static const struct got_error *
3273 search_start_log_view(struct tog_view *view)
3275 struct tog_log_view_state *s = &view->state.log;
3277 s->matched_entry = NULL;
3278 s->search_entry = NULL;
3279 return NULL;
3282 static const struct got_error *
3283 search_next_log_view(struct tog_view *view)
3285 const struct got_error *err = NULL;
3286 struct tog_log_view_state *s = &view->state.log;
3287 struct commit_queue_entry *entry;
3289 /* Display progress update in log view. */
3290 show_log_view(view);
3291 update_panels();
3292 doupdate();
3294 if (s->search_entry) {
3295 int errcode, ch;
3296 errcode = pthread_mutex_unlock(&tog_mutex);
3297 if (errcode)
3298 return got_error_set_errno(errcode,
3299 "pthread_mutex_unlock");
3300 ch = wgetch(view->window);
3301 errcode = pthread_mutex_lock(&tog_mutex);
3302 if (errcode)
3303 return got_error_set_errno(errcode,
3304 "pthread_mutex_lock");
3305 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3306 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3307 return NULL;
3309 if (view->searching == TOG_SEARCH_FORWARD)
3310 entry = TAILQ_NEXT(s->search_entry, entry);
3311 else
3312 entry = TAILQ_PREV(s->search_entry,
3313 commit_queue_head, entry);
3314 } else if (s->matched_entry) {
3316 * If the user has moved the cursor after we hit a match,
3317 * the position from where we should continue searching
3318 * might have changed.
3320 if (view->searching == TOG_SEARCH_FORWARD)
3321 entry = TAILQ_NEXT(s->selected_entry, entry);
3322 else
3323 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3324 entry);
3325 } else {
3326 entry = s->selected_entry;
3329 while (1) {
3330 int have_match = 0;
3332 if (entry == NULL) {
3333 if (s->thread_args.log_complete ||
3334 view->searching == TOG_SEARCH_BACKWARD) {
3335 view->search_next_done =
3336 (s->matched_entry == NULL ?
3337 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3338 s->search_entry = NULL;
3339 return NULL;
3342 * Poke the log thread for more commits and return,
3343 * allowing the main loop to make progress. Search
3344 * will resume at s->search_entry once we come back.
3346 s->thread_args.commits_needed++;
3347 return trigger_log_thread(view, 0);
3350 err = match_commit(&have_match, entry->id, entry->commit,
3351 &view->regex);
3352 if (err)
3353 break;
3354 if (have_match) {
3355 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3356 s->matched_entry = entry;
3357 break;
3360 s->search_entry = entry;
3361 if (view->searching == TOG_SEARCH_FORWARD)
3362 entry = TAILQ_NEXT(entry, entry);
3363 else
3364 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3367 if (s->matched_entry) {
3368 int cur = s->selected_entry->idx;
3369 while (cur < s->matched_entry->idx) {
3370 err = input_log_view(NULL, view, KEY_DOWN);
3371 if (err)
3372 return err;
3373 cur++;
3375 while (cur > s->matched_entry->idx) {
3376 err = input_log_view(NULL, view, KEY_UP);
3377 if (err)
3378 return err;
3379 cur--;
3383 s->search_entry = NULL;
3385 return NULL;
3388 static const struct got_error *
3389 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3390 struct got_repository *repo, const char *head_ref_name,
3391 const char *in_repo_path, int log_branches)
3393 const struct got_error *err = NULL;
3394 struct tog_log_view_state *s = &view->state.log;
3395 struct got_repository *thread_repo = NULL;
3396 struct got_commit_graph *thread_graph = NULL;
3397 int errcode;
3399 if (in_repo_path != s->in_repo_path) {
3400 free(s->in_repo_path);
3401 s->in_repo_path = strdup(in_repo_path);
3402 if (s->in_repo_path == NULL)
3403 return got_error_from_errno("strdup");
3406 /* The commit queue only contains commits being displayed. */
3407 TAILQ_INIT(&s->real_commits.head);
3408 s->real_commits.ncommits = 0;
3409 s->commits = &s->real_commits;
3411 TAILQ_INIT(&s->limit_commits.head);
3412 s->limit_view = 0;
3413 s->limit_commits.ncommits = 0;
3415 s->repo = repo;
3416 if (head_ref_name) {
3417 s->head_ref_name = strdup(head_ref_name);
3418 if (s->head_ref_name == NULL) {
3419 err = got_error_from_errno("strdup");
3420 goto done;
3423 s->start_id = got_object_id_dup(start_id);
3424 if (s->start_id == NULL) {
3425 err = got_error_from_errno("got_object_id_dup");
3426 goto done;
3428 s->log_branches = log_branches;
3429 s->use_committer = 1;
3431 STAILQ_INIT(&s->colors);
3432 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3433 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3434 get_color_value("TOG_COLOR_COMMIT"));
3435 if (err)
3436 goto done;
3437 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3438 get_color_value("TOG_COLOR_AUTHOR"));
3439 if (err) {
3440 free_colors(&s->colors);
3441 goto done;
3443 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3444 get_color_value("TOG_COLOR_DATE"));
3445 if (err) {
3446 free_colors(&s->colors);
3447 goto done;
3451 view->show = show_log_view;
3452 view->input = input_log_view;
3453 view->resize = resize_log_view;
3454 view->close = close_log_view;
3455 view->search_start = search_start_log_view;
3456 view->search_next = search_next_log_view;
3458 if (s->thread_args.pack_fds == NULL) {
3459 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3460 if (err)
3461 goto done;
3463 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3464 s->thread_args.pack_fds);
3465 if (err)
3466 goto done;
3467 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3468 !s->log_branches);
3469 if (err)
3470 goto done;
3471 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3472 s->repo, NULL, NULL);
3473 if (err)
3474 goto done;
3476 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3477 if (errcode) {
3478 err = got_error_set_errno(errcode, "pthread_cond_init");
3479 goto done;
3481 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3482 if (errcode) {
3483 err = got_error_set_errno(errcode, "pthread_cond_init");
3484 goto done;
3487 s->thread_args.commits_needed = view->nlines;
3488 s->thread_args.graph = thread_graph;
3489 s->thread_args.real_commits = &s->real_commits;
3490 s->thread_args.limit_commits = &s->limit_commits;
3491 s->thread_args.in_repo_path = s->in_repo_path;
3492 s->thread_args.start_id = s->start_id;
3493 s->thread_args.repo = thread_repo;
3494 s->thread_args.log_complete = 0;
3495 s->thread_args.quit = &s->quit;
3496 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3497 s->thread_args.selected_entry = &s->selected_entry;
3498 s->thread_args.searching = &view->searching;
3499 s->thread_args.search_next_done = &view->search_next_done;
3500 s->thread_args.regex = &view->regex;
3501 s->thread_args.limiting = &s->limit_view;
3502 s->thread_args.limit_regex = &s->limit_regex;
3503 s->thread_args.limit_commits = &s->limit_commits;
3504 done:
3505 if (err)
3506 close_log_view(view);
3507 return err;
3510 static const struct got_error *
3511 show_log_view(struct tog_view *view)
3513 const struct got_error *err;
3514 struct tog_log_view_state *s = &view->state.log;
3516 if (s->thread == 0) { //NULL) {
3517 int errcode = pthread_create(&s->thread, NULL, log_thread,
3518 &s->thread_args);
3519 if (errcode)
3520 return got_error_set_errno(errcode, "pthread_create");
3521 if (s->thread_args.commits_needed > 0) {
3522 err = trigger_log_thread(view, 1);
3523 if (err)
3524 return err;
3528 return draw_commits(view);
3531 static void
3532 log_move_cursor_up(struct tog_view *view, int page, int home)
3534 struct tog_log_view_state *s = &view->state.log;
3536 if (s->first_displayed_entry == NULL)
3537 return;
3538 if (s->selected_entry->idx == 0)
3539 view->count = 0;
3541 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3542 || home)
3543 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3545 if (!page && !home && s->selected > 0)
3546 --s->selected;
3547 else
3548 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3550 select_commit(s);
3551 return;
3554 static const struct got_error *
3555 log_move_cursor_down(struct tog_view *view, int page)
3557 struct tog_log_view_state *s = &view->state.log;
3558 const struct got_error *err = NULL;
3559 int eos = view->nlines - 2;
3561 if (s->first_displayed_entry == NULL)
3562 return NULL;
3564 if (s->thread_args.log_complete &&
3565 s->selected_entry->idx >= s->commits->ncommits - 1)
3566 return NULL;
3568 if (view_is_hsplit_top(view))
3569 --eos; /* border consumes the last line */
3571 if (!page) {
3572 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3573 ++s->selected;
3574 else
3575 err = log_scroll_down(view, 1);
3576 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3577 struct commit_queue_entry *entry;
3578 int n;
3580 s->selected = 0;
3581 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3582 s->last_displayed_entry = entry;
3583 for (n = 0; n <= eos; n++) {
3584 if (entry == NULL)
3585 break;
3586 s->first_displayed_entry = entry;
3587 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3589 if (n > 0)
3590 s->selected = n - 1;
3591 } else {
3592 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3593 s->thread_args.log_complete)
3594 s->selected += MIN(page,
3595 s->commits->ncommits - s->selected_entry->idx - 1);
3596 else
3597 err = log_scroll_down(view, page);
3599 if (err)
3600 return err;
3603 * We might necessarily overshoot in horizontal
3604 * splits; if so, select the last displayed commit.
3606 if (s->first_displayed_entry && s->last_displayed_entry) {
3607 s->selected = MIN(s->selected,
3608 s->last_displayed_entry->idx -
3609 s->first_displayed_entry->idx);
3612 select_commit(s);
3614 if (s->thread_args.log_complete &&
3615 s->selected_entry->idx == s->commits->ncommits - 1)
3616 view->count = 0;
3618 return NULL;
3621 static void
3622 view_get_split(struct tog_view *view, int *y, int *x)
3624 *x = 0;
3625 *y = 0;
3627 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3628 if (view->child && view->child->resized_y)
3629 *y = view->child->resized_y;
3630 else if (view->resized_y)
3631 *y = view->resized_y;
3632 else
3633 *y = view_split_begin_y(view->lines);
3634 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3635 if (view->child && view->child->resized_x)
3636 *x = view->child->resized_x;
3637 else if (view->resized_x)
3638 *x = view->resized_x;
3639 else
3640 *x = view_split_begin_x(view->begin_x);
3644 /* Split view horizontally at y and offset view->state->selected line. */
3645 static const struct got_error *
3646 view_init_hsplit(struct tog_view *view, int y)
3648 const struct got_error *err = NULL;
3650 view->nlines = y;
3651 view->ncols = COLS;
3652 err = view_resize(view);
3653 if (err)
3654 return err;
3656 err = offset_selection_down(view);
3658 return err;
3661 static const struct got_error *
3662 log_goto_line(struct tog_view *view, int nlines)
3664 const struct got_error *err = NULL;
3665 struct tog_log_view_state *s = &view->state.log;
3666 int g, idx = s->selected_entry->idx;
3668 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3669 return NULL;
3671 g = view->gline;
3672 view->gline = 0;
3674 if (g >= s->first_displayed_entry->idx + 1 &&
3675 g <= s->last_displayed_entry->idx + 1 &&
3676 g - s->first_displayed_entry->idx - 1 < nlines) {
3677 s->selected = g - s->first_displayed_entry->idx - 1;
3678 select_commit(s);
3679 return NULL;
3682 if (idx + 1 < g) {
3683 err = log_move_cursor_down(view, g - idx - 1);
3684 if (!err && g > s->selected_entry->idx + 1)
3685 err = log_move_cursor_down(view,
3686 g - s->first_displayed_entry->idx - 1);
3687 if (err)
3688 return err;
3689 } else if (idx + 1 > g)
3690 log_move_cursor_up(view, idx - g + 1, 0);
3692 if (g < nlines && s->first_displayed_entry->idx == 0)
3693 s->selected = g - 1;
3695 select_commit(s);
3696 return NULL;
3700 static const struct got_error *
3701 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3703 const struct got_error *err = NULL;
3704 struct tog_log_view_state *s = &view->state.log;
3705 int eos, nscroll;
3707 if (s->thread_args.load_all) {
3708 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3709 s->thread_args.load_all = 0;
3710 else if (s->thread_args.log_complete) {
3711 err = log_move_cursor_down(view, s->commits->ncommits);
3712 s->thread_args.load_all = 0;
3714 if (err)
3715 return err;
3718 eos = nscroll = view->nlines - 1;
3719 if (view_is_hsplit_top(view))
3720 --eos; /* border */
3722 if (view->gline)
3723 return log_goto_line(view, eos);
3725 switch (ch) {
3726 case '&':
3727 err = limit_log_view(view);
3728 break;
3729 case 'q':
3730 s->quit = 1;
3731 break;
3732 case '0':
3733 view->x = 0;
3734 break;
3735 case '$':
3736 view->x = MAX(view->maxx - view->ncols / 2, 0);
3737 view->count = 0;
3738 break;
3739 case KEY_RIGHT:
3740 case 'l':
3741 if (view->x + view->ncols / 2 < view->maxx)
3742 view->x += 2; /* move two columns right */
3743 else
3744 view->count = 0;
3745 break;
3746 case KEY_LEFT:
3747 case 'h':
3748 view->x -= MIN(view->x, 2); /* move two columns back */
3749 if (view->x <= 0)
3750 view->count = 0;
3751 break;
3752 case 'k':
3753 case KEY_UP:
3754 case '<':
3755 case ',':
3756 case CTRL('p'):
3757 log_move_cursor_up(view, 0, 0);
3758 break;
3759 case 'g':
3760 case '=':
3761 case KEY_HOME:
3762 log_move_cursor_up(view, 0, 1);
3763 view->count = 0;
3764 break;
3765 case CTRL('u'):
3766 case 'u':
3767 nscroll /= 2;
3768 /* FALL THROUGH */
3769 case KEY_PPAGE:
3770 case CTRL('b'):
3771 case 'b':
3772 log_move_cursor_up(view, nscroll, 0);
3773 break;
3774 case 'j':
3775 case KEY_DOWN:
3776 case '>':
3777 case '.':
3778 case CTRL('n'):
3779 err = log_move_cursor_down(view, 0);
3780 break;
3781 case '@':
3782 s->use_committer = !s->use_committer;
3783 view->action = s->use_committer ?
3784 "show committer" : "show commit author";
3785 break;
3786 case 'G':
3787 case '*':
3788 case KEY_END: {
3789 /* We don't know yet how many commits, so we're forced to
3790 * traverse them all. */
3791 view->count = 0;
3792 s->thread_args.load_all = 1;
3793 if (!s->thread_args.log_complete)
3794 return trigger_log_thread(view, 0);
3795 err = log_move_cursor_down(view, s->commits->ncommits);
3796 s->thread_args.load_all = 0;
3797 break;
3799 case CTRL('d'):
3800 case 'd':
3801 nscroll /= 2;
3802 /* FALL THROUGH */
3803 case KEY_NPAGE:
3804 case CTRL('f'):
3805 case 'f':
3806 case ' ':
3807 err = log_move_cursor_down(view, nscroll);
3808 break;
3809 case KEY_RESIZE:
3810 if (s->selected > view->nlines - 2)
3811 s->selected = view->nlines - 2;
3812 if (s->selected > s->commits->ncommits - 1)
3813 s->selected = s->commits->ncommits - 1;
3814 select_commit(s);
3815 if (s->commits->ncommits < view->nlines - 1 &&
3816 !s->thread_args.log_complete) {
3817 s->thread_args.commits_needed += (view->nlines - 1) -
3818 s->commits->ncommits;
3819 err = trigger_log_thread(view, 1);
3821 break;
3822 case KEY_ENTER:
3823 case '\r':
3824 view->count = 0;
3825 if (s->selected_entry == NULL)
3826 break;
3827 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3828 break;
3829 case 'T':
3830 view->count = 0;
3831 if (s->selected_entry == NULL)
3832 break;
3833 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3834 break;
3835 case KEY_BACKSPACE:
3836 case CTRL('l'):
3837 case 'B':
3838 view->count = 0;
3839 if (ch == KEY_BACKSPACE &&
3840 got_path_is_root_dir(s->in_repo_path))
3841 break;
3842 err = stop_log_thread(s);
3843 if (err)
3844 return err;
3845 if (ch == KEY_BACKSPACE) {
3846 char *parent_path;
3847 err = got_path_dirname(&parent_path, s->in_repo_path);
3848 if (err)
3849 return err;
3850 free(s->in_repo_path);
3851 s->in_repo_path = parent_path;
3852 s->thread_args.in_repo_path = s->in_repo_path;
3853 } else if (ch == CTRL('l')) {
3854 struct got_object_id *start_id;
3855 err = got_repo_match_object_id(&start_id, NULL,
3856 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3857 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3858 if (err) {
3859 if (s->head_ref_name == NULL ||
3860 err->code != GOT_ERR_NOT_REF)
3861 return err;
3862 /* Try to cope with deleted references. */
3863 free(s->head_ref_name);
3864 s->head_ref_name = NULL;
3865 err = got_repo_match_object_id(&start_id,
3866 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
3867 &tog_refs, s->repo);
3868 if (err)
3869 return err;
3871 free(s->start_id);
3872 s->start_id = start_id;
3873 s->thread_args.start_id = s->start_id;
3874 } else /* 'B' */
3875 s->log_branches = !s->log_branches;
3877 if (s->thread_args.pack_fds == NULL) {
3878 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3879 if (err)
3880 return err;
3882 err = got_repo_open(&s->thread_args.repo,
3883 got_repo_get_path(s->repo), NULL,
3884 s->thread_args.pack_fds);
3885 if (err)
3886 return err;
3887 tog_free_refs();
3888 err = tog_load_refs(s->repo, 0);
3889 if (err)
3890 return err;
3891 err = got_commit_graph_open(&s->thread_args.graph,
3892 s->in_repo_path, !s->log_branches);
3893 if (err)
3894 return err;
3895 err = got_commit_graph_iter_start(s->thread_args.graph,
3896 s->start_id, s->repo, NULL, NULL);
3897 if (err)
3898 return err;
3899 free_commits(&s->real_commits);
3900 free_commits(&s->limit_commits);
3901 s->first_displayed_entry = NULL;
3902 s->last_displayed_entry = NULL;
3903 s->selected_entry = NULL;
3904 s->selected = 0;
3905 s->thread_args.log_complete = 0;
3906 s->quit = 0;
3907 s->thread_args.commits_needed = view->lines;
3908 s->matched_entry = NULL;
3909 s->search_entry = NULL;
3910 view->offset = 0;
3911 break;
3912 case 'R':
3913 view->count = 0;
3914 err = view_request_new(new_view, view, TOG_VIEW_REF);
3915 break;
3916 default:
3917 view->count = 0;
3918 break;
3921 return err;
3924 static const struct got_error *
3925 apply_unveil(const char *repo_path, const char *worktree_path)
3927 const struct got_error *error;
3929 #ifdef PROFILE
3930 if (unveil("gmon.out", "rwc") != 0)
3931 return got_error_from_errno2("unveil", "gmon.out");
3932 #endif
3933 if (repo_path && unveil(repo_path, "r") != 0)
3934 return got_error_from_errno2("unveil", repo_path);
3936 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3937 return got_error_from_errno2("unveil", worktree_path);
3939 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3940 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3942 error = got_privsep_unveil_exec_helpers();
3943 if (error != NULL)
3944 return error;
3946 if (unveil(NULL, NULL) != 0)
3947 return got_error_from_errno("unveil");
3949 return NULL;
3952 static void
3953 init_curses(void)
3956 * Override default signal handlers before starting ncurses.
3957 * This should prevent ncurses from installing its own
3958 * broken cleanup() signal handler.
3960 signal(SIGWINCH, tog_sigwinch);
3961 signal(SIGPIPE, tog_sigpipe);
3962 signal(SIGCONT, tog_sigcont);
3963 signal(SIGINT, tog_sigint);
3964 signal(SIGTERM, tog_sigterm);
3966 initscr();
3967 cbreak();
3968 halfdelay(1); /* Do fast refresh while initial view is loading. */
3969 noecho();
3970 nonl();
3971 intrflush(stdscr, FALSE);
3972 keypad(stdscr, TRUE);
3973 curs_set(0);
3974 if (getenv("TOG_COLORS") != NULL) {
3975 start_color();
3976 use_default_colors();
3980 static const struct got_error *
3981 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3982 struct got_repository *repo, struct got_worktree *worktree)
3984 const struct got_error *err = NULL;
3986 if (argc == 0) {
3987 *in_repo_path = strdup("/");
3988 if (*in_repo_path == NULL)
3989 return got_error_from_errno("strdup");
3990 return NULL;
3993 if (worktree) {
3994 const char *prefix = got_worktree_get_path_prefix(worktree);
3995 char *p;
3997 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3998 if (err)
3999 return err;
4000 if (asprintf(in_repo_path, "%s%s%s", prefix,
4001 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4002 p) == -1) {
4003 err = got_error_from_errno("asprintf");
4004 *in_repo_path = NULL;
4006 free(p);
4007 } else
4008 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4010 return err;
4013 static const struct got_error *
4014 cmd_log(int argc, char *argv[])
4016 const struct got_error *error;
4017 struct got_repository *repo = NULL;
4018 struct got_worktree *worktree = NULL;
4019 struct got_object_id *start_id = NULL;
4020 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4021 char *start_commit = NULL, *label = NULL;
4022 struct got_reference *ref = NULL;
4023 const char *head_ref_name = NULL;
4024 int ch, log_branches = 0;
4025 struct tog_view *view;
4026 int *pack_fds = NULL;
4028 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4029 switch (ch) {
4030 case 'b':
4031 log_branches = 1;
4032 break;
4033 case 'c':
4034 start_commit = optarg;
4035 break;
4036 case 'r':
4037 repo_path = realpath(optarg, NULL);
4038 if (repo_path == NULL)
4039 return got_error_from_errno2("realpath",
4040 optarg);
4041 break;
4042 default:
4043 usage_log();
4044 /* NOTREACHED */
4048 argc -= optind;
4049 argv += optind;
4051 if (argc > 1)
4052 usage_log();
4054 error = got_repo_pack_fds_open(&pack_fds);
4055 if (error != NULL)
4056 goto done;
4058 if (repo_path == NULL) {
4059 cwd = getcwd(NULL, 0);
4060 if (cwd == NULL)
4061 return got_error_from_errno("getcwd");
4062 error = got_worktree_open(&worktree, cwd);
4063 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4064 goto done;
4065 if (worktree)
4066 repo_path =
4067 strdup(got_worktree_get_repo_path(worktree));
4068 else
4069 repo_path = strdup(cwd);
4070 if (repo_path == NULL) {
4071 error = got_error_from_errno("strdup");
4072 goto done;
4076 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4077 if (error != NULL)
4078 goto done;
4080 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4081 repo, worktree);
4082 if (error)
4083 goto done;
4085 init_curses();
4087 error = apply_unveil(got_repo_get_path(repo),
4088 worktree ? got_worktree_get_root_path(worktree) : NULL);
4089 if (error)
4090 goto done;
4092 /* already loaded by tog_log_with_path()? */
4093 if (TAILQ_EMPTY(&tog_refs)) {
4094 error = tog_load_refs(repo, 0);
4095 if (error)
4096 goto done;
4099 if (start_commit == NULL) {
4100 error = got_repo_match_object_id(&start_id, &label,
4101 worktree ? got_worktree_get_head_ref_name(worktree) :
4102 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4103 if (error)
4104 goto done;
4105 head_ref_name = label;
4106 } else {
4107 error = got_ref_open(&ref, repo, start_commit, 0);
4108 if (error == NULL)
4109 head_ref_name = got_ref_get_name(ref);
4110 else if (error->code != GOT_ERR_NOT_REF)
4111 goto done;
4112 error = got_repo_match_object_id(&start_id, NULL,
4113 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4114 if (error)
4115 goto done;
4118 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4119 if (view == NULL) {
4120 error = got_error_from_errno("view_open");
4121 goto done;
4123 error = open_log_view(view, start_id, repo, head_ref_name,
4124 in_repo_path, log_branches);
4125 if (error)
4126 goto done;
4127 if (worktree) {
4128 /* Release work tree lock. */
4129 got_worktree_close(worktree);
4130 worktree = NULL;
4132 error = view_loop(view);
4133 done:
4134 free(in_repo_path);
4135 free(repo_path);
4136 free(cwd);
4137 free(start_id);
4138 free(label);
4139 if (ref)
4140 got_ref_close(ref);
4141 if (repo) {
4142 const struct got_error *close_err = got_repo_close(repo);
4143 if (error == NULL)
4144 error = close_err;
4146 if (worktree)
4147 got_worktree_close(worktree);
4148 if (pack_fds) {
4149 const struct got_error *pack_err =
4150 got_repo_pack_fds_close(pack_fds);
4151 if (error == NULL)
4152 error = pack_err;
4154 tog_free_refs();
4155 return error;
4158 __dead static void
4159 usage_diff(void)
4161 endwin();
4162 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4163 "object1 object2\n", getprogname());
4164 exit(1);
4167 static int
4168 match_line(const char *line, regex_t *regex, size_t nmatch,
4169 regmatch_t *regmatch)
4171 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4174 static struct tog_color *
4175 match_color(struct tog_colors *colors, const char *line)
4177 struct tog_color *tc = NULL;
4179 STAILQ_FOREACH(tc, colors, entry) {
4180 if (match_line(line, &tc->regex, 0, NULL))
4181 return tc;
4184 return NULL;
4187 static const struct got_error *
4188 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4189 WINDOW *window, int skipcol, regmatch_t *regmatch)
4191 const struct got_error *err = NULL;
4192 char *exstr = NULL;
4193 wchar_t *wline = NULL;
4194 int rme, rms, n, width, scrollx;
4195 int width0 = 0, width1 = 0, width2 = 0;
4196 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4198 *wtotal = 0;
4200 rms = regmatch->rm_so;
4201 rme = regmatch->rm_eo;
4203 err = expand_tab(&exstr, line);
4204 if (err)
4205 return err;
4207 /* Split the line into 3 segments, according to match offsets. */
4208 seg0 = strndup(exstr, rms);
4209 if (seg0 == NULL) {
4210 err = got_error_from_errno("strndup");
4211 goto done;
4213 seg1 = strndup(exstr + rms, rme - rms);
4214 if (seg1 == NULL) {
4215 err = got_error_from_errno("strndup");
4216 goto done;
4218 seg2 = strdup(exstr + rme);
4219 if (seg2 == NULL) {
4220 err = got_error_from_errno("strndup");
4221 goto done;
4224 /* draw up to matched token if we haven't scrolled past it */
4225 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4226 col_tab_align, 1);
4227 if (err)
4228 goto done;
4229 n = MAX(width0 - skipcol, 0);
4230 if (n) {
4231 free(wline);
4232 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4233 wlimit, col_tab_align, 1);
4234 if (err)
4235 goto done;
4236 waddwstr(window, &wline[scrollx]);
4237 wlimit -= width;
4238 *wtotal += width;
4241 if (wlimit > 0) {
4242 int i = 0, w = 0;
4243 size_t wlen;
4245 free(wline);
4246 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4247 col_tab_align, 1);
4248 if (err)
4249 goto done;
4250 wlen = wcslen(wline);
4251 while (i < wlen) {
4252 width = wcwidth(wline[i]);
4253 if (width == -1) {
4254 /* should not happen, tabs are expanded */
4255 err = got_error(GOT_ERR_RANGE);
4256 goto done;
4258 if (width0 + w + width > skipcol)
4259 break;
4260 w += width;
4261 i++;
4263 /* draw (visible part of) matched token (if scrolled into it) */
4264 if (width1 - w > 0) {
4265 wattron(window, A_STANDOUT);
4266 waddwstr(window, &wline[i]);
4267 wattroff(window, A_STANDOUT);
4268 wlimit -= (width1 - w);
4269 *wtotal += (width1 - w);
4273 if (wlimit > 0) { /* draw rest of line */
4274 free(wline);
4275 if (skipcol > width0 + width1) {
4276 err = format_line(&wline, &width2, &scrollx, seg2,
4277 skipcol - (width0 + width1), wlimit,
4278 col_tab_align, 1);
4279 if (err)
4280 goto done;
4281 waddwstr(window, &wline[scrollx]);
4282 } else {
4283 err = format_line(&wline, &width2, NULL, seg2, 0,
4284 wlimit, col_tab_align, 1);
4285 if (err)
4286 goto done;
4287 waddwstr(window, wline);
4289 *wtotal += width2;
4291 done:
4292 free(wline);
4293 free(exstr);
4294 free(seg0);
4295 free(seg1);
4296 free(seg2);
4297 return err;
4300 static int
4301 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4303 FILE *f = NULL;
4304 int *eof, *first, *selected;
4306 if (view->type == TOG_VIEW_DIFF) {
4307 struct tog_diff_view_state *s = &view->state.diff;
4309 first = &s->first_displayed_line;
4310 selected = first;
4311 eof = &s->eof;
4312 f = s->f;
4313 } else if (view->type == TOG_VIEW_HELP) {
4314 struct tog_help_view_state *s = &view->state.help;
4316 first = &s->first_displayed_line;
4317 selected = first;
4318 eof = &s->eof;
4319 f = s->f;
4320 } else if (view->type == TOG_VIEW_BLAME) {
4321 struct tog_blame_view_state *s = &view->state.blame;
4323 first = &s->first_displayed_line;
4324 selected = &s->selected_line;
4325 eof = &s->eof;
4326 f = s->blame.f;
4327 } else
4328 return 0;
4330 /* Center gline in the middle of the page like vi(1). */
4331 if (*lineno < view->gline - (view->nlines - 3) / 2)
4332 return 0;
4333 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4334 rewind(f);
4335 *eof = 0;
4336 *first = 1;
4337 *lineno = 0;
4338 *nprinted = 0;
4339 return 0;
4342 *selected = view->gline <= (view->nlines - 3) / 2 ?
4343 view->gline : (view->nlines - 3) / 2 + 1;
4344 view->gline = 0;
4346 return 1;
4349 static const struct got_error *
4350 draw_file(struct tog_view *view, const char *header)
4352 struct tog_diff_view_state *s = &view->state.diff;
4353 regmatch_t *regmatch = &view->regmatch;
4354 const struct got_error *err;
4355 int nprinted = 0;
4356 char *line;
4357 size_t linesize = 0;
4358 ssize_t linelen;
4359 wchar_t *wline;
4360 int width;
4361 int max_lines = view->nlines;
4362 int nlines = s->nlines;
4363 off_t line_offset;
4365 s->lineno = s->first_displayed_line - 1;
4366 line_offset = s->lines[s->first_displayed_line - 1].offset;
4367 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4368 return got_error_from_errno("fseek");
4370 werase(view->window);
4372 if (view->gline > s->nlines - 1)
4373 view->gline = s->nlines - 1;
4375 if (header) {
4376 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4377 1 : view->gline - (view->nlines - 3) / 2 :
4378 s->lineno + s->selected_line;
4380 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4381 return got_error_from_errno("asprintf");
4382 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4383 0, 0);
4384 free(line);
4385 if (err)
4386 return err;
4388 if (view_needs_focus_indication(view))
4389 wstandout(view->window);
4390 waddwstr(view->window, wline);
4391 free(wline);
4392 wline = NULL;
4393 while (width++ < view->ncols)
4394 waddch(view->window, ' ');
4395 if (view_needs_focus_indication(view))
4396 wstandend(view->window);
4398 if (max_lines <= 1)
4399 return NULL;
4400 max_lines--;
4403 s->eof = 0;
4404 view->maxx = 0;
4405 line = NULL;
4406 while (max_lines > 0 && nprinted < max_lines) {
4407 enum got_diff_line_type linetype;
4408 attr_t attr = 0;
4410 linelen = getline(&line, &linesize, s->f);
4411 if (linelen == -1) {
4412 if (feof(s->f)) {
4413 s->eof = 1;
4414 break;
4416 free(line);
4417 return got_ferror(s->f, GOT_ERR_IO);
4420 if (++s->lineno < s->first_displayed_line)
4421 continue;
4422 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4423 continue;
4424 if (s->lineno == view->hiline)
4425 attr = A_STANDOUT;
4427 /* Set view->maxx based on full line length. */
4428 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4429 view->x ? 1 : 0);
4430 if (err) {
4431 free(line);
4432 return err;
4434 view->maxx = MAX(view->maxx, width);
4435 free(wline);
4436 wline = NULL;
4438 linetype = s->lines[s->lineno].type;
4439 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4440 linetype < GOT_DIFF_LINE_CONTEXT)
4441 attr |= COLOR_PAIR(linetype);
4442 if (attr)
4443 wattron(view->window, attr);
4444 if (s->first_displayed_line + nprinted == s->matched_line &&
4445 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4446 err = add_matched_line(&width, line, view->ncols, 0,
4447 view->window, view->x, regmatch);
4448 if (err) {
4449 free(line);
4450 return err;
4452 } else {
4453 int skip;
4454 err = format_line(&wline, &width, &skip, line,
4455 view->x, view->ncols, 0, view->x ? 1 : 0);
4456 if (err) {
4457 free(line);
4458 return err;
4460 waddwstr(view->window, &wline[skip]);
4461 free(wline);
4462 wline = NULL;
4464 if (s->lineno == view->hiline) {
4465 /* highlight full gline length */
4466 while (width++ < view->ncols)
4467 waddch(view->window, ' ');
4468 } else {
4469 if (width <= view->ncols - 1)
4470 waddch(view->window, '\n');
4472 if (attr)
4473 wattroff(view->window, attr);
4474 if (++nprinted == 1)
4475 s->first_displayed_line = s->lineno;
4477 free(line);
4478 if (nprinted >= 1)
4479 s->last_displayed_line = s->first_displayed_line +
4480 (nprinted - 1);
4481 else
4482 s->last_displayed_line = s->first_displayed_line;
4484 view_border(view);
4486 if (s->eof) {
4487 while (nprinted < view->nlines) {
4488 waddch(view->window, '\n');
4489 nprinted++;
4492 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4493 view->ncols, 0, 0);
4494 if (err) {
4495 return err;
4498 wstandout(view->window);
4499 waddwstr(view->window, wline);
4500 free(wline);
4501 wline = NULL;
4502 wstandend(view->window);
4505 return NULL;
4508 static char *
4509 get_datestr(time_t *time, char *datebuf)
4511 struct tm mytm, *tm;
4512 char *p, *s;
4514 tm = gmtime_r(time, &mytm);
4515 if (tm == NULL)
4516 return NULL;
4517 s = asctime_r(tm, datebuf);
4518 if (s == NULL)
4519 return NULL;
4520 p = strchr(s, '\n');
4521 if (p)
4522 *p = '\0';
4523 return s;
4526 static const struct got_error *
4527 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4528 off_t off, uint8_t type)
4530 struct got_diff_line *p;
4532 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4533 if (p == NULL)
4534 return got_error_from_errno("reallocarray");
4535 *lines = p;
4536 (*lines)[*nlines].offset = off;
4537 (*lines)[*nlines].type = type;
4538 (*nlines)++;
4540 return NULL;
4543 static const struct got_error *
4544 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4545 struct got_diff_line *s_lines, size_t s_nlines)
4547 struct got_diff_line *p;
4548 char buf[BUFSIZ];
4549 size_t i, r;
4551 if (fseeko(src, 0L, SEEK_SET) == -1)
4552 return got_error_from_errno("fseeko");
4554 for (;;) {
4555 r = fread(buf, 1, sizeof(buf), src);
4556 if (r == 0) {
4557 if (ferror(src))
4558 return got_error_from_errno("fread");
4559 if (feof(src))
4560 break;
4562 if (fwrite(buf, 1, r, dst) != r)
4563 return got_ferror(dst, GOT_ERR_IO);
4567 * The diff driver initialises the first line at offset zero when the
4568 * array isn't prepopulated, skip it; we already have it in *d_lines.
4570 for (i = 1; i < s_nlines; ++i)
4571 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4573 --s_nlines;
4575 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4576 if (p == NULL) {
4577 /* d_lines is freed in close_diff_view() */
4578 return got_error_from_errno("reallocarray");
4581 *d_lines = p;
4583 memcpy(*d_lines + *d_nlines, s_lines + 1, s_nlines * sizeof(*s_lines));
4584 *d_nlines += s_nlines;
4586 return NULL;
4589 static const struct got_error *
4590 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4591 struct got_object_id *commit_id, struct got_reflist_head *refs,
4592 struct got_repository *repo, int ignore_ws, int force_text_diff,
4593 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4595 const struct got_error *err = NULL;
4596 char datebuf[26], *datestr;
4597 struct got_commit_object *commit;
4598 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4599 time_t committer_time;
4600 const char *author, *committer;
4601 char *refs_str = NULL;
4602 struct got_pathlist_entry *pe;
4603 off_t outoff = 0;
4604 int n;
4606 if (refs) {
4607 err = build_refs_str(&refs_str, refs, commit_id, repo);
4608 if (err)
4609 return err;
4612 err = got_object_open_as_commit(&commit, repo, commit_id);
4613 if (err)
4614 return err;
4616 err = got_object_id_str(&id_str, commit_id);
4617 if (err) {
4618 err = got_error_from_errno("got_object_id_str");
4619 goto done;
4622 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4623 if (err)
4624 goto done;
4626 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4627 refs_str ? refs_str : "", refs_str ? ")" : "");
4628 if (n < 0) {
4629 err = got_error_from_errno("fprintf");
4630 goto done;
4632 outoff += n;
4633 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4634 if (err)
4635 goto done;
4637 n = fprintf(outfile, "from: %s\n",
4638 got_object_commit_get_author(commit));
4639 if (n < 0) {
4640 err = got_error_from_errno("fprintf");
4641 goto done;
4643 outoff += n;
4644 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4645 if (err)
4646 goto done;
4648 author = got_object_commit_get_author(commit);
4649 committer = got_object_commit_get_committer(commit);
4650 if (strcmp(author, committer) != 0) {
4651 n = fprintf(outfile, "via: %s\n", committer);
4652 if (n < 0) {
4653 err = got_error_from_errno("fprintf");
4654 goto done;
4656 outoff += n;
4657 err = add_line_metadata(lines, nlines, outoff,
4658 GOT_DIFF_LINE_AUTHOR);
4659 if (err)
4660 goto done;
4662 committer_time = got_object_commit_get_committer_time(commit);
4663 datestr = get_datestr(&committer_time, datebuf);
4664 if (datestr) {
4665 n = fprintf(outfile, "date: %s UTC\n", datestr);
4666 if (n < 0) {
4667 err = got_error_from_errno("fprintf");
4668 goto done;
4670 outoff += n;
4671 err = add_line_metadata(lines, nlines, outoff,
4672 GOT_DIFF_LINE_DATE);
4673 if (err)
4674 goto done;
4676 if (got_object_commit_get_nparents(commit) > 1) {
4677 const struct got_object_id_queue *parent_ids;
4678 struct got_object_qid *qid;
4679 int pn = 1;
4680 parent_ids = got_object_commit_get_parent_ids(commit);
4681 STAILQ_FOREACH(qid, parent_ids, entry) {
4682 err = got_object_id_str(&id_str, &qid->id);
4683 if (err)
4684 goto done;
4685 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4686 if (n < 0) {
4687 err = got_error_from_errno("fprintf");
4688 goto done;
4690 outoff += n;
4691 err = add_line_metadata(lines, nlines, outoff,
4692 GOT_DIFF_LINE_META);
4693 if (err)
4694 goto done;
4695 free(id_str);
4696 id_str = NULL;
4700 err = got_object_commit_get_logmsg(&logmsg, commit);
4701 if (err)
4702 goto done;
4703 s = logmsg;
4704 while ((line = strsep(&s, "\n")) != NULL) {
4705 n = fprintf(outfile, "%s\n", line);
4706 if (n < 0) {
4707 err = got_error_from_errno("fprintf");
4708 goto done;
4710 outoff += n;
4711 err = add_line_metadata(lines, nlines, outoff,
4712 GOT_DIFF_LINE_LOGMSG);
4713 if (err)
4714 goto done;
4717 TAILQ_FOREACH(pe, dsa->paths, entry) {
4718 struct got_diff_changed_path *cp = pe->data;
4719 int pad = dsa->max_path_len - pe->path_len + 1;
4721 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
4722 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
4723 dsa->rm_cols + 1, cp->rm);
4724 if (n < 0) {
4725 err = got_error_from_errno("fprintf");
4726 goto done;
4728 outoff += n;
4729 err = add_line_metadata(lines, nlines, outoff,
4730 GOT_DIFF_LINE_CHANGES);
4731 if (err)
4732 goto done;
4735 fputc('\n', outfile);
4736 outoff++;
4737 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4738 if (err)
4739 goto done;
4741 n = fprintf(outfile,
4742 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
4743 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4744 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4745 if (n < 0) {
4746 err = got_error_from_errno("fprintf");
4747 goto done;
4749 outoff += n;
4750 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4751 if (err)
4752 goto done;
4754 fputc('\n', outfile);
4755 outoff++;
4756 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4757 done:
4758 free(id_str);
4759 free(logmsg);
4760 free(refs_str);
4761 got_object_commit_close(commit);
4762 if (err) {
4763 free(*lines);
4764 *lines = NULL;
4765 *nlines = 0;
4767 return err;
4770 static const struct got_error *
4771 create_diff(struct tog_diff_view_state *s)
4773 const struct got_error *err = NULL;
4774 FILE *f = NULL, *tmp_diff_file = NULL;
4775 int obj_type;
4776 struct got_diff_line *lines = NULL;
4777 struct got_pathlist_head changed_paths;
4779 TAILQ_INIT(&changed_paths);
4781 free(s->lines);
4782 s->lines = malloc(sizeof(*s->lines));
4783 if (s->lines == NULL)
4784 return got_error_from_errno("malloc");
4785 s->nlines = 0;
4787 f = got_opentemp();
4788 if (f == NULL) {
4789 err = got_error_from_errno("got_opentemp");
4790 goto done;
4792 tmp_diff_file = got_opentemp();
4793 if (tmp_diff_file == NULL) {
4794 err = got_error_from_errno("got_opentemp");
4795 goto done;
4797 if (s->f && fclose(s->f) == EOF) {
4798 err = got_error_from_errno("fclose");
4799 goto done;
4801 s->f = f;
4803 if (s->id1)
4804 err = got_object_get_type(&obj_type, s->repo, s->id1);
4805 else
4806 err = got_object_get_type(&obj_type, s->repo, s->id2);
4807 if (err)
4808 goto done;
4810 switch (obj_type) {
4811 case GOT_OBJ_TYPE_BLOB:
4812 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4813 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4814 s->label1, s->label2, tog_diff_algo, s->diff_context,
4815 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
4816 s->f);
4817 break;
4818 case GOT_OBJ_TYPE_TREE:
4819 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4820 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4821 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4822 s->force_text_diff, NULL, s->repo, s->f);
4823 break;
4824 case GOT_OBJ_TYPE_COMMIT: {
4825 const struct got_object_id_queue *parent_ids;
4826 struct got_object_qid *pid;
4827 struct got_commit_object *commit2;
4828 struct got_reflist_head *refs;
4829 size_t nlines = 0;
4830 struct got_diffstat_cb_arg dsa = {
4831 0, 0, 0, 0, 0, 0,
4832 &changed_paths,
4833 s->ignore_whitespace,
4834 s->force_text_diff,
4835 tog_diff_algo
4838 lines = malloc(sizeof(*lines));
4839 if (lines == NULL) {
4840 err = got_error_from_errno("malloc");
4841 goto done;
4844 /* build diff first in tmp file then append to commit info */
4845 err = got_diff_objects_as_commits(&lines, &nlines,
4846 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4847 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4848 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
4849 if (err)
4850 break;
4852 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4853 if (err)
4854 goto done;
4855 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4856 /* Show commit info if we're diffing to a parent/root commit. */
4857 if (s->id1 == NULL) {
4858 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4859 refs, s->repo, s->ignore_whitespace,
4860 s->force_text_diff, &dsa, s->f);
4861 if (err)
4862 goto done;
4863 } else {
4864 parent_ids = got_object_commit_get_parent_ids(commit2);
4865 STAILQ_FOREACH(pid, parent_ids, entry) {
4866 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4867 err = write_commit_info(&s->lines,
4868 &s->nlines, s->id2, refs, s->repo,
4869 s->ignore_whitespace,
4870 s->force_text_diff, &dsa, s->f);
4871 if (err)
4872 goto done;
4873 break;
4877 got_object_commit_close(commit2);
4879 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
4880 lines, nlines);
4881 break;
4883 default:
4884 err = got_error(GOT_ERR_OBJ_TYPE);
4885 break;
4887 done:
4888 free(lines);
4889 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4890 if (s->f && fflush(s->f) != 0 && err == NULL)
4891 err = got_error_from_errno("fflush");
4892 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
4893 err = got_error_from_errno("fclose");
4894 return err;
4897 static void
4898 diff_view_indicate_progress(struct tog_view *view)
4900 mvwaddstr(view->window, 0, 0, "diffing...");
4901 update_panels();
4902 doupdate();
4905 static const struct got_error *
4906 search_start_diff_view(struct tog_view *view)
4908 struct tog_diff_view_state *s = &view->state.diff;
4910 s->matched_line = 0;
4911 return NULL;
4914 static void
4915 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
4916 size_t *nlines, int **first, int **last, int **match, int **selected)
4918 struct tog_diff_view_state *s = &view->state.diff;
4920 *f = s->f;
4921 *nlines = s->nlines;
4922 *line_offsets = NULL;
4923 *match = &s->matched_line;
4924 *first = &s->first_displayed_line;
4925 *last = &s->last_displayed_line;
4926 *selected = &s->selected_line;
4929 static const struct got_error *
4930 search_next_view_match(struct tog_view *view)
4932 const struct got_error *err = NULL;
4933 FILE *f;
4934 int lineno;
4935 char *line = NULL;
4936 size_t linesize = 0;
4937 ssize_t linelen;
4938 off_t *line_offsets;
4939 size_t nlines = 0;
4940 int *first, *last, *match, *selected;
4942 if (!view->search_setup)
4943 return got_error_msg(GOT_ERR_NOT_IMPL,
4944 "view search not supported");
4945 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
4946 &match, &selected);
4948 if (!view->searching) {
4949 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4950 return NULL;
4953 if (*match) {
4954 if (view->searching == TOG_SEARCH_FORWARD)
4955 lineno = *match + 1;
4956 else
4957 lineno = *match - 1;
4958 } else
4959 lineno = *first - 1 + *selected;
4961 while (1) {
4962 off_t offset;
4964 if (lineno <= 0 || lineno > nlines) {
4965 if (*match == 0) {
4966 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4967 break;
4970 if (view->searching == TOG_SEARCH_FORWARD)
4971 lineno = 1;
4972 else
4973 lineno = nlines;
4976 offset = view->type == TOG_VIEW_DIFF ?
4977 view->state.diff.lines[lineno - 1].offset :
4978 line_offsets[lineno - 1];
4979 if (fseeko(f, offset, SEEK_SET) != 0) {
4980 free(line);
4981 return got_error_from_errno("fseeko");
4983 linelen = getline(&line, &linesize, f);
4984 if (linelen != -1) {
4985 char *exstr;
4986 err = expand_tab(&exstr, line);
4987 if (err)
4988 break;
4989 if (match_line(exstr, &view->regex, 1,
4990 &view->regmatch)) {
4991 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4992 *match = lineno;
4993 free(exstr);
4994 break;
4996 free(exstr);
4998 if (view->searching == TOG_SEARCH_FORWARD)
4999 lineno++;
5000 else
5001 lineno--;
5003 free(line);
5005 if (*match) {
5006 *first = *match;
5007 *selected = 1;
5010 return err;
5013 static const struct got_error *
5014 close_diff_view(struct tog_view *view)
5016 const struct got_error *err = NULL;
5017 struct tog_diff_view_state *s = &view->state.diff;
5019 free(s->id1);
5020 s->id1 = NULL;
5021 free(s->id2);
5022 s->id2 = NULL;
5023 if (s->f && fclose(s->f) == EOF)
5024 err = got_error_from_errno("fclose");
5025 s->f = NULL;
5026 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5027 err = got_error_from_errno("fclose");
5028 s->f1 = NULL;
5029 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5030 err = got_error_from_errno("fclose");
5031 s->f2 = NULL;
5032 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5033 err = got_error_from_errno("close");
5034 s->fd1 = -1;
5035 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5036 err = got_error_from_errno("close");
5037 s->fd2 = -1;
5038 free(s->lines);
5039 s->lines = NULL;
5040 s->nlines = 0;
5041 return err;
5044 static const struct got_error *
5045 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5046 struct got_object_id *id2, const char *label1, const char *label2,
5047 int diff_context, int ignore_whitespace, int force_text_diff,
5048 struct tog_view *parent_view, struct got_repository *repo)
5050 const struct got_error *err;
5051 struct tog_diff_view_state *s = &view->state.diff;
5053 memset(s, 0, sizeof(*s));
5054 s->fd1 = -1;
5055 s->fd2 = -1;
5057 if (id1 != NULL && id2 != NULL) {
5058 int type1, type2;
5059 err = got_object_get_type(&type1, repo, id1);
5060 if (err)
5061 return err;
5062 err = got_object_get_type(&type2, repo, id2);
5063 if (err)
5064 return err;
5066 if (type1 != type2)
5067 return got_error(GOT_ERR_OBJ_TYPE);
5069 s->first_displayed_line = 1;
5070 s->last_displayed_line = view->nlines;
5071 s->selected_line = 1;
5072 s->repo = repo;
5073 s->id1 = id1;
5074 s->id2 = id2;
5075 s->label1 = label1;
5076 s->label2 = label2;
5078 if (id1) {
5079 s->id1 = got_object_id_dup(id1);
5080 if (s->id1 == NULL)
5081 return got_error_from_errno("got_object_id_dup");
5082 } else
5083 s->id1 = NULL;
5085 s->id2 = got_object_id_dup(id2);
5086 if (s->id2 == NULL) {
5087 err = got_error_from_errno("got_object_id_dup");
5088 goto done;
5091 s->f1 = got_opentemp();
5092 if (s->f1 == NULL) {
5093 err = got_error_from_errno("got_opentemp");
5094 goto done;
5097 s->f2 = got_opentemp();
5098 if (s->f2 == NULL) {
5099 err = got_error_from_errno("got_opentemp");
5100 goto done;
5103 s->fd1 = got_opentempfd();
5104 if (s->fd1 == -1) {
5105 err = got_error_from_errno("got_opentempfd");
5106 goto done;
5109 s->fd2 = got_opentempfd();
5110 if (s->fd2 == -1) {
5111 err = got_error_from_errno("got_opentempfd");
5112 goto done;
5115 s->diff_context = diff_context;
5116 s->ignore_whitespace = ignore_whitespace;
5117 s->force_text_diff = force_text_diff;
5118 s->parent_view = parent_view;
5119 s->repo = repo;
5121 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5122 int rc;
5124 rc = init_pair(GOT_DIFF_LINE_MINUS,
5125 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5126 if (rc != ERR)
5127 rc = init_pair(GOT_DIFF_LINE_PLUS,
5128 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5129 if (rc != ERR)
5130 rc = init_pair(GOT_DIFF_LINE_HUNK,
5131 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5132 if (rc != ERR)
5133 rc = init_pair(GOT_DIFF_LINE_META,
5134 get_color_value("TOG_COLOR_DIFF_META"), -1);
5135 if (rc != ERR)
5136 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5137 get_color_value("TOG_COLOR_DIFF_META"), -1);
5138 if (rc != ERR)
5139 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5140 get_color_value("TOG_COLOR_DIFF_META"), -1);
5141 if (rc != ERR)
5142 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5143 get_color_value("TOG_COLOR_DIFF_META"), -1);
5144 if (rc != ERR)
5145 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5146 get_color_value("TOG_COLOR_AUTHOR"), -1);
5147 if (rc != ERR)
5148 rc = init_pair(GOT_DIFF_LINE_DATE,
5149 get_color_value("TOG_COLOR_DATE"), -1);
5150 if (rc == ERR) {
5151 err = got_error(GOT_ERR_RANGE);
5152 goto done;
5156 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5157 view_is_splitscreen(view))
5158 show_log_view(parent_view); /* draw border */
5159 diff_view_indicate_progress(view);
5161 err = create_diff(s);
5163 view->show = show_diff_view;
5164 view->input = input_diff_view;
5165 view->reset = reset_diff_view;
5166 view->close = close_diff_view;
5167 view->search_start = search_start_diff_view;
5168 view->search_setup = search_setup_diff_view;
5169 view->search_next = search_next_view_match;
5170 done:
5171 if (err)
5172 close_diff_view(view);
5173 return err;
5176 static const struct got_error *
5177 show_diff_view(struct tog_view *view)
5179 const struct got_error *err;
5180 struct tog_diff_view_state *s = &view->state.diff;
5181 char *id_str1 = NULL, *id_str2, *header;
5182 const char *label1, *label2;
5184 if (s->id1) {
5185 err = got_object_id_str(&id_str1, s->id1);
5186 if (err)
5187 return err;
5188 label1 = s->label1 ? s->label1 : id_str1;
5189 } else
5190 label1 = "/dev/null";
5192 err = got_object_id_str(&id_str2, s->id2);
5193 if (err)
5194 return err;
5195 label2 = s->label2 ? s->label2 : id_str2;
5197 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5198 err = got_error_from_errno("asprintf");
5199 free(id_str1);
5200 free(id_str2);
5201 return err;
5203 free(id_str1);
5204 free(id_str2);
5206 err = draw_file(view, header);
5207 free(header);
5208 return err;
5211 static const struct got_error *
5212 set_selected_commit(struct tog_diff_view_state *s,
5213 struct commit_queue_entry *entry)
5215 const struct got_error *err;
5216 const struct got_object_id_queue *parent_ids;
5217 struct got_commit_object *selected_commit;
5218 struct got_object_qid *pid;
5220 free(s->id2);
5221 s->id2 = got_object_id_dup(entry->id);
5222 if (s->id2 == NULL)
5223 return got_error_from_errno("got_object_id_dup");
5225 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5226 if (err)
5227 return err;
5228 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5229 free(s->id1);
5230 pid = STAILQ_FIRST(parent_ids);
5231 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5232 got_object_commit_close(selected_commit);
5233 return NULL;
5236 static const struct got_error *
5237 reset_diff_view(struct tog_view *view)
5239 struct tog_diff_view_state *s = &view->state.diff;
5241 view->count = 0;
5242 wclear(view->window);
5243 s->first_displayed_line = 1;
5244 s->last_displayed_line = view->nlines;
5245 s->matched_line = 0;
5246 diff_view_indicate_progress(view);
5247 return create_diff(s);
5250 static void
5251 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5253 int start, i;
5255 i = start = s->first_displayed_line - 1;
5257 while (s->lines[i].type != type) {
5258 if (i == 0)
5259 i = s->nlines - 1;
5260 if (--i == start)
5261 return; /* do nothing, requested type not in file */
5264 s->selected_line = 1;
5265 s->first_displayed_line = i;
5268 static void
5269 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5271 int start, i;
5273 i = start = s->first_displayed_line + 1;
5275 while (s->lines[i].type != type) {
5276 if (i == s->nlines - 1)
5277 i = 0;
5278 if (++i == start)
5279 return; /* do nothing, requested type not in file */
5282 s->selected_line = 1;
5283 s->first_displayed_line = i;
5286 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5287 int, int, int);
5288 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5289 int, int);
5291 static const struct got_error *
5292 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5294 const struct got_error *err = NULL;
5295 struct tog_diff_view_state *s = &view->state.diff;
5296 struct tog_log_view_state *ls;
5297 struct commit_queue_entry *old_selected_entry;
5298 char *line = NULL;
5299 size_t linesize = 0;
5300 ssize_t linelen;
5301 int i, nscroll = view->nlines - 1, up = 0;
5303 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5305 switch (ch) {
5306 case '0':
5307 view->x = 0;
5308 break;
5309 case '$':
5310 view->x = MAX(view->maxx - view->ncols / 3, 0);
5311 view->count = 0;
5312 break;
5313 case KEY_RIGHT:
5314 case 'l':
5315 if (view->x + view->ncols / 3 < view->maxx)
5316 view->x += 2; /* move two columns right */
5317 else
5318 view->count = 0;
5319 break;
5320 case KEY_LEFT:
5321 case 'h':
5322 view->x -= MIN(view->x, 2); /* move two columns back */
5323 if (view->x <= 0)
5324 view->count = 0;
5325 break;
5326 case 'a':
5327 case 'w':
5328 if (ch == 'a') {
5329 s->force_text_diff = !s->force_text_diff;
5330 view->action = s->force_text_diff ?
5331 "force ASCII text enabled" :
5332 "force ASCII text disabled";
5334 else if (ch == 'w') {
5335 s->ignore_whitespace = !s->ignore_whitespace;
5336 view->action = s->ignore_whitespace ?
5337 "ignore whitespace enabled" :
5338 "ignore whitespace disabled";
5340 err = reset_diff_view(view);
5341 break;
5342 case 'g':
5343 case KEY_HOME:
5344 s->first_displayed_line = 1;
5345 view->count = 0;
5346 break;
5347 case 'G':
5348 case KEY_END:
5349 view->count = 0;
5350 if (s->eof)
5351 break;
5353 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5354 s->eof = 1;
5355 break;
5356 case 'k':
5357 case KEY_UP:
5358 case CTRL('p'):
5359 if (s->first_displayed_line > 1)
5360 s->first_displayed_line--;
5361 else
5362 view->count = 0;
5363 break;
5364 case CTRL('u'):
5365 case 'u':
5366 nscroll /= 2;
5367 /* FALL THROUGH */
5368 case KEY_PPAGE:
5369 case CTRL('b'):
5370 case 'b':
5371 if (s->first_displayed_line == 1) {
5372 view->count = 0;
5373 break;
5375 i = 0;
5376 while (i++ < nscroll && s->first_displayed_line > 1)
5377 s->first_displayed_line--;
5378 break;
5379 case 'j':
5380 case KEY_DOWN:
5381 case CTRL('n'):
5382 if (!s->eof)
5383 s->first_displayed_line++;
5384 else
5385 view->count = 0;
5386 break;
5387 case CTRL('d'):
5388 case 'd':
5389 nscroll /= 2;
5390 /* FALL THROUGH */
5391 case KEY_NPAGE:
5392 case CTRL('f'):
5393 case 'f':
5394 case ' ':
5395 if (s->eof) {
5396 view->count = 0;
5397 break;
5399 i = 0;
5400 while (!s->eof && i++ < nscroll) {
5401 linelen = getline(&line, &linesize, s->f);
5402 s->first_displayed_line++;
5403 if (linelen == -1) {
5404 if (feof(s->f)) {
5405 s->eof = 1;
5406 } else
5407 err = got_ferror(s->f, GOT_ERR_IO);
5408 break;
5411 free(line);
5412 break;
5413 case '(':
5414 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5415 break;
5416 case ')':
5417 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5418 break;
5419 case '{':
5420 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5421 break;
5422 case '}':
5423 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5424 break;
5425 case '[':
5426 if (s->diff_context > 0) {
5427 s->diff_context--;
5428 s->matched_line = 0;
5429 diff_view_indicate_progress(view);
5430 err = create_diff(s);
5431 if (s->first_displayed_line + view->nlines - 1 >
5432 s->nlines) {
5433 s->first_displayed_line = 1;
5434 s->last_displayed_line = view->nlines;
5436 } else
5437 view->count = 0;
5438 break;
5439 case ']':
5440 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5441 s->diff_context++;
5442 s->matched_line = 0;
5443 diff_view_indicate_progress(view);
5444 err = create_diff(s);
5445 } else
5446 view->count = 0;
5447 break;
5448 case '<':
5449 case ',':
5450 case 'K':
5451 up = 1;
5452 /* FALL THROUGH */
5453 case '>':
5454 case '.':
5455 case 'J':
5456 if (s->parent_view == NULL) {
5457 view->count = 0;
5458 break;
5460 s->parent_view->count = view->count;
5462 if (s->parent_view->type == TOG_VIEW_LOG) {
5463 ls = &s->parent_view->state.log;
5464 old_selected_entry = ls->selected_entry;
5466 err = input_log_view(NULL, s->parent_view,
5467 up ? KEY_UP : KEY_DOWN);
5468 if (err)
5469 break;
5470 view->count = s->parent_view->count;
5472 if (old_selected_entry == ls->selected_entry)
5473 break;
5475 err = set_selected_commit(s, ls->selected_entry);
5476 if (err)
5477 break;
5478 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5479 struct tog_blame_view_state *bs;
5480 struct got_object_id *id, *prev_id;
5482 bs = &s->parent_view->state.blame;
5483 prev_id = get_annotation_for_line(bs->blame.lines,
5484 bs->blame.nlines, bs->last_diffed_line);
5486 err = input_blame_view(&view, s->parent_view,
5487 up ? KEY_UP : KEY_DOWN);
5488 if (err)
5489 break;
5490 view->count = s->parent_view->count;
5492 if (prev_id == NULL)
5493 break;
5494 id = get_selected_commit_id(bs->blame.lines,
5495 bs->blame.nlines, bs->first_displayed_line,
5496 bs->selected_line);
5497 if (id == NULL)
5498 break;
5500 if (!got_object_id_cmp(prev_id, id))
5501 break;
5503 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5504 if (err)
5505 break;
5507 s->first_displayed_line = 1;
5508 s->last_displayed_line = view->nlines;
5509 s->matched_line = 0;
5510 view->x = 0;
5512 diff_view_indicate_progress(view);
5513 err = create_diff(s);
5514 break;
5515 default:
5516 view->count = 0;
5517 break;
5520 return err;
5523 static const struct got_error *
5524 cmd_diff(int argc, char *argv[])
5526 const struct got_error *error = NULL;
5527 struct got_repository *repo = NULL;
5528 struct got_worktree *worktree = NULL;
5529 struct got_object_id *id1 = NULL, *id2 = NULL;
5530 char *repo_path = NULL, *cwd = NULL;
5531 char *id_str1 = NULL, *id_str2 = NULL;
5532 char *label1 = NULL, *label2 = NULL;
5533 int diff_context = 3, ignore_whitespace = 0;
5534 int ch, force_text_diff = 0;
5535 const char *errstr;
5536 struct tog_view *view;
5537 int *pack_fds = NULL;
5539 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5540 switch (ch) {
5541 case 'a':
5542 force_text_diff = 1;
5543 break;
5544 case 'C':
5545 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5546 &errstr);
5547 if (errstr != NULL)
5548 errx(1, "number of context lines is %s: %s",
5549 errstr, errstr);
5550 break;
5551 case 'r':
5552 repo_path = realpath(optarg, NULL);
5553 if (repo_path == NULL)
5554 return got_error_from_errno2("realpath",
5555 optarg);
5556 got_path_strip_trailing_slashes(repo_path);
5557 break;
5558 case 'w':
5559 ignore_whitespace = 1;
5560 break;
5561 default:
5562 usage_diff();
5563 /* NOTREACHED */
5567 argc -= optind;
5568 argv += optind;
5570 if (argc == 0) {
5571 usage_diff(); /* TODO show local worktree changes */
5572 } else if (argc == 2) {
5573 id_str1 = argv[0];
5574 id_str2 = argv[1];
5575 } else
5576 usage_diff();
5578 error = got_repo_pack_fds_open(&pack_fds);
5579 if (error)
5580 goto done;
5582 if (repo_path == NULL) {
5583 cwd = getcwd(NULL, 0);
5584 if (cwd == NULL)
5585 return got_error_from_errno("getcwd");
5586 error = got_worktree_open(&worktree, cwd);
5587 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5588 goto done;
5589 if (worktree)
5590 repo_path =
5591 strdup(got_worktree_get_repo_path(worktree));
5592 else
5593 repo_path = strdup(cwd);
5594 if (repo_path == NULL) {
5595 error = got_error_from_errno("strdup");
5596 goto done;
5600 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5601 if (error)
5602 goto done;
5604 init_curses();
5606 error = apply_unveil(got_repo_get_path(repo), NULL);
5607 if (error)
5608 goto done;
5610 error = tog_load_refs(repo, 0);
5611 if (error)
5612 goto done;
5614 error = got_repo_match_object_id(&id1, &label1, id_str1,
5615 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5616 if (error)
5617 goto done;
5619 error = got_repo_match_object_id(&id2, &label2, id_str2,
5620 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5621 if (error)
5622 goto done;
5624 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5625 if (view == NULL) {
5626 error = got_error_from_errno("view_open");
5627 goto done;
5629 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5630 ignore_whitespace, force_text_diff, NULL, repo);
5631 if (error)
5632 goto done;
5633 error = view_loop(view);
5634 done:
5635 free(label1);
5636 free(label2);
5637 free(repo_path);
5638 free(cwd);
5639 if (repo) {
5640 const struct got_error *close_err = got_repo_close(repo);
5641 if (error == NULL)
5642 error = close_err;
5644 if (worktree)
5645 got_worktree_close(worktree);
5646 if (pack_fds) {
5647 const struct got_error *pack_err =
5648 got_repo_pack_fds_close(pack_fds);
5649 if (error == NULL)
5650 error = pack_err;
5652 tog_free_refs();
5653 return error;
5656 __dead static void
5657 usage_blame(void)
5659 endwin();
5660 fprintf(stderr,
5661 "usage: %s blame [-c commit] [-r repository-path] path\n",
5662 getprogname());
5663 exit(1);
5666 struct tog_blame_line {
5667 int annotated;
5668 struct got_object_id *id;
5671 static const struct got_error *
5672 draw_blame(struct tog_view *view)
5674 struct tog_blame_view_state *s = &view->state.blame;
5675 struct tog_blame *blame = &s->blame;
5676 regmatch_t *regmatch = &view->regmatch;
5677 const struct got_error *err;
5678 int lineno = 0, nprinted = 0;
5679 char *line = NULL;
5680 size_t linesize = 0;
5681 ssize_t linelen;
5682 wchar_t *wline;
5683 int width;
5684 struct tog_blame_line *blame_line;
5685 struct got_object_id *prev_id = NULL;
5686 char *id_str;
5687 struct tog_color *tc;
5689 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5690 if (err)
5691 return err;
5693 rewind(blame->f);
5694 werase(view->window);
5696 if (asprintf(&line, "commit %s", id_str) == -1) {
5697 err = got_error_from_errno("asprintf");
5698 free(id_str);
5699 return err;
5702 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5703 free(line);
5704 line = NULL;
5705 if (err)
5706 return err;
5707 if (view_needs_focus_indication(view))
5708 wstandout(view->window);
5709 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5710 if (tc)
5711 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5712 waddwstr(view->window, wline);
5713 while (width++ < view->ncols)
5714 waddch(view->window, ' ');
5715 if (tc)
5716 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5717 if (view_needs_focus_indication(view))
5718 wstandend(view->window);
5719 free(wline);
5720 wline = NULL;
5722 if (view->gline > blame->nlines)
5723 view->gline = blame->nlines;
5725 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5726 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5727 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5728 free(id_str);
5729 return got_error_from_errno("asprintf");
5731 free(id_str);
5732 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5733 free(line);
5734 line = NULL;
5735 if (err)
5736 return err;
5737 waddwstr(view->window, wline);
5738 free(wline);
5739 wline = NULL;
5740 if (width < view->ncols - 1)
5741 waddch(view->window, '\n');
5743 s->eof = 0;
5744 view->maxx = 0;
5745 while (nprinted < view->nlines - 2) {
5746 linelen = getline(&line, &linesize, blame->f);
5747 if (linelen == -1) {
5748 if (feof(blame->f)) {
5749 s->eof = 1;
5750 break;
5752 free(line);
5753 return got_ferror(blame->f, GOT_ERR_IO);
5755 if (++lineno < s->first_displayed_line)
5756 continue;
5757 if (view->gline && !gotoline(view, &lineno, &nprinted))
5758 continue;
5760 /* Set view->maxx based on full line length. */
5761 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5762 if (err) {
5763 free(line);
5764 return err;
5766 free(wline);
5767 wline = NULL;
5768 view->maxx = MAX(view->maxx, width);
5770 if (nprinted == s->selected_line - 1)
5771 wstandout(view->window);
5773 if (blame->nlines > 0) {
5774 blame_line = &blame->lines[lineno - 1];
5775 if (blame_line->annotated && prev_id &&
5776 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5777 !(nprinted == s->selected_line - 1)) {
5778 waddstr(view->window, " ");
5779 } else if (blame_line->annotated) {
5780 char *id_str;
5781 err = got_object_id_str(&id_str,
5782 blame_line->id);
5783 if (err) {
5784 free(line);
5785 return err;
5787 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5788 if (tc)
5789 wattr_on(view->window,
5790 COLOR_PAIR(tc->colorpair), NULL);
5791 wprintw(view->window, "%.8s", id_str);
5792 if (tc)
5793 wattr_off(view->window,
5794 COLOR_PAIR(tc->colorpair), NULL);
5795 free(id_str);
5796 prev_id = blame_line->id;
5797 } else {
5798 waddstr(view->window, "........");
5799 prev_id = NULL;
5801 } else {
5802 waddstr(view->window, "........");
5803 prev_id = NULL;
5806 if (nprinted == s->selected_line - 1)
5807 wstandend(view->window);
5808 waddstr(view->window, " ");
5810 if (view->ncols <= 9) {
5811 width = 9;
5812 } else if (s->first_displayed_line + nprinted ==
5813 s->matched_line &&
5814 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5815 err = add_matched_line(&width, line, view->ncols - 9, 9,
5816 view->window, view->x, regmatch);
5817 if (err) {
5818 free(line);
5819 return err;
5821 width += 9;
5822 } else {
5823 int skip;
5824 err = format_line(&wline, &width, &skip, line,
5825 view->x, view->ncols - 9, 9, 1);
5826 if (err) {
5827 free(line);
5828 return err;
5830 waddwstr(view->window, &wline[skip]);
5831 width += 9;
5832 free(wline);
5833 wline = NULL;
5836 if (width <= view->ncols - 1)
5837 waddch(view->window, '\n');
5838 if (++nprinted == 1)
5839 s->first_displayed_line = lineno;
5841 free(line);
5842 s->last_displayed_line = lineno;
5844 view_border(view);
5846 return NULL;
5849 static const struct got_error *
5850 blame_cb(void *arg, int nlines, int lineno,
5851 struct got_commit_object *commit, struct got_object_id *id)
5853 const struct got_error *err = NULL;
5854 struct tog_blame_cb_args *a = arg;
5855 struct tog_blame_line *line;
5856 int errcode;
5858 if (nlines != a->nlines ||
5859 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5860 return got_error(GOT_ERR_RANGE);
5862 errcode = pthread_mutex_lock(&tog_mutex);
5863 if (errcode)
5864 return got_error_set_errno(errcode, "pthread_mutex_lock");
5866 if (*a->quit) { /* user has quit the blame view */
5867 err = got_error(GOT_ERR_ITER_COMPLETED);
5868 goto done;
5871 if (lineno == -1)
5872 goto done; /* no change in this commit */
5874 line = &a->lines[lineno - 1];
5875 if (line->annotated)
5876 goto done;
5878 line->id = got_object_id_dup(id);
5879 if (line->id == NULL) {
5880 err = got_error_from_errno("got_object_id_dup");
5881 goto done;
5883 line->annotated = 1;
5884 done:
5885 errcode = pthread_mutex_unlock(&tog_mutex);
5886 if (errcode)
5887 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5888 return err;
5891 static void *
5892 blame_thread(void *arg)
5894 const struct got_error *err, *close_err;
5895 struct tog_blame_thread_args *ta = arg;
5896 struct tog_blame_cb_args *a = ta->cb_args;
5897 int errcode, fd1 = -1, fd2 = -1;
5898 FILE *f1 = NULL, *f2 = NULL;
5900 fd1 = got_opentempfd();
5901 if (fd1 == -1)
5902 return (void *)got_error_from_errno("got_opentempfd");
5904 fd2 = got_opentempfd();
5905 if (fd2 == -1) {
5906 err = got_error_from_errno("got_opentempfd");
5907 goto done;
5910 f1 = got_opentemp();
5911 if (f1 == NULL) {
5912 err = (void *)got_error_from_errno("got_opentemp");
5913 goto done;
5915 f2 = got_opentemp();
5916 if (f2 == NULL) {
5917 err = (void *)got_error_from_errno("got_opentemp");
5918 goto done;
5921 err = block_signals_used_by_main_thread();
5922 if (err)
5923 goto done;
5925 err = got_blame(ta->path, a->commit_id, ta->repo,
5926 tog_diff_algo, blame_cb, ta->cb_args,
5927 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5928 if (err && err->code == GOT_ERR_CANCELLED)
5929 err = NULL;
5931 errcode = pthread_mutex_lock(&tog_mutex);
5932 if (errcode) {
5933 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5934 goto done;
5937 close_err = got_repo_close(ta->repo);
5938 if (err == NULL)
5939 err = close_err;
5940 ta->repo = NULL;
5941 *ta->complete = 1;
5943 errcode = pthread_mutex_unlock(&tog_mutex);
5944 if (errcode && err == NULL)
5945 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5947 done:
5948 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5949 err = got_error_from_errno("close");
5950 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5951 err = got_error_from_errno("close");
5952 if (f1 && fclose(f1) == EOF && err == NULL)
5953 err = got_error_from_errno("fclose");
5954 if (f2 && fclose(f2) == EOF && err == NULL)
5955 err = got_error_from_errno("fclose");
5957 return (void *)err;
5960 static struct got_object_id *
5961 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5962 int first_displayed_line, int selected_line)
5964 struct tog_blame_line *line;
5966 if (nlines <= 0)
5967 return NULL;
5969 line = &lines[first_displayed_line - 1 + selected_line - 1];
5970 if (!line->annotated)
5971 return NULL;
5973 return line->id;
5976 static struct got_object_id *
5977 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5978 int lineno)
5980 struct tog_blame_line *line;
5982 if (nlines <= 0 || lineno >= nlines)
5983 return NULL;
5985 line = &lines[lineno - 1];
5986 if (!line->annotated)
5987 return NULL;
5989 return line->id;
5992 static const struct got_error *
5993 stop_blame(struct tog_blame *blame)
5995 const struct got_error *err = NULL;
5996 int i;
5998 if (blame->thread) {
5999 int errcode;
6000 errcode = pthread_mutex_unlock(&tog_mutex);
6001 if (errcode)
6002 return got_error_set_errno(errcode,
6003 "pthread_mutex_unlock");
6004 errcode = pthread_join(blame->thread, (void **)&err);
6005 if (errcode)
6006 return got_error_set_errno(errcode, "pthread_join");
6007 errcode = pthread_mutex_lock(&tog_mutex);
6008 if (errcode)
6009 return got_error_set_errno(errcode,
6010 "pthread_mutex_lock");
6011 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6012 err = NULL;
6013 blame->thread = 0; //NULL;
6015 if (blame->thread_args.repo) {
6016 const struct got_error *close_err;
6017 close_err = got_repo_close(blame->thread_args.repo);
6018 if (err == NULL)
6019 err = close_err;
6020 blame->thread_args.repo = NULL;
6022 if (blame->f) {
6023 if (fclose(blame->f) == EOF && err == NULL)
6024 err = got_error_from_errno("fclose");
6025 blame->f = NULL;
6027 if (blame->lines) {
6028 for (i = 0; i < blame->nlines; i++)
6029 free(blame->lines[i].id);
6030 free(blame->lines);
6031 blame->lines = NULL;
6033 free(blame->cb_args.commit_id);
6034 blame->cb_args.commit_id = NULL;
6035 if (blame->pack_fds) {
6036 const struct got_error *pack_err =
6037 got_repo_pack_fds_close(blame->pack_fds);
6038 if (err == NULL)
6039 err = pack_err;
6040 blame->pack_fds = NULL;
6042 return err;
6045 static const struct got_error *
6046 cancel_blame_view(void *arg)
6048 const struct got_error *err = NULL;
6049 int *done = arg;
6050 int errcode;
6052 errcode = pthread_mutex_lock(&tog_mutex);
6053 if (errcode)
6054 return got_error_set_errno(errcode,
6055 "pthread_mutex_unlock");
6057 if (*done)
6058 err = got_error(GOT_ERR_CANCELLED);
6060 errcode = pthread_mutex_unlock(&tog_mutex);
6061 if (errcode)
6062 return got_error_set_errno(errcode,
6063 "pthread_mutex_lock");
6065 return err;
6068 static const struct got_error *
6069 run_blame(struct tog_view *view)
6071 struct tog_blame_view_state *s = &view->state.blame;
6072 struct tog_blame *blame = &s->blame;
6073 const struct got_error *err = NULL;
6074 struct got_commit_object *commit = NULL;
6075 struct got_blob_object *blob = NULL;
6076 struct got_repository *thread_repo = NULL;
6077 struct got_object_id *obj_id = NULL;
6078 int obj_type, fd = -1;
6079 int *pack_fds = NULL;
6081 err = got_object_open_as_commit(&commit, s->repo,
6082 &s->blamed_commit->id);
6083 if (err)
6084 return err;
6086 fd = got_opentempfd();
6087 if (fd == -1) {
6088 err = got_error_from_errno("got_opentempfd");
6089 goto done;
6092 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6093 if (err)
6094 goto done;
6096 err = got_object_get_type(&obj_type, s->repo, obj_id);
6097 if (err)
6098 goto done;
6100 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6101 err = got_error(GOT_ERR_OBJ_TYPE);
6102 goto done;
6105 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6106 if (err)
6107 goto done;
6108 blame->f = got_opentemp();
6109 if (blame->f == NULL) {
6110 err = got_error_from_errno("got_opentemp");
6111 goto done;
6113 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6114 &blame->line_offsets, blame->f, blob);
6115 if (err)
6116 goto done;
6117 if (blame->nlines == 0) {
6118 s->blame_complete = 1;
6119 goto done;
6122 /* Don't include \n at EOF in the blame line count. */
6123 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6124 blame->nlines--;
6126 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6127 if (blame->lines == NULL) {
6128 err = got_error_from_errno("calloc");
6129 goto done;
6132 err = got_repo_pack_fds_open(&pack_fds);
6133 if (err)
6134 goto done;
6135 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6136 pack_fds);
6137 if (err)
6138 goto done;
6140 blame->pack_fds = pack_fds;
6141 blame->cb_args.view = view;
6142 blame->cb_args.lines = blame->lines;
6143 blame->cb_args.nlines = blame->nlines;
6144 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6145 if (blame->cb_args.commit_id == NULL) {
6146 err = got_error_from_errno("got_object_id_dup");
6147 goto done;
6149 blame->cb_args.quit = &s->done;
6151 blame->thread_args.path = s->path;
6152 blame->thread_args.repo = thread_repo;
6153 blame->thread_args.cb_args = &blame->cb_args;
6154 blame->thread_args.complete = &s->blame_complete;
6155 blame->thread_args.cancel_cb = cancel_blame_view;
6156 blame->thread_args.cancel_arg = &s->done;
6157 s->blame_complete = 0;
6159 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6160 s->first_displayed_line = 1;
6161 s->last_displayed_line = view->nlines;
6162 s->selected_line = 1;
6164 s->matched_line = 0;
6166 done:
6167 if (commit)
6168 got_object_commit_close(commit);
6169 if (fd != -1 && close(fd) == -1 && err == NULL)
6170 err = got_error_from_errno("close");
6171 if (blob)
6172 got_object_blob_close(blob);
6173 free(obj_id);
6174 if (err)
6175 stop_blame(blame);
6176 return err;
6179 static const struct got_error *
6180 open_blame_view(struct tog_view *view, char *path,
6181 struct got_object_id *commit_id, struct got_repository *repo)
6183 const struct got_error *err = NULL;
6184 struct tog_blame_view_state *s = &view->state.blame;
6186 STAILQ_INIT(&s->blamed_commits);
6188 s->path = strdup(path);
6189 if (s->path == NULL)
6190 return got_error_from_errno("strdup");
6192 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6193 if (err) {
6194 free(s->path);
6195 return err;
6198 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6199 s->first_displayed_line = 1;
6200 s->last_displayed_line = view->nlines;
6201 s->selected_line = 1;
6202 s->blame_complete = 0;
6203 s->repo = repo;
6204 s->commit_id = commit_id;
6205 memset(&s->blame, 0, sizeof(s->blame));
6207 STAILQ_INIT(&s->colors);
6208 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6209 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6210 get_color_value("TOG_COLOR_COMMIT"));
6211 if (err)
6212 return err;
6215 view->show = show_blame_view;
6216 view->input = input_blame_view;
6217 view->reset = reset_blame_view;
6218 view->close = close_blame_view;
6219 view->search_start = search_start_blame_view;
6220 view->search_setup = search_setup_blame_view;
6221 view->search_next = search_next_view_match;
6223 return run_blame(view);
6226 static const struct got_error *
6227 close_blame_view(struct tog_view *view)
6229 const struct got_error *err = NULL;
6230 struct tog_blame_view_state *s = &view->state.blame;
6232 if (s->blame.thread)
6233 err = stop_blame(&s->blame);
6235 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6236 struct got_object_qid *blamed_commit;
6237 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6238 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6239 got_object_qid_free(blamed_commit);
6242 free(s->path);
6243 free_colors(&s->colors);
6244 return err;
6247 static const struct got_error *
6248 search_start_blame_view(struct tog_view *view)
6250 struct tog_blame_view_state *s = &view->state.blame;
6252 s->matched_line = 0;
6253 return NULL;
6256 static void
6257 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6258 size_t *nlines, int **first, int **last, int **match, int **selected)
6260 struct tog_blame_view_state *s = &view->state.blame;
6262 *f = s->blame.f;
6263 *nlines = s->blame.nlines;
6264 *line_offsets = s->blame.line_offsets;
6265 *match = &s->matched_line;
6266 *first = &s->first_displayed_line;
6267 *last = &s->last_displayed_line;
6268 *selected = &s->selected_line;
6271 static const struct got_error *
6272 show_blame_view(struct tog_view *view)
6274 const struct got_error *err = NULL;
6275 struct tog_blame_view_state *s = &view->state.blame;
6276 int errcode;
6278 if (s->blame.thread == 0 && !s->blame_complete) {
6279 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6280 &s->blame.thread_args);
6281 if (errcode)
6282 return got_error_set_errno(errcode, "pthread_create");
6284 halfdelay(1); /* fast refresh while annotating */
6287 if (s->blame_complete)
6288 halfdelay(10); /* disable fast refresh */
6290 err = draw_blame(view);
6292 view_border(view);
6293 return err;
6296 static const struct got_error *
6297 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6298 struct got_repository *repo, struct got_object_id *id)
6300 struct tog_view *log_view;
6301 const struct got_error *err = NULL;
6303 *new_view = NULL;
6305 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6306 if (log_view == NULL)
6307 return got_error_from_errno("view_open");
6309 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6310 if (err)
6311 view_close(log_view);
6312 else
6313 *new_view = log_view;
6315 return err;
6318 static const struct got_error *
6319 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6321 const struct got_error *err = NULL, *thread_err = NULL;
6322 struct tog_view *diff_view;
6323 struct tog_blame_view_state *s = &view->state.blame;
6324 int eos, nscroll, begin_y = 0, begin_x = 0;
6326 eos = nscroll = view->nlines - 2;
6327 if (view_is_hsplit_top(view))
6328 --eos; /* border */
6330 switch (ch) {
6331 case '0':
6332 view->x = 0;
6333 break;
6334 case '$':
6335 view->x = MAX(view->maxx - view->ncols / 3, 0);
6336 view->count = 0;
6337 break;
6338 case KEY_RIGHT:
6339 case 'l':
6340 if (view->x + view->ncols / 3 < view->maxx)
6341 view->x += 2; /* move two columns right */
6342 else
6343 view->count = 0;
6344 break;
6345 case KEY_LEFT:
6346 case 'h':
6347 view->x -= MIN(view->x, 2); /* move two columns back */
6348 if (view->x <= 0)
6349 view->count = 0;
6350 break;
6351 case 'q':
6352 s->done = 1;
6353 break;
6354 case 'g':
6355 case KEY_HOME:
6356 s->selected_line = 1;
6357 s->first_displayed_line = 1;
6358 view->count = 0;
6359 break;
6360 case 'G':
6361 case KEY_END:
6362 if (s->blame.nlines < eos) {
6363 s->selected_line = s->blame.nlines;
6364 s->first_displayed_line = 1;
6365 } else {
6366 s->selected_line = eos;
6367 s->first_displayed_line = s->blame.nlines - (eos - 1);
6369 view->count = 0;
6370 break;
6371 case 'k':
6372 case KEY_UP:
6373 case CTRL('p'):
6374 if (s->selected_line > 1)
6375 s->selected_line--;
6376 else if (s->selected_line == 1 &&
6377 s->first_displayed_line > 1)
6378 s->first_displayed_line--;
6379 else
6380 view->count = 0;
6381 break;
6382 case CTRL('u'):
6383 case 'u':
6384 nscroll /= 2;
6385 /* FALL THROUGH */
6386 case KEY_PPAGE:
6387 case CTRL('b'):
6388 case 'b':
6389 if (s->first_displayed_line == 1) {
6390 if (view->count > 1)
6391 nscroll += nscroll;
6392 s->selected_line = MAX(1, s->selected_line - nscroll);
6393 view->count = 0;
6394 break;
6396 if (s->first_displayed_line > nscroll)
6397 s->first_displayed_line -= nscroll;
6398 else
6399 s->first_displayed_line = 1;
6400 break;
6401 case 'j':
6402 case KEY_DOWN:
6403 case CTRL('n'):
6404 if (s->selected_line < eos && s->first_displayed_line +
6405 s->selected_line <= s->blame.nlines)
6406 s->selected_line++;
6407 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6408 s->first_displayed_line++;
6409 else
6410 view->count = 0;
6411 break;
6412 case 'c':
6413 case 'p': {
6414 struct got_object_id *id = NULL;
6416 view->count = 0;
6417 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6418 s->first_displayed_line, s->selected_line);
6419 if (id == NULL)
6420 break;
6421 if (ch == 'p') {
6422 struct got_commit_object *commit, *pcommit;
6423 struct got_object_qid *pid;
6424 struct got_object_id *blob_id = NULL;
6425 int obj_type;
6426 err = got_object_open_as_commit(&commit,
6427 s->repo, id);
6428 if (err)
6429 break;
6430 pid = STAILQ_FIRST(
6431 got_object_commit_get_parent_ids(commit));
6432 if (pid == NULL) {
6433 got_object_commit_close(commit);
6434 break;
6436 /* Check if path history ends here. */
6437 err = got_object_open_as_commit(&pcommit,
6438 s->repo, &pid->id);
6439 if (err)
6440 break;
6441 err = got_object_id_by_path(&blob_id, s->repo,
6442 pcommit, s->path);
6443 got_object_commit_close(pcommit);
6444 if (err) {
6445 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6446 err = NULL;
6447 got_object_commit_close(commit);
6448 break;
6450 err = got_object_get_type(&obj_type, s->repo,
6451 blob_id);
6452 free(blob_id);
6453 /* Can't blame non-blob type objects. */
6454 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6455 got_object_commit_close(commit);
6456 break;
6458 err = got_object_qid_alloc(&s->blamed_commit,
6459 &pid->id);
6460 got_object_commit_close(commit);
6461 } else {
6462 if (got_object_id_cmp(id,
6463 &s->blamed_commit->id) == 0)
6464 break;
6465 err = got_object_qid_alloc(&s->blamed_commit,
6466 id);
6468 if (err)
6469 break;
6470 s->done = 1;
6471 thread_err = stop_blame(&s->blame);
6472 s->done = 0;
6473 if (thread_err)
6474 break;
6475 STAILQ_INSERT_HEAD(&s->blamed_commits,
6476 s->blamed_commit, entry);
6477 err = run_blame(view);
6478 if (err)
6479 break;
6480 break;
6482 case 'C': {
6483 struct got_object_qid *first;
6485 view->count = 0;
6486 first = STAILQ_FIRST(&s->blamed_commits);
6487 if (!got_object_id_cmp(&first->id, s->commit_id))
6488 break;
6489 s->done = 1;
6490 thread_err = stop_blame(&s->blame);
6491 s->done = 0;
6492 if (thread_err)
6493 break;
6494 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6495 got_object_qid_free(s->blamed_commit);
6496 s->blamed_commit =
6497 STAILQ_FIRST(&s->blamed_commits);
6498 err = run_blame(view);
6499 if (err)
6500 break;
6501 break;
6503 case 'L':
6504 view->count = 0;
6505 s->id_to_log = get_selected_commit_id(s->blame.lines,
6506 s->blame.nlines, s->first_displayed_line, s->selected_line);
6507 if (s->id_to_log)
6508 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6509 break;
6510 case KEY_ENTER:
6511 case '\r': {
6512 struct got_object_id *id = NULL;
6513 struct got_object_qid *pid;
6514 struct got_commit_object *commit = NULL;
6516 view->count = 0;
6517 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6518 s->first_displayed_line, s->selected_line);
6519 if (id == NULL)
6520 break;
6521 err = got_object_open_as_commit(&commit, s->repo, id);
6522 if (err)
6523 break;
6524 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6525 if (*new_view) {
6526 /* traversed from diff view, release diff resources */
6527 err = close_diff_view(*new_view);
6528 if (err)
6529 break;
6530 diff_view = *new_view;
6531 } else {
6532 if (view_is_parent_view(view))
6533 view_get_split(view, &begin_y, &begin_x);
6535 diff_view = view_open(0, 0, begin_y, begin_x,
6536 TOG_VIEW_DIFF);
6537 if (diff_view == NULL) {
6538 got_object_commit_close(commit);
6539 err = got_error_from_errno("view_open");
6540 break;
6543 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6544 id, NULL, NULL, 3, 0, 0, view, s->repo);
6545 got_object_commit_close(commit);
6546 if (err) {
6547 view_close(diff_view);
6548 break;
6550 s->last_diffed_line = s->first_displayed_line - 1 +
6551 s->selected_line;
6552 if (*new_view)
6553 break; /* still open from active diff view */
6554 if (view_is_parent_view(view) &&
6555 view->mode == TOG_VIEW_SPLIT_HRZN) {
6556 err = view_init_hsplit(view, begin_y);
6557 if (err)
6558 break;
6561 view->focussed = 0;
6562 diff_view->focussed = 1;
6563 diff_view->mode = view->mode;
6564 diff_view->nlines = view->lines - begin_y;
6565 if (view_is_parent_view(view)) {
6566 view_transfer_size(diff_view, view);
6567 err = view_close_child(view);
6568 if (err)
6569 break;
6570 err = view_set_child(view, diff_view);
6571 if (err)
6572 break;
6573 view->focus_child = 1;
6574 } else
6575 *new_view = diff_view;
6576 if (err)
6577 break;
6578 break;
6580 case CTRL('d'):
6581 case 'd':
6582 nscroll /= 2;
6583 /* FALL THROUGH */
6584 case KEY_NPAGE:
6585 case CTRL('f'):
6586 case 'f':
6587 case ' ':
6588 if (s->last_displayed_line >= s->blame.nlines &&
6589 s->selected_line >= MIN(s->blame.nlines,
6590 view->nlines - 2)) {
6591 view->count = 0;
6592 break;
6594 if (s->last_displayed_line >= s->blame.nlines &&
6595 s->selected_line < view->nlines - 2) {
6596 s->selected_line +=
6597 MIN(nscroll, s->last_displayed_line -
6598 s->first_displayed_line - s->selected_line + 1);
6600 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6601 s->first_displayed_line += nscroll;
6602 else
6603 s->first_displayed_line =
6604 s->blame.nlines - (view->nlines - 3);
6605 break;
6606 case KEY_RESIZE:
6607 if (s->selected_line > view->nlines - 2) {
6608 s->selected_line = MIN(s->blame.nlines,
6609 view->nlines - 2);
6611 break;
6612 default:
6613 view->count = 0;
6614 break;
6616 return thread_err ? thread_err : err;
6619 static const struct got_error *
6620 reset_blame_view(struct tog_view *view)
6622 const struct got_error *err;
6623 struct tog_blame_view_state *s = &view->state.blame;
6625 view->count = 0;
6626 s->done = 1;
6627 err = stop_blame(&s->blame);
6628 s->done = 0;
6629 if (err)
6630 return err;
6631 return run_blame(view);
6634 static const struct got_error *
6635 cmd_blame(int argc, char *argv[])
6637 const struct got_error *error;
6638 struct got_repository *repo = NULL;
6639 struct got_worktree *worktree = NULL;
6640 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6641 char *link_target = NULL;
6642 struct got_object_id *commit_id = NULL;
6643 struct got_commit_object *commit = NULL;
6644 char *commit_id_str = NULL;
6645 int ch;
6646 struct tog_view *view;
6647 int *pack_fds = NULL;
6649 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6650 switch (ch) {
6651 case 'c':
6652 commit_id_str = optarg;
6653 break;
6654 case 'r':
6655 repo_path = realpath(optarg, NULL);
6656 if (repo_path == NULL)
6657 return got_error_from_errno2("realpath",
6658 optarg);
6659 break;
6660 default:
6661 usage_blame();
6662 /* NOTREACHED */
6666 argc -= optind;
6667 argv += optind;
6669 if (argc != 1)
6670 usage_blame();
6672 error = got_repo_pack_fds_open(&pack_fds);
6673 if (error != NULL)
6674 goto done;
6676 if (repo_path == NULL) {
6677 cwd = getcwd(NULL, 0);
6678 if (cwd == NULL)
6679 return got_error_from_errno("getcwd");
6680 error = got_worktree_open(&worktree, cwd);
6681 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6682 goto done;
6683 if (worktree)
6684 repo_path =
6685 strdup(got_worktree_get_repo_path(worktree));
6686 else
6687 repo_path = strdup(cwd);
6688 if (repo_path == NULL) {
6689 error = got_error_from_errno("strdup");
6690 goto done;
6694 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6695 if (error != NULL)
6696 goto done;
6698 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6699 worktree);
6700 if (error)
6701 goto done;
6703 init_curses();
6705 error = apply_unveil(got_repo_get_path(repo), NULL);
6706 if (error)
6707 goto done;
6709 error = tog_load_refs(repo, 0);
6710 if (error)
6711 goto done;
6713 if (commit_id_str == NULL) {
6714 struct got_reference *head_ref;
6715 error = got_ref_open(&head_ref, repo, worktree ?
6716 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6717 if (error != NULL)
6718 goto done;
6719 error = got_ref_resolve(&commit_id, repo, head_ref);
6720 got_ref_close(head_ref);
6721 } else {
6722 error = got_repo_match_object_id(&commit_id, NULL,
6723 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6725 if (error != NULL)
6726 goto done;
6728 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6729 if (view == NULL) {
6730 error = got_error_from_errno("view_open");
6731 goto done;
6734 error = got_object_open_as_commit(&commit, repo, commit_id);
6735 if (error)
6736 goto done;
6738 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6739 commit, repo);
6740 if (error)
6741 goto done;
6743 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6744 commit_id, repo);
6745 if (error)
6746 goto done;
6747 if (worktree) {
6748 /* Release work tree lock. */
6749 got_worktree_close(worktree);
6750 worktree = NULL;
6752 error = view_loop(view);
6753 done:
6754 free(repo_path);
6755 free(in_repo_path);
6756 free(link_target);
6757 free(cwd);
6758 free(commit_id);
6759 if (commit)
6760 got_object_commit_close(commit);
6761 if (worktree)
6762 got_worktree_close(worktree);
6763 if (repo) {
6764 const struct got_error *close_err = got_repo_close(repo);
6765 if (error == NULL)
6766 error = close_err;
6768 if (pack_fds) {
6769 const struct got_error *pack_err =
6770 got_repo_pack_fds_close(pack_fds);
6771 if (error == NULL)
6772 error = pack_err;
6774 tog_free_refs();
6775 return error;
6778 static const struct got_error *
6779 draw_tree_entries(struct tog_view *view, const char *parent_path)
6781 struct tog_tree_view_state *s = &view->state.tree;
6782 const struct got_error *err = NULL;
6783 struct got_tree_entry *te;
6784 wchar_t *wline;
6785 char *index = NULL;
6786 struct tog_color *tc;
6787 int width, n, nentries, i = 1;
6788 int limit = view->nlines;
6790 s->ndisplayed = 0;
6791 if (view_is_hsplit_top(view))
6792 --limit; /* border */
6794 werase(view->window);
6796 if (limit == 0)
6797 return NULL;
6799 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6800 0, 0);
6801 if (err)
6802 return err;
6803 if (view_needs_focus_indication(view))
6804 wstandout(view->window);
6805 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6806 if (tc)
6807 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6808 waddwstr(view->window, wline);
6809 free(wline);
6810 wline = NULL;
6811 while (width++ < view->ncols)
6812 waddch(view->window, ' ');
6813 if (tc)
6814 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6815 if (view_needs_focus_indication(view))
6816 wstandend(view->window);
6817 if (--limit <= 0)
6818 return NULL;
6820 i += s->selected;
6821 if (s->first_displayed_entry) {
6822 i += got_tree_entry_get_index(s->first_displayed_entry);
6823 if (s->tree != s->root)
6824 ++i; /* account for ".." entry */
6826 nentries = got_object_tree_get_nentries(s->tree);
6827 if (asprintf(&index, "[%d/%d] %s",
6828 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
6829 return got_error_from_errno("asprintf");
6830 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
6831 free(index);
6832 if (err)
6833 return err;
6834 waddwstr(view->window, wline);
6835 free(wline);
6836 wline = NULL;
6837 if (width < view->ncols - 1)
6838 waddch(view->window, '\n');
6839 if (--limit <= 0)
6840 return NULL;
6841 waddch(view->window, '\n');
6842 if (--limit <= 0)
6843 return NULL;
6845 if (s->first_displayed_entry == NULL) {
6846 te = got_object_tree_get_first_entry(s->tree);
6847 if (s->selected == 0) {
6848 if (view->focussed)
6849 wstandout(view->window);
6850 s->selected_entry = NULL;
6852 waddstr(view->window, " ..\n"); /* parent directory */
6853 if (s->selected == 0 && view->focussed)
6854 wstandend(view->window);
6855 s->ndisplayed++;
6856 if (--limit <= 0)
6857 return NULL;
6858 n = 1;
6859 } else {
6860 n = 0;
6861 te = s->first_displayed_entry;
6864 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6865 char *line = NULL, *id_str = NULL, *link_target = NULL;
6866 const char *modestr = "";
6867 mode_t mode;
6869 te = got_object_tree_get_entry(s->tree, i);
6870 mode = got_tree_entry_get_mode(te);
6872 if (s->show_ids) {
6873 err = got_object_id_str(&id_str,
6874 got_tree_entry_get_id(te));
6875 if (err)
6876 return got_error_from_errno(
6877 "got_object_id_str");
6879 if (got_object_tree_entry_is_submodule(te))
6880 modestr = "$";
6881 else if (S_ISLNK(mode)) {
6882 int i;
6884 err = got_tree_entry_get_symlink_target(&link_target,
6885 te, s->repo);
6886 if (err) {
6887 free(id_str);
6888 return err;
6890 for (i = 0; i < strlen(link_target); i++) {
6891 if (!isprint((unsigned char)link_target[i]))
6892 link_target[i] = '?';
6894 modestr = "@";
6896 else if (S_ISDIR(mode))
6897 modestr = "/";
6898 else if (mode & S_IXUSR)
6899 modestr = "*";
6900 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6901 got_tree_entry_get_name(te), modestr,
6902 link_target ? " -> ": "",
6903 link_target ? link_target : "") == -1) {
6904 free(id_str);
6905 free(link_target);
6906 return got_error_from_errno("asprintf");
6908 free(id_str);
6909 free(link_target);
6910 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6911 0, 0);
6912 if (err) {
6913 free(line);
6914 break;
6916 if (n == s->selected) {
6917 if (view->focussed)
6918 wstandout(view->window);
6919 s->selected_entry = te;
6921 tc = match_color(&s->colors, line);
6922 if (tc)
6923 wattr_on(view->window,
6924 COLOR_PAIR(tc->colorpair), NULL);
6925 waddwstr(view->window, wline);
6926 if (tc)
6927 wattr_off(view->window,
6928 COLOR_PAIR(tc->colorpair), NULL);
6929 if (width < view->ncols - 1)
6930 waddch(view->window, '\n');
6931 if (n == s->selected && view->focussed)
6932 wstandend(view->window);
6933 free(line);
6934 free(wline);
6935 wline = NULL;
6936 n++;
6937 s->ndisplayed++;
6938 s->last_displayed_entry = te;
6939 if (--limit <= 0)
6940 break;
6943 return err;
6946 static void
6947 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6949 struct got_tree_entry *te;
6950 int isroot = s->tree == s->root;
6951 int i = 0;
6953 if (s->first_displayed_entry == NULL)
6954 return;
6956 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6957 while (i++ < maxscroll) {
6958 if (te == NULL) {
6959 if (!isroot)
6960 s->first_displayed_entry = NULL;
6961 break;
6963 s->first_displayed_entry = te;
6964 te = got_tree_entry_get_prev(s->tree, te);
6968 static const struct got_error *
6969 tree_scroll_down(struct tog_view *view, int maxscroll)
6971 struct tog_tree_view_state *s = &view->state.tree;
6972 struct got_tree_entry *next, *last;
6973 int n = 0;
6975 if (s->first_displayed_entry)
6976 next = got_tree_entry_get_next(s->tree,
6977 s->first_displayed_entry);
6978 else
6979 next = got_object_tree_get_first_entry(s->tree);
6981 last = s->last_displayed_entry;
6982 while (next && n++ < maxscroll) {
6983 if (last) {
6984 s->last_displayed_entry = last;
6985 last = got_tree_entry_get_next(s->tree, last);
6987 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6988 s->first_displayed_entry = next;
6989 next = got_tree_entry_get_next(s->tree, next);
6993 return NULL;
6996 static const struct got_error *
6997 tree_entry_path(char **path, struct tog_parent_trees *parents,
6998 struct got_tree_entry *te)
7000 const struct got_error *err = NULL;
7001 struct tog_parent_tree *pt;
7002 size_t len = 2; /* for leading slash and NUL */
7004 TAILQ_FOREACH(pt, parents, entry)
7005 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7006 + 1 /* slash */;
7007 if (te)
7008 len += strlen(got_tree_entry_get_name(te));
7010 *path = calloc(1, len);
7011 if (path == NULL)
7012 return got_error_from_errno("calloc");
7014 (*path)[0] = '/';
7015 pt = TAILQ_LAST(parents, tog_parent_trees);
7016 while (pt) {
7017 const char *name = got_tree_entry_get_name(pt->selected_entry);
7018 if (strlcat(*path, name, len) >= len) {
7019 err = got_error(GOT_ERR_NO_SPACE);
7020 goto done;
7022 if (strlcat(*path, "/", len) >= len) {
7023 err = got_error(GOT_ERR_NO_SPACE);
7024 goto done;
7026 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7028 if (te) {
7029 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7030 err = got_error(GOT_ERR_NO_SPACE);
7031 goto done;
7034 done:
7035 if (err) {
7036 free(*path);
7037 *path = NULL;
7039 return err;
7042 static const struct got_error *
7043 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7044 struct got_tree_entry *te, struct tog_parent_trees *parents,
7045 struct got_object_id *commit_id, struct got_repository *repo)
7047 const struct got_error *err = NULL;
7048 char *path;
7049 struct tog_view *blame_view;
7051 *new_view = NULL;
7053 err = tree_entry_path(&path, parents, te);
7054 if (err)
7055 return err;
7057 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7058 if (blame_view == NULL) {
7059 err = got_error_from_errno("view_open");
7060 goto done;
7063 err = open_blame_view(blame_view, path, commit_id, repo);
7064 if (err) {
7065 if (err->code == GOT_ERR_CANCELLED)
7066 err = NULL;
7067 view_close(blame_view);
7068 } else
7069 *new_view = blame_view;
7070 done:
7071 free(path);
7072 return err;
7075 static const struct got_error *
7076 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7077 struct tog_tree_view_state *s)
7079 struct tog_view *log_view;
7080 const struct got_error *err = NULL;
7081 char *path;
7083 *new_view = NULL;
7085 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7086 if (log_view == NULL)
7087 return got_error_from_errno("view_open");
7089 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7090 if (err)
7091 return err;
7093 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7094 path, 0);
7095 if (err)
7096 view_close(log_view);
7097 else
7098 *new_view = log_view;
7099 free(path);
7100 return err;
7103 static const struct got_error *
7104 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7105 const char *head_ref_name, struct got_repository *repo)
7107 const struct got_error *err = NULL;
7108 char *commit_id_str = NULL;
7109 struct tog_tree_view_state *s = &view->state.tree;
7110 struct got_commit_object *commit = NULL;
7112 TAILQ_INIT(&s->parents);
7113 STAILQ_INIT(&s->colors);
7115 s->commit_id = got_object_id_dup(commit_id);
7116 if (s->commit_id == NULL)
7117 return got_error_from_errno("got_object_id_dup");
7119 err = got_object_open_as_commit(&commit, repo, commit_id);
7120 if (err)
7121 goto done;
7124 * The root is opened here and will be closed when the view is closed.
7125 * Any visited subtrees and their path-wise parents are opened and
7126 * closed on demand.
7128 err = got_object_open_as_tree(&s->root, repo,
7129 got_object_commit_get_tree_id(commit));
7130 if (err)
7131 goto done;
7132 s->tree = s->root;
7134 err = got_object_id_str(&commit_id_str, commit_id);
7135 if (err != NULL)
7136 goto done;
7138 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7139 err = got_error_from_errno("asprintf");
7140 goto done;
7143 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7144 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7145 if (head_ref_name) {
7146 s->head_ref_name = strdup(head_ref_name);
7147 if (s->head_ref_name == NULL) {
7148 err = got_error_from_errno("strdup");
7149 goto done;
7152 s->repo = repo;
7154 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7155 err = add_color(&s->colors, "\\$$",
7156 TOG_COLOR_TREE_SUBMODULE,
7157 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7158 if (err)
7159 goto done;
7160 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7161 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7162 if (err)
7163 goto done;
7164 err = add_color(&s->colors, "/$",
7165 TOG_COLOR_TREE_DIRECTORY,
7166 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7167 if (err)
7168 goto done;
7170 err = add_color(&s->colors, "\\*$",
7171 TOG_COLOR_TREE_EXECUTABLE,
7172 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7173 if (err)
7174 goto done;
7176 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7177 get_color_value("TOG_COLOR_COMMIT"));
7178 if (err)
7179 goto done;
7182 view->show = show_tree_view;
7183 view->input = input_tree_view;
7184 view->close = close_tree_view;
7185 view->search_start = search_start_tree_view;
7186 view->search_next = search_next_tree_view;
7187 done:
7188 free(commit_id_str);
7189 if (commit)
7190 got_object_commit_close(commit);
7191 if (err)
7192 close_tree_view(view);
7193 return err;
7196 static const struct got_error *
7197 close_tree_view(struct tog_view *view)
7199 struct tog_tree_view_state *s = &view->state.tree;
7201 free_colors(&s->colors);
7202 free(s->tree_label);
7203 s->tree_label = NULL;
7204 free(s->commit_id);
7205 s->commit_id = NULL;
7206 free(s->head_ref_name);
7207 s->head_ref_name = NULL;
7208 while (!TAILQ_EMPTY(&s->parents)) {
7209 struct tog_parent_tree *parent;
7210 parent = TAILQ_FIRST(&s->parents);
7211 TAILQ_REMOVE(&s->parents, parent, entry);
7212 if (parent->tree != s->root)
7213 got_object_tree_close(parent->tree);
7214 free(parent);
7217 if (s->tree != NULL && s->tree != s->root)
7218 got_object_tree_close(s->tree);
7219 if (s->root)
7220 got_object_tree_close(s->root);
7221 return NULL;
7224 static const struct got_error *
7225 search_start_tree_view(struct tog_view *view)
7227 struct tog_tree_view_state *s = &view->state.tree;
7229 s->matched_entry = NULL;
7230 return NULL;
7233 static int
7234 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7236 regmatch_t regmatch;
7238 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7239 0) == 0;
7242 static const struct got_error *
7243 search_next_tree_view(struct tog_view *view)
7245 struct tog_tree_view_state *s = &view->state.tree;
7246 struct got_tree_entry *te = NULL;
7248 if (!view->searching) {
7249 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7250 return NULL;
7253 if (s->matched_entry) {
7254 if (view->searching == TOG_SEARCH_FORWARD) {
7255 if (s->selected_entry)
7256 te = got_tree_entry_get_next(s->tree,
7257 s->selected_entry);
7258 else
7259 te = got_object_tree_get_first_entry(s->tree);
7260 } else {
7261 if (s->selected_entry == NULL)
7262 te = got_object_tree_get_last_entry(s->tree);
7263 else
7264 te = got_tree_entry_get_prev(s->tree,
7265 s->selected_entry);
7267 } else {
7268 if (s->selected_entry)
7269 te = s->selected_entry;
7270 else if (view->searching == TOG_SEARCH_FORWARD)
7271 te = got_object_tree_get_first_entry(s->tree);
7272 else
7273 te = got_object_tree_get_last_entry(s->tree);
7276 while (1) {
7277 if (te == NULL) {
7278 if (s->matched_entry == NULL) {
7279 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7280 return NULL;
7282 if (view->searching == TOG_SEARCH_FORWARD)
7283 te = got_object_tree_get_first_entry(s->tree);
7284 else
7285 te = got_object_tree_get_last_entry(s->tree);
7288 if (match_tree_entry(te, &view->regex)) {
7289 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7290 s->matched_entry = te;
7291 break;
7294 if (view->searching == TOG_SEARCH_FORWARD)
7295 te = got_tree_entry_get_next(s->tree, te);
7296 else
7297 te = got_tree_entry_get_prev(s->tree, te);
7300 if (s->matched_entry) {
7301 s->first_displayed_entry = s->matched_entry;
7302 s->selected = 0;
7305 return NULL;
7308 static const struct got_error *
7309 show_tree_view(struct tog_view *view)
7311 const struct got_error *err = NULL;
7312 struct tog_tree_view_state *s = &view->state.tree;
7313 char *parent_path;
7315 err = tree_entry_path(&parent_path, &s->parents, NULL);
7316 if (err)
7317 return err;
7319 err = draw_tree_entries(view, parent_path);
7320 free(parent_path);
7322 view_border(view);
7323 return err;
7326 static const struct got_error *
7327 tree_goto_line(struct tog_view *view, int nlines)
7329 const struct got_error *err = NULL;
7330 struct tog_tree_view_state *s = &view->state.tree;
7331 struct got_tree_entry **fte, **lte, **ste;
7332 int g, last, first = 1, i = 1;
7333 int root = s->tree == s->root;
7334 int off = root ? 1 : 2;
7336 g = view->gline;
7337 view->gline = 0;
7339 if (g == 0)
7340 g = 1;
7341 else if (g > got_object_tree_get_nentries(s->tree))
7342 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7344 fte = &s->first_displayed_entry;
7345 lte = &s->last_displayed_entry;
7346 ste = &s->selected_entry;
7348 if (*fte != NULL) {
7349 first = got_tree_entry_get_index(*fte);
7350 first += off; /* account for ".." */
7352 last = got_tree_entry_get_index(*lte);
7353 last += off;
7355 if (g >= first && g <= last && g - first < nlines) {
7356 s->selected = g - first;
7357 return NULL; /* gline is on the current page */
7360 if (*ste != NULL) {
7361 i = got_tree_entry_get_index(*ste);
7362 i += off;
7365 if (i < g) {
7366 err = tree_scroll_down(view, g - i);
7367 if (err)
7368 return err;
7369 if (got_tree_entry_get_index(*lte) >=
7370 got_object_tree_get_nentries(s->tree) - 1 &&
7371 first + s->selected < g &&
7372 s->selected < s->ndisplayed - 1) {
7373 first = got_tree_entry_get_index(*fte);
7374 first += off;
7375 s->selected = g - first;
7377 } else if (i > g)
7378 tree_scroll_up(s, i - g);
7380 if (g < nlines &&
7381 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7382 s->selected = g - 1;
7384 return NULL;
7387 static const struct got_error *
7388 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7390 const struct got_error *err = NULL;
7391 struct tog_tree_view_state *s = &view->state.tree;
7392 struct got_tree_entry *te;
7393 int n, nscroll = view->nlines - 3;
7395 if (view->gline)
7396 return tree_goto_line(view, nscroll);
7398 switch (ch) {
7399 case 'i':
7400 s->show_ids = !s->show_ids;
7401 view->count = 0;
7402 break;
7403 case 'L':
7404 view->count = 0;
7405 if (!s->selected_entry)
7406 break;
7407 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7408 break;
7409 case 'R':
7410 view->count = 0;
7411 err = view_request_new(new_view, view, TOG_VIEW_REF);
7412 break;
7413 case 'g':
7414 case '=':
7415 case KEY_HOME:
7416 s->selected = 0;
7417 view->count = 0;
7418 if (s->tree == s->root)
7419 s->first_displayed_entry =
7420 got_object_tree_get_first_entry(s->tree);
7421 else
7422 s->first_displayed_entry = NULL;
7423 break;
7424 case 'G':
7425 case '*':
7426 case KEY_END: {
7427 int eos = view->nlines - 3;
7429 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7430 --eos; /* border */
7431 s->selected = 0;
7432 view->count = 0;
7433 te = got_object_tree_get_last_entry(s->tree);
7434 for (n = 0; n < eos; n++) {
7435 if (te == NULL) {
7436 if (s->tree != s->root) {
7437 s->first_displayed_entry = NULL;
7438 n++;
7440 break;
7442 s->first_displayed_entry = te;
7443 te = got_tree_entry_get_prev(s->tree, te);
7445 if (n > 0)
7446 s->selected = n - 1;
7447 break;
7449 case 'k':
7450 case KEY_UP:
7451 case CTRL('p'):
7452 if (s->selected > 0) {
7453 s->selected--;
7454 break;
7456 tree_scroll_up(s, 1);
7457 if (s->selected_entry == NULL ||
7458 (s->tree == s->root && s->selected_entry ==
7459 got_object_tree_get_first_entry(s->tree)))
7460 view->count = 0;
7461 break;
7462 case CTRL('u'):
7463 case 'u':
7464 nscroll /= 2;
7465 /* FALL THROUGH */
7466 case KEY_PPAGE:
7467 case CTRL('b'):
7468 case 'b':
7469 if (s->tree == s->root) {
7470 if (got_object_tree_get_first_entry(s->tree) ==
7471 s->first_displayed_entry)
7472 s->selected -= MIN(s->selected, nscroll);
7473 } else {
7474 if (s->first_displayed_entry == NULL)
7475 s->selected -= MIN(s->selected, nscroll);
7477 tree_scroll_up(s, MAX(0, nscroll));
7478 if (s->selected_entry == NULL ||
7479 (s->tree == s->root && s->selected_entry ==
7480 got_object_tree_get_first_entry(s->tree)))
7481 view->count = 0;
7482 break;
7483 case 'j':
7484 case KEY_DOWN:
7485 case CTRL('n'):
7486 if (s->selected < s->ndisplayed - 1) {
7487 s->selected++;
7488 break;
7490 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7491 == NULL) {
7492 /* can't scroll any further */
7493 view->count = 0;
7494 break;
7496 tree_scroll_down(view, 1);
7497 break;
7498 case CTRL('d'):
7499 case 'd':
7500 nscroll /= 2;
7501 /* FALL THROUGH */
7502 case KEY_NPAGE:
7503 case CTRL('f'):
7504 case 'f':
7505 case ' ':
7506 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7507 == NULL) {
7508 /* can't scroll any further; move cursor down */
7509 if (s->selected < s->ndisplayed - 1)
7510 s->selected += MIN(nscroll,
7511 s->ndisplayed - s->selected - 1);
7512 else
7513 view->count = 0;
7514 break;
7516 tree_scroll_down(view, nscroll);
7517 break;
7518 case KEY_ENTER:
7519 case '\r':
7520 case KEY_BACKSPACE:
7521 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7522 struct tog_parent_tree *parent;
7523 /* user selected '..' */
7524 if (s->tree == s->root) {
7525 view->count = 0;
7526 break;
7528 parent = TAILQ_FIRST(&s->parents);
7529 TAILQ_REMOVE(&s->parents, parent,
7530 entry);
7531 got_object_tree_close(s->tree);
7532 s->tree = parent->tree;
7533 s->first_displayed_entry =
7534 parent->first_displayed_entry;
7535 s->selected_entry =
7536 parent->selected_entry;
7537 s->selected = parent->selected;
7538 if (s->selected > view->nlines - 3) {
7539 err = offset_selection_down(view);
7540 if (err)
7541 break;
7543 free(parent);
7544 } else if (S_ISDIR(got_tree_entry_get_mode(
7545 s->selected_entry))) {
7546 struct got_tree_object *subtree;
7547 view->count = 0;
7548 err = got_object_open_as_tree(&subtree, s->repo,
7549 got_tree_entry_get_id(s->selected_entry));
7550 if (err)
7551 break;
7552 err = tree_view_visit_subtree(s, subtree);
7553 if (err) {
7554 got_object_tree_close(subtree);
7555 break;
7557 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7558 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7559 break;
7560 case KEY_RESIZE:
7561 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7562 s->selected = view->nlines - 4;
7563 view->count = 0;
7564 break;
7565 default:
7566 view->count = 0;
7567 break;
7570 return err;
7573 __dead static void
7574 usage_tree(void)
7576 endwin();
7577 fprintf(stderr,
7578 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7579 getprogname());
7580 exit(1);
7583 static const struct got_error *
7584 cmd_tree(int argc, char *argv[])
7586 const struct got_error *error;
7587 struct got_repository *repo = NULL;
7588 struct got_worktree *worktree = NULL;
7589 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7590 struct got_object_id *commit_id = NULL;
7591 struct got_commit_object *commit = NULL;
7592 const char *commit_id_arg = NULL;
7593 char *label = NULL;
7594 struct got_reference *ref = NULL;
7595 const char *head_ref_name = NULL;
7596 int ch;
7597 struct tog_view *view;
7598 int *pack_fds = NULL;
7600 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7601 switch (ch) {
7602 case 'c':
7603 commit_id_arg = optarg;
7604 break;
7605 case 'r':
7606 repo_path = realpath(optarg, NULL);
7607 if (repo_path == NULL)
7608 return got_error_from_errno2("realpath",
7609 optarg);
7610 break;
7611 default:
7612 usage_tree();
7613 /* NOTREACHED */
7617 argc -= optind;
7618 argv += optind;
7620 if (argc > 1)
7621 usage_tree();
7623 error = got_repo_pack_fds_open(&pack_fds);
7624 if (error != NULL)
7625 goto done;
7627 if (repo_path == NULL) {
7628 cwd = getcwd(NULL, 0);
7629 if (cwd == NULL)
7630 return got_error_from_errno("getcwd");
7631 error = got_worktree_open(&worktree, cwd);
7632 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7633 goto done;
7634 if (worktree)
7635 repo_path =
7636 strdup(got_worktree_get_repo_path(worktree));
7637 else
7638 repo_path = strdup(cwd);
7639 if (repo_path == NULL) {
7640 error = got_error_from_errno("strdup");
7641 goto done;
7645 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7646 if (error != NULL)
7647 goto done;
7649 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7650 repo, worktree);
7651 if (error)
7652 goto done;
7654 init_curses();
7656 error = apply_unveil(got_repo_get_path(repo), NULL);
7657 if (error)
7658 goto done;
7660 error = tog_load_refs(repo, 0);
7661 if (error)
7662 goto done;
7664 if (commit_id_arg == NULL) {
7665 error = got_repo_match_object_id(&commit_id, &label,
7666 worktree ? got_worktree_get_head_ref_name(worktree) :
7667 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7668 if (error)
7669 goto done;
7670 head_ref_name = label;
7671 } else {
7672 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7673 if (error == NULL)
7674 head_ref_name = got_ref_get_name(ref);
7675 else if (error->code != GOT_ERR_NOT_REF)
7676 goto done;
7677 error = got_repo_match_object_id(&commit_id, NULL,
7678 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7679 if (error)
7680 goto done;
7683 error = got_object_open_as_commit(&commit, repo, commit_id);
7684 if (error)
7685 goto done;
7687 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7688 if (view == NULL) {
7689 error = got_error_from_errno("view_open");
7690 goto done;
7692 error = open_tree_view(view, commit_id, head_ref_name, repo);
7693 if (error)
7694 goto done;
7695 if (!got_path_is_root_dir(in_repo_path)) {
7696 error = tree_view_walk_path(&view->state.tree, commit,
7697 in_repo_path);
7698 if (error)
7699 goto done;
7702 if (worktree) {
7703 /* Release work tree lock. */
7704 got_worktree_close(worktree);
7705 worktree = NULL;
7707 error = view_loop(view);
7708 done:
7709 free(repo_path);
7710 free(cwd);
7711 free(commit_id);
7712 free(label);
7713 if (ref)
7714 got_ref_close(ref);
7715 if (repo) {
7716 const struct got_error *close_err = got_repo_close(repo);
7717 if (error == NULL)
7718 error = close_err;
7720 if (pack_fds) {
7721 const struct got_error *pack_err =
7722 got_repo_pack_fds_close(pack_fds);
7723 if (error == NULL)
7724 error = pack_err;
7726 tog_free_refs();
7727 return error;
7730 static const struct got_error *
7731 ref_view_load_refs(struct tog_ref_view_state *s)
7733 struct got_reflist_entry *sre;
7734 struct tog_reflist_entry *re;
7736 s->nrefs = 0;
7737 TAILQ_FOREACH(sre, &tog_refs, entry) {
7738 if (strncmp(got_ref_get_name(sre->ref),
7739 "refs/got/", 9) == 0 &&
7740 strncmp(got_ref_get_name(sre->ref),
7741 "refs/got/backup/", 16) != 0)
7742 continue;
7744 re = malloc(sizeof(*re));
7745 if (re == NULL)
7746 return got_error_from_errno("malloc");
7748 re->ref = got_ref_dup(sre->ref);
7749 if (re->ref == NULL)
7750 return got_error_from_errno("got_ref_dup");
7751 re->idx = s->nrefs++;
7752 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7755 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7756 return NULL;
7759 static void
7760 ref_view_free_refs(struct tog_ref_view_state *s)
7762 struct tog_reflist_entry *re;
7764 while (!TAILQ_EMPTY(&s->refs)) {
7765 re = TAILQ_FIRST(&s->refs);
7766 TAILQ_REMOVE(&s->refs, re, entry);
7767 got_ref_close(re->ref);
7768 free(re);
7772 static const struct got_error *
7773 open_ref_view(struct tog_view *view, struct got_repository *repo)
7775 const struct got_error *err = NULL;
7776 struct tog_ref_view_state *s = &view->state.ref;
7778 s->selected_entry = 0;
7779 s->repo = repo;
7781 TAILQ_INIT(&s->refs);
7782 STAILQ_INIT(&s->colors);
7784 err = ref_view_load_refs(s);
7785 if (err)
7786 return err;
7788 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7789 err = add_color(&s->colors, "^refs/heads/",
7790 TOG_COLOR_REFS_HEADS,
7791 get_color_value("TOG_COLOR_REFS_HEADS"));
7792 if (err)
7793 goto done;
7795 err = add_color(&s->colors, "^refs/tags/",
7796 TOG_COLOR_REFS_TAGS,
7797 get_color_value("TOG_COLOR_REFS_TAGS"));
7798 if (err)
7799 goto done;
7801 err = add_color(&s->colors, "^refs/remotes/",
7802 TOG_COLOR_REFS_REMOTES,
7803 get_color_value("TOG_COLOR_REFS_REMOTES"));
7804 if (err)
7805 goto done;
7807 err = add_color(&s->colors, "^refs/got/backup/",
7808 TOG_COLOR_REFS_BACKUP,
7809 get_color_value("TOG_COLOR_REFS_BACKUP"));
7810 if (err)
7811 goto done;
7814 view->show = show_ref_view;
7815 view->input = input_ref_view;
7816 view->close = close_ref_view;
7817 view->search_start = search_start_ref_view;
7818 view->search_next = search_next_ref_view;
7819 done:
7820 if (err)
7821 free_colors(&s->colors);
7822 return err;
7825 static const struct got_error *
7826 close_ref_view(struct tog_view *view)
7828 struct tog_ref_view_state *s = &view->state.ref;
7830 ref_view_free_refs(s);
7831 free_colors(&s->colors);
7833 return NULL;
7836 static const struct got_error *
7837 resolve_reflist_entry(struct got_object_id **commit_id,
7838 struct tog_reflist_entry *re, struct got_repository *repo)
7840 const struct got_error *err = NULL;
7841 struct got_object_id *obj_id;
7842 struct got_tag_object *tag = NULL;
7843 int obj_type;
7845 *commit_id = NULL;
7847 err = got_ref_resolve(&obj_id, repo, re->ref);
7848 if (err)
7849 return err;
7851 err = got_object_get_type(&obj_type, repo, obj_id);
7852 if (err)
7853 goto done;
7855 switch (obj_type) {
7856 case GOT_OBJ_TYPE_COMMIT:
7857 *commit_id = obj_id;
7858 break;
7859 case GOT_OBJ_TYPE_TAG:
7860 err = got_object_open_as_tag(&tag, repo, obj_id);
7861 if (err)
7862 goto done;
7863 free(obj_id);
7864 err = got_object_get_type(&obj_type, repo,
7865 got_object_tag_get_object_id(tag));
7866 if (err)
7867 goto done;
7868 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7869 err = got_error(GOT_ERR_OBJ_TYPE);
7870 goto done;
7872 *commit_id = got_object_id_dup(
7873 got_object_tag_get_object_id(tag));
7874 if (*commit_id == NULL) {
7875 err = got_error_from_errno("got_object_id_dup");
7876 goto done;
7878 break;
7879 default:
7880 err = got_error(GOT_ERR_OBJ_TYPE);
7881 break;
7884 done:
7885 if (tag)
7886 got_object_tag_close(tag);
7887 if (err) {
7888 free(*commit_id);
7889 *commit_id = NULL;
7891 return err;
7894 static const struct got_error *
7895 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7896 struct tog_reflist_entry *re, struct got_repository *repo)
7898 struct tog_view *log_view;
7899 const struct got_error *err = NULL;
7900 struct got_object_id *commit_id = NULL;
7902 *new_view = NULL;
7904 err = resolve_reflist_entry(&commit_id, re, repo);
7905 if (err) {
7906 if (err->code != GOT_ERR_OBJ_TYPE)
7907 return err;
7908 else
7909 return NULL;
7912 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7913 if (log_view == NULL) {
7914 err = got_error_from_errno("view_open");
7915 goto done;
7918 err = open_log_view(log_view, commit_id, repo,
7919 got_ref_get_name(re->ref), "", 0);
7920 done:
7921 if (err)
7922 view_close(log_view);
7923 else
7924 *new_view = log_view;
7925 free(commit_id);
7926 return err;
7929 static void
7930 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7932 struct tog_reflist_entry *re;
7933 int i = 0;
7935 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7936 return;
7938 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7939 while (i++ < maxscroll) {
7940 if (re == NULL)
7941 break;
7942 s->first_displayed_entry = re;
7943 re = TAILQ_PREV(re, tog_reflist_head, entry);
7947 static const struct got_error *
7948 ref_scroll_down(struct tog_view *view, int maxscroll)
7950 struct tog_ref_view_state *s = &view->state.ref;
7951 struct tog_reflist_entry *next, *last;
7952 int n = 0;
7954 if (s->first_displayed_entry)
7955 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7956 else
7957 next = TAILQ_FIRST(&s->refs);
7959 last = s->last_displayed_entry;
7960 while (next && n++ < maxscroll) {
7961 if (last) {
7962 s->last_displayed_entry = last;
7963 last = TAILQ_NEXT(last, entry);
7965 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7966 s->first_displayed_entry = next;
7967 next = TAILQ_NEXT(next, entry);
7971 return NULL;
7974 static const struct got_error *
7975 search_start_ref_view(struct tog_view *view)
7977 struct tog_ref_view_state *s = &view->state.ref;
7979 s->matched_entry = NULL;
7980 return NULL;
7983 static int
7984 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7986 regmatch_t regmatch;
7988 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7989 0) == 0;
7992 static const struct got_error *
7993 search_next_ref_view(struct tog_view *view)
7995 struct tog_ref_view_state *s = &view->state.ref;
7996 struct tog_reflist_entry *re = NULL;
7998 if (!view->searching) {
7999 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8000 return NULL;
8003 if (s->matched_entry) {
8004 if (view->searching == TOG_SEARCH_FORWARD) {
8005 if (s->selected_entry)
8006 re = TAILQ_NEXT(s->selected_entry, entry);
8007 else
8008 re = TAILQ_PREV(s->selected_entry,
8009 tog_reflist_head, entry);
8010 } else {
8011 if (s->selected_entry == NULL)
8012 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8013 else
8014 re = TAILQ_PREV(s->selected_entry,
8015 tog_reflist_head, entry);
8017 } else {
8018 if (s->selected_entry)
8019 re = s->selected_entry;
8020 else if (view->searching == TOG_SEARCH_FORWARD)
8021 re = TAILQ_FIRST(&s->refs);
8022 else
8023 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8026 while (1) {
8027 if (re == NULL) {
8028 if (s->matched_entry == NULL) {
8029 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8030 return NULL;
8032 if (view->searching == TOG_SEARCH_FORWARD)
8033 re = TAILQ_FIRST(&s->refs);
8034 else
8035 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8038 if (match_reflist_entry(re, &view->regex)) {
8039 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8040 s->matched_entry = re;
8041 break;
8044 if (view->searching == TOG_SEARCH_FORWARD)
8045 re = TAILQ_NEXT(re, entry);
8046 else
8047 re = TAILQ_PREV(re, tog_reflist_head, entry);
8050 if (s->matched_entry) {
8051 s->first_displayed_entry = s->matched_entry;
8052 s->selected = 0;
8055 return NULL;
8058 static const struct got_error *
8059 show_ref_view(struct tog_view *view)
8061 const struct got_error *err = NULL;
8062 struct tog_ref_view_state *s = &view->state.ref;
8063 struct tog_reflist_entry *re;
8064 char *line = NULL;
8065 wchar_t *wline;
8066 struct tog_color *tc;
8067 int width, n;
8068 int limit = view->nlines;
8070 werase(view->window);
8072 s->ndisplayed = 0;
8073 if (view_is_hsplit_top(view))
8074 --limit; /* border */
8076 if (limit == 0)
8077 return NULL;
8079 re = s->first_displayed_entry;
8081 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8082 s->nrefs) == -1)
8083 return got_error_from_errno("asprintf");
8085 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8086 if (err) {
8087 free(line);
8088 return err;
8090 if (view_needs_focus_indication(view))
8091 wstandout(view->window);
8092 waddwstr(view->window, wline);
8093 while (width++ < view->ncols)
8094 waddch(view->window, ' ');
8095 if (view_needs_focus_indication(view))
8096 wstandend(view->window);
8097 free(wline);
8098 wline = NULL;
8099 free(line);
8100 line = NULL;
8101 if (--limit <= 0)
8102 return NULL;
8104 n = 0;
8105 while (re && limit > 0) {
8106 char *line = NULL;
8107 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8109 if (s->show_date) {
8110 struct got_commit_object *ci;
8111 struct got_tag_object *tag;
8112 struct got_object_id *id;
8113 struct tm tm;
8114 time_t t;
8116 err = got_ref_resolve(&id, s->repo, re->ref);
8117 if (err)
8118 return err;
8119 err = got_object_open_as_tag(&tag, s->repo, id);
8120 if (err) {
8121 if (err->code != GOT_ERR_OBJ_TYPE) {
8122 free(id);
8123 return err;
8125 err = got_object_open_as_commit(&ci, s->repo,
8126 id);
8127 if (err) {
8128 free(id);
8129 return err;
8131 t = got_object_commit_get_committer_time(ci);
8132 got_object_commit_close(ci);
8133 } else {
8134 t = got_object_tag_get_tagger_time(tag);
8135 got_object_tag_close(tag);
8137 free(id);
8138 if (gmtime_r(&t, &tm) == NULL)
8139 return got_error_from_errno("gmtime_r");
8140 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8141 return got_error(GOT_ERR_NO_SPACE);
8143 if (got_ref_is_symbolic(re->ref)) {
8144 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8145 ymd : "", got_ref_get_name(re->ref),
8146 got_ref_get_symref_target(re->ref)) == -1)
8147 return got_error_from_errno("asprintf");
8148 } else if (s->show_ids) {
8149 struct got_object_id *id;
8150 char *id_str;
8151 err = got_ref_resolve(&id, s->repo, re->ref);
8152 if (err)
8153 return err;
8154 err = got_object_id_str(&id_str, id);
8155 if (err) {
8156 free(id);
8157 return err;
8159 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8160 got_ref_get_name(re->ref), id_str) == -1) {
8161 err = got_error_from_errno("asprintf");
8162 free(id);
8163 free(id_str);
8164 return err;
8166 free(id);
8167 free(id_str);
8168 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8169 got_ref_get_name(re->ref)) == -1)
8170 return got_error_from_errno("asprintf");
8172 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
8173 0, 0);
8174 if (err) {
8175 free(line);
8176 return err;
8178 if (n == s->selected) {
8179 if (view->focussed)
8180 wstandout(view->window);
8181 s->selected_entry = re;
8183 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8184 if (tc)
8185 wattr_on(view->window,
8186 COLOR_PAIR(tc->colorpair), NULL);
8187 waddwstr(view->window, wline);
8188 if (tc)
8189 wattr_off(view->window,
8190 COLOR_PAIR(tc->colorpair), NULL);
8191 if (width < view->ncols - 1)
8192 waddch(view->window, '\n');
8193 if (n == s->selected && view->focussed)
8194 wstandend(view->window);
8195 free(line);
8196 free(wline);
8197 wline = NULL;
8198 n++;
8199 s->ndisplayed++;
8200 s->last_displayed_entry = re;
8202 limit--;
8203 re = TAILQ_NEXT(re, entry);
8206 view_border(view);
8207 return err;
8210 static const struct got_error *
8211 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8212 struct tog_reflist_entry *re, struct got_repository *repo)
8214 const struct got_error *err = NULL;
8215 struct got_object_id *commit_id = NULL;
8216 struct tog_view *tree_view;
8218 *new_view = NULL;
8220 err = resolve_reflist_entry(&commit_id, re, repo);
8221 if (err) {
8222 if (err->code != GOT_ERR_OBJ_TYPE)
8223 return err;
8224 else
8225 return NULL;
8229 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8230 if (tree_view == NULL) {
8231 err = got_error_from_errno("view_open");
8232 goto done;
8235 err = open_tree_view(tree_view, commit_id,
8236 got_ref_get_name(re->ref), repo);
8237 if (err)
8238 goto done;
8240 *new_view = tree_view;
8241 done:
8242 free(commit_id);
8243 return err;
8246 static const struct got_error *
8247 ref_goto_line(struct tog_view *view, int nlines)
8249 const struct got_error *err = NULL;
8250 struct tog_ref_view_state *s = &view->state.ref;
8251 int g, idx = s->selected_entry->idx;
8253 g = view->gline;
8254 view->gline = 0;
8256 if (g == 0)
8257 g = 1;
8258 else if (g > s->nrefs)
8259 g = s->nrefs;
8261 if (g >= s->first_displayed_entry->idx + 1 &&
8262 g <= s->last_displayed_entry->idx + 1 &&
8263 g - s->first_displayed_entry->idx - 1 < nlines) {
8264 s->selected = g - s->first_displayed_entry->idx - 1;
8265 return NULL;
8268 if (idx + 1 < g) {
8269 err = ref_scroll_down(view, g - idx - 1);
8270 if (err)
8271 return err;
8272 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8273 s->first_displayed_entry->idx + s->selected < g &&
8274 s->selected < s->ndisplayed - 1)
8275 s->selected = g - s->first_displayed_entry->idx - 1;
8276 } else if (idx + 1 > g)
8277 ref_scroll_up(s, idx - g + 1);
8279 if (g < nlines && s->first_displayed_entry->idx == 0)
8280 s->selected = g - 1;
8282 return NULL;
8286 static const struct got_error *
8287 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8289 const struct got_error *err = NULL;
8290 struct tog_ref_view_state *s = &view->state.ref;
8291 struct tog_reflist_entry *re;
8292 int n, nscroll = view->nlines - 1;
8294 if (view->gline)
8295 return ref_goto_line(view, nscroll);
8297 switch (ch) {
8298 case 'i':
8299 s->show_ids = !s->show_ids;
8300 view->count = 0;
8301 break;
8302 case 'm':
8303 s->show_date = !s->show_date;
8304 view->count = 0;
8305 break;
8306 case 'o':
8307 s->sort_by_date = !s->sort_by_date;
8308 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8309 view->count = 0;
8310 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8311 got_ref_cmp_by_commit_timestamp_descending :
8312 tog_ref_cmp_by_name, s->repo);
8313 if (err)
8314 break;
8315 got_reflist_object_id_map_free(tog_refs_idmap);
8316 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8317 &tog_refs, s->repo);
8318 if (err)
8319 break;
8320 ref_view_free_refs(s);
8321 err = ref_view_load_refs(s);
8322 break;
8323 case KEY_ENTER:
8324 case '\r':
8325 view->count = 0;
8326 if (!s->selected_entry)
8327 break;
8328 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8329 break;
8330 case 'T':
8331 view->count = 0;
8332 if (!s->selected_entry)
8333 break;
8334 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8335 break;
8336 case 'g':
8337 case '=':
8338 case KEY_HOME:
8339 s->selected = 0;
8340 view->count = 0;
8341 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8342 break;
8343 case 'G':
8344 case '*':
8345 case KEY_END: {
8346 int eos = view->nlines - 1;
8348 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8349 --eos; /* border */
8350 s->selected = 0;
8351 view->count = 0;
8352 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8353 for (n = 0; n < eos; n++) {
8354 if (re == NULL)
8355 break;
8356 s->first_displayed_entry = re;
8357 re = TAILQ_PREV(re, tog_reflist_head, entry);
8359 if (n > 0)
8360 s->selected = n - 1;
8361 break;
8363 case 'k':
8364 case KEY_UP:
8365 case CTRL('p'):
8366 if (s->selected > 0) {
8367 s->selected--;
8368 break;
8370 ref_scroll_up(s, 1);
8371 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8372 view->count = 0;
8373 break;
8374 case CTRL('u'):
8375 case 'u':
8376 nscroll /= 2;
8377 /* FALL THROUGH */
8378 case KEY_PPAGE:
8379 case CTRL('b'):
8380 case 'b':
8381 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8382 s->selected -= MIN(nscroll, s->selected);
8383 ref_scroll_up(s, MAX(0, nscroll));
8384 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8385 view->count = 0;
8386 break;
8387 case 'j':
8388 case KEY_DOWN:
8389 case CTRL('n'):
8390 if (s->selected < s->ndisplayed - 1) {
8391 s->selected++;
8392 break;
8394 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8395 /* can't scroll any further */
8396 view->count = 0;
8397 break;
8399 ref_scroll_down(view, 1);
8400 break;
8401 case CTRL('d'):
8402 case 'd':
8403 nscroll /= 2;
8404 /* FALL THROUGH */
8405 case KEY_NPAGE:
8406 case CTRL('f'):
8407 case 'f':
8408 case ' ':
8409 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8410 /* can't scroll any further; move cursor down */
8411 if (s->selected < s->ndisplayed - 1)
8412 s->selected += MIN(nscroll,
8413 s->ndisplayed - s->selected - 1);
8414 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8415 s->selected += s->ndisplayed - s->selected - 1;
8416 view->count = 0;
8417 break;
8419 ref_scroll_down(view, nscroll);
8420 break;
8421 case CTRL('l'):
8422 view->count = 0;
8423 tog_free_refs();
8424 err = tog_load_refs(s->repo, s->sort_by_date);
8425 if (err)
8426 break;
8427 ref_view_free_refs(s);
8428 err = ref_view_load_refs(s);
8429 break;
8430 case KEY_RESIZE:
8431 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8432 s->selected = view->nlines - 2;
8433 break;
8434 default:
8435 view->count = 0;
8436 break;
8439 return err;
8442 __dead static void
8443 usage_ref(void)
8445 endwin();
8446 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8447 getprogname());
8448 exit(1);
8451 static const struct got_error *
8452 cmd_ref(int argc, char *argv[])
8454 const struct got_error *error;
8455 struct got_repository *repo = NULL;
8456 struct got_worktree *worktree = NULL;
8457 char *cwd = NULL, *repo_path = NULL;
8458 int ch;
8459 struct tog_view *view;
8460 int *pack_fds = NULL;
8462 while ((ch = getopt(argc, argv, "r:")) != -1) {
8463 switch (ch) {
8464 case 'r':
8465 repo_path = realpath(optarg, NULL);
8466 if (repo_path == NULL)
8467 return got_error_from_errno2("realpath",
8468 optarg);
8469 break;
8470 default:
8471 usage_ref();
8472 /* NOTREACHED */
8476 argc -= optind;
8477 argv += optind;
8479 if (argc > 1)
8480 usage_ref();
8482 error = got_repo_pack_fds_open(&pack_fds);
8483 if (error != NULL)
8484 goto done;
8486 if (repo_path == NULL) {
8487 cwd = getcwd(NULL, 0);
8488 if (cwd == NULL)
8489 return got_error_from_errno("getcwd");
8490 error = got_worktree_open(&worktree, cwd);
8491 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8492 goto done;
8493 if (worktree)
8494 repo_path =
8495 strdup(got_worktree_get_repo_path(worktree));
8496 else
8497 repo_path = strdup(cwd);
8498 if (repo_path == NULL) {
8499 error = got_error_from_errno("strdup");
8500 goto done;
8504 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8505 if (error != NULL)
8506 goto done;
8508 init_curses();
8510 error = apply_unveil(got_repo_get_path(repo), NULL);
8511 if (error)
8512 goto done;
8514 error = tog_load_refs(repo, 0);
8515 if (error)
8516 goto done;
8518 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8519 if (view == NULL) {
8520 error = got_error_from_errno("view_open");
8521 goto done;
8524 error = open_ref_view(view, repo);
8525 if (error)
8526 goto done;
8528 if (worktree) {
8529 /* Release work tree lock. */
8530 got_worktree_close(worktree);
8531 worktree = NULL;
8533 error = view_loop(view);
8534 done:
8535 free(repo_path);
8536 free(cwd);
8537 if (repo) {
8538 const struct got_error *close_err = got_repo_close(repo);
8539 if (close_err)
8540 error = close_err;
8542 if (pack_fds) {
8543 const struct got_error *pack_err =
8544 got_repo_pack_fds_close(pack_fds);
8545 if (error == NULL)
8546 error = pack_err;
8548 tog_free_refs();
8549 return error;
8552 static const struct got_error*
8553 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8554 const char *str)
8556 size_t len;
8558 if (win == NULL)
8559 win = stdscr;
8561 len = strlen(str);
8562 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8564 if (focus)
8565 wstandout(win);
8566 if (mvwprintw(win, y, x, "%s", str) == ERR)
8567 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8568 if (focus)
8569 wstandend(win);
8571 return NULL;
8574 static const struct got_error *
8575 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8577 off_t *p;
8579 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8580 if (p == NULL) {
8581 free(*line_offsets);
8582 *line_offsets = NULL;
8583 return got_error_from_errno("reallocarray");
8586 *line_offsets = p;
8587 (*line_offsets)[*nlines] = off;
8588 ++(*nlines);
8589 return NULL;
8592 static const struct got_error *
8593 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8595 *ret = 0;
8597 for (;n > 0; --n, ++km) {
8598 char *t0, *t, *k;
8599 size_t len = 1;
8601 if (km->keys == NULL)
8602 continue;
8604 t = t0 = strdup(km->keys);
8605 if (t0 == NULL)
8606 return got_error_from_errno("strdup");
8608 len += strlen(t);
8609 while ((k = strsep(&t, " ")) != NULL)
8610 len += strlen(k) > 1 ? 2 : 0;
8611 free(t0);
8612 *ret = MAX(*ret, len);
8615 return NULL;
8619 * Write keymap section headers, keys, and key info in km to f.
8620 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8621 * wrap control and symbolic keys in guillemets, else use <>.
8623 static const struct got_error *
8624 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8626 int n, len = width;
8628 if (km->keys) {
8629 static const char *u8_glyph[] = {
8630 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8631 "\xe2\x80\xba" /* U+203A (utf8 >) */
8633 char *t0, *t, *k;
8634 int cs, s, first = 1;
8636 cs = got_locale_is_utf8();
8638 t = t0 = strdup(km->keys);
8639 if (t0 == NULL)
8640 return got_error_from_errno("strdup");
8642 len = strlen(km->keys);
8643 while ((k = strsep(&t, " ")) != NULL) {
8644 s = strlen(k) > 1; /* control or symbolic key */
8645 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8646 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8647 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8648 if (n < 0) {
8649 free(t0);
8650 return got_error_from_errno("fprintf");
8652 first = 0;
8653 len += s ? 2 : 0;
8654 *off += n;
8656 free(t0);
8658 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8659 if (n < 0)
8660 return got_error_from_errno("fprintf");
8661 *off += n;
8663 return NULL;
8666 static const struct got_error *
8667 format_help(struct tog_help_view_state *s)
8669 const struct got_error *err = NULL;
8670 off_t off = 0;
8671 int i, max, n, show = s->all;
8672 static const struct tog_key_map km[] = {
8673 #define KEYMAP_(info, type) { NULL, (info), type }
8674 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8675 GENERATE_HELP
8676 #undef KEYMAP_
8677 #undef KEY_
8680 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
8681 if (err)
8682 return err;
8684 n = nitems(km);
8685 err = max_key_str(&max, km, n);
8686 if (err)
8687 return err;
8689 for (i = 0; i < n; ++i) {
8690 if (km[i].keys == NULL) {
8691 show = s->all;
8692 if (km[i].type == TOG_KEYMAP_GLOBAL ||
8693 km[i].type == s->type || s->all)
8694 show = 1;
8696 if (show) {
8697 err = format_help_line(&off, s->f, &km[i], max);
8698 if (err)
8699 return err;
8700 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8701 if (err)
8702 return err;
8705 fputc('\n', s->f);
8706 ++off;
8707 err = add_line_offset(&s->line_offsets, &s->nlines, off);
8708 return err;
8711 static const struct got_error *
8712 create_help(struct tog_help_view_state *s)
8714 FILE *f;
8715 const struct got_error *err;
8717 free(s->line_offsets);
8718 s->line_offsets = NULL;
8719 s->nlines = 0;
8721 f = got_opentemp();
8722 if (f == NULL)
8723 return got_error_from_errno("got_opentemp");
8724 s->f = f;
8726 err = format_help(s);
8727 if (err)
8728 return err;
8730 if (s->f && fflush(s->f) != 0)
8731 return got_error_from_errno("fflush");
8733 return NULL;
8736 static const struct got_error *
8737 search_start_help_view(struct tog_view *view)
8739 view->state.help.matched_line = 0;
8740 return NULL;
8743 static void
8744 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
8745 size_t *nlines, int **first, int **last, int **match, int **selected)
8747 struct tog_help_view_state *s = &view->state.help;
8749 *f = s->f;
8750 *nlines = s->nlines;
8751 *line_offsets = s->line_offsets;
8752 *match = &s->matched_line;
8753 *first = &s->first_displayed_line;
8754 *last = &s->last_displayed_line;
8755 *selected = &s->selected_line;
8758 static const struct got_error *
8759 show_help_view(struct tog_view *view)
8761 struct tog_help_view_state *s = &view->state.help;
8762 const struct got_error *err;
8763 regmatch_t *regmatch = &view->regmatch;
8764 wchar_t *wline;
8765 char *line;
8766 ssize_t linelen;
8767 size_t linesz = 0;
8768 int width, nprinted = 0, rc = 0;
8769 int eos = view->nlines;
8771 if (view_is_hsplit_top(view))
8772 --eos; /* account for border */
8774 s->lineno = 0;
8775 rewind(s->f);
8776 werase(view->window);
8778 if (view->gline > s->nlines - 1)
8779 view->gline = s->nlines - 1;
8781 err = win_draw_center(view->window, 0, 0, view->ncols,
8782 view_needs_focus_indication(view),
8783 "tog help (press q to return to tog)");
8784 if (err)
8785 return err;
8786 if (eos <= 1)
8787 return NULL;
8788 waddstr(view->window, "\n\n");
8789 eos -= 2;
8791 s->eof = 0;
8792 view->maxx = 0;
8793 line = NULL;
8794 while (eos > 0 && nprinted < eos) {
8795 attr_t attr = 0;
8797 linelen = getline(&line, &linesz, s->f);
8798 if (linelen == -1) {
8799 if (!feof(s->f)) {
8800 free(line);
8801 return got_ferror(s->f, GOT_ERR_IO);
8803 s->eof = 1;
8804 break;
8806 if (++s->lineno < s->first_displayed_line)
8807 continue;
8808 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
8809 continue;
8810 if (s->lineno == view->hiline)
8811 attr = A_STANDOUT;
8813 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
8814 view->x ? 1 : 0);
8815 if (err) {
8816 free(line);
8817 return err;
8819 view->maxx = MAX(view->maxx, width);
8820 free(wline);
8821 wline = NULL;
8823 if (attr)
8824 wattron(view->window, attr);
8825 if (s->first_displayed_line + nprinted == s->matched_line &&
8826 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
8827 err = add_matched_line(&width, line, view->ncols - 1, 0,
8828 view->window, view->x, regmatch);
8829 if (err) {
8830 free(line);
8831 return err;
8833 } else {
8834 int skip;
8836 err = format_line(&wline, &width, &skip, line,
8837 view->x, view->ncols - 1, 0, view->x ? 1 : 0);
8838 if (err) {
8839 free(line);
8840 return err;
8842 rc = waddwstr(view->window, &wline[skip]);
8843 free(wline);
8844 wline = NULL;
8845 if (rc == ERR)
8846 return got_error_msg(GOT_ERR_IO, "waddwstr");
8848 if (s->lineno == view->hiline) {
8849 while (width++ < view->ncols)
8850 waddch(view->window, ' ');
8851 } else {
8852 if (width <= view->ncols)
8853 waddch(view->window, '\n');
8855 if (attr)
8856 wattroff(view->window, attr);
8857 if (++nprinted == 1)
8858 s->first_displayed_line = s->lineno;
8860 free(line);
8861 if (nprinted > 0)
8862 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
8863 else
8864 s->last_displayed_line = s->first_displayed_line;
8866 view_border(view);
8868 if (s->eof) {
8869 rc = waddnstr(view->window,
8870 "See the tog(1) manual page for full documentation",
8871 view->ncols - 1);
8872 if (rc == ERR)
8873 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8874 } else {
8875 wmove(view->window, view->nlines - 1, 0);
8876 wclrtoeol(view->window);
8877 wstandout(view->window);
8878 rc = waddnstr(view->window, "scroll down for more...",
8879 view->ncols - 1);
8880 if (rc == ERR)
8881 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
8882 if (getcurx(view->window) < view->ncols - 6) {
8883 rc = wprintw(view->window, "[%.0f%%]",
8884 100.00 * s->last_displayed_line / s->nlines);
8885 if (rc == ERR)
8886 return got_error_msg(GOT_ERR_IO, "wprintw");
8888 wstandend(view->window);
8891 return NULL;
8894 static const struct got_error *
8895 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
8897 struct tog_help_view_state *s = &view->state.help;
8898 const struct got_error *err = NULL;
8899 char *line = NULL;
8900 ssize_t linelen;
8901 size_t linesz = 0;
8902 int eos, nscroll;
8904 eos = nscroll = view->nlines;
8905 if (view_is_hsplit_top(view))
8906 --eos; /* border */
8908 s->lineno = s->first_displayed_line - 1 + s->selected_line;
8910 switch (ch) {
8911 case '0':
8912 view->x = 0;
8913 break;
8914 case '$':
8915 view->x = MAX(view->maxx - view->ncols / 3, 0);
8916 view->count = 0;
8917 break;
8918 case KEY_RIGHT:
8919 case 'l':
8920 if (view->x + view->ncols / 3 < view->maxx)
8921 view->x += 2;
8922 else
8923 view->count = 0;
8924 break;
8925 case KEY_LEFT:
8926 case 'h':
8927 view->x -= MIN(view->x, 2);
8928 if (view->x <= 0)
8929 view->count = 0;
8930 break;
8931 case 'g':
8932 case KEY_HOME:
8933 s->first_displayed_line = 1;
8934 view->count = 0;
8935 break;
8936 case 'G':
8937 case KEY_END:
8938 view->count = 0;
8939 if (s->eof)
8940 break;
8941 s->first_displayed_line = (s->nlines - eos) + 3;
8942 s->eof = 1;
8943 break;
8944 case 'k':
8945 case KEY_UP:
8946 if (s->first_displayed_line > 1)
8947 --s->first_displayed_line;
8948 else
8949 view->count = 0;
8950 break;
8951 case CTRL('u'):
8952 case 'u':
8953 nscroll /= 2;
8954 /* FALL THROUGH */
8955 case KEY_PPAGE:
8956 case CTRL('b'):
8957 case 'b':
8958 if (s->first_displayed_line == 1) {
8959 view->count = 0;
8960 break;
8962 while (--nscroll > 0 && s->first_displayed_line > 1)
8963 s->first_displayed_line--;
8964 break;
8965 case 'j':
8966 case KEY_DOWN:
8967 case CTRL('n'):
8968 if (!s->eof)
8969 ++s->first_displayed_line;
8970 else
8971 view->count = 0;
8972 break;
8973 case CTRL('d'):
8974 case 'd':
8975 nscroll /= 2;
8976 /* FALL THROUGH */
8977 case KEY_NPAGE:
8978 case CTRL('f'):
8979 case 'f':
8980 case ' ':
8981 if (s->eof) {
8982 view->count = 0;
8983 break;
8985 while (!s->eof && --nscroll > 0) {
8986 linelen = getline(&line, &linesz, s->f);
8987 s->first_displayed_line++;
8988 if (linelen == -1) {
8989 if (feof(s->f))
8990 s->eof = 1;
8991 else
8992 err = got_ferror(s->f, GOT_ERR_IO);
8993 break;
8996 free(line);
8997 break;
8998 default:
8999 view->count = 0;
9000 break;
9003 return err;
9006 static const struct got_error *
9007 close_help_view(struct tog_view *view)
9009 struct tog_help_view_state *s = &view->state.help;
9011 free(s->line_offsets);
9012 s->line_offsets = NULL;
9013 if (fclose(s->f) == EOF)
9014 return got_error_from_errno("fclose");
9016 return NULL;
9019 static const struct got_error *
9020 reset_help_view(struct tog_view *view)
9022 struct tog_help_view_state *s = &view->state.help;
9025 if (s->f && fclose(s->f) == EOF)
9026 return got_error_from_errno("fclose");
9028 wclear(view->window);
9029 view->count = 0;
9030 view->x = 0;
9031 s->all = !s->all;
9032 s->first_displayed_line = 1;
9033 s->last_displayed_line = view->nlines;
9034 s->matched_line = 0;
9036 return create_help(s);
9039 static const struct got_error *
9040 open_help_view(struct tog_view *view, struct tog_view *parent)
9042 const struct got_error *err = NULL;
9043 struct tog_help_view_state *s = &view->state.help;
9045 s->type = (enum tog_keymap_type)parent->type;
9046 s->first_displayed_line = 1;
9047 s->last_displayed_line = view->nlines;
9048 s->selected_line = 1;
9050 view->show = show_help_view;
9051 view->input = input_help_view;
9052 view->reset = reset_help_view;
9053 view->close = close_help_view;
9054 view->search_start = search_start_help_view;
9055 view->search_setup = search_setup_help_view;
9056 view->search_next = search_next_view_match;
9058 err = create_help(s);
9059 return err;
9062 static const struct got_error *
9063 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9064 enum tog_view_type request, int y, int x)
9066 const struct got_error *err = NULL;
9068 *new_view = NULL;
9070 switch (request) {
9071 case TOG_VIEW_DIFF:
9072 if (view->type == TOG_VIEW_LOG) {
9073 struct tog_log_view_state *s = &view->state.log;
9075 err = open_diff_view_for_commit(new_view, y, x,
9076 s->selected_entry->commit, s->selected_entry->id,
9077 view, s->repo);
9078 } else
9079 return got_error_msg(GOT_ERR_NOT_IMPL,
9080 "parent/child view pair not supported");
9081 break;
9082 case TOG_VIEW_BLAME:
9083 if (view->type == TOG_VIEW_TREE) {
9084 struct tog_tree_view_state *s = &view->state.tree;
9086 err = blame_tree_entry(new_view, y, x,
9087 s->selected_entry, &s->parents, s->commit_id,
9088 s->repo);
9089 } else
9090 return got_error_msg(GOT_ERR_NOT_IMPL,
9091 "parent/child view pair not supported");
9092 break;
9093 case TOG_VIEW_LOG:
9094 if (view->type == TOG_VIEW_BLAME)
9095 err = log_annotated_line(new_view, y, x,
9096 view->state.blame.repo, view->state.blame.id_to_log);
9097 else if (view->type == TOG_VIEW_TREE)
9098 err = log_selected_tree_entry(new_view, y, x,
9099 &view->state.tree);
9100 else if (view->type == TOG_VIEW_REF)
9101 err = log_ref_entry(new_view, y, x,
9102 view->state.ref.selected_entry,
9103 view->state.ref.repo);
9104 else
9105 return got_error_msg(GOT_ERR_NOT_IMPL,
9106 "parent/child view pair not supported");
9107 break;
9108 case TOG_VIEW_TREE:
9109 if (view->type == TOG_VIEW_LOG)
9110 err = browse_commit_tree(new_view, y, x,
9111 view->state.log.selected_entry,
9112 view->state.log.in_repo_path,
9113 view->state.log.head_ref_name,
9114 view->state.log.repo);
9115 else if (view->type == TOG_VIEW_REF)
9116 err = browse_ref_tree(new_view, y, x,
9117 view->state.ref.selected_entry,
9118 view->state.ref.repo);
9119 else
9120 return got_error_msg(GOT_ERR_NOT_IMPL,
9121 "parent/child view pair not supported");
9122 break;
9123 case TOG_VIEW_REF:
9124 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9125 if (*new_view == NULL)
9126 return got_error_from_errno("view_open");
9127 if (view->type == TOG_VIEW_LOG)
9128 err = open_ref_view(*new_view, view->state.log.repo);
9129 else if (view->type == TOG_VIEW_TREE)
9130 err = open_ref_view(*new_view, view->state.tree.repo);
9131 else
9132 err = got_error_msg(GOT_ERR_NOT_IMPL,
9133 "parent/child view pair not supported");
9134 if (err)
9135 view_close(*new_view);
9136 break;
9137 case TOG_VIEW_HELP:
9138 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9139 if (*new_view == NULL)
9140 return got_error_from_errno("view_open");
9141 err = open_help_view(*new_view, view);
9142 if (err)
9143 view_close(*new_view);
9144 break;
9145 default:
9146 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9149 return err;
9153 * If view was scrolled down to move the selected line into view when opening a
9154 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9156 static void
9157 offset_selection_up(struct tog_view *view)
9159 switch (view->type) {
9160 case TOG_VIEW_BLAME: {
9161 struct tog_blame_view_state *s = &view->state.blame;
9162 if (s->first_displayed_line == 1) {
9163 s->selected_line = MAX(s->selected_line - view->offset,
9164 1);
9165 break;
9167 if (s->first_displayed_line > view->offset)
9168 s->first_displayed_line -= view->offset;
9169 else
9170 s->first_displayed_line = 1;
9171 s->selected_line += view->offset;
9172 break;
9174 case TOG_VIEW_LOG:
9175 log_scroll_up(&view->state.log, view->offset);
9176 view->state.log.selected += view->offset;
9177 break;
9178 case TOG_VIEW_REF:
9179 ref_scroll_up(&view->state.ref, view->offset);
9180 view->state.ref.selected += view->offset;
9181 break;
9182 case TOG_VIEW_TREE:
9183 tree_scroll_up(&view->state.tree, view->offset);
9184 view->state.tree.selected += view->offset;
9185 break;
9186 default:
9187 break;
9190 view->offset = 0;
9194 * If the selected line is in the section of screen covered by the bottom split,
9195 * scroll down offset lines to move it into view and index its new position.
9197 static const struct got_error *
9198 offset_selection_down(struct tog_view *view)
9200 const struct got_error *err = NULL;
9201 const struct got_error *(*scrolld)(struct tog_view *, int);
9202 int *selected = NULL;
9203 int header, offset;
9205 switch (view->type) {
9206 case TOG_VIEW_BLAME: {
9207 struct tog_blame_view_state *s = &view->state.blame;
9208 header = 3;
9209 scrolld = NULL;
9210 if (s->selected_line > view->nlines - header) {
9211 offset = abs(view->nlines - s->selected_line - header);
9212 s->first_displayed_line += offset;
9213 s->selected_line -= offset;
9214 view->offset = offset;
9216 break;
9218 case TOG_VIEW_LOG: {
9219 struct tog_log_view_state *s = &view->state.log;
9220 scrolld = &log_scroll_down;
9221 header = view_is_parent_view(view) ? 3 : 2;
9222 selected = &s->selected;
9223 break;
9225 case TOG_VIEW_REF: {
9226 struct tog_ref_view_state *s = &view->state.ref;
9227 scrolld = &ref_scroll_down;
9228 header = 3;
9229 selected = &s->selected;
9230 break;
9232 case TOG_VIEW_TREE: {
9233 struct tog_tree_view_state *s = &view->state.tree;
9234 scrolld = &tree_scroll_down;
9235 header = 5;
9236 selected = &s->selected;
9237 break;
9239 default:
9240 selected = NULL;
9241 scrolld = NULL;
9242 header = 0;
9243 break;
9246 if (selected && *selected > view->nlines - header) {
9247 offset = abs(view->nlines - *selected - header);
9248 view->offset = offset;
9249 if (scrolld && offset) {
9250 err = scrolld(view, offset);
9251 *selected -= offset;
9255 return err;
9258 static void
9259 list_commands(FILE *fp)
9261 size_t i;
9263 fprintf(fp, "commands:");
9264 for (i = 0; i < nitems(tog_commands); i++) {
9265 const struct tog_cmd *cmd = &tog_commands[i];
9266 fprintf(fp, " %s", cmd->name);
9268 fputc('\n', fp);
9271 __dead static void
9272 usage(int hflag, int status)
9274 FILE *fp = (status == 0) ? stdout : stderr;
9276 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9277 getprogname());
9278 if (hflag) {
9279 fprintf(fp, "lazy usage: %s path\n", getprogname());
9280 list_commands(fp);
9282 exit(status);
9285 static char **
9286 make_argv(int argc, ...)
9288 va_list ap;
9289 char **argv;
9290 int i;
9292 va_start(ap, argc);
9294 argv = calloc(argc, sizeof(char *));
9295 if (argv == NULL)
9296 err(1, "calloc");
9297 for (i = 0; i < argc; i++) {
9298 argv[i] = strdup(va_arg(ap, char *));
9299 if (argv[i] == NULL)
9300 err(1, "strdup");
9303 va_end(ap);
9304 return argv;
9308 * Try to convert 'tog path' into a 'tog log path' command.
9309 * The user could simply have mistyped the command rather than knowingly
9310 * provided a path. So check whether argv[0] can in fact be resolved
9311 * to a path in the HEAD commit and print a special error if not.
9312 * This hack is for mpi@ <3
9314 static const struct got_error *
9315 tog_log_with_path(int argc, char *argv[])
9317 const struct got_error *error = NULL, *close_err;
9318 const struct tog_cmd *cmd = NULL;
9319 struct got_repository *repo = NULL;
9320 struct got_worktree *worktree = NULL;
9321 struct got_object_id *commit_id = NULL, *id = NULL;
9322 struct got_commit_object *commit = NULL;
9323 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9324 char *commit_id_str = NULL, **cmd_argv = NULL;
9325 int *pack_fds = NULL;
9327 cwd = getcwd(NULL, 0);
9328 if (cwd == NULL)
9329 return got_error_from_errno("getcwd");
9331 error = got_repo_pack_fds_open(&pack_fds);
9332 if (error != NULL)
9333 goto done;
9335 error = got_worktree_open(&worktree, cwd);
9336 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9337 goto done;
9339 if (worktree)
9340 repo_path = strdup(got_worktree_get_repo_path(worktree));
9341 else
9342 repo_path = strdup(cwd);
9343 if (repo_path == NULL) {
9344 error = got_error_from_errno("strdup");
9345 goto done;
9348 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9349 if (error != NULL)
9350 goto done;
9352 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9353 repo, worktree);
9354 if (error)
9355 goto done;
9357 error = tog_load_refs(repo, 0);
9358 if (error)
9359 goto done;
9360 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9361 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9362 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9363 if (error)
9364 goto done;
9366 if (worktree) {
9367 got_worktree_close(worktree);
9368 worktree = NULL;
9371 error = got_object_open_as_commit(&commit, repo, commit_id);
9372 if (error)
9373 goto done;
9375 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9376 if (error) {
9377 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9378 goto done;
9379 fprintf(stderr, "%s: '%s' is no known command or path\n",
9380 getprogname(), argv[0]);
9381 usage(1, 1);
9382 /* not reached */
9385 error = got_object_id_str(&commit_id_str, commit_id);
9386 if (error)
9387 goto done;
9389 cmd = &tog_commands[0]; /* log */
9390 argc = 4;
9391 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9392 error = cmd->cmd_main(argc, cmd_argv);
9393 done:
9394 if (repo) {
9395 close_err = got_repo_close(repo);
9396 if (error == NULL)
9397 error = close_err;
9399 if (commit)
9400 got_object_commit_close(commit);
9401 if (worktree)
9402 got_worktree_close(worktree);
9403 if (pack_fds) {
9404 const struct got_error *pack_err =
9405 got_repo_pack_fds_close(pack_fds);
9406 if (error == NULL)
9407 error = pack_err;
9409 free(id);
9410 free(commit_id_str);
9411 free(commit_id);
9412 free(cwd);
9413 free(repo_path);
9414 free(in_repo_path);
9415 if (cmd_argv) {
9416 int i;
9417 for (i = 0; i < argc; i++)
9418 free(cmd_argv[i]);
9419 free(cmd_argv);
9421 tog_free_refs();
9422 return error;
9425 int
9426 main(int argc, char *argv[])
9428 const struct got_error *error = NULL;
9429 const struct tog_cmd *cmd = NULL;
9430 int ch, hflag = 0, Vflag = 0;
9431 char **cmd_argv = NULL;
9432 static const struct option longopts[] = {
9433 { "version", no_argument, NULL, 'V' },
9434 { NULL, 0, NULL, 0}
9436 char *diff_algo_str = NULL;
9438 if (!isatty(STDIN_FILENO))
9439 errx(1, "standard input is not a tty");
9441 setlocale(LC_CTYPE, "");
9443 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9444 switch (ch) {
9445 case 'h':
9446 hflag = 1;
9447 break;
9448 case 'V':
9449 Vflag = 1;
9450 break;
9451 default:
9452 usage(hflag, 1);
9453 /* NOTREACHED */
9457 argc -= optind;
9458 argv += optind;
9459 optind = 1;
9460 optreset = 1;
9462 if (Vflag) {
9463 got_version_print_str();
9464 return 0;
9467 #ifndef PROFILE
9468 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9469 NULL) == -1)
9470 err(1, "pledge");
9471 #endif
9473 if (argc == 0) {
9474 if (hflag)
9475 usage(hflag, 0);
9476 /* Build an argument vector which runs a default command. */
9477 cmd = &tog_commands[0];
9478 argc = 1;
9479 cmd_argv = make_argv(argc, cmd->name);
9480 } else {
9481 size_t i;
9483 /* Did the user specify a command? */
9484 for (i = 0; i < nitems(tog_commands); i++) {
9485 if (strncmp(tog_commands[i].name, argv[0],
9486 strlen(argv[0])) == 0) {
9487 cmd = &tog_commands[i];
9488 break;
9493 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9494 if (diff_algo_str) {
9495 if (strcasecmp(diff_algo_str, "patience") == 0)
9496 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9497 if (strcasecmp(diff_algo_str, "myers") == 0)
9498 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9501 if (cmd == NULL) {
9502 if (argc != 1)
9503 usage(0, 1);
9504 /* No command specified; try log with a path */
9505 error = tog_log_with_path(argc, argv);
9506 } else {
9507 if (hflag)
9508 cmd->cmd_usage();
9509 else
9510 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9513 endwin();
9514 if (cmd_argv) {
9515 int i;
9516 for (i = 0; i < argc; i++)
9517 free(cmd_argv[i]);
9518 free(cmd_argv);
9521 if (error && error->code != GOT_ERR_CANCELLED &&
9522 error->code != GOT_ERR_EOF &&
9523 error->code != GOT_ERR_PRIVSEP_EXIT &&
9524 error->code != GOT_ERR_PRIVSEP_PIPE &&
9525 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9526 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9527 return 0;