1 /* Copyright (c) 2006-2010 Jonas Fonseca <fonseca@diku.dk>
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
19 #define TIG_VERSION "unknown-version"
34 #include <sys/types.h>
37 #include <sys/select.h>
49 /* ncurses(3): Must be defined to have extended wide-character functions. */
50 #define _XOPEN_SOURCE_EXTENDED
52 #ifdef HAVE_NCURSESW_NCURSES_H
53 #include <ncursesw/ncurses.h>
55 #ifdef HAVE_NCURSES_NCURSES_H
56 #include <ncurses/ncurses.h>
63 #define __NORETURN __attribute__((__noreturn__))
68 static void __NORETURN
die(const char *err
, ...);
69 static void warn(const char *msg
, ...);
70 static void report(const char *msg
, ...);
72 #define ABS(x) ((x) >= 0 ? (x) : -(x))
73 #define MIN(x, y) ((x) < (y) ? (x) : (y))
74 #define MAX(x, y) ((x) > (y) ? (x) : (y))
76 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
77 #define STRING_SIZE(x) (sizeof(x) - 1)
79 #define SIZEOF_STR 1024 /* Default string size. */
80 #define SIZEOF_REF 256 /* Size of symbolic or SHA1 ID. */
81 #define SIZEOF_REV 41 /* Holds a SHA-1 and an ending NUL. */
82 #define SIZEOF_ARG 32 /* Default argument array size. */
86 #define REVGRAPH_INIT 'I'
87 #define REVGRAPH_MERGE 'M'
88 #define REVGRAPH_BRANCH '+'
89 #define REVGRAPH_COMMIT '*'
90 #define REVGRAPH_BOUND '^'
92 #define SIZEOF_REVGRAPH 19 /* Size of revision ancestry graphics. */
94 /* This color name can be used to refer to the default term colors. */
95 #define COLOR_DEFAULT (-1)
97 #define ICONV_NONE ((iconv_t) -1)
99 #define ICONV_CONST /* nothing */
102 /* The format and size of the date column in the main view. */
103 #define DATE_FORMAT "%Y-%m-%d %H:%M"
104 #define DATE_COLS STRING_SIZE("2006-04-29 14:21 ")
105 #define DATE_SHORT_COLS STRING_SIZE("2006-04-29 ")
108 #define AUTHOR_COLS 19
110 #define MIN_VIEW_HEIGHT 4
112 #define NULL_ID "0000000000000000000000000000000000000000"
114 #define S_ISGITLINK(mode) (((mode) & S_IFMT) == 0160000)
116 /* Some ASCII-shorthands fitted into the ncurses namespace. */
118 #define KEY_RETURN '\r'
123 char id
[SIZEOF_REV
]; /* Commit SHA1 ID */
124 unsigned int head
:1; /* Is it the current HEAD? */
125 unsigned int tag
:1; /* Is it a tag? */
126 unsigned int ltag
:1; /* If so, is the tag local? */
127 unsigned int remote
:1; /* Is it a remote ref? */
128 unsigned int tracked
:1; /* Is it the remote for the current HEAD? */
129 char name
[1]; /* Ref name; tag or head names are shortened. */
133 char id
[SIZEOF_REV
]; /* Commit SHA1 ID */
134 size_t size
; /* Number of refs. */
135 struct ref
**refs
; /* References for this ID. */
138 static struct ref
*get_ref_head();
139 static struct ref_list
*get_ref_list(const char *id
);
140 static void foreach_ref(bool (*visitor
)(void *data
, const struct ref
*ref
), void *data
);
141 static int load_refs(void);
144 FORMAT_ALL
, /* Perform replacement in all arguments. */
145 FORMAT_DASH
, /* Perform replacement up until "--". */
146 FORMAT_NONE
/* No replacement should be performed. */
149 static bool format_argv(const char *dst
[], const char *src
[], enum format_flags flags
);
158 typedef enum input_status (*input_handler
)(void *data
, char *buf
, int c
);
160 static char *prompt_input(const char *prompt
, input_handler handler
, void *data
);
161 static bool prompt_yesno(const char *prompt
);
169 static bool prompt_menu(const char *prompt
, const struct menu_item
*items
, int *selected
);
172 * Allocation helpers ... Entering macro hell to never be seen again.
175 #define DEFINE_ALLOCATOR(name, type, chunk_size) \
177 name(type **mem, size_t size, size_t increase) \
179 size_t num_chunks = (size + chunk_size - 1) / chunk_size; \
180 size_t num_chunks_new = (size + increase + chunk_size - 1) / chunk_size;\
183 if (mem == NULL || num_chunks != num_chunks_new) { \
184 tmp = realloc(tmp, num_chunks_new * chunk_size * sizeof(type)); \
197 string_ncopy_do(char *dst
, size_t dstlen
, const char *src
, size_t srclen
)
199 if (srclen
> dstlen
- 1)
202 strncpy(dst
, src
, srclen
);
206 /* Shorthands for safely copying into a fixed buffer. */
208 #define string_copy(dst, src) \
209 string_ncopy_do(dst, sizeof(dst), src, sizeof(src))
211 #define string_ncopy(dst, src, srclen) \
212 string_ncopy_do(dst, sizeof(dst), src, srclen)
214 #define string_copy_rev(dst, src) \
215 string_ncopy_do(dst, SIZEOF_REV, src, SIZEOF_REV - 1)
217 #define string_add(dst, from, src) \
218 string_ncopy_do(dst + (from), sizeof(dst) - (from), src, sizeof(src))
221 string_expand(char *dst
, size_t dstlen
, const char *src
, int tabsize
)
225 for (size
= pos
= 0; size
< dstlen
- 1 && src
[pos
]; pos
++) {
226 if (src
[pos
] == '\t') {
227 size_t expanded
= tabsize
- (size
% tabsize
);
229 if (expanded
+ size
>= dstlen
- 1)
230 expanded
= dstlen
- size
- 1;
231 memcpy(dst
+ size
, " ", expanded
);
234 dst
[size
++] = src
[pos
];
242 chomp_string(char *name
)
246 while (isspace(*name
))
249 namelen
= strlen(name
) - 1;
250 while (namelen
> 0 && isspace(name
[namelen
]))
257 string_nformat(char *buf
, size_t bufsize
, size_t *bufpos
, const char *fmt
, ...)
260 size_t pos
= bufpos
? *bufpos
: 0;
263 pos
+= vsnprintf(buf
+ pos
, bufsize
- pos
, fmt
, args
);
269 return pos
>= bufsize
? FALSE
: TRUE
;
272 #define string_format(buf, fmt, args...) \
273 string_nformat(buf, sizeof(buf), NULL, fmt, args)
275 #define string_format_from(buf, from, fmt, args...) \
276 string_nformat(buf, sizeof(buf), from, fmt, args)
279 string_enum_compare(const char *str1
, const char *str2
, int len
)
283 #define string_enum_sep(x) ((x) == '-' || (x) == '_' || (x) == '.')
285 /* Diff-Header == DIFF_HEADER */
286 for (i
= 0; i
< len
; i
++) {
287 if (toupper(str1
[i
]) == toupper(str2
[i
]))
290 if (string_enum_sep(str1
[i
]) &&
291 string_enum_sep(str2
[i
]))
294 return str1
[i
] - str2
[i
];
300 #define enum_equals(entry, str, len) \
301 ((entry).namelen == (len) && !string_enum_compare((entry).name, str, len))
309 #define ENUM_MAP(name, value) { name, STRING_SIZE(name), value }
312 enum_map_name(const char *name
, size_t namelen
)
314 static char buf
[SIZEOF_STR
];
317 for (bufpos
= 0; bufpos
<= namelen
; bufpos
++) {
318 buf
[bufpos
] = tolower(name
[bufpos
]);
319 if (buf
[bufpos
] == '_')
327 #define enum_name(entry) enum_map_name((entry).name, (entry).namelen)
330 map_enum_do(const struct enum_map
*map
, size_t map_size
, int *value
, const char *name
)
332 size_t namelen
= strlen(name
);
335 for (i
= 0; i
< map_size
; i
++)
336 if (enum_equals(map
[i
], name
, namelen
)) {
337 *value
= map
[i
].value
;
344 #define map_enum(attr, map, name) \
345 map_enum_do(map, ARRAY_SIZE(map), attr, name)
347 #define prefixcmp(str1, str2) \
348 strncmp(str1, str2, STRING_SIZE(str2))
351 suffixcmp(const char *str
, int slen
, const char *suffix
)
353 size_t len
= slen
>= 0 ? slen
: strlen(str
);
354 size_t suffixlen
= strlen(suffix
);
356 return suffixlen
< len
? strcmp(str
+ len
- suffixlen
, suffix
) : -1;
361 * Unicode / UTF-8 handling
363 * NOTE: Much of the following code for dealing with Unicode is derived from
364 * ELinks' UTF-8 code developed by Scrool <scroolik@gmail.com>. Origin file is
365 * src/intl/charset.c from the UTF-8 branch commit elinks-0.11.0-g31f2c28.
369 unicode_width(unsigned long c
, int tab_size
)
372 (c
<= 0x115f /* Hangul Jamo */
375 || (c
>= 0x2e80 && c
<= 0xa4cf && c
!= 0x303f)
377 || (c
>= 0xac00 && c
<= 0xd7a3) /* Hangul Syllables */
378 || (c
>= 0xf900 && c
<= 0xfaff) /* CJK Compatibility Ideographs */
379 || (c
>= 0xfe30 && c
<= 0xfe6f) /* CJK Compatibility Forms */
380 || (c
>= 0xff00 && c
<= 0xff60) /* Fullwidth Forms */
381 || (c
>= 0xffe0 && c
<= 0xffe6)
382 || (c
>= 0x20000 && c
<= 0x2fffd)
383 || (c
>= 0x30000 && c
<= 0x3fffd)))
392 /* Number of bytes used for encoding a UTF-8 character indexed by first byte.
393 * Illegal bytes are set one. */
394 static const unsigned char utf8_bytes
[256] = {
395 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
396 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
397 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
398 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
399 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
400 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
401 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,
402 3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4, 5,5,5,5,6,6,1,1,
405 static inline unsigned char
406 utf8_char_length(const char *string
, const char *end
)
408 int c
= *(unsigned char *) string
;
410 return utf8_bytes
[c
];
413 /* Decode UTF-8 multi-byte representation into a Unicode character. */
414 static inline unsigned long
415 utf8_to_unicode(const char *string
, size_t length
)
417 unsigned long unicode
;
424 unicode
= (string
[0] & 0x1f) << 6;
425 unicode
+= (string
[1] & 0x3f);
428 unicode
= (string
[0] & 0x0f) << 12;
429 unicode
+= ((string
[1] & 0x3f) << 6);
430 unicode
+= (string
[2] & 0x3f);
433 unicode
= (string
[0] & 0x0f) << 18;
434 unicode
+= ((string
[1] & 0x3f) << 12);
435 unicode
+= ((string
[2] & 0x3f) << 6);
436 unicode
+= (string
[3] & 0x3f);
439 unicode
= (string
[0] & 0x0f) << 24;
440 unicode
+= ((string
[1] & 0x3f) << 18);
441 unicode
+= ((string
[2] & 0x3f) << 12);
442 unicode
+= ((string
[3] & 0x3f) << 6);
443 unicode
+= (string
[4] & 0x3f);
446 unicode
= (string
[0] & 0x01) << 30;
447 unicode
+= ((string
[1] & 0x3f) << 24);
448 unicode
+= ((string
[2] & 0x3f) << 18);
449 unicode
+= ((string
[3] & 0x3f) << 12);
450 unicode
+= ((string
[4] & 0x3f) << 6);
451 unicode
+= (string
[5] & 0x3f);
457 /* Invalid characters could return the special 0xfffd value but NUL
458 * should be just as good. */
459 return unicode
> 0xffff ? 0 : unicode
;
462 /* Calculates how much of string can be shown within the given maximum width
463 * and sets trimmed parameter to non-zero value if all of string could not be
464 * shown. If the reserve flag is TRUE, it will reserve at least one
465 * trailing character, which can be useful when drawing a delimiter.
467 * Returns the number of bytes to output from string to satisfy max_width. */
469 utf8_length(const char **start
, size_t skip
, int *width
, size_t max_width
, int *trimmed
, bool reserve
, int tab_size
)
471 const char *string
= *start
;
472 const char *end
= strchr(string
, '\0');
473 unsigned char last_bytes
= 0;
474 size_t last_ucwidth
= 0;
479 while (string
< end
) {
480 unsigned char bytes
= utf8_char_length(string
, end
);
482 unsigned long unicode
;
484 if (string
+ bytes
> end
)
487 /* Change representation to figure out whether
488 * it is a single- or double-width character. */
490 unicode
= utf8_to_unicode(string
, bytes
);
491 /* FIXME: Graceful handling of invalid Unicode character. */
495 ucwidth
= unicode_width(unicode
, tab_size
);
497 skip
-= ucwidth
<= skip
? ucwidth
: skip
;
501 if (*width
> max_width
) {
504 if (reserve
&& *width
== max_width
) {
505 string
-= last_bytes
;
506 *width
-= last_ucwidth
;
512 last_bytes
= ucwidth
? bytes
: 0;
513 last_ucwidth
= ucwidth
;
516 return string
- *start
;
527 #define DATE_(name) DATE_##name
532 static const struct enum_map date_map
[] = {
533 #define DATE_(name) ENUM_MAP(#name, DATE_##name)
543 static inline int timecmp(const struct time
*t1
, const struct time
*t2
)
545 return t1
->sec
- t2
->sec
;
549 mkdate(const struct time
*time
, enum date date
)
551 static char buf
[DATE_COLS
+ 1];
552 static const struct enum_map reldate
[] = {
553 { "second", 1, 60 * 2 },
554 { "minute", 60, 60 * 60 * 2 },
555 { "hour", 60 * 60, 60 * 60 * 24 * 2 },
556 { "day", 60 * 60 * 24, 60 * 60 * 24 * 7 * 2 },
557 { "week", 60 * 60 * 24 * 7, 60 * 60 * 24 * 7 * 5 },
558 { "month", 60 * 60 * 24 * 30, 60 * 60 * 24 * 30 * 12 },
562 if (!date
|| !time
|| !time
->sec
)
565 if (date
== DATE_RELATIVE
) {
567 time_t date
= time
->sec
+ time
->tz
;
571 gettimeofday(&now
, NULL
);
572 seconds
= now
.tv_sec
< date
? date
- now
.tv_sec
: now
.tv_sec
- date
;
573 for (i
= 0; i
< ARRAY_SIZE(reldate
); i
++) {
574 if (seconds
>= reldate
[i
].value
)
577 seconds
/= reldate
[i
].namelen
;
578 if (!string_format(buf
, "%ld %s%s %s",
579 seconds
, reldate
[i
].name
,
580 seconds
> 1 ? "s" : "",
581 now
.tv_sec
>= date
? "ago" : "ahead"))
587 gmtime_r(&time
->sec
, &tm
);
588 return strftime(buf
, sizeof(buf
), DATE_FORMAT
, &tm
) ? buf
: NULL
;
592 #define AUTHOR_VALUES \
598 #define AUTHOR_(name) AUTHOR_##name
601 AUTHOR_DEFAULT
= AUTHOR_FULL
604 static const struct enum_map author_map
[] = {
605 #define AUTHOR_(name) ENUM_MAP(#name, AUTHOR_##name)
611 get_author_initials(const char *author
)
613 static char initials
[AUTHOR_COLS
* 6 + 1];
615 const char *end
= strchr(author
, '\0');
617 #define is_initial_sep(c) (isspace(c) || ispunct(c) || (c) == '@' || (c) == '-')
619 memset(initials
, 0, sizeof(initials
));
620 while (author
< end
) {
624 while (is_initial_sep(*author
))
627 bytes
= utf8_char_length(author
, end
);
628 if (bytes
< sizeof(initials
) - 1 - pos
) {
630 initials
[pos
++] = *author
++;
634 for (i
= pos
; author
< end
&& !is_initial_sep(*author
); author
++) {
635 if (i
< sizeof(initials
) - 1)
636 initials
[i
++] = *author
;
647 argv_from_string(const char *argv
[SIZEOF_ARG
], int *argc
, char *cmd
)
651 while (*cmd
&& *argc
< SIZEOF_ARG
&& (valuelen
= strcspn(cmd
, " \t"))) {
652 bool advance
= cmd
[valuelen
] != 0;
655 argv
[(*argc
)++] = chomp_string(cmd
);
656 cmd
= chomp_string(cmd
+ valuelen
+ advance
);
659 if (*argc
< SIZEOF_ARG
)
661 return *argc
< SIZEOF_ARG
;
665 argv_from_env(const char **argv
, const char *name
)
667 char *env
= argv
? getenv(name
) : NULL
;
672 if (env
&& !argv_from_string(argv
, &argc
, env
))
673 die("Too many arguments in the `%s` environment variable", name
);
678 * Executing external commands.
682 IO_FD
, /* File descriptor based IO. */
683 IO_BG
, /* Execute command in the background. */
684 IO_FG
, /* Execute command with same std{in,out,err}. */
685 IO_RD
, /* Read only fork+exec IO. */
686 IO_WR
, /* Write only fork+exec IO. */
687 IO_AP
, /* Append fork+exec output to file. */
691 enum io_type type
; /* The requested type of pipe. */
692 const char *dir
; /* Directory from which to execute. */
693 pid_t pid
; /* PID of spawned process. */
694 int pipe
; /* Pipe end for reading or writing. */
695 int error
; /* Error status. */
696 const char *argv
[SIZEOF_ARG
]; /* Shell command arguments. */
697 char *buf
; /* Read buffer. */
698 size_t bufalloc
; /* Allocated buffer size. */
699 size_t bufsize
; /* Buffer content size. */
700 char *bufpos
; /* Current buffer position. */
701 unsigned int eof
:1; /* Has end of file been reached. */
705 io_reset(struct io
*io
)
709 io
->buf
= io
->bufpos
= NULL
;
710 io
->bufalloc
= io
->bufsize
= 0;
716 io_init(struct io
*io
, const char *dir
, enum io_type type
)
724 io_format(struct io
*io
, const char *dir
, enum io_type type
,
725 const char *argv
[], enum format_flags flags
)
727 io_init(io
, dir
, type
);
728 return format_argv(io
->argv
, argv
, flags
);
732 io_open(struct io
*io
, const char *fmt
, ...)
734 char name
[SIZEOF_STR
] = "";
738 io_init(io
, NULL
, IO_FD
);
741 fits
= vsnprintf(name
, sizeof(name
), fmt
, args
) < sizeof(name
);
745 io
->error
= ENAMETOOLONG
;
748 io
->pipe
= *name
? open(name
, O_RDONLY
) : STDIN_FILENO
;
751 return io
->pipe
!= -1;
755 io_kill(struct io
*io
)
757 return io
->pid
== 0 || kill(io
->pid
, SIGKILL
) != -1;
761 io_done(struct io
*io
)
772 pid_t waiting
= waitpid(pid
, &status
, 0);
781 return waiting
== pid
&&
782 !WIFSIGNALED(status
) &&
784 !WEXITSTATUS(status
);
791 io_start(struct io
*io
)
793 int pipefds
[2] = { -1, -1 };
795 if (io
->type
== IO_FD
)
798 if ((io
->type
== IO_RD
|| io
->type
== IO_WR
) && pipe(pipefds
) < 0) {
801 } else if (io
->type
== IO_AP
) {
802 pipefds
[1] = io
->pipe
;
805 if ((io
->pid
= fork())) {
808 if (pipefds
[!(io
->type
== IO_WR
)] != -1)
809 close(pipefds
[!(io
->type
== IO_WR
)]);
811 io
->pipe
= pipefds
[!!(io
->type
== IO_WR
)];
816 if (io
->type
!= IO_FG
) {
817 int devnull
= open("/dev/null", O_RDWR
);
818 int readfd
= io
->type
== IO_WR
? pipefds
[0] : devnull
;
819 int writefd
= (io
->type
== IO_RD
|| io
->type
== IO_AP
)
820 ? pipefds
[1] : devnull
;
822 dup2(readfd
, STDIN_FILENO
);
823 dup2(writefd
, STDOUT_FILENO
);
824 dup2(devnull
, STDERR_FILENO
);
827 if (pipefds
[0] != -1)
829 if (pipefds
[1] != -1)
833 if (io
->dir
&& *io
->dir
&& chdir(io
->dir
) == -1)
836 execvp(io
->argv
[0], (char *const*) io
->argv
);
840 if (pipefds
[!!(io
->type
== IO_WR
)] != -1)
841 close(pipefds
[!!(io
->type
== IO_WR
)]);
846 io_run(struct io
*io
, const char **argv
, const char *dir
, enum io_type type
)
848 io_init(io
, dir
, type
);
849 if (!format_argv(io
->argv
, argv
, FORMAT_NONE
))
855 io_complete(struct io
*io
)
857 return io_start(io
) && io_done(io
);
861 io_run_bg(const char **argv
)
865 if (!io_format(&io
, NULL
, IO_BG
, argv
, FORMAT_NONE
))
867 return io_complete(&io
);
871 io_run_fg(const char **argv
, const char *dir
)
875 if (!io_format(&io
, dir
, IO_FG
, argv
, FORMAT_NONE
))
877 return io_complete(&io
);
881 io_run_append(const char **argv
, enum format_flags flags
, int fd
)
885 if (!io_format(&io
, NULL
, IO_AP
, argv
, flags
)) {
891 return io_complete(&io
);
895 io_run_rd(struct io
*io
, const char **argv
, const char *dir
, enum format_flags flags
)
897 return io_format(io
, dir
, IO_RD
, argv
, flags
) && io_start(io
);
901 io_eof(struct io
*io
)
907 io_error(struct io
*io
)
913 io_strerror(struct io
*io
)
915 return strerror(io
->error
);
919 io_can_read(struct io
*io
)
921 struct timeval tv
= { 0, 500 };
925 FD_SET(io
->pipe
, &fds
);
927 return select(io
->pipe
+ 1, &fds
, NULL
, NULL
, &tv
) > 0;
931 io_read(struct io
*io
, void *buf
, size_t bufsize
)
934 ssize_t readsize
= read(io
->pipe
, buf
, bufsize
);
936 if (readsize
< 0 && (errno
== EAGAIN
|| errno
== EINTR
))
938 else if (readsize
== -1)
940 else if (readsize
== 0)
946 DEFINE_ALLOCATOR(io_realloc_buf
, char, BUFSIZ
)
949 io_get(struct io
*io
, int c
, bool can_read
)
955 if (io
->bufsize
> 0) {
956 eol
= memchr(io
->bufpos
, c
, io
->bufsize
);
958 char *line
= io
->bufpos
;
961 io
->bufpos
= eol
+ 1;
962 io
->bufsize
-= io
->bufpos
- line
;
969 io
->bufpos
[io
->bufsize
] = 0;
979 if (io
->bufsize
> 0 && io
->bufpos
> io
->buf
)
980 memmove(io
->buf
, io
->bufpos
, io
->bufsize
);
982 if (io
->bufalloc
== io
->bufsize
) {
983 if (!io_realloc_buf(&io
->buf
, io
->bufalloc
, BUFSIZ
))
985 io
->bufalloc
+= BUFSIZ
;
988 io
->bufpos
= io
->buf
;
989 readsize
= io_read(io
, io
->buf
+ io
->bufsize
, io
->bufalloc
- io
->bufsize
);
992 io
->bufsize
+= readsize
;
997 io_write(struct io
*io
, const void *buf
, size_t bufsize
)
1001 while (!io_error(io
) && written
< bufsize
) {
1004 size
= write(io
->pipe
, buf
+ written
, bufsize
- written
);
1005 if (size
< 0 && (errno
== EAGAIN
|| errno
== EINTR
))
1007 else if (size
== -1)
1013 return written
== bufsize
;
1017 io_read_buf(struct io
*io
, char buf
[], size_t bufsize
)
1019 char *result
= io_get(io
, '\n', TRUE
);
1022 result
= chomp_string(result
);
1023 string_ncopy_do(buf
, bufsize
, result
, strlen(result
));
1026 return io_done(io
) && result
;
1030 io_run_buf(const char **argv
, char buf
[], size_t bufsize
)
1034 return io_run_rd(&io
, argv
, NULL
, FORMAT_NONE
)
1035 && io_read_buf(&io
, buf
, bufsize
);
1039 io_load(struct io
*io
, const char *separators
,
1040 int (*read_property
)(char *, size_t, char *, size_t))
1048 while (state
== OK
&& (name
= io_get(io
, '\n', TRUE
))) {
1053 name
= chomp_string(name
);
1054 namelen
= strcspn(name
, separators
);
1056 if (name
[namelen
]) {
1058 value
= chomp_string(name
+ namelen
+ 1);
1059 valuelen
= strlen(value
);
1066 state
= read_property(name
, namelen
, value
, valuelen
);
1069 if (state
!= ERR
&& io_error(io
))
1077 io_run_load(const char **argv
, const char *separators
,
1078 int (*read_property
)(char *, size_t, char *, size_t))
1082 return io_format(&io
, NULL
, IO_RD
, argv
, FORMAT_NONE
)
1083 ? io_load(&io
, separators
, read_property
) : ERR
;
1092 /* XXX: Keep the view request first and in sync with views[]. */ \
1093 REQ_GROUP("View switching") \
1094 REQ_(VIEW_MAIN, "Show main view"), \
1095 REQ_(VIEW_DIFF, "Show diff view"), \
1096 REQ_(VIEW_LOG, "Show log view"), \
1097 REQ_(VIEW_TREE, "Show tree view"), \
1098 REQ_(VIEW_BLOB, "Show blob view"), \
1099 REQ_(VIEW_BLAME, "Show blame view"), \
1100 REQ_(VIEW_BRANCH, "Show branch view"), \
1101 REQ_(VIEW_HELP, "Show help page"), \
1102 REQ_(VIEW_PAGER, "Show pager view"), \
1103 REQ_(VIEW_STATUS, "Show status view"), \
1104 REQ_(VIEW_STAGE, "Show stage view"), \
1106 REQ_GROUP("View manipulation") \
1107 REQ_(ENTER, "Enter current line and scroll"), \
1108 REQ_(NEXT, "Move to next"), \
1109 REQ_(PREVIOUS, "Move to previous"), \
1110 REQ_(PARENT, "Move to parent"), \
1111 REQ_(VIEW_NEXT, "Move focus to next view"), \
1112 REQ_(REFRESH, "Reload and refresh"), \
1113 REQ_(MAXIMIZE, "Maximize the current view"), \
1114 REQ_(VIEW_CLOSE, "Close the current view"), \
1115 REQ_(QUIT, "Close all views and quit"), \
1117 REQ_GROUP("View specific requests") \
1118 REQ_(STATUS_UPDATE, "Update file status"), \
1119 REQ_(STATUS_REVERT, "Revert file changes"), \
1120 REQ_(STATUS_MERGE, "Merge file using external tool"), \
1121 REQ_(STAGE_NEXT, "Find next chunk to stage"), \
1123 REQ_GROUP("Cursor navigation") \
1124 REQ_(MOVE_UP, "Move cursor one line up"), \
1125 REQ_(MOVE_DOWN, "Move cursor one line down"), \
1126 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
1127 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
1128 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
1129 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
1131 REQ_GROUP("Scrolling") \
1132 REQ_(SCROLL_LEFT, "Scroll two columns left"), \
1133 REQ_(SCROLL_RIGHT, "Scroll two columns right"), \
1134 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
1135 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
1136 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
1137 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
1139 REQ_GROUP("Searching") \
1140 REQ_(SEARCH, "Search the view"), \
1141 REQ_(SEARCH_BACK, "Search backwards in the view"), \
1142 REQ_(FIND_NEXT, "Find next search match"), \
1143 REQ_(FIND_PREV, "Find previous search match"), \
1145 REQ_GROUP("Option manipulation") \
1146 REQ_(OPTIONS, "Open option menu"), \
1147 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
1148 REQ_(TOGGLE_DATE, "Toggle date display"), \
1149 REQ_(TOGGLE_DATE_SHORT, "Toggle short (date-only) dates"), \
1150 REQ_(TOGGLE_AUTHOR, "Toggle author display"), \
1151 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization"), \
1152 REQ_(TOGGLE_REFS, "Toggle reference display (tags/branches)"), \
1153 REQ_(TOGGLE_SORT_ORDER, "Toggle ascending/descending sort order"), \
1154 REQ_(TOGGLE_SORT_FIELD, "Toggle field to sort by"), \
1157 REQ_(PROMPT, "Bring up the prompt"), \
1158 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
1159 REQ_(SHOW_VERSION, "Show version information"), \
1160 REQ_(STOP_LOADING, "Stop all loading views"), \
1161 REQ_(EDIT, "Open in editor"), \
1162 REQ_(NONE, "Do nothing")
1165 /* User action requests. */
1167 #define REQ_GROUP(help)
1168 #define REQ_(req, help) REQ_##req
1170 /* Offset all requests to avoid conflicts with ncurses getch values. */
1171 REQ_OFFSET
= KEY_MAX
+ 1,
1178 struct request_info
{
1179 enum request request
;
1185 static const struct request_info req_info
[] = {
1186 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
1187 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
1194 get_request(const char *name
)
1196 int namelen
= strlen(name
);
1199 for (i
= 0; i
< ARRAY_SIZE(req_info
); i
++)
1200 if (enum_equals(req_info
[i
], name
, namelen
))
1201 return req_info
[i
].request
;
1211 /* Option and state variables. */
1212 static enum date opt_date
= DATE_DEFAULT
;
1213 static enum author opt_author
= AUTHOR_DEFAULT
;
1214 static bool opt_line_number
= FALSE
;
1215 static bool opt_line_graphics
= TRUE
;
1216 static bool opt_rev_graph
= FALSE
;
1217 static bool opt_show_refs
= TRUE
;
1218 static int opt_num_interval
= 5;
1219 static double opt_hscroll
= 0.50;
1220 static double opt_scale_split_view
= 2.0 / 3.0;
1221 static int opt_tab_size
= 8;
1222 static int opt_author_cols
= AUTHOR_COLS
;
1223 static char opt_path
[SIZEOF_STR
] = "";
1224 static char opt_file
[SIZEOF_STR
] = "";
1225 static char opt_ref
[SIZEOF_REF
] = "";
1226 static char opt_head
[SIZEOF_REF
] = "";
1227 static char opt_remote
[SIZEOF_REF
] = "";
1228 static char opt_encoding
[20] = "UTF-8";
1229 static iconv_t opt_iconv_in
= ICONV_NONE
;
1230 static iconv_t opt_iconv_out
= ICONV_NONE
;
1231 static char opt_search
[SIZEOF_STR
] = "";
1232 static char opt_cdup
[SIZEOF_STR
] = "";
1233 static char opt_prefix
[SIZEOF_STR
] = "";
1234 static char opt_git_dir
[SIZEOF_STR
] = "";
1235 static signed char opt_is_inside_work_tree
= -1; /* set to TRUE or FALSE */
1236 static char opt_editor
[SIZEOF_STR
] = "";
1237 static FILE *opt_tty
= NULL
;
1239 #define is_initial_commit() (!get_ref_head())
1240 #define is_head_commit(rev) (!strcmp((rev), "HEAD") || (get_ref_head() && !strcmp(rev, get_ref_head()->id)))
1244 * Line-oriented content detection.
1248 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1249 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1250 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
1251 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
1252 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
1253 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1254 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1255 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1256 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1257 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1258 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1259 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1260 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1261 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
1262 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
1263 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1264 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
1265 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1266 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1267 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1268 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
1269 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
1270 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
1271 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
1272 LINE(AUTHOR, "author ", COLOR_GREEN, COLOR_DEFAULT, 0), \
1273 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1274 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1275 LINE(ACKED, " Acked-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1276 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
1277 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
1278 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
1279 LINE(DELIMITER, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1280 LINE(DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
1281 LINE(MODE, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
1282 LINE(LINE_NUMBER, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
1283 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
1284 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
1285 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
1286 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
1287 LINE(MAIN_LOCAL_TAG,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1288 LINE(MAIN_REMOTE, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1289 LINE(MAIN_TRACKED, "", COLOR_YELLOW, COLOR_DEFAULT, A_BOLD), \
1290 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
1291 LINE(MAIN_HEAD, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
1292 LINE(MAIN_REVGRAPH,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1293 LINE(TREE_HEAD, "", COLOR_DEFAULT, COLOR_DEFAULT, A_BOLD), \
1294 LINE(TREE_DIR, "", COLOR_YELLOW, COLOR_DEFAULT, A_NORMAL), \
1295 LINE(TREE_FILE, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
1296 LINE(STAT_HEAD, "", COLOR_YELLOW, COLOR_DEFAULT, 0), \
1297 LINE(STAT_SECTION, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
1298 LINE(STAT_NONE, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
1299 LINE(STAT_STAGED, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1300 LINE(STAT_UNSTAGED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1301 LINE(STAT_UNTRACKED,"", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
1302 LINE(HELP_KEYMAP, "", COLOR_CYAN, COLOR_DEFAULT, 0), \
1303 LINE(HELP_GROUP, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
1304 LINE(BLAME_ID, "", COLOR_MAGENTA, COLOR_DEFAULT, 0)
1307 #define LINE(type, line, fg, bg, attr) \
1315 const char *name
; /* Option name. */
1316 int namelen
; /* Size of option name. */
1317 const char *line
; /* The start of line to match. */
1318 int linelen
; /* Size of string to match. */
1319 int fg
, bg
, attr
; /* Color and text attributes for the lines. */
1322 static struct line_info line_info
[] = {
1323 #define LINE(type, line, fg, bg, attr) \
1324 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
1329 static enum line_type
1330 get_line_type(const char *line
)
1332 int linelen
= strlen(line
);
1333 enum line_type type
;
1335 for (type
= 0; type
< ARRAY_SIZE(line_info
); type
++)
1336 /* Case insensitive search matches Signed-off-by lines better. */
1337 if (linelen
>= line_info
[type
].linelen
&&
1338 !strncasecmp(line_info
[type
].line
, line
, line_info
[type
].linelen
))
1341 return LINE_DEFAULT
;
1345 get_line_attr(enum line_type type
)
1347 assert(type
< ARRAY_SIZE(line_info
));
1348 return COLOR_PAIR(type
) | line_info
[type
].attr
;
1351 static struct line_info
*
1352 get_line_info(const char *name
)
1354 size_t namelen
= strlen(name
);
1355 enum line_type type
;
1357 for (type
= 0; type
< ARRAY_SIZE(line_info
); type
++)
1358 if (enum_equals(line_info
[type
], name
, namelen
))
1359 return &line_info
[type
];
1367 int default_bg
= line_info
[LINE_DEFAULT
].bg
;
1368 int default_fg
= line_info
[LINE_DEFAULT
].fg
;
1369 enum line_type type
;
1373 if (assume_default_colors(default_fg
, default_bg
) == ERR
) {
1374 default_bg
= COLOR_BLACK
;
1375 default_fg
= COLOR_WHITE
;
1378 for (type
= 0; type
< ARRAY_SIZE(line_info
); type
++) {
1379 struct line_info
*info
= &line_info
[type
];
1380 int bg
= info
->bg
== COLOR_DEFAULT
? default_bg
: info
->bg
;
1381 int fg
= info
->fg
== COLOR_DEFAULT
? default_fg
: info
->fg
;
1383 init_pair(type
, fg
, bg
);
1388 enum line_type type
;
1391 unsigned int selected
:1;
1392 unsigned int dirty
:1;
1393 unsigned int cleareol
:1;
1394 unsigned int other
:16;
1396 void *data
; /* User data */
1406 enum request request
;
1409 static const struct keybinding default_keybindings
[] = {
1410 /* View switching */
1411 { 'm', REQ_VIEW_MAIN
},
1412 { 'd', REQ_VIEW_DIFF
},
1413 { 'l', REQ_VIEW_LOG
},
1414 { 't', REQ_VIEW_TREE
},
1415 { 'f', REQ_VIEW_BLOB
},
1416 { 'B', REQ_VIEW_BLAME
},
1417 { 'H', REQ_VIEW_BRANCH
},
1418 { 'p', REQ_VIEW_PAGER
},
1419 { 'h', REQ_VIEW_HELP
},
1420 { 'S', REQ_VIEW_STATUS
},
1421 { 'c', REQ_VIEW_STAGE
},
1423 /* View manipulation */
1424 { 'q', REQ_VIEW_CLOSE
},
1425 { KEY_TAB
, REQ_VIEW_NEXT
},
1426 { KEY_RETURN
, REQ_ENTER
},
1427 { KEY_UP
, REQ_PREVIOUS
},
1428 { KEY_DOWN
, REQ_NEXT
},
1429 { 'R', REQ_REFRESH
},
1430 { KEY_F(5), REQ_REFRESH
},
1431 { 'O', REQ_MAXIMIZE
},
1433 /* Cursor navigation */
1434 { 'k', REQ_MOVE_UP
},
1435 { 'j', REQ_MOVE_DOWN
},
1436 { KEY_HOME
, REQ_MOVE_FIRST_LINE
},
1437 { KEY_END
, REQ_MOVE_LAST_LINE
},
1438 { KEY_NPAGE
, REQ_MOVE_PAGE_DOWN
},
1439 { ' ', REQ_MOVE_PAGE_DOWN
},
1440 { KEY_PPAGE
, REQ_MOVE_PAGE_UP
},
1441 { 'b', REQ_MOVE_PAGE_UP
},
1442 { '-', REQ_MOVE_PAGE_UP
},
1445 { KEY_LEFT
, REQ_SCROLL_LEFT
},
1446 { KEY_RIGHT
, REQ_SCROLL_RIGHT
},
1447 { KEY_IC
, REQ_SCROLL_LINE_UP
},
1448 { KEY_DC
, REQ_SCROLL_LINE_DOWN
},
1449 { 'w', REQ_SCROLL_PAGE_UP
},
1450 { 's', REQ_SCROLL_PAGE_DOWN
},
1453 { '/', REQ_SEARCH
},
1454 { '?', REQ_SEARCH_BACK
},
1455 { 'n', REQ_FIND_NEXT
},
1456 { 'N', REQ_FIND_PREV
},
1460 { 'z', REQ_STOP_LOADING
},
1461 { 'v', REQ_SHOW_VERSION
},
1462 { 'r', REQ_SCREEN_REDRAW
},
1463 { 'o', REQ_OPTIONS
},
1464 { '.', REQ_TOGGLE_LINENO
},
1465 { 'D', REQ_TOGGLE_DATE
},
1466 { 'A', REQ_TOGGLE_AUTHOR
},
1467 { 'g', REQ_TOGGLE_REV_GRAPH
},
1468 { 'F', REQ_TOGGLE_REFS
},
1469 { 'I', REQ_TOGGLE_SORT_ORDER
},
1470 { 'i', REQ_TOGGLE_SORT_FIELD
},
1471 { ':', REQ_PROMPT
},
1472 { 'u', REQ_STATUS_UPDATE
},
1473 { '!', REQ_STATUS_REVERT
},
1474 { 'M', REQ_STATUS_MERGE
},
1475 { '@', REQ_STAGE_NEXT
},
1476 { ',', REQ_PARENT
},
1480 #define KEYMAP_INFO \
1495 #define KEYMAP_(name) KEYMAP_##name
1500 static const struct enum_map keymap_table
[] = {
1501 #define KEYMAP_(name) ENUM_MAP(#name, KEYMAP_##name)
1506 #define set_keymap(map, name) map_enum(map, keymap_table, name)
1508 struct keybinding_table
{
1509 struct keybinding
*data
;
1513 static struct keybinding_table keybindings
[ARRAY_SIZE(keymap_table
)];
1516 add_keybinding(enum keymap keymap
, enum request request
, int key
)
1518 struct keybinding_table
*table
= &keybindings
[keymap
];
1520 table
->data
= realloc(table
->data
, (table
->size
+ 1) * sizeof(*table
->data
));
1522 die("Failed to allocate keybinding");
1523 table
->data
[table
->size
].alias
= key
;
1524 table
->data
[table
->size
++].request
= request
;
1527 /* Looks for a key binding first in the given map, then in the generic map, and
1528 * lastly in the default keybindings. */
1530 get_keybinding(enum keymap keymap
, int key
)
1534 for (i
= 0; i
< keybindings
[keymap
].size
; i
++)
1535 if (keybindings
[keymap
].data
[i
].alias
== key
)
1536 return keybindings
[keymap
].data
[i
].request
;
1538 for (i
= 0; i
< keybindings
[KEYMAP_GENERIC
].size
; i
++)
1539 if (keybindings
[KEYMAP_GENERIC
].data
[i
].alias
== key
)
1540 return keybindings
[KEYMAP_GENERIC
].data
[i
].request
;
1542 for (i
= 0; i
< ARRAY_SIZE(default_keybindings
); i
++)
1543 if (default_keybindings
[i
].alias
== key
)
1544 return default_keybindings
[i
].request
;
1546 return (enum request
) key
;
1555 static const struct key key_table
[] = {
1556 { "Enter", KEY_RETURN
},
1558 { "Backspace", KEY_BACKSPACE
},
1560 { "Escape", KEY_ESC
},
1561 { "Left", KEY_LEFT
},
1562 { "Right", KEY_RIGHT
},
1564 { "Down", KEY_DOWN
},
1565 { "Insert", KEY_IC
},
1566 { "Delete", KEY_DC
},
1568 { "Home", KEY_HOME
},
1570 { "PageUp", KEY_PPAGE
},
1571 { "PageDown", KEY_NPAGE
},
1581 { "F10", KEY_F(10) },
1582 { "F11", KEY_F(11) },
1583 { "F12", KEY_F(12) },
1587 get_key_value(const char *name
)
1591 for (i
= 0; i
< ARRAY_SIZE(key_table
); i
++)
1592 if (!strcasecmp(key_table
[i
].name
, name
))
1593 return key_table
[i
].value
;
1595 if (strlen(name
) == 1 && isprint(*name
))
1602 get_key_name(int key_value
)
1604 static char key_char
[] = "'X'";
1605 const char *seq
= NULL
;
1608 for (key
= 0; key
< ARRAY_SIZE(key_table
); key
++)
1609 if (key_table
[key
].value
== key_value
)
1610 seq
= key_table
[key
].name
;
1614 isprint(key_value
)) {
1615 key_char
[1] = (char) key_value
;
1619 return seq
? seq
: "(no key)";
1623 append_key(char *buf
, size_t *pos
, const struct keybinding
*keybinding
)
1625 const char *sep
= *pos
> 0 ? ", " : "";
1626 const char *keyname
= get_key_name(keybinding
->alias
);
1628 return string_nformat(buf
, BUFSIZ
, pos
, "%s%s", sep
, keyname
);
1632 append_keymap_request_keys(char *buf
, size_t *pos
, enum request request
,
1633 enum keymap keymap
, bool all
)
1637 for (i
= 0; i
< keybindings
[keymap
].size
; i
++) {
1638 if (keybindings
[keymap
].data
[i
].request
== request
) {
1639 if (!append_key(buf
, pos
, &keybindings
[keymap
].data
[i
]))
1649 #define get_key(keymap, request) get_keys(keymap, request, FALSE)
1652 get_keys(enum keymap keymap
, enum request request
, bool all
)
1654 static char buf
[BUFSIZ
];
1660 if (!append_keymap_request_keys(buf
, &pos
, request
, keymap
, all
))
1661 return "Too many keybindings!";
1662 if (pos
> 0 && !all
)
1665 if (keymap
!= KEYMAP_GENERIC
) {
1666 /* Only the generic keymap includes the default keybindings when
1667 * listing all keys. */
1671 if (!append_keymap_request_keys(buf
, &pos
, request
, KEYMAP_GENERIC
, all
))
1672 return "Too many keybindings!";
1677 for (i
= 0; i
< ARRAY_SIZE(default_keybindings
); i
++) {
1678 if (default_keybindings
[i
].request
== request
) {
1679 if (!append_key(buf
, &pos
, &default_keybindings
[i
]))
1680 return "Too many keybindings!";
1689 struct run_request
{
1692 const char *argv
[SIZEOF_ARG
];
1695 static struct run_request
*run_request
;
1696 static size_t run_requests
;
1698 DEFINE_ALLOCATOR(realloc_run_requests
, struct run_request
, 8)
1701 add_run_request(enum keymap keymap
, int key
, int argc
, const char **argv
)
1703 struct run_request
*req
;
1705 if (argc
>= ARRAY_SIZE(req
->argv
) - 1)
1708 if (!realloc_run_requests(&run_request
, run_requests
, 1))
1711 req
= &run_request
[run_requests
];
1712 req
->keymap
= keymap
;
1714 req
->argv
[0] = NULL
;
1716 if (!format_argv(req
->argv
, argv
, FORMAT_NONE
))
1719 return REQ_NONE
+ ++run_requests
;
1722 static struct run_request
*
1723 get_run_request(enum request request
)
1725 if (request
<= REQ_NONE
)
1727 return &run_request
[request
- REQ_NONE
- 1];
1731 add_builtin_run_requests(void)
1733 const char *cherry_pick
[] = { "git", "cherry-pick", "%(commit)", NULL
};
1734 const char *commit
[] = { "git", "commit", NULL
};
1735 const char *gc
[] = { "git", "gc", NULL
};
1742 { KEYMAP_MAIN
, 'C', ARRAY_SIZE(cherry_pick
) - 1, cherry_pick
},
1743 { KEYMAP_STATUS
, 'C', ARRAY_SIZE(commit
) - 1, commit
},
1744 { KEYMAP_GENERIC
, 'G', ARRAY_SIZE(gc
) - 1, gc
},
1748 for (i
= 0; i
< ARRAY_SIZE(reqs
); i
++) {
1751 req
= add_run_request(reqs
[i
].keymap
, reqs
[i
].key
, reqs
[i
].argc
, reqs
[i
].argv
);
1752 if (req
!= REQ_NONE
)
1753 add_keybinding(reqs
[i
].keymap
, req
, reqs
[i
].key
);
1758 * User config file handling.
1761 static int config_lineno
;
1762 static bool config_errors
;
1763 static const char *config_msg
;
1765 static const struct enum_map color_map
[] = {
1766 #define COLOR_MAP(name) ENUM_MAP(#name, COLOR_##name)
1778 static const struct enum_map attr_map
[] = {
1779 #define ATTR_MAP(name) ENUM_MAP(#name, A_##name)
1786 ATTR_MAP(UNDERLINE
),
1789 #define set_attribute(attr, name) map_enum(attr, attr_map, name)
1791 static int parse_step(double *opt
, const char *arg
)
1794 if (!strchr(arg
, '%'))
1797 /* "Shift down" so 100% and 1 does not conflict. */
1798 *opt
= (*opt
- 1) / 100;
1801 config_msg
= "Step value larger than 100%";
1806 config_msg
= "Invalid step value";
1813 parse_int(int *opt
, const char *arg
, int min
, int max
)
1815 int value
= atoi(arg
);
1817 if (min
<= value
&& value
<= max
) {
1822 config_msg
= "Integer value out of bound";
1827 set_color(int *color
, const char *name
)
1829 if (map_enum(color
, color_map
, name
))
1831 if (!prefixcmp(name
, "color"))
1832 return parse_int(color
, name
+ 5, 0, 255) == OK
;
1836 /* Wants: object fgcolor bgcolor [attribute] */
1838 option_color_command(int argc
, const char *argv
[])
1840 struct line_info
*info
;
1843 config_msg
= "Wrong number of arguments given to color command";
1847 info
= get_line_info(argv
[0]);
1849 static const struct enum_map obsolete
[] = {
1850 ENUM_MAP("main-delim", LINE_DELIMITER
),
1851 ENUM_MAP("main-date", LINE_DATE
),
1852 ENUM_MAP("main-author", LINE_AUTHOR
),
1856 if (!map_enum(&index
, obsolete
, argv
[0])) {
1857 config_msg
= "Unknown color name";
1860 info
= &line_info
[index
];
1863 if (!set_color(&info
->fg
, argv
[1]) ||
1864 !set_color(&info
->bg
, argv
[2])) {
1865 config_msg
= "Unknown color";
1870 while (argc
-- > 3) {
1873 if (!set_attribute(&attr
, argv
[argc
])) {
1874 config_msg
= "Unknown attribute";
1883 static int parse_bool(bool *opt
, const char *arg
)
1885 *opt
= (!strcmp(arg
, "1") || !strcmp(arg
, "true") || !strcmp(arg
, "yes"))
1890 static int parse_enum_do(unsigned int *opt
, const char *arg
,
1891 const struct enum_map
*map
, size_t map_size
)
1895 assert(map_size
> 1);
1897 if (map_enum_do(map
, map_size
, (int *) opt
, arg
))
1900 if (parse_bool(&is_true
, arg
) != OK
)
1903 *opt
= is_true
? map
[1].value
: map
[0].value
;
1907 #define parse_enum(opt, arg, map) \
1908 parse_enum_do(opt, arg, map, ARRAY_SIZE(map))
1911 parse_string(char *opt
, const char *arg
, size_t optsize
)
1913 int arglen
= strlen(arg
);
1918 if (arglen
== 1 || arg
[arglen
- 1] != arg
[0]) {
1919 config_msg
= "Unmatched quotation";
1922 arg
+= 1; arglen
-= 2;
1924 string_ncopy_do(opt
, optsize
, arg
, arglen
);
1929 /* Wants: name = value */
1931 option_set_command(int argc
, const char *argv
[])
1934 config_msg
= "Wrong number of arguments given to set command";
1938 if (strcmp(argv
[1], "=")) {
1939 config_msg
= "No value assigned";
1943 if (!strcmp(argv
[0], "show-author"))
1944 return parse_enum(&opt_author
, argv
[2], author_map
);
1946 if (!strcmp(argv
[0], "show-date"))
1947 return parse_enum(&opt_date
, argv
[2], date_map
);
1949 if (!strcmp(argv
[0], "show-rev-graph"))
1950 return parse_bool(&opt_rev_graph
, argv
[2]);
1952 if (!strcmp(argv
[0], "show-refs"))
1953 return parse_bool(&opt_show_refs
, argv
[2]);
1955 if (!strcmp(argv
[0], "show-line-numbers"))
1956 return parse_bool(&opt_line_number
, argv
[2]);
1958 if (!strcmp(argv
[0], "line-graphics"))
1959 return parse_bool(&opt_line_graphics
, argv
[2]);
1961 if (!strcmp(argv
[0], "line-number-interval"))
1962 return parse_int(&opt_num_interval
, argv
[2], 1, 1024);
1964 if (!strcmp(argv
[0], "author-width"))
1965 return parse_int(&opt_author_cols
, argv
[2], 0, 1024);
1967 if (!strcmp(argv
[0], "horizontal-scroll"))
1968 return parse_step(&opt_hscroll
, argv
[2]);
1970 if (!strcmp(argv
[0], "split-view-height"))
1971 return parse_step(&opt_scale_split_view
, argv
[2]);
1973 if (!strcmp(argv
[0], "tab-size"))
1974 return parse_int(&opt_tab_size
, argv
[2], 1, 1024);
1976 if (!strcmp(argv
[0], "commit-encoding"))
1977 return parse_string(opt_encoding
, argv
[2], sizeof(opt_encoding
));
1979 config_msg
= "Unknown variable name";
1983 /* Wants: mode request key */
1985 option_bind_command(int argc
, const char *argv
[])
1987 enum request request
;
1992 config_msg
= "Wrong number of arguments given to bind command";
1996 if (set_keymap(&keymap
, argv
[0]) == ERR
) {
1997 config_msg
= "Unknown key map";
2001 key
= get_key_value(argv
[1]);
2003 config_msg
= "Unknown key";
2007 request
= get_request(argv
[2]);
2008 if (request
== REQ_NONE
) {
2009 static const struct enum_map obsolete
[] = {
2010 ENUM_MAP("cherry-pick", REQ_NONE
),
2011 ENUM_MAP("screen-resize", REQ_NONE
),
2012 ENUM_MAP("tree-parent", REQ_PARENT
),
2016 if (map_enum(&alias
, obsolete
, argv
[2])) {
2017 if (alias
!= REQ_NONE
)
2018 add_keybinding(keymap
, alias
, key
);
2019 config_msg
= "Obsolete request name";
2023 if (request
== REQ_NONE
&& *argv
[2]++ == '!')
2024 request
= add_run_request(keymap
, key
, argc
- 2, argv
+ 2);
2025 if (request
== REQ_NONE
) {
2026 config_msg
= "Unknown request name";
2030 add_keybinding(keymap
, request
, key
);
2036 set_option(const char *opt
, char *value
)
2038 const char *argv
[SIZEOF_ARG
];
2041 if (!argv_from_string(argv
, &argc
, value
)) {
2042 config_msg
= "Too many option arguments";
2046 if (!strcmp(opt
, "color"))
2047 return option_color_command(argc
, argv
);
2049 if (!strcmp(opt
, "set"))
2050 return option_set_command(argc
, argv
);
2052 if (!strcmp(opt
, "bind"))
2053 return option_bind_command(argc
, argv
);
2055 config_msg
= "Unknown option command";
2060 read_option(char *opt
, size_t optlen
, char *value
, size_t valuelen
)
2065 config_msg
= "Internal error";
2067 /* Check for comment markers, since read_properties() will
2068 * only ensure opt and value are split at first " \t". */
2069 optlen
= strcspn(opt
, "#");
2073 if (opt
[optlen
] != 0) {
2074 config_msg
= "No option value";
2078 /* Look for comment endings in the value. */
2079 size_t len
= strcspn(value
, "#");
2081 if (len
< valuelen
) {
2083 value
[valuelen
] = 0;
2086 status
= set_option(opt
, value
);
2089 if (status
== ERR
) {
2090 warn("Error on line %d, near '%.*s': %s",
2091 config_lineno
, (int) optlen
, opt
, config_msg
);
2092 config_errors
= TRUE
;
2095 /* Always keep going if errors are encountered. */
2100 load_option_file(const char *path
)
2104 /* It's OK that the file doesn't exist. */
2105 if (!io_open(&io
, "%s", path
))
2109 config_errors
= FALSE
;
2111 if (io_load(&io
, " \t", read_option
) == ERR
||
2112 config_errors
== TRUE
)
2113 warn("Errors while loading %s.", path
);
2119 const char *home
= getenv("HOME");
2120 const char *tigrc_user
= getenv("TIGRC_USER");
2121 const char *tigrc_system
= getenv("TIGRC_SYSTEM");
2122 char buf
[SIZEOF_STR
];
2124 add_builtin_run_requests();
2127 tigrc_system
= SYSCONFDIR
"/tigrc";
2128 load_option_file(tigrc_system
);
2131 if (!home
|| !string_format(buf
, "%s/.tigrc", home
))
2135 load_option_file(tigrc_user
);
2148 /* The display array of active views and the index of the current view. */
2149 static struct view
*display
[2];
2150 static unsigned int current_view
;
2152 #define foreach_displayed_view(view, i) \
2153 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
2155 #define displayed_views() (display[1] != NULL ? 2 : 1)
2157 /* Current head and commit ID */
2158 static char ref_blob
[SIZEOF_REF
] = "";
2159 static char ref_commit
[SIZEOF_REF
] = "HEAD";
2160 static char ref_head
[SIZEOF_REF
] = "HEAD";
2163 const char *name
; /* View name */
2164 const char *cmd_env
; /* Command line set via environment */
2165 const char *id
; /* Points to either of ref_{head,commit,blob} */
2167 struct view_ops
*ops
; /* View operations */
2169 enum keymap keymap
; /* What keymap does this view have */
2170 bool git_dir
; /* Whether the view requires a git directory. */
2172 char ref
[SIZEOF_REF
]; /* Hovered commit reference */
2173 char vid
[SIZEOF_REF
]; /* View ID. Set to id member when updating. */
2175 int height
, width
; /* The width and height of the main window */
2176 WINDOW
*win
; /* The main window */
2177 WINDOW
*title
; /* The title window living below the main window */
2180 unsigned long offset
; /* Offset of the window top */
2181 unsigned long yoffset
; /* Offset from the window side. */
2182 unsigned long lineno
; /* Current line number */
2183 unsigned long p_offset
; /* Previous offset of the window top */
2184 unsigned long p_yoffset
;/* Previous offset from the window side */
2185 unsigned long p_lineno
; /* Previous current line number */
2186 bool p_restore
; /* Should the previous position be restored. */
2189 char grep
[SIZEOF_STR
]; /* Search string */
2190 regex_t
*regex
; /* Pre-compiled regexp */
2192 /* If non-NULL, points to the view that opened this view. If this view
2193 * is closed tig will switch back to the parent view. */
2194 struct view
*parent
;
2197 size_t lines
; /* Total number of lines */
2198 struct line
*line
; /* Line index */
2199 unsigned int digits
; /* Number of digits in the lines member. */
2202 struct line
*curline
; /* Line currently being drawn. */
2203 enum line_type curtype
; /* Attribute currently used for drawing. */
2204 unsigned long col
; /* Column when drawing. */
2205 bool has_scrolled
; /* View was scrolled. */
2215 /* What type of content being displayed. Used in the title bar. */
2217 /* Default command arguments. */
2219 /* Open and reads in all view content. */
2220 bool (*open
)(struct view
*view
);
2221 /* Read one line; updates view->line. */
2222 bool (*read
)(struct view
*view
, char *data
);
2223 /* Draw one line; @lineno must be < view->height. */
2224 bool (*draw
)(struct view
*view
, struct line
*line
, unsigned int lineno
);
2225 /* Depending on view handle a special requests. */
2226 enum request (*request
)(struct view
*view
, enum request request
, struct line
*line
);
2227 /* Search for regexp in a line. */
2228 bool (*grep
)(struct view
*view
, struct line
*line
);
2230 void (*select
)(struct view
*view
, struct line
*line
);
2231 /* Prepare view for loading */
2232 bool (*prepare
)(struct view
*view
);
2235 static struct view_ops blame_ops
;
2236 static struct view_ops blob_ops
;
2237 static struct view_ops diff_ops
;
2238 static struct view_ops help_ops
;
2239 static struct view_ops log_ops
;
2240 static struct view_ops main_ops
;
2241 static struct view_ops pager_ops
;
2242 static struct view_ops stage_ops
;
2243 static struct view_ops status_ops
;
2244 static struct view_ops tree_ops
;
2245 static struct view_ops branch_ops
;
2247 #define VIEW_STR(name, env, ref, ops, map, git) \
2248 { name, #env, ref, ops, map, git }
2250 #define VIEW_(id, name, ops, git, ref) \
2251 VIEW_STR(name, TIG_##id##_CMD, ref, ops, KEYMAP_##id, git)
2254 static struct view views
[] = {
2255 VIEW_(MAIN
, "main", &main_ops
, TRUE
, ref_head
),
2256 VIEW_(DIFF
, "diff", &diff_ops
, TRUE
, ref_commit
),
2257 VIEW_(LOG
, "log", &log_ops
, TRUE
, ref_head
),
2258 VIEW_(TREE
, "tree", &tree_ops
, TRUE
, ref_commit
),
2259 VIEW_(BLOB
, "blob", &blob_ops
, TRUE
, ref_blob
),
2260 VIEW_(BLAME
, "blame", &blame_ops
, TRUE
, ref_commit
),
2261 VIEW_(BRANCH
, "branch", &branch_ops
, TRUE
, ref_head
),
2262 VIEW_(HELP
, "help", &help_ops
, FALSE
, ""),
2263 VIEW_(PAGER
, "pager", &pager_ops
, FALSE
, "stdin"),
2264 VIEW_(STATUS
, "status", &status_ops
, TRUE
, ""),
2265 VIEW_(STAGE
, "stage", &stage_ops
, TRUE
, ""),
2268 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
2269 #define VIEW_REQ(view) ((view) - views + REQ_OFFSET + 1)
2271 #define foreach_view(view, i) \
2272 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2274 #define view_is_displayed(view) \
2275 (view == display[0] || view == display[1])
2279 set_view_attr(struct view
*view
, enum line_type type
)
2281 if (!view
->curline
->selected
&& view
->curtype
!= type
) {
2282 (void) wattrset(view
->win
, get_line_attr(type
));
2283 wchgat(view
->win
, -1, 0, type
, NULL
);
2284 view
->curtype
= type
;
2289 draw_chars(struct view
*view
, enum line_type type
, const char *string
,
2290 int max_len
, bool use_tilde
)
2292 static char out_buffer
[BUFSIZ
* 2];
2295 int trimmed
= FALSE
;
2296 size_t skip
= view
->yoffset
> view
->col
? view
->yoffset
- view
->col
: 0;
2301 len
= utf8_length(&string
, skip
, &col
, max_len
, &trimmed
, use_tilde
, opt_tab_size
);
2303 set_view_attr(view
, type
);
2305 if (opt_iconv_out
!= ICONV_NONE
) {
2306 ICONV_CONST
char *inbuf
= (ICONV_CONST
char *) string
;
2307 size_t inlen
= len
+ 1;
2309 char *outbuf
= out_buffer
;
2310 size_t outlen
= sizeof(out_buffer
);
2314 ret
= iconv(opt_iconv_out
, &inbuf
, &inlen
, &outbuf
, &outlen
);
2315 if (ret
!= (size_t) -1) {
2316 string
= out_buffer
;
2317 len
= sizeof(out_buffer
) - outlen
;
2321 waddnstr(view
->win
, string
, len
);
2323 if (trimmed
&& use_tilde
) {
2324 set_view_attr(view
, LINE_DELIMITER
);
2325 waddch(view
->win
, '~');
2333 draw_space(struct view
*view
, enum line_type type
, int max
, int spaces
)
2335 static char space
[] = " ";
2338 spaces
= MIN(max
, spaces
);
2340 while (spaces
> 0) {
2341 int len
= MIN(spaces
, sizeof(space
) - 1);
2343 col
+= draw_chars(view
, type
, space
, len
, FALSE
);
2351 draw_text(struct view
*view
, enum line_type type
, const char *string
, bool trim
)
2353 view
->col
+= draw_chars(view
, type
, string
, view
->width
+ view
->yoffset
- view
->col
, trim
);
2354 return view
->width
+ view
->yoffset
<= view
->col
;
2358 draw_graphic(struct view
*view
, enum line_type type
, chtype graphic
[], size_t size
)
2360 size_t skip
= view
->yoffset
> view
->col
? view
->yoffset
- view
->col
: 0;
2361 int max
= view
->width
+ view
->yoffset
- view
->col
;
2367 set_view_attr(view
, type
);
2368 /* Using waddch() instead of waddnstr() ensures that
2369 * they'll be rendered correctly for the cursor line. */
2370 for (i
= skip
; i
< size
; i
++)
2371 waddch(view
->win
, graphic
[i
]);
2374 if (size
< max
&& skip
<= size
)
2375 waddch(view
->win
, ' ');
2378 return view
->width
+ view
->yoffset
<= view
->col
;
2382 draw_field(struct view
*view
, enum line_type type
, const char *text
, int len
, bool trim
)
2384 int max
= MIN(view
->width
+ view
->yoffset
- view
->col
, len
);
2388 col
= draw_chars(view
, type
, text
, max
- 1, trim
);
2390 col
= draw_space(view
, type
, max
- 1, max
- 1);
2393 view
->col
+= draw_space(view
, LINE_DEFAULT
, max
- col
, max
- col
);
2394 return view
->width
+ view
->yoffset
<= view
->col
;
2398 draw_date(struct view
*view
, struct time
*time
)
2400 const char *date
= mkdate(time
, opt_date
);
2401 int cols
= opt_date
== DATE_SHORT
? DATE_SHORT_COLS
: DATE_COLS
;
2403 return draw_field(view
, LINE_DATE
, date
, cols
, FALSE
);
2407 draw_author(struct view
*view
, const char *author
)
2409 bool trim
= opt_author_cols
== 0 || opt_author_cols
> 5;
2410 bool abbreviate
= opt_author
== AUTHOR_ABBREVIATED
|| !trim
;
2412 if (abbreviate
&& author
)
2413 author
= get_author_initials(author
);
2415 return draw_field(view
, LINE_AUTHOR
, author
, opt_author_cols
, trim
);
2419 draw_mode(struct view
*view
, mode_t mode
)
2425 else if (S_ISLNK(mode
))
2427 else if (S_ISGITLINK(mode
))
2429 else if (S_ISREG(mode
) && mode
& S_IXUSR
)
2431 else if (S_ISREG(mode
))
2436 return draw_field(view
, LINE_MODE
, str
, STRING_SIZE("-rw-r--r-- "), FALSE
);
2440 draw_lineno(struct view
*view
, unsigned int lineno
)
2443 int digits3
= view
->digits
< 3 ? 3 : view
->digits
;
2444 int max
= MIN(view
->width
+ view
->yoffset
- view
->col
, digits3
);
2446 chtype separator
= opt_line_graphics
? ACS_VLINE
: '|';
2448 lineno
+= view
->offset
+ 1;
2449 if (lineno
== 1 || (lineno
% opt_num_interval
) == 0) {
2450 static char fmt
[] = "%1ld";
2452 fmt
[1] = '0' + (view
->digits
<= 9 ? digits3
: 1);
2453 if (string_format(number
, fmt
, lineno
))
2457 view
->col
+= draw_chars(view
, LINE_LINE_NUMBER
, text
, max
, TRUE
);
2459 view
->col
+= draw_space(view
, LINE_LINE_NUMBER
, max
, digits3
);
2460 return draw_graphic(view
, LINE_DEFAULT
, &separator
, 1);
2464 draw_view_line(struct view
*view
, unsigned int lineno
)
2467 bool selected
= (view
->offset
+ lineno
== view
->lineno
);
2469 assert(view_is_displayed(view
));
2471 if (view
->offset
+ lineno
>= view
->lines
)
2474 line
= &view
->line
[view
->offset
+ lineno
];
2476 wmove(view
->win
, lineno
, 0);
2478 wclrtoeol(view
->win
);
2480 view
->curline
= line
;
2481 view
->curtype
= LINE_NONE
;
2482 line
->selected
= FALSE
;
2483 line
->dirty
= line
->cleareol
= 0;
2486 set_view_attr(view
, LINE_CURSOR
);
2487 line
->selected
= TRUE
;
2488 view
->ops
->select(view
, line
);
2491 return view
->ops
->draw(view
, line
, lineno
);
2495 redraw_view_dirty(struct view
*view
)
2500 for (lineno
= 0; lineno
< view
->height
; lineno
++) {
2501 if (view
->offset
+ lineno
>= view
->lines
)
2503 if (!view
->line
[view
->offset
+ lineno
].dirty
)
2506 if (!draw_view_line(view
, lineno
))
2512 wnoutrefresh(view
->win
);
2516 redraw_view_from(struct view
*view
, int lineno
)
2518 assert(0 <= lineno
&& lineno
< view
->height
);
2520 for (; lineno
< view
->height
; lineno
++) {
2521 if (!draw_view_line(view
, lineno
))
2525 wnoutrefresh(view
->win
);
2529 redraw_view(struct view
*view
)
2532 redraw_view_from(view
, 0);
2537 update_view_title(struct view
*view
)
2539 char buf
[SIZEOF_STR
];
2540 char state
[SIZEOF_STR
];
2541 size_t bufpos
= 0, statelen
= 0;
2543 assert(view_is_displayed(view
));
2545 if (view
!= VIEW(REQ_VIEW_STATUS
) && view
->lines
) {
2546 unsigned int view_lines
= view
->offset
+ view
->height
;
2547 unsigned int lines
= view
->lines
2548 ? MIN(view_lines
, view
->lines
) * 100 / view
->lines
2551 string_format_from(state
, &statelen
, " - %s %d of %d (%d%%)",
2560 time_t secs
= time(NULL
) - view
->start_time
;
2562 /* Three git seconds are a long time ... */
2564 string_format_from(state
, &statelen
, " loading %lds", secs
);
2567 string_format_from(buf
, &bufpos
, "[%s]", view
->name
);
2568 if (*view
->ref
&& bufpos
< view
->width
) {
2569 size_t refsize
= strlen(view
->ref
);
2570 size_t minsize
= bufpos
+ 1 + /* abbrev= */ 7 + 1 + statelen
;
2572 if (minsize
< view
->width
)
2573 refsize
= view
->width
- minsize
+ 7;
2574 string_format_from(buf
, &bufpos
, " %.*s", (int) refsize
, view
->ref
);
2577 if (statelen
&& bufpos
< view
->width
) {
2578 string_format_from(buf
, &bufpos
, "%s", state
);
2581 if (view
== display
[current_view
])
2582 wbkgdset(view
->title
, get_line_attr(LINE_TITLE_FOCUS
));
2584 wbkgdset(view
->title
, get_line_attr(LINE_TITLE_BLUR
));
2586 mvwaddnstr(view
->title
, 0, 0, buf
, bufpos
);
2587 wclrtoeol(view
->title
);
2588 wnoutrefresh(view
->title
);
2592 apply_step(double step
, int value
)
2596 value
*= step
+ 0.01;
2597 return value
? value
: 1;
2601 resize_display(void)
2604 struct view
*base
= display
[0];
2605 struct view
*view
= display
[1] ? display
[1] : display
[0];
2607 /* Setup window dimensions */
2609 getmaxyx(stdscr
, base
->height
, base
->width
);
2611 /* Make room for the status window. */
2615 /* Horizontal split. */
2616 view
->width
= base
->width
;
2617 view
->height
= apply_step(opt_scale_split_view
, base
->height
);
2618 view
->height
= MAX(view
->height
, MIN_VIEW_HEIGHT
);
2619 view
->height
= MIN(view
->height
, base
->height
- MIN_VIEW_HEIGHT
);
2620 base
->height
-= view
->height
;
2622 /* Make room for the title bar. */
2626 /* Make room for the title bar. */
2631 foreach_displayed_view (view
, i
) {
2633 view
->win
= newwin(view
->height
, 0, offset
, 0);
2635 die("Failed to create %s view", view
->name
);
2637 scrollok(view
->win
, FALSE
);
2639 view
->title
= newwin(1, 0, offset
+ view
->height
, 0);
2641 die("Failed to create title window");
2644 wresize(view
->win
, view
->height
, view
->width
);
2645 mvwin(view
->win
, offset
, 0);
2646 mvwin(view
->title
, offset
+ view
->height
, 0);
2649 offset
+= view
->height
+ 1;
2654 redraw_display(bool clear
)
2659 foreach_displayed_view (view
, i
) {
2663 update_view_title(view
);
2668 toggle_enum_option_do(unsigned int *opt
, const char *help
,
2669 const struct enum_map
*map
, size_t size
)
2671 *opt
= (*opt
+ 1) % size
;
2672 redraw_display(FALSE
);
2673 report("Displaying %s %s", enum_name(map
[*opt
]), help
);
2676 #define toggle_enum_option(opt, help, map) \
2677 toggle_enum_option_do(opt, help, map, ARRAY_SIZE(map))
2679 #define toggle_date() toggle_enum_option(&opt_date, "dates", date_map)
2680 #define toggle_author() toggle_enum_option(&opt_author, "author names", author_map)
2683 toggle_view_option(bool *option
, const char *help
)
2686 redraw_display(FALSE
);
2687 report("%sabling %s", *option
? "En" : "Dis", help
);
2691 open_option_menu(void)
2693 const struct menu_item menu
[] = {
2694 { '.', "line numbers", &opt_line_number
},
2695 { 'D', "date display", &opt_date
},
2696 { 'A', "author display", &opt_author
},
2697 { 'g', "revision graph display", &opt_rev_graph
},
2698 { 'F', "reference display", &opt_show_refs
},
2703 if (prompt_menu("Toggle option", menu
, &selected
)) {
2704 if (menu
[selected
].data
== &opt_date
)
2706 else if (menu
[selected
].data
== &opt_author
)
2709 toggle_view_option(menu
[selected
].data
, menu
[selected
].text
);
2714 maximize_view(struct view
*view
)
2716 memset(display
, 0, sizeof(display
));
2718 display
[current_view
] = view
;
2720 redraw_display(FALSE
);
2730 goto_view_line(struct view
*view
, unsigned long offset
, unsigned long lineno
)
2732 if (lineno
>= view
->lines
)
2733 lineno
= view
->lines
> 0 ? view
->lines
- 1 : 0;
2735 if (offset
> lineno
|| offset
+ view
->height
<= lineno
) {
2736 unsigned long half
= view
->height
/ 2;
2739 offset
= lineno
- half
;
2744 if (offset
!= view
->offset
|| lineno
!= view
->lineno
) {
2745 view
->offset
= offset
;
2746 view
->lineno
= lineno
;
2753 /* Scrolling backend */
2755 do_scroll_view(struct view
*view
, int lines
)
2757 bool redraw_current_line
= FALSE
;
2759 /* The rendering expects the new offset. */
2760 view
->offset
+= lines
;
2762 assert(0 <= view
->offset
&& view
->offset
< view
->lines
);
2765 /* Move current line into the view. */
2766 if (view
->lineno
< view
->offset
) {
2767 view
->lineno
= view
->offset
;
2768 redraw_current_line
= TRUE
;
2769 } else if (view
->lineno
>= view
->offset
+ view
->height
) {
2770 view
->lineno
= view
->offset
+ view
->height
- 1;
2771 redraw_current_line
= TRUE
;
2774 assert(view
->offset
<= view
->lineno
&& view
->lineno
< view
->lines
);
2776 /* Redraw the whole screen if scrolling is pointless. */
2777 if (view
->height
< ABS(lines
)) {
2781 int line
= lines
> 0 ? view
->height
- lines
: 0;
2782 int end
= line
+ ABS(lines
);
2784 scrollok(view
->win
, TRUE
);
2785 wscrl(view
->win
, lines
);
2786 scrollok(view
->win
, FALSE
);
2788 while (line
< end
&& draw_view_line(view
, line
))
2791 if (redraw_current_line
)
2792 draw_view_line(view
, view
->lineno
- view
->offset
);
2793 wnoutrefresh(view
->win
);
2796 view
->has_scrolled
= TRUE
;
2800 /* Scroll frontend */
2802 scroll_view(struct view
*view
, enum request request
)
2806 assert(view_is_displayed(view
));
2809 case REQ_SCROLL_LEFT
:
2810 if (view
->yoffset
== 0) {
2811 report("Cannot scroll beyond the first column");
2814 if (view
->yoffset
<= apply_step(opt_hscroll
, view
->width
))
2817 view
->yoffset
-= apply_step(opt_hscroll
, view
->width
);
2818 redraw_view_from(view
, 0);
2821 case REQ_SCROLL_RIGHT
:
2822 view
->yoffset
+= apply_step(opt_hscroll
, view
->width
);
2826 case REQ_SCROLL_PAGE_DOWN
:
2827 lines
= view
->height
;
2828 case REQ_SCROLL_LINE_DOWN
:
2829 if (view
->offset
+ lines
> view
->lines
)
2830 lines
= view
->lines
- view
->offset
;
2832 if (lines
== 0 || view
->offset
+ view
->height
>= view
->lines
) {
2833 report("Cannot scroll beyond the last line");
2838 case REQ_SCROLL_PAGE_UP
:
2839 lines
= view
->height
;
2840 case REQ_SCROLL_LINE_UP
:
2841 if (lines
> view
->offset
)
2842 lines
= view
->offset
;
2845 report("Cannot scroll beyond the first line");
2853 die("request %d not handled in switch", request
);
2856 do_scroll_view(view
, lines
);
2861 move_view(struct view
*view
, enum request request
)
2863 int scroll_steps
= 0;
2867 case REQ_MOVE_FIRST_LINE
:
2868 steps
= -view
->lineno
;
2871 case REQ_MOVE_LAST_LINE
:
2872 steps
= view
->lines
- view
->lineno
- 1;
2875 case REQ_MOVE_PAGE_UP
:
2876 steps
= view
->height
> view
->lineno
2877 ? -view
->lineno
: -view
->height
;
2880 case REQ_MOVE_PAGE_DOWN
:
2881 steps
= view
->lineno
+ view
->height
>= view
->lines
2882 ? view
->lines
- view
->lineno
- 1 : view
->height
;
2894 die("request %d not handled in switch", request
);
2897 if (steps
<= 0 && view
->lineno
== 0) {
2898 report("Cannot move beyond the first line");
2901 } else if (steps
>= 0 && view
->lineno
+ 1 >= view
->lines
) {
2902 report("Cannot move beyond the last line");
2906 /* Move the current line */
2907 view
->lineno
+= steps
;
2908 assert(0 <= view
->lineno
&& view
->lineno
< view
->lines
);
2910 /* Check whether the view needs to be scrolled */
2911 if (view
->lineno
< view
->offset
||
2912 view
->lineno
>= view
->offset
+ view
->height
) {
2913 scroll_steps
= steps
;
2914 if (steps
< 0 && -steps
> view
->offset
) {
2915 scroll_steps
= -view
->offset
;
2917 } else if (steps
> 0) {
2918 if (view
->lineno
== view
->lines
- 1 &&
2919 view
->lines
> view
->height
) {
2920 scroll_steps
= view
->lines
- view
->offset
- 1;
2921 if (scroll_steps
>= view
->height
)
2922 scroll_steps
-= view
->height
- 1;
2927 if (!view_is_displayed(view
)) {
2928 view
->offset
+= scroll_steps
;
2929 assert(0 <= view
->offset
&& view
->offset
< view
->lines
);
2930 view
->ops
->select(view
, &view
->line
[view
->lineno
]);
2934 /* Repaint the old "current" line if we be scrolling */
2935 if (ABS(steps
) < view
->height
)
2936 draw_view_line(view
, view
->lineno
- steps
- view
->offset
);
2939 do_scroll_view(view
, scroll_steps
);
2943 /* Draw the current line */
2944 draw_view_line(view
, view
->lineno
- view
->offset
);
2946 wnoutrefresh(view
->win
);
2955 static void search_view(struct view
*view
, enum request request
);
2958 grep_text(struct view
*view
, const char *text
[])
2963 for (i
= 0; text
[i
]; i
++)
2965 regexec(view
->regex
, text
[i
], 1, &pmatch
, 0) != REG_NOMATCH
)
2971 select_view_line(struct view
*view
, unsigned long lineno
)
2973 unsigned long old_lineno
= view
->lineno
;
2974 unsigned long old_offset
= view
->offset
;
2976 if (goto_view_line(view
, view
->offset
, lineno
)) {
2977 if (view_is_displayed(view
)) {
2978 if (old_offset
!= view
->offset
) {
2981 draw_view_line(view
, old_lineno
- view
->offset
);
2982 draw_view_line(view
, view
->lineno
- view
->offset
);
2983 wnoutrefresh(view
->win
);
2986 view
->ops
->select(view
, &view
->line
[view
->lineno
]);
2992 find_next(struct view
*view
, enum request request
)
2994 unsigned long lineno
= view
->lineno
;
2999 report("No previous search");
3001 search_view(view
, request
);
3011 case REQ_SEARCH_BACK
:
3020 if (request
== REQ_FIND_NEXT
|| request
== REQ_FIND_PREV
)
3021 lineno
+= direction
;
3023 /* Note, lineno is unsigned long so will wrap around in which case it
3024 * will become bigger than view->lines. */
3025 for (; lineno
< view
->lines
; lineno
+= direction
) {
3026 if (view
->ops
->grep(view
, &view
->line
[lineno
])) {
3027 select_view_line(view
, lineno
);
3028 report("Line %ld matches '%s'", lineno
+ 1, view
->grep
);
3033 report("No match found for '%s'", view
->grep
);
3037 search_view(struct view
*view
, enum request request
)
3042 regfree(view
->regex
);
3045 view
->regex
= calloc(1, sizeof(*view
->regex
));
3050 regex_err
= regcomp(view
->regex
, opt_search
, REG_EXTENDED
);
3051 if (regex_err
!= 0) {
3052 char buf
[SIZEOF_STR
] = "unknown error";
3054 regerror(regex_err
, view
->regex
, buf
, sizeof(buf
));
3055 report("Search failed: %s", buf
);
3059 string_copy(view
->grep
, opt_search
);
3061 find_next(view
, request
);
3065 * Incremental updating
3069 reset_view(struct view
*view
)
3073 for (i
= 0; i
< view
->lines
; i
++)
3074 free(view
->line
[i
].data
);
3077 view
->p_offset
= view
->offset
;
3078 view
->p_yoffset
= view
->yoffset
;
3079 view
->p_lineno
= view
->lineno
;
3087 view
->update_secs
= 0;
3091 free_argv(const char *argv
[])
3095 for (argc
= 0; argv
[argc
]; argc
++)
3096 free((void *) argv
[argc
]);
3100 format_arg(const char *name
)
3106 const char *value_if_empty
;
3108 #define FORMAT_VAR(name, value, value_if_empty) \
3109 { name, STRING_SIZE(name), value, value_if_empty }
3110 FORMAT_VAR("%(directory)", opt_path
, ""),
3111 FORMAT_VAR("%(file)", opt_file
, ""),
3112 FORMAT_VAR("%(ref)", opt_ref
, "HEAD"),
3113 FORMAT_VAR("%(head)", ref_head
, ""),
3114 FORMAT_VAR("%(commit)", ref_commit
, ""),
3115 FORMAT_VAR("%(blob)", ref_blob
, ""),
3119 for (i
= 0; i
< ARRAY_SIZE(vars
); i
++)
3120 if (!strncmp(name
, vars
[i
].name
, vars
[i
].namelen
))
3121 return *vars
[i
].value
? vars
[i
].value
: vars
[i
].value_if_empty
;
3127 format_argv(const char *dst_argv
[], const char *src_argv
[], enum format_flags flags
)
3129 char buf
[SIZEOF_STR
];
3131 bool noreplace
= flags
== FORMAT_NONE
;
3133 free_argv(dst_argv
);
3135 for (argc
= 0; src_argv
[argc
]; argc
++) {
3136 const char *arg
= src_argv
[argc
];
3140 char *next
= strstr(arg
, "%(");
3141 int len
= next
- arg
;
3144 if (!next
|| noreplace
) {
3145 if (flags
== FORMAT_DASH
&& !strcmp(arg
, "--"))
3151 value
= format_arg(next
);
3154 report("Unknown replacement: `%s`", next
);
3159 if (!string_format_from(buf
, &bufpos
, "%.*s%s", len
, arg
, value
))
3162 arg
= next
&& !noreplace
? strchr(next
, ')') + 1 : NULL
;
3165 dst_argv
[argc
] = strdup(buf
);
3166 if (!dst_argv
[argc
])
3170 dst_argv
[argc
] = NULL
;
3172 return src_argv
[argc
] == NULL
;
3176 restore_view_position(struct view
*view
)
3178 if (!view
->p_restore
|| (view
->pipe
&& view
->lines
<= view
->p_lineno
))
3181 /* Changing the view position cancels the restoring. */
3182 /* FIXME: Changing back to the first line is not detected. */
3183 if (view
->offset
!= 0 || view
->lineno
!= 0) {
3184 view
->p_restore
= FALSE
;
3188 if (goto_view_line(view
, view
->p_offset
, view
->p_lineno
) &&
3189 view_is_displayed(view
))
3192 view
->yoffset
= view
->p_yoffset
;
3193 view
->p_restore
= FALSE
;
3199 end_update(struct view
*view
, bool force
)
3203 while (!view
->ops
->read(view
, NULL
))
3207 io_kill(view
->pipe
);
3208 io_done(view
->pipe
);
3213 setup_update(struct view
*view
, const char *vid
)
3216 string_copy_rev(view
->vid
, vid
);
3217 view
->pipe
= &view
->io
;
3218 view
->start_time
= time(NULL
);
3222 prepare_update(struct view
*view
, const char *argv
[], const char *dir
,
3223 enum format_flags flags
)
3226 end_update(view
, TRUE
);
3227 return io_format(&view
->io
, dir
, IO_RD
, argv
, flags
);
3231 prepare_update_file(struct view
*view
, const char *name
)
3234 end_update(view
, TRUE
);
3235 return io_open(&view
->io
, "%s/%s", opt_cdup
[0] ? opt_cdup
: ".", name
);
3239 begin_update(struct view
*view
, bool refresh
)
3242 end_update(view
, TRUE
);
3245 if (view
->ops
->prepare
) {
3246 if (!view
->ops
->prepare(view
))
3248 } else if (!io_format(&view
->io
, NULL
, IO_RD
, view
->ops
->argv
, FORMAT_ALL
)) {
3252 /* Put the current ref_* value to the view title ref
3253 * member. This is needed by the blob view. Most other
3254 * views sets it automatically after loading because the
3255 * first line is a commit line. */
3256 string_copy_rev(view
->ref
, view
->id
);
3259 if (!io_start(&view
->io
))
3262 setup_update(view
, view
->id
);
3268 update_view(struct view
*view
)
3270 char out_buffer
[BUFSIZ
* 2];
3272 /* Clear the view and redraw everything since the tree sorting
3273 * might have rearranged things. */
3274 bool redraw
= view
->lines
== 0;
3275 bool can_read
= TRUE
;
3280 if (!io_can_read(view
->pipe
)) {
3281 if (view
->lines
== 0 && view_is_displayed(view
)) {
3282 time_t secs
= time(NULL
) - view
->start_time
;
3284 if (secs
> 1 && secs
> view
->update_secs
) {
3285 if (view
->update_secs
== 0)
3287 update_view_title(view
);
3288 view
->update_secs
= secs
;
3294 for (; (line
= io_get(view
->pipe
, '\n', can_read
)); can_read
= FALSE
) {
3295 if (opt_iconv_in
!= ICONV_NONE
) {
3296 ICONV_CONST
char *inbuf
= line
;
3297 size_t inlen
= strlen(line
) + 1;
3299 char *outbuf
= out_buffer
;
3300 size_t outlen
= sizeof(out_buffer
);
3304 ret
= iconv(opt_iconv_in
, &inbuf
, &inlen
, &outbuf
, &outlen
);
3305 if (ret
!= (size_t) -1)
3309 if (!view
->ops
->read(view
, line
)) {
3310 report("Allocation failure");
3311 end_update(view
, TRUE
);
3317 unsigned long lines
= view
->lines
;
3320 for (digits
= 0; lines
; digits
++)
3323 /* Keep the displayed view in sync with line number scaling. */
3324 if (digits
!= view
->digits
) {
3325 view
->digits
= digits
;
3326 if (opt_line_number
|| view
== VIEW(REQ_VIEW_BLAME
))
3331 if (io_error(view
->pipe
)) {
3332 report("Failed to read: %s", io_strerror(view
->pipe
));
3333 end_update(view
, TRUE
);
3335 } else if (io_eof(view
->pipe
)) {
3337 end_update(view
, FALSE
);
3340 if (restore_view_position(view
))
3343 if (!view_is_displayed(view
))
3347 redraw_view_from(view
, 0);
3349 redraw_view_dirty(view
);
3351 /* Update the title _after_ the redraw so that if the redraw picks up a
3352 * commit reference in view->ref it'll be available here. */
3353 update_view_title(view
);
3357 DEFINE_ALLOCATOR(realloc_lines
, struct line
, 256)
3359 static struct line
*
3360 add_line_data(struct view
*view
, void *data
, enum line_type type
)
3364 if (!realloc_lines(&view
->line
, view
->lines
, 1))
3367 line
= &view
->line
[view
->lines
++];
3368 memset(line
, 0, sizeof(*line
));
3376 static struct line
*
3377 add_line_text(struct view
*view
, const char *text
, enum line_type type
)
3379 char *data
= text
? strdup(text
) : NULL
;
3381 return data
? add_line_data(view
, data
, type
) : NULL
;
3384 static struct line
*
3385 add_line_format(struct view
*view
, enum line_type type
, const char *fmt
, ...)
3387 char buf
[SIZEOF_STR
];
3390 va_start(args
, fmt
);
3391 if (vsnprintf(buf
, sizeof(buf
), fmt
, args
) >= sizeof(buf
))
3395 return buf
[0] ? add_line_text(view
, buf
, type
) : NULL
;
3403 OPEN_DEFAULT
= 0, /* Use default view switching. */
3404 OPEN_SPLIT
= 1, /* Split current view. */
3405 OPEN_RELOAD
= 4, /* Reload view even if it is the current. */
3406 OPEN_REFRESH
= 16, /* Refresh view using previous command. */
3407 OPEN_PREPARED
= 32, /* Open already prepared command. */
3411 open_view(struct view
*prev
, enum request request
, enum open_flags flags
)
3413 bool split
= !!(flags
& OPEN_SPLIT
);
3414 bool reload
= !!(flags
& (OPEN_RELOAD
| OPEN_REFRESH
| OPEN_PREPARED
));
3415 bool nomaximize
= !!(flags
& OPEN_REFRESH
);
3416 struct view
*view
= VIEW(request
);
3417 int nviews
= displayed_views();
3418 struct view
*base_view
= display
[0];
3420 if (view
== prev
&& nviews
== 1 && !reload
) {
3421 report("Already in %s view", view
->name
);
3425 if (view
->git_dir
&& !opt_git_dir
[0]) {
3426 report("The %s view is disabled in pager view", view
->name
);
3433 } else if (!nomaximize
) {
3434 /* Maximize the current view. */
3435 memset(display
, 0, sizeof(display
));
3437 display
[current_view
] = view
;
3440 /* No parent signals that this is the first loaded view. */
3441 if (prev
&& view
!= prev
) {
3442 view
->parent
= prev
;
3445 /* Resize the view when switching between split- and full-screen,
3446 * or when switching between two different full-screen views. */
3447 if (nviews
!= displayed_views() ||
3448 (nviews
== 1 && base_view
!= display
[0]))
3451 if (view
->ops
->open
) {
3453 end_update(view
, TRUE
);
3454 if (!view
->ops
->open(view
)) {
3455 report("Failed to load %s view", view
->name
);
3458 restore_view_position(view
);
3460 } else if ((reload
|| strcmp(view
->vid
, view
->id
)) &&
3461 !begin_update(view
, flags
& (OPEN_REFRESH
| OPEN_PREPARED
))) {
3462 report("Failed to load %s view", view
->name
);
3466 if (split
&& prev
->lineno
- prev
->offset
>= prev
->height
) {
3467 /* Take the title line into account. */
3468 int lines
= prev
->lineno
- prev
->offset
- prev
->height
+ 1;
3470 /* Scroll the view that was split if the current line is
3471 * outside the new limited view. */
3472 do_scroll_view(prev
, lines
);
3475 if (prev
&& view
!= prev
&& split
&& view_is_displayed(prev
)) {
3476 /* "Blur" the previous view. */
3477 update_view_title(prev
);
3480 if (view
->pipe
&& view
->lines
== 0) {
3481 /* Clear the old view and let the incremental updating refill
3484 view
->p_restore
= flags
& (OPEN_RELOAD
| OPEN_REFRESH
);
3486 } else if (view_is_displayed(view
)) {
3493 open_external_viewer(const char *argv
[], const char *dir
)
3495 def_prog_mode(); /* save current tty modes */
3496 endwin(); /* restore original tty modes */
3497 io_run_fg(argv
, dir
);
3498 fprintf(stderr
, "Press Enter to continue");
3501 redraw_display(TRUE
);
3505 open_mergetool(const char *file
)
3507 const char *mergetool_argv
[] = { "git", "mergetool", file
, NULL
};
3509 open_external_viewer(mergetool_argv
, opt_cdup
);
3513 open_editor(const char *file
)
3515 const char *editor_argv
[] = { "vi", file
, NULL
};
3518 editor
= getenv("GIT_EDITOR");
3519 if (!editor
&& *opt_editor
)
3520 editor
= opt_editor
;
3522 editor
= getenv("VISUAL");
3524 editor
= getenv("EDITOR");
3528 editor_argv
[0] = editor
;
3529 open_external_viewer(editor_argv
, opt_cdup
);
3533 open_run_request(enum request request
)
3535 struct run_request
*req
= get_run_request(request
);
3536 const char *argv
[ARRAY_SIZE(req
->argv
)] = { NULL
};
3539 report("Unknown run request");
3543 if (format_argv(argv
, req
->argv
, FORMAT_ALL
))
3544 open_external_viewer(argv
, NULL
);
3549 * User request switch noodle
3553 view_driver(struct view
*view
, enum request request
)
3557 if (request
== REQ_NONE
)
3560 if (request
> REQ_NONE
) {
3561 open_run_request(request
);
3562 /* FIXME: When all views can refresh always do this. */
3563 if (view
== VIEW(REQ_VIEW_STATUS
) ||
3564 view
== VIEW(REQ_VIEW_MAIN
) ||
3565 view
== VIEW(REQ_VIEW_LOG
) ||
3566 view
== VIEW(REQ_VIEW_BRANCH
) ||
3567 view
== VIEW(REQ_VIEW_STAGE
))
3568 request
= REQ_REFRESH
;
3573 if (view
&& view
->lines
) {
3574 request
= view
->ops
->request(view
, request
, &view
->line
[view
->lineno
]);
3575 if (request
== REQ_NONE
)
3582 case REQ_MOVE_PAGE_UP
:
3583 case REQ_MOVE_PAGE_DOWN
:
3584 case REQ_MOVE_FIRST_LINE
:
3585 case REQ_MOVE_LAST_LINE
:
3586 move_view(view
, request
);
3589 case REQ_SCROLL_LEFT
:
3590 case REQ_SCROLL_RIGHT
:
3591 case REQ_SCROLL_LINE_DOWN
:
3592 case REQ_SCROLL_LINE_UP
:
3593 case REQ_SCROLL_PAGE_DOWN
:
3594 case REQ_SCROLL_PAGE_UP
:
3595 scroll_view(view
, request
);
3598 case REQ_VIEW_BLAME
:
3600 report("No file chosen, press %s to open tree view",
3601 get_key(view
->keymap
, REQ_VIEW_TREE
));
3604 open_view(view
, request
, OPEN_DEFAULT
);
3609 report("No file chosen, press %s to open tree view",
3610 get_key(view
->keymap
, REQ_VIEW_TREE
));
3613 open_view(view
, request
, OPEN_DEFAULT
);
3616 case REQ_VIEW_PAGER
:
3617 if (!VIEW(REQ_VIEW_PAGER
)->pipe
&& !VIEW(REQ_VIEW_PAGER
)->lines
) {
3618 report("No pager content, press %s to run command from prompt",
3619 get_key(view
->keymap
, REQ_PROMPT
));
3622 open_view(view
, request
, OPEN_DEFAULT
);
3625 case REQ_VIEW_STAGE
:
3626 if (!VIEW(REQ_VIEW_STAGE
)->lines
) {
3627 report("No stage content, press %s to open the status view and choose file",
3628 get_key(view
->keymap
, REQ_VIEW_STATUS
));
3631 open_view(view
, request
, OPEN_DEFAULT
);
3634 case REQ_VIEW_STATUS
:
3635 if (opt_is_inside_work_tree
== FALSE
) {
3636 report("The status view requires a working tree");
3639 open_view(view
, request
, OPEN_DEFAULT
);
3647 case REQ_VIEW_BRANCH
:
3648 open_view(view
, request
, OPEN_DEFAULT
);
3653 request
= request
== REQ_NEXT
? REQ_MOVE_DOWN
: REQ_MOVE_UP
;
3655 if ((view
== VIEW(REQ_VIEW_DIFF
) &&
3656 view
->parent
== VIEW(REQ_VIEW_MAIN
)) ||
3657 (view
== VIEW(REQ_VIEW_DIFF
) &&
3658 view
->parent
== VIEW(REQ_VIEW_BLAME
)) ||
3659 (view
== VIEW(REQ_VIEW_STAGE
) &&
3660 view
->parent
== VIEW(REQ_VIEW_STATUS
)) ||
3661 (view
== VIEW(REQ_VIEW_BLOB
) &&
3662 view
->parent
== VIEW(REQ_VIEW_TREE
)) ||
3663 (view
== VIEW(REQ_VIEW_MAIN
) &&
3664 view
->parent
== VIEW(REQ_VIEW_BRANCH
))) {
3667 view
= view
->parent
;
3668 line
= view
->lineno
;
3669 move_view(view
, request
);
3670 if (view_is_displayed(view
))
3671 update_view_title(view
);
3672 if (line
!= view
->lineno
)
3673 view
->ops
->request(view
, REQ_ENTER
,
3674 &view
->line
[view
->lineno
]);
3677 move_view(view
, request
);
3683 int nviews
= displayed_views();
3684 int next_view
= (current_view
+ 1) % nviews
;
3686 if (next_view
== current_view
) {
3687 report("Only one view is displayed");
3691 current_view
= next_view
;
3692 /* Blur out the title of the previous view. */
3693 update_view_title(view
);
3698 report("Refreshing is not yet supported for the %s view", view
->name
);
3702 if (displayed_views() == 2)
3703 maximize_view(view
);
3710 case REQ_TOGGLE_LINENO
:
3711 toggle_view_option(&opt_line_number
, "line numbers");
3714 case REQ_TOGGLE_DATE
:
3718 case REQ_TOGGLE_AUTHOR
:
3722 case REQ_TOGGLE_REV_GRAPH
:
3723 toggle_view_option(&opt_rev_graph
, "revision graph display");
3726 case REQ_TOGGLE_REFS
:
3727 toggle_view_option(&opt_show_refs
, "reference display");
3730 case REQ_TOGGLE_SORT_FIELD
:
3731 case REQ_TOGGLE_SORT_ORDER
:
3732 report("Sorting is not yet supported for the %s view", view
->name
);
3736 case REQ_SEARCH_BACK
:
3737 search_view(view
, request
);
3742 find_next(view
, request
);
3745 case REQ_STOP_LOADING
:
3746 for (i
= 0; i
< ARRAY_SIZE(views
); i
++) {
3749 report("Stopped loading the %s view", view
->name
),
3750 end_update(view
, TRUE
);
3754 case REQ_SHOW_VERSION
:
3755 report("tig-%s (built %s)", TIG_VERSION
, __DATE__
);
3758 case REQ_SCREEN_REDRAW
:
3759 redraw_display(TRUE
);
3763 report("Nothing to edit");
3767 report("Nothing to enter");
3770 case REQ_VIEW_CLOSE
:
3771 /* XXX: Mark closed views by letting view->parent point to the
3772 * view itself. Parents to closed view should never be
3775 view
->parent
->parent
!= view
->parent
) {
3776 maximize_view(view
->parent
);
3777 view
->parent
= view
;
3785 report("Unknown key, press %s for help",
3786 get_key(view
->keymap
, REQ_VIEW_HELP
));
3795 * View backend utilities
3805 const enum sort_field
*fields
;
3806 size_t size
, current
;
3810 #define SORT_STATE(fields) { fields, ARRAY_SIZE(fields), 0 }
3811 #define get_sort_field(state) ((state).fields[(state).current])
3812 #define sort_order(state, result) ((state).reverse ? -(result) : (result))
3815 sort_view(struct view
*view
, enum request request
, struct sort_state
*state
,
3816 int (*compare
)(const void *, const void *))
3819 case REQ_TOGGLE_SORT_FIELD
:
3820 state
->current
= (state
->current
+ 1) % state
->size
;
3823 case REQ_TOGGLE_SORT_ORDER
:
3824 state
->reverse
= !state
->reverse
;
3827 die("Not a sort request");
3830 qsort(view
->line
, view
->lines
, sizeof(*view
->line
), compare
);
3834 DEFINE_ALLOCATOR(realloc_authors
, const char *, 256)
3836 /* Small author cache to reduce memory consumption. It uses binary
3837 * search to lookup or find place to position new entries. No entries
3838 * are ever freed. */
3840 get_author(const char *name
)
3842 static const char **authors
;
3843 static size_t authors_size
;
3844 int from
= 0, to
= authors_size
- 1;
3846 while (from
<= to
) {
3847 size_t pos
= (to
+ from
) / 2;
3848 int cmp
= strcmp(name
, authors
[pos
]);
3851 return authors
[pos
];
3859 if (!realloc_authors(&authors
, authors_size
, 1))
3861 name
= strdup(name
);
3865 memmove(authors
+ from
+ 1, authors
+ from
, (authors_size
- from
) * sizeof(*authors
));
3866 authors
[from
] = name
;
3873 parse_timesec(struct time
*time
, const char *sec
)
3875 time
->sec
= (time_t) atol(sec
);
3879 parse_timezone(struct time
*time
, const char *zone
)
3883 tz
= ('0' - zone
[1]) * 60 * 60 * 10;
3884 tz
+= ('0' - zone
[2]) * 60 * 60;
3885 tz
+= ('0' - zone
[3]) * 60;
3886 tz
+= ('0' - zone
[4]);
3895 /* Parse author lines where the name may be empty:
3896 * author <email@address.tld> 1138474660 +0100
3899 parse_author_line(char *ident
, const char **author
, struct time
*time
)
3901 char *nameend
= strchr(ident
, '<');
3902 char *emailend
= strchr(ident
, '>');
3904 if (nameend
&& emailend
)
3905 *nameend
= *emailend
= 0;
3906 ident
= chomp_string(ident
);
3909 ident
= chomp_string(nameend
+ 1);
3914 *author
= get_author(ident
);
3916 /* Parse epoch and timezone */
3917 if (emailend
&& emailend
[1] == ' ') {
3918 char *secs
= emailend
+ 2;
3919 char *zone
= strchr(secs
, ' ');
3921 parse_timesec(time
, secs
);
3923 if (zone
&& strlen(zone
) == STRING_SIZE(" +0700"))
3924 parse_timezone(time
, zone
+ 1);
3929 open_commit_parent_menu(char buf
[SIZEOF_STR
], int *parents
)
3931 char rev
[SIZEOF_REV
];
3932 const char *revlist_argv
[] = {
3933 "git", "log", "--no-color", "-1", "--pretty=format:%s", rev
, NULL
3935 struct menu_item
*items
;
3936 char text
[SIZEOF_STR
];
3940 items
= calloc(*parents
+ 1, sizeof(*items
));
3944 for (i
= 0; i
< *parents
; i
++) {
3945 string_copy_rev(rev
, &buf
[SIZEOF_REV
* i
]);
3946 if (!io_run_buf(revlist_argv
, text
, sizeof(text
)) ||
3947 !(items
[i
].text
= strdup(text
))) {
3955 ok
= prompt_menu("Select parent", items
, parents
);
3957 for (i
= 0; items
[i
].text
; i
++)
3958 free((char *) items
[i
].text
);
3964 select_commit_parent(const char *id
, char rev
[SIZEOF_REV
], const char *path
)
3966 char buf
[SIZEOF_STR
* 4];
3967 const char *revlist_argv
[] = {
3968 "git", "log", "--no-color", "-1",
3969 "--pretty=format:%P", id
, "--", path
, NULL
3973 if (!io_run_buf(revlist_argv
, buf
, sizeof(buf
)) ||
3974 (parents
= strlen(buf
) / 40) < 0) {
3975 report("Failed to get parent information");
3978 } else if (parents
== 0) {
3980 report("Path '%s' does not exist in the parent", path
);
3982 report("The selected commit has no parents");
3986 if (parents
> 1 && !open_commit_parent_menu(buf
, &parents
))
3989 string_copy_rev(rev
, &buf
[41 * parents
]);
3998 pager_draw(struct view
*view
, struct line
*line
, unsigned int lineno
)
4000 char text
[SIZEOF_STR
];
4002 if (opt_line_number
&& draw_lineno(view
, lineno
))
4005 string_expand(text
, sizeof(text
), line
->data
, opt_tab_size
);
4006 draw_text(view
, line
->type
, text
, TRUE
);
4011 add_describe_ref(char *buf
, size_t *bufpos
, const char *commit_id
, const char *sep
)
4013 const char *describe_argv
[] = { "git", "describe", commit_id
, NULL
};
4014 char ref
[SIZEOF_STR
];
4016 if (!io_run_buf(describe_argv
, ref
, sizeof(ref
)) || !*ref
)
4019 /* This is the only fatal call, since it can "corrupt" the buffer. */
4020 if (!string_nformat(buf
, SIZEOF_STR
, bufpos
, "%s%s", sep
, ref
))
4027 add_pager_refs(struct view
*view
, struct line
*line
)
4029 char buf
[SIZEOF_STR
];
4030 char *commit_id
= (char *)line
->data
+ STRING_SIZE("commit ");
4031 struct ref_list
*list
;
4032 size_t bufpos
= 0, i
;
4033 const char *sep
= "Refs: ";
4034 bool is_tag
= FALSE
;
4036 assert(line
->type
== LINE_COMMIT
);
4038 list
= get_ref_list(commit_id
);
4040 if (view
== VIEW(REQ_VIEW_DIFF
))
4041 goto try_add_describe_ref
;
4045 for (i
= 0; i
< list
->size
; i
++) {
4046 struct ref
*ref
= list
->refs
[i
];
4047 const char *fmt
= ref
->tag
? "%s[%s]" :
4048 ref
->remote
? "%s<%s>" : "%s%s";
4050 if (!string_format_from(buf
, &bufpos
, fmt
, sep
, ref
->name
))
4057 if (!is_tag
&& view
== VIEW(REQ_VIEW_DIFF
)) {
4058 try_add_describe_ref
:
4059 /* Add <tag>-g<commit_id> "fake" reference. */
4060 if (!add_describe_ref(buf
, &bufpos
, commit_id
, sep
))
4067 add_line_text(view
, buf
, LINE_PP_REFS
);
4071 pager_read(struct view
*view
, char *data
)
4078 line
= add_line_text(view
, data
, get_line_type(data
));
4082 if (line
->type
== LINE_COMMIT
&&
4083 (view
== VIEW(REQ_VIEW_DIFF
) ||
4084 view
== VIEW(REQ_VIEW_LOG
)))
4085 add_pager_refs(view
, line
);
4091 pager_request(struct view
*view
, enum request request
, struct line
*line
)
4095 if (request
!= REQ_ENTER
)
4098 if (line
->type
== LINE_COMMIT
&&
4099 (view
== VIEW(REQ_VIEW_LOG
) ||
4100 view
== VIEW(REQ_VIEW_PAGER
))) {
4101 open_view(view
, REQ_VIEW_DIFF
, OPEN_SPLIT
);
4105 /* Always scroll the view even if it was split. That way
4106 * you can use Enter to scroll through the log view and
4107 * split open each commit diff. */
4108 scroll_view(view
, REQ_SCROLL_LINE_DOWN
);
4110 /* FIXME: A minor workaround. Scrolling the view will call report("")
4111 * but if we are scrolling a non-current view this won't properly
4112 * update the view title. */
4114 update_view_title(view
);
4120 pager_grep(struct view
*view
, struct line
*line
)
4122 const char *text
[] = { line
->data
, NULL
};
4124 return grep_text(view
, text
);
4128 pager_select(struct view
*view
, struct line
*line
)
4130 if (line
->type
== LINE_COMMIT
) {
4131 char *text
= (char *)line
->data
+ STRING_SIZE("commit ");
4133 if (view
!= VIEW(REQ_VIEW_PAGER
))
4134 string_copy_rev(view
->ref
, text
);
4135 string_copy_rev(ref_commit
, text
);
4139 static struct view_ops pager_ops
= {
4150 static const char *log_argv
[SIZEOF_ARG
] = {
4151 "git", "log", "--no-color", "--cc", "--stat", "-n100", "%(head)", NULL
4155 log_request(struct view
*view
, enum request request
, struct line
*line
)
4160 open_view(view
, REQ_VIEW_LOG
, OPEN_REFRESH
);
4163 return pager_request(view
, request
, line
);
4167 static struct view_ops log_ops
= {
4178 static const char *diff_argv
[SIZEOF_ARG
] = {
4179 "git", "show", "--pretty=fuller", "--no-color", "--root",
4180 "--patch-with-stat", "--find-copies-harder", "-C", "%(commit)", NULL
4183 static struct view_ops diff_ops
= {
4198 static bool help_keymap_hidden
[ARRAY_SIZE(keymap_table
)];
4201 help_open_keymap_title(struct view
*view
, enum keymap keymap
)
4205 line
= add_line_format(view
, LINE_HELP_KEYMAP
, "[%c] %s bindings",
4206 help_keymap_hidden
[keymap
] ? '+' : '-',
4207 enum_name(keymap_table
[keymap
]));
4209 line
->other
= keymap
;
4211 return help_keymap_hidden
[keymap
];
4215 help_open_keymap(struct view
*view
, enum keymap keymap
)
4217 const char *group
= NULL
;
4218 char buf
[SIZEOF_STR
];
4220 bool add_title
= TRUE
;
4223 for (i
= 0; i
< ARRAY_SIZE(req_info
); i
++) {
4224 const char *key
= NULL
;
4226 if (req_info
[i
].request
== REQ_NONE
)
4229 if (!req_info
[i
].request
) {
4230 group
= req_info
[i
].help
;
4234 key
= get_keys(keymap
, req_info
[i
].request
, TRUE
);
4238 if (add_title
&& help_open_keymap_title(view
, keymap
))
4243 add_line_text(view
, group
, LINE_HELP_GROUP
);
4247 add_line_format(view
, LINE_DEFAULT
, " %-25s %-20s %s", key
,
4248 enum_name(req_info
[i
]), req_info
[i
].help
);
4251 group
= "External commands:";
4253 for (i
= 0; i
< run_requests
; i
++) {
4254 struct run_request
*req
= get_run_request(REQ_NONE
+ i
+ 1);
4258 if (!req
|| req
->keymap
!= keymap
)
4261 key
= get_key_name(req
->key
);
4263 key
= "(no key defined)";
4265 if (add_title
&& help_open_keymap_title(view
, keymap
))
4268 add_line_text(view
, group
, LINE_HELP_GROUP
);
4272 for (bufpos
= 0, argc
= 0; req
->argv
[argc
]; argc
++)
4273 if (!string_format_from(buf
, &bufpos
, "%s%s",
4274 argc
? " " : "", req
->argv
[argc
]))
4277 add_line_format(view
, LINE_DEFAULT
, " %-25s `%s`", key
, buf
);
4282 help_open(struct view
*view
)
4287 add_line_text(view
, "Quick reference for tig keybindings:", LINE_DEFAULT
);
4288 add_line_text(view
, "", LINE_DEFAULT
);
4290 for (keymap
= 0; keymap
< ARRAY_SIZE(keymap_table
); keymap
++)
4291 help_open_keymap(view
, keymap
);
4297 help_request(struct view
*view
, enum request request
, struct line
*line
)
4301 if (line
->type
== LINE_HELP_KEYMAP
) {
4302 help_keymap_hidden
[line
->other
] =
4303 !help_keymap_hidden
[line
->other
];
4304 view
->p_restore
= TRUE
;
4305 open_view(view
, REQ_VIEW_HELP
, OPEN_REFRESH
);
4310 return pager_request(view
, request
, line
);
4314 static struct view_ops help_ops
= {
4330 struct tree_stack_entry
{
4331 struct tree_stack_entry
*prev
; /* Entry below this in the stack */
4332 unsigned long lineno
; /* Line number to restore */
4333 char *name
; /* Position of name in opt_path */
4336 /* The top of the path stack. */
4337 static struct tree_stack_entry
*tree_stack
= NULL
;
4338 unsigned long tree_lineno
= 0;
4341 pop_tree_stack_entry(void)
4343 struct tree_stack_entry
*entry
= tree_stack
;
4345 tree_lineno
= entry
->lineno
;
4347 tree_stack
= entry
->prev
;
4352 push_tree_stack_entry(const char *name
, unsigned long lineno
)
4354 struct tree_stack_entry
*entry
= calloc(1, sizeof(*entry
));
4355 size_t pathlen
= strlen(opt_path
);
4360 entry
->prev
= tree_stack
;
4361 entry
->name
= opt_path
+ pathlen
;
4364 if (!string_format_from(opt_path
, &pathlen
, "%s/", name
)) {
4365 pop_tree_stack_entry();
4369 /* Move the current line to the first tree entry. */
4371 entry
->lineno
= lineno
;
4374 /* Parse output from git-ls-tree(1):
4376 * 100644 blob f931e1d229c3e185caad4449bf5b66ed72462657 tig.c
4379 #define SIZEOF_TREE_ATTR \
4380 STRING_SIZE("100644 blob f931e1d229c3e185caad4449bf5b66ed72462657\t")
4382 #define SIZEOF_TREE_MODE \
4383 STRING_SIZE("100644 ")
4385 #define TREE_ID_OFFSET \
4386 STRING_SIZE("100644 blob ")
4389 char id
[SIZEOF_REV
];
4391 struct time time
; /* Date from the author ident. */
4392 const char *author
; /* Author of the commit. */
4397 tree_path(const struct line
*line
)
4399 return ((struct tree_entry
*) line
->data
)->name
;
4403 tree_compare_entry(const struct line
*line1
, const struct line
*line2
)
4405 if (line1
->type
!= line2
->type
)
4406 return line1
->type
== LINE_TREE_DIR
? -1 : 1;
4407 return strcmp(tree_path(line1
), tree_path(line2
));
4410 static const enum sort_field tree_sort_fields
[] = {
4411 ORDERBY_NAME
, ORDERBY_DATE
, ORDERBY_AUTHOR
4413 static struct sort_state tree_sort_state
= SORT_STATE(tree_sort_fields
);
4416 tree_compare(const void *l1
, const void *l2
)
4418 const struct line
*line1
= (const struct line
*) l1
;
4419 const struct line
*line2
= (const struct line
*) l2
;
4420 const struct tree_entry
*entry1
= ((const struct line
*) l1
)->data
;
4421 const struct tree_entry
*entry2
= ((const struct line
*) l2
)->data
;
4423 if (line1
->type
== LINE_TREE_HEAD
)
4425 if (line2
->type
== LINE_TREE_HEAD
)
4428 switch (get_sort_field(tree_sort_state
)) {
4430 return sort_order(tree_sort_state
, timecmp(&entry1
->time
, &entry2
->time
));
4432 case ORDERBY_AUTHOR
:
4433 return sort_order(tree_sort_state
, strcmp(entry1
->author
, entry2
->author
));
4437 return sort_order(tree_sort_state
, tree_compare_entry(line1
, line2
));
4442 static struct line
*
4443 tree_entry(struct view
*view
, enum line_type type
, const char *path
,
4444 const char *mode
, const char *id
)
4446 struct tree_entry
*entry
= calloc(1, sizeof(*entry
) + strlen(path
));
4447 struct line
*line
= entry
? add_line_data(view
, entry
, type
) : NULL
;
4449 if (!entry
|| !line
) {
4454 strncpy(entry
->name
, path
, strlen(path
));
4456 entry
->mode
= strtoul(mode
, NULL
, 8);
4458 string_copy_rev(entry
->id
, id
);
4464 tree_read_date(struct view
*view
, char *text
, bool *read_date
)
4466 static const char *author_name
;
4467 static struct time author_time
;
4469 if (!text
&& *read_date
) {
4474 char *path
= *opt_path
? opt_path
: ".";
4475 /* Find next entry to process */
4476 const char *log_file
[] = {
4477 "git", "log", "--no-color", "--pretty=raw",
4478 "--cc", "--raw", view
->id
, "--", path
, NULL
4483 tree_entry(view
, LINE_TREE_HEAD
, opt_path
, NULL
, NULL
);
4484 report("Tree is empty");
4488 if (!io_run_rd(&io
, log_file
, opt_cdup
, FORMAT_NONE
)) {
4489 report("Failed to load tree data");
4493 io_done(view
->pipe
);
4498 } else if (*text
== 'a' && get_line_type(text
) == LINE_AUTHOR
) {
4499 parse_author_line(text
+ STRING_SIZE("author "),
4500 &author_name
, &author_time
);
4502 } else if (*text
== ':') {
4504 size_t annotated
= 1;
4507 pos
= strchr(text
, '\t');
4511 if (*opt_path
&& !strncmp(text
, opt_path
, strlen(opt_path
)))
4512 text
+= strlen(opt_path
);
4513 pos
= strchr(text
, '/');
4517 for (i
= 1; i
< view
->lines
; i
++) {
4518 struct line
*line
= &view
->line
[i
];
4519 struct tree_entry
*entry
= line
->data
;
4521 annotated
+= !!entry
->author
;
4522 if (entry
->author
|| strcmp(entry
->name
, text
))
4525 entry
->author
= author_name
;
4526 entry
->time
= author_time
;
4531 if (annotated
== view
->lines
)
4532 io_kill(view
->pipe
);
4538 tree_read(struct view
*view
, char *text
)
4540 static bool read_date
= FALSE
;
4541 struct tree_entry
*data
;
4542 struct line
*entry
, *line
;
4543 enum line_type type
;
4544 size_t textlen
= text
? strlen(text
) : 0;
4545 char *path
= text
+ SIZEOF_TREE_ATTR
;
4547 if (read_date
|| !text
)
4548 return tree_read_date(view
, text
, &read_date
);
4550 if (textlen
<= SIZEOF_TREE_ATTR
)
4552 if (view
->lines
== 0 &&
4553 !tree_entry(view
, LINE_TREE_HEAD
, opt_path
, NULL
, NULL
))
4556 /* Strip the path part ... */
4558 size_t pathlen
= textlen
- SIZEOF_TREE_ATTR
;
4559 size_t striplen
= strlen(opt_path
);
4561 if (pathlen
> striplen
)
4562 memmove(path
, path
+ striplen
,
4563 pathlen
- striplen
+ 1);
4565 /* Insert "link" to parent directory. */
4566 if (view
->lines
== 1 &&
4567 !tree_entry(view
, LINE_TREE_DIR
, "..", "040000", view
->ref
))
4571 type
= text
[SIZEOF_TREE_MODE
] == 't' ? LINE_TREE_DIR
: LINE_TREE_FILE
;
4572 entry
= tree_entry(view
, type
, path
, text
, text
+ TREE_ID_OFFSET
);
4577 /* Skip "Directory ..." and ".." line. */
4578 for (line
= &view
->line
[1 + !!*opt_path
]; line
< entry
; line
++) {
4579 if (tree_compare_entry(line
, entry
) <= 0)
4582 memmove(line
+ 1, line
, (entry
- line
) * sizeof(*entry
));
4586 for (; line
<= entry
; line
++)
4587 line
->dirty
= line
->cleareol
= 1;
4591 if (tree_lineno
> view
->lineno
) {
4592 view
->lineno
= tree_lineno
;
4600 tree_draw(struct view
*view
, struct line
*line
, unsigned int lineno
)
4602 struct tree_entry
*entry
= line
->data
;
4604 if (line
->type
== LINE_TREE_HEAD
) {
4605 if (draw_text(view
, line
->type
, "Directory path /", TRUE
))
4608 if (draw_mode(view
, entry
->mode
))
4611 if (opt_author
&& draw_author(view
, entry
->author
))
4614 if (opt_date
&& draw_date(view
, &entry
->time
))
4617 if (draw_text(view
, line
->type
, entry
->name
, TRUE
))
4625 char file
[SIZEOF_STR
] = "/tmp/tigblob.XXXXXX";
4626 int fd
= mkstemp(file
);
4629 report("Failed to create temporary file");
4630 else if (!io_run_append(blob_ops
.argv
, FORMAT_ALL
, fd
))
4631 report("Failed to save blob data to file");
4639 tree_request(struct view
*view
, enum request request
, struct line
*line
)
4641 enum open_flags flags
;
4644 case REQ_VIEW_BLAME
:
4645 if (line
->type
!= LINE_TREE_FILE
) {
4646 report("Blame only supported for files");
4650 string_copy(opt_ref
, view
->vid
);
4654 if (line
->type
!= LINE_TREE_FILE
) {
4655 report("Edit only supported for files");
4656 } else if (!is_head_commit(view
->vid
)) {
4659 open_editor(opt_file
);
4663 case REQ_TOGGLE_SORT_FIELD
:
4664 case REQ_TOGGLE_SORT_ORDER
:
4665 sort_view(view
, request
, &tree_sort_state
, tree_compare
);
4670 /* quit view if at top of tree */
4671 return REQ_VIEW_CLOSE
;
4674 line
= &view
->line
[1];
4684 /* Cleanup the stack if the tree view is at a different tree. */
4685 while (!*opt_path
&& tree_stack
)
4686 pop_tree_stack_entry();
4688 switch (line
->type
) {
4690 /* Depending on whether it is a subdirectory or parent link
4691 * mangle the path buffer. */
4692 if (line
== &view
->line
[1] && *opt_path
) {
4693 pop_tree_stack_entry();
4696 const char *basename
= tree_path(line
);
4698 push_tree_stack_entry(basename
, view
->lineno
);
4701 /* Trees and subtrees share the same ID, so they are not not
4702 * unique like blobs. */
4703 flags
= OPEN_RELOAD
;
4704 request
= REQ_VIEW_TREE
;
4707 case LINE_TREE_FILE
:
4708 flags
= display
[0] == view
? OPEN_SPLIT
: OPEN_DEFAULT
;
4709 request
= REQ_VIEW_BLOB
;
4716 open_view(view
, request
, flags
);
4717 if (request
== REQ_VIEW_TREE
)
4718 view
->lineno
= tree_lineno
;
4724 tree_grep(struct view
*view
, struct line
*line
)
4726 struct tree_entry
*entry
= line
->data
;
4727 const char *text
[] = {
4729 opt_author
? entry
->author
: "",
4730 mkdate(&entry
->time
, opt_date
),
4734 return grep_text(view
, text
);
4738 tree_select(struct view
*view
, struct line
*line
)
4740 struct tree_entry
*entry
= line
->data
;
4742 if (line
->type
== LINE_TREE_FILE
) {
4743 string_copy_rev(ref_blob
, entry
->id
);
4744 string_format(opt_file
, "%s%s", opt_path
, tree_path(line
));
4746 } else if (line
->type
!= LINE_TREE_DIR
) {
4750 string_copy_rev(view
->ref
, entry
->id
);
4754 tree_prepare(struct view
*view
)
4756 if (view
->lines
== 0 && opt_prefix
[0]) {
4757 char *pos
= opt_prefix
;
4759 while (pos
&& *pos
) {
4760 char *end
= strchr(pos
, '/');
4764 push_tree_stack_entry(pos
, 0);
4772 } else if (strcmp(view
->vid
, view
->id
)) {
4776 return io_format(&view
->io
, opt_cdup
, IO_RD
, view
->ops
->argv
, FORMAT_ALL
);
4779 static const char *tree_argv
[SIZEOF_ARG
] = {
4780 "git", "ls-tree", "%(commit)", "%(directory)", NULL
4783 static struct view_ops tree_ops
= {
4796 blob_read(struct view
*view
, char *line
)
4800 return add_line_text(view
, line
, LINE_DEFAULT
) != NULL
;
4804 blob_request(struct view
*view
, enum request request
, struct line
*line
)
4811 return pager_request(view
, request
, line
);
4815 static const char *blob_argv
[SIZEOF_ARG
] = {
4816 "git", "cat-file", "blob", "%(blob)", NULL
4819 static struct view_ops blob_ops
= {
4833 * Loading the blame view is a two phase job:
4835 * 1. File content is read either using opt_file from the
4836 * filesystem or using git-cat-file.
4837 * 2. Then blame information is incrementally added by
4838 * reading output from git-blame.
4841 static const char *blame_head_argv
[] = {
4842 "git", "blame", "--incremental", "--", "%(file)", NULL
4845 static const char *blame_ref_argv
[] = {
4846 "git", "blame", "--incremental", "%(ref)", "--", "%(file)", NULL
4849 static const char *blame_cat_file_argv
[] = {
4850 "git", "cat-file", "blob", "%(ref):%(file)", NULL
4853 struct blame_commit
{
4854 char id
[SIZEOF_REV
]; /* SHA1 ID. */
4855 char title
[128]; /* First line of the commit message. */
4856 const char *author
; /* Author of the commit. */
4857 struct time time
; /* Date from the author ident. */
4858 char filename
[128]; /* Name of file. */
4859 bool has_previous
; /* Was a "previous" line detected. */
4863 struct blame_commit
*commit
;
4864 unsigned long lineno
;
4869 blame_open(struct view
*view
)
4871 char path
[SIZEOF_STR
];
4873 if (!view
->parent
&& *opt_prefix
) {
4874 string_copy(path
, opt_file
);
4875 if (!string_format(opt_file
, "%s%s", opt_prefix
, path
))
4879 if (*opt_ref
|| !io_open(&view
->io
, "%s%s", opt_cdup
, opt_file
)) {
4880 if (!io_run_rd(&view
->io
, blame_cat_file_argv
, opt_cdup
, FORMAT_ALL
))
4884 setup_update(view
, opt_file
);
4885 string_format(view
->ref
, "%s ...", opt_file
);
4890 static struct blame_commit
*
4891 get_blame_commit(struct view
*view
, const char *id
)
4895 for (i
= 0; i
< view
->lines
; i
++) {
4896 struct blame
*blame
= view
->line
[i
].data
;
4901 if (!strncmp(blame
->commit
->id
, id
, SIZEOF_REV
- 1))
4902 return blame
->commit
;
4906 struct blame_commit
*commit
= calloc(1, sizeof(*commit
));
4909 string_ncopy(commit
->id
, id
, SIZEOF_REV
);
4915 parse_number(const char **posref
, size_t *number
, size_t min
, size_t max
)
4917 const char *pos
= *posref
;
4920 pos
= strchr(pos
+ 1, ' ');
4921 if (!pos
|| !isdigit(pos
[1]))
4923 *number
= atoi(pos
+ 1);
4924 if (*number
< min
|| *number
> max
)
4931 static struct blame_commit
*
4932 parse_blame_commit(struct view
*view
, const char *text
, int *blamed
)
4934 struct blame_commit
*commit
;
4935 struct blame
*blame
;
4936 const char *pos
= text
+ SIZEOF_REV
- 2;
4937 size_t orig_lineno
= 0;
4941 if (strlen(text
) <= SIZEOF_REV
|| pos
[1] != ' ')
4944 if (!parse_number(&pos
, &orig_lineno
, 1, 9999999) ||
4945 !parse_number(&pos
, &lineno
, 1, view
->lines
) ||
4946 !parse_number(&pos
, &group
, 1, view
->lines
- lineno
+ 1))
4949 commit
= get_blame_commit(view
, text
);
4955 struct line
*line
= &view
->line
[lineno
+ group
- 1];
4958 blame
->commit
= commit
;
4959 blame
->lineno
= orig_lineno
+ group
- 1;
4967 blame_read_file(struct view
*view
, const char *line
, bool *read_file
)
4970 const char **argv
= *opt_ref
? blame_ref_argv
: blame_head_argv
;
4973 if (view
->lines
== 0 && !view
->parent
)
4974 die("No blame exist for %s", view
->vid
);
4976 if (view
->lines
== 0 || !io_run_rd(&io
, argv
, opt_cdup
, FORMAT_ALL
)) {
4977 report("Failed to load blame data");
4981 io_done(view
->pipe
);
4987 size_t linelen
= strlen(line
);
4988 struct blame
*blame
= malloc(sizeof(*blame
) + linelen
);
4993 blame
->commit
= NULL
;
4994 strncpy(blame
->text
, line
, linelen
);
4995 blame
->text
[linelen
] = 0;
4996 return add_line_data(view
, blame
, LINE_BLAME_ID
) != NULL
;
5001 match_blame_header(const char *name
, char **line
)
5003 size_t namelen
= strlen(name
);
5004 bool matched
= !strncmp(name
, *line
, namelen
);
5013 blame_read(struct view
*view
, char *line
)
5015 static struct blame_commit
*commit
= NULL
;
5016 static int blamed
= 0;
5017 static bool read_file
= TRUE
;
5020 return blame_read_file(view
, line
, &read_file
);
5027 string_format(view
->ref
, "%s", view
->vid
);
5028 if (view_is_displayed(view
)) {
5029 update_view_title(view
);
5030 redraw_view_from(view
, 0);
5036 commit
= parse_blame_commit(view
, line
, &blamed
);
5037 string_format(view
->ref
, "%s %2d%%", view
->vid
,
5038 view
->lines
? blamed
* 100 / view
->lines
: 0);
5040 } else if (match_blame_header("author ", &line
)) {
5041 commit
->author
= get_author(line
);
5043 } else if (match_blame_header("author-time ", &line
)) {
5044 parse_timesec(&commit
->time
, line
);
5046 } else if (match_blame_header("author-tz ", &line
)) {
5047 parse_timezone(&commit
->time
, line
);
5049 } else if (match_blame_header("summary ", &line
)) {
5050 string_ncopy(commit
->title
, line
, strlen(line
));
5052 } else if (match_blame_header("previous ", &line
)) {
5053 commit
->has_previous
= TRUE
;
5055 } else if (match_blame_header("filename ", &line
)) {
5056 string_ncopy(commit
->filename
, line
, strlen(line
));
5064 blame_draw(struct view
*view
, struct line
*line
, unsigned int lineno
)
5066 struct blame
*blame
= line
->data
;
5067 struct time
*time
= NULL
;
5068 const char *id
= NULL
, *author
= NULL
;
5069 char text
[SIZEOF_STR
];
5071 if (blame
->commit
&& *blame
->commit
->filename
) {
5072 id
= blame
->commit
->id
;
5073 author
= blame
->commit
->author
;
5074 time
= &blame
->commit
->time
;
5077 if (opt_date
&& draw_date(view
, time
))
5080 if (opt_author
&& draw_author(view
, author
))
5083 if (draw_field(view
, LINE_BLAME_ID
, id
, ID_COLS
, FALSE
))
5086 if (draw_lineno(view
, lineno
))
5089 string_expand(text
, sizeof(text
), blame
->text
, opt_tab_size
);
5090 draw_text(view
, LINE_DEFAULT
, text
, TRUE
);
5095 check_blame_commit(struct blame
*blame
, bool check_null_id
)
5098 report("Commit data not loaded yet");
5099 else if (check_null_id
&& !strcmp(blame
->commit
->id
, NULL_ID
))
5100 report("No commit exist for the selected line");
5107 setup_blame_parent_line(struct view
*view
, struct blame
*blame
)
5109 const char *diff_tree_argv
[] = {
5110 "git", "diff-tree", "-U0", blame
->commit
->id
,
5111 "--", blame
->commit
->filename
, NULL
5114 int parent_lineno
= -1;
5115 int blamed_lineno
= -1;
5118 if (!io_run(&io
, diff_tree_argv
, NULL
, IO_RD
))
5121 while ((line
= io_get(&io
, '\n', TRUE
))) {
5123 char *pos
= strchr(line
, '+');
5125 parent_lineno
= atoi(line
+ 4);
5127 blamed_lineno
= atoi(pos
+ 1);
5129 } else if (*line
== '+' && parent_lineno
!= -1) {
5130 if (blame
->lineno
== blamed_lineno
- 1 &&
5131 !strcmp(blame
->text
, line
+ 1)) {
5132 view
->lineno
= parent_lineno
? parent_lineno
- 1 : 0;
5143 blame_request(struct view
*view
, enum request request
, struct line
*line
)
5145 enum open_flags flags
= display
[0] == view
? OPEN_SPLIT
: OPEN_DEFAULT
;
5146 struct blame
*blame
= line
->data
;
5149 case REQ_VIEW_BLAME
:
5150 if (check_blame_commit(blame
, TRUE
)) {
5151 string_copy(opt_ref
, blame
->commit
->id
);
5152 string_copy(opt_file
, blame
->commit
->filename
);
5154 view
->lineno
= blame
->lineno
;
5155 open_view(view
, REQ_VIEW_BLAME
, OPEN_REFRESH
);
5160 if (check_blame_commit(blame
, TRUE
) &&
5161 select_commit_parent(blame
->commit
->id
, opt_ref
,
5162 blame
->commit
->filename
)) {
5163 string_copy(opt_file
, blame
->commit
->filename
);
5164 setup_blame_parent_line(view
, blame
);
5165 open_view(view
, REQ_VIEW_BLAME
, OPEN_REFRESH
);
5170 if (!check_blame_commit(blame
, FALSE
))
5173 if (view_is_displayed(VIEW(REQ_VIEW_DIFF
)) &&
5174 !strcmp(blame
->commit
->id
, VIEW(REQ_VIEW_DIFF
)->ref
))
5177 if (!strcmp(blame
->commit
->id
, NULL_ID
)) {
5178 struct view
*diff
= VIEW(REQ_VIEW_DIFF
);
5179 const char *diff_index_argv
[] = {
5180 "git", "diff-index", "--root", "--patch-with-stat",
5181 "-C", "-M", "HEAD", "--", view
->vid
, NULL
5184 if (!blame
->commit
->has_previous
) {
5185 diff_index_argv
[1] = "diff";
5186 diff_index_argv
[2] = "--no-color";
5187 diff_index_argv
[6] = "--";
5188 diff_index_argv
[7] = "/dev/null";
5191 if (!prepare_update(diff
, diff_index_argv
, NULL
, FORMAT_DASH
)) {
5192 report("Failed to allocate diff command");
5195 flags
|= OPEN_PREPARED
;
5198 open_view(view
, REQ_VIEW_DIFF
, flags
);
5199 if (VIEW(REQ_VIEW_DIFF
)->pipe
&& !strcmp(blame
->commit
->id
, NULL_ID
))
5200 string_copy_rev(VIEW(REQ_VIEW_DIFF
)->ref
, NULL_ID
);
5211 blame_grep(struct view
*view
, struct line
*line
)
5213 struct blame
*blame
= line
->data
;
5214 struct blame_commit
*commit
= blame
->commit
;
5215 const char *text
[] = {
5217 commit
? commit
->title
: "",
5218 commit
? commit
->id
: "",
5219 commit
&& opt_author
? commit
->author
: "",
5220 commit
? mkdate(&commit
->time
, opt_date
) : "",
5224 return grep_text(view
, text
);
5228 blame_select(struct view
*view
, struct line
*line
)
5230 struct blame
*blame
= line
->data
;
5231 struct blame_commit
*commit
= blame
->commit
;
5236 if (!strcmp(commit
->id
, NULL_ID
))
5237 string_ncopy(ref_commit
, "HEAD", 4);
5239 string_copy_rev(ref_commit
, commit
->id
);
5242 static struct view_ops blame_ops
= {
5258 const char *author
; /* Author of the last commit. */
5259 struct time time
; /* Date of the last activity. */
5260 const struct ref
*ref
; /* Name and commit ID information. */
5263 static const struct ref branch_all
;
5265 static const enum sort_field branch_sort_fields
[] = {
5266 ORDERBY_NAME
, ORDERBY_DATE
, ORDERBY_AUTHOR
5268 static struct sort_state branch_sort_state
= SORT_STATE(branch_sort_fields
);
5271 branch_compare(const void *l1
, const void *l2
)
5273 const struct branch
*branch1
= ((const struct line
*) l1
)->data
;
5274 const struct branch
*branch2
= ((const struct line
*) l2
)->data
;
5276 switch (get_sort_field(branch_sort_state
)) {
5278 return sort_order(branch_sort_state
, timecmp(&branch1
->time
, &branch2
->time
));
5280 case ORDERBY_AUTHOR
:
5281 return sort_order(branch_sort_state
, strcmp(branch1
->author
, branch2
->author
));
5285 return sort_order(branch_sort_state
, strcmp(branch1
->ref
->name
, branch2
->ref
->name
));
5290 branch_draw(struct view
*view
, struct line
*line
, unsigned int lineno
)
5292 struct branch
*branch
= line
->data
;
5293 enum line_type type
= branch
->ref
->head
? LINE_MAIN_HEAD
: LINE_DEFAULT
;
5295 if (opt_date
&& draw_date(view
, &branch
->time
))
5298 if (opt_author
&& draw_author(view
, branch
->author
))
5301 draw_text(view
, type
, branch
->ref
== &branch_all
? "All branches" : branch
->ref
->name
, TRUE
);
5306 branch_request(struct view
*view
, enum request request
, struct line
*line
)
5308 struct branch
*branch
= line
->data
;
5313 open_view(view
, REQ_VIEW_BRANCH
, OPEN_REFRESH
);
5316 case REQ_TOGGLE_SORT_FIELD
:
5317 case REQ_TOGGLE_SORT_ORDER
:
5318 sort_view(view
, request
, &branch_sort_state
, branch_compare
);
5322 if (branch
->ref
== &branch_all
) {
5323 const char *all_branches_argv
[] = {
5324 "git", "log", "--no-color", "--pretty=raw", "--parents",
5325 "--topo-order", "--all", NULL
5327 struct view
*main_view
= VIEW(REQ_VIEW_MAIN
);
5329 if (!prepare_update(main_view
, all_branches_argv
, NULL
, FORMAT_NONE
)) {
5330 report("Failed to load view of all branches");
5333 open_view(view
, REQ_VIEW_MAIN
, OPEN_PREPARED
| OPEN_SPLIT
);
5335 open_view(view
, REQ_VIEW_MAIN
, OPEN_SPLIT
);
5345 branch_read(struct view
*view
, char *line
)
5347 static char id
[SIZEOF_REV
];
5348 struct branch
*reference
;
5354 switch (get_line_type(line
)) {
5356 string_copy_rev(id
, line
+ STRING_SIZE("commit "));
5360 for (i
= 0, reference
= NULL
; i
< view
->lines
; i
++) {
5361 struct branch
*branch
= view
->line
[i
].data
;
5363 if (strcmp(branch
->ref
->id
, id
))
5366 view
->line
[i
].dirty
= TRUE
;
5368 branch
->author
= reference
->author
;
5369 branch
->time
= reference
->time
;
5373 parse_author_line(line
+ STRING_SIZE("author "),
5374 &branch
->author
, &branch
->time
);
5386 branch_open_visitor(void *data
, const struct ref
*ref
)
5388 struct view
*view
= data
;
5389 struct branch
*branch
;
5391 if (ref
->tag
|| ref
->ltag
|| ref
->remote
)
5394 branch
= calloc(1, sizeof(*branch
));
5399 return !!add_line_data(view
, branch
, LINE_DEFAULT
);
5403 branch_open(struct view
*view
)
5405 const char *branch_log
[] = {
5406 "git", "log", "--no-color", "--pretty=raw",
5407 "--simplify-by-decoration", "--all", NULL
5410 if (!io_run_rd(&view
->io
, branch_log
, NULL
, FORMAT_NONE
)) {
5411 report("Failed to load branch data");
5415 setup_update(view
, view
->id
);
5416 branch_open_visitor(view
, &branch_all
);
5417 foreach_ref(branch_open_visitor
, view
);
5418 view
->p_restore
= TRUE
;
5424 branch_grep(struct view
*view
, struct line
*line
)
5426 struct branch
*branch
= line
->data
;
5427 const char *text
[] = {
5433 return grep_text(view
, text
);
5437 branch_select(struct view
*view
, struct line
*line
)
5439 struct branch
*branch
= line
->data
;
5441 string_copy_rev(view
->ref
, branch
->ref
->id
);
5442 string_copy_rev(ref_commit
, branch
->ref
->id
);
5443 string_copy_rev(ref_head
, branch
->ref
->id
);
5446 static struct view_ops branch_ops
= {
5465 char rev
[SIZEOF_REV
];
5466 char name
[SIZEOF_STR
];
5470 char rev
[SIZEOF_REV
];
5471 char name
[SIZEOF_STR
];
5475 static char status_onbranch
[SIZEOF_STR
];
5476 static struct status stage_status
;
5477 static enum line_type stage_line_type
;
5478 static size_t stage_chunks
;
5479 static int *stage_chunk
;
5481 DEFINE_ALLOCATOR(realloc_ints
, int, 32)
5483 /* This should work even for the "On branch" line. */
5485 status_has_none(struct view
*view
, struct line
*line
)
5487 return line
< view
->line
+ view
->lines
&& !line
[1].data
;
5490 /* Get fields from the diff line:
5491 * :100644 100644 06a5d6ae9eca55be2e0e585a152e6b1336f2b20e 0000000000000000000000000000000000000000 M
5494 status_get_diff(struct status
*file
, const char *buf
, size_t bufsize
)
5496 const char *old_mode
= buf
+ 1;
5497 const char *new_mode
= buf
+ 8;
5498 const char *old_rev
= buf
+ 15;
5499 const char *new_rev
= buf
+ 56;
5500 const char *status
= buf
+ 97;
5503 old_mode
[-1] != ':' ||
5504 new_mode
[-1] != ' ' ||
5505 old_rev
[-1] != ' ' ||
5506 new_rev
[-1] != ' ' ||
5510 file
->status
= *status
;
5512 string_copy_rev(file
->old
.rev
, old_rev
);
5513 string_copy_rev(file
->new.rev
, new_rev
);
5515 file
->old
.mode
= strtoul(old_mode
, NULL
, 8);
5516 file
->new.mode
= strtoul(new_mode
, NULL
, 8);
5518 file
->old
.name
[0] = file
->new.name
[0] = 0;
5524 status_run(struct view
*view
, const char *argv
[], char status
, enum line_type type
)
5526 struct status
*unmerged
= NULL
;
5530 if (!io_run(&io
, argv
, opt_cdup
, IO_RD
))
5533 add_line_data(view
, NULL
, type
);
5535 while ((buf
= io_get(&io
, 0, TRUE
))) {
5536 struct status
*file
= unmerged
;
5539 file
= calloc(1, sizeof(*file
));
5540 if (!file
|| !add_line_data(view
, file
, type
))
5544 /* Parse diff info part. */
5546 file
->status
= status
;
5548 string_copy(file
->old
.rev
, NULL_ID
);
5550 } else if (!file
->status
|| file
== unmerged
) {
5551 if (!status_get_diff(file
, buf
, strlen(buf
)))
5554 buf
= io_get(&io
, 0, TRUE
);
5558 /* Collapse all modified entries that follow an
5559 * associated unmerged entry. */
5560 if (unmerged
== file
) {
5561 unmerged
->status
= 'U';
5563 } else if (file
->status
== 'U') {
5568 /* Grab the old name for rename/copy. */
5569 if (!*file
->old
.name
&&
5570 (file
->status
== 'R' || file
->status
== 'C')) {
5571 string_ncopy(file
->old
.name
, buf
, strlen(buf
));
5573 buf
= io_get(&io
, 0, TRUE
);
5578 /* git-ls-files just delivers a NUL separated list of
5579 * file names similar to the second half of the
5580 * git-diff-* output. */
5581 string_ncopy(file
->new.name
, buf
, strlen(buf
));
5582 if (!*file
->old
.name
)
5583 string_copy(file
->old
.name
, file
->new.name
);
5587 if (io_error(&io
)) {
5593 if (!view
->line
[view
->lines
- 1].data
)
5594 add_line_data(view
, NULL
, LINE_STAT_NONE
);
5600 /* Don't show unmerged entries in the staged section. */
5601 static const char *status_diff_index_argv
[] = {
5602 "git", "diff-index", "-z", "--diff-filter=ACDMRTXB",
5603 "--cached", "-M", "HEAD", NULL
5606 static const char *status_diff_files_argv
[] = {
5607 "git", "diff-files", "-z", NULL
5610 static const char *status_list_other_argv
[] = {
5611 "git", "ls-files", "-z", "--others", "--exclude-standard", opt_prefix
, NULL
5614 static const char *status_list_no_head_argv
[] = {
5615 "git", "ls-files", "-z", "--cached", "--exclude-standard", NULL
5618 static const char *update_index_argv
[] = {
5619 "git", "update-index", "-q", "--unmerged", "--refresh", NULL
5622 /* Restore the previous line number to stay in the context or select a
5623 * line with something that can be updated. */
5625 status_restore(struct view
*view
)
5627 if (view
->p_lineno
>= view
->lines
)
5628 view
->p_lineno
= view
->lines
- 1;
5629 while (view
->p_lineno
< view
->lines
&& !view
->line
[view
->p_lineno
].data
)
5631 while (view
->p_lineno
> 0 && !view
->line
[view
->p_lineno
].data
)
5634 /* If the above fails, always skip the "On branch" line. */
5635 if (view
->p_lineno
< view
->lines
)
5636 view
->lineno
= view
->p_lineno
;
5640 if (view
->lineno
< view
->offset
)
5641 view
->offset
= view
->lineno
;
5642 else if (view
->offset
+ view
->height
<= view
->lineno
)
5643 view
->offset
= view
->lineno
- view
->height
+ 1;
5645 view
->p_restore
= FALSE
;
5649 status_update_onbranch(void)
5651 static const char *paths
[][2] = {
5652 { "rebase-apply/rebasing", "Rebasing" },
5653 { "rebase-apply/applying", "Applying mailbox" },
5654 { "rebase-apply/", "Rebasing mailbox" },
5655 { "rebase-merge/interactive", "Interactive rebase" },
5656 { "rebase-merge/", "Rebase merge" },
5657 { "MERGE_HEAD", "Merging" },
5658 { "BISECT_LOG", "Bisecting" },
5659 { "HEAD", "On branch" },
5661 char buf
[SIZEOF_STR
];
5665 if (is_initial_commit()) {
5666 string_copy(status_onbranch
, "Initial commit");
5670 for (i
= 0; i
< ARRAY_SIZE(paths
); i
++) {
5671 char *head
= opt_head
;
5673 if (!string_format(buf
, "%s/%s", opt_git_dir
, paths
[i
][0]) ||
5674 lstat(buf
, &stat
) < 0)
5680 if (io_open(&io
, "%s/rebase-merge/head-name", opt_git_dir
) &&
5681 io_read_buf(&io
, buf
, sizeof(buf
))) {
5683 if (!prefixcmp(head
, "refs/heads/"))
5684 head
+= STRING_SIZE("refs/heads/");
5688 if (!string_format(status_onbranch
, "%s %s", paths
[i
][1], head
))
5689 string_copy(status_onbranch
, opt_head
);
5693 string_copy(status_onbranch
, "Not currently on any branch");
5696 /* First parse staged info using git-diff-index(1), then parse unstaged
5697 * info using git-diff-files(1), and finally untracked files using
5698 * git-ls-files(1). */
5700 status_open(struct view
*view
)
5704 add_line_data(view
, NULL
, LINE_STAT_HEAD
);
5705 status_update_onbranch();
5707 io_run_bg(update_index_argv
);
5709 if (is_initial_commit()) {
5710 if (!status_run(view
, status_list_no_head_argv
, 'A', LINE_STAT_STAGED
))
5712 } else if (!status_run(view
, status_diff_index_argv
, 0, LINE_STAT_STAGED
)) {
5716 if (!status_run(view
, status_diff_files_argv
, 0, LINE_STAT_UNSTAGED
) ||
5717 !status_run(view
, status_list_other_argv
, '?', LINE_STAT_UNTRACKED
))
5720 /* Restore the exact position or use the specialized restore
5722 if (!view
->p_restore
)
5723 status_restore(view
);
5728 status_draw(struct view
*view
, struct line
*line
, unsigned int lineno
)
5730 struct status
*status
= line
->data
;
5731 enum line_type type
;
5735 switch (line
->type
) {
5736 case LINE_STAT_STAGED
:
5737 type
= LINE_STAT_SECTION
;
5738 text
= "Changes to be committed:";
5741 case LINE_STAT_UNSTAGED
:
5742 type
= LINE_STAT_SECTION
;
5743 text
= "Changed but not updated:";
5746 case LINE_STAT_UNTRACKED
:
5747 type
= LINE_STAT_SECTION
;
5748 text
= "Untracked files:";
5751 case LINE_STAT_NONE
:
5752 type
= LINE_DEFAULT
;
5753 text
= " (no files)";
5756 case LINE_STAT_HEAD
:
5757 type
= LINE_STAT_HEAD
;
5758 text
= status_onbranch
;
5765 static char buf
[] = { '?', ' ', ' ', ' ', 0 };
5767 buf
[0] = status
->status
;
5768 if (draw_text(view
, line
->type
, buf
, TRUE
))
5770 type
= LINE_DEFAULT
;
5771 text
= status
->new.name
;
5774 draw_text(view
, type
, text
, TRUE
);
5779 status_load_error(struct view
*view
, struct view
*stage
, const char *path
)
5781 if (displayed_views() == 2 || display
[current_view
] != view
)
5782 maximize_view(view
);
5783 report("Failed to load '%s': %s", path
, io_strerror(&stage
->io
));
5788 status_enter(struct view
*view
, struct line
*line
)
5790 struct status
*status
= line
->data
;
5791 const char *oldpath
= status
? status
->old
.name
: NULL
;
5792 /* Diffs for unmerged entries are empty when passing the new
5793 * path, so leave it empty. */
5794 const char *newpath
= status
&& status
->status
!= 'U' ? status
->new.name
: NULL
;
5796 enum open_flags split
;
5797 struct view
*stage
= VIEW(REQ_VIEW_STAGE
);
5799 if (line
->type
== LINE_STAT_NONE
||
5800 (!status
&& line
[1].type
== LINE_STAT_NONE
)) {
5801 report("No file to diff");
5805 switch (line
->type
) {
5806 case LINE_STAT_STAGED
:
5807 if (is_initial_commit()) {
5808 const char *no_head_diff_argv
[] = {
5809 "git", "diff", "--no-color", "--patch-with-stat",
5810 "--", "/dev/null", newpath
, NULL
5813 if (!prepare_update(stage
, no_head_diff_argv
, opt_cdup
, FORMAT_DASH
))
5814 return status_load_error(view
, stage
, newpath
);
5816 const char *index_show_argv
[] = {
5817 "git", "diff-index", "--root", "--patch-with-stat",
5818 "-C", "-M", "--cached", "HEAD", "--",
5819 oldpath
, newpath
, NULL
5822 if (!prepare_update(stage
, index_show_argv
, opt_cdup
, FORMAT_DASH
))
5823 return status_load_error(view
, stage
, newpath
);
5827 info
= "Staged changes to %s";
5829 info
= "Staged changes";
5832 case LINE_STAT_UNSTAGED
:
5834 const char *files_show_argv
[] = {
5835 "git", "diff-files", "--root", "--patch-with-stat",
5836 "-C", "-M", "--", oldpath
, newpath
, NULL
5839 if (!prepare_update(stage
, files_show_argv
, opt_cdup
, FORMAT_DASH
))
5840 return status_load_error(view
, stage
, newpath
);
5842 info
= "Unstaged changes to %s";
5844 info
= "Unstaged changes";
5847 case LINE_STAT_UNTRACKED
:
5849 report("No file to show");
5853 if (!suffixcmp(status
->new.name
, -1, "/")) {
5854 report("Cannot display a directory");
5858 if (!prepare_update_file(stage
, newpath
))
5859 return status_load_error(view
, stage
, newpath
);
5860 info
= "Untracked file %s";
5863 case LINE_STAT_HEAD
:
5867 die("line type %d not handled in switch", line
->type
);
5870 split
= view_is_displayed(view
) ? OPEN_SPLIT
: 0;
5871 open_view(view
, REQ_VIEW_STAGE
, OPEN_PREPARED
| split
);
5872 if (view_is_displayed(VIEW(REQ_VIEW_STAGE
))) {
5874 stage_status
= *status
;
5876 memset(&stage_status
, 0, sizeof(stage_status
));
5879 stage_line_type
= line
->type
;
5881 string_format(VIEW(REQ_VIEW_STAGE
)->ref
, info
, stage_status
.new.name
);
5888 status_exists(struct status
*status
, enum line_type type
)
5890 struct view
*view
= VIEW(REQ_VIEW_STATUS
);
5891 unsigned long lineno
;
5893 for (lineno
= 0; lineno
< view
->lines
; lineno
++) {
5894 struct line
*line
= &view
->line
[lineno
];
5895 struct status
*pos
= line
->data
;
5897 if (line
->type
!= type
)
5899 if (!pos
&& (!status
|| !status
->status
) && line
[1].data
) {
5900 select_view_line(view
, lineno
);
5903 if (pos
&& !strcmp(status
->new.name
, pos
->new.name
)) {
5904 select_view_line(view
, lineno
);
5914 status_update_prepare(struct io
*io
, enum line_type type
)
5916 const char *staged_argv
[] = {
5917 "git", "update-index", "-z", "--index-info", NULL
5919 const char *others_argv
[] = {
5920 "git", "update-index", "-z", "--add", "--remove", "--stdin", NULL
5924 case LINE_STAT_STAGED
:
5925 return io_run(io
, staged_argv
, opt_cdup
, IO_WR
);
5927 case LINE_STAT_UNSTAGED
:
5928 case LINE_STAT_UNTRACKED
:
5929 return io_run(io
, others_argv
, opt_cdup
, IO_WR
);
5932 die("line type %d not handled in switch", type
);
5938 status_update_write(struct io
*io
, struct status
*status
, enum line_type type
)
5940 char buf
[SIZEOF_STR
];
5944 case LINE_STAT_STAGED
:
5945 if (!string_format_from(buf
, &bufsize
, "%06o %s\t%s%c",
5948 status
->old
.name
, 0))
5952 case LINE_STAT_UNSTAGED
:
5953 case LINE_STAT_UNTRACKED
:
5954 if (!string_format_from(buf
, &bufsize
, "%s%c", status
->new.name
, 0))
5959 die("line type %d not handled in switch", type
);
5962 return io_write(io
, buf
, bufsize
);
5966 status_update_file(struct status
*status
, enum line_type type
)
5971 if (!status_update_prepare(&io
, type
))
5974 result
= status_update_write(&io
, status
, type
);
5975 return io_done(&io
) && result
;
5979 status_update_files(struct view
*view
, struct line
*line
)
5981 char buf
[sizeof(view
->ref
)];
5984 struct line
*pos
= view
->line
+ view
->lines
;
5987 int cursor_y
= -1, cursor_x
= -1;
5989 if (!status_update_prepare(&io
, line
->type
))
5992 for (pos
= line
; pos
< view
->line
+ view
->lines
&& pos
->data
; pos
++)
5995 string_copy(buf
, view
->ref
);
5996 getsyx(cursor_y
, cursor_x
);
5997 for (file
= 0, done
= 5; result
&& file
< files
; line
++, file
++) {
5998 int almost_done
= file
* 100 / files
;
6000 if (almost_done
> done
) {
6002 string_format(view
->ref
, "updating file %u of %u (%d%% done)",
6004 update_view_title(view
);
6005 setsyx(cursor_y
, cursor_x
);
6008 result
= status_update_write(&io
, line
->data
, line
->type
);
6010 string_copy(view
->ref
, buf
);
6012 return io_done(&io
) && result
;
6016 status_update(struct view
*view
)
6018 struct line
*line
= &view
->line
[view
->lineno
];
6020 assert(view
->lines
);
6023 /* This should work even for the "On branch" line. */
6024 if (line
< view
->line
+ view
->lines
&& !line
[1].data
) {
6025 report("Nothing to update");
6029 if (!status_update_files(view
, line
+ 1)) {
6030 report("Failed to update file status");
6034 } else if (!status_update_file(line
->data
, line
->type
)) {
6035 report("Failed to update file status");
6043 status_revert(struct status
*status
, enum line_type type
, bool has_none
)
6045 if (!status
|| type
!= LINE_STAT_UNSTAGED
) {
6046 if (type
== LINE_STAT_STAGED
) {
6047 report("Cannot revert changes to staged files");
6048 } else if (type
== LINE_STAT_UNTRACKED
) {
6049 report("Cannot revert changes to untracked files");
6050 } else if (has_none
) {
6051 report("Nothing to revert");
6053 report("Cannot revert changes to multiple files");
6056 } else if (prompt_yesno("Are you sure you want to revert changes?")) {
6057 char mode
[10] = "100644";
6058 const char *reset_argv
[] = {
6059 "git", "update-index", "--cacheinfo", mode
,
6060 status
->old
.rev
, status
->old
.name
, NULL
6062 const char *checkout_argv
[] = {
6063 "git", "checkout", "--", status
->old
.name
, NULL
6066 if (status
->status
== 'U') {
6067 string_format(mode
, "%5o", status
->old
.mode
);
6069 if (status
->old
.mode
== 0 && status
->new.mode
== 0) {
6070 reset_argv
[2] = "--force-remove";
6071 reset_argv
[3] = status
->old
.name
;
6072 reset_argv
[4] = NULL
;
6075 if (!io_run_fg(reset_argv
, opt_cdup
))
6077 if (status
->old
.mode
== 0 && status
->new.mode
== 0)
6081 return io_run_fg(checkout_argv
, opt_cdup
);
6088 status_request(struct view
*view
, enum request request
, struct line
*line
)
6090 struct status
*status
= line
->data
;
6093 case REQ_STATUS_UPDATE
:
6094 if (!status_update(view
))
6098 case REQ_STATUS_REVERT
:
6099 if (!status_revert(status
, line
->type
, status_has_none(view
, line
)))
6103 case REQ_STATUS_MERGE
:
6104 if (!status
|| status
->status
!= 'U') {
6105 report("Merging only possible for files with unmerged status ('U').");
6108 open_mergetool(status
->new.name
);
6114 if (status
->status
== 'D') {
6115 report("File has been deleted.");
6119 open_editor(status
->new.name
);
6122 case REQ_VIEW_BLAME
:
6128 /* After returning the status view has been split to
6129 * show the stage view. No further reloading is
6131 return status_enter(view
, line
);
6134 /* Simply reload the view. */
6141 open_view(view
, REQ_VIEW_STATUS
, OPEN_RELOAD
);
6147 status_select(struct view
*view
, struct line
*line
)
6149 struct status
*status
= line
->data
;
6150 char file
[SIZEOF_STR
] = "all files";
6154 if (status
&& !string_format(file
, "'%s'", status
->new.name
))
6157 if (!status
&& line
[1].type
== LINE_STAT_NONE
)
6160 switch (line
->type
) {
6161 case LINE_STAT_STAGED
:
6162 text
= "Press %s to unstage %s for commit";
6165 case LINE_STAT_UNSTAGED
:
6166 text
= "Press %s to stage %s for commit";
6169 case LINE_STAT_UNTRACKED
:
6170 text
= "Press %s to stage %s for addition";
6173 case LINE_STAT_HEAD
:
6174 case LINE_STAT_NONE
:
6175 text
= "Nothing to update";
6179 die("line type %d not handled in switch", line
->type
);
6182 if (status
&& status
->status
== 'U') {
6183 text
= "Press %s to resolve conflict in %s";
6184 key
= get_key(KEYMAP_STATUS
, REQ_STATUS_MERGE
);
6187 key
= get_key(KEYMAP_STATUS
, REQ_STATUS_UPDATE
);
6190 string_format(view
->ref
, text
, key
, file
);
6192 string_copy(opt_file
, status
->new.name
);
6196 status_grep(struct view
*view
, struct line
*line
)
6198 struct status
*status
= line
->data
;
6201 const char buf
[2] = { status
->status
, 0 };
6202 const char *text
[] = { status
->new.name
, buf
, NULL
};
6204 return grep_text(view
, text
);
6210 static struct view_ops status_ops
= {
6223 stage_diff_write(struct io
*io
, struct line
*line
, struct line
*end
)
6225 while (line
< end
) {
6226 if (!io_write(io
, line
->data
, strlen(line
->data
)) ||
6227 !io_write(io
, "\n", 1))
6230 if (line
->type
== LINE_DIFF_CHUNK
||
6231 line
->type
== LINE_DIFF_HEADER
)
6238 static struct line
*
6239 stage_diff_find(struct view
*view
, struct line
*line
, enum line_type type
)
6241 for (; view
->line
< line
; line
--)
6242 if (line
->type
== type
)
6249 stage_apply_chunk(struct view
*view
, struct line
*chunk
, bool revert
)
6251 const char *apply_argv
[SIZEOF_ARG
] = {
6252 "git", "apply", "--whitespace=nowarn", NULL
6254 struct line
*diff_hdr
;
6258 diff_hdr
= stage_diff_find(view
, chunk
, LINE_DIFF_HEADER
);
6263 apply_argv
[argc
++] = "--cached";
6264 if (revert
|| stage_line_type
== LINE_STAT_STAGED
)
6265 apply_argv
[argc
++] = "-R";
6266 apply_argv
[argc
++] = "-";
6267 apply_argv
[argc
++] = NULL
;
6268 if (!io_run(&io
, apply_argv
, opt_cdup
, IO_WR
))
6271 if (!stage_diff_write(&io
, diff_hdr
, chunk
) ||
6272 !stage_diff_write(&io
, chunk
, view
->line
+ view
->lines
))
6276 io_run_bg(update_index_argv
);
6278 return chunk
? TRUE
: FALSE
;
6282 stage_update(struct view
*view
, struct line
*line
)
6284 struct line
*chunk
= NULL
;
6286 if (!is_initial_commit() && stage_line_type
!= LINE_STAT_UNTRACKED
)
6287 chunk
= stage_diff_find(view
, line
, LINE_DIFF_CHUNK
);
6290 if (!stage_apply_chunk(view
, chunk
, FALSE
)) {
6291 report("Failed to apply chunk");
6295 } else if (!stage_status
.status
) {
6296 view
= VIEW(REQ_VIEW_STATUS
);
6298 for (line
= view
->line
; line
< view
->line
+ view
->lines
; line
++)
6299 if (line
->type
== stage_line_type
)
6302 if (!status_update_files(view
, line
+ 1)) {
6303 report("Failed to update files");
6307 } else if (!status_update_file(&stage_status
, stage_line_type
)) {
6308 report("Failed to update file");
6316 stage_revert(struct view
*view
, struct line
*line
)
6318 struct line
*chunk
= NULL
;
6320 if (!is_initial_commit() && stage_line_type
== LINE_STAT_UNSTAGED
)
6321 chunk
= stage_diff_find(view
, line
, LINE_DIFF_CHUNK
);
6324 if (!prompt_yesno("Are you sure you want to revert changes?"))
6327 if (!stage_apply_chunk(view
, chunk
, TRUE
)) {
6328 report("Failed to revert chunk");
6334 return status_revert(stage_status
.status
? &stage_status
: NULL
,
6335 stage_line_type
, FALSE
);
6341 stage_next(struct view
*view
, struct line
*line
)
6345 if (!stage_chunks
) {
6346 for (line
= view
->line
; line
< view
->line
+ view
->lines
; line
++) {
6347 if (line
->type
!= LINE_DIFF_CHUNK
)
6350 if (!realloc_ints(&stage_chunk
, stage_chunks
, 1)) {
6351 report("Allocation failure");
6355 stage_chunk
[stage_chunks
++] = line
- view
->line
;
6359 for (i
= 0; i
< stage_chunks
; i
++) {
6360 if (stage_chunk
[i
] > view
->lineno
) {
6361 do_scroll_view(view
, stage_chunk
[i
] - view
->lineno
);
6362 report("Chunk %d of %d", i
+ 1, stage_chunks
);
6367 report("No next chunk found");
6371 stage_request(struct view
*view
, enum request request
, struct line
*line
)
6374 case REQ_STATUS_UPDATE
:
6375 if (!stage_update(view
, line
))
6379 case REQ_STATUS_REVERT
:
6380 if (!stage_revert(view
, line
))
6384 case REQ_STAGE_NEXT
:
6385 if (stage_line_type
== LINE_STAT_UNTRACKED
) {
6386 report("File is untracked; press %s to add",
6387 get_key(KEYMAP_STAGE
, REQ_STATUS_UPDATE
));
6390 stage_next(view
, line
);
6394 if (!stage_status
.new.name
[0])
6396 if (stage_status
.status
== 'D') {
6397 report("File has been deleted.");
6401 open_editor(stage_status
.new.name
);
6405 /* Reload everything ... */
6408 case REQ_VIEW_BLAME
:
6409 if (stage_status
.new.name
[0]) {
6410 string_copy(opt_file
, stage_status
.new.name
);
6416 return pager_request(view
, request
, line
);
6422 VIEW(REQ_VIEW_STATUS
)->p_restore
= TRUE
;
6423 open_view(view
, REQ_VIEW_STATUS
, OPEN_REFRESH
);
6425 /* Check whether the staged entry still exists, and close the
6426 * stage view if it doesn't. */
6427 if (!status_exists(&stage_status
, stage_line_type
)) {
6428 status_restore(VIEW(REQ_VIEW_STATUS
));
6429 return REQ_VIEW_CLOSE
;
6432 if (stage_line_type
== LINE_STAT_UNTRACKED
) {
6433 if (!suffixcmp(stage_status
.new.name
, -1, "/")) {
6434 report("Cannot display a directory");
6438 if (!prepare_update_file(view
, stage_status
.new.name
)) {
6439 report("Failed to open file: %s", strerror(errno
));
6443 open_view(view
, REQ_VIEW_STAGE
, OPEN_REFRESH
);
6448 static struct view_ops stage_ops
= {
6465 char id
[SIZEOF_REV
]; /* SHA1 ID. */
6466 char title
[128]; /* First line of the commit message. */
6467 const char *author
; /* Author of the commit. */
6468 struct time time
; /* Date from the author ident. */
6469 struct ref_list
*refs
; /* Repository references. */
6470 chtype graph
[SIZEOF_REVGRAPH
]; /* Ancestry chain graphics. */
6471 size_t graph_size
; /* The width of the graph array. */
6472 bool has_parents
; /* Rewritten --parents seen. */
6475 /* Size of rev graph with no "padding" columns */
6476 #define SIZEOF_REVITEMS (SIZEOF_REVGRAPH - (SIZEOF_REVGRAPH / 2))
6479 struct rev_graph
*prev
, *next
, *parents
;
6480 char rev
[SIZEOF_REVITEMS
][SIZEOF_REV
];
6482 struct commit
*commit
;
6484 unsigned int boundary
:1;
6487 /* Parents of the commit being visualized. */
6488 static struct rev_graph graph_parents
[4];
6490 /* The current stack of revisions on the graph. */
6491 static struct rev_graph graph_stacks
[4] = {
6492 { &graph_stacks
[3], &graph_stacks
[1], &graph_parents
[0] },
6493 { &graph_stacks
[0], &graph_stacks
[2], &graph_parents
[1] },
6494 { &graph_stacks
[1], &graph_stacks
[3], &graph_parents
[2] },
6495 { &graph_stacks
[2], &graph_stacks
[0], &graph_parents
[3] },
6499 graph_parent_is_merge(struct rev_graph
*graph
)
6501 return graph
->parents
->size
> 1;
6505 append_to_rev_graph(struct rev_graph
*graph
, chtype symbol
)
6507 struct commit
*commit
= graph
->commit
;
6509 if (commit
->graph_size
< ARRAY_SIZE(commit
->graph
) - 1)
6510 commit
->graph
[commit
->graph_size
++] = symbol
;
6514 clear_rev_graph(struct rev_graph
*graph
)
6516 graph
->boundary
= 0;
6517 graph
->size
= graph
->pos
= 0;
6518 graph
->commit
= NULL
;
6519 memset(graph
->parents
, 0, sizeof(*graph
->parents
));
6523 done_rev_graph(struct rev_graph
*graph
)
6525 if (graph_parent_is_merge(graph
) &&
6526 graph
->pos
< graph
->size
- 1 &&
6527 graph
->next
->size
== graph
->size
+ graph
->parents
->size
- 1) {
6528 size_t i
= graph
->pos
+ graph
->parents
->size
- 1;
6530 graph
->commit
->graph_size
= i
* 2;
6531 while (i
< graph
->next
->size
- 1) {
6532 append_to_rev_graph(graph
, ' ');
6533 append_to_rev_graph(graph
, '\\');
6538 clear_rev_graph(graph
);
6542 push_rev_graph(struct rev_graph
*graph
, const char *parent
)
6546 /* "Collapse" duplicate parents lines.
6548 * FIXME: This needs to also update update the drawn graph but
6549 * for now it just serves as a method for pruning graph lines. */
6550 for (i
= 0; i
< graph
->size
; i
++)
6551 if (!strncmp(graph
->rev
[i
], parent
, SIZEOF_REV
))
6554 if (graph
->size
< SIZEOF_REVITEMS
) {
6555 string_copy_rev(graph
->rev
[graph
->size
++], parent
);
6560 get_rev_graph_symbol(struct rev_graph
*graph
)
6564 if (graph
->boundary
)
6565 symbol
= REVGRAPH_BOUND
;
6566 else if (graph
->parents
->size
== 0)
6567 symbol
= REVGRAPH_INIT
;
6568 else if (graph_parent_is_merge(graph
))
6569 symbol
= REVGRAPH_MERGE
;
6570 else if (graph
->pos
>= graph
->size
)
6571 symbol
= REVGRAPH_BRANCH
;
6573 symbol
= REVGRAPH_COMMIT
;
6579 draw_rev_graph(struct rev_graph
*graph
)
6582 chtype separator
, line
;
6584 enum { DEFAULT
, RSHARP
, RDIAG
, LDIAG
};
6585 static struct rev_filler fillers
[] = {
6591 chtype symbol
= get_rev_graph_symbol(graph
);
6592 struct rev_filler
*filler
;
6595 fillers
[DEFAULT
].line
= opt_line_graphics
? ACS_VLINE
: '|';
6596 filler
= &fillers
[DEFAULT
];
6598 for (i
= 0; i
< graph
->pos
; i
++) {
6599 append_to_rev_graph(graph
, filler
->line
);
6600 if (graph_parent_is_merge(graph
->prev
) &&
6601 graph
->prev
->pos
== i
)
6602 filler
= &fillers
[RSHARP
];
6604 append_to_rev_graph(graph
, filler
->separator
);
6607 /* Place the symbol for this revision. */
6608 append_to_rev_graph(graph
, symbol
);
6610 if (graph
->prev
->size
> graph
->size
)
6611 filler
= &fillers
[RDIAG
];
6613 filler
= &fillers
[DEFAULT
];
6617 for (; i
< graph
->size
; i
++) {
6618 append_to_rev_graph(graph
, filler
->separator
);
6619 append_to_rev_graph(graph
, filler
->line
);
6620 if (graph_parent_is_merge(graph
->prev
) &&
6621 i
< graph
->prev
->pos
+ graph
->parents
->size
)
6622 filler
= &fillers
[RSHARP
];
6623 if (graph
->prev
->size
> graph
->size
)
6624 filler
= &fillers
[LDIAG
];
6627 if (graph
->prev
->size
> graph
->size
) {
6628 append_to_rev_graph(graph
, filler
->separator
);
6629 if (filler
->line
!= ' ')
6630 append_to_rev_graph(graph
, filler
->line
);
6634 /* Prepare the next rev graph */
6636 prepare_rev_graph(struct rev_graph
*graph
)
6640 /* First, traverse all lines of revisions up to the active one. */
6641 for (graph
->pos
= 0; graph
->pos
< graph
->size
; graph
->pos
++) {
6642 if (!strcmp(graph
->rev
[graph
->pos
], graph
->commit
->id
))
6645 push_rev_graph(graph
->next
, graph
->rev
[graph
->pos
]);
6648 /* Interleave the new revision parent(s). */
6649 for (i
= 0; !graph
->boundary
&& i
< graph
->parents
->size
; i
++)
6650 push_rev_graph(graph
->next
, graph
->parents
->rev
[i
]);
6652 /* Lastly, put any remaining revisions. */
6653 for (i
= graph
->pos
+ 1; i
< graph
->size
; i
++)
6654 push_rev_graph(graph
->next
, graph
->rev
[i
]);
6658 update_rev_graph(struct view
*view
, struct rev_graph
*graph
)
6660 /* If this is the finalizing update ... */
6662 prepare_rev_graph(graph
);
6664 /* Graph visualization needs a one rev look-ahead,
6665 * so the first update doesn't visualize anything. */
6666 if (!graph
->prev
->commit
)
6669 if (view
->lines
> 2)
6670 view
->line
[view
->lines
- 3].dirty
= 1;
6671 if (view
->lines
> 1)
6672 view
->line
[view
->lines
- 2].dirty
= 1;
6673 draw_rev_graph(graph
->prev
);
6674 done_rev_graph(graph
->prev
->prev
);
6682 static const char *main_argv
[SIZEOF_ARG
] = {
6683 "git", "log", "--no-color", "--pretty=raw", "--parents",
6684 "--topo-order", "%(head)", NULL
6688 main_draw(struct view
*view
, struct line
*line
, unsigned int lineno
)
6690 struct commit
*commit
= line
->data
;
6692 if (!commit
->author
)
6695 if (opt_date
&& draw_date(view
, &commit
->time
))
6698 if (opt_author
&& draw_author(view
, commit
->author
))
6701 if (opt_rev_graph
&& commit
->graph_size
&&
6702 draw_graphic(view
, LINE_MAIN_REVGRAPH
, commit
->graph
, commit
->graph_size
))
6705 if (opt_show_refs
&& commit
->refs
) {
6708 for (i
= 0; i
< commit
->refs
->size
; i
++) {
6709 struct ref
*ref
= commit
->refs
->refs
[i
];
6710 enum line_type type
;
6713 type
= LINE_MAIN_HEAD
;
6715 type
= LINE_MAIN_LOCAL_TAG
;
6717 type
= LINE_MAIN_TAG
;
6718 else if (ref
->tracked
)
6719 type
= LINE_MAIN_TRACKED
;
6720 else if (ref
->remote
)
6721 type
= LINE_MAIN_REMOTE
;
6723 type
= LINE_MAIN_REF
;
6725 if (draw_text(view
, type
, "[", TRUE
) ||
6726 draw_text(view
, type
, ref
->name
, TRUE
) ||
6727 draw_text(view
, type
, "]", TRUE
))
6730 if (draw_text(view
, LINE_DEFAULT
, " ", TRUE
))
6735 draw_text(view
, LINE_DEFAULT
, commit
->title
, TRUE
);
6739 /* Reads git log --pretty=raw output and parses it into the commit struct. */
6741 main_read(struct view
*view
, char *line
)
6743 static struct rev_graph
*graph
= graph_stacks
;
6744 enum line_type type
;
6745 struct commit
*commit
;
6750 if (!view
->lines
&& !view
->parent
)
6751 die("No revisions match the given arguments.");
6752 if (view
->lines
> 0) {
6753 commit
= view
->line
[view
->lines
- 1].data
;
6754 view
->line
[view
->lines
- 1].dirty
= 1;
6755 if (!commit
->author
) {
6758 graph
->commit
= NULL
;
6761 update_rev_graph(view
, graph
);
6763 for (i
= 0; i
< ARRAY_SIZE(graph_stacks
); i
++)
6764 clear_rev_graph(&graph_stacks
[i
]);
6768 type
= get_line_type(line
);
6769 if (type
== LINE_COMMIT
) {
6770 commit
= calloc(1, sizeof(struct commit
));
6774 line
+= STRING_SIZE("commit ");
6776 graph
->boundary
= 1;
6780 string_copy_rev(commit
->id
, line
);
6781 commit
->refs
= get_ref_list(commit
->id
);
6782 graph
->commit
= commit
;
6783 add_line_data(view
, commit
, LINE_MAIN_COMMIT
);
6785 while ((line
= strchr(line
, ' '))) {
6787 push_rev_graph(graph
->parents
, line
);
6788 commit
->has_parents
= TRUE
;
6795 commit
= view
->line
[view
->lines
- 1].data
;
6799 if (commit
->has_parents
)
6801 push_rev_graph(graph
->parents
, line
+ STRING_SIZE("parent "));
6805 parse_author_line(line
+ STRING_SIZE("author "),
6806 &commit
->author
, &commit
->time
);
6807 update_rev_graph(view
, graph
);
6808 graph
= graph
->next
;
6812 /* Fill in the commit title if it has not already been set. */
6813 if (commit
->title
[0])
6816 /* Require titles to start with a non-space character at the
6817 * offset used by git log. */
6818 if (strncmp(line
, " ", 4))
6821 /* Well, if the title starts with a whitespace character,
6822 * try to be forgiving. Otherwise we end up with no title. */
6823 while (isspace(*line
))
6827 /* FIXME: More graceful handling of titles; append "..." to
6828 * shortened titles, etc. */
6830 string_expand(commit
->title
, sizeof(commit
->title
), line
, 1);
6831 view
->line
[view
->lines
- 1].dirty
= 1;
6838 main_request(struct view
*view
, enum request request
, struct line
*line
)
6840 enum open_flags flags
= display
[0] == view
? OPEN_SPLIT
: OPEN_DEFAULT
;
6844 open_view(view
, REQ_VIEW_DIFF
, flags
);
6848 open_view(view
, REQ_VIEW_MAIN
, OPEN_REFRESH
);
6858 grep_refs(struct ref_list
*list
, regex_t
*regex
)
6863 if (!opt_show_refs
|| !list
)
6866 for (i
= 0; i
< list
->size
; i
++) {
6867 if (regexec(regex
, list
->refs
[i
]->name
, 1, &pmatch
, 0) != REG_NOMATCH
)
6875 main_grep(struct view
*view
, struct line
*line
)
6877 struct commit
*commit
= line
->data
;
6878 const char *text
[] = {
6880 opt_author
? commit
->author
: "",
6881 mkdate(&commit
->time
, opt_date
),
6885 return grep_text(view
, text
) || grep_refs(commit
->refs
, view
->regex
);
6889 main_select(struct view
*view
, struct line
*line
)
6891 struct commit
*commit
= line
->data
;
6893 string_copy_rev(view
->ref
, commit
->id
);
6894 string_copy_rev(ref_commit
, view
->ref
);
6897 static struct view_ops main_ops
= {
6913 /* Whether or not the curses interface has been initialized. */
6914 static bool cursed
= FALSE
;
6916 /* Terminal hacks and workarounds. */
6917 static bool use_scroll_redrawwin
;
6918 static bool use_scroll_status_wclear
;
6920 /* The status window is used for polling keystrokes. */
6921 static WINDOW
*status_win
;
6923 /* Reading from the prompt? */
6924 static bool input_mode
= FALSE
;
6926 static bool status_empty
= FALSE
;
6928 /* Update status and title window. */
6930 report(const char *msg
, ...)
6932 struct view
*view
= display
[current_view
];
6938 char buf
[SIZEOF_STR
];
6941 va_start(args
, msg
);
6942 if (vsnprintf(buf
, sizeof(buf
), msg
, args
) >= sizeof(buf
)) {
6943 buf
[sizeof(buf
) - 1] = 0;
6944 buf
[sizeof(buf
) - 2] = '.';
6945 buf
[sizeof(buf
) - 3] = '.';
6946 buf
[sizeof(buf
) - 4] = '.';
6952 if (!status_empty
|| *msg
) {
6955 va_start(args
, msg
);
6957 wmove(status_win
, 0, 0);
6958 if (view
->has_scrolled
&& use_scroll_status_wclear
)
6961 vwprintw(status_win
, msg
, args
);
6962 status_empty
= FALSE
;
6964 status_empty
= TRUE
;
6966 wclrtoeol(status_win
);
6967 wnoutrefresh(status_win
);
6972 update_view_title(view
);
6981 /* Initialize the curses library */
6982 if (isatty(STDIN_FILENO
)) {
6983 cursed
= !!initscr();
6986 /* Leave stdin and stdout alone when acting as a pager. */
6987 opt_tty
= fopen("/dev/tty", "r+");
6989 die("Failed to open /dev/tty");
6990 cursed
= !!newterm(NULL
, opt_tty
, opt_tty
);
6994 die("Failed to initialize curses");
6996 nonl(); /* Disable conversion and detect newlines from input. */
6997 cbreak(); /* Take input chars one at a time, no wait for \n */
6998 noecho(); /* Don't echo input */
6999 leaveok(stdscr
, FALSE
);
7004 getmaxyx(stdscr
, y
, x
);
7005 status_win
= newwin(1, 0, y
- 1, 0);
7007 die("Failed to create status window");
7009 /* Enable keyboard mapping */
7010 keypad(status_win
, TRUE
);
7011 wbkgdset(status_win
, get_line_attr(LINE_STATUS
));
7013 TABSIZE
= opt_tab_size
;
7015 term
= getenv("XTERM_VERSION") ? NULL
: getenv("COLORTERM");
7016 if (term
&& !strcmp(term
, "gnome-terminal")) {
7017 /* In the gnome-terminal-emulator, the message from
7018 * scrolling up one line when impossible followed by
7019 * scrolling down one line causes corruption of the
7020 * status line. This is fixed by calling wclear. */
7021 use_scroll_status_wclear
= TRUE
;
7022 use_scroll_redrawwin
= FALSE
;
7024 } else if (term
&& !strcmp(term
, "xrvt-xpm")) {
7025 /* No problems with full optimizations in xrvt-(unicode)
7027 use_scroll_status_wclear
= use_scroll_redrawwin
= FALSE
;
7030 /* When scrolling in (u)xterm the last line in the
7031 * scrolling direction will update slowly. */
7032 use_scroll_redrawwin
= TRUE
;
7033 use_scroll_status_wclear
= FALSE
;
7038 get_input(int prompt_position
)
7041 int i
, key
, cursor_y
, cursor_x
;
7042 bool loading
= FALSE
;
7044 if (prompt_position
)
7048 foreach_view (view
, i
) {
7050 if (view_is_displayed(view
) && view
->has_scrolled
&&
7051 use_scroll_redrawwin
)
7052 redrawwin(view
->win
);
7053 view
->has_scrolled
= FALSE
;
7058 /* Update the cursor position. */
7059 if (prompt_position
) {
7060 getbegyx(status_win
, cursor_y
, cursor_x
);
7061 cursor_x
= prompt_position
;
7063 view
= display
[current_view
];
7064 getbegyx(view
->win
, cursor_y
, cursor_x
);
7065 cursor_x
= view
->width
- 1;
7066 cursor_y
+= view
->lineno
- view
->offset
;
7068 setsyx(cursor_y
, cursor_x
);
7070 /* Refresh, accept single keystroke of input */
7072 nodelay(status_win
, loading
);
7073 key
= wgetch(status_win
);
7075 /* wgetch() with nodelay() enabled returns ERR when
7076 * there's no input. */
7079 } else if (key
== KEY_RESIZE
) {
7082 getmaxyx(stdscr
, height
, width
);
7084 wresize(status_win
, 1, width
);
7085 mvwin(status_win
, height
- 1, 0);
7086 wnoutrefresh(status_win
);
7088 redraw_display(TRUE
);
7098 prompt_input(const char *prompt
, input_handler handler
, void *data
)
7100 enum input_status status
= INPUT_OK
;
7101 static char buf
[SIZEOF_STR
];
7106 while (status
== INPUT_OK
|| status
== INPUT_SKIP
) {
7109 mvwprintw(status_win
, 0, 0, "%s%.*s", prompt
, pos
, buf
);
7110 wclrtoeol(status_win
);
7112 key
= get_input(pos
+ 1);
7117 status
= pos
? INPUT_STOP
: INPUT_CANCEL
;
7124 status
= INPUT_CANCEL
;
7128 status
= INPUT_CANCEL
;
7132 if (pos
>= sizeof(buf
)) {
7133 report("Input string too long");
7137 status
= handler(data
, buf
, key
);
7138 if (status
== INPUT_OK
)
7139 buf
[pos
++] = (char) key
;
7143 /* Clear the status window */
7144 status_empty
= FALSE
;
7147 if (status
== INPUT_CANCEL
)
7155 static enum input_status
7156 prompt_yesno_handler(void *data
, char *buf
, int c
)
7158 if (c
== 'y' || c
== 'Y')
7160 if (c
== 'n' || c
== 'N')
7161 return INPUT_CANCEL
;
7166 prompt_yesno(const char *prompt
)
7168 char prompt2
[SIZEOF_STR
];
7170 if (!string_format(prompt2
, "%s [Yy/Nn]", prompt
))
7173 return !!prompt_input(prompt2
, prompt_yesno_handler
, NULL
);
7176 static enum input_status
7177 read_prompt_handler(void *data
, char *buf
, int c
)
7179 return isprint(c
) ? INPUT_OK
: INPUT_SKIP
;
7183 read_prompt(const char *prompt
)
7185 return prompt_input(prompt
, read_prompt_handler
, NULL
);
7188 static bool prompt_menu(const char *prompt
, const struct menu_item
*items
, int *selected
)
7190 enum input_status status
= INPUT_OK
;
7193 while (items
[size
].text
)
7196 while (status
== INPUT_OK
) {
7197 const struct menu_item
*item
= &items
[*selected
];
7201 mvwprintw(status_win
, 0, 0, "%s (%d of %d) ",
7202 prompt
, *selected
+ 1, size
);
7204 wprintw(status_win
, "[%c] ", (char) item
->hotkey
);
7205 wprintw(status_win
, "%s", item
->text
);
7206 wclrtoeol(status_win
);
7208 key
= get_input(COLS
- 1);
7213 status
= INPUT_STOP
;
7218 *selected
= *selected
- 1;
7220 *selected
= size
- 1;
7225 *selected
= (*selected
+ 1) % size
;
7229 status
= INPUT_CANCEL
;
7233 for (i
= 0; items
[i
].text
; i
++)
7234 if (items
[i
].hotkey
== key
) {
7236 status
= INPUT_STOP
;
7242 /* Clear the status window */
7243 status_empty
= FALSE
;
7246 return status
!= INPUT_CANCEL
;
7250 * Repository properties
7253 static struct ref
**refs
= NULL
;
7254 static size_t refs_size
= 0;
7255 static struct ref
*refs_head
= NULL
;
7257 static struct ref_list
**ref_lists
= NULL
;
7258 static size_t ref_lists_size
= 0;
7260 DEFINE_ALLOCATOR(realloc_refs
, struct ref
*, 256)
7261 DEFINE_ALLOCATOR(realloc_refs_list
, struct ref
*, 8)
7262 DEFINE_ALLOCATOR(realloc_ref_lists
, struct ref_list
*, 8)
7265 compare_refs(const void *ref1_
, const void *ref2_
)
7267 const struct ref
*ref1
= *(const struct ref
**)ref1_
;
7268 const struct ref
*ref2
= *(const struct ref
**)ref2_
;
7270 if (ref1
->tag
!= ref2
->tag
)
7271 return ref2
->tag
- ref1
->tag
;
7272 if (ref1
->ltag
!= ref2
->ltag
)
7273 return ref2
->ltag
- ref2
->ltag
;
7274 if (ref1
->head
!= ref2
->head
)
7275 return ref2
->head
- ref1
->head
;
7276 if (ref1
->tracked
!= ref2
->tracked
)
7277 return ref2
->tracked
- ref1
->tracked
;
7278 if (ref1
->remote
!= ref2
->remote
)
7279 return ref2
->remote
- ref1
->remote
;
7280 return strcmp(ref1
->name
, ref2
->name
);
7284 foreach_ref(bool (*visitor
)(void *data
, const struct ref
*ref
), void *data
)
7288 for (i
= 0; i
< refs_size
; i
++)
7289 if (!visitor(data
, refs
[i
]))
7299 static struct ref_list
*
7300 get_ref_list(const char *id
)
7302 struct ref_list
*list
;
7305 for (i
= 0; i
< ref_lists_size
; i
++)
7306 if (!strcmp(id
, ref_lists
[i
]->id
))
7307 return ref_lists
[i
];
7309 if (!realloc_ref_lists(&ref_lists
, ref_lists_size
, 1))
7311 list
= calloc(1, sizeof(*list
));
7315 for (i
= 0; i
< refs_size
; i
++) {
7316 if (!strcmp(id
, refs
[i
]->id
) &&
7317 realloc_refs_list(&list
->refs
, list
->size
, 1))
7318 list
->refs
[list
->size
++] = refs
[i
];
7326 qsort(list
->refs
, list
->size
, sizeof(*list
->refs
), compare_refs
);
7327 ref_lists
[ref_lists_size
++] = list
;
7332 read_ref(char *id
, size_t idlen
, char *name
, size_t namelen
)
7334 struct ref
*ref
= NULL
;
7337 bool remote
= FALSE
;
7338 bool tracked
= FALSE
;
7340 int from
= 0, to
= refs_size
- 1;
7342 if (!prefixcmp(name
, "refs/tags/")) {
7343 if (!suffixcmp(name
, namelen
, "^{}")) {
7351 namelen
-= STRING_SIZE("refs/tags/");
7352 name
+= STRING_SIZE("refs/tags/");
7354 } else if (!prefixcmp(name
, "refs/remotes/")) {
7356 namelen
-= STRING_SIZE("refs/remotes/");
7357 name
+= STRING_SIZE("refs/remotes/");
7358 tracked
= !strcmp(opt_remote
, name
);
7360 } else if (!prefixcmp(name
, "refs/heads/")) {
7361 namelen
-= STRING_SIZE("refs/heads/");
7362 name
+= STRING_SIZE("refs/heads/");
7363 if (!strncmp(opt_head
, name
, namelen
))
7366 } else if (!strcmp(name
, "HEAD")) {
7369 namelen
= strlen(opt_head
);
7374 /* If we are reloading or it's an annotated tag, replace the
7375 * previous SHA1 with the resolved commit id; relies on the fact
7376 * git-ls-remote lists the commit id of an annotated tag right
7377 * before the commit id it points to. */
7378 while (from
<= to
) {
7379 size_t pos
= (to
+ from
) / 2;
7380 int cmp
= strcmp(name
, refs
[pos
]->name
);
7394 if (!realloc_refs(&refs
, refs_size
, 1))
7396 ref
= calloc(1, sizeof(*ref
) + namelen
);
7399 memmove(refs
+ from
+ 1, refs
+ from
,
7400 (refs_size
- from
) * sizeof(*refs
));
7402 strncpy(ref
->name
, name
, namelen
);
7409 ref
->remote
= remote
;
7410 ref
->tracked
= tracked
;
7411 string_copy_rev(ref
->id
, id
);
7421 const char *head_argv
[] = {
7422 "git", "symbolic-ref", "HEAD", NULL
7424 static const char *ls_remote_argv
[SIZEOF_ARG
] = {
7425 "git", "ls-remote", opt_git_dir
, NULL
7427 static bool init
= FALSE
;
7431 argv_from_env(ls_remote_argv
, "TIG_LS_REMOTE");
7438 if (io_run_buf(head_argv
, opt_head
, sizeof(opt_head
)) &&
7439 !prefixcmp(opt_head
, "refs/heads/")) {
7440 char *offset
= opt_head
+ STRING_SIZE("refs/heads/");
7442 memmove(opt_head
, offset
, strlen(offset
) + 1);
7446 for (i
= 0; i
< refs_size
; i
++)
7449 if (io_run_load(ls_remote_argv
, "\t", read_ref
) == ERR
)
7452 /* Update the ref lists to reflect changes. */
7453 for (i
= 0; i
< ref_lists_size
; i
++) {
7454 struct ref_list
*list
= ref_lists
[i
];
7457 for (old
= new = 0; old
< list
->size
; old
++)
7458 if (!strcmp(list
->id
, list
->refs
[old
]->id
))
7459 list
->refs
[new++] = list
->refs
[old
];
7467 set_remote_branch(const char *name
, const char *value
, size_t valuelen
)
7469 if (!strcmp(name
, ".remote")) {
7470 string_ncopy(opt_remote
, value
, valuelen
);
7472 } else if (*opt_remote
&& !strcmp(name
, ".merge")) {
7473 size_t from
= strlen(opt_remote
);
7475 if (!prefixcmp(value
, "refs/heads/"))
7476 value
+= STRING_SIZE("refs/heads/");
7478 if (!string_format_from(opt_remote
, &from
, "/%s", value
))
7484 set_repo_config_option(char *name
, char *value
, int (*cmd
)(int, const char **))
7486 const char *argv
[SIZEOF_ARG
] = { name
, "=" };
7487 int argc
= 1 + (cmd
== option_set_command
);
7490 if (!argv_from_string(argv
, &argc
, value
))
7491 config_msg
= "Too many option arguments";
7493 error
= cmd(argc
, argv
);
7496 warn("Option 'tig.%s': %s", name
, config_msg
);
7500 set_environment_variable(const char *name
, const char *value
)
7502 size_t len
= strlen(name
) + 1 + strlen(value
) + 1;
7503 char *env
= malloc(len
);
7506 string_nformat(env
, len
, NULL
, "%s=%s", name
, value
) &&
7514 set_work_tree(const char *value
)
7516 char cwd
[SIZEOF_STR
];
7518 if (!getcwd(cwd
, sizeof(cwd
)))
7519 die("Failed to get cwd path: %s", strerror(errno
));
7520 if (chdir(opt_git_dir
) < 0)
7521 die("Failed to chdir(%s): %s", strerror(errno
));
7522 if (!getcwd(opt_git_dir
, sizeof(opt_git_dir
)))
7523 die("Failed to get git path: %s", strerror(errno
));
7525 die("Failed to chdir(%s): %s", cwd
, strerror(errno
));
7526 if (chdir(value
) < 0)
7527 die("Failed to chdir(%s): %s", value
, strerror(errno
));
7528 if (!getcwd(cwd
, sizeof(cwd
)))
7529 die("Failed to get cwd path: %s", strerror(errno
));
7530 if (!set_environment_variable("GIT_WORK_TREE", cwd
))
7531 die("Failed to set GIT_WORK_TREE to '%s'", cwd
);
7532 if (!set_environment_variable("GIT_DIR", opt_git_dir
))
7533 die("Failed to set GIT_DIR to '%s'", opt_git_dir
);
7534 opt_is_inside_work_tree
= TRUE
;
7538 read_repo_config_option(char *name
, size_t namelen
, char *value
, size_t valuelen
)
7540 if (!strcmp(name
, "i18n.commitencoding"))
7541 string_ncopy(opt_encoding
, value
, valuelen
);
7543 else if (!strcmp(name
, "core.editor"))
7544 string_ncopy(opt_editor
, value
, valuelen
);
7546 else if (!strcmp(name
, "core.worktree"))
7547 set_work_tree(value
);
7549 else if (!prefixcmp(name
, "tig.color."))
7550 set_repo_config_option(name
+ 10, value
, option_color_command
);
7552 else if (!prefixcmp(name
, "tig.bind."))
7553 set_repo_config_option(name
+ 9, value
, option_bind_command
);
7555 else if (!prefixcmp(name
, "tig."))
7556 set_repo_config_option(name
+ 4, value
, option_set_command
);
7558 else if (*opt_head
&& !prefixcmp(name
, "branch.") &&
7559 !strncmp(name
+ 7, opt_head
, strlen(opt_head
)))
7560 set_remote_branch(name
+ 7 + strlen(opt_head
), value
, valuelen
);
7566 load_git_config(void)
7568 const char *config_list_argv
[] = { "git", "config", "--list", NULL
};
7570 return io_run_load(config_list_argv
, "=", read_repo_config_option
);
7574 read_repo_info(char *name
, size_t namelen
, char *value
, size_t valuelen
)
7576 if (!opt_git_dir
[0]) {
7577 string_ncopy(opt_git_dir
, name
, namelen
);
7579 } else if (opt_is_inside_work_tree
== -1) {
7580 /* This can be 3 different values depending on the
7581 * version of git being used. If git-rev-parse does not
7582 * understand --is-inside-work-tree it will simply echo
7583 * the option else either "true" or "false" is printed.
7584 * Default to true for the unknown case. */
7585 opt_is_inside_work_tree
= strcmp(name
, "false") ? TRUE
: FALSE
;
7587 } else if (*name
== '.') {
7588 string_ncopy(opt_cdup
, name
, namelen
);
7591 string_ncopy(opt_prefix
, name
, namelen
);
7598 load_repo_info(void)
7600 const char *rev_parse_argv
[] = {
7601 "git", "rev-parse", "--git-dir", "--is-inside-work-tree",
7602 "--show-cdup", "--show-prefix", NULL
7605 return io_run_load(rev_parse_argv
, "=", read_repo_info
);
7613 static const char usage
[] =
7614 "tig " TIG_VERSION
" (" __DATE__
")\n"
7616 "Usage: tig [options] [revs] [--] [paths]\n"
7617 " or: tig show [options] [revs] [--] [paths]\n"
7618 " or: tig blame [rev] path\n"
7620 " or: tig < [git command output]\n"
7623 " -v, --version Show version and exit\n"
7624 " -h, --help Show help message and exit";
7626 static void __NORETURN
7629 /* XXX: Restore tty modes and let the OS cleanup the rest! */
7635 static void __NORETURN
7636 die(const char *err
, ...)
7642 va_start(args
, err
);
7643 fputs("tig: ", stderr
);
7644 vfprintf(stderr
, err
, args
);
7645 fputs("\n", stderr
);
7652 warn(const char *msg
, ...)
7656 va_start(args
, msg
);
7657 fputs("tig warning: ", stderr
);
7658 vfprintf(stderr
, msg
, args
);
7659 fputs("\n", stderr
);
7664 parse_options(int argc
, const char *argv
[])
7666 enum request request
= REQ_VIEW_MAIN
;
7667 const char *subcommand
;
7668 bool seen_dashdash
= FALSE
;
7669 /* XXX: This is vulnerable to the user overriding options
7670 * required for the main view parser. */
7671 const char *custom_argv
[SIZEOF_ARG
] = {
7672 "git", "log", "--no-color", "--pretty=raw", "--parents",
7673 "--topo-order", NULL
7677 if (!isatty(STDIN_FILENO
)) {
7678 io_open(&VIEW(REQ_VIEW_PAGER
)->io
, "");
7679 return REQ_VIEW_PAGER
;
7685 subcommand
= argv
[1];
7686 if (!strcmp(subcommand
, "status")) {
7688 warn("ignoring arguments after `%s'", subcommand
);
7689 return REQ_VIEW_STATUS
;
7691 } else if (!strcmp(subcommand
, "blame")) {
7692 if (argc
<= 2 || argc
> 4)
7693 die("invalid number of options to blame\n\n%s", usage
);
7697 string_ncopy(opt_ref
, argv
[i
], strlen(argv
[i
]));
7701 string_ncopy(opt_file
, argv
[i
], strlen(argv
[i
]));
7702 return REQ_VIEW_BLAME
;
7704 } else if (!strcmp(subcommand
, "show")) {
7705 request
= REQ_VIEW_DIFF
;
7712 custom_argv
[1] = subcommand
;
7716 for (i
= 1 + !!subcommand
; i
< argc
; i
++) {
7717 const char *opt
= argv
[i
];
7719 if (seen_dashdash
|| !strcmp(opt
, "--")) {
7720 seen_dashdash
= TRUE
;
7722 } else if (!strcmp(opt
, "-v") || !strcmp(opt
, "--version")) {
7723 printf("tig version %s\n", TIG_VERSION
);
7726 } else if (!strcmp(opt
, "-h") || !strcmp(opt
, "--help")) {
7727 printf("%s\n", usage
);
7731 custom_argv
[j
++] = opt
;
7732 if (j
>= ARRAY_SIZE(custom_argv
))
7733 die("command too long");
7736 if (!prepare_update(VIEW(request
), custom_argv
, NULL
, FORMAT_NONE
))
7737 die("Failed to format arguments");
7743 main(int argc
, const char *argv
[])
7745 const char *codeset
= "UTF-8";
7746 enum request request
= parse_options(argc
, argv
);
7750 signal(SIGINT
, quit
);
7751 signal(SIGPIPE
, SIG_IGN
);
7753 if (setlocale(LC_ALL
, "")) {
7754 codeset
= nl_langinfo(CODESET
);
7757 if (load_repo_info() == ERR
)
7758 die("Failed to load repo info.");
7760 if (load_options() == ERR
)
7761 die("Failed to load user config.");
7763 if (load_git_config() == ERR
)
7764 die("Failed to load repo config.");
7766 /* Require a git repository unless when running in pager mode. */
7767 if (!opt_git_dir
[0] && request
!= REQ_VIEW_PAGER
)
7768 die("Not a git repository");
7770 if (*opt_encoding
&& strcmp(codeset
, "UTF-8")) {
7771 opt_iconv_in
= iconv_open("UTF-8", opt_encoding
);
7772 if (opt_iconv_in
== ICONV_NONE
)
7773 die("Failed to initialize character set conversion");
7776 if (codeset
&& strcmp(codeset
, "UTF-8")) {
7777 opt_iconv_out
= iconv_open(codeset
, "UTF-8");
7778 if (opt_iconv_out
== ICONV_NONE
)
7779 die("Failed to initialize character set conversion");
7782 if (load_refs() == ERR
)
7783 die("Failed to load refs.");
7785 foreach_view (view
, i
)
7786 argv_from_env(view
->ops
->argv
, view
->cmd_env
);
7790 if (request
!= REQ_NONE
)
7791 open_view(NULL
, request
, OPEN_PREPARED
);
7792 request
= request
== REQ_NONE
? REQ_VIEW_MAIN
: REQ_NONE
;
7794 while (view_driver(display
[current_view
], request
)) {
7795 int key
= get_input(0);
7797 view
= display
[current_view
];
7798 request
= get_keybinding(view
->keymap
, key
);
7800 /* Some low-level request handling. This keeps access to
7801 * status_win restricted. */
7805 char *cmd
= read_prompt(":");
7807 if (cmd
&& isdigit(*cmd
)) {
7808 int lineno
= view
->lineno
+ 1;
7810 if (parse_int(&lineno
, cmd
, 1, view
->lines
+ 1) == OK
) {
7811 select_view_line(view
, lineno
- 1);
7814 report("Unable to parse '%s' as a line number", cmd
);
7818 struct view
*next
= VIEW(REQ_VIEW_PAGER
);
7819 const char *argv
[SIZEOF_ARG
] = { "git" };
7822 /* When running random commands, initially show the
7823 * command in the title. However, it maybe later be
7824 * overwritten if a commit line is selected. */
7825 string_ncopy(next
->ref
, cmd
, strlen(cmd
));
7827 if (!argv_from_string(argv
, &argc
, cmd
)) {
7828 report("Too many arguments");
7829 } else if (!prepare_update(next
, argv
, NULL
, FORMAT_DASH
)) {
7830 report("Failed to format command");
7832 open_view(view
, REQ_VIEW_PAGER
, OPEN_PREPARED
);
7840 case REQ_SEARCH_BACK
:
7842 const char *prompt
= request
== REQ_SEARCH
? "/" : "?";
7843 char *search
= read_prompt(prompt
);
7846 string_ncopy(opt_search
, search
, strlen(search
));
7847 else if (*opt_search
)
7848 request
= request
== REQ_SEARCH
?