fnc

Check-in Differences
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Difference From 0.10 To 0.11

2022-05-08 13:47
Bump version number: 0.12 (check-in: d32f0aee53 user: mark tags: trunk)
2022-05-08 13:45
CHANGES for 0.11 (check-in: 53c1d7eb57 user: mark tags: trunk, 0.11)
2022-05-08 13:43
Remove redundant fcli_has_unused_args() call from main() (check-in: 2cf1a6ee21 user: mark tags: trunk)
2022-03-23 14:12
Bump version number: 0.11 (check-in: 96169cac63 user: mark tags: trunk)
2022-03-23 14:07
CHANGES for 0.10 (check-in: dc8f00b193 user: mark tags: trunk, 0.10)
2022-03-22 14:54
Expand diff view C-{j,k} key maps to navigate parent blame view. (check-in: d05828fbb7 user: mark tags: trunk)

Changes to CHANGES.md.




























1
2
3
4
5
6
7



























**fnc 0.10** 2022-03-24

- fix gcc 9.3 compiler warnings (i.e., unused variable) (reported by stephan)
- restrict `C` key map for diffing local changes to check-in artifacts
- ensure timeline --branch option ignores cancelled branches (reported by sean)
- fix landlock initialisation of handled fs access perms (patch by Ashish)
- tighten landlock ruleset depending on which fnc command is called
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
**fnc 0.11** 2022-05-08

- handle diff of non-versioned files outside the work tree (reported by Dan)
- replace getpagesize() with portable sysconf(_SC_PAGESIZE) (patch by mgagnon)
- improve robustness by guarding against piped input abuse (reported by Dan)
- improve documentation regarding UTF-8 character encoding and fonts
- implement horizontal scroll of the log message summary line in timeline view
- fix out-of-bounds UB on 32-bit builds (reported by mgagnon)
- convert unified diff renderer to the improved line_type interface
- fix format specifier bug evinced on 32-bit builds (reported by mgagnon)
- improve unicode handling in terminals w/o UTF-8 support (reported by mgagnon)
- handle window resizing of horizontal and vertical splits (reported by mgagnon)
- improve regexp used to identify commit meta lines
- implement `fnc stash` to interactively select hunks to stash (cf. git add -p)
- fix diff regression introduced with `fnc stash` implementation [2870235eef78]
- simplify handling of diff driver error codes (i.e., binary, type, range)
- improve curses WINDOW reporter interface
- dynamically place help dialog title depending on viewport width
- improve return code RC macro to detect empty varargs token
- fix signed/unsigned comparison introduced in [41dfeb9ebb3d]
- display hunk index in `fnc stash` input prompt
- documentation improvements in README
- update in-tree SQLite lib to 3.38.5 with multiple bug fixes
- add `apply` alias for `fnc stash get` to facilitate Fossiler muscle memory
- simplify error, and tailor usage, reporting when handling invalid input
- remove redundant fcli_has_unused_args() call in main()

**fnc 0.10** 2022-03-24

- fix gcc 9.3 compiler warnings (i.e., unused variable) (reported by stephan)
- restrict `C` key map for diffing local changes to check-in artifacts
- ensure timeline --branch option ignores cancelled branches (reported by sean)
- fix landlock initialisation of handled fs access perms (patch by Ashish)
- tighten landlock ruleset depending on which fnc command is called

Changes to README.md.

1
2
3
4
5
6
7
8
9
10
# README

# fnc 0.10

## An interactive ncurses browser for [Fossil][0] repositories.

`fnc` uses [libfossil][1] to create a [`fossil ui`][2] experience in the
terminal.

Tested and confirmed to run on the following amd64 systems (additional platforms


|







1
2
3
4
5
6
7
8
9
10
# README

# fnc 0.11

## An interactive ncurses browser for [Fossil][0] repositories.

`fnc` uses [libfossil][1] to create a [`fossil ui`][2] experience in the
terminal.

Tested and confirmed to run on the following amd64 systems (additional platforms
49
50
51
52
53
54
55

















56
57
58
59
60
61
62
This will install the `fnc` executable and man page into `/usr/local/bin` and
`/usr/local/share/man/man1`, respectively. Alternatively, cryptographically
signed tarballs of the source code and binaries for some of the abovementioned
platforms are available to [download][3].

# Doc


















See `fnc --help` for a quick reference, and the [fnc(1)][4] manual page for more
comprehensive documentation. In-app help can also be accessed with the `?`,
`F1`, or `H` key binding. The following video briefly demonstrates some of the
key bindings in use.

[![fnc demo][5]][6]








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
This will install the `fnc` executable and man page into `/usr/local/bin` and
`/usr/local/share/man/man1`, respectively. Alternatively, cryptographically
signed tarballs of the source code and binaries for some of the abovementioned
platforms are available to [download][3].

# Doc

Commands available in **fnc**:

1. [**stash**](/uv/resources/doc/fnc.1.html#stash)
  - interactively select hunks to stash from the diff of local changes on disk
2. [**timeline**](/uv/resources/doc/fnc.1.html#timeline)
  - hyperlinked chronological commit history of the repository
3. [**diff**](/uv/resources/doc/fnc.1.html#diff)
  - diff of all changes between commits or blobs
4. [**blame**](/uv/resources/doc/fnc.1.html#blame)
  - annotated file displaying commit attribution history of each line
5. [**tree**](/uv/resources/doc/fnc.1.html#tree)
  - navigable file hierarchy of the repository tree
6. [**branch**](/uv/resources/doc/fnc.1.html#branch)
  - hyperlinked list of all public and private branches
7. [**config**](/uv/resources/doc/fnc.1.html#config)
  - configure or view fnc settings

See `fnc --help` for a quick reference, and the [fnc(1)][4] manual page for more
comprehensive documentation. In-app help can also be accessed with the `?`,
`F1`, or `H` key binding. The following video briefly demonstrates some of the
key bindings in use.

[![fnc demo][5]][6]

81
82
83
84
85
86
87



88
89
90
91
92
93
94
and complies with OpenBSD's KNF [style(9)][13]. Any patch containing
user-visible code addition, modification, or deletion (i.e., code that impacts
user interfaces) should concomitantly include updating documentation affected
by the change.

# Screenshots




![diff vsplit](https://fnc.bsdbox.org/uv/resources/img/fnc-diff-vsplit.png "diff vertical split")
![diff hsplit renamed](https://fnc.bsdbox.org/uv/resources/img/fnc-diff-hsplit-renamed.png "diff horizontal split file renamed")
![diff vsplit added](https://fnc.bsdbox.org/uv/resources/img/fnc-diff-vsplit-added.png "diff vertical split file added")
![diff vsplit removed](https://fnc.bsdbox.org/uv/resources/img/fnc-diff-vsplit-removed.png "diff vertical split file removed")
![blame vsplit](https://fnc.bsdbox.org/uv/resources/img/fnc-blame-vsplit.png "blame vertical split")
![tree vsplit](https://fnc.bsdbox.org/uv/resources/img/fnc-tree-vsplit.png "tree vertical split")
![branch hsplit](https://fnc.bsdbox.org/uv/resources/img/fnc-branch-hsplit.png "branch horizontal split")







>
>
>







98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
and complies with OpenBSD's KNF [style(9)][13]. Any patch containing
user-visible code addition, modification, or deletion (i.e., code that impacts
user interfaces) should concomitantly include updating documentation affected
by the change.

# Screenshots

![stash](https://fnc.bsdbox.org/uv/resources/img/fnc-stash.png "fnc stash")
![stash more](https://fnc.bsdbox.org/uv/resources/img/fnc-stash-more.png "stash more")
![stash help](https://fnc.bsdbox.org/uv/resources/img/fnc-stash-help.png "stash help")
![diff vsplit](https://fnc.bsdbox.org/uv/resources/img/fnc-diff-vsplit.png "diff vertical split")
![diff hsplit renamed](https://fnc.bsdbox.org/uv/resources/img/fnc-diff-hsplit-renamed.png "diff horizontal split file renamed")
![diff vsplit added](https://fnc.bsdbox.org/uv/resources/img/fnc-diff-vsplit-added.png "diff vertical split file added")
![diff vsplit removed](https://fnc.bsdbox.org/uv/resources/img/fnc-diff-vsplit-removed.png "diff vertical split file removed")
![blame vsplit](https://fnc.bsdbox.org/uv/resources/img/fnc-blame-vsplit.png "blame vertical split")
![tree vsplit](https://fnc.bsdbox.org/uv/resources/img/fnc-tree-vsplit.png "tree vertical split")
![branch hsplit](https://fnc.bsdbox.org/uv/resources/img/fnc-branch-hsplit.png "branch horizontal split")

Changes to fnc.bld.mk.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#
# FNC Common Build
#

# CONFIGURATION
CC ?=		cc
PREFIX ?=	/usr/local
MANDIR ?=	/share/man
VERSION ?=	0.10

# FLAGS NEEDED TO BUILD SQLITE3
SQLITE_CFLAGS =	${CFLAGS} -Wall -Werror -Wno-sign-compare -pedantic -std=c99 \
		-DNDEBUG=1 \
		-DSQLITE_DQS=0 \
		-DSQLITE_DEFAULT_MEMSTATUS=0 \
		-DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1 \








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#
# FNC Common Build
#

# CONFIGURATION
CC ?=		cc
PREFIX ?=	/usr/local
MANDIR ?=	/share/man
VERSION ?=	0.11

# FLAGS NEEDED TO BUILD SQLITE3
SQLITE_CFLAGS =	${CFLAGS} -Wall -Werror -Wno-sign-compare -pedantic -std=c99 \
		-DNDEBUG=1 \
		-DSQLITE_DQS=0 \
		-DSQLITE_DEFAULT_MEMSTATUS=0 \
		-DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1 \

Changes to include/diff.h.

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#define FNC_DIFF_WIDTH_MASK	((uint64_t)0x0fff0000)    /* SBS column width */
};

struct diff_out_state {
	fsl_output_f	 out;		/* Output callback */
	void		*state;		/* State for this->out() */
	enum line_type	*lines;		/* Diff line type (e.g., minus, plus) */
	uint32_t	*idx;		/* Index into this->lines */
	int		 rc;		/* Error reporting */
	char		 ansi;		/* ANSI colour code */
	struct {
		const fsl_buffer	*file;		/* Diffed file */
		char			*signature;	/* Matching function */
		uint32_t		 lastmatch;	/* Match line index */
		uint32_t		 lastline;	/* Last line scanned */







|







36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#define FNC_DIFF_WIDTH_MASK	((uint64_t)0x0fff0000)    /* SBS column width */
};

struct diff_out_state {
	fsl_output_f	 out;		/* Output callback */
	void		*state;		/* State for this->out() */
	enum line_type	*lines;		/* Diff line type (e.g., minus, plus) */
	uint32_t	 nlines;	/* Index into this->lines */
	int		 rc;		/* Error reporting */
	char		 ansi;		/* ANSI colour code */
	struct {
		const fsl_buffer	*file;		/* Diffed file */
		char			*signature;	/* Matching function */
		uint32_t		 lastmatch;	/* Match line index */
		uint32_t		 lastline;	/* Last line scanned */
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118

int		 unidiff(fsl__diff_cx *, struct diff_out_state *, void *,
		    uint16_t, uint64_t);
int		 unidiff_lineno(struct diff_out_state *, int, int, bool);
int		 unidiff_txt( struct diff_out_state *const, char, fsl_dline *,
		    int, void *);
int		 sbsdiff(fsl__diff_cx *, struct diff_out_state *, void *,
		    uint16_t, uint64_t);
int		 alloc_lines_and_width(fsl__diff_cx *, int *, uint16_t,
		    uint32_t, enum line_type **);
unsigned short	 etcount(const char *str, unsigned short n);
int		 sbsdiff_width(uint64_t);
int		 sbsdiff_separator(struct sbsline *, int, int);
int		 sbsdiff_lineno(struct sbsline *, int, int);
void		 sbsdiff_shift_left(struct sbsline *, const char *);
void		 sbsdiff_simplify_line(struct sbsline *, const char *);
int		 sbsdiff_column(struct diff_out_state *,
		    fsl_buffer const *, int);
int		 sbsdiff_txt(struct sbsline *, fsl_dline *, int);
int		 sbsdiff_newline(struct sbsline *);
int		 sbsdiff_space(struct sbsline *, int, int);
int		 sbsdiff_marker(struct sbsline *, const char *, const char *);
int		 sbsdiff_close_gap(int *);
unsigned char	*sbsdiff_align(fsl_dline *, int, fsl_dline *, int);
int		 sbsdiff_write_change(struct sbsline *, fsl_dline *, int,
		    fsl_dline *, int);








|
<
















>
94
95
96
97
98
99
100
101

102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
int		 unidiff(fsl__diff_cx *, struct diff_out_state *, void *,
		    uint16_t, uint64_t);
int		 unidiff_lineno(struct diff_out_state *, int, int, bool);
int		 unidiff_txt( struct diff_out_state *const, char, fsl_dline *,
		    int, void *);
int		 sbsdiff(fsl__diff_cx *, struct diff_out_state *, void *,
		    uint16_t, uint64_t);
int		 max_sbs_width(fsl__diff_cx *, int *, uint16_t);

unsigned short	 etcount(const char *str, unsigned short n);
int		 sbsdiff_width(uint64_t);
int		 sbsdiff_separator(struct sbsline *, int, int);
int		 sbsdiff_lineno(struct sbsline *, int, int);
void		 sbsdiff_shift_left(struct sbsline *, const char *);
void		 sbsdiff_simplify_line(struct sbsline *, const char *);
int		 sbsdiff_column(struct diff_out_state *,
		    fsl_buffer const *, int);
int		 sbsdiff_txt(struct sbsline *, fsl_dline *, int);
int		 sbsdiff_newline(struct sbsline *);
int		 sbsdiff_space(struct sbsline *, int, int);
int		 sbsdiff_marker(struct sbsline *, const char *, const char *);
int		 sbsdiff_close_gap(int *);
unsigned char	*sbsdiff_align(fsl_dline *, int, fsl_dline *, int);
int		 sbsdiff_write_change(struct sbsline *, fsl_dline *, int,
		    fsl_dline *, int);
int		 add_line_type(enum line_type **, uint32_t *, enum line_type);

Changes to lib/sqlite3.c.

more than 10,000 changes

Changes to lib/sqlite3.h.

142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
** been edited in any way since it was last checked in, then the last
** four hexadecimal digits of the hash may be modified.
**
** See also: [sqlite3_libversion()],
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
#define SQLITE_VERSION        "3.37.0"
#define SQLITE_VERSION_NUMBER 3037000
#define SQLITE_SOURCE_ID      "2021-10-04 11:10:15 8b24c177061c38361588f419eda9b7943b72a0c6b2855b6f39272451b8a1b813"

/*
** CAPI3REF: Run-Time Library Version Numbers
** KEYWORDS: sqlite3_version sqlite3_sourceid
**
** These interfaces provide the same information as the [SQLITE_VERSION],
** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros







|
|
|







142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
** been edited in any way since it was last checked in, then the last
** four hexadecimal digits of the hash may be modified.
**
** See also: [sqlite3_libversion()],
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
#define SQLITE_VERSION        "3.38.5"
#define SQLITE_VERSION_NUMBER 3038005
#define SQLITE_SOURCE_ID      "2022-05-06 15:25:27 78d9c993d404cdfaa7fdd2973fa1052e3da9f66215cff9c5540ebe55c407d9fe"

/*
** CAPI3REF: Run-Time Library Version Numbers
** KEYWORDS: sqlite3_version sqlite3_sourceid
**
** These interfaces provide the same information as the [SQLITE_VERSION],
** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
#define SQLITE_BUSY_TIMEOUT            (SQLITE_BUSY   |  (3<<8))
#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
#define SQLITE_CANTOPEN_DIRTYWAL       (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
#define SQLITE_CANTOPEN_SYMLINK        (SQLITE_CANTOPEN | (6<<8))
#define SQLITE_CANTOPEN_EXISTS         (SQLITE_CANTOPEN | (7<<8))
#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
#define SQLITE_CORRUPT_SEQUENCE        (SQLITE_CORRUPT | (2<<8))
#define SQLITE_CORRUPT_INDEX           (SQLITE_CORRUPT | (3<<8))
#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
#define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))







<







535
536
537
538
539
540
541

542
543
544
545
546
547
548
#define SQLITE_BUSY_TIMEOUT            (SQLITE_BUSY   |  (3<<8))
#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
#define SQLITE_CANTOPEN_DIRTYWAL       (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
#define SQLITE_CANTOPEN_SYMLINK        (SQLITE_CANTOPEN | (6<<8))

#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
#define SQLITE_CORRUPT_SEQUENCE        (SQLITE_CORRUPT | (2<<8))
#define SQLITE_CORRUPT_INDEX           (SQLITE_CORRUPT | (3<<8))
#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
#define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577













578
579
580
581
582
583
584
#define SQLITE_CONSTRAINT_PINNED       (SQLITE_CONSTRAINT |(11<<8))
#define SQLITE_CONSTRAINT_DATATYPE     (SQLITE_CONSTRAINT |(12<<8))
#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
#define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
#define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
#define SQLITE_OK_SYMLINK              (SQLITE_OK | (2<<8))

/*
** CAPI3REF: Flags For File Open Operations
**
** These bit values are intended for use in the
** 3rd parameter to the [sqlite3_open_v2()] interface and
** in the 4th parameter to the [sqlite3_vfs.xOpen] method.













*/
#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */







|







>
>
>
>
>
>
>
>
>
>
>
>
>







562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
#define SQLITE_CONSTRAINT_PINNED       (SQLITE_CONSTRAINT |(11<<8))
#define SQLITE_CONSTRAINT_DATATYPE     (SQLITE_CONSTRAINT |(12<<8))
#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
#define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
#define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
#define SQLITE_OK_SYMLINK              (SQLITE_OK | (2<<8)) /* internal use only */

/*
** CAPI3REF: Flags For File Open Operations
**
** These bit values are intended for use in the
** 3rd parameter to the [sqlite3_open_v2()] interface and
** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
**
** Only those flags marked as "Ok for sqlite3_open_v2()" may be
** used as the third argument to the [sqlite3_open_v2()] interface.
** The other flags have historically been ignored by sqlite3_open_v2(),
** though future versions of SQLite might change so that an error is
** raised if any of the disallowed bits are passed into sqlite3_open_v2().
** Applications should not depend on the historical behavior.
**
** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into
** [sqlite3_open_v2()] does *not* cause the underlying database file
** to be opened using O_EXCL.  Passing SQLITE_OPEN_EXCLUSIVE into
** [sqlite3_open_v2()] has historically be a no-op and might become an
** error in future versions of SQLite.
*/
#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
593
594
595
596
597
598
599

600
601
602
603
604
605
606
#define SQLITE_OPEN_SUPER_JOURNAL    0x00004000  /* VFS only */
#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
#define SQLITE_OPEN_NOFOLLOW         0x01000000  /* Ok for sqlite3_open_v2() */


/* Reserved:                         0x00F00000 */
/* Legacy compatibility: */
#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */


/*







>







605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
#define SQLITE_OPEN_SUPER_JOURNAL    0x00004000  /* VFS only */
#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
#define SQLITE_OPEN_NOFOLLOW         0x01000000  /* Ok for sqlite3_open_v2() */
#define SQLITE_OPEN_EXRESCODE        0x02000000  /* Extended result codes */

/* Reserved:                         0x00F00000 */
/* Legacy compatibility: */
#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */


/*
3412
3413
3414
3415
3416
3417
3418








3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433








3434
3435
3436
3437
3438
3439
3440
** the default shared cache setting provided by
** [sqlite3_enable_shared_cache()].)^
**
** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>
** <dd>The database is opened [shared cache] disabled, overriding
** the default shared cache setting provided by
** [sqlite3_enable_shared_cache()].)^








**
** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
** <dd>The database filename is not allowed to be a symbolic link</dd>
**
** [[OPEN_EXCLUSIVE]] ^(<dt>[SQLITE_OPEN_EXCLUSIVE]</dt>
** <dd>This flag causes the open to fail if the database file already
** exists.  The open will only be success if this flag is used in combination
** with the SQLITE_OPEN_CREATE and SQLITE_OPEN_READWRITE flags and if
** the file does not previously exist.</dd>
** </dl>)^
**
** If the 3rd parameter to sqlite3_open_v2() is not one of the
** required combinations shown above optionally combined with other
** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
** then the behavior is undefined.








**
** ^The fourth parameter to sqlite3_open_v2() is the name of the
** [sqlite3_vfs] object that defines the operating system interface that
** the new database connection should use.  ^If the fourth parameter is
** a NULL pointer then the default [sqlite3_vfs] object is used.
**
** ^If the filename is ":memory:", then a private, temporary in-memory database







>
>
>
>
>
>
>
>



<
<
<
<
<
<





|
>
>
>
>
>
>
>
>







3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442






3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
** the default shared cache setting provided by
** [sqlite3_enable_shared_cache()].)^
**
** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>
** <dd>The database is opened [shared cache] disabled, overriding
** the default shared cache setting provided by
** [sqlite3_enable_shared_cache()].)^
**
** [[OPEN_EXRESCODE]] ^(<dt>[SQLITE_OPEN_EXRESCODE]</dt>
** <dd>The database connection comes up in "extended result code mode".
** In other words, the database behaves has if
** [sqlite3_extended_result_codes(db,1)] where called on the database
** connection as soon as the connection is created. In addition to setting
** the extended result code mode, this flag also causes [sqlite3_open_v2()]
** to return an extended result code.</dd>
**
** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
** <dd>The database filename is not allowed to be a symbolic link</dd>






** </dl>)^
**
** If the 3rd parameter to sqlite3_open_v2() is not one of the
** required combinations shown above optionally combined with other
** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
** then the behavior is undefined.  Historic versions of SQLite
** have silently ignored surplus bits in the flags parameter to
** sqlite3_open_v2(), however that behavior might not be carried through
** into future versions of SQLite and so applications should not rely
** upon it.  Note in particular that the SQLITE_OPEN_EXCLUSIVE flag is a no-op
** for sqlite3_open_v2().  The SQLITE_OPEN_EXCLUSIVE does *not* cause
** the open to fail if the database already exists.  The SQLITE_OPEN_EXCLUSIVE
** flag is intended for use by the [sqlite3_vfs|VFS interface] only, and not
** by sqlite3_open_v2().
**
** ^The fourth parameter to sqlite3_open_v2() is the name of the
** [sqlite3_vfs] object that defines the operating system interface that
** the new database connection should use.  ^If the fourth parameter is
** a NULL pointer then the default [sqlite3_vfs] object is used.
**
** ^If the filename is ":memory:", then a private, temporary in-memory database
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810

3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823







3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843

3844
3845
3846
3847
3848
3849
3850
** [extended result code] even when extended result codes are
** disabled.
**
** The values returned by sqlite3_errcode() and/or
** sqlite3_extended_errcode() might change with each API call.
** Except, there are some interfaces that are guaranteed to never
** change the value of the error code.  The error-code preserving
** interfaces are:
**
** <ul>
** <li> sqlite3_errcode()
** <li> sqlite3_extended_errcode()
** <li> sqlite3_errmsg()
** <li> sqlite3_errmsg16()

** </ul>
**
** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
** text that describes the error, as either UTF-8 or UTF-16 respectively.
** ^(Memory to hold the error message string is managed internally.
** The application does not need to worry about freeing the result.
** However, the error string might be overwritten or deallocated by
** subsequent calls to other SQLite interface functions.)^
**
** ^The sqlite3_errstr() interface returns the English-language text
** that describes the [result code], as UTF-8.
** ^(Memory to hold the error message string is managed internally
** and must not be freed by the application)^.







**
** When the serialized [threading mode] is in use, it might be the
** case that a second error occurs on a separate thread in between
** the time of the first error and the call to these interfaces.
** When that happens, the second error will be reported since these
** interfaces always report the most recent result.  To avoid
** this, each thread can obtain exclusive use of the [database connection] D
** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
** all calls to the interfaces listed here are completed.
**
** If an interface fails with SQLITE_MISUSE, that means the interface
** was invoked incorrectly by the application.  In that case, the
** error code and message may or may not be set.
*/
SQLITE_API int sqlite3_errcode(sqlite3 *db);
SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
SQLITE_API const char *sqlite3_errmsg(sqlite3*);
SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
SQLITE_API const char *sqlite3_errstr(int);


/*
** CAPI3REF: Prepared Statement Object
** KEYWORDS: {prepared statement} {prepared statements}
**
** An instance of this object represents a single SQL statement that
** has been compiled into binary form and is ready to be evaluated.







|






>













>
>
>
>
>
>
>




















>







3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
** [extended result code] even when extended result codes are
** disabled.
**
** The values returned by sqlite3_errcode() and/or
** sqlite3_extended_errcode() might change with each API call.
** Except, there are some interfaces that are guaranteed to never
** change the value of the error code.  The error-code preserving
** interfaces include the following:
**
** <ul>
** <li> sqlite3_errcode()
** <li> sqlite3_extended_errcode()
** <li> sqlite3_errmsg()
** <li> sqlite3_errmsg16()
** <li> sqlite3_error_offset()
** </ul>
**
** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
** text that describes the error, as either UTF-8 or UTF-16 respectively.
** ^(Memory to hold the error message string is managed internally.
** The application does not need to worry about freeing the result.
** However, the error string might be overwritten or deallocated by
** subsequent calls to other SQLite interface functions.)^
**
** ^The sqlite3_errstr() interface returns the English-language text
** that describes the [result code], as UTF-8.
** ^(Memory to hold the error message string is managed internally
** and must not be freed by the application)^.
**
** ^If the most recent error references a specific token in the input
** SQL, the sqlite3_error_offset() interface returns the byte offset
** of the start of that token.  ^The byte offset returned by
** sqlite3_error_offset() assumes that the input SQL is UTF8.
** ^If the most recent error does not reference a specific token in the input
** SQL, then the sqlite3_error_offset() function returns -1.
**
** When the serialized [threading mode] is in use, it might be the
** case that a second error occurs on a separate thread in between
** the time of the first error and the call to these interfaces.
** When that happens, the second error will be reported since these
** interfaces always report the most recent result.  To avoid
** this, each thread can obtain exclusive use of the [database connection] D
** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
** all calls to the interfaces listed here are completed.
**
** If an interface fails with SQLITE_MISUSE, that means the interface
** was invoked incorrectly by the application.  In that case, the
** error code and message may or may not be set.
*/
SQLITE_API int sqlite3_errcode(sqlite3 *db);
SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
SQLITE_API const char *sqlite3_errmsg(sqlite3*);
SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
SQLITE_API const char *sqlite3_errstr(int);
SQLITE_API int sqlite3_error_offset(sqlite3 *db);

/*
** CAPI3REF: Prepared Statement Object
** KEYWORDS: {prepared statement} {prepared statements}
**
** An instance of this object represents a single SQL statement that
** has been compiled into binary form and is ready to be evaluated.
4248
4249
4250
4251
4252
4253
4254




4255
4256
4257
4258
4259
4260
4261
** statement might change the database file.  ^A false return does
** not guarantee that the statement will change the database file.
** ^For example, an UPDATE statement might have a WHERE clause that
** makes it a no-op, but the sqlite3_stmt_readonly() result would still
** be false.  ^Similarly, a CREATE TABLE IF NOT EXISTS statement is a
** read-only no-op if the table already exists, but
** sqlite3_stmt_readonly() still returns false for such a statement.




*/
SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);

/*
** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement
** METHOD: sqlite3_stmt
**







>
>
>
>







4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
** statement might change the database file.  ^A false return does
** not guarantee that the statement will change the database file.
** ^For example, an UPDATE statement might have a WHERE clause that
** makes it a no-op, but the sqlite3_stmt_readonly() result would still
** be false.  ^Similarly, a CREATE TABLE IF NOT EXISTS statement is a
** read-only no-op if the table already exists, but
** sqlite3_stmt_readonly() still returns false for such a statement.
**
** ^If prepared statement X is an [EXPLAIN] or [EXPLAIN QUERY PLAN]
** statement, then sqlite3_stmt_readonly(X) returns the same value as
** if the EXPLAIN or EXPLAIN QUERY PLAN prefix were omitted.
*/
SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);

/*
** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement
** METHOD: sqlite3_stmt
**
4316
4317
4318
4319
4320
4321
4322


4323
4324
4325
4326
4327
4328
4329
** sqlite3_value objects and they can be used interchangeably.  However,
** for maximum code portability it is recommended that applications
** still make the distinction between protected and unprotected
** sqlite3_value objects even when not strictly required.
**
** ^The sqlite3_value objects that are passed as parameters into the
** implementation of [application-defined SQL functions] are protected.


** ^The sqlite3_value object returned by
** [sqlite3_column_value()] is unprotected.
** Unprotected sqlite3_value objects may only be used as arguments
** to [sqlite3_result_value()], [sqlite3_bind_value()], and
** [sqlite3_value_dup()].
** The [sqlite3_value_blob | sqlite3_value_type()] family of
** interfaces require protected sqlite3_value objects.







>
>







4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
** sqlite3_value objects and they can be used interchangeably.  However,
** for maximum code portability it is recommended that applications
** still make the distinction between protected and unprotected
** sqlite3_value objects even when not strictly required.
**
** ^The sqlite3_value objects that are passed as parameters into the
** implementation of [application-defined SQL functions] are protected.
** ^The sqlite3_value objects returned by [sqlite3_vtab_rhs_value()]
** are protected.
** ^The sqlite3_value object returned by
** [sqlite3_column_value()] is unprotected.
** Unprotected sqlite3_value objects may only be used as arguments
** to [sqlite3_result_value()], [sqlite3_bind_value()], and
** [sqlite3_value_dup()].
** The [sqlite3_value_blob | sqlite3_value_type()] family of
** interfaces require protected sqlite3_value objects.
4936
4937
4938
4939
4940
4941
4942




4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
** of the string.  ^For clarity: the values returned by
** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
** bytes in the string, not the number of characters.
**
** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
** even empty strings, are always zero-terminated.  ^The return
** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.




**
** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
** [unprotected sqlite3_value] object.  In a multithreaded environment,
** an unprotected sqlite3_value object may only be used safely with
** [sqlite3_bind_value()] and [sqlite3_result_value()].
** If the [unprotected sqlite3_value] object returned by
** [sqlite3_column_value()] is used in any other way, including calls
** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
** or [sqlite3_value_bytes()], the behavior is not threadsafe.
** Hence, the sqlite3_column_value() interface
** is normally only useful within the implementation of
** [application-defined SQL functions] or [virtual tables], not within
** top-level application code.
**
** The these routines may attempt to convert the datatype of the result.
** ^For example, if the internal representation is FLOAT and a text result
** is requested, [sqlite3_snprintf()] is used internally to perform the
** conversion automatically.  ^(The following table details the conversions
** that are applied:
**
** <blockquote>
** <table border="1">







>
>
>
>














|







4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
** of the string.  ^For clarity: the values returned by
** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
** bytes in the string, not the number of characters.
**
** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
** even empty strings, are always zero-terminated.  ^The return
** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
**
** ^Strings returned by sqlite3_column_text16() always have the endianness
** which is native to the platform, regardless of the text encoding set
** for the database.
**
** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
** [unprotected sqlite3_value] object.  In a multithreaded environment,
** an unprotected sqlite3_value object may only be used safely with
** [sqlite3_bind_value()] and [sqlite3_result_value()].
** If the [unprotected sqlite3_value] object returned by
** [sqlite3_column_value()] is used in any other way, including calls
** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
** or [sqlite3_value_bytes()], the behavior is not threadsafe.
** Hence, the sqlite3_column_value() interface
** is normally only useful within the implementation of
** [application-defined SQL functions] or [virtual tables], not within
** top-level application code.
**
** These routines may attempt to convert the datatype of the result.
** ^For example, if the internal representation is FLOAT and a text result
** is requested, [sqlite3_snprintf()] is used internally to perform the
** conversion automatically.  ^(The following table details the conversions
** that are applied:
**
** <blockquote>
** <table border="1">
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
** <tr><td>  TEXT    <td>   BLOB    <td> No change
** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
** </table>
** </blockquote>)^
**
** Note that when type conversions occur, pointers returned by prior
** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
** sqlite3_column_text16() may be invalidated.
** Type conversions and pointer invalidations might occur







|







5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
** <tr><td>  TEXT    <td>   BLOB    <td> No change
** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
** <tr><td>  BLOB    <td>   TEXT    <td> [CAST] to TEXT, ensure zero terminator
** </table>
** </blockquote>)^
**
** Note that when type conversions occur, pointers returned by prior
** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
** sqlite3_column_text16() may be invalidated.
** Type conversions and pointer invalidations might occur
6387
6388
6389
6390
6391
6392
6393


































































6394
6395
6396
6397
6398
6399
6400
** ^The rollback callback is not invoked if a transaction is
** automatically rolled back because the database connection is closed.
**
** See also the [sqlite3_update_hook()] interface.
*/
SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);



































































/*
** CAPI3REF: Data Change Notification Callbacks
** METHOD: sqlite3
**
** ^The sqlite3_update_hook() interface registers a callback function
** with the [database connection] identified by the first argument







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
** ^The rollback callback is not invoked if a transaction is
** automatically rolled back because the database connection is closed.
**
** See also the [sqlite3_update_hook()] interface.
*/
SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);

/*
** CAPI3REF: Autovacuum Compaction Amount Callback
** METHOD: sqlite3
**
** ^The sqlite3_autovacuum_pages(D,C,P,X) interface registers a callback
** function C that is invoked prior to each autovacuum of the database
** file.  ^The callback is passed a copy of the generic data pointer (P),
** the schema-name of the attached database that is being autovacuumed,
** the the size of the database file in pages, the number of free pages,
** and the number of bytes per page, respectively.  The callback should
** return the number of free pages that should be removed by the
** autovacuum.  ^If the callback returns zero, then no autovacuum happens.
** ^If the value returned is greater than or equal to the number of
** free pages, then a complete autovacuum happens.
**
** <p>^If there are multiple ATTACH-ed database files that are being
** modified as part of a transaction commit, then the autovacuum pages
** callback is invoked separately for each file.
**
** <p><b>The callback is not reentrant.</b> The callback function should
** not attempt to invoke any other SQLite interface.  If it does, bad
** things may happen, including segmentation faults and corrupt database
** files.  The callback function should be a simple function that
** does some arithmetic on its input parameters and returns a result.
**
** ^The X parameter to sqlite3_autovacuum_pages(D,C,P,X) is an optional
** destructor for the P parameter.  ^If X is not NULL, then X(P) is
** invoked whenever the database connection closes or when the callback
** is overwritten by another invocation of sqlite3_autovacuum_pages().
**
** <p>^There is only one autovacuum pages callback per database connection.
** ^Each call to the sqlite3_autovacuum_pages() interface overrides all
** previous invocations for that database connection.  ^If the callback
** argument (C) to sqlite3_autovacuum_pages(D,C,P,X) is a NULL pointer,
** then the autovacuum steps callback is cancelled.  The return value
** from sqlite3_autovacuum_pages() is normally SQLITE_OK, but might
** be some other error code if something goes wrong.  The current
** implementation will only return SQLITE_OK or SQLITE_MISUSE, but other
** return codes might be added in future releases.
**
** <p>If no autovacuum pages callback is specified (the usual case) or
** a NULL pointer is provided for the callback,
** then the default behavior is to vacuum all free pages.  So, in other
** words, the default behavior is the same as if the callback function
** were something like this:
**
** <blockquote><pre>
** &nbsp;   unsigned int demonstration_autovac_pages_callback(
** &nbsp;     void *pClientData,
** &nbsp;     const char *zSchema,
** &nbsp;     unsigned int nDbPage,
** &nbsp;     unsigned int nFreePage,
** &nbsp;     unsigned int nBytePerPage
** &nbsp;   ){
** &nbsp;     return nFreePage;
** &nbsp;   }
** </pre></blockquote>
*/
SQLITE_API int sqlite3_autovacuum_pages(
  sqlite3 *db,
  unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int),
  void*,
  void(*)(void*)
);


/*
** CAPI3REF: Data Change Notification Callbacks
** METHOD: sqlite3
**
** ^The sqlite3_update_hook() interface registers a callback function
** with the [database connection] identified by the first argument
7029
7030
7031
7032
7033
7034
7035
7036
7037






























7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053


7054
7055
7056
7057
7058
7059
7060
#define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */

/*
** CAPI3REF: Virtual Table Constraint Operator Codes
**
** These macros define the allowed values for the
** [sqlite3_index_info].aConstraint[].op field.  Each value represents
** an operator that is part of a constraint term in the wHERE clause of
** a query that uses a [virtual table].






























*/
#define SQLITE_INDEX_CONSTRAINT_EQ         2
#define SQLITE_INDEX_CONSTRAINT_GT         4
#define SQLITE_INDEX_CONSTRAINT_LE         8
#define SQLITE_INDEX_CONSTRAINT_LT        16
#define SQLITE_INDEX_CONSTRAINT_GE        32
#define SQLITE_INDEX_CONSTRAINT_MATCH     64
#define SQLITE_INDEX_CONSTRAINT_LIKE      65
#define SQLITE_INDEX_CONSTRAINT_GLOB      66
#define SQLITE_INDEX_CONSTRAINT_REGEXP    67
#define SQLITE_INDEX_CONSTRAINT_NE        68
#define SQLITE_INDEX_CONSTRAINT_ISNOT     69
#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
#define SQLITE_INDEX_CONSTRAINT_ISNULL    71
#define SQLITE_INDEX_CONSTRAINT_IS        72
#define SQLITE_INDEX_CONSTRAINT_FUNCTION 150



/*
** CAPI3REF: Register A Virtual Table Implementation
** METHOD: sqlite3
**
** ^These routines are used to register a new [virtual table module] name.
** ^Module names must be registered before







|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>







7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
#define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */

/*
** CAPI3REF: Virtual Table Constraint Operator Codes
**
** These macros define the allowed values for the
** [sqlite3_index_info].aConstraint[].op field.  Each value represents
** an operator that is part of a constraint term in the WHERE clause of
** a query that uses a [virtual table].
**
** ^The left-hand operand of the operator is given by the corresponding
** aConstraint[].iColumn field.  ^An iColumn of -1 indicates the left-hand
** operand is the rowid.
** The SQLITE_INDEX_CONSTRAINT_LIMIT and SQLITE_INDEX_CONSTRAINT_OFFSET
** operators have no left-hand operand, and so for those operators the
** corresponding aConstraint[].iColumn is meaningless and should not be
** used.
**
** All operator values from SQLITE_INDEX_CONSTRAINT_FUNCTION through
** value 255 are reserved to represent functions that are overloaded
** by the [xFindFunction|xFindFunction method] of the virtual table
** implementation.
**
** The right-hand operands for each constraint might be accessible using
** the [sqlite3_vtab_rhs_value()] interface.  Usually the right-hand
** operand is only available if it appears as a single constant literal
** in the input SQL.  If the right-hand operand is another column or an
** expression (even a constant expression) or a parameter, then the
** sqlite3_vtab_rhs_value() probably will not be able to extract it.
** ^The SQLITE_INDEX_CONSTRAINT_ISNULL and
** SQLITE_INDEX_CONSTRAINT_ISNOTNULL operators have no right-hand operand
** and hence calls to sqlite3_vtab_rhs_value() for those operators will
** always return SQLITE_NOTFOUND.
**
** The collating sequence to be used for comparison can be found using
** the [sqlite3_vtab_collation()] interface.  For most real-world virtual
** tables, the collating sequence of constraints does not matter (for example
** because the constraints are numeric) and so the sqlite3_vtab_collation()
** interface is no commonly needed.
*/
#define SQLITE_INDEX_CONSTRAINT_EQ          2
#define SQLITE_INDEX_CONSTRAINT_GT          4
#define SQLITE_INDEX_CONSTRAINT_LE          8
#define SQLITE_INDEX_CONSTRAINT_LT         16
#define SQLITE_INDEX_CONSTRAINT_GE         32
#define SQLITE_INDEX_CONSTRAINT_MATCH      64
#define SQLITE_INDEX_CONSTRAINT_LIKE       65
#define SQLITE_INDEX_CONSTRAINT_GLOB       66
#define SQLITE_INDEX_CONSTRAINT_REGEXP     67
#define SQLITE_INDEX_CONSTRAINT_NE         68
#define SQLITE_INDEX_CONSTRAINT_ISNOT      69
#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL  70
#define SQLITE_INDEX_CONSTRAINT_ISNULL     71
#define SQLITE_INDEX_CONSTRAINT_IS         72
#define SQLITE_INDEX_CONSTRAINT_LIMIT      73
#define SQLITE_INDEX_CONSTRAINT_OFFSET     74
#define SQLITE_INDEX_CONSTRAINT_FUNCTION  150

/*
** CAPI3REF: Register A Virtual Table Implementation
** METHOD: sqlite3
**
** ^These routines are used to register a new [virtual table module] name.
** ^Module names must be registered before
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
** no longer needs the pClientData pointer.  ^The destructor will also
** be invoked if the call to sqlite3_create_module_v2() fails.
** ^The sqlite3_create_module()
** interface is equivalent to sqlite3_create_module_v2() with a NULL
** destructor.
**
** ^If the third parameter (the pointer to the sqlite3_module object) is
** NULL then no new module is create and any existing modules with the
** same name are dropped.
**
** See also: [sqlite3_drop_modules()]
*/
SQLITE_API int sqlite3_create_module(
  sqlite3 *db,               /* SQLite connection to register module with */
  const char *zName,         /* Name of the module */







|







7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
** no longer needs the pClientData pointer.  ^The destructor will also
** be invoked if the call to sqlite3_create_module_v2() fails.
** ^The sqlite3_create_module()
** interface is equivalent to sqlite3_create_module_v2() with a NULL
** destructor.
**
** ^If the third parameter (the pointer to the sqlite3_module object) is
** NULL then no new module is created and any existing modules with the
** same name are dropped.
**
** See also: [sqlite3_drop_modules()]
*/
SQLITE_API int sqlite3_create_module(
  sqlite3 *db,               /* SQLite connection to register module with */
  const char *zName,         /* Name of the module */
7851
7852
7853
7854
7855
7856
7857

7858
7859
7860
7861
7862
7863
7864
7865
#define SQLITE_TESTCTRL_PARSER_COVERAGE         26
#define SQLITE_TESTCTRL_RESULT_INTREAL          27
#define SQLITE_TESTCTRL_PRNG_SEED               28
#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     29
#define SQLITE_TESTCTRL_SEEK_COUNT              30
#define SQLITE_TESTCTRL_TRACEFLAGS              31
#define SQLITE_TESTCTRL_TUNE                    32

#define SQLITE_TESTCTRL_LAST                    32  /* Largest TESTCTRL */

/*
** CAPI3REF: SQL Keyword Checking
**
** These routines provide access to the set of SQL language keywords
** recognized by SQLite.  Applications can uses these routines to determine
** whether or not a specific identifier needs to be escaped (for example,







>
|







7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
#define SQLITE_TESTCTRL_PARSER_COVERAGE         26
#define SQLITE_TESTCTRL_RESULT_INTREAL          27
#define SQLITE_TESTCTRL_PRNG_SEED               28
#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     29
#define SQLITE_TESTCTRL_SEEK_COUNT              30
#define SQLITE_TESTCTRL_TRACEFLAGS              31
#define SQLITE_TESTCTRL_TUNE                    32
#define SQLITE_TESTCTRL_LOGEST                  33
#define SQLITE_TESTCTRL_LAST                    33  /* Largest TESTCTRL */

/*
** CAPI3REF: SQL Keyword Checking
**
** These routines provide access to the set of SQL language keywords
** recognized by SQLite.  Applications can uses these routines to determine
** whether or not a specific identifier needs to be escaped (for example,
8373
8374
8375
8376
8377
8378
8379










8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394


8395
8396
8397
8398
8399
8400
8401
**
** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
** <dd>^This is the number of times that the prepared statement has
** been run.  A single "run" for the purposes of this counter is one
** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
** The counter is incremented on the first [sqlite3_step()] call of each
** cycle.










**
** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
** <dd>^This is the approximate number of bytes of heap memory
** used to store the prepared statement.  ^This value is not actually
** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
** </dd>
** </dl>
*/
#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
#define SQLITE_STMTSTATUS_SORT              2
#define SQLITE_STMTSTATUS_AUTOINDEX         3
#define SQLITE_STMTSTATUS_VM_STEP           4
#define SQLITE_STMTSTATUS_REPREPARE         5
#define SQLITE_STMTSTATUS_RUN               6


#define SQLITE_STMTSTATUS_MEMUSED           99

/*
** CAPI3REF: Custom Page Cache Object
**
** The sqlite3_pcache type is opaque.  It is implemented by
** the pluggable module.  The SQLite core has no knowledge of







>
>
>
>
>
>
>
>
>
>















>
>







8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
**
** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
** <dd>^This is the number of times that the prepared statement has
** been run.  A single "run" for the purposes of this counter is one
** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
** The counter is incremented on the first [sqlite3_step()] call of each
** cycle.
**
** [[SQLITE_STMTSTATUS_FILTER_MISS]]
** [[SQLITE_STMTSTATUS_FILTER HIT]]
** <dt>SQLITE_STMTSTATUS_FILTER_HIT<br>
** SQLITE_STMTSTATUS_FILTER_MISS</dt>
** <dd>^SQLITE_STMTSTATUS_FILTER_HIT is the number of times that a join
** step was bypassed because a Bloom filter returned not-found.  The
** corresponding SQLITE_STMTSTATUS_FILTER_MISS value is the number of
** times that the Bloom filter returned a find, and thus the join step
** had to be processed as normal.
**
** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
** <dd>^This is the approximate number of bytes of heap memory
** used to store the prepared statement.  ^This value is not actually
** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
** </dd>
** </dl>
*/
#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
#define SQLITE_STMTSTATUS_SORT              2
#define SQLITE_STMTSTATUS_AUTOINDEX         3
#define SQLITE_STMTSTATUS_VM_STEP           4
#define SQLITE_STMTSTATUS_REPREPARE         5
#define SQLITE_STMTSTATUS_RUN               6
#define SQLITE_STMTSTATUS_FILTER_MISS       7
#define SQLITE_STMTSTATUS_FILTER_HIT        8
#define SQLITE_STMTSTATUS_MEMUSED           99

/*
** CAPI3REF: Custom Page Cache Object
**
** The sqlite3_pcache type is opaque.  It is implemented by
** the pluggable module.  The SQLite core has no knowledge of
9356
9357
9358
9359
9360
9361
9362

9363
9364
9365


9366
9367
9368
9369
9370










9371







9372
9373
9374
9375






































































































































































































































9376
9377
9378
9379
9380
9381
9382
** current implementation, the sqlite3_vtab_nochange() interface does always
** returns false for the enhanced [UPDATE FROM] statement.
*/
SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);

/*
** CAPI3REF: Determine The Collation For a Virtual Table Constraint

**
** This function may only be called from within a call to the [xBestIndex]
** method of a [virtual table].


**
** The first argument must be the sqlite3_index_info object that is the
** first parameter to the xBestIndex() method. The second argument must be
** an index into the aConstraint[] array belonging to the sqlite3_index_info
** structure passed to xBestIndex. This function returns a pointer to a buffer










** containing the name of the collation sequence for the corresponding







** constraint.
*/
SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);







































































































































































































































/*
** CAPI3REF: Conflict resolution modes
** KEYWORDS: {conflict resolution mode}
**
** These constants are returned by [sqlite3_vtab_on_conflict()] to
** inform a [virtual table] implementation what the [ON CONFLICT] mode
** is for the SQL statement being evaluated.







>


|
>
>

|
|
|
|
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
** current implementation, the sqlite3_vtab_nochange() interface does always
** returns false for the enhanced [UPDATE FROM] statement.
*/
SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);

/*
** CAPI3REF: Determine The Collation For a Virtual Table Constraint
** METHOD: sqlite3_index_info
**
** This function may only be called from within a call to the [xBestIndex]
** method of a [virtual table].  This function returns a pointer to a string
** that is the name of the appropriate collation sequence to use for text
** comparisons on the constraint identified by its arguments.
**
** The first argument must be the pointer to the [sqlite3_index_info] object
** that is the first parameter to the xBestIndex() method. The second argument
** must be an index into the aConstraint[] array belonging to the
** sqlite3_index_info structure passed to xBestIndex.
**
** Important:
** The first parameter must be the same pointer that is passed into the
** xBestMethod() method.  The first parameter may not be a pointer to a
** different [sqlite3_index_info] object, even an exact copy.
**
** The return value is computed as follows:
**
** <ol>
** <li><p> If the constraint comes from a WHERE clause expression that contains
**         a [COLLATE operator], then the name of the collation specified by
**         that COLLATE operator is returned.
** <li><p> If there is no COLLATE operator, but the column that is the subject
**         of the constraint specifies an alternative collating sequence via
**         a [COLLATE clause] on the column definition within the CREATE TABLE
**         statement that was passed into [sqlite3_declare_vtab()], then the
**         name of that alternative collating sequence is returned.
** <li><p> Otherwise, "BINARY" is returned.
** </ol>
*/
SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);

/*
** CAPI3REF: Determine if a virtual table query is DISTINCT
** METHOD: sqlite3_index_info
**
** This API may only be used from within an [xBestIndex|xBestIndex method]
** of a [virtual table] implementation. The result of calling this
** interface from outside of xBestIndex() is undefined and probably harmful.
**
** ^The sqlite3_vtab_distinct() interface returns an integer that is
** either 0, 1, or 2.  The integer returned by sqlite3_vtab_distinct()
** gives the virtual table additional information about how the query
** planner wants the output to be ordered. As long as the virtual table
** can meet the ordering requirements of the query planner, it may set
** the "orderByConsumed" flag.
**
** <ol><li value="0"><p>
** ^If the sqlite3_vtab_distinct() interface returns 0, that means
** that the query planner needs the virtual table to return all rows in the
** sort order defined by the "nOrderBy" and "aOrderBy" fields of the
** [sqlite3_index_info] object.  This is the default expectation.  If the
** virtual table outputs all rows in sorted order, then it is always safe for
** the xBestIndex method to set the "orderByConsumed" flag, regardless of
** the return value from sqlite3_vtab_distinct().
** <li value="1"><p>
** ^(If the sqlite3_vtab_distinct() interface returns 1, that means
** that the query planner does not need the rows to be returned in sorted order
** as long as all rows with the same values in all columns identified by the
** "aOrderBy" field are adjacent.)^  This mode is used when the query planner
** is doing a GROUP BY.
** <li value="2"><p>
** ^(If the sqlite3_vtab_distinct() interface returns 2, that means
** that the query planner does not need the rows returned in any particular
** order, as long as rows with the same values in all "aOrderBy" columns
** are adjacent.)^  ^(Furthermore, only a single row for each particular
** combination of values in the columns identified by the "aOrderBy" field
** needs to be returned.)^  ^It is always ok for two or more rows with the same
** values in all "aOrderBy" columns to be returned, as long as all such rows
** are adjacent.  ^The virtual table may, if it chooses, omit extra rows
** that have the same value for all columns identified by "aOrderBy".
** ^However omitting the extra rows is optional.
** This mode is used for a DISTINCT query.
** </ol>
**
** ^For the purposes of comparing virtual table output values to see if the
** values are same value for sorting purposes, two NULL values are considered
** to be the same.  In other words, the comparison operator is "IS"
** (or "IS NOT DISTINCT FROM") and not "==".
**
** If a virtual table implementation is unable to meet the requirements
** specified above, then it must not set the "orderByConsumed" flag in the
** [sqlite3_index_info] object or an incorrect answer may result.
**
** ^A virtual table implementation is always free to return rows in any order
** it wants, as long as the "orderByConsumed" flag is not set.  ^When the
** the "orderByConsumed" flag is unset, the query planner will add extra
** [bytecode] to ensure that the final results returned by the SQL query are
** ordered correctly.  The use of the "orderByConsumed" flag and the
** sqlite3_vtab_distinct() interface is merely an optimization.  ^Careful
** use of the sqlite3_vtab_distinct() interface and the "orderByConsumed"
** flag might help queries against a virtual table to run faster.  Being
** overly aggressive and setting the "orderByConsumed" flag when it is not
** valid to do so, on the other hand, might cause SQLite to return incorrect
** results.
*/
SQLITE_API int sqlite3_vtab_distinct(sqlite3_index_info*);

/*
** CAPI3REF: Identify and handle IN constraints in xBestIndex
**
** This interface may only be used from within an
** [xBestIndex|xBestIndex() method] of a [virtual table] implementation.
** The result of invoking this interface from any other context is
** undefined and probably harmful.
**
** ^(A constraint on a virtual table of the form
** "[IN operator|column IN (...)]" is
** communicated to the xBestIndex method as a
** [SQLITE_INDEX_CONSTRAINT_EQ] constraint.)^  If xBestIndex wants to use
** this constraint, it must set the corresponding
** aConstraintUsage[].argvIndex to a postive integer.  ^(Then, under
** the usual mode of handling IN operators, SQLite generates [bytecode]
** that invokes the [xFilter|xFilter() method] once for each value
** on the right-hand side of the IN operator.)^  Thus the virtual table
** only sees a single value from the right-hand side of the IN operator
** at a time.
**
** In some cases, however, it would be advantageous for the virtual
** table to see all values on the right-hand of the IN operator all at
** once.  The sqlite3_vtab_in() interfaces facilitates this in two ways:
**
** <ol>
** <li><p>
**   ^A call to sqlite3_vtab_in(P,N,-1) will return true (non-zero)
**   if and only if the [sqlite3_index_info|P->aConstraint][N] constraint
**   is an [IN operator] that can be processed all at once.  ^In other words,
**   sqlite3_vtab_in() with -1 in the third argument is a mechanism
**   by which the virtual table can ask SQLite if all-at-once processing
**   of the IN operator is even possible.
**
** <li><p>
**   ^A call to sqlite3_vtab_in(P,N,F) with F==1 or F==0 indicates
**   to SQLite that the virtual table does or does not want to process
**   the IN operator all-at-once, respectively.  ^Thus when the third
**   parameter (F) is non-negative, this interface is the mechanism by
**   which the virtual table tells SQLite how it wants to process the
**   IN operator.
** </ol>
**
** ^The sqlite3_vtab_in(P,N,F) interface can be invoked multiple times
** within the same xBestIndex method call.  ^For any given P,N pair,
** the return value from sqlite3_vtab_in(P,N,F) will always be the same
** within the same xBestIndex call.  ^If the interface returns true
** (non-zero), that means that the constraint is an IN operator
** that can be processed all-at-once.  ^If the constraint is not an IN
** operator or cannot be processed all-at-once, then the interface returns
** false.
**
** ^(All-at-once processing of the IN operator is selected if both of the
** following conditions are met:
**
** <ol>
** <li><p> The P->aConstraintUsage[N].argvIndex value is set to a positive
** integer.  This is how the virtual table tells SQLite that it wants to
** use the N-th constraint.
**
** <li><p> The last call to sqlite3_vtab_in(P,N,F) for which F was
** non-negative had F>=1.
** </ol>)^
**
** ^If either or both of the conditions above are false, then SQLite uses
** the traditional one-at-a-time processing strategy for the IN constraint.
** ^If both conditions are true, then the argvIndex-th parameter to the
** xFilter method will be an [sqlite3_value] that appears to be NULL,
** but which can be passed to [sqlite3_vtab_in_first()] and
** [sqlite3_vtab_in_next()] to find all values on the right-hand side
** of the IN constraint.
*/
SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle);

/*
** CAPI3REF: Find all elements on the right-hand side of an IN constraint.
**
** These interfaces are only useful from within the
** [xFilter|xFilter() method] of a [virtual table] implementation.
** The result of invoking these interfaces from any other context
** is undefined and probably harmful.
**
** The X parameter in a call to sqlite3_vtab_in_first(X,P) or
** sqlite3_vtab_in_next(X,P) must be one of the parameters to the
** xFilter method which invokes these routines, and specifically
** a parameter that was previously selected for all-at-once IN constraint
** processing use the [sqlite3_vtab_in()] interface in the
** [xBestIndex|xBestIndex method].  ^(If the X parameter is not
** an xFilter argument that was selected for all-at-once IN constraint
** processing, then these routines return [SQLITE_MISUSE])^ or perhaps
** exhibit some other undefined or harmful behavior.
**
** ^(Use these routines to access all values on the right-hand side
** of the IN constraint using code like the following:
**
** <blockquote><pre>
** &nbsp;  for(rc=sqlite3_vtab_in_first(pList, &pVal);
** &nbsp;      rc==SQLITE_OK && pVal
** &nbsp;      rc=sqlite3_vtab_in_next(pList, &pVal)
** &nbsp;  ){
** &nbsp;    // do something with pVal
** &nbsp;  }
** &nbsp;  if( rc!=SQLITE_OK ){
** &nbsp;    // an error has occurred
** &nbsp;  }
** </pre></blockquote>)^
**
** ^On success, the sqlite3_vtab_in_first(X,P) and sqlite3_vtab_in_next(X,P)
** routines return SQLITE_OK and set *P to point to the first or next value
** on the RHS of the IN constraint.  ^If there are no more values on the
** right hand side of the IN constraint, then *P is set to NULL and these
** routines return [SQLITE_DONE].  ^The return value might be
** some other value, such as SQLITE_NOMEM, in the event of a malfunction.
**
** The *ppOut values returned by these routines are only valid until the
** next call to either of these routines or until the end of the xFilter
** method from which these routines were called.  If the virtual table
** implementation needs to retain the *ppOut values for longer, it must make
** copies.  The *ppOut values are [protected sqlite3_value|protected].
*/
SQLITE_API int sqlite3_vtab_in_first(sqlite3_value *pVal, sqlite3_value **ppOut);
SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut);

/*
** CAPI3REF: Constraint values in xBestIndex()
** METHOD: sqlite3_index_info
**
** This API may only be used from within the [xBestIndex|xBestIndex method]
** of a [virtual table] implementation. The result of calling this interface
** from outside of an xBestIndex method are undefined and probably harmful.
**
** ^When the sqlite3_vtab_rhs_value(P,J,V) interface is invoked from within
** the [xBestIndex] method of a [virtual table] implementation, with P being
** a copy of the [sqlite3_index_info] object pointer passed into xBestIndex and
** J being a 0-based index into P->aConstraint[], then this routine
** attempts to set *V to the value of the right-hand operand of
** that constraint if the right-hand operand is known.  ^If the
** right-hand operand is not known, then *V is set to a NULL pointer.
** ^The sqlite3_vtab_rhs_value(P,J,V) interface returns SQLITE_OK if
** and only if *V is set to a value.  ^The sqlite3_vtab_rhs_value(P,J,V)
** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th
** constraint is not available.  ^The sqlite3_vtab_rhs_value() interface
** can return an result code other than SQLITE_OK or SQLITE_NOTFOUND if
** something goes wrong.
**
** The sqlite3_vtab_rhs_value() interface is usually only successful if
** the right-hand operand of a constraint is a literal value in the original
** SQL statement.  If the right-hand operand is an expression or a reference
** to some other column or a [host parameter], then sqlite3_vtab_rhs_value()
** will probably return [SQLITE_NOTFOUND].
**
** ^(Some constraints, such as [SQLITE_INDEX_CONSTRAINT_ISNULL] and
** [SQLITE_INDEX_CONSTRAINT_ISNOTNULL], have no right-hand operand.  For such
** constraints, sqlite3_vtab_rhs_value() always returns SQLITE_NOTFOUND.)^
**
** ^The [sqlite3_value] object returned in *V is a protected sqlite3_value
** and remains valid for the duration of the xBestIndex method call.
** ^When xBestIndex returns, the sqlite3_value object returned by
** sqlite3_vtab_rhs_value() is automatically deallocated.
**
** The "_rhs_" in the name of this routine is an abbreviation for
** "Right-Hand Side".
*/
SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **ppVal);

/*
** CAPI3REF: Conflict resolution modes
** KEYWORDS: {conflict resolution mode}
**
** These constants are returned by [sqlite3_vtab_on_conflict()] to
** inform a [virtual table] implementation what the [ON CONFLICT] mode
** is for the SQL statement being evaluated.

Changes to lib/sqlite3ext.h.

333
334
335
336
337
338
339














340
341
342
343
344
345
346
  /* Version 3.32.0 and later */
  char *(*create_filename)(const char*,const char*,const char*,
                           int,const char**);
  void (*free_filename)(char*);
  sqlite3_file *(*database_file_object)(const char*);
  /* Version 3.34.0 and later */
  int (*txn_state)(sqlite3*,const char*);














};

/*
** This is the function signature used for all extension entry points.  It
** is also defined in the file "loadext.c".
*/
typedef int (*sqlite3_loadext_entry)(







>
>
>
>
>
>
>
>
>
>
>
>
>
>







333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
  /* Version 3.32.0 and later */
  char *(*create_filename)(const char*,const char*,const char*,
                           int,const char**);
  void (*free_filename)(char*);
  sqlite3_file *(*database_file_object)(const char*);
  /* Version 3.34.0 and later */
  int (*txn_state)(sqlite3*,const char*);
  /* Version 3.36.1 and later */
  sqlite3_int64 (*changes64)(sqlite3*);
  sqlite3_int64 (*total_changes64)(sqlite3*);
  /* Version 3.37.0 and later */
  int (*autovacuum_pages)(sqlite3*,
     unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int),
     void*, void(*)(void*));
  /* Version 3.38.0 and later */
  int (*error_offset)(sqlite3*);
  int (*vtab_rhs_value)(sqlite3_index_info*,int,sqlite3_value**);
  int (*vtab_distinct)(sqlite3_index_info*);
  int (*vtab_in)(sqlite3_index_info*,int,int);
  int (*vtab_in_first)(sqlite3_value*,sqlite3_value**);
  int (*vtab_in_next)(sqlite3_value*,sqlite3_value**);
};

/*
** This is the function signature used for all extension entry points.  It
** is also defined in the file "loadext.c".
*/
typedef int (*sqlite3_loadext_entry)(
639
640
641
642
643
644
645












646
647
648
649
650
651
652
#define sqlite3_filename_wal           sqlite3_api->filename_wal
/* Version 3.32.0 and later */
#define sqlite3_create_filename        sqlite3_api->create_filename
#define sqlite3_free_filename          sqlite3_api->free_filename
#define sqlite3_database_file_object   sqlite3_api->database_file_object
/* Version 3.34.0 and later */
#define sqlite3_txn_state              sqlite3_api->txn_state












#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */

#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  /* This case when the file really is being compiled as a loadable 
  ** extension */
# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;







>
>
>
>
>
>
>
>
>
>
>
>







653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
#define sqlite3_filename_wal           sqlite3_api->filename_wal
/* Version 3.32.0 and later */
#define sqlite3_create_filename        sqlite3_api->create_filename
#define sqlite3_free_filename          sqlite3_api->free_filename
#define sqlite3_database_file_object   sqlite3_api->database_file_object
/* Version 3.34.0 and later */
#define sqlite3_txn_state              sqlite3_api->txn_state
/* Version 3.36.1 and later */
#define sqlite3_changes64              sqlite3_api->changes64
#define sqlite3_total_changes64        sqlite3_api->total_changes64
/* Version 3.37.0 and later */
#define sqlite3_autovacuum_pages       sqlite3_api->autovacuum_pages
/* Version 3.38.0 and later */
#define sqlite3_error_offset           sqlite3_api->error_offset
#define sqlite3_vtab_rhs_value         sqlite3_api->vtab_rhs_value
#define sqlite3_vtab_distinct          sqlite3_api->vtab_distinct
#define sqlite3_vtab_in                sqlite3_api->vtab_in
#define sqlite3_vtab_in_first          sqlite3_api->vtab_in_first
#define sqlite3_vtab_in_next           sqlite3_api->vtab_in_next
#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */

#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  /* This case when the file really is being compiled as a loadable 
  ** extension */
# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;

Deleted signify/fnc-09-release.pub.

1
2
untrusted comment: fnc 0.9 public key
RWR/Unt0CGtNwq8vE59836HrU7Jt8ETbuxx2mnap+FakP2TCZLEcaS4j
<
<




Added signify/fnc-11-release.pub.





>
>
1
2
untrusted comment: fnc 0.11 public key
RWQIBA4rVoFFDlh8+FWU6Oeg79hcWqdRXv1cTOzrwTeSxKiIUhMd5rRE

Changes to src/diff.c.

190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231


232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
		}
	}
	/* fsl__dump_triples(&c, __FILE__, __LINE__); */  /* DEBUG */
	if (!FLAG_CHK(flags, FNC_DIFF_NOOPT))
		fsl__diff_optimize(&c);
	/* fsl__dump_triples(&c, __FILE__, __LINE__); */  /* DEBUG */

	/*
	 * For SBS diffs, compute total number of lines and set file column
	 * width to the longest line in the diff and encode result in flags.
	 * XXX I'm ambivalent about converting unified diffs to the line_type
	 * interface as it's extra allocations for no immediate gain but creates
	 * opportunities to do cool things; leave it till we want to do them?
	 */
	if ((!sbswidth && FLAG_CHK(flags, FNC_DIFF_SIDEBYSIDE)) ||
	    sbswidth < 0) {
		flags |= ((int)(sbswidth & 0xFFFF)) << 8;
		FLAG_SET(flags, FNC_DIFF_SIDEBYSIDE);
		rc = alloc_lines_and_width(&c, &flags, context, *nlines, lines);
		if (rc)
			goto end;
	}

	if (out) {
		/*
		 * Compute a context or side-by-side diff.
		 * XXX Missing regex support.
		 */
		struct diff_out_state dos = diff_out_state_empty;
		if (FLAG_CHK(flags, FNC_DIFF_PROTOTYPE)) {
			memset(&dos.proto, 0, sizeof(dos.proto));
			dos.proto.file = blob1;
		}
		dos.out = out;
		dos.state = state;
		dos.lines = *lines;
		dos.idx = nlines;
		dos.ansi = !!(FLAG_CHK(flags, FNC_DIFF_ANSI_COLOR));
		if (FLAG_CHK(flags, FNC_DIFF_SIDEBYSIDE))
			rc = sbsdiff(&c, &dos, NULL /*regex*/, context, flags);
		else
			rc = unidiff(&c, &dos, NULL /*regex*/, context, flags);


	} else if (rawdata) {
		/* Return array of COPY/DELETE/INSERT triples. */
		*rawdata = c.aEdit;
		c.aEdit = NULL;
	}
end:
	fsl_free(c.aFrom);
	fsl_free(c.aTo);
	fsl_free(c.aEdit);
	return rc;
}

/*
 * Iterate copy elements in the c->aEdit 3-tuple to compute start and end lines,
 * including surrounding ctxt, of each chunk in the diff. Add result to nlines,
 * allocate the total and assign to *lines, which must be disposed of by the
 * caller. For SBS diffs, find the longest line and encode the length in *flags.
 */
int
alloc_lines_and_width(fsl__diff_cx *c, int *flags, uint16_t ctxt,
    uint32_t nlines, enum line_type **lines)
{
	int		i, j, k;
	int		endl, endr, start; /* Start and end of l+r chunks */
	uint32_t	n = 0;		   /* Number of lines in the diff */
	unsigned short	sz, sbswidth;	   /* Size of each line and max width */

	j = endl = endr = start = 0;
	k = c->nEdit;
	sbswidth = (*flags & FNC_DIFF_SIDEBYSIDE) ? sbsdiff_width(*flags) : 0;

	/* Find minimal copy/delete/insert triples. */







<
<
|
<
<
<
<




|

















|





>
>













<
<
<
|


|
<



<







190
191
192
193
194
195
196


197




198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240



241
242
243
244

245
246
247

248
249
250
251
252
253
254
		}
	}
	/* fsl__dump_triples(&c, __FILE__, __LINE__); */  /* DEBUG */
	if (!FLAG_CHK(flags, FNC_DIFF_NOOPT))
		fsl__diff_optimize(&c);
	/* fsl__dump_triples(&c, __FILE__, __LINE__); */  /* DEBUG */



	/* Encode longest line length in flags to set max sbs diff width */




	if ((!sbswidth && FLAG_CHK(flags, FNC_DIFF_SIDEBYSIDE)) ||
	    sbswidth < 0) {
		flags |= ((int)(sbswidth & 0xFFFF)) << 8;
		FLAG_SET(flags, FNC_DIFF_SIDEBYSIDE);
		rc = max_sbs_width(&c, &flags, context);
		if (rc)
			goto end;
	}

	if (out) {
		/*
		 * Compute a context or side-by-side diff.
		 * XXX Missing regex support.
		 */
		struct diff_out_state dos = diff_out_state_empty;
		if (FLAG_CHK(flags, FNC_DIFF_PROTOTYPE)) {
			memset(&dos.proto, 0, sizeof(dos.proto));
			dos.proto.file = blob1;
		}
		dos.out = out;
		dos.state = state;
		dos.lines = *lines;
		dos.nlines = *nlines;
		dos.ansi = !!(FLAG_CHK(flags, FNC_DIFF_ANSI_COLOR));
		if (FLAG_CHK(flags, FNC_DIFF_SIDEBYSIDE))
			rc = sbsdiff(&c, &dos, NULL /*regex*/, context, flags);
		else
			rc = unidiff(&c, &dos, NULL /*regex*/, context, flags);
		*lines = dos.lines;  /* realloc'd */
		*nlines = dos.nlines;
	} else if (rawdata) {
		/* Return array of COPY/DELETE/INSERT triples. */
		*rawdata = c.aEdit;
		c.aEdit = NULL;
	}
end:
	fsl_free(c.aFrom);
	fsl_free(c.aTo);
	fsl_free(c.aEdit);
	return rc;
}

/*



 * Find the longest line in the file and encode the length in *flags.
 */
int
max_sbs_width(fsl__diff_cx *c, int *flags, uint16_t ctxt)

{
	int		i, j, k;
	int		endl, endr, start; /* Start and end of l+r chunks */

	unsigned short	sz, sbswidth;	   /* Size of each line and max width */

	j = endl = endr = start = 0;
	k = c->nEdit;
	sbswidth = (*flags & FNC_DIFF_SIDEBYSIDE) ? sbsdiff_width(*flags) : 0;

	/* Find minimal copy/delete/insert triples. */
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
		start += c->aEdit[j];		  /* Chunk start line */
		endl = endr = start;
		endl += MAX(c->aEdit[j + 1], 0);  /* End of left side chunk */
		endr += MAX(c->aEdit[j + 2], 0);  /* End of right side chunk */
		s = MAX(start - ctxt, 0);	  /* Include leading ctxt */
		e = MIN(endl + ctxt, c->nFrom);	  /* L include trailing ctxt */
		e2 = MIN(endr + ctxt, c->nTo);	  /* R include trailing ctxt */
		n += MAX(MAX(e, e2) - s + ctxt + 2, 0); /* Max lines in chunk */

		/*
		 * Now find the longest line. We'll make both the left and right
		 * columns the width of the longest line from either side.
		 * XXX Consider keeping max width of both sides to make each
		 * column only as wide as its longest line; we can set a min
		 * default in diffs with added/removed files.







<







271
272
273
274
275
276
277

278
279
280
281
282
283
284
		start += c->aEdit[j];		  /* Chunk start line */
		endl = endr = start;
		endl += MAX(c->aEdit[j + 1], 0);  /* End of left side chunk */
		endr += MAX(c->aEdit[j + 2], 0);  /* End of right side chunk */
		s = MAX(start - ctxt, 0);	  /* Include leading ctxt */
		e = MIN(endl + ctxt, c->nFrom);	  /* L include trailing ctxt */
		e2 = MIN(endr + ctxt, c->nTo);	  /* R include trailing ctxt */


		/*
		 * Now find the longest line. We'll make both the left and right
		 * columns the width of the longest line from either side.
		 * XXX Consider keeping max width of both sides to make each
		 * column only as wide as its longest line; we can set a min
		 * default in diffs with added/removed files.
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341

		/* Account for insertions before adding lines to next chunk. */
		start += c->aEdit[j + 2];
	} while ((j += 3) < k - 3);

	*flags |= ((int)(sbswidth & 0xFFF)) << 16;  /* Encode max width */

	*lines = fsl_realloc(*lines, (nlines + n) * sizeof(enum line_type *));
	memset((*lines + nlines), 0, sizeof(enum line_type *) * n);

	return *lines ? FSL_RC_OK : FSL_RC_ERROR;
}

/*
 * Convert str byte size n to actual column width by expanding tabs and
 * accounting for unicode continuation bytes. Return the result.
 */
unsigned short
etcount(const char *str, unsigned short n)
{
	unsigned short c = 0;

	while (str && str[c] != '\n') {
		/* Expand tabs */
		if (str[c] == '\t')
			n += 8 - (c % 8);
		if (UTF_CONT(str[c]))
			--n;
		++c;
	}







<
<
<
|











|







302
303
304
305
306
307
308



309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328

		/* Account for insertions before adding lines to next chunk. */
		start += c->aEdit[j + 2];
	} while ((j += 3) < k - 3);

	*flags |= ((int)(sbswidth & 0xFFF)) << 16;  /* Encode max width */




	return FSL_RC_OK;
}

/*
 * Convert str byte size n to actual column width by expanding tabs and
 * accounting for unicode continuation bytes. Return the result.
 */
unsigned short
etcount(const char *str, unsigned short n)
{
	unsigned short c = 0;

	while (str && (str[c] != '\n' && str[c] != '\0')) {
		/* Expand tabs */
		if (str[c] == '\t')
			n += 8 - (c % 8);
		if (UTF_CONT(str[c]))
			--n;
		++c;
	}
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
				++idx;
				break;
			}
		}
		++idx;
	}

	if (dst)  /* trim trailing when copying '\n' */
		rc = fsl_buffer_append(dst, &src->mem[start], idx - start - 1);
	*offset = start;
	return rc;
}

/*
 * Scan the diffed file dst->proto->file from line pos preceding the start of







|







575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
				++idx;
				break;
			}
		}
		++idx;
	}

	if (dst)  /* trim trailing '\n' when copying */
		rc = fsl_buffer_append(dst, &src->mem[start], idx - start - 1);
	*offset = start;
	return rc;
}

/*
 * Scan the diffed file dst->proto->file from line pos preceding the start of
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701

702
703
704
705
706
707
708
709
{
	fsl_dline	*l, *r;		/* Left and right side of diff */
	fsl_buffer	 sbscols[5] = {
			    fsl_buffer_empty_m, fsl_buffer_empty_m,
			    fsl_buffer_empty_m, fsl_buffer_empty_m,
			    fsl_buffer_empty_m
			 };
	struct sbsline	 s;		/* Output line buffer */
	static int	 chunks = 0;	/* Number of chunks so far processed */
	int		 li, ri;	/* Index of next line in l[] and r[] */
	int		*c;		/* copy/delete/insert triples */
	int		 ci;		/* Index into c[] */
	int		 nc;		/* number of c[] triples to process */
	int		 max_ci;	/* Maximum value for ci */
	int		 nleft, nright; /* Number of l and r lines to output */
	int		 ntotal;	/* Total number of lines to output */
	int		 skip;		/* Number of lines to skip */
	int		 i, j, rc = FSL_RC_OK;
	uint32_t	*idx = dst->idx;
	enum line_type	*lines = dst->lines;

	bool		 showsep = false;

	li = ri = 0;
	memset(&s, 0, sizeof(s));
	s.output = dst;
	s.width = sbsdiff_width(flags);
	s.regex = regex;
	s.idx = -1;







|
|
|
|
|
|
|
|
|
|
|
<
|
>
|







669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686

687
688
689
690
691
692
693
694
695
696
{
	fsl_dline	*l, *r;		/* Left and right side of diff */
	fsl_buffer	 sbscols[5] = {
			    fsl_buffer_empty_m, fsl_buffer_empty_m,
			    fsl_buffer_empty_m, fsl_buffer_empty_m,
			    fsl_buffer_empty_m
			 };
	struct sbsline	  s;		/* Output line buffer */
	static int	  chunks = 0;	/* Number of chunks so far processed */
	int		  li, ri;	/* Index of next line in l[] and r[] */
	int		 *c;		/* copy/delete/insert triples */
	int		  ci;		/* Index into c[] */
	int		  nc;		/* number of c[] triples to process */
	int		  max_ci;	/* Maximum value for ci */
	int		  nleft, nright; /* Number of l and r lines to output */
	int		  ntotal;	/* Total number of lines to output */
	int		  skip;		/* Number of lines to skip */
	int		  i, j, rc = FSL_RC_OK;

	enum line_type	**lines = &dst->lines;
	uint32_t	 *nlines = &dst->nlines;
	bool		  showsep = false;

	li = ri = 0;
	memset(&s, 0, sizeof(s));
	s.output = dst;
	s.width = sbsdiff_width(flags);
	s.regex = regex;
	s.idx = -1;
789
790
791
792
793
794
795
796


797
798
799
800
801
802
803
		for (i = 1; i < nc; ++i) {
			nleft += c[ci + i * 3];
			nright += c[ci + i * 3];
		}

		/* Draw separator between blocks except the first. */
		if (showsep) {
			lines[(*idx)++] = LINE_DIFF_SEPARATOR;


			if (s.esc) {
				char ln[10];
				fsl_snprintf(ln, sizeof(ln), "%d",
				    li + skip + 1);
				rc = sbsdiff_separator(&s, fsl_strlen(ln),
				    SBS_LLINE);
				if (rc)







|
>
>







776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
		for (i = 1; i < nc; ++i) {
			nleft += c[ci + i * 3];
			nright += c[ci + i * 3];
		}

		/* Draw separator between blocks except the first. */
		if (showsep) {
			rc = add_line_type(lines, nlines, LINE_DIFF_SEPARATOR);
			if (rc)
				goto end;
			if (s.esc) {
				char ln[10];
				fsl_snprintf(ln, sizeof(ln), "%d",
				    li + skip + 1);
				rc = sbsdiff_separator(&s, fsl_strlen(ln),
				    SBS_LLINE);
				if (rc)
828
829
830
831
832
833
834


835
836
837
838

839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
			    chunks);

		/* Show the initial common area */
		li += skip;
		ri += skip;
		ntotal = c[ci] - skip;
		for (j = 0; !rc && j < ntotal; j++) {


			rc = sbsdiff_lineno(&s, li + j, SBS_LLINE);
			if (rc)
				break;
			s.idx = s.end = -1;

			rc = sbsdiff_txt(&s, &l[li + j], SBS_LTEXT);
			if (!rc)
				rc = sbsdiff_marker(&s, "   ", "");
			if (!rc)
				rc = sbsdiff_lineno(&s, ri + j, SBS_RLINE);
			if (!rc)
				rc = sbsdiff_txt(&s, &r[ri + j], SBS_RTEXT);
			lines[(*idx)++] = LINE_DIFF_CONTEXT;
		}
		if (rc)
			goto end;
		li += ntotal;
		ri += ntotal;

		/* Show the differences */







>
>
|
<
<

>
|






<







817
818
819
820
821
822
823
824
825
826


827
828
829
830
831
832
833
834
835

836
837
838
839
840
841
842
			    chunks);

		/* Show the initial common area */
		li += skip;
		ri += skip;
		ntotal = c[ci] - skip;
		for (j = 0; !rc && j < ntotal; j++) {
			rc = add_line_type(lines, nlines, LINE_DIFF_CONTEXT);
			if (!rc)
				rc = sbsdiff_lineno(&s, li + j, SBS_LLINE);


			s.idx = s.end = -1;
			if (!rc)
				rc = sbsdiff_txt(&s, &l[li + j], SBS_LTEXT);
			if (!rc)
				rc = sbsdiff_marker(&s, "   ", "");
			if (!rc)
				rc = sbsdiff_lineno(&s, ri + j, SBS_RLINE);
			if (!rc)
				rc = sbsdiff_txt(&s, &r[ri + j], SBS_RTEXT);

		}
		if (rc)
			goto end;
		li += ntotal;
		ri += ntotal;

		/* Show the differences */
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891



892
893
894
895
896
897
898

			alignment = sbsdiff_align(&l[li], nleft, &r[ri],
			    nright);
			if (!alignment) {
				rc = FSL_RC_OOM;
				goto end;
			}
			for (j = 0; !rc && nleft + nright > 0; j++, (*idx)++) {
				char tag[30] = "<span class=\"fsl-diff-";
				switch (alignment[j]) {
				case 1:
					/* Delete one line from the left */
					rc = sbsdiff_lineno(&s, li, SBS_LLINE);
					if (rc)
						goto end_align;
					s.idx = 0;
					fsl_strlcat(tag, "rm\">", sizeof(tag));
					s.tag = tag;
					s.end = LENGTH(&l[li]);
					lines[*idx] = LINE_DIFF_MINUS;
					rc = sbsdiff_txt(&s, &l[li], SBS_LTEXT);



					if (rc)
						goto end_align;
					rc = sbsdiff_marker(&s, " <", "&lt;");
					if (rc)
						goto end_align;
					rc = sbsdiff_newline(&s);
					if (rc)







|











<

>
>
>







860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878

879
880
881
882
883
884
885
886
887
888
889

			alignment = sbsdiff_align(&l[li], nleft, &r[ri],
			    nright);
			if (!alignment) {
				rc = FSL_RC_OOM;
				goto end;
			}
			for (j = 0; !rc && nleft + nright > 0; j++) {
				char tag[30] = "<span class=\"fsl-diff-";
				switch (alignment[j]) {
				case 1:
					/* Delete one line from the left */
					rc = sbsdiff_lineno(&s, li, SBS_LLINE);
					if (rc)
						goto end_align;
					s.idx = 0;
					fsl_strlcat(tag, "rm\">", sizeof(tag));
					s.tag = tag;
					s.end = LENGTH(&l[li]);

					rc = sbsdiff_txt(&s, &l[li], SBS_LTEXT);
					if (!rc)
						rc = add_line_type(lines,
						    nlines, LINE_DIFF_MINUS);
					if (rc)
						goto end_align;
					rc = sbsdiff_marker(&s, " <", "&lt;");
					if (rc)
						goto end_align;
					rc = sbsdiff_newline(&s);
					if (rc)
915
916
917
918
919
920
921
922
923



924
925
926
927
928
929
930
					rc = sbsdiff_lineno(&s, ri, SBS_RLINE);
					if (rc)
						goto end_align;
					s.idx = 0;
					fsl_strlcat(tag, "add\">", sizeof(tag));
					s.tag = tag;
					s.end = LENGTH(&r[ri]);
					lines[*idx] = LINE_DIFF_PLUS;
					rc = sbsdiff_txt(&s, &r[ri], SBS_RTEXT);



					if (rc)
						goto end_align;
					assert(nright > 0);
					nright--;
					ri++;
					break;
				case 3:







<

>
>
>







906
907
908
909
910
911
912

913
914
915
916
917
918
919
920
921
922
923
					rc = sbsdiff_lineno(&s, ri, SBS_RLINE);
					if (rc)
						goto end_align;
					s.idx = 0;
					fsl_strlcat(tag, "add\">", sizeof(tag));
					s.tag = tag;
					s.end = LENGTH(&r[ri]);

					rc = sbsdiff_txt(&s, &r[ri], SBS_RTEXT);
					if (!rc)
						rc = add_line_type(lines,
						    nlines, LINE_DIFF_PLUS);
					if (rc)
						goto end_align;
					assert(nright > 0);
					nright--;
					ri++;
					break;
				case 3:
947
948
949
950
951
952
953
954
955



956
957
958
959
960
961
962
					s.idx = 0;
					fsl_strlcat(tag, "rm\">", sizeof(tag));
					s.tag = tag;
					s.end = LENGTH(&l[li]);
					rc = sbsdiff_txt(&s, &l[li], SBS_LTEXT);
					if (rc)
						goto end_align;
					lines[*idx] = LINE_DIFF_EDIT;
					rc = sbsdiff_marker(&s, " | ", "|");



					if (rc)
						goto end_align;
					rc = sbsdiff_lineno(&s, ri, SBS_RLINE);
					if (rc)
						goto end_align;
					s.idx = 0;
					s.tag = "<span class=\"fsl-diff-add\">";







<

>
>
>







940
941
942
943
944
945
946

947
948
949
950
951
952
953
954
955
956
957
					s.idx = 0;
					fsl_strlcat(tag, "rm\">", sizeof(tag));
					s.tag = tag;
					s.end = LENGTH(&l[li]);
					rc = sbsdiff_txt(&s, &l[li], SBS_LTEXT);
					if (rc)
						goto end_align;

					rc = sbsdiff_marker(&s, " | ", "|");
					if (!rc)
						rc = add_line_type(lines,
						    nlines, LINE_DIFF_EDIT);
					if (rc)
						goto end_align;
					rc = sbsdiff_lineno(&s, ri, SBS_RLINE);
					if (rc)
						goto end_align;
					s.idx = 0;
					s.tag = "<span class=\"fsl-diff-add\">";
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989



990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015


1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
			}
end_align:
			fsl_free(alignment);
			if (rc)
				goto end;
			if (i < nc - 1) {
				ntotal = c[ci + i * 3 + 3];
				for (j = 0; !rc && j < ntotal; j++, (*idx)++) {
					rc = sbsdiff_lineno(&s, li + j,
					    SBS_LLINE);
					s.idx = s.end = -1;
					if (rc)
						goto end;
					lines[*idx] = LINE_DIFF_CONTEXT;
					rc = sbsdiff_txt(&s, &l[li + j],
					    SBS_LTEXT);



					if (rc)
						goto end;
					rc = sbsdiff_marker(&s, "   ", "");
					if (rc)
						goto end;
					rc = sbsdiff_lineno(&s, ri + j,
					    SBS_RLINE);
					if (rc)
						goto end;
					lines[*idx] = LINE_DIFF_CONTEXT;
					rc = sbsdiff_txt(&s, &r[ri + j],
					    SBS_RTEXT);
					if (rc)
						goto end;
				}
				ri += ntotal;
				li += ntotal;
			}
		}

		/* Show the final common area */
		assert(nc == i);
		ntotal = c[ci + nc * 3];
		if (ntotal > context)
			ntotal = context;
		for (j = 0; !rc && j < ntotal; j++, (*idx)++) {


			rc = sbsdiff_lineno(&s, li + j, SBS_LLINE);
			s.idx = s.end = -1;
			lines[*idx] = LINE_DIFF_CONTEXT;
			if (!rc)
				rc = sbsdiff_txt(&s, &l[li + j], SBS_LTEXT);
			if (!rc)
				rc = sbsdiff_marker(&s, "   ", "");
			if (!rc)
				rc = sbsdiff_lineno(&s, ri + j, SBS_RLINE);
			lines[*idx] = LINE_DIFF_CONTEXT;
			if (!rc)
				rc = sbsdiff_txt(&s, &r[ri + j], SBS_RTEXT);
			if (rc)
				goto end;
		}
	}  /* diff triplet loop */








|





<


>
>
>









<















|
>
>
|

<






<







969
970
971
972
973
974
975
976
977
978
979
980
981

982
983
984
985
986
987
988
989
990
991
992
993
994
995

996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015

1016
1017
1018
1019
1020
1021

1022
1023
1024
1025
1026
1027
1028
			}
end_align:
			fsl_free(alignment);
			if (rc)
				goto end;
			if (i < nc - 1) {
				ntotal = c[ci + i * 3 + 3];
				for (j = 0; !rc && j < ntotal; j++) {
					rc = sbsdiff_lineno(&s, li + j,
					    SBS_LLINE);
					s.idx = s.end = -1;
					if (rc)
						goto end;

					rc = sbsdiff_txt(&s, &l[li + j],
					    SBS_LTEXT);
					if (!rc)
						rc = add_line_type(lines,
						    nlines, LINE_DIFF_CONTEXT);
					if (rc)
						goto end;
					rc = sbsdiff_marker(&s, "   ", "");
					if (rc)
						goto end;
					rc = sbsdiff_lineno(&s, ri + j,
					    SBS_RLINE);
					if (rc)
						goto end;

					rc = sbsdiff_txt(&s, &r[ri + j],
					    SBS_RTEXT);
					if (rc)
						goto end;
				}
				ri += ntotal;
				li += ntotal;
			}
		}

		/* Show the final common area */
		assert(nc == i);
		ntotal = c[ci + nc * 3];
		if (ntotal > context)
			ntotal = context;
		for (j = 0; !rc && j < ntotal; j++) {
			rc = add_line_type(lines, nlines, LINE_DIFF_CONTEXT);
			if (!rc)
				rc = sbsdiff_lineno(&s, li + j, SBS_LLINE);
			s.idx = s.end = -1;

			if (!rc)
				rc = sbsdiff_txt(&s, &l[li + j], SBS_LTEXT);
			if (!rc)
				rc = sbsdiff_marker(&s, "   ", "");
			if (!rc)
				rc = sbsdiff_lineno(&s, ri + j, SBS_RLINE);

			if (!rc)
				rc = sbsdiff_txt(&s, &r[ri + j], SBS_RTEXT);
			if (rc)
				goto end;
		}
	}  /* diff triplet loop */

1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071


1072
1073
1074
1075
1076
1077
1078
1079
 *   context	Number of context lines
 *   flags	Flags controlling the diff
 */
int
unidiff(fsl__diff_cx *cx, struct diff_out_state *dst, void *regex,
    uint16_t context, uint64_t flags)
{
	fsl_dline	*l, *r;		/* Left and right side of diff */
	static int	 chunks = 0;	/* Number of chunks so far processed */
	int		 li, ri;	/* Index of next line in l[] and r[] */
	int		*c;		/* copy/delete/insert triples */
	int		 ci;		/* Index into c[] */
	int		 nc;		/* number of c[] triples to process */
	int		 max_ci;	/* Maximum value for ci */
	int		 nleft, nright; /* Number of l and r lines to output */
	int		 ntotal;	/* Total number of lines to output */
	int		 skip;		/* Number of lines to skip */
	int		 i, j, rc = FSL_RC_OK;


	bool		 html, proto, showln, showsep = false;

	proto = FLAG_CHK(flags, FNC_DIFF_PROTOTYPE);
	showln = FLAG_CHK(flags, FNC_DIFF_LINENO);
	html = FLAG_CHK(flags, FNC_DIFF_HTML);

	l = cx->aFrom;
	r = cx->aTo;







|
|
|
|
|
|
|
|
|
|
|
>
>
|







1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
 *   context	Number of context lines
 *   flags	Flags controlling the diff
 */
int
unidiff(fsl__diff_cx *cx, struct diff_out_state *dst, void *regex,
    uint16_t context, uint64_t flags)
{
	fsl_dline	 *l, *r;	/* Left and right side of diff */
	static int	  chunks = 0;	/* Number of chunks so far processed */
	int		  li, ri;	/* Index of next line in l[] and r[] */
	int		 *c;		/* copy/delete/insert triples */
	int		  ci;		/* Index into c[] */
	int		  nc;		/* number of c[] triples to process */
	int		  max_ci;	/* Maximum value for ci */
	int		  nleft, nright; /* Number of l and r lines to output */
	int		  ntotal;	/* Total number of lines to output */
	int		  skip;		/* Number of lines to skip */
	int		  i, j, rc = FSL_RC_OK;
	uint32_t	 *nlines = &dst->nlines;
	enum line_type	**lines = &dst->lines;
	bool		  html, proto, showln, showsep = false;

	proto = FLAG_CHK(flags, FNC_DIFF_PROTOTYPE);
	showln = FLAG_CHK(flags, FNC_DIFF_LINENO);
	html = FLAG_CHK(flags, FNC_DIFF_HTML);

	l = cx->aFrom;
	r = cx->aTo;
1156
1157
1158
1159
1160
1161
1162
1163



1164

1165
1166
1167
1168
1169
1170
1171
		if (showln) {
			if (!showsep)
				showsep = 1;  /* Don't show a top divider */
			else if (html)
				rc = diff_outf(dst,
				    "<span class=\"fsl-diff-hr\">%.*c</span>\n",
				    80, '.');
			else



				rc = diff_outf(dst, "%.95c\n", '.');

			if (!rc && html)
				rc = diff_outf(dst,
				    "<span class=\"fsl-diff-chunk-%d\"></span>",
				    chunks);
		} else {
			char const *ansi1 = "";
			char const *ansi2 = "";







|
>
>
>
|
>







1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
		if (showln) {
			if (!showsep)
				showsep = 1;  /* Don't show a top divider */
			else if (html)
				rc = diff_outf(dst,
				    "<span class=\"fsl-diff-hr\">%.*c</span>\n",
				    80, '.');
			else {
				rc = add_line_type(lines, nlines,
				    LINE_DIFF_SEPARATOR);
				if (!rc)
					rc = diff_outf(dst, "%.95c\n", '.');
			}
			if (!rc && html)
				rc = diff_outf(dst,
				    "<span class=\"fsl-diff-chunk-%d\"></span>",
				    chunks);
		} else {
			char const *ansi1 = "";
			char const *ansi2 = "";
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192

1193




1194
1195
1196
1197
1198
1199
1200
#endif
			/*
			 * If the patch changes an empty file or results in
			 * an empty file, the block header must use 0,0 as
			 * position indicator and not 1,0. Otherwise, patch
			 * would be confused and may reject the diff.
			 */
			if (!rc)
				rc = diff_outf(dst,"@@ %s-%d,%d %s+%d,%d%s @@",
				    ansi1, nleft ? li+skip+1 : 0, nleft, ansi2,

				    nright ? ri+skip+1 : 0, nright, ansi3);




			if (!rc) {
				if (html)
					rc = diff_outf(dst, "</span>");

				if (proto && li + skip > 1) {
					char *f = match_chunk_function(dst,
					    (li + skip) - 1);







|
|
|
>
|
>
>
>
>







1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
#endif
			/*
			 * If the patch changes an empty file or results in
			 * an empty file, the block header must use 0,0 as
			 * position indicator and not 1,0. Otherwise, patch
			 * would be confused and may reject the diff.
			 */
			if (!rc) {
				rc = diff_outf(dst, "@@ %s-%d,%d %s+%d,%d%s @@",
				    ansi1, nleft ? li + skip + 1 : 0, nleft,
				    ansi2, nright ?  ri + skip + 1 : 0,
				    nright, ansi3);
				if (!rc)
					rc = add_line_type(lines, nlines,
					    LINE_DIFF_CHUNK);
			}
			if (!rc) {
				if (html)
					rc = diff_outf(dst, "</span>");

				if (proto && li + skip > 1) {
					char *f = match_chunk_function(dst,
					    (li + skip) - 1);
1209
1210
1211
1212
1213
1214
1215

1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230


1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242


1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255


1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276

1277
1278
1279
1280
1281
1282
1283
1284
			return rc;

		/* Show the initial common area */
		li += skip;
		ri += skip;
		ntotal = c[ci] - skip;
		for (j = 0; !rc && j < ntotal; j++) {

			if (showln)
				rc = unidiff_lineno(dst,
				    li + j + 1, ri + j + 1, html);
			if (!rc)
				rc = unidiff_txt(dst, ' ', &l[li + j], html, 0);
		}
		if (rc)
			return rc;
		li += ntotal;
		ri += ntotal;

		/* Show the differences */
		for (i = 0; i < nc; i++) {
			ntotal = c[ci + i * 3 + 1];
			for (j = 0; !rc && j < ntotal; j++) {


				if (showln)
					rc = unidiff_lineno(dst, li + j + 1, 0,
					    html);
				if (!rc)
					rc = unidiff_txt(dst, '-', &l[li + j],
					    html, regex);
			}
			if (rc)
				return rc;
			li += ntotal;
			ntotal = c[ci + i * 3 + 2];
			for (j = 0; !rc && j < ntotal; j++) {


				if (showln)
					rc = unidiff_lineno(dst, 0, ri + j + 1,
					    html);
				if (!rc)
					rc = unidiff_txt(dst, '+', &r[ri + j],
					    html, regex);
			}
			if (rc)
				return rc;
			ri += ntotal;
			if (i < nc - 1) {
				ntotal = c[ci + i * 3 + 3];
				for (j = 0; !rc && j < ntotal; j++) {


					if (showln)
						rc = unidiff_lineno(dst,
						    li + j + 1, ri + j + 1,
						    html);
					if (!rc)
						rc = unidiff_txt(dst, ' ',
						    &l[li + j], html, 0);
				}
				if (rc)
					return rc;
				ri += ntotal;
				li += ntotal;
			}
		}

		/* Show the final common area */
		assert(nc==i);
		ntotal = c[ci + nc * 3];
		if (ntotal > context)
			ntotal = context;
		for (j = 0; !rc && j < ntotal; j++) {

			if (showln)
				rc = unidiff_lineno(dst, li + j + 1, ri + j + 1,
				    html);
			if (!rc)
				rc = unidiff_txt(dst, ' ', &l[li + j], html, 0);
		}
	}  /* _big_ for() loop */
	fsl_free(dst->proto.signature);







>
|














>
>
|











>
>
|












>
>
|




















>
|







1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
			return rc;

		/* Show the initial common area */
		li += skip;
		ri += skip;
		ntotal = c[ci] - skip;
		for (j = 0; !rc && j < ntotal; j++) {
			rc = add_line_type(lines, nlines, LINE_DIFF_CONTEXT);
			if (!rc && showln)
				rc = unidiff_lineno(dst,
				    li + j + 1, ri + j + 1, html);
			if (!rc)
				rc = unidiff_txt(dst, ' ', &l[li + j], html, 0);
		}
		if (rc)
			return rc;
		li += ntotal;
		ri += ntotal;

		/* Show the differences */
		for (i = 0; i < nc; i++) {
			ntotal = c[ci + i * 3 + 1];
			for (j = 0; !rc && j < ntotal; j++) {
				rc = add_line_type(lines, nlines,
				    LINE_DIFF_MINUS);
				if (!rc && showln)
					rc = unidiff_lineno(dst, li + j + 1, 0,
					    html);
				if (!rc)
					rc = unidiff_txt(dst, '-', &l[li + j],
					    html, regex);
			}
			if (rc)
				return rc;
			li += ntotal;
			ntotal = c[ci + i * 3 + 2];
			for (j = 0; !rc && j < ntotal; j++) {
				rc = add_line_type(lines, nlines,
				    LINE_DIFF_PLUS);
				if (!rc && showln)
					rc = unidiff_lineno(dst, 0, ri + j + 1,
					    html);
				if (!rc)
					rc = unidiff_txt(dst, '+', &r[ri + j],
					    html, regex);
			}
			if (rc)
				return rc;
			ri += ntotal;
			if (i < nc - 1) {
				ntotal = c[ci + i * 3 + 3];
				for (j = 0; !rc && j < ntotal; j++) {
					rc = add_line_type(lines, nlines,
					    LINE_DIFF_CONTEXT);
					if (!rc && showln)
						rc = unidiff_lineno(dst,
						    li + j + 1, ri + j + 1,
						    html);
					if (!rc)
						rc = unidiff_txt(dst, ' ',
						    &l[li + j], html, 0);
				}
				if (rc)
					return rc;
				ri += ntotal;
				li += ntotal;
			}
		}

		/* Show the final common area */
		assert(nc==i);
		ntotal = c[ci + nc * 3];
		if (ntotal > context)
			ntotal = context;
		for (j = 0; !rc && j < ntotal; j++) {
			rc = add_line_type(lines, nlines, LINE_DIFF_CONTEXT);
			if (!rc && showln)
				rc = unidiff_lineno(dst, li + j + 1, ri + j + 1,
				    html);
			if (!rc)
				rc = unidiff_txt(dst, ' ', &l[li + j], html, 0);
		}
	}  /* _big_ for() loop */
	fsl_free(dst->proto.signature);
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
 * Insertion and deletion costs are 50. Match costs are between 0 and 100 where
 * 0 is a perfect match 100 is a complete mismatch.
 *   left	lines of text on the left
 *   nleft	number of lines on the left
 *   right	lines of text on the right
 *   nright	number of lines on the right
 */
unsigned char
*sbsdiff_align(fsl_dline *left, int nleft, fsl_dline *right, int nright)
{
	int		 buf[100];	/* left[] stack if nright not too big */
	int		*row;		/* One row of the Wagner matrix */
	int		*ptr;		/* Space that needs to be freed */
	int		 nmatches;	/* Number of matches */
	int		 matchscore;	/* Match score */
	int		 minlen;	/* MIN(nleft, nright) */







|
|







1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
 * Insertion and deletion costs are 50. Match costs are between 0 and 100 where
 * 0 is a perfect match 100 is a complete mismatch.
 *   left	lines of text on the left
 *   nleft	number of lines on the left
 *   right	lines of text on the right
 *   nright	number of lines on the right
 */
unsigned char *
sbsdiff_align(fsl_dline *left, int nleft, fsl_dline *right, int nright)
{
	int		 buf[100];	/* left[] stack if nright not too big */
	int		*row;		/* One row of the Wagner matrix */
	int		*ptr;		/* Space that needs to be freed */
	int		 nmatches;	/* Number of matches */
	int		 matchscore;	/* Match score */
	int		 minlen;	/* MIN(nleft, nright) */
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
 *   right	Right line of the change
 *   rlnno	Line number of the right line
 */
int
sbsdiff_write_change(struct sbsline *dst, fsl_dline *left, int llnno,
    fsl_dline *right, int rlnno)
{
	static const char	 tag_rm[]   = "<span class=\"fsl-diff-rm\">";
	static const char	 tag_add[]  = "<span class=\"fsl-diff-add\">";
	static const char	 tag_chg[] = "<span class=\"fsl-diff-change\">";
	const char		*ltxt;	/* Text of the left line */
	const char		*rtxt;	/* Text of the right line */
	enum line_type		*lines = dst->output->lines;
	uint32_t		*idx = dst->output->idx;
	int	lcs[4] = {0, 0, 0, 0};	/* Bounds of common middle segment */
	int	leftsz;		/* Length of left line in bytes */
	int	rightsz;	/* Length of right line in bytes */
	int	shortest;	/* Shortest of left and right */
	int	npfx;		/* Length of common prefix */
	int	nsfx;		/* Length of common suffix */
	int	nleft;		/* leftsz - npfx - nsfx */







|
|
|
|
|
|
|







1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
 *   right	Right line of the change
 *   rlnno	Line number of the right line
 */
int
sbsdiff_write_change(struct sbsline *dst, fsl_dline *left, int llnno,
    fsl_dline *right, int rlnno)
{
	static const char	  tag_rm[] = "<span class=\"fsl-diff-rm\">";
	static const char	  tag_add[] = "<span class=\"fsl-diff-add\">";
	static const char	  tag_chg[] = "<span class=\"fsl-diff-change\">";
	const char		 *ltxt;	/* Text of the left line */
	const char		 *rtxt;	/* Text of the right line */
	enum line_type		**lines = &dst->output->lines;
	uint32_t		 *nlines = &dst->output->nlines;
	int	lcs[4] = {0, 0, 0, 0};	/* Bounds of common middle segment */
	int	leftsz;		/* Length of left line in bytes */
	int	rightsz;	/* Length of right line in bytes */
	int	shortest;	/* Shortest of left and right */
	int	npfx;		/* Length of common prefix */
	int	nsfx;		/* Length of common suffix */
	int	nleft;		/* leftsz - npfx - nsfx */
1790
1791
1792
1793
1794
1795
1796


1797
1798
1799
1800


1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821


1822
1823
1824
1825
1826
1827
1828
		rc = sbsdiff_lineno(dst, llnno, SBS_LLINE);
		if (rc)
			return rc;
		dst->idx2 = dst->end2 = 0;
		dst->idx = dst->end = -1;
		rc = sbsdiff_txt(dst, left, SBS_LTEXT);
		if (!rc && leftsz == rightsz && ltxt[leftsz] == rtxt[rightsz]) {


			rc = sbsdiff_marker(dst, "   ", "");
			lines[*idx] = LINE_DIFF_CONTEXT;
		}
		else {


			rc = sbsdiff_marker(dst, " | ", "|");
			lines[*idx] = LINE_DIFF_EDIT;
		}

		if (!rc) {
			rc = sbsdiff_lineno(dst, rlnno, SBS_RLINE);
			if (!rc) {
				dst->idx = npfx;
				dst->end = rightsz - nsfx;
				dst->tag = tag_add;
				rc = sbsdiff_txt(dst, right, SBS_RTEXT);
			}
		}
		return rc;
	}

	/* A single chunk of text deleted from the left */
	if (npfx + nsfx == rightsz) {
		lines[*idx] = LINE_DIFF_EDIT;
		/* Text deleted from the left */
		rc = sbsdiff_lineno(dst, llnno, SBS_LLINE);


		if (rc)
			return rc;
		dst->idx2 = dst->end2 = 0;
		dst->idx = npfx;
		dst->end = leftsz - nsfx;
		dst->tag = tag_rm;
		rc = sbsdiff_txt(dst, left, SBS_LTEXT);







>
>
|
<


>
>
|
<
















<


>
>







1805
1806
1807
1808
1809
1810
1811
1812
1813
1814

1815
1816
1817
1818
1819

1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835

1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
		rc = sbsdiff_lineno(dst, llnno, SBS_LLINE);
		if (rc)
			return rc;
		dst->idx2 = dst->end2 = 0;
		dst->idx = dst->end = -1;
		rc = sbsdiff_txt(dst, left, SBS_LTEXT);
		if (!rc && leftsz == rightsz && ltxt[leftsz] == rtxt[rightsz]) {
			rc = add_line_type(lines, nlines, LINE_DIFF_CONTEXT);
			if (!rc)
				rc = sbsdiff_marker(dst, "   ", "");

		}
		else {
			rc = add_line_type(lines, nlines, LINE_DIFF_EDIT);
			if (!rc)
				rc = sbsdiff_marker(dst, " | ", "|");

		}

		if (!rc) {
			rc = sbsdiff_lineno(dst, rlnno, SBS_RLINE);
			if (!rc) {
				dst->idx = npfx;
				dst->end = rightsz - nsfx;
				dst->tag = tag_add;
				rc = sbsdiff_txt(dst, right, SBS_RTEXT);
			}
		}
		return rc;
	}

	/* A single chunk of text deleted from the left */
	if (npfx + nsfx == rightsz) {

		/* Text deleted from the left */
		rc = sbsdiff_lineno(dst, llnno, SBS_LLINE);
		if (!rc)
			rc = add_line_type(lines, nlines, LINE_DIFF_EDIT);
		if (rc)
			return rc;
		dst->idx2 = dst->end2 = 0;
		dst->idx = npfx;
		dst->end = leftsz - nsfx;
		dst->tag = tag_rm;
		rc = sbsdiff_txt(dst, left, SBS_LTEXT);
1858
1859
1860
1861
1862
1863
1864
1865
1866


1867
1868
1869
1870
1871
1872
1873
			dst->tag = tag_rm;
		} else
			dst->tag = tag_chg;
		dst->idx2 = npfx + lcs[1];
		dst->end2 = leftsz - nsfx;
		dst->tag2 = lcs[3] == nright ? tag_rm : tag_chg;
		sbsdiff_simplify_line(dst, ltxt + npfx);
		lines[*idx] = LINE_DIFF_EDIT;
		rc = sbsdiff_txt(dst, left, SBS_LTEXT);


		if (!rc)
			rc = sbsdiff_marker(dst, " | ", "|");
		if (!rc)
			rc = sbsdiff_lineno(dst, rlnno, SBS_RLINE);
		if (rc)
			return rc;
		dst->idx = npfx;







<

>
>







1876
1877
1878
1879
1880
1881
1882

1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
			dst->tag = tag_rm;
		} else
			dst->tag = tag_chg;
		dst->idx2 = npfx + lcs[1];
		dst->end2 = leftsz - nsfx;
		dst->tag2 = lcs[3] == nright ? tag_rm : tag_chg;
		sbsdiff_simplify_line(dst, ltxt + npfx);

		rc = sbsdiff_txt(dst, left, SBS_LTEXT);
		if (!rc)
			rc = add_line_type(lines, nlines, LINE_DIFF_EDIT);
		if (!rc)
			rc = sbsdiff_marker(dst, " | ", "|");
		if (!rc)
			rc = sbsdiff_lineno(dst, rlnno, SBS_RLINE);
		if (rc)
			return rc;
		dst->idx = npfx;
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897

1898
1899
1900
1901
1902
1903
1904
		rc = sbsdiff_txt(dst, right, SBS_RTEXT);
		return rc;
	}

	/* If all else fails, show a single big change between left and right */
	rc = sbsdiff_lineno(dst, llnno, SBS_LLINE);
	if (!rc) {
		lines[*idx] = LINE_DIFF_EDIT;
		dst->idx2 = dst->end2 = 0;
		dst->idx = npfx;
		dst->end = leftsz - nsfx;
		dst->tag = tag_chg;
		rc = sbsdiff_txt(dst, left, SBS_LTEXT);
		if (!rc) {

			rc = sbsdiff_marker(dst, " | ", "|");
			if (!rc) {
				rc = sbsdiff_lineno(dst, rlnno, SBS_RLINE);
				if (!rc) {
					dst->end = rightsz - nsfx;
					sbsdiff_txt(dst, right, SBS_RTEXT);
				}







<






>







1903
1904
1905
1906
1907
1908
1909

1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
		rc = sbsdiff_txt(dst, right, SBS_RTEXT);
		return rc;
	}

	/* If all else fails, show a single big change between left and right */
	rc = sbsdiff_lineno(dst, llnno, SBS_LLINE);
	if (!rc) {

		dst->idx2 = dst->end2 = 0;
		dst->idx = npfx;
		dst->end = leftsz - nsfx;
		dst->tag = tag_chg;
		rc = sbsdiff_txt(dst, left, SBS_LTEXT);
		if (!rc) {
			rc = add_line_type(lines, nlines, LINE_DIFF_EDIT);
			rc = sbsdiff_marker(dst, " | ", "|");
			if (!rc) {
				rc = sbsdiff_lineno(dst, rlnno, SBS_RLINE);
				if (!rc) {
					dst->end = rightsz - nsfx;
					sbsdiff_txt(dst, right, SBS_RTEXT);
				}
2008
2009
2010
2011
2012
2013
2014
















			rc = diff_out(dst, ANSI_RESET, -1);
		if (!rc)
			rc = diff_out(dst, "\n", 1);
	}

	return rc;
}























>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
			rc = diff_out(dst, ANSI_RESET, -1);
		if (!rc)
			rc = diff_out(dst, "\n", 1);
	}

	return rc;
}

int
add_line_type(enum line_type **lines, uint32_t *nlines, enum line_type type)
{
	enum line_type *p;

	p = fsl_realloc(*lines, (*nlines + 1) * sizeof(enum line_type));
	if (p == NULL)
		return FSL_RC_ERROR;
	*lines = p;

	(*lines)[*nlines] = type;
	(*nlines)++;

	return FSL_RC_OK;
}

Changes to src/fnc.1.

22
23
24
25
26
27
28









29
30
31
32
33
34
35
.Sh SYNOPSIS
.Nm
.Op Ar command
.Op Fl h | -help
.Nm
.Op Fl h | -help
.Op Fl v | -version









.Nm
.Cm config
.Op Fl hu
.Op Fl -ls
.Op Fl R Ar path
.Op Ar setting Op Ar value
.Nm







>
>
>
>
>
>
>
>
>







22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
.Sh SYNOPSIS
.Nm
.Op Ar command
.Op Fl h | -help
.Nm
.Op Fl h | -help
.Op Fl v | -version
.Nm
.Cm stash
.Sm off
.Oo
.Cm get | pop
.Li |
.Fl ChPx
.Sm on
.Oc
.Nm
.Cm config
.Op Fl hu
.Op Fl -ls
.Op Fl R Ar path
.Op Ar setting Op Ar value
.Nm
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
.Op Fl R Ar path
.Op Fl s Ar order
.Op Ar glob
.Nm
.Op Ar path
.Sh DESCRIPTION
.Nm
is an interactive read-only browser for
.Xr fossil 1
repositories,
and supports multiple views to display repository data:
.Bl -tag -width Ds
.It Timeline view
Display commits from the repository's history in chronologically
descending order.







|







80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
.Op Fl R Ar path
.Op Fl s Ar order
.Op Ar glob
.Nm
.Op Ar path
.Sh DESCRIPTION
.Nm
is an interactive interface for
.Xr fossil 1
repositories,
and supports multiple views to display repository data:
.Bl -tag -width Ds
.It Timeline view
Display commits from the repository's history in chronologically
descending order.
195
196
197
198
199
200
201






























































































202
203
204
205
206
207
208
for the current
.Cm fnc config
invocation.
.It Fl u , -unset
Clear the specified
.Ar setting.
.El






























































































.Tg log
.It Cm timeline Oo Fl C | -no-colour Oc Oo Fl T | -tag Ar tag Oc \
Oo Fl b | -branch Ar branch Oc Oo Fl c | -commit Ar commit Oc \
Oo Fl f | -filter Ar glob Oc Oo Fl h | -help Oc  Oo Fl n | -limit Ar n Oc \
Oo Fl R | -repo Ar path Oc Oo Fl t | -type Ar type Oc \
Oo Fl u | -username Ar user Oc Oo Fl z | -utc Oc \
Op Ar path







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
for the current
.Cm fnc config
invocation.
.It Fl u , -unset
Clear the specified
.Ar setting.
.El
.Tg stash
.It Cm stash Oo Cm get Ns | Ns Cm pop Ns | Ns Oo Fl C | -no-colour Oc \
Oo Fl h | -help Oc Oo Fl P | -no-prototype Oc Oo Fl x | -context Ar n Oc Oc
.Dl Pq aliases: Cm snapshot , Cm snap , Cm save , Cm sta
When run with neither the
.Cm get
nor
.Cm pop
subcommands,
.Nm
.Cm stash
will present an interactive view of the local changes on disk and iterate
each hunk in the diff, prompting the user to either stash or keep the current
change in the checkout. Valid answers are as follows:
.Bl -column -offset 2s YXZ description
.Sy b Ta scroll back Ns \(ha
.Sy m Ta show more of the current hunk Ns \(ha
.Sy y Ta yes, stash the current hunk
.Sy n Ta no, do not stash the current hunk
.Sy a Ta yes, stash this hunk and all remaining hunks in the file
.Sy k Ta no, do not stash this hunk nor any remaining hunks in the file
.Sy A Ta yes, stash this hunk and all remaining hunks in the diff
.Sy K Ta no, do not stash this hunk nor any remaining hunks in the diff
.Sy ? Ta display help dialog
.El
.Pp
\(haConditionally available when the current hunk occupies the previous
and/or following page.
.Pp
When all hunks have been selected,
.Nm
will prompt the user to enter a stash message.  If not provided, a default
message of
.Qo
fnc stash HASH-PREFIX
.Qc ,
where
.Qq HASH-PREFIX
is an abbreviated SHA UUID hash of the current checkout,
will be used.  At any time prior to the final hunk being selected
.Po
i.e., before the stash message prompt
.Pc ,
the operation can be aborted by opening the help dialog and entering
.Qq Q ,
which will discard all selections and leave the checkout state unchanged.
.Pp
Available subcommands for
.Nm
.Cm stash
are as follows:
.Bl -ohang -width Ds
.It Cm get
.Dl Pq aliases: Cm apply
Retrieve the most recent stash entry and apply it to the current checkout.
.It Cm pop
Remove the most recent stash entry and apply it to the current checkout.
.El
.Pp
Options only apply to
.Nm
.Cm stash
.Po
i.e.,
neither the
.Cm get
nor
.Cm pop
subcommands
.Pc
and are as follows:
.Bl -tag -width Ds
.It Fl C , -no-colour
Disable coloured output, which is enabled by default on supported terminals.
.It Fl h , -help
Display
.Cm stash
command help and usage information then exit.
.It Fl P , -no-prototype
Disable hunk header display of which function or scope each change is in,
which is enabled by default.  The heuristic will produce reliable results for
all C-like languages
.Pq e.g., C/C++, Java, Python, JavaScript, Rust ;
however, Lisps and non-source code
.Pq e.g., Markdown, reStructuredText
will return meaningless results.
.It Fl x , -context Ar n
Set
.Ar n
context lines to be shown in the interactive stash diff display such that
0 \*(Le n \*(Le 64.  By default, 5 context lines are shown.
Illegal values are a no-op.
.El
.Pp
.Tg log
.It Cm timeline Oo Fl C | -no-colour Oc Oo Fl T | -tag Ar tag Oc \
Oo Fl b | -branch Ar branch Oc Oo Fl c | -commit Ar commit Oc \
Oo Fl f | -filter Ar glob Oc Oo Fl h | -help Oc  Oo Fl n | -limit Ar n Oc \
Oo Fl R | -repo Ar path Oc Oo Fl t | -type Ar type Oc \
Oo Fl u | -username Ar user Oc Oo Fl z | -utc Oc \
Op Ar path
352
353
354
355
356
357
358











359
360
361
362
363
364
365
.Cm fnc timeline
are as follows:
.Bl -tag -width Ds
.It Cm Arrow-down, j, >, \&.
Move selection cursor down the timeline.
.It Cm Arrow-up, k, <, \&,
Move selection cursor up the timeline.











.It Cm C-f, Page-down
Scroll timeline view one page downwards in the buffer.
.It Cm C-b, Page-up
Scroll timeline view one page upwards in the buffer.
.It Cm C-d
Scroll timeline view half a page downwards in the buffer.
.It Cm C-u







>
>
>
>
>
>
>
>
>
>
>







455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
.Cm fnc timeline
are as follows:
.Bl -tag -width Ds
.It Cm Arrow-down, j, >, \&.
Move selection cursor down the timeline.
.It Cm Arrow-up, k, <, \&,
Move selection cursor up the timeline.
.It Cm Arrow-right, l
Scroll the view two columns to the right in the buffer.  The comment field
moves left on the screen.
.It Cm Arrow-left, h
Scroll the view two columns to the left in the buffer.  The comment field
moves right on the screen.
.It Cm $
Scroll the view right to the end of the longest comment summary line on the
page.
.It Cm 0
Scroll the view left to the beginning of the line.
.It Cm C-f, Page-down
Scroll timeline view one page downwards in the buffer.
.It Cm C-b, Page-up
Scroll timeline view one page upwards in the buffer.
.It Cm C-d
Scroll timeline view half a page downwards in the buffer.
.It Cm C-u
1298
1299
1300
1301
1302
1303
1304















1305
1306
1307
1308
1309
1310
1311
1312
value is
.Qq yellow .
.El
.Pp
To clear environment variables, issue
.Cm unset Ar ENVIRONMENT_VARIABLE
in the shell.















.Sh EXIT STATUS
.Ex -std fnc
.Sh SEE ALSO
.Xr fossil 1 ,
.Xr re_format 7
.Xr sqlite3 1
.Sh AUTHOR
.An Mark Jamsek Aq Mt mark@jamsek.com







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
value is
.Qq yellow .
.El
.Pp
To clear environment variables, issue
.Cm unset Ar ENVIRONMENT_VARIABLE
in the shell.
.Pp
.Nm
displays best with UTF-8, and will detect whether UTF-8 is enabled to determine
which characters to draw in certain views.  If UTF-8 is supported by your
terminal but is currently disabled, it can be enabled with
.Qq export LC_ALL=en_US.UTF-8 ;
If not available,
.Nm
will revert to ASCII.  Relatedly, some fonts may render certain characters
poorly in the help screen;
.Li Monospace Regular ,
.Li JetBrains Mono ,
and
.Li Menlo
are known to render all characters well.
.Sh EXIT STATUS
.Ex -std fnc
.Sh SEE ALSO
.Xr fossil 1 ,
.Xr re_format 7
.Xr sqlite3 1
.Sh AUTHOR
.An Mark Jamsek Aq Mt mark@jamsek.com

Changes to src/fnc.c.

17
18
19
20
21
22
23



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49


50
51
52
53
54
55
56

57
58
59
60
61
62
63

/*
 * _POSIX_C_SOURCE >= 199309L needed for sigaction() & sigemptyset() on Linux,
 * but glibc docs claim _XOPEN_SOURCE >= 700 has the same effect, plus we need
 * _XOPEN_SOURCE >= 500 for ncurses wchar APIs on linux.
 */
#ifdef __linux__



# ifndef _XOPEN_SOURCE
#  define _XOPEN_SOURCE 700
# endif  /* _XOPEN_SOURCE */
# ifndef _DEFAULT_SOURCE
#  define _DEFAULT_SOURCE  /* strsep() on glibc >= 2.19. */
# endif  /* _DEFAULT_SOURCE */
# ifdef __has_include
#  if __has_include("linux/landlock.h")
#   define HAVE_LANDLOCK
#   include <linux/landlock.h>
#   include <linux/prctl.h>
#   include <sys/prctl.h>
#   include <sys/syscall.h>
#   include <fcntl.h>
#   include <libgen.h>
#  endif  /* LANDLOCK_H */
# endif  /* __has_include */
#endif  /* __linux__ */

#ifdef FCLI_USE_SIGACTION
#define FCLI_USE_SIGACTION 0  /* We want C-c to exit. */
#endif

#include <sys/queue.h>
#include <sys/ioctl.h>
#include <sys/stat.h>



#ifdef _WIN32
#include <windows.h>
#define ssleep(x) Sleep(x)
#else
#define ssleep(x) usleep((x) * 1000)
#endif

#include <ctype.h>
#include <curses.h>
#include <panel.h>
#include <locale.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>







>
>
>













<












>
>







>







17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

/*
 * _POSIX_C_SOURCE >= 199309L needed for sigaction() & sigemptyset() on Linux,
 * but glibc docs claim _XOPEN_SOURCE >= 700 has the same effect, plus we need
 * _XOPEN_SOURCE >= 500 for ncurses wchar APIs on linux.
 */
#ifdef __linux__
# ifndef _BSD_SOURCE
#  define _BSD_SOURCE	/* mkstemps(3) on glibc <= 2.19 */
# endif  /* _BSD_SOURCE */
# ifndef _XOPEN_SOURCE
#  define _XOPEN_SOURCE 700
# endif  /* _XOPEN_SOURCE */
# ifndef _DEFAULT_SOURCE
#  define _DEFAULT_SOURCE  /* strsep() on glibc >= 2.19. */
# endif  /* _DEFAULT_SOURCE */
# ifdef __has_include
#  if __has_include("linux/landlock.h")
#   define HAVE_LANDLOCK
#   include <linux/landlock.h>
#   include <linux/prctl.h>
#   include <sys/prctl.h>
#   include <sys/syscall.h>

#   include <libgen.h>
#  endif  /* LANDLOCK_H */
# endif  /* __has_include */
#endif  /* __linux__ */

#ifdef FCLI_USE_SIGACTION
#define FCLI_USE_SIGACTION 0  /* We want C-c to exit. */
#endif

#include <sys/queue.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>

#ifdef _WIN32
#include <windows.h>
#define ssleep(x) Sleep(x)
#else
#define ssleep(x) usleep((x) * 1000)
#endif
#include <fcntl.h>
#include <ctype.h>
#include <curses.h>
#include <panel.h>
#include <locale.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116

117
118
119

120

121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

139
140
141
142
143
144
145
146
147
148






149
150
151
152
153
154
155
/* Utility macros. */
#define MIN(_a, _b)	((_a) < (_b) ? (_a) : (_b))
#define MAX(_a, _b)	((_a) > (_b) ? (_a) : (_b))
#define ABS(_n)		((_n) >= 0 ? (_n) : -(_n))
#ifndef CTRL
#define CTRL(key)	((key) & 037)	/* CTRL+<key> input. */
#endif
#define nitems(a)	(sizeof((a)) / sizeof((a)[0]))
#define ndigits(_d, _n)	do { _d++; } while (_n /= 10)
#define STRINGIFYOUT(s)	#s
#define STRINGIFY(s)	STRINGIFYOUT(s)
#define CONCATOUT(a, b)	a ## b
#define CONCAT(a, b)	CONCATOUT(a, b)
#define FILE_POSITION	__FILE__ ":" STRINGIFY(__LINE__)
#define FLAG_SET(f, b)	((f) |= (b))
#define FLAG_CHK(f, b)	((f) & (b))
#define FLAG_TOG(f, b)	((f) ^= (b))
#define FLAG_CLR(f, b)	((f) &= ~(b))

/* Application macros. */
#define PRINT_VERSION	STRINGIFY(FNC_VERSION)
#define DEF_DIFF_CTX	5		/* Default diff context lines. */
#define MAX_DIFF_CTX	64		/* Max diff context lines. */
#define HSPLIT_SCALE	0.4		/* Default horizontal split scale. */
#define SPIN_INTERVAL	200		/* Status line progress indicator. */
#define LINENO_WIDTH	6		/* View lineno max column width. */
#define MAX_PCT_LEN	7		/* Line position upto max len 99.99% */
#define SPINNER		"\\|/-\0"
#define NULL_DEVICE	"/dev/null"
#define NULL_DEVICELEN	(sizeof(NULL_DEVICE) - 1)
#define KEY_ESCAPE	27

#if DEBUG
#define RC(r, fmt, ...)	fcli_err_set(r, "%s::%s " fmt,			\
			    __func__, FILE_POSITION, __VA_ARGS__)

#else

#define RC(r, fmt, ...) fcli_err_set(r, fmt, __VA_ARGS__)
#endif /* DEBUG */

/* fossil(1) db-related paths. */
#define REPODB		fsl_cx_db_file_repo(fcli_cx(), NULL)
#define REPODIR		getdirname(REPODB, -1, false)
#define CKOUTDIR	fsl_cx_ckout_dir_name(fcli_cx(), NULL)

/* Portability macros. */
#ifndef __OpenBSD__
# ifndef HAVE_STRTONUM  /* Use strtol and a range check to emulate strtonum. */
#  define strtonum(s, min, max, o)	strtol(s, (char **)o, 10)
#  define inrange(n, min, max)		(((n) >= (min)) && ((n) <= (max)))
# endif /* HAVE_STRTONUM */
#else
#  define inrange(n, min, max) true
#endif /* OpenBSD */


#ifndef __dead
#define __dead	__attribute__((noreturn))
#endif

#ifndef TAILQ_FOREACH_SAFE
/* Rewrite of OpenBSD 6.9 sys/queue.h for Linux builds. */
#define TAILQ_FOREACH_SAFE(var, head, field, tmp)			\
	for ((var) = ((head)->tqh_first);				\
		(var) != (NULL) && ((tmp) = TAILQ_NEXT(var, field), 1);	\
		(var) = (tmp))






#endif

/*
 * STAILQ was added to OpenBSD 6.9; fallback to SIMPLEQ for prior versions.
 * XXX This is an ugly hack; replace with a better solution.
 */
#ifdef __OpenBSD__







|
|
|
|
|
|
|
|
|
|
|













>

|
|
>

>
|

















>










>
>
>
>
>
>







91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
/* Utility macros. */
#define MIN(_a, _b)	((_a) < (_b) ? (_a) : (_b))
#define MAX(_a, _b)	((_a) > (_b) ? (_a) : (_b))
#define ABS(_n)		((_n) >= 0 ? (_n) : -(_n))
#ifndef CTRL
#define CTRL(key)	((key) & 037)	/* CTRL+<key> input. */
#endif
#define nitems(_a)		(sizeof((_a)) / sizeof((_a)[0]))
#define ndigits(_d, _n)		do { _d++; } while (_n /= 10)
#define STRINGIFYOUT(_s)	#_s
#define STRINGIFY(_s)		STRINGIFYOUT(_s)
#define CONCATOUT(_a, _b)	_a ## _b
#define CONCAT(_a, _b)		CONCATOUT(_a, _b)
#define FILE_POSITION		__FILE__ ":" STRINGIFY(__LINE__)
#define FLAG_SET(_f, _b)	((_f) |= (_b))
#define FLAG_CHK(_f, _b)	((_f) & (_b))
#define FLAG_TOG(_f, _b)	((_f) ^= (_b))
#define FLAG_CLR(_f, _b)	((_f) &= ~(_b))

/* Application macros. */
#define PRINT_VERSION	STRINGIFY(FNC_VERSION)
#define DEF_DIFF_CTX	5		/* Default diff context lines. */
#define MAX_DIFF_CTX	64		/* Max diff context lines. */
#define HSPLIT_SCALE	0.4		/* Default horizontal split scale. */
#define SPIN_INTERVAL	200		/* Status line progress indicator. */
#define LINENO_WIDTH	6		/* View lineno max column width. */
#define MAX_PCT_LEN	7		/* Line position upto max len 99.99% */
#define SPINNER		"\\|/-\0"
#define NULL_DEVICE	"/dev/null"
#define NULL_DEVICELEN	(sizeof(NULL_DEVICE) - 1)
#define KEY_ESCAPE	27
#define RC_RESET(_rc)	do { fcli_err_reset(); _rc = FSL_RC_OK; } while (0)
#if DEBUG
#define RC_DEBUG(_r, _fmt, ...)	fcli_err_set(_r, "%s::%s " _fmt,	\
				    __func__, FILE_POSITION, __VA_ARGS__)
#define RC(_r, ...)		RC_DEBUG(_r, __VA_ARGS__, "")
#else
#define RC_REL(_r, _fmt, ...)	fcli_err_set(_r, _fmt, __VA_ARGS__)
#define RC(_r, ...)		RC_REL(_r, __VA_ARGS__, "")
#endif /* DEBUG */

/* fossil(1) db-related paths. */
#define REPODB		fsl_cx_db_file_repo(fcli_cx(), NULL)
#define REPODIR		getdirname(REPODB, -1, false)
#define CKOUTDIR	fsl_cx_ckout_dir_name(fcli_cx(), NULL)

/* Portability macros. */
#ifndef __OpenBSD__
# ifndef HAVE_STRTONUM  /* Use strtol and a range check to emulate strtonum. */
#  define strtonum(s, min, max, o)	strtol(s, (char **)o, 10)
#  define inrange(n, min, max)		(((n) >= (min)) && ((n) <= (max)))
# endif /* HAVE_STRTONUM */
#else
#  define inrange(n, min, max) true
#endif /* OpenBSD */

#define PRINTFV(fmt, args) __attribute__((format (printf, fmt, args)))
#ifndef __dead
#define __dead	__attribute__((noreturn))
#endif

#ifndef TAILQ_FOREACH_SAFE
/* Rewrite of OpenBSD 6.9 sys/queue.h for Linux builds. */
#define TAILQ_FOREACH_SAFE(var, head, field, tmp)			\
	for ((var) = ((head)->tqh_first);				\
		(var) != (NULL) && ((tmp) = TAILQ_NEXT(var, field), 1);	\
		(var) = (tmp))
#endif
#ifndef STAILQ_FOREACH_SAFE
#define STAILQ_FOREACH_SAFE(var, head, field, tmp)			\
	for ((var) = ((head)->stqh_first);				\
		(var) && ((tmp) = STAILQ_NEXT(var, field), 1);		\
		(var) = (tmp))
#endif

/*
 * STAILQ was added to OpenBSD 6.9; fallback to SIMPLEQ for prior versions.
 * XXX This is an ugly hack; replace with a better solution.
 */
#ifdef __OpenBSD__
164
165
166
167
168
169
170

171
172
173
174
175
176

177
178
179
180
181
182
183

184
185
186
187
188
189
190
# endif /* strlcat */
# ifndef strlcpy
#  define strlcpy(_d, _s, _sz) fsl_strlcpy(_d, _s, _sz)
# endif /* strlcpy */
#endif /* __linux__ */

__dead static void	usage(void);

static void		usage_timeline(void);
static void		usage_diff(void);
static void		usage_tree(void);
static void		usage_blame(void);
static void		usage_branch(void);
static void		usage_config(void);

static int		fcli_flag_type_arg_cb(fcli_cliflag const *);
static int		cmd_timeline(fcli_command const *);
static int		cmd_diff(fcli_command const *);
static int		cmd_tree(fcli_command const *);
static int		cmd_blame(fcli_command const *);
static int		cmd_branch(fcli_command const *);
static int		cmd_config(fcli_command const *);


/*
 * Singleton initialising global configuration and state for app startup.
 */
static struct fnc_setup {
	/* Global options. */
	const char	*cmdarg;	/* Retain argv[1] for use/err report. */







>






>







>







179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# endif /* strlcat */
# ifndef strlcpy
#  define strlcpy(_d, _s, _sz) fsl_strlcpy(_d, _s, _sz)
# endif /* strlcpy */
#endif /* __linux__ */

__dead static void	usage(void);
static void		help_stash(const fcli_command *);
static void		usage_timeline(void);
static void		usage_diff(void);
static void		usage_tree(void);
static void		usage_blame(void);
static void		usage_branch(void);
static void		usage_config(void);
static void		usage_stash(void);
static int		fcli_flag_type_arg_cb(fcli_cliflag const *);
static int		cmd_timeline(fcli_command const *);
static int		cmd_diff(fcli_command const *);
static int		cmd_tree(fcli_command const *);
static int		cmd_blame(fcli_command const *);
static int		cmd_branch(fcli_command const *);
static int		cmd_config(fcli_command const *);
static int		cmd_stash(fcli_command const *);

/*
 * Singleton initialising global configuration and state for app startup.
 */
static struct fnc_setup {
	/* Global options. */
	const char	*cmdarg;	/* Retain argv[1] for use/err report. */
239
240
241
242
243
244
245
246
247
248
249
250
251
252

253
254
255
256
257
258
259
	/* Config options. */
	bool		 lsconf;	/* List all defined settings. */
	bool		 unset;		/* Unset the specified setting. */

	/* Command line flags and help. */
	fcli_help_info	  fnc_help;			/* Global help. */
	fcli_cliflag	  cliflags_global[3];		/* Global options. */
	fcli_command	  cmd_args[7];			/* App commands. */
	fcli_cliflag	  cliflags_timeline[13];	/* Timeline options. */
	fcli_cliflag	  cliflags_diff[12];		/* Diff options. */
	fcli_cliflag	  cliflags_tree[5];		/* Tree options. */
	fcli_cliflag	  cliflags_blame[8];		/* Blame options. */
	fcli_cliflag	  cliflags_branch[11];		/* Branch options. */
	fcli_cliflag	  cliflags_config[5];		/* Config options. */

} fnc_init = {
	NULL,		/* cmdarg copy of argv[1] to aid usage/error report. */
	NULL,		/* sym(bolic name) of commit to open defaults to tip. */
	NULL,		/* path for tree to open or timeline to find commits. */
	0,		/* err fnc error state. */
	false,		/* hflag if --help is requested. */
	false,		/* vflag if --version is requested. */







|






>







257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
	/* Config options. */
	bool		 lsconf;	/* List all defined settings. */
	bool		 unset;		/* Unset the specified setting. */

	/* Command line flags and help. */
	fcli_help_info	  fnc_help;			/* Global help. */
	fcli_cliflag	  cliflags_global[3];		/* Global options. */
	fcli_command	  cmd_args[8];			/* App commands. */
	fcli_cliflag	  cliflags_timeline[13];	/* Timeline options. */
	fcli_cliflag	  cliflags_diff[12];		/* Diff options. */
	fcli_cliflag	  cliflags_tree[5];		/* Tree options. */
	fcli_cliflag	  cliflags_blame[8];		/* Blame options. */
	fcli_cliflag	  cliflags_branch[11];		/* Branch options. */
	fcli_cliflag	  cliflags_config[5];		/* Config options. */
	fcli_cliflag	  cliflags_stash[5];		/* Stash options. */
} fnc_init = {
	NULL,		/* cmdarg copy of argv[1] to aid usage/error report. */
	NULL,		/* sym(bolic name) of commit to open defaults to tip. */
	NULL,		/* path for tree to open or timeline to find commits. */
	0,		/* err fnc error state. */
	false,		/* hflag if --help is requested. */
	false,		/* vflag if --version is requested. */
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
	false,		/* sbs diff defaults to false (show unified diff). */
	false,		/* ws defaults to acknowledge all whitespace. */
	false,		/* eol defaults to acknowledge eol whitespace. */
	false,		/* nocolour defaults to off (i.e., use diff colours). */
	true,		/* verbose defaults to on. */
	false,		/* invert diff defaults to off. */
	false,		/* showln in diff defaults to off. */
	true,		/* proto in diff chunk header defaults to on. */
	NULL,		/* before defaults to any time. */
	NULL,		/* after defaults to any time. */
	NULL,		/* sort by MRU or open/closed (dflt: lexicographical) */
	false,		/* closed only branches is off (defaults to all). */
	false,		/* open only branches is off by (defaults to all). */
	false,		/* noprivate is off (default to show private branch). */
	false,		/* do not list all defined settings by default. */







|







290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
	false,		/* sbs diff defaults to false (show unified diff). */
	false,		/* ws defaults to acknowledge all whitespace. */
	false,		/* eol defaults to acknowledge eol whitespace. */
	false,		/* nocolour defaults to off (i.e., use diff colours). */
	true,		/* verbose defaults to on. */
	false,		/* invert diff defaults to off. */
	false,		/* showln in diff defaults to off. */
	true,		/* proto in diff hunk header defaults to on. */
	NULL,		/* before defaults to any time. */
	NULL,		/* after defaults to any time. */
	NULL,		/* sort by MRU or open/closed (dflt: lexicographical) */
	false,		/* closed only branches is off (defaults to all). */
	false,		/* open only branches is off by (defaults to all). */
	false,		/* noprivate is off (default to show private branch). */
	false,		/* do not list all defined settings by default. */
313
314
315
316
317
318
319




320
321
322
323
324
325
326
	    cmd_blame, usage_blame, fnc_init.cliflags_blame},
	    {"branch", "br\0tag\0",
	    "Show navigable list of repository branches.",
	    cmd_branch, usage_branch, fnc_init.cliflags_branch},
	    {"config", "conf\0cfg\0settings\0set\0",
	    "Configure or view currently available settings.",
	    cmd_config, usage_config, fnc_init.cliflags_config},




	    {NULL, NULL, NULL, NULL, NULL}	/* Sentinel. */
	},

	{ /* cliflags_timeline timeline command related options. */
	    FCLI_FLAG("b", "branch", "<branch>", &fnc_init.filter_branch,
	    "Only display commits that reside on the given <branch>."),
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,







>
>
>
>







332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
	    cmd_blame, usage_blame, fnc_init.cliflags_blame},
	    {"branch", "br\0tag\0",
	    "Show navigable list of repository branches.",
	    cmd_branch, usage_branch, fnc_init.cliflags_branch},
	    {"config", "conf\0cfg\0settings\0set\0",
	    "Configure or view currently available settings.",
	    cmd_config, usage_config, fnc_init.cliflags_config},
	    {"stash", "snapshot\0snap\0save\0sta\0",
	    "Interactively select hunks to stash from the diff of local "
	    "changes on\n  disk.",
	    cmd_stash, usage_stash, fnc_init.cliflags_stash},
	    {NULL, NULL, NULL, NULL, NULL}	/* Sentinel. */
	},

	{ /* cliflags_timeline timeline command related options. */
	    FCLI_FLAG("b", "branch", "<branch>", &fnc_init.filter_branch,
	    "Only display commits that reside on the given <branch>."),
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
	    FCLI_FLAG_BOOL("i", "invert", &fnc_init.invert,
	    "Invert difference between artifacts. Inversion can also be "
	    "toggled\n    with the 'i' key binding in diff view."),
	    FCLI_FLAG_BOOL("l", "line-numbers", &fnc_init.showln,
	    "Show file line numbers in diff output.  Line numbers can also be "
	    "toggled\n    with the 'L' key binding in diff view."),
	    FCLI_FLAG_BOOL_INVERT("P", "no-prototype", &fnc_init.proto,
	    "Disable display of the enclosing function prototype in diff chunk"
	    "headers."),
	    FCLI_FLAG_BOOL_INVERT("q", "quiet", &fnc_init.verbose,
	    "Disable verbose diff output; that is, do not output complete"
	    " content\n    of newly added or deleted files. Verbosity can also"
	    " be toggled with\n    the 'v' key binding in diff view."),
	    FCLI_FLAG_CSTR("R", "repo", "<path>", NULL,
	    "Use the fossil(1) repository located at <path> for this diff\n    "







|







402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
	    FCLI_FLAG_BOOL("i", "invert", &fnc_init.invert,
	    "Invert difference between artifacts. Inversion can also be "
	    "toggled\n    with the 'i' key binding in diff view."),
	    FCLI_FLAG_BOOL("l", "line-numbers", &fnc_init.showln,
	    "Show file line numbers in diff output.  Line numbers can also be "
	    "toggled\n    with the 'L' key binding in diff view."),
	    FCLI_FLAG_BOOL_INVERT("P", "no-prototype", &fnc_init.proto,
	    "Disable display of the enclosing function prototype in diff hunk "
	    "headers."),
	    FCLI_FLAG_BOOL_INVERT("q", "quiet", &fnc_init.verbose,
	    "Disable verbose diff output; that is, do not output complete"
	    " content\n    of newly added or deleted files. Verbosity can also"
	    " be toggled with\n    the 'v' key binding in diff view."),
	    FCLI_FLAG_CSTR("R", "repo", "<path>", NULL,
	    "Use the fossil(1) repository located at <path> for this diff\n    "
518
519
520
521
522
523
524














525
526
527
528
529
530
531
	    "Use the fossil(1) repository located at <path> for this config\n"
	    "    invocation."),
	    FCLI_FLAG_BOOL("u", "unset", &fnc_init.unset,
	    "Unset (i.e., remove) the specified repository setting."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_tree. */















};

enum date_string {
	ISO8601_DATE_ONLY = 10,
	ISO8601_DATE_HHMM = 16,
	ISO8601_TIMESTAMP = 20
};







>
>
>
>
>
>
>
>
>
>
>
>
>
>







541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
	    "Use the fossil(1) repository located at <path> for this config\n"
	    "    invocation."),
	    FCLI_FLAG_BOOL("u", "unset", &fnc_init.unset,
	    "Unset (i.e., remove) the specified repository setting."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_tree. */

	{ /* cliflags_stash stash command related options. */
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
	    "Disable coloured diff output, which is enabled by default on\n    "
	    "supported terminals."),
	    FCLI_FLAG_BOOL("h", "help", NULL,
	    "Display stash command help and usage."),
	    FCLI_FLAG_BOOL_INVERT("P", "no-prototype", &fnc_init.proto,
	    "Disable display of the enclosing function prototype in diff hunk "
	    "headers."),
	    FCLI_FLAG("x", "context", "<n>", &fnc_init.context,
	    "Show <n> context lines when displaying diff; <n> is capped at 64."
	    "\n    Negative values are a no-op."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_stash. */
};

enum date_string {
	ISO8601_DATE_ONLY = 10,
	ISO8601_DATE_HHMM = 16,
	ISO8601_TIMESTAMP = 20
};
555
556
557
558
559
560
561





























562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579

enum fnc_diff_type {
	FNC_DIFF_CKOUT,
	FNC_DIFF_COMMIT,
	FNC_DIFF_BLOB,
	FNC_DIFF_WIKI
};






























struct input {
	void		*data;
	char		*prompt;
	enum input_type	 type;
	int		 flags;
#define SR_CLREOL	1 << 0
#define SR_UPDATE	1 << 1
#define SR_SLEEP	1 << 2
#define SR_RESET	1 << 3
#define SR_ALL		SR_CLREOL | SR_UPDATE | SR_SLEEP | SR_RESET
	char		 buf[BUFSIZ];
	long		 ret;
};

struct fnc_colour {
	STAILQ_ENTRY(fnc_colour) entries;
	regex_t	regex;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>










|







592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645

enum fnc_diff_type {
	FNC_DIFF_CKOUT,
	FNC_DIFF_COMMIT,
	FNC_DIFF_BLOB,
	FNC_DIFF_WIKI
};

enum fnc_diff_mode {
	DIFF_PLAIN,
	COMMIT_META,
	STASH_INTERACTIVE
};

enum fnc_diff_hunk {
	HUNK_NONE,
	HUNK_STASH,
	HUNK_CKOUT
};

enum fnc_patch_rc {
	PATCH_OK,
	PATCH_MALFORMED,
	PATCH_TRUNCATED,
	NO_PATCH,
	HUNK_FAILED,
	PATCH_FAILED,
};

enum stash_opt {
	NO_CHOICE,
	KEEP_FILE,	/* keep remaining hunks in file in ckout */
	KEEP_DIFF,	/* keep remaining hunks in diff in ckout */
	STASH_FILE,	/* stash the rest of the hunks in the file */
	STASH_DIFF	/* stash the rest of the hunks in the diff */
};

struct input {
	void		*data;
	char		*prompt;
	enum input_type	 type;
	int		 flags;
#define SR_CLREOL	1 << 0
#define SR_UPDATE	1 << 1
#define SR_SLEEP	1 << 2
#define SR_RESET	1 << 3
#define SR_ALL		(SR_CLREOL | SR_UPDATE | SR_SLEEP | SR_RESET)
	char		 buf[BUFSIZ];
	long		 ret;
};

struct fnc_colour {
	STAILQ_ENTRY(fnc_colour) entries;
	regex_t	regex;
716
717
718
719
720
721
722

723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743






















































744

745
746
747

748
749
750
751
752
753
754
		fsl_id_t	 rid;
	} tagged;
	const char		*curr_ckout_uuid;
	const char		*glob;  /* Match commits containing glob. */
	char			*path;	/* Match commits involving path. */
	int			 selected;
	int			 nscrolled;

	sig_atomic_t		 quit;
	pthread_t		 thread_id;
	bool			 colour;
	bool			 showmeta;
};

struct fnc_pathlist_entry {
	TAILQ_ENTRY(fnc_pathlist_entry) entry;
	const char	*path;
	size_t		 pathlen;
	void		*data;  /* XXX May want to save id, mode, etc. */
};
TAILQ_HEAD(fnc_pathlist_head, fnc_pathlist_entry);

struct index {
	size_t		*lineno;
	off_t		*offset;
	uint32_t	 n;
	uint32_t	 idx;
};























































struct fnc_diff_view_state {

	struct fnc_view			*parent_view;
	struct fnc_commit_artifact	*selected_entry;
	struct fnc_pathlist_head	*paths;

	fsl_buffer			 buf;
	struct fnc_colours		 colours;
	struct index			 index;
	FILE				*f;
	fsl_uuid_str			 id1;
	fsl_uuid_str			 id2;
	int				 first_line_onscreen;







>





















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>



>







782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
		fsl_id_t	 rid;
	} tagged;
	const char		*curr_ckout_uuid;
	const char		*glob;  /* Match commits containing glob. */
	char			*path;	/* Match commits involving path. */
	int			 selected;
	int			 nscrolled;
	uint16_t		 maxx;
	sig_atomic_t		 quit;
	pthread_t		 thread_id;
	bool			 colour;
	bool			 showmeta;
};

struct fnc_pathlist_entry {
	TAILQ_ENTRY(fnc_pathlist_entry) entry;
	const char	*path;
	size_t		 pathlen;
	void		*data;  /* XXX May want to save id, mode, etc. */
};
TAILQ_HEAD(fnc_pathlist_head, fnc_pathlist_entry);

struct index {
	size_t		*lineno;
	off_t		*offset;
	uint32_t	 n;
	uint32_t	 idx;
};

/*
 * A stash context is comprised of two patch contexts: a (1) patch of all hunks
 * selected to stash; and a (2) patch of all hunks kept in the checkout. Each
 * patch has a queue of fnc_patch_file(s), one for each versioned file with
 * hunks to be stashed or kept. Each fnc_patch_file has a queue of hunks with
 * an array of all context, plus, and minus lines comprising the hunk. Each
 * patch context produces a patch(1) file that gets applied to the base ckout.
 */
struct fnc_patch_hunk {
	STAILQ_ENTRY(fnc_patch_hunk) entries;
	char		**lines;	/* plus, minus, context lines */
	long		  offset;	/* line offset into this hunk */
	size_t		  nlines;	/* number of *lines */
	size_t		  cap;		/* capacity of **lines */
	int_least32_t	  oldfrom;	/* start line in "from" file */
	int_least32_t	  oldlines;	/* number of lines from "oldfrom" */
	int_least32_t	  newfrom;	/* start line in "new" file */
	int_least32_t	  newlines;	/* number of lines from "newfrom" */
	bool		  nonl;		/* line continuation flag */
	enum fnc_patch_rc rc;
};

STAILQ_HEAD(fnc_patch_hunk_head, fnc_patch_hunk);
struct fnc_patch_file {
	STAILQ_ENTRY(fnc_patch_file)	entries;
	char				old[PATH_MAX];
	char				new[PATH_MAX];
	struct fnc_patch_hunk_head	head;
};

typedef int (*fnc_patch_report_cb)(struct fnc_patch_file *, const char *,
    const char *, char *);
STAILQ_HEAD(fnc_patch_file_head, fnc_patch_file);
struct patch_cx {
	fnc_patch_report_cb		 report_cb;
	struct fnc_patch_file		*pf;	/* current fnc_patch_file */
	struct fnc_patch_file_head	 head;	/* queue of fnc_patch_file(s) */
	uint8_t				 context; /* MAX_DIFF_CTX lines = 64 */
	enum fnc_patch_rc		 rc;
	bool				 report;
};

struct stash_cx {
	struct patch_cx	 pcx;
	struct index	 hunk;	   /* line indexes for each hunk in the diff */
	char		 patch[2][PATH_MAX]; /* stash & ckout patch filepath */
	unsigned char	*stash;	   /* bit array into this.hunk->lineno */
#define NBITS	(sizeof(unsigned char) * 8)
#define nbytes(nbits)	(((nbits) + 7) >> 3)
#define BIT_SET(_B, _i)	(_B[(_i / NBITS)] |=  (1 << (_i % NBITS)))
#define BIT_CLR(_B, _i)	(_B[(_i / NBITS)] &= ~(1 << (_i % NBITS)))
#define BIT_CHK(_B, _i)	(_B[(_i / NBITS)] &   (1 << (_i % NBITS)))
};

struct fnc_diff_view_state {
	struct fnc_view			*view;
	struct fnc_view			*parent_view;
	struct fnc_commit_artifact	*selected_entry;
	struct fnc_pathlist_head	*paths;
	struct stash_cx			 scx;
	fsl_buffer			 buf;
	struct fnc_colours		 colours;
	struct index			 index;
	FILE				*f;
	fsl_uuid_str			 id1;
	fsl_uuid_str			 id2;
	int				 first_line_onscreen;
762
763
764
765
766
767
768


769
770
771
772
773
774
775
776
777
778
779
	int				 lineno;
	int				 gtl;
	uint32_t			 ndlines;
	size_t				 ncols;
	size_t				 nlines;
	enum line_type			*dlines;
	enum line_attr			 sline;


	off_t				*line_offsets;
	bool				 eof;
	bool				 colour;
	bool				 showmeta;
	bool				 showln;
	bool				 patch;
};

TAILQ_HEAD(fnc_parent_trees, fnc_parent_tree);
struct fnc_tree_view_state {			  /* Parent trees of the- */
	struct fnc_parent_trees		 parents; /* -current subtree. */







>
>



<







885
886
887
888
889
890
891
892
893
894
895
896

897
898
899
900
901
902
903
	int				 lineno;
	int				 gtl;
	uint32_t			 ndlines;
	size_t				 ncols;
	size_t				 nlines;
	enum line_type			*dlines;
	enum line_attr			 sline;
	enum fnc_diff_hunk		 stash;
	enum fnc_diff_mode		 diff_mode;
	off_t				*line_offsets;
	bool				 eof;
	bool				 colour;

	bool				 showln;
	bool				 patch;
};

TAILQ_HEAD(fnc_parent_trees, fnc_parent_tree);
struct fnc_tree_view_state {			  /* Parent trees of the- */
	struct fnc_parent_trees		 parents; /* -current subtree. */
980
981
982
983
984
985
986

987
988
989
990
991
992
993

994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
static int		 signal_tl_thread(struct fnc_view *, int);
static int		 draw_commits(struct fnc_view *);
static void		 parse_emailaddr_username(char **);
static int		 formatln(wchar_t **, int *, const char *, size_t, int,
			    bool);
static size_t		 expand_tab(char **, const char *, int);
static int		 multibyte_to_wchar(const char *, wchar_t **, size_t *);

static int		 write_commit_line(struct fnc_view *,
			    struct fnc_commit_artifact *, int);
static int		 view_input(struct fnc_view **, int *,
			    struct fnc_view *, struct view_tailhead *);
static int		 cycle_view(struct fnc_view *);
static int		 toggle_fullscreen(struct fnc_view **,
			    struct fnc_view *);

static int		 help(struct fnc_view *);
static int		 padpopup(struct fnc_view *, int, int, FILE *,
			    const char *);
static void		 centerprint(WINDOW *, int, int, int, const char *,
			    chtype);
static int		 tl_input_handler(struct fnc_view **, struct fnc_view *,
			    int);
static int		 move_tl_cursor_down(struct fnc_view *, uint16_t);
static void		 move_tl_cursor_up(struct fnc_view *, uint16_t, bool);
static int		 timeline_scroll_down(struct fnc_view *, int);
static void		 timeline_scroll_up(struct fnc_tl_view_state *, int);
static bool		 tagged_commit(struct fnc_tl_view_state *);







>







>

|
|
|
|







1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
static int		 signal_tl_thread(struct fnc_view *, int);
static int		 draw_commits(struct fnc_view *);
static void		 parse_emailaddr_username(char **);
static int		 formatln(wchar_t **, int *, const char *, size_t, int,
			    bool);
static size_t		 expand_tab(char **, const char *, int);
static int		 multibyte_to_wchar(const char *, wchar_t **, size_t *);
static int		 replace_unicode(char **, const char *);
static int		 write_commit_line(struct fnc_view *,
			    struct fnc_commit_artifact *, int);
static int		 view_input(struct fnc_view **, int *,
			    struct fnc_view *, struct view_tailhead *);
static int		 cycle_view(struct fnc_view *);
static int		 toggle_fullscreen(struct fnc_view **,
			    struct fnc_view *);
static int		 stash_help(struct fnc_view *, int8_t);
static int		 help(struct fnc_view *);
static int		 padpopup(struct fnc_view *, const char *[][2],
			    const char **, const char *, int8_t);
static int		 centerprint(WINDOW *, size_t, size_t, size_t,
			    const char *, chtype);
static int		 tl_input_handler(struct fnc_view **, struct fnc_view *,
			    int);
static int		 move_tl_cursor_down(struct fnc_view *, uint16_t);
static void		 move_tl_cursor_up(struct fnc_view *, uint16_t, bool);
static int		 timeline_scroll_down(struct fnc_view *, int);
static void		 timeline_scroll_up(struct fnc_tl_view_state *, int);
static bool		 tagged_commit(struct fnc_tl_view_state *);
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033

1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063

























































1064
1065
1066
1067
1068
1069
1070
static int		 view_search_start(struct fnc_view *);
static void		 tl_grep_init(struct fnc_view *);
static int		 tl_search_next(struct fnc_view *);
static bool		 find_commit_match(struct fnc_commit_artifact *,
			    regex_t *);
static int		 init_diff_view(struct fnc_view **, int, int,
			    struct fnc_commit_artifact *, struct fnc_view *,
			    bool);
static int		 open_diff_view(struct fnc_view *,
			    struct fnc_commit_artifact *,
			    struct fnc_pathlist_head *,
			    struct fnc_view *, bool);
static void		 set_diff_opt(struct fnc_diff_view_state *);
static void		 show_diff_status(struct fnc_view *);
static int		 create_diff(struct fnc_diff_view_state *);
static int		 create_changeset(struct fnc_commit_artifact *);

static int		 write_commit_meta(struct fnc_diff_view_state *);
static int		 countlines(const char *);
static int		 wrapline(char *, fsl_size_t,
			    struct fnc_diff_view_state *, off_t *);
static int		 add_line_offset(off_t **, size_t *, off_t);
static int		 add_line_type(enum line_type **, enum line_type,
			    uint32_t *, uint32_t, bool);
static int		 diff_commit(struct fnc_diff_view_state *);
static int		 diff_checkout(struct fnc_diff_view_state *);
static int		 write_diff_meta(struct fnc_diff_view_state *,
			    const char *, fsl_uuid_str, const char *,
			    fsl_uuid_str, enum fsl_ckout_change_e);
static int		 diff_file(struct fnc_diff_view_state *, fsl_buffer *,
			    const char *, fsl_uuid_str, const char *,
			    enum fsl_ckout_change_e);
static int		 diff_non_checkin(struct fnc_diff_view_state *);
static int		 diff_file_artifact(struct fnc_diff_view_state *,
			    fsl_id_t, const fsl_card_F *, const fsl_card_F *,
			    fsl_ckout_change_e);
static int		 show_diff(struct fnc_view *);
static int		 write_diff(struct fnc_view *, char *);
static int		 match_line(const char *, regex_t *, size_t,
			    regmatch_t *);
static int		 draw_matched_line(struct fnc_view *, const char *,
			    int *, int, int, regmatch_t *, attr_t);
static void		 drawborder(struct fnc_view *);
static int		 diff_input_handler(struct fnc_view **,
			    struct fnc_view *, int);
static int		 request_tl_commits(struct fnc_view *);
static int		 reset_diff_view(struct fnc_view *, bool);

























































static int		 set_selected_commit(struct fnc_diff_view_state *,
			    struct commit_entry *);
static void		 diff_grep_init(struct fnc_view *);
static int		 find_next_match(struct fnc_view *);
static void		 grep_set_view(struct fnc_view *, FILE **, off_t **,
			    size_t *, int **, int **, int **, int **,
			    uint8_t *);







|



|




>

|



<
<






|
|















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165


1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
static int		 view_search_start(struct fnc_view *);
static void		 tl_grep_init(struct fnc_view *);
static int		 tl_search_next(struct fnc_view *);
static bool		 find_commit_match(struct fnc_commit_artifact *,
			    regex_t *);
static int		 init_diff_view(struct fnc_view **, int, int,
			    struct fnc_commit_artifact *, struct fnc_view *,
			    enum fnc_diff_mode);
static int		 open_diff_view(struct fnc_view *,
			    struct fnc_commit_artifact *,
			    struct fnc_pathlist_head *,
			    struct fnc_view *, enum fnc_diff_mode);
static void		 set_diff_opt(struct fnc_diff_view_state *);
static void		 show_diff_status(struct fnc_view *);
static int		 create_diff(struct fnc_diff_view_state *);
static int		 create_changeset(struct fnc_commit_artifact *);
static int		 make_stash_diff(struct fnc_diff_view_state *, char *);
static int		 write_commit_meta(struct fnc_diff_view_state *);
/* static int		 countlines(const char *); */
static int		 wrapline(char *, fsl_size_t,
			    struct fnc_diff_view_state *, off_t *);
static int		 add_line_offset(off_t **, size_t *, off_t);


static int		 diff_commit(struct fnc_diff_view_state *);
static int		 diff_checkout(struct fnc_diff_view_state *);
static int		 write_diff_meta(struct fnc_diff_view_state *,
			    const char *, fsl_uuid_str, const char *,
			    fsl_uuid_str, enum fsl_ckout_change_e);
static int		 diff_file(struct fnc_diff_view_state *, fsl_buffer *,
			    const char *, const char *, fsl_uuid_str,
			    const char *, enum fsl_ckout_change_e);
static int		 diff_non_checkin(struct fnc_diff_view_state *);
static int		 diff_file_artifact(struct fnc_diff_view_state *,
			    fsl_id_t, const fsl_card_F *, const fsl_card_F *,
			    fsl_ckout_change_e);
static int		 show_diff(struct fnc_view *);
static int		 write_diff(struct fnc_view *, char *);
static int		 match_line(const char *, regex_t *, size_t,
			    regmatch_t *);
static int		 draw_matched_line(struct fnc_view *, const char *,
			    int *, int, int, regmatch_t *, attr_t);
static void		 drawborder(struct fnc_view *);
static int		 diff_input_handler(struct fnc_view **,
			    struct fnc_view *, int);
static int		 request_tl_commits(struct fnc_view *);
static int		 reset_diff_view(struct fnc_view *, bool);
static int		 stash_get_rm_cb(fsl_ckout_unmanage_state const *);
static int		 stash_get_add_cb(fsl_ckout_manage_state const *,
			    bool *);
static int		 f__add_files_in_sfile(int *, int);
static int		 f__stash_get(bool);
static int		 fnc_stash(struct fnc_view *);
static int		 select_hunks(struct fnc_view *);
static int		 stash_input_handler(struct fnc_view *, bool *);
static void		 set_choice(struct fnc_diff_view_state *, bool *,
			    struct input *, struct index *, uint32_t *,
			    size_t *, size_t *, bool *, enum stash_opt *);
static unsigned char	*alloc_bitstring(size_t);
static int		 generate_prompt(char ***, char *, size_t, short);
static void		 free_answers(char **);
static bool		 valid_input(const char *, char **);
static int		 revert_ckout(bool, bool);
static int		 rm_vfile_renames_cb(fsl_stmt *, void *);
static int		 fnc_patch(struct patch_cx *, const char *);
static int		 scan_patch(struct patch_cx *, FILE *);
static int		 find_patch_file(struct fnc_patch_file **,
			    struct patch_cx *, FILE *);
static int		 parse_filename(const char *, char **, int);
static int		 set_patch_paths(struct fnc_patch_file *, const char *,
			    const char *);
static int		 parse_hunk(struct fnc_patch_hunk **, FILE *, uint8_t,
			    bool *);
static int		 parse_hdr(char *, bool *, struct fnc_patch_hunk *);
static int		 strtolnum(char **, int_least32_t *);
static int		 pushline(struct fnc_patch_hunk *, const char *);
static int		 alloc_hunk_line(struct fnc_patch_hunk *, const char *);
static int		 peek_special_line(struct fnc_patch_hunk *, FILE *, int);
static int		 apply_patch(struct patch_cx *, struct fnc_patch_file *,
			    bool);
static int		 fnc_open_tmpfile(char **, FILE **, const char *,
			    const char *);
static int		 patch_file(struct fnc_patch_file *, const char *,
			    FILE *, int, mode_t *);
static int		 apply_hunk(FILE *, struct fnc_patch_hunk *, long *);
static int		 locate_hunk(FILE *, struct fnc_patch_hunk *, off_t *,
			    long *);
static int		 copyfile(FILE *, FILE *, off_t, off_t);
static int		 test_hunk(FILE *, struct fnc_patch_hunk *);
static int		 fnc_add_vfile(struct patch_cx *, const char *, bool);
static int		 fnc_addvfile_cb(const fsl_ckout_manage_state *, bool *);
static int		 fnc_rm_vfile(struct patch_cx *, const char *, bool);
static int		 fnc_rmvfile_cb(const fsl_ckout_unmanage_state *);
static int		 fnc_rename_vfile(const char *, const char *);
static int		 patch_reporter(struct fnc_patch_file *,
			    const char *, const char *, char *);
static int		 patch_report(const char *, const char *,
			    char *, long, long, long, long, long,
			    enum fnc_patch_rc);
static void		 free_patch(struct fnc_patch_file *);
static int		 f__stash_path(int, int, const char *);
static int		 f__check_stash_tables(void);
static int		 f__stash_create(const char *, int);
/* static int		 fnc_execp(const char *const *, const int); */
static int		 set_selected_commit(struct fnc_diff_view_state *,
			    struct commit_entry *);
static void		 diff_grep_init(struct fnc_view *);
static int		 find_next_match(struct fnc_view *);
static void		 grep_set_view(struct fnc_view *, FILE **, off_t **,
			    size_t *, int **, int **, int **, int **,
			    uint8_t *);
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198

1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
static void		 view_set_child(struct fnc_view *, struct fnc_view *);
static int		 view_close_child(struct fnc_view *);
static int		 close_tree_view(struct fnc_view *);
static int		 close_timeline_view(struct fnc_view *);
static int		 close_diff_view(struct fnc_view *);
static void		 free_index(struct index *);
static void		 free_tags(struct fnc_tl_view_state *, bool);
static int		 view_resize(struct fnc_view *, enum view_mode);
static bool		 screen_is_split(struct fnc_view *);
static bool		 screen_is_shared(struct fnc_view *);
static void		 updatescreen(WINDOW *, bool, bool);
static void		 fnc_resizeterm(void);
static int		 join_tl_thread(struct fnc_tl_view_state *);
static void		 fnc_free_commits(struct commit_queue *);
static void		 fnc_commit_artifact_close(struct fnc_commit_artifact*);
static int		 fsl_file_artifact_free(void *, void *);
static void		 sigwinch_handler(int);
static void		 sigpipe_handler(int);
static void		 sigcont_handler(int);
static int		 draw_lineno(struct fnc_view *, int, int, attr_t);
static bool		 gotoline(struct fnc_view *, int *, int *);
static int		 strtonumcheck(long *, const char *, const int,
			    const int);
static int		 fnc_prompt_input(struct fnc_view *, struct input *);
static int		 fnc_date_to_mtime(double *, const char *, int);
static int		 cook_input(char *, int, WINDOW *);
static int		 sitrep(struct fnc_view *, const char *, int);
static char		*fnc_strsep (char **, const char *);
static bool		 fnc_str_has_upper(const char *);
static int		 fnc_make_sql_glob(char **, char **, const char *,
			    bool);

#ifndef HAVE_LANDLOCK
static int		 init_unveil(const char *, const char *, bool);
#else
static int		 init_landlock(const char **, const int);
static const char	*gettzfile(void);
#define init_unveil(_r, _c, _s)	\
	init_landlock((const char*[]){_r, _c, P_tmpdir, gettzfile()}, 4)
#endif  /* HAVE_LANDLOCK */
static const char	*getdirname(const char *, fsl_int_t, bool);
static int		 set_colours(struct fnc_colours *, enum fnc_view_id);
static int		 set_colour_scheme(struct fnc_colours *,
			    const int (*)[2], const char **, int);
static int		 init_colour(enum fnc_opt_id);
static int		 default_colour(enum fnc_opt_id);







|


















|




>

|


<
|
<







1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385

1386

1387
1388
1389
1390
1391
1392
1393
static void		 view_set_child(struct fnc_view *, struct fnc_view *);
static int		 view_close_child(struct fnc_view *);
static int		 close_tree_view(struct fnc_view *);
static int		 close_timeline_view(struct fnc_view *);
static int		 close_diff_view(struct fnc_view *);
static void		 free_index(struct index *);
static void		 free_tags(struct fnc_tl_view_state *, bool);
static int		 view_resize(struct fnc_view *, bool);
static bool		 screen_is_split(struct fnc_view *);
static bool		 screen_is_shared(struct fnc_view *);
static void		 updatescreen(WINDOW *, bool, bool);
static void		 fnc_resizeterm(void);
static int		 join_tl_thread(struct fnc_tl_view_state *);
static void		 fnc_free_commits(struct commit_queue *);
static void		 fnc_commit_artifact_close(struct fnc_commit_artifact*);
static int		 fsl_file_artifact_free(void *, void *);
static void		 sigwinch_handler(int);
static void		 sigpipe_handler(int);
static void		 sigcont_handler(int);
static int		 draw_lineno(struct fnc_view *, int, int, attr_t);
static bool		 gotoline(struct fnc_view *, int *, int *);
static int		 strtonumcheck(long *, const char *, const int,
			    const int);
static int		 fnc_prompt_input(struct fnc_view *, struct input *);
static int		 fnc_date_to_mtime(double *, const char *, int);
static int		 cook_input(char *, int, WINDOW *);
static int PRINTFV(3, 4) sitrep(struct fnc_view *, int, const char *, ...);
static char		*fnc_strsep (char **, const char *);
static bool		 fnc_str_has_upper(const char *);
static int		 fnc_make_sql_glob(char **, char **, const char *,
			    bool);
static const char	*gettzfile(void);
#ifndef HAVE_LANDLOCK
static int		 init_unveil(const char **, const char **, int, bool);
#else
static int		 init_landlock(const char **, const int);

#define init_unveil(_p, _m, _n, _d)	init_landlock(_p, _n)

#endif  /* HAVE_LANDLOCK */
static const char	*getdirname(const char *, fsl_int_t, bool);
static int		 set_colours(struct fnc_colours *, enum fnc_view_id);
static int		 set_colour_scheme(struct fnc_colours *,
			    const int (*)[2], const char **, int);
static int		 init_colour(enum fnc_opt_id);
static int		 default_colour(enum fnc_opt_id);
1226
1227
1228
1229
1230
1231
1232
1233









1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252

1253
1254
1255
1256
1257
1258
1259

1260


1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300


1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321







1322
1323
1324
1325
1326
1327
1328
				    const char *, size_t);

int
main(int argc, const char **argv)
{
	fcli_command	*cmd = NULL;
	char		*path = NULL;
	int		 rc = 0;










	if (!setlocale(LC_CTYPE, ""))
		fsl_fprintf(stderr, "[!] Warning: Can't set locale.\n");

	fnc_init.cmdarg = argv[1];	/* Which cmd to show usage if needed. */
#if DEBUG
	fcli.clientFlags.verbose = 2;	/* Verbose error reporting. */
#endif
	rc = fcli_setup_v2(argc, argv, fnc_init.cliflags_global,
	    &fnc_init.fnc_help);
	if (rc)
		goto end;

	if (fnc_init.vflag) {
		fnc_show_version();
		goto end;
	} else if (fnc_init.hflag)
		usage();
		/* NOT REACHED */


#ifdef __OpenBSD__
	/*
	 * See pledge(2). This is the most restrictive set we can operate under.
	 * Look for any adverse impact & revise when implementing new features.
	 * stdio (close, sigaction); rpath (chdir getcwd lstat); wpath (getcwd);
	 * cpath (symlink); flock (open); tty (TIOCGWINSZ); unveil (unveil).

	 */


	if (pledge("stdio rpath wpath cpath flock tty unveil", NULL) == -1) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS), "%s", "pledge");
		goto end;
	}
#endif
	rc = fcli_fingerprint_check(true);
	if (rc)
		goto end;

	if (argc == 1)
		cmd = &fnc_init.cmd_args[FNC_VIEW_TIMELINE];
	else {
		rc = fcli_dispatch_commands(fnc_init.cmd_args, false);
		if (rc == FSL_RC_NOT_FOUND && argc == 2) {
			/*
			 * Check if user entered fnc path/in/repo; if valid path
			 * is found, assume fnc timeline path/in/repo was meant.
			 */
			rc = map_repo_path(&path);
			if (rc == FSL_RC_NOT_FOUND || !path) {
				rc = RC(rc,
				    "'%s' is not a valid command or path",
				    argv[1]);
				fnc_init.err = rc;
				usage();
				/* NOT REACHED */
			} else if (rc)
				goto end;
			cmd = &fnc_init.cmd_args[FNC_VIEW_TIMELINE];
			fnc_init.path = path;
			fcli_err_reset(); /* cmd_timeline::fcli_process_flags */
		} else if (rc)
			goto end;
	}

	if ((rc = fcli_has_unused_args(false))) {
		fnc_init.err = rc;
		usage();
		/* NOT REACHED */
	}



	if (!fsl_cx_db_repo(fcli_cx())) {
		rc = RC(FSL_RC_MISUSE, "%s", "repository database required");
		goto end;
	}

	if (cmd != NULL)
		rc = cmd->f(cmd);
end:
	fsl_free(path);
	endwin();
	if (rc) {
		if (rc == FCLI_RC_HELP)
			rc = 0;
		else if (rc == FSL_RC_BREAK) {
			const fsl_cx *const f = fcli_cx();
			const char *errstr;
			fsl_error_get(&f->error, &errstr, NULL);
			fsl_fprintf(stdout, "%s", errstr);
			fcli_err_reset();  /* For fcli_end_of_main() */
			rc = 0;







		}
	}
	putchar('\n');
	return fcli_end_of_main(rc);
}

static int







|
>
>
>
>
>
>
>
>
>
















|
<
|
>
|






>

>
>
|
|




<
<
<


|







|
|


<
<
<
|
<
|
|
|
<
<
|
|
<
<
<
<

>
>


|







|

<
<
|




|
|
>
>
>
>
>
>
>







1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440

1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459



1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473



1474

1475
1476
1477


1478
1479




1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494


1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
				    const char *, size_t);

int
main(int argc, const char **argv)
{
	fcli_command	*cmd = NULL;
	char		*path = NULL;
	int		 rc = FSL_RC_OK;

	/*
	 * XXX Guard against misuse. Will have to take another approach once
	 * the test harness is finished as we pipe input for our tests cases.
	 */
	if (!isatty(fileno(stdin))) {
		rc = RC(FSL_RC_MISUSE, "invalid input device");
		goto end;
	}

	if (!setlocale(LC_CTYPE, ""))
		fsl_fprintf(stderr, "[!] Warning: Can't set locale.\n");

	fnc_init.cmdarg = argv[1];	/* Which cmd to show usage if needed. */
#if DEBUG
	fcli.clientFlags.verbose = 2;	/* Verbose error reporting. */
#endif
	rc = fcli_setup_v2(argc, argv, fnc_init.cliflags_global,
	    &fnc_init.fnc_help);
	if (rc)
		goto end;

	if (fnc_init.vflag) {
		fnc_show_version();
		goto end;
	} else if (fnc_init.hflag) {

		rc = FCLI_RC_HELP;
		goto end;
	}
#ifdef __OpenBSD__
	/*
	 * See pledge(2). This is the most restrictive set we can operate under.
	 * Look for any adverse impact & revise when implementing new features.
	 * stdio (close, sigaction); rpath (chdir getcwd lstat); wpath (getcwd);
	 * cpath (symlink); flock (open); tty (TIOCGWINSZ); unveil (unveil).
	 * XXX 'fnc stash' needs more perms, call pledge(2) from cmd_stash().
	 */
	if (!(!fsl_strcmp(fnc_init.cmdarg, "stash") ||
	    fcli_cmd_aliascmp(&fnc_init.cmd_args[6], fnc_init.cmdarg)) &&
	    pledge("stdio rpath wpath cpath flock tty unveil", NULL) == -1) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS), "pledge");
		goto end;
	}
#endif
	rc = fcli_fingerprint_check(true);



	if (argc == 1)
		cmd = &fnc_init.cmd_args[FNC_VIEW_TIMELINE];
	else if (!rc) {
		rc = fcli_dispatch_commands(fnc_init.cmd_args, false);
		if (rc == FSL_RC_NOT_FOUND && argc == 2) {
			/*
			 * Check if user entered fnc path/in/repo; if valid path
			 * is found, assume fnc timeline path/in/repo was meant.
			 */
			rc = map_repo_path(&path);
			if (rc == FSL_RC_UNKNOWN_RESOURCE || !path) {
				rc = RC(FSL_RC_NOT_FOUND,
				    "'%s' is not a valid command or path",
				    argv[1]);



			} else if (!rc) {

				cmd = &fnc_init.cmd_args[FNC_VIEW_TIMELINE];
				fnc_init.path = path;
				fcli_err_reset(); /* for fcli_process_flags */


			}
		}




	}
	if (rc)
		goto end;

	if (!fsl_cx_db_repo(fcli_cx())) {
		rc = RC(FSL_RC_MISUSE, "repository database required");
		goto end;
	}

	if (cmd != NULL)
		rc = cmd->f(cmd);
end:
	fsl_free(path);
	!isendwin() ? endwin() : 0;  /* may have been called in cmd_stash() */
	if (rc) {


		if (rc == FSL_RC_BREAK) {
			const fsl_cx *const f = fcli_cx();
			const char *errstr;
			fsl_error_get(&f->error, &errstr, NULL);
			fsl_fprintf(stdout, "%s", errstr);
			RC_RESET(rc);  /* for fcli_end_of_main() */
		} else if (rc == FSL_RC_UNKNOWN_RESOURCE) {
			/* file not found by map_repo_path() */
			fcli_err_set(FSL_RC_NOT_FOUND, "%s",
			    fsl_buffer_cstr(&fcli_error()->msg));
		} else {
			fnc_init.err = rc == FCLI_RC_HELP ? FSL_RC_OK : rc;
			usage();
			/* NOT REACHED */
		}
	}
	putchar('\n');
	return fcli_end_of_main(rc);
}

static int
1360
1361
1362
1363
1364
1365
1366
1367

1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
		if (rc)
			goto end;
	}

	rc = init_curses();
	if (rc)
		goto end;
	rc = init_unveil(REPODB, CKOUTDIR, false);

	if (rc)
		goto end;

	rc = init_timeline_view(&v, 0, 0, rid, path, glob);
	if (!rc)
		rc = view_loop(v);
end:
	fsl_free(glob);
	fsl_free(path);
	return rc;
}

static int
init_timeline_view(struct fnc_view **view, int x, int y, fsl_id_t rid,
    const char *path, const char *glob)
{
	int rc = FSL_RC_OK;

	*view = view_open(0, 0, y, x, FNC_VIEW_TIMELINE);
	if (view == NULL)
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
	if (!rc)
		rc = open_timeline_view(*view, rid, path, glob);

	return rc;
}

/*







|
>




















|







1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
		if (rc)
			goto end;
	}

	rc = init_curses();
	if (rc)
		goto end;
	rc = init_unveil(((const char *[]){REPODB, CKOUTDIR, P_tmpdir,
	    gettzfile()}), ((const char *[]){"rw", "rwc", "rwc", "r"}), 4, true);
	if (rc)
		goto end;

	rc = init_timeline_view(&v, 0, 0, rid, path, glob);
	if (!rc)
		rc = view_loop(v);
end:
	fsl_free(glob);
	fsl_free(path);
	return rc;
}

static int
init_timeline_view(struct fnc_view **view, int x, int y, fsl_id_t rid,
    const char *path, const char *glob)
{
	int rc = FSL_RC_OK;

	*view = view_open(0, 0, y, x, FNC_VIEW_TIMELINE);
	if (view == NULL)
		rc = RC(FSL_RC_ERROR, "view_open");
	if (!rc)
		rc = open_timeline_view(*view, rid, path, glob);

	return rc;
}

/*
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476

1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518

	*requested_path = NULL;

	/* If no path argument is supplied, default to repository root. */
	if (!fcli_next_arg(false)) {
		*requested_path = fsl_strdup("/");
		if (*requested_path == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		return rc;
	}

	canonpath = fsl_strdup(fcli_next_arg(true));
	if (canonpath == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		goto end;
	}

	/*
	 * If no checkout (e.g., 'fnc timeline -R') copy the path verbatim to
	 * check its validity against a deck of F cards in open_timeline_view().
	 */
	ckoutdir0 = fsl_cx_ckout_dir_name(f, &len);
	if (!ckoutdir0) {
		path = fsl_strdup(canonpath);
		goto end;
	}

	path = realpath(canonpath, NULL);
	if (path == NULL && (errno == ENOENT || errno == ENOTDIR)) {
		/* Path is not on disk, assume it is relative to repo root. */
		rc = fsl_file_canonical_name2(ckoutdir0, canonpath, &buf, NULL);
		if (rc) {
			rc = RC(rc, "%s", "fsl_file_canonical_name2");
			goto end;
		}
		fsl_free(path);
		path = realpath(fsl_buffer_cstr(&buf), NULL);
		if (path) {
			/* Confirmed path is relative to repository root. */
			fsl_free(path);
			path = fsl_strdup(canonpath);
			if (path == NULL)
				rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		} else {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_NOT_FOUND),
			    "'%s' not found in tree", canonpath);
			*requested_path = fsl_strdup(canonpath);
		}
		goto end;
	}
	fsl_free(path);
	/*
	 * Use the cwd as the virtual root to canonicalise the supplied path if
	 * it is either: (a) relative; or (b) the root of the current checkout.
	 * Otherwise, use the root of the current checkout.
	 */
	rc = fsl_cx_getcwd(f, &buf);
	if (rc)
		goto end;
	ckoutdir = fsl_mprintf("%.*s", len - 1, ckoutdir0);
	root = fsl_strcmp(ckoutdir, fsl_buffer_cstr(&buf)) == 0;
	fsl_buffer_reuse(&buf);
	rc = fsl_ckout_filename_check(f, (canonpath[0] == '.' || !root) ?
	    true : false, canonpath, &buf);
	if (rc)
		goto end;

	fsl_free(canonpath);
	canonpath = fsl_strdup(fsl_buffer_str(&buf));

	if (canonpath[0] == '\0') {
		path = fsl_strdup(canonpath);
		if (path == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	} else {
		fsl_buffer_reuse(&buf);
		rc = fsl_file_canonical_name2(f->ckout.dir, canonpath, &buf,
		    false);
		if (rc)
			goto end;
		path = fsl_strdup(fsl_buffer_str(&buf));
		if (path == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		if (access(path, F_OK) != 0) {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
			    "path does not exist or inaccessible [%s]", path);
			goto end;
		}
		/*
		 * Now we have an absolute path, check again if it's the ckout
		 * dir; if so, clear it to signal an open_timeline_view() check.
		 */
		len = fsl_strlen(path);
		if (!fsl_strcmp(path, f->ckout.dir)) {
			fsl_free(path);
			path = fsl_strdup("");
			if (path == NULL) {
				rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
				goto end;
			}
		} else if (len > f->ckout.dirLen && path_is_child(path,
		    f->ckout.dir, f->ckout.dirLen)) {
			char *child;
			/*
			 * Matched on-disk path within the repository; strip







|





|


















|









|
|
|

<
<


<















>






|










|
















|







1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644


1645
1646

1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704

	*requested_path = NULL;

	/* If no path argument is supplied, default to repository root. */
	if (!fcli_next_arg(false)) {
		*requested_path = fsl_strdup("/");
		if (*requested_path == NULL)
			return RC(FSL_RC_ERROR, "fsl_strdup");
		return rc;
	}

	canonpath = fsl_strdup(fcli_next_arg(true));
	if (canonpath == NULL) {
		rc = RC(FSL_RC_ERROR, "fsl_strdup");
		goto end;
	}

	/*
	 * If no checkout (e.g., 'fnc timeline -R') copy the path verbatim to
	 * check its validity against a deck of F cards in open_timeline_view().
	 */
	ckoutdir0 = fsl_cx_ckout_dir_name(f, &len);
	if (!ckoutdir0) {
		path = fsl_strdup(canonpath);
		goto end;
	}

	path = realpath(canonpath, NULL);
	if (path == NULL && (errno == ENOENT || errno == ENOTDIR)) {
		/* Path is not on disk, assume it is relative to repo root. */
		rc = fsl_file_canonical_name2(ckoutdir0, canonpath, &buf, NULL);
		if (rc) {
			rc = RC(rc, "fsl_file_canonical_name2");
			goto end;
		}
		fsl_free(path);
		path = realpath(fsl_buffer_cstr(&buf), NULL);
		if (path) {
			/* Confirmed path is relative to repository root. */
			fsl_free(path);
			path = fsl_strdup(canonpath);
			if (path == NULL)
				rc = RC(FSL_RC_ERROR, "fsl_strdup");
		} else
			rc = RC(FSL_RC_UNKNOWN_RESOURCE,
			    "'%s' not found in tree", canonpath);


		goto end;
	}

	/*
	 * Use the cwd as the virtual root to canonicalise the supplied path if
	 * it is either: (a) relative; or (b) the root of the current checkout.
	 * Otherwise, use the root of the current checkout.
	 */
	rc = fsl_cx_getcwd(f, &buf);
	if (rc)
		goto end;
	ckoutdir = fsl_mprintf("%.*s", len - 1, ckoutdir0);
	root = fsl_strcmp(ckoutdir, fsl_buffer_cstr(&buf)) == 0;
	fsl_buffer_reuse(&buf);
	rc = fsl_ckout_filename_check(f, (canonpath[0] == '.' || !root) ?
	    true : false, canonpath, &buf);
	if (rc)
		goto end;
	fsl_free(path);
	fsl_free(canonpath);
	canonpath = fsl_strdup(fsl_buffer_str(&buf));

	if (canonpath[0] == '\0') {
		path = fsl_strdup(canonpath);
		if (path == NULL) {
			rc = RC(FSL_RC_ERROR, "fsl_strdup");
			goto end;
		}
	} else {
		fsl_buffer_reuse(&buf);
		rc = fsl_file_canonical_name2(f->ckout.dir, canonpath, &buf,
		    false);
		if (rc)
			goto end;
		path = fsl_strdup(fsl_buffer_str(&buf));
		if (path == NULL) {
			rc = RC(FSL_RC_ERROR, "fsl_strdup");
			goto end;
		}
		if (access(path, F_OK) != 0) {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
			    "path does not exist or inaccessible [%s]", path);
			goto end;
		}
		/*
		 * Now we have an absolute path, check again if it's the ckout
		 * dir; if so, clear it to signal an open_timeline_view() check.
		 */
		len = fsl_strlen(path);
		if (!fsl_strcmp(path, f->ckout.dir)) {
			fsl_free(path);
			path = fsl_strdup("");
			if (path == NULL) {
				rc = RC(FSL_RC_ERROR, "fsl_strdup");
				goto end;
			}
		} else if (len > f->ckout.dirLen && path_is_child(path,
		    f->ckout.dir, f->ckout.dirLen)) {
			char *child;
			/*
			 * Matched on-disk path within the repository; strip
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546

1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561



1562
1563
1564
1565
1566
1567
1568
	}

	/* Trim trailing slash if it exists. */
	if (path[fsl_strlen(path) - 1] == '/')
		path[fsl_strlen(path) - 1] = '\0';

end:
	fsl_buffer_clear(&buf);
	fsl_free(canonpath);
	fsl_free(ckoutdir);
	if (rc)

		fsl_free(path);
	else {
		/* Make path absolute from repository root. */
		if (path[0] != '/' && (path[0] != '.' && path[1] != '/')) {
			char *abspath;
			if ((abspath = fsl_mprintf("/%s", path)) == NULL) {
				rc = RC(FSL_RC_ERROR, "%s", "fsl_mprintf");
				goto end;
			}
			fsl_free(path);
			path = abspath;
		}

		*requested_path = path;
	}



	return rc;
}

static bool
path_is_child(const char *child, const char *parent, size_t parentlen)
{
	if (parentlen == 0 || fnc_path_is_root_dir(parent))







<
<
<
|
>

|




|
<







>
>
>







1722
1723
1724
1725
1726
1727
1728



1729
1730
1731
1732
1733
1734
1735
1736
1737

1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
	}

	/* Trim trailing slash if it exists. */
	if (path[fsl_strlen(path) - 1] == '/')
		path[fsl_strlen(path) - 1] = '\0';

end:



	if (rc) {
		*requested_path = fsl_strdup(canonpath);
		fsl_free(path);
	} else {
		/* Make path absolute from repository root. */
		if (path[0] != '/' && (path[0] != '.' && path[1] != '/')) {
			char *abspath;
			if ((abspath = fsl_mprintf("/%s", path)) == NULL) {
				rc = RC(FSL_RC_ERROR, "fsl_mprintf");

			}
			fsl_free(path);
			path = abspath;
		}

		*requested_path = path;
	}
	fsl_buffer_clear(&buf);
	fsl_free(canonpath);
	fsl_free(ckoutdir);
	return rc;
}

static bool
path_is_child(const char *child, const char *parent, size_t parentlen)
{
	if (parentlen == 0 || fnc_path_is_root_dir(parent))
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
	    abspath[parentlen - 1 /* Trailing slash */] != '/')
		return RC(FSL_RC_TYPE, "invalid path [%s]", abspath);
	while (abspath[parentlen] == '/')
		++abspath;
	bufsz = len - parentlen + 1;
	*child = fsl_malloc(bufsz);
	if (*child == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	if (strlcpy(*child, abspath + parentlen, bufsz) >= bufsz) {
		rc = RC(FSL_RC_RANGE, "%s", "strlcpy");
		fsl_free(*child);
		*child = NULL;
	}
	return rc;
}

#if 0







|

|







1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
	    abspath[parentlen - 1 /* Trailing slash */] != '/')
		return RC(FSL_RC_TYPE, "invalid path [%s]", abspath);
	while (abspath[parentlen] == '/')
		++abspath;
	bufsz = len - parentlen + 1;
	*child = fsl_malloc(bufsz);
	if (*child == NULL)
		return RC(FSL_RC_ERROR, "fsl_malloc");
	if (strlcpy(*child, abspath + parentlen, bufsz) >= bufsz) {
		rc = RC(FSL_RC_RANGE, "strlcpy");
		fsl_free(*child);
		*child = NULL;
	}
	return rc;
}

#if 0
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677

static int
fnc_set_signals(void)
{
	if (sigaction(SIGPIPE, &(struct sigaction){{sigpipe_handler}}, NULL)
	    == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "sigaction(SIGPIPE)");
	if (sigaction(SIGWINCH, &(struct sigaction){{sigwinch_handler}}, NULL)
	    == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "sigaction(SIGWINCH)");
	if (sigaction(SIGCONT, &(struct sigaction){{sigcont_handler}}, NULL)
	    == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "sigaction(SIGCONT)");

	return FSL_RC_OK;
}

static struct fnc_view *
view_open(int nlines, int ncols, int start_ln, int start_col,
    enum fnc_view_id vid)







|



|



|







1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863

static int
fnc_set_signals(void)
{
	if (sigaction(SIGPIPE, &(struct sigaction){{sigpipe_handler}}, NULL)
	    == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "sigaction(SIGPIPE)");
	if (sigaction(SIGWINCH, &(struct sigaction){{sigwinch_handler}}, NULL)
	    == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "sigaction(SIGWINCH)");
	if (sigaction(SIGCONT, &(struct sigaction){{sigcont_handler}}, NULL)
	    == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "sigaction(SIGCONT)");

	return FSL_RC_OK;
}

static struct fnc_view *
view_open(int nlines, int ncols, int start_ln, int start_col,
    enum fnc_view_id vid)
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
	fsl_id_t			 idtag = 0;
	int				 idx, rc = FSL_RC_OK;

	if (path != s->path) {
		fsl_free(s->path);
		s->path = fsl_strdup(path);
		if (s->path == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	}

	/*
	 * TODO: See about opening this API.
	 * If a path has been supplied, create a table of all path's
	 * ancestors and add "AND blob.rid IN fsl_computed_ancestors" to query.
	 */
	/* if (path[1]) { */
	/*	rc = fsl_compute_ancestors(db, rid, 0, 0); */
	/*	if (rc) */
	/*		return RC(FSL_RC_DB, "%s", "fsl_compute_ancestors"); */
	/* } */
	s->thread_cx.q = NULL;
	/* s->selected = 0; */	/* Unnecessary? */

	TAILQ_INIT(&s->commits.head);
	s->commits.ncommits = 0;








|










|







1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
	fsl_id_t			 idtag = 0;
	int				 idx, rc = FSL_RC_OK;

	if (path != s->path) {
		fsl_free(s->path);
		s->path = fsl_strdup(path);
		if (s->path == NULL)
			return RC(FSL_RC_ERROR, "fsl_strdup");
	}

	/*
	 * TODO: See about opening this API.
	 * If a path has been supplied, create a table of all path's
	 * ancestors and add "AND blob.rid IN fsl_computed_ancestors" to query.
	 */
	/* if (path[1]) { */
	/*	rc = fsl_compute_ancestors(db, rid, 0, 0); */
	/*	if (rc) */
	/*		return RC(FSL_RC_DB, "fsl_compute_ancestors"); */
	/* } */
	s->thread_cx.q = NULL;
	/* s->selected = 0; */	/* Unnecessary? */

	TAILQ_INIT(&s->commits.head);
	s->commits.ncommits = 0;

1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
		fsl_free(id);
		if (!ispath)
			return RC(FSL_RC_NOT_FOUND, "'%s' invalid path in [%s]",
			    path + 1, fnc_init.sym ? fnc_init.sym : "tip");
	}

	if ((rc = pthread_cond_init(&s->thread_cx.commit_consumer, NULL))) {
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_cond_init");
		goto end;
	}
	if ((rc = pthread_cond_init(&s->thread_cx.commit_producer, NULL))) {
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_cond_init");
		goto end;
	}

	fsl_buffer_appendf(&sql, "SELECT "
	    /* 0 */"uuid, "
	    /* 1 */"datetime(event.mtime%s), "
	    /* 2 */"coalesce(euser, user), "







|
<



|
<







1962
1963
1964
1965
1966
1967
1968
1969

1970
1971
1972
1973

1974
1975
1976
1977
1978
1979
1980
		fsl_free(id);
		if (!ispath)
			return RC(FSL_RC_NOT_FOUND, "'%s' invalid path in [%s]",
			    path + 1, fnc_init.sym ? fnc_init.sym : "tip");
	}

	if ((rc = pthread_cond_init(&s->thread_cx.commit_consumer, NULL))) {
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS), "pthread_cond_init");

		goto end;
	}
	if ((rc = pthread_cond_init(&s->thread_cx.commit_producer, NULL))) {
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS), "pthread_cond_init");

		goto end;
	}

	fsl_buffer_appendf(&sql, "SELECT "
	    /* 0 */"uuid, "
	    /* 1 */"datetime(event.mtime%s), "
	    /* 2 */"coalesce(euser, user), "
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
	view->close = close_timeline_view;
	view->grep_init = tl_grep_init;
	view->grep = tl_search_next;

	s->thread_cx.q = fsl_stmt_malloc();
	rc = fsl_db_prepare(db, s->thread_cx.q, "%b", &sql);
	if (rc) {
		rc = RC(rc, "%s", "fsl_db_prepare");
		goto end;
	}
	rc = fsl_stmt_step(s->thread_cx.q);
	switch (rc) {
	case FSL_RC_STEP_ROW:
		rc = 0;
		break;
	case FSL_RC_STEP_ERROR:
		rc = RC(rc, "%s", "fsl_stmt_step");
		goto end;
	case FSL_RC_STEP_DONE:
		rc = RC(FSL_RC_BREAK, "%s", "no matching records");
		goto end;
	}

	s->colour = !fnc_init.nocolour && has_colors();
	s->showmeta = true;
	s->thread_cx.rc = 0;
	s->thread_cx.db = db;







|








|


|







2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
	view->close = close_timeline_view;
	view->grep_init = tl_grep_init;
	view->grep = tl_search_next;

	s->thread_cx.q = fsl_stmt_malloc();
	rc = fsl_db_prepare(db, s->thread_cx.q, "%b", &sql);
	if (rc) {
		rc = RC(rc, "fsl_db_prepare");
		goto end;
	}
	rc = fsl_stmt_step(s->thread_cx.q);
	switch (rc) {
	case FSL_RC_STEP_ROW:
		rc = 0;
		break;
	case FSL_RC_STEP_ERROR:
		rc = RC(rc, "fsl_stmt_step");
		goto end;
	case FSL_RC_STEP_DONE:
		rc = RC(FSL_RC_BREAK, "no matching records");
		goto end;
	}

	s->colour = !fnc_init.nocolour && has_colors();
	s->showmeta = true;
	s->thread_cx.rc = 0;
	s->thread_cx.db = db;
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
{
	struct view_tailhead	 views;
	struct fnc_view		*new_view;
	int			 done = 0, err = 0, rc = 0;

	if ((rc = pthread_mutex_lock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	TAILQ_INIT(&views);
	TAILQ_INSERT_HEAD(&views, view, entries);

	view->active = true;
	rc = view->show(view);
	if (rc)







|







2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
{
	struct view_tailhead	 views;
	struct fnc_view		*new_view;
	int			 done = 0, err = 0, rc = 0;

	if ((rc = pthread_mutex_lock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "pthread_mutex_lock");

	TAILQ_INIT(&views);
	TAILQ_INSERT_HEAD(&views, view, entries);

	view->active = true;
	rc = view->show(view);
	if (rc)
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
				prev = view->parent;

			if (view->parent) {
				view->parent->child = NULL;
				view->parent->focus_child = false;
				/* Restore fullscreen line height. */
				view->parent->nlines = view->parent->lines;
				rc = view_resize(view->parent, VIEW_SPLIT_NONE);
				if (rc)
					goto end;
			} else
				TAILQ_REMOVE(&views, view, entries);

			rc = view_close(view);
			if (rc)







|







2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
				prev = view->parent;

			if (view->parent) {
				view->parent->child = NULL;
				view->parent->focus_child = false;
				/* Restore fullscreen line height. */
				view->parent->nlines = view->parent->lines;
				rc = view_resize(view->parent, false);
				if (rc)
					goto end;
			} else
				TAILQ_REMOVE(&views, view, entries);

			rc = view_close(view);
			if (rc)
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
		view = TAILQ_FIRST(&views);
		TAILQ_REMOVE(&views, view, entries);
		view_close(view);
	}

	if ((err = pthread_mutex_unlock(&fnc_mutex)) && !rc)
		rc = RC(fsl_errno_to_rc(err, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");

	return rc;
}

static int
show_timeline_view(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	int				 rc = 0;

	if (!s->thread_id) {
		rc = pthread_create(&s->thread_id, NULL, tl_producer_thread,
		    &s->thread_cx);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_create");
		if (s->thread_cx.ncommits_needed > 0) {
			rc = signal_tl_thread(view, 1);
			if (rc)
				return rc;
		}
	}








|















|







2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
		view = TAILQ_FIRST(&views);
		TAILQ_REMOVE(&views, view, entries);
		view_close(view);
	}

	if ((err = pthread_mutex_unlock(&fnc_mutex)) && !rc)
		rc = RC(fsl_errno_to_rc(err, FSL_RC_ACCESS),
		    "pthread_mutex_unlock");

	return rc;
}

static int
show_timeline_view(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	int				 rc = 0;

	if (!s->thread_id) {
		rc = pthread_create(&s->thread_id, NULL, tl_producer_thread,
		    &s->thread_cx);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_create");
		if (s->thread_cx.ncommits_needed > 0) {
			rc = signal_tl_thread(view, 1);
			if (rc)
				return rc;
		}
	}

2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
			else if (cx->ncommits_needed > 0)
				cx->ncommits_needed--;
			break;
		}

		if ((rc = pthread_mutex_lock(&fnc_mutex))) {
			rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
			break;
		} else if (*cx->first_commit_onscreen == NULL) {
			*cx->first_commit_onscreen =
			    TAILQ_FIRST(&cx->commits->head);
			*cx->selected_entry = *cx->first_commit_onscreen;
		} else if (*cx->quit)
			done = true;

		if ((rc = pthread_cond_signal(&cx->commit_producer))) {
			rc = RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "%s", "pthread_cond_signal");
			pthread_mutex_unlock(&fnc_mutex);
			break;
		}

		if (done)
			cx->ncommits_needed = 0;
		else if (cx->ncommits_needed == 0) {
			if ((rc = pthread_cond_wait(&cx->commit_consumer,
			    &fnc_mutex)))
				rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
				    "%s", "pthread_cond_wait");
			if (*cx->quit)
				done = true;
		}

		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
	}

	cx->eotl = true;
	return (void *)(intptr_t)rc;
}

static int
block_main_thread_signals(void)
{
	sigset_t set;

	if (sigemptyset(&set) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "sigemptyset");

	/* Bespoke signal handlers for SIGWINCH and SIGCONT. */
	if (sigaddset(&set, SIGWINCH) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "sigaddset");
	if (sigaddset(&set, SIGCONT) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "sigaddset");

	/* ncurses handles SIGTSTP. */
	if (sigaddset(&set, SIGTSTP) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "sigaddset");

	if (pthread_sigmask(SIG_BLOCK, &set, NULL))
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "%s",
		    "pthread_sigmask");

	return FSL_RC_OK;
}

static int
build_commits(struct fnc_tl_thread_cx *cx)







|










|










|






|












|
<



|
<

|
<



|
<


|







2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396

2397
2398
2399
2400

2401
2402

2403
2404
2405
2406

2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
			else if (cx->ncommits_needed > 0)
				cx->ncommits_needed--;
			break;
		}

		if ((rc = pthread_mutex_lock(&fnc_mutex))) {
			rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_mutex_lock");
			break;
		} else if (*cx->first_commit_onscreen == NULL) {
			*cx->first_commit_onscreen =
			    TAILQ_FIRST(&cx->commits->head);
			*cx->selected_entry = *cx->first_commit_onscreen;
		} else if (*cx->quit)
			done = true;

		if ((rc = pthread_cond_signal(&cx->commit_producer))) {
			rc = RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "pthread_cond_signal");
			pthread_mutex_unlock(&fnc_mutex);
			break;
		}

		if (done)
			cx->ncommits_needed = 0;
		else if (cx->ncommits_needed == 0) {
			if ((rc = pthread_cond_wait(&cx->commit_consumer,
			    &fnc_mutex)))
				rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
				    "pthread_cond_wait");
			if (*cx->quit)
				done = true;
		}

		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_mutex_unlock");
	}

	cx->eotl = true;
	return (void *)(intptr_t)rc;
}

static int
block_main_thread_signals(void)
{
	sigset_t set;

	if (sigemptyset(&set) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "sigemptyset");


	/* Bespoke signal handlers for SIGWINCH and SIGCONT. */
	if (sigaddset(&set, SIGWINCH) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "sigaddset");

	if (sigaddset(&set, SIGCONT) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "sigaddset");


	/* ncurses handles SIGTSTP. */
	if (sigaddset(&set, SIGTSTP) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE), "sigaddset");


	if (pthread_sigmask(SIG_BLOCK, &set, NULL))
		return RC(fsl_errno_to_rc(errno, FSL_RC_MISUSE),
		    "pthread_sigmask");

	return FSL_RC_OK;
}

static int
build_commits(struct fnc_tl_thread_cx *cx)
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
		 * of the APIs down the fsl_stmt_step() call stack fails;
		 * irrespective of whether fsl_db_prepare_cached() was used.
		 */
		fsl_size_t loaded = cx->commits->ncommits + 1;
		cx->reset = false;
		rc = fsl_stmt_reset(cx->q);
		if (rc)
			return RC(rc, "%s", "fsl_stmt_reset");
		while (loaded--)
			if ((rc = fsl_stmt_step(cx->q)) != FSL_RC_STEP_ROW)
				return RC(rc, "%s", "fsl_stmt_step");
	}
	/*
	 * Step through the given SQL query, passing each row to the commit
	 * builder to build commits for the timeline.
	 */
	do {
		struct fnc_commit_artifact	*commit = NULL;
		struct commit_entry		*dup_entry, *entry;

		rc = commit_builder(&commit, 0, cx->q);
		if (rc)
			return RC(rc, "%s", "commit_builder");
		/*
		 * TODO: Find out why, without this, fnc reads and displays
		 * the first (i.e., latest) commit twice. This hack checks to
		 * see if the current row returned a UUID matching the last
		 * commit added to the list to avoid adding a duplicate entry.
		 */
		dup_entry = TAILQ_FIRST(&cx->commits->head);
		if (cx->commits->ncommits == 1 &&
		    !fsl_strcmp(dup_entry->commit->uuid, commit->uuid)) {
			fnc_commit_artifact_close(commit);
			cx->ncommits_needed++;
			continue;
		}

		entry = fsl_malloc(sizeof(*entry));
		if (entry == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_malloc");

		entry->commit = commit;

		rc = pthread_mutex_lock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");

		entry->idx = cx->commits->ncommits;
		TAILQ_INSERT_TAIL(&cx->commits->head, entry, entries);
		cx->commits->ncommits++;

		if (!cx->endjmp && *cx->searching == SEARCH_FORWARD &&
		    *cx->search_status == SEARCH_WAITING) {
			if (find_commit_match(commit, cx->regex))
				*cx->search_status = SEARCH_CONTINUE;
		}

		rc = pthread_mutex_unlock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");

	} while ((rc = fsl_stmt_step(cx->q)) == FSL_RC_STEP_ROW
	    && *cx->searching == SEARCH_FORWARD
	    && *cx->search_status == SEARCH_WAITING);

	return rc;
}







|


|











|
















|






|






|


<




|







2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479

2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
		 * of the APIs down the fsl_stmt_step() call stack fails;
		 * irrespective of whether fsl_db_prepare_cached() was used.
		 */
		fsl_size_t loaded = cx->commits->ncommits + 1;
		cx->reset = false;
		rc = fsl_stmt_reset(cx->q);
		if (rc)
			return RC(rc, "fsl_stmt_reset");
		while (loaded--)
			if ((rc = fsl_stmt_step(cx->q)) != FSL_RC_STEP_ROW)
				return RC(rc, "fsl_stmt_step");
	}
	/*
	 * Step through the given SQL query, passing each row to the commit
	 * builder to build commits for the timeline.
	 */
	do {
		struct fnc_commit_artifact	*commit = NULL;
		struct commit_entry		*dup_entry, *entry;

		rc = commit_builder(&commit, 0, cx->q);
		if (rc)
			return RC(rc, "commit_builder");
		/*
		 * TODO: Find out why, without this, fnc reads and displays
		 * the first (i.e., latest) commit twice. This hack checks to
		 * see if the current row returned a UUID matching the last
		 * commit added to the list to avoid adding a duplicate entry.
		 */
		dup_entry = TAILQ_FIRST(&cx->commits->head);
		if (cx->commits->ncommits == 1 &&
		    !fsl_strcmp(dup_entry->commit->uuid, commit->uuid)) {
			fnc_commit_artifact_close(commit);
			cx->ncommits_needed++;
			continue;
		}

		entry = fsl_malloc(sizeof(*entry));
		if (entry == NULL)
			return RC(FSL_RC_ERROR, "fsl_malloc");

		entry->commit = commit;

		rc = pthread_mutex_lock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_mutex_lock");

		entry->idx = cx->commits->ncommits;
		TAILQ_INSERT_TAIL(&cx->commits->head, entry, entries);
		cx->commits->ncommits++;

		if (!cx->endjmp && *cx->searching == SEARCH_FORWARD &&
		    *cx->search_status == SEARCH_WAITING)
			if (find_commit_match(commit, cx->regex))
				*cx->search_status = SEARCH_CONTINUE;


		rc = pthread_mutex_unlock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_mutex_unlock");

	} while ((rc = fsl_stmt_step(cx->q)) == FSL_RC_STEP_ROW
	    && *cx->searching == SEARCH_FORWARD
	    && *cx->search_status == SEARCH_WAITING);

	return rc;
}
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
		    "FROM tag, tagxref WHERE tagname GLOB 'sym-*' "
		    "AND tag.tagid=tagxref.tagid AND tagxref.rid=blob.rid "
		    "AND tagxref.tagtype > 0) as tags, "
		    /*6*/"coalesce(ecomment, comment) AS comment "
		    "FROM event JOIN blob WHERE blob.rid=%d AND event.objid=%d",
		    fnc_init.utc ? "" : ", 'localtime'", rid, rid);
		if (rc)
			return RC(FSL_RC_DB, "%s", "fsl_db_prepare");
		fsl_stmt_step(q);
	}

	type = fsl_stmt_g_text(q, 4, NULL);
	comment = fsl_stmt_g_text(q, 6, NULL);
	prefix = NULL;








|







2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
		    "FROM tag, tagxref WHERE tagname GLOB 'sym-*' "
		    "AND tag.tagid=tagxref.tagid AND tagxref.rid=blob.rid "
		    "AND tagxref.tagtype > 0) as tags, "
		    /*6*/"coalesce(ecomment, comment) AS comment "
		    "FROM event JOIN blob WHERE blob.rid=%d AND event.objid=%d",
		    fnc_init.utc ? "" : ", 'localtime'", rid, rid);
		if (rc)
			return RC(FSL_RC_DB, "fsl_db_prepare");
		fsl_stmt_step(q);
	}

	type = fsl_stmt_g_text(q, 4, NULL);
	comment = fsl_stmt_g_text(q, 6, NULL);
	prefix = NULL;

2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
	case 'f':
		type = "forum";
		break;
	};
	if (!rc && comment)
		rc = fsl_buffer_append(&buf, comment, -1);
	if (rc) {
		rc = RC(rc, "%s", "fsl_buffer_append");
		goto end;
	}

	commit = calloc(1, sizeof(*commit));
	if (commit == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");
		goto end;
	}

	if (!rid && (rc = fsl_stmt_get_id(q, 3, &rid))) {
		rc = RC(rc, "%s", "fsl_stmt_get_id");
		goto end;
	}
	/* Is there a more efficient way to get the parent? */
	commit->puuid = fsl_db_g_text(db, NULL,
	    "SELECT uuid FROM plink, blob WHERE plink.cid=%d "
	    "AND blob.rid=plink.pid AND plink.isprim", rid);
	commit->prid = fsl_uuid_to_rid(f, commit->puuid);







|





|




|







2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
	case 'f':
		type = "forum";
		break;
	};
	if (!rc && comment)
		rc = fsl_buffer_append(&buf, comment, -1);
	if (rc) {
		rc = RC(rc, "fsl_buffer_append");
		goto end;
	}

	commit = calloc(1, sizeof(*commit));
	if (commit == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "calloc");
		goto end;
	}

	if (!rid && (rc = fsl_stmt_get_id(q, 3, &rid))) {
		rc = RC(rc, "fsl_stmt_get_id");
		goto end;
	}
	/* Is there a more efficient way to get the parent? */
	commit->puuid = fsl_db_g_text(db, NULL,
	    "SELECT uuid FROM plink, blob WHERE plink.cid=%d "
	    "AND blob.rid=plink.pid AND plink.isprim", rid);
	commit->prid = fsl_uuid_to_rid(f, commit->puuid);
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
		if (view->mode == VIEW_SPLIT_HRZN)
			cx->reset = true;

		/* Wake timeline thread. */
		rc = pthread_cond_signal(&cx->commit_consumer);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "%s", "pthread_cond_signal");

		/*
		 * Mutex will be released while view_loop().view_input() waits
		 * in wgetch(), at which point the timeline thread will run.
		 */
		if (!wait)
			break;

		/* Show status update in timeline view. */
		show_timeline_view(view);
		update_panels();
		doupdate();

		/* Wait while the next commit is being loaded. */
		rc = pthread_cond_wait(&cx->commit_producer, &fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_cond_wait");

		/* Show status update in timeline view. */
		show_timeline_view(view);
		update_panels();
		doupdate();
	}








|

















|







2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
		if (view->mode == VIEW_SPLIT_HRZN)
			cx->reset = true;

		/* Wake timeline thread. */
		rc = pthread_cond_signal(&cx->commit_consumer);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "pthread_cond_signal");

		/*
		 * Mutex will be released while view_loop().view_input() waits
		 * in wgetch(), at which point the timeline thread will run.
		 */
		if (!wait)
			break;

		/* Show status update in timeline view. */
		show_timeline_view(view);
		update_panels();
		doupdate();

		/* Wait while the next commit is being loaded. */
		rc = pthread_cond_wait(&cx->commit_producer, &fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_cond_wait");

		/* Show status update in timeline view. */
		show_timeline_view(view);
		update_panels();
		doupdate();
	}

2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513

	if (tcx->ncommits_needed > 0 && !tcx->eotl) {
		if ((idxstr = fsl_mprintf(" [%d/%d] %s",
		    entry ? entry->idx + 1 : 0, s->commits.ncommits,
		    (view->searching && !view->search_status) ?
		    "searching..." : view->search_status == SEARCH_ABORTED ?
		    "aborted" : "loading...")) == NULL) {
			rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
			goto end;
		}
	} else {
		if (view->searching) {
			switch (view->search_status) {
			case SEARCH_COMPLETE:
				search_str = "no more matches";







|







2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692

	if (tcx->ncommits_needed > 0 && !tcx->eotl) {
		if ((idxstr = fsl_mprintf(" [%d/%d] %s",
		    entry ? entry->idx + 1 : 0, s->commits.ncommits,
		    (view->searching && !view->search_status) ?
		    "searching..." : view->search_status == SEARCH_ABORTED ?
		    "aborted" : "loading...")) == NULL) {
			rc = RC(FSL_RC_RANGE, "fsl_mprintf");
			goto end;
		}
	} else {
		if (view->searching) {
			switch (view->search_status) {
			case SEARCH_COMPLETE:
				search_str = "no more matches";
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
		}

		if ((idxstr = fsl_mprintf("%s [%d/%d] %s",
		    !fsl_strcmp(uuid, s->curr_ckout_uuid) ? " [current]" : "",
		    entry ? entry->idx + 1 : 0, s->commits.ncommits,
		    search_str ? search_str : (branch ? branch : "")))
		    == NULL) {
			rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
			goto end;
		}
	}
	/*
	 * Compute cols needed to fit all components of the headline to truncate
	 * the hash component if needed. wiki, tag, and ticket artifacts don't
	 * have a branch component, checkins and some technotes do, so add a col







|







2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
		}

		if ((idxstr = fsl_mprintf("%s [%d/%d] %s",
		    !fsl_strcmp(uuid, s->curr_ckout_uuid) ? " [current]" : "",
		    entry ? entry->idx + 1 : 0, s->commits.ncommits,
		    search_str ? search_str : (branch ? branch : "")))
		    == NULL) {
			rc = RC(FSL_RC_RANGE, "fsl_mprintf");
			goto end;
		}
	}
	/*
	 * Compute cols needed to fit all components of the headline to truncate
	 * the hash component if needed. wiki, tag, and ticket artifacts don't
	 * have a branch component, checkins and some technotes do, so add a col
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
	if (s->path[1]) {
		if ((headln = fsl_mprintf("%s%c%.*s %s%s", type ? type : "",
		    type ? ' ' : SPINNER[tcx->spin_idx], view->ncols <
		    ncols_needed ? view->ncols - (ncols_needed -
		    FSL_STRLEN_K256) : FSL_STRLEN_K256, uuid ? uuid :
		    "........................................",
		    s->path, idxstr)) == NULL) {
			rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
			headln = NULL;
			goto end;
		}
	} else if ((headln = fsl_mprintf("%s%c%.*s%s", type ? type : "", type ?
	    ' ' : SPINNER[tcx->spin_idx], view->ncols < ncols_needed ?
	    view->ncols - (ncols_needed - FSL_STRLEN_K256) : FSL_STRLEN_K256,
	    uuid ? uuid : "........................................", idxstr))
	    == NULL) {
		rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		headln = NULL;
		goto end;
	}
	if (SPINNER[++tcx->spin_idx] == '\0')
		tcx->spin_idx = 0;
	rc = formatln(&wline, &wlen, headln, view->ncols, 0, false);
	if (rc)







|








|







2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
	if (s->path[1]) {
		if ((headln = fsl_mprintf("%s%c%.*s %s%s", type ? type : "",
		    type ? ' ' : SPINNER[tcx->spin_idx], view->ncols <
		    ncols_needed ? view->ncols - (ncols_needed -
		    FSL_STRLEN_K256) : FSL_STRLEN_K256, uuid ? uuid :
		    "........................................",
		    s->path, idxstr)) == NULL) {
			rc = RC(FSL_RC_RANGE, "fsl_mprintf");
			headln = NULL;
			goto end;
		}
	} else if ((headln = fsl_mprintf("%s%c%.*s%s", type ? type : "", type ?
	    ' ' : SPINNER[tcx->spin_idx], view->ncols < ncols_needed ?
	    view->ncols - (ncols_needed - FSL_STRLEN_K256) : FSL_STRLEN_K256,
	    uuid ? uuid : "........................................", idxstr))
	    == NULL) {
		rc = RC(FSL_RC_RANGE, "fsl_mprintf");
		headln = NULL;
		goto end;
	}
	if (SPINNER[++tcx->spin_idx] == '\0')
		tcx->spin_idx = 0;
	rc = formatln(&wline, &wlen, headln, view->ncols, 0, false);
	if (rc)
2584
2585
2586
2587
2588
2589
2590

2591


2592

2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608





2609
2610
2611
2612
2613
2614
2615
		++wlen;
	}
	wattroff(view->window, rx);
	fsl_free(wline);
	if (view->nlines <= 1)
		goto end;


	/* Parse commits to be written on screen for the longest username. */


	entry = s->first_commit_onscreen;

	while (entry) {
		wchar_t		*wstr;
		char		*user;
		int		 wusrlen;
		if (ncommits >= view->nlines - 1)
			break;
		user = fsl_strdup(entry->commit->user);
		if (user == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		if (strpbrk(user, "<@>") != NULL)
			parse_emailaddr_username(&user);
		rc = formatln(&wstr, &wusrlen, user, view->ncols, 0, false);
		if (maxlen < wusrlen)
			maxlen = wusrlen;





		fsl_free(wstr);
		fsl_free(user);
		++ncommits;
		entry = TAILQ_NEXT(entry, entries);
	}

	ncommits = 0;







>
|
>
>

>


|





|





<
|
>
>
>
>
>







2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789

2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
		++wlen;
	}
	wattroff(view->window, rx);
	fsl_free(wline);
	if (view->nlines <= 1)
		goto end;

	/*
	 * Parse commits to be written on screen for the longest username,
	 * and the longest log message summary line (i.e., up to first '\n')
	 */
	entry = s->first_commit_onscreen;
	s->maxx = 0;  /* length of longest summary commit message */
	while (entry) {
		wchar_t		*wstr;
		char		*end, *msg, *user;
		int		 wusrlen;
		if (ncommits >= view->nlines - 1)
			break;
		user = fsl_strdup(entry->commit->user);
		if (user == NULL) {
			rc = RC(FSL_RC_ERROR, "fsl_strdup");
			goto end;
		}
		if (strpbrk(user, "<@>") != NULL)
			parse_emailaddr_username(&user);
		rc = formatln(&wstr, &wusrlen, user, view->ncols, 0, false);

		maxlen = MAX(maxlen, wusrlen);
		msg = entry->commit->comment;
		if ((end = strchr(msg, '\n')))
			s->maxx = MAX(s->maxx, end - msg);
		else
			s->maxx = MAX(s->maxx, fsl_strlen(msg));
		fsl_free(wstr);
		fsl_free(user);
		++ncommits;
		entry = TAILQ_NEXT(entry, entries);
	}

	ncommits = 0;
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
			i++;
		} else if (width == -1) {
			if (wline[i] == L'\t') {
				width = TABSIZE -
				    ((cols + start_column) % TABSIZE);
			} else {
				width = 1;
				wline[i] = L'.';
			}
			if (cols + width > column_limit)
				break;
			cols += width;
			i++;
		} else {
			rc = RC(FSL_RC_RANGE, "%s", "wcwidth");
			goto end;
		}
	}
	wline[i] = L'\0';
	if (wstrlen)
		*wstrlen = cols;
end:







|






|







2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
			i++;
		} else if (width == -1) {
			if (wline[i] == L'\t') {
				width = TABSIZE -
				    ((cols + start_column) % TABSIZE);
			} else {
				width = 1;
				wline[i] = L'?';
			}
			if (cols + width > column_limit)
				break;
			cols += width;
			i++;
		} else {
			rc = RC(FSL_RC_RANGE, "wcwidth");
			goto end;
		}
	}
	wline[i] = L'\0';
	if (wstrlen)
		*wstrlen = cols;
end:
2763
2764
2765
2766
2767
2768
2769

2770
2771
2772
2773
2774
2775
2776
2777
2778
2779







2780
2781
2782


2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796

2797
2798
2799
2800
2801
2802
2803
2804





































2805
2806
2807
2808
2809
2810
2811
	*ptr = dst;
	return sz;
}

static int
multibyte_to_wchar(const char *src, wchar_t **dst, size_t *dstlen)
{

	int	rc = 0;

	/*
	 * mbstowcs POSIX extension specifies that the number of wchar that
	 * would be written are returned when first arg is a null pointer:
	 * https://en.cppreference.com/w/cpp/string/multibyte/mbstowcs
	 */
	*dstlen = mbstowcs(NULL, src, 0);
	if (*dstlen == (size_t)-1) {
		if (errno == EILSEQ)







			return RC(FSL_RC_RANGE,
			    "invalid multibyte character [%s]", src);
		return RC(FSL_RC_MISUSE, "mbstowcs(%s)", src);


	}


	*dst = NULL;
	*dst = fsl_malloc(sizeof(wchar_t) * (*dstlen + 1));
	if (*dst == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "malloc");
		goto end;
	}

	if (mbstowcs(*dst, src, *dstlen) != *dstlen)
		rc = RC(FSL_RC_SIZE_MISMATCH, "mbstowcs(%s)", src);

end:

	if (rc) {
		fsl_free(*dst);
		*dst = NULL;
		*dstlen = 0;
	}

	return rc;
}






































/*
 * When the terminal is >= 110 columns wide, the commit summary line in the
 * timeline view will take the form:
 *
 *   DATE UUID USERNAME  COMMIT-COMMENT
 *







>
|








|
>
>
>
>
>
>
>
|

<
>
>




|

|



|



>








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976

2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
	*ptr = dst;
	return sz;
}

static int
multibyte_to_wchar(const char *src, wchar_t **dst, size_t *dstlen)
{
	char	*rep = NULL;
	int	 rc = FSL_RC_OK;

	/*
	 * mbstowcs POSIX extension specifies that the number of wchar that
	 * would be written are returned when first arg is a null pointer:
	 * https://en.cppreference.com/w/cpp/string/multibyte/mbstowcs
	 */
	*dstlen = mbstowcs(NULL, src, 0);
	if (*dstlen == (size_t)-1) {
		if (errno != EILSEQ)
			return RC(FSL_RC_MISUSE, "mbstowcs(%s)", src);

		if (replace_unicode(&rep, src))
			return rc;

		*dstlen = mbstowcs(NULL, rep, 0);
		if (*dstlen == (size_t)-1) {
			rc = RC(FSL_RC_RANGE,
			    "invalid multibyte character [%s]", src);

			goto end;
		}
	}


	*dst = NULL;
	*dst = fsl_malloc((*dstlen + 1) * sizeof(**dst));
	if (*dst == NULL) {
		rc = RC(FSL_RC_ERROR, "malloc");
		goto end;
	}

	if (mbstowcs(*dst, rep ? rep : src, *dstlen) != *dstlen)
		rc = RC(FSL_RC_SIZE_MISMATCH, "mbstowcs(%s)", src);

end:
	fsl_free(rep);
	if (rc) {
		fsl_free(*dst);
		*dst = NULL;
		*dstlen = 0;
	}

	return rc;
}

/*
 * Iterate mbs, writing each char to *ptr, and replace any non-printable or
 * unicode characters that are invalid in the environment's current character
 * encoding with a '?'. *ptr must eventually be disposed of by the caller.
 */
static int
replace_unicode(char **ptr, const char *mbs)
{
	const char	*src;
	char		*dst;
	wchar_t		 wc;
	int		 width, len;

	len = fsl_strlen(mbs);
	*ptr = fsl_malloc(len + 1);  /* NUL */
	if (*ptr == NULL)
		return RC(FSL_RC_ERROR, "fsl_malloc");

	src = mbs;
	dst = *ptr;

	while (*src) {
		if ((len = mbtowc(&wc, src, MB_CUR_MAX)) == -1) {  /* invalid */
			*dst++ = '?';
			++src;
		} else if (*src != '\r' && *src != '\n' &&
		    (width = wcwidth(wc)) == -1) {  /* not printable */
			*dst++ = '?';
			src += len;
		} else  /* valid */
			while (len-- > 0)
				*dst++ = *src++;
	}
	*dst = '\0';
	return FSL_RC_OK;
}

/*
 * When the terminal is >= 110 columns wide, the commit summary line in the
 * timeline view will take the form:
 *
 *   DATE UUID USERNAME  COMMIT-COMMENT
 *
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
    int maxlen)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct fnc_colour		*c = NULL;
	wchar_t				*wstr = NULL;
	char				*comment0 = NULL, *comment = NULL;
	char				*date = NULL;
	char				*eol = NULL, *pad = NULL, *user = NULL;
	size_t				 i = 0;
	int				 col, limit, wlen;
	int				 rc = FSL_RC_OK;

	/* Trim time component from timestamp for the date field. */
	date = fsl_strdup(commit->timestamp);
	while (!fsl_isspace(date[i++])) {}







|







3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
    int maxlen)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct fnc_colour		*c = NULL;
	wchar_t				*wstr = NULL;
	char				*comment0 = NULL, *comment = NULL;
	char				*date = NULL;
	char				*eol = NULL, *user = NULL;
	size_t				 i = 0;
	int				 col, limit, wlen;
	int				 rc = FSL_RC_OK;

	/* Trim time component from timestamp for the date field. */
	date = fsl_strdup(commit->timestamp);
	while (!fsl_isspace(date[i++])) {}
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883



2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894


2895
2896
2897
2898
2899
2900


2901
2902
2903
2904

2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949





2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960


2961
2962
2963
2964
2965
2966
2967



2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
	 * the longest username on the screen.
	 */
	user = fsl_strdup(commit->user);
	if (user == NULL)
		goto end;
	if (strpbrk(user, "<@>") != NULL)
		parse_emailaddr_username(&user);
	rc = formatln(&wstr, &wlen, user, view->ncols - col,
	    col, false);
	if (rc)
		goto end;
	if (s->colour)
		c = get_colour(&s->colours, FNC_COLOUR_USER);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddwstr(view->window, wstr);
	fsl_free(wstr);
	pad = fsl_mprintf("%*c",  maxlen - wlen + 2, ' ');
	waddstr(view->window, pad);



	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
	col += (maxlen + 2);
	if (col > view->ncols)
		goto end;

	/* Only show comment up to the first newline character. */
	comment0 = fsl_strdup(commit->comment);
	comment = comment0;
	if (comment == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");


	while (*comment == '\n')
		++comment;
	eol = strchr(comment, '\n');
	if (eol)
		*eol = '\0';
	limit = view->ncols - col;


	rc = formatln(&wstr, &wlen, comment, limit, col, false);
	if (rc)
		goto end;
	waddwstr(view->window, wstr);

	col += wlen;
	while (col < view->ncols) {
		waddch(view->window, ' ');
		++col;
	}
end:
	fsl_free(date);
	fsl_free(user);
	fsl_free(wstr);
	fsl_free(pad);
	fsl_free(comment0);
	return rc;
}

static int
view_input(struct fnc_view **new, int *done, struct fnc_view *view,
    struct view_tailhead *views)
{
	struct fnc_view	*v;
	int		 ch, rc = 0;

	*new = NULL;

	/* Clear search indicator string. */
	if (view->search_status == SEARCH_COMPLETE ||
	    view->search_status == SEARCH_NO_MATCH)
		view->search_status = SEARCH_CONTINUE;

	if (view->searching && view->search_status == SEARCH_WAITING) {
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		sched_yield();
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
		rc = view->grep(view);
		return rc;
	}

	nodelay(stdscr, FALSE);
	/* Allow thread to make progress while waiting for input. */
	if ((rc = pthread_mutex_unlock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");





	ch = wgetch(view->window);
	if ((rc = pthread_mutex_lock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	if (rec_sigwinch || rec_sigcont) {
		fnc_resizeterm();
		rec_sigwinch = 0;
		rec_sigcont = 0;
		TAILQ_FOREACH(v, views, entries) {
			rc = view_resize(v, v->mode);


			if (rc)
				return rc;
			rc = v->input(new, v, KEY_RESIZE);
			if (rc)
				return rc;
			if (v->child) {
				rc = view_resize(v->child, v->child->mode);



				if (rc)
					return rc;
				rc = v->child->input(new, v->child, KEY_RESIZE);
				if (rc)
					return rc;
			}
		}
	}

	switch (ch) {
	case '\t':
		rc = cycle_view(view);
		break;
	case KEY_F(1):
	case 'H':
	case '?':
		rc = help(view);
		if (rc == FSL_RC_BREAK) {
			rc = FSL_RC_OK;
			*done = 1;
		}
		break;
	case 'q':
		if (view->parent && view->parent->vid == FNC_VIEW_TIMELINE &&
		    view->mode == VIEW_SPLIT_HRZN) {
			/* May need more commits to fill fullscreen. */
			rc = request_tl_commits(view->parent);
			view->parent->mode = VIEW_SPLIT_NONE;







|
<







|
|
|
>
>
>


<






|
|
>
>





|
>
>
|
|
|
|
>
|








<









|











|



|








|
>
>
>
>
>
|


|






|
>
>






|
>
>
>

















<
<
<
<







3099
3100
3101
3102
3103
3104
3105
3106

3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121

3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153

3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233




3234
3235
3236
3237
3238
3239
3240
	 * the longest username on the screen.
	 */
	user = fsl_strdup(commit->user);
	if (user == NULL)
		goto end;
	if (strpbrk(user, "<@>") != NULL)
		parse_emailaddr_username(&user);
	rc = formatln(&wstr, &wlen, user, view->ncols - col, col, false);

	if (rc)
		goto end;
	if (s->colour)
		c = get_colour(&s->colours, FNC_COLOUR_USER);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddwstr(view->window, wstr);
	col += wlen;
	while (col < view->ncols && wlen < maxlen + 2) {
		waddch(view->window, ' ');
		++col;
		++wlen;
	}
	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);

	if (col > view->ncols)
		goto end;

	/* Only show comment up to the first newline character. */
	comment0 = fsl_strdup(commit->comment);
	comment = comment0;
	if (comment == NULL) {
		rc = RC(FSL_RC_ERROR, "fsl_strdup");
		goto end;
	}
	while (*comment == '\n')
		++comment;
	eol = strchr(comment, '\n');
	if (eol)
		*eol = '\0';
	limit = view->pos.col + view->ncols - col;
	if (view->pos.col < (etcount(comment, fsl_strlen(comment)) - 1)) {
		fsl_free(wstr);
		rc = formatln(&wstr, &wlen, comment, limit, col, true);
		if (rc)
			goto end;
		waddwstr(view->window, wstr + view->pos.col);
	}
	col += MAX(wlen - view->pos.col, 0);
	while (col < view->ncols) {
		waddch(view->window, ' ');
		++col;
	}
end:
	fsl_free(date);
	fsl_free(user);
	fsl_free(wstr);

	fsl_free(comment0);
	return rc;
}

static int
view_input(struct fnc_view **new, int *done, struct fnc_view *view,
    struct view_tailhead *views)
{
	struct fnc_view	*v;
	int		 ch = 0, rc = 0;

	*new = NULL;

	/* Clear search indicator string. */
	if (view->search_status == SEARCH_COMPLETE ||
	    view->search_status == SEARCH_NO_MATCH)
		view->search_status = SEARCH_CONTINUE;

	if (view->searching && view->search_status == SEARCH_WAITING) {
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_mutex_unlock");
		sched_yield();
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_mutex_lock");
		rc = view->grep(view);
		return rc;
	}

	nodelay(stdscr, FALSE);
	/* Allow thread to make progress while waiting for input. */
	if ((rc = pthread_mutex_unlock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "pthread_mutex_unlock");
	/*
	 * XXX This check is not yet needed, but is pre-empting the NYI feature
	 * of calling fnc_stash from the diff_input_handler() with a key map.
	 */
	if (view->state.diff.diff_mode != STASH_INTERACTIVE)
		ch = wgetch(view->window);
	if ((rc = pthread_mutex_lock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "pthread_mutex_lock");

	if (rec_sigwinch || rec_sigcont) {
		fnc_resizeterm();
		rec_sigwinch = 0;
		rec_sigcont = 0;
		TAILQ_FOREACH(v, views, entries) {
			rc = view_resize(v, v->child &&
			    screen_is_split(v->child));
			updatescreen(v->window, true, true);
			if (rc)
				return rc;
			rc = v->input(new, v, KEY_RESIZE);
			if (rc)
				return rc;
			if (v->child) {
				rc = view_resize(v->child, v->child->active &&
				    screen_is_shared(v->child));
				drawborder(v->child);
				updatescreen(v->child->window, true, true);
				if (rc)
					return rc;
				rc = v->child->input(new, v->child, KEY_RESIZE);
				if (rc)
					return rc;
			}
		}
	}

	switch (ch) {
	case '\t':
		rc = cycle_view(view);
		break;
	case KEY_F(1):
	case 'H':
	case '?':
		rc = help(view);




		break;
	case 'q':
		if (view->parent && view->parent->vid == FNC_VIEW_TIMELINE &&
		    view->mode == VIEW_SPLIT_HRZN) {
			/* May need more commits to fill fullscreen. */
			rc = request_tl_commits(view->parent);
			view->parent->mode = VIEW_SPLIT_NONE;
3027
3028
3029
3030
3031
3032
3033




3034
3035
3036
3037
3038
3039
3040
	case CTRL('z'):
		raise(SIGTSTP);
	default:
		rc = view->input(new, view, ch);
		break;
	}





	return rc;
}

static int
cycle_view(struct fnc_view *view)
{
	int rc = FSL_RC_OK;







>
>
>
>







3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
	case CTRL('z'):
		raise(SIGTSTP);
	default:
		rc = view->input(new, view, ch);
		break;
	}

	if (rc == FSL_RC_BREAK) {
		rc = FSL_RC_OK;
		*done = 1;
	}
	return rc;
}

static int
cycle_view(struct fnc_view *view)
{
	int rc = FSL_RC_OK;
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103


















































3104
3105
3106
3107
3108
3109
3110
			rc = offset_selected_line(view->parent);
		if (!rc)
			rc = offset_selected_line(view);
	}

	return rc;
}

static int
help(struct fnc_view *view)
{
	FILE			*help = NULL;


















































	char			*title = NULL;
	static const char	*keys[][2] = {
	    {""},
	    {""}, /* Global */
	    {"  H,?,F1           ", "  ❬H❭❬?❭❬F1❭      "},
	    {"  k,<Up>           ", "  ❬↑❭❬k❭          "},
	    {"  j,<Down>         ", "  ❬↓❭❬j❭          "},









|

|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
			rc = offset_selected_line(view->parent);
		if (!rc)
			rc = offset_selected_line(view);
	}

	return rc;
}

static int
stash_help(struct fnc_view *view, int8_t scroll)
{
	char			*title = NULL;
	static const char	*keys[][2] = {
	    {""},
	    {""},
	    {"  b ", "  ❬b❭ "},
	    {"  m ", "  ❬m❭ "},
	    {"  y ", "  ❬y❭ "},
	    {"  n ", "  ❬n❭ "},
	    {"  a ", "  ❬a❭ "},
	    {"  k ", "  ❬k❭ "},
	    {"  A ", "  ❬A❭ "},
	    {"  K ", "  ❬K❭ "},
	    {"  ? ", "  ❬?❭ "},
	    {"  q ", "  ❬q❭ "},
	    {"  Q ", "  ❬Q❭ "},
	    {""},
	    {""},
	    {0}
	};
	static const char *desc[] = {
	    "",
	    "Stash",
	    "- scroll back to the previous page^",
	    "- show more of this hunk on the next page^",
	    "- stash this hunk",
	    "- do not stash this hunk",
	    "- stash this hunk and all remaining hunks in the file",
	    "- do not stash this hunk nor any remaining hunks in the file",
	    "- stash this hunk and all remaining hunks in the diff",
	    "- do not stash this hunk nor any remaining hunks in the diff",
	    "- display this help screen",
	    "- exit this help screen",
	    "- exit help and quit fnc stash aborting any selections",
	    "",
	    "^conditionally available when hunks occupy multiple pages"
	};
	int	rc = FSL_RC_OK;

	title = fsl_mprintf("%s %s Help\n", fcli_progname(), PRINT_VERSION);
	if (title == NULL)
		return RC(FSL_RC_ERROR, "fsl_mprintf");

	rc = padpopup(view, keys, desc, title, scroll);

	fsl_free(title);
	return rc;
}

static int
help(struct fnc_view *view)
{
	char			*title = NULL;
	static const char	*keys[][2] = {
	    {""},
	    {""}, /* Global */
	    {"  H,?,F1           ", "  ❬H❭❬?❭❬F1❭      "},
	    {"  k,<Up>           ", "  ❬↑❭❬k❭          "},
	    {"  j,<Down>         ", "  ❬↓❭❬j❭          "},
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207

3208

3209
3210
3211
3212
3213
3214
3215
	    "Move selection cursor or page down one line",
	    "Scroll view up one page",
	    "Scroll view down one page",
	    "Scroll view up one half page",
	    "Scroll view down one half page",
	    "Jump to first line or start of the view",
	    "Jump to last line or end of the view",
	    "Scroll the view right (diff, blame, help)",
	    "Scroll the view left (diff, blame, help)",
	    "Scroll right to the end of the longest line (diff, blame, help)",

	    "Scroll left to the beginning of the line (diff, blame, help)",

	    "Switch focus between open views",
	    "Toggle coloured output",
	    "Toggle fullscreen",
	    "Open prompt to enter search term (not available in this view)",
	    "Find next line or token matching the current search term",
	    "Find previous line or token matching the current search term",
	    "Quit the active view",







|
|
|
>
|
>







3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
	    "Move selection cursor or page down one line",
	    "Scroll view up one page",
	    "Scroll view down one page",
	    "Scroll view up one half page",
	    "Scroll view down one half page",
	    "Jump to first line or start of the view",
	    "Jump to last line or end of the view",
	    "Scroll the view right (timeline, diff, blame, help)",
	    "Scroll the view left (timeline, diff, blame, help)",
	    "Scroll right to the end of the longest line "
	    "(timeline, diff, blame, help)",
	    "Scroll left to the beginning of the line "
	    "(timeline, diff, blame, help)",
	    "Switch focus between open views",
	    "Toggle coloured output",
	    "Toggle fullscreen",
	    "Open prompt to enter search term (not available in this view)",
	    "Find next line or token matching the current search term",
	    "Find previous line or token matching the current search term",
	    "Quit the active view",
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
	    "Navigate to next file in the diff",
	    "Navigate to previous file in the diff",
	    "Open and populate branch view with all repository branches",
	    "Open prompt to enter file number and navigate to file",
	    "Toggle inversion of diff output",
	    "Toggle display of file line numbers",
	    "Prompt for path to write a patch of the currently viewed diff",
	    "Toggle display of function name in chunk header",
	    "Display side-by-side formatted diff",
	    "Toggle verbosity of diff output",
	    "Toggle ignore end-of-line whitespace-only changes in diff",
	    "Toggle ignore whitespace-only changes in diff",
	    "Decrease the number of context lines",
	    "Increase the number of context lines",
	    "Display commit diff of next line in the file / timeline entry",







|







3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
	    "Navigate to next file in the diff",
	    "Navigate to previous file in the diff",
	    "Open and populate branch view with all repository branches",
	    "Open prompt to enter file number and navigate to file",
	    "Toggle inversion of diff output",
	    "Toggle display of file line numbers",
	    "Prompt for path to write a patch of the currently viewed diff",
	    "Toggle display of function name in hunk header",
	    "Display side-by-side formatted diff",
	    "Toggle verbosity of diff output",
	    "Toggle ignore end-of-line whitespace-only changes in diff",
	    "Toggle ignore whitespace-only changes in diff",
	    "Decrease the number of context lines",
	    "Increase the number of context lines",
	    "Display commit diff of next line in the file / timeline entry",
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325

3326
3327
3328
3329

3330



3331

3332





















3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353


3354
3355
3356
3357
3358
3359
3360
	    "Toggle display of the SHA hash that identifies the branch",
	    "Toggle branch sort order (lexicographical -> mru -> state)",
	    "Open a tree view of the currently selected branch",
	    "Reload view with all repository branches and no filters applied",
	    "",
	    "  See fnc(1) for complete list of options and key bindings."
	};
	int	cs, ln, width = 0, rc = 0;

	cs = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0) ? 1 : 0;

	title = fsl_mprintf("%s %s Help\n", fcli_progname(), PRINT_VERSION);
	if (title == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_mprintf");

	help = tmpfile();
	if (help == NULL)
		return RC(FSL_RC_IO, "%s", "tmpfile");

	/*
	 * Format help text, and compute longest line and total number of
	 * lines in text to be displayed to determine pad dimensions.
	 */
	width = fsl_strlen(title);
	for (ln = 0; keys[ln][0]; ++ln) {
		if (keys[ln][1]) {
			width = MAX((fsl_size_t)width,
			    fsl_strlen(keys[ln][cs]) + fsl_strlen(desc[ln]));
		}
		fsl_fprintf(help, "%s%s%c", keys[ln][cs], desc[ln],
		    keys[ln + 1] ? '\n' : 0);
	}
	rewind(help);

	rc = padpopup(view, width, ln, help, title);
	if (fclose(help) == EOF)
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fclose");

	fsl_free(title);
	return rc;
}

/*
 * Create popup pad in which to write the supplied txt string and optional
 * title. The pad is contained within a window that is offset four columns in
 * and two lines down from the parent window.
 */
static int
padpopup(struct fnc_view *view, int width, int height, FILE *txt,
    const char *title)
{
	WINDOW		*win, *content;

	char		*line = NULL;
	ssize_t		 linelen;
	size_t		 linesz;
	int		 ch, cury, curx, end, wy, wx, x0, y0, rc = FSL_RC_OK;





	x0 = 4;		/* Number of columns to border window. */

	y0 = 2;		/* Number of lines to border window. */





















	cury = curx = 0;
	wx = getmaxx(view->window) - ((x0 + 1) * 2); /* Width of window. */
	wy = getmaxy(view->window) - ((y0 + 1) * 2); /* Height of window */
	ch = ERR;

	if ((win = newwin(wy, wx, y0, x0)) == 0)
		return RC(FSL_RC_ERROR, "%s", "newwin");
	if ((content = newpad(height + 1, width + 1)) == 0) {
		delwin(win);
		return RC(FSL_RC_ERROR, "%s", "newpad");
	}

	doupdate();
	keypad(content, TRUE);

	/* Write text content to pad. */
	if (title)
		centerprint(content, 0, 0, wx, title, 0);
	while ((linelen = getline(&line, &linesz, txt)) != -1)
		waddstr(content, line);
	fsl_free(line);



	end = (getcury(content) - (wy - 3));  /* No. lines past end of pad. */
	do {
		switch (ch) {
			case KEY_UP:
			case 'k':
				if (cury > 0)







<
|
<



|

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<











|
|


>



|
>

>
>
>
|
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|
|



|
|

|







|
|
|

>
>







3575
3576
3577
3578
3579
3580
3581

3582

3583
3584
3585
3586
3587



















3588


3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
	    "Toggle display of the SHA hash that identifies the branch",
	    "Toggle branch sort order (lexicographical -> mru -> state)",
	    "Open a tree view of the currently selected branch",
	    "Reload view with all repository branches and no filters applied",
	    "",
	    "  See fnc(1) for complete list of options and key bindings."
	};

	int	rc = FSL_RC_OK;


	title = fsl_mprintf("%s %s Help\n", fcli_progname(), PRINT_VERSION);
	if (title == NULL)
		return RC(FSL_RC_ERROR, "fsl_mprintf");




















	rc = padpopup(view, keys, desc, title, -1);



	fsl_free(title);
	return rc;
}

/*
 * Create popup pad in which to write the supplied txt string and optional
 * title. The pad is contained within a window that is offset four columns in
 * and two lines down from the parent window.
 */
static int
padpopup(struct fnc_view *view, const char *keys[][2], const char **desc,
    const char *title, int8_t stash)
{
	WINDOW		*win, *content;
	FILE		*txt;
	char		*line = NULL;
	ssize_t		 linelen;
	size_t		 linesz;
	int		 ch, cury, curx, end, ln, width, wy, wx, x0, y0;
	int		 cs, rc = FSL_RC_OK;

	txt = tmpfile();
	if (txt == NULL)
		return RC(FSL_RC_IO, "tmpfile");

	cs = (fsl_strcmp(nl_langinfo(CODESET), "UTF-8") == 0) ? 1 : 0;

	/*
	 * Format help text, and compute longest line and total number of
	 * lines in text to be displayed to determine pad dimensions.
	 */
	width = fsl_strlen(title);
	for (ln = 0; keys[ln][0]; ++ln) {
		if ((!stash && (ln == 2 || ln == 3)) || (stash < 1 && ln == 14)
		    || (stash == 1 && ln == 2) || (stash == 2 && ln == 3))
			continue;  /* only show available stash keymaps */
		if (keys[ln][1]) {
			width = MAX((fsl_size_t)width,
			    fsl_strlen(keys[ln][cs]) + fsl_strlen(desc[ln]));
		}
		fsl_fprintf(txt, "%s%s%c", keys[ln][cs], desc[ln],
		    keys[ln + 1] ? '\n' : 0);
	}
	++width;
	rewind(txt);

	x0 = 4;	 /* column number at which to start the help window */
	y0 = 2;	 /* line number at which to start the help window */
	cury = curx = 0;
	wx = getmaxx(view->window) - ((x0 + 1) * 2);  /* window width */
	wy = MIN(ln + 3, getmaxy(view->window) - ((y0 + 1) * 2));  /* height */
	ch = ERR;

	if ((win = newwin(wy, wx, y0, x0)) == 0)
		return RC(FSL_RC_ERROR, "newwin");
	if ((content = newpad(ln + 1, width + 1)) == 0) {
		delwin(win);
		return RC(FSL_RC_ERROR, "newpad");
	}

	doupdate();
	keypad(content, TRUE);

	/* Write text content to pad. */
	if (title)
		rc = centerprint(content, 0, 0, MIN(wx, width), title, 0);
	while (!rc && (linelen = getline(&line, &linesz, txt)) != -1)
		rc = waddstr(content, line);
	fsl_free(line);
	if (rc)
		return rc;

	end = (getcury(content) - (wy - 3));  /* No. lines past end of pad. */
	do {
		switch (ch) {
			case KEY_UP:
			case 'k':
				if (cury > 0)
3419
3420
3421
3422
3423
3424
3425



3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449

3450
3451
3452
3453
3454
3455
3456
3457

3458
3459


3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471















3472
3473
3474
3475
3476
3477
3478
		box(win, 0, 0);
		wnoutrefresh(win);
		pnoutrefresh(content, cury, curx, y0 + 1, x0 + 1, wy, wx);
		doupdate();
	} while (!rc && (ch = wgetch(content)) != 'q' && ch != KEY_ESCAPE
	    && ch != ERR);




	/* Destroy window. */
	werase(win);
	wrefresh(win);
	delwin(win);
	delwin(content);

	/* Restore fnc window content. */
	touchwin(view->window);
	wnoutrefresh(view->window);
	doupdate();

	return rc;
}

static void
centerprint(WINDOW *win, int starty, int startx, int cols, const char *str,
    chtype colour)
{
	int	x, y;

	if (win == NULL)
		win = stdscr;

	getyx(win, y, x);

	x = startx ? startx : x;
	y = starty ? starty : y;
	if (!cols)
		cols = getmaxx(win);

	x = startx + (cols - fsl_strlen(str)) / 2;
	wattron(win, colour ? colour : A_UNDERLINE);
	mvwprintw(win, y, x, "%s", str);

	wattroff(win, colour ? colour : A_UNDERLINE);
	refresh();


}

static int
tl_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	int				 rc = FSL_RC_OK;
	uint16_t			 nscroll = view->nlines - 2;

	free_tags(s, true);

	switch (ch) {















	case KEY_DOWN:
	case 'j':
	case '.':
	case '>':
		rc = move_tl_cursor_down(view, 0);
		break;
	case CTRL('d'):







>
>
>














|
|
|

|




|
>
|
<
<
<

<

|
>


>
>












>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761



3762

3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
		box(win, 0, 0);
		wnoutrefresh(win);
		pnoutrefresh(content, cury, curx, y0 + 1, x0 + 1, wy, wx);
		doupdate();
	} while (!rc && (ch = wgetch(content)) != 'q' && ch != KEY_ESCAPE
	    && ch != ERR);

	if (fclose(txt) == EOF)
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "fclose");

	/* Destroy window. */
	werase(win);
	wrefresh(win);
	delwin(win);
	delwin(content);

	/* Restore fnc window content. */
	touchwin(view->window);
	wnoutrefresh(view->window);
	doupdate();

	return rc;
}

static int
centerprint(WINDOW *win, size_t starty, size_t startx, size_t width,
    const char *str, chtype colour)
{
	size_t	len, x, y;

	if (win == NULL)
		win = stdscr;

	len = fsl_strlen(str);
	y = MAX(starty, 0);					/* start line */
	x = startx ? startx : width > len ? (width - len) / 2 : 0;  /* column */





	wattron(win, colour ? colour : A_UNDERLINE);
	if (mvwprintw(win, y, x, "%s", str) == ERR)
		return RC(FSL_RC_RANGE, "mvwprintw");
	wattroff(win, colour ? colour : A_UNDERLINE);
	refresh();

	return FSL_RC_OK;
}

static int
tl_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	int				 rc = FSL_RC_OK;
	uint16_t			 nscroll = view->nlines - 2;

	free_tags(s, true);

	switch (ch) {
	case '0':
		view->pos.col = 0;
		break;
	case '$':
		view->pos.col = MAX(s->maxx - view->ncols / 2, 0);
		break;
	case KEY_RIGHT:
	case 'l':
		if (view->pos.col + view->ncols / 2 < s->maxx)
			view->pos.col += 2;
		break;
	case KEY_LEFT:
	case 'h':
		view->pos.col -= MIN(view->pos.col, 2);
		break;
	case KEY_DOWN:
	case 'j':
	case '.':
	case '>':
		rc = move_tl_cursor_down(view, 0);
		break;
	case CTRL('d'):
3509
3510
3511
3512
3513
3514
3515

3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545

3546
3547
3548
3549
3550
3551
3552
		move_tl_cursor_up(view, false, true);
		break;
	case KEY_RESIZE:
		if (s->selected > view->nlines - 2)
			s->selected = view->nlines - 2;
		if (s->selected > s->commits.ncommits - 1)
			s->selected = s->commits.ncommits - 1;

		select_commit(s);
		if (s->commits.ncommits < view->nlines - 1 &&
		    !s->thread_cx.eotl) {
			s->thread_cx.ncommits_needed += (view->nlines - 1) -
			    s->commits.ncommits;
			rc = signal_tl_thread(view, 1);
		}
		break;
	case 'C': {
		if (s->selected_entry->commit->type[0] != 'c') {
			rc = sitrep(view, "-- requires check-in artifact --",
			    SR_ALL);
			break;
		}
		fsl_cx *const f = fcli_cx();
		/*
		 * XXX This is not good but I can't think of an alternative
		 * without patching libf: fsl_ckout_changes_scan() returns a
		 * db lock error via fsl_vfile_changes_scan() when versioned
		 * files are modified in-session. Clear it and notify user.
		 */
		rc = fsl_ckout_changes_scan(f);
		if (rc == FSL_RC_DB) {
			rc = sitrep(view, "-- checkout db busy --", SR_ALL);
			break;
		} else if (rc)
			return RC(rc, "%s", "fsl_ckout_changes_scan");
		if (!fsl_ckout_has_changes(f)) {
			sitrep(view, "-- no local changes --",
			    SR_CLREOL | SR_UPDATE | SR_SLEEP);

			break;
		}
		s->selected_entry->commit->diff_type = FNC_DIFF_CKOUT;
	}	/* FALL THROUGH */
	case ' ':
		if (!tagged_commit(s))
			break;







>










|
|











|


|

<
|
>







3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869

3870
3871
3872
3873
3874
3875
3876
3877
3878
		move_tl_cursor_up(view, false, true);
		break;
	case KEY_RESIZE:
		if (s->selected > view->nlines - 2)
			s->selected = view->nlines - 2;
		if (s->selected > s->commits.ncommits - 1)
			s->selected = s->commits.ncommits - 1;
		s->selected = MAX(s->selected, 0);
		select_commit(s);
		if (s->commits.ncommits < view->nlines - 1 &&
		    !s->thread_cx.eotl) {
			s->thread_cx.ncommits_needed += (view->nlines - 1) -
			    s->commits.ncommits;
			rc = signal_tl_thread(view, 1);
		}
		break;
	case 'C': {
		if (s->selected_entry->commit->type[0] != 'c') {
			rc = sitrep(view, SR_ALL,
			    "-- requires check-in artifact --");
			break;
		}
		fsl_cx *const f = fcli_cx();
		/*
		 * XXX This is not good but I can't think of an alternative
		 * without patching libf: fsl_ckout_changes_scan() returns a
		 * db lock error via fsl_vfile_changes_scan() when versioned
		 * files are modified in-session. Clear it and notify user.
		 */
		rc = fsl_ckout_changes_scan(f);
		if (rc == FSL_RC_DB) {
			rc = sitrep(view, SR_ALL, "-- checkout db busy --");
			break;
		} else if (rc)
			return RC(rc, "fsl_ckout_changes_scan");
		if (!fsl_ckout_has_changes(f)) {

			sitrep(view, SR_CLREOL | SR_UPDATE | SR_SLEEP,
			    "-- no local changes --");
			break;
		}
		s->selected_entry->commit->diff_type = FNC_DIFF_CKOUT;
	}	/* FALL THROUGH */
	case ' ':
		if (!tagged_commit(s))
			break;
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
		struct input input = {NULL, "filter: ", INPUT_ALPHA, SR_CLREOL};
		rc = fnc_prompt_input(view, &input);
		if (rc)
			return rc;
		s->glob = input.buf;
		rc = request_view(new_view, view, FNC_VIEW_TIMELINE);
		if (rc == FSL_RC_BREAK) {
			rc = sitrep(view, "-- no matching commits --", SR_ALL);
		}
		break;
	}
	case 't':
		if (s->selected_entry == NULL)
			break;
		if (!fsl_rid_is_a_checkin(fcli_cx(),
		    s->selected_entry->commit->rid))
			sitrep(view,
			    "-- tree requires check-in artifact --",
			    SR_CLREOL | SR_UPDATE | SR_SLEEP);
		else
			rc = request_view(new_view, view, FNC_VIEW_TREE);
		break;
	case 'q':
		s->quit = 1;
		break;
	default:







|








|
|
<







3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908

3909
3910
3911
3912
3913
3914
3915
		struct input input = {NULL, "filter: ", INPUT_ALPHA, SR_CLREOL};
		rc = fnc_prompt_input(view, &input);
		if (rc)
			return rc;
		s->glob = input.buf;
		rc = request_view(new_view, view, FNC_VIEW_TIMELINE);
		if (rc == FSL_RC_BREAK) {
			rc = sitrep(view, SR_ALL, "-- no matching commits --");
		}
		break;
	}
	case 't':
		if (s->selected_entry == NULL)
			break;
		if (!fsl_rid_is_a_checkin(fcli_cx(),
		    s->selected_entry->commit->rid))
			sitrep(view, SR_CLREOL | SR_UPDATE | SR_SLEEP,
			    "-- tree requires check-in artifact --");

		else
			rc = request_view(new_view, view, FNC_VIEW_TREE);
		break;
	case 'q':
		s->quit = 1;
		break;
	default:
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772

	switch (request) {
	case FNC_VIEW_DIFF: {
		struct fnc_tl_view_state *s = &view->state.timeline;
		if (s->selected_entry == NULL)
			break;
		rc = init_diff_view(new_view, x, y, s->selected_entry->commit,
		    view, s->showmeta);
		break;
	}
	case FNC_VIEW_BLAME: {
		struct fnc_tree_view_state *s = &view->state.tree;
		rc = blame_tree_entry(new_view, x, y, s->selected_entry,
		    &s->parents, s->commit_id);
		break;







|







4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097

	switch (request) {
	case FNC_VIEW_DIFF: {
		struct fnc_tl_view_state *s = &view->state.timeline;
		if (s->selected_entry == NULL)
			break;
		rc = init_diff_view(new_view, x, y, s->selected_entry->commit,
		    view, s->showmeta ? COMMIT_META : DIFF_PLAIN);
		break;
	}
	case FNC_VIEW_BLAME: {
		struct fnc_tree_view_state *s = &view->state.tree;
		rc = blame_tree_entry(new_view, x, y, s->selected_entry,
		    &s->parents, s->commit_id);
		break;
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
		rc = browse_commit_tree(new_view, x, y, s->selected_entry,
		    s->path);
		break;
	}
	case FNC_VIEW_BRANCH: {
		*new_view = view_open(0, 0, y, x, FNC_VIEW_BRANCH);
		if (*new_view == NULL)
			return RC(FSL_RC_ERROR, "%s", "view_open");
		rc = open_branch_view(*new_view, BRANCH_LS_OPEN_CLOSED, NULL,
		    0, 0);
		/* FALL THROUGH */
	}
	default:
		break;
	}







|







4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
		rc = browse_commit_tree(new_view, x, y, s->selected_entry,
		    s->path);
		break;
	}
	case FNC_VIEW_BRANCH: {
		*new_view = view_open(0, 0, y, x, FNC_VIEW_BRANCH);
		if (*new_view == NULL)
			return RC(FSL_RC_ERROR, "view_open");
		rc = open_branch_view(*new_view, BRANCH_LS_OPEN_CLOSED, NULL,
		    0, 0);
		/* FALL THROUGH */
	}
	default:
		break;
	}
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
static int
split_view(struct fnc_view *view, int *start_ln)
{
	int rc = FSL_RC_OK;

	view->mode = VIEW_SPLIT_HRZN;
	view->nlines = *start_ln;
	rc = view_resize(view, VIEW_SPLIT_NONE);
	if (!rc) {
		view->nlines = *start_ln - 1;
		rc = offset_selected_line(view);
	}

	return rc;
}







|







4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
static int
split_view(struct fnc_view *view, int *start_ln)
{
	int rc = FSL_RC_OK;

	view->mode = VIEW_SPLIT_HRZN;
	view->nlines = *start_ln;
	rc = view_resize(view, false);
	if (!rc) {
		view->nlines = *start_ln - 1;
		rc = offset_selected_line(view);
	}

	return rc;
}
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
	view->start_col = view->mode != VIEW_SPLIT_HRZN ?
	    view_split_start_col(0) : 0;
	view->nlines = LINES - view->start_ln;
	view->ncols = COLS - view->start_col;
	view->lines = LINES;
	view->cols = COLS;

	rc = view_resize(view, view->mode);
	if (rc)
		return rc;

	if (view->parent && view->mode == VIEW_SPLIT_HRZN)
		view->parent->nlines = view->lines - view->nlines - 1;

	if (mvwin(view->window, view->start_ln, view->start_col) == ERR)
		return RC(FSL_RC_ERROR, "%s", "mvwin");

	return rc;
}

static int
make_fullscreen(struct fnc_view *view)
{
	int	 rc = FSL_RC_OK;

	view->start_col = 0;
	view->start_ln = 0;
	view->nlines = LINES;
	view->ncols = COLS;
	view->lines = LINES;
	view->cols = COLS;

	rc = view_resize(view, VIEW_SPLIT_NONE);
	if (rc)
		return rc;

	if (mvwin(view->window, view->start_ln, view->start_col) == ERR)
		return RC(FSL_RC_ERROR, "%s", "mvwin");

	return rc;
}

/*
 * Find start column for vertical split. If terminal width is < 120 columns,
 * return 0 (i.e., do not split; open new view in the existing one). If >= 120,







|







|
















|




|







4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
	view->start_col = view->mode != VIEW_SPLIT_HRZN ?
	    view_split_start_col(0) : 0;
	view->nlines = LINES - view->start_ln;
	view->ncols = COLS - view->start_col;
	view->lines = LINES;
	view->cols = COLS;

	rc = view_resize(view, false);
	if (rc)
		return rc;

	if (view->parent && view->mode == VIEW_SPLIT_HRZN)
		view->parent->nlines = view->lines - view->nlines - 1;

	if (mvwin(view->window, view->start_ln, view->start_col) == ERR)
		return RC(FSL_RC_ERROR, "mvwin");

	return rc;
}

static int
make_fullscreen(struct fnc_view *view)
{
	int	 rc = FSL_RC_OK;

	view->start_col = 0;
	view->start_ln = 0;
	view->nlines = LINES;
	view->ncols = COLS;
	view->lines = LINES;
	view->cols = COLS;

	rc = view_resize(view, false);
	if (rc)
		return rc;

	if (mvwin(view->window, view->start_ln, view->start_col) == ERR)
		return RC(FSL_RC_ERROR, "mvwin");

	return rc;
}

/*
 * Find start column for vertical split. If terminal width is < 120 columns,
 * return 0 (i.e., do not split; open new view in the existing one). If >= 120,
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
	int		 rc = FSL_RC_OK;

	height = fnc_conf_getopt(FNC_VIEW_SPLIT_HEIGHT, false);

	if (height && height[fsl_strlen(height) - 1] == '%') {
		n = strtol(height, NULL, 10);
		if (n > INT_MAX || (errno == ERANGE && n == LONG_MAX))
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_RANGE),
			    "%s", "strtol");
		if (n < INT_MIN || (errno == ERANGE && n == LONG_MIN))
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_RANGE),
			    "%s", "strtol");
		if (!rc)
			n = lines * ((float)n / 100);
	} else if (height)
		rc = strtonumcheck(&n, height, 0, lines);

	fsl_free(height);
	return !rc && n && n < (lines - 2) ? lines - n : lines * HSPLIT_SCALE;







|
<

|
<







4373
4374
4375
4376
4377
4378
4379
4380

4381
4382

4383
4384
4385
4386
4387
4388
4389
	int		 rc = FSL_RC_OK;

	height = fnc_conf_getopt(FNC_VIEW_SPLIT_HEIGHT, false);

	if (height && height[fsl_strlen(height) - 1] == '%') {
		n = strtol(height, NULL, 10);
		if (n > INT_MAX || (errno == ERANGE && n == LONG_MAX))
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_RANGE), "strtol");

		if (n < INT_MIN || (errno == ERANGE && n == LONG_MIN))
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_RANGE), "strtol");

		if (!rc)
			n = lines * ((float)n / 100);
	} else if (height)
		rc = strtonumcheck(&n, height, 0, lines);

	fsl_free(height);
	return !rc && n && n < (lines - 2) ? lines - n : lines * HSPLIT_SCALE;
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
	update_panels();
	doupdate();

	if (s->search_commit) {
		int	ch;
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		ch = wgetch(view->window);
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
		if (ch == KEY_BACKSPACE) {
			view->search_status = SEARCH_ABORTED;
			goto end;
		}
		if (view->searching == SEARCH_FORWARD)
			entry = TAILQ_NEXT(s->search_commit, entries);
		else







|



|







4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
	update_panels();
	doupdate();

	if (s->search_commit) {
		int	ch;
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_mutex_unlock");
		ch = wgetch(view->window);
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_mutex_lock");
		if (ch == KEY_BACKSPACE) {
			view->search_status = SEARCH_ABORTED;
			goto end;
		}
		if (view->searching == SEARCH_FORWARD)
			entry = TAILQ_NEXT(s->search_commit, entries);
		else
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231

4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
	s->search_commit = NULL;
end:
	cbreak();
	return rc;
}

static bool
find_commit_match(struct fnc_commit_artifact *commit,
regex_t *regex)
{
	regmatch_t	regmatch;


	if (regexec(regex, commit->user, 1, &regmatch, 0) == 0 ||
	    regexec(regex, (char *)commit->uuid, 1, &regmatch, 0) == 0 ||
	    regexec(regex, commit->comment, 1, &regmatch, 0) == 0 ||
	    (commit->branch && regexec(regex, commit->branch, 1, &regmatch, 0)
	     == 0))
		return true;

	return false;
}

static int
view_close(struct fnc_view *view)







|
<



>
|
|
|
<
<







4543
4544
4545
4546
4547
4548
4549
4550

4551
4552
4553
4554
4555
4556
4557


4558
4559
4560
4561
4562
4563
4564
	s->search_commit = NULL;
end:
	cbreak();
	return rc;
}

static bool
find_commit_match(struct fnc_commit_artifact *commit, regex_t *regex)

{
	regmatch_t	regmatch;

	if ((commit->branch && !regexec(regex, commit->branch, 1, &regmatch, 0))
	    || !regexec(regex, commit->user, 1, &regmatch, 0)
	    || !regexec(regex, (char *)commit->uuid, 1, &regmatch, 0)
	    || !regexec(regex, commit->comment, 1, &regmatch, 0))


		return true;

	return false;
}

static int
view_close(struct fnc_view *view)
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
	int	 rc = 0;

	if (s->thread_id) {
		s->quit = 1;

		if ((rc = pthread_cond_signal(&s->thread_cx.commit_consumer)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "%s", "pthread_cond_signal");
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		if ((rc = pthread_join(s->thread_id, &err)) ||
		    err == PTHREAD_CANCELED)
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "%s", "pthread_join");
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");

		s->thread_id = 0;
	}

	if ((rc = pthread_cond_destroy(&s->thread_cx.commit_consumer)))
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_cond_destroy");

	if ((rc = pthread_cond_destroy(&s->thread_cx.commit_producer)))
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_cond_destroy");

	return rc;
}

static void
fnc_free_commits(struct commit_queue *commits)
{







|


|



|


|





|
<


|
<







4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643

4644
4645
4646

4647
4648
4649
4650
4651
4652
4653
	int	 rc = 0;

	if (s->thread_id) {
		s->quit = 1;

		if ((rc = pthread_cond_signal(&s->thread_cx.commit_consumer)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "pthread_cond_signal");
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_mutex_unlock");
		if ((rc = pthread_join(s->thread_id, &err)) ||
		    err == PTHREAD_CANCELED)
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "pthread_join");
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_mutex_lock");

		s->thread_id = 0;
	}

	if ((rc = pthread_cond_destroy(&s->thread_cx.commit_consumer)))
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS), "pthread_cond_destroy");


	if ((rc = pthread_cond_destroy(&s->thread_cx.commit_producer)))
		RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS), "pthread_cond_destroy");


	return rc;
}

static void
fnc_free_commits(struct commit_queue *commits)
{
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412

4413
4414
4415
4416
4417
4418

4419
4420
4421
4422
4423
4424
4425
4426
4427

	return 0;
}

static int
init_diff_view(struct fnc_view **new_view, int start_col, int start_ln,
    struct fnc_commit_artifact *commit, struct fnc_view *parent_view,
    bool showmeta)
{
	struct fnc_view	*diff_view;
	int		 rc = 0;

	diff_view = view_open(0, 0, start_ln, start_col, FNC_VIEW_DIFF);
	if (diff_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	rc = open_diff_view(diff_view, commit, NULL, parent_view, showmeta);
	if (!rc)
		*new_view = diff_view;

	return rc;
}

static int
open_diff_view(struct fnc_view *view, struct fnc_commit_artifact *commit,
    struct fnc_pathlist_head *paths, struct fnc_view *parent_view,
    bool showmeta)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	int				 rc = FSL_RC_OK;

	set_diff_opt(s);

	s->index.n = 0;
	s->index.idx = 0;

	s->paths = paths;
	s->selected_entry = commit;
	s->first_line_onscreen = 1;
	s->last_line_onscreen = view->nlines;
	s->selected_line = 1;
	s->f = NULL;

	s->parent_view = parent_view;
	s->showmeta = showmeta;

	if (s->colour) {
		STAILQ_INIT(&s->colours);
		rc = set_colours(&s->colours, FNC_VIEW_DIFF);
		if (rc)
			return rc;
	}







|






|

|









|








>






>

|







4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748

	return 0;
}

static int
init_diff_view(struct fnc_view **new_view, int start_col, int start_ln,
    struct fnc_commit_artifact *commit, struct fnc_view *parent_view,
    enum fnc_diff_mode mode)
{
	struct fnc_view	*diff_view;
	int		 rc = 0;

	diff_view = view_open(0, 0, start_ln, start_col, FNC_VIEW_DIFF);
	if (diff_view == NULL)
		return RC(FSL_RC_ERROR, "view_open");

	rc = open_diff_view(diff_view, commit, NULL, parent_view, mode);
	if (!rc)
		*new_view = diff_view;

	return rc;
}

static int
open_diff_view(struct fnc_view *view, struct fnc_commit_artifact *commit,
    struct fnc_pathlist_head *paths, struct fnc_view *parent_view,
    enum fnc_diff_mode mode)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	int				 rc = FSL_RC_OK;

	set_diff_opt(s);

	s->index.n = 0;
	s->index.idx = 0;
	s->scx.hunk.n = 0;
	s->paths = paths;
	s->selected_entry = commit;
	s->first_line_onscreen = 1;
	s->last_line_onscreen = view->nlines;
	s->selected_line = 1;
	s->f = NULL;
	s->view = view;
	s->parent_view = parent_view;
	s->diff_mode = mode;

	if (s->colour) {
		STAILQ_INIT(&s->colours);
		rc = set_colours(&s->colours, FNC_VIEW_DIFF);
		if (rc)
			return rc;
	}
4555
4556
4557
4558
4559
4560
4561

4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642




4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659









4660
4661
4662

4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679









4680



4681
4682
4683
4684
4685
4686










































































4687
4688
4689
4690
4691
4692
4693
	char	*line, *st0 = NULL, *st = NULL;
	off_t	 off = 0;
	uint32_t idx = 0;
	int	 rc = 0;

	s->maxx = 0;


	free(s->dlines);
	s->dlines = fsl_malloc(sizeof(enum line_type *));
	if (s->dlines == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	s->ndlines = 0;
	free(s->line_offsets);
	s->line_offsets = fsl_malloc(sizeof(off_t));
	if (s->line_offsets == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	s->nlines = 0;

	fout = tmpfile();
	if (fout == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "tmpfile");
		goto end;
	}
	if (s->f && fclose(s->f) == EOF) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fclose");
		goto end;
	}
	s->f = fout;

	rc = add_line_offset(&s->line_offsets, &s->nlines, 0);
	if (rc)
		goto end;

	/*
	 * We'll diff artifacts of type "ci" (i.e., "checkin") separately, as
	 * it's a different process to diff the others (wiki, technote, etc.).
	 */
	if (s->selected_entry->diff_type == FNC_DIFF_COMMIT &&
	    !s->selected_entry->changeset.used)
		rc = create_changeset(s->selected_entry);
	else if (s->selected_entry->diff_type == FNC_DIFF_BLOB)
		rc = diff_file_artifact(s, s->selected_entry->prid, NULL,
		    NULL, FSL_CKOUT_CHANGE_MOD);
	if (!rc && s->showmeta)
		rc = write_commit_meta(s);
	if (!rc && s->selected_entry->diff_type == FNC_DIFF_WIKI)
		rc = diff_non_checkin(s);
	if (rc)
		goto end;

	/*
	 * Delay assigning diff headline labels (i.e., diff id1 id2) till now
	 * because wiki parent commits are obtained in diff_non_checkin().
	 */
	if (s->selected_entry->puuid) {
		fsl_free(s->id1);
		s->id1 = fsl_strdup(s->selected_entry->puuid);
		if (s->id1 == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	} else
		s->id1 = NULL;	/* Initial commit, tag, technote, etc. */
	if (s->selected_entry->uuid) {
		fsl_free(s->id2);
		s->id2 = fsl_strdup(s->selected_entry->uuid);
		if (s->id2 == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	} else
		s->id2 = NULL;	/* Local work tree. */

	if (!s->showmeta) {
		s->index.offset = fsl_realloc(s->index.offset,
		    (s->index.n + 1) * sizeof(off_t));
		s->index.offset[s->index.n++] = 0;
	}

	/*
	 * Diff local changes on disk in the current checkout differently to
	 * checked-in versions: the former compares on disk file content with
	 * file artifacts; the latter compares file artifact blobs only.
	 */
	if (s->selected_entry->diff_type == FNC_DIFF_COMMIT)
		diff_commit(s);
	else if (s->selected_entry->diff_type == FNC_DIFF_CKOUT)
		diff_checkout(s);





	if (s->patch) {
		char *dflt = fsl_mprintf("path [%.10s.patch]: ", s->id2);
		struct input in = {NULL, dflt, INPUT_ALPHA, SR_CLREOL};
		fnc_prompt_input(s->parent_view ?
		    s->parent_view->child : NULL, &in);
		fsl_free(dflt);
		if (!in.buf[0]) {
			fsl_strlcpy(in.buf, s->id2, 11);
			fsl_strlcat(in.buf, ".patch", sizeof(in.buf));
		}
		s->patch = false;
		rc = fsl_buffer_to_filename(&s->buf, in.buf);
		if (rc)
			goto end;
	}










	/*
	 * Parse the diff buffer line-by-line to record byte offsets of each
	 * line for scrolling and searching in diff view.

	 */
	st0 = fsl_strdup(fsl_buffer_str(&s->buf));
	st = st0;
	off = (s->line_offsets)[s->nlines - 1];
	s->index.lineno = fsl_malloc(s->index.n * sizeof(size_t));
	while ((line = fnc_strsep(&st, "\n")) != NULL) {
		int lineno, n = fprintf(s->f, "%s\n", line);
		s->maxx = MAX(s->maxx, n);
		if (s->index.offset && idx < s->index.n &&
		    off == s->index.offset[idx]) {
			lineno = s->nlines + (idx ? 1 : 0);
			s->index.lineno[idx++] = lineno;
		}
		off += n;
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
		if (rc)
			goto end;









	}



	--s->nlines;  /* Don't count EOF '\n' */
end:
	fsl_free(st0);
	fsl_buffer_clear(&s->buf);
	if (s->f && fflush(s->f) != 0 && rc == 0)
		rc = RC(FSL_RC_IO, "%s", "fflush");










































































	return rc;
}

static int
create_changeset(struct fnc_commit_artifact *commit)
{
	fsl_cx		*const f = fcli_cx();







>

|

|




|




|



|


















|














|








|





|














>
>
>
>




|
<











>
>
>
>
>
>
>
>
>


|
>

<
<




|









>
>
>
>
>
>
>
>
>
|
>
>
>





|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973

4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998


4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
	char	*line, *st0 = NULL, *st = NULL;
	off_t	 off = 0;
	uint32_t idx = 0;
	int	 rc = 0;

	s->maxx = 0;

	free_index(&s->index);
	free(s->dlines);
	s->dlines = fsl_malloc(sizeof(enum line_type));
	if (s->dlines == NULL)
		return RC(FSL_RC_ERROR, "fsl_malloc");
	s->ndlines = 0;
	free(s->line_offsets);
	s->line_offsets = fsl_malloc(sizeof(off_t));
	if (s->line_offsets == NULL)
		return RC(FSL_RC_ERROR, "fsl_malloc");
	s->nlines = 0;

	fout = tmpfile();
	if (fout == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "tmpfile");
		goto end;
	}
	if (s->f && fclose(s->f) == EOF) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "fclose");
		goto end;
	}
	s->f = fout;

	rc = add_line_offset(&s->line_offsets, &s->nlines, 0);
	if (rc)
		goto end;

	/*
	 * We'll diff artifacts of type "ci" (i.e., "checkin") separately, as
	 * it's a different process to diff the others (wiki, technote, etc.).
	 */
	if (s->selected_entry->diff_type == FNC_DIFF_COMMIT &&
	    !s->selected_entry->changeset.used)
		rc = create_changeset(s->selected_entry);
	else if (s->selected_entry->diff_type == FNC_DIFF_BLOB)
		rc = diff_file_artifact(s, s->selected_entry->prid, NULL,
		    NULL, FSL_CKOUT_CHANGE_MOD);
	if (!rc && s->diff_mode == COMMIT_META)
		rc = write_commit_meta(s);
	if (!rc && s->selected_entry->diff_type == FNC_DIFF_WIKI)
		rc = diff_non_checkin(s);
	if (rc)
		goto end;

	/*
	 * Delay assigning diff headline labels (i.e., diff id1 id2) till now
	 * because wiki parent commits are obtained in diff_non_checkin().
	 */
	if (s->selected_entry->puuid) {
		fsl_free(s->id1);
		s->id1 = fsl_strdup(s->selected_entry->puuid);
		if (s->id1 == NULL) {
			rc = RC(FSL_RC_ERROR, "fsl_strdup");
			goto end;
		}
	} else
		s->id1 = NULL;	/* Initial commit, tag, technote, etc. */
	if (s->selected_entry->uuid) {
		fsl_free(s->id2);
		s->id2 = fsl_strdup(s->selected_entry->uuid);
		if (s->id2 == NULL) {
			rc = RC(FSL_RC_ERROR, "fsl_strdup");
			goto end;
		}
	} else
		s->id2 = NULL;	/* Local work tree. */

	if (s->diff_mode != COMMIT_META) {
		s->index.offset = fsl_realloc(s->index.offset,
		    (s->index.n + 1) * sizeof(off_t));
		s->index.offset[s->index.n++] = 0;
	}

	/*
	 * Diff local changes on disk in the current checkout differently to
	 * checked-in versions: the former compares on disk file content with
	 * file artifacts; the latter compares file artifact blobs only.
	 */
	if (s->selected_entry->diff_type == FNC_DIFF_COMMIT)
		diff_commit(s);
	else if (s->selected_entry->diff_type == FNC_DIFF_CKOUT)
		diff_checkout(s);

	rc = add_line_type(&s->dlines, &s->ndlines, LINE_BLANK);  /* eof \n */
	if (rc)
		goto end;

	if (s->patch) {
		char *dflt = fsl_mprintf("path [%.10s.patch]: ", s->id2);
		struct input in = {NULL, dflt, INPUT_ALPHA, SR_CLREOL};
		fnc_prompt_input(s->view, &in);

		fsl_free(dflt);
		if (!in.buf[0]) {
			fsl_strlcpy(in.buf, s->id2, 11);
			fsl_strlcat(in.buf, ".patch", sizeof(in.buf));
		}
		s->patch = false;
		rc = fsl_buffer_to_filename(&s->buf, in.buf);
		if (rc)
			goto end;
	}

	st0 = fsl_strdup(fsl_buffer_str(&s->buf));
	st = st0;

	if (s->stash) {
		/* Arrived here via fnc_stash(); make diffs and return */
		rc = make_stash_diff(s, st);
		goto end;
	}

	/*
	 * Parse the diff buffer line-by-line to record byte offsets of each
	 * line for scrolling and searching in diff view. And save line offsets
	 * of each file in the diff for C-n/p key maps.
	 */


	off = (s->line_offsets)[s->nlines - 1];
	s->index.lineno = fsl_malloc(s->index.n * sizeof(size_t));
	while ((line = fnc_strsep(&st, "\n")) != NULL) {
		int lineno, n = fprintf(s->f, "%s\n", line);
		s->maxx = MAX(s->maxx, n);	/* longest line for hscroll */
		if (s->index.offset && idx < s->index.n &&
		    off == s->index.offset[idx]) {
			lineno = s->nlines + (idx ? 1 : 0);
			s->index.lineno[idx++] = lineno;
		}
		off += n;
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
		if (rc)
			goto end;
		/* If in stash mode, save line offsets for each hunk. */
		if (s->diff_mode == STASH_INTERACTIVE &&
		    s->nlines < s->ndlines - 1 &&
		    s->dlines[s->nlines] == LINE_DIFF_CHUNK) {
			s->scx.hunk.lineno = fsl_realloc(s->scx.hunk.lineno,
			    (s->scx.hunk.n + 1) * sizeof(size_t));
			if (s->scx.hunk.lineno == NULL) {
				rc = RC(FSL_RC_ERROR, "realloc");
				goto end;
			}
			s->scx.hunk.lineno[s->scx.hunk.n++] = s->nlines;
		}
	}
	--s->nlines;  /* Don't count EOF '\n' */
end:
	fsl_free(st0);
	fsl_buffer_clear(&s->buf);
	if (s->f && fflush(s->f) != 0 && rc == 0)
		rc = RC(FSL_RC_IO, "fflush");
	return rc;
}

/*
 * Iterate lines in string st for each diff hunk line (i.e., @@ -w,x +y,z @@),
 * and write a patch file at $TMPDIR/fnc-XXXXXX-{stash,ckout}.diff corresponding
 * to the stash step identified by s->stash:
 *   1. HUNK_STASH: diff of all hunks selected to stash
 *   2. HUNK_CKOUT: diff of all hunks to be kept in the checkout
 */
static int
make_stash_diff(struct fnc_diff_view_state *s, char *st)
{
	FILE		*f = NULL;
	const char	*line, *tmpd;
	char		*pp, *pp0, *tmppath;
	size_t		 idx, lineno;
	int		 i, rc = FSL_RC_OK;
	bool		 drop;

	if ((tmpd = getenv("TMPDIR")) == NULL || *tmpd == '\0')
		tmpd = P_tmpdir;
	for (i = fsl_strlen(tmpd) - 1; i > 0 && tmpd[i] == '/'; i--)
		/* nop */;
	++i;

	/* Make temp files for stash and ckout patches. */
	if (s->stash == HUNK_STASH) {
		tmppath = fsl_mprintf("%.*s/fnc", i, tmpd);
		rc = fnc_open_tmpfile(&pp, &f, tmppath, "-stash.diff");
		pp0 = s->scx.patch[0];
	} else {
		tmppath = fsl_mprintf("%.*s/fnc", i, tmpd);
		rc = fnc_open_tmpfile(&pp, &f, tmppath, "-ckout.diff");
		pp0 = s->scx.patch[1];
	}
	fsl_free(tmppath);
	if (rc)
		return rc;

	fsl_strlcpy(pp0, pp, sizeof(s->scx.patch[0]));
	fsl_free(pp);

	lineno = 0;
	idx = 0;
	while (!rc && lineno < s->ndlines &&
	    (line = fnc_strsep(&st, "\n")) != NULL) {
		/*
		 * Write all index headers irrespective of whether the file has
		 * any selected hunks, otherwise we end up with orphaned hunks.
		 */
		if (s->dlines[lineno] == LINE_DIFF_INDEX ||
		    s->dlines[lineno] == LINE_DIFF_META)
			drop = false;
		if (s->dlines[lineno++] == LINE_DIFF_CHUNK) {
			/* Stash diff and hunk not marked for stash? Drop it. */
			if (s->stash == HUNK_STASH)
				drop = !BIT_CHK(s->scx.stash, idx) ?
				    true : false;
			else  /* ckout diff & hunk marked for stash? drop it */
				drop = BIT_CHK(s->scx.stash, idx) ?
				    true : false;
			++idx;
		}
		if (drop)
			continue;
		if (fprintf(f, "%s\n", line) < 0)
			rc = RC(FSL_RC_RANGE, "fprintf");
	}

	if (f && fflush(f) != 0)
		rc = RC(FSL_RC_IO, "fflush");
	fsl_fclose(f);

	return rc;
}

static int
create_changeset(struct fnc_commit_artifact *commit)
{
	fsl_cx		*const f = fcli_cx();
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
	    "(SELECT name FROM filename WHERE filename.fnid=mlink.pfnid) "
	    "FROM mlink JOIN filename ON filename.fnid=mlink.fnid "
	    "WHERE mlink.mid=%d AND NOT mlink.isaux "
	    "AND (mlink.fid > 0 "
	    "OR mlink.fnid NOT IN (SELECT pfnid FROM mlink WHERE mid=%d)) "
	    "ORDER BY name", commit->rid, commit->rid);
	if (rc)
		return RC(FSL_RC_DB, "%s", "fsl_cx_prepare");

	while ((rc = fsl_stmt_step(st)) == FSL_RC_STEP_ROW) {
		struct fsl_file_artifact *fdiff = NULL;
		const char *path, *oldpath, *olduuid, *uuid;
		/* TODO: Parse file mode to display in commit changeset. */
		/* int perm; */








|







5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
	    "(SELECT name FROM filename WHERE filename.fnid=mlink.pfnid) "
	    "FROM mlink JOIN filename ON filename.fnid=mlink.fnid "
	    "WHERE mlink.mid=%d AND NOT mlink.isaux "
	    "AND (mlink.fid > 0 "
	    "OR mlink.fnid NOT IN (SELECT pfnid FROM mlink WHERE mid=%d)) "
	    "ORDER BY name", commit->rid, commit->rid);
	if (rc)
		return RC(FSL_RC_DB, "fsl_cx_prepare");

	while ((rc = fsl_stmt_step(st)) == FSL_RC_STEP_ROW) {
		struct fsl_file_artifact *fdiff = NULL;
		const char *path, *oldpath, *olduuid, *uuid;
		/* TODO: Parse file mode to display in commit changeset. */
		/* int perm; */

4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804

4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840

4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867

4868
4869
4870
4871
4872
4873
4874
4875
4876

4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927

static int
write_commit_meta(struct fnc_diff_view_state *s)
{
	char		*line = NULL, *st0 = NULL, *st = NULL;
	fsl_size_t	 linelen, idx = 0;
	off_t		 off = 0;
	int		 rc = FSL_RC_OK, n = 7;  /* Min lines in commit meta */

	n += countlines(s->selected_entry->comment);
	n += s->selected_entry->changeset.used;
	rc = add_line_type(&s->dlines, LINE_DIFF_META, &s->ndlines, n, true);
	if (rc)
		goto end;

	if ((n = fprintf(s->f,"%s %s\n", s->selected_entry->type,
	    s->selected_entry->uuid)) < 0)
		goto end;
	off += n;
	rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;

	if ((n = fprintf(s->f,"user: %s\n", s->selected_entry->user)) < 0)
		goto end;
	off += n;
	rc = add_line_type(&s->dlines, LINE_DIFF_USER, &s->ndlines, 0, true);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;

	if ((n = fprintf(s->f,"tags: %s\n", s->selected_entry->branch ?
	    s->selected_entry->branch : "/dev/null")) < 0)
		goto end;
	off += n;
	rc = add_line_type(&s->dlines, LINE_DIFF_TAGS, &s->ndlines, 0, true);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;

	if ((n = fprintf(s->f,"date: %s\n",
	    s->selected_entry->timestamp)) < 0)
		goto end;
	off += n;
	rc = add_line_type(&s->dlines, LINE_DIFF_DATE, &s->ndlines, 0, true);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;


	fputc('\n', s->f);
	++off;
	rc = add_line_type(&s->dlines, LINE_BLANK, &s->ndlines, 0, true);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;

	st0 = fsl_strdup(s->selected_entry->comment);
	st = st0;
	if (st == NULL) {
		RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		goto end;
	}
	while ((line = fnc_strsep(&st, "\n")) != NULL) {
		linelen = fsl_strlen(line);
		if (linelen >= s->ncols) {
			rc = wrapline(line, s->ncols - LINENO_WIDTH, s, &off);
			if (rc)
				goto end;
		}
		else {
			if ((n = fprintf(s->f, "%s\n", line)) < 0)
				goto end;
			off += n;
			rc = add_line_type(&s->dlines, LINE_DIFF_COMMENT,
			    &s->ndlines, 0, true);
			if (!rc)
				rc = add_line_offset(&s->line_offsets,
				    &s->nlines, off);
			if (rc)
				goto end;

		}
	}


	fputc('\n', s->f);
	++off;
	rc = add_line_type(&s->dlines, LINE_BLANK, &s->ndlines, 0, true);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;

	if (s->selected_entry->diff_type == FNC_DIFF_WIKI)
		goto end;  /* No changeset for wiki commits. */

	for (idx = 0; idx < s->selected_entry->changeset.used; ++idx) {
		char				*changeline;
		struct fsl_file_artifact	*file_change;

		file_change = s->selected_entry->changeset.list[idx];

		switch (file_change->change) {
		case FSL_CKOUT_CHANGE_MOD:
			changeline = "[~] ";
			break;
		case FSL_CKOUT_CHANGE_ADDED:
			changeline = "[+] ";
			break;
		case FSL_CKOUT_CHANGE_RENAMED:
			changeline = fsl_mprintf("[>] %s -> ",
			   file_change->fc->priorName);

			break;
		case FSL_CKOUT_CHANGE_REMOVED:
			changeline = "[-] ";
			break;
		default:
			changeline = "[!] ";
			break;
		}
		if ((n = fprintf(s->f, "%s%s\n", changeline,

		    file_change->fc->name)) < 0)
			goto end;
		off += n;
		rc = add_line_type(&s->dlines, LINE_DIFF_META, &s->ndlines, 0,
		    true);
		if (!rc)
			rc = add_line_offset(&s->line_offsets, &s->nlines, off);
		if (rc)
			goto end;
	}

	/* Add blank line between end of changeset and diff. */
	fputc('\n', s->f);
	++off;
	rc = add_line_type(&s->dlines, LINE_BLANK, &s->ndlines, 0, true);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;
	s->index.offset = fsl_realloc(s->index.offset,
	    (s->index.n + 1) * sizeof(off_t));
	s->index.offset[s->index.n++] = off;
end:
	free(st0);
	free(line);
	if (rc) {
		free(*&s->line_offsets);
		s->line_offsets = NULL;
		s->nlines = 0;
	}
	return rc;
}

static int
countlines(const char *str)
{
	int n, idx;

	for (idx = 0, n = 1; str[idx]; ++idx)
		if (str[idx] == '\n')
			++n;

	return str[idx - 1] == '\n' ? n : ++n;
}

/*
 * Wrap long lines at the terminal's available column width. The caller
 * must ensure the limit parameter has taken into account whether the
 * screen is currently split, and not mistakenly pass in the curses COLS macro
 * without deducting the parent panel's width. This function doesn't break
 * words, and will wrap at the end of the last word that can wholly fit within







|

<
<
|














|









|









|





>


|








|













|
|









>


|









|












|

>








|
>
|


|
<









|


















|
|
|
|

|
|
|

|
|







5172
5173
5174
5175
5176
5177
5178
5179
5180


5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301

5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347

static int
write_commit_meta(struct fnc_diff_view_state *s)
{
	char		*line = NULL, *st0 = NULL, *st = NULL;
	fsl_size_t	 linelen, idx = 0;
	off_t		 off = 0;
	int		 n, rc = FSL_RC_OK;



	rc = add_line_type(&s->dlines, &s->ndlines, LINE_DIFF_META);
	if (rc)
		goto end;

	if ((n = fprintf(s->f,"%s %s\n", s->selected_entry->type,
	    s->selected_entry->uuid)) < 0)
		goto end;
	off += n;
	rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;

	if ((n = fprintf(s->f,"user: %s\n", s->selected_entry->user)) < 0)
		goto end;
	off += n;
	rc = add_line_type(&s->dlines, &s->ndlines, LINE_DIFF_USER);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;

	if ((n = fprintf(s->f,"tags: %s\n", s->selected_entry->branch ?
	    s->selected_entry->branch : "/dev/null")) < 0)
		goto end;
	off += n;
	rc = add_line_type(&s->dlines, &s->ndlines, LINE_DIFF_TAGS);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;

	if ((n = fprintf(s->f,"date: %s\n",
	    s->selected_entry->timestamp)) < 0)
		goto end;
	off += n;
	rc = add_line_type(&s->dlines, &s->ndlines, LINE_DIFF_DATE);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;

	/* Add blank line between end of commit metadata and comment. */
	fputc('\n', s->f);
	++off;
	rc = add_line_type(&s->dlines, &s->ndlines, LINE_BLANK);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;

	st0 = fsl_strdup(s->selected_entry->comment);
	st = st0;
	if (st == NULL) {
		RC(FSL_RC_ERROR, "fsl_strdup");
		goto end;
	}
	while ((line = fnc_strsep(&st, "\n")) != NULL) {
		linelen = fsl_strlen(line);
		if (linelen >= s->ncols) {
			rc = wrapline(line, s->ncols - LINENO_WIDTH, s, &off);
			if (rc)
				goto end;
		}
		else {
			if ((n = fprintf(s->f, "%s\n", line)) < 0)
				goto end;
			off += n;
			rc = add_line_type(&s->dlines, &s->ndlines,
			    LINE_DIFF_COMMENT);
			if (!rc)
				rc = add_line_offset(&s->line_offsets,
				    &s->nlines, off);
			if (rc)
				goto end;

		}
	}

	/* Add blank line between end of comment and changeset. */
	fputc('\n', s->f);
	++off;
	rc = add_line_type(&s->dlines, &s->ndlines, LINE_BLANK);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;

	if (s->selected_entry->diff_type == FNC_DIFF_WIKI)
		goto end;  /* No changeset for wiki commits. */

	for (idx = 0; idx < s->selected_entry->changeset.used; ++idx) {
		char				*changeline, *t = NULL;
		struct fsl_file_artifact	*file_change;

		file_change = s->selected_entry->changeset.list[idx];

		switch (file_change->change) {
		case FSL_CKOUT_CHANGE_MOD:
			changeline = "[~] ";
			break;
		case FSL_CKOUT_CHANGE_ADDED:
			changeline = "[+] ";
			break;
		case FSL_CKOUT_CHANGE_RENAMED:
			t = fsl_mprintf("[>] %s -> ",
			   file_change->fc->priorName);
			changeline = t;
			break;
		case FSL_CKOUT_CHANGE_REMOVED:
			changeline = "[-] ";
			break;
		default:
			changeline = "[!] ";
			break;
		}
		n = fprintf(s->f, "%s%s\n", changeline, file_change->fc->name);
		fsl_free(t);
		if (n < 0)
			goto end;
		off += n;
		rc = add_line_type(&s->dlines, &s->ndlines, LINE_DIFF_META);

		if (!rc)
			rc = add_line_offset(&s->line_offsets, &s->nlines, off);
		if (rc)
			goto end;
	}

	/* Add blank line between end of changeset and diff. */
	fputc('\n', s->f);
	++off;
	rc = add_line_type(&s->dlines, &s->ndlines, LINE_BLANK);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, off);
	if (rc)
		goto end;
	s->index.offset = fsl_realloc(s->index.offset,
	    (s->index.n + 1) * sizeof(off_t));
	s->index.offset[s->index.n++] = off;
end:
	free(st0);
	free(line);
	if (rc) {
		free(*&s->line_offsets);
		s->line_offsets = NULL;
		s->nlines = 0;
	}
	return rc;
}

/* static int */
/* countlines(const char *str) */
/* { */
/* 	int n, idx; */

/* 	for (idx = 0, n = 1; str[idx]; ++idx) */
/* 		if (str[idx] == '\n') */
/* 			++n; */

/* 	return str[idx - 1] == '\n' ? n : ++n; */
/* } */

/*
 * Wrap long lines at the terminal's available column width. The caller
 * must ensure the limit parameter has taken into account whether the
 * screen is currently split, and not mistakenly pass in the curses COLS macro
 * without deducting the parent panel's width. This function doesn't break
 * words, and will wrap at the end of the last word that can wholly fit within
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
	int		 n = 0, rc = 0;

	while ((word = fnc_strsep(&line, " ")) != NULL) {
		wordlen = fsl_strlen(word);
		if ((cursor + wordlen) >= limit) {
			fputc('\n', s->f);
			++(*off);
			rc = add_line_type(&s->dlines, LINE_DIFF_COMMENT,
			    &s->ndlines, 0, true);
			if (!rc)
				rc = add_line_offset(&s->line_offsets,
				    &s->nlines, *off);
			if (rc)
				return rc;
			cursor = 0;
		}
		if ((n  = fprintf(s->f, "%s ", word)) < 0)
			return rc;
		*off += n;
		cursor += n;
	}
	fputc('\n', s->f);
	++(*off);
	rc = add_line_type(&s->dlines, LINE_DIFF_COMMENT, &s->ndlines, 0, true);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, *off);

	return rc;
}

static int
add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
{
	off_t	*p;

	p = fsl_realloc(*line_offsets, (*nlines + 1) * sizeof(off_t));
	if (p == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_realloc");
	*line_offsets = p;
	(*line_offsets)[*nlines] = off;
	(*nlines)++;

	return 0;
}

static int
add_line_type(enum line_type **lines, enum line_type type, uint32_t *nlines,
    uint32_t alloc, bool incr)
{
	if (alloc) {
		enum line_type *p;
		p = fsl_realloc(*lines,
		    (*nlines + alloc) * sizeof(enum line_type *));
		if (p == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_realloc");
		*lines = p;
	}

	(*lines)[*nlines] = type;
	if (incr)
		(*nlines)++;

	return FSL_RC_OK;
}

/*
 * Fill the buffer with the differences between commit->uuid and commit->puuid.
 * commit->rid (to load into deck d2) is the *this* version, and commit->puuid
 * (to be loaded into deck d1) is the version we diff against. Step through the
 * deck of F(ile) cards from both versions to determine: (1) if we have new
 * files added (i.e., no F card counterpart in d1); (2) files deleted (i.e., no
 * F card counterpart in d2); (3) or otherwise the same file (i.e., F card







|
|














|









|



|







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400




















5401
5402
5403
5404
5405
5406
5407
	int		 n = 0, rc = 0;

	while ((word = fnc_strsep(&line, " ")) != NULL) {
		wordlen = fsl_strlen(word);
		if ((cursor + wordlen) >= limit) {
			fputc('\n', s->f);
			++(*off);
			rc = add_line_type(&s->dlines, &s->ndlines,
			    LINE_DIFF_COMMENT);
			if (!rc)
				rc = add_line_offset(&s->line_offsets,
				    &s->nlines, *off);
			if (rc)
				return rc;
			cursor = 0;
		}
		if ((n  = fprintf(s->f, "%s ", word)) < 0)
			return rc;
		*off += n;
		cursor += n;
	}
	fputc('\n', s->f);
	++(*off);
	rc = add_line_type(&s->dlines, &s->ndlines, LINE_DIFF_COMMENT);
	if (!rc)
		rc = add_line_offset(&s->line_offsets, &s->nlines, *off);

	return rc;
}

static int
add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
{
	off_t *p;

	p = fsl_realloc(*line_offsets, (*nlines + 1) * sizeof(off_t));
	if (p == NULL)
		return RC(FSL_RC_ERROR, "fsl_realloc");
	*line_offsets = p;
	(*line_offsets)[*nlines] = off;
	(*nlines)++;

	return 0;
}





















/*
 * Fill the buffer with the differences between commit->uuid and commit->puuid.
 * commit->rid (to load into deck d2) is the *this* version, and commit->puuid
 * (to be loaded into deck d1) is the version we diff against. Step through the
 * deck of F(ile) cards from both versions to determine: (1) if we have new
 * files added (i.e., no F card counterpart in d1); (2) files deleted (i.e., no
 * F card counterpart in d2); (3) or otherwise the same file (i.e., F card
5095
5096
5097
5098
5099
5100
5101
5102

5103
5104
5105
5106
5107
5108
5109
5110
5111





5112
5113
5114
5115
5116
5117
5118
			change = FSL_CKOUT_CHANGE_MOD;
			if (diff)
				rc = diff_file_artifact(s, id1, fc1, fc2,
				    change);
			fsl_deck_F_next(&d1, &fc1);
			fsl_deck_F_next(&d2, &fc2);
		}
		if (rc == FSL_RC_RANGE) {

			fsl_buffer_append(&s->buf,
			    "\nDiff has too many changes\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc == FSL_RC_DIFF_BINARY) {
			fsl_buffer_append(&s->buf,
			    "\nBinary files cannot be diffed\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);





		} else if (rc)
			goto end;
	}
end:
	fsl_deck_finalize(&d1);
	fsl_deck_finalize(&d2);
	return rc;







|
>
|
|
<
<
|
<

<

>
>
>
>
>







5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505


5506

5507

5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
			change = FSL_CKOUT_CHANGE_MOD;
			if (diff)
				rc = diff_file_artifact(s, id1, fc1, fc2,
				    change);
			fsl_deck_F_next(&d1, &fc1);
			fsl_deck_F_next(&d2, &fc2);
		}
		if (rc == FSL_RC_RANGE || rc == FSL_RC_DIFF_BINARY ||
		    rc == FSL_RC_TYPE) {
			fsl_buffer_append(&s->buf, rc == FSL_RC_RANGE ?
			    "\nDiff has too many changes\n" :


			    rc == FSL_RC_TYPE ? "\nNot a regular file\n" :

			    "\nBinary files cannot be diffed\n", -1);

			fsl_cx_err_reset(f);
			rc = add_line_type(&s->dlines, &s->ndlines,
			    LINE_DIFF_COMMENT);
			if (!rc)
				rc = add_line_type(&s->dlines, &s->ndlines,
				    LINE_BLANK);
		} else if (rc)
			goto end;
	}
end:
	fsl_deck_finalize(&d1);
	fsl_deck_finalize(&d2);
	return rc;
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177

5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193

5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204

5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216


5217
5218
5219
5220
5221
5222
5223
5224
	 * changes. Otherwise query the current checkout state for changes.
	 */
	if (vid != cid) {
		/* Keep vfile ckout state; but unload vid when finished. */
		rc = fsl_vfile_load(f, vid, false, NULL);
		if (rc)
			goto unload;
		fsl_buffer_appendf(&sql, "SELECT v2.pathname, v2.deleted, "
		    "v2.chnged, v2.rid == 0, v1.rid, v1.islink"
		    " FROM vfile v1, vfile v2"
		    " WHERE v1.pathname=v2.pathname AND v1.vid=%d AND v2.vid=%d"
		    " AND (v2.deleted OR v2.chnged OR v1.mrid != v2.rid)"
		    " UNION "
		    "SELECT pathname, 1, 0, 0, 0, islink"
		    " FROM vfile v1"
		    " WHERE v1.vid = %d"
		    " AND NOT EXISTS(SELECT 1 FROM vfile v2"
		    " WHERE v2.vid = %d AND v2.pathname = v1.pathname)"
		    " UNION "
		    "SELECT pathname, 0, 0, 1, 0, islink"
		    " FROM vfile v2"
		    " WHERE v2.vid = %d"
		    " AND NOT EXISTS(SELECT 1 FROM vfile v1"
		    " WHERE v1.vid = %d AND v1.pathname = v2.pathname)"
		    " ORDER BY 1", vid, cid, vid, cid, cid, vid);
	} else {
		fsl_buffer_appendf(&sql, "SELECT pathname, deleted, chnged, "
		    "rid == 0, rid, islink"
		    " FROM vfile"
		    " WHERE vid = %d"
		    " AND (deleted OR chnged OR rid == 0)"

		    " ORDER BY pathname", cid);
	}
	st = fsl_stmt_malloc();
	rc = fsl_cx_prepare(f, st, "%b", &sql);
	if (rc) {
		rc = RC(rc, "%s", "fsl_cx_prepare");
		goto yield;
	}

	while ((rc = fsl_stmt_step(st)) == FSL_RC_STEP_ROW) {
		const char	*path;
		int		 deleted, changed, added, fid, symlink;
		enum		 fsl_ckout_change_e change;
		bool		 diff = true;

		path = fsl_stmt_g_text(st, 0, NULL);

		deleted = fsl_stmt_g_int32(st, 1);
		changed = fsl_stmt_g_int32(st, 2);
		added = fsl_stmt_g_int32(st, 3);
		fid = fsl_stmt_g_int32(st, 4);
		symlink = fsl_stmt_g_int32(st, 5);
		rc = fsl_file_canonical_name2(f->ckout.dir, path, &abspath,
		    false);
		if (rc)
			goto yield;

		if (deleted)

			change = FSL_CKOUT_CHANGE_REMOVED;
		else if (fsl_file_access(fsl_buffer_cstr(&abspath), F_OK))
			change = FSL_CKOUT_CHANGE_MISSING;
		else if (added) {
			fid = 0;
			change = FSL_CKOUT_CHANGE_ADDED;
		} else if (changed == 3) {
			fid = 0;
			change = FSL_CKOUT_CHANGE_MERGE_ADD;
		} else if (changed == 5) {
			fid = 0;
			change = FSL_CKOUT_CHANGE_INTEGRATE_ADD;


		} else
			change = FSL_CKOUT_CHANGE_MOD;

		/*
		 * For changed files of which this checkout is already aware,
		 * grab their hash to make comparisons. For removed files, if
		 * diffing against a version other than the current checkout,
		 * load the version's manifest to parse for known versions of







|
|




|





|






|
|


|
>





|




|





>
|
|
|
|
|





|
>

|










>
>
|







5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
	 * changes. Otherwise query the current checkout state for changes.
	 */
	if (vid != cid) {
		/* Keep vfile ckout state; but unload vid when finished. */
		rc = fsl_vfile_load(f, vid, false, NULL);
		if (rc)
			goto unload;
		fsl_buffer_appendf(&sql, "SELECT v2.pathname, v2.origname, "
		    " v2.deleted, v2.chnged, v2.rid == 0, v1.rid, v1.islink"
		    " FROM vfile v1, vfile v2"
		    " WHERE v1.pathname=v2.pathname AND v1.vid=%d AND v2.vid=%d"
		    " AND (v2.deleted OR v2.chnged OR v1.mrid != v2.rid)"
		    " UNION "
		    "SELECT pathname, origname, 1, 0, 0, 0, islink"
		    " FROM vfile v1"
		    " WHERE v1.vid = %d"
		    " AND NOT EXISTS(SELECT 1 FROM vfile v2"
		    " WHERE v2.vid = %d AND v2.pathname = v1.pathname)"
		    " UNION "
		    "SELECT pathname, origname, 0, 0, 1, 0, islink"
		    " FROM vfile v2"
		    " WHERE v2.vid = %d"
		    " AND NOT EXISTS(SELECT 1 FROM vfile v1"
		    " WHERE v1.vid = %d AND v1.pathname = v2.pathname)"
		    " ORDER BY 1", vid, cid, vid, cid, cid, vid);
	} else {
		fsl_buffer_appendf(&sql, "SELECT pathname, origname, deleted, "
		    "chnged, rid == 0, rid, islink"
		    " FROM vfile"
		    " WHERE vid = %d"
		    " AND (deleted OR chnged OR rid==0"
		    "  OR (origname IS NOT NULL AND origname<>pathname))"
		    " ORDER BY pathname", cid);
	}
	st = fsl_stmt_malloc();
	rc = fsl_cx_prepare(f, st, "%b", &sql);
	if (rc) {
		rc = RC(rc, "fsl_cx_prepare");
		goto yield;
	}

	while ((rc = fsl_stmt_step(st)) == FSL_RC_STEP_ROW) {
		const char	*path, *ogpath;
		int		 deleted, changed, added, fid, symlink;
		enum		 fsl_ckout_change_e change;
		bool		 diff = true;

		path = fsl_stmt_g_text(st, 0, NULL);
		ogpath = fsl_stmt_g_text(st, 1, NULL);
		deleted = fsl_stmt_g_int32(st, 2);
		changed = fsl_stmt_g_int32(st, 3);
		added = fsl_stmt_g_int32(st, 4);
		fid = fsl_stmt_g_int32(st, 5);
		symlink = fsl_stmt_g_int32(st, 6);
		rc = fsl_file_canonical_name2(f->ckout.dir, path, &abspath,
		    false);
		if (rc)
			goto yield;

		if (deleted) {
			ogpath = path;
			change = FSL_CKOUT_CHANGE_REMOVED;
		} else if (fsl_file_access(fsl_buffer_cstr(&abspath), F_OK))
			change = FSL_CKOUT_CHANGE_MISSING;
		else if (added) {
			fid = 0;
			change = FSL_CKOUT_CHANGE_ADDED;
		} else if (changed == 3) {
			fid = 0;
			change = FSL_CKOUT_CHANGE_MERGE_ADD;
		} else if (changed == 5) {
			fid = 0;
			change = FSL_CKOUT_CHANGE_INTEGRATE_ADD;
		} else if (fsl_strcmp(ogpath, path))
			change = FSL_CKOUT_CHANGE_RENAMED;
		else
			change = FSL_CKOUT_CHANGE_MOD;

		/*
		 * For changed files of which this checkout is already aware,
		 * grab their hash to make comparisons. For removed files, if
		 * diffing against a version other than the current checkout,
		 * load the version's manifest to parse for known versions of
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264






5265
5266
5267
5268
5269
5270
5271
			if (rc)
				goto yield;
			do {
				fsl_deck_F_next(&d, &cf);
				if (cf && !fsl_strcmp(cf->name, path)) {
					xminus = fsl_strdup(cf->uuid);
					if (xminus == NULL) {
						RC(FSL_RC_ERROR, "%s",
						    "fsl_strdup");
						goto yield;
					}
					fid = fsl_uuid_to_rid(f, xminus);
					break;
				}
			} while (cf);
			fsl_deck_finalize(&d);
		}
		if (!xminus)
			xminus = fsl_strdup(NULL_DEVICE);
		allow_symlinks = fsl_config_get_bool(f, FSL_CONFDB_REPO, false,
		    "allow-symlinks");
		if (!symlink != !(fsl_is_symlink(fsl_buffer_cstr(&abspath)) &&
		    allow_symlinks)) {
			rc = write_diff_meta(s, path, xminus, path, NULL_DEVICE,
			    change);
			fsl_buffer_append(&s->buf,
			    "\nSymbolic links cannot be diffed\n", -1);






			if (rc)
				goto yield;
			continue;
		}
		if (fid > 0 && change != FSL_CKOUT_CHANGE_ADDED) {
			rc = fsl_content_get(f, fid, &bminus);
			if (rc)







|
<


















>
>
>
>
>
>







5645
5646
5647
5648
5649
5650
5651
5652

5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
			if (rc)
				goto yield;
			do {
				fsl_deck_F_next(&d, &cf);
				if (cf && !fsl_strcmp(cf->name, path)) {
					xminus = fsl_strdup(cf->uuid);
					if (xminus == NULL) {
						RC(FSL_RC_ERROR, "fsl_strdup");

						goto yield;
					}
					fid = fsl_uuid_to_rid(f, xminus);
					break;
				}
			} while (cf);
			fsl_deck_finalize(&d);
		}
		if (!xminus)
			xminus = fsl_strdup(NULL_DEVICE);
		allow_symlinks = fsl_config_get_bool(f, FSL_CONFDB_REPO, false,
		    "allow-symlinks");
		if (!symlink != !(fsl_is_symlink(fsl_buffer_cstr(&abspath)) &&
		    allow_symlinks)) {
			rc = write_diff_meta(s, path, xminus, path, NULL_DEVICE,
			    change);
			fsl_buffer_append(&s->buf,
			    "\nSymbolic links cannot be diffed\n", -1);
			if (!rc)
				rc = add_line_type(&s->dlines, &s->ndlines,
				    LINE_DIFF_COMMENT);
			if (!rc)
				rc = add_line_type(&s->dlines, &s->ndlines,
				    LINE_BLANK);
			if (rc)
				goto yield;
			continue;
		}
		if (fid > 0 && change != FSL_CKOUT_CHANGE_ADDED) {
			rc = fsl_content_get(f, fid, &bminus);
			if (rc)
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292

5293
5294
5295
5296
5297
5298
5299
5300
5301





5302
5303
5304
5305
5306
5307
5308
				if (!fsl_strncmp(pe->path, path, pe->pathlen)
				    || !fsl_strcmp(pe->path, path)) {
					diff = true;
					break;
				}
		}
		if (diff)
			rc = diff_file(s, &bminus, path, xminus,
			    fsl_buffer_cstr(&abspath), change);
		fsl_buffer_reuse(&bminus);
		fsl_buffer_reuse(&abspath);
		fsl_free(xminus);
		xminus = NULL;
		if (rc == FSL_RC_RANGE) {

			fsl_buffer_append(&s->buf,
			    "\nDiff has too many changes\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc == FSL_RC_DIFF_BINARY) {
			fsl_buffer_append(&s->buf,
			    "\nBinary files cannot be diffed\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);





		} else if (rc)
			goto yield;
	}

yield:
	fsl_stmt_finalize(st);
	fsl_free(xminus);







|





|
>
|
|
<
<
|
<

<

>
>
>
>
>







5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707


5708

5709

5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
				if (!fsl_strncmp(pe->path, path, pe->pathlen)
				    || !fsl_strcmp(pe->path, path)) {
					diff = true;
					break;
				}
		}
		if (diff)
			rc = diff_file(s, &bminus, ogpath, path, xminus,
			    fsl_buffer_cstr(&abspath), change);
		fsl_buffer_reuse(&bminus);
		fsl_buffer_reuse(&abspath);
		fsl_free(xminus);
		xminus = NULL;
		if (rc == FSL_RC_RANGE || rc == FSL_RC_DIFF_BINARY ||
		    rc == FSL_RC_TYPE) {
			fsl_buffer_append(&s->buf, rc == FSL_RC_RANGE ?
			    "\nDiff has too many changes\n" :


			    rc == FSL_RC_TYPE ? "\nNot a regular file\n" :

			    "\nBinary files cannot be diffed\n", -1);

			fsl_cx_err_reset(f);
			rc = add_line_type(&s->dlines, &s->ndlines,
			    LINE_DIFF_COMMENT);
			if (!rc)
				rc = add_line_type(&s->dlines, &s->ndlines,
				    LINE_BLANK);
		} else if (rc)
			goto yield;
	}

yield:
	fsl_stmt_finalize(st);
	fsl_free(xminus);
5357
5358
5359
5360
5361
5362
5363


5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375












5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
	case FSL_CKOUT_CHANGE_MOD:
		/* FALL THROUGH */
	default:
		minus = xminus;
		plus = xplus;
		break;
	}



	if FLAG_CHK(s->diff_flags, FNC_DIFF_INVERT) {
		const char *tmp = minus;
		minus = plus;
		plus = tmp;
		tmp = zminus;
		zminus = zplus;
		zplus = tmp;
	}

	if (!FLAG_CHK(s->diff_flags, FNC_DIFF_BRIEF)) {
		int c, i;












		for (c = 0, i = 10; !rc && i < 14; ++c) {
			rc = add_line_type(&s->dlines, (enum line_type)i,
			    &s->ndlines, (!c ? 6 : 0), true);
			i += (c > 3 || c % 2) ? 1 : 0;
		}
		if (!rc)
			rc = fsl_buffer_appendf(&s->buf, "%sIndex: %s\n%.71c\n",
			    s->buf.used ? "\n" : "", index, '=');
		if (!rc)
			rc = fsl_buffer_appendf(&s->buf,
			    "hash - %s\nhash + %s\n", minus, plus);
		if (!rc)
			rc = fsl_buffer_appendf(&s->buf, "--- %s\n+++ %s\n",
			    zminus, zplus);
	}







>
>











|
>
>
>
>
>
>
>
>
>
>
>
>

|
<



|
|







5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805

5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
	case FSL_CKOUT_CHANGE_MOD:
		/* FALL THROUGH */
	default:
		minus = xminus;
		plus = xplus;
		break;
	}

	zminus = zminus ? zminus : zplus;

	if FLAG_CHK(s->diff_flags, FNC_DIFF_INVERT) {
		const char *tmp = minus;
		minus = plus;
		plus = tmp;
		tmp = zminus;
		zminus = zplus;
		zplus = tmp;
	}

	if (!FLAG_CHK(s->diff_flags, FNC_DIFF_BRIEF)) {
		int c;
		enum line_type i;

		if (s->buf.used) {
			/*
			 * There're previous files in the diff--I don't like
			 * Git's contiguous lines between files--so add a new
			 * line before this file's 'Index: file/path' line.
			 */
			rc = add_line_type(&s->dlines, &s->ndlines, LINE_BLANK);
			if (!rc)
				rc = fsl_buffer_append(&s->buf, "\n", 1);
		}
		for (c = 0, i = 10; !rc && i < 14; ++c) {
			rc = add_line_type(&s->dlines, &s->ndlines, i);

			i += (c > 3 || c % 2) ? 1 : 0;
		}
		if (!rc)
			rc = fsl_buffer_appendf(&s->buf, "Index: %s\n%.71c\n",
			    index, '=');
		if (!rc)
			rc = fsl_buffer_appendf(&s->buf,
			    "hash - %s\nhash + %s\n", minus, plus);
		if (!rc)
			rc = fsl_buffer_appendf(&s->buf, "--- %s\n+++ %s\n",
			    zminus, zplus);
	}
5401
5402
5403
5404
5405
5406
5407
5408

5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
 *   xminus   hex UUID containing the SHA{1,3} hash of the file named zminus
 *   abspath  absolute path to the file on disk being diffed
 *   change   enum denoting the versioning change of the file
 * diff_flags, context, and sbs are the same parameters as diff_file_artifact()
 */
static int
diff_file(struct fnc_diff_view_state *s, fsl_buffer *bminus, const char *zminus,
    fsl_uuid_str xminus, const char *abspath, enum fsl_ckout_change_e change)

{
	fsl_cx		*const f = fcli_cx();
	fsl_buffer	 bplus = fsl_buffer_empty;
	fsl_buffer	 xplus = fsl_buffer_empty;
	const char	*zplus = NULL;
	int		 rc = 0;

	/*
	 * If it exists, read content of abspath to diff EXCEPT for the content
	 * of 'fossil rm FILE' files because they will either: (1) have the same
	 * content as the versioned file's blob in bminus or (2) have changes.
	 * As a result, the upcoming call to fsl_diff_text_to_buffer() _will_







|
>




<







5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840

5841
5842
5843
5844
5845
5846
5847
 *   xminus   hex UUID containing the SHA{1,3} hash of the file named zminus
 *   abspath  absolute path to the file on disk being diffed
 *   change   enum denoting the versioning change of the file
 * diff_flags, context, and sbs are the same parameters as diff_file_artifact()
 */
static int
diff_file(struct fnc_diff_view_state *s, fsl_buffer *bminus, const char *zminus,
    const char *zplus, fsl_uuid_str xminus, const char *abspath,
    enum fsl_ckout_change_e change)
{
	fsl_cx		*const f = fcli_cx();
	fsl_buffer	 bplus = fsl_buffer_empty;
	fsl_buffer	 xplus = fsl_buffer_empty;

	int		 rc = 0;

	/*
	 * If it exists, read content of abspath to diff EXCEPT for the content
	 * of 'fossil rm FILE' files because they will either: (1) have the same
	 * content as the versioned file's blob in bminus or (2) have changes.
	 * As a result, the upcoming call to fsl_diff_text_to_buffer() _will_
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
		 * removed file with 'fossil diff -v' output—remove the above
		 * 'if (change != FSL_CKOUT_CHANGE_REMOVED)' from the else
		 * condition and uncomment the following three lines of code.
		 */
		/* if (change == FSL_CKOUT_CHANGE_REMOVED && */
		/*     !fsl_buffer_compare(bminus, &bplus)) */
		/*	fsl_buffer_clear(&bplus); */
		zplus = zminus;
	}

	switch (fsl_strlen(xminus)) {
	case FSL_STRLEN_K256:
		rc = fsl_sha3sum_buffer(&bplus, &xplus);
		break;
	case FSL_STRLEN_SHA1:







<







5862
5863
5864
5865
5866
5867
5868

5869
5870
5871
5872
5873
5874
5875
		 * removed file with 'fossil diff -v' output—remove the above
		 * 'if (change != FSL_CKOUT_CHANGE_REMOVED)' from the else
		 * condition and uncomment the following three lines of code.
		 */
		/* if (change == FSL_CKOUT_CHANGE_REMOVED && */
		/*     !fsl_buffer_compare(bminus, &bplus)) */
		/*	fsl_buffer_clear(&bplus); */

	}

	switch (fsl_strlen(xminus)) {
	case FSL_STRLEN_K256:
		rc = fsl_sha3sum_buffer(&bplus, &xplus);
		break;
	case FSL_STRLEN_SHA1:
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
			    zminus);
	} else if (FLAG_CHK(s->diff_flags, FNC_DIFF_VERBOSE) ||
	    (bminus->used && bplus.used))
		rc = fnc_diff_text_to_buffer(bminus, &bplus, &s->buf,
		    &s->dlines, &s->ndlines, s->context, s->sbs,
		    s->diff_flags);
end:
	rc = add_line_type(&s->dlines, LINE_BLANK, &s->ndlines, 0, true);
	fsl_buffer_clear(&bplus);
	fsl_buffer_clear(&xplus);
	return rc;
}

/*
 * Parse the deck of non-checkin commits to present a 'fossil ui' equivalent







<







5914
5915
5916
5917
5918
5919
5920

5921
5922
5923
5924
5925
5926
5927
			    zminus);
	} else if (FLAG_CHK(s->diff_flags, FNC_DIFF_VERBOSE) ||
	    (bminus->used && bplus.used))
		rc = fnc_diff_text_to_buffer(bminus, &bplus, &s->buf,
		    &s->dlines, &s->ndlines, s->context, s->sbs,
		    s->diff_flags);
end:

	fsl_buffer_clear(&bplus);
	fsl_buffer_clear(&xplus);
	return rc;
}

/*
 * Parse the deck of non-checkin commits to present a 'fossil ui' equivalent
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
	fsl_id_t	 prid = 0;
	fsl_size_t	 idx;
	int		 rc = 0;

	fsl_deck *d = NULL;
	d = fsl_deck_malloc();
	if (d == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_deck_malloc");

	fsl_deck_init(f, d, FSL_SATYPE_ANY);
	rc = fsl_deck_load_rid(f, d, s->selected_entry->rid, FSL_SATYPE_ANY);
	if (rc)
		goto end;

	/*
	 * Present ticket commits as a series of field: value tuples as per
	 * the Fossil UI /info/UUID view.
	 */
	if (d->type == FSL_SATYPE_TICKET) {
		for (idx = 0; idx < d->J.used; ++idx) {
			fsl_card_J *ticket = d->J.list[idx];
			bool icom = !fsl_strncmp(ticket->field, "icom", 4);
			fsl_buffer_appendf(&s->buf, "%d. %s:%s%s%c\n", idx + 1,
			    ticket->field, icom ? "\n\n" : " ", ticket->value,
			    icom ? '\n' : ' ');
		}
		goto end;
	}

	if (d->type == FSL_SATYPE_CONTROL) {
		for (idx = 0; idx < d->T.used; ++idx) {
			fsl_card_T *ctl = d->T.list[idx];
			fsl_buffer_appendf(&s->buf, "Tag %d ", idx + 1);
			switch (ctl->type) {
			case FSL_TAGTYPE_CANCEL:
				fsl_buffer_append(&s->buf, "[CANCEL]", -1);
				break;
			case FSL_TAGTYPE_ADD:
				fsl_buffer_append(&s->buf, "[ADD]", -1);
				break;







|














|









|







5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
	fsl_id_t	 prid = 0;
	fsl_size_t	 idx;
	int		 rc = 0;

	fsl_deck *d = NULL;
	d = fsl_deck_malloc();
	if (d == NULL)
		return RC(FSL_RC_ERROR, "fsl_deck_malloc");

	fsl_deck_init(f, d, FSL_SATYPE_ANY);
	rc = fsl_deck_load_rid(f, d, s->selected_entry->rid, FSL_SATYPE_ANY);
	if (rc)
		goto end;

	/*
	 * Present ticket commits as a series of field: value tuples as per
	 * the Fossil UI /info/UUID view.
	 */
	if (d->type == FSL_SATYPE_TICKET) {
		for (idx = 0; idx < d->J.used; ++idx) {
			fsl_card_J *ticket = d->J.list[idx];
			bool icom = !fsl_strncmp(ticket->field, "icom", 4);
			fsl_buffer_appendf(&s->buf, "%llu. %s:%s%s%c\n", idx + 1,
			    ticket->field, icom ? "\n\n" : " ", ticket->value,
			    icom ? '\n' : ' ');
		}
		goto end;
	}

	if (d->type == FSL_SATYPE_CONTROL) {
		for (idx = 0; idx < d->T.used; ++idx) {
			fsl_card_T *ctl = d->T.list[idx];
			fsl_buffer_appendf(&s->buf, "Tag %llu ", idx + 1);
			switch (ctl->type) {
			case FSL_TAGTYPE_CANCEL:
				fsl_buffer_append(&s->buf, "[CANCEL]", -1);
				break;
			case FSL_TAGTYPE_ADD:
				fsl_buffer_append(&s->buf, "[ADD]", -1);
				break;
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
		if (rc == FSL_RC_STEP_ROW) {
			rc = 0;
			zminus0 = fsl_strdup(fsl_stmt_g_text(&stmt, 0, NULL));
			zminus = zminus0;
		} else if (rc == FSL_RC_STEP_DONE)
			rc = 0;
		else if (rc) {
			rc = RC(rc, "%s", "fsl_stmt_step");
			goto end;
		}
		xminus0 = fsl_rid_to_uuid(f, vid1);
		xminus = xminus0;
		fsl_stmt_finalize(&stmt);
		fsl_content_get(f, vid1, &fbuf1);
	}







|







6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
		if (rc == FSL_RC_STEP_ROW) {
			rc = 0;
			zminus0 = fsl_strdup(fsl_stmt_g_text(&stmt, 0, NULL));
			zminus = zminus0;
		} else if (rc == FSL_RC_STEP_DONE)
			rc = 0;
		else if (rc) {
			rc = RC(rc, "fsl_stmt_step");
			goto end;
		}
		xminus0 = fsl_rid_to_uuid(f, vid1);
		xminus = xminus0;
		fsl_stmt_finalize(&stmt);
		fsl_content_get(f, vid1, &fbuf1);
	}
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
		if (rc == FSL_RC_STEP_ROW) {
			rc = 0;
			zplus0 = fsl_strdup(fsl_stmt_g_text(&stmt, 0, NULL));
			zplus = zplus0;
		} else if (rc == FSL_RC_STEP_DONE)
			rc = 0;
		else if (rc) {
			rc = RC(rc, "%s", "fsl_stmt_step");
			goto end;
		}
		xplus0 = fsl_rid_to_uuid(f, vid2);
		xplus = xplus0;
		fsl_stmt_finalize(&stmt);
		fsl_content_get(f, vid2, &fbuf2);
	}







|







6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
		if (rc == FSL_RC_STEP_ROW) {
			rc = 0;
			zplus0 = fsl_strdup(fsl_stmt_g_text(&stmt, 0, NULL));
			zplus = zplus0;
		} else if (rc == FSL_RC_STEP_DONE)
			rc = 0;
		else if (rc) {
			rc = RC(rc, "fsl_stmt_step");
			goto end;
		}
		xplus0 = fsl_rid_to_uuid(f, vid2);
		xplus = xplus0;
		fsl_stmt_finalize(&stmt);
		fsl_content_get(f, vid2, &fbuf2);
	}
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795

5796
5797
5798
5799
5800

5801

5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
		    s->diff_flags);
	if (rc)
		RC(rc, "%s: fnc_diff_text_to_buffer\n"
		    " -> %s [%s]\n -> %s [%s]", fsl_rc_cstr(rc),
		    a ? a->name : NULL_DEVICE, a ? a->uuid : NULL_DEVICE,
		    b ? b->name : NULL_DEVICE, b ? b->uuid : NULL_DEVICE);
end:
	rc = add_line_type(&s->dlines, LINE_BLANK, &s->ndlines, 0, true);
	fsl_free(zminus0);
	fsl_free(zplus0);
	fsl_free(xminus0);
	fsl_free(xplus0);
	fsl_buffer_clear(&fbuf1);
	fsl_buffer_clear(&fbuf2);
	return rc;
}

static int
show_diff(struct fnc_view *view)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	char				*headln, *id2, *id1 = NULL;

	/* Some diffs (e.g., technote, tag) have no parent hash to display. */
	id1 = fsl_strdup(s->id1 ? s->id1 : "/dev/null");
	if (id1 == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");

	/*
	 * If diffing the work tree, we have no hash to display for it.
	 * XXX Display "work tree" or "checkout" or "/dev/null" for clarity?
	 */
	id2 = fsl_strdup(s->id2 ? s->id2 : "");
	if (id2 == NULL) {
		fsl_free(id1);
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	}

	if ((headln = fsl_mprintf("diff %.40s %.40s", id1, id2)) == NULL) {
		fsl_free(id1);
		fsl_free(id2);
		return RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
	}

	fsl_free(id1);
	fsl_free(id2);
	return write_diff(view, headln);
}

static int
write_diff(struct fnc_view *view, char *headln)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	regmatch_t			*regmatch = &view->regmatch;
	struct fnc_colour		*c = NULL;
	wchar_t				*wcstr;
	char				*line;
	size_t				 linesz = 0;
	ssize_t				 linelen;
	off_t				 line_offset;
	attr_t				 rx = A_BOLD;
	int				 col, wstrlen, max_lines = view->nlines;
	int				 nlines = s->nlines;
	int				 nprinted = 0, rc = FSL_RC_OK;
	bool				 selected;

	s->lineno = s->first_line_onscreen - 1;
	line_offset = s->line_offsets[s->first_line_onscreen - 1];
	if (fseeko(s->f, line_offset, SEEK_SET))
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "fseeko");

	werase(view->window);

	if (headln) {
		static char	pct[MAX_PCT_LEN];
		double		percent;
		int		ln, pctlen;

		ln = s->gtl ? s->gtl : s->lineno + s->selected_line;
		percent = 100.00 * ln / nlines;
		pctlen = snprintf(pct, MAX_PCT_LEN, "%.*lf%%",
		    percent > 99.99 ? 0 : 2, percent);
		if (pctlen < 0)

			return RC(FSL_RC_RANGE, "%s", "snprintf");

		line = fsl_mprintf("[%d/%d] %s", ln, nlines, headln);
		if (line == NULL)
			return RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0, false);
		fsl_free(line);
		fsl_free(headln);
		if (rc)
			return rc;

		if (screen_is_shared(view) || view->active)







<


















|








|





|















|











|







>




|
>
|
>


|







6144
6145
6146
6147
6148
6149
6150

6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
		    s->diff_flags);
	if (rc)
		RC(rc, "%s: fnc_diff_text_to_buffer\n"
		    " -> %s [%s]\n -> %s [%s]", fsl_rc_cstr(rc),
		    a ? a->name : NULL_DEVICE, a ? a->uuid : NULL_DEVICE,
		    b ? b->name : NULL_DEVICE, b ? b->uuid : NULL_DEVICE);
end:

	fsl_free(zminus0);
	fsl_free(zplus0);
	fsl_free(xminus0);
	fsl_free(xplus0);
	fsl_buffer_clear(&fbuf1);
	fsl_buffer_clear(&fbuf2);
	return rc;
}

static int
show_diff(struct fnc_view *view)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	char				*headln, *id2, *id1 = NULL;

	/* Some diffs (e.g., technote, tag) have no parent hash to display. */
	id1 = fsl_strdup(s->id1 ? s->id1 : "/dev/null");
	if (id1 == NULL)
		return RC(FSL_RC_ERROR, "fsl_strdup");

	/*
	 * If diffing the work tree, we have no hash to display for it.
	 * XXX Display "work tree" or "checkout" or "/dev/null" for clarity?
	 */
	id2 = fsl_strdup(s->id2 ? s->id2 : "");
	if (id2 == NULL) {
		fsl_free(id1);
		return RC(FSL_RC_ERROR, "fsl_strdup");
	}

	if ((headln = fsl_mprintf("diff %.40s %.40s", id1, id2)) == NULL) {
		fsl_free(id1);
		fsl_free(id2);
		return RC(FSL_RC_RANGE, "fsl_mprintf");
	}

	fsl_free(id1);
	fsl_free(id2);
	return write_diff(view, headln);
}

static int
write_diff(struct fnc_view *view, char *headln)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	regmatch_t			*regmatch = &view->regmatch;
	struct fnc_colour		*c = NULL;
	wchar_t				*wcstr;
	char				*line;
	size_t				 lidx, linesz = 0;
	ssize_t				 linelen;
	off_t				 line_offset;
	attr_t				 rx = A_BOLD;
	int				 col, wstrlen, max_lines = view->nlines;
	int				 nlines = s->nlines;
	int				 nprinted = 0, rc = FSL_RC_OK;
	bool				 selected;

	s->lineno = s->first_line_onscreen - 1;
	line_offset = s->line_offsets[s->first_line_onscreen - 1];
	if (fseeko(s->f, line_offset, SEEK_SET))
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "fseeko");

	werase(view->window);

	if (headln) {
		static char	pct[MAX_PCT_LEN];
		double		percent;
		int		ln, pctlen;

		ln = s->gtl ? s->gtl : s->lineno + s->selected_line;
		percent = 100.00 * ln / nlines;
		pctlen = snprintf(pct, MAX_PCT_LEN, "%.*lf%%",
		    percent > 99.99 ? 0 : 2, percent);
		if (pctlen < 0 || pctlen >= MAX_PCT_LEN)
			return RC(fsl_errno_to_rc(errno, FSL_RC_RANGE),
			    "snprintf");

		line = fsl_mprintf("[%d/%d] %s", ln, nlines, headln);
		if (line == NULL)
			return RC(FSL_RC_RANGE, "fsl_mprintf");
		rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0, false);
		fsl_free(line);
		fsl_free(headln);
		if (rc)
			return rc;

		if (screen_is_shared(view) || view->active)
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850

5851
5852
5853
5854
5855




5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
		if (linelen == -1) {
			if (feof(s->f)) {
				s->eof = true;
				break;
			}
			fsl_free(line);
			RC(ferror(s->f) ? fsl_errno_to_rc(errno, FSL_RC_IO) :
			    FSL_RC_IO, "%s", "getline");
			return rc;
		}

		if (++s->lineno < s->first_line_onscreen)
			continue;
		if (s->gtl)
			if (!gotoline(view, &s->lineno, &nprinted))
				continue;

		rx = 0;

		if ((selected = nprinted == s->selected_line - 1))
			rx = A_BOLD | A_REVERSE;
		if (s->showln)
			col = draw_lineno(view, nlines, s->lineno, rx);





		if (s->colour)
			c = FLAG_CHK(s->diff_flags, FNC_DIFF_SIDEBYSIDE) ?
			    get_colour(&s->colours, s->dlines[s->lineno - 1]) :
			    match_colour(&s->colours, line);
		if (c && !(selected && s->sline == SLINE_MONO))
			rx |= COLOR_PAIR(c->scheme);
		if (c || selected)
			wattron(view->window, rx);

		if (s->first_line_onscreen + nprinted == s->matched_line &&
		    regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {







|










>





>
>
>
>

<
|
|







6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288

6289
6290
6291
6292
6293
6294
6295
6296
6297
		if (linelen == -1) {
			if (feof(s->f)) {
				s->eof = true;
				break;
			}
			fsl_free(line);
			RC(ferror(s->f) ? fsl_errno_to_rc(errno, FSL_RC_IO) :
			    FSL_RC_IO, "getline");
			return rc;
		}

		if (++s->lineno < s->first_line_onscreen)
			continue;
		if (s->gtl)
			if (!gotoline(view, &s->lineno, &nprinted))
				continue;

		rx = 0;
		lidx = s->lineno - 1;
		if ((selected = nprinted == s->selected_line - 1))
			rx = A_BOLD | A_REVERSE;
		if (s->showln)
			col = draw_lineno(view, nlines, s->lineno, rx);

		if (s->diff_mode == STASH_INTERACTIVE &&
		    s->scx.hunk.lineno[s->scx.hunk.idx] == lidx)
			rx = A_REVERSE;  /* highlight current hunk to stash */

		if (s->colour)

			c = get_colour(&s->colours,
			    s->dlines[MIN(s->ndlines - 1, lidx)]);
		if (c && !(selected && s->sline == SLINE_MONO))
			rx |= COLOR_PAIR(c->scheme);
		if (c || selected)
			wattron(view->window, rx);

		if (s->first_line_onscreen + nprinted == s->matched_line &&
		    regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
		while (!s->eof && i++ < nscroll) {
			linelen = getline(&line, &linesz, s->f);
			++s->first_line_onscreen;
			if (linelen == -1) {
				if (!feof(s->f))
					return RC(ferror(s->f) ?
					    fsl_errno_to_rc(errno, FSL_RC_IO) :
					    FSL_RC_IO, "%s", "getline");
				if (s->selected_line > nscroll)
					s->selected_line = view->nlines - 2;
				else
					s->selected_line = nscroll;
				s->eof = true;
				break;
			}







|







6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
		while (!s->eof && i++ < nscroll) {
			linelen = getline(&line, &linesz, s->f);
			++s->first_line_onscreen;
			if (linelen == -1) {
				if (!feof(s->f))
					return RC(ferror(s->f) ?
					    fsl_errno_to_rc(errno, FSL_RC_IO) :
					    FSL_RC_IO, "getline");
				if (s->selected_line > nscroll)
					s->selected_line = view->nlines - 2;
				else
					s->selected_line = nscroll;
				s->eof = true;
				break;
			}
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
	case 'b': {
		int start_col = 0;
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		branch_view = view_open(view->nlines, view->ncols,
		    view->start_ln, start_col, FNC_VIEW_BRANCH);
		if (branch_view == NULL)
			return RC(FSL_RC_ERROR, "%s", "view_open");
		rc = open_branch_view(branch_view, BRANCH_LS_OPEN_CLOSED, NULL,
		    0, 0);
		if (rc) {
			view_close(branch_view);
			return rc;
		}
		view->active = false;







|







6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
	case 'b': {
		int start_col = 0;
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		branch_view = view_open(view->nlines, view->ncols,
		    view->start_ln, start_col, FNC_VIEW_BRANCH);
		if (branch_view == NULL)
			return RC(FSL_RC_ERROR, "view_open");
		rc = open_branch_view(branch_view, BRANCH_LS_OPEN_CLOSED, NULL,
		    0, 0);
		if (rc) {
			view_close(branch_view);
			return rc;
		}
		view->active = false;
6365
6366
6367
6368
6369
6370
6371





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
		/* FALL THROUGH */
	default:
		break;
	}

	return rc;
}






























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































static int
reset_diff_view(struct fnc_view *view, bool stay)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	int				 n, rc = FSL_RC_OK;

	n = s->nlines;
	free_index(&s->index);
	fsl_free(s->dlines);
	s->dlines = NULL;
	s->ndlines = 0;
	show_diff_status(view);
	rc = create_diff(s);
	if (rc)
		return rc;

	if (stay) {
		float scale = (float)s->first_line_onscreen / n;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








<
<
<
<







6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887




8888
8889
8890
8891
8892
8893
8894
		/* FALL THROUGH */
	default:
		break;
	}

	return rc;
}

static int
f__stash_get(bool pop)
{
	fsl_cx	*const f = fcli_cx();
	fsl_db	*db = fsl_needs_ckout(f);
	fsl_stmt q = fsl_stmt_empty;
	int	 nadded, stashid, vid, rc0, rc = FSL_RC_OK;
	uint32_t cc = 0;

	stashid = fsl_db_g_int32(db, 0, "SELECT max(stashid) FROM stash");
	if (!stashid) {
		f_out(">> empty stash");
		return rc;
	}

	vid = f->ckout.rid;

	rc = fsl_db_prepare(db, &q, "SELECT blob.rid, isRemoved, isExec,"
	    "  isLink, origname, newname, delta FROM stashfile, blob"
	    " WHERE stashid=%d AND blob.uuid=stashfile.hash UNION ALL"
	    "  SELECT 0, isRemoved, isExec, isLink, origname, newname, delta"
	    "  FROM stashfile WHERE stashid=%d AND stashfile.hash IS NULL",
	    stashid, stashid);
	if (rc)
		return RC(rc, "fsl_db_prepare");
	fsl_db_exec_multi(db,
	    "CREATE TEMP TABLE sfile(pathname TEXT PRIMARY KEY %s)",
	    fsl_cx_filename_collation(f));
	if (rc)
		return RC(rc, "fsl_db_exec_multi");

	while (fsl_stmt_step(&q) == FSL_RC_STEP_ROW) {
		fsl_buffer	 delta = fsl_buffer_empty;
		const void	*blob = NULL;
		const char	*ogname = fsl_stmt_g_text(&q, 4, NULL);
		const char	*name = fsl_stmt_g_text(&q, 5, NULL);
		int		 rid = fsl_stmt_g_int32(&q, 0);
		int		 removed = fsl_stmt_g_int32(&q, 1);
		int		 exec = fsl_stmt_g_int32(&q, 2);
		int		 link = fsl_stmt_g_int32(&q, 3);
		char		*ogpath = fsl_mprintf("%s%s", CKOUTDIR, ogname);
		char		*path = fsl_mprintf("%s%s", CKOUTDIR, name);
		fsl_size_t	 len = 0;

		if (!rid) {	/* new file */
			rc = fsl_db_exec_multi(db,
			    "INSERT OR IGNORE INTO sfile(pathname) VALUES(%Q)",
			    name);
			if (!rc)
				rc = fsl_stmt_get_blob(&q, 6, &blob, &len);
			fsl_buffer_external(&delta, blob, len);
			if (!rc)
				rc = fsl_buffer_to_filename(&delta, path);
			if (!rc)
				rc = fsl_file_exec_set(path, exec);
			if (rc) {
				rc = RC(rc, "new file: %s", name);
				goto clear_delta;
			}
		} else if (removed) {
			fsl_ckout_unmanage_opt opt =
			    fsl_ckout_unmanage_opt_empty;
			opt.scanForChanges = false;
			opt.vfileIds = NULL;
			opt.relativeToCwd = false;
			opt.callback = stash_get_rm_cb;
			opt.callbackState = NULL;
			opt.filename = ogname;
			rc = fsl_ckout_unmanage(f, &opt);
			if (rc) {
				rc = RC(rc, "fsl_ckout_unmanage(%s)", ogname);
				goto clear_delta;
			}
			/*
			 * XXX Unlike fossil(1), we don't want to rm the file
			 * from disk because removal has not been committed,
			 * only stashed. We've unmanaged it, let the user rm it.
			 */
			/* fsl_file_unlink(ogpath); */
		} else if (fsl__ckout_safe_file_check(f, path))
			/* nop--ignore unsafe path */;
		else {
			fsl_buffer	a, b, out, disk;
			fsl_error	err;
			int		newlink = fsl_is_symlink(ogpath);

			a = b = out = disk = fsl_buffer_empty;

			rc = fsl_stmt_get_blob(&q, 6, &blob, &len);
			fsl_buffer_external(&delta, blob, len);
			if (rc) {
				rc = RC(rc, "fsl_stmt_get_blob");
				goto clear_delta;
			}
			rc = fsl_buffer_fill_from_filename(&disk, ogpath);
			if (rc == FSL_RC_NOT_FOUND)
				rc = fsl_buffer_fill_from_filename(&disk, path);
			if (rc) {
				rc = RC(rc, "fsl_buffer_fill_from_filename(%s)",
				    ogpath);
				goto clear_file;
			}
			rc = fsl_content_get(f, rid, &a);
			if (rc) {
				rc = RC(rc, "fsl_content_get(%d)", rid);
				goto clear_file;
			}
			rc = fsl_buffer_delta_apply2(&a, &delta, &b, &err);
			if (rc) {
				rc = RC(err.code, "%s",
				    fsl_buffer_cstr(&err.msg));
				goto clear_file;
			}

			if (link == newlink && !fsl_buffer_compare(&disk, &a)) {
				if (link || newlink)
					rc = fsl_file_unlink(path);
				if (!rc && link) {
					bool linkit = fsl_config_get_bool(f,
					    FSL_CONFDB_REPO, false,
					    "allow-symlinks");
					rc = fsl_symlink_create(
					    fsl_buffer_cstr(&b), path, linkit);
					f_out("[>] %s  -> %s\n",
					    fsl_buffer_cstr(&b), name);
				} else if (!rc)
					rc = fsl_buffer_to_filename(&b, path);
				if (!rc)
					rc = fsl_file_exec_set(path, exec);
				if (rc) {
					rc = RC(rc, "update file: %s", name);
					goto clear_file;
				}
				if (ogname && fsl_strcmp(ogname, name))
					f_out("[>] %s  ->  %s\n", ogname, name);
				else
					f_out("[u] %s\n", name);
			} else {
				bool lnk = false;
				if (link || newlink) {
					lnk = true;
					fsl_buffer_clear(&b);
					/* f_out(">> cannot merge symlink %s\n", name); */
				} else {
					rc = fsl_buffer_merge3(&a, &disk, &b,
					    &out, &cc);
					if (!rc)
						rc = fsl_buffer_to_filename(&out,
						    path);
					if (!rc)
						rc = fsl_file_exec_set(path,
						    exec);
					if (rc) {
						rc = RC(rc, "merge file: %s",
						    path);
						goto clear_file;
					}
				}
				if (cc)
					f_out("[!] %s  -> %u "
					    "merge conflict(s)\n", name, cc);
				else if (lnk)
					f_out("[!] %s  -> symlink\n", name);
				else if (ogname && fsl_strcmp(ogname, name))
					f_out("[~] %s  ->  %s\n", ogname, name);
				else
					f_out("[~] %s\n", name);
			}
clear_file:
			fsl_buffer_clear(&a);
			fsl_buffer_clear(&b);
			fsl_buffer_clear(&out);
			fsl_buffer_clear(&disk);
			if (rc)
				goto clear_delta;
		}
clear_delta:
		fsl_buffer_clear(&delta);
		if (!rc && fsl_strcmp(ogname, name)) {
			fsl_file_unlink(ogpath);
			if (rc)
				rc = RC(rc, "fsl_file_unlink(%s)", ogpath);
			rc = rc ? rc : fsl_db_exec_multi(db,
			    "UPDATE vfile SET pathname='%q', origname='%q'"
			    " WHERE pathname='%q' %s AND vid=%d", name, ogname,
			    ogname, fsl_cx_filename_collation(f), vid);
		}
		fsl_free(path);
		fsl_free(ogpath);
		if (rc)
			break;
	}
	if (!rc)
		rc = f__add_files_in_sfile(&nadded, vid);
	rc0 = fsl_stmt_finalize(&q);
	rc = rc ? rc : rc0;

	if (cc)
		f_out("\n>> merge conflict(s): %u\n", cc);

	if (pop) {
		rc = fsl_db_exec_multi(db, "DELETE FROM stash WHERE stashid=%d;"
		    "DELETE FROM stashfile WHERE stashid=%d;",
		    stashid, stashid);
	}
	return rc;
}

static int
f__add_files_in_sfile(int *nadded, int vid)
{
	fsl_cx	*const f = fcli_cx();
	fsl_db	*db = fsl_needs_ckout(f);
	int	 rc0, rc = FSL_RC_OK;
	fsl_stmt loop = fsl_stmt_empty;  /* SQL to loop over all files to add */

	rc = fsl_db_prepare(db, &loop,
	    "SELECT pathname FROM sfile"
	    " WHERE pathname NOT IN"
	    "  (SELECT sfile.pathname FROM vfile, sfile"
	    "   WHERE vfile.islink AND NOT vfile.deleted"
	    "   AND sfile.pathname>(vfile.pathname||'/')"
	    "   AND sfile.pathname<(vfile.pathname||'0'))"
	    " ORDER BY pathname");
	if (rc)
		return RC(rc, "fsl_db_prepare");

	while (!rc && fsl_stmt_step(&loop) == FSL_RC_STEP_ROW) {
		fsl_ckout_manage_opt opt = fsl_ckout_manage_opt_empty;
		const char *add = fsl_stmt_g_text(&loop, 0, NULL);
		if (!fsl_strcmp(add, REPODB))
			continue;
		if (fsl_is_reserved_fn(add, -1))
			continue;
		opt.filename = add;
		opt.relativeToCwd = false;  /* abs repo paths from fnc diff */
		opt.checkIgnoreGlobs = true;  /* XXX make an 'fnc stash' opt */
		opt.callback = stash_get_add_cb;
		rc = fsl_ckout_manage(f, &opt);
		*nadded += opt.counts.added;
	}

	rc0 = fsl_stmt_finalize(&loop);
	return rc ? RC(rc, "fsl_ckout_manage") : rc0;
}

static int
stash_get_rm_cb(fsl_ckout_unmanage_state const *st)
{
	f_out("[-] %s\n", st->filename);
	return FSL_RC_OK;
}

static int
stash_get_add_cb(fsl_ckout_manage_state const *cms, bool *include)
{
	*include = true;
	f_out("[+] %s\n", cms->filename);
	return FSL_RC_OK;
}

/*
 * Get hunks selected to stash from the user and make two patch(1) files:
 * (1) diff of all hunks selected to stash; and (2) diff of all hunks to be
 * kept in the checkout. Then revert the checkout and use patch files to:
 *   1. apply patch of hunks selected to stash
 *   2. stash (and revert) checkout
 *   3. apply patch of hunks that were not selected to stash
 * This produces a ckout with only those changes that were not selected
 * to stash, achieving the same function as 'git add -p'. The user can
 * now test the code, commit, then run 'fnc stash pop' and repeat.
 */
static int
fnc_stash(struct fnc_view *view)
{
	struct fnc_diff_view_state	 *s = &view->state.diff;
	struct stash_cx			 *scx = &s->scx;
	struct input			  in;
	char				 *msg = NULL, *prompt = NULL;
	int				  rc = FSL_RC_OK;

	scx->stash = alloc_bitstring(scx->hunk.n);
	if (scx->stash == NULL)
		return RC(FSL_RC_ERROR, "calloc");

	rc = select_hunks(view);  /* get hunks to stash */
	if (rc)
		goto end;

	/* Use default stash msg of "fnc stash CKOUT-HASH" if not provided. */
	msg = fsl_mprintf("fnc stash %.11s", s->id2);
	prompt = fsl_mprintf("stash message [%s]: ", msg);
	in = (struct input){NULL, prompt, INPUT_ALPHA, SR_CLREOL};
	rc = fnc_prompt_input(view, &in);
	if (in.buf[0]) {
		fsl_free(msg);
		msg = fsl_mprintf("%s", in.buf);
	}
	if (rc) {
		rc = RC(rc, "fnc_prompt_input");
		goto end;
	}

	s->stash = HUNK_STASH;  /* make patch of hunks selected to stash */
	rc = create_diff(s);
	s->stash = HUNK_CKOUT;  /* make patch of hunks to keep in ckout */
	if (!rc)
		rc = create_diff(s);
	if (rc)
		goto end;

	endwin();  /* restore tty so we can report progress to stdout */

	/* Clean ckout to apply patches; vfile already scanned in cmd_stash() */
	rc = revert_ckout(true, false);
	if (rc) {
		rc = RC(rc, "revert_ckout");
		goto end;
	}

	/* XXX With revert_ckout() finished, we can drop privileges further. */
	rc = init_unveil(((const char *[]){"/usr/bin/patch", "fossil"}),
	    ((const char *[]){"rx", "rx"}), 2, true);
	if (rc)
		goto end;

	scx->pcx.context = s->context;
	scx->pcx.report = true;  /* report files with changes stashed */
	rc = fnc_patch(&scx->pcx, scx->patch[0]);  /* (1) apply stash patch */
	scx->pcx.report = false; /* don't report changes kept in ckout */
	if (!rc) {
		/* fnc_execp((const char *const []) */
		/*     {"fossil", "stash", "save", "-m", msg, (char *)NULL}, 10); */
		rc = f__stash_create(msg, fcli_cx()->ckout.rid);  /* (2) */
		if (!rc)
			rc = revert_ckout(false, false);
	}
	if (!rc)
		rc = fnc_patch(&scx->pcx, scx->patch[1]);  /* (3) ckout patch */
	rc = (rc == NO_PATCH ? FSL_RC_OK : rc);
end:
	fsl_free(scx->stash);
	fsl_free(scx->hunk.lineno);
	fsl_free(msg);
	fsl_free(prompt);
	return rc;
}

/*
 * Allocate, zero, and return an unsigned char pointer of enough bytes
 * to store n bits, which must eventually be disposed of by the caller.
 */
static unsigned char *
alloc_bitstring(size_t n)
{
	size_t		 idx;
	unsigned char	*bs;

	bs = (unsigned char *)calloc((size_t)nbytes(n), sizeof(unsigned char));

	for (idx = 0; bs && idx < n; ++idx)
		BIT_CLR(bs, idx);

	return bs;
}

static int
select_hunks(struct fnc_view *view)
{
	int	rc = FSL_RC_OK;
	bool	stashing = false;

	rc = stash_input_handler(view, &stashing);

	if (!rc && !stashing)
		rc = RC(FSL_RC_BREAK, "No hunks selected to stash, "
		    "checkout state unchanged.");

	return rc;
}

/*
 * Iterate each hunk of changes in the local checkout, and prompt the user
 * for their choice with: "stash this hunk (b,m,y,n,a,k,A,K,?)? [y]"
 *   b - scroll back (only available if hunk occupies previous page)
 *   m - show more (only available if hunk occupies following page)
 *   y - stash this hunk (default choice if [return] is pressed)
 *   n - do not stash this hunk
 *   a - stash this hunk and all remaining hunks in the _file_
 *   k - do not stash this hunk nor any remaining hunks in the _file_
 *   A - stash this hunk and all remaining hunks in the _diff_
 *   K - do not stash this hunk nor any remaining hunks in the _diff_
 *   ? - display stash help dialog box
 * Key maps in the stash help dialog:
 *   q - quit the help
 *   Q - exit help and quit fnc stash _discarding_ any selections
 * XXX This input handling and the set_choice() code is tricky!
 */
static int
stash_input_handler(struct fnc_view *view, bool *stashing)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	struct index			*hunks;
	struct input			 in;
	size_t				 last, nxt = 0, nf = 0;
	uint32_t			*nh;
	int				 hl, rc = FSL_RC_OK;
	enum stash_opt			 choice = NO_CHOICE;
	bool				 lastfile = false;

	hunks = &s->scx.hunk;
	nh = &hunks->idx;
	in = (struct input){NULL, NULL, INPUT_ALPHA, SR_CLREOL, "X"};

	/* Iterate hunks and prompt user to stash or keep in ckout. */
	while (!rc && *nh < hunks->n) {
		char	**ans = NULL;
		char	  prompt[64];
		int	  len;
		enum { NONE, DOWN, UP, BOTH } scroll;
		/*
		 * If not yet in the last file of the diff and the next hunk
		 * to choose is in the next file, reset any sticky file choice.
		 */
		if (!lastfile && nxt && hunks->lineno[*nh] >= nxt) {
			nxt = 0;
			*in.buf = 'X';
			choice = NO_CHOICE;
		}

		/*
		 * Place hunk header, or file Index line if showing the
		 * first hunk in the file, at the top of the screen.
		 */
		s->first_line_onscreen = hunks->lineno[*nh] + 1;
		if (s->dlines[hunks->lineno[*nh] - 5] == LINE_DIFF_INDEX)
			s->first_line_onscreen = hunks->lineno[*nh] - 5;
		s->selected_line = 1;
		hl = s->first_line_onscreen;  /* current hunk start line */
redraw:
		rc = view->show(view);
		if (rc)
			return rc;
		updatescreen(view->window, true, true);
		keypad(view->window, false);  /* don't accept arrow keys */

		last = s->last_line_onscreen;
		len = snprintf(prompt, sizeof(prompt),
		    "[%u/%u] stash this hunk (", hunks->idx + 1, hunks->n);
		if (len < 0 || (len > 0 && (size_t)len >= sizeof(prompt)))
			return RC(fsl_errno_to_rc(errno, FSL_RC_RANGE),
			    "snprintf");
		scroll = NONE;

		/* Enable 'b,m' answers if hunk occupies multiple pages. */
		if (s->first_line_onscreen > hl)
			scroll = UP;
		if ((*nh < hunks->n - 1 && ((nf == s->index.n - 1 &&
		    hunks->lineno[*nh] >= s->index.lineno[nf] + 5) ||
		    last < s->index.lineno[nf]) &&
		    last < hunks->lineno[*nh + 1]) ||
		    (*nh == hunks->n - 1 && last < s->nlines))
			scroll = scroll ? BOTH : DOWN;

		rc = generate_prompt(&ans, prompt, sizeof(prompt), scroll);
		if (rc) {
			free_answers(ans);
			return RC(rc, "generate_prompt(%s)", STRINGIFY(scroll));
		}
		in.prompt = prompt;

		do {
			if (choice || valid_input(in.buf, ans))
				break;  /* ongoing persistent answer */

			rc = fnc_prompt_input(view, &in);

			if (*in.buf == '?' || *in.buf == 'H' ||
			    (int)*in.buf == (KEY_F(1)))
				rc = stash_help(view, scroll);

		} while (!rc && !choice && !valid_input(in.buf, ans));

		free_answers(ans);
		if (*in.buf == 'm' || *in.buf == 'b') {	 /* scroll pgup/pgdn */
			s->first_line_onscreen = *in.buf == 'm' ?
			    s->last_line_onscreen :
			    MAX(hl, s->first_line_onscreen - view->nlines + 2);
			*in.buf = 'X';
			goto redraw;
		}

		set_choice(s, stashing, &in, hunks, nh, &nxt, &nf, &lastfile,
		    &choice);
	}
	return rc;
}

/*
 * Construct a set of valid answers based on scroll and assign to *ptr, and
 * generate the corresponding prompt containing the available answers from
 * which to choose. *ptr must eventually be disposed of by the caller.
 */
static int
generate_prompt(char ***ptr, char *prompt, size_t sz, short scroll)
{
	char	**ans;
	char	 *opts[10] = {"b", "m", "y", "n", "a", "k", "A", "K", "", NULL};
	size_t	  n, oi, ai = 0;

	/* Set valid answers. */
	switch (scroll) {
		case 3:			/* BOTH  "bmynakAK?" */
		oi = 0;
		n = 10;
		break;
		case 2:			/* UP  "bynakAK?" */
		opts[0] = "m";
		opts[1] = "b";
		/* FALL THROUGH */
	case 1:				/* DOWN  "mynakAK?" */
		oi = 1;
		n = 9;
		break;
	case 0:				/* NONE  "ynakAK?" */
		oi = 2;
		n = 8;
		break;
	}

	/* Generate valid answers array. */
	ans = calloc(n, sizeof(*ans));
	if (ans == NULL)
		return RC(FSL_RC_ERROR, "calloc");
	while (ai < n)
		ans[ai++] = fsl_strdup(opts[oi++]);

	/* Generate prompt string. */
	for (ai = 0; ai < n - 2; ++ai) {
		char *t = fsl_mprintf("%s%c", ans[ai], ',');
		if (t == NULL)
			return RC(FSL_RC_ERROR, "fsl_mprintf");
		if (fsl_strlcat(prompt, t, sz) >= sz)
			return RC(FSL_RC_RANGE, "fsl_strlcat(%s, %s, %lu)",
			    prompt, t, sz);
		fsl_free(t);
	}
	if (fsl_strlcat(prompt, "?)? [y] ", sz) >= sz)
		return RC(FSL_RC_RANGE, "fsl_strlcat(%s, %s, %lu)",
		    prompt, "?)? [y] ", sz);

	*ptr = ans;
	return FSL_RC_OK;;
}

/*
 * Return true if in is found in valid, else return false.
 * valid must be terminated with a sentinel (NULL) pointer.
 */
static bool
valid_input(const char *in, char **valid)
{
	size_t idx;

	for (idx = 0; valid[idx]; ++idx)
		if (!fsl_strcmp(in, valid[idx]))
			return true;

	return false;
}

/*
 * Set or clear the corresponding bit in bitstring s->scx.stash based on the
 * answer in in.buf. If a persistent choice was made, assign it to *ch. Advance
 * next file *nf in relation to next hunk *nh, and assign next file start line
 * to *nxt. If the current file is the last file, set *lastfile. Advance *nh.
 */
static void
set_choice(struct fnc_diff_view_state *s, bool *stashing, struct input *in,
    struct index *hunks, uint32_t *nh, size_t *nxt, size_t *nf, bool *lastfile,
    enum stash_opt *ch)
{
	struct index	*files;
	unsigned char	*bs;

	files = &s->index;
	bs = s->scx.stash;

	/* Update bitstring based on ongoing persistent or single hunk choice */
	if (*in->buf != 'n' && *in->buf != 'k' && *in->buf != 'K') {
		BIT_SET(bs, *nh);  /* stash hunk */
		*stashing = true;
	} else  /* 'n' 'k' 'K' */
		BIT_CLR(bs, *nh);  /* keep hunk in ckout */

	/* Check for a new persistent choice. */
	if (*in->buf == 'a')
		*ch = STASH_FILE;
	else if (*in->buf == 'k')
		*ch = KEEP_FILE;
	else if (*in->buf == 'A')
		*ch = STASH_DIFF;
	else if (*in->buf == 'K')
		*ch = KEEP_DIFF;
	if (!*ch)
		*in->buf = 'X';  /* no persistent choice; reset */

	/* We're in the last file, so any persistent choice can stick */
	if (*nf == files->n - 1 && hunks->lineno[*nh] >= files->lineno[*nf])
		*lastfile = true;

	if ((*ch == STASH_FILE || *ch == KEEP_FILE) &&
	    *in->buf != 'y' && *in->buf != 'n') {
		*nxt = files->lineno[MIN(*nf + (*nf ? 0 : 1), files->n - 1)] + 5;
		*in->buf = *ch == STASH_FILE ? 'y': 'n';
	}

	/* Update next file in relation to the next hunk. */
	while (*nf < files->n - 1 && *nh < hunks->n - 1 &&
	    files->lineno[*nf] + 5 <= hunks->lineno[*nh + 1])
		++(*nf);

	++(*nh);
}

static void
free_answers(char **ans)
{
	size_t i = 0;

	while (ans[i])
		fsl_free(ans[i++]);
	fsl_free(ans);
}

/*
 * Revert the current checkout. If renames is set, don't revert files that are
 * renamed with _no_ changes. If scan is set, scan for changes before reverting.
 */
static int
revert_ckout(bool renames, bool scan)
{
	fsl_cx			*const f = fcli_cx();
	fsl_db			*db = fsl_needs_ckout(f);
	fsl_stmt		 q = fsl_stmt_empty;
	fsl_ckout_revert_opt	 opt = fsl_ckout_revert_opt_empty;
	fsl_id_bag		 idbag = fsl_id_bag_empty;
	int			 rc = FSL_RC_OK;

	rc = fsl_ckout_vfile_ids(fcli.f, 0, &idbag, ".", false, true);

	if (!rc && renames) {
		/*
		 * XXX Don't revert renamed files with _NO_ changes because
		 * we need to stash them, but there's no way to apply them
		 * with a diff as there's no hunks; however, we can apply our
		 * stash patch to the checkout with renames in the vfile.
		 */
		rc = fsl_db_prepare(db, &q, "SELECT id, origname, pathname"
		    " FROM vfile WHERE origname IS NOT NULL"
		    " AND origname<>pathname AND chnged=0");
		if (!rc)
			rc = fsl_stmt_each(&q, rm_vfile_renames_cb, &idbag);
		fsl_stmt_finalize(&q);
	}

	opt.scanForChanges = scan;
	opt.filename = NULL;
	opt.callback = NULL;
	opt.callbackState = NULL;
	opt.vfileIds = &idbag;
	if (!rc)
		rc = fsl_ckout_revert(fcli_cx(), &opt);

	fsl_id_bag_clear(&idbag);
	return rc;
}

static int
rm_vfile_renames_cb(fsl_stmt *stmt, void *state)
{
	fsl_id_bag *bag = (fsl_id_bag *)state;
	const char *ogname = fsl_stmt_g_text(stmt, 1, NULL);
	const char *name = fsl_stmt_g_text(stmt, 2, NULL);
	fsl_id_t id = fsl_stmt_g_id(stmt, 0);

	fsl_id_bag_remove(bag, id);
	f_out("[s>] %s  ->  %s\n", ogname, name);

	return FSL_RC_OK;
}

/*
 * Scan patch(1) file found at path for valid patches, and populate patch
 * context pcx with an fnc_patch_file queue of all diffed files, each
 * containing an fnc_patch_hunk queue representing the file's changes. Iterate
 * the file queue and apply each fnc_patch_file to the checkout.
 */
static int
fnc_patch(struct patch_cx *pcx, const char *path)
{
	struct fnc_patch_file	*patch, *t;
	FILE			*fp;
	int			 fd, rc = FSL_RC_OK;

	fd = open(path, O_RDONLY | O_CLOEXEC);
	if (fd == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_IO), "open(%s)", path);

	if ((fp = fdopen(fd, "r")) == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_IO), "fdopen");

	pcx->report_cb = patch_reporter;
	STAILQ_INIT(&pcx->head);   /* queue of files to be patched */
	rc = scan_patch(pcx, fp);  /* read patch file to construct patch ADTs */
	fclose(fp);
	close(fd);
	if (rc)
		return rc;

	STAILQ_FOREACH_SAFE(patch, &pcx->head, entries, t) {
		pcx->pf = patch;
		rc = apply_patch(pcx, patch, false);
		STAILQ_REMOVE(&pcx->head, patch, fnc_patch_file, entries);
		free_patch(patch);
		if (rc)
			break;
	}

	return rc;
}

/*
 * Scan patch file fp to construct an fnc_patch_file pf for each versioned
 * file found with changes, and queue them in pcx->head. Parse each pf for
 * valid hunks, and queue them in pf->head to produce a hierarchical ADT of
 * files->hunks->lines to be patched.
 */
static int
scan_patch(struct patch_cx *pcx, FILE *fp)
{
	int	rc = FSL_RC_OK;
	bool	eof = false, patch_found = false;

	while (!feof(fp)) {
		struct fnc_patch_file *pf = NULL;
		rc = find_patch_file(&pf, pcx, fp);
		if (rc) {
			fsl_free(pf);
			goto end;
		}

		STAILQ_INIT(&pf->head);  /* queue of hunks per file to patch */
		patch_found = true;
		for (;;) {
			struct fnc_patch_hunk *h = NULL;
			rc = parse_hunk(&h, fp, pcx->context, &eof);
			if (rc)
				goto end;
			if (h)
				STAILQ_INSERT_TAIL(&pf->head, h, entries);
			if (eof) {
				STAILQ_INSERT_TAIL(&pcx->head, pf, entries);
				break;
			}
		}
	}
end:
	if (rc == NO_PATCH && patch_found)
		rc = FSL_RC_OK;  /* ignore valid case of index with no hunks */
	return rc;
}

/*
 * Find the next versioned file in patch(1) file fp by parsing the path from
 * the diff ---/+++ header line. If found, construct and assign a new
 * fnc_patch_file to *ptr, which must eventually be disposed of by the caller.
 */
static int
find_patch_file(struct fnc_patch_file **ptr, struct patch_cx *pcx, FILE *fp)
{
	struct fnc_patch_file	*pf = NULL;
	char			*old = NULL, *new = NULL;
	char			*line = NULL;
	size_t			 linesize = 0;
	ssize_t			 linelen;
	int			 create, rc = FSL_RC_OK;

	pf = calloc(1, sizeof(*pf));
	if (pf == NULL)
		return RC(FSL_RC_ERROR, "fsl_malloc");

	while ((linelen = getline(&line, &linesize, fp)) != -1) {
		if (!strncmp(line, "--- ", 4)) {
			fsl_free(old);
			rc = parse_filename(line + 4, &old, 0);
		} else if (!strncmp(line, "+++ ", 4)) {
			fsl_free(new);
			rc = parse_filename(line + 4, &new, 0);
		}

		if (rc)
			break;

		if (!strncmp(line, "@@ -", 4)) {
			create = !fsl_strncmp(line + 4, "0,0", 3);
			if ((old == NULL && new == NULL) ||
			    (!create && old == NULL))
				rc = PATCH_MALFORMED;
			else
				rc = set_patch_paths(pf, old, new);

			if (rc)
				break;

			/* Rewind to previous line. */
			if (fseek(fp, linelen * -1, SEEK_CUR) == -1)
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO),
				    "fseek");
			break;
		}
	}

	if (!rc)
		*ptr = pf;

	fsl_free(old);
	fsl_free(new);
	fsl_free(line);

	if (ferror(fp) && !rc)
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "getline");
	if (feof(fp) && !rc)
		rc = NO_PATCH;

	return rc;
}

static int
parse_filename(const char *at, char **name, int strip)
{
	char	*fullname, *t;
	int	 l, tab, rc = FSL_RC_OK;

	*name = NULL;
	if (*at == '\0')
		return rc;

	while (isspace((unsigned char)*at))
		++at;

	/* If path is /dev/null, file is being removed or created. */
	if (!fsl_strncmp(at, NULL_DEVICE, NULL_DEVICELEN))
		return rc;

	t = fsl_strdup(at);
	if (t == NULL)
		return RC(FSL_RC_ERROR, "fsl_strdup");
	*name = fullname = t;
	tab = strchr(t, '\t') != NULL;

	/* Strip path components and NUL-terminate. */
	for (l = strip;
	    *t != '\0' && ((tab && *t != '\t') || !isspace((unsigned char)*t));
	    ++t) {
		if (t[0] == '/' && t[1] != '/' && t[1] != '\0')
			if (--l >= 0)
				*name = t + 1;
	}
	*t = '\0';

	*name = fsl_strdup(*name);
	fsl_free(fullname);
	if (*name == NULL)
		return RC(FSL_RC_ERROR, "fsl_strdup");

	return rc;
}

static int
set_patch_paths(struct fnc_patch_file *pf, const char *old, const char *new)
{
	int	rc = FSL_RC_OK;
	size_t	ret = 0;

	/* Prefer the new name if it's neither /dev/null nor a renamed file. */
	if (new != NULL && old != NULL && !fsl_strcmp(new, old))
		ret = fsl_strlcpy(pf->old, new, sizeof(pf->old));
	else if (old != NULL)
		ret = fsl_strlcpy(pf->old, old, sizeof(pf->old));
	if (ret >= sizeof(pf->old))
		rc = RC(FSL_RC_RANGE, "fsl_strlcpy");

	if (!rc && new != NULL)
		ret = fsl_strlcpy(pf->new, new, sizeof(pf->new));
	if (!rc && ret >= sizeof(pf->new))
		rc = RC(FSL_RC_RANGE, "fsl_strlcpy");

	return rc;
}

/*
 * Parse patch(1) file fp and extract the changed lines data from each hunk
 * header to construct an fnc_patch_hunk object and assign it to *ptr, which
 * must eventually be dispoed of by the caller. Iterate the section of changed
 * lines, and push each +/- and context line onto the hdr->lines array, which
 * must also be disposed of by the caller.
 */
static int
parse_hunk(struct fnc_patch_hunk **ptr, FILE *fp, uint8_t context, bool *eof)
{
	struct fnc_patch_hunk	*hdr = NULL;
	char			*line = NULL, ch;
	size_t			 linesize = 0;
	ssize_t			 linelen;
	long			 leftold, leftnew;
	int			 rc = FSL_RC_OK;

	linelen = getline(&line, &linesize, fp);
	if (linelen == -1) {
		*eof = true;  /* end of this versioned file in the patch file */
		goto end;
	}

	if ((hdr = calloc(1, sizeof(*hdr))) == NULL) {
		rc = RC(FSL_RC_ERROR, "calloc");
		goto end;
	}

	hdr->lines = NULL;
	rc = parse_hdr(line, eof, hdr);
	if (rc)
		goto end;

	if (*eof) {
		if (fseek(fp, linelen * -1, SEEK_CUR) == -1)
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO),
			    "fseek");
		goto end;
	}

	leftold = hdr->oldlines;
	leftnew = hdr->newlines;

	while (leftold > 0 || leftnew > 0) {
		linelen = getline(&line, &linesize, fp);
		if (linelen == -1) {
			if (ferror(fp)) {
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO),
				    "getline");
				goto end;
			}

			if (leftold < 3 && leftnew < 3) {
				*eof = true;	/* trim trailing newlines */
				break;
			}

			rc = PATCH_TRUNCATED;
			goto end;
		}
		if (line[linelen - 1] == '\n')
			line[linelen - 1] = '\0';

		ch = *line;
		if (ch == '\t' || ch == '\0')
			ch = ' ';	/* leading space got eaten */

		switch (ch) {
		case '-':
			leftold--;
			break;
		case ' ':
			leftold--;
			leftnew--;
			break;
		case '+':
			leftnew--;
			break;
		default:
			rc = PATCH_MALFORMED;
			goto end;
		}

		if (leftold < 0 || leftnew < 0) {
			rc = PATCH_MALFORMED;
			goto end;
		}

		rc = pushline(hdr, line);
		if (rc)
			goto end;

		if ((ch == '-' && leftold == 0) ||
		    (ch == '+' && leftnew == 0)) {
			rc = peek_special_line(hdr, fp, ch == '+');
			if (rc)
				goto end;
		}
	}
end:
	/*
	 * XXX Check for hdr->lines as fnc diff adds a trailing empty newline
	 * between diffs (i.e., before the next file's Index line), which, if
	 * added, will produce a false negative in patch_file().
	 */
	if (!rc && hdr && hdr->lines)
		*ptr = hdr;
	else
		fsl_free(hdr);
	fsl_free(line);
	return rc;
}

/*
 * Parse hunk header line and assign corresponding new and old lines to
 * hdr->{old,new}lines, respectively.
 */
static int
parse_hdr(char *s, bool *eof, struct fnc_patch_hunk *hdr)
{
	int rc = FSL_RC_OK;

	*eof = false;
	if (fsl_strncmp(s, "@@ -", 4)) {
		*eof = true;
		return rc;
	}

	s += 4;
	if (!*s)
		return rc;

	rc = strtolnum(&s, &hdr->oldfrom);
	if (!rc && *s == ',') {
		s++;
		rc = strtolnum(&s, &hdr->oldlines);
	} else
		hdr->oldlines = 1;
	if (rc)
		return rc;

	if (*s == ' ')
		++s;
	if (*s != '+' || !*++s)
		return PATCH_MALFORMED;

	rc = strtolnum(&s, &hdr->newfrom);
	if (!rc && *s == ',') {
		s++;
		rc = strtolnum(&s, &hdr->newlines);
	} else
		hdr->newlines = 1;
	if (rc)
		return rc;

	if (*s == ' ')
		++s;
	if (*s != '@')
		return PATCH_MALFORMED;

	if (hdr->oldfrom >= LONG_MAX - hdr->oldlines ||
	    hdr->newfrom >= LONG_MAX - hdr->newlines ||
	    hdr->oldlines >= LONG_MAX - hdr->newlines - 1)
		rc = PATCH_MALFORMED;

	if (hdr->oldlines == 0)
		hdr->oldfrom++;

	return rc;
}

static int
strtolnum(char **str, int_least32_t *n)
{
	char		*cmp, *p, c;
	const char	*errstr;
#ifdef __OpenBSD__
	cmp = NULL;  /* strtonum() assigns last arg to NULL on success */
#else
	cmp = "\0";  /* strtol() assigns 2nd arg to NUL on success */
#endif

	for (p = *str; isdigit((unsigned char)*p); ++p)
		/* nop */;

	c = *p;
	*p = '\0';

	*n = strtonum(*str, 0, LONG_MAX, &errstr);
	if ((errstr && *errstr != *cmp) || (!errstr && errstr != cmp))
		return PATCH_MALFORMED;

	*p = c;
	*str = p;
	return FSL_RC_OK;
}

static int
pushline(struct fnc_patch_hunk *hdr, const char *line)
{
	static int rc = FSL_RC_OK;
	char *p = NULL;

	if (*line != '+' && *line != '-' && *line != ' ' && *line != '\\') {
		if ((p = fsl_mprintf(" %s", line)) == NULL)
			return RC(FSL_RC_ERROR, "fsl_mprintf");
		line = p;
	}

	rc = alloc_hunk_line(hdr, line);

	fsl_free(p);
	return rc;
}

static int
alloc_hunk_line(struct fnc_patch_hunk *h, const char *line)
{
	void	*t;
	size_t	 newcap;

	if (h->nlines == h->cap) {
		if ((newcap = h->cap * 1.5) == 0)
			newcap = 16;
		t = fsl_realloc(h->lines, newcap * sizeof(char *));
		if (t == NULL)
			return RC(FSL_RC_ERROR, "fsl_realloc");
		h->lines = t;
		memset(h->lines + h->cap, 0,
		    sizeof(*h->lines) * (newcap - h->cap));
		h->cap = newcap;
	}

	if ((t = fsl_strdup(line)) == NULL)
		return RC(FSL_RC_ERROR, "fsl_strdup");

	h->lines[h->nlines++] = t;
	return FSL_RC_OK;
}

static int
peek_special_line(struct fnc_patch_hunk *hdr, FILE *fp,
    int send)
{
	int ch, rc = FSL_RC_OK;

	ch = fgetc(fp);
	if (ch != EOF && ch != '\\') {
		ungetc(ch, fp);
		return rc;
	}

	if (ch == '\\' && send) {
		rc = pushline(hdr, "\\");
		if (rc)
			return rc;
	}

	while (ch != EOF && ch != '\n')
		ch = fgetc(fp);

	if (ch != EOF || feof(fp))
		return rc;
	return RC(FSL_RC_IO, "fgetc");
}

static int
apply_patch(struct patch_cx *pcx, struct fnc_patch_file *p, bool nop)
{
	const char	*newpath, *oldpath;
	char		*parent = NULL, *tmppath = NULL, *template = NULL;
	FILE		*tmp = NULL;
	int		 renamed = 0, rc = FSL_RC_OK;
#define DFLT_FILEMODE (S_IFREG | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
#define DFLT_DIRMODE (S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
	mode_t mode = DFLT_FILEMODE;

	newpath = p->new;
	oldpath = p->old;

	if (oldpath[0])
		renamed = fsl_strcmp(oldpath, newpath);

	if ((template = fsl_mprintf("%sfnc-patch",
	    fcli_cx()->ckout.dir)) == NULL) {
		rc = RC(FSL_RC_ERROR, "fsl_mprintf");
		goto end;
	}

	if (!nop)
		rc = fnc_open_tmpfile(&tmppath, &tmp, template, NULL);
	if (!rc)
		rc = patch_file(p, oldpath, tmp, nop, &mode);
	if (rc || nop)
		goto end;

	if (p->old[0] && !p->new[0]) {			/* file deleted */
		rc = fnc_rm_vfile(pcx, oldpath, false);
		goto end;
	}

	if (fchmod(fileno(tmp), mode) == -1) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
		    "fchmod: %s %d", newpath, mode);
		goto end;
	}

	fclose(tmp);

	if (rename(tmppath, newpath) == -1) {
		if (errno != ENOENT) {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
			    "rename(%s, %s)", tmppath, newpath);
			goto end;
		}

		rc = fsl_mkdir_for_file(newpath, true);
		if (rc || rename(tmppath, newpath) == -1) {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
			    "rename(%s, %s)", tmppath, newpath);
			goto end;
		}
	}

	if (renamed) {
		/*
		 * XXX Removing the original name versioned file and adding
		 * the renamed version produces a verbose diff with "duplicate"
		 * entries showing the entire file contents of the previous
		 * name versioned file deleted, and the entire file contents,
		 * including any edits, added under the new name. This makes it
		 * difficult to discern changes. By performing a rename in the
		 * vfile table, we get a more useful diff with rename context.
		 */
		/* rc = fnc_rm_vfile(pcx, oldpath, false); */
		/* if (!rc) */
		/* 	rc = fnc_add_vfile(pcx, newpath, false); */
		rc = fnc_rename_vfile(oldpath, newpath);
		if (!rc && pcx->report)
			rc = patch_reporter(p, oldpath, newpath, "~");
	} else if (!p->old[0]) {			/* file added */
		rc = fnc_add_vfile(pcx, newpath, false);
		/* rc = fnc_execp((const char *const []) */
		/*     {"fossil", "add", newpath, (char *)NULL}, 10); */
	} else if (pcx->report)
		rc = patch_reporter(p, oldpath, newpath, "~");
end:
	fsl_free(parent);
	fsl_free(template);
	if (tmppath != NULL)
		unlink(tmppath);
	fsl_free(tmppath);
	return rc;
}

/*
 * Open new tmp file at basepath, which is expected to be an absolute path,
 * with optional suffix. The final filename will be "basepath-XXXXXX[SUFFIX]"
 * where XXXXXX is a random character string populated by mkstemp(3) (or
 * mkstemps(3) if suffix is not NULL).
 */
static int
fnc_open_tmpfile(char **path, FILE **outfile, const char *basepath,
    const char *suffix)
{
	int fd, rc = FSL_RC_OK;

	*outfile = NULL;

	if ((*path = fsl_mprintf("%s-XXXXXX%s", basepath,
	    suffix ? suffix : "")) == NULL)
		return RC(FSL_RC_ERROR, "fsl_mprintf");

	if (suffix)
		fd = mkstemps(*path, fsl_strlen(suffix));
	else
	    fd = mkstemp(*path);
	if (fd == -1) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s(%s)",
		    suffix ? "mkstemps" : "mkstemp", *path);
		fsl_free(*path);
		*path = NULL;
		return rc;
	}

	*outfile = fdopen(fd, "w+");
	if (*outfile == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "fdopen: %s", *path);
		fsl_free(*path);
		*path = NULL;
	}

	return rc;
}

/*
 * Apply patch file p to the versioned file at path by iterating and applying
 * each hunk from p->head and creating thepatched file in tmp. Upon success,
 * copy to the versioned file at path.
 */
static int
patch_file(struct fnc_patch_file *p, const char *path, FILE *tmp, int nop,
    mode_t *mode)
{
	struct fnc_patch_hunk	*h;
	struct stat		 sb;
	FILE			*orig;
	char			*line = NULL;
	off_t			 copypos, pos;
	ssize_t			 linelen;
	size_t			 linesize = 0;
	long			 lineno = 0;
	int			 rc = FSL_RC_OK;

	if (!p->old[0]) {			/* create new versioned file */
		h = STAILQ_FIRST(&p->head);
		if (h == NULL || STAILQ_NEXT(h, entries) != NULL)
			return PATCH_MALFORMED;
		if (nop)
			return rc;
		return apply_hunk(tmp, h, &lineno);
	}

	if ((orig = fopen(path, "r")) == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO),
		    "fopen(%s, \"r\")", path);
		goto end;
	}

	if (fstat(fileno(orig), &sb) == -1) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "fstat(%s)", path);
		goto end;
	}
	*mode = sb.st_mode;

	copypos = 0;
	STAILQ_FOREACH(h, &p->head, entries) {
		if (h->lines == NULL)
			break;

	retry:
		rc = locate_hunk(orig, h, &pos, &lineno);
		if (rc && rc == HUNK_FAILED)
			h->rc = rc;
		if (rc)
			goto end;
		if (!nop)
			rc = copyfile(tmp, orig, copypos, pos);
		if (rc)
			goto end;
		copypos = pos;

		rc = test_hunk(orig, h);
		if (rc && rc == HUNK_FAILED) {
			/*
			 * Retry applying the hunk by starting the search
			 * after the previous partial match.
			 */
			if (fseek(orig, pos, SEEK_SET) == -1) {
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO),
				    "fseek");
				goto end;
			}
			linelen = getline(&line, &linesize, orig);
			if (linelen == -1) {
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO),
				    "getline");
				goto end;
			}
			++lineno;
			goto retry;
		}
		if (rc)
			goto end;

		if (lineno + 1 != h->oldfrom)
			h->offset = lineno + 1 - h->oldfrom;

		if (!nop)
			rc = apply_hunk(tmp, h, &lineno);
		if (rc)
			goto end;

		copypos = ftello(orig);
		if (copypos == -1) {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "ftello");
			goto end;
		}
	}

	if (!p->new[0] && sb.st_size != copypos) {
		h = STAILQ_FIRST(&p->head);
		rc = h->rc = HUNK_FAILED;
	} else if (!nop && !feof(orig))  /* success! copy to versioned file */
		rc = copyfile(tmp, orig, copypos, -1);
end:
	if (orig != NULL)
		fclose(orig);
	return rc;
}

static int
apply_hunk(FILE *tmp, struct fnc_patch_hunk *h, long *lineno)
{
	size_t	i = 0;

	for (i = 0; i < h->nlines; ++i) {
		switch (*h->lines[i]) {
		case ' ':
			if (fprintf(tmp, "%s\n", h->lines[i] + 1) < 0)
				return RC(fsl_errno_to_rc(errno, FSL_RC_IO),
				    "fprintf");
			/* fallthrough */
		case '-':
			(*lineno)++;
			break;
		case '+':
			if (fprintf(tmp, "%s", h->lines[i] + 1) < 0)
				return RC(fsl_errno_to_rc(errno, FSL_RC_IO),
				    "fprintf");
			if (i != h->nlines - 1 || !h->nonl) {
				if (fprintf(tmp, "\n") < 0)
					return RC(fsl_errno_to_rc(errno,
					    FSL_RC_IO), "fprintf");
			}
			break;
		}
	}
	return FSL_RC_OK;
}

static int
locate_hunk(FILE *orig, struct fnc_patch_hunk *h, off_t *pos, long *lineno)
{
	char	*line = NULL;
	char	 mode = *h->lines[0];
	ssize_t	 linelen;
	size_t	 linesize = 0;
	off_t	 match = -1;
	long	 match_lineno = -1;
	int	 rc = FSL_RC_OK;

	for (;;) {
		linelen = getline(&line, &linesize, orig);
		if (linelen == -1) {
			if (ferror(orig))
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO),
				    "getline");
			else if (match == -1)
				rc = HUNK_FAILED;
			break;
		}
		if (line[linelen - 1] == '\n')
			line[linelen - 1] = '\0';
		(*lineno)++;

		if ((mode == ' ' && !fsl_strcmp(h->lines[0] + 1, line)) ||
		    (mode == '-' && !fsl_strcmp(h->lines[0] + 1, line)) ||
		    (mode == '+' && *lineno == h->oldfrom)) {
			match = ftello(orig);
			if (match == -1) {
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO),
				    "ftello");
				break;
			}
			match -= linelen;
			match_lineno = (*lineno) - 1;
		}

		if (*lineno >= h->oldfrom && match != -1)
			break;
	}

	if (!rc) {
		*pos = match;
		*lineno = match_lineno;
		if (fseek(orig, match, SEEK_SET) == -1)
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "fseek");
	}

	fsl_free(line);
	return rc;
}

/*
 * Starting at copypos until pos, copy data from orig into tmp.
 * If pos is -1, copy until EOF.
 */
static int
copyfile(FILE *tmp, FILE *orig, off_t copypos, off_t pos)
{
	char	buf[BUFSIZ];
	size_t	len, r, w;

	if (fseek(orig, copypos, SEEK_SET) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_IO), "fseek");

	while (pos == -1 || copypos < pos) {
		len = sizeof(buf);
		if (pos > 0)
			len = MIN(len, (size_t)pos - copypos);
		r = fread(buf, 1, len, orig);
		if (r != len && ferror(orig))
			return RC(fsl_errno_to_rc(errno, FSL_RC_IO), "fread");
		w = fwrite(buf, 1, r, tmp);
		if (w != r)
			return RC(fsl_errno_to_rc(errno, FSL_RC_IO), "fwrite");
		copypos += len;
		if (r != len && feof(orig)) {
			if (pos == -1)
				return FSL_RC_OK;
			return HUNK_FAILED;
		}
	}
	return FSL_RC_OK;
}

static int
test_hunk(FILE *orig, struct fnc_patch_hunk *h)
{
	char	*line = NULL;
	ssize_t	 linelen;
	size_t	 linesize = 0, i = 0;
	int	 rc = FSL_RC_OK;

	for (i = 0; i < h->nlines; ++i) {
		switch (*h->lines[i]) {
		case '+':
			continue;
		case ' ':
		case '-':
			linelen = getline(&line, &linesize, orig);
			if (linelen == -1) {
				if (ferror(orig))
					rc = RC(fsl_errno_to_rc(errno,
					    FSL_RC_IO), "getline");
				else
					rc = HUNK_FAILED;
				goto end;
			}
			if (line[linelen - 1] == '\n')
				line[linelen - 1] = '\0';
			if (fsl_strcmp(h->lines[i] + 1, line)) {
				rc = HUNK_FAILED;
				goto end;
			}
			break;
		}
	}
end:
	fsl_free(line);
	return rc;
}

static int
fnc_add_vfile(struct patch_cx *pcx, const char *path, bool nop)
{
	fsl_cx			*const f = fcli_cx();
	fsl_db			*db;
	fsl_ckout_manage_opt	 opt = fsl_ckout_manage_opt_empty;
	int			 rc = FSL_RC_OK;
	bool			 trans = false;

	db = fsl_needs_ckout(f);
	if (!db)
		goto end;

	rc = fsl_db_transaction_begin(db);
	if (rc) {
		fsl_cx_uplift_db_error(f, db);
		goto end;
	}
	trans = true;

	opt.filename = path;
	opt.relativeToCwd = false;  /* relative repo root paths from fnc diff */
	opt.checkIgnoreGlobs = true;  /* XXX make an 'fnc stash' option? */
	opt.callbackState = pcx;  /* patch context and report cb */
	opt.callback = fnc_addvfile_cb;
	rc = fsl_ckout_manage(f, &opt);
	if (rc)
		goto end;

	if (nop) {
		f_out("dry run...rolling back transaction.\n");
		fsl_db_transaction_rollback(db);
	} else
		rc = fsl_db_transaction_end(db, false);
	trans = false;
end:
	if (trans) {
		const int rc2 = fsl_db_transaction_end(db, true);
		rc = rc ? rc : rc2;
	}
	return rc;
}

static int
fnc_addvfile_cb(fsl_ckout_manage_state const *cx, bool *include)
{
	struct patch_cx	*pcx = cx->opt->callbackState;
	int		 rc = FSL_RC_OK;

	if (pcx->report)
		rc = pcx->report_cb(pcx->pf, pcx->pf->old, pcx->pf->new, "+");
	if (!rc)
		*include = true;

	return rc;
}

static int
fnc_rm_vfile(struct patch_cx *pcx, const char *path, bool nop)
{
	fsl_cx			*const f = fcli_cx();
	fsl_db			*db;
	fsl_ckout_unmanage_opt	 opt = fsl_ckout_unmanage_opt_empty;
	int			 rc = FSL_RC_OK;
	bool			 trans = false;

	db = fsl_cx_db_ckout(f);
	if (!db) {
		rc = fsl_cx_err_set(f, FSL_RC_NOT_A_CKOUT, "ckout required");
		goto end;
	}

	rc = fsl_cx_transaction_begin(f);
	if (rc)
		goto end;
	trans = true;

	opt.filename = path;
	opt.scanForChanges = false;
	opt.vfileIds = NULL;
	opt.relativeToCwd = false;  /* relative repo root paths from fnc diff */
	opt.callback = fnc_rmvfile_cb;
	opt.callbackState = pcx;
	rc = fsl_ckout_unmanage(f, &opt);
	if (rc)
		goto end;

	if (nop) {
		f_out("dry run...rolling back transaction.\n");
		fsl_db_transaction_rollback(db);
	} else
		rc = fsl_db_transaction_end(db, false);
	trans = false;
end:
	if (trans) {
		const int rc2 = fsl_db_transaction_end(db, true);
		rc = rc ? rc : rc2;
	}
	return rc;
}

static int
fnc_rmvfile_cb(fsl_ckout_unmanage_state const *cx)
{
	struct patch_cx	*pcx = cx->opt->callbackState;
	int		 rc = FSL_RC_OK;

	if (pcx->report)
		rc = pcx->report_cb(pcx->pf, pcx->pf->old, pcx->pf->new, "-");

	return rc;
}

static int
fnc_rename_vfile(const char *oldpath, const char *newpath)
{
	fsl_cx	*const f = fcli_cx();
	fsl_db	*db = fsl_needs_ckout(f);
	int	 rc = FSL_RC_OK;

	rc = fsl_db_exec_multi(db,
	    "UPDATE vfile SET pathname='%q', origname='%q'"
	    " WHERE pathname='%q' %s AND vid=%d", newpath, oldpath,
	    oldpath, fsl_cx_filename_collation(f), f->ckout.rid);
	if (rc)
		fsl_file_unlink(newpath);
	else {
		const char *dir = getdirname(oldpath, -1, false);
		rc = fsl_file_unlink(oldpath);
		if (!fsl_dir_is_empty(dir))
			rc = fsl_rmdir(dir);
	}

	return rc;
}

static int
patch_reporter(struct fnc_patch_file *p, const char *old, const char *new,
    char *status)
{
	struct fnc_patch_hunk	*h;
	int			 rc = FSL_RC_OK;

	rc = patch_report(old, new, status, 0, 0, 0, 0, 0, 0);
	if (rc)
		return rc;

	STAILQ_FOREACH(h, &p->head, entries) {
		if (h->offset == 0 && !h->rc)
			continue;

		rc = patch_report(old, new, 0, h->oldfrom, h->oldlines,
		    h->newfrom, h->newlines, h->offset, h->rc);
	}

	return rc;
}

static int
patch_report(const char *old, const char *new, char *status,
    long oldfrom, long oldlines, long newfrom, long newlines, long offset,
    enum fnc_patch_rc hunkrc)
{
	const char *path = !new[0] ? old : new;

	while (*path == '/')
		path++;

	if (old[0] && new[0] && fsl_strcmp(old, new))
		printf("[s%s] %s  ->  %s\n", status, old, new);
	else
		printf("[s%s] %s\n", status, path);

	if (offset != 0 || hunkrc) {
		printf("@@ -%ld,%ld +%ld,%ld @@ ", oldfrom,
		    oldlines, newfrom, newlines);
		if (hunkrc)
			printf("error %d: %s\n", hunkrc, STRINGIFY(hunkrc));
		else
			printf("applied with offset %ld\n", offset);
	}
	fflush(stdout);

	return FSL_RC_OK;
}

static void
free_patch(struct fnc_patch_file *p)
{
	struct fnc_patch_hunk	*h;
	size_t			 i;

	while (!STAILQ_EMPTY(&p->head)) {
		h = STAILQ_FIRST(&p->head);
		STAILQ_REMOVE_HEAD(&p->head, entries);

		for (i = 0; i < h->nlines; ++i) {
			fsl_free(h->lines[i]);
			h->lines[i] = NULL;
		}
		fsl_free(h->lines);
		fsl_free(h);
		h = NULL;
	}
	fsl_free(p);
}

/*
 * exec(2) arg[0] with args arg after a fork(2). Optionally wait wait seconds
 * for child process to complete; set to zero or a negative integer to not wait.
 */
#if 0
static int
fnc_execp(const char *const *arg, const int wait)
{
	pid_t	pid;
	int	status, timeout, rc = FSL_RC_OK;

	pid = fork();
	if (pid == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS), "fork");
	else if (pid == 0)
		if (execvp(arg[0], (char *const *)arg) == -1)
			return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
			    "ecexve");

	if (wait < 1)
		return rc;

	timeout = wait;

	while (waitpid(pid , &status , WNOHANG) == 0) {
		if ( --timeout < 0 )
			return RC(FSL_RC_RANGE, "timeout for child [%d]", pid);
		sleep(1);
	}

	if (WIFEXITED(status) != 1 || WEXITSTATUS(status) != 0)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
			"%s: WEXITSTATUS %d | WIFEXITED %d [status %d]", arg[0],
			WEXITSTATUS(status), WIFEXITED(status), status);

	return rc;
}
#endif

/*
 * Create new stash of changes in checkout vid with stash message msg.
 */
static int
f__stash_create(const char *msg, int vid)
{
	fsl_cx	*const f = fcli_cx();
	fsl_db	*db = fsl_needs_ckout(f);
	int	 stashid, rc = FSL_RC_OK;

	rc = f__check_stash_tables();
	if (rc)
		return RC(rc, "check_stash_tables");

	stashid = fsl_config_get_int32(f, FSL_CONFDB_CKOUT, 1, "stash-next");
	rc = fsl_config_set_id(f, FSL_CONFDB_CKOUT, "stash-next", stashid + 1);
	if (!rc)
		rc = fsl_ckout_changes_scan(f);
	if (rc)
		return rc;

	fsl_db_exec_multi(db,
	    "INSERT INTO stash(stashid, vid, hash, comment, ctime)"
	    " VALUES(%d, %d, (SELECT uuid FROM blob WHERE rid = %d),"
	    " %Q, julianday('now'))", stashid, vid, vid, msg);

	rc = f__stash_path(stashid, vid, ".");

	return rc;
}

/*
 * Check checkout database for up-to-date stash and stashfile tables. Create
 * or upgrade if needed.
 */
static int
f__check_stash_tables(void)
{
	static const char stashtab[] =
	    "CREATE TABLE IF NOT EXISTS stash(\n"
	    " stashid INTEGER PRIMARY KEY, -- Unique stash identifier\n"
	    " vid INTEGER,          -- Legacy baseline RID value. Do not use.\n"
	    " hash TEXT,            -- The SHA hash for the baseline\n"
	    " comment TEXT,         -- Comment for this stash.  Or NULL\n"
	    " ctime TIMESTAMP       -- When the stash was created\n"
	    ");\n"
	    "CREATE TABLE IF NOT EXISTS stashfile(\n"
	    " stashid INTEGER REFERENCES stash, -- Stash containing this file\n"
	    " isAdded BOOLEAN,       -- True if this file is added\n"
	    " isRemoved BOOLEAN,     -- True if this file is deleted\n"
	    " isExec BOOLEAN,        -- True if file is executable\n"
	    " isLink BOOLEAN,        -- True if file is a symlink\n"
	    " rid INTEGER,           -- Legacy baseline RID value. Do not use\n"
	    " hash TEXT,             -- Hash for baseline or NULL\n"
	    " origname TEXT,         -- Original filename\n"
	    " newname TEXT,          -- New name for file at next check-in\n"
	    " delta BLOB,            -- Delta from baseline or raw content\n"
	    " PRIMARY KEY(newname, stashid)\n"
	    ");\n"
	    "INSERT OR IGNORE INTO vvar(name,value) VALUES('stash-next',1);\n";
	fsl_cx	*const f = fcli_cx();
	fsl_db	*db = fsl_needs_ckout(f);
	int	 rc = FSL_RC_OK;

	if (fsl_db_table_has_column(db, "stashfile", "hash")) {
		/*
		 * Schema is up-to-date, but an older version of Fossil that
		 * doesn't know about the stash.hash and stashfile.hash columns
		 * may have run since the schema was updated, and added entries
		 * with NULL hash columns. Check for this case, and input any
		 * missing hash values.
		 */
		if (fsl_db_g_int32(db, 0, "SELECT hash IS NULL FROM stash "
		    "ORDER BY stashid DESC LIMIT 1")) {
			rc = fsl_db_exec_multi(db, "UPDATE stash"
			    " SET hash=(SELECT uuid FROM blob"
			    "  WHERE blob.rid=stash.vid)"
			    " WHERE hash IS NULL;"
			    "UPDATE stashfile"
			    " SET hash=(SELECT uuid FROM blob"
			    "  WHERE blob.rid=stashfile.rid)"
			    " WHERE hash IS NULL AND rid>0;");
		}
		return rc;
	}

	if (!fsl_db_table_exists(db, FSL_DBROLE_CKOUT, "stashfile") ||
	    !fsl_db_table_exists(db, FSL_DBROLE_CKOUT, "stash")) {
		/* Tables don't exist; create them from scratch. */
		rc = fsl_db_exec(db, "DROP TABLE IF EXISTS stash;");
		if (!rc)
			rc = fsl_db_exec(db, "DROP TABLE IF EXISTS stashfile;");
		if (!rc)
			rc = fsl_db_exec_multi(db, stashtab);
		return rc;
	}

	/*
	 * Tables exist but aren't necessarily current. Upgrade to the latest
	 * format. Assume the 2011-09-01 format that includes the column
	 * stashfile.isLink. Upgrade the PRIMARY KEY change on 2016-10-16 and
	 * the addition of the "hash" columns on 2019-01-19.
	 */
	rc = fsl_db_exec_multi(db,
	    "ALTER TABLE stash RENAME TO old_stash;"
	    "ALTER TABLE stashfile RENAME TO old_stashfile;");
	if (!rc)
		rc = fsl_db_exec_multi(db, stashtab);
	if (!rc)
		rc = fsl_db_exec_multi(db,
		    "INSERT INTO stash(stashid,vid,hash,comment,ctime)"
		    " SELECT stashid, vid,"
		    "  (SELECT uuid FROM blob WHERE blob.rid=old_stash.vid),"
		    "  comment, ctime FROM old_stash; "
		    "DROP TABLE old_stash;");
	if (!rc)
		rc = fsl_db_exec_multi(db,
		    "INSERT INTO stashfile(stashid, isAdded, isRemoved,"
		    " isExec, isLink, rid, hash, origname, newname, delta)"
		    " SELECT stashid, isAdded, isRemoved, isExec, isLink, rid,"
		    "  (SELECT uuid FROM blob WHERE blob.rid=old_stashfile.rid),"
		    "  origname, newname, delta FROM old_stashfile; "
		    "DROP TABLE old_stashfile;");

	return rc;
}

/*
 * Add file(s) at path to the stash changeset identified by stashid based on
 * checkout vid. If path is a directory, all files in that dir will be added.
 * If path is ".", the entire checkout will be stashed from the repository root.
 */
static int
f__stash_path(int stashid, int vid, const char *path)
{
	fsl_cx		*const f = fcli_cx();
	fsl_db		*db = fsl_needs_ckout(f);
	fsl_buffer	 sql = fsl_buffer_empty;	/* query statement */
	fsl_stmt	 q = fsl_stmt_empty;		/* vfile statement */
	fsl_stmt	 ins = fsl_stmt_empty;		/* insert statement */
	int		 rc = FSL_RC_OK;

	rc = fsl_buffer_appendf(&sql,
	    "SELECT deleted, isexe, islink, mrid, pathname,"
	    "  coalesce(origname,pathname)"
	    " FROM vfile WHERE vid=%d AND (chnged OR deleted OR"
	    "  (origname IS NOT NULL AND origname<>pathname) OR mrid==0)",
	    vid);
	if (!rc && fsl_strcmp(path, ".")) {  /* specific file provided */
		rc = fsl_buffer_appendf(&sql,
		    " AND (pathname GLOB '%q/*' OR origname GLOB '%q/*'"
		    " OR pathname=%Q OR origname=%Q)", path, path, path, path);
	}
	if (rc)
		return RC(rc, "fsl_buffer_appendf");

	fsl_simplify_sql_buffer(&sql);
	rc = fsl_db_prepare(db, &q, "%s", fsl_buffer_str(&sql));
	fsl_buffer_clear(&sql);
	if (rc)
		return RC(rc, "fsl_db_prepare(%s): %d", "stash query", vid);

	rc = fsl_db_prepare(db, &ins,
	    "INSERT INTO stashfile(stashid, isAdded, isRemoved, isExec, isLink,"
	    "  rid, hash, origname, newname, delta)"
	    "VALUES(%d,:isadd,:isrm,:isexe,:islink,:rid,"
	    "(SELECT uuid FROM blob WHERE rid=:rid),:orig,:new,:content)",
	    stashid);
	if (rc)
		return RC(rc, "fsl_db_prepare(%s): %d", "stash insert", stashid);

	while (fsl_stmt_step(&q) == FSL_RC_STEP_ROW) {
		fsl_buffer	 content = fsl_buffer_empty;
		char		 path[PATH_MAX];
		int		 deleted = fsl_stmt_g_int32(&q, 0);
		int		 rid = fsl_stmt_g_int32(&q, 3);
		const char	*name = fsl_stmt_g_text(&q, 4, NULL);
		const char	*ogname = fsl_stmt_g_text(&q, 5, NULL);

		fsl_strlcpy(path, CKOUTDIR, sizeof(path));
		fsl_strlcat(path, name, sizeof(path));

		rc = fsl_stmt_bind_int32_name(&ins, ":rid", rid);
		if (!rc)
			rc = fsl_stmt_bind_int32_name(&ins, ":isadd", rid==0);
		if (!rc)
			rc = fsl_stmt_bind_int32_name(&ins, ":isrm", deleted);
		if (!rc)
			rc = fsl_stmt_bind_int32_name(&ins, ":isexe",
			    fsl_stmt_g_int32(&q, 1));
		if (!rc)
			rc = fsl_stmt_bind_int32_name(&ins, ":islink",
			    fsl_stmt_g_int32(&q, 2));
		if (rc) {
			rc = RC(rc, "fsl_stmt_bind_int32_name");
			goto end;
		}

		rc = fsl_stmt_bind_text_name(&ins, ":orig", ogname, -1, false);
		if (!rc)
			rc = fsl_stmt_bind_text_name(&ins, ":new", name, -1,
			    false);
		if (rc) {
			rc = RC(rc, "fsl_stmt_bind_text_name");
			goto end;
		}

		if (!rid) {	/* new file */
			rc = fsl_buffer_fill_from_filename(&content, path);
			if (rc) {
				rc = RC(rc, "fsl_buffer_fill_from_filename(%s)",
				    path);
				goto end;
			}
			rc = fsl_stmt_bind_blob_name(&ins, ":content",
			    content.mem, content.used, false);
			if (rc) {
				rc = RC(rc, "fsl_stmt_bind_blob_name");
				goto clear_delta;
			}
		} else if (deleted) {
			fsl_buffer_clear(&content);
			rc = fsl_stmt_bind_null_name(&ins, ":content");
			if (rc) {
				rc = RC(rc, "fsl_stmt_bind_null_name");
				goto end;
			}
		} else {	/* modified file */
			fsl_buffer orig = fsl_buffer_empty;
			fsl_buffer disk = fsl_buffer_empty;

			rc = fsl_buffer_fill_from_filename(&disk, path);
			if (rc) {
				rc = RC(rc, "fsl_buffer_fill_from_filename(%s)",
				    path);
				goto end;
			}
			rc = fsl_content_get(f, rid, &orig);
			if (rc) {
				rc = RC(rc, "fsl_content_get(%d)", rid);
				goto clear_file;
			}
			rc = fsl_buffer_delta_create(&orig, &disk, &content);
			if (rc) {
				rc = RC(rc, "fsl_buffer_delta_create");
				goto clear_file;
			}
			rc = fsl_stmt_bind_blob_name(&ins, ":content",
			    content.mem, content.used, false);
			if (rc)
				rc = RC(rc, "fsl_stmt_bind_blob_name");
clear_file:
			fsl_buffer_clear(&orig);
			fsl_buffer_clear(&disk);
		}
		if (rc)
			goto clear_delta;
		rc = fsl_stmt_bind_int32_name(&ins, ":islink",
		    fsl_is_symlink(path));
		if (rc)
			rc = RC(rc, "fsl_stmt_bind_int32_name");
		else {
			fsl_stmt_step(&ins);
			fsl_stmt_reset(&ins);
		}
clear_delta:
		fsl_buffer_clear(&content);
		if (rc)
			goto end;
	}
end:
	fsl_stmt_finalize(&ins);
	fsl_stmt_finalize(&q);
	return rc;
}

static int
reset_diff_view(struct fnc_view *view, bool stay)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	int				 n, rc = FSL_RC_OK;

	n = s->nlines;




	show_diff_status(view);
	rc = create_diff(s);
	if (rc)
		return rc;

	if (stay) {
		float scale = (float)s->first_line_onscreen / n;
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437

static int
set_selected_commit(struct fnc_diff_view_state *s, struct commit_entry *entry)
{
	fsl_free(s->id2);
	s->id2 = fsl_strdup(entry->commit->uuid);
	if (s->id2 == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	fsl_free(s->id1);
	s->id1 = entry->commit->puuid ? fsl_strdup(entry->commit->puuid) : NULL;
	s->selected_entry = entry->commit;

	return 0;
}








|







8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941

static int
set_selected_commit(struct fnc_diff_view_state *s, struct commit_entry *entry)
{
	fsl_free(s->id2);
	s->id2 = fsl_strdup(entry->commit->uuid);
	if (s->id2 == NULL)
		return RC(FSL_RC_ERROR, "fsl_strdup");
	fsl_free(s->id1);
	s->id1 = entry->commit->puuid ? fsl_strdup(entry->commit->puuid) : NULL;
	s->selected_entry = entry->commit;

	return 0;
}

6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
			else
				lineno = nlines;
		}

		offset = line_offsets[lineno - 1];
		if (fseeko(f, offset, SEEK_SET) != 0) {
			fsl_free(line);
			return RC(fsl_errno_to_rc(errno, FSL_RC_IO),
			    "%s", "fseeko");
		}
		/* Expand tabs for accurate rm_so/rm_eo offsets. */
		linelen = getline(&line, &linesz, f);
		expand_tab(&exstr, line, linelen);
		if (linelen != -1 && regexec(&view->regex, exstr, 1,
		    &view->regmatch, 0) == 0) {
			int *pos = &view->pos.col;







|
<







8994
8995
8996
8997
8998
8999
9000
9001

9002
9003
9004
9005
9006
9007
9008
			else
				lineno = nlines;
		}

		offset = line_offsets[lineno - 1];
		if (fseeko(f, offset, SEEK_SET) != 0) {
			fsl_free(line);
			return RC(fsl_errno_to_rc(errno, FSL_RC_IO), "fseeko");

		}
		/* Expand tabs for accurate rm_so/rm_eo offsets. */
		linelen = getline(&line, &linesz, f);
		expand_tab(&exstr, line, linelen);
		if (linelen != -1 && regexec(&view->regex, exstr, 1,
		    &view->regmatch, 0) == 0) {
			int *pos = &view->pos.col;
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
static int
close_diff_view(struct fnc_view *view)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	int				 rc = 0;

	if (s->f && fclose(s->f) == EOF)
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fclose");
	fsl_free(s->id1);
	s->id1 = NULL;
	fsl_free(s->id2);
	s->id2 = NULL;
	fsl_free(s->line_offsets);
	free_colours(&s->colours);
	s->line_offsets = NULL;







|







9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
static int
close_diff_view(struct fnc_view *view)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	int				 rc = 0;

	if (s->f && fclose(s->f) == EOF)
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "fclose");
	fsl_free(s->id1);
	s->id1 = NULL;
	fsl_free(s->id2);
	s->id2 = NULL;
	fsl_free(s->line_offsets);
	free_colours(&s->colours);
	s->line_offsets = NULL;
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655


6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689













6690
6691











6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
		cols = size.ws_col;
		lines = size.ws_row;
	}
	resize_term(lines, cols);
}

static int
view_resize(struct fnc_view *view, enum view_mode mode)
{
	int	 nlines, ncols, rc = FSL_RC_OK;



	if (view->lines > LINES)
		nlines = view->nlines - (view->lines - LINES);
	else
		nlines = view->nlines + (LINES - view->lines);

	if (view->cols > COLS)
		ncols = view->ncols - (view->cols - COLS);
	else
		ncols = view->ncols + (COLS - view->cols);

	if (wresize(view->window, nlines, ncols) == ERR)
		return RC(FSL_RC_ERROR, "%s", "wresize");
	if (replace_panel(view->panel, view->window) == ERR)
		return RC(FSL_RC_ERROR, "%s", "replace_panel");
	wclear(view->window);

	view->nlines = nlines;
	view->ncols = ncols;
	view->lines = LINES;
	view->cols = COLS;

	if (view->child && mode != VIEW_SPLIT_NONE) {
		view->child->start_col = view_split_start_col(view->start_col);
		if (view->mode == VIEW_SPLIT_HRZN || !view->child->start_col) {
			rc = make_fullscreen(view->child);
			if (view->child->active)
				show_panel(view->child->panel);
			else
				show_panel(view->panel);
		} else {
			rc = make_splitscreen(view->child);
			show_panel(view->child->panel);
		}













	}












	return rc;
}

/*
 * Consume repeatable arguments containing artifact type values used in
 * constructing the SQL query to generate commit records of the specified type
 * for the timeline. n.b. filter_types->values is owned by fcli—do not free.
 * TODO: Enhance to generalise processing of various repeatable args--paths,
 * usernames, branches, etc.--so we can filter on multiples of these values.
 */
static int
fcli_flag_type_arg_cb(fcli_cliflag const *v)
{
	struct artifact_types	*ft = &fnc_init.filter_types;
	const char		*t = *((const char **)v->flagValue);

	/* Valid types: ci, e, f, g, t, w */
	if (t[2] || (t[1] && (*t != 'c' || t[1] != 'i')) || (!t[1] &&
	    (*t != 'e' && *t != 'f' && *t != 'g' && *t != 't' && *t != 'w'))) {
		fnc_init.err = RC(FSL_RC_TYPE, "invalid type: %s", t);
		usage();
		/* NOT REACHED */
	}

	ft->values = fsl_realloc(ft->values, (ft->nitems + 1) * sizeof(char *));







|

|
>
>












|

|







|











>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
>
>
>
>
>
>
>
>
>
>
>

















|







9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
		cols = size.ws_col;
		lines = size.ws_row;
	}
	resize_term(lines, cols);
}

static int
view_resize(struct fnc_view *view, bool split)
{
	int dif, nlines, ncols, rc = FSL_RC_OK;

	dif = LINES - view->lines; /* if resized, what's the line difference? */

	if (view->lines > LINES)
		nlines = view->nlines - (view->lines - LINES);
	else
		nlines = view->nlines + (LINES - view->lines);

	if (view->cols > COLS)
		ncols = view->ncols - (view->cols - COLS);
	else
		ncols = view->ncols + (COLS - view->cols);

	if (wresize(view->window, nlines, ncols) == ERR)
		/* recover by clearing and redrawing */;
	if (replace_panel(view->panel, view->window) == ERR)
		return RC(FSL_RC_ERROR, "replace_panel");
	wclear(view->window);

	view->nlines = nlines;
	view->ncols = ncols;
	view->lines = LINES;
	view->cols = COLS;

	if (view->child) {
		view->child->start_col = view_split_start_col(view->start_col);
		if (view->mode == VIEW_SPLIT_HRZN || !view->child->start_col) {
			rc = make_fullscreen(view->child);
			if (view->child->active)
				show_panel(view->child->panel);
			else
				show_panel(view->panel);
		} else {
			rc = make_splitscreen(view->child);
			show_panel(view->child->panel);
		}
		/*
		 * If the terminal has been resized and it's a timeline view,
		 * and there aren't enough commits loaded to populate the view,
		 * request more commits now for the next screen redraw.
		 */
		if (view->vid == FNC_VIEW_TIMELINE && dif) {
			struct fnc_tl_view_state *ts = &view->state.timeline;
			if (ts->commits.ncommits < ts->selected_entry->idx +
			    view->lines - ts->selected) {
				ts->nscrolled = ts->selected_entry->idx +
				    view->lines - ts->selected -
				    ts->commits.ncommits + ABS(dif);
				rc = request_tl_commits(view);
			}
		}
		/*
		 * If the terminal was resized with a horizontal split, for
		 * some reason unbeknownst to me, we need to reset the split
		 * screen dimensions now else it'll render a fullscreen view.
		 * XXX Delete this to force fullscreen when resizing a hsplit.
		 */
		if (!rc && split) {
			rc = make_splitscreen(view->child);
			show_panel(view->child->panel);
		}
	}
	return rc;
}

/*
 * Consume repeatable arguments containing artifact type values used in
 * constructing the SQL query to generate commit records of the specified type
 * for the timeline. n.b. filter_types->values is owned by fcli—do not free.
 * TODO: Enhance to generalise processing of various repeatable args--paths,
 * usernames, branches, etc.--so we can filter on multiples of these values.
 */
static int
fcli_flag_type_arg_cb(fcli_cliflag const *v)
{
	struct artifact_types	*ft = &fnc_init.filter_types;
	const char		*t = *((const char **)v->flagValue);

	/* Valid types: ci, e, f, g, t, w */
	if (strlen(t) > 2 || (t[1] && (*t != 'c' || t[1] != 'i')) || (!t[1] &&
	    (*t != 'e' && *t != 'f' && *t != 'g' && *t != 't' && *t != 'w'))) {
		fnc_init.err = RC(FSL_RC_TYPE, "invalid type: %s", t);
		usage();
		/* NOT REACHED */
	}

	ft->values = fsl_realloc(ft->values, (ft->nitems + 1) * sizeof(char *));
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777



6778
6779
6780
6781
6782
6783
6784
6785
	 */
	/* fsl_cx *f = fcli_cx(); */
	/* f->output = fsl_outputer_FILE; */
	/* f->output.state.state = (fnc_init.err == true) ? stderr : stdout; */
	FILE *f = fnc_init.err ? stderr : stdout;
	size_t idx = 0;

	endwin();

	/* If a command was passed on the CLI, output its corresponding help. */
	if (fnc_init.cmdarg)
		for (idx = 0; idx < nitems(fnc_init.cmd_args); ++idx) {
			fcli_command cmd = fnc_init.cmd_args[idx];
			if (!fsl_strcmp(fnc_init.cmdarg, cmd.name) ||
			    fcli_cmd_aliascmp(&cmd, fnc_init.cmdarg)) {



				fcli_command_help(&cmd, true, true);
				exit(fcli_end_of_main(fnc_init.err));
			}
		}

	/* Otherwise, output help/usage for all commands. */
	fcli_command_help(fnc_init.cmd_args, true, false);
	fsl_fprintf(f, "  note: %s "







|







>
>
>
|







9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
	 */
	/* fsl_cx *f = fcli_cx(); */
	/* f->output = fsl_outputer_FILE; */
	/* f->output.state.state = (fnc_init.err == true) ? stderr : stdout; */
	FILE *f = fnc_init.err ? stderr : stdout;
	size_t idx = 0;

	!isendwin() ? endwin() : 0;

	/* If a command was passed on the CLI, output its corresponding help. */
	if (fnc_init.cmdarg)
		for (idx = 0; idx < nitems(fnc_init.cmd_args); ++idx) {
			fcli_command cmd = fnc_init.cmd_args[idx];
			if (!fsl_strcmp(fnc_init.cmdarg, cmd.name) ||
			    fcli_cmd_aliascmp(&cmd, fnc_init.cmdarg)) {
				if (!fsl_strcmp(cmd.name, "stash")) {
					help_stash(&cmd);
				} else
					fcli_command_help(&cmd, true, true);
				exit(fcli_end_of_main(fnc_init.err));
			}
		}

	/* Otherwise, output help/usage for all commands. */
	fcli_command_help(fnc_init.cmd_args, true, false);
	fsl_fprintf(f, "  note: %s "
6848
6849
6850
6851
6852
6853
6854

















































































































6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " usage: %s config [-R path] [-h|--help] [--ls] "
	    "[setting [value|--unset]]\n"
	    "  e.g.: %s config FNC_COLOUR_COMMIT blue\n\n" ,
	    fcli_progname(), fcli_progname());
}


















































































































static int
cmd_diff(fcli_command const *argv)
{
	fsl_cx				*const f = fcli_cx();
	struct fnc_view			*view;
	struct fnc_commit_artifact	*commit = NULL;
	struct fnc_pathlist_head	 paths;
	struct fnc_pathlist_entry	*pe;
	fsl_deck			 d = fsl_deck_empty;
	fsl_stmt			*q = NULL;
	const char			*artifact1 = NULL, *artifact2 = NULL;
	char				*path0 = NULL;
	fsl_id_t			 prid = -1, rid = -1;
	int				 rc = FSL_RC_OK;
	unsigned short			 blob = 0;
	enum fnc_diff_type		 diff_type = FNC_DIFF_CKOUT;
	bool				 showmeta = false;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	TAILQ_INIT(&paths);








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

















|







9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " usage: %s config [-R path] [-h|--help] [--ls] "
	    "[setting [value|--unset]]\n"
	    "  e.g.: %s config FNC_COLOUR_COMMIT blue\n\n" ,
	    fcli_progname(), fcli_progname());
}

static void
usage_stash(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " usage: %s stash [get|pop | [-C|--no-colour] [-h|--help] "
	    "[-P|--no-prototype] [-x|--context n]]\n"
	    "  e.g.: %s stash -x 10\n\n", fcli_progname(), fcli_progname());
}

static void
help_stash(const fcli_command *cmd)
{
	fcli_command_help(cmd, false, true);
	f_out("[stash] subcommands:\n\n");
	f_out("  get\n    "
	    "Apply the most recent stash changeset to the checkout.\n\n");
	f_out("  pop\n    Remove the most recent stash changeset, "
	    "and apply to the checkout.\n\n");
	usage_stash();
}

static int
cmd_stash(fcli_command const *argv)
{
	fsl_cx				*const f = fcli_cx();
	struct fnc_view			*view = NULL;
	struct fnc_commit_artifact	*commit = NULL;
	fsl_id_t			 prid = -1, rid = -1;
	int				 rc = FSL_RC_OK;
	enum fnc_diff_type		 diff_type = FNC_DIFF_CKOUT;
	enum fnc_diff_mode		 diff_mode = STASH_INTERACTIVE;

#ifdef __OpenBSD__
	if (pledge("stdio rpath wpath cpath fattr flock tty unveil", NULL) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS), "pledge");
#endif

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	if (fcli_next_arg(false)) {
		const char *cmd;
		bool pop = false;
		if (fsl_strcmp((cmd = fcli_next_arg(true)), "get") &&
		    fsl_strcmp(cmd, "apply") && !(pop = !fsl_strcmp(cmd, "pop")))
			return RC(FSL_RC_NOT_FOUND,
			    "invalid stash subcommand: %s", cmd);
		return f__stash_get(pop);
	}

	rc = fsl_sym_to_rid(f, "current", FSL_SATYPE_CHECKIN, &prid);
	if (rc || prid < 0)
		return RC(rc, "fsl_sym_to_rid");

	fsl_ckout_version_info(f, &rid, NULL);
	if ((rc = fsl_ckout_changes_scan(f)))
		return RC(rc, "fsl_ckout_changes_scan");
	if (!fsl_ckout_has_changes(f)) {
		fsl_fprintf(stdout, "No local changes.\n");
		return rc;
	}

	commit = calloc(1, sizeof(*commit));
	if (commit == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "calloc");
	commit->prid = prid;
	commit->rid = rid;
	commit->puuid = fsl_rid_to_uuid(f, prid);
	commit->uuid = fsl_rid_to_uuid(f, rid);
	commit->type = fsl_strdup("blob");
	commit->diff_type = diff_type;

	rc = init_curses();
	if (rc)
		goto end;
	/*
	 * XXX revert_ckout:fsl_ckout_revert()^ walks the tree from / to the
	 * ckout stat(2)ing every dir so we need rx on root. Revoke privileges
	 * on root after returning from revert_ckout().
	 * ^fsl__vfile_to_ckout:fsl_mkdir_for_file:fsl_dir_check()
	 */
	rc = init_unveil(((const char *[]){"/", REPODIR, CKOUTDIR, P_tmpdir,
	    gettzfile()}), ((const char *[]){"rx", "rwc", "rwc", "rwc", "r"}),
	    5, false);
	if (rc)
		goto end;

	view = view_open(0, 0, 0, 0, FNC_VIEW_DIFF);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "view_open");
		goto end;
	}

	rc = open_diff_view(view, commit, NULL, NULL, diff_mode);
	if (!rc) {
		rc = show_diff(view);
		if (!rc)
			rc = fnc_stash(view);
	}
end:
	/*
	 * We must check for changes based on file content--not mtime--else
	 * the lib will report files as unchanged in some cases.
	 */
	fsl_vfile_changes_scan(f, f->ckout.rid, FSL_VFILE_CKSIG_HASH);
	if (commit)
		fnc_commit_artifact_close(commit);
	if (view)
		view_close(view);
	return rc;
}

static int
cmd_diff(fcli_command const *argv)
{
	fsl_cx				*const f = fcli_cx();
	struct fnc_view			*view;
	struct fnc_commit_artifact	*commit = NULL;
	struct fnc_pathlist_head	 paths;
	struct fnc_pathlist_entry	*pe;
	fsl_deck			 d = fsl_deck_empty;
	fsl_stmt			*q = NULL;
	const char			*artifact1 = NULL, *artifact2 = NULL;
	char				*path0 = NULL;
	fsl_id_t			 prid = -1, rid = -1;
	int				 rc = FSL_RC_OK;
	unsigned short			 blob = 0;
	enum fnc_diff_type		 diff_type = FNC_DIFF_CKOUT;
	enum fnc_diff_mode		 diff_mode = DIFF_PLAIN;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	TAILQ_INIT(&paths);

6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937

6938


6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970


6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013

7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
		    &rid)) {
			artifact2 = fcli_next_arg(true);
			diff_type = FNC_DIFF_COMMIT;
			if (!fsl_rid_is_a_checkin(f, rid))
				++blob;
		}
	}
	if (fcli_error()->code == FSL_RC_NOT_FOUND) {
		fcli_err_reset();  /* If args aren't symbols, treat as paths. */
		rc = 0;
	}
	if (blob == 2)
		diff_type = FNC_DIFF_BLOB;
	if (!artifact1 && diff_type != FNC_DIFF_BLOB) {
		artifact1 = "current";
		rc = fsl_sym_to_rid(f, artifact1, FSL_SATYPE_CHECKIN, &prid);
		if (rc || prid < 0) {
			rc = RC(rc, "%s", "fsl_sym_to_rid");
			goto end;
		}
	}
	if (!artifact2 && diff_type != FNC_DIFF_BLOB) {
		fsl_ckout_version_info(f, &rid, NULL);
		if ((rc = fsl_ckout_changes_scan(f)))
			return RC(rc, "%s", "fsl_ckout_changes_scan");
		if (!fsl_strcmp(artifact1, "current") &&
		    !fsl_ckout_has_changes(f)) {
			fsl_fprintf(stdout, "No local changes.\n");
			return rc;
		}
	}
	while (fcli_next_arg(false) && diff_type != FNC_DIFF_BLOB) {
		struct fnc_pathlist_entry *ins;
		char *path, *path_to_diff;
		rc = map_repo_path(&path0);
		path = path0;
		while (path[0] == '/')
			++path;
		if (rc) {
			if (rc != FSL_RC_NOT_FOUND ||
			    (!fsl_strcmp(artifact1, "current") && !artifact2)) {

				rc = RC(rc, "invalid artifact hash: %s", path);


				goto end;
			}
			rc = 0;
			fcli_err_reset();
			/* Path may be valid in tree of specified commit(s). */
			const fsl_card_F *cf = NULL;
			rc = fsl_deck_load_sym(f, &d, artifact1,
			    FSL_SATYPE_CHECKIN);
			if (rc)
				goto end;
			cf = fsl_deck_F_search(&d, path);
			if (cf == NULL) {
				if (!artifact2) {
					rc = RC(FSL_RC_NOT_FOUND,
					    "'%s' not found in tree [%s]", path,
					    artifact1);
					goto end;
				}
				fsl_deck_finalize(&d);
				rc = fsl_deck_load_sym(f, &d, artifact2,
				    FSL_SATYPE_CHECKIN);
				if (rc)
					goto end;
				cf = fsl_deck_F_search(&d, path);
				if (cf == NULL) {
					rc = RC(FSL_RC_NOT_FOUND,
					    "'%s' not found in trees [%s] [%s]",
					    path, artifact1, artifact2);
					goto end;
				}
			}
		}


		path_to_diff = fsl_strdup(path);
		if (path_to_diff == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		rc = fnc_pathlist_insert(&ins, &paths, path_to_diff, NULL);
		if (rc || ins == NULL /* Duplicate path. */)
			fsl_free(path_to_diff);
		if (rc)
			goto end;
	}

	if (diff_type != FNC_DIFF_BLOB && diff_type != FNC_DIFF_CKOUT) {
		q = fsl_stmt_malloc();
		rc = commit_builder(&commit, rid, q);
		if (rc)
			goto end;
		if (commit->prid == prid)
			showmeta = true;
		else {
			fsl_free(commit->puuid);
			commit->prid = prid;
			commit->puuid = fsl_rid_to_uuid(f, prid);
		}
	} else {
		commit = calloc(1, sizeof(*commit));
		if (commit == NULL) {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
			    "%s", "calloc");
			goto end;
		}
		commit->prid = prid;
		commit->rid = rid;
		commit->puuid = fsl_rid_to_uuid(f, prid);
		commit->uuid = fsl_rid_to_uuid(f, rid);
		commit->type = fsl_strdup("blob");
		commit->diff_type = diff_type;
	}

	rc = init_curses();
	if (rc)
		goto end;
	rc = init_unveil(REPODB, CKOUTDIR, false);

	if (rc)
		goto end;

	view = view_open(0, 0, 0, 0, FNC_VIEW_DIFF);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_diff_view(view, commit, &paths, NULL, showmeta);
	if (!rc)
		rc = view_loop(view);
end:
	fsl_free(path0);
	fsl_deck_finalize(&d);
	fsl_stmt_finalize(q);
	if (commit)







|
|
<
<






|






|











<
<

|
|
>
|
>
>


|
<









|

















|
>
>


|















|









|













|
>





|



|







9542
9543
9544
9545
9546
9547
9548
9549
9550


9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575


9576
9577
9578
9579
9580
9581
9582
9583
9584
9585

9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
		    &rid)) {
			artifact2 = fcli_next_arg(true);
			diff_type = FNC_DIFF_COMMIT;
			if (!fsl_rid_is_a_checkin(f, rid))
				++blob;
		}
	}
	if (fcli_error()->code == FSL_RC_NOT_FOUND)
		RC_RESET(rc);  /* If args aren't symbols, treat as paths. */


	if (blob == 2)
		diff_type = FNC_DIFF_BLOB;
	if (!artifact1 && diff_type != FNC_DIFF_BLOB) {
		artifact1 = "current";
		rc = fsl_sym_to_rid(f, artifact1, FSL_SATYPE_CHECKIN, &prid);
		if (rc || prid < 0) {
			rc = RC(rc, "fsl_sym_to_rid");
			goto end;
		}
	}
	if (!artifact2 && diff_type != FNC_DIFF_BLOB) {
		fsl_ckout_version_info(f, &rid, NULL);
		if ((rc = fsl_ckout_changes_scan(f)))
			return RC(rc, "fsl_ckout_changes_scan");
		if (!fsl_strcmp(artifact1, "current") &&
		    !fsl_ckout_has_changes(f)) {
			fsl_fprintf(stdout, "No local changes.\n");
			return rc;
		}
	}
	while (fcli_next_arg(false) && diff_type != FNC_DIFF_BLOB) {
		struct fnc_pathlist_entry *ins;
		char *path, *path_to_diff;
		rc = map_repo_path(&path0);
		path = path0;


		if (rc) {
			if (rc != FSL_RC_UNKNOWN_RESOURCE) {
				if (!fsl_strcmp(artifact1, "current") &&
				    !artifact2) {
					rc = RC(rc, "invalid artifact hash: %s",
					    path);
				}
				goto end;
			}
			RC_RESET(rc);

			/* Path may be valid in tree of specified commit(s). */
			const fsl_card_F *cf = NULL;
			rc = fsl_deck_load_sym(f, &d, artifact1,
			    FSL_SATYPE_CHECKIN);
			if (rc)
				goto end;
			cf = fsl_deck_F_search(&d, path);
			if (cf == NULL) {
				if (!artifact2) {
					rc = RC(FSL_RC_UNKNOWN_RESOURCE,
					    "'%s' not found in tree [%s]", path,
					    artifact1);
					goto end;
				}
				fsl_deck_finalize(&d);
				rc = fsl_deck_load_sym(f, &d, artifact2,
				    FSL_SATYPE_CHECKIN);
				if (rc)
					goto end;
				cf = fsl_deck_F_search(&d, path);
				if (cf == NULL) {
					rc = RC(FSL_RC_NOT_FOUND,
					    "'%s' not found in trees [%s] [%s]",
					    path, artifact1, artifact2);
					goto end;
				}
			}
		} else
			while (path[0] == '/')
				++path;
		path_to_diff = fsl_strdup(path);
		if (path_to_diff == NULL) {
			rc = RC(FSL_RC_ERROR, "fsl_strdup");
			goto end;
		}
		rc = fnc_pathlist_insert(&ins, &paths, path_to_diff, NULL);
		if (rc || ins == NULL /* Duplicate path. */)
			fsl_free(path_to_diff);
		if (rc)
			goto end;
	}

	if (diff_type != FNC_DIFF_BLOB && diff_type != FNC_DIFF_CKOUT) {
		q = fsl_stmt_malloc();
		rc = commit_builder(&commit, rid, q);
		if (rc)
			goto end;
		if (commit->prid == prid)
			diff_mode = COMMIT_META;
		else {
			fsl_free(commit->puuid);
			commit->prid = prid;
			commit->puuid = fsl_rid_to_uuid(f, prid);
		}
	} else {
		commit = calloc(1, sizeof(*commit));
		if (commit == NULL) {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
			    "calloc");
			goto end;
		}
		commit->prid = prid;
		commit->rid = rid;
		commit->puuid = fsl_rid_to_uuid(f, prid);
		commit->uuid = fsl_rid_to_uuid(f, rid);
		commit->type = fsl_strdup("blob");
		commit->diff_type = diff_type;
	}

	rc = init_curses();
	if (rc)
		goto end;
	rc = init_unveil(((const char *[]){REPODB, CKOUTDIR, P_tmpdir,
	    gettzfile()}), ((const char *[]){"rw", "rwc", "rwc", "r"}), 4, true);
	if (rc)
		goto end;

	view = view_open(0, 0, 0, 0, FNC_VIEW_DIFF);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "view_open");
		goto end;
	}

	rc = open_diff_view(view, commit, &paths, NULL, diff_mode);
	if (!rc)
		rc = view_loop(view);
end:
	fsl_free(path0);
	fsl_deck_finalize(&d);
	fsl_stmt_finalize(q);
	if (commit)
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
    struct commit_entry *entry, const char *path)
{
	struct fnc_view	*tree_view;
	int		 rc = 0;

	tree_view = view_open(0, 0, start_ln, start_col, FNC_VIEW_TREE);
	if (tree_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	rc = open_tree_view(tree_view, path, entry->commit->rid);
	if (rc)
		return rc;

	*new_view = tree_view;








|







9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
    struct commit_entry *entry, const char *path)
{
	struct fnc_view	*tree_view;
	int		 rc = 0;

	tree_view = view_open(0, 0, start_ln, start_col, FNC_VIEW_TREE);
	if (tree_view == NULL)
		return RC(FSL_RC_ERROR, "view_open");

	rc = open_tree_view(tree_view, path, entry->commit->rid);
	if (rc)
		return rc;

	*new_view = tree_view;

7107
7108
7109
7110
7111
7112
7113
7114

7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
		    fcli_progname());
		goto end;
	}

	rc = init_curses();
	if (rc)
		goto end;
	rc = init_unveil(REPODB, CKOUTDIR, false);

	if (rc)
		goto end;

	view = view_open(0, 0, 0, 0, FNC_VIEW_TREE);
	if (view == NULL) {
		RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_tree_view(view, path, rid);
	if (!rc)
		rc = view_loop(view);
end:







|
>





|







9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
		    fcli_progname());
		goto end;
	}

	rc = init_curses();
	if (rc)
		goto end;
	rc = init_unveil(((const char *[]){REPODB, CKOUTDIR, P_tmpdir,
	    gettzfile()}), ((const char *[]){"rw", "rwc", "rwc", "r"}), 4, true);
	if (rc)
		goto end;

	view = view_open(0, 0, 0, 0, FNC_VIEW_TREE);
	if (view == NULL) {
		RC(FSL_RC_ERROR, "view_open");
		goto end;
	}

	rc = open_tree_view(view, path, rid);
	if (!rc)
		rc = view_loop(view);
end:
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152

	TAILQ_INIT(&s->parents);
	s->show_id = false;
	s->colour = !fnc_init.nocolour && has_colors();
	s->rid = rid;
	s->commit_id = fsl_rid_to_uuid(f, rid);
	if (s->commit_id == NULL)
		return RC(FSL_RC_AMBIGUOUS, "%s", "fsl_rid_to_uuid");

	/*
	 * Construct tree of entire repository from which all (sub)tress will
	 * be derived. This object will be released when this view closes.
	 */
	rc = create_repository_tree(&s->repo, &s->commit_id, s->rid);
	if (rc)







|







9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799

	TAILQ_INIT(&s->parents);
	s->show_id = false;
	s->colour = !fnc_init.nocolour && has_colors();
	s->rid = rid;
	s->commit_id = fsl_rid_to_uuid(f, rid);
	if (s->commit_id == NULL)
		return RC(FSL_RC_AMBIGUOUS, "fsl_rid_to_uuid");

	/*
	 * Construct tree of entire repository from which all (sub)tress will
	 * be derived. This object will be released when this view closes.
	 */
	rc = create_repository_tree(&s->repo, &s->commit_id, s->rid);
	if (rc)
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
		rc = walk_tree_path(s, s->repo, &s->root, path);
		if (rc)
			goto end;
	}


	if ((s->tree_label = fsl_mprintf("checkin %s", s->commit_id)) == NULL) {
		rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		goto end;
	}

	s->first_entry_onscreen = &s->tree->entries[0];
	s->selected_entry = &s->tree->entries[0];

	if (s->colour) {







|







9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
		rc = walk_tree_path(s, s->repo, &s->root, path);
		if (rc)
			goto end;
	}


	if ((s->tree_label = fsl_mprintf("checkin %s", s->commit_id)) == NULL) {
		rc = RC(FSL_RC_RANGE, "fsl_mprintf");
		goto end;
	}

	s->first_entry_onscreen = &s->tree->entries[0];
	s->selected_entry = &s->tree->entries[0];

	if (s->colour) {
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236

		slash = strchr(p, '/');
		if (slash == NULL)
			te_name = fsl_strdup(p);
		else
			te_name = fsl_strndup(p, slash - p);
		if (te_name == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			break;
		}

		te = find_tree_entry(s->tree, te_name, fsl_strlen(te_name));
		if (te == NULL) {
			rc = RC(FSL_RC_NOT_FOUND, "find_tree_entry(%s)",
			    te_name);







|







9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883

		slash = strchr(p, '/');
		if (slash == NULL)
			te_name = fsl_strdup(p);
		else
			te_name = fsl_strndup(p, slash - p);
		if (te_name == NULL) {
			rc = RC(FSL_RC_ERROR, "fsl_strdup");
			break;
		}

		te = find_tree_entry(s->tree, te_name, fsl_strlen(te_name));
		if (te == NULL) {
			rc = RC(FSL_RC_NOT_FOUND, "find_tree_entry(%s)",
			    te_name);
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259

		slash = strchr(p, '/');
		if (slash)
			subpath = fsl_strndup(path, slash - path);
		else
			subpath = fsl_strdup(path);
		if (subpath == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			break;
		}

		rc = tree_builder(repo, &tree, subpath + 1 /* Leading slash */);
		if (rc)
			break;
		rc = visit_subtree(s, tree);







|







9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906

		slash = strchr(p, '/');
		if (slash)
			subpath = fsl_strndup(path, slash - path);
		else
			subpath = fsl_strdup(path);
		if (subpath == NULL) {
			rc = RC(FSL_RC_ERROR, "fsl_strdup");
			break;
		}

		rc = tree_builder(repo, &tree, subpath + 1 /* Leading slash */);
		if (rc)
			break;
		rc = visit_subtree(s, tree);
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
	struct fnc_repository_tree	*ptr;
	fsl_deck			 d = fsl_deck_empty;
	const fsl_card_F		*cf = NULL;
	int				 rc = 0;

	ptr = fsl_malloc(sizeof(struct fnc_repository_tree));
	if (ptr == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	memset(ptr, 0, sizeof(struct fnc_repository_tree));

	rc = fsl_deck_load_rid(f, &d, rid, FSL_SATYPE_CHECKIN);
	if (rc)
		return RC(rc, "fsl_deck_load_rid(%d) [%s]", rid, id);
	rc = fsl_deck_F_rewind(&d);
	if (rc)
		goto end;
	rc = fsl_deck_F_next(&d, &cf);
	if (rc)
		goto end;

	while (cf) {
		char		*filename = NULL, *uuid = NULL;
		fsl_time_t	 mtime;

		filename = fsl_strdup(cf->name);
		if (filename == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		uuid = fsl_strdup(cf->uuid);
		if (uuid == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		rc = fsl_mtime_of_F_card(f, rid, cf, &mtime);
		if (!rc)
			rc = link_tree_node(ptr, filename, uuid,
			    fsl_unix_to_julian(mtime));
		fsl_free(filename);







|




|













|




|







9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
	struct fnc_repository_tree	*ptr;
	fsl_deck			 d = fsl_deck_empty;
	const fsl_card_F		*cf = NULL;
	int				 rc = 0;

	ptr = fsl_malloc(sizeof(struct fnc_repository_tree));
	if (ptr == NULL)
		return RC(FSL_RC_ERROR, "fsl_malloc");
	memset(ptr, 0, sizeof(struct fnc_repository_tree));

	rc = fsl_deck_load_rid(f, &d, rid, FSL_SATYPE_CHECKIN);
	if (rc)
		return RC(rc, "fsl_deck_load_rid(%d) [%s]", rid, *id);
	rc = fsl_deck_F_rewind(&d);
	if (rc)
		goto end;
	rc = fsl_deck_F_next(&d, &cf);
	if (rc)
		goto end;

	while (cf) {
		char		*filename = NULL, *uuid = NULL;
		fsl_time_t	 mtime;

		filename = fsl_strdup(cf->name);
		if (filename == NULL) {
			rc = RC(FSL_RC_ERROR, "fsl_strdup");
			goto end;
		}
		uuid = fsl_strdup(cf->uuid);
		if (uuid == NULL) {
			rc = RC(FSL_RC_ERROR, "fsl_strdup");
			goto end;
		}
		rc = fsl_mtime_of_F_card(f, rid, cf, &mtime);
		if (!rc)
			rc = link_tree_node(ptr, filename, uuid,
			    fsl_unix_to_julian(mtime));
		fsl_free(filename);
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
	struct fnc_tree_entry		*te = NULL;
	struct fnc_repo_tree_node	*tn = NULL;
	int				 i = 0;

	*tree = NULL;
	*tree = fsl_malloc(sizeof(**tree));
	if (*tree == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	memset(*tree, 0, sizeof(**tree));

	/*
	 * Count how many elements will comprise the tree to be allocated.
	 * If dir is the root of the repository tree (i.e., "/"), only tree
	 * nodes (tn) with no parent_dir belong to this tree. Otherwise, tree
	 * nodes whose parent_dir matches dir will comprise the requested tree.
	 */
	for(tn = repo->head; tn; tn = tn->next) {
		if ((!tn->parent_dir && fsl_strcmp(dir, "/")) ||
		    (tn->parent_dir && fsl_strcmp(dir, tn->parent_dir->path)))
			continue;
		++i;
	}
	(*tree)->entries = calloc(i, sizeof(struct fnc_tree_entry));
	if ((*tree)->entries == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");
	/* Construct the tree to be displayed. */
	for(tn = repo->head, i = 0; tn; tn = tn->next) {
		if ((!tn->parent_dir && fsl_strcmp(dir, "/")) ||
		    (tn->parent_dir && fsl_strcmp(dir, tn->parent_dir->path)))
			continue;
		te = &(*tree)->entries[i];
		te->mode = tn->mode;
		te->mtime = tn->mtime;
		te->basename = fsl_strdup(tn->basename);
		if (te->basename == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		te->path = fsl_strdup(tn->path);
		if (te->path == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		te->uuid = fsl_strdup(tn->uuid);
		if (te->uuid == NULL && !S_ISDIR(te->mode))
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		te->idx = i++;
	}
	(*tree)->nentries = i;

	return 0;
}








|
















|










|


|


|







9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
	struct fnc_tree_entry		*te = NULL;
	struct fnc_repo_tree_node	*tn = NULL;
	int				 i = 0;

	*tree = NULL;
	*tree = fsl_malloc(sizeof(**tree));
	if (*tree == NULL)
		return RC(FSL_RC_ERROR, "fsl_malloc");
	memset(*tree, 0, sizeof(**tree));

	/*
	 * Count how many elements will comprise the tree to be allocated.
	 * If dir is the root of the repository tree (i.e., "/"), only tree
	 * nodes (tn) with no parent_dir belong to this tree. Otherwise, tree
	 * nodes whose parent_dir matches dir will comprise the requested tree.
	 */
	for(tn = repo->head; tn; tn = tn->next) {
		if ((!tn->parent_dir && fsl_strcmp(dir, "/")) ||
		    (tn->parent_dir && fsl_strcmp(dir, tn->parent_dir->path)))
			continue;
		++i;
	}
	(*tree)->entries = calloc(i, sizeof(struct fnc_tree_entry));
	if ((*tree)->entries == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "calloc");
	/* Construct the tree to be displayed. */
	for(tn = repo->head, i = 0; tn; tn = tn->next) {
		if ((!tn->parent_dir && fsl_strcmp(dir, "/")) ||
		    (tn->parent_dir && fsl_strcmp(dir, tn->parent_dir->path)))
			continue;
		te = &(*tree)->entries[i];
		te->mode = tn->mode;
		te->mtime = tn->mtime;
		te->basename = fsl_strdup(tn->basename);
		if (te->basename == NULL)
			return RC(FSL_RC_ERROR, "fsl_strdup");
		te->path = fsl_strdup(tn->path);
		if (te->path == NULL)
			return RC(FSL_RC_ERROR, "fsl_strdup");
		te->uuid = fsl_strdup(tn->uuid);
		if (te->uuid == NULL && !S_ISDIR(te->mode))
			return RC(FSL_RC_ERROR, "fsl_strdup");
		te->idx = i++;
	}
	(*tree)->nentries = i;

	return 0;
}

7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
		 * If not at end of path string, node is a directory so don't
		 * allocate space for the hash.
		 */
		if (uuid != 0 && path[i] == '\0')
			nodesz += FSL_STRLEN_K256 + 1; /* NUL */
		tn = fsl_malloc(nodesz);
		if (tn == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
		memset(tn, 0, sizeof(*tn));

		tn->path = (char *)&tn[1];
		memcpy(tn->path, path, i);
		tn->path[i] = '\0';
		tn->pathlen = i;








|







10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
		 * If not at end of path string, node is a directory so don't
		 * allocate space for the hash.
		 */
		if (uuid != 0 && path[i] == '\0')
			nodesz += FSL_STRLEN_K256 + 1; /* NUL */
		tn = fsl_malloc(nodesz);
		if (tn == NULL)
			return RC(FSL_RC_ERROR, "fsl_malloc");
		memset(tn, 0, sizeof(*tn));

		tn->path = (char *)&tn[1];
		memcpy(tn->path, path, i);
		tn->path[i] = '\0';
		tn->pathlen = i;

7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
	TAILQ_FOREACH(pt, parents, entry)
		len += strlen(pt->selected_entry->basename) + 1 /* slash */;
	if (te)
		len += strlen(te->basename);

	*path = calloc(1, len);
	if (path == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");

	(*path)[0] = '/';  /* Make it absolute from the repository root. */
	pt = TAILQ_LAST(parents, fnc_parent_trees);
	while (pt) {
		const char *name = pt->selected_entry->basename;
		if (strlcat(*path, name, len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, %s, %d)",
			    *path, name, len);
			goto end;
		}
		if (strlcat(*path, "/", len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, \"/\", %d)",
			    *path, len);
			goto end;
		}
		pt = TAILQ_PREV(pt, fnc_parent_trees, entry);
	}
	if (te) {
		if (strlcat(*path, te->basename, len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, %s, %d)",
			    *path, te->basename, len);
			goto end;
		}
	}
end:
	if (rc) {
		fsl_free(*path);







|






|




|







|







10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
	TAILQ_FOREACH(pt, parents, entry)
		len += strlen(pt->selected_entry->basename) + 1 /* slash */;
	if (te)
		len += strlen(te->basename);

	*path = calloc(1, len);
	if (path == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "calloc");

	(*path)[0] = '/';  /* Make it absolute from the repository root. */
	pt = TAILQ_LAST(parents, fnc_parent_trees);
	while (pt) {
		const char *name = pt->selected_entry->basename;
		if (strlcat(*path, name, len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, %s, %lu)",
			    *path, name, len);
			goto end;
		}
		if (strlcat(*path, "/", len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, \"/\", %lu)",
			    *path, len);
			goto end;
		}
		pt = TAILQ_PREV(pt, fnc_parent_trees, entry);
	}
	if (te) {
		if (strlcat(*path, te->basename, len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, %s, %lu)",
			    *path, te->basename, len);
			goto end;
		}
	}
end:
	if (rc) {
		fsl_free(*path);
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
		te = &s->tree->entries[idx];
		mode = te->mode;

		if (s->show_id) {
			idstr = fsl_strdup(te->uuid);
			/* Directories don't have UUIDs; pad with "..." dots. */
			if (idstr == NULL && !S_ISDIR(mode))
				return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			/* If needed, pad SHA1 hash to align w/ SHA3 hashes. */
			if (idstr == NULL || fsl_strlen(idstr) < hashlen) {
				char buf[hashlen], pad = '.';
				buf[hashlen] = '\0';
				idstr = fsl_mprintf("%s%s", idstr ? idstr : "",
				    (char *)memset(buf, pad,
				    hashlen - fsl_strlen(idstr)));
				if (idstr == NULL)
					return RC(FSL_RC_RANGE,
					    "%s", "fsl_mprintf");
				idstr[hashlen] = '\0';
				/* idstr = fsl_mprintf("%*c", hashlen, ' '); */
			}
		}
		if (S_ISLNK(mode)) {
			fsl_size_t	ch;








|








|
<







10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381

10382
10383
10384
10385
10386
10387
10388
		te = &s->tree->entries[idx];
		mode = te->mode;

		if (s->show_id) {
			idstr = fsl_strdup(te->uuid);
			/* Directories don't have UUIDs; pad with "..." dots. */
			if (idstr == NULL && !S_ISDIR(mode))
				return RC(FSL_RC_ERROR, "fsl_strdup");
			/* If needed, pad SHA1 hash to align w/ SHA3 hashes. */
			if (idstr == NULL || fsl_strlen(idstr) < hashlen) {
				char buf[hashlen], pad = '.';
				buf[hashlen] = '\0';
				idstr = fsl_mprintf("%s%s", idstr ? idstr : "",
				    (char *)memset(buf, pad,
				    hashlen - fsl_strlen(idstr)));
				if (idstr == NULL)
					return RC(FSL_RC_RANGE, "fsl_mprintf");

				idstr[hashlen] = '\0';
				/* idstr = fsl_mprintf("%*c", hashlen, ' '); */
			}
		}
		if (S_ISLNK(mode)) {
			fsl_size_t	ch;

7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
		line = fsl_mprintf("%s%s%.*s  %s%s%s%s", idstr ? idstr : "",
		    (*iso8601 && idstr) ?  "  " : "", ISO8601_DATE_HHMM,
		    *iso8601 ? iso8601 : "", te->basename, modestr,
		    targetlnk ? " -> ": "", targetlnk ? targetlnk : "");
		fsl_free(idstr);
		fsl_free(targetlnk);
		if (rc || line == NULL)
			return RC(rc ? rc : FSL_RC_RANGE, "%s",
			    rc ? "fsl_julian_to_iso8601" : "fsl_mprintf");
		rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0, false);
		if (rc) {
			fsl_free(line);
			break;
		}
		if (n == s->selected) {
			wattr_on(view->window, A_REVERSE, NULL);







|
|







10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
		line = fsl_mprintf("%s%s%.*s  %s%s%s%s", idstr ? idstr : "",
		    (*iso8601 && idstr) ?  "  " : "", ISO8601_DATE_HHMM,
		    *iso8601 ? iso8601 : "", te->basename, modestr,
		    targetlnk ? " -> ": "", targetlnk ? targetlnk : "");
		fsl_free(idstr);
		fsl_free(targetlnk);
		if (rc || line == NULL)
			return rc ? RC(rc, "fsl_julian_to_iso8601") :
			    RC(FSL_RC_RANGE, "fsl_mprintf");
		rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0, false);
		if (rc) {
			fsl_free(line);
			break;
		}
		if (n == s->selected) {
			wattr_on(view->window, A_REVERSE, NULL);
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
		    fsl_buffer_cstr(&fb));
		goto end;
	}

	bufsz = s.st_size ? (s.st_size + 1 /* NUL */) : PATH_MAX;
	buf = fsl_malloc(bufsz);
	if (buf == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_malloc");
		goto end;
	}

	nbytes = readlink(fsl_buffer_cstr(&fb), buf, bufsz);
	if (nbytes == -1) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "readlink(%s)",
		    fsl_buffer_cstr(&fb));







|







10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
		    fsl_buffer_cstr(&fb));
		goto end;
	}

	bufsz = s.st_size ? (s.st_size + 1 /* NUL */) : PATH_MAX;
	buf = fsl_malloc(bufsz);
	if (buf == NULL) {
		rc = RC(FSL_RC_ERROR, "fsl_malloc");
		goto end;
	}

	nbytes = readlink(fsl_buffer_cstr(&fb), buf, bufsz);
	if (nbytes == -1) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "readlink(%s)",
		    fsl_buffer_cstr(&fb));
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
	switch (ch) {
	case 'b':
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		branch_view = view_open(view->nlines, view->ncols,
		    view->start_ln, start_col, FNC_VIEW_BRANCH);
		if (branch_view == NULL)
			return RC(FSL_RC_ERROR, "%s", "view_open");
		rc = open_branch_view(branch_view, BRANCH_LS_OPEN_CLOSED, NULL,
		    0, 0);
		if (rc) {
			view_close(branch_view);
			return rc;
		}
		view->active = false;







|







10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
	switch (ch) {
	case 'b':
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		branch_view = view_open(view->nlines, view->ncols,
		    view->start_ln, start_col, FNC_VIEW_BRANCH);
		if (branch_view == NULL)
			return RC(FSL_RC_ERROR, "view_open");
		rc = open_branch_view(branch_view, BRANCH_LS_OPEN_CLOSED, NULL,
		    0, 0);
		if (rc) {
			view_close(branch_view);
			return rc;
		}
		view->active = false;
8071
8072
8073
8074
8075
8076
8077

8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106

	fid = fsl_uuid_to_rid(f, s->selected_entry->uuid);
	rc = fsl_content_get(f, fid, &buf);
	if (rc)
		goto end;

	if (fsl_looks_like_binary(&buf))

		sitrep(view, "-- cannot blame binary file --",
		    SR_UPDATE | SR_SLEEP);
	else
		rc = request_view(new_view, view, FNC_VIEW_BLAME);
end:
	fsl_buffer_clear(&buf);
	return rc;
}

static int
timeline_tree_entry(struct fnc_view **new_view, int start_col,
    struct fnc_tree_view_state *s)
{
	struct fnc_view	*timeline_view;
	char		*path;
	int		 rc = 0;

	*new_view = NULL;

	timeline_view = view_open(0, 0, 0, start_col, FNC_VIEW_TIMELINE);
	if (timeline_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	/* Construct repository relative path for timeline query. */
	rc = tree_entry_path(&path, &s->parents, s->selected_entry);
	if (rc)
		return rc;

	rc = open_timeline_view(timeline_view, s->rid, path, NULL);







>
|
<



















|







10717
10718
10719
10720
10721
10722
10723
10724
10725

10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752

	fid = fsl_uuid_to_rid(f, s->selected_entry->uuid);
	rc = fsl_content_get(f, fid, &buf);
	if (rc)
		goto end;

	if (fsl_looks_like_binary(&buf))
		sitrep(view, SR_UPDATE | SR_SLEEP,
		    "-- cannot blame binary file --");

	else
		rc = request_view(new_view, view, FNC_VIEW_BLAME);
end:
	fsl_buffer_clear(&buf);
	return rc;
}

static int
timeline_tree_entry(struct fnc_view **new_view, int start_col,
    struct fnc_tree_view_state *s)
{
	struct fnc_view	*timeline_view;
	char		*path;
	int		 rc = 0;

	*new_view = NULL;

	timeline_view = view_open(0, 0, 0, start_col, FNC_VIEW_TIMELINE);
	if (timeline_view == NULL)
		return RC(FSL_RC_ERROR, "view_open");

	/* Construct repository relative path for timeline query. */
	rc = tree_entry_path(&path, &s->parents, s->selected_entry);
	if (rc)
		return rc;

	rc = open_timeline_view(timeline_view, s->rid, path, NULL);
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
static int
visit_subtree(struct fnc_tree_view_state *s, struct fnc_tree_object *subtree)
{
	struct fnc_parent_tree	*parent;

	parent = calloc(1, sizeof(*parent));
	if (parent == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");

	parent->tree = s->tree;
	parent->first_entry_onscreen = s->first_entry_onscreen;
	parent->selected_entry = s->selected_entry;
	parent->selected = s->selected;
	TAILQ_INSERT_HEAD(&s->parents, parent, entry);
	s->tree = subtree;







|







10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
static int
visit_subtree(struct fnc_tree_view_state *s, struct fnc_tree_object *subtree)
{
	struct fnc_parent_tree	*parent;

	parent = calloc(1, sizeof(*parent));
	if (parent == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "calloc");

	parent->tree = s->tree;
	parent->first_entry_onscreen = s->first_entry_onscreen;
	parent->selected_entry = s->selected_entry;
	parent->selected = s->selected;
	TAILQ_INSERT_HEAD(&s->parents, parent, entry);
	s->tree = subtree;
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208

	rc = tree_entry_path(&path, parents, te);
	if (rc)
		return rc;

	blame_view = view_open(0, 0, start_ln, start_col, FNC_VIEW_BLAME);
	if (blame_view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_blame_view(blame_view, path, commit_id, 0, 0, NULL);
	if (rc)
		view_close(blame_view);
	else







|







10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854

	rc = tree_entry_path(&path, parents, te);
	if (rc)
		return rc;

	blame_view = view_open(0, 0, start_ln, start_col, FNC_VIEW_BLAME);
	if (blame_view == NULL) {
		rc = RC(FSL_RC_ERROR, "view_open");
		goto end;
	}

	rc = open_blame_view(blame_view, path, commit_id, 0, 0, NULL);
	if (rc)
		view_close(blame_view);
	else
8398
8399
8400
8401
8402
8403
8404
8405

8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
cmd_config(const fcli_command *argv)
{
	const char	*opt = NULL, *value = NULL;
	char		*prev, *v;
	enum fnc_opt_id	 setid;
	int		 rc = FSL_RC_OK;

	rc = init_unveil(REPODIR, CKOUTDIR, true);

	if (rc)
		return rc;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	opt = fcli_next_arg(true);
	if (opt == NULL || fnc_init.lsconf) {
		if (fnc_init.unset) {
			fnc_init.err = RC(FSL_RC_MISSING_INFO,
			    "%s", "-u|--unset requires <setting>");
			usage();
			/* NOT REACHED */
		}
		return fnc_conf_lsopt(fnc_init.lsconf ? false : true);
	}

	setid = fnc_conf_str2enum(opt);







|
>











|







11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
cmd_config(const fcli_command *argv)
{
	const char	*opt = NULL, *value = NULL;
	char		*prev, *v;
	enum fnc_opt_id	 setid;
	int		 rc = FSL_RC_OK;

	rc = init_unveil(((const char *[]){REPODIR, CKOUTDIR, P_tmpdir,
	    gettzfile()}), ((const char *[]){"rwc", "rwc", "rwc", "r"}), 4, true);
	if (rc)
		return rc;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	opt = fcli_next_arg(true);
	if (opt == NULL || fnc_init.lsconf) {
		if (fnc_init.unset) {
			fnc_init.err = RC(FSL_RC_MISSING_INFO,
			    "-u|--unset requires <setting>");
			usage();
			/* NOT REACHED */
		}
		return fnc_conf_lsopt(fnc_init.lsconf ? false : true);
	}

	setid = fnc_conf_str2enum(opt);
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
set_colours(struct fnc_colours *s, enum fnc_view_id vid)
{
	int rc = FSL_RC_OK;

	switch (vid) {
	case FNC_VIEW_DIFF: {
		static const char *regexp_diff[] = {
		    "^((checkin|wiki|ticket|technote) "
		    "[0-9a-f]|hash [+-] |\\[[+~>-]] |[+-]{3} )",
		    "^user:", "^date:", "^tags:", "^-|^[0-9 ]+ -",
		    "^\\+|^[0-9 ]+ \\+", "^@@",
		    /*
		     * XXX Ugly hack to fail matching _DIFF_SBS_EDIT early
		     * until all diff modes use the new line_type interface.
		     */
		    "a^"







|
|







11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
set_colours(struct fnc_colours *s, enum fnc_view_id vid)
{
	int rc = FSL_RC_OK;

	switch (vid) {
	case FNC_VIEW_DIFF: {
		static const char *regexp_diff[] = {
		    "^((checkin|wiki|ticket|technote) [0-9a-f]\\s\\s*$|"
		    "hash [+-] |\\[[+~>-]] |[+-]{3} )",
		    "^user:", "^date:", "^tags:", "^-|^[0-9 ]+ -",
		    "^\\+|^[0-9 ]+ \\+", "^@@",
		    /*
		     * XXX Ugly hack to fail matching _DIFF_SBS_EDIT early
		     * until all diff modes use the new line_type interface.
		     */
		    "a^"
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
		         init_colour(FNC_COLOUR_BRANCH_PRIVATE)}
		};
		rc = set_colour_scheme(s, pairs_branch, regexp_branch,
		    nitems(regexp_branch));
		break;
	}
	default:
		rc = RC(FSL_RC_TYPE, "invalid fnc_view_id: %s", vid);
	}

	init_pair(FNC_COLOUR_HL_SEARCH, init_colour(FNC_COLOUR_HL_SEARCH), -1);

	return rc;
}

static int
set_colour_scheme(struct fnc_colours *colours, const int (*pairs)[2],
    const char **regexp, int n)
{
	struct fnc_colour	*colour;
	int			 idx, rc = 0;

	for (idx = 0; idx < n; ++idx) {
		colour = fsl_malloc(sizeof(*colour));
		if (colour == NULL)
			return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
			    "%s", "fsl_malloc");

		rc = regcomp(&colour->regex, regexp[idx],
		    REG_EXTENDED | REG_NEWLINE | REG_NOSUB);
		if (rc) {
			static char regerr[512];
			regerror(rc, &colour->regex, regerr, sizeof(regerr));
			fsl_free(colour);







|


















|







11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
		         init_colour(FNC_COLOUR_BRANCH_PRIVATE)}
		};
		rc = set_colour_scheme(s, pairs_branch, regexp_branch,
		    nitems(regexp_branch));
		break;
	}
	default:
		rc = RC(FSL_RC_TYPE, "invalid fnc_view_id: %d", vid);
	}

	init_pair(FNC_COLOUR_HL_SEARCH, init_colour(FNC_COLOUR_HL_SEARCH), -1);

	return rc;
}

static int
set_colour_scheme(struct fnc_colours *colours, const int (*pairs)[2],
    const char **regexp, int n)
{
	struct fnc_colour	*colour;
	int			 idx, rc = 0;

	for (idx = 0; idx < n; ++idx) {
		colour = fsl_malloc(sizeof(*colour));
		if (colour == NULL)
			return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
			    "fsl_malloc");

		rc = regcomp(&colour->regex, regexp[idx],
		    REG_EXTENDED | REG_NEWLINE | REG_NOSUB);
		if (rc) {
			static char regerr[512];
			regerror(rc, &colour->regex, regerr, sizeof(regerr));
			fsl_free(colour);
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
	fsl_db	*db = NULL;
	char	*optval = NULL, *envvar = NULL;

	db = fsl_needs_repo(f);

	if (!db) {
		/* Theoretically, this shouldn't happen. */
		RC(FSL_RC_DB, "%s", "fsl_needs_repo");
		return NULL;
	}

	optval = fsl_db_g_text(db, NULL,
	    "SELECT value FROM config WHERE name=%Q", fnc_conf_enum2str(id));

	if (optval == NULL || ls)







|







11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
	fsl_db	*db = NULL;
	char	*optval = NULL, *envvar = NULL;

	db = fsl_needs_repo(f);

	if (!db) {
		/* Theoretically, this shouldn't happen. */
		RC(FSL_RC_DB, "fsl_needs_repo");
		return NULL;
	}

	optval = fsl_db_g_text(db, NULL,
	    "SELECT value FROM config WHERE name=%Q", fnc_conf_enum2str(id));

	if (optval == NULL || ls)
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
{
	fsl_cx	*const f = fcli_cx();
	fsl_db	*db = NULL;

	db = fsl_needs_repo(f);

	if (!db)  /* Theoretically, this shouldn't happen. */
		return RC(FSL_RC_DB, "%s", "fsl_needs_repo");

	if (unset)
		return fsl_db_exec(db, "DELETE FROM config WHERE name=%Q",
		    fnc_conf_enum2str(id));

	return fsl_db_exec(db,
	    "INSERT OR REPLACE INTO config(name, value, mtime) "







|







11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
{
	fsl_cx	*const f = fcli_cx();
	fsl_db	*db = NULL;

	db = fsl_needs_repo(f);

	if (!db)  /* Theoretically, this shouldn't happen. */
		return RC(FSL_RC_DB, "fsl_needs_repo");

	if (unset)
		return fsl_db_exec(db, "DELETE FROM config WHERE name=%Q",
		    fnc_conf_enum2str(id));

	return fsl_db_exec(db,
	    "INSERT OR REPLACE INTO config(name, value, mtime) "
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919

8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
		fsl_ckout_version_info(f, &rid, NULL);
		if (!rid)  /* -R|--repo option used */
			fsl_sym_to_rid(f, "tip", FSL_SATYPE_CHECKIN, &rid);
	}

	rc = map_repo_path(&path);
	if (rc) {
		if (rc != FSL_RC_NOT_FOUND || !fnc_init.sym)
			goto end;
		/* Path may be valid in repository tree of specified commit. */
		rc = 0;
		fcli_err_reset();
	}

	commit_id = fsl_rid_to_uuid(f, rid);
	if (rc || (path[0] == '/' && path[1] == '\0')) {
		rc = rc ? rc : RC(FSL_RC_MISSING_INFO,
		    "%s blame requires versioned file path", fcli_progname());
		goto end;
	}

	rc = init_curses();
	if (rc)
		goto end;
	rc = init_unveil(REPODB, CKOUTDIR, false);

	if (rc)
		goto end;

	view = view_open(0, 0, 0, 0, FNC_VIEW_BLAME);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", view_open);
		goto end;
	}

	rc = open_blame_view(view, path, commit_id, tip, nlimit,
	    fnc_init.lineno);
	if (rc)
		goto end;







|


|
<












|
>





|







11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552

11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
		fsl_ckout_version_info(f, &rid, NULL);
		if (!rid)  /* -R|--repo option used */
			fsl_sym_to_rid(f, "tip", FSL_SATYPE_CHECKIN, &rid);
	}

	rc = map_repo_path(&path);
	if (rc) {
		if (rc != FSL_RC_UNKNOWN_RESOURCE || !fnc_init.sym)
			goto end;
		/* Path may be valid in repository tree of specified commit. */
		RC_RESET(rc);

	}

	commit_id = fsl_rid_to_uuid(f, rid);
	if (rc || (path[0] == '/' && path[1] == '\0')) {
		rc = rc ? rc : RC(FSL_RC_MISSING_INFO,
		    "%s blame requires versioned file path", fcli_progname());
		goto end;
	}

	rc = init_curses();
	if (rc)
		goto end;
	rc = init_unveil(((const char *[]){REPODB, CKOUTDIR, P_tmpdir,
	    gettzfile()}), ((const char *[]){"rw", "rwc", "rwc", "r"}), 4, true);
	if (rc)
		goto end;

	view = view_open(0, 0, 0, 0, FNC_VIEW_BLAME);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "view_open");
		goto end;
	}

	rc = open_blame_view(view, path, commit_id, tip, nlimit,
	    fnc_init.lineno);
	if (rc)
		goto end;
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
	struct fnc_blame_view_state	*s = &view->state.blame;
	int				 rc = 0;

	CONCAT(STAILQ, _INIT)(&s->blamed_commits);

	s->path = fsl_strdup(path);
	if (s->path == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");

	rc = fnc_commit_qid_alloc(&s->blamed_commit, commit_id);
	if (rc) {
		fsl_free(s->path);
		return rc;
	}








|







11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
	struct fnc_blame_view_state	*s = &view->state.blame;
	int				 rc = 0;

	CONCAT(STAILQ, _INIT)(&s->blamed_commits);

	s->path = fsl_strdup(path);
	if (s->path == NULL)
		return RC(FSL_RC_ERROR, "fsl_strdup");

	rc = fnc_commit_qid_alloc(&s->blamed_commit, commit_id);
	if (rc) {
		fsl_free(s->path);
		return rc;
	}

9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
		    filepath, s->blamed_commit->id);
		goto end;
	}
	rc = fsl_card_F_content(f, cf, &buf);
	if (rc)
		goto end;
	if (fsl_looks_like_binary(&buf)) {
		rc = RC(FSL_RC_DIFF_BINARY, "%s", "cannot blame binary file");
		goto end;
	}

	/*
	 * We load f with the actual file content to map line offsets so we
	 * accurately find tokens when running a search.
	 */
	blame->f = tmpfile();
	if (blame->f == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "tmpfile");
		goto end;
	}

	opt = &blame->thread_cx.blame_opt;
	opt->filename = fsl_strdup(filepath);
	fcli_fax((char *)opt->filename);
	rc = fsl_sym_to_rid(f, s->blamed_commit->id, FSL_SATYPE_CHECKIN,







|









|







11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
		    filepath, s->blamed_commit->id);
		goto end;
	}
	rc = fsl_card_F_content(f, cf, &buf);
	if (rc)
		goto end;
	if (fsl_looks_like_binary(&buf)) {
		rc = RC(FSL_RC_DIFF_BINARY, "cannot blame binary file");
		goto end;
	}

	/*
	 * We load f with the actual file content to map line offsets so we
	 * accurately find tokens when running a search.
	 */
	blame->f = tmpfile();
	if (blame->f == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "tmpfile");
		goto end;
	}

	opt = &blame->thread_cx.blame_opt;
	opt->filename = fsl_strdup(filepath);
	fcli_fax((char *)opt->filename);
	rc = fsl_sym_to_rid(f, s->blamed_commit->id, FSL_SATYPE_CHECKIN,
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
		if (rc)
			goto end;
		s->gtl = ln;
	}

	blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
	if (blame->lines == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");
		goto end;
	}

	master = fsl_config_get_text(f, FSL_CONFDB_REPO, "main-branch", NULL);
	if (master == NULL) {
		master = fsl_strdup("trunk");
		if (master == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	}
	root = fsl_mprintf("root:%s", master);
	rc = fsl_sym_to_uuid(f, root, FSL_SATYPE_CHECKIN,
	    &blame->cb_cx.root_commit, NULL);
	if (rc) {
		rc = RC(rc, "%s", "fsl_sym_to_uuid");
		goto end;
	}

	blame->cb_cx.view = view;
	blame->cb_cx.lines = blame->lines;
	blame->cb_cx.nlines = blame->nlines;
	blame->cb_cx.commit_id = fsl_strdup(s->blamed_commit->id);
	if (blame->cb_cx.commit_id == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		goto end;
	}
	blame->cb_cx.quit = &s->done;

	blame->thread_cx.path = s->path;
	blame->thread_cx.cb_cx = &blame->cb_cx;
	blame->thread_cx.complete = &s->blame_complete;







|







|







|








|







11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
		if (rc)
			goto end;
		s->gtl = ln;
	}

	blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
	if (blame->lines == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "calloc");
		goto end;
	}

	master = fsl_config_get_text(f, FSL_CONFDB_REPO, "main-branch", NULL);
	if (master == NULL) {
		master = fsl_strdup("trunk");
		if (master == NULL) {
			rc = RC(FSL_RC_ERROR, "fsl_strdup");
			goto end;
		}
	}
	root = fsl_mprintf("root:%s", master);
	rc = fsl_sym_to_uuid(f, root, FSL_SATYPE_CHECKIN,
	    &blame->cb_cx.root_commit, NULL);
	if (rc) {
		rc = RC(rc, "fsl_sym_to_uuid");
		goto end;
	}

	blame->cb_cx.view = view;
	blame->cb_cx.lines = blame->lines;
	blame->cb_cx.nlines = blame->nlines;
	blame->cb_cx.commit_id = fsl_strdup(s->blamed_commit->id);
	if (blame->cb_cx.commit_id == NULL) {
		rc = RC(FSL_RC_ERROR, "fsl_strdup");
		goto end;
	}
	blame->cb_cx.quit = &s->done;

	blame->thread_cx.path = s->path;
	blame->thread_cx.cb_cx = &blame->cb_cx;
	blame->thread_cx.complete = &s->blame_complete;
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
	if (nlines) {
		if (line_offsets && *line_offsets == NULL) {
			*nlines = 1;
			nalloc = alloc_chunksz;
			*line_offsets = calloc(nalloc, sizeof(**line_offsets));
			if (*line_offsets == NULL)
				return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
				    "%s", "calloc");

			/* Consume the first line. */
			while (i < len) {
				if (buf->mem[i] == '\n')
					break;
				++i;
			}







|







11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
	if (nlines) {
		if (line_offsets && *line_offsets == NULL) {
			*nlines = 1;
			nalloc = alloc_chunksz;
			*line_offsets = calloc(nalloc, sizeof(**line_offsets));
			if (*line_offsets == NULL)
				return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
				    "calloc");

			/* Consume the first line. */
			while (i < len) {
				if (buf->mem[i] == '\n')
					break;
				++i;
			}
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249

				n = *nlines + alloc_chunksz;
				oldsz = nalloc * sizeof(**line_offsets);
				newsz = n * sizeof(**line_offsets);
				if (newsz <= oldsz) {
					size_t b = oldsz - newsz;
					if (b < oldsz / 2 &&
					    b < (size_t)getpagesize()) {
						memset((char *)*line_offsets
						    + newsz, 0, b);
						goto allocated;
					}
				}
				new = fsl_realloc(*line_offsets, newsz);
				if (new == NULL) {
					fsl_free(*line_offsets);
					*line_offsets = NULL;
					return RC(FSL_RC_ERROR, "%s",
					    "fsl_realloc");
				}
				*line_offsets = new;
allocated:
				nalloc = n;
			}
			if (line_offsets) {
				off = total_len + i + 1;
				(*line_offsets)[*nlines - 1] = off;
			}
			++i;
		}
	}
	n = fwrite(buf->mem, 1, len, out);
	if (n != len)
		return RC(ferror(out) ? fsl_errno_to_rc(errno, FSL_RC_IO)
		    : FSL_RC_IO, "%s", "fwrite");
	total_len += len;

	if (fflush(out) != 0)
		return RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fflush");
	rewind(out);

	if (filesz)
		*filesz = total_len;

	return rc;
}

static int
show_blame_view(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	int				 rc = 0;

	if (!s->blame.thread_id && !s->blame_complete) {
		rc = pthread_create(&s->blame.thread_id, NULL, blame_thread,
		    &s->blame.thread_cx);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_create");

		halfdelay(1);	/* Fast refresh while annotating.  */
	}

	if (s->blame_complete)
		cbreak();	/* Return to blocking mode. */








|









|
<















|



|



















|







11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848

11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895

				n = *nlines + alloc_chunksz;
				oldsz = nalloc * sizeof(**line_offsets);
				newsz = n * sizeof(**line_offsets);
				if (newsz <= oldsz) {
					size_t b = oldsz - newsz;
					if (b < oldsz / 2 &&
					    b < (size_t)sysconf(_SC_PAGESIZE)) {
						memset((char *)*line_offsets
						    + newsz, 0, b);
						goto allocated;
					}
				}
				new = fsl_realloc(*line_offsets, newsz);
				if (new == NULL) {
					fsl_free(*line_offsets);
					*line_offsets = NULL;
					return RC(FSL_RC_ERROR, "fsl_realloc");

				}
				*line_offsets = new;
allocated:
				nalloc = n;
			}
			if (line_offsets) {
				off = total_len + i + 1;
				(*line_offsets)[*nlines - 1] = off;
			}
			++i;
		}
	}
	n = fwrite(buf->mem, 1, len, out);
	if (n != len)
		return RC(ferror(out) ? fsl_errno_to_rc(errno, FSL_RC_IO)
		    : FSL_RC_IO, "fwrite");
	total_len += len;

	if (fflush(out) != 0)
		return RC(fsl_errno_to_rc(errno, FSL_RC_IO), "fflush");
	rewind(out);

	if (filesz)
		*filesz = total_len;

	return rc;
}

static int
show_blame_view(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	int				 rc = 0;

	if (!s->blame.thread_id && !s->blame_complete) {
		rc = pthread_create(&s->blame.thread_id, NULL, blame_thread,
		    &s->blame.thread_cx);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_create");

		halfdelay(1);	/* Fast refresh while annotating.  */
	}

	if (s->blame_complete)
		cbreak();	/* Return to blocking mode. */

9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
	int				 rc0, rc;

	rc = block_main_thread_signals();
	if (rc)
		return (void *)(intptr_t)rc;

	rc = fsl_annotate(f, &cx->blame_opt);
	if (rc && fsl_cx_err_get_e(f)->code == FSL_RC_BREAK) {
		fcli_err_reset();
		rc = 0;
	}

	rc0 = pthread_mutex_lock(&fnc_mutex);
	if (rc0)
		return (void *)(intptr_t)RC(fsl_errno_to_rc(rc0, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	*cx->complete = true;

	rc0 = pthread_mutex_unlock(&fnc_mutex);
	if (rc0 && !rc)
		rc = RC(fsl_errno_to_rc(rc0, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");

	return (void *)(intptr_t)rc;
}

static int
blame_cb(void *state, fsl_annotate_opt const * const opt,
    fsl_annotate_step const * const step)
{
	struct fnc_blame_cb_cx	*cx = state;
	struct fnc_blame_line	*line;
	int			 rc = 0;

	rc = pthread_mutex_lock(&fnc_mutex);
	if (rc)
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	if (*cx->quit) {
		rc = fcli_err_set(FSL_RC_BREAK, "user quit");
		goto end;
	}

	line = &cx->lines[step->lineNumber - 1];
	if (line->annotated)
		goto end;

	if (step->mtime) {
		line->id = fsl_strdup(step->versionHash);
		if (line->id == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", fsl_strdup);
			goto end;
		}
		line->annotated = true;
	} else
		line->id = NULL;

	/* -r can return lines with no version, so use root check-in. */
	if (opt->originRid && !line->id) {
		line->id = fsl_strdup(cx->root_commit);
		line->annotated = true;
	}

	line->lineno = step->lineNumber;
	cx->maxlen = MAX(step->lineLength, cx->maxlen);
	++cx->nlines;
end:
	rc = pthread_mutex_unlock(&fnc_mutex);
	if (rc)
		rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");
	return rc;
}

static int
draw_blame(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;







|
<
|
<




|






|















|













|



















|







11907
11908
11909
11910
11911
11912
11913
11914

11915

11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
	int				 rc0, rc;

	rc = block_main_thread_signals();
	if (rc)
		return (void *)(intptr_t)rc;

	rc = fsl_annotate(f, &cx->blame_opt);
	if (rc && fsl_cx_err_get_e(f)->code == FSL_RC_BREAK)

		RC_RESET(rc);


	rc0 = pthread_mutex_lock(&fnc_mutex);
	if (rc0)
		return (void *)(intptr_t)RC(fsl_errno_to_rc(rc0, FSL_RC_ACCESS),
		    "pthread_mutex_lock");

	*cx->complete = true;

	rc0 = pthread_mutex_unlock(&fnc_mutex);
	if (rc0 && !rc)
		rc = RC(fsl_errno_to_rc(rc0, FSL_RC_ACCESS),
		    "pthread_mutex_unlock");

	return (void *)(intptr_t)rc;
}

static int
blame_cb(void *state, fsl_annotate_opt const * const opt,
    fsl_annotate_step const * const step)
{
	struct fnc_blame_cb_cx	*cx = state;
	struct fnc_blame_line	*line;
	int			 rc = 0;

	rc = pthread_mutex_lock(&fnc_mutex);
	if (rc)
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "pthread_mutex_lock");

	if (*cx->quit) {
		rc = fcli_err_set(FSL_RC_BREAK, "user quit");
		goto end;
	}

	line = &cx->lines[step->lineNumber - 1];
	if (line->annotated)
		goto end;

	if (step->mtime) {
		line->id = fsl_strdup(step->versionHash);
		if (line->id == NULL) {
			rc = RC(FSL_RC_ERROR, "fsl_strdup");
			goto end;
		}
		line->annotated = true;
	} else
		line->id = NULL;

	/* -r can return lines with no version, so use root check-in. */
	if (opt->originRid && !line->id) {
		line->id = fsl_strdup(cx->root_commit);
		line->annotated = true;
	}

	line->lineno = step->lineNumber;
	cx->maxlen = MAX(step->lineLength, cx->maxlen);
	++cx->nlines;
end:
	rc = pthread_mutex_unlock(&fnc_mutex);
	if (rc)
		rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "pthread_mutex_unlock");
	return rc;
}

static int
draw_blame(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
	const int			 idfield = 11;  /* Prefix + space. */
	bool				 selected;

	rewind(blame->f);
	werase(view->window);

	if ((line = fsl_mprintf("checkin %s", s->blamed_commit->id)) == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "fsl_mprintf");
		return rc;
	}

	rc = formatln(&wcstr, &width, line, view->ncols, 0, false);
	fsl_free(line);
	line = NULL;
	if (rc)







|
<







11996
11997
11998
11999
12000
12001
12002
12003

12004
12005
12006
12007
12008
12009
12010
	const int			 idfield = 11;  /* Prefix + space. */
	bool				 selected;

	rewind(blame->f);
	werase(view->window);

	if ((line = fsl_mprintf("checkin %s", s->blamed_commit->id)) == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "fsl_mprintf");

		return rc;
	}

	rc = formatln(&wcstr, &width, line, view->ncols, 0, false);
	fsl_free(line);
	line = NULL;
	if (rc)
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
		if (linelen == -1) {
			if (feof(blame->f)) {
				s->eof = true;
				break;
			}
			fsl_free(line);
			return RC(ferror(blame->f) ? fsl_errno_to_rc(errno,
			    FSL_RC_IO) : FSL_RC_IO, "%s", "getline");
		}
		if (++lineno < s->first_line_onscreen)
			continue;
		if (s->gtl)
			if (!gotoline(view, &lineno, &nprinted))
				continue;








|







12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
		if (linelen == -1) {
			if (feof(blame->f)) {
				s->eof = true;
				break;
			}
			fsl_free(line);
			return RC(ferror(blame->f) ? fsl_errno_to_rc(errno,
			    FSL_RC_IO) : FSL_RC_IO, "getline");
		}
		if (++lineno < s->first_line_onscreen)
			continue;
		if (s->gtl)
			if (!gotoline(view, &lineno, &nprinted))
				continue;

9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
				waddstr(view->window, "          ");
			} else if (blame_line->annotated) {
				char *id_str;
				id_str = fsl_strndup(blame_line->id,
				    idfield - 1);
				if (id_str == NULL) {
					fsl_free(line);
					return RC(FSL_RC_ERROR, "%s",
					    "fsl_strdup");
				}
				if (s->colour)
					c = get_colour(&s->colours,
					    FNC_COLOUR_COMMIT);
				if (c)
					wattr_on(view->window,
					    COLOR_PAIR(c->scheme), NULL);







|
<







12077
12078
12079
12080
12081
12082
12083
12084

12085
12086
12087
12088
12089
12090
12091
				waddstr(view->window, "          ");
			} else if (blame_line->annotated) {
				char *id_str;
				id_str = fsl_strndup(blame_line->id,
				    idfield - 1);
				if (id_str == NULL) {
					fsl_free(line);
					return RC(FSL_RC_ERROR, "fsl_strdup");

				}
				if (s->colour)
					c = get_colour(&s->colours,
					    FNC_COLOUR_COMMIT);
				if (c)
					wattr_on(view->window,
					    COLOR_PAIR(c->scheme), NULL);
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
			wattroff(view->window, rx);
		waddch(view->window, ' ');

		if (view->ncols <= idfield) {
			wcstr = wcsdup(L"");
			if (wcstr == NULL) {
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_RANGE),
				    "%s", "wcsdup");
				fsl_free(line);
				return rc;
			}
		} else if (s->first_line_onscreen + nprinted == s->matched_line
		    && regmatch->rm_so >= 0 &&
		    regmatch->rm_so < regmatch->rm_eo) {
			rc = draw_matched_line(view, line, &width,







|







12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
			wattroff(view->window, rx);
		waddch(view->window, ' ');

		if (view->ncols <= idfield) {
			wcstr = wcsdup(L"");
			if (wcstr == NULL) {
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_RANGE),
				    "wcsdup");
				fsl_free(line);
				return rc;
			}
		} else if (s->first_line_onscreen + nprinted == s->matched_line
		    && regmatch->rm_so >= 0 &&
		    regmatch->rm_so < regmatch->rm_eo) {
			rc = draw_matched_line(view, line, &width,
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719

9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
			if (pid == NULL)
				break;
			/* Check file exists in parent check-in. */
			rc = fsl_deck_load_sym(f, &d, pid, FSL_SATYPE_CHECKIN);
			if (rc) {
				fsl_deck_finalize(&d);
				fsl_free(pid);
				return RC(rc, "%s", "fsl_deck_load_sym");
			}
			rc = fsl_deck_F_rewind(&d);
			if (rc) {
				fsl_deck_finalize(&d);
				fsl_free(pid);
				return RC(rc, "%s", "fsl_deck_F_rewind");
			}
			if (fsl_deck_F_search(&d, s->path +
			    (fnc_init.sym ? 0 : 1)) == NULL) {

				char *m = fsl_mprintf("-- %s not in [%.12s] --",
				    s->path + (fnc_init.sym ? 0 : 1), pid);
				if (m == NULL)
					rc = RC(FSL_RC_ERROR, "%s",
					    "fsl_mprintf");
				sitrep(view, m,
				    SR_CLREOL | SR_UPDATE | SR_SLEEP);
				fsl_deck_finalize(&d);
				fsl_free(pid);
				fsl_free(m);
				break;
			}
			rc = fnc_commit_qid_alloc(&s->blamed_commit, pid);
			if (rc)
				return rc;
		} else {
			if (!fsl_uuidcmp(id, s->blamed_commit->id))







|





|



>
|

<
<
<
<
<


<







12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364





12365
12366

12367
12368
12369
12370
12371
12372
12373
			if (pid == NULL)
				break;
			/* Check file exists in parent check-in. */
			rc = fsl_deck_load_sym(f, &d, pid, FSL_SATYPE_CHECKIN);
			if (rc) {
				fsl_deck_finalize(&d);
				fsl_free(pid);
				return RC(rc, "fsl_deck_load_sym");
			}
			rc = fsl_deck_F_rewind(&d);
			if (rc) {
				fsl_deck_finalize(&d);
				fsl_free(pid);
				return RC(rc, "fsl_deck_F_rewind");
			}
			if (fsl_deck_F_search(&d, s->path +
			    (fnc_init.sym ? 0 : 1)) == NULL) {
				sitrep(view, SR_ALL ^ SR_RESET,
				    "-- %s not in [%.12s] --",
				    s->path + (fnc_init.sym ? 0 : 1), pid);





				fsl_deck_finalize(&d);
				fsl_free(pid);

				break;
			}
			rc = fnc_commit_qid_alloc(&s->blamed_commit, pid);
			if (rc)
				return rc;
		} else {
			if (!fsl_uuidcmp(id, s->blamed_commit->id))
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
	}
	case 'T':
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		branch_view = view_open(view->nlines, view->ncols,
		    view->start_ln, start_col, FNC_VIEW_BRANCH);
		if (branch_view == NULL)
			return RC(FSL_RC_ERROR, "%s", "view_open");
		rc = open_branch_view(branch_view, BRANCH_LS_OPEN_CLOSED, NULL,
		    0, 0);
		if (rc) {
			view_close(branch_view);
			return rc;
		}
		view->active = false;







|







12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
	}
	case 'T':
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		branch_view = view_open(view->nlines, view->ncols,
		    view->start_ln, start_col, FNC_VIEW_BRANCH);
		if (branch_view == NULL)
			return RC(FSL_RC_ERROR, "view_open");
		rc = open_branch_view(branch_view, BRANCH_LS_OPEN_CLOSED, NULL,
		    0, 0);
		if (rc) {
			view_close(branch_view);
			return rc;
		}
		view->active = false;
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
			diff_view = *alt_view;
		} else {
			if (view_is_parent(view))
				start_col = view_split_start_col(view->start_col);
			diff_view = view_open(0, 0, 0, start_col, FNC_VIEW_DIFF);
			if (diff_view == NULL) {
				fnc_commit_artifact_close(commit);
				rc = RC(FSL_RC_ERROR, "%s", "view_open");
				break;
			}
		}
		rc = open_diff_view(diff_view, commit, NULL, view, true);
		s->selected_entry = commit;
		if (rc) {
			fnc_commit_artifact_close(commit);
			view_close(diff_view);
			break;
		}
		if (*alt_view)  /* view is already active */







|



|







12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
			diff_view = *alt_view;
		} else {
			if (view_is_parent(view))
				start_col = view_split_start_col(view->start_col);
			diff_view = view_open(0, 0, 0, start_col, FNC_VIEW_DIFF);
			if (diff_view == NULL) {
				fnc_commit_artifact_close(commit);
				rc = RC(FSL_RC_ERROR, "view_open");
				break;
			}
		}
		rc = open_diff_view(diff_view, commit, NULL, view, COMMIT_META);
		s->selected_entry = commit;
		if (rc) {
			fnc_commit_artifact_close(commit);
			view_close(diff_view);
			break;
		}
		if (*alt_view)  /* view is already active */
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
static int
fnc_commit_qid_alloc(struct fnc_commit_qid **qid, fsl_uuid_cstr id)
{
	int rc = 0;

	*qid = calloc(1, sizeof(**qid));
	if (*qid == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");

	(*qid)->id = fsl_strdup(id);
	if ((*qid)->id == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		fnc_commit_qid_free(*qid);
		*qid = NULL;
	}

	return rc;
}








|



|







12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
static int
fnc_commit_qid_alloc(struct fnc_commit_qid **qid, fsl_uuid_cstr id)
{
	int rc = 0;

	*qid = calloc(1, sizeof(**qid));
	if (*qid == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "calloc");

	(*qid)->id = fsl_strdup(id);
	if ((*qid)->id == NULL) {
		rc = RC(FSL_RC_ERROR, "fsl_strdup");
		fnc_commit_qid_free(*qid);
		*qid = NULL;
	}

	return rc;
}

9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
	int idx, rc = 0;

	if (blame->thread_id) {
		intptr_t retval;
		rc = pthread_mutex_unlock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		rc = pthread_join(blame->thread_id, (void **)&retval);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_join");
		rc = pthread_mutex_lock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
		if (!rc && fsl_cx_err_get_e(fcli_cx())->code == FSL_RC_BREAK) {
			rc = 0;
			fcli_err_reset();
		}
		blame->thread_id = 0;
	}
	if (blame->f) {
		if (fclose(blame->f) == EOF && rc == 0)
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s",
			    fclose);
		blame->f = NULL;
	}
	if (blame->lines) {
		for (idx = 0; idx < blame->nlines; ++idx)
			fsl_free(blame->lines[idx].id);
		fsl_free(blame->lines);
		blame->lines = NULL;







|



|



|
|
|
<
<




|
<







12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588


12589
12590
12591
12592
12593

12594
12595
12596
12597
12598
12599
12600
	int idx, rc = 0;

	if (blame->thread_id) {
		intptr_t retval;
		rc = pthread_mutex_unlock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_mutex_unlock");
		rc = pthread_join(blame->thread_id, (void **)&retval);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_join");
		rc = pthread_mutex_lock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "pthread_mutex_lock");
		if (!rc && fsl_cx_err_get_e(fcli_cx())->code == FSL_RC_BREAK)
			RC_RESET(rc);


		blame->thread_id = 0;
	}
	if (blame->f) {
		if (fclose(blame->f) == EOF && rc == 0)
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "fclose");

		blame->f = NULL;
	}
	if (blame->lines) {
		for (idx = 0; idx < blame->nlines; ++idx)
			fsl_free(blame->lines[idx].id);
		fsl_free(blame->lines);
		blame->lines = NULL;
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
{
	int	*done = state;
	int	 rc = 0;

	rc = pthread_mutex_lock(&fnc_mutex);
	if (rc)
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");

	if (*done)
		rc = fcli_err_set(FSL_RC_BREAK, "user quit");

	rc = pthread_mutex_unlock(&fnc_mutex);
	if (rc)
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	return rc;
}

static void
fnc_commit_qid_free(struct fnc_commit_qid *qid)
{







|







|







12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
{
	int	*done = state;
	int	 rc = 0;

	rc = pthread_mutex_lock(&fnc_mutex);
	if (rc)
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "pthread_mutex_unlock");

	if (*done)
		rc = fcli_err_set(FSL_RC_BREAK, "user quit");

	rc = pthread_mutex_unlock(&fnc_mutex);
	if (rc)
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "pthread_mutex_lock");

	return rc;
}

static void
fnc_commit_qid_free(struct fnc_commit_qid *qid)
{
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	branch_flags = BRANCH_LS_OPEN_CLOSED;
	if (fnc_init.open && fnc_init.closed)
		return RC(FSL_RC_MISUSE, "%s",
		    "--open and --close are mutually exclusive options");
	else if (fnc_init.open)
		branch_flags = BRANCH_LS_OPEN_ONLY;
	else if (fnc_init.closed)
		branch_flags = BRANCH_LS_CLOSED_ONLY;

	if (fnc_init.sort) {







|







12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	branch_flags = BRANCH_LS_OPEN_CLOSED;
	if (fnc_init.open && fnc_init.closed)
		return RC(FSL_RC_MISUSE,
		    "--open and --close are mutually exclusive options");
	else if (fnc_init.open)
		branch_flags = BRANCH_LS_OPEN_ONLY;
	else if (fnc_init.closed)
		branch_flags = BRANCH_LS_CLOSED_ONLY;

	if (fnc_init.sort) {
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058

10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
	}
	if (fnc_init.noprivate)
		FLAG_SET(branch_flags, BRANCH_LS_NO_PRIVATE);
	if (fnc_init.reverse)
		FLAG_SET(branch_flags, BRANCH_SORT_REVERSE);

	if (fnc_init.after && fnc_init.before) {
		return RC(FSL_RC_MISUSE, "%s",
		    "--before and --after are mutually exclusive options");
	} else if (fnc_init.after || fnc_init.before) {
		const char *d = NULL;
		d = fnc_init.after ? fnc_init.after : fnc_init.before;
		when = fnc_init.after ? 1 : -1;
		rc = fnc_date_to_mtime(&dateline, d, when);
		if (rc)
			return rc;
	}
	glob = fsl_strdup(fcli_next_arg(true));

	rc = init_curses();
	if (rc)
		goto end;
	rc = init_unveil(REPODB, CKOUTDIR, false);

	if (rc)
		goto end;

	view = view_open(0, 0, 0, 0, FNC_VIEW_BRANCH);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_branch_view(view, branch_flags, glob, dateline, when);
	if (!rc)
		rc = view_loop(view);
end:







|














|
>





|







12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
	}
	if (fnc_init.noprivate)
		FLAG_SET(branch_flags, BRANCH_LS_NO_PRIVATE);
	if (fnc_init.reverse)
		FLAG_SET(branch_flags, BRANCH_SORT_REVERSE);

	if (fnc_init.after && fnc_init.before) {
		return RC(FSL_RC_MISUSE,
		    "--before and --after are mutually exclusive options");
	} else if (fnc_init.after || fnc_init.before) {
		const char *d = NULL;
		d = fnc_init.after ? fnc_init.after : fnc_init.before;
		when = fnc_init.after ? 1 : -1;
		rc = fnc_date_to_mtime(&dateline, d, when);
		if (rc)
			return rc;
	}
	glob = fsl_strdup(fcli_next_arg(true));

	rc = init_curses();
	if (rc)
		goto end;
	rc = init_unveil(((const char *[]){REPODB, CKOUTDIR, P_tmpdir,
	    gettzfile()}), ((const char *[]){"rw", "rwc", "rwc", "r"}), 4, true);
	if (rc)
		goto end;

	view = view_open(0, 0, 0, 0, FNC_VIEW_BRANCH);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "view_open");
		goto end;
	}

	rc = open_branch_view(view, branch_flags, glob, dateline, when);
	if (!rc)
		rc = view_loop(view);
end:
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
	if (!rc && FLAG_CHK(s->branch_flags, BRANCH_SORT_REVERSE))
		rc = fsl_buffer_append(&sql," DESC", -1);
	if (rc)
		goto end;

	stmt = fsl_stmt_malloc();
	if (stmt == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_stmt_malloc");
		goto end;
	}

	rc = fsl_cx_prepare(f, stmt, fsl_buffer_cstr(&sql));
	if (rc)
		goto end;








|







12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
	if (!rc && FLAG_CHK(s->branch_flags, BRANCH_SORT_REVERSE))
		rc = fsl_buffer_append(&sql," DESC", -1);
	if (rc)
		goto end;

	stmt = fsl_stmt_malloc();
	if (stmt == NULL) {
		rc = RC(FSL_RC_ERROR, "fsl_stmt_malloc");
		goto end;
	}

	rc = fsl_cx_prepare(f, stmt, fsl_buffer_cstr(&sql));
	if (rc)
		goto end;

10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
	    " AND tagxref.tagtype>0"
	    " AND tag.tagname='branch'"
	    " AND event.objid=tagxref.rid "
	    "GROUP BY 1;";
	int rc = 0;

	if (!db)
		return RC(FSL_RC_NOT_A_CKOUT, "%s", "fsl_needs_repo");
	rc = fsl_db_exec(db, tmp_branchlist_table);

	return rc ? RC(fsl_cx_uplift_db_error2(f, db, rc), "%s", "fsl_db_exec")
	    : rc;
}

static int
alloc_branch(struct fnc_branch **branch, const char *name, double mtime,
    bool open, bool priv, bool curr)
{
	fsl_uuid_str	id = NULL;
	char		iso8601[ISO8601_TIMESTAMP], *date = NULL;
	int		rc = 0;

	*branch = calloc(1, sizeof(**branch));
	if (*branch == NULL)
		return RC(FSL_RC_ERROR, "%s", "calloc");

	rc = fsl_sym_to_uuid(fcli_cx(), name, FSL_SATYPE_ANY, &id, NULL);
	if (rc || id == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_sym_to_uuid");
		fnc_branch_close(*branch);
		*branch = NULL;
		return rc;
	}

	fsl_julian_to_iso8601(mtime, iso8601, false);
	date = fsl_mprintf("%.*s", ISO8601_DATE_ONLY, iso8601);

	(*branch)->id = id;
	(*branch)->name = fsl_strdup(name);
	(*branch)->date = date;
	(*branch)->open = open;
	(*branch)->private = priv;
	(*branch)->current = curr;
	if ((*branch)->name == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		fnc_branch_close(*branch);
		*branch = NULL;
	}

	return rc;
}

static int
fnc_branchlist_insert(struct fnc_branchlist_entry **newp,
    struct fnc_branchlist_head *branches, struct fnc_branch *branch)
{
	struct fnc_branchlist_entry *new, *be;

	*newp = NULL;

	new = fsl_malloc(sizeof(*new));
	if (new == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	new->branch = branch;
	*newp = new;

	be = TAILQ_LAST(branches, fnc_branchlist_head);
	if (!be) {
		/* Empty list; add first branch. */
		TAILQ_INSERT_HEAD(branches, new, entries);







|


|
<












|



|















|

















|







12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891

12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
	    " AND tagxref.tagtype>0"
	    " AND tag.tagname='branch'"
	    " AND event.objid=tagxref.rid "
	    "GROUP BY 1;";
	int rc = 0;

	if (!db)
		return RC(FSL_RC_NOT_A_CKOUT, "fsl_needs_repo");
	rc = fsl_db_exec(db, tmp_branchlist_table);

	return rc ? RC(fsl_cx_uplift_db_error2(f, db, rc), "fsl_db_exec") : rc;

}

static int
alloc_branch(struct fnc_branch **branch, const char *name, double mtime,
    bool open, bool priv, bool curr)
{
	fsl_uuid_str	id = NULL;
	char		iso8601[ISO8601_TIMESTAMP], *date = NULL;
	int		rc = 0;

	*branch = calloc(1, sizeof(**branch));
	if (*branch == NULL)
		return RC(FSL_RC_ERROR, "calloc");

	rc = fsl_sym_to_uuid(fcli_cx(), name, FSL_SATYPE_ANY, &id, NULL);
	if (rc || id == NULL) {
		rc = RC(FSL_RC_ERROR, "fsl_sym_to_uuid");
		fnc_branch_close(*branch);
		*branch = NULL;
		return rc;
	}

	fsl_julian_to_iso8601(mtime, iso8601, false);
	date = fsl_mprintf("%.*s", ISO8601_DATE_ONLY, iso8601);

	(*branch)->id = id;
	(*branch)->name = fsl_strdup(name);
	(*branch)->date = date;
	(*branch)->open = open;
	(*branch)->private = priv;
	(*branch)->current = curr;
	if ((*branch)->name == NULL) {
		rc = RC(FSL_RC_ERROR, "fsl_strdup");
		fnc_branch_close(*branch);
		*branch = NULL;
	}

	return rc;
}

static int
fnc_branchlist_insert(struct fnc_branchlist_entry **newp,
    struct fnc_branchlist_head *branches, struct fnc_branch *branch)
{
	struct fnc_branchlist_entry *new, *be;

	*newp = NULL;

	new = fsl_malloc(sizeof(*new));
	if (new == NULL)
		return RC(FSL_RC_ERROR, "fsl_malloc");
	new->branch = branch;
	*newp = new;

	be = TAILQ_LAST(branches, fnc_branchlist_head);
	if (!be) {
		/* Empty list; add first branch. */
		TAILQ_INSERT_HEAD(branches, new, entries);
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
	if (limit == 0)
		return rc;

	be = s->first_branch_onscreen;

	if ((line = fsl_mprintf("branches [%d/%d]", be->idx + s->selected + 1,
	    s->nbranches)) == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_mprintf");

	rc = formatln(&wline, &width, line, view->ncols, 0, false);
	if (rc) {
		fsl_free(line);
		return rc;
	}
	if (screen_is_shared(view) || view->active)







|







12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
	if (limit == 0)
		return rc;

	be = s->first_branch_onscreen;

	if ((line = fsl_mprintf("branches [%d/%d]", be->idx + s->selected + 1,
	    s->nbranches)) == NULL)
		return RC(FSL_RC_ERROR, "fsl_mprintf");

	rc = formatln(&wline, &width, line, view->ncols, 0, false);
	if (rc) {
		fsl_free(line);
		return rc;
	}
	if (screen_is_shared(view) || view->active)
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
		    s->show_id ? be->branch->id : "", s->show_id ? "  " : "",
		    s->show_date ? be->branch->date : "",
		    s->show_date ? "  " : "",
		    be->branch->name,
		    be->branch->private ? "*" : "",
		    be->branch->current ? "@" : "");
		if (line == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_mprintf");

		if (s->colour)
			c = match_colour(&s->colours, line);

		rc = formatln(&wline, &width, line, view->ncols, 0, false);
		if (rc) {
			fsl_free(line);







|







13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
		    s->show_id ? be->branch->id : "", s->show_id ? "  " : "",
		    s->show_date ? be->branch->date : "",
		    s->show_date ? "  " : "",
		    be->branch->name,
		    be->branch->private ? "*" : "",
		    be->branch->current ? "@" : "");
		if (line == NULL)
			return RC(FSL_RC_ERROR, "fsl_mprintf");

		if (s->colour)
			c = match_colour(&s->colours, line);

		rc = formatln(&wline, &width, line, view->ncols, 0, false);
		if (rc) {
			fsl_free(line);
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
	fsl_id_t	 rid;
	int		 rc = 0;

	*new_view = NULL;

	rid = fsl_uuid_to_rid(fcli_cx(), be->branch->id);
	if (rid < 0)
		return RC(rc, "%s", "fsl_uuid_to_rid");

	tree_view = view_open(0, 0, 0, start_col, FNC_VIEW_TREE);
	if (tree_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	rc = open_tree_view(tree_view, "/", rid);
	if (!rc)
		*new_view = tree_view;
	return rc;
}








|



|







13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
	fsl_id_t	 rid;
	int		 rc = 0;

	*new_view = NULL;

	rid = fsl_uuid_to_rid(fcli_cx(), be->branch->id);
	if (rid < 0)
		return RC(rc, "fsl_uuid_to_rid");

	tree_view = view_open(0, 0, 0, start_col, FNC_VIEW_TREE);
	if (tree_view == NULL)
		return RC(FSL_RC_ERROR, "view_open");

	rc = open_tree_view(tree_view, "/", rid);
	if (!rc)
		*new_view = tree_view;
	return rc;
}

10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
	int				 rc = 0;

	if (inserted)
		*inserted = NULL;

	new = fsl_malloc(sizeof(*new));
	if (new == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	new->path = path;
	new->pathlen = fsl_strlen(path);
	new->data = data;

	/*
	 * Most likely, supplied paths will be sorted (e.g., fnc diff *.c), so
	 * post-order traversal will be more efficient when inserting entries.







|







13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
	int				 rc = 0;

	if (inserted)
		*inserted = NULL;

	new = fsl_malloc(sizeof(*new));
	if (new == NULL)
		return RC(FSL_RC_ERROR, "fsl_malloc");
	new->path = path;
	new->pathlen = fsl_strlen(path);
	new->data = data;

	/*
	 * Most likely, supplied paths will be sorted (e.g., fnc diff *.c), so
	 * post-order traversal will be more efficient when inserting entries.
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
		free(pe);
	}
}

static void
fnc_show_version(void)
{
	printf("%s %s\n", fcli_progname(), PRINT_VERSION);
}

static int
strtonumcheck(long *ret, const char *nstr, const int min, const int max)
{
	const char	*ptr;
	long		 n;







|







13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
		free(pe);
	}
}

static void
fnc_show_version(void)
{
	printf("%s %s", fcli_progname(), PRINT_VERSION);
}

static int
strtonumcheck(long *ret, const char *nstr, const int min, const int max)
{
	const char	*ptr;
	long		 n;
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967


10968

10969
10970
10971
10972

10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990

static int
fnc_prompt_input(struct fnc_view *view, struct input *input)
{
	int  rc = FSL_RC_OK;

	if (input->prompt)
		sitrep(view, input->prompt, input->flags);

	rc = cook_input(input->buf, sizeof(input->buf),
	    view ? view->window : stdscr);
	if (rc || !input->buf[0])
		return rc;

	if (input->type == INPUT_NUMERIC) {
		long n = 0;
		int min = INT_MIN, max = INT_MAX;
		if (input->data) {
			min = *(int *)input->data;
			max = ((int *)input->data)[1];
		}
		rc = strtonumcheck(&n, input->buf, min, max);
		if (rc == FSL_RC_MISUSE)
			rc = sitrep(view, "-- numeric input only --", SR_ALL);
		else if (rc == FSL_RC_RANGE || n < min || n > max)
			rc = sitrep(view, "-- line outside range --", SR_ALL);
		else
			input->ret = n;
	}

	return rc;
}

static int
cook_input(char *ret, int sz, WINDOW *win)
{
	int rc;

	nocbreak();
	echo();
	rc = wgetnstr(win, ret, sz);
	cbreak();
	noecho();
	raw();

	return rc == ERR ? FSL_RC_ERROR : FSL_RC_OK;
}

static int
sitrep(struct fnc_view *view, const char *msg, int flags)
{
	WINDOW	*win = view ? view->window : stdscr;
	int	 line = (view ? view->nlines : LINES) - 1;



	wattr_on(win, A_BOLD, NULL);

	mvwaddstr(win, line, 0, msg);
	if (FLAG_CHK(flags, SR_CLREOL))
		wclrtoeol(win);
	wattr_off(win, A_BOLD, NULL);

	if (FLAG_CHK(flags, SR_UPDATE)) {
		update_panels();
		doupdate();
	}
	if (FLAG_CHK(flags, SR_RESET))
		fcli_err_reset();
	if (FLAG_CHK(flags, SR_SLEEP))
		sleep(1);

	return FSL_RC_OK;
}

/*
 * Attempt to parse string d, which must resemble either an ISO8601 formatted
 * date (e.g., 2021-10-10, 2020-01-01T10:10:10), disgregarding any trailing
 * garbage or space characters such that "2021-10-10x" or "2020-01-01 10:10:10"
 * will pass, or an _unambiguous_ DD/MM/YYYY or MM/DD/YYYY formatted date. Upon
 * success, use when to determine which time component to add to the date (i.e.,







|

|
<












|

|



















|


|
|

|
<

>
>
|
>
|
|
|
|
>
|
|
|
|
|
|
|
|

|
|







13548
13549
13550
13551
13552
13553
13554
13555
13556
13557

13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598

13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626

static int
fnc_prompt_input(struct fnc_view *view, struct input *input)
{
	int  rc = FSL_RC_OK;

	if (input->prompt)
		sitrep(view, input->flags, "%s", input->prompt);

	rc = cook_input(input->buf, sizeof(input->buf), view->window);

	if (rc || !input->buf[0])
		return rc;

	if (input->type == INPUT_NUMERIC) {
		long n = 0;
		int min = INT_MIN, max = INT_MAX;
		if (input->data) {
			min = *(int *)input->data;
			max = ((int *)input->data)[1];
		}
		rc = strtonumcheck(&n, input->buf, min, max);
		if (rc == FSL_RC_MISUSE)
			rc = sitrep(view, SR_ALL, "-- numeric input only --");
		else if (rc == FSL_RC_RANGE || n < min || n > max)
			rc = sitrep(view, SR_ALL, "-- line outside range --");
		else
			input->ret = n;
	}

	return rc;
}

static int
cook_input(char *ret, int sz, WINDOW *win)
{
	int rc;

	nocbreak();
	echo();
	rc = wgetnstr(win, ret, sz);
	cbreak();
	noecho();
	raw();

	return rc == ERR ? RC(FSL_RC_ERROR, "wgetnstr") : FSL_RC_OK;
}

static int PRINTFV(3, 4)
sitrep(struct fnc_view *view, int flags, const char *msg, ...)
{
       va_list args;


       va_start(args, msg);
       /* vw_printw(view->window, msg, args); */
       wattr_on(view->window, A_BOLD, NULL);
       wmove(view->window, view->nlines - 1, 0);
       vw_printw(view->window, msg, args);
       if (FLAG_CHK(flags, SR_CLREOL))
               wclrtoeol(view->window);
       wattr_off(view->window, A_BOLD, NULL);
       va_end(args);
       if (FLAG_CHK(flags, SR_UPDATE)) {
               update_panels();
               doupdate();
       }
       if (FLAG_CHK(flags, SR_RESET))
               fcli_err_reset();
       if (FLAG_CHK(flags, SR_SLEEP))
               sleep(1);

       return FSL_RC_OK;
 }

/*
 * Attempt to parse string d, which must resemble either an ISO8601 formatted
 * date (e.g., 2021-10-10, 2020-01-01T10:10:10), disgregarding any trailing
 * garbage or space characters such that "2021-10-10x" or "2020-01-01 10:10:10"
 * will pass, or an _unambiguous_ DD/MM/YYYY or MM/DD/YYYY formatted date. Upon
 * success, use when to determine which time component to add to the date (i.e.,
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
{
	if (fold) {
		*op = fsl_strdup("LIKE");
		if (*op == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		*glob = fsl_mprintf("%%%%%s%%%%", str);
		if (*glob == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_mprintf");
	} else {
		*op = fsl_strdup("GLOB");
		if (*op == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		*glob = fsl_mprintf("*%s*", str);
		if (*glob == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_mprintf");
	}

	return FSL_RC_OK;
}

static const char *
getdirname(const char *path, fsl_int_t len, bool slash)







|



|


|







13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
{
	if (fold) {
		*op = fsl_strdup("LIKE");
		if (*op == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		*glob = fsl_mprintf("%%%%%s%%%%", str);
		if (*glob == NULL)
			return RC(FSL_RC_ERROR, "fsl_mprintf");
	} else {
		*op = fsl_strdup("GLOB");
		if (*op == NULL)
			return RC(FSL_RC_ERROR, "fsl_strdup");
		*glob = fsl_mprintf("*%s*", str);
		if (*glob == NULL)
			return RC(FSL_RC_ERROR, "fsl_mprintf");
	}

	return FSL_RC_OK;
}

static const char *
getdirname(const char *path, fsl_int_t len, bool slash)
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131

11132
11133
11134
11135
11136
11137
11138
11139
11140

11141
11142
11143
11144
11145
11146

11147
11148
11149
11150
11151
11152
11153
11154
11155
 * operations. Write and create permissions are briefly listed inline, but we
 * effectively veil the entire fs except the repo db, ckout, and /tmp dirs.
 * The create permissions for the repository and checkout dirs are (perhaps
 * unintuitively) needed as fossil(1) creates temporary journal files in both.
 */
#ifndef HAVE_LANDLOCK
static int
init_unveil(const char *repodb, const char *ckoutdir, bool cfg)
{
#ifdef __OpenBSD__
	/* wc repo db for 'fnc config' command: fnc_conf_setopt(). */
	if (unveil(repodb, cfg ? "rwc" : "rw") == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
		    "unveil(%s, \"rw\")", repodb);

	/* wc .fslckout for fsl_ckout_changes_scan() in cmd_diff(). */

	if (ckoutdir && unveil(ckoutdir, "rwc") == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
		    "unveil(%s, \"rwc\")", ckoutdir);

	/* rwc /tmp for tmpfile() in help(), create_diff(), and run_blame(). */
	if (unveil(P_tmpdir, "rwc") == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
		    "unveil(%s, \"rwc\")", P_tmpdir);


	if (unveil(NULL, NULL) == -1)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
		    "%s", "unveil");
#endif  /* __OpenBSD__ */
	return FSL_RC_OK;
}


#else  /* HAVE_LANDLOCK */
static const char *
gettzfile(void)
{
	static char	 ret[PATH_MAX];
	const char	*tzdir, *tz;
	size_t		 n;








|


|
<
<
<

<
>
|
|
|
|
<
<
<
<

>
|
|
|



>

<







13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762



13763

13764
13765
13766
13767
13768




13769
13770
13771
13772
13773
13774
13775
13776
13777
13778

13779
13780
13781
13782
13783
13784
13785
 * operations. Write and create permissions are briefly listed inline, but we
 * effectively veil the entire fs except the repo db, ckout, and /tmp dirs.
 * The create permissions for the repository and checkout dirs are (perhaps
 * unintuitively) needed as fossil(1) creates temporary journal files in both.
 */
#ifndef HAVE_LANDLOCK
static int
init_unveil(const char **paths, const char **perms, int n, bool disable)
{
#ifdef __OpenBSD__
	int i;





	for (i = 0; i < n; ++i) {
		if (unveil(paths[i], perms[i]) == -1)
			return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
			    "unveil(%s, \"%s\")", paths[i], perms[i]);
	}





	if (disable)
		if (unveil(NULL, NULL) == -1)
			return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
			    "unveil");
#endif  /* __OpenBSD__ */
	return FSL_RC_OK;
}
#endif


static const char *
gettzfile(void)
{
	static char	 ret[PATH_MAX];
	const char	*tzdir, *tz;
	size_t		 n;

11170
11171
11172
11173
11174
11175
11176

11177
11178
11179
11180
11181
11182
11183
	return ret;
}

/*
 * Sans libc wrappers, use the following shims provided by Landlock authors.
 * https://www.kernel.org/doc/html/latest/userspace-api/landlock.html
 */

#ifndef landlock_create_ruleset
static inline int
landlock_create_ruleset(const struct landlock_ruleset_attr *const attr,
    const size_t size, const __u32 flags)
{
	return syscall(__NR_landlock_create_ruleset, attr, size, flags);
}







>







13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
	return ret;
}

/*
 * Sans libc wrappers, use the following shims provided by Landlock authors.
 * https://www.kernel.org/doc/html/latest/userspace-api/landlock.html
 */
#ifdef HAVE_LANDLOCK
#ifndef landlock_create_ruleset
static inline int
landlock_create_ruleset(const struct landlock_ruleset_attr *const attr,
    const size_t size, const __u32 flags)
{
	return syscall(__NR_landlock_create_ruleset, attr, size, flags);
}
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239

	rfd = landlock_create_ruleset(&attr, sizeof(attr), 0);
	if (rfd == -1) {
		/* Landlock is not supported or disabled by the kernel. */
		if (errno == ENOSYS || errno == EOPNOTSUPP)
			return rc;
		return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
		    "landlock: %s", "failed to create ruleset");
	}

	/* Iterate paths to grant fs permissions. */
	for (i = 0; !rc && i < n; ++i) {
		struct stat sb;
		if (paths[i] == NULL)
			continue;







|







13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870

	rfd = landlock_create_ruleset(&attr, sizeof(attr), 0);
	if (rfd == -1) {
		/* Landlock is not supported or disabled by the kernel. */
		if (errno == ENOSYS || errno == EOPNOTSUPP)
			return rc;
		return RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
		    "landlock: failed to create ruleset");
	}

	/* Iterate paths to grant fs permissions. */
	for (i = 0; !rc && i < n; ++i) {
		struct stat sb;
		if (paths[i] == NULL)
			continue;
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
			path_beneath.allowed_access = LANDLOCK_ACCESS_DIR;
			if (!S_ISDIR(sb.st_mode))
				path_beneath.allowed_access =
				    LANDLOCK_ACCESS_FS_READ_FILE;
			if (landlock_add_rule(rfd, LANDLOCK_RULE_PATH_BENEATH,
			    &path_beneath, 0))
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
				    "landlock: %s", "failed to update ruleset");
			close(path_beneath.parent_fd);
		}
	}

	if (!rc && prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == -1)
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
		    "landlock: %s", "failed to restrict privileges");

	if (!rc && landlock_restrict_self(rfd, 0)) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
		    "landlock: %s", "failed to enforce ruleset");
	}

	close(rfd);
	return rc;
}
#endif  /* HAVE_LANDLOCK */







|






|



|






13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
			path_beneath.allowed_access = LANDLOCK_ACCESS_DIR;
			if (!S_ISDIR(sb.st_mode))
				path_beneath.allowed_access =
				    LANDLOCK_ACCESS_FS_READ_FILE;
			if (landlock_add_rule(rfd, LANDLOCK_RULE_PATH_BENEATH,
			    &path_beneath, 0))
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
				    "landlock: failed to update ruleset");
			close(path_beneath.parent_fd);
		}
	}

	if (!rc && prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == -1)
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
		    "landlock: failed to restrict privileges");

	if (!rc && landlock_restrict_self(rfd, 0)) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
		    "landlock: failed to enforce ruleset");
	}

	close(rfd);
	return rc;
}
#endif  /* HAVE_LANDLOCK */