fnc

Check-in Differences
Login

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

Difference From 0.6 To 0.7

2022-01-08 13:33
[9918bb8dab] Bump version number: 0.8 (user: mark tags: trunk)
2022-01-08 13:30
[2c45034580] CHANGES for 0.7 (user: mark tags: trunk, 0.7)
2022-01-08 13:10
[277b68b64f] Bump year in license headers (user: mark tags: trunk)
2021-11-21 15:32
[f3d6c2ff7b] Bump version number: 0.7 (user: mark tags: trunk)
2021-11-21 15:28
[bbf8590008] CHANGES for 0.6 (user: mark tags: trunk, 0.6)
2021-11-21 14:40
[3d1f3389a3] Add user-defined colour support to the branch view. (user: mark tags: trunk)

Changes to CHANGES.md.












































1
2
3
4
5
6
7
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







**fnc 0.7** 2022-01-09

- factor out common make(1) and gmake build bits
- make build depend on make file
- make all commands compatible with `-R|--repository` (i.e., no checkout needed)
- implement Vim-like smartcase for commands that filter repository results
- improve timeline arg parsing for more informative output upon invalid input
- plug small memory leak when the timeline command fails to initialise a view
- fix database locking issue when opening multiple tree views from the timeline
- add pledge(2) and unveil(2) support on OpenBSD builds
- add (s)ort keymap (i.e., `--sort` CLI option counterpart) to the branch view
- add (d)ate keymap to toggle display of last modified timestamp in tree view
- allow blame of empty files rather than erroring out
- fix NULL dereference UB when the ".." parent dir is selected in tree view
- merge upstream fix when annotating files with shallow history
- add support for configurable horizontal split view mode (timeline -> diff)
- keep the last/first line in view when paging down/up to stay oriented
- expand horizontal splitscreen support to include tree -> blame views
- improve handling of cached commit builder statements
- plug small memleak of file labels when traversing commits from the diff view
- display message rather than error out when binary files are blamed
- expand horizontal split coverage to include timeline -> tree views
- implement '#' keymap to display line numbers in blame view
- implement (L)ine keymap to navigate directly to the entered line in blame view
- convert diff code to use upstream v2 API
- keep lines on screen in view when using keymaps that modify diff content
- reset diff search state when traversing commits from the diff view
- apply upstream diff fix to render consecutive edited lines as one block
- implement '#' keymap to display line numbers in diff view
- improve `C-f/C-b` paging in the in-app help window
- add user-defined option to configure search highlight colours
- implement navigate to (L)ine keymap in diff view
- enhance timeline and diff view headers
- implement user-defined option to configure line selection cursor in diff view
- implement Vim-like `C-e/C-y` keymaps to scroll down/up one line in diff view
- implement horizontal scrolling in diff and blame views
- improve view request handling and optimise new view initialisation
- implement `C-n/C-p` keymap to navigate to the next/previous file in the diff
- implement (F)ile keymap to navigate directly to a file in the diff
- apply upstream diff v2 fix for rendering untouched lines as changed
- implement Vim-like `C-d/C-u` keymaps to scroll the view down/up half a page
- enhance search behaviour in all views

**fnc 0.6** 2021-11-22

- implement support for user-defined colours in tl, diff, tree and blame views
- make branch view accessible from all other views
- optimise colour scheme initialisation
- implement new 'fnc config' interface to configure per-project settings
- improve build by making make file make(1) compatible

Changes to GNUmakefile.

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
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
1

2
3
4


5
6



7

8










































9
10
11
12
13
14
15
16
17
































-
+


-
-
+
+
-
-
-

-

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-









-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
#
# FNC Makefile
# FNC GNU Makefile
#

# CONFIGUGRAION
CC ?=		cc
# CONFIGURATION
include fnc.bld.mk
PREFIX ?=	/usr/local
MANDIR ?=	/share/man
VERSION ?=	0.6

# USED BELOW FOR PLATFORM SPECIFIC LDFLAGS
UNAME :=	$(shell uname -s)

# FLAGS NEEDED TO BUILD SQLITE3
SQLITE_CFLAGS =	${CFLAGS} -Wall -Werror -Wno-sign-compare -pedantic -std=c99 \
		-DNDEBUG=1 \
		-DSQLITE_DQS=0 \
		-DSQLITE_THREADSAFE=0 \
		-DSQLITE_DEFAULT_MEMSTATUS=0 \
		-DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1 \
		-DSQLITE_LIKE_DOESNT_MATCH_BLOBS \
		-DSQLITE_OMIT_DECLTYPE \
		-DSQLITE_OMIT_PROGRESS_CALLBACK \
		-DSQLITE_OMIT_SHARED_CACHE \
		-DSQLITE_OMIT_LOAD_EXTENSION \
		-DSQLITE_MAX_EXPR_DEPTH=0 \
		-DSQLITE_USE_ALLOCA \
		-DSQLITE_ENABLE_LOCKING_STYLE=0 \
		-DSQLITE_DEFAULT_FILE_FORMAT=4 \
		-DSQLITE_ENABLE_EXPLAIN_COMMENTS \
		-DSQLITE_ENABLE_FTS4 \
		-DSQLITE_ENABLE_DBSTAT_VTAB \
		-DSQLITE_ENABLE_JSON1 \
		-DSQLITE_ENABLE_FTS5 \
		-DSQLITE_ENABLE_STMTVTAB \
		-DSQLITE_HAVE_ZLIB \
		-DSQLITE_INTROSPECTION_PRAGMAS \
		-DSQLITE_ENABLE_DBPAGE_VTAB \
		-DSQLITE_TRUSTED_SCHEMA=0

# This makefile
MAKEFILE := $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))

# FLAGS NEEDED TO BUILD LIBFOSSIL
FOSSIL_CFLAGS =	${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99

# On SOME Linux (e.g., Ubuntu 18.04.6), we have to include wchar curses from
# I/.../ncursesw, but linking to -lncursesw (w/ no special -L path) works fine.
# FLAGS NEEDED TO BUILD FNC
FNC_CFLAGS =	${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99 \
		-I./lib -I./include -I/usr/include/ncursesw \
		-D_XOPEN_SOURCE_EXTENDED -DVERSION=${VERSION}

FNC_LDFLAGS =	${LDFLAGS} -lm -lutil -lz -lpthread -fPIC

# OSX has ncursesw, and needs iconv.
ifeq ($(UNAME),Darwin)
# OSX
FNC_LDFLAGS +=	-lncurses -lpanel -liconv
else
# Linux (tested on Debian), OpenBSD, FreeBSD
FNC_LDFLAGS +=	-lncursesw -lpanelw
endif

all: bin

bin: lib/sqlite3.o lib/libfossil.o src/fnc.o src/fnc

lib/sqlite3.o: lib/sqlite3.c lib/sqlite3.h $(MAKEFILE)
	${CC} ${SQLITE_CFLAGS} -c $< -o $@

lib/libfossil.o: lib/libfossil.c lib/libfossil.h $(MAKEFILE)
	${CC} ${FOSSIL_CFLAGS} -c $< -o $@

src/fnc.o: src/fnc.c include/settings.h $(MAKEFILE)
	${CC} ${FNC_CFLAGS} -c $< -o $@

src/fnc: src/fnc.o lib/libfossil.o lib/sqlite3.o $(MAKEFILE)
	${CC} -o $@ src/fnc.o lib/libfossil.o lib/sqlite3.o ${FNC_LDFLAGS}

install:
	install -s -m 0755 src/fnc ${PREFIX}/bin/fnc
	install -m 0644 src/fnc.1 ${PREFIX}${MANDIR}/man1/fnc.1

uninstall:
	rm -f ${PREFIX}/bin/fnc ${PREFIX}${MANDIR}/man1/fnc.1

clean:
	rm -f lib/*.o src/*.o src/fnc

release: clean
	tar czvf ../fnc-${VERSION}.tgz -C .. fnc-${VERSION}

.PHONY: clean release

Changes to LICENSE.

1

2
3
4
5
6
7
8
9
10
11
12
13

1
2
3
4
5
6
7
8
9
10
11
12
13
-
+












Copyright (c) 2021 Mark Jamsek <mark@jamsek.com>
Copyright (c) 2021, 2022 Mark Jamsek <mark@jamsek.com>

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Changes to Makefile.

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
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
1
2
3
4


5
6



7

8
9







































10
11
12
13
14
15
16
17



































-
-
+
+
-
-
-

-


-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-








-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
#
# FNC Makefile
#

# CONFIGUGRAION
CC ?=		cc
# CONFIGURATION
.include "fnc.bld.mk"
PREFIX ?=	/usr/local
MANDIR ?=	/share/man
VERSION ?=	0.6

# USED BELOW FOR PLATFORM SPECIFIC LDFLAGS
UNAME !=	uname -s

# FLAGS NEEDED TO BUILD SQLITE3
SQLITE_CFLAGS =	${CFLAGS} -Wall -Werror -Wno-sign-compare -pedantic -std=c99 \
		-DNDEBUG=1 \
		-DSQLITE_DQS=0 \
		-DSQLITE_THREADSAFE=0 \
		-DSQLITE_DEFAULT_MEMSTATUS=0 \
		-DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1 \
		-DSQLITE_LIKE_DOESNT_MATCH_BLOBS \
		-DSQLITE_OMIT_DECLTYPE \
		-DSQLITE_OMIT_PROGRESS_CALLBACK \
		-DSQLITE_OMIT_SHARED_CACHE \
		-DSQLITE_OMIT_LOAD_EXTENSION \
		-DSQLITE_MAX_EXPR_DEPTH=0 \
		-DSQLITE_USE_ALLOCA \
		-DSQLITE_ENABLE_LOCKING_STYLE=0 \
		-DSQLITE_DEFAULT_FILE_FORMAT=4 \
		-DSQLITE_ENABLE_EXPLAIN_COMMENTS \
		-DSQLITE_ENABLE_FTS4 \
		-DSQLITE_ENABLE_DBSTAT_VTAB \
		-DSQLITE_ENABLE_JSON1 \
		-DSQLITE_ENABLE_FTS5 \
		-DSQLITE_ENABLE_STMTVTAB \
		-DSQLITE_HAVE_ZLIB \
		-DSQLITE_INTROSPECTION_PRAGMAS \
		-DSQLITE_ENABLE_DBPAGE_VTAB \
		-DSQLITE_TRUSTED_SCHEMA=0

# FLAGS NEEDED TO BUILD LIBFOSSIL
FOSSIL_CFLAGS =	${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99

# On SOME Linux (e.g., Ubuntu 18.04.6), we have to include wchar curses from
# I/.../ncursesw, but linking to -lncursesw (w/ no special -L path) works fine.
# FLAGS NEEDED TO BUILD FNC
FNC_CFLAGS =	${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99 \
		-I./lib -I./include -I/usr/include/ncursesw \
		-D_XOPEN_SOURCE_EXTENDED -DVERSION=${VERSION}

FNC_LDFLAGS =	${LDFLAGS} -lm -lutil -lz -lpthread -fPIC

# OSX has ncursesw, and needs iconv.
.if $(UNAME) == Darwin
# OSX
FNC_LDFLAGS +=	-lncurses -lpanel -liconv
.else
# Linux (tested on Debian), OpenBSD, FreeBSD
FNC_LDFLAGS +=	-lncursesw -lpanelw
.endif

all: bin

bin: lib/sqlite3.o lib/libfossil.o src/fnc.o src/fnc

lib/sqlite3.o: lib/sqlite3.c lib/sqlite3.h
	${CC} ${SQLITE_CFLAGS} -c $< -o $@

lib/libfossil.o: lib/libfossil.c lib/libfossil.h
	${CC} ${FOSSIL_CFLAGS} -c $< -o $@

src/fnc.o: src/fnc.c include/settings.h
	${CC} ${FNC_CFLAGS} -c $< -o $@

src/fnc: src/fnc.o lib/libfossil.o lib/sqlite3.o Makefile
	${CC} -o $@ src/fnc.o lib/libfossil.o lib/sqlite3.o ${FNC_LDFLAGS}

install:
	install -s -m 0755 src/fnc ${PREFIX}/bin/fnc
	install -m 0644 src/fnc.1 ${PREFIX}${MANDIR}/man1/fnc.1

uninstall:
	rm -f ${PREFIX}/bin/fnc ${PREFIX}${MANDIR}/man1/fnc.1

clean:
	rm -f lib/*.o src/*.o src/fnc

release: clean
	tar czvf ../fnc-${VERSION}.tgz -C .. fnc-${VERSION}

.PHONY: clean release

Changes to README.md.

1
2
3

4
5
6
7
8
9
10
1
2

3
4
5
6
7
8
9
10


-
+







# README

# fnc 0.5
# fnc 0.6

## An ncurses browser for [Fossil][0] repositories in the terminal.

`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
79
80
81
82
83
84
85










86
87
88
89
90
91
92
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102







+
+
+
+
+
+
+
+
+
+







![diff removed file](https://fnc.bsdbox.org/uv/resources/img/fnc-diff-split-file-removed.png "fnc diff file removed")
![blame split screen](https://fnc.bsdbox.org/uv/resources/img/fnc-blame-splitscreen.png "fnc blame split screen")
![tree split screen](https://fnc.bsdbox.org/uv/resources/img/fnc-tree-splitscreen.png "fnc tree split screen")
![branch split screen](https://fnc.bsdbox.org/uv/resources/img/fnc-branch-splitscreen.png "fnc branch split screen")
![in-app help](https://fnc.bsdbox.org/uv/resources/img/fnc-inapp_help.png "fnc in-app help")
![timeline help](https://fnc.bsdbox.org/uv/resources/img/fnc-timeline-help.png "fnc timeline help")

# Trivia

**fnc** [fɪŋk]  
*noun* (n.)  
1. an ncurses browser for [Fossil][0] repositories in the terminal  
*verb* (v.)  
2. to inform  
etymology  
From the German word *Fink*, meaning "finch", a type of bird.

[0]: https://fossil-scm.org
[1]: https://fossil.wanderinghorse.net/r/libfossil
[2]: https://fossil-scm.org/home/help?cmd=ui
[3]: https://fnc.bsdbox.org/uv/download.html
[4]: https://fnc.bsdbox.org/uv/resources/doc/fnc.1.html
[5]: https://fnc.bsdbox.org/uv/resources/img/fnc-timeline-fullscreen.png
[6]: https://itac.bsdbox.org/fnc-demo.mp4

Added fnc.bld.mk.
















































































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
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
69
70
71
72
73
74
75
76
77
78
79
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
#
# FNC Common Build
#

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

# FLAGS NEEDED TO BUILD SQLITE3
SQLITE_CFLAGS =	${CFLAGS} -Wall -Werror -Wno-sign-compare -pedantic -std=c99 \
		-DNDEBUG=1 \
		-DSQLITE_DQS=0 \
		-DSQLITE_THREADSAFE=0 \
		-DSQLITE_DEFAULT_MEMSTATUS=0 \
		-DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1 \
		-DSQLITE_LIKE_DOESNT_MATCH_BLOBS \
		-DSQLITE_OMIT_DECLTYPE \
		-DSQLITE_OMIT_PROGRESS_CALLBACK \
		-DSQLITE_OMIT_SHARED_CACHE \
		-DSQLITE_OMIT_LOAD_EXTENSION \
		-DSQLITE_MAX_EXPR_DEPTH=0 \
		-DSQLITE_USE_ALLOCA \
		-DSQLITE_ENABLE_LOCKING_STYLE=0 \
		-DSQLITE_DEFAULT_FILE_FORMAT=4 \
		-DSQLITE_ENABLE_EXPLAIN_COMMENTS \
		-DSQLITE_ENABLE_FTS4 \
		-DSQLITE_ENABLE_DBSTAT_VTAB \
		-DSQLITE_ENABLE_JSON1 \
		-DSQLITE_ENABLE_FTS5 \
		-DSQLITE_ENABLE_STMTVTAB \
		-DSQLITE_HAVE_ZLIB \
		-DSQLITE_INTROSPECTION_PRAGMAS \
		-DSQLITE_ENABLE_DBPAGE_VTAB \
		-DSQLITE_TRUSTED_SCHEMA=0

# FLAGS NEEDED TO BUILD LIBFOSSIL
FOSSIL_CFLAGS =	${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99

# On SOME Linux (e.g., Ubuntu 18.04.6), we have to include wchar curses from
# I/.../ncursesw, but linking to -lncursesw (w/ no special -L path) works fine.
# FLAGS NEEDED TO BUILD FNC
FNC_CFLAGS =	${CFLAGS} -Wall -Werror -Wsign-compare -pedantic -std=c99 \
		-I./lib -I./include -I/usr/include/ncursesw \
		-D_XOPEN_SOURCE_EXTENDED -DVERSION=${VERSION}

FNC_LDFLAGS =	${LDFLAGS} -lm -lutil -lz -lpthread -fPIC

all: bin

bin: lib/sqlite3.o lib/libfossil.o src/fnc.o src/fnc

lib/sqlite3.o: lib/sqlite3.c lib/sqlite3.h
	${CC} ${SQLITE_CFLAGS} -c $< -o $@

lib/libfossil.o: lib/libfossil.c lib/libfossil.h
	${CC} ${FOSSIL_CFLAGS} -c $< -o $@

src/fnc.o: src/fnc.c include/settings.h fnc.bld.mk
	${CC} ${FNC_CFLAGS} -c $< -o $@

src/fnc: src/fnc.o lib/libfossil.o lib/sqlite3.o fnc.bld.mk
	${CC} -o $@ src/fnc.o lib/libfossil.o lib/sqlite3.o ${FNC_LDFLAGS}

install:
	install -s -m 0755 src/fnc ${PREFIX}/bin/fnc
	install -m 0644 src/fnc.1 ${PREFIX}${MANDIR}/man1/fnc.1

uninstall:
	rm -f ${PREFIX}/bin/fnc ${PREFIX}${MANDIR}/man1/fnc.1

clean:
	rm -f lib/*.o src/*.o src/fnc

release: clean
	tar czvf ../fnc-${VERSION}.tgz -C .. fnc-${VERSION}

.PHONY: clean release

Changes to include/settings.h.

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
35
36
37
38
39
40
41
42















































43




44

45
46
47
48
49
50












51


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
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
69
70
71
72
73
74
75
76
77
78
79
80

81






82
83
84
85
86
87
88
89
90
91
92
93
94
95
96







+
+
+
+
+
+
+
+


-
+
-
-
-
-

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+
+
+
+
-
+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+

+
+
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#define GEN_ENUM_SYM(pfx, id)	pfx##_##id
#define GEN_ENUM(name, pfx, info)				\
	enum name { info(pfx, GEN_ENUM_SYM) };

#define GEN_STR_SYM(pfx, id)	#pfx"_"#id
#define GEN_STR(name, pfx, info)				\
	static const char *name[] = { info(pfx, GEN_STR_SYM) };

/*
 * All configurable fnc settings, which can be stored in either the fossil(1)
 * repository (e.g., repo.fossil) or global (i.e., $HOME/.fossil) db. Note that
 * repository (e.g., ./repo.fossil) or shell envvars with `export SETTING=val`.
 * each setting _MAY_ be mapped to a valid enum, in which case its index here
 * _MUST_ be mapped to the index/value of its enum counterpart (i.e., either
 * explicitly set equivalent values in the enum, or use offsets when indexing
 * them).
 */
#define SETTINGS(SET)					\
	SET(FNC_START_SETTINGS)		/*  0 */	\
	SET(FNC_COLOUR_COMMIT)		/*  1 */	\
	SET(FNC_COLOUR_USER)		/*  2 */	\
	SET(FNC_COLOUR_DATE)		/*  3 */	\
	SET(FNC_COLOUR_DIFF_META)	/*  4 */	\
	SET(FNC_COLOUR_DIFF_MINUS)	/*  5 */	\
	SET(FNC_COLOUR_DIFF_PLUS)	/*  6 */	\
	SET(FNC_COLOUR_DIFF_CHUNK)	/*  7 */	\
	SET(FNC_COLOUR_DIFF_TAGS)	/*  8 */	\
	SET(FNC_COLOUR_TREE_LINK)	/*  9 */	\
	SET(FNC_COLOUR_TREE_DIR)	/* 10 */	\
	SET(FNC_COLOUR_TREE_EXEC)	/* 11 */	\
	SET(FNC_COLOUR_BRANCH_OPEN)	/* 12 */	\
	SET(FNC_COLOUR_BRANCH_CLOSED)	/* 13 */	\
	SET(FNC_COLOUR_BRANCH_CURRENT)	/* 14 */	\
	SET(FNC_COLOUR_BRANCH_PRIVATE)	/* 15 */	\
	SET(FNC_EOF_SETTINGS)		/* 16 */
#define USER_OPTIONS(pfx, _)					\
	_(pfx, START_SETTINGS),					\
	_(pfx, COLOUR_COMMIT),					\
	_(pfx, COLOUR_USER),					\
	_(pfx, COLOUR_DATE),					\
	_(pfx, COLOUR_DIFF_META),				\
	_(pfx, COLOUR_DIFF_MINUS),				\
	_(pfx, COLOUR_DIFF_PLUS),				\
	_(pfx, COLOUR_DIFF_CHUNK),				\
	_(pfx, COLOUR_DIFF_TAGS),				\
	_(pfx, COLOUR_TREE_LINK),				\
	_(pfx, COLOUR_TREE_DIR),				\
	_(pfx, COLOUR_TREE_EXEC),				\
	_(pfx, COLOUR_BRANCH_OPEN),				\
	_(pfx, COLOUR_BRANCH_CLOSED),				\
	_(pfx, COLOUR_BRANCH_CURRENT),				\
	_(pfx, COLOUR_BRANCH_PRIVATE),				\
	_(pfx, COLOUR_HL_LINE),					\
	_(pfx, COLOUR_HL_SEARCH),				\
	_(pfx, VIEW_SPLIT_MODE),				\
	_(pfx, VIEW_SPLIT_WIDTH),				\
	_(pfx, VIEW_SPLIT_HEIGHT),				\
	_(pfx, EOF_SETTINGS)

#define LINE_ATTR_ENUM(pfx, _)					\
	_(pfx, AUTO),						\
	_(pfx, MONO)

#define INPUT_TYPE_ENUM(pfx, _)					\
	_(pfx, ALPHA),						\
	_(pfx, NUMERIC)

#define LINE_TYPE_ENUM(pfx, _)					\
	_(pfx, TIMELINE_HEADER),				\
	_(pfx, TIMELINE_COMMIT),				\
	_(pfx, DIFF_HEADER),					\
	_(pfx, DIFF_ARTIFACT),					\
	_(pfx, DIFF_USER),					\
	_(pfx, DIFF_TAGS),					\
	_(pfx, DIFF_DATE),					\
	_(pfx, DIFF_COMMENT),					\
	_(pfx, DIFF_CHANGESET),					\
	_(pfx, DIFF_INDEX),					\
	_(pfx, DIFF_META),					\
	_(pfx, DIFF_MINUS),					\
	_(pfx, DIFF_PLUS),					\
	_(pfx, DIFF_CHUNK),					\

#define VIEW_MODE_ENUM(pfx, _)					\
	_(pfx, NONE),						\
	_(pfx, VERT),						\
	_(pfx, HRZN)
/*

 * To construct the string array and enum:
 *	static const char *fnc_settings[] = { SETTINGS(GEN_STR) };
 *	enum settings { SETTINGS(GEN_ENUM) };
 */
#define GEN_ENUM(_id)	_id,
#define GEN_STR(_str)	#_str,
#define ENUM_INFO(_)						\
	_(fnc_opt_id, FNC, USER_OPTIONS)			\
	_(line_attr, SLINE, LINE_ATTR_ENUM)			\
	_(input_type, INPUT, INPUT_TYPE_ENUM)			\
	_(line_type, LINE, LINE_TYPE_ENUM)			\
	_(view_mode, VIEW_SPLIT, VIEW_MODE_ENUM)

#define GEN_ENUMS(name, pfx, info) GEN_ENUM(name, pfx, info)
ENUM_INFO(GEN_ENUMS)

#define STR_INFO(_)						\
	_(fnc_opt_name, FNC, USER_OPTIONS)

#define GEN_STRINGS(name, pfx, info) GEN_STR(name, pfx, info)
STR_INFO(GEN_STRINGS)

Changes to lib/libfossil-config.h.

51
52
53
54
55
56
57
58

59
60
61
62
63
64
65
51
52
53
54
55
56
57

58
59
60
61
62
63
64
65







-
+







#if !defined(HAVE_STDINT_H)
#  define HAVE_STDINT_H 1
#endif
#if !defined(_DEFAULT_SOURCE)
#  define _DEFAULT_SOURCE 1
#endif
#if !defined(_XOPEN_SOURCE)
#  define _XOPEN_SOURCE 500
#  define _XOPEN_SOURCE 700
#endif
#else
#if !defined(HAVE_LSTAT)
#  define HAVE_LSTAT 0
#endif
#if !defined(HAVE_LTDL_H)
#  define HAVE_LTDL_H 0

Changes to lib/libfossil.c.

1
2

3
4
5
6
7
8
9
1

2
3
4
5
6
7
8
9

-
+







#include "libfossil.h"
/* start of file fsl.c */
/* start of file ./src/fsl.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
44
45
46
47
48
49
50


51
52
53
54
55
56
57
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59







+
+







const fsl_buffer fsl_buffer_empty = fsl_buffer_empty_m;
const fsl_card_F fsl_card_F_empty = fsl_card_F_empty_m;
const fsl_card_F_list fsl_card_F_list_empty = fsl_card_F_list_empty_m;
const fsl_card_J fsl_card_J_empty = fsl_card_J_empty_m;
const fsl_card_Q fsl_card_Q_empty = fsl_card_Q_empty_m;
const fsl_card_T fsl_card_T_empty = fsl_card_T_empty_m;
const fsl_checkin_opt fsl_checkin_opt_empty = fsl_checkin_opt_empty_m;
const fsl_cidiff_opt fsl_cidiff_opt_empty = fsl_cidiff_opt_empty_m;
const fsl_cidiff_state fsl_cidiff_state_empty = fsl_cidiff_state_empty_m;
const fsl_ckout_manage_opt fsl_ckout_manage_opt_empty =
  fsl_ckout_manage_opt_empty_m;
const fsl_ckout_unmanage_opt fsl_ckout_unmanage_opt_empty =
  fsl_ckout_unmanage_opt_empty_m;
const fsl_ckup_opt fsl_ckup_opt_empty = fsl_ckup_opt_m;
const fsl_confirmer fsl_confirmer_empty = fsl_confirmer_empty_m;
const fsl_cx fsl_cx_empty = fsl_cx_empty_m;
375
376
377
378
379
380
381
382
383
384



385
386
387
388
389
390
391
377
378
379
380
381
382
383



384
385
386
387
388
389
390
391
392
393







-
-
-
+
+
+







}

int fsl_stricmp_cmp( void const * lhs, void const * rhs ){
  return fsl_stricmp((char const *)lhs, (char const *)rhs);
}

fsl_size_t fsl_strlen( char const * src ){
  fsl_size_t i = 0;
  if(src) for( ; *src; ++i, ++src ){}
  return i;
  char const * const b = src;
  if(src) while( *src ) ++src;
  return (fsl_size_t)(src - b);
}

char * fsl_strndup( char const * src, fsl_int_t len ){
  if(!src) return NULL;
  else{
    fsl_buffer b = fsl_buffer_empty;
    if(len<0) len = (fsl_int_t)fsl_strlen(src);
922
923
924
925
926
927
928
929

930
931
932
933
934
935
936
937
938
939
940
941
942


943
944
945
946
947
948
949
924
925
926
927
928
929
930

931
932
933
934
935
936
937
938
939
940
941
942


943
944
945
946
947
948
949
950
951







-
+











-
-
+
+







}

/**
   Convenience form of fsl_simplify_sql() which assumes b holds an SQL
   string. It gets processed by fsl_simplify_sql() and its 'used'
   length potentially gets adjusted to match the adjusted SQL string.
*/
fsl_size_t fsl_simplify_sql_buffer( fsl_buffer * b ){
fsl_size_t fsl_simplify_sql_buffer( fsl_buffer * const b ){
  return b->used = fsl_simplify_sql( (char *)b->mem, (fsl_int_t)b->used );
}

char const *fsl_preferred_ckout_db_name(){
#if FSL_PLATFORM_IS_WINDOWS
  return "_FOSSIL_";
#else
  return ".fslckout";
#endif
}

char fsl_isatty(int fd){
  return isatty(fd) ? 1 : 0;
bool fsl_isatty(int fd){
  return isatty(fd) ? true : false;
}

bool fsl__is_reserved_fn_windows(const char *zPath, fsl_int_t nameLen){
  static const char *const azRes[] = {
    "CON", "PRN", "AUX", "NUL", "COM", "LPT"
  };
  unsigned int i;
1017
1018
1019
1020
1021
1022
1023




1024
1025
1026
1027
1028
1029
1030


1031
1032
1033
1034
1035
1036
1037
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







+
+
+
+





-
-
+
+







      return zEnd[-10]=='/' ? true : !!gotSuffix;
    }
    default:{
      return false;
    }
  }
}

void fsl_randomness(unsigned int n, void *tgt){
  sqlite3_randomness((int)n, tgt);
}

#undef MARKER
#if defined(_WIN32) || defined(WIN32)
#undef isatty
#endif
/* end of file fsl.c */
/* start of file annotate.c */
/* end of file ./src/fsl.c */
/* start of file ./src/annotate.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
1321
1322
1323
1324
1325
1326
1327
1328
1329






1330
1331
1332
1333
1334
1335
1336
1327
1328
1329
1330
1331
1332
1333


1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346







-
-
+
+
+
+
+
+







      if(NULL==x){
        rc = FSL_RC_OOM;
        goto end;
      }
      a->aVers = x;
      a->naVers = n;
    }
#define AnnStr(COL,FLD) zCol = fsl_stmt_g_text(&q, COL, &nCol); \
    zTmp = fsl_strndup(zCol, nCol); \
#define AnnStr(COL,FLD) zCol = NULL; \
    rc = fsl_stmt_get_text(&q, COL, &zCol, &nCol);  \
    if(rc) goto end;                                \
    else if(!zCol){ goto end;                                           \
      /*zCol=""; nCol=0; //causes downstream 'RID 0 is invalid' error*/}  \
    zTmp = fsl_strndup(zCol, (fsl_int_t)nCol);  \
    if(!zTmp){ rc = FSL_RC_OOM; goto end; } \
    a->aVers[a->nVers].FLD = zTmp
    AnnStr(0,zFUuid);
    AnnStr(1,zMUuid);
    AnnStr(2,zUser);
#undef AnnStr
    a->aVers[a->nVers].mtime = mtime;
1487
1488
1489
1490
1491
1492
1493
1494
1495


1496
1497
1498
1499
1500
1501
1502
1497
1498
1499
1500
1501
1502
1503


1504
1505
1506
1507
1508
1509
1510
1511
1512







-
-
+
+







  fsl__cx_scratchpad_yield(f, scratch);
  fsl__annotator_clean(&ann);
  return rc;
}

#undef MARKER
#undef blob_to_utf8_no_bom
/* end of file annotate.c */
/* start of file appendf.c */
/* end of file ./src/annotate.c */
/* start of file ./src/appendf.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/************************************************************************
The printf-like implementation in this file is based on the one found
in the sqlite3 distribution is in the Public Domain.

This copy was forked for use with the clob API in Feb 2008 by Stephan
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
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







+
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







         && (c=fsl_utf8_read_char(z, zEnd, &zNext));
       z = zNext ){
    if( c=='\\' || c=='"' ){
      out("\\", 1);
      outc;
    }else if( c<' ' ){
      out("\\",1);
      switch(c){
      if( c=='\n' ){
        out("n",1);
      }else if( c=='\r' ){
        out("r",1);
      }else{
        unsigned char ubuf[5] = {'u',0,0,0,0};
        int i;
        for(i = 4; i>0; --i){
          ubuf[i] = "0123456789abcdef"[c&0xf];
          c >>= 4;
        }
        out(ubuf,5);
        case '\b': out("b",1); break;
        case '\f': out("f",1); break;
        case '\n': out("n",1); break;
        case '\t': out("t",1); break;
        case '\r': out("r",1); break;
        default:{
          unsigned char ubuf[5] = {'u',0,0,0,0};
          int i;
          for(i = 4; i>0; --i){
            ubuf[i] = "0123456789abcdef"[c&0xf];
            c >>= 4;
          }
          out(ubuf,5);
          break;
        }
      }
    }else if(c<128){
      outc;
    }/* At this point we know that c is part of a multi-byte
        character. We're assuming legal UTF8 input, which means
        emitting a surrogate pair if the value is > 0xffff. */
    else if(c<0xFFFF){
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
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







-
+

















-
+







      }
      case etSTRING: {
        bufpt = va_arg(ap,char*);
        length = bufpt
          ? StrNLen32(bufpt,
                      (precision>0 && flag_alternateform)
                      ? precision*4/*max bytes per char*/
                      : (precision ? precision : -1))
                      : (precision>=0 ? precision : -1))
          : (int)0;
        if(flag_alternateform && length && (precision>0 || width>0)){
          appendf__utf8_altform(bufpt, &length, &precision, &width);
        }else if( length && precision>=0 && precision<length ){
          length = precision;
        }
        break;
      }
      case etDYNSTRING: {
        /* etDYNSTRING needs to be handled separately because it
           free()s its argument (which isn't available outside this
           block). This means, though, that %-#z does not work. */
        bufpt = va_arg(ap,char*);
        length = bufpt
          ? StrNLen32(bufpt,
                      (precision>0 && flag_alternateform)
                      ? precision*4/*max bytes per char*/
                      : (precision ? precision : -1))
                      : (precision>=0 ? precision : -1))
          : (int)0;
        if(flag_alternateform && length && (precision>0 || width>0)){
          appendf__utf8_altform(bufpt, &length, &precision, &width);
        }else if( length && precision>=0 && precision<length ){
          length = precision;
        }
        pfrc = spech_dynstring( pfAppend, pfAppendArg,
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
3241
3242


3243
3244
3245
3246
3247
3248
3249
3229
3230
3231
3232
3233
3234
3235


3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255

3256
3257
3258
3259
3260
3261
3262
3263
3264







-
-
+
+


















-
+
+







  va_start( vargs, fmt );
  rc = fsl_snprintfv( dest, n, fmt, vargs );
  va_end( vargs );
  return rc;
}

#undef MARKER
/* end of file appendf.c */
/* start of file auth.c */
/* end of file ./src/appendf.c */
/* start of file ./src/auth.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/***************************************************************************
  This file contains routines related to working with user authentication.
*/


FSL_EXPORT char * fsl_sha1_shared_secret( fsl_cx * f, char const * zLoginName,
FSL_EXPORT char * fsl_sha1_shared_secret( fsl_cx * const f,
                                          char const * zLoginName,
                                          char const * zPw ){
    if(!f || !zPw || !zLoginName) return 0;
    else{
        fsl_sha1_cx hash = fsl_sha1_cx_empty;
        unsigned char zResult[20];
        char zDigest[41];
        if(!f->cache.projectCode){
3266
3267
3268
3269
3270
3271
3272
3273

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
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







-
+






-
+












-
+







        fsl_sha1_update(&hash, zPw, fsl_strlen(zPw));
        fsl_sha1_final(&hash, zResult);
        fsl_sha1_digest_to_base16(zResult, zDigest);
        return fsl_strndup( zDigest, FSL_STRLEN_SHA1 );
    }
}

FSL_EXPORT char * fsl_repo_login_group_name(fsl_cx * f){
FSL_EXPORT char * fsl_repo_login_group_name(fsl_cx * const f){
  return f
    ? fsl_config_get_text(f, FSL_CONFDB_REPO,
                          "login-group-name", 0)
    : 0;
}

FSL_EXPORT char * fsl_repo_login_cookie_name(fsl_cx * f){
FSL_EXPORT char * fsl_repo_login_cookie_name(fsl_cx * const f){
  fsl_db * db;
  if(!f || !(db = fsl_cx_db_repo(f))) return 0;
  else{
    char const * sql =
      "SELECT 'fossil-' || substr(value,1,16)"
      "  FROM config"
      " WHERE name IN ('project-code','login-group-code')"
      " ORDER BY name /*sort*/";
    return fsl_db_g_text(db, 0, sql);
  }
}

FSL_EXPORT int fsl_repo_login_search_uid(fsl_cx * f, char const * zUsername,
FSL_EXPORT int fsl_repo_login_search_uid(fsl_cx * const f, char const * zUsername,
                                         char const * zPasswd,
                                         fsl_id_t * userId){
  int rc;
  char * zSecret;
  fsl_db * db;
  if(!f || !userId
     || !zUsername || !*zUsername
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
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
3361
3362
3363
3364
3365







-
+




















-
-
+
+







                     "   AND login NOT IN ('anonymous','nobody','developer','reader')"
                     "   AND (pw=%Q OR (length(pw)<>40 AND pw=%Q))",
                     zUsername, zSecret, zPasswd);
  fsl_free(zSecret);
  return rc;
}

FSL_EXPORT int fsl_repo_login_clear( fsl_cx * f, fsl_id_t userId ){
FSL_EXPORT int fsl_repo_login_clear( fsl_cx * const f, fsl_id_t userId ){
  fsl_db * db;
  if(!f) return FSL_RC_MISUSE;
  else if(!(db = fsl_needs_repo(f))) return FSL_RC_NOT_A_REPO;
  else{
    int const rc = fsl_db_exec(db,
                       "UPDATE user SET cookie=NULL, ipaddr=NULL, "
                       " cexpire=0 WHERE "
                       " CASE WHEN %"FSL_ID_T_PFMT">=0 THEN uid=%"FSL_ID_T_PFMT""
                       " ELSE uid>0 END"
                       " AND login NOT IN('anonymous','nobody',"
                       " 'developer','reader')",
                       (fsl_id_t)userId, (fsl_id_t)userId);
    if(rc){
      fsl_cx_uplift_db_error(f, db);
    }
    return rc;
  }
}

#undef MARKER
/* end of file auth.c */
/* start of file bag.c */
/* end of file ./src/auth.c */
/* start of file ./src/bag.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
3535
3536
3537
3538
3539
3540
3541
3542
3543


3544
3545
3546
3547
3548
3549
3550
3550
3551
3552
3553
3554
3555
3556


3557
3558
3559
3560
3561
3562
3563
3564
3565







-
-
+
+







void fsl_id_bag_swap(fsl_id_bag * const lhs, fsl_id_bag * const rhs){
  fsl_id_bag x = *lhs;
  *lhs = *rhs;
  *rhs = x;
}

#undef fsl_id_bag_hash
/* end of file bag.c */
/* start of file buffer.c */
/* end of file ./src/bag.c */
/* start of file ./src/buffer.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
3563
3564
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


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
3668
3669

3670
3671
3672




3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684









3685
3686
3687
3688
3689
3690
3691
3692
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
3668
3669
3670
3671
3672
3673
3674





3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695

3696
3697
3698

3699
3700

3701
3702




3703
3704
3705
3706
3707
3708
3709
3710

3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
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







+

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+



-
+
-
-
-
-
-
+
+
+
+
-
-
+


+
-
+
+


-
+
+



+

+
+
+
+
+
-
-
-
+
+
+
+
+
+
+
+






-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


-
+


-
+

-
+

-
-
-
-
+
+
+
+




-
+

















-
+
















-
-
+
+

-
-
-
+
-
-
-
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
-









#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

#define buffer_is_external(b) (b->mem && 0==b->capacity)

/**
   Materializes external buffer b by allocating b->used+extra+1
   bytes, copying b->used bytes from b->mem to the new block,
   NUL-terminating the block, and replacing b->mem with the new
   block. Returns 0 on success, else FSL_RC_OOM.

   Asserts that b is an external buffer.
*/
static int fsl__buffer_materialize( fsl_buffer * const b, fsl_size_t extra ){
  assert(buffer_is_external(b));
  fsl_size_t const n = b->used + extra + 1;
  unsigned char * x = (unsigned char *)fsl_malloc(n);
  if(!x) return FSL_RC_OOM;
  memcpy(x, b->mem, b->used);
  b->capacity = n;
  x[b->used] = 0;
  b->mem = x;
  return 0;
}

int fsl_buffer_materialize( fsl_buffer * const b ){
  return buffer_is_external(b) ? fsl__buffer_materialize(b, 0) : 0;
}

#define buffer_materialize(B,N) (buffer_is_external(B) ? fsl__buffer_materialize((B),(N)) : 0)

void fsl_buffer_external( fsl_buffer * const b, void const * mem, fsl_int_t n ){
  if(b->mem) fsl_buffer_clear(b);
  if(n<0) n =(fsl_int_t)fsl_strlen((char const *)mem);
  b->used = n;
  b->cursor = 0;
  b->mem = (unsigned char *)mem;
  b->capacity = 0;
}

fsl_buffer * fsl_buffer_reuse( fsl_buffer * b ){
  if(b->capacity){
    assert(b->mem);
    b->mem[0] = 0;
  }
  b->used = b->cursor = 0;
fsl_buffer * fsl_buffer_reuse( fsl_buffer * const b ){
  if(buffer_is_external(b)){
    *b = fsl_buffer_empty;
  }else{
    if(b->capacity){
      assert(b->mem);
      b->mem[0] = 0;
      b->used = 0;
    }
    b->cursor = 0;
  }
  return b;
}

void fsl_buffer_clear( fsl_buffer * buf ){
void fsl_buffer_clear( fsl_buffer * const buf ){
  if(buf){
    if(buf->mem) fsl_free(buf->mem);
    *buf = fsl_buffer_empty;
  }
}
  if(buf->capacity) fsl_free(buf->mem);
  *buf = fsl_buffer_empty;
}


int fsl_buffer_reserve( fsl_buffer * buf, fsl_size_t n ){
int fsl_buffer_reserve( fsl_buffer * const buf, fsl_size_t n ){
  if( ! buf ) return FSL_RC_MISUSE;
  else if( 0 == n ){
    if(!buffer_is_external(buf)){
    fsl_free(buf->mem);
      fsl_free(buf->mem);
    }/* else if it has memory, it's owned elsewhere */
    *buf = fsl_buffer_empty;
    return 0;
  }else if( buf->capacity >= n ){
  }else if( !buffer_is_external(buf) && buf->capacity >= n ){
    assert(buf->mem);
    return 0;
  }else{
    unsigned char * x;
    bool const isExt = buffer_is_external(buf);
    assert((buf->used < n) && "Buffer in-use greater than capacity!");
    if(isExt && n<=buf->used){
      /*For external buffers, always keep at least the initially-pointed-to
        size. */
      n = buf->used + 1;
    }
    x = (unsigned char *)fsl_realloc( buf->mem, n );
    if( ! x ) return FSL_RC_OOM;
    memset( x + buf->used, 0, n - buf->used );
    x = (unsigned char *)fsl_realloc( isExt ? NULL : buf->mem, n );
    if( !x ) return FSL_RC_OOM;
    else if(isExt){
      memcpy( x, buf->mem, buf->used );
      x[buf->used] = 0;
    }else{
      memset( x + buf->used, 0, n - buf->used );
    }
    buf->mem = x;
    buf->capacity = n;
    return 0;
  }
}

int fsl_buffer_resize( fsl_buffer * buf, fsl_size_t n ){
  if( !buf ) return FSL_RC_MISUSE;
  else if(n && (buf->capacity == n+1)){
    buf->used = n;
    buf->mem[n] = 0;
int fsl_buffer_resize( fsl_buffer * const b, fsl_size_t n ){
  if(buffer_is_external(b)){
    if(n==b->used) return 0;
    else if(n==0){
      b->capacity = 0;
      fsl_buffer_external(b, "", 0);
      return 0;
    }
    unsigned char * x = (unsigned char *)fsl_malloc( n+1/*NUL*/ );
    if( !x ) return FSL_RC_OOM;
    memcpy(x, b->mem, n < b->used ? n : b->used);
    x[n] = 0;
    b->mem = x;
    b->capacity = n+1;
    b->used = n;
    return 0;
  }else if(n && (b->capacity == n+1)){
    b->used = n;
    b->mem[n] = 0;
    return 0;
  }else{
    unsigned char * x = (unsigned char *)fsl_realloc( buf->mem,
    unsigned char * x = (unsigned char *)fsl_realloc( b->mem,
                                                      n+1/*NUL*/ );
    if( ! x ) return FSL_RC_OOM;
    if(n > buf->capacity){
    if(n > b->capacity){
      /* zero-fill new parts */
      memset( x + buf->capacity, 0, n - buf->capacity +1/*NUL*/ );
      memset( x + b->capacity, 0, n - b->capacity +1/*NUL*/ );
    }
    buf->capacity = n + 1 /*NUL*/;
    buf->used = n;
    buf->mem = x;
    buf->mem[buf->used] = 0;
    b->capacity = n + 1 /*NUL*/;
    b->used = n;
    b->mem = x;
    b->mem[b->used] = 0;
    return 0;
  }
}

int fsl_buffer_compare(fsl_buffer const * lhs, fsl_buffer const * rhs){
int fsl_buffer_compare(fsl_buffer const * const lhs, fsl_buffer const * const rhs){
  fsl_size_t const szL = lhs->used;
  fsl_size_t const szR = rhs->used;
  fsl_size_t const sz = (szL<szR) ? szL : szR;
  int rc = memcmp(lhs->mem, rhs->mem, sz);
  if(0 == rc){
    rc = (szL==szR)
      ? 0
      : ((szL<szR) ? -1 : 1);
  }
  return rc;
}

/*
   Compare two blobs in constant time and return zero if they are equal.
   Constant time comparison only applies for blobs of the same length.
   If lengths are different, immediately returns 1.
*/
int fsl_buffer_compare_O1(fsl_buffer const * lhs, fsl_buffer const * rhs){
int fsl_buffer_compare_O1(fsl_buffer const * const lhs, fsl_buffer const * const rhs){
  fsl_size_t const szL = lhs->used;
  fsl_size_t const szR = rhs->used;
  fsl_size_t i;
  unsigned char const *buf1;
  unsigned char const *buf2;
  unsigned char rc = 0;
  if( szL!=szR || szL==0 ) return 1;
  buf1 = lhs->mem;
  buf2 = rhs->mem;
  for( i=0; i<szL; i++ ){
    rc = rc | (buf1[i] ^ buf2[i]);
  }
  return rc;
}


int fsl_buffer_append( fsl_buffer * b,
                       void const * data,
int fsl_buffer_append( fsl_buffer * const b,
                       void const * const data,
                       fsl_int_t len ){
  if(!b || !data) return FSL_RC_MISUSE;
  else{
    fsl_size_t sz = b->used;
  fsl_size_t sz = b->used;
    int rc = 0;
    assert(b->capacity ? !!b->mem : !b->mem);
    assert(b->used <= b->capacity);
  if(len<0) len = (fsl_int_t)fsl_strlen((char const *)data);
  if(buffer_materialize(b, (fsl_size_t)len + 1)) return FSL_RC_OOM;
  assert(b->capacity ? !!b->mem : !b->mem);
  assert(b->used <= b->capacity);
    if(len<0){
      len = (fsl_int_t)fsl_strlen((char const *)data);
    }
    sz += len + 1/*NUL*/;
    rc = b->capacity<sz ? fsl_buffer_reserve( b, sz ) : 0;
    if(!rc){
      assert(b->capacity >= sz);
      if(len>0) memcpy(b->mem + b->used, data, (size_t)len);
      b->used += len;
      b->mem[b->used] = 0;
    }
    return rc;
  sz += len + 1/*NUL*/;
  int const rc = b->capacity<sz ? fsl_buffer_reserve( b, sz ) : 0;
  if(!rc){
    assert(b->capacity >= sz);
    if(len>0) memcpy(b->mem + b->used, data, (size_t)len);
    b->used += len;
    b->mem[b->used] = 0;
  }
  return rc;
  }
}

int fsl_buffer_appendfv( fsl_buffer * const b, char const * fmt,
                         va_list args){
  return fsl_appendfv( fsl_output_f_buffer, b, fmt, args );
}

3700
3701
3702
3703
3704
3705
3706
3707

3708
3709
3710
3711

3712
3713
3714
3715
3716
3717
3718
3719
3720
3721


3722
3723
3724

3725
3726


3727
3728
3729
3730


3731

3732
3733

3734
3735
3736
3737
3738
3739
3740
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
3804
3805
3806


3807
3808
3809
3810
3811

3812
3813
3814
3815
3816
3817
3818
3819







-
+



-
+








-
-
+
+



+
-
-
+
+


-
-
+
+

+

-
+







    va_start(args,fmt);
    rc = fsl_buffer_appendfv( b, fmt, args );
    va_end(args);
    return rc;
  }
}

char const * fsl_buffer_cstr(fsl_buffer const *b){
char const * fsl_buffer_cstr(fsl_buffer const * const b){
  return b ? (char const *)b->mem : NULL;
}

char const * fsl_buffer_cstr2(fsl_buffer const *b, fsl_size_t * len){
char const * fsl_buffer_cstr2(fsl_buffer const * const b, fsl_size_t * const len){
  char const * rc = NULL;
  if(b){
    rc = (char const *)b->mem;
    if(len) *len = b->used;
  }
  return rc;
}

char * fsl_buffer_str(fsl_buffer const *b){
  return b ? (char *)b->mem : NULL;
char * fsl_buffer_str(fsl_buffer const * const b){
  return (char *)b->mem;
}


#if 0
fsl_size_t fsl_buffer_size(fsl_buffer const * b){
  return b ? b->used : 0U;
fsl_size_t fsl_buffer_size(fsl_buffer const * const b){
  return b->used;
}

fsl_size_t fsl_buffer_capacity(fsl_buffer const * b){
  return b ? b->capacity : 0;
fsl_size_t fsl_buffer_capacity(fsl_buffer const * const b){
  return b->capacity;
}
#endif

bool fsl_data_is_compressed(unsigned char const * mem, fsl_size_t len){
bool fsl_data_is_compressed(unsigned char const * const mem, fsl_size_t len){
  if(!mem || (len<6)) return 0;
#if 0
  else return ('x'==mem[4])
    && (0234==mem[5]);
  /*
    This check fails for one particular artifact in the tcl core.
    Notes gathered while debugging...
3894
3895
3896
3897
3898
3899
3900
3901

3902
3903
3904

3905
3906
3907
3908
3909







3910
3911
3912
3913















3914
3915





3916
3917

3918
3919
3920
3921
3922





3923
3924
3925
3926
3927
3928
3929
3930



3931
3932


3933
3934
3935
3936




3937
3938
3939
3940
3941
3942




















3943
3944
3945
3946
3947
3948
3949
3973
3974
3975
3976
3977
3978
3979

3980
3981
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
4027
4028
4029



4030
4031
4032


4033
4034




4035
4036
4037
4038






4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065







-
+


-
+



-
-
+
+
+
+
+
+
+




+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
+
+
+

-
+
-
-
-
-
-
+
+
+
+
+





-
-
-
+
+
+
-
-
+
+
-
-
-
-
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







    }else{
      fsl_buffer_reserve(&temp, 0);
    }
    return rc;
  }
}

int fsl_buffer_uncompress(fsl_buffer const *pIn, fsl_buffer *pOut){
int fsl_buffer_uncompress(fsl_buffer const * const pIn, fsl_buffer * const pOut){
  unsigned int nOut;
  unsigned char *inBuf;
  unsigned int nIn = pIn->used;
  unsigned int const nIn = pIn->used;
  fsl_buffer temp = fsl_buffer_empty;
  int rc;
  unsigned long int nOut2;
  if( nIn<=4 ){
    return FSL_RC_RANGE;
  if(nIn<=4 || !fsl_data_is_compressed(pIn->mem, pIn->used)){
    if(pIn==pOut || !pIn->mem) rc = 0;
    else{
      fsl_buffer_reuse(pOut);
      rc = fsl_buffer_append(pOut, pIn->mem, pIn->used);
    }
    return rc;
  }
  inBuf = pIn->mem;
  nOut = (inBuf[0]<<24) + (inBuf[1]<<16) + (inBuf[2]<<8) + inBuf[3];
  /* MARKER(("decompress size: %u\n", nOut)); */
  if(pIn!=pOut && pOut->capacity>=nOut+1){
    assert(pIn->mem != pOut->mem);
#if 0
    /* why does this cause corruption (in the form of overwriting a
       buffer somewhere in the fsl_content_get() constellation)?
       fsl_repo_rebuild() works but fsl_repo_extract() can trigger
       it:

       (FSL_RC_RANGE): Delta: copy extends past end of input
    */
    fsl_buffer_external(&temp, pOut->mem, pOut->capacity);
#else
    fsl_buffer_swap(&temp, pOut);
#endif
  }else{
  rc = fsl_buffer_reserve(&temp, nOut+1);
  if(rc) return rc;
    rc = fsl_buffer_reserve(&temp, nOut+1);
    if(rc) return rc;
    temp.mem[nOut] = 0;
  }
  
  nOut2 = (long int)nOut;
  rc = uncompress(temp.mem, &nOut2,
  rc = uncompress(temp.mem, &nOut2, &inBuf[4], nIn - 4)
                  &inBuf[4], nIn - 4)
    /* valgrind says there's an uninitialized memory access
       somewhere under uncompress(), _presumably_ for one of
       these arguments, but i can't find it. fsl_buffer_reserve()
       always memsets() new bytes to 0.
    /* In some libz versions (<1.2.4, apparently), valgrind says
       there's an uninitialized memory access somewhere under
       uncompress(), _presumably_ for one of these arguments, but i
       can't find it. fsl_buffer_reserve() always memsets() new bytes
       to 0.

       Turns out it's a known problem:

       https://www.zlib.net/zlib_faq.html#faq36
    */;
  if( rc!=Z_OK ){
    fsl_buffer_reserve(&temp, 0);
    return FSL_RC_ERROR;
  switch(rc){
    case 0:
      /* this is always true but having this assert
  }
  rc = fsl_buffer_resize(&temp, nOut2);
         here makes me nervous: assert(nOut2 == nOut); */
      assert(nOut2<=nOut);
  if(!rc){
    temp.used = (fsl_size_t)nOut2;
    if( pOut==pIn ){
      fsl_buffer_reserve(pOut, 0);
      temp.mem[nOut2] = 0;
      temp.used = (fsl_size_t)nOut2;
#if 1
      fsl_buffer_swap(&temp, pOut);
    }
    assert(!pOut->mem);
    *pOut = temp;
  }else{
    fsl_buffer_reserve(&temp, 0);
  }
#else
      if(temp.mem!=pOut->mem){
        if(pOut->capacity>=temp.capacity){
          pOut->used = 0;
          MARKER(("uncompress() re-using target buffer.\n"));
          fsl_buffer_append(pOut, temp.mem, temp.capacity);
        }else{
          fsl_buffer_swap(pOut, &temp);
        }
      }
#endif
      break;
    case Z_DATA_ERROR: rc = FSL_RC_CONSISTENCY; break;
    case Z_MEM_ERROR: rc = FSL_RC_OOM; break;
    case Z_BUF_ERROR:
      assert(!"Cannot happen!");
      rc = FSL_RC_RANGE; break;
    default: rc = FSL_RC_ERROR; break;
  }
  if(temp.mem!=pOut->mem) fsl_buffer_clear(&temp);
  return rc;
}


int fsl_buffer_fill_from( fsl_buffer * const dest, fsl_input_f src,
                          void * const state )
{
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034




4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051


4052
4053
4054
4055

4056
4057
4058
4059
4060
4061



4062
4063
4064
4065

4066
4067
4068
4069



4070
4071

4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089



4090
4091
4092
4093



4094
4095
4096
4097
4098
4099
4100






4101
4102
4103

4104
4105
4106
4107



4108
4109
4110

4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130

4131
4132

4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146




4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165


4166
4167



4168
4169
4170
4171
4172



4173
4174
4175
4176
4177
4178

4179




4180
4181
4182


4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198



4199
4200
4201




4202
4203
4204







4205
4206
4207
4208
4209
4210



4211




4212
4213
4214
4215


4216

4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234

4235


4236
4237
4238
4239
4240
4241
4242
4243







-
-
-
-
+
+
+
+















-
-
+
+
-
-
-

+



-
-
-
+
+
+



-
+
-
-
-
-
+
+
+
-
-
+















-
-
-
+
+
+
-
-
-
-
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
+
-
-
-
-
+
+
+

-
-
+
-


















-
+
-
-
+







                     fsl_buffer const * const src ){
  fsl_buffer_reuse(dest);
  return src->used
    ? fsl_buffer_append( dest, src->mem, src->used )
    : 0;
}

int fsl_buffer_delta_apply2( fsl_buffer const * orig,
                             fsl_buffer const * pDelta,
                             fsl_buffer * pTarget,
                             fsl_error * pErr){
int fsl_buffer_delta_apply2( fsl_buffer const * const orig,
                             fsl_buffer const * const pDelta,
                             fsl_buffer * const pTarget,
                             fsl_error * const pErr){
  int rc;
  fsl_size_t n = 0;
  fsl_buffer out = fsl_buffer_empty;
  rc = fsl_delta_applied_size( pDelta->mem, pDelta->used, &n);
  if(rc){
    if(pErr){
      fsl_error_set(pErr, rc, "fsl_delta_applied_size() failed.");
    }
    return rc;
  }
  rc = fsl_buffer_resize( &out, n );
  if(rc) return rc;
  rc = fsl_delta_apply2( orig->mem, orig->used,
                        pDelta->mem, pDelta->used,
                        out.mem, pErr);
  if(rc){
    fsl_buffer_clear(&out);
  if(0==rc){
    fsl_buffer_swap(&out, pTarget);
  }else{
    fsl_buffer_clear(pTarget);
    *pTarget = out;
  }
  fsl_buffer_clear(&out);
  return rc;
}

int fsl_buffer_delta_apply( fsl_buffer const * orig,
                            fsl_buffer const * pDelta,
                            fsl_buffer * pTarget){
int fsl_buffer_delta_apply( fsl_buffer const * const orig,
                            fsl_buffer const * const pDelta,
                            fsl_buffer * const pTarget){
  return fsl_buffer_delta_apply2(orig, pDelta, pTarget, NULL);
}

void fsl_buffer_defossilize( fsl_buffer * b ){
void fsl_buffer_defossilize( fsl_buffer * const b ){
  if(b){
    fsl_bytes_defossilize( b->mem, &b->used );
  }
}
  fsl_bytes_defossilize( b->mem, &b->used );
}


int fsl_buffer_to_filename( fsl_buffer const * b, char const * fname ){
int fsl_buffer_to_filename( fsl_buffer const * const b, char const * fname ){
  FILE * f;
  int rc = 0;
  if(!b || !fname) return FSL_RC_MISUSE;
  f = fsl_fopen(fname, "wb");
  if(!f) rc = fsl_errno_to_rc(errno, FSL_RC_IO);
  else{
    if(b->used) {
      size_t const frc = fwrite(b->mem, b->used, 1, f);
      rc = (1==frc) ? 0 : FSL_RC_IO;
    }
    fsl_fclose(f);
  }
  return rc;
}

int fsl_buffer_delta_create( fsl_buffer const * src,
                             fsl_buffer const * newVers,
                             fsl_buffer * delta){
int fsl_buffer_delta_create( fsl_buffer const * const src,
                             fsl_buffer const * const newVers,
                             fsl_buffer * const delta){
  if(!src || !newVers || !delta) return FSL_RC_MISUSE;
  else if((src == newVers)
          || (src==delta)
          || (newVers==delta)) return FSL_RC_MISUSE;
  if((src == newVers)
     || (src==delta)
     || (newVers==delta)) return FSL_RC_MISUSE;
  else{
    int rc = fsl_buffer_reserve( delta, newVers->used + 60 );
    if(!rc){
      delta->used = 0;
      rc = fsl_delta_create( src->mem, src->used,
                             newVers->mem, newVers->used,
                             delta->mem, &delta->used );
  int rc = fsl_buffer_reserve( delta, newVers->used + 60 );
  if(!rc){
    delta->used = 0;
    rc = fsl_delta_create( src->mem, src->used,
                           newVers->mem, newVers->used,
                           delta->mem, &delta->used );
      if(!rc){
        rc = fsl_buffer_resize( delta, delta->used );
      }
  }
    }
    return rc;
  }
}
  return rc;
}



int fsl_output_f_buffer( void * state,
int fsl_output_f_buffer( void * state, void const * src, fsl_size_t n ){
                         void const * src, fsl_size_t n ){
  return (!state || !src)
    ? FSL_RC_MISUSE
    : fsl_buffer_append((fsl_buffer*)state, src, n);
}

int fsl_finalizer_f_buffer( void * state, void * mem ){
  fsl_buffer * b = (fsl_buffer*)mem;
  fsl_buffer_reserve(b, 0);
  *b = fsl_buffer_empty;
  return 0;
}

int fsl_buffer_strftime(fsl_buffer * const b, char const * format,
                        const struct tm *timeptr){
  if(!b || !format || !*format || !timeptr) return FSL_RC_MISUSE;
  else{
    enum {BufSize = 128};
    char buf[BufSize];
    fsl_size_t len = fsl_strftime(buf, BufSize, format, timeptr);
    fsl_size_t const len = fsl_strftime(buf, BufSize, format, timeptr);
    if(!len) return FSL_RC_RANGE;
    return fsl_buffer_append(b, buf, (fsl_int_t)len);
    return len ? fsl_buffer_append(b, buf, (fsl_int_t)len) : FSL_RC_RANGE;
  }
}

int fsl_buffer_stream_lines(fsl_output_f fTo, void * const toState,
                            fsl_buffer * const pFrom, fsl_size_t N){
  char *z = (char *)pFrom->mem;
  fsl_size_t i = pFrom->cursor;
4246
4247
4248
4249
4250
4251
4252


4253
4254



4255
4256
4257
4258
4259
4260
4261
4350
4351
4352
4353
4354
4355
4356
4357
4358


4359
4360
4361
4362
4363
4364
4365
4366
4367
4368







+
+
-
-
+
+
+







    fsl_buffer_clear(&fc);
#endif
    return rc;
  }
}

char * fsl_buffer_take(fsl_buffer * const b){
  char * z = NULL;
  if(0==buffer_materialize(b,0)){
  char * z = (char *)b->mem;
  *b = fsl_buffer_empty;
    z = (char *)b->mem;
    *b = fsl_buffer_empty;
  }
  return z;
}

fsl_size_t fsl_buffer_seek(fsl_buffer * const b, fsl_int_t offset,
                           fsl_buffer_seek_e  whence){
  int64_t c = (int64_t)b->cursor;
  switch(whence){
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
4335


4336
4337
4338
4339
4340
4341
4342
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425

4426
4427
4428
4429
4430
4431
4432
4433
4434

4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447


4448
4449
4450
4451
4452
4453
4454
4455
4456







+






+

-
+
+
+





+
-
+










+
+
-
-
+
+







    if(i++) rc = fsl_buffer_append(b, separator, sepLen);
    if(!rc) rc = fsl_buffer_appendf(b, "%" FSL_ID_T_PFMT, e);
  }
  return rc;
}

int fsl_buffer_append_tcl_literal(fsl_buffer * const b,
                                  bool escapeSquigglies,
                                  char const * z, fsl_int_t n){
  int rc;
  if(n<0) n = fsl_strlen(z);
  rc = fsl_buffer_append(b, "\"", 1);
  for(fsl_int_t i=0; 0==rc && i<n; ++i){
    char c = z[i];
    bool skipSlash = false;
    switch( c ){
      case '\r':  c = 'r';
      case '\r':  c = 'r'; goto slash;
      case '}': case '{': skipSlash = !escapeSquigglies;
        /* fall through */
      case '[':
      case ']':
      case '$':
      case '"':
      case '\\':
      slash:
        if((rc = fsl_buffer_append(b, "\\", 1))) break;
        if(!skipSlash && (rc = fsl_buffer_append(b, "\\", 1))) break;
        /* fall through */
      default:
        rc = fsl_buffer_append(b, &c, 1);
    }
  }
  if(0==rc) rc = fsl_buffer_append(b, "\"", 1);
  return rc;
}

#undef MARKER
#undef buffer_is_external
#undef buffer_materialize
/* end of file buffer.c */
/* start of file cache.c */
/* end of file ./src/buffer.c */
/* start of file ./src/cache.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
4489
4490
4491
4492
4493
4494
4495
4496
4497


4498
4499
4500
4501
4502
4503
4504
4603
4604
4605
4606
4607
4608
4609


4610
4611
4612
4613
4614
4615
4616
4617
4618







-
-
+
+







  }
  assert(!"delta-loop in repository");
  return fsl_cx_err_set(f, FSL_RC_CONSISTENCY,
                        "Serious problem: delta-loop in repository");
}

#undef MARKER
/* end of file cache.c */
/* start of file checkin.c */
/* end of file ./src/cache.c */
/* start of file ./src/checkin.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
4538
4539
4540
4541
4542
4543
4544
4545


4546
4547

4548

4549
4550
4551

4552
4553
4554
4555
4556
4557
4558
4652
4653
4654
4655
4656
4657
4658

4659
4660
4661
4662
4663

4664
4665
4666

4667
4668
4669
4670
4671
4672
4673
4674







-
+
+


+
-
+


-
+







   ignore if (e.g.) the parent content is already a delta of something
   else.

   The wise caller will have a transaction in place when calling this.

   Returns 0 on success. On error rid and uuid are not modified.
*/
static int fsl_checkin_import_file( fsl_cx * f, char const * zRelName,
static int fsl_checkin_import_file( fsl_cx * const f,
                                    char const * const zRelName,
                                    fsl_id_t parentRid,
                                    bool allowMergeConflict,
                                    fsl_id_t * const rid,
                                    fsl_id_t *rid, fsl_uuid_str * uuid){
                                    fsl_uuid_str * const uuid){
  fsl_buffer * nbuf = fsl__cx_scratchpad(f);
  fsl_size_t const oldSize = nbuf->used;
  fsl_buffer * fbuf = &f->fileContent;
  fsl_buffer * const fbuf = &f->cache.fileContent;
  char const * fn;
  int rc;
  fsl_id_t fnid = 0;
  fsl_id_t rcRid = 0;
  assert(!fbuf->used && "Misuse of f->fileContent");
  assert(f->ckout.dir);
  rc = fsl__repo_filename_fnid2(f, zRelName, &fnid, 1);
4781
4782
4783
4784
4785
4786
4787
4788

4789
4790
4791
4792
4793
4794
4795
4897
4898
4899
4900
4901
4902
4903

4904
4905
4906
4907
4908
4909
4910
4911







-
+







  if(rc) fsl_db_transaction_rollback(db);
  else{
    rc = fsl_cx_uplift_db_error2(f, db, fsl_db_transaction_commit(db));
  }
  return rc;
}

int fsl_checkin_dequeue(fsl_cx * f, fsl_checkin_queue_opt const * opt){
int fsl_checkin_dequeue(fsl_cx * const f, fsl_checkin_queue_opt const * opt){
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return FSL_RC_NOT_A_CKOUT;
  int rc = fsl_db_transaction_begin(db);
  if(rc) return fsl_cx_uplift_db_error2(f, db, rc);
  fsl_id_bag list = fsl_id_bag_empty;
  fsl_buffer * canon = 0;
  char const * fn;
4822
4823
4824
4825
4826
4827
4828
4829

4830
4831
4832
4833


4834
4835
4836
4837
4838
4839
4840
4938
4939
4940
4941
4942
4943
4944

4945
4946



4947
4948
4949
4950
4951
4952
4953
4954
4955







-
+

-
-
-
+
+







  if(rc) fsl_db_transaction_rollback(db);
  else{
    rc = fsl_cx_uplift_db_error2(f, db, fsl_db_transaction_commit(db));
  }
  return rc;
}

bool fsl_checkin_is_enqueued(fsl_cx * f, char const * zName,
bool fsl_checkin_is_enqueued(fsl_cx * const f, char const * zName,
                             bool relativeToCwd){
  fsl_db * db;
  if(!f || !zName || !*zName) return 0;
  else if(!(db = fsl_needs_ckout(f))) return 0;
  if(!zName || !*zName) return false;
  else if(!fsl_cx_db_ckout(f)) return false;
  else if(!f->ckin.selectedIds.entryCount){
    /* Behave like fsl_is_enqueued() SQL function. */
    return true;
  }
  else {
    bool rv = false;
    fsl_buffer * const canon = fsl__cx_scratchpad(f);
4851
4852
4853
4854
4855
4856
4857
4858
4859

4860
4861
4862
4863
4864
4865
4866
4966
4967
4968
4969
4970
4971
4972


4973
4974
4975
4976
4977
4978
4979
4980







-
-
+







           : false);
    }
    fsl__cx_scratchpad_yield(f, canon);
    return rv;
  }
}


void fsl_checkin_discard(fsl_cx * f){
void fsl_checkin_discard(fsl_cx * const f){
  if(f){
    fsl_id_bag_clear(&f->ckin.selectedIds);
    fsl_deck_finalize(&f->ckin.mf);
  }
}

/**
5675
5676
5677
5678
5679
5680
5681
5682

5683
5684
5685
5686
5687
5688
5689
5789
5790
5791
5792
5793
5794
5795

5796
5797
5798
5799
5800
5801
5802
5803







-
+







                         "WHERE fsl_is_enqueued(id)",
                         vid, d->rid);
  if(!rc) rc = fsl__ckout_version_write(f, d->rid, NULL);
  RC;
  assert(d->f == f);
  rc = fsl_checkin_add_unsent(f, d->rid);
  RC;
  rc = fsl__ckout_clear_merge_state(f);
  rc = fsl__ckout_clear_merge_state(f, true);
  RC;
  /*
    todo(?) from fossil(1) follows. Most of this seems to be what the
    vfile handling does (above).

    db_multi_exec("PRAGMA %s.application_id=252006673;", db_name("repository"));
    db_multi_exec("PRAGMA %s.application_id=252006674;", db_name("localdb"));
5769
5770
5771
5772
5773
5774
5775
5776
5777


5778
5779
5780
5781
5782
5783
5784
5883
5884
5885
5886
5887
5888
5889


5890
5891
5892
5893
5894
5895
5896
5897
5898







-
-
+
+







  fsl_checkin_discard(f);
  fsl_deck_finalize(d);
  return rc;
}


#undef MARKER
/* end of file checkin.c */
/* start of file checkout.c */
/* end of file ./src/checkin.c */
/* start of file ./src/checkout.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
5806
5807
5808
5809
5810
5811
5812
5813
5814


5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834

5835
5836
5837
5838
5839
5840
5841
5920
5921
5922
5923
5924
5925
5926


5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947

5948
5949
5950
5951
5952
5953
5954
5955







-
-
+
+



















-
+







/**
    Kludge for type-safe strncmp/strnicmp inconsistency.
*/
static int fsl_strnicmp_int(char const *zA, char const * zB, fsl_size_t nByte){
  return fsl_strnicmp( zA, zB, (fsl_int_t)nByte);
}

int fsl_ckout_filename_check( fsl_cx * f, bool relativeToCwd,
                              char const * zOrigName, fsl_buffer * pOut ){
int fsl_ckout_filename_check( fsl_cx * const f, bool relativeToCwd,
                              char const * zOrigName, fsl_buffer * const pOut ){
  int rc;
  if(!zOrigName || !*zOrigName) return FSL_RC_MISUSE;
  else if(!fsl_needs_ckout(f)/* will update f's error state*/){
    return FSL_RC_NOT_A_CKOUT;
  }
#if 0
  /* Is this sane? */
  else if(fsl_is_simple_pathname(zOrigName,1)){
    rc = 0;
    if(pOut){
      rc = fsl_buffer_append(pOut, zOrigName, fsl_strlen(zOrigName));
    }
  }
#endif
  else{
    char const * zLocalRoot;
    char const * zFull;
    fsl_size_t nLocalRoot;
    fsl_size_t nFull;
    fsl_buffer * full = fsl__cx_scratchpad(f);
    fsl_buffer * const full = fsl__cx_scratchpad(f);
    int (*xCmp)(char const *, char const *,fsl_size_t);
    bool endsWithSlash;
    assert(f->ckout.dir);
    zLocalRoot = f->ckout.dir;
    assert(zLocalRoot);
    assert(*zLocalRoot);
    nLocalRoot = f->ckout.dirLen;
5853
5854
5855
5856
5857
5858
5859
5860

5861
5862
5863
5864
5865
5866
5867
5967
5968
5969
5970
5971
5972
5973

5974
5975
5976
5977
5978
5979
5980
5981







-
+







                            "file name: %s\n",
                            rc, fsl_rc_cstr(rc),
                            zOrigName);
      }
      goto end;
    }
    zFull = fsl_buffer_cstr2(full, &nFull);
    xCmp = fsl_cx_is_case_sensitive(f)
    xCmp = fsl_cx_is_case_sensitive(f,false)
      ? fsl_strncmp
      : fsl_strnicmp_int;
    assert(zFull);
    assert(nFull>0);
    endsWithSlash = '/' == zFull[nFull-1];
    if( ((nFull==nLocalRoot-1 || (nFull==nLocalRoot && endsWithSlash))
         && xCmp(zLocalRoot, zFull, nFull)==0)
6033
6034
6035
6036
6037
6038
6039










6040
6041
6042
6043
6044
6045
6046
6047
6048



6049
6050
6051
6052
6053
6054
6055
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







+
+
+
+
+
+
+
+
+
+






-
-
-
+
+
+







  return fsl_db_exists(fsl_cx_db_ckout(f),
                       "SELECT 1 FROM vfile"
                       " WHERE vid=%"FSL_ID_T_PFMT
                       " AND pathname=%Q %s",
                       f->ckout.rid, zFilename,
                       fsl_cx_filename_collation(f));
}


/** Initialized-with-defaults fsl_ckout_manage_state structure, intended for
    const-copy initialization. */
#define fsl_ckout_manage_state_empty_m {NULL,NULL,NULL}
/** Initialized-with-defaults fsl_ckout_manage_state structure, intended for
    non-const copy initialization. */
static const fsl_ckout_manage_state fsl_ckout_manage_state_empty
= fsl_ckout_manage_state_empty_m;

/**
   Internal machinery for fsl_ckout_manage(). zFilename MUST
   be a checkout-relative file which is known to exist. fst MUST
   be an object populated by fsl_stat()'ing zFilename. isInVFile
   MUST be the result of having passed zFilename to fsl_co_is_in_vfile().
 */
static int fsl_ckout_manage_impl( fsl_cx * f, char const *zFilename,
                                       fsl_fstat const *fst,
                                       bool isInVFile){
static int fsl_ckout_manage_impl(fsl_cx * const f, char const *zFilename,
                                 fsl_fstat const *fst,
                                 bool isInVFile){
  int rc = 0;
  fsl_db * const db = fsl_needs_ckout(f);
  assert(fsl_is_simple_pathname(zFilename, true));
  if( isInVFile ){
    rc = fsl_db_exec(db, "UPDATE vfile SET deleted=0,"
                     " mtime=%"PRIi64
                     " WHERE vid=%"FSL_ID_T_PFMT
6099
6100
6101
6102
6103
6104
6105
6106

6107
6108
6109
6110
6111
6112
6113
6223
6224
6225
6226
6227
6228
6229

6230
6231
6232
6233
6234
6235
6236
6237







-
+







static int fsl_dircrawl_f_add(fsl_dircrawl_state const *);

/**
   Attempts to add file or directory (recursively) cas->absBuf to the
   current repository. isCrawling must be true if this is a
   fsl_dircrawl()-invoked call, else false.
*/
static int co_add_one(CoAddState * cas, bool isCrawling){
static int co_add_one(CoAddState * const cas, bool isCrawling){
  int rc = 0;
  fsl_buffer_reuse(cas->coRelBuf);
  rc = fsl_cx_stat2(cas->f, cas->opt->relativeToCwd,
                    fsl_buffer_cstr(cas->absBuf), &cas->fst,
                    fsl_buffer_reuse(cas->coRelBuf), false)
    /* Reminder: will fail if file is outside of the checkout tree */;
  if(rc) return rc;
6130
6131
6132
6133
6134
6135
6136

6137
6138




6139
6140
6141
6142
6143
6144
6145
6254
6255
6256
6257
6258
6259
6260
6261


6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272







+
-
-
+
+
+
+







        }else if(cas->opt->checkIgnoreGlobs){
          char const * m =
            fsl_cx_glob_matches(cas->f, FSL_GLOBS_IGNORE, zCoRel);
          if(m) skipped = true;
        }
        if(!skipped && cas->opt->callback){
          bool yes = false;
          fsl_ckout_manage_state mst = fsl_ckout_manage_state_empty;
          rc = cas->opt->callback( zCoRel, &yes,
                                   cas->opt->callbackState );
          mst.opt = cas->opt;
          mst.filename = zCoRel;
          mst.f = cas->f;
          rc = cas->opt->callback( &mst, &yes );
          if(rc) goto end;
          else if(!yes) skipped = true;
        }
      }
      if(skipped){
        ++cas->opt->counts.skipped;
      }else{
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
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316






6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368




6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380







+
+
+

+
+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
















+
+
-
-
-
-
+
+
+
+
+







                          "fsl_fstat_type_e #%d", cas->fst.type);
      break;
  }
  end:
  return rc;
}

/**
   fsl_dircrawl_f() impl for fsl_ckout_manage().
*/
static int fsl_dircrawl_f_add(fsl_dircrawl_state const *dst){
  switch(dst->entryType){
    case FSL_FSTAT_TYPE_DIR:
  if(FSL_FSTAT_TYPE_FILE!=dst->entryType) return 0;
  CoAddState * cas = (CoAddState*)dst->callbackState;
  int rc = fsl_buffer_appendf(fsl_buffer_reuse(cas->absBuf),
                              "%s/%s", dst->absoluteDir, dst->entryName);
  if(!rc) rc = co_add_one(cas, true);
  return rc;
    case FSL_FSTAT_TYPE_FILE:{
      CoAddState * const cas = (CoAddState*)dst->callbackState;
      int const rc = fsl_buffer_appendf(fsl_buffer_reuse(cas->absBuf),
                                        "%s/%s", dst->absoluteDir, dst->entryName);
      if(rc) return rc;
      switch(dst->entryType){
        case FSL_FSTAT_TYPE_DIR:
          return fsl_is_top_of_ckout(fsl_buffer_cstr(cas->absBuf))
            /* Never recurse into nested checkouts */
            ? FSL_RC_NOOP : 0;
        case FSL_FSTAT_TYPE_FILE:
          return co_add_one(cas, true);
        default:
          fsl__fatal(FSL_RC_ERROR,"Not possible: caught above.");
          return 0;
      }
    }
    default:
      return 0;
  }
}

/**
   Returns true if the absolute path zAbsName is f->ckout.dir, disregarding
   an optional trailing slash on zAbsName.
*/
static bool fsl__is_ckout_dir(fsl_cx * const f, char const * const zAbsName){
  /* Keeping in mind that f->ckout.dir is always slash-terminated...*/
  assert(f->ckout.dirLen>0);
  return (0==fsl_strncmp(zAbsName, f->ckout.dir, f->ckout.dirLen-1)
          && 0==zAbsName[f->ckout.dirLen-1]
          /* ==> matches except that zAbsName is NUL-terminated where
             ckout.dir has a trailing slash. */)
    || 0==fsl_strcmp(zAbsName, f->ckout.dir);
}

int fsl_ckout_manage( fsl_cx * const f, fsl_ckout_manage_opt * const opt_ ){
  int rc = 0;
  CoAddState cas = CoAddState_empty;
  fsl_ckout_manage_opt opt;
  if(!f) return FSL_RC_MISUSE;
  else if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  assert(f->ckout.rid>=0);
  opt = *opt_
    /*use a copy in case the user manages to modify
      opt_ from a callback. */;
  cas.absBuf = fsl__cx_scratchpad(f);
  cas.coRelBuf = fsl__cx_scratchpad(f);
  rc = fsl_file_canonical_name(opt.filename, cas.absBuf, false);
  if(!rc){
    char const * const zAbs = fsl_buffer_cstr(cas.absBuf);
    if(!fsl_is_top_of_ckout(zAbs) || fsl__is_ckout_dir(f, zAbs)){
    cas.f = f;
    cas.opt = &opt;
    rc = co_add_one(&cas, false);
    opt_->counts = opt.counts;
      cas.f = f;
      cas.opt = &opt;
      rc = co_add_one(&cas, false);
      opt_->counts = opt.counts;
    }
  }
  fsl__cx_scratchpad_yield(f, cas.absBuf);
  fsl__cx_scratchpad_yield(f, cas.coRelBuf);
  return rc;
}

/**
6253
6254
6255
6256
6257
6258
6259








6260
6261
6262
6263
6264
6265
6266
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437







+
+
+
+
+
+
+
+







  fsl_stmt_finalize(&insId);
  return rc;
  dberr:
  assert(rc);
  rc = fsl_cx_uplift_db_error2(f, db, rc);
  goto end;
}

/** Initialized-with-defaults fsl_ckout_unmanage_state structure, intended for
    const-copy initialization. */
#define fsl_ckout_unmanage_state_empty_m {NULL,NULL,NULL}
/** Initialized-with-defaults fsl_ckout_unmanage_state structure, intended for
    non-const copy initialization. */
static const fsl_ckout_unmanage_state fsl_ckout_unmanage_state_empty
= fsl_ckout_unmanage_state_empty_m;

int fsl_ckout_unmanage(fsl_cx * const f, fsl_ckout_unmanage_opt const * opt){
  int rc;
  fsl_db * const db = fsl_needs_ckout(f);
  fsl_buffer * fname = 0;
  fsl_id_t const vid = f->ckout.rid;
  fsl_stmt q = fsl_stmt_empty;
6336
6337
6338
6339
6340
6341
6342



6343
6344
6345






6346
6347
6348
6349
6350
6351
6352
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517


6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530







+
+
+

-
-
+
+
+
+
+
+







                          "/*%s()*/",
                          vid, zNorm, zNorm, vid, __func__);
      if(rc) goto dberr;
    }
  }/*opt->filename*/

  if(q.stmt){
    fsl_ckout_unmanage_state ust = fsl_ckout_unmanage_state_empty;
    ust.opt = opt;
    ust.f = f;
    while(FSL_RC_STEP_ROW==fsl_stmt_step(&q)){
      char const * fn = fsl_stmt_g_text(&q, 0, NULL);
      rc = opt->callback(fn, opt->callbackState);
      rc = fsl_stmt_get_text(&q, 0, &ust.filename, NULL);
      if(rc){
        rc = fsl_cx_uplift_db_error2(f, db, rc);
        goto end;
      }
      rc = opt->callback(&ust);
      if(rc) goto end;
    }
    fsl_stmt_finalize(&q);
  }
  /* Remove rm'd ADDed-but-not-yet-committed entries... */
  rc = fsl_db_exec(db,
                   "DELETE FROM vfile WHERE vid=%" FSL_ID_T_PFMT
6373
6374
6375
6376
6377
6378
6379
6380

6381
6382
6383
6384
6385
6386
6387
6388
6389
6390

6391
6392
6393
6394
6395
6396
6397
6551
6552
6553
6554
6555
6556
6557

6558
6559
6560
6561
6562
6563
6564
6565
6566
6567

6568
6569
6570
6571
6572
6573
6574
6575







-
+









-
+








}

int fsl_ckout_changes_scan(fsl_cx * const f){
  return fsl_vfile_changes_scan(f, -1, 0);
}

int fsl_ckout_install_schema(fsl_cx * const f, bool dropIfExists){
int fsl__ckout_install_schema(fsl_cx * const f, bool dropIfExists){
  char const * tNames[] = {
  "vvar", "vfile", "vmerge", 0
  };
  int rc;
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return f->error.code;
  if(dropIfExists){
    char const * t;
    int i;
    char const * dbName = fsl_db_role_label(FSL_DBROLE_CKOUT);
    char const * dbName = fsl_db_role_name(FSL_DBROLE_CKOUT);
    for(i=0; 0!=(t = tNames[i]); ++i){
      rc = fsl_db_exec(db, "DROP TABLE IF EXISTS %s.%s /*%s()*/",
                       dbName, t, __func__);
      if(rc) break;
    }
    if(!rc){
      rc = fsl_db_exec(db, "DROP TRIGGER IF EXISTS "
6414
6415
6416
6417
6418
6419
6420
6421

6422
6423
6424
6425


6426
6427











6428

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
6592
6593
6594
6595
6596
6597
6598

6599

6600


6601
6602

6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614

6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630



6631
6632
6633
6634
6635
6636
6637
6638
6639

6640
6641
6642
6643
6644
6645
6646
6647







-
+
-

-
-
+
+
-

+
+
+
+
+
+
+
+
+
+
+
-
+















-
-
-









-
+







  return fsl_db_exists(db,
                       "SELECT 1 FROM vfile WHERE chnged "
                       "OR coalesce(origname != pathname, 0) "
                       "/*%s()*/", __func__)
    || fsl_db_exists(db,"SELECT 1 FROM vmerge /*%s()*/", __func__);
}

int fsl__ckout_clear_merge_state( fsl_cx *f ){
int fsl__ckout_clear_merge_state( fsl_cx * const f, bool fullWipe ){
  fsl_db * const d = fsl_needs_ckout(f);
  int rc;
  if(d){
    rc = fsl_db_exec(d,"DELETE FROM vmerge /*%s()*/", __func__);
  if(fullWipe){
    rc = fsl_cx_exec(f,"DELETE FROM vmerge /*%s()*/", __func__);
    rc = fsl_cx_uplift_db_error2(f, d, rc);
  }else{
    rc = fsl_cx_exec_multi(f,
                     "DELETE FROM vmerge WHERE id IN("
                     "SELECT vm.id FROM vmerge vm, vfile vf "
                     "WHERE vm.id=vf.id AND vf.chnged=0"
                     ");"
                     "DELETE FROM vmerge WHERE NOT EXISTS("
                     "SELECT 1 FROM vmerge WHERE id>0"
                     ") AND NOT EXISTS ("
                     "SELECT 1 FROM vfile WHERE chnged>1"
                     ");"
                     "/*%s()*/", __func__ );
    rc = FSL_RC_NOT_A_CKOUT;

  }
  return rc;
}

int fsl_ckout_clear_db(fsl_cx *f){
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return f->error.code;
  return fsl_db_exec_multi(db,
                           "DELETE FROM vfile;"
                           "DELETE FROM vmerge;"
                           "DELETE FROM vvar WHERE name IN"
                           "('checkout','checkout-hash') "
                           "/*%s()*/", __func__);
}

fsl_db * fsl_cx_db_for_role(fsl_cx *, fsl_dbrole_e)
  /* defined in cx.c */;

/**
   Updates f->ckout.dir and dirLen based on the current state of
   f->ckout.db. Returns 0 on success, FSL_RC_OOM on allocation error,
   some other code if canonicalization of the name fails
   (e.g. filesystem error or cwd cannot be resolved).
*/
static int fsl_update_ckout_dir(fsl_cx *f){
  int rc;
  fsl_buffer ckDir = fsl_buffer_empty;
  fsl_db * dbC = fsl_cx_db_for_role(f, FSL_DBROLE_CKOUT);
  fsl_db * dbC = fsl__cx_db_for_role(f, FSL_DBROLE_CKOUT);
  assert(dbC->filename);
  assert(*dbC->filename);
  rc = fsl_file_canonical_name(dbC->filename, &ckDir, false);
  if(rc) return rc;
  char * zCanon = fsl_buffer_take(&ckDir);
  //MARKER(("dbC->filename=%s\n", dbC->filename));
  //MARKER(("zCanon=%s\n", zCanon));
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
6509
6510
6511
6512
6513
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







-
+



-
+







-
-
-
-
-
-
-








+
+
+
+
+
+
+
+
+







    /*MARKER(("Updated ckout.dir: %d %s\n",
      (int)f->ckout.dirLen, f->ckout.dir));*/
  }
  return rc;
}


int fsl_repo_open_ckout(fsl_cx *f, const fsl_repo_open_ckout_opt *opt){
int fsl_repo_open_ckout(fsl_cx * const f, const fsl_repo_open_ckout_opt *opt){
  fsl_db *dbC = 0;
  fsl_buffer *cwd = 0;
  int rc = 0;

  bool didChdir = false;
  if(!opt) return FSL_RC_MISUSE;
  else if(!fsl_needs_repo(f)){
    return f->error.code;
  }else if(fsl_cx_db_ckout(f)){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "A checkout is already attached.");
  }
  if(opt->targetDir && *opt->targetDir){
    if(fsl_chdir(opt->targetDir)){
      return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "Directory not found or inaccessible: %s",
                            opt->targetDir);
    }
  }
  cwd = fsl__cx_scratchpad(f);
  assert(!cwd->used);
  if((rc = fsl_cx_getcwd(f, cwd))){
    assert(!cwd->used);
    fsl__cx_scratchpad_yield(f, cwd);
    return fsl_cx_err_set(f, rc, "Error %d [%s]: unable to "
                          "determine current directory.",
                          rc, fsl_rc_cstr(rc));
  }
  if(opt->targetDir && *opt->targetDir){
    if(fsl_chdir(opt->targetDir)){
      fsl__cx_scratchpad_yield(f, cwd);
      return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "Directory not found or inaccessible: %s",
                            opt->targetDir);
    }
    didChdir = true;
  }
  /**
     AS OF HERE: do not use 'return'. Use goto end so that we can
     chdir() back to our original cwd!
  */
  if(!fsl_dir_is_empty("."/*we've already chdir'd if
                            we were going to*/)) {
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551

6552
6553
6554

6555
6556
6557
6558
6559
6560

6561
6562
6563
6564
6565
6566
6567
6568
6569

6570


6571
6572
6573
6574
6575
6576

6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6728
6729
6730
6731
6732
6733
6734



6735
6736
6737

6738



6739
6740

6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751

6752
6753
6754
6755
6756
6757
6758

6759
6760
6761
6762
6763
6764
6765

6766
6767
6768
6769
6770
6771
6772







-
-
-
+


-
+
-
-
-


-
+









+
-
+
+





-
+






-







  /**
     Create and attach ckout db...
  */
  assert(!fsl_cx_db_ckout(f));
  const char * dbName = opt->ckoutDbFile
    ? opt->ckoutDbFile : fsl_preferred_ckout_db_name();
  fsl_cx_err_reset(f);
  int fsl_cx_attach_role(fsl_cx * const , const char *, fsl_dbrole_e)
    /* defined in cx.c */;
  rc = fsl_cx_attach_role(f, dbName, FSL_DBROLE_CKOUT);
  rc = fsl__cx_attach_role(f, dbName, FSL_DBROLE_CKOUT, true);
  if(rc) goto end;
  fsl_db * const theDbC = fsl_cx_db_ckout(f);
  dbC = fsl_cx_db_for_role(f, FSL_DBROLE_CKOUT);
  dbC = fsl__cx_db_for_role(f, FSL_DBROLE_CKOUT);
  assert(theDbC != dbC && "Not anymore.");
  assert(theDbC == f->dbMain);
  assert(!f->error.code);
  assert(dbC->name);
  assert(dbC->filename);
  rc = fsl_ckout_install_schema(f, opt->dbOverwritePolicy);
  rc = fsl__ckout_install_schema(f, opt->dbOverwritePolicy);
  if(!rc){
    rc = fsl_db_exec(theDbC,"INSERT OR IGNORE INTO "
                     "%s.vvar (name,value) "
                     "VALUES('checkout',0),"
                     "('checkout-hash',null)",
                     dbC->name);
  }
  if(rc) rc = fsl_cx_uplift_db_error(f, theDbC);
  end:
  if(didChdir){
  if(opt->targetDir && *opt->targetDir && cwd->used){
    assert(opt->targetDir && *opt->targetDir);
    assert(cwd->used /* is this true in the root dir? */);
    fsl_chdir(fsl_buffer_cstr(cwd))
      /* Ignoring error because we have no recovery strategy! */;
  }
  fsl__cx_scratchpad_yield(f, cwd);
  if(!rc){
    fsl_db * const dbR = fsl_cx_db_for_role(f, FSL_DBROLE_REPO);
    fsl_db * const dbR = fsl__cx_db_for_role(f, FSL_DBROLE_REPO);
    assert(dbR);
    assert(dbR->filename && *dbR->filename);
    rc = fsl_config_set_text(f, FSL_CONFDB_CKOUT, "repository",
                             dbR->filename);
  }
  if(!rc) rc = fsl_update_ckout_dir(f);
  fsl_buffer_clear(cwd);
  return rc;
}

int fsl__is_locally_modified(fsl_cx * const f,
                            const char * zFilename,
                            fsl_size_t origSize,
                            const char * zOrigHash,
6814
6815
6816
6817
6818
6819
6820
6821

6822
6823
6824
6825
6826
6827
6828
6996
6997
6998
6999
7000
7001
7002

7003
7004
7005
7006
7007
7008
7009
7010







-
+







  RepoExtractCkup * const rec = (RepoExtractCkup *)xs->callbackState;
  const char * zFilename;
  fsl_ckup_state coState = fsl_ckup_state_empty;
  fsl_time_t mtime = 0;
  fsl_fstat fst = fsl_fstat_empty;
  fsl_ckup_localmod_e modType = FSL_RECO_MOD_UNKNOWN;
  bool loadedContent = false;
  fsl_buffer * content = &f->fileContent;
  fsl_buffer * const content = &f->cache.fileContent;
  assert(0==content->used
         && "Internal Misuse of fsl_cx::fileContent buffer.");
  //assert(xs->content);
  assert(xs->fCard->uuid && "We shouldn't be getting deletions "
         "via delta manifests.");
  rc = fsl_buffer_append(rec->tgtDir, xs->fCard->name, -1);
  if(rc) return rc;
7161
7162
7163
7164
7165
7166
7167
7168

7169
7170
7171
7172
7173
7174
7175
7343
7344
7345
7346
7347
7348
7349

7350
7351
7352
7353
7354
7355
7356
7357







-
+







    if(rc) goto end;
    while(FSL_RC_STEP_ROW==(rc = fsl_stmt_step(&q))){
      fsl_size_t nFn = 0;
      char const * fn = fsl_stmt_g_text(&q, 0, &nFn);
      absPath->used = ckdirLen;
      rc = fsl_buffer_append(absPath, fn, nFn);
      if(rc) break;
      fsl_ckout_rm_empty_dirs(f, absPath)
      fsl__ckout_rm_empty_dirs(f, absPath)
        /* To see this in action, use (f-co tip) to check out the tip of
           a repo, then use (f-co rid:1) to back up to the initial empty
           checkin. It "should" leave you with a directory devoid of
           anything but .fslckout and any non-SCM'd content.
        */;
    }
    if(FSL_RC_STEP_DONE==rc) rc = 0;
7277
7278
7279
7280
7281
7282
7283
7284

7285
7286
7287
7288
7289
7290
7291
7459
7460
7461
7462
7463
7464
7465

7466
7467
7468
7469
7470
7471
7472
7473







-
+







    if(rc) goto end;
  }
  rc = fsl_ckout_manifest_write(f, -1, -1, -1, NULL);

  end:
  if(!rc){
    rc = fsl_vfile_unload_except(f, cOpt->checkinRid);
    if(!rc) rc = fsl__ckout_clear_merge_state(f);
    if(!rc) rc = fsl__ckout_clear_merge_state(f, true);
  }
  /*
    TODO: if "repo-cksum" config db setting is set, confirm R-card of
    cOpt->checkinRid against on-disk contents.
  */
  if(cOpt->confirmer.callback){
    fsl_cx_confirmer(f, &oldConfirm, NULL);
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
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







-
-
+











-
+
+







  }
  /*
  ** The record.fn field is used to match files against each other.  The
  ** FV table contains one row for each each unique filename in
  ** in the current checkout, the pivot, and the version being merged.
  */
  rc = fsl_db_exec_multi(dbC,
    "DROP TABLE IF EXISTS fv;"
    "CREATE TEMP TABLE fv("
    "CREATE TEMP TABLE IF NOT EXISTS fv("
    "  fn TEXT %s PRIMARY KEY,"   /* The filename relative to root */
    "  idv INTEGER,"              /* VFILE entry for current version */
    "  idt INTEGER,"              /* VFILE entry for target version */
    "  chnged BOOLEAN,"           /* True if current version has been edited */
    "  islinkv BOOLEAN,"          /* True if current file is a link */
    "  islinkt BOOLEAN,"          /* True if target file is a link */
    "  ridv INTEGER,"             /* Record ID for current version */
    "  ridt INTEGER,"             /* Record ID for target */
    "  isexe BOOLEAN,"            /* Does target have execute permission? */
    "  deleted BOOLEAN DEFAULT 0,"/* File marked by "rm" to become unmanaged */
    "  fnt TEXT %s"               /* Filename of same file on target version */
    ") /*%s()*/;",
    ") /*%s()*/; "
    "DELETE FROM fv;",
    collation, collation, __func__ );
  if(rc) goto dberr;
  /* Add files found in the current version
  */
  rc = fsl_db_exec_multi(dbC,
    "INSERT OR IGNORE INTO fv("
            "fn,fnt,idv,idt,ridv,"
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
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







-
-
-
+
+
+








-
+

-
+








-
-
+
+







       || 0==fsl_strncmp(z,"true",4)){
      z = "ru"/*historical default*/;
    }else if(!fsl_str_bool(z)){
      z = "";
    }
    for(;*z;++z){
      switch(*z){
        case 'r': *m |= 0x001; break;
        case 'u': *m |= 0x010; break;
        case 't': *m |= 0x100; break;
        case 'r': *m |= FSL_MANIFEST_MAIN; break;
        case 'u': *m |= FSL_MANIFEST_UUID; break;
        case 't': *m |= FSL_MANIFEST_TAGS; break;
        default: break;
      }
    }
    fsl_free(str);
  }
  f->cache.manifestSetting = (short)*m;
}

int fsl_ckout_manifest_write(fsl_cx *f, int manifest, int manifestUuid,
int fsl_ckout_manifest_write(fsl_cx * const f, int manifest, int manifestUuid,
                             int manifestTags,
                             int * wrote){
                             int * const wrote){
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return FSL_RC_NOT_A_CKOUT;
  else if(!f->ckout.rid){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Checkout RID is 0, so it has no manifest.");
  }
  int W = 0;
  int rc = 0;
  fsl_buffer * b = fsl__cx_scratchpad(f);
  fsl_buffer * content = &f->fileContent;
  fsl_buffer * const b = fsl__cx_scratchpad(f);
  fsl_buffer * const content = &f->cache.fileContent;
  char * str = 0;
  fsl_time_t const mtime = f->ckout.mtime>0
    ? fsl_julian_to_unix(f->ckout.mtime)
    : 0;
  fsl_buffer_reuse(content);
  if(manifest<0 || manifestUuid<0 || manifestTags<0){
    int setting = 0;
8192
8193
8194
8195
8196
8197
8198
8199

8200
8201
8202
8203
8204
8205
8206
8207
8208

8209
8210
8211
8212
8213
8214
8215
8374
8375
8376
8377
8378
8379
8380

8381
8382
8383
8384
8385
8386
8387
8388
8389

8390
8391
8392
8393
8394
8395
8396
8397







-
+








-
+







                        (int)errLen, zFilename);
  }
  end:
  fsl__cx_scratchpad_yield(f, fn);
  return rc;
}

bool fsl_is_rooted_in_ckout(fsl_cx *f, char const *zAbsPath){
bool fsl_is_rooted_in_ckout(fsl_cx * const f, char const * const zAbsPath){
  return f->ckout.dir
    ? 0==fsl_strncmp(zAbsPath, f->ckout.dir, f->ckout.dirLen)
    /* ^^^ fossil(1) uses stricmp() there, but that's a bug. However,
       NOT using stricmp() on case-insensitive filesystems is arguably
       also a bug. */
    : false;
}

int fsl_is_rooted_in_ckout2(fsl_cx *f, char const *zAbsPath){
int fsl_is_rooted_in_ckout2(fsl_cx * const f, char const * const zAbsPath){
  int rc = 0;
  if(!fsl_is_rooted_in_ckout(f, zAbsPath)){
    rc = fsl_cx_err_set(f, FSL_RC_RANGE, "Path is not rooted "
                        "in the current checkout: %s",
                        zAbsPath);
  }
  return rc;
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
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







-
+
+



-
+


-
-
-
-
-
+
+
+
+
-

+
-
-
+
+
-
+

-
-
-






-
+



-
+




-
-
+




-
-
+

-



-
-
-







}

/**
   Queues the directory part of the given filename into temp table
   fx_revert_rmdir for an eventual rmdir() attempt on it in
   fsl_revert_rmdir_fini().
*/
static int fsl_revert_rmdir_queue(fsl_cx * f, fsl_db * db, fsl_stmt * st,
static int fsl_revert_rmdir_queue(fsl_cx * const f, fsl_db * const db,
                                  fsl_stmt * const st,
                                  char const * zFilename){
  int rc = 0;
  if( !st->stmt ){
    rc = fsl_db_exec(db, "CREATE TEMP TABLE IF NOT EXISTS "
    rc = fsl_cx_exec(f, "CREATE TEMP TABLE IF NOT EXISTS "
                     "fx_revert_rmdir(n TEXT PRIMARY KEY) "
                     "WITHOUT ROWID /* %s() */", __func__);
    if(rc) goto dberr;
    rc = fsl_db_prepare(db, st, "INSERT OR IGNORE INTO "
                        "fx_revert_rmdir(n) "
                        "VALUES(fsl_dirpart(?,0)) /* %s() */",
                        __func__);
    if(0==rc) rc = fsl_cx_prepare(f, st, "INSERT OR IGNORE INTO "
                                  "fx_revert_rmdir(n) "
                                  "VALUES(fsl_dirpart(?,0)) /* %s() */",
                                  __func__);
    if(rc) goto dberr;
  }
  if(0==rc){
  rc = fsl_stmt_bind_step(st, "s", zFilename);
  if(rc) goto dberr;
    rc = fsl_stmt_bind_step(st, "s", zFilename);
    if(rc) rc = fsl_cx_uplift_db_error2(f, db, rc);
  end:
  }
  return rc;
  dberr:
  rc = fsl_cx_uplift_db_error2(f, db, rc);
  goto end;
}

/**
   Attempts to rmdir all dirs queued by fsl_revert_rmdir_queue(). Silently
   ignores rmdir failure but will return non-0 for db errors.
*/
static int fsl_revert_rmdir_fini(fsl_cx * f, fsl_db * db){
static int fsl_revert_rmdir_fini(fsl_cx * const f){
  int rc;
  fsl_stmt st = fsl_stmt_empty;
  fsl_buffer * const b = fsl__cx_scratchpad(f);
  rc = fsl_db_prepare(db, &st,
  rc = fsl_cx_prepare(f, &st,
                      "SELECT fsl_ckout_dir()||n "
                      "FROM fx_revert_rmdir "
                      "ORDER BY length(n) DESC /* %s() */",
                      __func__);
  if(rc) goto dberr;
  while(FSL_RC_STEP_ROW == fsl_stmt_step(&st)){
  while(0==rc && FSL_RC_STEP_ROW == fsl_stmt_step(&st)){
    fsl_size_t nDir = 0;
    char const * zDir = fsl_stmt_g_text(&st, 0, &nDir);
    fsl_buffer_reuse(b);
    rc = fsl_buffer_append(b, zDir, (fsl_int_t)nDir);
    if(rc) break;
    fsl_ckout_rm_empty_dirs(f, b);
    if(0==rc) fsl__ckout_rm_empty_dirs(f, b);
  }
  end:
  fsl__cx_scratchpad_yield(f, b);
  fsl_stmt_finalize(&st);
  return rc;
  dberr:
  rc = fsl_cx_uplift_db_error2(f, db, rc);
  goto end;
}

int fsl_ckout_revert( fsl_cx * const f,
                      fsl_ckout_revert_opt const * opt ){
  /**
     Reminder to whoever works on this code: the initial
     implementation was done almost entirely without the benefit of
8333
8334
8335
8336
8337
8338
8339
8340
8341


8342
8343
8344
8345
8346
8347
8348
8506
8507
8508
8509
8510
8511
8512


8513
8514
8515
8516
8517
8518
8519
8520
8521







-
-
+
+







    if(fname->used) fsl_buffer_strip_slashes(fname);
    if(1==fname->used && '.'==*zNorm){
      /* Special case: handle "." from ckout root intuitively */
      fsl_buffer_reuse(fname);
      assert(0==*zNorm);
    }
  }
  rc = fsl_db_transaction_begin(db);
  if(rc) goto dberr;
  rc = fsl_cx_transaction_begin(f);
  if(rc) goto end;
  inTrans = true;
  if(opt->scanForChanges){
    rc = fsl_vfile_changes_scan(f, 0, 0);
    if(rc) goto end;
  }
  sql = fsl__cx_scratchpad(f);
  rc = fsl_buffer_appendf(sql, 
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
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







-
+


-
-
-
-
+
-










-
+

-
+







                           " OR deleted<>0"
                           " OR rid=0"
                           " OR coalesce(origname,pathname)"
                           "    <>pathname"
                           ")", -1);
  }
  assert(!rc);
  rc = fsl_db_prepare(db, &q, "%b /* %s() */", sql, __func__);
  rc = fsl_cx_prepare(f, &q, "%b /* %s() */", sql, __func__);
  fsl__cx_scratchpad_yield(f, sql);
  sql = 0;
  if(rc) goto dberr;
  if((!zNorm || !*zNorm) && !opt->vfileIds){
    rc = fsl__ckout_clear_merge_state(f);
    if(rc) goto end;
  if(rc) goto end;
  }
  while((FSL_RC_STEP_ROW==fsl_stmt_step(&q))){
    fsl_id_t const id = fsl_stmt_g_id(&q, 0);
    fsl_id_t const rid = fsl_stmt_g_id(&q, 1);
    int32_t const deleted = fsl_stmt_g_int32(&q, 2);
    char const * const zName = fsl_stmt_g_text(&q, 3, NULL);
    char const * const zNameOrig = fsl_stmt_g_text(&q, 4, NULL);
    bool const renamed =
      zNameOrig ? !!fsl_strcmp(zName, zNameOrig) : false;
    fsl_ckout_revert_e changeType = FSL_REVERT_NONE;
    if(!rid){ // Added but not yet checked in.
      rc = fsl_db_exec(db, "DELETE FROM vfile WHERE id=%" FSL_ID_T_PFMT,
      rc = fsl_cx_exec(f, "DELETE FROM vfile WHERE id=%" FSL_ID_T_PFMT,
                       id);
      if(rc) goto dberr;
      if(rc) goto end;
      changeType = FSL_REVERT_UNMANAGE;
    }else{
      int wasWritten = 0;
      if(renamed){
        if((rc=fsl_mkdir_for_file(zNameOrig, true))){
          rc = fsl_cx_err_set(f, rc, "mkdir() failed for file: %s",
                              zNameOrig);
8422
8423
8424
8425
8426
8427
8428
8429

8430
8431
8432
8433
8434

8435
8436
8437
8438
8439
8440
8441
8591
8592
8593
8594
8595
8596
8597

8598
8599
8600
8601
8602

8603
8604
8605
8606
8607
8608
8609
8610







-
+




-
+







          }
        }
        /* Ignore any errors: this operation is an optimization,
           not a requirement. Worse case, the entry with the old
           name is left in the filesystem. */
      }
      if(!vfUpdate.stmt){
        rc = fsl_db_prepare(db, &vfUpdate,
        rc = fsl_cx_prepare(f, &vfUpdate,
                            "UPDATE vfile SET chnged=0, deleted=0, "
                            "pathname=coalesce(origname,pathname), "
                            "origname=NULL "
                            "WHERE id=?1 /*%s()*/", __func__);
        if(rc) goto dberr;
        if(rc) goto end;
      }
      rc = fsl_stmt_bind_step(&vfUpdate, "R", id)
        /* Has to be done before fsl__vfile_to_ckout() because that
           function writes to vfile.pathname. */;
      if(rc) goto dberr;
      rc = fsl__vfile_to_ckout(f, id, &wasWritten);
      if(rc) break;
8461
8462
8463
8464
8465
8466
8467
8468

8469
8470
8471
8472
8473
8474
8475
8476



8477
8478
8479
8480
8481
8482
8483
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







-
+








+
+
+







  end:
  if(fname) fsl__cx_scratchpad_yield(f, fname);
  if(sql) fsl__cx_scratchpad_yield(f, sql);
  fsl_stmt_finalize(&q);
  fsl_stmt_finalize(&vfUpdate);
  if(qRmdir.stmt){
    fsl_stmt_finalize(&qRmdir);
    if(!rc) rc = fsl_revert_rmdir_fini(f, db);
    if(!rc) rc = fsl_revert_rmdir_fini(f);
    fsl_db_exec(db, "DROP TABLE IF EXISTS fx_revert_rmdir /* %s() */",
                __func__);
  }
  if(opt->vfileIds){
    fsl_db_exec_multi(db, "DROP TABLE IF EXISTS fx_revert_id "
                      "/* %s() */", __func__)
      /* Ignoring result code */;
  }
  if(0==rc){
    rc = fsl__ckout_clear_merge_state(f, false);
  }
  if(inTrans){
    int const rc2 = fsl_db_transaction_end(db, !!rc);
    if(!rc) rc = rc2;
  }
  return rc;
  dberr:
  assert(rc);
8546
8547
8548
8549
8550
8551
8552
8553

8554
8555
8556
8557
8558
8559
8560
8718
8719
8720
8721
8722
8723
8724

8725
8726
8727
8728
8729
8730
8731
8732







-
+







                           fsl_time_t * repoMtime,
                           fsl_time_t * localMtime){

  int rc = 0;
  fsl_id_t fid = 0;
  fsl_fstat fst = fsl_fstat_empty;
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  if(0<=vid){
  if(0>=vid){
    fsl_ckout_version_info(f, &vid, NULL);
  }
  fid = fsl_repo_filename_fnid(f, fc->name);
  if(fid<=0){
    rc = fsl_cx_err_get(f, NULL, NULL);
    return rc ? rc : fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                                    "Could not resolve filename: %s",
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
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








+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
+
+












-

+
+
+
+
+
+
+
+







  }
  if(repoMtime){
    rc = fsl_mtime_of_manifest_file(f, vid, fid, repoMtime);
  }
  return rc;
}


char const ** fsl_ckout_dbnames(void){
  static char const *dbNames[] = {".fslckout", "_FOSSIL_", NULL};
  return dbNames;
}

char const * fsl_is_top_of_ckout(char const *zDirName){
  // counterpart of fossil(1)'s vfile_top_of_checkout()
  enum {BufLen = 2048};
  char nameBuf[BufLen];
  char * z = &nameBuf[0];
  fsl_size_t sz = fsl_strlcpy(z, zDirName, BufLen);
  if(sz>=(fsl_size_t)BufLen - 11/*_FOSSIL_/.fslckout suffix*/) return NULL;
  char const **dbNames = fsl_ckout_dbnames();
  char const * dbName;
  z[sz++] = '/';
  z[sz] = 0;
  for( int i = 0; NULL!=(dbName=dbNames[i]); ++i){
    fsl_strlcpy(z + sz , dbName, (fsl_size_t)BufLen - sz);
    if(fsl_file_size(z)>=1024) return dbName;
  }
  return NULL;
}

#undef MARKER
/* end of file checkout.c */
/* start of file cli.c */
/* end of file ./src/checkout.c */
/* start of file ./src/cli.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

#include <string.h> /* for strchr() */
#if !defined(ORG_FOSSIL_SCM_FSL_CORE_H_INCLUDED)
/* When not in the amalgamation build, force assert() to always work... */
#  if defined(NDEBUG)
#    undef NDEBUG
#    define DEBUG 1
#  endif
#endif
#include <assert.h> /* for the benefit of test apps */

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)
8669
8670
8671
8672
8673
8674
8675
8676

8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8871
8872
8873
8874
8875
8876
8877

8878




8879
8880
8881
8882
8883
8884
8885







-
+
-
-
-
-







  assert(f);
  if(fcli.transient.repoDbArg){
    FCLI_V3(("Trying to open repo db file [%s]...\n", fcli.transient.repoDbArg));
    rc = fsl_repo_open( f, fcli.transient.repoDbArg );
  }
  else if(fcli.clientFlags.checkoutDir){
    fsl_buffer dir = fsl_buffer_empty;
    char const * dirName;
    char const * dirName = fcli.clientFlags.checkoutDir;
    rc = fsl_file_canonical_name(fcli.clientFlags.checkoutDir,
                                 &dir, 0);
    assert(!rc);
    dirName = (char const *)fsl_buffer_cstr(&dir);
    FCLI_V3(("Trying to open checkout from [%s]...\n",
             dirName));
    rc = fsl_ckout_open_dir(f, dirName, true);
    FCLI_V3(("checkout open rc=%s\n", fsl_rc_cstr(rc)));

    /* if(FSL_RC_NOT_FOUND==rc) rc = FSL_RC_NOT_A_CKOUT; */
    if(rc){
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
8939
8940
8941
8942
8943
8944
8945

8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962

8963
8964
8965
8966
8967
8968
8969
8970







-
+
















-
+







static struct {
  fsl_list list;
}  FCliFree = {
fsl_list_empty_m
};

static void fcli_shutdown(void){
  fsl_cx * f = fcli.f;
  fsl_cx * const f = fcli.f;
  int rc = 0;
 
  fsl_error_clear(&fcli.err);
  fsl_free(fcli.argv)/*contents are in the FCliFree list*/;

  if(f){
    while(fsl_cx_transaction_level(f)){
      MARKER(("WARNING: open db transaction at shutdown-time. "
              "Rolling back.\n"));
      fsl_cx_transaction_end(f, true);
    }
    if(1 &&
       fsl_cx_db_ckout(f)){
      /* For testing/demo only: this is implicit
         when we call fsl_cx_finalize().
      */
      rc = fsl_ckout_close(f);
      rc = fsl_close_scm_dbs(f);
      FCLI_V3(("Closed checkout/repo db(s). rc=%s\n", fsl_rc_cstr(rc)));
      //assert(0==rc);
    }
  }
  fsl_list_clear(&FCliFree.list, fsl_list_v_fsl_free, 0);
  fsl_list_reserve(&FCliFree.list, 0);
  if(f){
8892
8893
8894
8895
8896
8897
8898
8899

8900
8901
8902
8903
8904
8905
8906
8907
8908



8909
8910
8911
8912
8913
8914
8915
9090
9091
9092
9093
9094
9095
9096

9097
9098
9099
9100
9101
9102
9103



9104
9105
9106
9107
9108
9109
9110
9111
9112
9113







-
+






-
-
-
+
+
+







    if(fcli.appHelp && fcli.appHelp->callback){
      fcli.appHelp->callback();
      f_out("\n");
    }
  }
  if(showGlobal){
    if(!showApp){
      f_out("Invoke --help three times to list "
      f_out("Invoke --help three times (or --help -V -V) to list "
            "both the framework- and app-level options.\n");
    }else{
      f_out("Invoke --help once to list only the "
            "app-level flags.\n");
    }
  }else{
    f_out("Invoke --help twice to list the framework-level "
          "options. Use --help three times to list both "
          "framework- and app-level options.\n");
    f_out("Invoke --help twice (or --help -V) to list the "
          "framework-level options. Use --help three times "
          "to list both framework- and app-level options.\n");
  }
  f_out("\nFlags which require values may be passed as "
        "--flag=value or --flag value.\n\n");
}

int fcli_process_flags( fcli_cliflag const * defs ) {
  fcli_cliflag const * f;
9366
9367
9368
9369
9370
9371
9372
9373

9374
9375

9376
9377
9378
9379
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
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







-
+
-
-
+
-
-
-
-











+
+
+
-
+
+
+
+
+
+
+
+
+
+














-
-
+
+



-
-
-
-
-
-
+
+
-













-
+







      fsl_cx_user_set(f, u);
      fsl_free(u);
    }
  }
  return rc;
}

static int fcli_setup2(int argc, char const * const * argv,
static int check_help_invoked(void){
                       const fcli_cliflag * flags){
  int rc;
  int rc = 0;
  FCliHelpState.flags = flags;
  rc = fcli_setup_common1(false, argc, argv);
  if(rc) return rc;
  assert(!fcli__error->code);
  if(fcli.transient.helpRequested){
    /* Do this last so that we can get the default user name and such
       for display in the help text. */
    fcli_help();
    rc = FCLI_RC_HELP;
  }else if(fcli.transient.versionRequested){
    f_out("libfossil version: %s\nCheckin: %s\nCheckin timestamp: %s\n",
          fsl_library_version(),
          FSL_LIB_VERSION_HASH,
          FSL_LIB_VERSION_TIMESTAMP);
    rc = FCLI_RC_HELP;
  }
  return rc;
}
  }else{

static int fcli_setup2(int argc, char const * const * argv,
                       const fcli_cliflag * flags){
  int rc;
  FCliHelpState.flags = flags;
  rc = fcli_setup_common1(false, argc, argv);
  if(rc) return rc;
  assert(!fcli__error->code);
  rc = check_help_invoked();
  if(!rc){
    rc = fcli_process_flags(flags);
    if(rc) assert(fcli__error->msg.used);
    if(!rc){
      rc = fcli_setup_common2();
    }
  }
  return rc;
}

int fcli_setup_v2(int argc, char const * const * argv,
                  fcli_cliflag const * const cliFlags,
                  fcli_help_info const * const helpInfo ){
  if(NULL!=cliFlags) fcli.cliFlags = cliFlags;
  if(NULL!=helpInfo) fcli.appHelp = helpInfo;
  if(fcli.cliFlags){
    return fcli_setup2(argc, argv, fcli.cliFlags);
  if(cliFlags || fcli.cliFlags){
    return fcli_setup2(argc, argv, cliFlags ? cliFlags : fcli.cliFlags);
  }
  int rc = fcli_setup_common1(true, argc, argv);
  if(!rc){
    //f_out("fcli.transient.helpRequested=%d\n",fcli.transient.helpRequested);
    if(fcli.transient.helpRequested){
      /* Do this last so that we can get the default user name and such
         for display in the help text. */
      fcli_help();
      rc = FCLI_RC_HELP;
    rc = check_help_invoked();
    if(!rc){
    }else{
      if( fcli_flag2(NULL, "no-checkout", NULL) ){
        fcli.clientFlags.checkoutDir = NULL;
      }
      fcli_flag2(NULL,"user", &fcli.transient.userArg);
      fcli.config.traceSql =  fcli_flag2(NULL,"trace-sql", NULL);
      fcli_flag2("R", "repo", &fcli.transient.repoDbArg);
      rc = fcli_setup_common2();
    }
  }
  return rc;
}

int fcli_setup(int argc, char const * const * argv ){
  return fcli_setup_v2(argc, argv, NULL, NULL);
  return fcli_setup_v2(argc, argv, fcli.cliFlags, fcli.appHelp);
}

int fcli_err_report2(bool clear, char const * file, int line){
  int errRc = 0;
  char const * msg = NULL;
  errRc = fsl_error_get( fcli__error, &msg, NULL );
  if(!errRc && fcli.f && fcli.f->interrupted){
9640
9641
9642
9643
9644
9645
9646
9647

9648
9649
9650

9651
9652
9653
9654
9655
9656
9657
9840
9841
9842
9843
9844
9845
9846

9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858







-
+



+







  f_out("  (aliases: ");
  while ( *alias!=0 ){
    f_out("%s%s", alias, *(strchr(alias, 0) + 1) ? ", " : ")\n");
    alias = strchr(alias, 0) + 1;
  }
}

void fcli_fax(void * mem){
void * fcli_fax(void * mem){
  if(mem){
    fsl_list_append( &FCliFree.list, mem );
  }
  return mem;
}

int fcli_ckout_show_info(bool useUtc){
  fsl_cx * const f = fcli_cx();
  int rc = 0;
  fsl_stmt st = fsl_stmt_empty;
  fsl_db * const dbR = fsl_cx_db_repo(f);
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
9870
9871
9872
9873
9874
9875
9876

9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892

9893
9894
9895
9896
9897

9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909

9910
9911
9912
9913
9914
9915

9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
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
9972
9973
9974
9975
9976
9977
9978




9979
9980
9981
9982
9983
9984
9985







-
+















-
+




-












-
+





-
+










+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


-
+





-
+



















-
-
-
-







  assert((uuid && (rid>0)) || (!uuid && (0==rid)));

  f_out("%*s %s\n", lblWidth, "repository-db:",
        fsl_cx_db_file_repo(f, NULL));
  f_out("%*s %s\n", lblWidth, "checkout-root:",
        fsl_cx_ckout_dir_name(f, NULL));

  rc = fsl_db_prepare(dbR, &st, "SELECT "
  rc = fsl_cx_prepare(f, &st, "SELECT "
                      /*0*/"datetime(event.mtime%s) AS timestampString, "
                      /*1*/"coalesce(euser, user) AS user, "
                      /*2*/"(SELECT group_concat(substr(tagname,5), ', ') FROM tag, tagxref "
                      "WHERE tagname GLOB 'sym-*' AND tag.tagid=tagxref.tagid "
                      "AND tagxref.rid=blob.rid AND tagxref.tagtype>0) as tags, "
                      /*3*/"coalesce(ecomment, comment) AS comment, "
                      /*4*/"uuid AS uuid "
                      "FROM event JOIN blob "
                      "WHERE "
                      "event.type='ci' "
                      "AND blob.rid=%"FSL_ID_T_PFMT" "
                      "AND blob.rid=event.objid "
                      "ORDER BY event.mtime DESC",
                      useUtc ? "" : ", 'localtime'",
                      rid);
  if(rc) goto dberr;
  if(rc) goto end;
  if( FSL_RC_STEP_ROW != fsl_stmt_step(&st)){
    /* fcli_err_set(FSL_RC_ERROR, "Event data for checkout not found."); */
    f_out("\nNo 'event' data found. This is only normal for an empty repo.\n");
    goto end;

  }

  f_out("%*s %s %s %s (RID %"FSL_ID_T_PFMT")\n",
        lblWidth, "checkout-version:",
        fsl_stmt_g_text(&st, 4, NULL),
        fsl_stmt_g_text(&st, 0, NULL),
        useUtc ? "UTC" : "local",
        rid );

  {
    /* list parent(s) */
    fsl_stmt stP = fsl_stmt_empty;
    rc = fsl_db_prepare(dbR, &stP, "SELECT "
    rc = fsl_cx_prepare(f, &stP, "SELECT "
                        "uuid, pid, isprim "
                        "FROM plink JOIN blob ON pid=rid "
                        "WHERE cid=%"FSL_ID_T_PFMT" "
                        "ORDER BY isprim DESC, mtime DESC /*sort*/",
                        rid);
    if(rc) goto dberr;
    if(rc) goto end;
    while( FSL_RC_STEP_ROW == fsl_stmt_step(&stP) ){
      char const * zLabel = fsl_stmt_g_int32(&stP,2)
        ? "parent:" : "merged-from:";
      f_out("%*s %s\n", lblWidth, zLabel,
            fsl_stmt_g_text(&stP, 0, NULL));
      
    }
    fsl_stmt_finalize(&stP);
  }
  {
    /* list merge parent(s) */
    fsl_stmt stP = fsl_stmt_empty;
    rc = fsl_cx_prepare(f, &stP, "SELECT "
                        "mhash, id FROm vmerge WHERE id<=0");
    if(rc) goto end;
    while( FSL_RC_STEP_ROW == fsl_stmt_step(&stP) ){
      char const * zClass;
      int32_t const id = fsl_stmt_g_int32(&stP,1);
      switch(id){
        case FSL_MERGE_TYPE_INTEGRATE: zClass = "integrate-merge:"; break;
        case FSL_MERGE_TYPE_BACKOUT: zClass = "backout-merge:"; break;
        case FSL_MERGE_TYPE_CHERRYPICK: zClass = "cherrypick-merge:"; break;
        case FSL_MERGE_TYPE_NORMAL: zClass = "merged-with:"; break;
        default:
          fsl__fatal(FSL_RC_RANGE,
                     "Unexpected value %"PRIi32" in vmerge.id",id);
          break;
      }
      f_out("%*s %s\n", lblWidth, zClass,
            fsl_stmt_g_text(&stP, 0, NULL));
    }
    fsl_stmt_finalize(&stP);
  }
  {
    /* list children */
    fsl_stmt stC = fsl_stmt_empty;
    rc = fsl_db_prepare(dbR, &stC, "SELECT "
    rc = fsl_cx_prepare(f, &stC, "SELECT "
                        "uuid, cid, isprim "
                        "FROM plink JOIN blob ON cid=rid "
                        "WHERE pid=%"FSL_ID_T_PFMT" "
                        "ORDER BY isprim DESC, mtime DESC /*sort*/",
                        rid);
    if(rc) goto dberr;
    if(rc) goto end;
    while( FSL_RC_STEP_ROW == fsl_stmt_step(&stC) ){
      char const * zLabel = fsl_stmt_g_int32(&stC,2)
        ? "child:" : "merged-into:";
      f_out("%*s %s\n", lblWidth, zLabel,
            fsl_stmt_g_text(&stC, 0, NULL));
      
    }
    fsl_stmt_finalize(&stC);
  }

  f_out("%*s %s\n", lblWidth, "user:",
        fsl_stmt_g_text(&st, 1, NULL));

  f_out("%*s %s\n", lblWidth, "tags:",
        fsl_stmt_g_text(&st, 2, NULL));

  f_out("%*s %s\n", lblWidth, "comment:",
        fsl_stmt_g_text(&st, 3, NULL));

  dberr:
  if(rc){
    fsl_cx_uplift_db_error(f, dbR);
  }
  end:
  fsl_stmt_finalize(&st);

  return rc;
}

static int fsl_stmt_each_f_ambiguous( fsl_stmt * stmt, void * state ){
9819
9820
9821
9822
9823
9824
9825
9826


9827
9828
9829
9830
9831
9832
9833
10039
10040
10041
10042
10043
10044
10045

10046
10047
10048
10049
10050
10051
10052
10053
10054







-
+
+







fsl_db * fcli_needs_repo(void){
  if(fcli.f) return fsl_needs_repo(fcli.f);
  fcli_err_set(FSL_RC_NOT_A_REPO,
               "No repository db is opened.");
  return NULL;
}

int fcli_args_to_vfile_ids(fsl_id_bag *tgt, fsl_id_t vid,
int fcli_args_to_vfile_ids(fsl_id_bag * const tgt,
                           fsl_id_t vid,
                           bool relativeToCwd,
                           bool changedFilesOnly){
  if(!fcli.argc){
    return fcli_err_set(FSL_RC_MISUSE,
                        "No file/dir name arguments provided.");
  }
  int rc = 0;
9862
9863
9864
9865
9866
9867
9868
9869

9870
9871
9872
9873
9874
9875
9876
10083
10084
10085
10086
10087
10088
10089

10090
10091
10092
10093
10094
10095
10096
10097







-
+







        return zEnd+1;
      default: break;
    }
  }
  return zEnd;
}

void fcli_diff_colors(fsl_diff_opt * const tgt, fcli_diff_colors_e theme){
void fcli_diff_colors(fsl_dibu_opt * const tgt, fcli_diff_colors_e theme){
  char const * zIns = 0;
  char const * zEdit = 0;
  char const * zDel = 0;
  char const * zReset = 0;
  switch(theme){
    case FCLI_DIFF_COLORS_RG:
          zIns = "\x1b[32m";
9917
9918
9919
9920
9921
9922
9923
9924
9925


9926
9927
9928
9929
9930
9931
9932
10138
10139
10140
10141
10142
10143
10144


10145
10146
10147
10148
10149
10150
10151
10152
10153







-
-
+
+







}

#undef FCLI_V3
#undef fcli_empty_m
#undef fcli__error
#undef MARKER
#undef FCLI_USE_SIGACTION
/* end of file cli.c */
/* start of file content.c */
/* end of file ./src/cli.c */
/* start of file ./src/content.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
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
9972

9973
9974
9975
9976
9977
9978

9979
9980
9981
9982
9983
9984
9985
9986
9987
9988

9989
9990
9991
9992
9993
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
10043
10044
10045























10046
10047
10048
10049
10050




10051
10052
10053
10054
10055
10056
10057
10058
10166
10167
10168
10169
10170
10171
10172

10173




10174
10175
10176

10177
10178



10179
10180
10181
10182




10183
10184
10185
10186




10187
10188
10189


10190

10191
10192
10193
10194

10195
10196
10197
10198
10199
10200
10201
10202
10203
10204

10205
10206
10207
10208
10209
10210

10211
10212
10213
10214
10215
10216
10217
10218
10219
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
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







-
+
-
-
-
-
+
+

-
+

-
-
-
+
+
+
+
-
-
-
-
+
+
+
+
-
-
-
-
+
+
+
-
-
+
-




-
+









-
+





-
+
+













-

-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
-







#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)


fsl_int_t fsl_content_size( fsl_cx * f, fsl_id_t blobRid ){
fsl_int_t fsl_content_size( fsl_cx * const f, fsl_id_t blobRid ){
  fsl_db * dbR = f ? fsl_cx_db_repo(f) : NULL;
  if(!f) return -3;
  else if(blobRid<=0) return -4;
  else if(!dbR) return -5;
  if(blobRid<=0) return -3;
  else if(!fsl_needs_repo(f)) return -4;
  else{
    int rc;
    int rc = 0;
    fsl_int_t rv = -2;
    fsl_stmt * q = NULL;
    rc = fsl_db_prepare_cached(dbR, &q,
                               "SELECT size FROM blob "
    fsl_stmt * const q = &f->cache.stmt.contentSize;
    if(!q->stmt){
      rc = fsl_cx_prepare(f, q,
                          "SELECT size FROM blob WHERE rid=?1 "
                               "WHERE rid=? "
                               "/*%s()*/",__func__);
    if(!rc){
      rc = fsl_stmt_bind_id(q, 1, blobRid);
                          "/*%s()*/",__func__);
      if(rc) return -6;
    }
    rc = fsl_stmt_bind_step(q, "R", blobRid);
      if(!rc){
        if(FSL_RC_STEP_ROW==fsl_stmt_step(q)){
          rv = (fsl_int_t)fsl_stmt_g_int64(q, 0);
        }
    if(FSL_RC_STEP_ROW==rc){
      rv = (fsl_int_t)fsl_stmt_g_int64(q, 0);
    }
      }
      fsl_stmt_cached_yield(q);
    fsl_stmt_reset(q);
    }
    return rv;
  }
}

bool fsl_content_is_available(fsl_cx * f, fsl_id_t rid){
static bool fsl_content_is_available(fsl_cx * const f, fsl_id_t rid){
  fsl_id_t srcid = 0;
  int rc = 0, depth = 0 /* Limit delta recursion depth */;
  while( depth++ < 100000 ){
    if( fsl_id_bag_contains(&f->cache.blobContent.missing, rid) ){
      return false;
    }else if( fsl_id_bag_contains(&f->cache.blobContent.available, rid) ){
      return true;
    }else if( fsl_content_size(f, rid)<0 ){
      fsl_id_bag_insert(&f->cache.blobContent.missing, rid)
        /* ignore possible OOM error */;
        /* ignore possible OOM error - not fatal */;
      return false;
    }
    rc = fsl_delta_src_id(f, rid, &srcid);
    if(rc) break;
    else if( 0==srcid ){
      fsl_id_bag_insert(&f->cache.blobContent.available, rid);
      fsl_id_bag_insert(&f->cache.blobContent.available, rid)
        /* ignore possible OOM error - not fatal */;
      return true;
    }
    rid = srcid;
  }
  if(0==rc){
    /* This "cannot happen" (never has historically, and would be
       indicative of what amounts to corruption in the repo). */
    fsl__fatal(FSL_RC_RANGE,"delta-loop in repository");
  }
  return false;
}



int fsl_content_blob( fsl_cx * const f, fsl_id_t blobRid, fsl_buffer * const tgt ){
  fsl_db * const dbR = fsl_cx_db_repo(f);
  fsl_db * const dbR = fsl_needs_repo(f);
  if(blobRid<=0) return FSL_RC_RANGE;
  else if(!dbR) return FSL_RC_NOT_A_REPO;
  else{
    int rc;
    fsl_stmt * q = NULL;
    rc = fsl_db_prepare_cached( dbR, &q,
                                "SELECT content, size FROM blob "
                                "WHERE rid=?"
                                "/*%s()*/",__func__);
    if(!rc){
      rc = fsl_stmt_bind_id(q, 1, blobRid);
      if(!rc && (FSL_RC_STEP_ROW==(rc=fsl_stmt_step(q)))){
        void const * mem = NULL;
        fsl_size_t memLen = 0;
        if(fsl_stmt_g_int64(q, 1)<0){
          rc = fsl_cx_err_set(f, FSL_RC_PHANTOM,
                              "Cannot fetch content for phantom "
                              "blob #%"FSL_ID_T_PFMT".",
                              blobRid);
        }else{
  if(!dbR) return FSL_RC_NOT_A_REPO;
  else if(blobRid<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Invalid RID for %s().", __func__);
  }
  int rc = 0;
  fsl_stmt * const q = &f->cache.stmt.contentBlob;
  if(!q->stmt){
    rc = fsl_db_prepare( dbR, q,
                         "SELECT content, size FROM blob "
                         "WHERE rid=?1"
                         "/*%s()*/",__func__);
    if(rc) goto end;
  }
  rc = fsl_stmt_bind_id(q, 1, blobRid);
  if(!rc && (FSL_RC_STEP_ROW==(rc=fsl_stmt_step(q)))){
    void const * mem = NULL;
    fsl_size_t memLen = 0;
    int64_t const sz = fsl_stmt_g_int64(q, 1);
    if(sz<0){
      rc = fsl_cx_err_set(f, FSL_RC_PHANTOM,
                          "Cannot fetch content for phantom "
                          "blob #%"FSL_ID_T_PFMT".",
                          blobRid);
    }
    else if(sz){
          tgt->used = 0;
          fsl_stmt_get_blob(q, 0, &mem, &memLen);
          if(mem && memLen){
            rc = fsl_buffer_append(tgt, mem, memLen);
            if(!rc && fsl_buffer_is_compressed(tgt)){
              rc = fsl_buffer_uncompress(tgt, tgt);
            }
          }
        }
      }else if(FSL_RC_STEP_DONE==rc){
        rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "No blob found for rid %"FSL_ID_T_PFMT".",
                            blobRid);
      }
      fsl_stmt_cached_yield(q);
      rc = fsl_stmt_get_blob(q, 0, &mem, &memLen);
      if(rc){
        rc = fsl_cx_err_set(f, rc,
                            "Error fetching blob content for "
                            "blob #%"FSL_ID_T_PFMT".", blobRid);
      }else{
        fsl_buffer bb = fsl_buffer_empty;
        assert(memLen>0);
        fsl_buffer_external(&bb, mem, memLen);
        rc = fsl_buffer_uncompress(&bb, tgt);
      }
    }else{
      rc = 0;
      fsl_buffer_reuse(tgt);
    }
  }
  else if(FSL_RC_STEP_DONE==rc){
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                        "No blob found for rid %"FSL_ID_T_PFMT".",
                        blobRid);
  }
  end:
  fsl_stmt_reset(q);
    }
    if(rc && !f->error.code && dbR->error.code){
      fsl_cx_uplift_db_error(f, dbR);
    }
    return rc;
  if(rc && !f->error.code && dbR->error.code){
    rc = fsl_cx_uplift_db_error2(f, dbR, rc);
  }
  return rc;
  }
}


bool fsl_content_is_private(fsl_cx * const f, fsl_id_t rid){
  fsl_stmt * s1 = NULL;
  fsl_db * db = fsl_cx_db_repo(f);
  int rc = db
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111

10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125


10126
10127


10128
10129

10130
10131





10132
10133
10134
10135
10136

10137
10138
10139
10140

10141
10142
10143
10144
10145
10146
10147
10148
10149
10150


10151
10152
10153
10154
10155


10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167

10168
10169
10170

10171
10172
10173
10174
10175
10176


10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10313
10314
10315
10316
10317
10318
10319

10320
10321
10322
10323

10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351


10352
10353


10354
10355
10356
10357
10358


10359
10360
10361
10362
10363
10364
10365
10366
10367

10368
10369
10370
10371

10372
10373
10374
10375
10376
10377
10378
10379
10380


10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400

10401
10402
10403

10404
10405
10406
10407
10408
10409

10410
10411
10412
10413
10414












10415
10416
10417
10418
10419
10420
10421







-




-















+












-
-
+
+
-
-
+
+


+
-
-
+
+
+
+
+




-
+



-
+








-
-
+
+





+
+











-
+


-
+





-
+
+



-
-
-
-
-
-
-
-
-
-
-
-







                          "Fossil has no repo opened.");
  }
  else{
    int rc;
    bool gotIt = 0;
    fsl_id_t nextRid;
    fsl__bccache * const ac = &f->cache.blobContent;
    fsl_buffer_reuse(tgt);
    if(fsl_id_bag_contains(&ac->missing, rid)){
      /* Early out if we know the content is not available */
      return FSL_RC_NOT_FOUND;
    }

    /* Look for the artifact in the cache first */
    if(0!=(FSL_CX_F_BLOB_CACHE & f->flags)
       && fsl_id_bag_contains(&ac->inCache, rid) ){
      fsl_size_t i;
      fsl__bccache_line * line;
      for(i=0; i<ac->used; ++i){
        line = &ac->list[i];
        if( line->rid==rid ){
          ++ac->metrics.hits;
          rc = fsl_buffer_copy(tgt, &line->content);
          line->age = ac->nextAge++;
          return rc;
        }
      }
    }
    fsl_buffer_reuse(tgt);
    ++ac->metrics.misses;
    nextRid = 0;
    rc = fsl_delta_src_id(f, rid, &nextRid);
    /* MARKER(("rc=%d, nextRid=%"FSL_ID_T_PFMT"\n", rc, nextRid)); */
    if(rc) return rc;
    if( nextRid == 0 ){
      /* This is not a delta, so get its raw content. */
      rc = fsl_content_blob(f, rid, tgt);
      gotIt = 0==rc;
    }else{
      /* Looks like a delta, so let's expand it... */
      fsl_int_t n           /* number of used entries in 'a' */;
      fsl_int_t nAlloc = 10 /* number it items allocated in 'a' */;
      fsl_id_t * a = NULL    /* array of rids we expand */;
      fsl_int_t mx;
      fsl_id_t * a = NULL;
      fsl_int_t mx;
      fsl_buffer delta = fsl_buffer_empty;
      //fsl_buffer D = fsl_buffer_empty;
      fsl_buffer * const delta = &f->cache.deltaContent;
      fsl_buffer next = fsl_buffer_empty  /* delta-applied content */ ;
      assert(nextRid>0);
      unsigned int nAlloc = 20;
      a = fsl_malloc( sizeof(a[0]) * nAlloc );
      if(!a) return FSL_RC_OOM;
      a = (fsl_id_t*)fsl_malloc(sizeof(fsl_id_t) * nAlloc);
      if(!a){
        rc = FSL_RC_OOM;
        goto end_delta;
      }
      a[0] = rid;
      a[1] = nextRid;
      n = 1;
      while( !fsl_id_bag_contains(&ac->inCache, nextRid)
             && !fsl_delta_src_id(f, nextRid, &nextRid)
             && 0==(rc=fsl_delta_src_id(f, nextRid, &nextRid))
             && (nextRid>0)){
        /* Figure out how big n needs to be... */
        ++n;
        if( n >= nAlloc ){
        if( n >= (fsl_int_t)nAlloc ){
          /* Expand 'a' */
          void * remem;
          if( n > fsl_db_g_int64(db, 0,
                                "SELECT max(rid) FROM blob")){
            rc = fsl_cx_err_set(f, FSL_RC_RANGE,
                                "Infinite loop in delta table.");
            goto end_delta;
          }
          nAlloc = nAlloc * 2;
          remem = fsl_realloc(a, nAlloc*sizeof(a[0]));
          unsigned int const nAlloc2 = nAlloc * 2;
          remem = fsl_realloc(a, nAlloc2 * sizeof(fsl_id_t));
          if(!remem){
            rc = FSL_RC_OOM;
            goto end_delta;
          }
          a = (fsl_id_t*)remem;
          nAlloc = nAlloc2;
          /*MARKER(("deltaIds allocated = %u\n", nAlloc));*/
        }
        a[n] = nextRid;
      }
      /**
         Recursively expand deltas to get the content...
      */
      mx = n;
      rc = fsl_content_get( f, a[n], tgt );
      /* MARKER(("Getting content for rid #%"FSL_ID_T_PFMT", rc=%d\n", a[n], rc)); */
      --n;
      for( ; !rc && (n>=0); --n){
        rc = fsl_content_blob(f, a[n], &delta);
        rc = fsl_content_blob(f, a[n], delta);
        /* MARKER(("Getting/applying delta rid #%"FSL_ID_T_PFMT", rc=%d\n", a[n], rc)); */
        if(rc) goto end_delta;
        if(!delta.used){
        if(!delta->used){
          assert(!"Is this possible? The fossil tree has a similar "
                 "condition but i naively don't believe it's necessary.");
          continue;
        }
        next = fsl_buffer_empty;
        rc = fsl_buffer_delta_apply2(tgt, &delta, &next, &f->error);
        rc = fsl_buffer_delta_apply2(tgt, delta, &next, &f->error);
        //assert(FSL_RC_RANGE!=rc);
        if(rc) goto end_delta;
#if 1
        /*
           In my (very simple) tests this cache costs us more than it
           saves. TODO: re-test this once we can do a 'rebuild', or
           something more intensive than processing a single
           manifest's R-card. At that point we can set a f->flags bit
           to enable or disable this block for per-use-case
           optimization purposes.

           We also probably want to cache fsl_deck instances instead
           of Manifest blobs (fsl_buffer) like fossil(1) does,
           otherwise this cache really doesn't save us much
           work/memory.

           2021-03-24: in a debug build, running:

           f-parseparty -t c -c -q

           (i.e.: parse and crosslink all checkin artifacts)

           on the libfossil repo with 2003 checkins takes:
10221
10222
10223
10224
10225
10226
10227
10228
10229

10230
10231
10232
10233
10234
10235
10236
10444
10445
10446
10447
10448
10449
10450

10451
10452
10453
10454
10455
10456
10457
10458
10459







-

+







#else
        if(mx){/*unused var*/}
        fsl_buffer_clear(tgt);
#endif
        *tgt = next;
      }
      end_delta:
      fsl_buffer_clear(&delta);
      fsl_free(a);
      fsl_buffer_reuse(delta);
      gotIt = 0==rc;
    }

    if(!rc){
      rc = fsl_id_bag_insert(gotIt
                             ? &f->cache.blobContent.available
                             : &f->cache.blobContent.missing,
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
10476
10477
10478
10479
10480
10481
10482

10483
10484
10485
10486
10487
10488
10489
10490
10491
10492

10493
10494
10495

10496
10497
10498
10499
10500
10501
10502

10503
10504
10505
10506
10507
10508
10509
10510
10511

10512
10513
10514
10515
10516
10517
10518







-
+









-



-
+






-
+








-








/**
    Mark artifact rid as being available now. Update f's cache to show
    that everything that was formerly unavailable because rid was
    missing is now available. Returns 0 on success. f must have
    an opened repo and rid must be valid.
 */
static int fsl_content_mark_available(fsl_cx * const f, fsl_id_t rid){
static int fsl__content_mark_available(fsl_cx * const f, fsl_id_t rid){
  fsl_id_bag pending = fsl_id_bag_empty;
  int rc;
  fsl_stmt * st = NULL;
  fsl_db * db = fsl_cx_db_repo(f);
  assert(f);
  assert(db);
  assert(rid>0);
  if( fsl_id_bag_contains(&f->cache.blobContent.available, rid) ) return 0;
  rc = fsl_id_bag_insert(&pending, rid);
  if(rc) goto end;
  while( 0==rc && (rid = fsl_id_bag_first(&pending))!=0 ){
    fsl_id_bag_remove(&pending, rid);
    rc = fsl_id_bag_insert(&f->cache.blobContent.available, rid);
    if(rc) goto end;
    if(rc) break;
    fsl_id_bag_remove(&f->cache.blobContent.missing, rid);
    if(!st){
      rc = fsl_db_prepare_cached(db, &st,
                                 "SELECT rid FROM delta "
                                 "WHERE srcid=?"
                                 "/*%s()*/",__func__);
      if(rc) goto end;
      if(rc) break;
    }
    rc = fsl_stmt_bind_id(st, 1, rid);
    while( !rc && (FSL_RC_STEP_ROW==fsl_stmt_step(st)) ){
      fsl_id_t const nx = fsl_stmt_g_id(st,0);
      assert(nx>0);
      rc = fsl_id_bag_insert(&pending, nx);
    }
  }
  end:
  if(st) fsl_stmt_cached_yield(st);
  fsl_id_bag_clear(&pending);
  return rc;
}

/**
   When a record is converted from a phantom to a real record, if that
10589
10590
10591
10592
10593
10594
10595
10596

10597
10598
10599
10600
10601
10602
10603
10810
10811
10812
10813
10814
10815
10816

10817
10818
10819
10820
10821
10822
10823
10824







-
+







    if(!rc){
      rc = fsl_db_exec(dbR, "DELETE FROM phantom "
                       "WHERE rid=%"FSL_ID_T_PFMT, rid
                       /* FIXME? use cached statement? */);
      if( !rc && (srcId==0 ||
                  0==fsl__bccache_check_available(f, srcId)) ){
        isDephantomize = true;
        rc = fsl_content_mark_available(f, rid);
        rc = fsl__content_mark_available(f, rid);
      }
    }
    fsl_stmt_cached_yield(s1);
    s1 = NULL;
    if(rc) goto end;
#endif
  }else{
10653
10654
10655
10656
10657
10658
10659
10660

10661
10662
10663
10664
10665
10666
10667
10874
10875
10876
10877
10878
10879
10880

10881
10882
10883
10884
10885
10886
10887
10888







-
+







  if( !isDephantomize
      && fsl_id_bag_contains(&f->cache.blobContent.missing, rid) && 
      (srcId==0 || (0==fsl__bccache_check_available(f,srcId)))){
    /*
      TODO: document what this is for.
      TODO: figure out what that is.
    */
    rc = fsl_content_mark_available(f, rid);
    rc = fsl__content_mark_available(f, rid);
    if(rc) goto end;
  }
  if( isDephantomize ){
    rc = fsl_after_dephantomize(f, rid, false);
    if(rc) goto end;
  }

10717
10718
10719
10720
10721
10722
10723
10724
10725


10726
10727
10728
10729
10730
10731
10732
10938
10939
10940
10941
10942
10943
10944


10945
10946
10947
10948
10949
10950
10951
10952
10953







-
-
+
+







  }
  /* TODO? cached query */
  return 1==fsl_db_g_int32( db, 0,
                            "SELECT 1 FROM shun WHERE uuid=%Q",
                            zUuid);
}

int fsl__content_new( fsl_cx * f, fsl_uuid_cstr uuid, bool isPrivate,
                     fsl_id_t * newId ){
int fsl__content_new( fsl_cx * const f, fsl_uuid_cstr uuid,
                      bool isPrivate, fsl_id_t * const newId ){
  fsl_id_t rid = 0;
  int rc;
  fsl_db * db = fsl_cx_db_repo(f);
  fsl_stmt * s1 = NULL, * s2 = NULL;
  int const uuidLen = uuid ? fsl_is_uuid(uuid) : 0;
  if(!f || !uuid) return FSL_RC_MISUSE;
  else if(!uuidLen) return FSL_RC_RANGE;
10797
10798
10799
10800
10801
10802
10803
10804

10805
10806
10807
10808
10809

10810
10811
10812
10813
10814
10815
10816

10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831

10832
10833
10834
10835
10836
10837

10838
10839

10840
10841
10842
10843
10844
10845
10846
11018
11019
11020
11021
11022
11023
11024

11025
11026
11027
11028


11029
11030
11031
11032
11033
11034
11035

11036

11037
11038
11039
11040

11041
11042
11043
11044
11045
11046
11047
11048

11049

11050




11051


11052
11053
11054
11055
11056
11057
11058
11059







-
+



-
-
+






-
+
-




-








-
+
-

-
-
-
-
+
-
-
+







    }
  }
  return rc;
}

int fsl__content_undeltify(fsl_cx * const f, fsl_id_t rid){
  int rc;
  fsl_db * db = f ? fsl_cx_db_repo(f) : NULL;
  fsl_db * const db = fsl_needs_repo(f);
  fsl_id_t srcid = 0;
  fsl_buffer x = fsl_buffer_empty;
  fsl_stmt s = fsl_stmt_empty;
  if(!f) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  if(!db) return FSL_RC_NOT_A_REPO;
  else if(rid<=0) return FSL_RC_RANGE;
  rc = fsl_db_transaction_begin(db);
  if(rc) return fsl_cx_uplift_db_error2(f, db, rc);
  /* Reminder: the original impl does not do this in a
     transaction, _possibly_ because it's only done from places
     where a transaction is active (that's unconfirmed).
     Nested transactions are very cheap, though.
     Nested transactions are very cheap, though. */
  */
  rc = fsl_delta_src_id( f, rid, &srcid );
  if(rc || srcid<=0) goto end;
  rc = fsl_content_get(f, rid, &x);
  if( rc || !x.used ) goto end;
  /* TODO? use cached statements */
  rc = fsl_db_prepare(db, &s,
                      "UPDATE blob SET content=?,"
                      " size=%" FSL_SIZE_T_PFMT
                      " WHERE rid=%" FSL_ID_T_PFMT,
                      x.used, rid);
  if(rc) goto dberr;
  rc = fsl_buffer_compress(&x, &x);
  if(rc) goto end;
  rc = fsl_stmt_bind_blob(&s, 1, x.mem,
  rc = fsl_stmt_bind_step(&s, "B", &x);
                          (fsl_int_t)x.used, 0);
  if(rc) goto dberr;
  rc = fsl_stmt_step(&s);
  if(FSL_RC_STEP_DONE==rc) rc = 0;
  else goto dberr;
  rc = fsl_db_exec(db, "DELETE FROM delta "
  rc = fsl_db_exec(db, "DELETE FROM delta WHERE rid=%"FSL_ID_T_PFMT,
                   "WHERE rid=%"FSL_ID_T_PFMT,
                   (fsl_id_t)rid);
                   rid);
  if(rc) goto dberr;
#if 0
  /*
    fossil does not do this, but that seems like an inconsistency.

    On that topic Richard says:

10870
10871
10872
10873
10874
10875
10876
10877
10878


10879
10880
10881
10882

10883
10884
10885
10886
10887
10888
10889
11083
11084
11085
11086
11087
11088
11089


11090
11091
11092
11093


11094
11095
11096
11097
11098
11099
11100
11101







-
-
+
+


-
-
+







}

int fsl__content_deltify(fsl_cx * f, fsl_id_t rid,
                        fsl_id_t srcid, bool force){
  fsl_id_t s;
  fsl_buffer data = fsl_buffer_empty;
  fsl_buffer src = fsl_buffer_empty;
  fsl_buffer delta = fsl_buffer_empty;
  fsl_db * db = f ? fsl_cx_db_repo(f) : NULL;
  fsl_buffer * const delta = &f->cache.deltaContent;
  fsl_db * const db = fsl_needs_repo(f);
  int rc = 0;
  enum { MinSizeThreshold = 50 };
  if(!f) return FSL_RC_MISUSE;
  else if(rid<=0 || srcid<=0) return FSL_RC_RANGE;
  if(rid<=0 || srcid<=0) return FSL_RC_RANGE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  else if( srcid==rid ) return 0;
  else if(!fsl_content_is_available(f, rid)){
    return 0;
  }
  if(!force){
    fsl_id_t tmpRid = 0;
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
11133
11134
11135
11136
11137
11138
11139


11140
11141
11142
11143
11144


11145
11146
11147
11148

11149
11150
11151
11152
11153
11154
11155

11156
11157
11158
11159
11160
11161
11162
11163







-
-
+




-
-
+
+


-
+






-
+







      break;
    }
  }
  if(rc) return rc;
  /* As of here, don't return on error. Use (goto end) instead, or be
     really careful, b/c buffers might need cleaning. */
  rc = fsl_content_get(f, srcid, &src);
  if(rc
     || (src.used < MinSizeThreshold)
  if(rc || (src.used < MinSizeThreshold)
     /* See API doc comments about minimum size to delta/undelta. */
     ) goto end;
  rc = fsl_content_get(f, rid, &data);
  if(rc || (data.used < MinSizeThreshold)) goto end;
  rc = fsl_buffer_delta_create(&src, &data, &delta);
  if( !rc && (delta.used <= (data.used * 3 / 4 /* 75% */))){
  rc = fsl_buffer_delta_create(&src, &data, delta);
  if( !rc && (delta->used <= (data.used * 3 / 4 /* 75% */))){
    fsl_stmt * s1 = NULL;
    fsl_stmt * s2 = NULL;
    rc = fsl_buffer_compress(&delta, &delta);
    rc = fsl_buffer_compress(delta, &data);
    if(rc) goto end;
    rc = fsl_db_prepare_cached(db, &s1,
                               "UPDATE blob SET content=? "
                               "WHERE rid=?/*%s()*/",__func__);
    if(!rc){
      fsl_stmt_bind_id(s1, 2, rid);
      rc = fsl_stmt_bind_blob(s1, 1, delta.mem, delta.used, 0);
      rc = fsl_stmt_bind_blob(s1, 1, data.mem, data.used, 0);
      if(!rc){
        rc = fsl_db_prepare_cached(db, &s2,
                                   "REPLACE INTO delta(rid,srcid) "
                                   "VALUES(?,?)/*%s()*/",__func__);
        if(!rc){
          fsl_stmt_bind_id(s2, 1, rid);
          fsl_stmt_bind_id(s2, 2, srcid);
10969
10970
10971
10972
10973
10974
10975
10976

10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994


10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015

11016
11017
11018
11019
11020
11021
11022
11180
11181
11182
11183
11184
11185
11186

11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204

11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226

11227
11228
11229
11230
11231
11232
11233
11234







-
+

















-
+
+




















-
+







  }
  end:
  if(rc && db->error.code && !f->error.code){
    fsl_cx_uplift_db_error(f,db);
  }
  fsl_buffer_clear(&src);
  fsl_buffer_clear(&data);
  fsl_buffer_clear(&delta);
  fsl_buffer_reuse(delta);
  return rc;
}

/**
    Removes all entries from the repo's blob table which are listed in
    the shun table.
 */
int fsl__repo_shun_artifacts(fsl_cx * const f){
  fsl_stmt q = fsl_stmt_empty;
  int rc;
  fsl_db * db = f ? fsl_cx_db_repo(f) : NULL;
  if(!f) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  rc = fsl_db_transaction_begin(db);
  if(rc) return rc;
  rc = fsl_db_exec_multi(db,
                         "CREATE TEMP TABLE IF NOT EXISTS "
                         "toshun(rid INTEGER PRIMARY KEY);"
                         "toshun(rid INTEGER PRIMARY KEY); "
                         "DELETE FROM toshun; "
                         "INSERT INTO toshun SELECT rid FROM blob, shun "
                         "WHERE blob.uuid=shun.uuid;"
  );
  if(rc) goto end;
  /* Ensure that deltas generated from the to-be-shunned data
     are unpacked into non-delta form...
  */
  rc = fsl_db_prepare(db, &q,
                      "SELECT rid FROM delta WHERE srcid IN toshun"
                      );
  if(rc) goto end;
  while( !rc && (FSL_RC_STEP_ROW==fsl_stmt_step(&q)) ){
    fsl_id_t const srcid = fsl_stmt_g_id(&q, 0);
    rc = fsl__content_undeltify(f, srcid);
  }
  fsl_stmt_finalize(&q);
  if(!rc){
    rc = fsl_db_exec_multi(db,
            "DELETE FROM delta WHERE rid IN toshun;"
            "DELETE FROM blob WHERE rid IN toshun;"
            "DROP TABLE toshun;"
            "DELETE FROM toshun;"
            "DELETE FROM private "
            "WHERE NOT EXISTS "
            "(SELECT 1 FROM blob WHERE rid=private.rid);"
    );
  }
  end:
  if(!rc) rc = fsl_db_transaction_commit(db);
11037
11038
11039
11040
11041
11042
11043
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
11072
11073
11074
11075
11076



11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094



11095
11096

11097
11098
11099
11100
11101
11102
11103
11249
11250
11251
11252
11253
11254
11255


11256
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
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300


11301
11302
11303
11304

11305
11306
11307
11308
11309
11310
11311
11312







-
-
+
+


















-
-
-
-
+
-
-
-





-
+
+
+
















-
-
+
+
+

-
+







  return rc ? fsl_cx_uplift_db_error(f, db) : 0;
}

/**
    Load the record ID rid and up to N-1 closest ancestors into
    the "fsl_computed_ancestors" table.
 */
static int fsl_compute_ancestors( fsl_db * db, fsl_id_t rid,
                                  int N, char directOnly ){
static int fsl__compute_ancestors( fsl_db * const db, fsl_id_t rid,
                                   int N, bool directOnly ){
  fsl_stmt st = fsl_stmt_empty;
  int rc = fsl_db_prepare(db, &st,
    "WITH RECURSIVE "
    "  ancestor(rid, mtime) AS ("
    "    SELECT ?, mtime "
    "      FROM event WHERE objid=? "
    "    UNION "
    "    SELECT plink.pid, event.mtime"
    "      FROM ancestor, plink, event"
    "     WHERE plink.cid=ancestor.rid"
    "       AND event.objid=plink.pid %s"
    "     ORDER BY mtime DESC LIMIT ?"
    "  )"
    "INSERT INTO fsl_computed_ancestors"
    "  SELECT rid FROM ancestor;",
    directOnly ? "AND plink.isPrim" : ""
  );
  if(!rc){
    fsl_stmt_bind_id(&st, 1, rid);
    fsl_stmt_bind_id(&st, 2, rid);
    fsl_stmt_bind_int32(&st, 3, (int32_t)N);
    rc = fsl_stmt_step(&st);
    rc = fsl_stmt_bind_step(&st, "RRi", rid, rid, (int32_t)N);
    if(FSL_RC_STEP_DONE==rc){
      rc = 0;
    }
  }
  fsl_stmt_finalize(&st);
  return rc;
}

int fsl_mtime_of_F_card(fsl_cx * f, fsl_id_t vid, fsl_card_F const * fc, fsl_time_t *pMTime){
int fsl_mtime_of_F_card(fsl_cx * const f, fsl_id_t vid,
                        fsl_card_F const * const fc,
                        fsl_time_t * const pMTime){
  if(!f || !fc) return FSL_RC_MISUSE;
  else if(vid<=0) return FSL_RC_RANGE;
  else if(!fc->uuid){
    if(pMTime) *pMTime = 0;
    return 0;
  }else{
    fsl_id_t fid = fsl_uuid_to_rid(f, fc->uuid);
    if(fid<=0){
      assert(f->error.code);
      return f->error.code;
    }else{
      return fsl_mtime_of_manifest_file(f, vid, fid, pMTime);
    }
  }
}

int fsl_mtime_of_manifest_file(fsl_cx * f, fsl_id_t vid, fsl_id_t fid, fsl_time_t *pMTime){
  fsl_db * db = fsl_needs_repo(f);
int fsl_mtime_of_manifest_file(fsl_cx * const f, fsl_id_t vid, fsl_id_t fid,
                               fsl_time_t * const pMTime){
  fsl_db * const db = fsl_needs_repo(f);
  fsl_stmt * q = NULL;
  int rc;
  int rc = 0;
  if(!db) return FSL_RC_NOT_A_REPO;

  if(fid<=0){
    /* Only fetch the checkin time... */
    int64_t i = -1;
    rc = fsl_db_get_int64(db, &i, 
                          "SELECT (mtime-2440587.5)*86400 "
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124




11125
11126

11127
11128
11129
11130
11131
11132
11133
11324
11325
11326
11327
11328
11329
11330



11331
11332
11333
11334
11335

11336
11337
11338
11339
11340
11341
11342
11343







-
-
-
+
+
+
+

-
+







    /*
      Computing (and keeping) ancestors is relatively costly, so we
      keep only the copy associated with f->cache.mtimeManifest
      around. For the general case, we will be feeding this function
      files from the same manifest.
    */
    f->cache.mtimeManifest = vid;
    rc = fsl_db_exec_multi(db,"DROP TABLE IF EXISTS temp.fsl_computed_ancestors;"
                           "CREATE TEMP TABLE fsl_computed_ancestors"
                           "(x INTEGER PRIMARY KEY);");
    rc = fsl_db_exec_multi(db, "CREATE TEMP TABLE IF NOT EXISTS "
                           "fsl_computed_ancestors"
                           "(x INTEGER PRIMARY KEY); "
                           "DELETE FROM fsl_computed_ancestors;");
    if(!rc){
      rc = fsl_compute_ancestors(db, vid, 1000000, 1);
      rc = fsl__compute_ancestors(db, vid, 1000000, 1);
    }
    if(rc){
      fsl_cx_uplift_db_error(f, db);
      return rc;
    }
  }
  rc = fsl_db_prepare_cached(db, &q,
11143
11144
11145
11146
11147
11148
11149


11150
11151
11152
11153
11154
11155

11156
11157
11158
11159
11160
11161
11162
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366

11367
11368
11369
11370
11371
11372
11373
11374







+
+





-
+







      rc = 0;
      if(pMTime) *pMTime = (fsl_time_t)fsl_stmt_g_int64(q, 0);
    }else{
      assert(rc);
      if(FSL_RC_STEP_DONE==rc) rc = FSL_RC_NOT_FOUND;
    }
    fsl_stmt_cached_yield(q);
    /* Reminder: DO NOT clean up fsl_computed ancestors here. Doing so
       is not only costly later on but also breaks test code. */
  }
  return rc;
}

int fsl_card_F_content( fsl_cx * f, fsl_card_F const * fc,
                        fsl_buffer * dest ){
                        fsl_buffer * const dest ){
  if(!f || !fc || !dest) return FSL_RC_MISUSE;
  else if(!fc->uuid){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "Cannot fetch content of a deleted file "
                          "because it has no UUID.");
  }
  else if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228

11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11424
11425
11426
11427
11428
11429
11430

11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443

11444
11445
11446
11447
11448
11449
11450







-









+



-







*/
int fsl_import_file( fsl_cx * f, char relativeToCwd,
                     char const * zName,
                     fsl_id_t parentRid,
                     fsl_id_t *rid, fsl_uuid_str * uuid ){
  fsl_buffer * canon = 0; // canonicalized filename
  fsl_buffer * nbuf = 0; // filename buffer
  fsl_buffer * fbuf = &f->fileContent; // file content buffer
  char const * fn;
  int rc;
  fsl_id_t fnid = 0;
  fsl_id_t rcRid = 0;
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  char inTrans = 0;
  if(!zName || !*zName) return FSL_RC_MISUSE;
  else if(!f->ckout.dir) return FSL_RC_NOT_A_CKOUT;
  else if(!db) return FSL_RC_NOT_A_REPO;
  fsl_buffer * const fbuf = fsl__cx_content_buffer(f);
  canon = fsl__cx_scratchpad(f);
  nbuf = fsl__cx_scratchpad(f);

  assert(!fbuf->used && "Misuse of f->fileContent");
  assert(f->ckout.dir);

  /* Normalize the name... i often regret having
     fsl_ckout_filename_check() return checkout-relative paths.
  */
  rc = fsl_ckout_filename_check(f, relativeToCwd, zName, canon);
  if(rc) goto end;
11371
11372
11373
11374
11375
11376
11377
11378
11379


11380
11381
11382
11383
11384
11385
11386
11582
11583
11584
11585
11586
11587
11588


11589
11590
11591
11592
11593
11594
11595
11596
11597







-
-
+
+







  );
  end:
  fsl_stmt_finalize(&q);
  return rc;
}

#undef MARKER
/* end of file content.c */
/* start of file config.c */
/* end of file ./src/content.c */
/* start of file ./src/config.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
12520
12521
12522
12523
12524
12525
12526
12527
12528


12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561


12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12731
12732
12733
12734
12735
12736
12737


12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759

12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775

12776
12777
12778
12779
12780
12781
12782







-
-
+
+




















-












+
+


-








#undef fsl__configs_get_v
#undef fsl__configs_get_x1
#undef fsl__configs_get_x2
#undef SELECT_FROM_CONFIG
#undef MARKER
#undef ARRAYLEN
/* end of file config.c */
/* start of file cx.c */
/* end of file ./src/config.c */
/* start of file ./src/cx.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*************************************************************************
  This file houses most of the context-related APIs.
*/
#if !defined(FSL_ENABLE_SQLITE_REGEXP)
#  define FSL_ENABLE_SQLITE_REGEXP 0
#endif
#if FSL_ENABLE_SQLITE_REGEXP
#endif
#include "sqlite3.h"
#include <assert.h>

#if defined(_WIN32)
# include <windows.h>
# define F_OK 0
# define W_OK 2
#else
# include <unistd.h> /* F_OK */
#endif

#include <stdlib.h>
#include <string.h>
#include <stdio.h> /* FILE class */
#include <errno.h>

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

/** Number of fsl_cx::scratchpads buffers. */
#define FSL_CX_NSCRATCH \
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613

12614
12615
12616
12617
12618
12619
12620
12812
12813
12814
12815
12816
12817
12818

12819
12820
12821
12822

12823
12824
12825
12826
12827
12828
12829
12830







-




-
+







   state or output channel.

   Results are undefined if !f or f's memory has not been properly
   initialized.
*/
static void fsl__cx_reset( fsl_cx * const f, bool closeDatabases );


int fsl_cx_init( fsl_cx ** tgt, fsl_cx_init_opt const * param ){
  static fsl_cx_init_opt paramDefaults = fsl_cx_init_opt_default_m;
  int rc = 0;
  fsl_cx * f;
  extern int fsl_cx_install_timeline_crosslinkers(fsl_cx * const f)
  extern int fsl__cx_install_timeline_crosslinkers(fsl_cx * const f)
    /*in deck.c*/;
  if(!tgt) return FSL_RC_MISUSE;
  else if(!param){
    if(!paramDefaults.output.state){
      paramDefaults.output.state = stdout;
    }
    param = &paramDefaults;
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
12707
12708

12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720

12721
12722
12723
12724
12725
12726
12727

12728


12729
12730
12731
12732
12733



12734
12735
12736
12737

12738
12739

12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12880
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
12950
12951
12952
12953


12954
12955
12956
12957
12958
12959
12960
12961
12962

12963
12964
12965

12966
12967
12968
12969
12970
12971
12972







-
-
-
+
-
-
-

-
+
-
-
-
-
-
-
-
-
+




-
+








+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+



+











-
+






-
+

+
+



-
-
+
+
+




+

-
+


-







      /* Clean up pseudo-leak valgrind complains about:
         https://www.sqlite.org/c3ref/auto_extension.html */;
  }
#endif
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
#endif
  f->dbMem.f = f /* so that dbMem gets fsl_xxx() SQL funcs installed. */;
  rc = fsl_db_open( &f->dbMem, "", 0 );
  if(!rc){
  if(!rc) rc = fsl__cx_install_timeline_crosslinkers(f);
    /* Attempt to ensure that the TEMP tables/indexes use FILE storage. */
    rc = fsl_db_exec(&f->dbMem, "PRAGMA temp_store=FILE;");
  }
  if(!rc){
    rc = fsl_cx_install_timeline_crosslinkers(f);
    f->cache.tempDirs = fsl_temp_dirs_get();
  }
  if(rc){
    if(f->dbMem.error.code){
      fsl_cx_uplift_db_error(f, &f->dbMem);
    }
  }else{
    f->dbMain = &f->dbMem;
    f->dbMem.role = FSL_DBROLE_MAIN;
    if(!f->cache.tempDirs) rc = FSL_RC_OOM;
  }
  return rc;
}

static void fsl__cx_mcache_clear(fsl_cx * const f){
void fsl__cx_mcache_clear(fsl_cx * const f){
  const unsigned cacheLen =
    (unsigned)(sizeof(fsl__mcache_empty.aAge)
               /sizeof(fsl__mcache_empty.aAge[0]));
  for(unsigned i = 0; i < cacheLen; ++i){
    fsl_deck_finalize(&f->cache.mcache.decks[i]);
  }
  f->cache.mcache = fsl__mcache_empty;
}

void fsl__cx_clear_repo_caches(fsl_cx * const f){
  fsl__bccache_reset(&f->cache.blobContent);
  fsl__cx_mcache_clear(f);
  fsl__cx_clear_mf_seen(f, false);
  f->cache.allowSymlinks =
    f->cache.caseInsensitive =
    f->cache.seenDeltaManifest =
    f->cache.manifestSetting = -1;
}

static void fsl__cx_finalize_cached_stmt(fsl_cx * const f){
#define STMT(X) fsl_stmt_finalize(&f->cache.stmt.X)
  STMT(deltaSrcId);
  STMT(uuidToRid);
  STMT(uuidToRidGlob);
  STMT(contentSize);
  STMT(contentBlob);
  STMT(nextEntry);
#undef STMT
}

static void fsl__cx_reset(fsl_cx * const f, bool closeDatabases){
  fsl_checkin_discard(f);
  fsl__cx_finalize_cached_stmt(f);
#define SFREE(X) fsl_free(X); X = NULL
  if(closeDatabases){
    fsl_cx_close_dbs(f);
    /*
      Reminder: f->dbMem is NOT closed here: it's an internal detail,
      not public state. We could arguably close and reopen it here,
      but then we introduce a potenital error case (OOM) where we
      currently have none (thus the void return).

      2021-11-09: it turns out we've had an error case all along
      here: if any cached statements are opened for one of the dbs,
      that can prohibit its detachement.
      that can prohibit its detachment.
    */
    SFREE(f->ckout.dir);
    f->ckout.dirLen = 0;
    /* assert(NULL==f->dbMain); */
  }
  SFREE(f->repo.user);
  SFREE(f->ckout.uuid);
  fsl__cx_ckout_clear(f);
  SFREE(f->cache.projectCode);
  SFREE(f->ticket.titleColumn);
  SFREE(f->ticket.statusColumn);
#undef SFREE
  fsl_error_clear(&f->error);
  f->interrupted = 0;
  fsl__card_J_list_free(&f->ticket.customFields, 1);
  fsl_buffer_clear(&f->fileContent);
  fsl__card_J_list_free(&f->ticket.customFields, true);
  fsl_buffer_clear(&f->cache.fileContent);
  fsl_buffer_clear(&f->cache.deltaContent);
  for(int i = 0; i < FSL_CX_NSCRATCH; ++i){
    fsl_buffer_clear(&f->scratchpads.buf[i]);
    f->scratchpads.used[i] = false;
  }
  fsl__cx_clear_repo_caches(f);
  fsl__bccache_clear(&f->cache.blobContent);
  fsl__cx_mcache_clear(f);
  fsl__cx_clear_mf_seen(f, true);
  fsl_id_bag_clear(&f->cache.leafCheck);
  fsl_id_bag_clear(&f->cache.toVerify);
  fsl__cx_clear_mf_seen(f, true);
  assert(NULL==f->cache.mfSeen.list);
  if(f->xlinkers.list){
    fsl_free(f->xlinkers.list);
    f->xlinkers = fsl_xlinker_list_empty;
  }
#define SLIST(L) fsl_list_visit_free(L, 1)
#define GLOBL(X) SLIST(&f->cache.globs.X)
12757
12758
12759
12760
12761
12762
12763
12764

12765
12766
12767
12768
12769
12770
12771
12772

12773
12774
12775
12776
12777
12778
12779
12780
12781
12980
12981
12982
12983
12984
12985
12986

12987
12988

12989
12990
12991
12992
12993
12994
12995
12996

12997
12998
12999
13000
13001
13002
13003







-
+

-






+

-








void fsl__cx_clear_mf_seen(fsl_cx * const f, bool freeMemory){
  if(freeMemory) fsl_id_bag_clear(&f->cache.mfSeen);
  else fsl_id_bag_reset(&f->cache.mfSeen);
}

void fsl_cx_finalize( fsl_cx * const f ){
  void const * allocStamp = f ? f->allocStamp : NULL;
  void const * const allocStamp = f ? f->allocStamp : NULL;
  if(!f) return;

  if(f->clientState.finalize.f){
    f->clientState.finalize.f( f->clientState.finalize.state,
                               f->clientState.state );
  }
  f->clientState = fsl_state_empty;
  f->output = fsl_outputer_empty;
  fsl_temp_dirs_free(f->cache.tempDirs);
  fsl__cx_reset(f, true);
  fsl_db_close(&f->dbMem);
  *f = fsl_cx_empty;
  if(&fsl_cx_empty == allocStamp){
    fsl_free(f);
  }else{
    f->allocStamp = allocStamp;
  }

12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
13016
13017
13018
13019
13020
13021
13022

13023
13024
13025
13026
13027
13028
13029







-







  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
#endif
}

void fsl_cx_err_reset(fsl_cx * const f){
  //f->interrupted = 0; // No! ONLY modify this via fsl_cx_interrupt()
  fsl_error_reset(&f->error);
  fsl_db_err_reset(&f->dbMem);
  fsl_db_err_reset(&f->repo.db);
  fsl_db_err_reset(&f->config.db);
  fsl_db_err_reset(&f->ckout.db);
}

int fsl_cx_err_set_e( fsl_cx * const f, fsl_error * const err ){
  if(!f) return FSL_RC_MISUSE;
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904

12905
12906
12907
12908
12909
12910

12911
12912
12913
12914
12915
12916
12917
13116
13117
13118
13119
13120
13121
13122



13123

13124
13125
13126


13127
13128
13129
13130
13131
13132
13133
13134







-
-
-
+
-



-
-
+







    assert(db && "misuse: no DB handle to uplift error from!");
    if(db->error.code) rc = fsl_cx_uplift_db_error(f, db);
  }
  return rc;
}

fsl_db * fsl_cx_db_config( fsl_cx * const f ){
  if(!f) return NULL;
  else if(f->dbMain && (FSL_DBROLE_CONFIG & f->dbMain->role)) return f->dbMain;
  else if(f->config.db.dbh) return &f->config.db;
  return f->config.db.dbh ? &f->config.db : NULL;
  else return NULL;
}

fsl_db * fsl_cx_db_repo( fsl_cx * const f ){
  if(!f) return NULL;
  else if(f->dbMain && (FSL_DBROLE_REPO & f->dbMain->role)) return f->dbMain;
  if(f->dbMain && (FSL_DBROLE_REPO & f->dbMain->role)) return f->dbMain;
  else if(f->repo.db.dbh) return &f->repo.db;
  else return NULL;
}

fsl_db * fsl_needs_repo(fsl_cx * const f){
  fsl_db * const db = fsl_cx_db_repo(f);
  if(!db){
12927
12928
12929
12930
12931
12932
12933
12934
12935

12936
12937
12938
12939
12940
12941

12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957

12958
12959
12960
12961
12962
12963
12964
12965
12966

12967
12968
12969
12970
12971
12972
12973















12974
12975





12976
12977
12978
12979








12980

12981

12982
12983
12984
12985






12986
12987
12988












12989
12990
12991
12992
12993
12994
12995
12996
12997
12998





















12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020




13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043

13044
13045
13046
13047




13048
13049
13050
13051
13052

13053
13054
13055
13056


13057
13058
13059
13060


13061
13062
13063
13064
13065
13066
13067
13068




13069
13070
13071
13072
13073



13074









13075


13076
































13077
13078
13079
13080
13081







13082
13083
13084
13085
13086
13087

13088
13089
13090

13091
13092


13093

13094

13095
13096
13097

13098



13099

13100






13101
13102
13103
13104



13105
13106

13107
13108

13109
13110
13111
13112
13113

13114
13115
13116

13117
13118
13119



13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146

13147
13148
13149
13150
13151
13152
13153
13154

13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167

13168
13169
13170
13171
13172
13173
13174
13144
13145
13146
13147
13148
13149
13150


13151
13152
13153
13154
13155
13156

13157
13158

13159













13160
13161
13162
13163
13164
13165
13166
13167
13168

13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191


13192
13193
13194
13195
13196
13197



13198
13199
13200
13201
13202
13203
13204
13205
13206
13207

13208




13209
13210
13211
13212
13213
13214



13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227









13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260










13261
13262
13263
13264

13265



















13266

13267




13268
13269
13270
13271
13272

13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284


13285
13286
13287
13288






13289
13290
13291
13292





13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305

13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340





13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351


13352



13353


13354
13355
13356
13357

13358
13359
13360

13361
13362
13363
13364
13365
13366
13367

13368
13369
13370
13371
13372
13373
13374



13375
13376
13377


13378


13379





13380



13381



13382
13383
13384
13385
13386
13387
























13388

13389
13390
13391
13392
13393
13394

13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407

13408
13409
13410
13411
13412
13413
13414
13415







-
-
+





-
+

-

-
-
-
-
-
-
-
-
-
-
-
-
-
+








-
+







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
+
+
+

-
-
-
+
+
+
+
+
+
+
+

+
-
+
-
-
-
-
+
+
+
+
+
+
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+












-
-
-
-
-
-
-
-
-
-
+
+
+
+
-

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

-
+
-
-
-
-
+
+
+
+

-



+




+
+


-
-
+
+


-
-
-
-
-
-
+
+
+
+
-
-
-
-
-
+
+
+

+
+
+
+
+
+
+
+
+
-
+
+

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
+
+




-
-
+
-
-
-
+
-
-
+
+

+
-
+


-
+

+
+
+

+
-
+
+
+
+
+
+

-
-
-
+
+
+
-
-
+
-
-
+
-
-
-
-
-
+
-
-
-
+
-
-
-
+
+
+



-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-






-
+












-
+







    fsl_cx_err_set(f, FSL_RC_NOT_A_CKOUT,
                   "Fossil context has no opened checkout db.");
  }
  return db;
}

fsl_db * fsl_cx_db_ckout( fsl_cx * const f ){
  if(!f) return NULL;
  else if(f->dbMain && (FSL_DBROLE_CKOUT & f->dbMain->role)) return f->dbMain;
  if(f->dbMain && (FSL_DBROLE_CKOUT & f->dbMain->role)) return f->dbMain;
  else if(f->ckout.db.dbh) return &f->ckout.db;
  else return NULL;
}

fsl_db * fsl_cx_db( fsl_cx * const f ){
  return f ? f->dbMain : NULL;
  return f->dbMain;
}
/** @internal

    Returns one of f->db{Config,Repo,Ckout,Mem}
    or NULL.

    ACHTUNG and REMINDER TO SELF: the current (2021-03) design means
    that none of these handles except for FSL_DBROLE_MAIN actually has
    an sqlite3 db handle assigned to it. This returns a handle to the
    "level of abstraction" we need to keep track of each db's name and
    db-specific other state.

    e.g. passing a role of FSL_DBROLE_CKOUT this does NOT return
    the same thing as fsl_cx_db_ckout().
*/
fsl_db * fsl_cx_db_for_role(fsl_cx * const f, fsl_dbrole_e r){
fsl_db * fsl__cx_db_for_role(fsl_cx * const f, fsl_dbrole_e r){
  switch(r){
    case FSL_DBROLE_CONFIG:
      return &f->config.db;
    case FSL_DBROLE_REPO:
      return &f->repo.db;
    case FSL_DBROLE_CKOUT:
      return &f->ckout.db;
    case FSL_DBROLE_MAIN:
      return &f->dbMem;
      return f->dbMain;
    case FSL_DBROLE_NONE:
    default:
      return NULL;
  }
}

/**
   Returns the "counterpart" role for the given db role.
*/
static fsl_dbrole_e fsl__dbrole_counterpart(fsl_dbrole_e r){
  switch(r){
    case FSL_DBROLE_REPO: return FSL_DBROLE_CKOUT;
    case FSL_DBROLE_CKOUT: return FSL_DBROLE_REPO;
    default:
      fsl__fatal(FSL_RC_MISUSE,
                 "Serious internal API misuse uncovered by %s().",
                 __func__);
      return FSL_DBROLE_NONE;
  }
}

/**
    Detaches the given db role from f->dbMain and removes the role
    from f->dbMain->role.
    Detaches/closes the given db role from f->dbMain and removes the
    role from f->dbMain->role. If r reflects the current primary db
    and a secondary db is attached, the secondary gets detached.  If r
    corresponds to the secondary db, only that db is detached. If
    f->dbMain is the given role then f->dbMain is set to NULL.
*/
static int fsl_cx_detach_role(fsl_cx * const f, fsl_dbrole_e r){
  if(NULL==f->dbMain) return FSL_RC_MISUSE;
  else if(!(r & f->dbMain->role)){
static int fsl__cx_detach_role(fsl_cx * const f, fsl_dbrole_e r){
  assert(FSL_DBROLE_CONFIG!=r && "Config db now has its own handle.");
  assert(FSL_DBROLE_REPO==r || FSL_DBROLE_CKOUT==r);
  if(NULL==f->dbMain){
    assert(!"Internal API misuse: don't try to detach when dbMain is NULL.");
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot close/detach db: none opened.");
  }else if(!(r & f->dbMain->role)){
    assert(!"Misuse: cannot detach unattached role.");
    return fsl_cx_err_set(f, FSL_DBROLE_CKOUT==r
    return FSL_RC_NOT_FOUND;
                          ? FSL_RC_NOT_A_CKOUT
  }
  else{
    fsl_db * const db = fsl_cx_db_for_role(f,r);
    int rc;
                          : FSL_RC_NOT_A_REPO,
                          "Cannot close/detach unattached role: %s",
                          fsl_db_role_name(r));
  }else{
    fsl_db * const db = fsl__cx_db_for_role(f,r);
    int rc = 0;
    assert(db && "Internal API misuse.");
    assert(f->dbMain != db);
    rc = fsl__db_cached_clear_role(f->dbMain, r)
    switch(r){
      case FSL_DBROLE_REPO:
        fsl__cx_clear_repo_caches(f);
        break;
      case FSL_DBROLE_CKOUT:
        fsl__cx_ckout_clear(f);
        break;
      default:
        fsl__fatal(FSL_RC_ERROR, "Cannot happen. Really.");
    }
    fsl__cx_finalize_cached_stmt(f);
    fsl__db_cached_clear_role(f->dbMain, r)
      /* Make sure that we destroy any cached statements which are
         known to be tied to this db role. This is primarily a kludge
         for the global config db to avoid that closing it fails due
         to a lock held by those statements. This is a special case
         for the global db (as opposed to the repo/ckout dbs) because
         exactly when that db is opened and close is not as tightly
         controlled/funneled as the other dbs. */;    
    if(0==rc){
      rc = fsl_db_detach( f->dbMain, fsl_db_role_label(r) );
      //MARKER(("rc=%s %s %s\n", fsl_rc_cstr(rc), fsl_db_role_label(r),
         known to be tied to this db role. */;    
    if(db->dbh){
      /* This is our MAIN db. CLOSE it. If we still have a
         secondary/counterpart db open, we'll detach it first. */
      fsl_dbrole_e const counterpart = fsl__dbrole_counterpart(r);
      assert(f->dbMain == db);
      if(db->role & counterpart){
        /* When closing the main db, detach the counterpart db first
           (if it's attached). We'll ignore any result code here, for
           sanity's sake. */
        assert(fsl__cx_db_for_role(f,counterpart)->filename &&
               "Inconsistent internal db handle state.");
        fsl__cx_detach_role(f, counterpart);
      }
      fsl_db_close(db);
      f->dbMain = NULL;
    }else{
      /* This is our secondary db. DETACH it. */
      assert(f->dbMain != db);
      rc = fsl_db_detach( f->dbMain, fsl_db_role_name(r) );
      //MARKER(("rc=%s %s %s\n", fsl_rc_cstr(rc), fsl_db_role_name(r),
      //        fsl_buffer_cstr(&f->dbMain->error.msg)));
      if(rc){
        fsl_cx_uplift_db_error(f, f->dbMain);
      }else{
        f->dbMain->role &= ~r;
        fsl__db_clear_strings(db, true);
      }
    }
    return rc;
  }
}


/** @internal

    Attaches the given db file to f with the given role. This function "should"
    be static but we need it in fsl_repo.c when creating a new repository.
*/
int fsl_cx_attach_role(fsl_cx * const f, const char *zDbName,
                       fsl_dbrole_e r){
  char const * label = fsl_db_role_label(r);
  fsl_db * const db = fsl_cx_db_for_role(f, r);
int fsl__cx_attach_role(fsl_cx * const f, const char *zDbName,
                         fsl_dbrole_e r, bool createIfNotExists){
  char const * dbName = fsl_db_role_name(r);
  fsl_db * const db = fsl__cx_db_for_role(f, r);
  char ** nameDest = NULL;
  int rc;
  if(!f->dbMain){
    fsl__fatal(FSL_RC_MISUSE,"Internal API misuse: f->dbMain has "
              "not been set, so cannot attach role.");
    return FSL_RC_MISUSE;
  }
  else if(r & f->dbMain->role){
    assert(!"Misuse: role is already attached.");
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Db role %s is already attached.",
                          label);                          
  }
#if 0
  MARKER(("r=%s db=%p, ckout.db=%p\n", label,
          (void*)db, (void*)&f->ckout.db));
  MARKER(("r=%s db=%p, repo.db=%p\n", label,
          (void*)db, (void*)&f->repo.db));
  MARKER(("r=%s db=%p, dbMain=%p\n", label,
          (void*)db, (void*)f->dbMain));
#endif
  assert(db);
  assert(label);
  assert(!db->dbh && "Internal API misuse: don't call this when db is connected.");
  assert(f->dbMain != db);
  assert(!db->filename);
  assert(!db->name);
  nameDest = &db->filename;
  assert(!db->filename && "Don't re-attach!");
  assert(!db->name && "Don't re-attach!");
  assert(dbName);
  assert(f->dbMain != db && "Don't re-attach the main db!");
  switch(r){
    case FSL_DBROLE_CONFIG:
    case FSL_DBROLE_REPO:
    case FSL_DBROLE_CKOUT:
      break;
    case FSL_DBROLE_CONFIG:
    case FSL_DBROLE_MAIN:
    case FSL_DBROLE_NONE:
    default:
      assert(!"cannot happen/not legal");
      fsl__fatal(FSL_RC_RANGE, "Serious internal API misuse via %s().",
                 __func__);
      return FSL_RC_RANGE;
  }
  *nameDest = fsl_strdup(zDbName);
  db->name = *nameDest ? fsl_strdup(label) : NULL;
  db->f = f;
  db->name = fsl_strdup(dbName);
  if(!db->name){
    rc = FSL_RC_OOM;
    /* Design note: we do the strdup() before the ATTACH because if
       the attach succeeds and strdup fails, detaching the db will
       almost certainly fail because it must allocate for its prepared
       statement and other internals. We would end up having to leave
       the db attached and returning a failure, which could lead to a
       memory leak (or worse) downstream.
    goto end;
  }
  if(!f->dbMain){
    // This is our first/main db. OPEN it.
    */
  }else{
    /*MARKER(("Attached %p role %d %s %s\n",
      (void const *)db, r, db->name, db->filename));*/
    rc = fsl_db_attach(f->dbMain, zDbName, label);
    rc = fsl_db_open( db, zDbName, createIfNotExists
                      ? FSL_OPEN_F_RWC
                      : FSL_OPEN_F_RW );
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      fsl_db_close(db);
      goto end;
    }
    int const sqrc = sqlite3_db_config(db->dbh,
                                       SQLITE_DBCONFIG_MAINDBNAME,
                                       dbName);
    if(sqrc){
      rc = fsl__db_errcode(&f->config.db, sqrc);
      fsl_cx_uplift_db_error(f, f->dbMain);
      fsl_cx_uplift_db_error2(f, db, rc);
      fsl_db_close(db);
    }else{
      rc = fsl__cx_init_db(f, db);
      db->role |= r;
      assert(db == f->dbMain)/*even on failure*/;
      /* Should we fsl__cx_detach_role() here? */
    }
  }else{
    // This is our secondary db. ATTACH it.
    assert(db != f->dbMain);
    db->filename = fsl_strdup(zDbName);
    if(!db->filename){
      rc = FSL_RC_OOM;
    }else{
      bool createdIt = false;
      if(createIfNotExists
         && 0!=fsl_file_access( zDbName, F_OK )){
        FILE * const cf = fsl_fopen(zDbName, "w");
        if(!cf){
          rc = fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_IO),
                              "Error creating new db file [%s].",
                              zDbName);
          goto end;
        }
        fsl_fclose(cf);
        createdIt = true;
      }
      rc = fsl_db_attach(f->dbMain, zDbName, dbName);
      if(rc){
        fsl_cx_uplift_db_error(f, f->dbMain);
        fsl_db_close(db)/*cleans up strings*/;
        db->f = NULL;
        if(createdIt) fsl_file_unlink(zDbName);
      }else{
      //MARKER(("Attached db %p %s from %s\n",
      //  (void*)db, label, db->filename));
      f->dbMain->role |= r;
    }
  }
        /*MARKER(("Attached %p role %d %s %s\n",
          (void const *)db, r, db->name, db->filename));*/
        f->dbMain->role |= r;
      }
    }
  }
  end:
  return rc;
}

int fsl_config_close( fsl_cx * const f ){
  int rc = 0;
  fsl_db * const db = &f->config.db;
  if(fsl_db_transaction_level(&f->config.db)){
  if(f->dbMain && (FSL_DBROLE_CONFIG & f->dbMain->role)){
    /* Config db is ATTACHed. */
    rc = fsl_cx_detach_role(f, FSL_DBROLE_CONFIG);
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
  }else{
    fsl_db_close(db);
                          "Cannot close config db with an "
                          "opened transaction.");
  }
  fsl_db_close(&f->config.db);
  return rc;
  return 0;
}

int fsl_repo_close( fsl_cx * const f ){
int fsl_close_scm_dbs(fsl_cx * const f){
  if(fsl_cx_transaction_level(f)){
    /* TODO???: force a full rollback and close it */
    //if(f->repo.db.dbh) fsl_db_rollback_force(&f->repo.db);
    //if(f->ckout.db.dbh) fsl_db_rollback_force(&f->ckout.db);
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot close repo or checkout with an "
                          "Cannot close repo with an opened transaction.");
                          "opened transaction.");
  }else if(!f->dbMain){
    // Make sure that all string resources are cleaned up...
    fsl_db_close(&f->repo.db);
    fsl_db_close(&f->ckout.db);
    return 0;
  }else{
    int rc = 0;
    fsl_db * const db = &f->repo.db;
    if(f->dbMain && (FSL_DBROLE_REPO & f->dbMain->role)){
    fsl_db * const dbR = &f->repo.db;
    return fsl__cx_detach_role(f, f->dbMain == dbR
                               ? FSL_DBROLE_REPO
      /* Repo db is ATTACHed. */
      if(FSL_DBROLE_CKOUT & f->dbMain->role){
                               : FSL_DBROLE_CKOUT)
        rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
                            "Cannot close repo while checkout is "
      /* Will also close the counterpart db. */;
                            "opened.");
      }else{
        assert(f->dbMain!=db);
        rc = fsl_cx_detach_role(f, FSL_DBROLE_REPO);
      }
  }    
    }else{
      fsl_db_close(db);
    }
}
    assert(!db->dbh);
    return rc;
  }

int fsl_repo_close( fsl_cx * const f ){
  return fsl_close_scm_dbs(f);
}

int fsl_ckout_close( fsl_cx * const f ){
  if(fsl_cx_transaction_level(f)){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot close checkout with opened transaction.");
  }else{
    int rc = 0;
    fsl_db * const db = &f->ckout.db;
    if(f->dbMain && (FSL_DBROLE_CKOUT & f->dbMain->role)){
      /* Checkout db is ATTACHed. */
      rc = fsl_cx_detach_role(f, FSL_DBROLE_CKOUT);
      fsl_repo_close(f)
        /* Because the repo is implicitly opened, we "should"
           implicitly close it. This is debatable but "probably almost
           always" desired. i can't currently envisage a reasonable
           use-case which requires closing the checkout but keeping
           the repo opened.  The repo can always be re-opened by
           itself. */;
    }else{
      fsl_db_close(db);
    }
    fsl_free(f->ckout.uuid);
    f->ckout.uuid = NULL;
    f->ckout.rid = 0;
    assert(!db->dbh);
    return rc;
  return fsl_close_scm_dbs(f);
  }
}

/**
   If zDbName is a valid checkout database file, open it and return 0.
   If it is not a valid local database file, return a non-0 code.
*/
static int fsl_cx_ckout_open_db(fsl_cx * f, const char *zDbName){
static int fsl__cx_ckout_open_db(fsl_cx * f, const char *zDbName){
  /* char *zVFileDef; */
  int rc;
  fsl_int_t const lsize = fsl_file_size(zDbName);
  if( -1 == lsize  ){
    return FSL_RC_NOT_FOUND /* might be FSL_RC_ACCESS? */;
  }
  if( lsize%1024!=0 || lsize<4096 ){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "File's size is not correct for a "
                          "checkout db: %s",
                          zDbName);
  }
  rc = fsl_cx_attach_role(f, zDbName, FSL_DBROLE_CKOUT);
  rc = fsl__cx_attach_role(f, zDbName, FSL_DBROLE_CKOUT, false);
  return rc;
}


int fsl_cx_execv( fsl_cx * const f, char const * sql, va_list args ){
  int const rc = (f->dbMain && sql)
    ? fsl_db_execv(f->dbMain, sql, args)
13247
13248
13249
13250
13251
13252
13253
13254

13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267

13268
13269
13270
13271
13272
13273
13274
13488
13489
13490
13491
13492
13493
13494

13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507

13508
13509
13510
13511
13512
13513
13514
13515







-
+












-
+







    schema's tables.
 */
static int fsl_config_file_reset(fsl_cx * const f, char const * dbName){
  fsl_db DB = fsl_db_empty;
  fsl_db * db = &DB;
  int rc = 0;
  bool isAttached = false;
  const char * zPrefix = fsl_db_role_label(FSL_DBROLE_CONFIG);
  const char * zPrefix = fsl_db_role_name(FSL_DBROLE_CONFIG);
  if(-1 != fsl_file_size(dbName)){
    rc = fsl_file_unlink(dbName);
    if(rc){
      return fsl_cx_err_set(f, rc,
                            "Error %s while removing old config file (%s)",
                            fsl_rc_cstr(rc), dbName);
    }
  }
  /**
     Hoop-jumping: because the schema file has a cfg. prefix for the
     table(s), and we cannot assign an arbitrary name to an open()'d
     db, we first open the db (making the the "main" db), then
     ATTACH it to itself to provide the fsl_db_role_label() alias.
     ATTACH it to itself to provide the fsl_db_role_name() alias.
  */
  rc = fsl_db_open(db, dbName, FSL_OPEN_F_RWC);
  if(rc) goto end;
  rc = fsl_db_attach(db, dbName, zPrefix);
  if(rc) goto end;
  isAttached = true;
  rc = fsl_db_exec_multi(db, "%s", fsl_schema_config());
13344
13345
13346
13347
13348
13349
13350
13351


13352
13353
13354
13355
13356
13357
13358
13585
13586
13587
13588
13589
13590
13591

13592
13593
13594
13595
13596
13597
13598
13599
13600







-
+
+








int fsl_config_open( fsl_cx * const f, char const * openDbName ){
  int rc = 0;
  const char * zDbName = 0;
  char * zPrefName = 0;
  if(fsl_cx_db_config(f)){
    if(NULL==openDbName || 0==*openDbName) return 0/*nothing to do*/;
    else fsl_config_close(f);
    fsl_config_close(f);
    assert(!f->config.db.dbh);
  }
  if(openDbName && *openDbName){
    zDbName = openDbName;
  }else{
    rc = fsl_config_global_preferred_name(&zPrefName);
    if(rc) goto end;
    zDbName = zPrefName;
13373
13374
13375
13376
13377
13378
13379







13380







13381
13382
13383
13384
13385
13386
13387
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628

13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642







+
+
+
+
+
+
+
-
+
+
+
+
+
+
+







    rc = fsl_cx_err_set(f, FSL_RC_ACCESS,
                        "Configuration database [%s] "
                        "must be writeable.", zDbName);
    goto end;
  }
#endif
  assert(NULL==fsl_cx_db_config(f));
  rc = fsl_db_open(&f->config.db, zDbName,
                   FSL_OPEN_F_RW | (f->cxConfig.traceSql
                                    ? FSL_OPEN_F_TRACE_SQL
                                    : 0));
  if(0==rc){
    int const sqrc = sqlite3_db_config(f->config.db.dbh,
                                       SQLITE_DBCONFIG_MAINDBNAME,
  rc = fsl_cx_attach_role(f, zDbName, FSL_DBROLE_CONFIG);
                                       fsl_db_role_name(FSL_DBROLE_CONFIG));
    if(sqrc) rc = fsl__db_errcode(&f->config.db, sqrc);
  }
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, &f->config.db, rc);
    fsl_db_close(&f->config.db);
  }
  end:
  fsl_free(zPrefName);
  return rc;
}

static void fsl_cx_username_from_repo(fsl_cx * f){
  fsl_db * dbR = fsl_cx_db_repo(f);
13467
13468
13469
13470
13471
13472
13473










































13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486

13487
13488
13489
13490
13491
13492
13493
13494


13495
13496
13497
13498
13499
13500
13501
13502
13503
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
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
13786
13787
13788
13789


13790
13791


13792
13793
13794
13795
13796
13797
13798







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+












-
+






-
-
+
+
-
-







    case FSL_HPOLICY_SHA1: p = FSL_HPOLICY_SHA1; break;
    case FSL_HPOLICY_SHUN_SHA1: p = FSL_HPOLICY_SHUN_SHA1; break;
    default: p = FSL_HPOLICY_AUTO; break;
  }
  f->cxConfig.hashPolicy = p;
}

#if 0
/**
    Return true if the schema is out-of-date. db must be an opened
    repo db.
 */
static bool fsl__db_repo_schema_is_outofdate(fsl_db *db){
  return fsl_db_exists(db, "SELECT 1 FROM config "
                       "WHERE name='aux-schema' "
                       "AND value<>'%s'",
                       FSL_AUX_SCHEMA);
}

/*
   Returns 0 if db appears to have a current repository schema, 1 if
   it appears to have an out of date schema, and -1 if it appears to
   not be a repository.
*/
int fsl__db_repo_verify_schema(fsl_db * const db){
  if(fsl__db_repo_schema_is_outofdate(db)) return 1;
  else return fsl_db_exists(db,
                            "SELECT 1 FROM config "
                            "WHERE name='project-code'")
    ? 0 : -1;
}
int fsl_repo_schema_validate(fsl_cx * const f, fsl_db * const db){
  int rc = 0;
  int const check = fsl__db_repo_verify_schema(db);
  if(0 != check){
    rc = (check<0)
      ? fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                      "DB file [%s] does not appear to be "
                      "a repository.", db->filename)
      : fsl_cx_err_set(f, FSL_RC_REPO_NEEDS_REBUILD,
                      "DB file [%s] appears to be a fossil "
                      "repsitory, but is out-of-date and needs "
                      "a rebuild.",
                      db->filename);
  }
  return rc;
}
#endif

int fsl_repo_open( fsl_cx * const f, char const * repoDbFile
                   /* , bool readOnlyCurrentlyIgnored */ ){
  if(fsl_cx_db_repo(f)){
    return fsl_cx_err_set(f, FSL_RC_ACCESS,
                          "Context already has an opened repository.");
  }else{
    int rc;
    if(0!=fsl_file_access( repoDbFile, F_OK )){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Repository db [%s] not found or cannot be read.",
                          repoDbFile);
    }else{
      rc = fsl_cx_attach_role(f, repoDbFile, FSL_DBROLE_REPO);
      rc = fsl__cx_attach_role(f, repoDbFile, FSL_DBROLE_REPO, false);
      if(!rc && !(FSL_CX_F_IS_OPENING_CKOUT & f->flags)){
        rc = fsl_cx_after_open(f);
      }
      if(!rc){
        fsl_db * const db = fsl_cx_db_repo(f);
        fsl_cx_username_from_repo(f);
        f->cache.allowSymlinks =
          fsl_config_get_bool(f, FSL_CONFDB_REPO,
        fsl_cx_allows_symlinks(f, true);
        fsl_cx_is_case_sensitive(f, true);
                              false,
                              "allow-symlinks");
        f->cache.seenDeltaManifest =
          fsl_config_get_int32(f, FSL_CONFDB_REPO, -1,
                               "seen-delta-manifest");
        fsl_cx_fetch_hash_policy(f);
        if(f->cxConfig.hashPolicy==FSL_HPOLICY_AUTO){
          if(fsl_db_exists(db, "SELECT 1 FROM blob WHERE length(uuid)>40")
             || !fsl_db_exists(db, "SELECT 1 FROM blob WHERE length(uuid)==40")){
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
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876


13877


13878
13879
13880
13881
13882
13883
13884







+
+
+
+
+
+
+







-
-
+
-
-







  f->ckout.mtime = f->ckout.rid>0
    ? fsl_db_g_double(fsl_cx_db_repo(f), 0.0,
                      "SELECT mtime FROM event "
                      "WHERE objid=%" FSL_ID_T_PFMT,
                      f->ckout.rid)
    : 0.0;
}

void fsl__cx_ckout_clear( fsl_cx * const f ){
  fsl_free(f->ckout.uuid);
  f->ckout.rid = -1;
  f->ckout.uuid = NULL;
  f->ckout.mtime = 0.0;
}

int fsl__ckout_version_fetch( fsl_cx * const f ){
  fsl_id_t rid = 0;
  int rc = 0;
  fsl_db * dbC = fsl_cx_db_ckout(f);
  fsl_db * dbR = dbC ? fsl_needs_repo(f) : NULL;
  assert(!dbC || (dbC && dbR));
  fsl_free(f->ckout.uuid);
  f->ckout.rid = -1;
  fsl__cx_ckout_clear(f);
  f->ckout.uuid = NULL;
  f->ckout.mtime = 0.0;
  if(!dbC){
    return 0;
  }
  fsl_cx_err_reset(f);
  rid = fsl_config_get_id(f, FSL_CONFDB_CKOUT, -1, "checkout");
  //MARKER(("rc=%s rid=%d\n",fsl_rc_cstr(f->error.code), (int)rid));
  if(rid>0){
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13984
13985
13986
13987
13988
13989
13990

13991
13992
13993
13994
13995
13996
13997







-







                         fsl_buffer * const pOut ){
  int rc;
  fsl_int_t dLen = 0, i;
  enum { DbCount = 2 };
  const char aDbName[DbCount][10] = { "_FOSSIL_", ".fslckout" };
  fsl_buffer Buf = fsl_buffer_empty;
  fsl_buffer * buf = &Buf;
  buf->used = 0;
  if(dirName){
    dLen = fsl_strlen(dirName);
    if(0==dLen) return FSL_RC_RANGE;
    rc = fsl_buffer_reserve( buf, (fsl_size_t)(dLen + 10) );
    if(!rc) rc = fsl_buffer_append( buf, dirName, dLen );
    if(rc){
      fsl_buffer_clear(buf);
13772
13773
13774
13775
13776
13777
13778
13779

13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793

13794
13795
13796
13797


13798
13799
13800
13801
13802






13803



13804
13805
13806
13807
13808
13809
13810
13811
13812

13813
13814
13815
13816
13817


13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
14070
14071
14072
14073
14074
14075
14076

14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090

14091
14092
14093


14094
14095
14096
14097



14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114


14115
14116
14117
14118


14119
14120



14121
14122
14123
14124
14125
14126
14127







-
+













-
+


-
-
+
+


-
-
-
+
+
+
+
+
+

+
+
+







-
-
+



-
-
+
+
-
-
-







      }
    }
  }
  fsl_buffer_clear(buf);
  return FSL_RC_NOT_FOUND;
}

int fsl_cx_getcwd(fsl_cx * f, fsl_buffer * pOut){
int fsl_cx_getcwd(fsl_cx * const f, fsl_buffer * const pOut){
  char cwd[FILENAME_MAX] = {0};
  fsl_size_t cwdLen = 0;
  int rc = fsl_getcwd(cwd, (fsl_size_t)sizeof(cwd), &cwdLen);
  if(rc){
    return fsl_cx_err_set(f, rc,
                          "Could not get current working directory!");
  }
  rc = fsl_buffer_append(pOut, cwd, cwdLen);
  return rc
    ? fsl_cx_err_set(f, rc/*must be an OOM*/, NULL)
    : 0;
}

int fsl_ckout_open_dir( fsl_cx * f, char const * dirName,
int fsl_ckout_open_dir( fsl_cx * const f, char const * dirName,
                        bool checkParentDirs ){
  int rc;
  fsl_buffer Buf = fsl_buffer_empty;
  fsl_buffer * buf = &Buf;
  fsl_buffer * const buf = fsl__cx_scratchpad(f);
  fsl_buffer * const bufD = fsl__cx_scratchpad(f);
  char const * zName;
  if(fsl_cx_db_ckout(f)){
    return fsl_cx_err_set( f, FSL_RC_ACCESS,
                           "A checkout is already opened. "
                           "Close it before opening another.");
    rc = fsl_cx_err_set( f, FSL_RC_ACCESS,
                         "A checkout is already opened. "
                         "Close it before opening another.");
    goto end; 
  }else if(!dirName){
    dirName = ".";
  }
  rc = fsl_file_canonical_name( dirName, bufD, false );
  if(rc) goto end;
  dirName = fsl_buffer_cstr(bufD);
  rc = fsl_ckout_db_search(dirName, checkParentDirs, buf);
  if(rc){
    if(FSL_RC_NOT_FOUND==rc){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Could not find checkout under [%s].",
                          dirName ? dirName : ".");
    }
    fsl_buffer_clear(buf);
    return rc;
    goto end;
  }
  assert(buf->used>1 /* "/<FILENAME>" */);
  zName = fsl_buffer_cstr(buf);
  rc = fsl_cx_ckout_open_db(f, zName);
  if(rc){
  rc = fsl__cx_ckout_open_db(f, zName);
  if(0==rc){
    fsl_buffer_clear(buf);
    return rc;
  }else{
    /* Checkout db is now opened. Fiddle some internal
       bits...
    */
    unsigned char * end = buf->mem+buf->used-1;
    /* Find dir part */
    while(end>buf->mem && (unsigned char)'/'!=*end) --end;
    assert('/' == (char)*end && "fsl_ckout_db_search() appends '/<DBNAME>'");
13838
13839
13840
13841
13842
13843
13844
13845
13846




13847
13848
13849
13850
13851
13852
13853

13854
13855
13856
13857
13858
13859
13860
13861
13862
13863

13864
13865
13866
13867
13868







13869
13870
13871
13872
13873
13874
13875
14138
14139
14140
14141
14142
14143
14144

14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155

14156
14157
14158
14159
14160
14161
14162
14163
14164
14165

14166





14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180







-

+
+
+
+






-
+









-
+
-
-
-
-
-
+
+
+
+
+
+
+







    rc = fsl_repo_open_for_ckout(f);
    f->flags &= ~FSL_CX_F_IS_OPENING_CKOUT;
    if(!rc) rc = fsl_cx_after_open(f);
    if(rc){
      /* Is this sane? Is not doing it sane? */
      fsl_ckout_close(f);
    }
    return rc;
  }
  end:
  fsl__cx_scratchpad_yield(f, buf);
  fsl__cx_scratchpad_yield(f, bufD);
  return rc;
}


char const * fsl_cx_db_file_for_role(fsl_cx const * f,
                                     fsl_dbrole_e r,
                                     fsl_size_t * len){
  fsl_db const * db = fsl_cx_db_for_role((fsl_cx*)f, r);
  fsl_db const * db = fsl__cx_db_for_role((fsl_cx*)f, r);
  char const * rc = db ? db->filename : NULL;
  if(len) *len = fsl_strlen(rc);
  return rc;
}

char const * fsl_cx_db_name_for_role(fsl_cx const * f,
                                     fsl_dbrole_e r,
                                     fsl_size_t * len){
  if(FSL_DBROLE_MAIN == r){
    /* special case to be removed when f->dbMem bits are
    if(f->dbMain){
       finished. */
    if(len) *len=4;
    return "main";
  }else{
    fsl_db const * db = fsl_cx_db_for_role((fsl_cx*)f, r);
      if(len) *len=4;
      return "main";
    }else{
      return NULL;
    }
  }else{
    fsl_db const * db = fsl__cx_db_for_role((fsl_cx*)f, r);
    char const * rc = db ? db->name : NULL;
    if(len) *len = rc ? fsl_strlen(rc) : 0;
    return rc;
  }
}

char const * fsl_cx_db_file_config(fsl_cx const * f,
14071
14072
14073
14074
14075
14076
14077




14078
14079
14080






14081
14082
14083
14084







14085
14086
14087
14088

14089
14090




14091




14092
14093

14094
14095
14096
14097



14098
14099

14100
14101
14102
14103

14104
14105
14106
14107
14108




14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121

14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135

14136
14137
14138
14139
14140
14141
14142
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386



14387
14388
14389
14390
14391
14392
14393
14394


14395
14396
14397
14398
14399
14400
14401
14402
14403
14404

14405
14406
14407
14408
14409
14410
14411

14412
14413
14414
14415
14416

14417
14418



14419
14420
14421
14422

14423
14424
14425
14426

14427
14428
14429
14430


14431
14432
14433
14434
14435
14436
14437
14438









14439














14440
14441
14442
14443
14444
14445
14446
14447







+
+
+
+
-
-
-
+
+
+
+
+
+


-
-
+
+
+
+
+
+
+



-
+


+
+
+
+
-
+
+
+
+

-
+

-
-
-
+
+
+

-
+



-
+



-
-
+
+
+
+




-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+







}

int fsl_cx_stat(fsl_cx * const f, bool relativeToCwd,
                char const * zName, fsl_fstat * const tgt){
  return fsl_cx_stat2(f, relativeToCwd, zName, tgt, NULL, false);
}

bool fsl_cx_allows_symlinks(fsl_cx * const f, bool forceRecheck){
  if(forceRecheck || f->cache.allowSymlinks<0){
    f->cache.allowSymlinks = fsl_config_get_bool(f, FSL_CONFDB_REPO,
                                                 false, "allow-symlinks");

void fsl_cx_case_sensitive_set(fsl_cx * f, bool caseSensitive){
  f->cache.caseInsensitive = caseSensitive;
  }
  return f->cache.allowSymlinks>0;
}

void fsl_cx_case_sensitive_set(fsl_cx * const f, bool caseSensitive){
  f->cache.caseInsensitive = caseSensitive ? 0 : 1;
}

bool fsl_cx_is_case_sensitive(fsl_cx const * f){
  return !f->cache.caseInsensitive;
bool fsl_cx_is_case_sensitive(fsl_cx * const f, bool forceRecheck){
  if(forceRecheck || f->cache.caseInsensitive<0){
    f->cache.caseInsensitive =
      fsl_config_get_bool(f, FSL_CONFDB_REPO,
                          true, "case-sensitive") ? 0 : 1;
  }
  return f->cache.caseInsensitive <= 0;
}

char const * fsl_cx_filename_collation(fsl_cx const * f){
  return f->cache.caseInsensitive ? "COLLATE nocase" : "";
  return f->cache.caseInsensitive>0 ? "COLLATE nocase" : "";
}

fsl_buffer * fsl__cx_content_buffer(fsl_cx * const f){
  if(f->cache.fileContent.used){
    fsl__fatal(FSL_RC_MISUSE,
               "Called %s() while the content buffer has bytes in use.");

  }
  return &f->cache.fileContent;
}

void fsl__cx_content_buffer_yield(fsl_cx * const f){
  enum { MaxSize = 1024 * 1024 * 2 };
  enum { MaxSize = 1024 * 1024 * 10 };
  assert(f);
  if(f->fileContent.capacity>MaxSize){
    fsl_buffer_resize(&f->fileContent, MaxSize);
    assert(f->fileContent.capacity<=MaxSize+1);
  if(f->cache.fileContent.capacity>MaxSize){
    fsl_buffer_resize(&f->cache.fileContent, MaxSize);
    assert(f->cache.fileContent.capacity<=MaxSize+1);
  }
  fsl_buffer_reuse(&f->fileContent);
  fsl_buffer_reuse(&f->cache.fileContent);
}

fsl_error const * fsl_cx_err_get_e(fsl_cx const * f){
  return f ? &f->error : NULL;
  return &f->error;
}

int fsl_cx_close_dbs( fsl_cx * const f ){
  if(fsl_cx_transaction_level(f)){
    /* Is this really necessary? */
  if(fsl_cx_transaction_level(f)
     || (f->config.db.dbh && fsl_db_transaction_level(&f->config.db))){
    /* Is this really necessary? Should we instead
       force rollback(s) and close the dbs? */
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot close the databases when a "
                          "transaction is pending.");
  }
  if(NULL==f->dbMain) return 0;
  int rc = 0, rc1;
  rc = fsl__db_cached_clear_role(f->dbMain, 0);
  if(rc) return fsl_cx_uplift_db_error(f, f->dbMain);
  rc1 = fsl_ckout_close(f);
  if(rc1) rc = rc1;
  rc1 = fsl_repo_close(f);
  if(rc1) rc = rc1;
  rc1 = fsl_config_close(f);
  fsl_config_close(f);
  if(rc1) rc = rc1;
  /* Forcibly reset the role and db strings for this case, even
     if closing ostensibly fails. */
  f->dbMain->role = FSL_DBROLE_MAIN;
  fsl__db_clear_strings(&f->repo.db, true);
  fsl__db_clear_strings(&f->ckout.db, true);
  fsl__db_clear_strings(&f->config.db, true);
  assert(!f->repo.db.dbh);
  assert(!f->ckout.db.dbh);
  assert(!f->config.db.dbh);
  assert(!f->repo.db.filename);
  assert(!f->ckout.db.filename);
  assert(!f->config.db.filename);
  return rc;
  return fsl_close_scm_dbs(f);
}

char const * fsl_cx_glob_matches( fsl_cx * const f, int gtype,
                                  char const * str ){
  int i, count = 0;
  char const * rv = NULL;
  fsl_list const * lists[] = {0,0,0};
14186
14187
14188
14189
14190
14191
14192
14193

14194
14195
14196
14197
14198
14199
14200
14491
14492
14493
14494
14495
14496
14497

14498
14499
14500
14501
14502
14503
14504
14505







-
+







}

int fsl_cx_hash_filename( fsl_cx * f, bool useAlternate,
                          const char * zFilename, fsl_buffer * pOut){
  /* FIXME: reimplement this to stream the content in bite-sized
     chunks. That requires duplicating most of fsl_buffer_fill_from()
     and fsl_cx_hash_buffer(). */
  fsl_buffer * content = &f->fileContent;
  fsl_buffer * const content = &f->cache.fileContent;
  int rc;
  assert(!content->used && "Internal recursive misuse of fsl_cx::fileContent");
  fsl_buffer_reuse(content);
  rc = fsl_buffer_fill_from_filename(content, zFilename);
  if(!rc){
    rc = fsl_cx_hash_buffer(f, useAlternate, content, pOut);
  }
14294
14295
14296
14297
14298
14299
14300
14301

14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321


14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338



14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352

14353
14354
14355
14356
14357
14358
14359
14599
14600
14601
14602
14603
14604
14605

14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624


14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642

14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658

14659
14660
14661
14662
14663
14664
14665
14666







-
+


















-
-
+
+
















-
+
+
+













-
+







    f->cache.seenDeltaManifest = 1;
    rc = fsl_config_set_bool(f, FSL_CONFDB_REPO,
                             "seen-delta-manifest", 1);
  }
  return rc;
}

int fsl_reserved_fn_check(fsl_cx *f, const char *zPath,
int fsl_reserved_fn_check(fsl_cx * const f, const char *zPath,
                          fsl_int_t nPath, bool relativeToCwd){
  static const int errRc = FSL_RC_RANGE;
  int rc = 0;
  char const * z1 = 0;
  if(nPath<0) nPath = (fsl_int_t)fsl_strlen(zPath);
  if(fsl_is_reserved_fn(zPath, nPath)){
    return fsl_cx_err_set(f, errRc,
                        "Filename is reserved, not legal "
                        "for adding to a repository: %.*s",
                        (int)nPath, zPath);
  }
  if(!(f->flags & FSL_CX_F_ALLOW_WINDOWS_RESERVED_NAMES)
     && fsl__is_reserved_fn_windows(zPath, nPath)){
    return fsl_cx_err_set(f, errRc,
                          "Filename is a Windows reserved name: %.*s",
                          (int)nPath, zPath);
  }
  if((z1 = fsl_cx_db_file_for_role(f, FSL_DBROLE_REPO, NULL))){
    fsl_buffer * c1 = fsl__cx_scratchpad(f);
    fsl_buffer * c2 = fsl__cx_scratchpad(f);
    fsl_buffer * const c1 = fsl__cx_scratchpad(f);
    fsl_buffer * const c2 = fsl__cx_scratchpad(f);
    rc = fsl_file_canonical_name2(relativeToCwd ? NULL : f->ckout.dir/*NULL is okay*/,
                                  z1, c1, false);
    if(!rc) rc = fsl_file_canonical_name2(relativeToCwd ? NULL : f->ckout.dir,
                                          zPath, c2, false);
    //MARKER(("\nzPath=%s\nc1=%s\nc2=%s\n", zPath,
    //fsl_buffer_cstr(c1), fsl_buffer_cstr(c2)));
    if(!rc && c1->used == c2->used &&
       0==fsl_stricmp(fsl_buffer_cstr(c1), fsl_buffer_cstr(c2))){
      rc = fsl_cx_err_set(f, errRc, "File is the repository database: %.*s",
                          (int)nPath, zPath);
    }
    fsl__cx_scratchpad_yield(f, c1);
    fsl__cx_scratchpad_yield(f, c2);
    if(rc) return rc;
  }
  assert(!rc);
  while(f->ckout.dir || relativeToCwd){
  while(true){
    /* Check the name against the repo's "manifest" setting and reject
       any filenames which that setting implies. */
    int manifestSetting = 0;
    fsl_ckout_manifest_setting(f, &manifestSetting);
    if(!manifestSetting) break;
    typedef struct {
      short flag;
      char const * fn;
    } MSetting;
    const MSetting M[] = {
    {FSL_MANIFEST_MAIN, "manifest"},
    {FSL_MANIFEST_UUID, "manifest.uuid"},
    {FSL_MANIFEST_TAGS, "manifest.tags"},
    {0,0}
    };
    fsl_buffer * c1 = fsl__cx_scratchpad(f);
    fsl_buffer * const c1 = fsl__cx_scratchpad(f);
    if(f->ckout.dir){
      rc = fsl_ckout_filename_check(f, relativeToCwd, zPath, c1);
    }else{
      rc = fsl_file_canonical_name2("", zPath, c1, false);
    }
    if(rc) goto yield;
    char const * const z = fsl_buffer_cstr(c1);
14423
14424
14425
14426
14427
14428
14429
14430

14431
14432
14433
14434
14435
14436
14437
14730
14731
14732
14733
14734
14735
14736

14737
14738
14739
14740
14741
14742
14743
14744







-
+







            "Fatal internal fsl_cx::scratchpads misuse: "
            "passed a non-scratchpad buffer.");
}


/** @internal

   Don't use this. Use fsl_cx_rm_empty_dirs() instead.
   Don't use this. Use fsl__ckout_rm_empty_dirs() instead.

   Attempts to remove empty directories from under a checkout,
   starting with tgtDir and working upwards until it either cannot
   remove one or it reaches the top of the checkout dir.

   The first argument must be the canonicalized absolute path to the
   checkout root. The second is the length of coRoot - if it's
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455




14456
14457
14458
14459
14460
14461
14462

14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482


14483
14484
14485

14486
14487
14488
14489
14490

14491
14492
14493
14494
14495
14496
14497
14498

14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509

14510
14511
14512
14513
14514
14515
14516
14753
14754
14755
14756
14757
14758
14759



14760
14761
14762
14763
14764
14765
14766
14767
14768
14769

14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789

14790
14791
14792
14793

14794
14795
14796
14797
14798

14799
14800
14801
14802
14803
14804
14805
14806

14807
14808
14809
14810
14811
14812






14813
14814
14815
14816
14817
14818
14819
14820







-
-
-
+
+
+
+






-
+



















-
+
+


-
+




-
+







-
+





-
-
-
-
-
-
+








   Results are undefined if tgtDir is not an absolute path or does not
   have coRoot as its initial prefix.

   There are any number of valid reasons removal of a directory might
   fail, and this routine stops at the first one which does.
*/
static unsigned fsl_rm_empty_dirs(char const *coRoot, fsl_int_t rootLen,
                                  fsl_buffer * tgtDir){
  if(rootLen<0) rootLen = fsl_strlen(coRoot);
static unsigned fsl__rm_empty_dirs(char const * const coRoot,
                                   fsl_int_t rootLen,
                                  fsl_buffer const * const tgtDir){
  if(rootLen<0) rootLen = (fsl_int_t)fsl_strlen(coRoot);
  char const * zAbs = fsl_buffer_cstr(tgtDir);
  char const * zCoDirPart = zAbs + rootLen;
  char * zEnd = fsl_buffer_str(tgtDir) + tgtDir->used - 1;
  unsigned rc = 0;
  assert(coRoot);
  if(0!=memcmp(coRoot, zAbs, (size_t)rootLen)){
    assert(!"Misuse of fsl_rm_empty_dirs()");
    assert(!"Misuse of fsl__rm_empty_dirs()");
    return 0;
  }
  if(fsl_rmdir(zAbs)) return rc;
  ++rc;
  /** Now walk up each dir in the path and try to remove each,
      stopping when removal of one fails or we reach coRoot. */
  while(zEnd>zCoDirPart){
    for( ; zEnd>zCoDirPart && '/'!=*zEnd; --zEnd ){}
    if(zEnd==zCoDirPart) break;
    else if('/'==*zEnd){
      *zEnd = 0;
      assert(zEnd>zCoDirPart);
      if(fsl_rmdir(zAbs)) break;
      ++rc;
    }
  }
  return rc;
}

unsigned int fsl_ckout_rm_empty_dirs(fsl_cx * const f, fsl_buffer * const tgtDir){
unsigned int fsl__ckout_rm_empty_dirs(fsl_cx * const f,
                                      fsl_buffer const * const tgtDir){
  int rc = f->ckout.dir ? 0 : FSL_RC_NOT_A_CKOUT;
  if(!rc){
    rc = fsl_rm_empty_dirs(f->ckout.dir, f->ckout.dirLen, tgtDir);
    rc = fsl__rm_empty_dirs(f->ckout.dir, f->ckout.dirLen, tgtDir);
  }
  return rc;
}

int fsl_ckout_rm_empty_dirs_for_file(fsl_cx * const f, char const *zAbsPath){
int fsl__ckout_rm_empty_dirs_for_file(fsl_cx * const f, char const *zAbsPath){
  if(!fsl_is_rooted_in_ckout(f, zAbsPath)){
    assert(!"Internal API misuse!");
    return FSL_RC_MISUSE;
  }else{
    fsl_buffer * const p = fsl__cx_scratchpad(f);
    fsl_int_t const nAbs = (fsl_int_t)fsl_strlen(zAbsPath);
    int const rc = fsl_file_dirpart(zAbsPath, nAbs, p, false);
    if(!rc) fsl_rm_empty_dirs(f->ckout.dir, f->ckout.dirLen, p);
    if(!rc) fsl__rm_empty_dirs(f->ckout.dir, f->ckout.dirLen, p);
    fsl__cx_scratchpad_yield(f,p);
    return rc;
  }
}

bool fsl_repo_forbids_delta_manifests(fsl_cx * f){
  return fsl_config_get_bool(f, FSL_CONFDB_REPO, false,
                             "forbid-delta-manifests");
}

int fsl_ckout_fingerprint_check(fsl_cx * f){
int fsl_ckout_fingerprint_check(fsl_cx * const f){
  fsl_db * const db = fsl_cx_db_ckout(f);
  if(!db) return 0;
  int rc = 0;
  char const * zCkout = 0;
  char * zRepo = 0;
  fsl_id_t rcvCkout = 0;
  fsl_buffer * const buf = fsl__cx_scratchpad(f);
14594
14595
14596
14597
14598
14599
14600
14601
14602


14603
14604
14605
14606
14607
14608
14609
14898
14899
14900
14901
14902
14903
14904


14905
14906
14907
14908
14909
14910
14911
14912
14913







-
-
+
+







  struct tm * tm = fsl_cx_localtime(f, &clock);
  return tm ? mktime(tm) : 0;
}
#endif

#undef MARKER
#undef FSL_CX_NSCRATCH
/* end of file cx.c */
/* start of file db.c */
/* end of file ./src/cx.c */
/* start of file ./src/db.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
14639
14640
14641
14642
14643
14644
14645


































14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656

14657
14658
14659
14660
14661

14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682

14683
14684
14685
14686
14687
14688
14689
14690
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992


14993

14994
14995
14996

14997
















14998
14999
15000


15001

15002
15003
15004
15005
15006
15007
15008







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+









-
-
+
-



-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-



-
-
+
-







 */
static int fsl_list_v_fsl_stmt_finalize(void * obj, void * visitorState ){
  if(obj) fsl_stmt_finalize( (fsl_stmt*)obj );
  return 0;
}
#endif


int fsl__db_errcode(fsl_db * const db, int sqliteCode){
  int rc = 0;
  if(!sqliteCode) sqliteCode = sqlite3_errcode(db->dbh);
  switch(sqliteCode & 0xff){
    case SQLITE_ROW:
    case SQLITE_DONE:
    case SQLITE_OK: rc = 0; break;
    case SQLITE_NOMEM: rc = FSL_RC_OOM; break;
    case SQLITE_INTERRUPT: rc = FSL_RC_INTERRUPTED; break;
    case SQLITE_TOOBIG:
    case SQLITE_FULL:
    case SQLITE_NOLFS:
    case SQLITE_RANGE: rc = FSL_RC_RANGE; break;
    case SQLITE_NOTFOUND: rc = FSL_RC_NOT_FOUND; break;
    case SQLITE_PERM:
    case SQLITE_AUTH:
    case SQLITE_LOCKED:
    case SQLITE_READONLY: rc = FSL_RC_ACCESS; break;
    case SQLITE_CORRUPT: rc = FSL_RC_CONSISTENCY; break;
    case SQLITE_CANTOPEN:
    case SQLITE_IOERR:
      rc = FSL_RC_IO; break;
    default:
      //MARKER(("sqlite3_errcode()=0x%04x\n", rc));
      rc = FSL_RC_DB; break;
  }
  return rc
    ? fsl_error_set(&db->error, rc,
                    "sqlite3 error #%d: %s",
                    sqliteCode, sqlite3_errmsg(db->dbh))
    : (fsl_error_reset(&db->error), 0);
}

void fsl__db_clear_strings(fsl_db * const db, bool alsoErrorState ){
  fsl_free(db->filename);
  db->filename = NULL;
  fsl_free(db->name);
  db->name = NULL;
  if(alsoErrorState) fsl_error_clear(&db->error);
}

int fsl_db_err_get( fsl_db const * const db, char const ** msg, fsl_size_t * len ){
  return db
    ? fsl_error_get(&db->error, msg, len)
  return fsl_error_get(&db->error, msg, len);
    : FSL_RC_MISUSE;
}

fsl_db * fsl_stmt_db( fsl_stmt * const stmt ){
  return stmt ? stmt->db : NULL;
  return stmt->db;
}

/**
    Resets db->error state based on the given code and the current
    error string from the db driver. Returns FSL_RC_DB on success,
    some other non-0 value on error (most likely FSL_RC_OOM while
    allocating the error string - that's the only other error case as
    long as db is opened). Results are undefined if !db or db is not
    opened.
 */
static int fsl_err_from_db( fsl_db * const db, int dbCode ){
  assert(db && db->dbh);
  db->error.msg.used =0 ;
  return fsl_error_set(&db->error, FSL_RC_DB,
                       "Db error #%d: %s",
                       dbCode, sqlite3_errmsg(db->dbh));
}

char const * fsl_stmt_sql( fsl_stmt * const stmt, fsl_size_t * const len ){
  return stmt
    ? fsl_buffer_cstr2(&stmt->sql, len)
  return fsl_buffer_cstr2(&stmt->sql, len);
    : NULL;
}

char const * fsl_db_filename(fsl_db const * db, fsl_size_t * len){
  if(len && db->filename) *len = fsl_strlen(db->filename);
  return db->filename;
}

14726
14727
14728
14729
14730
14731
14732
14733
14734

14735

14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756



14757
14758
14759
14760
14761
14762
14763
15044
15045
15046
15047
15048
15049
15050


15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071



15072
15073
15074
15075
15076
15077
15078
15079
15080
15081







-
-
+

+


















-
-
-
+
+
+







    }
    db->cacheHead = 0;
  }
  return rc;
}

void fsl_db_close( fsl_db * const db ){
  if(!db) return;
  void const * allocStamp = db->allocStamp;
  void const * const allocStamp = db->allocStamp;
  fsl_cx * const f = db->f;
  if(!db->dbh) return;
  fsl_db_stmt_cache_clear(db);
  if(db->f && db->f->dbMain==db){
    /*
      Horrible, horrible dependency, and only necessary if the
      fsl_cx API gets sloppy or repo/checkout/config DBs are
      otherwised closed improperly (i.e. not via the fsl_cx API).
    */
    assert(0 != db->role);
    f->dbMain = NULL;
  }
  while(db->beginCount>0){
    fsl_db_transaction_end(db, 1);
  }
  if(0!=db->openStatementCount){
    MARKER(("WARNING: %d open statement(s) left on db [%s].\n",
            (int)db->openStatementCount, db->filename));
  }
  if(db->dbh){
    sqlite3_close(db->dbh);
    /* ignoring results in the style of "destructors may not
       throw". */
    sqlite3_close_v2(db->dbh);
    /* Ignore results in the style of "destructors
       may not throw.". */
  }
  fsl__db_clear_strings(db, true);
  fsl_db_cleanup_beforeCommit(db);
  fsl_buffer_clear(&db->cachePrepBuf);
  *db = fsl_db_empty;
  if(&fsl_db_empty == allocStamp){
    fsl_free( db );
14789
14790
14791
14792
14793
14794
14795
14796

14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
15107
15108
15109
15110
15111
15112
15113

15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127

15128
15129
15130
15131
15132
15133
15134







-
+













-







char const * fsl_db_name(fsl_db const * const db){
  return db ? db->name : NULL;
}

/**
    Returns the db name for the given role.
 */
const char * fsl_db_role_label(fsl_dbrole_e r){
const char * fsl_db_role_name(fsl_dbrole_e r){
  switch(r){
    case FSL_DBROLE_CONFIG:
      return "cfg";
    case FSL_DBROLE_REPO:
      return "repo";
    case FSL_DBROLE_CKOUT:
      return "ckout";
    case FSL_DBROLE_MAIN:
      return "main";
    case FSL_DBROLE_TEMP:
      return "temp";
    case FSL_DBROLE_NONE:
    default:
      assert(!"cannot happen/not legal");
      return NULL;
  }
}

char * fsl_db_julian_to_iso8601( fsl_db * const db, double j,
                                 bool msPrecision,
                                 bool localTime){
15035
15036
15037
15038
15039
15040
15041
15042

15043
15044
15045
15046
15047
15048
15049
15352
15353
15354
15355
15356
15357
15358

15359
15360
15361
15362
15363
15364
15365
15366







-
+







    st->flags = FSL_STMT_F_CACHE_HELD;
    *rv = st;
  }
  end:
  return rc;
}

int fsl_db_prepare_cached( fsl_db * db, fsl_stmt ** st, char const * sql, ... ){
int fsl_db_prepare_cached( fsl_db * const db, fsl_stmt ** st, char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_preparev_cached( db, st, sql, args );
  va_end(args);
  return rc;
}
15088
15089
15090
15091
15092
15093
15094
15095

15096
15097
15098
15099
15100
15101
15102
15405
15406
15407
15408
15409
15410
15411

15412
15413
15414
15415
15416
15417
15418
15419







-
+







  return rc;
}

int fsl_stmt_finalize( fsl_stmt * const stmt ){
  if(!stmt) return FSL_RC_MISUSE;
  else{
    void const * allocStamp = stmt->allocStamp;
    fsl_db * db = stmt->db;
    fsl_db * const db = stmt->db;
    if(db){
      if(stmt->sql.mem){
        /* ^^^ b/c that buffer is set at the same time
           that openStatementCount is incremented.
        */
        --stmt->db->openStatementCount;
      }
15169
15170
15171
15172
15173
15174
15175
15176

15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189

15190
15191
15192
15193
15194

15195
15196

15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210

15211
15212
15213
15214
15215
15216
15217
15218
15219
15220

15221
15222

15223
15224
15225
15226

15227
15228
15229
15230
15231
15232
15233
15234
15235

15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254

15255
15256
15257
15258
15259
15260
15261
15486
15487
15488
15489
15490
15491
15492

15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503



15504
15505
15506
15507
15508

15509
15510

15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524

15525
15526
15527
15528
15529
15530
15531
15532
15533
15534

15535
15536

15537
15538
15539
15540

15541
15542
15543
15544
15545
15546
15547
15548
15549

15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568

15569
15570
15571
15572
15573
15574
15575
15576







-
+










-
-
-
+




-
+

-
+













-
+









-
+

-
+



-
+








-
+


















-
+







    fsl_stmt_finalize(s);
    break;
  }
  return rc;
}

int fsl_stmt_step( fsl_stmt * const stmt ){
  if(!stmt || !stmt->stmt) return FSL_RC_MISUSE;
  if(!stmt->stmt) return FSL_RC_MISUSE;
  else{
    int const rc = sqlite3_step(stmt->stmt);
    assert(stmt->db);
    switch( rc ){
      case SQLITE_ROW:
        ++stmt->rowCount;
        return FSL_RC_STEP_ROW;
      case SQLITE_DONE:
        return FSL_RC_STEP_DONE;
      default:
        return fsl_error_set(&stmt->db->error, FSL_RC_STEP_ERROR,
                             "sqlite3_step(): sqlite error #%d: %s",
                             rc, sqlite3_errmsg(stmt->db->dbh));
        return fsl__db_errcode(stmt->db, rc);
    }
  }
}

int fsl_db_eachv( fsl_db * db, fsl_stmt_each_f callback,
int fsl_db_eachv( fsl_db * const db, fsl_stmt_each_f callback,
                  void * callbackState, char const * sql, va_list args ){
  if(!db || !db->dbh || !callback || !sql) return FSL_RC_MISUSE;
  if(!db->dbh || !callback || !sql) return FSL_RC_MISUSE;
  else if(!*sql) return FSL_RC_RANGE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(!rc){
      rc = fsl_stmt_each( &st, callback, callbackState );
      fsl_stmt_finalize( &st );
    }
    return rc;
  }
}

int fsl_db_each( fsl_db * db, fsl_stmt_each_f callback,
int fsl_db_each( fsl_db * const db, fsl_stmt_each_f callback,
                 void * callbackState, char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_eachv( db, callback, callbackState, sql, args );
  va_end(args);
  return rc;
}

int fsl_stmt_each( fsl_stmt * stmt, fsl_stmt_each_f callback,
int fsl_stmt_each( fsl_stmt * const stmt, fsl_stmt_each_f callback,
                   void * callbackState ){
  if(!stmt || !callback) return FSL_RC_MISUSE;
  if(!callback) return FSL_RC_MISUSE;
  else{
    int strc;
    int rc = 0;
    char doBreak = 0;
    bool doBreak = false;
    while( !doBreak && (FSL_RC_STEP_ROW == (strc=fsl_stmt_step(stmt)))){
      rc = callback( stmt, callbackState );
      switch(rc){
        case 0: continue;
        case FSL_RC_BREAK:
          rc = 0;
          /* fall through */
        default:
          doBreak = 1;
          doBreak = true;
          break;
      }
    }
    return rc
      ? rc
      : ((FSL_RC_STEP_ERROR==strc)
         ? FSL_RC_DB
         : 0);
  }
}

int fsl_stmt_reset2( fsl_stmt * const stmt, bool resetRowCounter ){
  if(!stmt->stmt || !stmt->db) return FSL_RC_MISUSE;
  else{
    int const rc = sqlite3_reset(stmt->stmt);
    if(resetRowCounter) stmt->rowCount = 0;
    assert(stmt->db);
    return rc
      ? fsl_err_from_db(stmt->db, rc)
      ? fsl__db_errcode(stmt->db, rc)
      : 0;
  }
}

int fsl_stmt_reset( fsl_stmt * const stmt ){
  return fsl_stmt_reset2(stmt, 0);
}
15400
15401
15402
15403
15404
15405
15406
15407

15408
15409
15410
15411
15412
15413
15414

15415
15416
15417
15418
15419
15420
15421

15422
15423
15424
15425
15426
15427
15428

15429
15430
15431
15432
15433
15434
15435

15436
15437
15438
15439
15440
15441
15442
15443
15444
15445

15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456

15457
15458
15459
15460
15461
15462
15463
15715
15716
15717
15718
15719
15720
15721

15722
15723
15724
15725
15726
15727
15728

15729
15730
15731
15732
15733
15734
15735

15736
15737
15738
15739
15740
15741
15742

15743
15744
15745
15746
15747
15748
15749

15750
15751
15752
15753
15754
15755
15756
15757
15758
15759

15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770

15771
15772
15773
15774
15775
15776
15777
15778







-
+






-
+






-
+






-
+






-
+









-
+










-
+







#define BIND_PARAM_CHECK \
  if(!(stmt && stmt->stmt && stmt->db && stmt->db->dbh)) return FSL_RC_MISUSE; else
#define BIND_PARAM_CHECK2 BIND_PARAM_CHECK \
  if(ndx<1 || ndx>stmt->paramCount) return FSL_RC_RANGE; else
int fsl_stmt_bind_null( fsl_stmt * const stmt, int ndx ){
  BIND_PARAM_CHECK2 {
    int const rc = sqlite3_bind_null( stmt->stmt, ndx );
    return rc ? fsl_err_from_db(stmt->db, rc) : 0;
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_int32( fsl_stmt * const stmt, int ndx, int32_t v ){
  BIND_PARAM_CHECK2 {
    int const rc = sqlite3_bind_int( stmt->stmt, ndx, (int)v );
    return rc ? fsl_err_from_db(stmt->db, rc) : 0;
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_int64( fsl_stmt * const stmt, int ndx, int64_t v ){
  BIND_PARAM_CHECK2 {
    int const rc = sqlite3_bind_int64( stmt->stmt, ndx, (sqlite3_int64)v );
    return rc ? fsl_err_from_db(stmt->db, rc) : 0;
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_id( fsl_stmt * const stmt, int ndx, fsl_id_t v ){
  BIND_PARAM_CHECK2 {
    int const rc = sqlite3_bind_int64( stmt->stmt, ndx, (sqlite3_int64)v );
    return rc ? fsl_err_from_db(stmt->db, rc) : 0;
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_double( fsl_stmt * const stmt, int ndx, double v ){
  BIND_PARAM_CHECK2 {
    int const rc = sqlite3_bind_double( stmt->stmt, ndx, (double)v );
    return rc ? fsl_err_from_db(stmt->db, rc) : 0;
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_blob( fsl_stmt * const stmt, int ndx, void const * src,
                        fsl_size_t len, bool makeCopy ){
  BIND_PARAM_CHECK2 {
    int rc;
    rc = sqlite3_bind_blob( stmt->stmt, ndx, src, (int)len,
                            makeCopy ? SQLITE_TRANSIENT : SQLITE_STATIC );
    return rc ? fsl_err_from_db(stmt->db, rc) : 0;
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_text( fsl_stmt * const stmt, int ndx, char const * src,
                        fsl_int_t len, bool makeCopy ){
  BIND_PARAM_CHECK {
    int rc;
    if(len<0) len = fsl_strlen((char const *)src);
    rc = sqlite3_bind_text( stmt->stmt, ndx, src, len,
                            makeCopy ? SQLITE_TRANSIENT : SQLITE_STATIC );
    return rc ? fsl_err_from_db(stmt->db, rc) : 0;
    return rc ? fsl__db_errcode(stmt->db, rc) : 0;
  }
}

int fsl_stmt_bind_null_name( fsl_stmt * const stmt, char const * param ){
  BIND_PARAM_CHECK{
    return fsl_stmt_bind_null( stmt,
                               sqlite3_bind_parameter_index( stmt->stmt,
15571
15572
15573
15574
15575
15576
15577
15578

15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596

15597
15598
15599
15600
15601
15602
15603
15886
15887
15888
15889
15890
15891
15892

15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910

15911
15912
15913
15914
15915
15916
15917
15918







-
+

















-
+







      ? sqlite3_column_text(stmt->stmt, ndx)
      : NULL;
    if(out) *out = (char const *)t;
    if(outLen){
      int const x = sqlite3_column_bytes(stmt->stmt, ndx);
      *outLen = (x>0) ? (fsl_size_t)x : 0;
    }
    return 0;
    return t ? 0 : fsl__db_errcode(stmt->db, 0);
  }
}

int fsl_stmt_get_blob( fsl_stmt * const stmt, int ndx, void const **out,
                       fsl_size_t * outLen ){
  GET_CHECK {
    void const * t = (out || outLen)
      ? sqlite3_column_blob(stmt->stmt, ndx)
      : NULL;
    if(out) *out = t;
    if(outLen){
      if(!t) *outLen = 0;
      else{
        int sz = sqlite3_column_bytes(stmt->stmt, ndx);
        *outLen = (sz>=0) ? (fsl_size_t)sz : 0;
      }
    }
    return 0;
    return t ? 0 : fsl__db_errcode(stmt->db, 0);
  }
}

#undef GET_CHECK

fsl_id_t fsl_stmt_g_id( fsl_stmt * const stmt, int index ){
  fsl_id_t rv = -1;
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634



15635
15636
15637
15638
15639
15640
15641
15642
15643
15644

15645
15646
15647

15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666

15667
15668
15669
15670
15671
15672
15673
15674
15675

15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710

15711
15712
15713
15714
15715
15716


15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741

15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760

15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878


15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896

15897
15898
15899

15900
15901
15902

15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918

15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939

15940
15941
15942
15943
15944

15945
15946
15947

15948
15949
15950

15951
15952
15953
15954
15955

15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974


15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105

16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116

16117
16118
16119
16120

16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147










16148
16149
16150
16151
16152
16153
16154
16155
15940
15941
15942
15943
15944
15945
15946



15947
15948
15949










15950



15951



















15952









15953



































15954






15955
15956

























15957



















15958






















































































































15959
15960


















15961



15962



15963
















15964





















15965





15966



15967



15968





15969



















15970
15971









































































15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990

























15991
15992
15993
15994
15995
15996
15997
15998






15999
16000
16001
16002
16003
16004
16005
16006
16007
16008


16009

16010
16011

16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026













16027
16028
16029
16030
16031
16032
16033
16034
16035
16036

16037
16038
16039
16040
16041
16042
16043







-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
+
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
+
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
+
-
-
-
+
-
-
-
+
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-



















-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-








-
-
-
-
-
-
+









-
-
+
-


-
+














-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-







  char const * rv = NULL;
  fsl_stmt_get_text(stmt, index, &rv, outLen);
  return rv;
}


/**
   This function outputs tracing info using fsl_fprintf((FILE*)zFILE,...).
   Defaults to stdout if zFILE is 0.
 */
   This sqlite3_trace_v2() callback outputs tracing info using
   fsl_fprintf((FILE*)c,...).  Defaults to stdout if c is NULL.
*/
static void fsl_db_sql_trace(void *zFILE, const char *zSql){
  int const n = fsl_strlen(zSql);
  static int counter = 0;
  /* FIXME: in v1 this uses fossil_trace(), but don't have
     that functionality here yet. */
  fsl_fprintf(zFILE ? (FILE*)zFILE : stdout,
              "SQL TRACE #%d: %s%s\n", ++counter,
              zSql, (n>0 && zSql[n-1]==';') ? "" : ";");
}

static int fsl__db_sq3TraceV2(unsigned t,void*c,void*p,void*x){
/*
   SQL function for debugging.
  
  static unsigned int counter = 0;
   The print() function writes its arguments to fsl_output()
   if the bound fsl_cx->cxConfig.sqlPrint flag is true.
*/
static void fsl_db_sql_print(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  assert(f);
  if( f->cxConfig.sqlPrint ){
    int i;
    for(i=0; i<argc; i++){
      char c = i==argc-1 ? '\n' : ' ';
      fsl_outputf(f, "%s%c", sqlite3_value_text(argv[i]), c);
    }
  }
}

  if(c ||p){/*unused*/}
/*
   SQL function to return the number of seconds since 1970.  This is
   the same as strftime('%s','now') but is more compact.
*/
static void fsl_db_now_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  switch(t){
  sqlite3_result_int64(context, (sqlite3_int64)time(0));
}

/*
   SQL function to convert a Julian Day to a Unix timestamp.
*/
static void fsl_db_j2u_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  double const jd = (double)sqlite3_value_double(argv[0]);
  sqlite3_result_int64(context, (sqlite3_int64)fsl_julian_to_unix(jd));
}

/*
   SQL function FSL_CKOUT_DIR([bool includeTrailingSlash=1]) returns
   the top-level checkout directory, optionally (by default) with a
   trailing slash. Returns NULL if the fsl_cx instance bound to
   sqlite3_user_data() has no checkout.
*/
static void fsl_db_cx_chkout_dir_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  int const includeSlash = argc
    ? sqlite3_value_int(argv[0])
    : 1;
  if(f && f->ckout.dir && f->ckout.dirLen){
    sqlite3_result_text(context, f->ckout.dir,
                        (int)f->ckout.dirLen
                        - (includeSlash ? 0 : 1),
                        SQLITE_TRANSIENT);
    case SQLITE_TRACE_STMT:{
  }else{
    sqlite3_result_null(context);
  }
}


      char const * zSql = (char const *)x;
      char * zExp = zSql
/**
    SQL Function to return the check-in time for a file.
    Requires (vid,fid) RID arguments, as described for
    fsl_mtime_of_manifest_file().
 */
static void fsl_db_checkin_mtime_udf(
                                     sqlite3_context *context,
                                     int argc,
                                     sqlite3_value **argv
){
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  fsl_time_t mtime = 0;
  int rc;
  fsl_id_t vid, fid;
  assert(f);
  vid = (fsl_id_t)sqlite3_value_int(argv[0]);
  fid = (fsl_id_t)sqlite3_value_int(argv[1]);
  rc = fsl_mtime_of_manifest_file(f, vid, fid, &mtime);
  if( rc==0 ){
    sqlite3_result_int64(context, mtime);
  }else{
    sqlite3_result_error(context, "fsl_mtime_of_manifest_file() failed", -1); 
  }
}

        ? sqlite3_expanded_sql((sqlite3_stmt*)p)

static void fsl_db_content_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  fsl_id_t rid = 0;
  char const * arg;
  int rc;
  fsl_buffer b = fsl_buffer_empty;
  assert(f);
  if(1 != argc){
    sqlite3_result_error(context, "Expecting one argument", -1);
    return;
  }
  if(SQLITE_INTEGER==sqlite3_value_type(argv[0])){
    rid = (fsl_id_t)sqlite3_value_int64(argv[0]);
    arg = NULL;
        : NULL;
  }else{
    arg = (const char*)sqlite3_value_text(argv[0]);
    if(!arg){
      sqlite3_result_error(context, "Invalid argument", -1);
      return;
    }
    rc = fsl_sym_to_rid(f, arg, FSL_SATYPE_CHECKIN, &rid);
    if(rc) goto cx_err;
    else if(!rid){
      sqlite3_result_error(context, "No blob found", -1);
      return;
    }
  }
  rc = fsl_content_get(f, rid, &b);
  if(rc) goto cx_err;
  /* Curiously, i'm seeing no difference in allocation counts here... */
  sqlite3_result_blob(context, b.mem, (int)b.used, fsl_free);
  b = fsl_buffer_empty;
  return;
  cx_err:
  fsl_buffer_clear(&b);
  assert(f->error.msg.used);
  if(FSL_RC_OOM==rc){
    sqlite3_result_error_nomem(context);
  }else{
    assert(f->error.msg.used);
    sqlite3_result_error(context, (char const *)f->error.msg.mem,
                         (int)f->error.msg.used);
  }
}

static void fsl_db_sym2rid_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  char const * arg;
  assert(f);
  if(1 != argc){
    sqlite3_result_error(context, "Expecting one argument", -1);
    return;
  }
  arg = (const char*)sqlite3_value_text(argv[0]);
  if(!arg){
    sqlite3_result_error(context, "Expecting a STRING argument", -1);
  }else{
    fsl_id_t rid = 0;
    int const rc = fsl_sym_to_rid(f, arg, FSL_SATYPE_CHECKIN, &rid);
    if(rc){
      if(FSL_RC_OOM==rc){
        sqlite3_result_error_nomem(context);
      }else{
        assert(f->error.msg.used);
        sqlite3_result_error(context, (char const *)f->error.msg.mem,
                             (int)f->error.msg.used);
      }
      fsl_cx_err_reset(f)
        /* This is arguable but keeps this error from poluting
           down-stream code (seen it happen in unit tests).  The irony
           is, it's very possible/likely that the error will propagate
           back up into f->error at some point.
        */;
    }else{
      assert(rid>0);
      sqlite3_result_int64(context, rid);
    }
  }
}

static void fsl_db_dirpart_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  char const * arg;
  int rc;
  fsl_buffer b = fsl_buffer_empty;
  int fSlash = 0;
  if(argc<1 || argc>2){
    sqlite3_result_error(context,
                         "Expecting (string) or (string,bool) arguments",
                         -1);
    return;
  }
  arg = (const char*)sqlite3_value_text(argv[0]);
  if(!arg){
    sqlite3_result_error(context, "Invalid argument", -1);
    return;
  }
  if(argc>1){
    fSlash = sqlite3_value_int(argv[1]);
  }
  rc = fsl_file_dirpart(arg, -1, &b, fSlash ? 1 : 0);
  if(!rc){
    if(b.used && *b.mem){
#if 0
      sqlite3_result_text(context, (char const *)b.mem,
                          (int)b.used, SQLITE_TRANSIENT);
#else
      sqlite3_result_text(context, (char const *)b.mem,
                          (int)b.used, fsl_free);
      b = fsl_buffer_empty /* we passed ^^^^^ on ownership of b.mem */;
#endif
    }else{
      sqlite3_result_null(context);
    }
  }else{
    if(FSL_RC_OOM==rc){
      sqlite3_result_error_nomem(context);
    }else{
      sqlite3_result_error(context, "fsl_dirpart() failed!", -1);
    }
  }
  fsl_buffer_clear(&b);
}


      fsl_fprintf(c ? (FILE*)c : stdout,
                  "SQL TRACE #%u: %s\n",
/*
   Implement the user() SQL function.  user() takes no arguments and
   returns the user ID of the current user.
*/
static void fsl_db_user_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  assert(f);
  if(f->repo.user){
    sqlite3_result_text(context, f->repo.user, -1, SQLITE_STATIC);
  }else{
    sqlite3_result_null(context);
  }
}

                  ++counter,
/**
   SQL function:

                  zExp ? zExp :
   fsl_is_enqueued(vfile.id)
   fsl_if_enqueued(vfile.id, X, Y)

                  (zSql ? zSql : "(NO SQL?)"));
   On the commit command, when filenames are specified (in order to do
   a partial commit) the vfile.id values for the named files are
   loaded into the fsl_cx state.  This function looks at that state to
   see if a file is named in that list.

   In the first form (1 argument) return TRUE if either no files are
   named (meaning that all changes are to be committed) or if id is
   found in the list.

   In the second form (3 arguments) return argument X if true and Y if
   false unless Y is NULL, in which case always return X.
*/
static void fsl_db_selected_for_checkin_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
      sqlite3_free(zExp);
){
  int rc = 0;
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  fsl_id_bag * bag = &f->ckin.selectedIds;
  assert(argc==1 || argc==3);
  if( bag->entryCount ){
    fsl_id_t const iId = (fsl_id_t)sqlite3_value_int64(argv[0]);
    rc = iId ? (fsl_id_bag_contains(bag, iId) ? 1 : 0) : 0;
  }else{
    rc = 1;
  }
  if(1==argc){
    sqlite3_result_int(context, rc);
  }else{
    assert(3 == argc);
    assert( rc==0 || rc==1 );
    if( sqlite3_value_type(argv[2-rc])==SQLITE_NULL ) rc = 1-rc;
    sqlite3_result_value(context, argv[2-rc]);
  }
}

      break;
/**
   fsl_match_vfile_or_dir(p1,p2)

   A helper for resolving expressions like:

    }
   WHERE pathname='X' C OR
      (pathname>'X/' C AND pathname<'X0' C)

    default:
   i.e. is 'X' a match for the LHS or is it a directory prefix of
   LHS?

      break;
   C = empty or COLLATE NOCASE, depending on the case-sensitivity
   setting of the fsl_cx instance associated with
   sqlite3_user_data(context). p1 is typically vfile.pathname or
   vfile.origname, and p2 is the string being compared against that.

  }
   Resolves to NULL if either argument is NULL, 0 if the comparison
   shown above is false, 1 if the comparison is an exact match, or 2
   if p2 is a directory prefix part of p1.
*/
static void fsl_db_match_vfile_or_dir(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  char const * p1;
  char const * p2;
  fsl_buffer * b = 0;
  int rc = 0;
  assert(f);
  if(2 != argc){
    sqlite3_result_error(context, "Expecting two arguments", -1);
    return;
  }
  return 0;
}
  p1 = (const char*)sqlite3_value_text(argv[0]);
  p2 = (const char*)sqlite3_value_text(argv[1]);
  if(!p1 || !p2){
    sqlite3_result_null(context);
    return;
  }
  int (*cmp)(char const *, char const *) =
    f->cache.caseInsensitive ? fsl_stricmp : fsl_strcmp;
  if(0==cmp(p1, p2)){
    sqlite3_result_int(context, 1);
    return;
  }
  b = fsl__cx_scratchpad(f);
  rc = fsl_buffer_appendf(b, "%s/", p2);
  if(rc) goto oom;
  else if(cmp(p1, fsl_buffer_cstr(b))>0){
    b->mem[b->used-1] = '0';
    if(cmp(p1, fsl_buffer_cstr(b))<0)
    rc = 2;
  }
  assert(0==rc || 2==rc);
  sqlite3_result_int(context, rc);
  end:
  fsl__cx_scratchpad_yield(f, b);
  return;
  oom:
  sqlite3_result_error_nomem(context);
  goto end;
}

/**
   F(glob-list-name, filename)

   Returns 1 if the 2nd argument matches any glob in the fossil glob
   list named by the first argument. The first argument must be a name
   resolvable via fsl_glob_name_to_category() or an error is
   triggered. The second value is intended to be a string, but NULL is
   accepted (but never matches anything).

   If no match is found, 0 is returned. An empty glob list never matches
   anything.
*/
static void fsl_db_cx_glob_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * const f = (fsl_cx*)sqlite3_user_data(context);
  fsl_list * li = NULL;
  fsl_glob_category_e globType;
  char const * p1;
  char const * p2;
  p2 = (const char*)sqlite3_value_text(argv[1])/*value to check*/;
  if(NULL==p2 || 0==p2[0]){
    sqlite3_result_int(context, 0);
    return;
  }
  p1 = (const char*)sqlite3_value_text(argv[0])/*glob set name*/;
  globType  = fsl_glob_name_to_category(p1);
  if(FSL_GLOBS_INVALID==globType){
    char buf[100] = {0};
    buf[sizeof(buf)-1] = 0;
    fsl_snprintf(buf, (fsl_size_t)sizeof(buf)-1,
                 "Unknown glob pattern name: %#.*s",
                 50, p1 ? p1 : "NULL");
    sqlite3_result_error(context, buf, -1);
    return;
  }
  fsl_cx_glob_list(f, globType, &li, false);
  assert(li);
  sqlite3_result_int(context, fsl_glob_list_matches(li, p2) ? 1 : 0);
}


fsl_db * fsl_db_malloc(){
  fsl_db * rc = (fsl_db *)fsl_malloc(sizeof(fsl_db));
  if(rc){
    *rc = fsl_db_empty;
    rc->allocStamp = &fsl_db_empty;
  }
  return rc;
}

fsl_stmt * fsl_stmt_malloc(){
  fsl_stmt * rc = (fsl_stmt *)fsl_malloc(sizeof(fsl_stmt));
  if(rc){
    *rc = fsl_stmt_empty;
    rc->allocStamp = &fsl_stmt_empty;
  }
  return rc;
}


/**
    Return true if the schema is out-of-date. db must be an opened
    repo db.
 */
static char fsl_db_repo_schema_is_outofdate(fsl_db *db){
  return fsl_db_exists(db, "SELECT 1 FROM config "
                       "WHERE name='aux-schema' "
                       "AND value<>'%s'",
                       FSL_AUX_SCHEMA);
}

/*
   Returns 0 if db appears to have a current repository schema, 1 if
   it appears to have an out of date schema, and -1 if it appears to
   not be a repository.
*/
int fsl__db_repo_verify_schema(fsl_db * db){
  if(fsl_db_repo_schema_is_outofdate(db)) return 1;
  else return fsl_db_exists(db,
                            "SELECT 1 FROM config "
                            "WHERE name='project-code'")
    ? 0 : -1;
}

/**
   Callback for use with sqlite3_commit_hook(). The argument must be a
   (fsl_db*). This function returns 0 only if it surmises that
   fsl_db_transaction_end() triggered the COMMIT. On error it might
   assert() or abort() the application, so this really is just a
   sanity check for something which "must not happen."
*/
static int fsl_db_verify_begin_was_not_called(void * db_fsl){
#if 0
  return 0;
#else
  /* i cannot explain why, but the ptr i'm getting here is most definately
     not a proper fsl_db. */
  fsl_db * db = (fsl_db *)db_fsl;
  fsl_db * const db = (fsl_db *)db_fsl;
  assert(db && "What else could it be?");
  assert(db->dbh && "Else we can't have been called by sqlite3, could we have?");
  if(db->beginCount>0){
    fsl__fatal(FSL_RC_MISUSE,"SQL: COMMIT was called from "
              "outside of fsl_db_transaction_end() while a "
              "fsl_db_transaction_begin()-started transaction "
              "is pending.");
    return 2;
  }
  /* we have no context: sqlite3_result_error(context, "fsl_mtime_of_manifest_file() failed", -1);  */
  else return 0;
  return 0;
#endif
}

int fsl_db_open( fsl_db * db, char const * dbFile,
int fsl_db_open( fsl_db * const db, char const * dbFile,
                 int openFlags ){
  int rc;
  fsl_dbh_t * dbh = NULL;
  int isMem = 0;
  if(!db || !dbFile) return FSL_RC_MISUSE;
  else if(db->dbh) return FSL_RC_MISUSE;
  else if(!(isMem = (!*dbFile || 0==fsl_strcmp(":memory:", dbFile)))
          && !(FSL_OPEN_F_CREATE & openFlags)
          && fsl_file_access(dbFile, 0)){
    return fsl_error_set(&db->error, FSL_RC_NOT_FOUND,
                         "DB file not found: %s", dbFile);
  }
  else{
    int sOpenFlags = 0;
    if(isMem){
      sOpenFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
    }else{
      if(FSL_OPEN_F_RO & openFlags){
        sOpenFlags |= SQLITE_OPEN_READONLY;
      }else{
        if(FSL_OPEN_F_RW & openFlags){
          sOpenFlags |= SQLITE_OPEN_READWRITE;
        }
        if(FSL_OPEN_F_CREATE & openFlags){
          sOpenFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
        }
        if(!sOpenFlags) sOpenFlags = SQLITE_OPEN_READONLY;
    if(FSL_OPEN_F_RO & openFlags){
      sOpenFlags |= SQLITE_OPEN_READONLY;
    }else{
      if(FSL_OPEN_F_RW & openFlags){
        sOpenFlags |= SQLITE_OPEN_READWRITE;
      }
      if(FSL_OPEN_F_CREATE & openFlags){
        sOpenFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
      }
      if(!sOpenFlags) sOpenFlags = SQLITE_OPEN_READONLY;
      }
    }
    rc = sqlite3_open_v2( dbFile, &dbh, sOpenFlags, NULL );
    if(rc){
      if(dbh){
        /* By some complete coincidence, FSL_RC_DB==SQLITE_CANTOPEN. */
        rc = fsl_error_set(&db->error, FSL_RC_DB,
                           "Opening db file [%s] failed with "
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204

16205
16206
16207
16208


16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306










16307
16308


16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324

16325
16326
16327
16328
16329
16330

16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341


16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353


16354
16355
16356
16357
16358

16359
16360
16361
16362
16363
16364











16365
16366
16367
16368
16369


16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381

16382
16383
16384
16385
16386
16387

16388
16389
16390
16391
16392
16393
16394
16071
16072
16073
16074
16075
16076
16077















16078




16079
16080

16081
16082











































































16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113

16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130

16131
16132
16133
16134
16135
16136

16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147

16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160

16161
16162
16163
16164
16165
16166

16167






16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182

16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195

16196
16197
16198
16199
16200
16201

16202
16203
16204
16205
16206
16207
16208
16209







-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
+
+
-


-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-




















+
+
+
+
+
+
+
+
+
+

-
+
+















-
+





-
+










-
+
+











-
+
+




-
+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+




-
+
+











-
+





-
+







        goto end;
      }else if(!db->filename){
        rc = FSL_RC_OOM;
        goto end;
      }
    }
    db->dbh = dbh;
    if(FSL_OPEN_F_SCHEMA_VALIDATE & openFlags){
      int check;
      check = fsl__db_repo_verify_schema(db);
      if(0 != check){
        rc = (check<0)
          ? fsl_error_set(&db->error, FSL_RC_NOT_A_REPO,
                          "DB file [%s] does not appear to be "
                          "a repository.", dbFile)
          : fsl_error_set(&db->error, FSL_RC_REPO_NEEDS_REBUILD,
                          "DB file [%s] appears to be a fossil "
                          "repsitory, but is out-of-date and needs "
                          "a rebuild.",
                          dbFile);
        assert(rc == db->error.code);
        goto end;
    sqlite3_extended_result_codes(dbh, 1);
      }
    }

    if( (openFlags & FSL_OPEN_F_TRACE_SQL)
    sqlite3_commit_hook(dbh, fsl_db_verify_begin_was_not_called, db);
    if(FSL_OPEN_F_TRACE_SQL & openFlags){
        || (db->f && db->f->cxConfig.traceSql) ){
      fsl_db_sqltrace_enable(db, stdout);
    }

    if(db->f){
      /*
        Plug in fsl_cx-specific functionality to this one.

        TODO: move this into the fsl_cx code. Its placement here is
        largely historical.
      */
      fsl_cx * f = db->f;
      /* This all comes from db.c:db_open()... */
      /* FIXME: check result codes here. */
      sqlite3_commit_hook(dbh, fsl_db_verify_begin_was_not_called, db);
      sqlite3_busy_timeout(dbh, 5000 /* historical value */);
      sqlite3_wal_autocheckpoint(dbh, 1);  /* Set to checkpoint frequently */
      sqlite3_exec(dbh, "PRAGMA foreign_keys=OFF;", 0, 0, 0);
      sqlite3_create_function(dbh, "now", 0, SQLITE_ANY, 0,
                              fsl_db_now_udf, 0, 0);
      sqlite3_create_function(dbh, "fsl_ci_mtime", 2,
                              SQLITE_ANY | SQLITE_DETERMINISTIC, f,
                              fsl_db_checkin_mtime_udf, 0, 0);
      sqlite3_create_function(dbh, "fsl_user", 0,
                              SQLITE_ANY | SQLITE_DETERMINISTIC, f,
                              fsl_db_user_udf, 0, 0);
      sqlite3_create_function(dbh, "fsl_print", -1,
                              SQLITE_UTF8
                              /* not strictly SQLITE_DETERMINISTIC
                                 because it produces output */,
                              f, fsl_db_sql_print,0,0);
      sqlite3_create_function(dbh, "fsl_content", 1,
                              SQLITE_ANY | SQLITE_DETERMINISTIC, f,
                              fsl_db_content_udf, 0, 0);
      sqlite3_create_function(dbh, "fsl_sym2rid", 1,
                              SQLITE_ANY | SQLITE_DETERMINISTIC, f,
                              fsl_db_sym2rid_udf, 0, 0);
      sqlite3_create_function(dbh, "fsl_dirpart", 1,
                              SQLITE_ANY | SQLITE_DETERMINISTIC, NULL,
                              fsl_db_dirpart_udf, 0, 0);
      sqlite3_create_function(dbh, "fsl_dirpart", 2,
                              SQLITE_ANY | SQLITE_DETERMINISTIC, NULL,
                              fsl_db_dirpart_udf, 0, 0);
      sqlite3_create_function(dbh, "fsl_j2u", 1,
                              SQLITE_ANY | SQLITE_DETERMINISTIC, NULL,
                              fsl_db_j2u_udf, 0, 0);
      /*
        fsl_i[sf]_selected() both require access to the f's list of
        files being considered for commit.
      */
      sqlite3_create_function(dbh, "fsl_is_enqueued", 1, SQLITE_UTF8, f,
                              fsl_db_selected_for_checkin_udf,0,0 );
      sqlite3_create_function(dbh, "fsl_if_enqueued", 3, SQLITE_UTF8, f,
                              fsl_db_selected_for_checkin_udf,0,0 );

      sqlite3_create_function(dbh, "fsl_ckout_dir", -1,
                              SQLITE_ANY /* | SQLITE_DETERMINISTIC ? */,
                              f, fsl_db_cx_chkout_dir_udf,0,0 );
      sqlite3_create_function(dbh, "fsl_match_vfile_or_dir", 2,
                              SQLITE_ANY | SQLITE_DETERMINISTIC,
                              f, fsl_db_match_vfile_or_dir,0,0 );
      sqlite3_create_function(dbh, "fsl_glob", 2,
                              SQLITE_UTF8 | SQLITE_DETERMINISTIC,
                              /* noting that ^^^^^ it's only deterministic
                                 for a given statement execution IF no SQL
                                 triggers an effect which forces the globs to
                                 reload. That "shouldn't ever happen." */
                              f, fsl_db_cx_glob_udf, 0, 0 );

#if 0
      /* functions registered in v1 by db.c:db_open(). */
      /* porting cgi() requires access to the HTTP/CGI
         layer. i.e. this belongs downstream. */
      sqlite3_create_function(dbh, "cgi", 1, SQLITE_ANY, 0, db_sql_cgi, 0, 0);
      sqlite3_create_function(dbh, "cgi", 2, SQLITE_ANY, 0, db_sql_cgi, 0, 0);
      re_add_sql_func(db) /* Requires the regex bits. */;
#endif
    }/*if(db->f)*/
  }
  end:
  if(rc){
#if 1
    /* This is arguable... */
    if(db->f && db->error.code && !db->f->error.code){
      /* COPY db's error state as f's. */
      fsl_error_copy( &db->error, &db->f->error );
    }
#endif
    if(dbh){
      sqlite3_close(dbh);
      db->dbh = NULL;
    }
  }else{
    assert(db->dbh);
  }
  return rc;
}


static int fsl__db_err_not_opened(fsl_db * const db){
  return fsl_error_set(&db->error, FSL_RC_MISUSE,
                       "DB is not opened.");
}
static int fsl__db_err_sql_empty(fsl_db * const db){
  return fsl_error_set(&db->error, FSL_RC_MISUSE,
                       "Empty SQL is not permitted.");
 }

int fsl_db_exec_multiv( fsl_db * const db, const char * sql, va_list args){
  if(!db || !db->dbh || !sql) return FSL_RC_MISUSE;
  if(!db->dbh) return fsl__db_err_not_opened(db);
  else if(!sql || !*sql) return fsl__db_err_sql_empty(db);
  else{
    fsl_buffer buf = fsl_buffer_empty;
    int rc = 0;
    char const * z;
    char const * zEnd = NULL;
    rc = fsl_buffer_appendfv( &buf, sql, args );
    if(rc){
      fsl_buffer_clear(&buf);
      return rc;
    }
    z = fsl_buffer_cstr(&buf);
    while( (SQLITE_OK==rc) && *z ){
      fsl_stmt_t * pStmt = NULL;
      rc = sqlite3_prepare_v2(db->dbh, z, buf.used, &pStmt, &zEnd);
      if( SQLITE_OK != rc ){
        rc = fsl_err_from_db(db, rc);
        rc = fsl__db_errcode(db, rc);
        break;
      }
      if(pStmt){
        while( SQLITE_ROW == sqlite3_step(pStmt) ){}
        rc = sqlite3_finalize(pStmt);
        if(rc) rc = fsl_err_from_db(db, rc);
        if(rc) rc = fsl__db_errcode(db, rc);
      }
      buf.used -= (zEnd-z);
      z = zEnd;
    }
    fsl_buffer_reserve(&buf, 0);
    return rc;
  }
}

int fsl_db_exec_multi( fsl_db * const db, const char * sql, ...){
  if(!db || !db->dbh || !sql) return FSL_RC_MISUSE;
  if(!db->dbh) return fsl__db_err_not_opened(db);
  else if(!sql || !*sql) return fsl__db_err_sql_empty(db);
  else{
    int rc;
    va_list args;
    va_start(args,sql);
    rc = fsl_db_exec_multiv( db, sql, args );
    va_end(args);
    return rc;
  }
}

int fsl_db_execv( fsl_db * const db, const char * sql, va_list args){
  if(!db || !db->dbh || !sql) return FSL_RC_MISUSE;
  if(!db->dbh) return fsl__db_err_not_opened(db);
  else if(!sql || !*sql) return fsl__db_err_sql_empty(db);
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
    if(0==rc){
    /* rc = fsl_stmt_step( &st ); */
    while(FSL_RC_STEP_ROW == (rc=fsl_stmt_step(&st))){}
    fsl_stmt_finalize(&st);
    return (FSL_RC_STEP_ERROR==rc)
      ? FSL_RC_DB
      : 0;
      //while(FSL_RC_STEP_ROW == (rc=fsl_stmt_step(&st))){}
      //^^^ why did we historically do this instead of:
      rc = fsl_stmt_step( &st );
      fsl_stmt_finalize(&st);
    }
    switch(rc){
      case FSL_RC_STEP_DONE:
      case FSL_RC_STEP_ROW: rc = 0; break;
      default: break;
    }
    return rc;
  }
}

int fsl_db_exec( fsl_db * const db, const char * sql, ...){
  if(!db || !db->dbh || !sql) return FSL_RC_MISUSE;
  if(!db->dbh) return fsl__db_err_not_opened(db);
  else if(!sql || !*sql) return fsl__db_err_sql_empty(db);
  else{
    int rc;
    va_list args;
    va_start(args,sql);
    rc = fsl_db_execv( db, sql, args );
    va_end(args);
    return rc;
  }
}

int fsl_db_changes_recent(fsl_db * const db){
  return (db && db->dbh)
  return db->dbh
    ? sqlite3_changes(db->dbh)
    : 0;
}

int fsl_db_changes_total(fsl_db * const db){
  return (db && db->dbh)
  return db->dbh
    ? sqlite3_total_changes(db->dbh)
    : 0;
}

/**
    Sets db->priorChanges to sqlite3_total_changes(db->dbh).
*/
16412
16413
16414
16415
16416
16417
16418
16419

16420
16421
16422
16423
16424
16425

16426
16427
16428
16429
16430
16431
16432



16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445



16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457


16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471














16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484


































16485
16486
16487
16488
16489
16490
16491
16227
16228
16229
16230
16231
16232
16233

16234
16235
16236
16237
16238
16239

16240
16241
16242
16243
16244
16245


16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259


16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276














16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291












16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332







-
+





-
+





-
-
+
+
+











-
-
+
+
+












+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







}

int fsl_db_transaction_level(fsl_db * const db){
  return db->doRollback ? -db->beginCount : db->beginCount;
}

int fsl_db_transaction_commit(fsl_db * const db){
  return (db && db->dbh)
  return db->dbh
    ? fsl_db_transaction_end(db, 0)
    : FSL_RC_MISUSE;
}

int fsl_db_transaction_rollback(fsl_db * const db){
  return (db && db->dbh)
  return db->dbh
    ? fsl_db_transaction_end(db, 1)
    : FSL_RC_MISUSE;
}

int fsl_db_rollback_force( fsl_db * const db ){
  if(!db || !db->dbh) return FSL_RC_MISUSE;
  else{
  if(!db->dbh){
    return fsl__db_err_not_opened(db);
  }else{
    int rc;
    db->beginCount = 0;
    fsl_db_cleanup_beforeCommit(db);
    rc = fsl_db_exec(db, "ROLLBACK");
    fsl_db_reset_change_count(db);
    return rc;
  }
}

int fsl_db_transaction_end(fsl_db * const db, bool doRollback){
  int rc = 0;
  if(!db || !db->dbh) return FSL_RC_MISUSE;
  else if (db->beginCount<=0){
  if(!db->dbh){
    return fsl__db_err_not_opened(db);
  }else if (db->beginCount<=0){
    return fsl_error_set(&db->error, FSL_RC_RANGE,
                         "No transaction is active.");
  }
  if(doRollback) ++db->doRollback
    /* ACHTUNG: note that db->dbRollback is set before
       continuing so that if we return due to a non-0 beginCount
       that the rollback flag propagates through the
       transaction's stack.
    */;
  if(--db->beginCount > 0) return 0;
  assert(0==db->beginCount && "The commit-hook check relies on this.");
  assert(db->doRollback>=0);
  int const changeCount =
    sqlite3_total_changes(db->dbh) - db->priorChanges;
  if((0==db->doRollback)
     && (db->priorChanges < sqlite3_total_changes(db->dbh))){
    /* Execute before-commit hooks and leaf checks */
    fsl_size_t x = 0;
    for( ; !rc && (x < db->beforeCommit.used); ++x ){
      char const * sql = (char const *)db->beforeCommit.list[x];
      /* MARKER(("Running before-commit code: [%s]\n", sql)); */
      if(sql) rc = fsl_db_exec_multi( db, "%s", sql );
    }
    if(!rc && db->f && (FSL_DBROLE_REPO & db->role)){
      /*
         i don't like this one bit - this is low-level SCM
         functionality in an otherwise generic routine. Maybe we need
         fsl_cx_transaction_begin/end() instead.
  if(0==db->doRollback){
    if(changeCount>0){
      /* Execute before-commit hooks and leaf checks */
      fsl_size_t x = 0;
      for( ; !rc && (x < db->beforeCommit.used); ++x ){
        char const * sql = (char const *)db->beforeCommit.list[x];
        /* MARKER(("Running before-commit code: [%s]\n", sql)); */
        if(sql) rc = fsl_db_exec_multi( db, "%s", sql );
      }
      if(!rc && db->f && (FSL_DBROLE_REPO & db->role)){
        /*
          i don't like this one bit - this is low-level SCM
          functionality in an otherwise generic routine. Maybe we need
          fsl_cx_transaction_begin/end() instead.

         Much later: we have that routine now but will need to replace
         all relevant calls to fsl_db_transaction_begin()/end() with
         those routines before we can consider moving this there.
      */
      rc = fsl__repo_leafdo_pending_checks(db->f);
      if(!rc && db->f->cache.toVerify.used){
        rc = fsl__repo_verify_at_commit(db->f);
      }else{
        fsl_repo_verify_cancel(db->f);
      }
    }
    db->doRollback = rc ? 1 : 0;
          Much later: we have that routine now but will need to replace
          all relevant calls to fsl_db_transaction_begin()/end() with
          those routines before we can consider moving this there.
        */
        rc = fsl__repo_leafdo_pending_checks(db->f);
        if(!rc && db->f->cache.toVerify.used){
          rc = fsl__repo_verify_at_commit(db->f);
        }else{
          fsl_repo_verify_cancel(db->f);
        }
      }
      db->doRollback = rc ? 1 : 0;
    }
  }
  if(db->doRollback && db->f && changeCount>0){
    /**
       If a rollback is underway (from a transaction in which data was
       written), certain fsl_cx caches might be referring to record
       IDs which were injected as part of the being-rolled-back
       transaction. The only(?) reasonably sane way to deal with that
       is to flush all relevant caches. It is unfortunate that this
       bit is in the db class, as opposed to the fsl_cx class, but we
       currently have no hook which would allow us to trigger this
       from that class.
    */
#if 1
    fsl__bccache_reset(&db->f->cache.blobContent);
    fsl__cx_mcache_clear(db->f);
#else
    /* This one resets all of ^^^ plus certain repo-side config
       settings, but it's not yet clear whether that they will be
       reloaded when needed. */
    fsl__cx_clear_repo_caches(d->f);
#endif
  }
  fsl_db_cleanup_beforeCommit(db);
  fsl_db_reset_change_count(db);
  rc = fsl_db_exec(db, db->doRollback ? "ROLLBACK" : "COMMIT");
  db->doRollback = 0;
  return rc;
#if 0
16552
16553
16554
16555
16556
16557
16558
16559

16560
16561
16562
16563
16564
16565
16566
16393
16394
16395
16396
16397
16398
16399

16400
16401
16402
16403
16404
16405
16406
16407







-
+







  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_int32v(db, rv, sql, args);
  va_end(args);
  return rc;
}

int fsl_db_get_int64v( fsl_db * db, int64_t * rv,
int fsl_db_get_int64v( fsl_db * const db, int64_t * rv,
                       char const * sql, va_list args){
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
16577
16578
16579
16580
16581
16582
16583
16584

16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595

16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620

16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631

16632
16633
16634
16635
16636
16637
16638
16418
16419
16420
16421
16422
16423
16424

16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435

16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452

16453
16454
16455
16456
16457
16458
16459

16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470

16471
16472
16473
16474
16475
16476
16477
16478







-
+










-
+
















-







-
+










-
+







        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_int64( fsl_db * db, int64_t * rv,
int fsl_db_get_int64( fsl_db * const db, int64_t * rv,
                      char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_int64v(db, rv, sql, args);
  va_end(args);
  return rc;
}


int fsl_db_get_idv( fsl_db * db, fsl_id_t * rv,
int fsl_db_get_idv( fsl_db * const db, fsl_id_t * rv,
                       char const * sql, va_list args){
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
    rc = fsl_stmt_step( &st );
    switch(rc){
      case FSL_RC_STEP_ROW:
        *rv = (fsl_id_t)sqlite3_column_int64(st.stmt, 0);
        /* Fall through */
      case FSL_RC_STEP_DONE:
        rc = 0;
        break;
      default:
        assert(FSL_RC_STEP_ERROR==rc);
        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_id( fsl_db * db, fsl_id_t * rv,
int fsl_db_get_id( fsl_db * const db, fsl_id_t * rv,
                      char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_idv(db, rv, sql, args);
  va_end(args);
  return rc;
}


int fsl_db_get_sizev( fsl_db * db, fsl_size_t * rv,
int fsl_db_get_sizev( fsl_db * const db, fsl_size_t * rv,
                      char const * sql, va_list args){
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
16656
16657
16658
16659
16660
16661
16662
16663

16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674

16675
16676
16677
16678
16679
16680
16681
16496
16497
16498
16499
16500
16501
16502

16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513

16514
16515
16516
16517
16518
16519
16520
16521







-
+










-
+







        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_size( fsl_db * db, fsl_size_t * rv,
int fsl_db_get_size( fsl_db * const db, fsl_size_t * rv,
                      char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_sizev(db, rv, sql, args);
  va_end(args);
  return rc;
}


int fsl_db_get_doublev( fsl_db * db, double * rv,
int fsl_db_get_doublev( fsl_db * const db, double * rv,
                       char const * sql, va_list args){
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
16692
16693
16694
16695
16696
16697
16698
16699

16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711

16712
16713
16714
16715
16716
16717
16718
16532
16533
16534
16535
16536
16537
16538

16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550

16551
16552
16553
16554
16555
16556
16557
16558







-
+











-
+







        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_double( fsl_db * db, double * rv,
int fsl_db_get_double( fsl_db * const db, double * rv,
                      char const * sql,
                      ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_doublev(db, rv, sql, args);
  va_end(args);
  return rc;
}


int fsl_db_get_textv( fsl_db * db, char ** rv,
int fsl_db_get_textv( fsl_db * const db, char ** rv,
                      fsl_size_t *rvLen,
                      char const * sql, va_list args){
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
16747
16748
16749
16750
16751
16752
16753
16754

16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765

16766
16767
16768
16769
16770
16771
16772
16587
16588
16589
16590
16591
16592
16593

16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604

16605
16606
16607
16608
16609
16610
16611
16612







-
+










-
+







        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_text( fsl_db * db, char ** rv,
int fsl_db_get_text( fsl_db * const db, char ** rv,
                     fsl_size_t * rvLen,
                     char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_textv(db, rv, rvLen, sql, args);
  va_end(args);
  return rc;
}

int fsl_db_get_blobv( fsl_db * db, void ** rv,
int fsl_db_get_blobv( fsl_db * const db, void ** rv,
                      fsl_size_t *rvLen,
                      char const * sql, va_list args){
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
16799
16800
16801
16802
16803
16804
16805
16806

16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818


16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832



16833
16834
16835




16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851


16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871

16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882

16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893

16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904

16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915

16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926

16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937

16938
16939
16940
16941
16942
16943
16944
16945
16946
16947

16948
16949
16950
16951
16952
16953
16954
16639
16640
16641
16642
16643
16644
16645

16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656


16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675



16676
16677
16678
16679
16680
16681
16682
16683
16684
16685

16686
16687
16688
16689
16690
16691
16692


16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713

16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724

16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735

16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746

16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757

16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768

16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779

16780
16781
16782
16783
16784
16785
16786
16787
16788
16789

16790
16791
16792
16793
16794
16795
16796
16797







-
+










-
-
+
+














+
+
+
-
-
-
+
+
+
+






-







-
-
+
+



















-
+










-
+










-
+










-
+










-
+










-
+










-
+









-
+







        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_blob( fsl_db * db, void ** rv,
int fsl_db_get_blob( fsl_db * const db, void ** rv,
                     fsl_size_t * rvLen,
                     char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_blobv(db, rv, rvLen, sql, args);
  va_end(args);
  return rc;
}

int fsl_db_get_bufferv( fsl_db * db, fsl_buffer * b,
                        char asBlob, char const * sql,
int fsl_db_get_bufferv( fsl_db * const db, fsl_buffer * const b,
                        bool asBlob, char const * sql,
                        va_list args){
  if(!db || !db->dbh || !b || !sql || !*sql) return FSL_RC_MISUSE;
  else{
    fsl_stmt st = fsl_stmt_empty;
    int rc = 0;
    rc = fsl_db_preparev( db, &st, sql, args );
    if(rc) return rc;
    rc = fsl_stmt_step( &st );
    switch(rc){
      case FSL_RC_STEP_ROW:{
        void const * str = asBlob
          ? sqlite3_column_blob(st.stmt, 0)
          : (void const *)sqlite3_column_text(st.stmt, 0);
        int const len = sqlite3_column_bytes(st.stmt,0);
        if(len && !str){
          rc = FSL_RC_OOM;
        }else{
        rc = 0;
        b->used = 0;
        rc = fsl_buffer_append( b, str, len );
          rc = 0;
          b->used = 0;
          rc = fsl_buffer_append( b, str, len );
        }
        break;
      }
      case FSL_RC_STEP_DONE:
        rc = 0;
        break;
      default:
        assert(FSL_RC_STEP_ERROR==rc);
        break;
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_get_buffer( fsl_db * db, fsl_buffer * b,
                       char asBlob,
int fsl_db_get_buffer( fsl_db * const db, fsl_buffer * const b,
                       bool asBlob,
                       char const * sql, ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_bufferv(db, b, asBlob, sql, args);
  va_end(args);
  return rc;
}

int32_t fsl_db_g_int32( fsl_db * const db, int32_t dflt,
                        char const * sql, ... ){
  int32_t rv = dflt;
  va_list args;
  va_start(args,sql);
  fsl_db_get_int32v(db, &rv, sql, args);
  va_end(args);
  return rv;
}

int64_t fsl_db_g_int64( fsl_db * db, int64_t dflt,
int64_t fsl_db_g_int64( fsl_db * const db, int64_t dflt,
                            char const * sql,
                            ... ){
  int64_t rv = dflt;
  va_list args;
  va_start(args,sql);
  fsl_db_get_int64v(db, &rv, sql, args);
  va_end(args);
  return rv;
}

fsl_id_t fsl_db_g_id( fsl_db * db, fsl_id_t dflt,
fsl_id_t fsl_db_g_id( fsl_db * const db, fsl_id_t dflt,
                            char const * sql,
                            ... ){
  fsl_id_t rv = dflt;
  va_list args;
  va_start(args,sql);
  fsl_db_get_idv(db, &rv, sql, args);
  va_end(args);
  return rv;
}

fsl_size_t fsl_db_g_size( fsl_db * db, fsl_size_t dflt,
fsl_size_t fsl_db_g_size( fsl_db * const db, fsl_size_t dflt,
                        char const * sql,
                        ... ){
  fsl_size_t rv = dflt;
  va_list args;
  va_start(args,sql);
  fsl_db_get_sizev(db, &rv, sql, args);
  va_end(args);
  return rv;
}

double fsl_db_g_double( fsl_db * db, double dflt,
double fsl_db_g_double( fsl_db * const db, double dflt,
                              char const * sql,
                              ... ){
  double rv = dflt;
  va_list args;
  va_start(args,sql);
  fsl_db_get_doublev(db, &rv, sql, args);
  va_end(args);
  return rv;
}

char * fsl_db_g_text( fsl_db * db, fsl_size_t * len,
char * fsl_db_g_text( fsl_db * const db, fsl_size_t * len,
                      char const * sql,
                      ... ){
  char * rv = NULL;
  va_list args;
  va_start(args,sql);
  fsl_db_get_textv(db, &rv, len, sql, args);
  va_end(args);
  return rv;
}

void * fsl_db_g_blob( fsl_db * db, fsl_size_t * len,
void * fsl_db_g_blob( fsl_db * const db, fsl_size_t * len,
                      char const * sql,
                      ... ){
  void * rv = NULL;
  va_list args;
  va_start(args,sql);
  fsl_db_get_blob(db, &rv, len, sql, args);
  va_end(args);
  return rv;
}

double fsl_db_julian_now(fsl_db * db){
double fsl_db_julian_now(fsl_db * const db){
  double rc = -1.0;
  if(db && db->dbh){
    /* TODO? use cached statement? So far not used often enough to
       justify it. */
    fsl_db_get_double( db, &rc, "SELECT julianday('now')");
  }
  return rc;
}

double fsl_db_string_to_julian(fsl_db * db, char const * str){
double fsl_db_string_to_julian(fsl_db * const db, char const * str){
  double rc = -1.0;
  if(db && db->dbh){
    /* TODO? use cached statement? So far not used often enough to
       justify it. */
    fsl_db_get_double( db, &rc, "SELECT julianday(%Q)",str);
  }
  return rc;
16978
16979
16980
16981
16982
16983
16984
16985

16986
16987
16988
16989
16990
16991
16992
16821
16822
16823
16824
16825
16826
16827

16828
16829
16830
16831
16832
16833
16834
16835







-
+







  return rc;
}

bool fsl_db_table_exists(fsl_db * const db,
                        fsl_dbrole_e whichDb,
                        const char *zTable
){
  const char *zDb = fsl_db_role_label( whichDb );
  const char *zDb = fsl_db_role_name( whichDb );
  int rc = db->dbh
    ? sqlite3_table_column_metadata(db->dbh, zDb, zTable, 0,
                                    0, 0, 0, 0, 0)
    : !SQLITE_OK;
  return rc==SQLITE_OK ? true : false;
}

17005
17006
17007
17008
17009
17010
17011
17012
17013


17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029

17030
17031


17032
17033
17034
17035
17036
17037
17038
16848
16849
16850
16851
16852
16853
16854


16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871

16872
16873

16874
16875
16876
16877
16878
16879
16880
16881
16882







-
-
+
+















-
+

-
+
+







      break;
    }
  }
  fsl_stmt_finalize(&q);
  return rv;
}

char * fsl_db_random_hex(fsl_db * db, fsl_size_t n){
  if(!db || !n) return NULL;
char * fsl_db_random_hex(fsl_db * const db, fsl_size_t n){
  if(!db->dbh || !n) return NULL;
  else{
    fsl_size_t rvLen = 0;
    char * rv = fsl_db_g_text(db, &rvLen,
                              "SELECT lower(hex("
                              "randomblob(%"FSL_SIZE_T_PFMT")))",
                              (fsl_size_t)(n/2+1));
    if(rv){
      assert(rvLen>=n);
      rv[n]=0;
    }
    return rv;
  }
}


int fsl_db_select_slistv( fsl_db * db, fsl_list * tgt,
int fsl_db_select_slistv( fsl_db * const db, fsl_list * const tgt,
                          char const * fmt, va_list args ){
  if(!db || !tgt || !fmt) return FSL_RC_MISUSE;
  if(!db->dbh) return fsl__db_err_not_opened(db);
  else if(!fmt || !*fmt) return fsl__db_err_sql_empty(db);
  else if(!*fmt) return FSL_RC_RANGE;
  else{
    int rc;
    fsl_stmt st = fsl_stmt_empty;
    fsl_size_t nlen;
    char const * n;
    char * cp;
17048
17049
17050
17051
17052
17053
17054
17055

17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067



17068
17069
17070
17071
17072
17073
17074
16892
16893
16894
16895
16896
16897
16898

16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909


16910
16911
16912
16913
16914
16915
16916
16917
16918
16919







-
+










-
-
+
+
+







      }
    }
    fsl_stmt_finalize(&st);
    return rc;
  }
}

int fsl_db_select_slist( fsl_db * const db, fsl_list * tgt,
int fsl_db_select_slist( fsl_db * const db, fsl_list * const tgt,
                         char const * fmt, ... ){
  int rc;
  va_list va;
  va_start (va,fmt);
  rc = fsl_db_select_slistv(db, tgt, fmt, va);
  va_end(va);
  return rc;
}

void fsl_db_sqltrace_enable( fsl_db * const db, FILE * outStream ){
  if(db && db->dbh){
    sqlite3_trace(db->dbh, fsl_db_sql_trace, outStream);
  if(db->dbh){
    sqlite3_trace_v2(db->dbh, SQLITE_TRACE_STMT,
                     fsl__db_sq3TraceV2, outStream);
  }
}

int fsl_db_init( fsl_error * err,
                 char const * zFilename,
                 char const * zSchema,
                 ... ){
17128
17129
17130
17131
17132
17133
17134
17135
17136


17137
17138
17139
17140

17141
17142
17143
17144
17145




17146
17147

17148
17149
17150
17151

17152


17153
17154
17155
17156
17157
17158
17159
16973
16974
16975
16976
16977
16978
16979


16980
16981
16982
16983
16984

16985
16986




16987
16988
16989
16990


16991




16992

16993
16994
16995
16996
16997
16998
16999
17000
17001







-
-
+
+



-
+

-
-
-
-
+
+
+
+
-
-
+
-
-
-
-
+
-
+
+







  }
  fsl_output(f, "\n", 1);
  return 0;
}


#undef MARKER
/* end of file db.c */
/* start of file deck.c */
/* end of file ./src/db.c */
/* start of file ./src/deck.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 Stephan Beal (https://wanderinghorse.net).
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt


  
  This program is free software; you can redistribute it and/or
  modify it under the terms of the Simplified BSD License (also
  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code
  known as the "2-Clause License" or "FreeBSD License".)
  

  This program is distributed in the hope that it will be useful,
  but without any warranty; without even the implied warranty of
  merchantability or fitness for a particular purpose.
  
  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
  *****************************************************************************
*/
/*
  This file houses the manifest/control-artifact-related APIs.
*/
#include <assert.h>
#include <stdlib.h> /* qsort() */
#include <memory.h> /* memcmp() */

/* Only for debugging */
17174
17175
17176
17177
17178
17179
17180
17181


17182
17183
17184
17185

17186
17187
17188
17189
17190
17191
17192
17016
17017
17018
17019
17020
17021
17022

17023
17024
17025
17026
17027

17028
17029
17030
17031
17032
17033
17034
17035







-
+
+



-
+







FSL_CARD_F_LIST_NEEDS_SORT = 0x01
};

/**
   Transfers the contents of d into f->cache.mcache. If d is
   dynamically allocated then it is also freed. In any case, after
   calling this the caller must behave as if the deck had been passed
   to fsl_deck_finalize().
   to fsl_deck_finalize() and (if it is unknown whether d is stack
   allocated) also freed.

   If manifest caching is disabled for f, d is immediately finalized.
*/
static void fsl__cx_mcache_insert(fsl_cx *f, fsl_deck * d){
static void fsl__cx_mcache_insert(fsl_cx * const f, fsl_deck * d){
  if(!(f->flags & FSL_CX_F_MANIFEST_CACHE)){
    fsl_deck_finalize(d);
    return;
  }
  static const unsigned cacheLen =
    (unsigned)(sizeof(fsl__mcache_empty.aAge)
               /sizeof(fsl__mcache_empty.aAge[0]));
17214
17215
17216
17217
17218
17219
17220
17221

17222
17223
17224
17225
17226
17227
17228
17057
17058
17059
17060
17061
17062
17063

17064
17065
17066
17067
17068
17069
17070
17071







-
+







    mc->decks[i] = *d;
    *d = fsl_deck_empty;
    if(&fsl_deck_empty == mc->decks[i].allocStamp){
      /* d was fsl_deck_malloc()'d so we need to free it, but cannot
         send it through fsl_deck_finalize() because that would try to
         clean up the memory we just transferred ownership of to
         mc->decks[i]. So... */
      mc->decks[i].allocStamp = 0;
      mc->decks[i].allocStamp = NULL;
      fsl_free(d);
    }
    d = pBaseline;
  }
}

/**
17599
17600
17601
17602
17603
17604
17605

17606




17607
17608
17609
17610
17611
17612
17613
17442
17443
17444
17445
17446
17447
17448
17449

17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460







+
-
+
+
+
+







static void fsl_deck_clean_T(fsl_deck * const m){
  fsl_list_clear(&m->T, fsl_list_v_card_T_free, NULL);
}
static void fsl_deck_clean_U(fsl_deck * const m){
  fsl_deck_clean_string(m, &m->U);
}
static void fsl_deck_clean_W(fsl_deck * const m){
  if(m->W.capacity/*dynamically-allocated buffer*/){
  CBUF(W);
    CBUF(W);
  }else{/*empty or external buffer pointing into to m->content.mem*/
    m->W = fsl_buffer_empty;
  }
}

void fsl_deck_clean2(fsl_deck * const m, fsl_buffer * const xferBuf){
  if(!m) return;
  fsl_deck_clean_version(m);  
  fsl_deck_clean_A(m);
  fsl_deck_clean_B(m);
17898
17899
17900
17901
17902
17903
17904
17905

17906
17907
17908
17909
17910
17911
17912
17745
17746
17747
17748
17749
17750
17751

17752
17753
17754
17755
17756
17757
17758
17759







-
+









/**
    If fsl_card_is_legal(d->type, card), returns true, else updates
    d->f->error with a description of the constraint violation and
    returns 0.
 */
static bool fsl_deck_check_type( fsl_deck * d, char card ){
static bool fsl_deck_check_type( fsl_deck * const d, char card ){
  if(fsl_card_is_legal(d->type, card)) return true;
  else{
    fsl_cx_err_set(d->f, FSL_RC_TYPE,
                   "Card type '%c' is not allowed "
                   "in artifacts of type %s.",
                   card, fsl_satype_cstr(d->type));
    return false;
18041
18042
18043
18044
18045
18046
18047
18048

18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065

18066
18067
18068
18069











18070
18071
18072
18073
18074
18075
18076
17888
17889
17890
17891
17892
17893
17894

17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913




17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931







-
+

















+
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+








int fsl_deck_I_set( fsl_deck * const mf, fsl_uuid_cstr uuid){
  if(uuid && mf->H) return FSL_RC_SYNTAX;
  int const uLen = uuid ? fsl_is_uuid(uuid) : 0;
  return fsl_deck_sethex_impl(mf, uuid, 'I', uLen, &mf->I);
}

int fsl_deck_J_add( fsl_deck * const mf, char isAppend,
int fsl_deck_J_add( fsl_deck * const mf, bool isAppend,
                    char const * field, char const * value){
  if(!field) return FSL_RC_MISUSE;
  else if(!*field) return FSL_RC_SYNTAX;
  else if(!fsl_deck_check_type(mf,'J')) return mf->f->error.code;
  else{
    int rc;
    fsl_card_J * cp = fsl_card_J_malloc(isAppend, field, value);
    if(!cp) rc = FSL_RC_OOM;
    else if( 0 != (rc = fsl_list_append(&mf->J, cp))){
      fsl_card_J_free(cp);
    }
    return rc;
  }
}


int fsl_deck_K_set( fsl_deck * const mf, fsl_uuid_cstr uuid){
  if(uuid){
  int const uLen = fsl_is_uuid(uuid);
  return uLen
    ? fsl_deck_sethex_impl(mf, uuid, 'K', uLen, &mf->K)
    : FSL_RC_SYNTAX;
    int const uLen = fsl_is_uuid(uuid);
    return uLen
      ? fsl_deck_sethex_impl(mf, uuid, 'K', uLen, &mf->K)
      : FSL_RC_SYNTAX;
  }else{
    char buf[FSL_STRLEN_SHA1+1];
    unsigned char rnd[FSL_STRLEN_SHA1/20];
    fsl_randomness(FSL_STRLEN_SHA1/2, rnd);
    fsl_sha1_digest_to_base16(rnd, buf);
    return fsl_deck_sethex_impl(mf, buf, 'K', FSL_STRLEN_SHA1, &mf->K);
  }
}

int fsl_deck_L_set( fsl_deck * const mf, char const * v, fsl_int_t n){
  return mf
    ? fsl_deck_set_string(mf, 'L', &mf->L, v, n)
    : FSL_RC_SYNTAX;
}
18230
18231
18232
18233
18234
18235
18236
18237

18238
18239
18240
18241
18242
18243
18244
18085
18086
18087
18088
18089
18090
18091

18092
18093
18094
18095
18096
18097
18098
18099







-
+







  }else if(!mf->F.used){
    theHash = FSL_MD5_INITIAL_HASH;
    /* fall through and set hash */
  }else{
    int rc = 0;
    fsl_card_F const * fc;
    fsl_id_t fileRid;
    fsl_buffer * const buf = &f->fileContent;
    fsl_buffer * const buf = &f->cache.fileContent;
    unsigned char digest[16];
    fsl_md5_cx md5 = fsl_md5_cx_empty;
    enum { NumBufSize = 40 };
    char numBuf[NumBufSize] = {0};
    assert(!buf->used && "Misuse of f->fileContent buffer.");
    rc = fsl_deck_F_rewind(mf);
    if(rc) goto end;
18388
18389
18390
18391
18392
18393
18394
18395

18396
18397
18398
18399
18400
18401
18402
18243
18244
18245
18246
18247
18248
18249

18250
18251
18252
18253
18254
18255
18256
18257







-
+







  unsigned len = 0;
  for(; z[len]; ++len){
    if(z[len] <= 32) return false;
  }
  return len>0;
}

int fsl_deck_branch_set( fsl_deck * d, char const * branchName ){
int fsl_deck_branch_set( fsl_deck * const d, char const * branchName ){
  if(!fsl_is_valid_branchname(branchName)){
    return fsl_cx_err_set(d->f, FSL_RC_RANGE, "Branch name contains "
                          "invalid characters.");
  }
  int rc= fsl_deck_T_add(d, FSL_TAGTYPE_PROPAGATING, NULL,
                         "branch", branchName);
  if(!rc){
18544
18545
18546
18547
18548
18549
18550
18551

18552
18553
18554
18555
18556
18557
18558
18399
18400
18401
18402
18403
18404
18405

18406
18407
18408
18409
18410
18411
18412
18413







-
+







    if(rc){
      fsl_card_F_list_pop(&mf->F);
    }
    return rc;
  }
}

int fsl_deck_F_foreach( fsl_deck * d, fsl_card_F_visitor_f cb, void * visitorState ){
int fsl_deck_F_foreach( fsl_deck * const d, fsl_card_F_visitor_f cb, void * const visitorState ){
  if(!cb) return FSL_RC_MISUSE;
  else{
    fsl_card_F const * fc;
    int rc = fsl_deck_F_rewind(d);
    while( !rc && !(rc=fsl_deck_F_next(d, &fc)) && fc) {
      rc = cb( fc, visitorState );
    }
18643
18644
18645
18646
18647
18648
18649
18650

18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668

18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681

18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692

18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705

18706
18707
18708
18709
18710
18711

18712
18713
18714
18715
18716
18717
18718
18498
18499
18500
18501
18502
18503
18504

18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522

18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535

18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546

18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559

18560
18561
18562
18563
18564
18565

18566
18567
18568
18569
18570
18571
18572
18573







-
+

















-
+












-
+










-
+












-
+





-
+







  return os->rc;
}

/**
    Internal helper for fsl_deck_output(). Appends formatted output to
    os->out() via fsl_output_f_mf(). Returns os->rc (0 on success).
 */
static int fsl_deck_append( fsl_deck_out_state * os,
static int fsl_deck_append( fsl_deck_out_state * const os,
                            char const * fmt, ... ){
  fsl_int_t rc;
  va_list args;
  assert(os);
  assert(fmt && *fmt);
  va_start(args,fmt);
  rc = fsl_appendfv( fsl_output_f_mf, os, fmt, args);
  va_end(args);
  if(rc<0 && !os->rc) os->rc = FSL_RC_IO;
  return os->rc;
}

/**
    Fossilizes (inp, inp+len] bytes to os->scratch,
    overwriting any existing contents.
    Updates and returns os->rc.
 */
static int fsl_deck_fossilize( fsl_deck_out_state * os,
static int fsl_deck_fossilize( fsl_deck_out_state * const os,
                               unsigned char const * inp,
                               fsl_int_t len){
  fsl_buffer_reuse(os->scratch);
  return os->rc = len
    ? fsl_bytes_fossilize(inp, len, os->scratch)
    : 0;
}

/** Confirms that the given card letter is valid for od->d->type, and
    updates os->rc and os->error if it's not. Returns true if it's
    valid.
*/
static bool fsl_deck_out_tcheck(fsl_deck_out_state * os, char letter){
static bool fsl_deck_out_tcheck(fsl_deck_out_state * const os, char letter){
  if(!fsl_card_is_legal(os->d->type, letter)){
    os->rc = fsl_error_set(&os->error, FSL_RC_TYPE,
                           "%c-card is not valid for deck type %s.",
                           letter, fsl_satype_cstr(os->d->type));
  }
  return os->rc ? false : true;
}

/* Appends a UUID-valued card to os from os->d->{{card}} if the given
   UUID is not NULL, else this is a no-op. */
static int fsl_deck_out_uuid( fsl_deck_out_state * os, char card, fsl_uuid_str uuid ){
static int fsl_deck_out_uuid( fsl_deck_out_state * const os, char card, fsl_uuid_str uuid ){
  if(uuid && fsl_deck_out_tcheck(os, card)){
    if(!fsl_is_uuid(uuid)){
      os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                             "Malformed UUID in %c card.", card);
    }else{
      fsl_deck_append(os, "%c %s\n", card, uuid);
    }
  }
  return os->rc;
}

/* Appends the B card to os from os->d->B. */
static int fsl_deck_out_B( fsl_deck_out_state * os ){
static int fsl_deck_out_B( fsl_deck_out_state * const os ){
  return fsl_deck_out_uuid(os, 'B', os->d->B.uuid);
}


/* Appends the A card to os from os->d->A. */
static int fsl_deck_out_A( fsl_deck_out_state * os ){
static int fsl_deck_out_A( fsl_deck_out_state * const os ){
  if(os->d->A.name && fsl_deck_out_tcheck(os, 'A')){
    if(!os->d->A.name || !*os->d->A.name){
      os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                             "A-card is missing its name property");

    }else if(!os->d->A.tgt || !*os->d->A.tgt){
      os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
18740
18741
18742
18743
18744
18745
18746
18747

18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763

18764
18765
18766
18767
18768
18769

18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784

18785
18786
18787
18788
18789
18790
18791
18595
18596
18597
18598
18599
18600
18601

18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617

18618
18619
18620
18621
18622
18623

18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638

18639
18640
18641
18642
18643
18644
18645
18646







-
+















-
+





-
+














-
+








/**
    Internal helper for outputing cards which are simple strings.
    str is the card to output (NULL values are ignored), letter is
    the card letter being output. If doFossilize is true then
    the output gets fossilize-formatted.
 */
static int fsl_deck_out_letter_str( fsl_deck_out_state * os, char letter,
static int fsl_deck_out_letter_str( fsl_deck_out_state * const os, char letter,
                                    char const * str, char doFossilize ){
  if(str && fsl_deck_out_tcheck(os, letter)){
    if(doFossilize){
      fsl_deck_fossilize(os, (unsigned char const *)str, -1);
      if(!os->rc){
        fsl_deck_append(os, "%c %b\n", letter, os->scratch);
      }
    }else{
      fsl_deck_append(os, "%c %s\n", letter, str);
    }
  }
  return os->rc;
}

/* Appends the C card to os from os->d->C. */
static int fsl_deck_out_C( fsl_deck_out_state * os ){
static int fsl_deck_out_C( fsl_deck_out_state * const os ){
  return fsl_deck_out_letter_str( os, 'C', os->d->C, 1 );
}


/* Appends the D card to os from os->d->D. */
static int fsl_deck_out_D( fsl_deck_out_state * os ){
static int fsl_deck_out_D( fsl_deck_out_state * const os ){
  if((os->d->D > 0.0) && fsl_deck_out_tcheck(os, 'D')){
    char ds[24];
    if(!fsl_julian_to_iso8601(os->d->D, ds, 1)){
      os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                             "D-card contains invalid "
                             "Julian Day value.");
    }else{
      fsl_deck_append(os, "D %s\n", ds);
    }
  }
  return os->rc;
}

/* Appends the E card to os from os->d->E. */
static int fsl_deck_out_E( fsl_deck_out_state * os ){
static int fsl_deck_out_E( fsl_deck_out_state * const os ){
  if(os->d->E.uuid && fsl_deck_out_tcheck(os, 'E')){
    char ds[24];
    char msPrecision = FSL_SATYPE_EVENT!=os->d->type
      /* The timestamps on Events historically have seconds precision,
         not ms.
      */;
    if(!fsl_is_uuid(os->d->E.uuid)){
18801
18802
18803
18804
18805
18806
18807
18808

18809
18810
18811
18812
18813

18814
18815
18816
18817
18818
18819
18820
18821
18822

18823
18824
18825
18826
18827
18828
18829
18656
18657
18658
18659
18660
18661
18662

18663
18664
18665
18666
18667

18668
18669
18670
18671
18672
18673
18674
18675
18676

18677
18678
18679
18680
18681
18682
18683
18684







-
+




-
+








-
+







      fsl_deck_append(os, "E %s %s\n", ds, os->d->E.uuid);
    }
  }
  return os->rc;
}

/* Appends the G card to os from os->d->G. */
static int fsl_deck_out_G( fsl_deck_out_state * os ){
static int fsl_deck_out_G( fsl_deck_out_state * const os ){
  return fsl_deck_out_uuid(os, 'G', os->d->G);
}

/* Appends the H card to os from os->d->H. */
static int fsl_deck_out_H( fsl_deck_out_state * os ){
static int fsl_deck_out_H( fsl_deck_out_state * const os ){
  if(os->d->H && os->d->I){
    return os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                                  "Forum post may not have both H- and I-cards.");
  }
  return fsl_deck_out_letter_str( os, 'H', os->d->H, 1 );
}

/* Appends the I card to os from os->d->I. */
static int fsl_deck_out_I( fsl_deck_out_state * os ){
static int fsl_deck_out_I( fsl_deck_out_state * const os ){
  if(os->d->I && os->d->H){
    return os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                                  "Forum post may not have both H- and I-cards.");
  }
  return fsl_deck_out_uuid(os, 'I', os->d->I);
}

18887
18888
18889
18890
18891
18892
18893
18894

18895
18896
18897
18898
18899
18900
18901
18902
18903
18904

18905
18906
18907
18908
18909
18910
18911
18742
18743
18744
18745
18746
18747
18748

18749
18750
18751
18752
18753
18754
18755
18756
18757
18758

18759
18760
18761
18762
18763
18764
18765
18766







-
+









-
+







      if(!rc) rc = fsl_deck_append( os, " %b", os->scratch);
    }
  }
  if(!rc) fsl_output_f_mf(os, "\n", 1);
  return os->rc;
}

static int fsl_deck_out_list_obj( fsl_deck_out_state * os,
static int fsl_deck_out_list_obj( fsl_deck_out_state * const os,
                                  char letter,
                                  fsl_list const * li,
                                  fsl_list_visitor_f visitor){
  if(li->used && fsl_deck_out_tcheck(os, letter)){
    os->rc = fsl_list_visit( li, 0, visitor, os );
  }
  return os->rc;
}

static int fsl_deck_out_F( fsl_deck_out_state * os ){
static int fsl_deck_out_F( fsl_deck_out_state * const os ){
  if(os->d->F.used && fsl_deck_out_tcheck(os, 'F')){
    uint32_t i;
    for(i=0; !os->rc && i <os->d->F.used; ++i){
      os->rc = fsl_deck_out_F_one(os, F_at(&os->d->F, i));
    }
  }
  return os->rc;
18938
18939
18940
18941
18942
18943
18944
18945

18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964

18965
18966
18967
18968
18969
18970

18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985

18986
18987
18988
18989
18990

18991
18992
18993
18994
18995
18996
18997
18998
18999
19000

19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017

19018
19019
19020
19021
19022
19023
19024
18793
18794
18795
18796
18797
18798
18799

18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818

18819
18820
18821
18822
18823
18824

18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839

18840
18841
18842
18843
18844

18845
18846
18847
18848
18849
18850
18851
18852
18853
18854

18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871

18872
18873
18874
18875
18876
18877
18878
18879







-
+


















-
+





-
+














-
+




-
+









-
+
















-
+







}

/**
    fsl_list_visitor_f() impl for outputing J cards. obj must
    be a (fsl_card_J *).
 */
static int fsl_list_v_mf_output_card_J(void * obj, void * visitorState ){
  fsl_deck_out_state * os = (fsl_deck_out_state *)visitorState;
  fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState;
  fsl_card_J const * c = (fsl_card_J const *)obj;
  fsl_deck_fossilize( os, (unsigned char const *)c->field, -1 );
  if(!os->rc){
    fsl_deck_append(os, "J %s%b", c->append ? "+" : "", os->scratch);
    if(!os->rc){
      if(c->value && *c->value){
        fsl_deck_fossilize( os, (unsigned char const *)c->value, -1 );
        if(!os->rc){
          fsl_deck_append(os, " %b\n", os->scratch);
        }
      }else{
        fsl_deck_append(os, "\n");
      }
    }
  }
  return os->rc;
}

static int fsl_deck_out_J( fsl_deck_out_state * os ){
static int fsl_deck_out_J( fsl_deck_out_state * const os ){
  return fsl_deck_out_list_obj(os, 'J', &os->d->J,
                               fsl_list_v_mf_output_card_J);
}

/* Appends the K card to os from os->d->K. */
static int fsl_deck_out_K( fsl_deck_out_state * os ){
static int fsl_deck_out_K( fsl_deck_out_state * const os ){
  if(os->d->K && fsl_deck_out_tcheck(os, 'K')){
    if(!fsl_is_uuid(os->d->K)){
      os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                             "Invalid UUID in K card.");
    }
    else{
      fsl_deck_append(os, "K %s\n", os->d->K);
    }
  }
  return os->rc;
}


/* Appends the L card to os from os->d->L. */
static int fsl_deck_out_L( fsl_deck_out_state * os ){
static int fsl_deck_out_L( fsl_deck_out_state * const os ){
  return fsl_deck_out_letter_str(os, 'L', os->d->L, 1);
}

/* Appends the N card to os from os->d->N. */
static int fsl_deck_out_N( fsl_deck_out_state * os ){
static int fsl_deck_out_N( fsl_deck_out_state * const os ){
  return fsl_deck_out_letter_str( os, 'N', os->d->N, 1 );
}

/**
    fsl_list_visitor_f() impl for outputing P cards. obj must
    be a (fsl_deck_out_state *) and obj->counter must be
    set to 0 before running the visit iteration.
 */
static int fsl_list_v_mf_output_card_P(void * obj, void * visitorState ){
  fsl_deck_out_state * os = (fsl_deck_out_state *)visitorState;
  fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState;
  char const * uuid = (char const *)obj;
  int const uLen = uuid ? fsl_is_uuid(uuid) : 0;
  if(!uLen){
    os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                           "Invalid UUID in P card.");
  }
  else if(!os->counter++) fsl_output_f_mf(os, "P ", 2);
  else fsl_output_f_mf(os, " ", 1);
  /* Reminder: fsl_appendf_f_mf() updates os->rc. */
  if(!os->rc){
    fsl_output_f_mf(os, uuid, (fsl_size_t)uLen);
  }
  return os->rc;
}


static int fsl_deck_out_P( fsl_deck_out_state * os ){
static int fsl_deck_out_P( fsl_deck_out_state * const os ){
  if(!fsl_deck_out_tcheck(os, 'P')) return os->rc;
  else if(os->d->P.used){
    os->counter = 0;
    os->rc = fsl_list_visit( &os->d->P, 0, fsl_list_v_mf_output_card_P, os );
    assert(os->counter);
    if(!os->rc) fsl_output_f_mf(os, "\n", 1);
  }
19054
19055
19056
19057
19058
19059
19060
19061

19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076

19077
19078
19079
19080
19081
19082
19083
18909
18910
18911
18912
18913
18914
18915

18916

18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929

18930
18931
18932
18933
18934
18935
18936
18937







-
+
-













-
+







  assert(l);
  assert(r);
  if(!l) return r ? 1 : 0;
  else if(!r) return -1;
  else{
    /* Lexical sorting must account for the +/- characters, and a '+'
       sorts before '-', which is why this next part may seem
       backwards at first.
       backwards at first. */
    */
    assert(l->type);
    assert(r->type);
    if(l->type<0 && r->type>0) return 1;
    else if(l->type>0 && r->type<0) return -1;
    else return fsl_strcmp(l->target, r->target);
  }
}

/**
    fsl_list_visitor_f() impl for outputing Q cards. obj must
    be a (fsl_deck_out_state *).
*/
static int fsl_list_v_mf_output_card_Q(void * obj, void * visitorState ){
  fsl_deck_out_state * os = (fsl_deck_out_state *)visitorState;
  fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState;
  fsl_card_Q const * cp = (fsl_card_Q const *)obj;
  char const prefix = (cp->type==FSL_CHERRYPICK_ADD)
    ? '+' : '-';
  assert(cp->type);
  assert(cp->target);
  if(cp->type != FSL_CHERRYPICK_ADD &&
     cp->type != FSL_CHERRYPICK_BACKOUT){
19101
19102
19103
19104
19105
19106
19107
19108

19109
19110
19111
19112
19113
19114
19115
19116

19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135

19136
19137
19138
19139
19140
19141
19142
18955
18956
18957
18958
18959
18960
18961

18962
18963
18964
18965
18966
18967
18968
18969

18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988

18989
18990
18991
18992
18993
18994
18995
18996







-
+







-
+


















-
+







    }
  }else{
    fsl_deck_append(os, "Q %c%s\n", prefix, cp->target);
  }
  return os->rc;
}

static int fsl_deck_out_Q( fsl_deck_out_state * os ){
static int fsl_deck_out_Q( fsl_deck_out_state * const os ){
  return fsl_deck_out_list_obj(os, 'Q', &os->d->Q,
                               fsl_list_v_mf_output_card_Q);
}

/**
    Appends the R card from os->d->R to os.
 */
static int fsl_deck_out_R( fsl_deck_out_state * os ){
static int fsl_deck_out_R( fsl_deck_out_state * const os ){
  if(os->d->R && fsl_deck_out_tcheck(os, 'R')){
    if((FSL_STRLEN_MD5!=fsl_strlen(os->d->R))
            || !fsl_validate16(os->d->R, FSL_STRLEN_MD5)){
      os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                             "Malformed MD5 in R-card.");
    }
    else{
      fsl_deck_append(os, "R %s\n", os->d->R);
    }
  }
  return os->rc;
}

/**
    fsl_list_visitor_f() impl for outputing T cards. obj must
    be a (fsl_deck_out_state *).
 */
static int fsl_list_v_mf_output_card_T(void * obj, void * visitorState ){
  fsl_deck_out_state * os = (fsl_deck_out_state *)visitorState;
  fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState;
  fsl_card_T * t = (fsl_card_T *)obj;
  char prefix = 0;
  switch(os->d->type){
    case FSL_SATYPE_TECHNOTE:
      if( t->uuid ){
        return os->rc = fsl_error_set(&os->error, FSL_RC_SYNTAX,
                                      "Non-self-referential T-card is not "
19330
19331
19332
19333
19334
19335
19336
19337

19338
19339
19340
19341
19342
19343
19344
19345
19346

19347
19348
19349
19350
19351

19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362

19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379

19380
19381
19382
19383
19384

19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400

19401
19402
19403
19404
19405
19406
19407
19408
19409

19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423

19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443

19444
19445
19446
19447
19448
19449
19450
19451
19452
19453

19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466

19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477

19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496

19497
19498
19499
19500
19501
19502
19503
19184
19185
19186
19187
19188
19189
19190

19191
19192
19193
19194
19195
19196
19197
19198
19199

19200
19201
19202
19203
19204

19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215

19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232

19233
19234
19235
19236
19237

19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253

19254
19255
19256
19257
19258
19259
19260
19261
19262

19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276

19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296

19297
19298
19299
19300
19301
19302
19303
19304
19305
19306

19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319

19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330

19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349

19350
19351
19352
19353
19354
19355
19356
19357







-
+








-
+




-
+










-
+
















-
+




-
+















-
+








-
+













-
+



















-
+









-
+












-
+










-
+


















-
+







      }
    }
    return rc;
  }
}

/* Appends the T cards to os from os->d->T. */
static int fsl_deck_out_T( fsl_deck_out_state * os ){
static int fsl_deck_out_T( fsl_deck_out_state * const os ){
  os->rc = fsl_deck_T_verify_order( os->d, &os->error);
  return os->rc
    ? os->rc
    : fsl_deck_out_list_obj(os, 'T', &os->d->T,
                            fsl_list_v_mf_output_card_T);
}

/* Appends the U card to os from os->d->U. */
static int fsl_deck_out_U( fsl_deck_out_state * os ){
static int fsl_deck_out_U( fsl_deck_out_state * const os ){
  return fsl_deck_out_letter_str(os, 'U', os->d->U, 1);
}

/* Appends the W card to os from os->d->W. */
static int fsl_deck_out_W( fsl_deck_out_state * os ){
static int fsl_deck_out_W( fsl_deck_out_state * const os ){
  if(os->d->W.used && fsl_deck_out_tcheck(os, 'W')){
    fsl_deck_append(os, "W %"FSL_SIZE_T_PFMT"\n%b\n",
                    (fsl_size_t)os->d->W.used,
                    &os->d->W );
  }
  return os->rc;
}


/* Appends the Z card to os from os' accummulated md5 hash. */
static int fsl_deck_out_Z( fsl_deck_out_state * os ){
static int fsl_deck_out_Z( fsl_deck_out_state * const os ){
  unsigned char digest[16];
  char md5[FSL_STRLEN_MD5+1];
  fsl_md5_final(&os->md5, digest);
  fsl_md5_digest_to_base16(digest, md5);
  assert(!md5[32]);
  os->md5.isInit = 0 /* Keep further output from updating the MD5 */;
  return fsl_deck_append(os, "Z %.*s\n", FSL_STRLEN_MD5, md5);
}

static int qsort_cmp_strings( void const * lhs, void const * rhs ){
  char const * l = *((char const **)lhs);
  char const * r = *((char const **)rhs);
  return fsl_strcmp(l,r);
}

static int fsl_list_v_mf_output_card_M(void * obj, void * visitorState ){
  fsl_deck_out_state * os = (fsl_deck_out_state *)visitorState;
  fsl_deck_out_state * const os = (fsl_deck_out_state *)visitorState;
  char const * m = (char const *)obj;
  return fsl_deck_append(os, "M %s\n", m);
}

static int fsl_deck_output_cluster( fsl_deck_out_state * os ){
static int fsl_deck_output_cluster( fsl_deck_out_state * const os ){
  if(!os->d->M.used){
    os->rc = fsl_error_set(&os->error, FSL_RC_RANGE,
                           "M-card list may not be empty.");
  }else{
    fsl_deck_out_list_obj(os, 'M', &os->d->M,
                          fsl_list_v_mf_output_card_M);
  }
  return os->rc;
}


/* Helper for fsl_deck_output_CATYPE() */
#define DOUT(LETTER) rc = fsl_deck_out_##LETTER(os); \
  if(rc || os->rc) return os->rc ? os->rc : rc

static int fsl_deck_output_control( fsl_deck_out_state * os ){
static int fsl_deck_output_control( fsl_deck_out_state * const os ){
  int rc;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(D);
  DOUT(T);
  DOUT(U);
  return os->rc;
}

static int fsl_deck_output_event( fsl_deck_out_state * os ){
static int fsl_deck_output_event( fsl_deck_out_state * const os ){
  int rc = 0;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(C);
  DOUT(D);
  DOUT(E);
  DOUT(N);
  DOUT(P);
  DOUT(T);
  DOUT(U);
  DOUT(W);
  return os->rc;
}

static int fsl_deck_output_mf( fsl_deck_out_state * os ){
static int fsl_deck_output_mf( fsl_deck_out_state * const os ){
  int rc = 0;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(B);
  DOUT(C);
  DOUT(D);
  DOUT(F);
  DOUT(K);
  DOUT(L);
  DOUT(N);
  DOUT(P);
  DOUT(Q);
  DOUT(R);
  DOUT(T);
  DOUT(U);
  DOUT(W);
  return os->rc;
}


static int fsl_deck_output_ticket( fsl_deck_out_state * os ){
static int fsl_deck_output_ticket( fsl_deck_out_state * const os ){
  int rc;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(D);
  DOUT(J);
  DOUT(K);
  DOUT(U);
  return os->rc;
}

static int fsl_deck_output_wiki( fsl_deck_out_state * os ){
static int fsl_deck_output_wiki( fsl_deck_out_state * const os ){
  int rc;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(C);
  DOUT(D);
  DOUT(L);
  DOUT(N);
  DOUT(P);
  DOUT(U);
  DOUT(W);
  return os->rc;
}

static int fsl_deck_output_attachment( fsl_deck_out_state * os ){
static int fsl_deck_output_attachment( fsl_deck_out_state * const os ){
  int rc = 0;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(A);
  DOUT(C);
  DOUT(D);
  DOUT(N);
  DOUT(U);
  return os->rc;
}

static int fsl_deck_output_forumpost( fsl_deck_out_state * os ){
static int fsl_deck_output_forumpost( fsl_deck_out_state * const os ){
  int rc;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(D);
  DOUT(G);
  DOUT(H);
  DOUT(I);
  DOUT(N);
  DOUT(P);
  DOUT(U);
  DOUT(W);
  return os->rc;
}

/**
    Only for testing/debugging purposes, as it allows constructs which
    are not semantically legal and are CERTAINLY not legal to stuff in
    the database.
 */
static int fsl_deck_output_any( fsl_deck_out_state * os ){
static int fsl_deck_output_any( fsl_deck_out_state * const os ){
  int rc = 0;
  /* Reminder: cards must be output in strict lexical order. */
  DOUT(B);
  DOUT(C);
  DOUT(D);
  DOUT(E);
  DOUT(F);
19513
19514
19515
19516
19517
19518
19519
19520

19521
19522
19523
19524
19525
19526
19527
19367
19368
19369
19370
19371
19372
19373

19374
19375
19376
19377
19378
19379
19380
19381







-
+







  DOUT(W);
  return os->rc;
}

#undef DOUT


int fsl_deck_unshuffle( fsl_deck * d, bool calculateRCard ){
int fsl_deck_unshuffle( fsl_deck * const d, bool calculateRCard ){
  fsl_list * li;
  int rc = 0;
  if(!d || !d->f) return FSL_RC_MISUSE;
  fsl_cx_err_reset(d->f);
#define SORT(CARD,CMP) li = &d->CARD; fsl_list_sort(li, CMP)
  SORT(J,fsl__qsort_cmp_J_cards);
  SORT(M,qsort_cmp_strings);
19555
19556
19557
19558
19559
19560
19561
19562


19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573




19574
19575
19576
19577
19578
19579
19580
19409
19410
19411
19412
19413
19414
19415

19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439







-
+
+











+
+
+
+







          */;
      }
    }
  }
  return rc;
}

int fsl_deck_output( fsl_deck * d, fsl_output_f out, void * outputState ){
int fsl_deck_output( fsl_deck * const d, fsl_output_f out,
                     void * outputState ){
  static const bool allowTypeAny = false
    /* Only enable for debugging/testing. Allows outputing decks of
       type FSL_SATYPE_ANY, which bypasses some validation checks and
       may trigger other validation assertions. And may allow you to
       inject garbage into the repo. So be careful.
    */;

  fsl_deck_out_state OS = fsl_deck_out_state_empty;
  fsl_deck_out_state * const os = &OS;
  fsl_cx * const f = d->f;
  int rc = 0;
  if(NULL==out && NULL==outputState && f){
    out = f->output.out;
    outputState = f->output.state;
  }
  if(!f || !out) return FSL_RC_MISUSE;
  else if(FSL_SATYPE_ANY==d->type){
    if(!allowTypeAny){
      return fsl_cx_err_set(d->f, FSL_RC_TYPE,
                            "Artifact type ANY cannot be"
                            "output unless it is enabled in this "
                            "code (it's dangerous).");
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666

19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19516
19517
19518
19519
19520
19521
19522

19523

19524
19525
19526

19527

19528
19529
19530
19531
19532
19533
19534







-

-
+


-

-








/**
   Adds a record in the pending_xlink temp table, to be processed
   when crosslinking is completed. Returns 0 on success, non-0 for
   db error.
*/
static int fsl__deck_crosslink_add_pending(fsl_cx * f, char cType, fsl_uuid_cstr uuid){
  int rc = 0;
  assert(f->cache.isCrosslinking);
  rc = fsl_db_exec(f->dbMain,
  return fsl_cx_exec(f,
                   "INSERT OR IGNORE INTO pending_xlink VALUES('%c%q')",
                   cType, uuid);
  return fsl_cx_uplift_db_error2(f, 0, rc);
}


/** @internal
   
    Add a single entry to the mlink table.  Also add the filename to
    the filename table if it is not there already.
   
    Parameters:
19974
19975
19976
19977
19978
19979
19980
19981
19982


19983
19984
19985
19986
19987
19988

19989
19990
19991
19992
19993
19994
19995
19996




19997
19998
19999
20000
20001
20002
20003
19830
19831
19832
19833
19834
19835
19836


19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864







-
-
+
+






+








+
+
+
+







    fc->perm = perms;
    return 0;
  }else{
    return fsl_deck_F_add(d, zName, uuid, perms, priorName);
  }
}

int fsl_deck_F_set_content( fsl_deck * d, char const * zName,
                            fsl_buffer const * src,
int fsl_deck_F_set_content( fsl_deck * const d, char const * zName,
                            fsl_buffer const * const src,
                            fsl_fileperm_e perm, 
                            char const * priorName){
  fsl_uuid_str zHash = 0;
  fsl_id_t rid = 0;
  fsl_id_t prevRid = 0;
  int rc = 0;
  assert(d->f);
  if(d->rid>0){
    return fsl_cx_err_set(d->f, FSL_RC_MISUSE,
                          "%s() cannot be applied to a saved deck.",
                          __func__);
  }else if(!fsl_cx_transaction_level(d->f)){
    return fsl_cx_err_set(d->f, FSL_RC_MISUSE,
                          "%s() requires that a transaction is active.",
                          __func__);
  }else if(!fsl_is_simple_pathname(zName, true)){
    return fsl_cx_err_set(d->f, FSL_RC_RANGE,
                          "Filename is not valid for use as a repository "
                          "entry: %s", zName);
  }
  rc = fsl_repo_blob_lookup(d->f, src, &rid, &zHash);
  if(rc && FSL_RC_NOT_FOUND!=rc) goto end;
  assert(zHash);
  if(!rid){
    fsl_card_F const * fc;
    /* This is new content. Save it, then see if we have a previous version
20727
20728
20729
20730
20731
20732
20733


















20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744


20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764

20765
20766
20767
20768
20769

20770
20771
20772
20773
20774
20775
20776

20777
20778
20779
20780
20781

20782
20783
20784
20785
20786
20787
20788
20789
20790

20791
20792
20793
20794
20795

20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807

20808
20809

20810
20811
20812
20813
20814
20815
20816
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621


20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642

20643
20644
20645
20646
20647

20648
20649
20650
20651
20652
20653
20654

20655
20656
20657
20658
20659

20660
20661
20662
20663
20664
20665
20666
20667
20668

20669
20670
20671
20672
20673

20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685

20686
20687

20688
20689
20690
20691
20692
20693
20694
20695







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+









-
-
+
+



















-
+




-
+






-
+




-
+








-
+




-
+











-
+

-
+







  }
  if(!rc && parentId){
    rc = fsl__tag_propagate_all(d->f, parentId);
  }
  return rc;
}

int fsl__call_xlink_listeners(fsl_deck * const d){
  int rc = 0;
  fsl_xlinker * xl = NULL;
  fsl_cx_err_reset(d->f);
  for( fsl_size_t i = 0; !rc && (i < d->f->xlinkers.used); ++i ){
    xl = d->f->xlinkers.list+i;
    rc = xl->f( d, xl->state );
  }
  if(rc && !d->f->error.code){
    assert(xl);
    rc = fsl_cx_err_set(d->f, rc, "Crosslink callback handler "
                        "'%s' failed with code %d (%s) for "
                        "artifact RID #%" FSL_ID_T_PFMT ".",
                        xl->name, rc, fsl_rc_cstr(rc),
                        d->rid);
  }
  return rc;
}

/**
   Overrideable crosslink listener which updates the timeline for
   attachment records.
*/
static int fsl_deck_xlink_f_attachment(fsl_deck * const d, void * state){
  if(FSL_SATYPE_ATTACHMENT!=d->type) return 0;
  int rc;
  fsl_db * const db = fsl_cx_db_repo(d->f);
  fsl_buffer comment = fsl_buffer_empty;
  const char isAdd = (d->A.src && *d->A.src) ? 1 : 0;
  fsl_buffer * const comment = fsl__cx_scratchpad(d->f);
  const bool isAdd = (d->A.src && *d->A.src) ? 1 : 0;
  char attachToType = 'w'
    /* Assume wiki until we know otherwise, keeping in mind that the
       d->A.tgt might not yet be in the blob table, in which case
       we are unable to know, for certain, what the target is.
       That only affects the timeline (event table), though, not
       the crosslinking of the attachment itself. */;
  assert(db);
  if(fsl_is_uuid(d->A.tgt)){
    if( fsl_db_exists(db, "SELECT 1 FROM tag WHERE tagname='tkt-%q'",
                      d->A.tgt)){
      attachToType = 't' /* attach to a known ticket */;
    }else if( fsl_db_exists(db, "SELECT 1 FROM tag WHERE tagname='event-%q'",
                            d->A.tgt)){
      attachToType = 'e' /* attach to a known technote (event) */;
    }
  }
  if('w'==attachToType){
    /* Attachment applies to a wiki page */
    if(isAdd){
      rc = fsl_buffer_appendf(&comment,
      rc = fsl_buffer_appendf(comment,
                              "Add attachment \"%h\" "
                              "to wiki page [%h]",
                              d->A.name, d->A.tgt);
    }else{
      rc = fsl_buffer_appendf(&comment,
      rc = fsl_buffer_appendf(comment,
                              "Delete attachment \"%h\" "
                              "from wiki page [%h]",
                              d->A.name, d->A.tgt);
    }
  }else if('e' == attachToType){/*technote*/
    if(isAdd){
      rc = fsl_buffer_appendf(&comment,
      rc = fsl_buffer_appendf(comment,
                              "Add attachment [/artifact/%!S|%h] to "
                              "tech note [/technote/%!S|%S]",
                              d->A.src, d->A.name, d->A.tgt, d->A.tgt);
    }else{
      rc = fsl_buffer_appendf(&comment,
      rc = fsl_buffer_appendf(comment,
                              "Delete attachment \"/artifact/%!S|%h\" "
                              "from tech note [/technote/%!S|%S]",
                              d->A.name, d->A.name, d->A.tgt,
                              d->A.tgt);
    }
  }else{
    /* Attachment applies to a ticket */
    if(isAdd){
      rc = fsl_buffer_appendf(&comment,
      rc = fsl_buffer_appendf(comment,
                              "Add attachment [/artifact/%!S|%h] "
                              "to ticket [%!S|%S]",
                              d->A.src, d->A.name, d->A.tgt, d->A.tgt);
    }else{
      rc = fsl_buffer_appendf(&comment,
      rc = fsl_buffer_appendf(comment,
                              "Delete attachment \"%h\" "
                              "from ticket [%!S|%S]",
                              d->A.name, d->A.tgt, d->A.tgt);
    }
  }
  if(!rc){
    rc = fsl_db_exec(db,
                     "REPLACE INTO event(type,mtime,objid,user,comment)"
                     "VALUES("
                     "'%c',%"FSL_JULIAN_T_PFMT",%"FSL_ID_T_PFMT","
                     "%Q,%B)",
                     attachToType, d->D, d->rid, d->U, &comment);
                     attachToType, d->D, d->rid, d->U, comment);
  }
  fsl_buffer_clear(&comment);
  fsl__cx_scratchpad_yield(d->f, comment);
  return rc;
}

/**
   Overrideable crosslink listener which updates the timeline for
   checkin records.
*/
20869
20870
20871
20872
20873
20874
20875
20876

20877
20878
20879
20880
20881
20882
20883
20748
20749
20750
20751
20752
20753
20754

20755
20756
20757
20758
20759
20760
20761
20762







-
+







    construct. Note that we are using a lot of historical code which
    hard-codes english-lanuage text and links which only work in
    fossil(1). i would prefer to farm this out to a crosslink
    callback, and provide a default implementation which more or
    less mimics fossil(1).
  */
  int rc = 0;
  fsl_buffer comment = fsl_buffer_empty;
  fsl_buffer * const comment = fsl__cx_scratchpad(d->f);
  fsl_size_t i;
  const char *zName;
  const char *zValue;
  const char *zUuid;
  int branchMove = 0;
  int const uuidLen = 8;
  fsl_card_T const * tag = NULL;
20906
20907
20908
20909
20910
20911
20912
20913

20914
20915
20916
20917
20918

20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930

20931
20932
20933
20934
20935
20936

20937
20938
20939

20940
20941
20942

20943
20944

20945
20946

20947
20948

20949
20950
20951

20952
20953
20954
20955

20956
20957
20958

20959
20960

20961
20962

20963
20964

20965
20966

20967
20968

20969
20970

20971
20972

20973
20974
20975

20976
20977

20978
20979
20980

20981
20982
20983
20984

20985
20986

20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001


21002
21003
21004
21005
21006
21007

21008
21009
21010
21011
21012
21013
21014
20785
20786
20787
20788
20789
20790
20791

20792
20793
20794
20795
20796

20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808

20809
20810
20811
20812
20813
20814

20815
20816
20817

20818
20819
20820

20821
20822

20823
20824

20825
20826

20827
20828
20829

20830
20831
20832
20833

20834
20835
20836

20837
20838

20839
20840

20841
20842

20843
20844

20845
20846

20847
20848

20849
20850

20851
20852
20853

20854
20855

20856
20857
20858

20859
20860
20861
20862

20863
20864

20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878


20879
20880
20881
20882
20883
20884
20885

20886
20887
20888
20889
20890
20891
20892
20893







-
+




-
+











-
+





-
+


-
+


-
+

-
+

-
+

-
+


-
+



-
+


-
+

-
+

-
+

-
+

-
+

-
+

-
+

-
+


-
+

-
+


-
+



-
+

-
+













-
-
+
+





-
+








     That said, sorting by UUID would have a nice side-effect on the
     output of grouping tags by the UUID they tag. So far
     (201404) such groups of tags have not appeared in the wild
     because fossil(1) has no mechanism for creating them.
  */
  for( i = 0; !rc && (i < li->used); ++i, prevTag = tag){
    char isProp = 0, isAdd = 0, isCancel = 0;
    bool isProp = 0, isAdd = 0, isCancel = 0;
    tag = (fsl_card_T const *)li->list[i];
    zUuid = tag->uuid;
    if(!zUuid /*tag on self*/) continue;
    if( i==0 || 0!=fsl_uuidcmp(tag->uuid, prevTag->uuid)){
      rc = fsl_buffer_appendf(&comment,
      rc = fsl_buffer_appendf(comment,
                              " Edit [%.*s]:", uuidLen, zUuid);
      branchMove = 0;
    }
    if(rc) goto end;
    isProp = FSL_TAGTYPE_PROPAGATING==tag->type;
    isAdd = FSL_TAGTYPE_ADD==tag->type;
    isCancel = FSL_TAGTYPE_CANCEL==tag->type;
    assert(isProp || isAdd || isCancel);
    zName = tag->name;
    zValue = tag->value;
    if( isProp && 0==fsl_strcmp(zName, "branch")){
      rc = fsl_buffer_appendf(&comment,
      rc = fsl_buffer_appendf(comment,
                              " Move to branch %s"
                              "[/timeline?r=%h&nd&dp=%.*s | %h].",
                              zValue, zValue, uuidLen, zUuid, zValue);
      branchMove = 1;
    }else if( isProp && fsl_strcmp(zName, "bgcolor")==0 ){
      rc = fsl_buffer_appendf(&comment,
      rc = fsl_buffer_appendf(comment,
                              " Change branch background color to \"%h\".", zValue);
    }else if( isAdd && fsl_strcmp(zName, "bgcolor")==0 ){
      rc = fsl_buffer_appendf(&comment,
      rc = fsl_buffer_appendf(comment,
                              " Change background color to \"%h\".", zValue);
    }else if( isCancel && fsl_strcmp(zName, "bgcolor")==0 ){
      rc = fsl_buffer_appendf(&comment, " Cancel background color.");
      rc = fsl_buffer_appendf(comment, " Cancel background color.");
    }else if( isAdd && fsl_strcmp(zName, "comment")==0 ){
      rc = fsl_buffer_appendf(&comment, " Edit check-in comment.");
      rc = fsl_buffer_appendf(comment, " Edit check-in comment.");
    }else if( isAdd && fsl_strcmp(zName, "user")==0 ){
      rc = fsl_buffer_appendf(&comment, " Change user to \"%h\".", zValue);
      rc = fsl_buffer_appendf(comment, " Change user to \"%h\".", zValue);
    }else if( isAdd && fsl_strcmp(zName, "date")==0 ){
      rc = fsl_buffer_appendf(&comment, " Timestamp %h.", zValue);
      rc = fsl_buffer_appendf(comment, " Timestamp %h.", zValue);
    }else if( isCancel && memcmp(zName, "sym-",4)==0 ){
      if( !branchMove ){
        rc = fsl_buffer_appendf(&comment, " Cancel tag %h.", zName+4);
        rc = fsl_buffer_appendf(comment, " Cancel tag %h.", zName+4);
      }
    }else if( isProp && memcmp(zName, "sym-",4)==0 ){
      if( !branchMove ){
        rc = fsl_buffer_appendf(&comment, " Add propagating tag \"%h\".", zName+4);
        rc = fsl_buffer_appendf(comment, " Add propagating tag \"%h\".", zName+4);
      }
    }else if( isAdd && memcmp(zName, "sym-",4)==0 ){
      rc = fsl_buffer_appendf(&comment, " Add tag \"%h\".", zName+4);
      rc = fsl_buffer_appendf(comment, " Add tag \"%h\".", zName+4);
    }else if( isCancel && memcmp(zName, "sym-",4)==0 ){
      rc = fsl_buffer_appendf(&comment, " Cancel tag \"%h\".", zName+4);
      rc = fsl_buffer_appendf(comment, " Cancel tag \"%h\".", zName+4);
    }else if( isAdd && fsl_strcmp(zName, "closed")==0 ){
      rc = fsl_buffer_append(&comment, " Marked \"Closed\"", -1);
      rc = fsl_buffer_append(comment, " Marked \"Closed\"", -1);
      if( !rc && zValue && *zValue ){
        rc = fsl_buffer_appendf(&comment, " with note \"%h\"", zValue);
        rc = fsl_buffer_appendf(comment, " with note \"%h\"", zValue);
      }
      if(!rc) rc = fsl_buffer_append(&comment, ".", 1);
      if(!rc) rc = fsl_buffer_append(comment, ".", 1);
    }else if( isCancel && fsl_strcmp(zName, "closed")==0 ){
      rc = fsl_buffer_append(&comment, " Removed the \"Closed\" mark", -1);
      rc = fsl_buffer_append(comment, " Removed the \"Closed\" mark", -1);
      if( !rc && zValue && *zValue ){
        rc = fsl_buffer_appendf(&comment, " with note \"%h\"", zValue);
        rc = fsl_buffer_appendf(comment, " with note \"%h\"", zValue);
      }
      if(!rc) rc = fsl_buffer_append(&comment, ".", 1);
      if(!rc) rc = fsl_buffer_append(comment, ".", 1);
    }else {
      if( isCancel ){
        rc = fsl_buffer_appendf(&comment, " Cancel \"%h\"", zName);
        rc = fsl_buffer_appendf(comment, " Cancel \"%h\"", zName);
      }else if( isAdd ){
        rc = fsl_buffer_appendf(&comment, " Add \"%h\"", zName);
        rc = fsl_buffer_appendf(comment, " Add \"%h\"", zName);
      }else{
        assert(isProp);
        rc = fsl_buffer_appendf(&comment, " Add propagating \"%h\"", zName);
        rc = fsl_buffer_appendf(comment, " Add propagating \"%h\"", zName);
      }
      if(rc) goto end;
      if( zValue && zValue[0] ){
        rc = fsl_buffer_appendf(&comment, " with value \"%h\".", zValue);
        rc = fsl_buffer_appendf(comment, " with value \"%h\".", zValue);
      }else{
        rc = fsl_buffer_append(&comment, ".", 1);
        rc = fsl_buffer_append(comment, ".", 1);
      }
    }
  } /* foreach tag loop */
  if(!rc){
    /* TODO: cached statement */
    rc = fsl_db_exec(db,
                     "REPLACE INTO event"
                     "(type,mtime,objid,user,comment) "
                     "VALUES('g',"
                     "%"FSL_JULIAN_T_PFMT","
                     "%"FSL_ID_T_PFMT","
                     "%Q,%Q)",
                     mtime, d->rid, d->U,
                     (comment.used>1)
                     ? (fsl_buffer_cstr(&comment)
                     (comment->used>1)
                     ? (fsl_buffer_cstr(comment)
                        +1/*leading space on all entries*/)
                     : NULL);
  }

  end:
  fsl_buffer_clear(&comment);
  fsl__cx_scratchpad_yield(d->f, comment);
  return rc;

}

static int fsl_deck_xlink_f_forum(fsl_deck * const d, void * state){
  if(FSL_SATYPE_FORUMPOST!=d->type) return 0;
  int rc = 0;
21198
21199
21200
21201
21202
21203
21204
21205

21206
21207
21208
21209
21210
21211
21212
21077
21078
21079
21080
21081
21082
21083

21084
21085
21086
21087
21088
21089
21090
21091







-
+







    to do all updates to the event (timeline) table via these
    crosslinkers and perform the core, UI-agnostic, crosslinking bits
    in the internal fsl__deck_crosslink_XXX() functions. That should
    allow clients to override how the timeline is updated without
    requiring them to understand the rest of the required schema
    updates.
*/
int fsl_cx_install_timeline_crosslinkers(fsl_cx * const f){
int fsl__cx_install_timeline_crosslinkers(fsl_cx * const f){
  int rc;
  assert(!f->xlinkers.used);
  assert(!f->xlinkers.list);
  rc = fsl_xlink_listener(f, "fsl/attachment/timeline",
                          fsl_deck_xlink_f_attachment, 0);
  if(!rc) rc = fsl_xlink_listener(f, "fsl/checkin/timeline",
                          fsl_deck_xlink_f_checkin, 0);
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509



21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522





































21523
21524
21525






21526
21527
21528
21529
21530
21531
21532
21379
21380
21381
21382
21383
21384
21385



21386
21387
21388













21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425



21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438







-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
+
+
+







  end:
  return rc;
}

static int fsl__deck_crosslink_ticket(fsl_deck * const d){
  int rc;
  fsl_cx * const f = d->f;
#if 0
  fsl_db * const db = fsl_cx_db_repo(f);
#endif
  char * zTag;
  fsl_stmt qAtt = fsl_stmt_empty;
  assert(f->cache.isCrosslinking
  /*
    TODO: huge block from manifest_crosslink().  A full port
    requires other infrastructure for collapsing relatively close
    time values into the same time for timeline purposes. i'd prefer
    to farm this out to a crosslink callback.  Even then, the future
    of tickets in libfossil is uncertain, but we should crosslink
    them so that repos stay compatible with fossil(1) without
    requiring a rebuild using fossil(1).
  */
  if(f->flags & FSL_CX_F_SKIP_UNKNOWN_CROSSLINKS){
    return 0;
  }
  rc = fsl_cx_err_set(f, FSL_RC_NYI,
         && "This only works if fsl__crosslink_begin() is active.");
  zTag = fsl_mprintf("tkt-%s", d->K);
  if(!zTag) return FSL_RC_OOM;
  rc = fsl__tag_insert(f, FSL_TAGTYPE_ADD, zTag, NULL,
                       d->rid, d->D, d->rid, NULL);
  fsl_free(zTag);
  if(rc) goto end;
  assert(d->K);
  rc = fsl__deck_crosslink_add_pending(f, 't', d->K);
  if(rc) goto end;;
  /* Locate and update comment for any attachments */
  rc = fsl_cx_prepare(f, &qAtt,
                      "SELECT attachid, src, target, filename FROM attachment"
                      " WHERE target=%Q",
                      d->K);
  while(0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&qAtt)){
    const char *zAttachId = fsl_stmt_g_text(&qAtt, 0, NULL);
    const char *zSrc = fsl_stmt_g_text(&qAtt, 1, NULL);
    const char *zTarget = fsl_stmt_g_text(&qAtt, 2, NULL);
    const char *zName = fsl_stmt_g_text(&qAtt, 3, NULL);
    const bool isAdd = (zSrc && zSrc[0]) ? true : false;
    char *zComment;
    if( isAdd ){
      zComment =
        fsl_mprintf(
                    "Add attachment [/artifact/%!S|%h] to ticket [%!S|%S]",
                    zSrc, zName, zTarget, zTarget);
    }else{
      zComment =
        fsl_mprintf("Delete attachment \"%h\" from ticket [%!S|%S]",
                    zName, zTarget, zTarget);
    }
    if(!zComment){
      rc = FSL_RC_OOM;
      break;
    }
    rc = fsl_cx_exec_multi(f, "UPDATE event SET comment=%Q, type='t'"
                      "MISSING: a huge block of TICKET stuff from "
                      "manifest_crosslink(). It requires infrastructure "
                      "libfossil does not yet have.");
                           " WHERE objid=%Q",
                           zComment, zAttachId);
    fsl_free(zComment);
  }
  end:
  fsl_stmt_finalize(&qAtt);
  return rc;
}

int fsl__deck_crosslink_one( fsl_deck * const d ){
  int rc;
  assert(d->f && "API misuse:fsl_deck::f == NULL");
  rc = fsl__crosslink_begin(d->f);
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618




21619
21620

21621
21622

21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647

21648
21649
21650
21651
21652
21653
21654
21655
21656
21512
21513
21514
21515
21516
21517
21518


21519



21520
21521
21522
21523


21524


21525















21526
21527
21528
21529
21530
21531
21532
21533
21534

21535
21536

21537
21538
21539
21540
21541
21542
21543







-
-

-
-
-
+
+
+
+
-
-
+
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-









-
+

-







      rc = fsl__deck_crosslink_attachment(d);
      break;
    /* FSL_SATYPE_CONTROL is handled above except for the timeline
       update, which is handled by a callback below */
    default:
      break;
  }
  if(rc) goto end;

  /* Call any crosslink callbacks... */
  if(f->xlinkers.list){
    fsl_size_t i;
    fsl_xlinker * xl = NULL;
  if(0==rc && FSL_SATYPE_TICKET!=d->type){
    /* ^^^ the real work of ticket crosslinking is delated until
       fsl__crosslink_end(), for reasons lost to history, so we'll skip
       calling the xlink listeners for those until that step. */
    for( i = 0; !rc && (i < f->xlinkers.used); ++i ){
      xl = f->xlinkers.list+i;
    rc = fsl__call_xlink_listeners(d);
      rc = xl->f( d, xl->state );
    }
  }
    if(rc){
      assert(xl);
      if(!f->error.code){
        if(f->dbMain->error.code){
          fsl_cx_uplift_db_error(f, f->dbMain);
        }else{
          fsl_cx_err_set(f, rc, "Crosslink callback handler "
                         "'%s' failed with code %d (%s) for "
                         "artifact RID #%" FSL_ID_T_PFMT ".",
                         xl->name, rc, fsl_rc_cstr(rc),
                         d->rid);
        }
      }
    }
  }/*end crosslink callbacks*/
  end:
  if(!rc){
    rc = fsl_db_transaction_end(db, false);
  }else{
    if(db->error.code && !f->error.code){
      fsl_cx_uplift_db_error(f,db);
    }
    fsl_db_transaction_end(db, true);
  }
  return rc;
  return rc ? rc : f->interrupted;
}/*end fsl__deck_crosslink()*/



/**
    Return true if z points to the first character after a blank line.
    Tolerate either \r\n or \n line endings. As this looks backwards
    in z, z must point to at least 3 characters past the beginning of
    a legal string.
21745
21746
21747
21748
21749
21750
21751
21752

21753
21754

21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766

21767
21768
21769


21770
21771
21772
21773
21774
21775





21776
21777
21778
21779






21780
21781
21782
21783

21784
21785
21786
21787

21788
21789
21790
21791
21792
21793
21794
21795

21796
21797
21798
21799
21800
21801

21802
21803
21804

21805
21806
21807
21808
21809
21810
21811
21632
21633
21634
21635
21636
21637
21638

21639
21640

21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652

21653
21654


21655
21656
21657
21658
21659



21660
21661
21662
21663
21664
21665



21666
21667
21668
21669
21670
21671




21672
21673
21674
21675

21676
21677
21678
21679
21680
21681
21682
21683

21684
21685
21686
21687
21688
21689

21690
21691
21692

21693
21694
21695
21696
21697
21698
21699
21700







-
+

-
+











-
+

-
-
+
+



-
-
-
+
+
+
+
+

-
-
-
+
+
+
+
+
+
-
-
-
-
+



-
+







-
+





-
+


-
+







  *pn = (fsl_size_t)n;
  return;
}


/**
    Internal helper for parsing manifests. Holds a source file (memory
    range) and gets updated by fsl_deck_next_token() and friends.
    range) and gets updated by fsl__deck_next_token() and friends.
*/
struct fsl_src {
struct fsl__src {
  /**
      First char of the next token.
   */
  unsigned char * z;
  /**
      One-past-the-end of the manifest.
   */
  unsigned char * zEnd;
  /**
      True if z points to the start of a new line.
   */
  char atEol;
  bool atEol;
};
typedef struct fsl_src fsl_src;
static const fsl_src fsl_src_empty = {NULL,NULL,0};
typedef struct fsl__src fsl__src;
static const fsl__src fsl__src_empty = {NULL,NULL,0};

/**
   Return a pointer to the next token.  The token is zero-terminated.
   Return NULL if there are no more tokens on the current line.  If
   pLen is not NULL and this function returns non-NULL then *pLen is
   set to the byte length of the new token.
   Return NULL if there are no more tokens on the current line, but
   the call after that will return non-NULL unless we have reached the
   end of the input. If this function returns non-NULL then *pLen is
   set to the byte length of the new token. Once the end of the input
   is reached, this function always returns NULL.
*/
static unsigned char *fsl_deck_next_token(fsl_src *p, fsl_size_t *pLen){
  unsigned char *z;
  unsigned char *zStart;
static unsigned char *fsl__deck_next_token(fsl__src * const p,
                                           fsl_size_t * const pLen){
  if( p->atEol ) return NULL;
  int c;
  unsigned char * z = p->z;
  unsigned char * const zStart = z;
  int c;
  if( p->atEol ) return NULL;
  zStart = z = p->z;
  while( (c=(*z))!=' ' && c!='\n' ){ ++z; }
  while( (c=(*z))!=' ' && c!='\n' ) ++z;
  *z = 0;
  p->z = &z[1];
  p->atEol = c=='\n';
  if( pLen ) *pLen = z - zStart;
  *pLen = z - zStart;
  return zStart;
}

/**
    Return the card-type for the next card. Return 0 if there are no
    more cards or if we are not at the end of the current card.
 */
static unsigned char mf_next_card(fsl_src *p){
static unsigned char deck__next_card(fsl__src * const p){
  unsigned char c;
  if( !p->atEol || p->z>=p->zEnd ) return 0;
  c = p->z[0];
  if( p->z[1]==' ' ){
    p->z += 2;
    p->atEol = 0;
    p->atEol = false;
  }else if( p->z[1]=='\n' ){
    p->z += 2;
    p->atEol = 1;
    p->atEol = true;
  }else{
    c = 0;
  }
  return c;
}

/**
21878
21879
21880
21881
21882
21883
21884
21885

21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897


21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911

21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924







21925
21926

21927
21928

21929
21930





21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941

21942
21943
21944
21945

21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961



21962
21963
21964
21965
21966
21967
21968
21767
21768
21769
21770
21771
21772
21773

21774
21775

21776
21777
21778
21779
21780
21781
21782
21783


21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798

21799













21800
21801
21802
21803
21804
21805
21806


21807


21808


21809
21810
21811
21812
21813
21814
21815
21816
21817







21818
21819
21820
21821

21822
21823
21824
21825
21826
21827


21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846







-
+

-








-
-
+
+













-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
+
-
-
+
-
-
+
+
+
+
+




-
-
-
-
-
-
-
+



-
+





-
-









+
+
+







#ifdef ERROR
#  undef ERROR
#endif
#define ERROR(RC,MSG) do{ rc = (RC); zMsg = (MSG); goto bailout; } while(0)
#define SYNTAX(MSG) ERROR(rc ? rc : FSL_RC_SYNTAX,MSG)
  bool isRepeat = 0/* , hasSelfRefTag = 0 */;
  int rc = 0;
  fsl_src x = fsl_src_empty;
  fsl__src x = fsl__src_empty;
  char const * zMsg = NULL;
  fsl_id_bag * seen;
  char cType = 0, cPrevType = 0;
  unsigned char * z = src ? src->mem : NULL;
  fsl_size_t tokLen = 0;
  unsigned char * token;
  fsl_size_t n = z ? src->used : 0;
  unsigned char * uuid;
  double ts;
  int cardCount = 0;
  fsl_cx * f;
  fsl_error * err;
  fsl_cx * const f = d->f;
  fsl_error * const err = f ? &f->error : 0;
  int stealBuf = 0 /* gets incremented if we need to steal src->mem. */;
  unsigned nSelfTag = 0 /* number of T cards which refer to '*' (this artifact). */;
  unsigned nSimpleTag = 0 /* number of T cards with "+" prefix */;
  /*
    lettersSeen keeps track of the card letters we have seen so that
    we can then relatively quickly figure out what type of manifest we
    have parsed without having to inspect the card contents. Each
    index records a count of how many of that card we've seen.
  */
  int lettersSeen[27] = {0/*A*/,0,0,0,0,0,0,0,0,0,0,0,0,
                         0,0,0,0,0,0,0,0,0,0,0,0,0/*Z*/,
                         0 /* sentinel element for reasons lost to
                             history but removing it breaks stuff. */};
  if(!d->f || !z) return FSL_RC_MISUSE;
  if(!f || !z) return FSL_RC_MISUSE;
  /* Every control artifact ends with a '\n' character.  Exit early
     if that is not the case for this artifact. */
  f = d->f;

  if(rid>0){
    d->rid = rid;
#if 1
    if(fsl__cx_mcache_search2(f, rid, d, FSL_SATYPE_ANY, &rc) || rc){
      if(0==rc){
        assert(d->rid == rid);
        fsl_buffer_clear(src);
      }
      return rc;
  if(rid>0 && (fsl__cx_mcache_search2(f, rid, d, FSL_SATYPE_ANY, &rc)
               || rc)){
    if(0==rc){
      assert(d->rid == rid);
      fsl_buffer_clear(src);
    }
    return rc;
    }
#endif
  }else if(rid<0){
  }

    return fsl_error_set(err, FSL_RC_RANGE,
  err = &f->error;
  if(!*z || !n || ( '\n' != z[n-1]) ){
                         "Invalid (negative) RID %" FSL_ID_T_PFMT
                         " for %s()", rid, __func__);
  }else if(!*z || !n || ( '\n' != z[n-1]) ){
    /* Every control artifact ends with a '\n' character. Exit early
       if that is not the case for this artifact. */
    return fsl_error_set(err, FSL_RC_SYNTAX, "%s.",
                         n ? "Not terminated with \\n"
                         : "Zero-length input");
  }
  else if(rid<0){
    return fsl_error_set(err, FSL_RC_RANGE,
                         "Invalid (negative) RID %"FSL_ID_T_PFMT
                         " for fsl_deck_parse()", rid);
  }
  seen = &f->cache.mfSeen;
  if((0==rid) || fsl_id_bag_contains(seen,rid)){
  if((0==rid) || fsl_id_bag_contains(&f->cache.mfSeen,rid)){
    isRepeat = 1;
  }else{
    isRepeat = 0;
    rc = fsl_id_bag_insert(seen, rid);
    rc = fsl_id_bag_insert(&f->cache.mfSeen, rid);
    if(rc){
      assert(FSL_RC_OOM==rc);
      return rc;
    }
  }
  fsl_deck_clean(d);
  fsl_deck_init(f, d, FSL_SATYPE_ANY);

  /*
    Verify that the first few characters of the artifact look like a
    control artifact.
  */
  if( !fsl_might_be_artifact(src) ){
    SYNTAX("Content does not look like a structural artifact");
  }

  fsl_deck_clean(d);
  fsl_deck_init(f, d, FSL_SATYPE_ANY);

  /*
    Strip off the PGP signature if there is one. Example of signed
    manifest:

    https://fossil-scm.org/index.html/artifact/28987096ac
  */
  {
21980
21981
21982
21983
21984
21985
21986
21987

21988
21989
21990
21991
21992

21993
21994
21995

21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014

22015
22016
22017
22018
22019
22020
22021
21858
21859
21860
21861
21862
21863
21864

21865
21866
21867
21868
21869

21870
21871
21872

21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891

21892
21893
21894
21895
21896
21897
21898
21899







-
+




-
+


-
+


















-
+







     if( !isRepeat ) g.parseCnt[0]++; */

  /*
    Reminder: parsing modifies the input (to simplify the
    tokenization/parsing).

    As of mid-201403, we recycle as much as possible from the source
    buffer and take over ownership _if_ we do so.
    buffer.
  */
  /* Now parse, card by card... */
  x.z = z;
  x.zEnd = z+n;
  x.atEol= 1;
  x.atEol= true;

  /* Parsing helpers... */
#define TOKEN(DEFOS) tokLen=0; token = fsl_deck_next_token(&x,&tokLen);    \
#define TOKEN(DEFOS) tokLen=0; token = fsl__deck_next_token(&x,&tokLen);    \
  if(token && tokLen && (DEFOS)) fsl_bytes_defossilize(token, &tokLen)
#define TOKEN_EXISTS(MSG_IF_NOT) if(!token){ SYNTAX(MSG_IF_NOT); }(void)0
#define TOKEN_CHECKHEX(MSG) if(token && (int)tokLen!=fsl_is_uuid((char const *)token))\
  { SYNTAX(MSG); }
#define TOKEN_UUID(CARD) TOKEN_CHECKHEX("Malformed UUID in " #CARD "-card")
#define TOKEN_MD5(ERRMSG) if(!token || FSL_STRLEN_MD5!=(int)tokLen) \
  {SYNTAX(ERRMSG);}
  /**
     Reminder: we do not know the type of the manifest at this point,
     so all of the fsl_deck_add/set() bits below can't do their
     validation. We have to determine at parse-time (or afterwards)
     which type of deck it is based on the cards we've seen. We guess
     the type as early as possible to enable during-parse validation,
     and do a post-parse check for the legality of cards added before
     validation became possible.
   */
  
#define SEEN(CARD) lettersSeen[*#CARD - 'A']
  for( cPrevType=1; !rc && (0 < (cType = mf_next_card(&x)));
  for( cPrevType=1; !rc && (0 < (cType = deck__next_card(&x)));
       cPrevType = cType ){
    ++cardCount;
    if(cType<cPrevType){
      if(d->E.uuid && 'N'==cType && 'P'==cPrevType){
        /* Workaround for a pair of historical fossil bugs
           which synergized to allow malformed technotes to
           be saved:
22029
22030
22031
22032
22033
22034
22035
22036

22037
22038
22039
22040
22041
22042
22043
21907
21908
21909
21910
21911
21912
21913

21914
21915
21916
21917
21918
21919
21920
21921







-
+







        ++lettersSeen[cType-'A'];
    }else{
      SYNTAX("Invalid card name");
    }
    switch(cType){
      /*
             A <filename> <target> ?<source>?
        

         Identifies an attachment to either a wiki page, a ticket, or
         a technote.  <source> is the artifact that is the attachment.
         <source> is omitted to delete an attachment.  <target> is the
         name of a wiki page, technote, or ticket to which that
         attachment is connected.
      */
      case 'A':{
22064
22065
22066
22067
22068
22069
22070
22071

22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088

22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107

22108
22109
22110
22111
22112
22113
22114
21942
21943
21944
21945
21946
21947
21948

21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965

21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984

21985
21986
21987
21988
21989
21990
21991
21992







-
+
















-
+


















-
+







        /*rc = fsl_deck_A_set(d, (char const *)name,
          (char const *)uuid, (char const *)src);*/
        d->type = FSL_SATYPE_ATTACHMENT;
        break;
      }
      /*
            B <uuid>
        

         A B-line gives the UUID for the baseline of a delta-manifest.
      */
      case 'B':{
        if(d->B.uuid){
          SYNTAX("Multiple B-cards");
        }
        TOKEN(0);
        TOKEN_UUID(B);
        d->B.uuid = (char *)token;
        ++stealBuf;
        d->type = FSL_SATYPE_CHECKIN;
        /* rc = fsl_deck_B_set(d, (char const *)token); */
        break;
      }
      /*
             C <comment>
        

         Comment text is fossil-encoded.  There may be no more than
         one C line.  C lines are required for manifests, are optional
         for Events and Attachments, and are disallowed on all other
         control files.
      */
      case 'C':{
        if( d->C ){
          SYNTAX("more than one C-card");
        }
        TOKEN(1);
        TOKEN_EXISTS("Missing comment text for C-card");
        /* rc = fsl_deck_C_set(d, (char const *)token, (fsl_int_t)tokLen); */
        d->C = (char *)token;
        ++stealBuf;
        break;
      }
      /*
             D <timestamp>
        

         The timestamp should be ISO 8601.   YYYY-MM-DDtHH:MM:SS
         There can be no more than 1 D line.  D lines are required
         for all control files except for clusters.
      */
      case 'D':{
#define TOKEN_DATETIME(LETTER,MEMBER)                                     \
        if( d->MEMBER>0.0 ) { SYNTAX("More than one "#LETTER"-card"); } \
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135







22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150

22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164


22165
22166
22167
22168
22169






22170
22171
22172
22173
22174
22175
22176
22177
22178
22001
22002
22003
22004
22005
22006
22007






22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028

22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045





22046
22047
22048
22049
22050
22051


22052
22053
22054
22055
22056
22057
22058







-
-
-
-
-
-
+
+
+
+
+
+
+














-
+














+
+
-
-
-
-
-
+
+
+
+
+
+
-
-








        TOKEN_DATETIME(D,D);
        rc = fsl_deck_D_set(d, ts);
        break;
      }
      /*
             E <timestamp> <uuid>
        
         An "event" card that contains the timestamp of the event in the 
         format YYYY-MM-DDtHH:MM:SS and a unique identifier for the event.
         The event timestamp is distinct from the D timestamp.  The D
         timestamp is when the artifact was created whereas the E timestamp
         is when the specific event is said to occur.

         An "event" (technote) card that contains the timestamp of the
         event in the format YYYY-MM-DDtHH:MM:SS and a unique
         identifier for the event. The event timestamp is distinct
         from the D timestamp. The D timestamp is when the artifact
         was created whereas the E timestamp is when the specific
         event is said to occur.
      */
      case 'E':{
        TOKEN_DATETIME(E,E.julian);
        TOKEN(0);
        TOKEN_EXISTS("Missing UUID part of E-card");
        TOKEN_UUID(E);
        d->E.julian = ts;
        d->E.uuid = (char *)token;
        ++stealBuf;
        d->type = FSL_SATYPE_EVENT;
        break;
      }
      /*
             F <filename> ?<uuid>? ?<permissions>? ?<old-name>?
        

         Identifies a file in a manifest.  Multiple F lines are
         allowed in a manifest.  F lines are not allowed in any other
         control file.  The filename and old-name are fossil-encoded.

         In delta manifests, deleted files are denoted by the 1-arg
         form. In baseline manifests, deleted files simply are not in
         the manifest.
      */
      case 'F':{
        char * name;
        char * perms = NULL;
        char * priorName = NULL;
        fsl_fileperm_e perm = FSL_FILE_PERM_REGULAR;
        fsl_card_F * fc = NULL;
        rc = 0;
        if(!d->F.capacity){
        /**
           Basic tests with various repos have shown that the
           approximate number of F-cards in a manifest is rougly the
           manifest size/75. We'll use that as an initial alloc size.
        */
          /**
             Basic tests with various repos have shown that the
             approximate number of F-cards in a manifest is roughly
             the manifest size/75. We'll use that as an initial alloc
             size.
          */
        rc = 0;
        if(!d->F.capacity){
          rc = fsl_card_F_list_reserve(&d->F, src->used/75+10);
        }
        TOKEN(0);
        TOKEN_EXISTS("Missing name for F-card");
        name = (char *)token;
        TOKEN(0);
        TOKEN_UUID(F);
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209

22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229

22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246

22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264

22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282


22283
22284
22285
22286
22287
22288
22289
22075
22076
22077
22078
22079
22080
22081

22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108

22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125

22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143

22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160


22161
22162
22163
22164
22165
22166
22167
22168
22169







-







+



















-
+
















-
+

















-
+
















-
-
+
+







              /*MARKER(("Unmatched perms string character: %d / %c !", (int)*perms, *perms));*/
              SYNTAX("Invalid perms string character");
          }
          TOKEN(0);
          if(token) priorName = (char *)token;
        }
        fsl_bytes_defossilize( (unsigned char *)name, 0 );
        if(priorName) fsl_bytes_defossilize( (unsigned char *)priorName, 0 );
        if(fsl_is_reserved_fn(name, -1)){
          /* Some historical (pre-late-2020) manifests contain files
             they really shouldn't, like _FOSSIL_ and .fslckout.
             Since late 2020, fossil simply skips over these when
             parsing manifests, so we'll do the same. */
          break;
        }
        if(priorName) fsl_bytes_defossilize( (unsigned char *)priorName, 0 );
        fc = rc ? 0 : fsl_card_F_list_push(&d->F);
        if(!fc){
          zMsg = "OOM";
          goto bailout;
        }
        ++stealBuf;
        assert(d->F.used>1
               ? (FSL_CARD_F_LIST_NEEDS_SORT & d->F.flags)
               : 1);
        fc->deckOwnsStrings = true;
        fc->name = name;
        fc->priorName = priorName;
        fc->perm = perm;
        fc->uuid = (fsl_uuid_str)uuid;
        d->type = FSL_SATYPE_CHECKIN;
        break;
      }
      /*
        G <uuid>
        

        A G-line gives the UUID for the thread root of a forum post.
      */
      case 'G':{
        if(d->G){
          SYNTAX("Multiple G-cards");
        }
        TOKEN(0);
        TOKEN_EXISTS("Missing UUID in G-card");
        TOKEN_UUID(G);
        d->G = (char*)token;
        ++stealBuf;
        d->type = FSL_SATYPE_FORUMPOST;
        break;
      }
     /*
         H <forum post title>
        

         H text is fossil-encoded.  There may be no more than one H
         line.  H lines are optional for forum posts and are
         disallowed on all other control files.
      */
      case 'H':{
        if( d->H ){
          SYNTAX("more than one H-card");
        }
        TOKEN(1);
        TOKEN_EXISTS("Missing text for H-card");
        d->H = (char *)token;
        ++stealBuf;
        d->type = FSL_SATYPE_FORUMPOST;
        break;
      }
      /*
        I <uuid>
        

        A I-line gives the UUID for the in-response-to UUID for 
        a forum post.
      */
      case 'I':{
        if(d->I){
          SYNTAX("Multiple I-cards");
        }
        TOKEN(0);
        TOKEN_EXISTS("Missing UUID in I-card");
        TOKEN_UUID(I);
        d->I = (char*)token;
        ++stealBuf;
        d->type = FSL_SATYPE_FORUMPOST;
        break;
      }
      /*
             J <name> ?<value>?
        
         J <name> ?<value>?

         Specifies a name value pair for ticket.  If the first character
         of <name> is "+" then the <value> is appended to any preexisting
         value.  If <value> is omitted then it is understood to be an
         empty string.
      */
      case 'J':{
        char const * field;
22298
22299
22300
22301
22302
22303
22304
22305
22306


22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324


22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341


22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361


22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377


22378
22379
22380
22381
22382
22383
22384
22178
22179
22180
22181
22182
22183
22184


22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202


22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219


22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239


22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255


22256
22257
22258
22259
22260
22261
22262
22263
22264







-
-
+
+
















-
-
+
+















-
-
+
+


















-
-
+
+














-
-
+
+







        TOKEN(1);
        rc = fsl_deck_J_add(d, isAppend, field,
                            (char const *)token);
        d->type = FSL_SATYPE_TICKET;
        break;
      }
      /*
            K <uuid>
        
         K <uuid>

         A K-line gives the UUID for the ticket which this control file
         is amending.
      */
      case 'K':{
        if(d->K){
          SYNTAX("Multiple K-cards");
        }
        TOKEN(0);
        TOKEN_EXISTS("Missing UUID in K-card");
        TOKEN_UUID(K);
        d->K = (char*)token;
        ++stealBuf;
        d->type = FSL_SATYPE_TICKET;
        break;
      }
      /*
             L <wikititle>
        
         L <wikititle>

         The wiki page title is fossil-encoded.  There may be no more than
         one L line.
      */
      case 'L':{
        if(d->L){
          SYNTAX("Multiple L-cards");
        }
        TOKEN(1);
        TOKEN_EXISTS("Missing text for L-card");
        d->L = (char*)token;
        ++stealBuf;
        d->type = FSL_SATYPE_WIKI;
        break;
      }
      /*
            M <uuid>
        
         M <uuid>

         An M-line identifies another artifact by its UUID.  M-lines
         occur in clusters only.
      */
      case 'M':{
        TOKEN(0);
        TOKEN_EXISTS("Missing UUID for M-card");
        TOKEN_UUID(M);
        ++stealBuf;
        d->type = FSL_SATYPE_CLUSTER;
        rc = fsl_list_append(&d->M, token);
        if( !rc && d->M.used>1 &&
            fsl_strcmp((char const *)d->M.list[d->M.used-2],
                       (char const *)token)>=0 ){
          SYNTAX("M-card in the wrong order");
        }
        break;
      }
      /*
            N <uuid>
        
         N <uuid>

         An N-line identifies the mimetype of wiki or comment text.
      */
      case 'N':{
        if(1<SEEN(N)){
          SYNTAX("Multiple N-cards");
        }
        TOKEN(0);
        TOKEN_EXISTS("Missing UUID on N-card");
        ++stealBuf;
        d->N = (char *)token;
        break;
      }

      /*
             P <uuid> ...
        
         P <uuid> ...

         Specify one or more other artifacts which are the parents of
         this artifact.  The first parent is the primary parent.  All
         others are parents by merge.
      */
      case 'P':{
        if(1<SEEN(P)){
          SYNTAX("More than one P-card");
22400
22401
22402
22403
22404
22405
22406
22407
22408


22409
22410
22411
22412
22413
22414
22415
22280
22281
22282
22283
22284
22285
22286


22287
22288
22289
22290
22291
22292
22293
22294
22295







-
-
+
+







          if(!rc){
            TOKEN(0);
          }
        }
        break;
      }
      /*
             Q (+|-)<uuid> ?<uuid>?
        
         Q (+|-)<uuid> ?<uuid>?

         Specify one or a range of checkins that are cherrypicked into
         this checkin ("+") or backed out of this checkin ("-").
      */
      case 'Q':{
        fsl_cherrypick_type_e qType = FSL_CHERRYPICK_INVALID;
        TOKEN(0);
        TOKEN_EXISTS("Missing target UUID for Q-card");
22428
22429
22430
22431
22432
22433
22434
22435
22436


22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455



22456
22457
22458
22459
22460
22461
22462



22463
22464

22465
22466
22467
22468
22469
22470
22471
22308
22309
22310
22311
22312
22313
22314


22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332



22333
22334
22335
22336
22337
22338
22339



22340
22341
22342
22343

22344
22345
22346
22347
22348
22349
22350
22351







-
-
+
+
















-
-
-
+
+
+




-
-
-
+
+
+

-
+







        }
        d->type = FSL_SATYPE_CHECKIN;
        rc = fsl_deck_Q_add(d, qType, (char const *)uuid,
                            (char const *)token);
        break;
      }
      /*
             R <md5sum>
        
         R <md5sum>

         Specify the MD5 checksum over the name and content of all files
         in the manifest.
      */
      case 'R':{
        if(1<SEEN(R)){
          SYNTAX("More than one R-card");
        }
        TOKEN(0);
        TOKEN_EXISTS("Missing MD5 token in R-card");
        TOKEN_MD5("Malformed MD5 token in R-card");
        d->R = (char *)token;
        ++stealBuf;
        d->type = FSL_SATYPE_CHECKIN;
        break;
      }
      /*
            T (+|*|-)<tagname> <uuid> ?<value>?
        
         Create or cancel a tag or property.  The tagname is fossil-encoded.
         T (+|*|-)<tagname> <uuid> ?<value>?

         Create or cancel a tag or property. The tagname is fossil-encoded.
         The first character of the name must be either "+" to create a
         singleton tag, "*" to create a propagating tag, or "-" to create
         anti-tag that undoes a prior "+" or blocks propagation of of
         a "*".
        
         The tag is applied to <uuid>.  If <uuid> is "*" then the tag is
         applied to the current manifest.  If <value> is provided then 

         The tag is applied to <uuid>. If <uuid> is "*" then the tag is
         applied to the current manifest. If <value> is provided then 
         the tag is really a property with the given value.
        

         Tags are not allowed in clusters.  Multiple T lines are allowed.
      */
      case 'T':{
        unsigned char * name, * value;
        fsl_tagtype_e tagType = FSL_TAGTYPE_INVALID;
        TOKEN(1);
        TOKEN_EXISTS("Missing name for T-card");
22494
22495
22496
22497
22498
22499
22500
22501

22502
22503
22504







22505
22506
22507


















22508
22509
22510
22511
22512


22513
22514
22515
22516
22517
22518
22519
22374
22375
22376
22377
22378
22379
22380

22381
22382


22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413


22414
22415
22416
22417
22418
22419
22420
22421
22422







-
+

-
-
+
+
+
+
+
+
+



+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+



-
-
+
+







          case '+': tagType = FSL_TAGTYPE_ADD;
            ++nSimpleTag;
            break;
          case '-': tagType = FSL_TAGTYPE_CANCEL; break;
          default: SYNTAX("Malformed tag name");
        }
        ++name /* skip type marker byte */;
        /* Potential todo: add the order check from this commit:
        /* Tag order check from:

        https://fossil-scm.org/index.html/info/55cacfcace
        */
           https://fossil-scm.org/home/info/55cacfcace

           (It was subsequently made stricter so that the same tag
           type/name/target combination fails.)

           That's difficult to do here until _after_ we add the new
           tag to the list... */
        rc = fsl_deck_T_add(d, tagType, (fsl_uuid_cstr)uuid,
                            (char const *)name,
                            (char const *)value);
        if(0==rc && d->T.used>1){
          fsl_card_T const * tagPrev =
            (fsl_card_T const *)d->T.list[d->T.used-2];
          fsl_card_T const * tagSelf =
            (fsl_card_T const *)d->T.list[d->T.used-1];
          int const cmp = fsl_card_T_cmp(&tagPrev, &tagSelf);
          if(cmp>=0){
            rc = fsl_cx_err_set(d->f, FSL_RC_SYNTAX,
                                "T-cards are not in lexical order: "
                                "%c%s %s %c%s",
                                fsl_tag_prefix_char(tagPrev->type),
                                tagPrev->name,
                                cmp ? ">=" : "==",
                                fsl_tag_prefix_char(tagSelf->type),
                                tagSelf->name);
            goto bailout;
          }
        }
        break;
      }
      /*
             U ?<login>?
        
         U ?<login>?

         Identify the user who created this control file by their
         login.  Only one U line is allowed.  Prohibited in clusters.
         If the user name is omitted, take that to be "anonymous".
      */
      case 'U':{
        if(d->U) SYNTAX("More than one U-card");
        TOKEN(1);
22543
22544
22545
22546
22547
22548
22549
22550
22551




22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562

22563
22564
22565
22566
22567
22568
22569
22446
22447
22448
22449
22450
22451
22452


22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466

22467
22468
22469
22470
22471
22472
22473
22474







-
-
+
+
+
+










-
+







        wlen = fsl_str_to_size((char const *)token);
        if((fsl_size_t)-1==wlen){
          SYNTAX("Wiki size token is invalid");
        }
        if( (&x.z[wlen+1]) > x.zEnd){
          SYNTAX("Not enough content after W-card");
        }
        rc = fsl_buffer_append(&d->W, x.z, wlen);
        if(rc) goto bailout;
        //rc = fsl_buffer_append(&d->W, x.z, wlen);
        //if(rc) goto bailout;
        fsl_buffer_external(&d->W, x.z, wlen);
        ++stealBuf;
        x.z += wlen;
        if( '\n' != x.z[0] ){
          SYNTAX("W-card content not \\n terminated");
        }
        x.z[0] = 0;
        ++x.z;
        break;
      }
      /*
             Z <md5sum>
        

         MD5 checksum on this control file.  The checksum is over all
         lines (other than PGP-signature lines) prior to the current
         line.  This must be the last record.
        
         This card is required for all control file types except for
         Manifest. It is not required for manifest only for historical
         compatibility reasons.
22610
22611
22612
22613
22614
22615
22616
22617

22618
22619
22620
22621
22622
22623
22624
22625
22515
22516
22517
22518
22519
22520
22521

22522

22523
22524
22525
22526
22527
22528
22529







-
+
-







    rc = d->f->error.code;
    goto bailout;
  }

  if(FSL_SATYPE_ANY==d->type){
    rc = fsl_cx_err_set(f, FSL_RC_ERROR,
                        "Internal error: could not determine type of "
                        "control artifact we just (successfully!) "
                        "artifact we just (successfully!) parsed.");
                        "parsed.");
    goto bailout;
  }else {
    /*
      Make sure we didn't pick up any cards which were picked up
      before d->type was guessed and are invalid for the post-guessed
      type.
    */
22645
22646
22647
22648
22649
22650
22651
22652

22653
22654
22655
22656
22657
22658

22659
22660
22661
22662
22663
22664
22665
22666

22667
22668

22669
22670
22671
22672
22673
22674
22675
22549
22550
22551
22552
22553
22554
22555

22556
22557
22558
22559
22560
22561

22562
22563
22564
22565
22566
22567
22568
22569

22570
22571

22572
22573
22574
22575
22576
22577
22578
22579







-
+





-
+







-
+

-
+







         FSL_SATYPE_FORUMPOST==d->type);
  assert(0==rc);

  /* Additional checks based on artifact type */
  switch( d->type ){
    case FSL_SATYPE_CONTROL: {
      if( nSelfTag ){
        SYNTAX("self-referential T-card in control artifact");
        SYNTAX("Self-referential T-card in control artifact");
      }
      break;
    }
    case FSL_SATYPE_TECHNOTE: {
      if( d->T.used!=nSelfTag ){
        SYNTAX("non-self-referential T-card in technote");
        SYNTAX("Non-self-referential T-card in technote");
      }else if( d->T.used!=nSimpleTag ){
        SYNTAX("T-card with '*' or '-' in technote");
      }
      break;
    }
    case FSL_SATYPE_FORUMPOST: {
      if( d->H && d->I ){
        SYNTAX("cannot have I-card and H-card in a forum post");
        SYNTAX("Cannot have I-card and H-card in a forum post");
      }else if( d->P.used>1 ){
        SYNTAX("too many arguments to P-card");
        SYNTAX("Too many arguments to P-card");
      }
      break;
    }
    default: break;
  }

  assert(!d->content.mem);
22930
22931
22932
22933
22934
22935
22936
22937

22938
22939
22940
22941
22942
22943
22944
22834
22835
22836
22837
22838
22839
22840

22841
22842
22843
22844
22845
22846
22847
22848







-
+







#undef FCARD
}

int fsl_deck_save( fsl_deck * const d, bool isPrivate ){
  int rc;
  fsl_cx * const f = d->f;
  fsl_db * const db = fsl_needs_repo(f);
  fsl_buffer * const buf = &d->f->fileContent;
  fsl_buffer * const buf = &d->f->cache.fileContent;
  fsl_id_t newRid = 0;
  bool const oldPrivate = f->cache.markPrivate;
  if(!f || !d ) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  if(d->rid>0){
#if 1
    return 0;
23108
23109
23110
23111
23112
23113
23114
23115
23116

23117
23118
23119
23120
23121
23122
23123
23124

23125
23126
23127
23128
23129
23130
23131
23132
23133



23134
23135
23136
23137
23138
23139
23140
23012
23013
23014
23015
23016
23017
23018


23019
23020
23021
23022
23023
23024
23025


23026
23027
23028
23029
23030
23031
23032
23033


23034
23035
23036
23037
23038
23039
23040
23041
23042
23043







-
-
+






-
-
+







-
-
+
+
+







    if(rc) break;
  }
  fsl_stmt_finalize(&q);
  if(rc) goto end;

  /* Process entries from pending_xlink temp table... */
  rc = fsl_cx_prepare(f, &q, "SELECT id FROM pending_xlink");
  if(rc) goto end;
  while( FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){
  while( 0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){
    const char *zId = fsl_stmt_g_text(&q, 0, NULL);
    char cType;
    if(!zId || !*zId) continue;
    cType = zId[0];
    ++zId;
    if('t'==cType){
      /* FSL-MISSING:
         ticket_rebuild_entry(zId) */
      rc = fsl__ticket_rebuild(f, zId);
      continue;
    }else if('w'==cType){
      /* FSL-MISSING:
         backlink_wiki_refresh(zId) */
      continue;
    }
  }
  fsl_stmt_finalize(&q);
  rc = fsl_cx_exec(f, "DROP TABLE pending_xlink");
  fsl_stmt_finalize(&q); 
  if(rc) goto end;
  rc = fsl_cx_exec(f, "DELETE FROM pending_xlink");
  if(rc) goto end;
  /* If multiple check-ins happen close together in time, adjust their
     times by a few milliseconds to make sure they appear in chronological
     order.
  */
  rc = fsl_cx_prepare(f, &q,
                      "UPDATE time_fudge SET m1=m2-:incr "
23164
23165
23166
23167
23168
23169
23170
23171
23172

23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189

23190
23191


23192
23193
23194
23195
23196



23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210


23211
23212
23213
23214
23215
23216
23217
23067
23068
23069
23070
23071
23072
23073


23074

23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091


23092
23093
23094
23095
23096
23097

23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112


23113
23114
23115
23116
23117
23118
23119
23120
23121







-
-
+
-
















+
-
-
+
+




-
+
+
+












-
-
+
+







    rc = fsl_cx_exec(f, "UPDATE event SET"
                     " mtime=(SELECT m1 FROM time_fudge WHERE mid=objid)"
                     " WHERE objid IN (SELECT mid FROM time_fudge)"
                     " AND (mtime=omtime OR omtime IS NULL)"
                     );
  }
  end:
  if(!rc){
    fsl_cx_exec(f, "DROP TABLE time_fudge");
  fsl_cx_exec(f, "DELETE FROM time_fudge");
  }
  if(rc) fsl_cx_transaction_end(f, true);
  else rc = fsl_cx_transaction_end(f, false);
  return rc;
}

int fsl__crosslink_begin(fsl_cx * const f){
  int rc;
  assert(f);
  assert(0==f->cache.isCrosslinking);
  if(f->cache.isCrosslinking){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Crosslink is already running.");
  }
  rc = fsl_cx_transaction_begin(f);
  if(rc) return rc;
  rc = fsl_cx_exec_multi(f,
     "CREATE TEMP TABLE IF NOT EXISTS "
     "CREATE TEMP TABLE pending_xlink(id TEXT PRIMARY KEY)WITHOUT ROWID;"
     "CREATE TEMP TABLE time_fudge("
     "pending_xlink(id TEXT PRIMARY KEY)WITHOUT ROWID;"
     "CREATE TEMP TABLE IF NOT EXISTS time_fudge("
     "  mid INTEGER PRIMARY KEY,"    /* The rid of a manifest */
     "  m1 REAL,"                    /* The timestamp on mid */
     "  cid INTEGER,"                /* A child or mid */
     "  m2 REAL"                     /* Timestamp on the child */
     ");");
     ");"
     "DELETE FROM pending_xlink; "
     "DELETE FROM time_fudge;");
  if(0==rc){
    f->cache.isCrosslinking = true;
  }else{
    fsl_cx_transaction_end(f, true);
  }
  return rc;
}

#undef MARKER
#undef AGE_FUDGE_WINDOW
#undef AGE_ADJUST_INCREMENT
#undef F_at
/* end of file deck.c */
/* start of file delta.c */
/* end of file ./src/deck.c */
/* start of file ./src/delta.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471

23472
23473
23474
23475
23476
23477
23478
23358
23359
23360
23361
23362
23363
23364

23365
23366
23367
23368
23369
23370
23371
23372
23373

23374
23375
23376
23377
23378
23379
23380
23381







-









-
+







  unsigned int i, base;
  unsigned int nHash;          /* Number of hash table entries */
  unsigned int *landmark;      /* Primary hash table */
  unsigned int *collide = NULL;  /* Collision chain */
  int lastRead = -1;           /* Last byte of zSrc read by a COPY command */
  int rc;                      /* generic return code checker. */
  unsigned int olen = 0;       /* current output length. */
  unsigned int total = 0;      /* total byte count. */
  fsl_delta_hash h;
  unsigned char theBuf[IntegerBufSize] = {0,};
  unsigned char * intBuf = theBuf;
  if(!zSrc || !zOut || !out) return FSL_RC_MISUSE;
  /* Add the target file size to the beginning of the delta
  */
#ifdef OUT
#undef OUT
#endif
#define OUT(BLOB,LEN) rc=out(outState, BLOB, LEN); if(0 != rc) {fsl_free(collide); return rc;} else total += LEN
#define OUT(BLOB,LEN) rc=out(outState, BLOB, LEN); if(0 != rc) {fsl_free(collide); return rc;} else (void)0
#define OUTCH(CHAR) OUT(CHAR,1)
#define PINT(I) intBuf = theBuf; olen=fsl_delta_int_put(I, &intBuf); OUT(theBuf,olen)
  PINT(lenOut);
  OUTCH("\n");

  /* If the source file is very small, it means that we have no
     chance of ever doing a copy command.  Just output a single
23850
23851
23852
23853
23854
23855
23856
23857
23858


23859
23860
23861
23862
23863
23864
23865
23753
23754
23755
23756
23757
23758
23759


23760
23761
23762
23763
23764
23765
23766
23767
23768







-
-
+
+







){
  return fsl_delta_apply2(zSrc, lenSrc_, zDelta, lenDelta_, zOut, NULL);
}

#undef NHASH
#undef DEBUG1
#undef DEBUG2
/* end of file delta.c */
/* start of file diff.c */
/* end of file ./src/delta.c */
/* start of file ./src/diff.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
23776
23777
23778
23779
23780
23781
23782




23783





















































23784













































23785
23786
23787
23788
23789







































































































































23790
23791
23792
23793
23794
23795
23796







-
-
-
-

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-





-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-







  the delta-generation).
*/
#include <assert.h>
#include <memory.h>
#include <stdlib.h>
#include <string.h> /* for memmove()/strlen() */

#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

typedef uint64_t u64;
typedef void ReCompiled /* porting crutch. i would strongly prefer to
                           replace the regex support with a stateful
                           predicate callback.
                        */;

#define DIFF_CONTEXT_MASK ((u64)0x0000ffff) /* Lines of context. Default if 0 */
#define DIFF_WIDTH_MASK   ((u64)0x00ff0000) /* side-by-side column width */
#define DIFF_IGNORE_EOLWS ((u64)0x01000000) /* Ignore end-of-line whitespace */
#define DIFF_IGNORE_ALLWS ((u64)0x03000000) /* Ignore all whitespace */
#define DIFF_SIDEBYSIDE   ((u64)0x04000000) /* Generate a side-by-side diff */
#define DIFF_VERBOSE      ((u64)0x08000000) /* Missing shown as empty files */
#define DIFF_BRIEF        ((u64)0x10000000) /* Show filenames only */
#define DIFF_HTML         ((u64)0x20000000) /* Render for HTML */
#define DIFF_LINENO       ((u64)0x40000000) /* Show line numbers */
#define DIFF_NOOPT        (((u64)0x01)<<32) /* Suppress optimizations (debug) */
#define DIFF_INVERT       (((u64)0x02)<<32) /* Invert the diff (debug) */
#define DIFF_CONTEXT_EX   (((u64)0x04)<<32) /* Use context even if zero */
#define DIFF_NOTTOOBIG    (((u64)0x08)<<32) /* Only display if not too big */
#define DIFF_STRIP_EOLCR  (((u64)0x10)<<32) /* Strip trailing CR */

/* Annotation flags (any DIFF flag can be used as Annotation flag as well) */
#define ANN_FILE_VERS   (((u64)0x20)<<32) /* Show file vers rather than commit vers */
#define ANN_FILE_ANCEST (((u64)0x40)<<32) /* Prefer check-ins in the ANCESTOR table */


/*
  ANSI escape codes: https://en.wikipedia.org/wiki/ANSI_escape_code
*/
#define ANSI_COLOR_BLACK(BOLD) ((BOLD) ? "\x1b[30m" : "\x1b[30m")
#define ANSI_COLOR_RED(BOLD) ((BOLD) ? "\x1b[31;1m" : "\x1b[31m")
#define ANSI_COLOR_GREEN(BOLD) ((BOLD) ? "\x1b[32;1m" : "\x1b[32m")
#define ANSI_COLOR_YELLOW(BOLD) ((BOLD) ? "\x1b[33;1m" : "\x1b[33m")
#define ANSI_COLOR_BLUE(BOLD) ((BOLD) ? "\x1b[34;1m" : "\x1b[34m")
#define ANSI_COLOR_MAGENTA(BOLD) ((BOLD) ? "\x1b[35;1m" : "\x1b[35m")
#define ANSI_COLOR_CYAN(BOLD) ((BOLD) ? "\x1b[36;1m" : "\x1b[36m")
#define ANSI_COLOR_WHITE(BOLD) ((BOLD) ? "\x1b[37;1m" : "\x1b[37m")
#define ANSI_DIFF_ADD(BOLD) ANSI_COLOR_GREEN(BOLD)
#define ANSI_DIFF_RM(BOLD) ANSI_COLOR_RED(BOLD)
#define ANSI_DIFF_MOD(BOLD) ANSI_COLOR_BLUE(BOLD)
#define ANSI_BG_BLACK(BOLD) ((BOLD) ? "\x1b[40;1m" : "\x1b[40m")
#define ANSI_BG_RED(BOLD) ((BOLD) ? "\x1b[41;1m" : "\x1b[41m")
#define ANSI_BG_GREEN(BOLD) ((BOLD) ? "\x1b[42;1m" : "\x1b[42m")
#define ANSI_BG_YELLOW(BOLD) ((BOLD) ? "\x1b[43;1m" : "\x1b[43m")
#define ANSI_BG_BLUE(BOLD) ((BOLD) ? "\x1b[44;1m" : "\x1b[44m")
#define ANSI_BG_MAGENTA(BOLD) ((BOLD) ? "\x1b[45;1m" : "\x1b[45m")
#define ANSI_BG_CYAN(BOLD) ((BOLD) ? "\x1b[46;1m" : "\x1b[46m")
#define ANSI_BG_WHITE(BOLD) ((BOLD) ? "\x1b[47;1m" : "\x1b[47m")
#define ANSI_RESET_COLOR   "\x1b[39;49m"
#define ANSI_RESET_ALL     "\x1b[0m"
#define ANSI_RESET ANSI_RESET_ALL
/*#define ANSI_BOLD     ";1m"*/

/**
    Extract the number of lines of context from diffFlags.
 */
static int diff_context_lines(uint64_t diffFlags){
  int n = diffFlags & DIFF_CONTEXT_MASK;
  if( n==0 && (diffFlags & DIFF_CONTEXT_EX)==0 ) n = 5;
  return n;
}

/*
   Extract the width of columns for side-by-side diff.  Supply an
   appropriate default if no width is given.
*/
static int diff_width(uint64_t diffFlags){
  int w = (diffFlags & DIFF_WIDTH_MASK)/(DIFF_CONTEXT_MASK+1);
  if( w==0 ) w = 80;
  return w;
}

/**
    Converts mask of public fsl_diff_flag_t (32-bit) values to the
    Fossil-internal 64-bit bitmask used by the DIFF_xxx macros. Why?
    (A) fossil(1) uses the macro approach and a low-level encoding of
    data in the bitmask (e.g. the context lines count). The public API
    hides the lower-level flags and allows the internal API to take
    care of the encoding.
*/
static uint64_t fsl_diff_flags_convert( int mask ){
  uint64_t rc = 0U;
#define DO(F) if( (mask & F)==F ) rc |= (((u64)F) << 24)
  DO(FSL_DIFF_IGNORE_EOLWS);
  DO(FSL_DIFF_IGNORE_ALLWS);
  DO(FSL_DIFF_SIDEBYSIDE);
  DO(FSL_DIFF_VERBOSE);
  DO(FSL_DIFF_BRIEF);
  DO(FSL_DIFF_HTML);
  DO(FSL_DIFF_LINENO);
  DO(FSL_DIFF_NOOPT);
  DO(FSL_DIFF_INVERT);
  DO(FSL_DIFF_NOTTOOBIG);
  DO(FSL_DIFF_STRIP_EOLCR);
#undef DO
  return rc;
}

/*
   Length of a dline
*/
#define LENGTH(X)   ((X)->n)

/**
    Holds output state for diff generation.
 */
struct DiffOutState {
  /** Output callback. */
  fsl_output_f out;
  /** State for this->out(). */
  void * oState;
  /** For propagating output errors. */
  int rc;
  char ansiColor;
};
typedef struct DiffOutState DiffOutState;
static const DiffOutState DiffOutState_empty = {
NULL/*out*/,
NULL/*oState*/,
0/*rc*/,
0/*useAnsiColor*/
};

/**
    Internal helper. Sends src to o->out(). If n is negative, fsl_strlen()
    is used to determine the length.
 */
static int diff_out( DiffOutState * const o, void const * src, fsl_int_t n ){
  return o->rc = n
    ? o->out(o->oState, src, n<0 ? fsl_strlen((char const *)src) : (fsl_size_t)n)
    : 0;
}

/**
    fsl_output_f() impl for use with diff_outf(). state must be a
    (DiffOutState*).
 */
static int fsl_output_f_diff_out( void * state, void const * src,
                                  fsl_size_t n ){
  DiffOutState * const os = (DiffOutState *)state;
  return os->rc = os->out(os->oState, src, n);
}

static int diff_outf( DiffOutState * o, char const * fmt, ... ){
  va_list va;
  va_start(va,fmt);
  fsl_appendfv(fsl_output_f_diff_out, o, fmt, va);
  va_end(va);
  return o->rc;
}

/*
   Append a single line of context-diff output to pOut.
*/
static int appendDiffLine(
  DiffOutState *const pOut, /* Where to write the line of output */
  char cPrefix,       /* One of " ", "+",  or "-" */
  fsl_dline *pLine,       /* The line to be output */
  int html,           /* True if generating HTML.  False for plain text */
  ReCompiled *pRe     /* Colorize only if line matches this Regex */
){
  int rc = 0;
  char const * ansiPrefix =
    !pOut->ansiColor
    ? NULL 
    : (('+'==cPrefix)
       ? ANSI_DIFF_ADD(0)
       : (('-'==cPrefix) ? ANSI_DIFF_RM(0) : NULL))
    ;
  if(ansiPrefix) rc = diff_out(pOut, ansiPrefix, -1 );
  if(!rc) rc = diff_out(pOut, &cPrefix, 1);
  if(rc) return rc;
  else if( html ){
#if 0
    if( pRe /*MISSING: && re_dline_match(pRe, pLine, 1)==0 */ ){
      cPrefix = ' ';
    }else
#endif
    if( cPrefix=='+' ){
      rc = diff_out(pOut, "<span class=\"fsl-diff-add\">", -1);
    }else if( cPrefix=='-' ){
      rc = diff_out(pOut, "<span class=\"fsl-diff-rm\">", -1);
    }
    if(!rc){
      /* unsigned short n = pLine->n; */
      /* while( n>0 && (pLine->z[n-1]=='\n' || pLine->z[n-1]=='\r') ) n--; */
      rc = pOut->rc = fsl_htmlize(pOut->out, pOut->oState,
                                  pLine->z, pLine->n);
      if( !rc && cPrefix!=' ' ){
        rc = diff_out(pOut, "</span>", -1);
      }
    }
  }else{
    rc = diff_out(pOut, pLine->z, pLine->n);
  }
  if(!rc){
    if(ansiPrefix){
      rc = diff_out(pOut, ANSI_RESET, -1 );
    }
    if(!rc) rc = diff_out(pOut, "\n", 1);
  }
  return rc;
}


/*
   Add two line numbers to the beginning of an output line for a context
   diff.  One or the other of the two numbers might be zero, which means
   to leave that number field blank.  The "html" parameter means to format
   the output for HTML.
*/
static int appendDiffLineno(DiffOutState *pOut, int lnA,
                            int lnB, int html){
  int rc = 0;
  if( html ){
    rc = diff_out(pOut, "<span class=\"fsl-diff-lineno\">", -1);
  }
  if(!rc){
    if( lnA>0 ){
      rc = diff_outf(pOut, "%6d ", lnA);
    }else{
      rc = diff_out(pOut, "       ", 7);
    }
  }
  if(!rc){
    if( lnB>0 ){
      rc = diff_outf(pOut, "%6d  ", lnB);
    }else{
      rc = diff_out(pOut, "        ", 8);
    }
    if( !rc && html ){
      rc = diff_out(pOut, "</span>", -1);
    }
  }
  return rc;
}


/*
   Minimum of two values
*/
static int minInt(int a, int b){ return a<b ? a : b; }

/**
    Compute the optimal longest common subsequence (LCS) using an
    exhaustive search. This version of the LCS is only used for
24200
24201
24202
24203
24204
24205
24206


24207
24208
24209
24210
24211
24212
24213
24214
24215


24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266




















































24267
24268
24269
24270
24271
24272
24273
24274

24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885



















































23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937








23938




23939
23940
23941
23942
23943
23944
23945







+
+









+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
-
-
-
-







  int dist = 0;              /* Distance of match from center */
  int mid;                   /* Center of the chng */
  int iSXb, iSYb, iEXb, iEYb;   /* Best match so far */
  int iSXp, iSYp, iEXp, iEYp;   /* Previous match */
  sqlite3_int64 bestScore;      /* Best score so far */
  sqlite3_int64 score;          /* Score for current candidate LCS */
  int span;                     /* combined width of the input sequences */
  int cutoff = 4;            /* Max hash chain entries to follow */
  int nextCutoff = -1;       /* Value of cutoff for next iteration */

  span = (iE1 - iS1) + (iE2 - iS2);
  bestScore = -10000;
  score = 0;
  iSXb = iSXp = iS1;
  iEXb = iEXp = iS1;
  iSYb = iSYp = iS2;
  iEYb = iEYp = iS2;
  mid = (iE1 + iS1)/2;
  do{
    nextCutoff = 0;
  for(i=iS1; i<iE1; i++){
    int limit = 0;
    j = p->aTo[p->aFrom[i].h % p->nTo].iHash;
    while( j>0
      && (j-1<iS2 || j>=iE2 || p->cmpLine(&p->aFrom[i], &p->aTo[j-1]))
    ){
      if( limit++ > 10 ){
        j = 0;
        break;
      }
      j = p->aTo[j-1].iNext;
    }
    if( j==0 ) continue;
    assert( i>=iSXb && i>=iSXp );
    if( i<iEXb && j>=iSYb && j<iEYb ) continue;
    if( i<iEXp && j>=iSYp && j<iEYp ) continue;
    iSX = i;
    iSY = j-1;
    pA = &p->aFrom[iSX-1];
    pB = &p->aTo[iSY-1];
    n = minInt(iSX-iS1, iSY-iS2);
    for(k=0; k<n && p->cmpLine(pA,pB)==0; k++, pA--, pB--){}
    iSX -= k;
    iSY -= k;
    iEX = i+1;
    iEY = j;
    pA = &p->aFrom[iEX];
    pB = &p->aTo[iEY];
    n = minInt(iE1-iEX, iE2-iEY);
    for(k=0; k<n && p->cmpLine(pA,pB)==0; k++, pA++, pB++){}
    iEX += k;
    iEY += k;
    skew = (iSX-iS1) - (iSY-iS2);
    if( skew<0 ) skew = -skew;
    dist = (iSX+iEX)/2 - mid;
    if( dist<0 ) dist = -dist;
    score = (iEX - iSX)*(sqlite3_int64)span - (skew + dist);
    if( score>bestScore ){
      bestScore = score;
      iSXb = iSX;
      iSYb = iSY;
      iEXb = iEX;
      iEYb = iEY;
    }else if( iEX>iEXp ){
      iSXp = iSX;
      iSYp = iSY;
      iEXp = iEX;
      iEYp = iEY;
    }
  }
  if(
    for(i=iS1; i<iE1; i++){
      int limit = 0;
      j = p->aTo[p->aFrom[i].h % p->nTo].iHash;
      while( j>0
        && (j-1<iS2 || j>=iE2 || p->cmpLine(&p->aFrom[i], &p->aTo[j-1]))
      ){
        if( limit++ > cutoff ){
          j = 0;
          nextCutoff = cutoff*4;
          break;
        }
        j = p->aTo[j-1].iNext;
      }
      if( j==0 ) continue;
      assert( i>=iSXb && i>=iSXp );
      if( i<iEXb && j>=iSYb && j<iEYb ) continue;
      if( i<iEXp && j>=iSYp && j<iEYp ) continue;
      iSX = i;
      iSY = j-1;
      pA = &p->aFrom[iSX-1];
      pB = &p->aTo[iSY-1];
      n = minInt(iSX-iS1, iSY-iS2);
      for(k=0; k<n && p->cmpLine(pA,pB)==0; k++, pA--, pB--){}
      iSX -= k;
      iSY -= k;
      iEX = i+1;
      iEY = j;
      pA = &p->aFrom[iEX];
      pB = &p->aTo[iEY];
      n = minInt(iE1-iEX, iE2-iEY);
      for(k=0; k<n && p->cmpLine(pA,pB)==0; k++, pA++, pB++){}
      iEX += k;
      iEY += k;
      skew = (iSX-iS1) - (iSY-iS2);
      if( skew<0 ) skew = -skew;
      dist = (iSX+iEX)/2 - mid;
      if( dist<0 ) dist = -dist;
      score = (iEX - iSX)*(sqlite3_int64)span - (skew + dist);
      if( score>bestScore ){
        bestScore = score;
        iSXb = iSX;
        iSYb = iSY;
        iEXb = iEX;
        iEYb = iEY;
      }else if( iEX>iEXp ){
        iSXp = iSX;
        iSYp = iSY;
        iEXp = iEX;
        iEYp = iEY;
      }
    }
  }while( iSXb==iEXb && nextCutoff && (cutoff=nextCutoff)<=64 );
#if 0
     1
     /* CANNOT EXPLAIN why we get different diff results than fossil
        unless we use fsl_diff_optimal_lcs() despite using, insofar as
        i can tell, the same inputs. There is some aspect i'm
        overlooking. */
#else
     iSXb==iEXb && (sqlite3_int64)(iE1-iS1)*(iE2-iS2)<400
  if( iSXb==iEXb && (sqlite3_int64)(iE1-iS1)*(iE2-iS2)<2500 ){
#endif
     ){
    /* If no common sequence is found using the hashing heuristic and
    ** the input is not too big, use the expensive exact solution */
    fsl__diff_optimal_lcs(p, iS1, iE1, iS2, iE2, piSX, piEX, piSY, piEY);
  }else{
    *piSX = iSXb;
    *piSY = iSYb;
    *piEX = iEXb;
    *piEY = iEYb;
  }
24533
24534
24535
24536
24537
24538
24539










































































































































































































































24540
24541
24542
24543
24544
24545
24546
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+








    lnFrom += del;
    lnTo += ins;
  }
  //fsl__dump_triples(p, __FILE__, __LINE__);
}


#if !defined(FSL_OMIT_DEPRECATED)

#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

typedef uint64_t u64;
typedef void ReCompiled /* porting crutch. i would strongly prefer to
                           replace the regex support with a stateful
                           predicate callback.
                        */;

#define DIFF_CONTEXT_MASK ((u64)0x0000ffff) /* Lines of context. Default if 0 */
#define DIFF_WIDTH_MASK   ((u64)0x00ff0000) /* side-by-side column width */
#define DIFF_IGNORE_EOLWS ((u64)0x01000000) /* Ignore end-of-line whitespace */
#define DIFF_IGNORE_ALLWS ((u64)0x03000000) /* Ignore all whitespace */
#define DIFF_SIDEBYSIDE   ((u64)0x04000000) /* Generate a side-by-side diff */
#define DIFF_VERBOSE      ((u64)0x08000000) /* Missing shown as empty files */
#define DIFF_BRIEF        ((u64)0x10000000) /* Show filenames only */
#define DIFF_HTML         ((u64)0x20000000) /* Render for HTML */
#define DIFF_LINENO       ((u64)0x40000000) /* Show line numbers */
#define DIFF_NOOPT        (((u64)0x01)<<32) /* Suppress optimizations (debug) */
#define DIFF_INVERT       (((u64)0x02)<<32) /* Invert the diff (debug) */
#define DIFF_CONTEXT_EX   (((u64)0x04)<<32) /* Use context even if zero */
#define DIFF_NOTTOOBIG    (((u64)0x08)<<32) /* Only display if not too big */
#define DIFF_STRIP_EOLCR  (((u64)0x10)<<32) /* Strip trailing CR */

/*
  ANSI escape codes: https://en.wikipedia.org/wiki/ANSI_escape_code
*/
#define ANSI_COLOR_BLACK(BOLD) ((BOLD) ? "\x1b[30m" : "\x1b[30m")
#define ANSI_COLOR_RED(BOLD) ((BOLD) ? "\x1b[31;1m" : "\x1b[31m")
#define ANSI_COLOR_GREEN(BOLD) ((BOLD) ? "\x1b[32;1m" : "\x1b[32m")
#define ANSI_COLOR_YELLOW(BOLD) ((BOLD) ? "\x1b[33;1m" : "\x1b[33m")
#define ANSI_COLOR_BLUE(BOLD) ((BOLD) ? "\x1b[34;1m" : "\x1b[34m")
#define ANSI_COLOR_MAGENTA(BOLD) ((BOLD) ? "\x1b[35;1m" : "\x1b[35m")
#define ANSI_COLOR_CYAN(BOLD) ((BOLD) ? "\x1b[36;1m" : "\x1b[36m")
#define ANSI_COLOR_WHITE(BOLD) ((BOLD) ? "\x1b[37;1m" : "\x1b[37m")
#define ANSI_DIFF_ADD(BOLD) ANSI_COLOR_GREEN(BOLD)
#define ANSI_DIFF_RM(BOLD) ANSI_COLOR_RED(BOLD)
#define ANSI_DIFF_MOD(BOLD) ANSI_COLOR_BLUE(BOLD)
#define ANSI_BG_BLACK(BOLD) ((BOLD) ? "\x1b[40;1m" : "\x1b[40m")
#define ANSI_BG_RED(BOLD) ((BOLD) ? "\x1b[41;1m" : "\x1b[41m")
#define ANSI_BG_GREEN(BOLD) ((BOLD) ? "\x1b[42;1m" : "\x1b[42m")
#define ANSI_BG_YELLOW(BOLD) ((BOLD) ? "\x1b[43;1m" : "\x1b[43m")
#define ANSI_BG_BLUE(BOLD) ((BOLD) ? "\x1b[44;1m" : "\x1b[44m")
#define ANSI_BG_MAGENTA(BOLD) ((BOLD) ? "\x1b[45;1m" : "\x1b[45m")
#define ANSI_BG_CYAN(BOLD) ((BOLD) ? "\x1b[46;1m" : "\x1b[46m")
#define ANSI_BG_WHITE(BOLD) ((BOLD) ? "\x1b[47;1m" : "\x1b[47m")
#define ANSI_RESET_COLOR   "\x1b[39;49m"
#define ANSI_RESET_ALL     "\x1b[0m"
#define ANSI_RESET ANSI_RESET_ALL
/*#define ANSI_BOLD     ";1m"*/

/**
    Converts mask of public fsl_diff_flag_t (32-bit) values to the
    Fossil-internal 64-bit bitmask used by the DIFF_xxx macros. Why?
    (A) fossil(1) uses the macro approach and a low-level encoding of
    data in the bitmask (e.g. the context lines count). The public API
    hides the lower-level flags and allows the internal API to take
    care of the encoding.
*/
static uint64_t fsl_diff_flags_convert( int mask ){
  uint64_t rc = 0U;
#define DO(F) if( (mask & F)==F ) rc |= (((u64)F) << 24)
  DO(FSL_DIFF2_IGNORE_EOLWS);
  DO(FSL_DIFF2_IGNORE_ALLWS);
  DO(FSL_DIFF2_LINE_NUMBERS);
  DO(FSL_DIFF_SIDEBYSIDE);
  DO(FSL_DIFF2_NOTTOOBIG);
  DO(FSL_DIFF2_STRIP_EOLCR);
  DO(FSL_DIFF_VERBOSE);
  DO(FSL_DIFF_BRIEF);
  DO(FSL_DIFF_HTML);
  DO(FSL_DIFF_NOOPT);
  DO(FSL_DIFF_INVERT);
#undef DO
  return rc;
}

/**
    Holds output state for diff generation.
 */
struct DiffOutState {
  /** Output callback. */
  fsl_output_f out;
  /** State for this->out(). */
  void * oState;
  /** For propagating output errors. */
  int rc;
  char ansiColor;
};
typedef struct DiffOutState DiffOutState;
static const DiffOutState DiffOutState_empty = {
NULL/*out*/,
NULL/*oState*/,
0/*rc*/,
0/*useAnsiColor*/
};

/**
    Internal helper. Sends src to o->out(). If n is negative, fsl_strlen()
    is used to determine the length.
 */
static int diff_out( DiffOutState * const o, void const * src, fsl_int_t n ){
  return o->rc = n
    ? o->out(o->oState, src, n<0 ? fsl_strlen((char const *)src) : (fsl_size_t)n)
    : 0;
}

/**
    fsl_output_f() impl for use with diff_outf(). state must be a
    (DiffOutState*).
 */
static int fsl_output_f_diff_out( void * state, void const * src,
                                  fsl_size_t n ){
  DiffOutState * const os = (DiffOutState *)state;
  return os->rc = os->out(os->oState, src, n);
}

static int diff_outf( DiffOutState * o, char const * fmt, ... ){
  va_list va;
  va_start(va,fmt);
  fsl_appendfv(fsl_output_f_diff_out, o, fmt, va);
  va_end(va);
  return o->rc;
}

/*
   Append a single line of context-diff output to pOut.
*/
static int appendDiffLine(
  DiffOutState *const pOut, /* Where to write the line of output */
  char cPrefix,       /* One of " ", "+",  or "-" */
  fsl_dline *pLine,       /* The line to be output */
  int html,           /* True if generating HTML.  False for plain text */
  ReCompiled *pRe     /* Colorize only if line matches this Regex */
){
  int rc = 0;
  char const * ansiPrefix =
    !pOut->ansiColor
    ? NULL 
    : (('+'==cPrefix)
       ? ANSI_DIFF_ADD(0)
       : (('-'==cPrefix) ? ANSI_DIFF_RM(0) : NULL))
    ;
  if(ansiPrefix) rc = diff_out(pOut, ansiPrefix, -1 );
  if(!rc) rc = diff_out(pOut, &cPrefix, 1);
  if(rc) return rc;
  else if( html ){
#if 0
    if( pRe /*MISSING: && re_dline_match(pRe, pLine, 1)==0 */ ){
      cPrefix = ' ';
    }else
#endif
    if( cPrefix=='+' ){
      rc = diff_out(pOut, "<span class=\"fsl-diff-add\">", -1);
    }else if( cPrefix=='-' ){
      rc = diff_out(pOut, "<span class=\"fsl-diff-rm\">", -1);
    }
    if(!rc){
      /* unsigned short n = pLine->n; */
      /* while( n>0 && (pLine->z[n-1]=='\n' || pLine->z[n-1]=='\r') ) n--; */
      rc = pOut->rc = fsl_htmlize(pOut->out, pOut->oState,
                                  pLine->z, pLine->n);
      if( !rc && cPrefix!=' ' ){
        rc = diff_out(pOut, "</span>", -1);
      }
    }
  }else{
    rc = diff_out(pOut, pLine->z, pLine->n);
  }
  if(!rc){
    if(ansiPrefix){
      rc = diff_out(pOut, ANSI_RESET, -1 );
    }
    if(!rc) rc = diff_out(pOut, "\n", 1);
  }
  return rc;
}


/*
   Add two line numbers to the beginning of an output line for a context
   diff.  One or the other of the two numbers might be zero, which means
   to leave that number field blank.  The "html" parameter means to format
   the output for HTML.
*/
static int appendDiffLineno(DiffOutState *pOut, int lnA,
                            int lnB, int html){
  int rc = 0;
  if( html ){
    rc = diff_out(pOut, "<span class=\"fsl-diff-lineno\">", -1);
  }
  if(!rc){
    if( lnA>0 ){
      rc = diff_outf(pOut, "%6d ", lnA);
    }else{
      rc = diff_out(pOut, "       ", 7);
    }
  }
  if(!rc){
    if( lnB>0 ){
      rc = diff_outf(pOut, "%6d  ", lnB);
    }else{
      rc = diff_out(pOut, "        ", 8);
    }
    if( !rc && html ){
      rc = diff_out(pOut, "</span>", -1);
    }
  }
  return rc;
}

/**
    Extract the number of lines of context from diffFlags.
 */
static int diff_context_lines(uint64_t diffFlags){
  int n = diffFlags & DIFF_CONTEXT_MASK;
  if( n==0 && (diffFlags & DIFF_CONTEXT_EX)==0 ) n = 5;
  return n;
}

/*
   Extract the width of columns for side-by-side diff.  Supply an
   appropriate default if no width is given.
*/
static int diff_width(uint64_t diffFlags){
  int w = (diffFlags & DIFF_WIDTH_MASK)/(DIFF_CONTEXT_MASK+1);
  if( w==0 ) w = 80;
  return w;
}

/*
   Given a raw diff p[] in which the p->aEdit[] array has been filled
   in, compute a context diff into pOut.
*/
static int contextDiff(
  fsl__diff_cx *p,      /* The difference */
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25329
25330
25331
25332
25333
25334
25335

25336
25337
25338
25339
25340
25341
25342







-







  int rc = 0;
  int a = 0;    /* Index of next line in A[] */
  int b = 0;    /* Index of next line in B[] */
  int *R;       /* Array of COPY/DELETE/INSERT triples */
  int r;        /* Index into R[] */
  int nr;       /* Number of COPY/DELETE/INSERT triples to process */
  int mxr;      /* Maximum value for r */
  int na, nb;   /* Number of lines shown from A and B */
  int i, j;     /* Loop counters */
  int m, ma, mb;/* Number of lines to output */
  int skip;     /* Number of lines to skip */
  static int nChunk = 0; /* Number of chunks of diff output seen so far */
  SbsLine s;    /* Output line buffer */
  int nContext; /* Lines of context above and below each change */
  int showDivider = 0;  /* True to show the divider */
25505
25506
25507
25508
25509
25510
25511
25512

25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25398
25399
25400
25401
25402
25403
25404

25405

25406

25407
25408

25409
25410















25411
25412
25413
25414
25415
25416
25417







-
+
-

-


-


-
-
-
-
-
-
-
-
-
-
-
-
-
-
-







        a = xa;
        b = xb;
        continue;
      }
    }
#endif
    /* For the current block comprising nr triples, figure out
       how many lines of A and B are to be displayed
       how many lines to skip. */
    */
    if( R[r]>nContext ){
      na = nb = nContext;
      skip = R[r] - nContext;
    }else{
      na = nb = R[r];
      skip = 0;
    }
    for(i=0; i<nr; i++){
      na += R[r+i*3+1];
      nb += R[r+i*3+2];
    }
    if( R[r+nr*3]>nContext ){
      na += nContext;
      nb += nContext;
    }else{
      na += R[r+nr*3];
      nb += R[r+nr*3];
    }
    for(i=1; i<nr; i++){
      na += R[r+i*3];
      nb += R[r+i*3];
    }

    /* Draw the separator between blocks */
    if( showDivider ){
      if( s.escHtml ){
        char zLn[10];
        fsl_snprintf(zLn, sizeof(zLn), "%d", a+skip+1);
        rc = sbsWriteSep(&s, strlen(zLn), SBS_LNA);
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25717
25718
25719
25720
25721
25722
25723


25724
25725
25726
25727
25728
25729
25730







-
-







                  short contextLines,
                  short sbsWidth,
                  int diffFlags ){
  return fsl_diff_text_impl(pA, pB, out, outState,
                            contextLines, sbsWidth, diffFlags, NULL );
}



int fsl_diff_text_to_buffer(fsl_buffer const *pA, fsl_buffer const *pB,
                            fsl_buffer * pOut,
                            short contextLines,
                            short sbsWidth,
                            int diffFlags ){
  return (pA && pB && pOut)
    ? fsl_diff_text_impl(pA, pB, fsl_output_f_buffer, pOut,
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25749
25750
25751
25752
25753
25754
25755


25756
25757
25758
25759
25760
25761
25762







-
-







#undef DIFF_NOTTOOBIG
#undef DIFF_STRIP_EOLCR
#undef SBS_LNA
#undef SBS_TXTA
#undef SBS_MKR
#undef SBS_LNB
#undef SBS_TXTB
#undef ANN_FILE_VERS
#undef ANN_FILE_ANCEST

#undef ANSI_COLOR_BLACK
#undef ANSI_COLOR_RED
#undef ANSI_COLOR_GREEN
#undef ANSI_COLOR_YELLOW
#undef ANSI_COLOR_BLUE
#undef ANSI_COLOR_MAGENTA
25901
25902
25903
25904
25905
25906
25907

25908
25909


25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941


25942
25943
25944
25945
25946
25947
25948
25772
25773
25774
25775
25776
25777
25778
25779


25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799

25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810


25811
25812
25813
25814
25815
25816
25817
25818
25819







+
-
-
+
+


















-











-
-
+
+







#undef ANSI_BG_WHITE
#undef ANSI_RESET_COLOR
#undef ANSI_RESET_ALL
#undef ANSI_RESET
#undef ANSI_DIFF_ADD
#undef ANSI_DIFF_MOD
#undef ANSI_DIFF_RM
#endif /*FSL_OMIT_DEPRECATED*/
/* end of file diff.c */
/* start of file diff2.c */
/* end of file ./src/diff.c */
/* start of file ./src/diff2.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/**
   This file houses the "2nd generation" diff-generation APIs. This
   code is a straight port of those algorithms from the Fossil SCM
   project, initially implemented by D. Richard Hipp, ported and
   the license re-assigned to this project with this consent.
*/
#include <assert.h>
#include <memory.h>
#include <stdlib.h>
#include <string.h> /* for memmove()/strlen() */

#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)


const fsl_diff_opt fsl_diff_opt_empty = fsl_diff_opt_empty_m;
const fsl_diff_builder fsl_diff_builder_empty = fsl_diff_builder_empty_m;
const fsl_dibu_opt fsl_dibu_opt_empty = fsl_dibu_opt_empty_m;
const fsl_dibu fsl_dibu_empty = fsl_dibu_empty_m;
const fsl_dline fsl_dline_empty = fsl_dline_empty_m;
const fsl_dline_change fsl_dline_change_empty = fsl_dline_change_empty_m;
const fsl__diff_cx fsl__diff_cx_empty = fsl__diff_cx_empty_m;

void fsl__diff_cx_clean(fsl__diff_cx * const cx){
  fsl_free(cx->aFrom);
  fsl_free(cx->aTo);
26387
26388
26389
26390
26391
26392
26393

































































































































26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406

26407
26408

26409
26410
26411
26412
26413
26414
26415
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408

26409
26410
26411
26412
26413
26414
26415
26416







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+













+

-
+







/*
** The threshold at which diffBlockAlignment transitions from the
** O(N*N) Wagner minimum-edit-distance algorithm to a less process
** O(NlogN) divide-and-conquer approach.
*/
#define DIFF_ALIGN_MX  1225

/**
   FSL_DIFF_SMALL_GAP=0 is a temporary(? as of 2022-01-04) patch for a
   cosmetic-only (but unsightly) quirk of the diff engine where it
   produces a pair of identical DELETE/INSERT lines. Richard's
   preliminary solution for it is to remove the "small gap merging,"
   but he notes (in fossil /chat) that he's not recommending this as
   "the" fix.

   PS: we colloquially know this as "the lineno diff" because it was first
   reported in a diff which resulted in:

```
-  int     lineno;
+  int     lineno;
```

   (No, there are no whitespace changes there.)

   To reiterate, though: this is not a "bug," in that it does not
   cause incorrect results when applying the resulting unfified-diff
   patches. It does, however, cause confusion for human users.


   Here are two inputs which, when diffed, expose the lineno behavior:

   #1:

```
struct fnc_diff_view_state {
  int     first_line_onscreen;
  int     last_line_onscreen;
  int     diff_flags;
  int     context;
  int     sbs;
  int     matched_line;
  int     current_line;
  int     lineno;
  size_t     ncols;
  size_t     nlines;
  off_t    *line_offsets;
  bool     eof;
  bool     colour;
  bool     showmeta;
  bool     showln;
};
```

   #2:

```
struct fnc_diff_view_state {
  int     first_line_onscreen;
  int     last_line_onscreen;
  int     diff_flags;
  int     context;
  int     sbs;
  int     matched_line;
  int     selected_line;
  int     lineno;
  int     gtl;
  size_t     ncols;
  size_t     nlines;
  off_t    *line_offsets;
  bool     eof;
  bool     colour;
  bool     showmeta;
  bool     showln;
};
```

   Result without this patch:

```
Index: X.0
==================================================================
--- X.0
+++ X.1
@@ -3,15 +3,16 @@
   int     last_line_onscreen;
   int     diff_flags;
   int     context;
   int     sbs;
   int     matched_line;
+  int     selected_line;
-  int     current_line;
-  int     lineno;
+  int     lineno;
+  int     gtl;
   size_t     ncols;
   size_t     nlines;
   off_t    *line_offsets;
   bool     eof;
   bool     colour;
   bool     showmeta;
   bool     showln;
 };
```

    And with the patch:

```
Index: X.0
==================================================================
--- X.0
+++ X.1
@@ -3,15 +3,16 @@
   int     last_line_onscreen;
   int     diff_flags;
   int     context;
   int     sbs;
   int     matched_line;
-  int     current_line;
+  int     selected_line;
   int     lineno;
+  int     gtl;
   size_t     ncols;
   size_t     nlines;
   off_t    *line_offsets;
   bool     eof;
   bool     colour;
   bool     showmeta;
   bool     showln;
 };
```

*/
#define FSL_DIFF_SMALL_GAP 0

#if FSL_DIFF_SMALL_GAP
/*
** R[] is an array of six integer, two COPY/DELETE/INSERT triples for a
** pair of adjacent differences.  Return true if the gap between these
** two differences is so small that they should be rendered as a single
** edit.
*/
static int smallGap2(const int *R, int ma, int mb){
  int m = R[3];
  ma += R[4] + m;
  mb += R[5] + m;
  if( ma*mb>DIFF_ALIGN_MX ) return 0;
  return m<=2 || m<=(R[1]+R[2]+R[4]+R[5])/8;
}
#endif

static unsigned short diff_opt_context_lines(fsl_diff_opt const * opt){
static unsigned short diff_opt_context_lines(fsl_dibu_opt const * opt){
  const unsigned short dflt = 5;
  unsigned short n = opt ? opt->contextLines : dflt;
  if( !n && (opt->diffFlags & FSL_DIFF2_CONTEXT_ZERO)==0 ){
    n = dflt;
  }
  return n;
}
26520
26521
26522
26523
26524
26525
26526
26527

26528
26529
26530
26531
26532
26533
26534
26521
26522
26523
26524
26525
26526
26527

26528
26529
26530
26531
26532
26533
26534
26535







-
+







** each other.  Insertion and deletion costs are 50.  Match costs
** are between 0 and 100 where 0 is a perfect match 100 is a complete
** mismatch.
*/
static int diffBlockAlignment(
  const fsl_dline *aLeft, int nLeft,     /* Text on the left */
  const fsl_dline *aRight, int nRight,   /* Text on the right */
  fsl_diff_opt *pOpt,                  /* Configuration options */
  fsl_dibu_opt * const pOpt,             /* Configuration options */
  unsigned char **pResult, /* Raw result */
  unsigned *pNResult               /* OUTPUT: length of result */
){
  int i, j, k;                 /* Loop counters */
  int *a = 0;                  /* One row of the Wagner matrix */
  int *pToFree = 0;            /* Space that needs to be freed */
  unsigned char *aM = 0;       /* Wagner result matrix */
26703
26704
26705
26706
26707
26708
26709
26710

26711
26712
26713
26714

26715
26716
26717
26718

26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732

26733

26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745

26746
26747

26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758

26759
26760
26761
26762
26763
26764
26765
26704
26705
26706
26707
26708
26709
26710

26711
26712
26713
26714

26715
26716
26717
26718

26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732

26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749

26750
26751
26752
26753

26754
26755
26756
26757
26758
26759

26760
26761
26762
26763
26764
26765
26766
26767







-
+



-
+



-
+













-
+

+












+

-
+



-






-
+







  end:
  fsl_free(pToFree);
  return rc;
}


/*
** Format a diff using a fsl_diff_builder object
** Format a diff using a fsl_dibu object
*/
static int fdb__format(
  fsl__diff_cx * const cx,
  fsl_diff_builder * const pBuilder
  fsl_dibu * const pBuilder
){
  const fsl_dline *A;        /* Left side of the diff */
  const fsl_dline *B;        /* Right side of the diff */
  fsl_diff_opt * const pOpt = pBuilder->opt;
  fsl_dibu_opt * const pOpt = pBuilder->opt;
  const int *R;          /* Array of COPY/DELETE/INSERT triples */
  unsigned int a;    /* Index of next line in A[] */
  unsigned int b;    /* Index of next line in B[] */
  unsigned int r;        /* Index into R[] */
  unsigned int nr;       /* Number of COPY/DELETE/INSERT triples to process */
  unsigned int mxr;      /* Maximum value for r */
  unsigned int na, nb;   /* Number of lines shown from A and B */
  unsigned int i, j;     /* Loop counters */
  unsigned int m, ma, mb;/* Number of lines to output */
  signed int skip;   /* Number of lines to skip */
  unsigned int contextLines; /* Lines of context above and below each change */
  unsigned short passNumber = 0;
  int rc = 0;

  
#define RC if(rc) goto end
#define METRIC(M) if(1==passNumber) ++pBuilder->metrics.M
  pass_again:
  contextLines = diff_opt_context_lines(pOpt);
  skip = 0;
  a = b = 0;
  A = cx->aFrom;
  B = cx->aTo;
  R = cx->aEdit;
  mxr = cx->nEdit;
  //MARKER(("contextLines=%u, nEdit = %d, mxr=%u\n", contextLines, cx->nEdit, mxr));
  while( mxr>2 && R[mxr-1]==0 && R[mxr-2]==0 ){ mxr -= 3; }

  pBuilder->lnLHS = pBuilder->lnRHS = 0;
  ++passNumber;
  if(pBuilder->start){
    pBuilder->passNumber = ++passNumber;
    pBuilder->passNumber = passNumber;
    rc = pBuilder->start(pBuilder);
    RC;
  }

  for(r=0; r<mxr; r += 3*nr){
    /* Figure out how many triples to show in a single block */
    for(nr=1; R[r+nr*3]>0 && R[r+nr*3]<(int)contextLines*2; nr++){}

#if 0
    /* MISSING: this "should" be replaced by a stateful predicate
       function, probably in the fsl_diff_opt class. */
       function, probably in the fsl_dibu_opt class. */
    /* If there is a regex, skip this block (generate no diff output)
    ** if the regex matches or does not match both insert and delete.
    ** Only display the block if one side matches but the other side does
    ** not.
    */
    if( pOpt->pRe ){
      int hideBlock = 1;
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817



















26818
26819
26820
26821
26822
26823
26824
26808
26809
26810
26811
26812
26813
26814





26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840







-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







    for(i=1; i<nr; i++){
      na += R[r+i*3];
      nb += R[r+i*3];
    }

    //MARKER(("Chunk header... a=%u, b=%u, na=%u, nb=%u, skip=%d\n", a, b, na, nb, skip));
    if(pBuilder->chunkHeader
#if 0
       /* The following two bits are a kludge to keep from injecting
          a chunk header between chunks which are directly adjacent */
       && pBuilder->lnLHS != (uint32_t)(na ? a+skip+1 : a+skip)-1
       && pBuilder->lnRHS != (uint32_t)(nb ? b+skip+1 : b+skip)-1
       /* The following bit is a kludge to keep from injecting a chunk
          header between chunks which are directly adjacent.

          The problem, however, is that we cannot skip _reliably_
          without also knowing how the next chunk aligns. If we skip
          it here, the _previous_ chunk header may well be telling
          the user a lie with regards to line numbers.

          Fossil itself does not have this issue because it generates
          these chunk headers directly in this routine, instead of in
          the diff builder, depending on a specific flag being set in
          builder->opt. Also (related), in that implementation, fossil
          will collapse chunks which are separated by less than the
          context distance into contiguous chunks (see below). Because
          we farm out the chunkHeader lines to the builder, we cannot
          reliably do that here.
       */
#if 0
       && !skip
#endif
       ){
      rc = pBuilder->chunkHeader(pBuilder,
                                 (uint32_t)(na ? a+skip+1 : a+skip),
                                 (uint32_t)na,
                                 (uint32_t)(nb ? b+skip+1 : b+skip),
                                 (uint32_t)nb);
26834
26835
26836
26837
26838
26839
26840
26841
26842




26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856


26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867







-
-
+
+
+
+







    //MARKER(("Show the initial common... a=%u, b=%u, m=%u, r=%u, skip=%d\n", a, b, m, r, skip));
    if( skip>0 ){
      if( NULL==pBuilder->chunkHeader && skip<(int)contextLines ){
        /* 2021-09-27: BUG: this is incompatible with unified diff
           format. The generated header lines say we're skipping X
           lines but we then end up including lines which that header
           says to skip. As a workaround, we'll only run this when
           pBuilder->chunkHeader is NULL, noting that fossil's
           diff builder interface does not have that method.
           pBuilder->chunkHeader is NULL, noting that fossil's diff
           builder interface does not have that method (and thus
           doesn't have this issue, instead generating chunk headers
           directly in this algorithm).

           Without this block, our "utxt" diff builder can mimic
           fossil's non-diff builder unified diff format, except that
           we add Index lines (feature or bug?). With this block,
           the header values output above are wrong.
        */
        /* If the amount to skip is less that the context band, then
26871
26872
26873
26874
26875
26876
26877

26878

26879
26880
26881
26882
26883
26884
26885
26886

26887
26888
26889
26890
26891
26892
26893
26894
26895
26896

26897
26898
26899
26900
26901
26902
26903
26904

26905
26906
26907
26908
26909
26910
26911
26912
26913
26914

26915
26916

26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928

26929
26930
26931
26932
26933
26934
26935
26889
26890
26891
26892
26893
26894
26895
26896

26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935

26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959







+
-
+








+










+








+









-
+


+












+







    /* Show the differences */
    for(i=0; i<nr; i++){
      unsigned int nAlign;
      unsigned char *alignment = 0;
      ma = R[r+i*3+1];   /* Lines on left but not on right */
      mb = R[r+i*3+2];   /* Lines on right but not on left */

#if FSL_DIFF_SMALL_GAP
      /* Try merging the current block with subsequent blocks, if the
  /* Try merging the current block with subsequent blocks, if the
      ** subsequent blocks are nearby and their result isn't too big.
      */
      while( i<nr-1 && smallGap2(&R[r+i*3],ma,mb) ){
        i++;
        m = R[r+i*3];
        ma += R[r+i*3+1] + m;
        mb += R[r+i*3+2] + m;
      }
#endif

      /* Try to find an alignment for the lines within this one block */
      rc = diffBlockAlignment(&A[a], ma, &B[b], mb, pOpt,
                              &alignment, &nAlign);
      RC;
      for(j=0; ma+mb>0; j++){
        assert( j<nAlign );
        switch( alignment[j] ){
          case 1: {
            /* Delete one line from the left */
            METRIC(deletions);
            rc = pBuilder->deletion(pBuilder, &A[a]);
            if(rc) goto bail;
            ma--;
            a++;
            break;
          }
          case 2: {
            /* Insert one line on the right */
            METRIC(insertions);
            rc = pBuilder->insertion(pBuilder, &B[b]);
            if(rc) goto bail;
            assert( mb>0 );
            mb--;
            b++;
            break;
          }
          case 3: {
            /* The left line is changed into the right line */
            if( cx->cmpLine(&A[a], &B[b])==0 ){
            if( 0==cx->cmpLine(&A[a], &B[b]) ){
              rc = pBuilder->common(pBuilder, &A[a]);
            }else{
              METRIC(edits);
              rc = pBuilder->edit(pBuilder, &A[a], &B[b]);
            }
            if(rc) goto bail;
            assert( ma>0 && mb>0 );
            ma--;
            mb--;
            a++;
            b++;
            break;
          }
          case 4: {
            /* Delete from left then separately insert on the right */
            METRIC(replacements);
            rc = pBuilder->replacement(pBuilder, &A[a], &B[b]);
            if(rc) goto bail;
            ma--;
            a++;
            mb--;
            b++;
            break;
26966
26967
26968
26969
26970
26971
26972

26973
26974
26975
26976
26977
26978
26979
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004







+







    RC;
  }
  if( R[r]>(int)contextLines ){
    rc = pBuilder->skip(pBuilder, R[r] - contextLines);
  }
  end:
#undef RC
#undef METRIC
  if(0==rc){
    if(pBuilder->finish) pBuilder->finish(pBuilder);
    if(pBuilder->twoPass && 1==passNumber){
      goto pass_again;
    }
  }
  return rc;
26994
26995
26996
26997
26998
26999
27000
27001
27002


27003
27004
27005
27006
27007
27008

27009
27010
27011
27012
27013
27014
27015
27019
27020
27021
27022
27023
27024
27025


27026
27027
27028
27029
27030
27031
27032

27033
27034
27035
27036
27037
27038
27039
27040







-
-
+
+





-
+







   it. On error, *outRaw is not modified but pBuilder may have emitted
   partial output. That is not knowable for the general
   case. Ownership of pBuilder is not changed. If pBuilder is not NULL
   then pBuilder->opt must be non-NULL.
*/
static int fsl_diff2_text_impl(fsl_buffer const *pA,
                               fsl_buffer const *pB,
                               fsl_diff_builder * const pBuilder,
                               fsl_diff_opt const * const opt_,
                               fsl_dibu * const pBuilder,
                               fsl_dibu_opt const * const opt_,
                               int ** outRaw){
  int rc = 0;
  fsl__diff_cx c = fsl__diff_cx_empty;
  bool ignoreWs = false;
  int ansiOptCount = 0;
  fsl_diff_opt opt = *opt_
  fsl_dibu_opt opt = *opt_
    /*we need a copy for the sake of the FSL_DIFF2_INVERT flag*/;
  if(!pA || !pB || (pBuilder && outRaw)) return FSL_RC_MISUSE;

  blob_to_utf8_no_bom(pA, 0);
  blob_to_utf8_no_bom(pB, 0);

  if( opt.diffFlags & FSL_DIFF2_INVERT ){
27082
27083
27084
27085
27086
27087
27088
27089

27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105

27106
27107
27108
27109
27110
27111

27112
27113



27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124



27125
27126

27127
27128

27129
27130
27131
27132
27133
27134
27135
27136




27137
27138

27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149













































































27150
27151













27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168

27169
27170
27171





27172
27173
27174


27175
27176
27177
27178
27179
27180
27181
27182
27183
27184












27185
27186
27187
27188
27189
27190
27191












27192
27193
27194
27195
27196










27197
27198
27199
27200
27201










27202
27203
27204
27205
27206
27207
27208
27209
27210



















27211
27212
27213


27214
27215

27216
27217
27218
27219
27220








27221










27222
27223
27224
27225
27226
27227
27228
27229

27230
27231

27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242

27243
27244
27245
27246
27247
27248
27249

27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261

27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273

27274
27275
27276
27277
27278
27279
27280

27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292

27293
27294
27295
27296
27297
27298
27299
27300






















27301
27302
27303
27304
27305



27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317





27318
27319
27320
27321
27322
27323
27324
27107
27108
27109
27110
27111
27112
27113

27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129

27130
27131
27132
27133
27134
27135

27136
27137

27138
27139
27140
27141
27142
27143








27144
27145
27146
27147

27148
27149

27150
27151
27152
27153
27154
27155



27156
27157
27158
27159
27160

27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249


27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278

27279
27280
27281
27282
27283
27284
27285
27286
27287
27288


27289
27290
27291
27292
27293
27294
27295





27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309





27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322




27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333




27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344








27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364


27365
27366
27367
27368
27369
27370
27371



27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394


27395

27396
27397

27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408

27409
27410
27411
27412
27413
27414
27415

27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427

27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439

27440
27441
27442
27443
27444
27445
27446

27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462






27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487


27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500


27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512







-
+















-
+





-
+

-
+
+
+



-
-
-
-
-
-
-
-
+
+
+

-
+

-
+





-
-
-
+
+
+
+

-
+











+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
















-
+



+
+
+
+
+

-
-
+
+





-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+


-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
+
+
+
+
+
+
+
+
+
+

-
-
-
-
+
+
+
+
+
+
+
+
+
+

-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
+
+


+


-
-
-
+
+
+
+
+
+
+
+

+
+
+
+
+
+
+
+
+
+




-
-

-
+

-
+










-
+






-
+











-
+











-
+






-
+












+


-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+



-
-
+
+
+










-
-
+
+
+
+
+







     - DIFF_NUMSTAT flag is not implemented. For that matter,
     flags which result in output going anywhere except for
     pBuilder->out are not implemented here, e.g. DIFF_RAW.

     That last point makes this impl tiny compared to the original!
  */
  if(pBuilder){
    fsl_diff_opt * const oldOpt = pBuilder->opt;
    fsl_dibu_opt * const oldOpt = pBuilder->opt;
    pBuilder->opt = &opt;
    rc = fdb__format(&c, pBuilder);
    pBuilder->opt = oldOpt;
  }
  end:
  if(0==rc && outRaw){
    *outRaw = c.aEdit;
    c.aEdit = 0;
  }
  fsl__diff_cx_clean(&c);
  return rc;
}

int fsl_diff_v2(fsl_buffer const * pv1,
                fsl_buffer const * pv2,
                fsl_diff_builder * const pBuilder){
                fsl_dibu * const pBuilder){
  return fsl_diff2_text_impl(pv1, pv2, pBuilder, pBuilder->opt, NULL);
}

int fsl_diff_v2_raw(fsl_buffer const * pv1,
                    fsl_buffer const * pv2,
                    fsl_diff_opt const * const opt,
                    fsl_dibu_opt const * const opt,
                    int **outRaw ){
  return fsl_diff2_text_impl(pv1, pv2, NULL, opt, outRaw);
  return fsl_diff2_text_impl(pv1, pv2, NULL,
                             opt ? opt : &fsl_dibu_opt_empty,
                             outRaw);
}


/**
   Allocator for fsl_diff_builder instances. If extra is >0 then that
   much extra space is allocated as part of the same block and the
   pimpl member of the returned object is pointed to that space.
*/
static fsl_diff_builder * fsl__diff_builder_alloc(fsl_size_t extra){
  fsl_diff_builder * rc =
    (fsl_diff_builder*)fsl_malloc(sizeof(fsl_diff_builder) + extra);
fsl_dibu * fsl_dibu_alloc(fsl_size_t extra){
  fsl_dibu * rc =
    (fsl_dibu*)fsl_malloc(sizeof(fsl_dibu) + extra);
  if(rc){
    *rc = fsl_diff_builder_empty;
    *rc = fsl_dibu_empty;
    if(extra){
      rc->pimpl = ((unsigned char *)rc)+sizeof(fsl_diff_builder);
      rc->pimpl = ((unsigned char *)rc)+sizeof(fsl_dibu);
    }
  }
  return rc;
}

static int fdb__out(fsl_diff_builder *const b,
                    char const *z, fsl_size_t n){
  return b->opt->out(b->opt->outState, z, n);
static int fdb__out(fsl_dibu *const b,
                    char const *z, fsl_int_t n){
  if(n<0) n = (fsl_int_t)fsl_strlen(z);
  return b->opt->out(b->opt->outState, z, (fsl_size_t)n);
}
static int fdb__outf(fsl_diff_builder * const b,
static int fdb__outf(fsl_dibu * const b,
                     char const *fmt, ...){
  int rc = 0;
  va_list va;
  assert(b->opt->out);
  va_start(va,fmt);
  rc = fsl_appendfv(b->opt->out, b->opt->outState, fmt, va);
  va_end(va);
  return rc;
}


/**
   Column indexes for DiffCounter::cols.
*/
enum DiffCounterCols {
DICO_NUM1 = 0, DICO_TEXT1,
DICO_MOD,
DICO_NUM2, DICO_TEXT2,
DICO_count
};
/**
   Internal state for the text-mode split diff builder. Used for
   calculating column widths in the builder's first pass so that
   the second pass can output everything in a uniform width.
*/
struct DiffCounter {
  /**
     Largest column width we've yet seen. These are only updated for
     DICO_TEXT1 and DICO_TEXT2. The others currently have fixed widths.

     FIXME: these are in bytes, not text columns. The current code may
     truncate multibyte characters.
  */
  uint32_t maxWidths[DICO_count];
  /**
     Max line numbers seen for the LHS/RHS input files. This is likely
     much higher than the number of diff lines.

     This can be used, e.g., to size and allocate a curses PAD in the
     second pass of the start() method.
  */
  uint32_t lineCount[2];
  /**
     The actual number of lines needed for rendering the file.
  */
  uint32_t displayLines;
};
typedef struct DiffCounter DiffCounter;
static const DiffCounter DiffCounter_empty = {{1,10,3,1,10},{0,0},0};
#define DICOSTATE(VNAME) DiffCounter * const VNAME = (DiffCounter *)b->pimpl

static int maxColWidth(fsl_dibu const * const b,
                       DiffCounter const * const sst,
                       int mwIndex){
  static const short minColWidth =
    10/*b->opt.columnWidth values smaller than this are treated as
        this value*/;
  switch(mwIndex){
    case DICO_NUM1:
    case DICO_NUM2:
    case DICO_MOD: return sst->maxWidths[mwIndex];
    case DICO_TEXT1: case DICO_TEXT2: break;
    default:
      assert(!"internal API misuse: invalid column index.");
      break;
  }
  int const y =
    (b->opt->columnWidth>0
     && b->opt->columnWidth<=sst->maxWidths[mwIndex])
    ? (int)b->opt->columnWidth
    : (int)sst->maxWidths[mwIndex];
  return minColWidth > y ? minColWidth : y;
}

static void fdb__dico_update_maxlen(DiffCounter * const sst,
                                    int col,
                                    char const * const z,
                                    uint32_t n){
  if(sst->maxWidths[col]<n){
#if 0
    sst->maxWidths[col] = n;
#else
    n = (uint32_t)fsl_strlen_utf8(z, (fsl_int_t)n);
    if(sst->maxWidths[col]<n) sst->maxWidths[col] = n;
#endif
  }
}

static int fdb__debug_start(fsl_diff_builder * const b){
  int rc = fdb__outf(b, "DEBUG builder starting up.\n");
static int fdb__debug_start(fsl_dibu * const b){
  int rc = fdb__outf(b, "DEBUG builder starting pass #%d.\n",
                     b->passNumber);
  if(1==b->passNumber){
    DICOSTATE(sst);
    *sst = DiffCounter_empty;
    if(b->opt->nameLHS) ++sst->displayLines;
    if(b->opt->nameRHS) ++sst->displayLines;
    if(b->opt->hashLHS) ++sst->displayLines;
    if(b->opt->hashRHS) ++sst->displayLines;
    ++b->fileCount;
    return rc;
  }
  if(0==rc && b->opt->nameLHS){
    rc = fdb__outf(b,"LHS: %s\n", b->opt->nameLHS);
  }
  if(0==rc && b->opt->nameRHS){
    rc = fdb__outf(b,"RHS: %s\n", b->opt->nameRHS);
  }
  if(0==rc && b->opt->hashLHS){
    rc = fdb__outf(b,"LHS hash: %s\n", b->opt->hashLHS);
  }
  if(0==rc && b->opt->hashRHS){
    rc = fdb__outf(b,"RHS hash: %s\n", b->opt->hashRHS);
  }
  return rc;
}


static int fdb__debug_chunkHeader(fsl_diff_builder* const b,
static int fdb__debug_chunkHeader(fsl_dibu* const b,
                                  uint32_t lnnoLHS, uint32_t linesLHS,
                                  uint32_t lnnoRHS, uint32_t linesRHS ){
#if 1
  if(1==b->passNumber){
    DICOSTATE(sst);
    ++sst->displayLines;
    return 0;
  }
  return fdb__outf(b, "@@ -%" PRIu32 ",%" PRIu32
                   " +%" PRIu32 ",%" PRIu32 " @@\n",
                   lnnoLHS, linesLHS, lnnoRHS, linesRHS);
                " +%" PRIu32 ",%" PRIu32 " @@\n",
                lnnoLHS, linesLHS, lnnoRHS, linesRHS);
#else
  return 0;
#endif
}

static int fdb__debug_skip(fsl_diff_builder * const p, uint32_t n){
  const int rc = fdb__outf(p, "SKIP %u (%u..%u left and %u..%u right)\n",
                           n, p->lnLHS+1, p->lnLHS+n, p->lnRHS+1, p->lnRHS+n);
  p->lnLHS += n;
  p->lnRHS += n;
static int fdb__debug_skip(fsl_dibu * const b, uint32_t n){
  if(1==b->passNumber){
    DICOSTATE(sst);
    b->lnLHS += n;
    b->lnRHS += n;
    ++sst->displayLines;
    return 0;
  }
  const int rc = fdb__outf(b, "SKIP %u (%u..%u left and %u..%u right)\n",
                           n, b->lnLHS+1, b->lnLHS+n, b->lnRHS+1, b->lnRHS+n);
  b->lnLHS += n;
  b->lnRHS += n;
  return rc;
}
static int fdb__debug_common(fsl_diff_builder * const p, fsl_dline const * pLine){
  ++p->lnLHS;
  ++p->lnRHS;
  return fdb__outf(p, "COMMON  %8u %8u %.*s\n",
                   p->lnLHS, p->lnRHS, (int)pLine->n, pLine->z);
static int fdb__debug_common(fsl_dibu * const b, fsl_dline const * pLine){
  DICOSTATE(sst);
  ++b->lnLHS;
  ++b->lnRHS;
  if(1==b->passNumber){
    ++sst->displayLines;
    fdb__dico_update_maxlen(sst, DICO_TEXT1, pLine->z, pLine->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT2, pLine->z, pLine->n);
    return 0;
  }
  return fdb__outf(b, "COMMON  %8u %8u %.*s\n",
                   b->lnLHS, b->lnRHS, (int)pLine->n, pLine->z);
}
static int fdb__debug_insertion(fsl_diff_builder * const p, fsl_dline const * pLine){
  p->lnRHS++;
  return fdb__outf(p, "INSERT           %8u %.*s\n",
                   p->lnRHS, (int)pLine->n, pLine->z);
static int fdb__debug_insertion(fsl_dibu * const b, fsl_dline const * pLine){
  DICOSTATE(sst);
  ++b->lnRHS;
  if(1==b->passNumber){
    ++sst->displayLines;
    fdb__dico_update_maxlen(sst, DICO_TEXT1, pLine->z, pLine->n);
    return 0;
  }
  return fdb__outf(b, "INSERT           %8u %.*s\n",
                   b->lnRHS, (int)pLine->n, pLine->z);
}
static int fdb__debug_deletion(fsl_diff_builder * const p, fsl_dline const * pLine){
  p->lnLHS++;
  return fdb__outf(p, "DELETE  %8u          %.*s\n",
                   p->lnLHS, (int)pLine->n, pLine->z);
static int fdb__debug_deletion(fsl_dibu * const b, fsl_dline const * pLine){
  DICOSTATE(sst);
  ++b->lnLHS;
  if(1==b->passNumber){
    ++sst->displayLines;
    fdb__dico_update_maxlen(sst, DICO_TEXT2, pLine->z, pLine->n);
    return 0;
  }
  return fdb__outf(b, "DELETE  %8u          %.*s\n",
                   b->lnLHS, (int)pLine->n, pLine->z);
}
static int fdb__debug_replacement(fsl_diff_builder * const p,
                              fsl_dline const * lineLhs,
                              fsl_dline const * lineRhs) {
  int rc;
  p->lnLHS++;
  p->lnRHS++;
  rc = fdb__outf(p, "REPLACE %8u          %.*s\n",
      p->lnLHS, (int)lineLhs->n, lineLhs->z);
static int fdb__debug_replacement(fsl_dibu * const b,
                                  fsl_dline const * lineLhs,
                                  fsl_dline const * lineRhs) {
#if 0
  int rc = b->deletion(b, lineLhs);
  if(0==rc) rc = b->insertion(b, lineRhs);
  return rc;
#else    
  DICOSTATE(sst);
  ++b->lnLHS;
  ++b->lnRHS;
  if(1==b->passNumber){
    ++sst->displayLines;
    fdb__dico_update_maxlen(sst, DICO_TEXT1, lineLhs->z, lineLhs->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT2, lineRhs->z, lineRhs->n);
    return 0;
  }
  int rc = fdb__outf(b, "REPLACE %8u          %.*s\n",
                     b->lnLHS, (int)lineLhs->n, lineLhs->z);
  if(!rc){
    rc = fdb__outf(p, "            %8u %.*s\n",
                   p->lnRHS, (int)lineRhs->n, lineRhs->z);
    rc = fdb__outf(b, "            %8u %.*s\n",
                   b->lnRHS, (int)lineRhs->n, lineRhs->z);
  }
  return rc;
#endif
}
                 
static int fdb__debug_edit(fsl_diff_builder * const b,
                           fsl_dline const * pX,
                           fsl_dline const * pY){
static int fdb__debug_edit(fsl_dibu * const b,
                           fsl_dline const * lineLHS,
                           fsl_dline const * lineRHS){
#if 0
  int rc = b->deletion(b, lineLHS);
  if(0==rc) rc = b->insertion(b, lineRHS);
  return rc;
#else    
  int rc = 0;
  DICOSTATE(sst);
  ++b->lnLHS;
  ++b->lnRHS;
  if(1==b->passNumber){
    sst->displayLines += 4
      /* this is actually 3 or 4, but we don't know that from here */;
    fdb__dico_update_maxlen(sst, DICO_TEXT1, lineLHS->z, lineLHS->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT2, lineRHS->z, lineRHS->n);
    return 0;
  }
  int i, j;
  int x;
  fsl_dline_change chng = fsl_dline_change_empty;
#define RC if(rc) goto end
  b->lnLHS++;
  b->lnRHS++;
  rc = fdb__outf(b, "EDIT    %8u          %.*s\n",
                 b->lnLHS, (int)pX->n, pX->z);
                 b->lnLHS, (int)lineLHS->n, lineLHS->z);
  RC;
  fsl_dline_change_spans(pX, pY, &chng);
  fsl_dline_change_spans(lineLHS, lineRHS, &chng);
  for(i=x=0; i<chng.n; i++){
    int ofst = chng.a[i].iStart1;
    int len = chng.a[i].iLen1;
    if( len ){
      char c = '0' + i;
      if( x==0 ){
        rc = fdb__outf(b, "%*s", 26, "");
        RC;
      }
      while( ofst > x ){
        if( (pX->z[x]&0xc0)!=0x80 ){
        if( (lineLHS->z[x]&0xc0)!=0x80 ){
          rc = fdb__out(b, " ", 1);
          RC;
        }
        x++;
      }
      for(j=0; j<len; j++, x++){
        if( (pX->z[x]&0xc0)!=0x80 ){
        if( (lineLHS->z[x]&0xc0)!=0x80 ){
          rc = fdb__out(b, &c, 1);
          RC;
        }
      }
    }
  }
  if( x ){
    rc = fdb__out(b, "\n", 1);
    RC;
  }
  rc = fdb__outf(b, "                 %8u %.*s\n",
                 b->lnRHS, (int)pY->n, pY->z);
                 b->lnRHS, (int)lineRHS->n, lineRHS->z);
  RC;
  for(i=x=0; i<chng.n; i++){
    int ofst = chng.a[i].iStart2;
    int len = chng.a[i].iLen2;
    if( len ){
      char c = '0' + i;
      if( x==0 ){
        rc = fdb__outf(b, "%*s", 26, "");
        RC;
      }
      while( ofst > x ){
        if( (pY->z[x]&0xc0)!=0x80 ){
        if( (lineRHS->z[x]&0xc0)!=0x80 ){
          rc = fdb__out(b, " ", 1);
          RC;
        }
        x++;
      }
      for(j=0; j<len; j++, x++){
        if( (pY->z[x]&0xc0)!=0x80 ){
        if( (lineRHS->z[x]&0xc0)!=0x80 ){
          rc = fdb__out(b, &c, 1);
          RC;
        }
      }
    }
  }
  if( x ){
    rc = fdb__out(b, "\n", 1);
  }
  end:
#undef RC
  return rc;
#endif
}

static int fdb__debug_finish(fsl_diff_builder * const b){
  return fdb__outf(b, "END with %u lines left and %u lines right\n",
                   b->lnLHS, b->lnRHS);
}

static void fdb__generic_finalize(fsl_diff_builder * const b){
static int fdb__debug_finish(fsl_dibu * const b){
  DICOSTATE(sst);
  if(1==b->passNumber){
    sst->lineCount[0] = b->lnLHS;
    sst->lineCount[1] = b->lnRHS;
    return 0;
  }
  int rc = fdb__outf(b, "END with %u LHS file lines "
                     "and %u RHS lines (max. %u display lines)\n",
                     b->lnLHS, b->lnRHS, sst->displayLines);
  if(0==rc){
    rc = fdb__outf(b,"Col widths: num left=%u, col left=%u, "
                   "modifier=%u, num right=%u, col right=%u\n",
                   sst->maxWidths[0], sst->maxWidths[1],
                   sst->maxWidths[2], sst->maxWidths[3],
                   sst->maxWidths[4]);
  }
  return rc;
}

void fsl_dibu_finalizer(fsl_dibu * const b){
  *b = fsl_dibu_empty;
  fsl_free(b);
}

static fsl_diff_builder * fsl__diff_builder_debug(void){
  fsl_diff_builder * rc = fsl__diff_builder_alloc(0);
static fsl_dibu * fsl__diff_builder_debug(void){
  fsl_dibu * rc =
    fsl_dibu_alloc((fsl_size_t)sizeof(DiffCounter));
  if(rc){
    rc->chunkHeader = fdb__debug_chunkHeader;
    rc->start = fdb__debug_start;
    rc->skip = fdb__debug_skip;
    rc->common = fdb__debug_common;
    rc->insertion = fdb__debug_insertion;
    rc->deletion = fdb__debug_deletion;
    rc->replacement = fdb__debug_replacement;
    rc->edit = fdb__debug_edit;
    rc->finish = fdb__debug_finish;
    rc->finalize = fdb__generic_finalize;
    assert(!rc->pimpl);
    rc->finalize = fsl_dibu_finalizer;
    rc->twoPass = true;
    assert(0!=rc->pimpl);
    DiffCounter * const sst = (DiffCounter*)rc->pimpl;
    *sst = DiffCounter_empty;
    assert(0==rc->implFlags);
    assert(0==rc->lnLHS);
    assert(0==rc->lnRHS);
    assert(NULL==rc->opt);
  }
  return rc;
}
27342
27343
27344
27345
27346
27347
27348
27349

27350
27351
27352
27353
27354
27355
27356

27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371

27372
27373
27374

27375
27376
27377
27378
27379
27380
27381
27382

27383
27384
27385
27386
27387
27388
27389
27390

27391
27392
27393
27394
27395
27396
27397
27398

27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411



27412
27413
27414
27415
27416
27417
27418

27419



27420

27421
27422
27423

27424
27425
27426

27427
27428
27429
27430

27431
27432
27433
27434
27435
27436
27437

27438
27439
27440
27441
27442


27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453

27454
27455
27456
27457
27458
27459
27460
27461
27462
































27463

27464




27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476

27477
27478












































27479
27480
27481
27482






27483
27484
27485



27486
27487
27488
27489

27490

27491
27492
27493

27494
27495

27496
27497







27498
27499

27500
27501
27502
27503
27504
27505










27506

27507
27508
27509
27510
27511
27512











27513
27514
27515
27516
27517
27518

27519


27520
27521
27522




27523
27524

27525

27526

27527
27528
27529
27530
27531
27532
27533
27534


















27535




27536
27537



27538
27539
27540
27541
27542
27543

27544
27545
27546
27547
27548
27549
27550
27551

27552
27553
27554
27555
27556
27557
27558
27559







27560



27561
27562
27563
27564
27565





27566



27567
27568
27569
27570
27571
27572
27573
27574
27575

27576
27577
27578

27579
27580
27581
27582
27583
27584
27585
27586
27587

27588
27589

27590
27591
27592
27593

27594
27595
27596
27597
27598
27599



27600
27601
27602
27603
27604
27605

27606
27607
27608
27609





27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625

27626
27627
27628
27629
27630
27631
27632
27633
27634

27635
27636
27637
27638
27639
27640
27641
27642
27643

27644
27645
27646
27647
27648
27649
27650
27651
27652

27653
27654
27655
27656
27657
27658
27659
27660
27661

27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676



27677
27678
27679
27680
27681
27682
27683

27684
27685
27686

27687
27688

27689
27690

27691
27692
27693
27694

27695
27696

27697
27698
27699
27700
27701
27702
27703
27704
27705

27706

27707
27708

27709
27710

27711
27712










27713
27714
27715
27716

27717
27718

27719
27720
27721
27722
27723
27724



27725
27726
27727
27728
27729
27730
27731
27732
27733
27734

27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809

27810
27811
27812
27813
27814
27815


27816
27817
27818

27819
27820
27821
27822
27823
27824

27825
27826
27827
27828


27829
27830
27831
27832
27833
27834
27835
27836

27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851

27852
27853
27854
27855
27856
27857



27858
27859

27860
27861

27862
27863
27864
27865

27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881


27882
27883
27884
27885
27886
27887

27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918

27919
27920
27921

27922
27923
27924
27925
27926


27927
27928
27929
27930
27931
27932
27933
27934
27935

27936
27937
27938

27939
27940
27941

27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952

27953
27954
27955

27956
27957
27958

27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969

27970
27971
27972
27973
27974
27975
27976
27977
27978

27979
27980
27981
27982
27983


27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995


27996
27997
27998

27999
28000
28001
28002


28003
28004

28005
28006
28007
28008
28009
28010


28011
28012
28013
28014
28015
28016



28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031


28032
28033
28034
28035
28036
28037


28038
28039

28040
28041

28042
28043
28044

28045
28046
28047

28048
28049
28050

28051
28052
28053

28054
28055

28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075




28076
28077
28078
28079
28080
28081
28082
27530
27531
27532
27533
27534
27535
27536

27537
27538
27539
27540
27541
27542
27543

27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558

27559
27560
27561

27562
27563
27564
27565
27566
27567
27568
27569

27570
27571
27572
27573
27574
27575
27576
27577

27578
27579
27580
27581
27582
27583
27584
27585

27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596



27597
27598
27599
27600
27601
27602
27603
27604
27605

27606
27607
27608
27609
27610

27611
27612
27613

27614
27615
27616

27617
27618
27619
27620

27621
27622
27623
27624
27625
27626
27627

27628
27629
27630
27631


27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643

27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685

27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702

27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749




27750
27751
27752
27753
27754
27755
27756
27757

27758
27759
27760
27761
27762
27763

27764
27765
27766
27767
27768

27769
27770
27771
27772


27773
27774
27775
27776
27777
27778
27779
27780
27781
27782






27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794






27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810

27811
27812
27813
27814



27815
27816
27817
27818
27819
27820
27821

27822
27823
27824
27825







27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848


27849
27850
27851
27852
27853
27854
27855
27856

27857
27858
27859
27860
27861
27862
27863
27864

27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880

27881
27882
27883
27884
27885
27886


27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903

27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916

27917
27918

27919
27920
27921
27922

27923
27924
27925
27926
27927
27928

27929
27930
27931
27932
27933
27934
27935
27936

27937
27938
27939


27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959

27960
27961
27962
27963
27964
27965
27966
27967
27968

27969
27970
27971
27972
27973
27974
27975
27976
27977

27978
27979
27980
27981
27982
27983
27984
27985
27986

27987
27988
27989
27990
27991
27992
27993
27994
27995

27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008



28009
28010
28011
28012
28013
28014
28015
28016
28017

28018
28019
28020

28021
28022

28023
28024

28025
28026
28027
28028

28029
28030

28031
28032
28033
28034
28035
28036
28037
28038
28039

28040
28041
28042
28043

28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062

28063
28064

28065
28066
28067
28068



28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094































































28095
28096
28097
28098
28099


28100
28101
28102
28103

28104
28105
28106
28107
28108
28109

28110
28111
28112


28113
28114
28115
28116
28117
28118
28119
28120
28121

28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136

28137
28138
28139
28140



28141
28142
28143
28144

28145
28146

28147
28148
28149
28150

28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165


28166
28167
28168
28169
28170
28171
28172

28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189















28190
28191
28192

28193
28194
28195
28196


28197
28198
28199
28200
28201
28202
28203
28204
28205
28206

28207
28208
28209

28210
28211
28212

28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223

28224
28225
28226

28227
28228
28229

28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240

28241
28242
28243
28244
28245
28246
28247
28248
28249

28250
28251
28252
28253


28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265


28266
28267
28268
28269

28270
28271
28272


28273
28274
28275

28276
28277
28278
28279
28280


28281
28282
28283
28284
28285



28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301


28302
28303
28304
28305
28306
28307


28308
28309
28310

28311
28312

28313
28314
28315

28316
28317
28318

28319
28320
28321

28322
28323
28324

28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345



28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356







-
+






-
+














-
+


-
+







-
+







-
+







-
+










-
-
-
+
+
+






-
+

+
+
+
-
+


-
+


-
+



-
+






-
+



-
-
+
+










-
+









+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+

+
+
+
+











-
+


+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
+
+
+
+
+
+


-
+
+
+



-
+

+


-
+


+
-
-
+
+
+
+
+
+
+


+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+

+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+





-
+

+
+
-
-
-
+
+
+
+


+
-
+

+

-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+
+
+
+
-
-
+
+
+





-
+







-
+








+
+
+
+
+
+
+
-
+
+
+



-
-
+
+
+
+
+

+
+
+








-
+



+








-
+

-
+



-
+





-
+
+
+





-
+


-
-
+
+
+
+
+















-
+








-
+








-
+








-
+








-
+












-
-
-
+
+
+






-
+


-
+

-
+

-
+



-
+

-
+








-
+

+

-
+


+


+
+
+
+
+
+
+
+
+
+



-
+

-
+



-
-
-
+
+
+










+












-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+




-
-
+
+


-
+





-
+


-
-
+
+







-
+














-
+



-
-
-
+
+
+

-
+

-
+



-
+














-
-
+
+





-
+
















-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+


-
+



-
-
+
+








-
+


-
+


-
+










-
+


-
+


-
+










-
+








-
+



-
-
+
+










-
-
+
+


-
+


-
-
+
+

-
+




-
-
+
+



-
-
-
+
+
+













-
-
+
+




-
-
+
+

-
+

-
+


-
+


-
+


-
+


-
+


+

















-
-
-
+
+
+
+







**
** The SUBARRAY is an array of 3*N+1 strings with N>=0.  The triples
** represent common-text, left-text, and right-text.  The last string
** in SUBARRAY is the common-suffix.  Any string can be empty if it does
** not apply.
*/

static int fdb__outj(fsl_diff_builder * const b,
static int fdb__outj(fsl_dibu * const b,
                     char const *zJson, int n){
  return n<0
    ? fdb__outf(b, "%!j", zJson)
    : fdb__outf(b, "%!.*j", n, zJson);
}

static int fdb__json1_start(fsl_diff_builder * const b){
static int fdb__json1_start(fsl_dibu * const b){
  int rc = fdb__outf(b, "{\"hashLHS\": %!j, \"hashRHS\": %!j, ",
                     b->opt->hashLHS, b->opt->hashRHS);
  if(0==rc && b->opt->nameLHS){
    rc = fdb__outf(b, "\"nameLHS\": %!j, ", b->opt->nameLHS);
  }
  if(0==rc && b->opt->nameRHS){
    rc = fdb__outf(b, "\"nameRHS\": %!j, ", b->opt->nameRHS);
  }
  if(0==rc){
    rc = fdb__out(b, "\"diff\":[", 8);
  }
  return rc;
}

static int fdb__json1_skip(fsl_diff_builder * const b, uint32_t n){
static int fdb__json1_skip(fsl_dibu * const b, uint32_t n){
  return fdb__outf(b, "1,%" PRIu32 ",\n", n);
}
static int fdb__json1_common(fsl_diff_builder * const b, fsl_dline const * pLine){
static int fdb__json1_common(fsl_dibu * const b, fsl_dline const * pLine){
  int rc = fdb__out(b, "2,",2);
  if(!rc) {
    rc = fdb__outj(b, pLine->z, (int)pLine->n);
    if(!rc) rc = fdb__out(b, ",\n",2);
  }
  return rc;
}
static int fdb__json1_insertion(fsl_diff_builder * const b, fsl_dline const * pLine){
static int fdb__json1_insertion(fsl_dibu * const b, fsl_dline const * pLine){
  int rc = fdb__out(b, "3,",2);
  if(!rc){
    rc = fdb__outj(b, pLine->z, (int)pLine->n);
    if(!rc) rc = fdb__out(b, ",\n",2);
  }
  return rc;
}
static int fdb__json1_deletion(fsl_diff_builder * const b, fsl_dline const * pLine){
static int fdb__json1_deletion(fsl_dibu * const b, fsl_dline const * pLine){
  int rc = fdb__out(b, "4,",2);
  if(!rc){
    rc = fdb__outj(b, pLine->z, (int)pLine->n);
    if(!rc) rc = fdb__out(b, ",\n",2);
  }
  return rc;
}
static int fdb__json1_replacement(fsl_diff_builder * const b,
static int fdb__json1_replacement(fsl_dibu * const b,
                              fsl_dline const * lineLhs,
                              fsl_dline const * lineRhs) {
  int rc = fdb__out(b, "5,[\"\",",6);
  if(!rc) rc = fdb__outf(b,"%!.*j", (int)lineLhs->n, lineLhs->z);
  if(!rc) rc = fdb__out(b, ",", 1);
  if(!rc) rc = fdb__outf(b,"%!.*j", (int)lineRhs->n, lineRhs->z);
  if(!rc) rc = fdb__out(b, ",\"\"],\n",6);
  return rc;
}
                 
static int fdb__json1_edit(fsl_diff_builder * const b,
                           fsl_dline const * pX,
                           fsl_dline const * pY){
static int fdb__json1_edit(fsl_dibu * const b,
                           fsl_dline const * lineLHS,
                           fsl_dline const * lineRHS){
  int rc = 0;
  int i,x;
  fsl_dline_change chng = fsl_dline_change_empty;

#define RC if(rc) goto end
  rc = fdb__out(b, "5,[", 3); RC;
  fsl_dline_change_spans(pX, pY, &chng);
  fsl_dline_change_spans(lineLHS, lineRHS, &chng);
  for(i=x=0; i<(int)chng.n; i++){
    if(i>0){
      rc = fdb__out(b, ",", 1); RC;
    }
    rc = fdb__outj(b, pX->z + x, (int)chng.a[i].iStart1 - x); RC;
    rc = fdb__outj(b, lineLHS->z + x, (int)chng.a[i].iStart1 - x); RC;
    x = chng.a[i].iStart1;
    rc = fdb__out(b, ",", 1); RC;
    rc = fdb__outj(b, pX->z + x, (int)chng.a[i].iLen1); RC;
    rc = fdb__outj(b, lineLHS->z + x, (int)chng.a[i].iLen1); RC;
    x += chng.a[i].iLen1;
    rc = fdb__out(b, ",", 1); RC;
    rc = fdb__outj(b, pY->z + chng.a[i].iStart2,
    rc = fdb__outj(b, lineRHS->z + chng.a[i].iStart2,
                   (int)chng.a[i].iLen2); RC;
  }
  rc = fdb__out(b, ",", 1); RC;
  rc = fdb__outj(b, pX->z + x, (int)(pX->n - x)); RC;
  rc = fdb__outj(b, lineLHS->z + x, (int)(lineLHS->n - x)); RC;
  rc = fdb__out(b, "],\n",3); RC;
  end:
  return rc;
#undef RC
}

static int fdb__json1_finish(fsl_diff_builder * const b){
static int fdb__json1_finish(fsl_dibu * const b){
  return fdb__out(b, "0]}", 3);
}

static fsl_diff_builder * fsl__diff_builder_json1(void){
  fsl_diff_builder * rc = fsl__diff_builder_alloc(0);
static fsl_dibu * fsl__diff_builder_json1(void){
  fsl_dibu * rc = fsl_dibu_alloc(0);
  if(rc){
    rc->chunkHeader = NULL;
    rc->start = fdb__json1_start;
    rc->skip = fdb__json1_skip;
    rc->common = fdb__json1_common;
    rc->insertion = fdb__json1_insertion;
    rc->deletion = fdb__json1_deletion;
    rc->replacement = fdb__json1_replacement;
    rc->edit = fdb__json1_edit;
    rc->finish = fdb__json1_finish;
    rc->finalize = fdb__generic_finalize;
    rc->finalize = fsl_dibu_finalizer;
    assert(!rc->pimpl);
    assert(0==rc->implFlags);
    assert(0==rc->lnLHS);
    assert(0==rc->lnRHS);
    assert(NULL==rc->opt);
  }
  return rc;
}

/**
   State for the text-mode unified(-ish) diff builder.  We do some
   hoop-jumping here in order to combine runs of delete/insert pairs
   into a group of deletes followed by a group of inserts. It's a
   cosmetic detail only but it makes for more readable output.
*/
struct DiBuUnified {
  /** True if currently processing a block of deletes, else false. */
  bool deleting;
  /** Buffer for insertion lines which are part of delete/insert
      pairs. */
  fsl_buffer bufIns;
};
typedef struct DiBuUnified DiBuUnified;

#define UIMPL(V) DiBuUnified * const V = (DiBuUnified*)b->pimpl
/**
   If utxt diff builder b has any INSERT lines to flush, this
   flushes them. Sets b->impl->deleting to false. Returns non-0
   on output error.
*/
static int fdb__utxt_flush_ins(fsl_dibu * const b){
  int rc = 0;
  UIMPL(p);
  p->deleting = false;
  if(p->bufIns.used>0){
    rc = fdb__out(b, fsl_buffer_cstr(&p->bufIns), p->bufIns.used);
    fsl_buffer_reuse(&p->bufIns);
  }
  return rc;
}

static int fdb__utxt_start(fsl_diff_builder * const b){
static int fdb__utxt_start(fsl_dibu * const b){
  int rc = 0;
  UIMPL(p);
  p->deleting = false;
  if(p->bufIns.mem) fsl_buffer_reuse(&p->bufIns);
  else fsl_buffer_reserve(&p->bufIns, 1024 * 2);
  if(0==(FSL_DIFF2_NOINDEX & b->opt->diffFlags)){
    rc = fdb__outf(b,"Index: %s\n%.66c\n",
                   b->opt->nameLHS/*RHS?*/, '=');
  }
  if(0==rc){
    rc = fdb__outf(b, "--- %s\n+++ %s\n",
                   b->opt->nameLHS, b->opt->nameRHS);
  }
  return rc;
}

static int fdb__utxt_chunkHeader(fsl_diff_builder* const b,
static int fdb__utxt_chunkHeader(fsl_dibu* const b,
                                 uint32_t lnnoLHS, uint32_t linesLHS,
                                 uint32_t lnnoRHS, uint32_t linesRHS ){
  /*
     Annoying cosmetic bug: the libf impl of this diff will sometimes
     render two directly-adjecent chunks with a separator, e.g.:
  */

  // $ f-vdiff --forat u 072d63965188 a725befe5863 -l '*vdiff*' | head -30
  // Index: f-apps/f-vdiff.c
  // ==================================================================
  // --- f-apps/f-vdiff.c
  // +++ f-apps/f-vdiff.c
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  //     36     36    fsl_buffer fname;
  //     37     37    fsl_buffer fcontent1;
  //     38     38    fsl_buffer fcontent2;
  //     39     39    fsl_buffer fhash;
  //     40     40    fsl_list globs;
  //            41 +  fsl_dibu_opt diffOpt;
  //            42 +  fsl_diff_builder * diffBuilder;
  //     41     43  } VDiffApp = {
  //     42     44  NULL/*glob*/,
  //     43     45  5/*contextLines*/,
  //     44     46  0/*sbsWidth*/,
  //     45     47  0/*diffFlags*/,
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  //     46     48  0/*brief*/,
  //     47     49  fsl_buffer_empty_m/*fname*/,
  //     48     50  fsl_buffer_empty_m/*fcontent1*/,

  /*
    Note now the chunks before/after the second ~~~ line are
    consecutive lines of code. In fossil(1) that case is accounted for
    in the higher-level diff engine, which can not only collapse
    adjacent blocks but also does the rendering of chunk headers in
    that main algorithm (something we cannot do in the library because
    we need the fsl_dibu to be able to output to arbitrary
    distinations). We can only _partially_ account for it here,
    eliminating the extraneous ~~~ line when we're in line-number
    mode. In non-line-number mode we have to output the chunk header
    as-is. If we skip it then the _previous_ chunk header, if any,
    will contain incorrect numbers for the chunk, invaliding the diff
    for purposes of tools which import unified-format diffs.
  */
  int rc = fdb__utxt_flush_ins(b);
  if(0==rc){
  if(FSL_DIFF2_LINE_NUMBERS & b->opt->diffFlags){
    return fdb__outf(b, "%.40c\n", '~');
  }else{
    return fdb__outf(b, "@@ -%" PRIu32 ",%" PRIu32
    if(FSL_DIFF2_LINE_NUMBERS & b->opt->diffFlags){
      rc = (lnnoLHS == b->lnLHS+1 && lnnoRHS == b->lnRHS+1)
        ? 0
        : fdb__outf(b, "%.40c\n", '~');
    }else{
      rc = fdb__outf(b, "@@ -%" PRIu32 ",%" PRIu32
                     " +%" PRIu32 ",%" PRIu32 " @@\n",
                     lnnoLHS, linesLHS, lnnoRHS, linesRHS);
  }
    }
  }
  return rc;
}


static int fdb__utxt_skip(fsl_diff_builder * const b, uint32_t n){
static int fdb__utxt_skip(fsl_dibu * const b, uint32_t n){
  //MARKER(("SKIP\n"));
  int rc = fdb__utxt_flush_ins(b);
  b->lnLHS += n;
  b->lnRHS += n;
  return 0;
  return rc;
}

/**
/** Outputs line numbers to b->opt->out. */
static int fdb__utxt_lineno(fsl_diff_builder * const b, uint32_t lnL, uint32_t lnR){
   Outputs line numbers, if configured to, to b->opt->out.

   - 2 line numbers = common lines
   - lnL only = deletion
   - lnR only = insertion
*/
static int fdb__utxt_lineno(fsl_dibu * const b, uint32_t lnL, uint32_t lnR){
  int rc = 0;
  if(FSL_DIFF2_LINE_NUMBERS & b->opt->diffFlags){
    UIMPL(p);
    rc = lnL
      ? fdb__outf(b, "%s%6" PRIu32 "%s ",
                  (lnR ? "" : b->opt->ansiColor.deletion),
                  lnL,
                  (lnR ? "" : b->opt->ansiColor.reset))
      : fdb__out(b, "       ", 7);
    if(lnL){ // common or delete
      rc = fdb__outf(b, "%s%6" PRIu32 "%s ",
                     (lnR ? "" : b->opt->ansiColor.deletion),
                     lnL,
                     (lnR ? "" : b->opt->ansiColor.reset));
    }else if(p->deleting){ // insert during deletion grouping
      rc = fsl_buffer_append(&p->bufIns, "       ", 7);
    }else{ // insert w/o deleting grouping
      rc = fdb__out(b, "       ", 7);
    }
    if(0==rc){
      if(!lnL && lnR && p->deleting){ // insert during deletion grouping
      rc = lnR
      ? fdb__outf(b, "%s%6" PRIu32 "%s ",
                  (lnL ? "" : b->opt->ansiColor.insertion),
                  lnR,
                  (lnL ? "" : b->opt->ansiColor.reset))
      : fdb__out(b, "       ", 7);
        rc = fsl_buffer_appendf(&p->bufIns, "%s%6" PRIu32 "%s ",
                                b->opt->ansiColor.insertion,
                                lnR, b->opt->ansiColor.reset);
      }else if(lnR){ // common or insert w/o deletion grouping.
        rc = fdb__outf(b, "%s%6" PRIu32 "%s ",
                       (lnL ? "" : b->opt->ansiColor.insertion),
                       lnR,
                       (lnL ? "" : b->opt->ansiColor.reset));
      }else{ // deletion
        rc = fdb__out(b, "       ", 7);
      }
    }
  }
  return rc;
}

static int fdb__utxt_common(fsl_diff_builder * const b, fsl_dline const * pLine){
static int fdb__utxt_common(fsl_dibu * const b, fsl_dline const * pLine){
  //MARKER(("COMMON\n"));
  int rc = fdb__utxt_flush_ins(b);
  if(0==rc){
  ++b->lnLHS;
  ++b->lnRHS;
  const int rc = fdb__utxt_lineno(b, b->lnLHS, b->lnRHS);
    ++b->lnLHS;
    ++b->lnRHS;
    rc = fdb__utxt_lineno(b, b->lnLHS, b->lnRHS);
  }
  return rc ? rc : fdb__outf(b, " %.*s\n", (int)pLine->n, pLine->z);
}

static int fdb__utxt_insertion(fsl_diff_builder * const b, fsl_dline const * pLine){
static int fdb__utxt_insertion(fsl_dibu * const b, fsl_dline const * pLine){
  //MARKER(("INSERT\n"));
  int rc;
  ++b->lnRHS;
  const int rc = fdb__utxt_lineno(b, 0, b->lnRHS);
  return rc ? rc : fdb__outf(b, "%s+%.*s%s\n",
                             b->opt->ansiColor.insertion,
                             (int)pLine->n, pLine->z,
                             b->opt->ansiColor.reset);
}
static int fdb__utxt_deletion(fsl_diff_builder * const b, fsl_dline const * pLine){
  rc = fdb__utxt_lineno(b, 0, b->lnRHS);
  if(0==rc){
    UIMPL(p);
    if(p->deleting){
      rc = fsl_buffer_appendf(&p->bufIns, "%s+%.*s%s\n",
                              b->opt->ansiColor.insertion,
                              (int)pLine->n, pLine->z,
                              b->opt->ansiColor.reset);
    }else{
      rc = fdb__outf(b, "%s+%.*s%s\n",
                     b->opt->ansiColor.insertion,
                     (int)pLine->n, pLine->z,
                     b->opt->ansiColor.reset);
    }
  }
  return rc;
}
static int fdb__utxt_deletion(fsl_dibu * const b, fsl_dline const * pLine){
  //MARKER(("DELETE\n"));
  UIMPL(p);
  int rc = p->deleting ? 0 : fdb__utxt_flush_ins(b);
  if(0==rc){
    p->deleting = true;
  ++b->lnLHS;
  const int rc = fdb__utxt_lineno(b, b->lnLHS, 0);
    ++b->lnLHS;
    rc = fdb__utxt_lineno(b, b->lnLHS, 0);
  }
  return rc ? rc : fdb__outf(b, "%s-%.*s%s\n",
                             b->opt->ansiColor.deletion,
                             (int)pLine->n, pLine->z,
                             b->opt->ansiColor.reset);
}
static int fdb__utxt_replacement(fsl_diff_builder * const b,
static int fdb__utxt_replacement(fsl_dibu * const b,
                                 fsl_dline const * lineLhs,
                                 fsl_dline const * lineRhs) {
  //MARKER(("REPLACE\n"));
  int rc = b->deletion(b, lineLhs);
  if(0==rc) rc = b->insertion(b, lineRhs);
  return rc;
}
static int fdb__utxt_edit(fsl_diff_builder * const b,
static int fdb__utxt_edit(fsl_dibu * const b,
                           fsl_dline const * lineLhs,
                           fsl_dline const * lineRhs){
  //MARKER(("EDIT\n"));
  int rc = b->deletion(b, lineLhs);
  if(0==rc) rc = b->insertion(b, lineRhs);
  return rc;
}

static int fdb__utxt_finish(fsl_dibu * const b){
  int rc = fdb__utxt_flush_ins(b);
  UIMPL(p);
  fsl_buffer_reuse(&p->bufIns);
  return rc;
}

static void fdb__utxt_finalize(fsl_diff_builder * const b){
static void fdb__utxt_finalize(fsl_dibu * const b){
  UIMPL(p);
  fsl_buffer_clear(&p->bufIns);
  fsl_free(b);
}

static fsl_diff_builder * fsl__diff_builder_utxt(void){
  fsl_diff_builder * rc = fsl__diff_builder_alloc(0);
static fsl_dibu * fsl__diff_builder_utxt(void){
  const DiBuUnified DiBuUnified_empty = {
  false, fsl_buffer_empty_m
  };
  fsl_dibu * rc = fsl_dibu_alloc(sizeof(DiBuUnified));
  if(!rc) return NULL;
  assert(NULL!=rc->pimpl);
  assert(NULL==rc->finally);
  *((DiBuUnified*)rc->pimpl) = DiBuUnified_empty;
  rc->chunkHeader = fdb__utxt_chunkHeader;
  rc->start = fdb__utxt_start;
  rc->skip = fdb__utxt_skip;
  rc->common = fdb__utxt_common;
  rc->insertion = fdb__utxt_insertion;
  rc->deletion = fdb__utxt_deletion;
  rc->replacement = fdb__utxt_replacement;
  rc->edit = fdb__utxt_edit;
  rc->finish = NULL;
  rc->finish = fdb__utxt_finish;
  rc->finalize = fdb__utxt_finalize;
  return rc;
}
#undef UIMPL

struct DiBuTcl {
  /** Buffer for TCL-format string conversion */
  fsl_buffer str;
};
typedef struct DiBuTcl DiBuTcl;
static const DiBuTcl DiBuTcl_empty = {fsl_buffer_empty_m};

#define BR_OPEN if(FSL_DIFF2_TCL_BRACES & b->opt->diffFlags) \
#define BR_OPEN if(FSL_DIBU_TCL_BRACES & b->implFlags) \
    rc = fdb__out(b, "{", 1)
#define BR_CLOSE if(FSL_DIFF2_TCL_BRACES & b->opt->diffFlags) \
#define BR_CLOSE if(FSL_DIBU_TCL_BRACES & b->implFlags) \
    rc = fdb__out(b, "}", 1)

#define DTCL_BUFFER(B) &((DiBuTcl*)(B)->pimpl)->str
static int fdb__outtcl(fsl_diff_builder * const b,
static int fdb__outtcl(fsl_dibu * const b,
                       char const *z, unsigned int n,
                       char chAppend ){
  int rc;
  fsl_buffer * const o = DTCL_BUFFER(b);
  fsl_buffer_reuse(o);
  rc = fsl_buffer_append_tcl_literal(o, z, n);
  rc = fsl_buffer_append_tcl_literal(o,
                                     (b->implFlags & FSL_DIBU_TCL_BRACES_ESC),
                                     z, n);
  if(0==rc) rc = fdb__out(b, (char const *)o->mem, o->used);
  if(chAppend && 0==rc) rc = fdb__out(b, &chAppend, 1);
  return rc;
}

static int fdb__tcl_start(fsl_diff_builder * const b){
static int fdb__tcl_start(fsl_dibu * const b){
  int rc = 0;
  fsl_buffer_reuse(DTCL_BUFFER(b));
  BR_OPEN;
  if(0==rc) rc = fdb__out(b, "\n", 1);
  if(1==++b->fileCount &&
     FSL_DIBU_TCL_TK==(b->implFlags & FSL_DIBU_TCL_TK)){
    rc = fdb__out(b, "set difftxt {\n", -1);
  }
  if(0==rc && b->fileCount>1) rc = fdb__out(b, "\n", 1);
  if(0==rc && b->opt->nameLHS){
    char const * zRHS =
      b->opt->nameRHS ? b->opt->nameRHS : b->opt->nameLHS;
    BR_OPEN;
    if(0==rc) rc = fdb__out(b, "FILE ", 5);
    if(0==rc) rc = fdb__outtcl(b, b->opt->nameLHS,
                               (unsigned)fsl_strlen(b->opt->nameLHS), ' ');
    if(0==rc) rc = fdb__outtcl(b, zRHS,
                               (unsigned)fsl_strlen(zRHS), 0);
    if(0==rc) {BR_CLOSE;}
    if(0==rc) rc = fdb__out(b, "\n", 1);
  }
  return rc;
}

static int fdb__tcl_skip(fsl_diff_builder * const b, uint32_t n){
static int fdb__tcl_skip(fsl_dibu * const b, uint32_t n){
  int rc = 0;
  BR_OPEN;
  if(0==rc) rc = fdb__outf(b, "SKIP %" PRIu32, n);
  if(0==rc) {BR_CLOSE;}
  if(0==rc) rc = fdb__outf(b, "\n", 1);
  return rc;
}

static int fdb__tcl_common(fsl_diff_builder * const b, fsl_dline const * pLine){
static int fdb__tcl_common(fsl_dibu * const b, fsl_dline const * pLine){
  int rc = 0;
  BR_OPEN;
  if(0==rc) rc = fdb__out(b, "COM  ", 5);
  if(0==rc) rc= fdb__outtcl(b, pLine->z, pLine->n, 0);
  if(0==rc) {BR_CLOSE;}
  if(0==rc) rc = fdb__outf(b, "\n", 1);
  return rc;
}
static int fdb__tcl_insertion(fsl_diff_builder * const b, fsl_dline const * pLine){
static int fdb__tcl_insertion(fsl_dibu * const b, fsl_dline const * pLine){
  int rc = 0;
  BR_OPEN;
  if(0==rc) rc = fdb__out(b, "INS  ", 5);
  if(0==rc) rc = fdb__outtcl(b, pLine->z, pLine->n, 0);
  if(0==rc) {BR_CLOSE;}
  if(0==rc) rc = fdb__outf(b, "\n", 1);
  return rc;
}
static int fdb__tcl_deletion(fsl_diff_builder * const b, fsl_dline const * pLine){
static int fdb__tcl_deletion(fsl_dibu * const b, fsl_dline const * pLine){
  int rc = 0;
  BR_OPEN;
  if(0==rc) rc = fdb__out(b, "DEL  ", 5);
  if(0==rc) rc = fdb__outtcl(b, pLine->z, pLine->n, 0);
  if(0==rc) {BR_CLOSE;}
  if(0==rc) rc = fdb__outf(b, "\n", 1);
  return rc;
}
static int fdb__tcl_replacement(fsl_diff_builder * const b,
static int fdb__tcl_replacement(fsl_dibu * const b,
                                fsl_dline const * lineLhs,
                                fsl_dline const * lineRhs) {
  int rc = 0;
  BR_OPEN;
  if(0==rc) rc = fdb__out(b, "EDIT \"\" ", 8);
  if(0==rc) rc = fdb__outtcl(b, lineLhs->z, lineLhs->n, ' ');
  if(0==rc) rc = fdb__outtcl(b, lineRhs->z, lineRhs->n, 0);
  if(0==rc) {BR_CLOSE;}
  if(0==rc) rc = fdb__outf(b, "\n", 1);
  return rc;
}
                 
static int fdb__tcl_edit(fsl_diff_builder * const b,
                         fsl_dline const * pX,
                         fsl_dline const * pY){
static int fdb__tcl_edit(fsl_dibu * const b,
                         fsl_dline const * lineLHS,
                         fsl_dline const * lineRHS){
  int rc = 0;
  int i, x;
  fsl_dline_change chng = fsl_dline_change_empty;
#define RC if(rc) goto end
  BR_OPEN;
  rc = fdb__out(b, "EDIT", 4); RC;
  fsl_dline_change_spans(pX, pY, &chng);
  fsl_dline_change_spans(lineLHS, lineRHS, &chng);
  for(i=x=0; i<chng.n; i++){
    rc = fdb__out(b, " ", 1); RC;
    rc = fdb__outtcl(b, pX->z + x, chng.a[i].iStart1 - x, ' '); RC;
    rc = fdb__outtcl(b, lineLHS->z + x, chng.a[i].iStart1 - x, ' '); RC;
    x = chng.a[i].iStart1;
    rc = fdb__outtcl(b, pX->z + x, chng.a[i].iLen1, ' '); RC;
    rc = fdb__outtcl(b, lineLHS->z + x, chng.a[i].iLen1, ' '); RC;
    x += chng.a[i].iLen1;
    rc = fdb__outtcl(b, pY->z + chng.a[i].iStart2,
    rc = fdb__outtcl(b, lineRHS->z + chng.a[i].iStart2,
                     chng.a[i].iLen2, 0); RC;
  }
  assert(0==rc);
  if( x < pX->n ){
  if( x < lineLHS->n ){
    rc = fdb__out(b, " ", 1); RC;
    rc = fdb__outtcl(b, pX->z + x, pX->n - x, 0); RC;
    rc = fdb__outtcl(b, lineLHS->z + x, lineLHS->n - x, 0); RC;
  }
  BR_CLOSE; RC;
  rc = fdb__out(b, "\n", 1);
  end:
#undef RC
  return rc;
}

static int fdb__tcl_finish(fsl_diff_builder * const b){
static int fdb__tcl_finish(fsl_dibu * const b){
  int rc = 0;
#if 0
  BR_CLOSE;
  if(0==rc && FSL_DIFF2_TCL_BRACES & b->opt->diffFlags){
  if(0==rc && FSL_DIBU_TCL_BRACES & b->implFlags){
    rc = fdb__out(b, "\n", 1);
  }
#endif
  return rc;
}
static int fdb__tcl_finally(fsl_dibu * const b){
  int rc = 0;
  if(FSL_DIBU_TCL_TK==(b->implFlags & FSL_DIBU_TCL_TK)){
    extern char const * fsl_difftk_cstr;
    rc = fdb__out(b, "}\nset fossilcmd {}\n", -1);
    if(0==rc) fdb__out(b, fsl_difftk_cstr, -1);
  }
  return rc;
}

#undef BR_OPEN
#undef BR_CLOSE

static void fdb__tcl_finalize(fsl_diff_builder * const b){
static void fdb__tcl_finalize(fsl_dibu * const b){
  fsl_buffer_clear( &((DiBuTcl*)b->pimpl)->str );
  *b = fsl_diff_builder_empty;
  *b = fsl_dibu_empty;
  fsl_free(b);
}

static fsl_diff_builder * fsl__diff_builder_tcl(void){
  fsl_diff_builder * rc =
    fsl__diff_builder_alloc((fsl_size_t)sizeof(DiBuTcl));
static fsl_dibu * fsl__diff_builder_tcl(void){
  fsl_dibu * rc =
    fsl_dibu_alloc((fsl_size_t)sizeof(DiBuTcl));
  if(rc){
    rc->chunkHeader = NULL;
    rc->start = fdb__tcl_start;
    rc->skip = fdb__tcl_skip;
    rc->common = fdb__tcl_common;
    rc->insertion = fdb__tcl_insertion;
    rc->deletion = fdb__tcl_deletion;
    rc->replacement = fdb__tcl_replacement;
    rc->edit = fdb__tcl_edit;
    rc->finish = fdb__tcl_finish;
    rc->finally = fdb__tcl_finally;
    rc->finalize = fdb__tcl_finalize;
    assert(0!=rc->pimpl);
    DiBuTcl * const dbt = (DiBuTcl*)rc->pimpl;
    *dbt = DiBuTcl_empty;
    if(fsl_buffer_reserve(&dbt->str, 120)){
      rc->finalize(rc);
      rc = 0;
    }
  }
  return rc;
}

/**
   Column indexes for SplitText::cols.
*/
enum SplitTextCols {
STC_NUM1 = 0, STC_TEXT1,
STC_MOD,
STC_NUM2, STC_TEXT2,
STC_count
};
/**
   Internal state for the text-mode split diff builder.

   This builder buffers its contents in 5 buffers: 2 each for the
   LHS/RHS line numbers and content and one for the "change marker" (a
   center column). Each of the STC_NUM1, STC_NUM2, STC_TEXT1, and
   STC_TEXT2 columns is stored as one NUL-delimited string in each of
   the corresponding column buffers. STC_MOD is a simple byte array,
   with each byte corresponding two one line of the diff and marking
   what type of linle it is (common, insertion, deletion, or
   edit/replacement).

   The STC_SKIP column is managed differently. It is zero-filled,
   with a non-0 value at each line of the diff which represents a
   skipped gap. Potential TODO: combine this and STC_MOD.
*/
struct SplitTxt {
  /**
     Largest column width we've yet seen. These are only updated for
     STC_TEXT1 and STC_TEXT2. The others currently have fixed widths.

     FIXME: these are in bytes, not text columns. The current code may
     truncate multibyte characters.
  */
  uint32_t maxWidths[STC_count];
};
typedef struct SplitTxt SplitTxt;
static const SplitTxt SplitTxt_empty = {{1,10,3,1,10}};
#define SPLITSTATE(VNAME) SplitTxt * const VNAME = (SplitTxt *)b->pimpl

static int maxColWidth(fsl_diff_builder const * const b,
                       SplitTxt const * const sst,
                       int mwIndex){
  static const short minColWidth =
    10/*b->opt.columnWidth values smaller than this are treated as
        this value*/;
  switch(mwIndex){
    case STC_NUM1:
    case STC_NUM2:
    case STC_MOD: return sst->maxWidths[mwIndex];
    case STC_TEXT1: case STC_TEXT2: break;
    default:
      assert(!"internal API misuse: invalid column index.");
      break;
  }
  int const y =
    (b->opt->columnWidth>0
     && b->opt->columnWidth<=sst->maxWidths[mwIndex])
    ? (int)b->opt->columnWidth
    : (int)sst->maxWidths[mwIndex];
  return minColWidth > y ? minColWidth : y;
}

static int fdb__splittxt_mod(fsl_diff_builder * const b, char ch){
static int fdb__splittxt_mod(fsl_dibu * const b, char ch){
  assert(2==b->passNumber);
  return fdb__outf(b, " %c ", ch);
}

static int fdb__splittxt_lineno(fsl_diff_builder * const b,
                                SplitTxt const * const sst,
static int fdb__splittxt_lineno(fsl_dibu * const b,
                                DiffCounter const * const sst,
                                bool isLeft, uint32_t n){
  assert(2==b->passNumber);
  int const col = isLeft ? STC_NUM1 : STC_NUM2;
  int const col = isLeft ? DICO_NUM1 : DICO_NUM2;
  return n
    ? fdb__outf(b, "%*" PRIu32 " ", sst->maxWidths[col], n)
    : fdb__outf(b, "%.*c ", sst->maxWidths[col], ' ');
}

static int fdb__splittxt_start(fsl_diff_builder * const b){
static int fdb__splittxt_start(fsl_dibu * const b){
  int rc = 0;
  if(1==b->passNumber){
    SPLITSTATE(sst);
    *sst = SplitTxt_empty;
    DICOSTATE(sst);
    *sst = DiffCounter_empty;
    ++b->fileCount;
    return rc;
  }
  if(b->fileCount>1){
    rc = fdb__out(b, "\n", 1);
  }
  if(0==rc){
    fsl_diff_opt const * const o = b->opt;
    fsl_dibu_opt const * const o = b->opt;
    if(o->nameLHS || o->nameRHS
       || o->hashLHS || o->hashRHS){
      rc = fdb__outf(b, "--- %s%s%s\n+++ %s%s%s\n",
                     o->nameLHS ? o->nameLHS : "",
                     (o->nameLHS && o->hashLHS) ? " " : "",
                     o->hashLHS ? o->hashLHS : "",
                     o->nameRHS ? o->nameRHS : "",
                     (o->nameRHS && o->hashRHS) ? " " : "",
                     o->hashRHS ? o->hashRHS : "");
    }
  }
  return rc;
}

static int fdb__splittxt_skip(fsl_diff_builder * const b, uint32_t n){
static int fdb__splittxt_skip(fsl_dibu * const b, uint32_t n){
  b->lnLHS += n;
  b->lnRHS += n;
  if(1==b->passNumber) return 0;
  SPLITSTATE(sst);
  int const maxWidth1 = maxColWidth(b, sst, STC_TEXT1);
  int const maxWidth2 = maxColWidth(b, sst, STC_TEXT2);
  DICOSTATE(sst);
  int const maxWidth1 = maxColWidth(b, sst, DICO_TEXT1);
  int const maxWidth2 = maxColWidth(b, sst, DICO_TEXT2);
  return fdb__outf(b, "%.*c %.*c   %.*c %.*c\n",
                 sst->maxWidths[STC_NUM1], '~',
                 sst->maxWidths[DICO_NUM1], '~',
                 maxWidth1, '~',
                 sst->maxWidths[STC_NUM2], '~',
                 sst->maxWidths[DICO_NUM2], '~',
                 maxWidth2, '~');
}

static int fdb__splittxt_color(fsl_diff_builder * const b,
static int fdb__splittxt_color(fsl_dibu * const b,
                               int modType){
  char const *z = 0;
  switch(modType){
    case (int)'i': z = b->opt->ansiColor.insertion; break;
    case (int)'d': z = b->opt->ansiColor.deletion; break;
    case (int)'r'/*replacement*/: 
    case (int)'e': z = b->opt->ansiColor.edit; break;
    case 0: z = b->opt->ansiColor.reset; break;
    default:
      assert(!"invalid color op!");
  }
  return z&&*z ? fdb__outf(b, "%s", z) : 0;
}

static int fdb__splittxt_side(fsl_diff_builder * const b,
                              SplitTxt * const sst,
static int fdb__splittxt_side(fsl_dibu * const b,
                              DiffCounter * const sst,
                              bool isLeft,
                              fsl_dline const * const pLine){
  int rc = fdb__splittxt_lineno(b, sst, isLeft,
                                pLine ? (isLeft ? b->lnLHS : b->lnRHS) : 0U);
  if(0==rc){
    uint32_t const w = maxColWidth(b, sst, isLeft ? STC_TEXT1 : STC_TEXT2);
    uint32_t const w = maxColWidth(b, sst, isLeft ? DICO_TEXT1 : DICO_TEXT2);
    if(pLine){
      fsl_size_t const nU =
        /* Measure column width in UTF8 characters, not bytes! */
        fsl_strlen_utf8(pLine->z, (fsl_int_t)pLine->n);
      rc = fdb__outf(b, "%#.*s", (int)(w < nU ? w : nU), pLine->z);
      if(0==rc && w>nU){
        rc = fdb__outf(b, "%.*c", (int)(w - nU), ' ');
      }
    }else{
      rc = fdb__outf(b, "%.*c", (int)w, ' ');
    }
    if(0==rc && !isLeft) rc = fdb__out(b, "\n", 1);
  }
  return rc;
}

static void fdb__splittext_update_maxlen(SplitTxt * const sst,
                                         int col,
                                         char const * const z,
                                         uint32_t n){
  if(sst->maxWidths[col]<n){
#if 0
    sst->maxWidths[col] = n;
#else
    n = (uint32_t)fsl_strlen_utf8(z, (fsl_int_t)n);
    if(sst->maxWidths[col]<n) sst->maxWidths[col] = n;
#endif
  }
}

static int fdb__splittxt_common(fsl_diff_builder * const b,
static int fdb__splittxt_common(fsl_dibu * const b,
                                fsl_dline const * const pLine){
  int rc = 0;
  SPLITSTATE(sst);
  DICOSTATE(sst);
  ++b->lnLHS;
  ++b->lnRHS;
  if(1==b->passNumber){
    fdb__splittext_update_maxlen(sst, STC_TEXT1, pLine->z, pLine->n);
    fdb__splittext_update_maxlen(sst, STC_TEXT2, pLine->z, pLine->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT1, pLine->z, pLine->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT2, pLine->z, pLine->n);
    return 0;
  }
  rc = fdb__splittxt_side(b, sst, true, pLine);
  if(0==rc) rc = fdb__splittxt_mod(b, ' ');
  if(0==rc) rc = fdb__splittxt_side(b, sst, false, pLine);
  return rc;
}

static int fdb__splittxt_insertion(fsl_diff_builder * const b,
static int fdb__splittxt_insertion(fsl_dibu * const b,
                                   fsl_dline const * const pLine){
  int rc = 0;
  SPLITSTATE(sst);
  DICOSTATE(sst);
  ++b->lnRHS;
  if(1==b->passNumber){
    fdb__splittext_update_maxlen(sst, STC_TEXT1, pLine->z, pLine->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT1, pLine->z, pLine->n);
    return rc;
  }
  rc = fdb__splittxt_color(b, 'i');
  if(0==rc) rc = fdb__splittxt_side(b, sst, true, NULL);
  if(0==rc) rc = fdb__splittxt_mod(b, '>');
  if(0==rc) rc = fdb__splittxt_side(b, sst, false, pLine);
  if(0==rc) rc = fdb__splittxt_color(b, 0);
  return rc;
}

static int fdb__splittxt_deletion(fsl_diff_builder * const b,
static int fdb__splittxt_deletion(fsl_dibu * const b,
                                  fsl_dline const * const pLine){
  int rc = 0;
  SPLITSTATE(sst);
  DICOSTATE(sst);
  ++b->lnLHS;
  if(1==b->passNumber){
    fdb__splittext_update_maxlen(sst, STC_TEXT2, pLine->z, pLine->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT2, pLine->z, pLine->n);
    return rc;
  }
  rc = fdb__splittxt_color(b, 'd');
  if(0==rc) rc = fdb__splittxt_side(b, sst, true, pLine);
  if(0==rc) rc = fdb__splittxt_mod(b, '<');
  if(0==rc) rc = fdb__splittxt_side(b, sst, false, NULL);
  if(0==rc) rc = fdb__splittxt_color(b, 0);
  return rc;
}

static int fdb__splittxt_replacement(fsl_diff_builder * const b,
static int fdb__splittxt_replacement(fsl_dibu * const b,
                                     fsl_dline const * const lineLhs,
                                     fsl_dline const * const lineRhs) {
#if 0
  int rc = b->deletion(b, lineLhs);
  if(0==rc) rc = b->insertion(b, lineRhs);
  return rc;
#else    
  int rc = 0;
  SPLITSTATE(sst);
  DICOSTATE(sst);
  ++b->lnLHS;
  ++b->lnRHS;
  if(1==b->passNumber){
    fdb__splittext_update_maxlen(sst, STC_TEXT1, lineLhs->z, lineLhs->n);
    fdb__splittext_update_maxlen(sst, STC_TEXT2, lineRhs->z, lineRhs->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT1, lineLhs->z, lineLhs->n);
    fdb__dico_update_maxlen(sst, DICO_TEXT2, lineRhs->z, lineRhs->n);
    return 0;
  }
  rc = fdb__splittxt_color(b, 'e');
  if(0==rc) rc = fdb__splittxt_side(b, sst, true, lineLhs);
  if(0==rc) rc = fdb__splittxt_mod(b, '|');
  if(0==rc) rc = fdb__splittxt_side(b, sst, false, lineRhs);
  if(0==rc) rc = fdb__splittxt_color(b, 0);
  return rc;
#endif
}
                 
static int fdb__splittxt_finish(fsl_diff_builder * const b){

static int fdb__splittxt_finish(fsl_dibu * const b){
  int rc = 0;
  if(1==b->passNumber){
    SPLITSTATE(sst);
    DICOSTATE(sst);
    uint32_t ln = b->lnLHS;
    /* Calculate width of line number columns. */
    sst->maxWidths[STC_NUM1] = sst->maxWidths[STC_NUM2] = 1;
    for(; ln>=10; ln/=10) ++sst->maxWidths[STC_NUM1];
    sst->maxWidths[DICO_NUM1] = sst->maxWidths[DICO_NUM2] = 1;
    for(; ln>=10; ln/=10) ++sst->maxWidths[DICO_NUM1];
    ln = b->lnRHS;
    for(; ln>=10; ln/=10) ++sst->maxWidths[STC_NUM2];
    for(; ln>=10; ln/=10) ++sst->maxWidths[DICO_NUM2];
  }
  return rc;
}

static void fdb__splittxt_finalize(fsl_diff_builder * const b){
  *b = fsl_diff_builder_empty;
static void fdb__splittxt_finalize(fsl_dibu * const b){
  *b = fsl_dibu_empty;
  fsl_free(b);
}

static fsl_diff_builder * fsl__diff_builder_splittxt(void){
  fsl_diff_builder * rc =
    fsl__diff_builder_alloc((fsl_size_t)sizeof(SplitTxt));
static fsl_dibu * fsl__diff_builder_splittxt(void){
  fsl_dibu * rc =
    fsl_dibu_alloc((fsl_size_t)sizeof(DiffCounter));
  if(rc){
    rc->twoPass = true;
    rc->chunkHeader = NULL;
    rc->start = fdb__splittxt_start;
    rc->skip = fdb__splittxt_skip;
    rc->common = fdb__splittxt_common;
    rc->insertion = fdb__splittxt_insertion;
    rc->deletion = fdb__splittxt_deletion;
    rc->replacement = fdb__splittxt_replacement;
    rc->edit = fdb__splittxt_replacement;
    rc->finish = fdb__splittxt_finish;
    rc->finalize = fdb__splittxt_finalize;
    assert(0!=rc->pimpl);
    SplitTxt * const sst = (SplitTxt*)rc->pimpl;
    *sst = SplitTxt_empty;
    DiffCounter * const sst = (DiffCounter*)rc->pimpl;
    *sst = DiffCounter_empty;
  }
  return rc;
}

int fsl_diff_builder_factory( fsl_diff_builder_e type,
                              fsl_diff_builder **pOut ){
int fsl_dibu_factory( fsl_dibu_e type,
                              fsl_dibu **pOut ){
  int rc = FSL_RC_TYPE;
  fsl_diff_builder * (*factory)(void) = NULL;
  fsl_dibu * (*factory)(void) = NULL;
  switch(type){
    case FSL_DIFF_BUILDER_DEBUG:
    case FSL_DIBU_DEBUG:
      factory = fsl__diff_builder_debug;
      break;
    case FSL_DIFF_BUILDER_JSON1:
    case FSL_DIBU_JSON1:
      factory = fsl__diff_builder_json1;
      break;
    case FSL_DIFF_BUILDER_UNIFIED_TEXT:
    case FSL_DIBU_UNIFIED_TEXT:
      factory = fsl__diff_builder_utxt;
      break;
    case FSL_DIFF_BUILDER_TCL:
    case FSL_DIBU_TCL:
      factory = fsl__diff_builder_tcl;
      break;
    case FSL_DIFF_BUILDER_SPLIT_TEXT:
    case FSL_DIBU_SPLIT_TEXT:
      factory = fsl__diff_builder_splittxt;
      break;
    case FSL_DIBU_INVALID: break;
  }
  if(NULL!=factory){
    *pOut = factory();
    rc = *pOut ? 0 : FSL_RC_OOM;
  }
  return rc;
}

#undef DIFF_ALIGN_MX
#undef DIFF_CANNOT_COMPUTE_BINARY
#undef DIFF_CANNOT_COMPUTE_SYMLINK
#undef DIFF_TOO_MANY_CHANGES
#undef DIFF_WHITESPACE_ONLY
#undef fsl_dline_empty_m
#undef MARKER
#undef DTCL_BUFFER
#undef blob_to_utf8_no_bom
#undef SPLITSTATE
/* end of file diff2.c */
/* start of file encode.c */
#undef DICOSTATE
#undef FSL_DIFF_SMALL_GAP
/* end of file ./src/diff2.c */
/* start of file ./src/encode.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
28347
28348
28349
28350
28351
28352
28353
28354
28355


28356
28357
28358
28359
28360
28361
28362
28621
28622
28623
28624
28625
28626
28627


28628
28629
28630
28631
28632
28633
28634
28635
28636







-
-
+
+







    return (char *)b.mem /* transfer ownership */;
  }else{
    fsl_buffer_clear(&b);
    return NULL;
  }
}

/* end of file encode.c */
/* start of file event.c */
/* end of file ./src/encode.c */
/* start of file ./src/event.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
28394
28395
28396
28397
28398
28399
28400
28401
28402


28403
28404
28405
28406
28407
28408
28409
28668
28669
28670
28671
28672
28673
28674


28675
28676
28677
28678
28679
28680
28681
28682
28683







-
-
+
+







    }
    return rc;
  }
}


#undef MARKER
/* end of file event.c */
/* start of file fs.c */
/* end of file ./src/event.c */
/* start of file ./src/fs.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
28418
28419
28420
28421
28422
28423
28424
28425

28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438

28439
28440
28441
28442
28443
28444
28445
28692
28693
28694
28695
28696
28697
28698

28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711

28712
28713
28714
28715
28716
28717
28718
28719







-
+












-
+








#include <assert.h>
#include <string.h> /* strlen() */
#include <stddef.h> /* NULL on linux */
#include <ctype.h>
#include <errno.h>
#include <dirent.h>
#ifdef _WIN32
#if FSL_PLATFORM_IS_WINDOWS
# define DIR _WDIR
# define dirent _wdirent
# define opendir _wopendir
# define readdir _wreaddir
# define closedir _wclosedir
# include <direct.h>
# include <windows.h>
# include <sys/utime.h>
# if !defined(ELOOP)
#  define ELOOP 114 /* Missing in MinGW */
# endif
#else
# include <unistd.h> /* access(2) */
# include <unistd.h> /* access(2), readlink(2) */
# include <sys/types.h>
# include <sys/time.h>
#endif
#include <sys/stat.h>

/* Only for debugging */
#include <stdio.h>
28534
28535
28536
28537
28538
28539
28540
28541

28542
28543
28544
28545
28546
28547
28548
28549
28808
28809
28810
28811
28812
28813
28814

28815

28816
28817
28818
28819
28820
28821
28822







-
+
-







  memcpy(zBuf, zPwdUtf8, nPwd+1);
  fsl_filename_free(zPwdUtf8);
  if(outLen) *outLen = nPwd;
  return 0;
#else
  if(!zBuf) return FSL_RC_MISUSE;
  else if(!nBuf) return FSL_RC_RANGE;
  else if( getcwd(zBuf,
  else if( NULL==getcwd(zBuf,nBuf) ){
                  nBuf /*-1 not necessary: getcwd() NUL-terminates*/)==0 ){
    return fsl_errno_to_rc(errno, FSL_RC_IO);
  }else{
    if(outLen) *outLen = fsl_strlen(zBuf);
    return 0;
  }
#endif
}
28564
28565
28566
28567
28568
28569
28570
28571

28572
28573
28574
28575
28576
28577
28578
28837
28838
28839
28840
28841
28842
28843

28844
28845
28846
28847
28848
28849
28850
28851







-
+







#if !defined(S_ISLNK)
# define S_ISLNK(x) (0)
#endif

/* Reminder: the semantics of the 3rd parameter are
   reversed from v1's fossil_stat().
*/
int fsl_stat(const char *zFilename, fsl_fstat * fst,
int fsl_stat(const char *zFilename, fsl_fstat * const fst,
             bool derefSymlinks){
  /* FIXME: port in fossil(1) win32_stat() */
  if(!zFilename) return FSL_RC_MISUSE;
  else if(!*zFilename) return FSL_RC_RANGE;
  else{
    int rc;
    struct stat buf;
28663
28664
28665
28666
28667
28668
28669




28670
28671

28672
28673



28674
28675
28676
28677
28678
28679
28680
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947

28948


28949
28950
28951
28952
28953
28954
28955
28956
28957
28958







+
+
+
+

-
+
-
-
+
+
+







  fsl_fstat fst;
  return ( 0 != fsl_stat(zFilename, &fst, 1) )
    ? false
    : (FSL_FSTAT_TYPE_FILE == fst.type);
}

bool fsl_is_symlink(const char *zFilename){
#if FSL_PLATFORM_IS_WINDOWS
  if(zFilename){/*unused var*/}
  return false;
#else
  fsl_fstat fst;
  return ( 0 != fsl_stat(zFilename, &fst, 0) )
  return (0 == fsl_stat(zFilename, &fst, 0))
    ? false
    : (FSL_FSTAT_TYPE_LINK == fst.type);
    ? (FSL_FSTAT_TYPE_LINK == fst.type)
    : false;
#endif
}

/*
   Return true if zPath is an absolute pathname.  Return false
   if it is relative.
*/
bool fsl_is_absolute_path(const char *zPath){
28777
28778
28779
28780
28781
28782
28783

28784
28785
28786
28787
28788
28789
28790
28791
28792

28793
28794
28795
28796
28797
28798
28799
28800
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069


29070

29071
29072
29073
29074
29075
29076
29077







+







-
-
+
-










fsl_size_t fsl_file_simplify_name(char *z, fsl_int_t n_, bool slash){
  fsl_size_t i;
  fsl_size_t n = (n_<0) ? fsl_strlen(z) : (fsl_size_t)n_;
  fsl_int_t j;
  bool const hadSlash = n && (z[n-1]=='/');
  /* On windows and cygwin convert all \ characters to / */
#if defined(_WIN32) || defined(__CYGWIN__)
  for(i=0; i<n; i++){
    if( z[i]=='\\' ) z[i] = '/';
  }
#endif
  /* Removing trailing "/" characters */
  if( !slash ){
    while( n>1 && z[n-1]=='/' ){ n--; }
  while( n>1 && z[n-1]=='/' ){--n;}
  }

  /* Remove duplicate '/' characters.  Except, two // at the beginning
     of a pathname is allowed since this is important on windows. */
  for(i=j=1; i<n; i++){
    z[j++] = z[i];
    while( z[i]=='/' && i<n-1 && z[i+1]=='/' ) i++;
  }
28822
28823
28824
28825
28826
28827
28828

28829
28830
28831
28832
28833
28834
28835

28836
28837
28838
28839
28840
28841
28842
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112

29113
29114
29115
29116
29117
29118
29119
29120







+






-
+







        continue;
      }
    }
    if( j>=0 ) z[j] = z[i];
    j++;
  }
  if( j==0 ) z[j++] = '.';
  if(slash && hadSlash && '/'!=z[j-1]) z[j++] = '/';
  z[j] = 0;
  return (fsl_size_t)j;
}

int fsl_file_canonical_name2(const char *zRoot,
                             const char *zOrigName,
                             fsl_buffer *pOut, bool slash){
                             fsl_buffer * const pOut, bool slash){
  int rc;
  if(!zOrigName || !pOut) return FSL_RC_MISUSE;
  else if( fsl_is_absolute_path(zOrigName) || (zRoot && !*zRoot)){
    rc = fsl_buffer_append( pOut, zOrigName, -1 );
#if defined(_WIN32) || defined(__CYGWIN__)
    if(!rc){
      char *zOut;
28880
28881
28882
28883
28884
28885
28886

28887

28888
28889
28890
28891
28892
28893

28894
28895
28896
28897
28898
28899
28900
29158
29159
29160
29161
29162
29163
29164
29165

29166
29167
29168
29169
29170
29171

29172
29173
29174
29175
29176
29177
29178
29179







+
-
+





-
+







    pOut->used = newLen;
  }
  return rc;
}


int fsl_file_canonical_name(const char *zOrigName,
                            fsl_buffer * const pOut,
                            fsl_buffer *pOut, bool slash){
                            bool slash){
  return fsl_file_canonical_name2(NULL, zOrigName, pOut, slash);
}

int fsl_file_dirpart(char const * zFilename,
                     fsl_int_t nLen,
                     fsl_buffer * pOut,
                     fsl_buffer * const pOut,
                     bool leaveSlash){
  if(!zFilename || !*zFilename || !pOut) return FSL_RC_MISUSE;
  else if(!nLen) return FSL_RC_RANGE;
  else{
    fsl_size_t n = (nLen>0) ? (fsl_size_t)nLen : fsl_strlen(zFilename);
    char const * z = zFilename + n;
    char doBreak = 0;
29165
29166
29167
29168
29169
29170
29171






29172
29173
29174
29175
29176
29177
29178
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463







+
+
+
+
+
+







    FILE_ATTRIBUTE_ENCRYPTED | FILE_ATTRIBUTE_NORMAL |
    FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
  );
  return dwAttributes==FILE_ATTRIBUTE_DIRECTORY;
}
#endif


bool fsl_file_isexec(const char *zFilename){
  fsl_fstat st = fsl_fstat_empty;
  int const s = fsl_stat(zFilename, &st, true);
  return 0==s ? (st.perm & FSL_FSTAT_PERM_EXE) : false;
}

int fsl_rmdir(const char *zFilename){
  int rc = fsl_dir_check(zFilename);
  if(rc<1) return rc ? FSL_RC_TYPE : FSL_RC_NOT_FOUND;
#ifdef _WIN32
  wchar_t *z = (wchar_t*)fsl_utf8_to_filename(zFilename);
  if(w32_file_is_normal_dir(z)){
29517
29518
29519
29520
29521
29522
29523




29524
29525
29526



29527
29528
29529
29530
29531
29532
29533
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812



29813
29814
29815
29816
29817
29818
29819
29820
29821
29822







+
+
+
+
-
-
-
+
+
+







    }
  }
  if(err) rc = fsl_errno_to_rc(errno, FSL_RC_IO);
  return rc;
#endif
}

/**
   fsl_dircrawl() part for handling a single directory. fst must be
   valid state from a freshly-fsl_fstat()'d DIRECTORY.
*/
static int fsl_dircrawl_impl(fsl_buffer * dbuf, fsl_fstat * fst,
                             fsl_dircrawl_f cb, void * cbState,
                             fsl_dircrawl_state * dst,
static int fsl_dircrawl_impl(fsl_buffer * const dbuf, fsl_fstat * const fst,
                             fsl_dircrawl_f cb, void * const cbState,
                             fsl_dircrawl_state * const dst,
                             unsigned int depth){
  int rc = 0;
  DIR *dir = opendir(fsl_buffer_cstr(dbuf));
  struct dirent * dent = 0;
  fsl_size_t const dPos = dbuf->used;
  if(!dir){
    return fsl_errno_to_rc(errno, FSL_RC_IO);
29567
29568
29569
29570
29571
29572
29573


29574
29575
29576
29577
29578
29579
29580
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871







+
+







    rc = cb( dst );
    if(!rc){
      dbuf->mem[dbuf->used] = '/';
      dbuf->used = newLen;
      if(FSL_FSTAT_TYPE_DIR==fst->type){
        rc = fsl_dircrawl_impl( dbuf, fst, cb, cbState, dst, depth+1 );
      }
    }else if(FSL_RC_NOOP == rc){
      rc = 0;
    }
  }
  closedir(dir);
  return rc;
}

int fsl_dircrawl(char const * dirName, fsl_dircrawl_f callback,
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610




29611
29612
29613
29614
29615
29616
29617
29892
29893
29894
29895
29896
29897
29898



29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909







-
-
-
+
+
+
+







  }
  fsl_buffer_clear(&dbuf);
  return rc;
}

bool fsl_is_file_or_link(const char *zFilename){
  fsl_fstat fst = fsl_fstat_empty;
  if(fsl_stat(zFilename, &fst, false)) return false;
  return fst.type==FSL_FSTAT_TYPE_FILE
    || fst.type==FSL_FSTAT_TYPE_LINK;
  return fsl_stat(zFilename, &fst, false)
    ? false
    : (fst.type==FSL_FSTAT_TYPE_FILE
       || fst.type==FSL_FSTAT_TYPE_LINK);
}

fsl_size_t fsl_strip_trailing_slashes(char * name, fsl_int_t nameLen){
  fsl_size_t rc = 0;
  if(nameLen < 0) nameLen = (fsl_int_t)fsl_strlen(name);
  if(nameLen){
    char * z = name + nameLen - 1;
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637




29638
29639
29640
29641

29642
29643
29644
29645
29646
29647

29648
29649
29650
29651





























































































































29652
29653
29654






















































































29655
29656
29657
29658
29659
29660
29661
29920
29921
29922
29923
29924
29925
29926



29927
29928
29929
29930
29931
29932


29933

29934
29935
29936


29937

29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065



30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158







-
-
-
+
+
+
+


-
-
+
-



-
-
+
-



+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







                                        (fsl_int_t)b->used);
}

int fsl_file_rename(const char *zFrom, const char *zTo){
  int rc;
#if defined(_WIN32)
  /** 2021-03-24: fossil's impl of this routine has 2 additional
      params (bool isFromDir, bool isToDir), which are only used on
      Windows platforms and are only to allow for 12 bytes of edge
      case in MAX_PATH handling.  We don't need them. */
      params (bool isFromDir, bool isToDir), which are passed on to
      fsl_utf8_to_filename(), only used on Windows platforms, and are
      only to allow for 12 bytes of edge case in MAX_PATH handling.
      We don't need them. */
  wchar_t *zMbcsFrom = fsl_utf8_to_filename(zFrom);
  wchar_t *zMbcsTo = zMbcsFrom ? fsl_utf8_to_filename(zTo) : 0;
  rc = zMbcsTo
    ? _wrename(zMbcsFrom, zMbcsTo)
  rc = zMbcsTo ? _wrename(zMbcsFrom, zMbcsTo) : FSL_RC_OOM;
    : FSL_RC_OOM;
#else
  char *zMbcsFrom = fsl_utf8_to_filename(zFrom);
  char *zMbcsTo = zMbcsFrom ? fsl_utf8_to_filename(zTo) : 0;
  rc = zMbcsTo
    ? rename(zMbcsFrom, zMbcsTo)
  rc = zMbcsTo ? rename(zMbcsFrom, zMbcsTo) : FSL_RC_OOM;
    : FSL_RC_OOM;
#endif
  fsl_filename_free(zMbcsTo);
  fsl_filename_free(zMbcsFrom);
  return -1==rc ? fsl_errno_to_rc(errno, FSL_RC_IO) : rc;
}

char ** fsl_temp_dirs_get(void){
#if FSL_PLATFORM_IS_WINDOWS
  const char *azDirs[] = {
     ".",
     NULL
  };
  unsigned int const nDirs = 4
    /* GetTempPath(), $TEMP, $TMP, azDirs */;
#else
  const char *azDirs[] = {
     "/var/tmp",
     "/usr/tmp",
     "/tmp",
     "/temp",
     ".", NULL
  };
  unsigned int const nDirs = 6
    /* $TMPDIR, azDirs */;
#endif
  char *z;
  char const *zC;
  char ** zDirs = NULL;
  unsigned int i, n = 0;

  zDirs = (char **)fsl_malloc(sizeof(char*) * (nDirs + 1));
  if(!zDirs) return NULL;
  for(i = 0; i<=nDirs; ++i) zDirs[i] = NULL;
#define DOZ \
  if(z && fsl_dir_check(z)>0) zDirs[n++] = z;   \
  else if(z) fsl_filename_free(z)

#if FSL_PLATFORM_IS_WINDOWS
  wchar_t zTmpPath[MAX_PATH];

  if( GetTempPathW(MAX_PATH, zTmpPath) ){
    z = fsl_filename_to_utf8(zTmpPath);
    DOZ;
  }
  z = fsl_getenv("TEMP");
  DOZ;
  z = fsl_getenv("TMP");
  DOZ;
#else /* Unix-like */
  z = fsl_getenv("TMPDIR");
  DOZ;
#endif
  for( i = 0; (zC = azDirs[i]); ++i ){
    z = fsl_filename_to_utf8(azDirs[i]);
    DOZ;
  }
#undef DOZ
  /* Strip any trailing slashes unless the only character is a
     slash. Note that we ignore the root-dir case on Windows here,
     mainly because this developer can't test it and secondarily
     because it's a highly unlikely case. */
  for(i = 0; i < n; ++i ){
    fsl_size_t len;
    z = zDirs[i];
    len = fsl_strlen(z);
    while(len>1 && (z[len-1]=='/' || z[len-1]=='\\')){
      z[--len] = 0;
    }    
  }
  return zDirs;  
}

void fsl_temp_dirs_free(char **aDirs){
  if(aDirs){
    char * z;
    for(unsigned i = 0; (z = aDirs[i]); ++i){
      fsl_filename_free(z);
      aDirs[i] = NULL;
    }
    fsl_free(aDirs);
  }
}

int fsl_file_tempname(fsl_buffer * const tgt, char const *zPrefix,
                      char * const * const dirs){
  int rc = 0;
  unsigned int tries = 0; 
  const unsigned char zChars[] =
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "0123456789_";
  enum { RandSize = 24 };
  char zRand[RandSize + 1];
  int i;
  char const * zDir = "";
  if(dirs){
    for(i = 0; (zDir=dirs[i++]); ){
      /* We repeat this check, performed in fsl_temp_dirs_get(), for the
         sake of long-lived apps where a given temp dir might disappear
         at some point. */
      if(fsl_dir_check(zDir)>0) break;
    }
    if(!zDir) return FSL_RC_NOT_FOUND;
  }
  if(!zPrefix) zPrefix = "libfossil";
  fsl_buffer_reuse(tgt);
  /* Pre-fill buffer to allocate it in advance and remember the length
     of the base filename part so that we don't have to re-write the
     prefix each iteration below. */
  rc = fsl_buffer_appendf(tgt, "%/%s%s%s%.*cZ",
                          zDir, *zDir ? "/" : "",
                          zPrefix, *zPrefix ? "~" : "",
                          (int)RandSize, 'X');
  fsl_size_t const baseLen = rc ? 0 : (tgt->used - RandSize - 1);
  do{
    if(++tries == 20){
      rc = FSL_RC_RANGE;
      break;
    }
    fsl_randomness(RandSize, zRand);
    for( i=0; i < RandSize; ++i ){
      zRand[i] = (char)zChars[ ((unsigned char)zRand[i])%(sizeof(zChars)-1) ];
    }
    zRand[RandSize] = 0;
    tgt->used = baseLen;
    rc = fsl_buffer_append(tgt, zRand, (fsl_int_t)RandSize);
    assert(0==rc && "We pre-allocated the buffer above.");
  }while(0==rc && fsl_file_size(fsl_buffer_cstr(tgt)) >= 0);
  return rc
    ? (FSL_RC_OOM==rc ? rc : fsl_errno_to_rc(errno, FSL_RC_IO))
    : 0;
  return rc;
}

int fsl_file_copy(char const *zFrom, char const *zTo){
  FILE * in = 0, *out = 0;
  int rc;
  in = fsl_fopen(zFrom, "rb");
  if(!in) return fsl_errno_to_rc(errno, FSL_RC_IO);
  rc = fsl_mkdir_for_file(zTo, false);
  if(rc) goto end;
  out = fsl_fopen(zTo, "wb");
  rc = out
    ? fsl_stream(fsl_input_f_FILE, in, fsl_output_f_FILE, out)
    : fsl_errno_to_rc(errno, FSL_RC_IO);
  end:
  if(in) fsl_fclose(in);
  if(out) fsl_fclose(out);
  if(0==rc && fsl_file_isexec(zFrom)){
    fsl_file_exec_set(zTo, true);
  }
  return rc;
}

int fsl_symlink_read(fsl_buffer * const tgt, char const * zFilename){
#if FSL_PLATFORM_IS_WINDOWS
  fsl_buffer_reuse(tgt);
  return 0;
#else
  enum { BufLen = 1024 * 2 };
  char buf[BufLen];
  int rc;
  ssize_t const len = readlink(zFilename, buf, BufLen-1);
  if(len<0) rc = fsl_errno_to_rc(errno, FSL_RC_IO);
  else{
    fsl_buffer_reuse(tgt);
    rc = fsl_buffer_append(tgt, buf, (fsl_size_t)len);
  }
  return rc;
#endif
}

int fsl_symlink_create(const char *zTargetFile, const char *zLinkFile,
                       bool realLink){
  int rc;
#if !FSL_PLATFORM_IS_WINDOWS
  if( realLink ){
    char *zName, zBuf[1024 * 2];
    fsl_size_t nName = fsl_strlen(zLinkFile);
    if( nName>=sizeof(zBuf) ){
      zName = fsl_mprintf("%s", zLinkFile);
      if(!zName) return FSL_RC_OOM;
    }else{
      zName = zBuf;
      memcpy(zName, zLinkFile, nName+1);
    }
    nName = fsl_file_simplify_name(zName, (fsl_int_t)nName, false);
    rc = fsl_mkdir_for_file(zName, false);
    if(0==rc && 0!=symlink(zTargetFile, zName) ){
      rc = fsl_errno_to_rc(errno, FSL_RC_IO);
    }
    if( zName!=zBuf ) fsl_free(zName);
  }else
#endif
  {
    rc = fsl_mkdir_for_file(zLinkFile, false);
    if(0==rc){
      fsl_buffer content = fsl_buffer_empty;
      fsl_buffer_external(&content, zTargetFile, -1);
      fsl_file_unlink(zLinkFile)
        /* in case it's already a symlink, we don't want the following
           to overwrite the symlinked-to file */;
      rc = fsl_buffer_to_filename(&content, zLinkFile);
    }
  }
  return rc;
}

int fsl__symlink_copy(char const *zFrom, char const *zTo, bool realLink){
  int rc;
  fsl_buffer b = fsl_buffer_empty;
  rc = fsl_symlink_read(&b, zFrom);
  if(0==rc){
    rc = fsl_symlink_create(fsl_buffer_cstr(&b), zTo, realLink);
  }
  fsl_buffer_clear(&b);
  return rc;
}

#if 0
int fsl_file_relative_name( char const * zRoot, char const * zPath,
                            fsl_buffer * pOut, char retainSlash ){
  int rc = FSL_RC_NYI;
  char * zPath;
29672
29673
29674
29675
29676
29677
29678
29679
29680


29681
29682
29683
29684
29685
29686
29687
30169
30170
30171
30172
30173
30174
30175


30176
30177
30178
30179
30180
30181
30182
30183
30184







-
-
+
+







#ifdef _WIN32
#  undef DIR
#  undef dirent
#  undef opendir
#  undef readdir
#  undef closedir
#endif
/* end of file fs.c */
/* start of file forum.c */
/* end of file ./src/fs.c */
/* start of file ./src/forum.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
29718
29719
29720
29721
29722
29723
29724
29725
29726


29727
29728
29729
29730
29731
29732
29733
30215
30216
30217
30218
30219
30220
30221


30222
30223
30224
30225
30226
30227
30228
30229
30230







-
-
+
+







  }
  return rc;
}



#undef MARKER
/* end of file forum.c */
/* start of file glob.c */
/* end of file ./src/forum.c */
/* start of file ./src/glob.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
29807
29808
29809
29810
29811
29812
29813
29814
29815


29816
29817
29818
29819
29820
29821
29822
30304
30305
30306
30307
30308
30309
30310


30311
30312
30313
30314
30315
30316
30317
30318
30319







-
-
+
+







    }
  }
  return *z==0;
#endif
}


int fsl_glob_list_parse( fsl_list * tgt, char const * zPatternList ){
  fsl_size_t i;             /* Loop counters */
int fsl_glob_list_parse( fsl_list * const tgt, char const * zPatternList ){
  fsl_size_t i;             /* Loop counter */
  char const *z = zPatternList;
  char * cp;
  char delimiter;    /* '\'' or '\"' or 0 */
  int rc = 0;
  char const * end;
  if( !tgt || !zPatternList ) return FSL_RC_MISUSE;
  else if(!*zPatternList) return 0;
29864
29865
29866
29867
29868
29869
29870
29871

29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890


29891
29892
29893
29894
29895
29896
29897
30361
30362
30363
30364
30365
30366
30367

30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385


30386
30387
30388
30389
30390
30391
30392
30393
30394







-
+

















-
-
+
+







      glob = (char const *)globList->list[i];
      if( fsl_str_glob( glob, zNeedle ) ) return glob;
    }
    return NULL;
  }
}

int fsl_glob_list_append( fsl_list * tgt, char const * zGlob ){
int fsl_glob_list_append( fsl_list * const tgt, char const * zGlob ){
  if(!tgt || !zGlob || !*zGlob) return FSL_RC_MISUSE;
  else{
    char * cp = fsl_strdup(zGlob);
    int rc = cp ? 0 : FSL_RC_OOM;
    if(!rc){
      rc = fsl_list_append(tgt, cp);
      if(rc) fsl_free(cp);
    }
    return rc;
  }
}


void fsl_glob_list_clear( fsl_list * const globList ){
  if(globList) fsl_list_visit_free(globList, 1);
}

/* end of file glob.c */
/* start of file io.c */
/* end of file ./src/glob.c */
/* start of file ./src/io.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
30023
30024
30025
30026
30027
30028
30029
30030
30031


30032
30033
30034
30035
30036
30037
30038
30520
30521
30522
30523
30524
30525
30526


30527
30528
30529
30530
30531
30532
30533
30534
30535







-
-
+
+







    if(rc) break;
    rn1 = rn2 = BufSize;
  }
  return rc;
}

#undef MARKER
/* end of file io.c */
/* start of file leaf.c */
/* end of file ./src/io.c */
/* start of file ./src/leaf.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059



30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070

30071
30072
30073
30074
30075
30076
30077
30547
30548
30549
30550
30551
30552
30553



30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575







-
-
-
+
+
+











+








/* Only for debugging */
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

int fsl_repo_leaves_rebuild(fsl_cx * f){
  fsl_db * db = f ? fsl_cx_db_repo(f) : NULL;
  return !db ? FSL_RC_MISUSE : fsl_db_exec_multi(db,
int fsl_repo_leaves_rebuild(fsl_cx * const f){
  fsl_db * const db = fsl_cx_db_repo(f);
  int rc = fsl_db_exec_multi(db,
    "DELETE FROM leaf;"
    "INSERT OR IGNORE INTO leaf"
    "  SELECT cid FROM plink"
    "  EXCEPT"
    "  SELECT pid FROM plink"
    "   WHERE coalesce((SELECT value FROM tagxref"
                       " WHERE tagid=%d AND rid=plink.pid),'trunk')"
         " == coalesce((SELECT value FROM tagxref"
                       " WHERE tagid=%d AND rid=plink.cid),'trunk')",
    FSL_TAGID_BRANCH, FSL_TAGID_BRANCH
  );
  return rc ? fsl_cx_uplift_db_error2(f, db, rc) : 0;
}

fsl_int_t fsl_count_nonbranch_children(fsl_cx * const f, fsl_id_t rid){
  int32_t rv = 0;
  int rc;
  fsl_db * const db = fsl_cx_db_repo(f);
  if(!db || !db->dbh || (rid<=0)) return -1;
30201
30202
30203
30204
30205
30206
30207
30208

30209
30210
30211
30212
30213
30214
30215
30699
30700
30701
30702
30703
30704
30705

30706
30707
30708
30709
30710
30711
30712
30713







-
+







      !rc && rid; rid=fsl_id_bag_next(&f->cache.leafCheck,rid)){
    rc = fsl__repo_leafcheck(f, rid);
  }
  fsl_id_bag_reset(&f->cache.leafCheck);
  return rc;
}

int fsl_leaves_compute(fsl_cx * f, fsl_id_t vid,
int fsl_leaves_compute(fsl_cx * const f, fsl_id_t vid,
                       fsl_leaves_compute_e closeMode){
  fsl_db * const db = fsl_needs_repo(f);
  if(!db) return FSL_RC_NOT_A_REPO;
  int rc = 0;

  /* Create the LEAVES table if it does not already exist.  Make sure
  ** it is empty.
30343
30344
30345
30346
30347
30348
30349
30350

30351
30352
30353
30354
30355

30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369

30370
30371
30372
30373
30374
30375
30376



30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387







30388
30389
30390
30391
30392


30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412

30413
30414
30415
30416
30417
30418
30419
30841
30842
30843
30844
30845
30846
30847

30848
30849
30850
30851
30852

30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866

30867
30868
30869
30870
30871



30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883


30884
30885
30886
30887
30888
30889
30890
30891
30892
30893


30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914

30915
30916
30917
30918
30919
30920
30921
30922







-
+




-
+













-
+




-
-
-
+
+
+









-
-
+
+
+
+
+
+
+



-
-
+
+



















-
+







  return rc;
  dberr:
  assert(rc);
  rc = fsl_cx_uplift_db_error2(f, db, rc);
  goto end;
}

bool fsl_leaves_computed_has(fsl_cx * f){
bool fsl_leaves_computed_has(fsl_cx * const f){
  return fsl_db_exists(fsl_cx_db_repo(f),
                       "SELECT 1 FROM leaves");
}

fsl_int_t fsl_leaves_computed_count(fsl_cx * f){
fsl_int_t fsl_leaves_computed_count(fsl_cx * const f){
  int32_t rv = -1;
  fsl_db * const db = fsl_cx_db_repo(f);
  int const rc = fsl_db_get_int32(db, &rv,
                                 "SELECT COUNT(*) FROM leaves");
  if(rc){
    fsl_cx_uplift_db_error2(f, db, rc);
    assert(-1==rv);
  }else{
    assert(rv>=0);
  }
  return rv;
}

fsl_id_t fsl_leaves_computed_latest(fsl_cx * f){
fsl_id_t fsl_leaves_computed_latest(fsl_cx * const f){
  fsl_id_t rv = 0;
  fsl_db * const db = fsl_cx_db_repo(f);
  int const rc =
    fsl_db_get_id(db, &rv,
                    "SELECT rid FROM leaves, event"
                    " WHERE event.objid=leaves.rid"
                    " ORDER BY event.mtime DESC");
                  "SELECT rid FROM leaves, event"
                  " WHERE event.objid=leaves.rid"
                  " ORDER BY event.mtime DESC");
  if(rc){
    fsl_cx_uplift_db_error2(f, db, rc);
    assert(!rv);
  }else{
    assert(rv>=0);
  }
  return rv;
}

void fsl_leaves_computed_cleanup(fsl_cx * f){
  fsl_db_exec(fsl_cx_db_repo(f), "DROP TABLE IF EXISTS leaves");
void fsl_leaves_computed_cleanup(fsl_cx * const f){
  if(fsl_cx_exec(f, "DROP TABLE IF EXISTS temp.leaves")){
    /**
       Naively assume that locking is keeping us from dropping it,
       and simply empty it instead. */
    fsl_cx_exec(f, "DELETE FROM temp.leaves");
  }
}

#undef MARKER
/* end of file leaf.c */
/* start of file list.c */
/* end of file ./src/leaf.c */
/* start of file ./src/list.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/************************************************************************
  This file houses the implementations for the fsl_list routines.
*/

#include <assert.h>
#include <stdlib.h> /* malloc() and friends, qsort() */
#include <memory.h> /* memset() */
int fsl_list_reserve( fsl_list * self, fsl_size_t n )
int fsl_list_reserve( fsl_list * const self, fsl_size_t n )
{
  if( !self ) return FSL_RC_MISUSE;
  else if(0 == n){
    if(0 == self->capacity) return 0;
    fsl_free(self->list);
    *self = fsl_list_empty;
    return 0;
30428
30429
30430
30431
30432
30433
30434
30435

30436
30437
30438
30439
30440
30441

30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462

30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475

30476
30477
30478
30479
30480
30481
30482
30931
30932
30933
30934
30935
30936
30937

30938
30939
30940
30941
30942
30943

30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964

30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977

30978
30979
30980
30981
30982
30983
30984
30985







-
+





-
+




















-
+












-
+







    memset( m + self->capacity, 0, (sizeof(void*)*(n-self->capacity)));
    self->capacity = n;
    self->list = m;
    return 0;
  }
}

void fsl_list_swap( fsl_list * lhs, fsl_list * rhs ){
void fsl_list_swap( fsl_list * const lhs, fsl_list * const rhs ){
  fsl_list tmp = *lhs;
  *rhs = *lhs;
  *lhs = tmp;
}

int fsl_list_append( fsl_list * self, void* cp ){
int fsl_list_append( fsl_list * const self, void* cp ){
  if( !self ) return FSL_RC_MISUSE;
  assert(self->used <= self->capacity);
  if(self->used == self->capacity){
    int rc;
    fsl_size_t const cap = self->capacity
      ? (self->capacity * 2)
      : 10;
    rc = fsl_list_reserve(self, cap);
    if(rc) return rc;
  }
  self->list[self->used++] = cp;
  if(self->used<self->capacity) self->list[self->used]=NULL;
  return 0;
}

int fsl_list_v_fsl_free(void * obj, void * visitorState ){
  if(obj) fsl_free( obj );
  return 0;
}

int fsl_list_clear( fsl_list * self, fsl_list_visitor_f childFinalizer,
int fsl_list_clear( fsl_list * const self, fsl_list_visitor_f childFinalizer,
                    void * finalizerState ){
  /*
    TODO: manually traverse the list and set each list entry for which
    the finalizer succeeds to NULL, so that we can provide
    well-defined behaviour if childFinalizer() fails and we abort the
    loop.
   */
  int rc = fsl_list_visit(self, 0, childFinalizer, finalizerState );
  if(!rc) fsl_list_reserve(self, 0);
  return rc;
}

void fsl_list_visit_free( fsl_list * self, bool freeListMem ){
void fsl_list_visit_free( fsl_list * const self, bool freeListMem ){
  fsl_list_visit(self, 0, fsl_list_v_fsl_free, NULL );
  if(freeListMem) fsl_list_reserve(self, 0);
  else self->used = 0;
}


int fsl_list_visit( fsl_list const * self, int order,
30497
30498
30499
30500
30501
30502
30503
30504

30505
30506
30507
30508
30509
30510
30511
31000
31001
31002
31003
31004
31005
31006

31007
31008
31009
31010
31011
31012
31013
31014







-
+







      }
    }
  }
  return rc;
}


int fsl_list_visit_p( fsl_list * self, int order,
int fsl_list_visit_p( fsl_list * const self, int order,
                      bool shiftIfNulled,
                      fsl_list_visitor_f visitor, void * visitorState )
{
  int rc = FSL_RC_OK;
  if( self && self->used && visitor ){
    fsl_int_t i = 0;
    fsl_int_t pos = (order<0) ? self->used-1 : 0;
30529
30530
30531
30532
30533
30534
30535
30536

30537
30538
30539
30540
30541
30542
30543
31032
31033
31034
31035
31036
31037
31038

31039
31040
31041
31042
31043
31044
31045
31046







-
+







        }
      }
    }
  }
  return rc;
}

void fsl_list_sort( fsl_list * li,
void fsl_list_sort( fsl_list * const li,
                    fsl_generic_cmp_f cmp){
  if(li && li->used>1){
    qsort( li->list, li->used, sizeof(void*), cmp );
  }
}


30561
30562
30563
30564
30565
30566
30567
30568
30569


30570
30571
30572
30573
30574
30575
30576
31064
31065
31066
31067
31068
31069
31070


31071
31072
31073
31074
31075
31076
31077
31078
31079







-
-
+
+







}


fsl_int_t fsl_list_index_of_cstr( fsl_list const * li,
                                  char const * key ){
  return fsl_list_index_of(li, key, fsl_strcmp_cmp);
}
/* end of file list.c */
/* start of file lookslike.c */
/* end of file ./src/list.c */
/* start of file ./src/lookslike.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
30619
30620
30621
30622
30623
30624
30625





30626
30627
30628
30629
30630
30631
30632
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140







+
+
+
+
+







#undef US2B
#undef US3A
#undef US3B
#undef US4A
#undef US4B
#undef US4C
#undef US0A

bool fsl_looks_like_binary(fsl_buffer const * const b){
  return (fsl_looks_like_utf8(b, FSL_LOOKSLIKE_BINARY) & FSL_LOOKSLIKE_BINARY)
    != FSL_LOOKSLIKE_NONE;
}

int fsl_looks_like_utf8(fsl_buffer const * const b, int stopFlags){
  fsl_size_t n = 0;
  const char *z = fsl_buffer_cstr2(b, &n);
  int j, c, flags = FSL_LOOKSLIKE_NONE;  /* Assume UTF-8 text, prove otherwise */

  if( n==0 ) return flags;  /* Empty file -> text */
30709
30710
30711
30712
30713
30714
30715
30716
30717


30718
30719
30720
30721
30722
30723
30724
31217
31218
31219
31220
31221
31222
31223


31224
31225
31226
31227
31228
31229
31230
31231
31232







-
-
+
+







      c = (c>=0xC0) ? (c|3) : ' '; /* determine next lead byte */
    } else {
      c = *++z;
    }
  }
  return c<0x80 /* Final lead byte must be ASCII. */;
}
/* end of file lookslike.c */
/* start of file md5.c */
/* end of file ./src/lookslike.c */
/* start of file ./src/md5.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/*
   The code is modified for use in fossil (then libfossil).  The
   original header comment follows:
*/
/*
 * This code implements the MD5 message-digest algorithm.
31152
31153
31154
31155
31156
31157
31158
31159
31160



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































31161
31162
31163
31164
31165
31166
31167
31660
31661
31662
31663
31664
31665
31666


31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948







-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+








#undef F1
#undef F2
#undef F3
#undef F4
#undef MD5STEP
#undef byteReverse
/* end of file md5.c */
/* start of file merge3.c */
/* end of file ./src/md5.c */
/* start of file ./src/merge.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
#include <assert.h>
#include <memory.h>
#include <stdlib.h>
#include <string.h> /* memmove()/strlen() */

#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)

#define FSL__TABLE_PIVOT "aqueue"

/**
   Sets the primary version of a merge.  The primary version is
   one of the two files that have a common ancestor.  The other file
   is the secondary.  There can be multiple secondaries but only a
   single primary.  The primary must be set first.

   In the merge algorithm, the file being merged in is the primary.
   The current check-out or other files that have been merged into
   the current checkout are the secondaries.

   The act of setting the primary resets the pivot-finding algorithm.

   Returns 0 on success, non-0 on serious error.

   This works using a TEMP db, so does not strictly require
   a repo or checkout.

   @see fsl__pivot_set_secondary()
   @see fsl__pivot_find()
*/
static int fsl__pivot_set_primary(fsl_cx * const f, fsl_id_t rid){
  /* Set up table used to do the search */
  int rc = fsl_cx_exec_multi(f,
    "CREATE TEMP TABLE IF NOT EXISTS " FSL__TABLE_PIVOT "("
    "  rid INTEGER,"              /* The record id for this version */
    "  mtime REAL,"               /* Time when this version was created */
    "  pending BOOLEAN,"          /* True if we have not check this one yet */
    "  src BOOLEAN,"               /* 1 for primary.  0 for others */
    "  PRIMARY KEY(rid,src)"
    ") WITHOUT ROWID;"
    "DELETE FROM " FSL__TABLE_PIVOT ";"
    "CREATE INDEX IF NOT EXISTS " FSL__TABLE_PIVOT "_idx1 ON " FSL__TABLE_PIVOT "(pending, mtime);"
  );
  if(0==rc){
    /* Insert the primary record */
    rc = fsl_cx_exec(f,
      "INSERT INTO " FSL__TABLE_PIVOT "(rid, mtime, pending, src)"
      "  SELECT %" FSL_ID_T_PFMT ", mtime, 1, 1 "
      "  FROM event WHERE objid=%" FSL_ID_T_PFMT
      " AND type='ci' LIMIT 1",
      rid, rid );
  }
  return rc;  
}

/**
   Set a secondary file of a merge. The primary file must be set
   first. There must be at least one secondary but there can be more
   than one if desired.

   Returns 0 on success, non-0 on db error.

   @see fsl__pivot_set_primary()
   @see fsl__pivot_find()
*/
static int fsl__pivot_set_secondary(fsl_cx * const f, fsl_id_t rid){
  return fsl_cx_exec(f,
    "INSERT OR IGNORE INTO " FSL__TABLE_PIVOT "(rid, mtime, pending, src)"
    "  SELECT %" FSL_ID_T_PFMT ", mtime, 1, 0 "
    "FROM event WHERE objid=%" FSL_ID_T_PFMT " AND type='ci'",
    rid, rid
  );
}


/**
   Searches for the most recent common ancestor of the primary and one of
   the secondaries in a merge.

   On success, *outRid is set to its value and 0 is returned. If no
   match is found, *outRid is set to 0 and 0 is returned. Returns
   non-0 on error, indicating either a lower-level db error or an
   allocation error.

   If ignoreMerges is true, it follows only "primary" parent links.

   @see fsl__pivot_set_primary()
   @see fsl__pivot_set_secondary()
*/
static int fsl__pivot_find(fsl_cx * const f, bool ignoreMerges, fsl_id_t *outRid){
  fsl_db * const db = fsl_cx_db(f);
  int rc;
  fsl_stmt q1 = fsl_stmt_empty, q2 = fsl_stmt_empty,
    u1 = fsl_stmt_empty, i1 = fsl_stmt_empty;
  fsl_id_t rid = 0;
  if(fsl_db_g_int32(db, 0, "SELECT COUNT(distinct src) FROM " FSL__TABLE_PIVOT "")<2){
    return fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Pivot list [" FSL__TABLE_PIVOT "] contains neither primary "
                          "nor secondary entries.");
  }
  /* Prepare queries we will be needing
  **
  ** The first query finds the oldest pending version on the
  ** FSL__TABLE_PIVOT. This will be next one searched.
  */
  rc = fsl_cx_prepare(f, &q1,
                      "SELECT rid FROM " FSL__TABLE_PIVOT " WHERE pending"
                      " ORDER BY pending DESC, mtime DESC");
  if(rc) goto end;

  /* Check to see if the record :rid is a common ancestor.  The result
  ** set contains one or more rows if it is and is the empty set if it
  ** is not.
  */
  rc = fsl_cx_prepare(f, &q2,
    "SELECT 1 FROM " FSL__TABLE_PIVOT " A, plink, " FSL__TABLE_PIVOT " B"
    " WHERE plink.pid=?1"
    "   AND plink.cid=B.rid"
    "   AND A.rid=?1"
    "   AND A.src!=B.src %s",
    ignoreMerges ? "AND plink.isprim" : ""
  );
  if(rc) goto end;

  /* Mark the :rid record has having been checked.  It is not the
  ** common ancestor.
  */
  rc = fsl_cx_prepare(f, &u1,
    "UPDATE " FSL__TABLE_PIVOT " SET pending=0 WHERE rid=?1"
  );
  if(rc) goto end;

  /* Add to the queue all ancestors of :rid.
  */
  rc = fsl_cx_prepare(f, &i1,
    "REPLACE INTO " FSL__TABLE_PIVOT " "
    "SELECT plink.pid,"
    " coalesce((SELECT mtime FROM event X WHERE X.objid=plink.pid), 0.0),"
    " 1,"
    " " FSL__TABLE_PIVOT ".src "
    "  FROM plink, " FSL__TABLE_PIVOT
    " WHERE plink.cid=?1"
    "   AND " FSL__TABLE_PIVOT ".rid=?1 %s",
    ignoreMerges ? "AND plink.isprim" : ""
  );
  if(rc) goto end;
  while(FSL_RC_STEP_ROW==(rc = fsl_stmt_step(&q1))){
    rid = fsl_stmt_g_id(&q1, 0);
    fsl_stmt_reset(&q1);
    rc = fsl_stmt_bind_step(&q2, "R", rid);
    if(rc) break/*error or found match*/;
    rc = fsl_stmt_bind_step(&i1, "R", rid);
    assert(FSL_RC_STEP_ROW!=rc);
    if(0==rc) rc = fsl_stmt_bind_step(&u1, "R", rid);
    if(rc) break;
    assert(FSL_RC_STEP_ROW!=rc);
    rid = 0;
  }
  switch(rc){
    case 0: break;
    case FSL_RC_STEP_ROW:
    case FSL_RC_STEP_DONE: rc = 0; break;
    default:
      rc = fsl_cx_uplift_db_error2(f, NULL, rc);
      break;
  }
  end:
  fsl_stmt_finalize(&q1);
  fsl_stmt_finalize(&q2);
  fsl_stmt_finalize(&u1);
  fsl_stmt_finalize(&i1);
  if(0==rc  && rid) *outRid = rid;
  return rc;
}

/**
   Searches f's current repository for the nearest fork related to
   version vid.

   More specifically: this looks for the most recent leaf that is (1)
   not equal to vid and (2) has not already been merged into vid and
   (3) the leaf is not closed and (4) the leaf is in the same branch
   as vid.

   If checkVmerge is true then the current checkout
   database is also checked (via the vmerge table), in which case a
   checkout must be opened.

   On success, returns 0 and assigns *outRid to the resulting RID.

   On error:

   - FSL_RC_NOT_A_REPO or FSL_RC_NOT_A_CKOUT if called when no repo or
     (if checkVmerge is true) no checkout.

   - FSL_RC_NOT_FOUND: no closest merge was found.

   - FSL_RC_OOM: on allocation error

   - Any number of potential other errors from the db layer.

   f's error state will contain more information about errors reported
   here.
*/
/*static*/ int fsl__find_nearest_fork(fsl_cx * const f,
                                  fsl_id_t vid, bool checkVmerge,
                                  fsl_id_t * outRid){
  fsl_db * const db = checkVmerge
    ? fsl_needs_ckout(f) : fsl_needs_repo(f);
  fsl_buffer * const sql = fsl__cx_scratchpad(f);
  fsl_stmt q;
  if(!db){
    return checkVmerge ? FSL_RC_NOT_A_CKOUT : FSL_RC_NOT_A_REPO;
  }
  q = fsl_stmt_empty;
  int rc = fsl_buffer_appendf(sql,
    "SELECT leaf.rid"
    "  FROM leaf, event"
    " WHERE leaf.rid=event.objid"
    "   AND leaf.rid!=%" FSL_ID_T_PFMT,  /* Constraint (1) */
    vid
  );
  if(rc) goto end;
  if( checkVmerge ){
    rc = fsl_buffer_append(sql,
      "   AND leaf.rid NOT IN (SELECT merge FROM vmerge)"
      /* Constraint (2) */, -1 );
    if(rc) goto end;
  }
  rc = fsl_buffer_appendf(sql,
    "   AND NOT EXISTS(SELECT 1 FROM tagxref" /* Constraint (3) */
                  "     WHERE rid=leaf.rid"
                  "       AND tagid=%d"
                  "       AND tagtype>0)"
    "   AND (SELECT value FROM tagxref"      /* Constraint (4) */
          "  WHERE tagid=%d AND rid=%" FSL_ID_T_PFMT " AND tagtype>0) ="
          " (SELECT value FROM tagxref"
          "  WHERE tagid=%d AND rid=leaf.rid AND tagtype>0)"
    " ORDER BY event.mtime DESC LIMIT 1",
                         FSL_TAGID_CLOSED,
                         FSL_TAGID_BRANCH,
                         vid, FSL_TAGID_BRANCH
  );
  if(rc) goto end;
  rc = fsl_db_prepare(db, &q, "%b", sql);
  if(rc){
    rc = fsl_cx_uplift_db_error2(f, db, rc);
    goto end;
  }
  rc = fsl_stmt_step(&q);
  switch(rc){
    case FSL_RC_STEP_ROW:
      rc = 0;
      *outRid = fsl_stmt_g_id(&q, 0);
      assert(*outRid>0);
      break;
    case FSL_RC_STEP_DONE:
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Cannot find nearest fork of RID #%"
                          FSL_ID_T_PFMT ".", vid);
      break;
    default:
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      break;
  }
  end:
  fsl_stmt_finalize(&q);
  fsl__cx_scratchpad_yield(f, sql);
  return rc;
}

/**
   Name for the merge algo's version of the fv table, noting that it
   differs enough from the update algo's version that they do not
   map 1-to-1 without some degree of pain which might make sense
   once merge is in the library and working.
*/
#define FSL__TABLE_FVM "fvm"

static int fsl__renames_init(fsl_cx * const f){
  char const * const coll = fsl_cx_filename_collation(f);
  return fsl_cx_exec_multi(f,
    "CREATE TEMP TABLE IF NOT EXISTS " FSL__TABLE_FVM "(\n"
    "  fn TEXT UNIQUE %s,\n"       /* The filename */
    "  idv INTEGER DEFAULT 0,\n"   /* VFILE entry for current version */
    "  idp INTEGER DEFAULT 0,\n"   /* VFILE entry for the pivot */
    "  idm INTEGER DEFAULT 0,\n"   /* VFILE entry for version merging in */
    "  chnged BOOLEAN,\n"          /* True if current version has been edited */
    "  ridv INTEGER DEFAULT 0,\n"  /* Record ID for current version */
    "  ridp INTEGER DEFAULT 0,\n"  /* Record ID for pivot */
    "  ridm INTEGER DEFAULT 0,\n"  /* Record ID for merge */
    "  isexe BOOLEAN,\n"           /* Execute permission enabled */
    "  fnp TEXT UNIQUE %s,\n"      /* The filename in the pivot */
    "  fnm TEXT UNIQUE %s,\n"      /* The filename in the merged version */
    "  fnn TEXT UNIQUE %s,\n"      /* The filename in the name pivot */
    "  islinkv BOOLEAN,\n"         /* True if current version is a symlink */
    "  islinkm BOOLEAN\n"          /* True if merged version in is a symlink */
    ");"
    "DELETE FROM " FSL__TABLE_FVM ";",
    coll, coll, coll, coll);
}

static int fsl__renames_finalize(fsl_cx * const f){
  return fsl_cx_exec(f,
                     //"DROP TABLE IF EXISTS " FSL__TABLE_FVM
                     "DELETE FROM " FSL__TABLE_FVM);
}

static int fsl__renames_add(fsl_cx * const f,
                            char const * zFnCol,
                            fsl_id_t vid, fsl_id_t nid,
                            bool reverseOk){
  int rc;
  uint32_t i; /* loop counter */
  uint32_t nChng; /* # of entries in aChng */
  fsl_id_t * aChng = 0; /* Array of filename changes */
  fsl_stmt q1 = fsl_stmt_empty, q2 = fsl_stmt_empty;
  fsl_db * const db = fsl_cx_db_repo(f);
  rc = fsl__find_filename_changes(f, nid, vid, reverseOk, &nChng, &aChng);
  if(rc) goto end;
  else if(0==nChng) return 0;
  rc = fsl_cx_prepare(f, &q1,
                      "SELECT name FROM filename WHERE fnid=?1");
  if(0==rc){
    rc = fsl_cx_prepare(f, &q2,
                        "SELECT name FROM filename WHERE fnid=?1");
  }
  for(i=0; 0==rc && i < nChng; ++i){
    char const *zN;
    char const *zV;
    rc = fsl_stmt_bind_step(&q1, "R", aChng[i*2]);
    if(FSL_RC_STEP_ROW==rc){
      rc = fsl_stmt_bind_step(&q2, "R", aChng[i*2+1]);
      if(FSL_RC_STEP_ROW==rc) rc = 0;
    }
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, NULL, rc);
      break;
    }
    rc = fsl_stmt_get_text(&q1, 0, &zN, NULL);
    if(0==rc) rc = fsl_stmt_get_text(&q2, 0, &zV, NULL);
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, db, rc);
      break;
    }
    rc = fsl_cx_exec(f,"INSERT OR IGNORE INTO " FSL__TABLE_FVM
                     "(%s,fnn) VALUES(%Q,%Q)",
                     zFnCol, zV, zN);
    if(0==rc && 0==fsl_db_changes_recent(db)){
      rc = fsl_cx_exec_multi(f, "UPDATE " FSL__TABLE_FVM
                             " SET %s=%Q WHERE fnn=%Q",
                             zFnCol, zV, zN);
    }
  }
  end:
  fsl_stmt_finalize(&q1);
  fsl_stmt_finalize(&q2);
  fsl_free(aChng);
  return rc;
}

/**
   Part of fsl_ckout_merge() related to collecting filenames and
   setting up renames. Returns 0 on success.
*/
static int fsl__renames_tweak(fsl_cx * const f, fsl_id_t mid,
                              fsl_id_t pid, fsl_id_t vid,
                              fsl_id_t nid,
                              fsl_merge_opt const * const mOpt){
  int rc = 0;
  char vAncestor = 'p'; /* If P is an ancestor of V then 'p', else 'n' */

  rc = fsl__renames_init(f);
  if(0==rc) rc = fsl__renames_add(f, "fn", vid, nid, false);
  if(0==rc) rc = fsl__renames_add(f, "fnp", pid, nid, false);
  if(0==rc) rc = fsl__renames_add(f, "fnm", mid, nid,
                                  FSL_MERGE_TYPE_BACKOUT==mOpt->mergeType);
  /*
    It goes without saying that all of the SQL wizardry which follows
    was implemented by D. Richard Hipp. Its usage here does not imply
    any real understanding of it on the fossil-to-libfossil porter's
    part.
  */
  if(rc) goto end;
  else if(nid!=pid){
    /* See forum thread https://fossil-scm.org/forum/forumpost/549700437b
    **
    ** If a filename changes between nid and one of the other check-ins
    ** pid, vid, or mid, then it might not have changed for all of them.
    ** try to fill in the appropriate filename in all slots where the
    ** name is missing.
    **
    ** This does not work if
    **   (1) The filename changes more than once in between nid and vid/mid
    **   (2) Two or more filenames swap places - for example if A is renamed
    **       to B and B is renamed to A.
    ** The Fossil merge algorithm breaks down in those cases.  It will need
    ** to be completely rewritten to handle such complex cases.  Such cases
    ** appear to be rare, and also confusing to humans.
    */
    rc = fsl_cx_exec(f,
      "UPDATE OR IGNORE " FSL__TABLE_FVM
      " SET fnp=vfile.pathname FROM vfile"
      " WHERE fnp IS NULL"
      " AND vfile.pathname = " FSL__TABLE_FVM ".fnn"
      " AND vfile.vid=%" FSL_ID_T_PFMT,
      pid
    );
    if(rc) goto end;
    rc = fsl_cx_exec(f,
      "UPDATE OR IGNORE " FSL__TABLE_FVM
      " SET fn=vfile.pathname FROM vfile"
      " WHERE fn IS NULL"
      " AND vfile.pathname = "
      "   coalesce(" FSL__TABLE_FVM ".fnp," FSL__TABLE_FVM ".fnn)"
      " AND vfile.vid=%" FSL_ID_T_PFMT,
      vid
    );
    if(rc) goto end;
    rc = fsl_cx_exec(f,
      "UPDATE OR IGNORE " FSL__TABLE_FVM
      " SET fnm=vfile.pathname FROM vfile"
      " WHERE fnm IS NULL"
      " AND vfile.pathname ="
      "  coalesce(" FSL__TABLE_FVM ".fnp," FSL__TABLE_FVM ".fnn)"
      " AND vfile.vid=%" FSL_ID_T_PFMT,
      mid
    );
    if(rc) goto end;
    rc = fsl_cx_exec(f,
      "UPDATE OR IGNORE " FSL__TABLE_FVM
      " SET fnp=vfile.pathname FROM vfile"
      " WHERE fnp IS NULL"
      " AND vfile.pathname"
      "   IN (" FSL__TABLE_FVM ".fnm," FSL__TABLE_FVM ".fn)"
      " AND vfile.vid=%" FSL_ID_T_PFMT,
      pid
    );
    if(rc) goto end;
    rc = fsl_cx_exec(f,
      "UPDATE OR IGNORE " FSL__TABLE_FVM
      " SET fn=vfile.pathname FROM vfile"
      " WHERE fn IS NULL"
      " AND vfile.pathname = " FSL__TABLE_FVM ".fnm"
      " AND vfile.vid=%" FSL_ID_T_PFMT,
      vid
    );
    if(rc) goto end;
    rc = fsl_cx_exec(f,
      "UPDATE OR IGNORE " FSL__TABLE_FVM
      " SET fnm=vfile.pathname FROM vfile"
      " WHERE fnm IS NULL"
      " AND vfile.pathname = " FSL__TABLE_FVM ".fn"
      " AND vfile.vid=%" FSL_ID_T_PFMT,
      mid
    );
    if(rc) goto end;
  }
  assert(0==rc);
  if(mOpt->baselineRid>0){
    fsl_db * const db = fsl_cx_db_repo(f);
    fsl_db_err_reset(db);
    vAncestor = fsl_db_exists(db,
      "WITH RECURSIVE ancestor(id) AS ("
      "  VALUES(%" FSL_ID_T_PFMT ")"
      "  UNION"
      "  SELECT pid FROM plink, ancestor"
      "   WHERE cid=ancestor.id"
      "   AND pid!=%" FSL_ID_T_PFMT
      "   AND cid!=%" FSL_ID_T_PFMT ")"
      "SELECT 1 FROM ancestor"
      "  WHERE id=%" FSL_ID_T_PFMT " LIMIT 1",
      vid, nid, pid, pid
    ) ? 'p' : 'n';
    assert(0==fsl_db_err_get(db, NULL, NULL));
  }

  /*
  ** Add files found in V
  */
  rc = fsl_cx_exec_multi(f,
    "UPDATE OR IGNORE " FSL__TABLE_FVM
    " SET fn=coalesce(fn%c,fnn) WHERE fn IS NULL;"
    "REPLACE INTO "
    FSL__TABLE_FVM "(fn,fnp,fnm,fnn,idv,ridv,islinkv,isexe,chnged)"
    " SELECT pathname, fnp, fnm, fnn, id, rid, islink, vf.isexe, vf.chnged"
    "   FROM vfile vf"
    "   LEFT JOIN " FSL__TABLE_FVM " ON fn=coalesce(origname,pathname)"
    "    AND rid>0 AND vf.chnged NOT IN (3,5)"
    "  WHERE vid=%" FSL_ID_T_PFMT ";",
    vAncestor, vid
  );
  if(rc) goto end;
  /*
  ** Add files found in P
  */
  rc = fsl_cx_exec_multi(f,
    "UPDATE OR IGNORE " FSL__TABLE_FVM " SET fnp=coalesce(fnn,"
    "   (SELECT coalesce(origname,pathname) FROM vfile WHERE id=idv))"
    " WHERE fnp IS NULL;"
    "INSERT OR IGNORE INTO " FSL__TABLE_FVM "(fnp)"
    " SELECT coalesce(origname,pathname) FROM vfile WHERE vid=%" FSL_ID_T_PFMT ";",
    pid
  );
  if(rc) goto end;

  /*
  ** Add files found in M
  */
  rc = fsl_cx_exec_multi(f,
    "UPDATE OR IGNORE " FSL__TABLE_FVM " SET fnm=fnp WHERE fnm IS NULL;"
    "INSERT OR IGNORE INTO " FSL__TABLE_FVM "(fnm)"
    " SELECT pathname FROM vfile WHERE vid=%" FSL_ID_T_PFMT ";",
    mid
  );
  if(rc) goto end;

  /*
  ** Compute the file version ids for P and M
  */
  if( pid==vid ){
    rc = fsl_cx_exec_multi(f,
      "UPDATE " FSL__TABLE_FVM " SET idp=idv, ridp=ridv"
      " WHERE ridv>0 AND chnged NOT IN (3,5)"
    );
  }else{
    rc = fsl_cx_exec_multi(f,
      "UPDATE " FSL__TABLE_FVM
      " SET idp=coalesce(vfile.id,0), ridp=coalesce(vfile.rid,0)"
      " FROM vfile"
      " WHERE vfile.vid=%" FSL_ID_T_PFMT
      " AND " FSL__TABLE_FVM ".fnp=vfile.pathname",
      pid
    );
  }
  if(rc) goto end;
  rc = fsl_cx_exec_multi(f,
    "UPDATE " FSL__TABLE_FVM " SET"
    " idm=coalesce(vfile.id,0),"
    " ridm=coalesce(vfile.rid,0),"
    " islinkm=coalesce(vfile.islink,0),"
    " isexe=coalesce(vfile.isexe," FSL__TABLE_FVM ".isexe)"
    " FROM vfile"
    " WHERE vid=%" FSL_ID_T_PFMT " AND fnm=pathname",
    mid
  );
  if(rc) goto end;

  /*
  ** Update the execute bit on files where it's changed from P->M but
  ** not P->V
  */
  if(!mOpt->dryRun){
    fsl_stmt q = fsl_stmt_empty;
    rc = fsl_cx_prepare(f, &q,
      "SELECT idv, fn, " FSL__TABLE_FVM ".isexe "
      "FROM " FSL__TABLE_FVM ", vfile p, vfile v"
      " WHERE p.id=idp AND v.id=idv AND " FSL__TABLE_FVM ".isexe!=p.isexe"
      " AND v.isexe=p.isexe"
    );
    if(rc) goto end;
    fsl_buffer * const fnAbs =
      fsl__cx_scratchpad(f)/*absolute filenames*/;
    rc = fsl_buffer_reserve(fnAbs, f->ckout.dirLen + 256);
    if(0==rc){
      rc = fsl_buffer_append(fnAbs, f->ckout.dir, f->ckout.dirLen);
    }
    while( 0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){
      fsl_id_t const idv = fsl_stmt_g_id(&q, 0);
      int const isExe = fsl_stmt_g_int32(&q, 2);
      fsl_size_t nName = 0;
      const char *zName = 0;
      rc = fsl_stmt_get_text(&q, 1, &zName, &nName);
      if(rc) break;
      fnAbs->mem[f->ckout.dirLen] = 0;
      fnAbs->used = f->ckout.dirLen;
      rc = fsl_buffer_append(fnAbs, zName, (fsl_int_t)nName);
      if(rc) break;
      fsl_file_exec_set( fsl_buffer_cstr(fnAbs), !!isExe )
        /* Ignoring error */;
      rc = fsl_cx_exec(f, "UPDATE vfile SET isexe=%d "
                       "WHERE id=%" FSL_ID_T_PFMT,
                       isExe, idv);
    }
    fsl__cx_scratchpad_yield(f, fnAbs);
    fsl_stmt_finalize(&q);
  }
  end:
  return rc;
}/*fsl__renames_tweak()*/

/**
   Adds an an entry in the vmerge table for the given id and rid.
   Returns 0 on success, uplifts any db error into f's error state.
*/
static int fsl__vmerge_insert(fsl_cx * const f, fsl_id_t id, fsl_id_t rid){
  return fsl_cx_exec(f,
    "INSERT OR IGNORE INTO vmerge(id,merge,mhash)"
    "VALUES(%" FSL_ID_T_PFMT ",%" FSL_ID_T_PFMT
    ",(SELECT uuid FROM blob WHERE rid=%" FSL_ID_T_PFMT "))",
    id, rid, rid
  );
}

#define fsl_merge_state_empty_m {        \
  NULL/*f*/,                             \
  NULL/*opt*/,                           \
  NULL/*filename*/,                      \
  NULL/*prevName*/,                      \
  FSL_MERGE_FCHANGE_NONE/*fileChangeType*/ \
}
/**
   Initialized-with-defaults fsl_merge_state instance,
   intended for use in non-const copy initialization.
*/
const fsl_merge_state fsl_merge_state_empty = fsl_merge_state_empty_m;

int fsl_ckout_merge(fsl_cx * const f, fsl_merge_opt const * const opt){
  /**
     Notation:

     V (vid)  The current checkout
     M (mid)  The version being merged in
     P (pid)  The "pivot" - the most recent common ancestor of V and M.
     N (nid)  The "name pivot" - for detecting renames

     What follows was initially based on:

     https://fossil-scm.org/home/file/src/merge.c?ci=e340af58a249dc09&ln=331-1065
  */
  int rc = 0;
  fsl_db * const db = fsl_needs_ckout(f);
  bool inTrans = false;
  fsl_id_t const vid = f->ckout.rid /* current checkout (V) */;
  fsl_id_t pid = 0 /* pivot RID (P): most recent common ancestor of V and M*/;
  fsl_id_t mid = opt->mergeRid /* merge-in version (M) */;
  fsl_id_t nid = 0 /* "name pivot" version (N) */;
  bool doIntegrate = FSL_MERGE_TYPE_INTEGRATE==opt->mergeType;
  fsl_stmt q = fsl_stmt_empty;
  fsl_buffer * const absPath = fsl__cx_scratchpad(f);
  fsl_merge_state mState = fsl_merge_state_empty;
  if(!db) rc = FSL_RC_NOT_A_CKOUT;
  else if(0==vid){
    rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
                        "Cannot merge into empty top-level checkin.");
  }else if(FSL_MERGE_TYPE_CHERRYPICK==opt->mergeType
           && opt->baselineRid>0){
    rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
                          "Cannot use the baselineRid option "
                          "with a cherry-pick merge.");
  }
  if(!rc) rc = fsl_cx_transaction_begin(f);
  if(rc) goto end;
  inTrans = true;
  if((pid = opt->baselineRid)>0){
    if(!fsl_rid_is_version(f, pid)){
      rc = fsl_cx_err_set(f, FSL_RC_TYPE,
                          "Baseline RID #%" FSL_ID_T_PFMT
                          " does not refer to a checkin version.");
      goto end;
    }
  }
  if(FSL_MERGE_TYPE_CHERRYPICK==opt->mergeType
     || FSL_MERGE_TYPE_BACKOUT==opt->mergeType){
    pid = fsl_db_g_id(db, 0, "SELECT pid FROM plink WHERE cid=%"
                           FSL_ID_T_PFMT " AND isprim",
                           mid);
    if(0==pid){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND, "Cannot find an ancestor "
                          "for to-merge RID #%" FSL_ID_T_PFMT ".",
                          mid);
      goto end;
    }
  }else{
    if(opt->baselineRid<=0){
      fsl_stmt q = fsl_stmt_empty;
      rc = fsl__pivot_set_primary(f, mid);
      if(0==rc) rc = fsl__pivot_set_secondary(f, vid);
      if(rc) goto end;
      rc = fsl_cx_prepare(f, &q, "SELECT merge FROM vmerge WHERE id=0");
      while( 0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){
        rc = fsl__pivot_set_secondary(f, fsl_stmt_g_id(&q, 0));
      }
      fsl_stmt_finalize(&q);
      if(0==rc) rc = fsl__pivot_find(f, false, &pid);
      if(rc) goto end;
      else if( pid<=0 ){
        rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "Cannot find a common ancestor between "
                            "RID #%" FSL_ID_T_PFMT
                            " and RID #%" FSL_ID_T_PFMT ".",
                            pid, vid);
        goto end;
      }
    }
    rc = fsl__pivot_set_primary(f, mid);
    if(0==rc) rc = fsl__pivot_set_secondary(f, vid);
    if(0==rc) rc = fsl__pivot_find(f, true, &nid);
    if(rc) goto end;
    else if( nid!=pid ){
      rc = fsl__pivot_set_primary(f, nid);
      if(0==rc) rc = fsl__pivot_set_secondary(f, pid);
      if(0==rc) rc = fsl__pivot_find(f, true, &nid);
      if(rc) goto end;
    }
    /* ^^^ the above block is a great example of much error checking
       intrudes on the library API compared to fossil(1). */
  }
  if( FSL_MERGE_TYPE_BACKOUT == opt->mergeType ){
    fsl_id_t const t = pid;
    pid = mid;
    mid = t;
  }
  if(0==nid) nid = pid;
  if(opt->debug){
    MARKER(("pid=%" FSL_ID_T_PFMT
            ", mid=%" FSL_ID_T_PFMT
            ", nid=%" FSL_ID_T_PFMT
            ", vid=%" FSL_ID_T_PFMT
            " integrate=%d\n",
            pid, mid, nid, vid, doIntegrate));
  }
  if(mid == pid){
    rc = fsl_cx_err_set(f, FSL_RC_RANGE, "Cowardly refusing to perform "
                        "no-op merge from/to RID #%" FSL_ID_T_PFMT ".",
                        mid);
    goto end;
  }else if(mid == vid){
    rc = fsl_cx_err_set(f, FSL_RC_RANGE, "Cowardly refusing to merge "
                        "version [%S] into itself.", f->ckout.uuid);
    goto end;
  }else if(!fsl_rid_is_version(f, pid)){
    rc = fsl_cx_err_set(f, FSL_RC_TYPE,
                        "RID #%" FSL_ID_T_PFMT " does not refer "
                        "to a checkin version.", pid);
    goto end;
  }else{
    uint32_t missing = 0;
    rc = fsl_vfile_load(f, mid, false, &missing);
    if(0==rc && 0==missing){
      rc = fsl_vfile_load(f, pid, false, &missing);
    }
    if(0==rc && missing){
      rc = fsl_cx_err_set(f, FSL_RC_PHANTOM,
                          "Cannot merge due to missing content in one "
                          "or more participating versions.");
    }
    if(rc) goto end;
  }
  if( doIntegrate && (fsl_content_is_private(f, mid)
                      || !fsl_rid_is_leaf(f, mid)) ){
    doIntegrate = false;
  }
  if(opt->scanForChanges){
    rc = fsl_vfile_changes_scan(f, vid, FSL_VFILE_CKSIG_ENOTFILE);
    if(rc) goto end;
  }
  rc = fsl__renames_tweak(f, mid, pid, vid, nid, opt);
  if(rc) goto end;
  if(opt->debug){
    MARKER(("pid=%" FSL_ID_T_PFMT
            ", mid=%" FSL_ID_T_PFMT
            ", nid=%" FSL_ID_T_PFMT
            ", vid=%" FSL_ID_T_PFMT
            " integrate=%d\n",
            pid, mid, nid, vid, doIntegrate));
    MARKER(("Contents of " FSL__TABLE_FVM ":\n"));
    if(1==opt->debug){
      fsl_db_each(db, fsl_stmt_each_f_dump, NULL,
                  "SELECT fn,fnp,fnm,chnged,ridv,ridp,ridm, "
                  " isexe,islinkv islinkm, fnn "
                  " FROM " FSL__TABLE_FVM
                  " WHERE chnged OR (ridv!=ridm AND ridm!=ridp)"
                  " ORDER BY fn, fnp, fnm ");
    }else{
      fsl_db_each(db, fsl_stmt_each_f_dump, NULL,
                  "SELECT * FROM " FSL__TABLE_FVM
                  " ORDER BY fn, fnp, fnm");
    }
    MARKER(("Contents of " FSL__TABLE_PIVOT ":\n"));
    fsl_db_each(db, fsl_stmt_each_f_dump, NULL,
                "SELECT * FROM " FSL__TABLE_PIVOT
                " ORDER BY src DESC, rid, pending, src");
    MARKER(("Contents of [vmerge]:\n"));
    fsl_db_each(db, fsl_stmt_each_f_dump, NULL,
                "SELECT * FROM vmerge order by merge");
  }
  mState.f = f;
  mState.opt = opt;
#define MCB(FCT,RMI,FN) \
  mState.fileChangeType = FCT; \
  mState.fileRmInfo = RMI; \
  mState.filename = FN; \
  rc = opt->callback(&mState); \
  mState.priorName = NULL
#define MCB2(FCT,FN) MCB(FCT,FSL_CKUP_RM_NOT,FN)
  /************************************************************************
  ** All of the information needed to do the merge is now contained in the
  ** FV table.  Starting here, we begin to actually carry out the merge.
  **
  ** First, find files in M and V but not in P and report conflicts.
  ** The file in M will be ignored.  It will be treated as if it
  ** does not exist.
  */
  rc = fsl_cx_prepare(f, &q, "SELECT idm FROM " FSL__TABLE_FVM
                      " WHERE idp=0 AND idv>0 AND idm>0");
  if(rc) goto end;
  while( 0==rc && FSL_RC_STEP_ROW==(rc = fsl_stmt_step(&q)) ){
    fsl_id_t const idm = fsl_stmt_g_id(&q, 0);
    rc = fsl_cx_exec(f, "UPDATE " FSL__TABLE_FVM
                     " SET idm=0 WHERE idm=%" FSL_ID_T_PFMT, idm);
    if(0==rc && opt->callback){
      fsl_buffer * const bName = fsl__cx_scratchpad(f);
      rc = fsl_db_get_buffer(db, bName, false,
                             "SELECT pathname FROM vfile WHERE id=%" FSL_ID_T_PFMT,
                             idm);
      if(0==rc){
        MCB2(FSL_MERGE_FCHANGE_CONFLICT_ANCESTOR,
             fsl_buffer_cstr(bName));
      }
      fsl__cx_scratchpad_yield(f, bName);
    }
  }
  fsl_stmt_finalize(&q);
  switch(rc){
    case 0:
    case FSL_RC_STEP_DONE: rc = 0; break;
    default: goto end;
  }

  /*
  ** Find files that have changed from P->M but not P->V.
  ** Copy the M content over into V.
  */
  rc = fsl_cx_prepare(f, &q,
    "SELECT idv, ridm, fn, islinkm FROM " FSL__TABLE_FVM
    " WHERE idp>0 AND idv>0 AND idm>0"
    "   AND ridm!=ridp AND ridv=ridp AND NOT chnged"
  );
  if(rc) goto end;
  while( 0==rc && (FSL_RC_STEP_ROW==fsl_stmt_step(&q)) ){
    fsl_id_t const idv = fsl_stmt_g_id(&q, 0);
    fsl_id_t const ridm = fsl_stmt_g_id(&q, 1);
    int const islinkm = fsl_stmt_g_int32(&q, 3);
    /* Copy content from idm over into idv.  Overwrite idv. */
    if(opt->debug){
      const char *zName = fsl_stmt_g_text(&q, 2, NULL);
      MARKER(("COPIED (M)=>(V) %s\n", zName));
    }
    if( !opt->dryRun ){
      //undo_save(zName);
      rc = fsl_cx_exec(f,
        "UPDATE vfile SET mtime=0, mrid=%" FSL_ID_T_PFMT
        ", chnged=%d, islink=%d,"
        " mhash=CASE WHEN rid<>%" FSL_ID_T_PFMT
        " THEN (SELECT uuid FROM blob WHERE blob.rid=%" FSL_ID_T_PFMT ") END"
        " WHERE id=%" FSL_ID_T_PFMT,
        ridm, doIntegrate ? 4 : 2, islinkm, ridm, ridm, idv
      );
      if(0==rc) rc = fsl__vfile_to_ckout(f, idv, NULL);
    }
    if(0==rc && opt->callback){
      const char *zName = 0;
      rc = fsl_stmt_get_text(&q, 2, &zName, NULL);
      if(0==rc){
        MCB2(FSL_MERGE_FCHANGE_COPIED,zName);
      }
    }
  }
  fsl_stmt_finalize(&q);
  switch(rc){
    case 0:
    case FSL_RC_STEP_DONE: rc = 0; break;
    default: goto end;
  }

  /*
  ** Do a three-way merge on files that have changes on both P->M and P->V.
  */
  rc = fsl_cx_prepare(f, &q,
    "SELECT ridm, idv, ridp, ridv,"
    " FSL_GLOB('binary-glob'," FSL__TABLE_FVM ".fn),"
    " fn, isexe, islinkv, islinkm FROM " FSL__TABLE_FVM
    " WHERE idp>0 AND idv>0 AND idm>0"
    "   AND ridm!=ridp AND (ridv!=ridp OR chnged)"
  );
  if(0==rc){
    rc = fsl_buffer_append( absPath, f->ckout.dir, (fsl_int_t)f->ckout.dirLen);
  }
  while( 0==rc && (FSL_RC_STEP_ROW==fsl_stmt_step(&q)) ){
    fsl_id_t const ridm = fsl_stmt_g_id(&q, 0);
    fsl_id_t const idv = fsl_stmt_g_id(&q, 1);
    fsl_id_t const ridp = fsl_stmt_g_id(&q, 2);
    fsl_id_t const  ridv = fsl_stmt_g_id(&q, 3);
    int32_t isBinary = fsl_stmt_g_int32(&q, 4);
    int32_t const isExe = fsl_stmt_g_int32(&q, 6);
    int32_t const islinkv = fsl_stmt_g_int32(&q, 7);
    int32_t const islinkm = fsl_stmt_g_int32(&q, 8);
    char const *zFullPath;
    const char *zName = NULL;
    fsl_size_t nName = 0;
    rc = fsl_stmt_get_text(&q, 5, &zName, &nName);
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, NULL, rc);
      break;
    }
    /* Do a 3-way merge of idp->idm into idp->idv.  The results go into idv. */
    if(opt->debug){
      MARKER(("MERGE %s  (pivot=%d v1=%d v2=%d)\n",
              zName, (int)ridp, (int)ridm, (int)ridv));
    }
    if( islinkv || islinkm ){
      //MARKER(("***** Cannot merge symlink %s\n", zName));
      if(opt->callback){
        MCB2(FSL_MERGE_FCHANGE_CONFLICT_SYMLINK,zName);
      }
    }else if(isBinary){
      if(opt->callback){
        MCB2(FSL_MERGE_FCHANGE_CONFLICT_BINARY,zName);
      }
    }else{
      fsl_buffer m = fsl_buffer_empty;
      fsl_buffer p = fsl_buffer_empty;
      fsl_buffer r = fsl_buffer_empty;
      //if( !dryRunFlag ) undo_save(zName);
      if(opt->debug){
        MARKER(("Merge: %s\n", zName));
      }
      absPath->used = f->ckout.dirLen;
      rc = fsl_buffer_append(absPath, zName, (fsl_int_t)nName);
      if(rc) break;
      zFullPath = fsl_buffer_cstr(absPath);
      rc = fsl_content_get(f, ridp, &p);
      if(0==rc) rc = fsl_content_get(f, ridm, &m);
      if(0==rc){
        //unsigned mergeFlags = dryRunFlag ? MERGE_DRYRUN : 0;
        //if(keepMergeFlag!=0) mergeFlags |= MERGE_KEEP_FILES;
        //rc = merge_3way(&p, zFullPath, &m, &r, mergeFlags);
        unsigned int nConflict = 0;
        fsl_buffer * const contentLocal = fsl__cx_content_buffer(f);
        rc = fsl_buffer_fill_from_filename(contentLocal, zFullPath);
        if(0==rc){
          rc = fsl_buffer_merge3( &p, contentLocal, &m, &r, &nConflict );
          switch(rc){
            case 0:
              if(opt->debug){
                MARKER(("%swriting merged file w/ %u conflict(s): %s\n",
                        opt->dryRun ? "Not " : "", nConflict, zName));
              }
              if(!opt->dryRun){
                rc = fsl_buffer_to_filename(&r, zFullPath);
                if(0==rc) fsl_file_exec_set(zFullPath, !!isExe);
              }
              break;
            case FSL_RC_DIFF_BINARY:
            case FSL_RC_TYPE:
              /* 2021-12-15: fsl_buffer_merge3() currently returns
                 FSL_RC_TYPE for binary, but "should" return
                 FSL_RC_DIFF_BINARY.  Changing that is TODO. */
              rc = 0; isBinary = 1;
              break;
            default: break;
          }
        }
        fsl__cx_content_buffer_yield(f);
        if(0==rc && !isBinary){
          rc = fsl_cx_exec(f, "UPDATE vfile "
                           "SET mtime=0 WHERE id=%" FSL_ID_T_PFMT, idv);
        }
        if(0==rc && opt->callback){
          fsl_merge_fchange_e const fce =
            isBinary
            ? FSL_MERGE_FCHANGE_CONFLICT_BINARY
            : (nConflict
               ? FSL_MERGE_FCHANGE_CONFLICT_MERGED
               : FSL_MERGE_FCHANGE_MERGED);
          MCB2(fce,zName);
        }
      }
      fsl_buffer_clear(&p);
      fsl_buffer_clear(&m);
      fsl_buffer_clear(&r);
    }
    if(0==rc) rc = fsl__vmerge_insert(f, idv, ridm);
  }
  fsl_stmt_finalize(&q);
  switch(rc){
    case 0:
    case FSL_RC_STEP_DONE: rc = 0; break;
    default: goto end;
  }

  /*
  ** Drop files that are in P and V but not in M
  */
  rc = fsl_cx_prepare(f, &q,
    "SELECT idv, fn, chnged FROM " FSL__TABLE_FVM
    " WHERE idp>0 AND idv>0 AND idm=0"
  );
  while( 0==rc && FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&q)) ){
    fsl_id_t const idv = fsl_stmt_g_id(&q, 0);
    int32_t const chnged = fsl_stmt_g_int32(&q, 2);
    const char *zName;
    fsl_size_t nName = 0;
    rc = fsl_stmt_get_text(&q, 1, &zName, &nName);
    if(rc) break;
    /* Delete the file idv */
    if(opt->debug){
      MARKER(("DELETE %s\n", zName));
    }
    if( chnged ){
      if(opt->debug){
        MARKER(("WARNING: local edits lost for %s", zName));
      }
    }
    //if( !dryRunFlag ) undo_save(zName);
    rc = fsl_cx_exec(f,
      "UPDATE vfile SET deleted=1 WHERE id=%" FSL_ID_T_PFMT, idv
    );
    if(!chnged && !opt->dryRun ){
      /* ^^^ this differs from fossil(1), which always deletes the
         local file regardless of whether it has local changes. */
      absPath->used = f->ckout.dirLen;
      rc = fsl_buffer_append(absPath, zName, (fsl_int_t)nName);
      if(0==rc) fsl_file_unlink(fsl_buffer_cstr(absPath));
    }
    if(opt->callback){
      fsl_ckup_rm_state_e const rme =
        chnged ? FSL_CKUP_RM_KEPT : FSL_CKUP_RM;
      MCB(FSL_MERGE_FCHANGE_RM,rme,zName);
    }
  }
  fsl_stmt_finalize(&q);
  switch(rc){
    case 0:
    case FSL_RC_STEP_DONE: rc = 0; break;
    default: goto end;
  }

  /* For certain sets of renames (e.g. A -> B and B -> A), a file that is
  ** being renamed must first be moved to a temporary location to avoid
  ** being overwritten by another rename operation. A row is added to the
  ** TMPRN table for each of these temporary renames.
  */
  rc = fsl_cx_exec_multi(f,
    "CREATE TEMP TABLE IF NOT EXISTS tmprn(fn UNIQUE, tmpfn);"
    "DELETE FROM tmprn;"
  );

  /*
  ** Rename files that have taken a rename on P->M but which keep the same
  ** name on P->V.  If a file is renamed on P->V only or on both P->V and
  ** P->M then we retain the V name of the file.
  */
  rc = fsl_cx_prepare(f, &q,
    "SELECT idv, fnp, fnm, isexe FROM " FSL__TABLE_FVM
    " WHERE idv>0 AND idp>0 AND idm>0 AND fnp=fn AND fnm!=fnp"
  );
  while( 0==rc && FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&q)) ){
    fsl_id_t const idv = fsl_stmt_g_id(&q, 0);
    int32_t const isExe = fsl_stmt_g_int32(&q, 3);
    const char *zOldName;
    const char *zNewName;
    rc = fsl_stmt_get_text(&q, 1, &zOldName, NULL);
    if(0==rc) rc = fsl_stmt_get_text(&q, 2, &zNewName, NULL);
    if(rc) break;
    if(opt->debug){
      MARKER(("RENAME %s -> %s\n", zOldName, zNewName));
    }
    //if( !dryRunFlag ) undo_save(zOldName);
    //if( !dryRunFlag ) undo_save(zNewName);
    rc = fsl_cx_exec_multi(f,
      "UPDATE vfile SET pathname=NULL, origname=pathname"
      " WHERE vid=%" FSL_ID_T_PFMT " AND pathname=%Q;"
      "UPDATE vfile SET pathname=%Q, origname=coalesce(origname,pathname)"
      " WHERE id=%" FSL_ID_T_PFMT ";",
      vid, zNewName, zNewName, idv
    );
    if(rc) break;
    if( !opt->dryRun ){
      fsl_buffer * const bFullOld = fsl__cx_scratchpad(f);
      fsl_buffer * const bFullNew = fsl__cx_scratchpad(f);
      fsl_buffer * const bTmp = fsl__cx_scratchpad(f);
      char const *zFullOldPath;
      char const *zFullNewPath;
      bool const realSymlinks = fsl_cx_allows_symlinks(f, false);
      rc = fsl_db_get_buffer(db, bFullOld, false,
                             "SELECT tmpfn FROM tmprn WHERE fn=%Q", zOldName);
      if(!rc && !bFullOld->used){
        rc = fsl_buffer_appendf(bFullOld, "%s%s", f->ckout.dir, zOldName);
      }
      if(0==rc) rc = fsl_buffer_appendf(bFullNew, "%s%s", f->ckout.dir, zNewName);
      if(rc) goto merge_rename_end;
      zFullOldPath = fsl_buffer_cstr(bFullOld);
      zFullNewPath = fsl_buffer_cstr(bFullNew);
      if( fsl_file_size(zFullNewPath)>=0 ){
        rc = fsl_file_tempname(bTmp, "", NULL);
        if(rc) goto merge_rename_end;
        rc = fsl_cx_exec(f, "INSERT INTO tmprn(fn,tmpfn) VALUES(%Q,%B)",
                         zNewName, bTmp);
        if(rc) goto merge_rename_end;
        rc = fsl_is_symlink(zFullNewPath)
          ? fsl__symlink_copy(zFullNewPath, fsl_buffer_cstr(bTmp), realSymlinks)
          : fsl_file_copy(zFullNewPath, fsl_buffer_cstr(bTmp));
        if(rc){
          rc = fsl_cx_err_set(f, rc, "Error copying file [%s].",
                              zFullNewPath);
        }
        if(rc) goto merge_rename_end;
      }
      rc = fsl_is_symlink(zFullOldPath)
        ? fsl__symlink_copy(zFullOldPath, zFullNewPath, realSymlinks)
        : fsl_file_copy(zFullOldPath, zFullNewPath);
      if(0==rc){
        fsl_file_exec_set(zFullNewPath, !!isExe);
        fsl_file_unlink(zFullOldPath);
        /* ^^^ Ignore errors: not critical here */
      }
      merge_rename_end:
      fsl__cx_scratchpad_yield(f, bFullOld);
      fsl__cx_scratchpad_yield(f, bFullNew);
      fsl__cx_scratchpad_yield(f, bTmp);
    }
    if(0==rc && opt->callback){
      mState.priorName = zOldName;
      MCB2(FSL_MERGE_FCHANGE_RENAMED,zNewName);
    }
  }
  fsl_stmt_finalize(&q);
  switch(rc){
    case 0:
    case FSL_RC_STEP_DONE: rc = 0; break;
    default: goto end;
  }
  /**
     TODO??? The above loop can leave temp files laying around. We
     should(?)  to (for each tmpfn in tmprn =>
     unlink(tmpfn)). fossil(1) does not do that, but that seems like a
     bug.
  */
  /* A file that has been deleted and replaced by a renamed file will have a
  ** NULL pathname. Change it to something that makes the output of "status"
  ** and similar commands make sense for such files and that will (most likely)
  ** not be an actual existing pathname.
  */
  rc = fsl_cx_exec(f,
    "UPDATE vfile SET pathname=origname || ' (overwritten by rename)'"
    " WHERE pathname IS NULL"
  );
  if(rc) goto end;
  /*
  ** Insert into V any files that are not in V or P but are in M.
  */
  rc = fsl_cx_prepare(f, &q,
    "SELECT idm, fnm FROM " FSL__TABLE_FVM
    " WHERE idp=0 AND idv=0 AND idm>0"
  );
  while( 0==rc && FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&q)) ){
    fsl_id_t const idm = fsl_stmt_g_id(&q, 0);
    const char *zName;
    fsl_buffer * const bFullName = fsl__cx_scratchpad(f);
    rc = fsl_cx_exec(f,
      "REPLACE INTO vfile(vid,chnged,deleted,rid,mrid,"
                         "isexe,islink,pathname,mhash)"
      "  SELECT %" FSL_ID_T_PFMT ",%d,0,rid,mrid,isexe,islink,pathname,"
            "CASE WHEN rid<>mrid"
            " THEN (SELECT uuid FROM blob WHERE blob.rid=vfile.mrid) END "
            "FROM vfile WHERE id=%" FSL_ID_T_PFMT,
      vid, doIntegrate
           ? FSL_VFILE_CHANGE_INTEGRATE_MOD
           : FSL_VFILE_CHANGE_MERGE_ADD,
      idm);
    if(0==rc) rc = fsl_stmt_get_text(&q, 1, &zName, NULL);
    if(0==rc) rc = fsl_buffer_appendf(bFullName, "%s%s", f->ckout.dir, zName);
    if(rc) goto merge_add_end;
    fsl_merge_fchange_e fchange;
    if( fsl_is_file_or_link(fsl_buffer_cstr(bFullName))
        && !fsl_db_exists(db, "SELECT 1 FROM fv WHERE fn=%Q", zName) ){
      if(opt->debug){
        MARKER(("ADDED %s (overwrites an unmanaged file)\n", zName));
      }
      fchange = FSL_MERGE_FCHANGE_CONFLICT_ADDED_UNMANAGED;
    }else{
      if(opt->debug){
        MARKER(("ADDED %s\n", zName));
      }
      fchange = FSL_MERGE_FCHANGE_ADDED;
    }
    if( !opt->dryRun ){
      //undo_save(zName);
      rc = fsl__vfile_to_ckout(f, idm, NULL);
    }
    merge_add_end:
    fsl__cx_scratchpad_yield(f, bFullName);
    if(0==rc && opt->callback){
      MCB2(fchange,zName);
    }
  }
  fsl_stmt_finalize(&q);
  switch(rc){
    case 0:
    case FSL_RC_STEP_DONE: rc = 0; break;
    default: goto end;
  }

  fsl_id_t vmergeWho = 0;
  switch(opt->mergeType){
    case FSL_MERGE_TYPE_CHERRYPICK:
      vmergeWho = mid;
      /* For a cherry-pick merge, make the default check-in comment the same
      ** as the check-in comment on the check-in that is being merged in. */
      if(0==rc){
        rc = fsl_cx_exec(f,
               "REPLACE INTO vvar(name,value)"
               " SELECT 'ci-comment', coalesce(ecomment,comment) FROM event"
               "  WHERE type='ci' AND objid=%" FSL_ID_T_PFMT,
               mid);
      }
      break;
    case FSL_MERGE_TYPE_BACKOUT:
      vmergeWho = pid;
      break;
    case FSL_MERGE_TYPE_INTEGRATE:
    case FSL_MERGE_TYPE_NORMAL:
      vmergeWho = mid;
      break;
  }
  if(0==rc){
    rc = fsl__vmerge_insert(f, (int)opt->mergeType, vmergeWho);
  }
#undef MCB
#undef MCB2
  end:
  if(opt->debug){
    MARKER(("fsl_ckout_merge() made it to the end with rc %s.\n",
            fsl_rc_cstr(rc)));
  }
  fsl__cx_scratchpad_yield(f, absPath);
  if(0==rc){
    fsl__renames_finalize(f);
  }
  fsl_stmt_finalize(&q);
  if(inTrans){
    if(0==rc){
      rc = fsl_vfile_unload_except(f, vid);
      // ^^^ not strictly needed unless we're NOT rolling back
    }
    int const rc2 = fsl_cx_transaction_end(f, 0!=rc);
    if(rc2 && 0==rc) rc = rc2;
  }
  return rc;
}

#undef FSL__TABLE_PIVOT
#undef FSL__TABLE_FVM

#undef MARKER
/* end of file ./src/merge.c */
/* start of file ./src/merge3.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279




31280
31281
31282
31283
31284
31285
31286
31287
31288


31289
31290
31291
31292
31293
31294
31295
31296
31297
31298


31299
31300
31301
31302
31303

31304
31305
31306
31307
31308


31309



31310
31311
31312
31313
31314
31315
31316
33050
33051
33052
33053
33054
33055
33056




33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068

33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079

33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094

33095
33096
33097
33098
33099
33100
33101
33102
33103
33104







-
-
-
-
+
+
+
+








-
+
+









-
+
+





+





+
+
-
+
+
+







    sz -= aC[1];
    aC += 3;
  }
  return true;
}

/**
   pSrc contains an edited file where aC[] describes the edit.  Part
   of pSrc has already been output.  This routine outputs additional
   lines of pSrc - lines that correspond to the next sz lines of the
   original unedited file.
   pSrc contains an edited file where aC[] describes the edit,
   starting at index i. Part of pSrc has already been output. This
   routine outputs additional lines of pSrc - lines that correspond to
   the next sz lines of the original unedited file.

   Note that sz counts the number of lines of text in the original
   file, but text is output from the edited file, so the number of
   lines transfer to pOut might be different from sz. Fewer lines
   appear in pOut if there are deletes. More lines appear if there
   are inserts.

   The aC[] array is updated and the new index into aC[] is returned
   via the final argument.
   via the newIndex. The running line number count is updated via
   pLn.

   Returns 0 on success, FSL_RC_OOM on allocation error.
*/
static
int output_one_side(fsl_buffer *pOut,
                    fsl_buffer *pSrc,
                    int *aC,
                    int i,
                    int sz,
                    int *newIndex){
                    int *newIndex,
                    int *pLn){
  int rc = 0;
  while( sz>0 ){
    if( aC[i]==0 && aC[i+1]==0 && aC[i+2]==0 ) break;
    if( aC[i]>=sz ){
      rc = fsl_buffer_copy_lines(pOut, pSrc, sz);
      *pLn += sz;
      if(rc) break;
      aC[i] -= sz;
      break;
    }
    rc = fsl_buffer_copy_lines(pOut, pSrc, aC[i]);
    *pLn += aC[i];
    if(!rc){
    if(!rc) rc = fsl_buffer_copy_lines(pOut, pSrc, aC[i+2]);
      rc = fsl_buffer_copy_lines(pOut, pSrc, aC[i+2]);
      *pLn += aC[i+2];
    }
    if(rc) break;
    sz -= aC[i] + aC[i+1];
    i += 3;
  }
  if(!rc) *newIndex = i;
  return rc;
}
31338
31339
31340
31341
31342
31343
31344
31345
31346

31347
31348
31349
31350
31351
31352
31353
33126
33127
33128
33129
33130
33131
33132


33133
33134
33135
33136
33137
33138
33139
33140







-
-
+







}

/**
   Ensure that the text in p, if not empty, ends with a new line. If
   useCrLf is true adds "\r\n" otherwise "\n".  Returns 0 on success
   or p is empty, and FSL_RC_OOM on OOM.
*/
static
int ensure_line_end(fsl_buffer *p, bool useCrLf){
static int ensure_line_end(fsl_buffer *p, bool useCrLf){
  int rc = 0;
  if( !p->used ) return 0;
  if( p->mem[p->used-1]!='\n' ){
    rc = fsl_buffer_append(p, useCrLf ? "\r\n" : "\n", useCrLf ? 2 : 1);
  }
  return rc;
}
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396




31397
31398
31399









31400
31401
31402
31403
31404
31405
31406
31407
31408




31409
















31410

31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425

31426

31427
31428
31429
31430
31431
31432
31433
33173
33174
33175
33176
33177
33178
33179




33180
33181
33182
33183
33184


33185
33186
33187
33188
33189
33190
33191
33192
33193

33194
33195
33196
33197




33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218

33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235

33236
33237
33238
33239
33240
33241
33242
33243







-
-
-
-
+
+
+
+

-
-
+
+
+
+
+
+
+
+
+
-




-
-
-
-
+
+
+
+

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+















+
-
+








   NEVER, EVER change these. They MUST match the ones used
   by fossil.
*/
static
const char *const mergeMarker[] = {
 /*123456789 123456789 123456789 123456789 123456789 123456789 123456789*/
  "<<<<<<< BEGIN MERGE CONFLICT: local copy shown first <<<<<<<<<<<<<<<",
  "||||||| COMMON ANCESTOR content follows ||||||||||||||||||||||||||||",
  "======= MERGED IN content follows ==================================",
  ">>>>>>> END MERGE CONFLICT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
  "<<<<<<< BEGIN MERGE CONFLICT: local copy shown first <<<<<<<<<<<<",
  "||||||| COMMON ANCESTOR content follows |||||||||||||||||||||||||",
  "======= MERGED IN content follows ===============================",
  ">>>>>>> END MERGE CONFLICT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
};

static fsl_int_t assert_mema_lengths(){
enum {
/* strlen() of each mergeMarker entry. */
MEMA_LENGTH = 65
};
/**
   Asserts, the first time it is called, that all mergeMarker entries
   are of the same length and returns that length.
*/
static inline fsl_int_t assert_mema_lengths(){
  static const fsl_int_t mmLen = 68;
  static bool once = true;
  if(once){
    once = false;
    assert(sizeof(mergeMarker)/sizeof(mergeMarker[0]) == 4);
    assert((fsl_int_t)fsl_strlen(mergeMarker[0])==mmLen);
    assert((fsl_int_t)fsl_strlen(mergeMarker[1])==mmLen);
    assert((fsl_int_t)fsl_strlen(mergeMarker[2])==mmLen);
    assert((fsl_int_t)fsl_strlen(mergeMarker[3])==mmLen);
    assert((fsl_int_t)fsl_strlen(mergeMarker[0])==MEMA_LENGTH);
    assert((fsl_int_t)fsl_strlen(mergeMarker[1])==MEMA_LENGTH);
    assert((fsl_int_t)fsl_strlen(mergeMarker[2])==MEMA_LENGTH);
    assert((fsl_int_t)fsl_strlen(mergeMarker[3])==MEMA_LENGTH);
  }
  return MEMA_LENGTH;
}

/*
** Write out mergeMarker[iMark] to pOut, along with the given line
** number (if>0). Returns 0 on success, FSL_RC_OOM on allocation
** error.
*/
static int append_merge_mark(fsl_buffer * const pOut, int iMark,
                             int ln, bool useCrLf){
  int rc = ensure_line_end(pOut, useCrLf);
  if(0==rc){
    rc = fsl_buffer_append(pOut, mergeMarker[iMark], MEMA_LENGTH);
    if( 0==rc && ln>0 ) rc = fsl_buffer_appendf(pOut, " (line %d)", ln);
    if(0==rc) rc = ensure_line_end(pOut, useCrLf);
  }
  return mmLen;
  return rc;
}

int fsl_buffer_merge3(fsl_buffer * const pPivot,
                      fsl_buffer * const pV1,
                      fsl_buffer * const pV2,
                      fsl_buffer * const pOut,
                      unsigned int * const conflictCount){
  int *aC1 = 0;          /* Changes from pPivot to pV1 */
  int *aC2 = 0;          /* Changes from pPivot to pV2 */
  int i1, i2;            /* Index into aC1[] and aC2[] */
  int nCpy, nDel, nIns;  /* Number of lines to copy, delete, or insert */
  int limit1, limit2;    /* Sizes of aC1[] and aC2[] */
  int rc = 0;
  unsigned int nConflict = 0;     /* Number of merge conflicts seen so far */
  bool useCrLf = false;
  int ln1, ln2, lnPivot; /* Line numbers for all files */
  const fsl_int_t mmLen = assert_mema_lengths();
  assert_mema_lengths();

#define RC if(rc) { \
    MARKER(("rc=%s\n", fsl_rc_cstr(rc))); goto end; } (void)0
  fsl_buffer_reuse(pOut);         /* Merge results stored in pOut */
  
  /* If both pV1 and pV2 start with a UTF-8 byte-order-mark (BOM),
  ** keep it in the output. This should be secure enough not to cause
31451
31452
31453
31454
31455
31456
31457
31458
31459


31460
31461
31462
31463
31464
31465
31466
33261
33262
33263
33264
33265
33266
33267


33268
33269
33270
33271
33272
33273
33274
33275
33276







-
-
+
+







  ** and pPivot => pV2 (into aC2).  Each of the aC1 and aC2 arrays is
  ** an array of integer triples.  Within each triple, the first integer
  ** is the number of lines of text to copy directly from the pivot,
  ** the second integer is the number of lines of text to omit from the
  ** pivot, and the third integer is the number of lines of text that are
  ** inserted.  The edit array ends with a triple of 0,0,0.
  */
  rc = fsl__diff_text_raw(pPivot, pV1, 0, &aC1);
  if(!rc) rc = fsl__diff_text_raw(pPivot, pV2, 0, &aC2);
  rc = fsl_diff_v2_raw(pPivot, pV1, NULL, &aC1);
  if(!rc) rc = fsl_diff_v2_raw(pPivot, pV2, NULL, &aC2);
  RC;
  assert(aC1 && aC2);

  /* Rewind inputs:  Needed to reconstruct output */
  fsl_buffer_rewind(pV1);
  fsl_buffer_rewind(pV2);
  fsl_buffer_rewind(pPivot);
31482
31483
31484
31485
31486
31487
31488

31489
31490
31491
31492
31493
31494
31495
31496
31497
31498

31499

31500

31501
31502
31503
31504
31505
31506
31507
31508
31509
31510

31511

31512

31513
31514
31515
31516
31517
31518
31519
31520
31521
31522

31523

31524

31525
31526
31527
31528
31529
31530
31531
31532
31533
31534

31535

31536

31537
31538
31539

31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551

31552
31553
31554
31555

31556
31557
31558
31559


31560
31561

31562
31563
31564
31565
31566




31567
31568
31569
31570
31571

31572
31573
31574
31575
31576
31577
31578
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361

33362

33363
33364
33365
33366
33367
33368
33369
33370
33371
33372

33373




33374

33375


33376
33377
33378

33379
33380




33381
33382
33383
33384
33385




33386
33387
33388
33389
33390
33391
33392
33393







+










+

+

+










+

+

+










+

+

+










+

+

+


-
+
-










-
+
-
-
-
-
+
-

-
-
+
+

-
+

-
-
-
-
+
+
+
+

-
-
-
-
+








  /* Loop over the two edit vectors and use them to compute merged text
  ** which is written into pOut.  i1 and i2 are multiples of 3 which are
  ** indices into aC1[] and aC2[] to the edit triple currently being
  ** processed
  */
  i1 = i2 = 0;
  ln1 = ln2 = lnPivot = 1;
  while( i1<limit1 && i2<limit2 ){
    FDEBUG( printf("%d: %2d %2d %2d   %d: %2d %2d %2d\n",
           i1/3, aC1[i1], aC1[i1+1], aC1[i1+2],
           i2/3, aC2[i2], aC2[i2+1], aC2[i2+2]); )

    if( aC1[i1]>0 && aC2[i2]>0 ){
      /* Output text that is unchanged in both V1 and V2 */
      nCpy = mymin(aC1[i1], aC2[i2]);
      FDEBUG( printf("COPY %d\n", nCpy); )
      rc = fsl_buffer_copy_lines(pOut, pPivot, (fsl_size_t)nCpy);
      lnPivot += nCpy;
      if(!rc) rc = fsl_buffer_copy_lines(0, pV1, (fsl_size_t)nCpy);
      ln1 += nCpy;
      if(!rc) rc = fsl_buffer_copy_lines(0, pV2, (fsl_size_t)nCpy);
      ln2 += nCpy;
      RC;
      aC1[i1] -= nCpy;
      aC2[i2] -= nCpy;
    }else
    if( aC1[i1] >= aC2[i2+1] && aC1[i1]>0 && aC2[i2+1]+aC2[i2+2]>0 ){
      /* Output edits to V2 that occurs within unchanged regions of V1 */
      nDel = aC2[i2+1];
      nIns = aC2[i2+2];
      FDEBUG( printf("EDIT -%d+%d left\n", nDel, nIns); )
      rc = fsl_buffer_copy_lines(0, pPivot, (fsl_size_t)nDel);
      lnPivot += nDel;
      if(!rc) rc = fsl_buffer_copy_lines(0, pV1, (fsl_size_t)nDel);
      ln1 += nDel;
      if(!rc) rc = fsl_buffer_copy_lines(pOut, pV2, (fsl_size_t)nIns);
      ln2 += nIns;
      RC;
      aC1[i1] -= nDel;
      i2 += 3;
    }else
    if( aC2[i2] >= aC1[i1+1] && aC2[i2]>0 && aC1[i1+1]+aC1[i1+2]>0 ){
      /* Output edits to V1 that occur within unchanged regions of V2 */
      nDel = aC1[i1+1];
      nIns = aC1[i1+2];
      FDEBUG( printf("EDIT -%d+%d right\n", nDel, nIns); )
      rc = fsl_buffer_copy_lines(0, pPivot, (fsl_size_t)nDel);
      lnPivot += nDel;
      if(!rc) fsl_buffer_copy_lines(0, pV2, (fsl_size_t)nDel);
      ln2 += nDel;
      if(!rc) fsl_buffer_copy_lines(pOut, pV1, (fsl_size_t)nIns);
      ln1 += nIns;
      aC2[i2] -= nDel;
      i1 += 3;
    }else
    if( sameEdit(&aC1[i1], &aC2[i2], pV1, pV2) ){
      /* Output edits that are identical in both V1 and V2. */
      assert( aC1[i1]==0 );
      nDel = aC1[i1+1];
      nIns = aC1[i1+2];
      FDEBUG( printf("EDIT -%d+%d both\n", nDel, nIns); )
      rc = fsl_buffer_copy_lines(0, pPivot, (fsl_size_t)nDel);
      lnPivot += nDel;
      if(!rc) fsl_buffer_copy_lines(pOut, pV1, (fsl_size_t)nIns);
      ln1 += nIns;
      if(!rc) fsl_buffer_copy_lines(0, pV2, (fsl_size_t)nIns);
      ln2 += nIns;
      i1 += 3;
      i2 += 3;
    }else
    }else{
    {
      /* We have found a region where different edits to V1 and V2 overlap.
      ** This is a merge conflict.  Find the size of the conflict, then
      ** output both possible edits separated by distinctive marks.
      */
      int sz = 1;    /* Size of the conflict in lines */
      ++nConflict;
      while( !ends_at_CPY(&aC1[i1], sz) || !ends_at_CPY(&aC2[i2], sz) ){
        ++sz;
      }
      FDEBUG( printf("CONFLICT %d\n", sz); )
      rc = ensure_line_end(pOut, useCrLf);
      rc = append_merge_mark(pOut, 0, ln1, useCrLf);
      if(!rc) rc = fsl_buffer_append(pOut, mergeMarker[0], mmLen);
      if(!rc) rc = ensure_line_end(pOut, useCrLf);
      RC;
      rc = output_one_side(pOut, pV1, aC1, i1, sz, &i1);
      if(!rc) rc = output_one_side(pOut, pV1, aC1, i1, sz, &i1, &ln1);
      if(!rc) rc = ensure_line_end(pOut, useCrLf);
      RC;
      rc = fsl_buffer_append(pOut, mergeMarker[1], mmLen);
      if(!rc) rc = ensure_line_end(pOut, useCrLf);

      rc = append_merge_mark(pOut, 1, lnPivot, useCrLf);
      if(!rc) rc = fsl_buffer_copy_lines(pOut, pPivot, sz);
      if(!rc) rc = ensure_line_end(pOut, useCrLf);
      lnPivot += sz;
      RC;
      rc = fsl_buffer_append(pOut, mergeMarker[2], mmLen);
      if(!rc) rc = ensure_line_end(pOut, useCrLf);
      if(!rc) rc = output_one_side(pOut, pV2, aC2, i2, sz, &i2);
      if(!rc) rc = ensure_line_end(pOut, useCrLf);

      rc = append_merge_mark(pOut, 2, ln2, useCrLf);
      if(!rc) rc = output_one_side(pOut, pV2, aC2, i2, sz, &i2, &ln2);
      if(!rc) rc = append_merge_mark(pOut, 3, -1, useCrLf);
      RC;
      rc = fsl_buffer_append(pOut, mergeMarker[3], mmLen);
      if(!rc) rc = ensure_line_end(pOut, useCrLf);
      RC;
   }
    }

    /* If we are finished with an edit triple, advance to the next
    ** triple.
    */
    if( i1<limit1 && aC1[i1]==0 && aC1[i1+1]==0 && aC1[i1+2]==0 ) i1+=3;
    if( i2<limit2 && aC2[i2]==0 && aC2[i2+1]==0 && aC2[i2+2]==0 ) i2+=3;
  }
31609
31610
31611
31612
31613
31614
31615
31616
31617



31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630


31631
31632
31633
31634
31635
31636
31637
33424
33425
33426
33427
33428
33429
33430


33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444


33445
33446
33447
33448
33449
33450
33451
33452
33453







-
-
+
+
+











-
-
+
+







  fsl_size_t const len = (fsl_size_t)assert_mema_lengths();
  if(p->used <= len) return false;
  fsl_size_t j;
  const char * const z = (const char *)p->mem;
  fsl_size_t const n = p->used - len + 1;
  for(i=0; i<n; ){
    for(j=0; j<4; ++j){
      if( (memcmp(&z[i], mergeMarker[j], len)==0)
          && (i+1==n || z[i+len]=='\n' || z[i+len]=='\r') ) return true;
      if( 0==memcmp(&z[i], mergeMarker[j], len) ){
        return true;
      }
    }
    while( i<n && z[i]!='\n' ){ ++i; }
    while( i<n && (z[i]=='\n' || z[i]=='\r') ){ ++i; }
  }
  return false;
}

#undef mymin
#undef FDEBUG
#undef ISFDEBUG
#undef MARKER
/* end of file merge3.c */
/* start of file popen.c */
/* end of file ./src/merge3.c */
/* start of file ./src/popen.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
** Copyright (c) 2010 D. Richard Hipp
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the Simplified BSD License (also
31651
31652
31653
31654
31655
31656
31657
31658

31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
33467
33468
33469
33470
33471
33472
33473

33474
33475
33476






33477
33478
33479
33480
33481
33482
33483







-
+


-
-
-
-
-
-







*/
/*************************************************************************
  This copy has been modified slightly for use in the libfossil project.
*/
#undef __STRICT_ANSI__
#include <errno.h>

#ifdef _WIN32
#if FSL_PLATFORM_IS_WINDOWS
#include <windows.h>
#include <fcntl.h>
/*
   Print a fatal error and quit.
*/
static void win32_fatal_error(const char *zMsg){
  /*fossil_fatal("%s", zMsg); TODO: what to do here? */
}
#else
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#endif

/*
31694
31695
31696
31697
31698
31699
31700
31701

31702
31703
31704
31705
31706
31707
31708
33504
33505
33506
33507
33508
33509
33510

33511
33512
33513
33514
33515
33516
33517
33518







-
+







# define PTR_TO_INT(X)  ((int)(intptr_t)(X))
#else                          /* Generates a warning - but it always works */
# define INT_TO_PTR(X)  ((void*)(X))
# define PTR_TO_INT(X)  ((int)(X))
#endif


#ifdef _WIN32
#if FSL_PLATFORM_IS_WINDOWS
/*
   On windows, create a child process and specify the stdin, stdout,
   and stderr channels for that process to use.
  
   Return the number of errors.
*/
static int win32_create_child_process(
31738
31739
31740
31741
31742
31743
31744
31745


31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766

31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778


31779
31780
31781
31782
31783


31784
31785
31786
31787
31788
31789
31790
33548
33549
33550
33551
33552
33553
33554

33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576

33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588

33589
33590
33591
33592
33593
33594

33595
33596
33597
33598
33599
33600
33601
33602
33603







-
+
+




















-
+











-
+
+




-
+
+







     &pi    /* Process Info */
  );
  if( rc ){
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
    *pChildPid = pi.dwProcessId;
  }else{
    win32_fatal_error("cannot create child process");
    //fsl__fatal(FSL_RC_ERROR, "cannot create child process");
    rc = FSL_RC_ERROR;
  }
  return rc!=0;
}
#endif

/**
    Create a child process running shell command "zCmd".  *ppOut gets
    assigned to a FILE that becomes the standard input of the child process.  
    (The caller writes to *ppOut in order to send text to the child.)
    *pfdIn gets assigned to the stdout from the child process.  (The caller
    reads from *pfdIn in order to receive input from the child.)
    Note that *pfdIn is an unbuffered file descriptor, not a FILE.
    The process ID of the child is written into *pChildPid.
   
    On success the values returned via *pfdIn, *ppOut, and *pChildPid
    must be passed to fsl_pclose2() to properly clean up.
   
    Return 0 on success, non-0 on error.
 */
int fsl_popen2(const char *zCmd, int *pfdIn, FILE **ppOut, int *pChildPid){
#ifdef _WIN32
#if FSL_PLATFORM_IS_WINDOWS
  /* FIXME: port these win32_fatal_error() bits to error codes. */
  HANDLE hStdinRd, hStdinWr, hStdoutRd, hStdoutWr, hStderr;
  SECURITY_ATTRIBUTES saAttr;    
  DWORD childPid = 0;
  int fd;

  saAttr.nLength = sizeof(saAttr);
  saAttr.bInheritHandle = TRUE;
  saAttr.lpSecurityDescriptor = NULL; 
  hStderr = GetStdHandle(STD_ERROR_HANDLE);
  if( !CreatePipe(&hStdoutRd, &hStdoutWr, &saAttr, 4096) ){
    win32_fatal_error("cannot create pipe for stdout");
    //win32_fatal_error("cannot create pipe for stdout");
    return FSL_RC_IO;
  }
  SetHandleInformation( hStdoutRd, HANDLE_FLAG_INHERIT, FALSE);

  if( !CreatePipe(&hStdinRd, &hStdinWr, &saAttr, 4096) ){
    win32_fatal_error("cannot create pipe for stdin");
    //win32_fatal_error("cannot create pipe for stdin");
    return FSL_RC_IO;
  }
  SetHandleInformation( hStdinWr, HANDLE_FLAG_INHERIT, FALSE);
  
  win32_create_child_process(fsl_utf8_to_unicode(zCmd),
                             hStdinRd, hStdoutWr, hStderr,&childPid);
  *pChildPid = childPid;
  *pfdIn = _open_osfhandle(PTR_TO_INT(hStdoutRd), 0);
31830
31831
31832
31833
31834
31835
31836
31837


31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851



31852






31853
31854
31855

31856
31857
31858
31859

31860
31861
31862
31863


31864
31865
31866
31867
31868
31869
31870


31871
31872
31873
31874
31875
31876
31877
33643
33644
33645
33646
33647
33648
33649

33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668

33669
33670
33671
33672
33673
33674
33675
33676

33677
33678
33679
33680
33681
33682
33683
33684


33685
33686
33687
33688
33689
33690
33691


33692
33693
33694
33695
33696
33697
33698
33699
33700







-
+
+














+
+
+
-
+
+
+
+
+
+


-
+




+


-
-
+
+





-
-
+
+







    close(pout[0]);
    close(pout[1]);
    close(1);
    fd = dup(pin[1]);
    if( fd!=1 ) nErr++;
    close(pin[0]);
    close(pin[1]);
    execl("/bin/sh", "/bin/sh", "-c", zCmd, (char*)0);
    execl("/bin/sh", "/bin/sh", "-c", zCmd, (char*)0)
      /* doesn't return on success */;
    return fsl_errno_to_rc(errno, FSL_RC_ERROR);
  }else{
    /* This is the parent process */
    close(pin[1]);
    *pfdIn = pin[0];
    close(pout[0]);
    *ppOut = fdopen(pout[1], "w");
    return 0;
  }
#endif
}

/**
    Close the connection to a child process previously created using
    fsl_popen2(). All 3 arguments are assumed to values returned via
    fsl_popen2()'s output parameters: the input file descriptor,
    output FILE handle, and child process PID.
    fsl_popen2().  Kill off the child process, then close the pipes.

    If childPid is not zero, that process is killed with SIGINT before
    the I/O channels are closed.

    On Windows platforms, killing of the child process is not
    implemented. (Patches are welcomed.)
 */
void fsl_pclose2(int fdIn, FILE *pOut, int childPid){
#ifdef _WIN32
#if FSL_PLATFORM_IS_WINDOWS
  /* Not implemented, yet */
  close(fdIn);
  fclose(pOut);
#else
  if(childPid>0) kill(childPid, SIGINT);
  close(fdIn);
  fclose(pOut);
  kill(childPid, SIGINT);
  while( waitpid(0, 0, WNOHANG)>0 ) {}
  while( waitpid(childPid>0 ? (pid_t)childPid : (pid_t)0,
                 NULL, WNOHANG)>0 ) {}
#endif
}

#undef PTR_TO_INT
#undef INT_TO_PTR
/* end of file popen.c */
/* start of file pq.c */
/* end of file ./src/popen.c */
/* start of file ./src/pq.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
31939
31940
31941
31942
31943
31944
31945
31946
31947


31948
31949
31950
31951
31952
31953
31954
33762
33763
33764
33765
33766
33767
33768


33769
33770
33771
33772
33773
33774
33775
33776
33777







-
-
+
+







  if( pp ) *pp = p->list[0].data;
  for(i=0; i<((fsl_id_t)p->used-1); ++i){
    p->list[i] = p->list[i+1];
  }
  --p->used;
  return e;
}
/* end of file pq.c */
/* start of file repo.c */
/* end of file ./src/pq.c */
/* start of file ./src/repo.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014


32015
32016
32017
32018
32019
32020

32021

32022
32023

32024
32025

32026
32027
32028


32029
32030
32031
32032


32033
32034
32035
32036
32037
32038
32039
32040
32041












32042
32043
32044
32045
32046
32047
32048
33825
33826
33827
33828
33829
33830
33831






33832
33833



33834
33835

33836
33837
33838
33839

33840
33841

33842
33843


33844
33845




33846
33847
33848
33849







33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868







-
-
-
-
-
-
+
+
-
-
-


-
+

+

-
+

-
+

-
-
+
+
-
-
-
-
+
+


-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+







                    " WHERE tagid=%d AND tagxref.rid=ancestor.rid"
                    "   AND value=%Q AND tagtype>0)"
    "  LIMIT 1",
    rid, rid, FSL_TAGID_BRANCH, zBranch
  );
}

/**
   TODO: figure out if this needs to be in the public API and, if it does,
   change its signature to:

   int fsl_branch_of_rid(fsl_cx *f, fsl_int_t rid, char **zOut )

int fsl_branch_of_rid(fsl_cx * const f, fsl_int_t rid,
                      bool doFallback, char ** zOut ){
   So that we can distinguish "not found" from OOM errors.
*/
static char * fsl_branch_of_rid(fsl_cx * const f, fsl_int_t rid){
  char *zBr = 0;
  fsl_db * const db = fsl_cx_db_repo(f);
  fsl_stmt * st = 0;
  fsl_stmt st = fsl_stmt_empty;
  int rc;
  if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
  assert(db);
  rc = fsl_db_prepare_cached(db, &st,
  rc = fsl_cx_prepare(f, &st,
      "SELECT value FROM tagxref "
      "WHERE rid=? AND tagid=%d "
      "WHERE rid=%" FSL_ID_T_PFMT " AND tagid=%d "
      "AND tagtype>0 "
      "/*%s()*/", FSL_TAGID_BRANCH,__func__);
  if(rc) return 0;
      "/*%s()*/", rid, FSL_TAGID_BRANCH,__func__);
  if(rc) return rc;
  rc = fsl_stmt_bind_id(st, 1, rid);
  if(rc) goto end;
  if( fsl_stmt_step(st)==FSL_RC_STEP_ROW ){
    zBr = fsl_strdup(fsl_stmt_g_text(st,0,0));
  if( fsl_stmt_step(&st)==FSL_RC_STEP_ROW ){
    zBr = fsl_strdup(fsl_stmt_g_text(&st,0,0));
    if(!zBr) rc = FSL_RC_OOM;
  }
  end:
  fsl_stmt_cached_yield(st);
  if( !rc && zBr==0 ){
    zBr = fsl_config_get_text(f, FSL_CONFDB_REPO, "main-branch", 0);
    if(!zBr) zBr = fsl_strdup("trunk");
  }
  return zBr;
  fsl_stmt_finalize(&st);
  if( !rc ){
    if( zBr==0 && doFallback ){
      zBr = fsl_config_get_text(f, FSL_CONFDB_REPO, "main-branch", 0);
      if(!zBr){
        zBr = fsl_strdup("trunk");
        if(!zBr) rc = FSL_RC_OOM;
      }
    }
    if(0==rc) *zOut = zBr;
  }
  return rc;
}

/**
   morewt ==> most recent event with tag

   Comments from original fossil implementation:

32115
32116
32117
32118
32119
32120
32121

32122
32123


32124
32125
32126
32127
32128
32129
32130
32131
32132
33935
33936
33937
33938
33939
33940
33941
33942


33943
33944


33945
33946
33947
33948
33949
33950
33951







+
-
-
+
+
-
-







*/
static fsl_id_t fsl_start_of_branch(fsl_cx * f, fsl_id_t rid,
                                    enum fsl_stobr_type eType){
  fsl_db * db;
  fsl_stmt q = fsl_stmt_empty;
  int rc;
  fsl_id_t ans = rid;
  char * zBr = 0;
  char *zBr = fsl_branch_of_rid(f, rid);
  if(!zBr){
  rc = fsl_branch_of_rid(f, rid, true, &zBr);
  if(rc) return rc;
    goto oom;
  }
  db = fsl_cx_db_repo(f);
  assert(db);
  rc = fsl_db_prepare(db, &q,
    "SELECT pid, EXISTS(SELECT 1 FROM tagxref"
                       " WHERE tagid=%d AND tagtype>0"
                       "   AND value=%Q AND rid=plink.pid)"
    "  FROM plink"
32150
32151
32152
32153
32154
32155
32156
32157
32158



32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
33969
33970
33971
33972
33973
33974
33975


33976
33977
33978
33979
33980


33981
33982
33983
33984
33985
33986
33987







-
-
+
+
+


-
-







      break;
    }
    ans = fsl_stmt_g_id(&q, 0);
  }while( fsl_stmt_g_int32(&q, 1)==1 && ans>0 );
  fsl_stmt_finalize(&q);
  end:
  if( ans>0 && eType==FSL_STOBR_YOAN ){
    zBr = fsl_branch_of_rid(f, ans);
    if(zBr){
    rc = fsl_branch_of_rid(f, ans, true, &zBr);
    if(rc) goto oom;
    else{
      ans = fsl_youngest_ancestor_in_branch(f, rid, zBr);
      fsl_free(zBr);
    }else{
      goto oom;
    }
  }
  return ans;
  oom:
  if(!f->error.code){
    fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  }/* Else assume the OOM is really a misleading
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467



32468
32469

32470
32471

32472
32473
32474
32475
32476
32477
32478
32479











32480
32481

32482
32483
32484
32485
32486

32487
32488
32489
32490
32491
32492
32493







32494
32495
32496
32497



32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517




















32518
32519
32520
32521
32522
32523
32524
32525
32526
32527









32528
32529
32530
32531



32532
32533

32534
32535
32536
32537
32538
32539
32540
32541
34275
34276
34277
34278
34279
34280
34281




34282
34283
34284


34285


34286








34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297


34298




34299
34300







34301
34302
34303
34304
34305
34306
34307




34308
34309
34310




















34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330










34331
34332
34333
34334
34335
34336
34337
34338
34339




34340
34341
34342


34343

34344
34345
34346
34347
34348
34349
34350







-
-
-
-
+
+
+
-
-
+
-
-
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
-
-
+
-
-
-
-

+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
-
-
-
-
+
+
+
-
-
+
-







  }
  else if(uuidLen>FSL_STRLEN_K256){
    fsl_cx_err_set(f, FSL_RC_RANGE, "UUID is too long: %s", uuid);
    return -4;
  }
  else {
    fsl_id_t rid = -5;
    fsl_stmt q = fsl_stmt_empty;
    fsl_stmt * qS = NULL;
    int rc;
    rc = fsl_is_uuid_len((int)uuidLen)
    fsl_stmt * q = NULL;
    int rc = 0;
    bool const isGlob = !fsl_is_uuid_len((int)uuidLen);
      /* Optimization for the common internally-used case.

    if(isGlob){
         FIXME: there is an *astronomically small* chance of a prefix
         collision on a v1-length uuidLen against a v2-length
      q = &f->cache.stmt.uuidToRidGlob;
         blob.uuid value, leading to no match found for an existing v2
         uuid here. Like... a *REALLY* small chance.
      */
      ? fsl_db_prepare_cached(db, &qS,
                              "SELECT rid FROM blob WHERE "
                              "uuid=? /*%s()*/",__func__)
      : fsl_db_prepare(db, &q,
                       "SELECT rid FROM blob WHERE "
      if(!q->stmt){
        rc = fsl_cx_prepare(f, q,
                            "SELECT rid FROM blob WHERE "
                            "uuid GLOB ?1 || '*' /*%s()*/",__func__);
      }
    }else{
      /* Optimization for the common internally-used case.*/
      q = &f->cache.stmt.uuidToRid;
      if(!q->stmt){
        rc = fsl_cx_prepare(f, q,
                            "SELECT rid FROM blob WHERE "
                       "uuid GLOB '%s*'",
                       uuid);
                            "uuid=?1 /*%s()*/",__func__);
    if(!rc){
      fsl_stmt * st = qS ? qS : &q;
      if(qS){
        rc = fsl_stmt_bind_text(qS, 1, uuid, (fsl_int_t)uuidLen, 0);
      }
    }
      if(!rc){
        rc = fsl_stmt_step(st);
        switch(rc){
          case FSL_RC_STEP_ROW:
            rc = 0;
            rid = fsl_stmt_g_id(st, 0);
            if(!qS){
    if(rc) return -10;
    rc = fsl_stmt_bind_step(q, "s", uuid);
    switch(rc){
      case FSL_RC_STEP_ROW:
        rc = 0;
        rid = fsl_stmt_g_id(q, 0);
        if(isGlob){
              /*
                Check for an ambiguous result. We don't need this for
                the (qS==st) case because that one does an exact match
                on a unique key.
          /* Check for an ambiguous result. We don't need this for
             the !isGlob case because that one does an exact match
             on a unique key. */
              */
              rc = fsl_stmt_step(st);
              switch(rc){
                case FSL_RC_STEP_ROW:
                  rc = 0;
                  fsl_cx_err_set(f, FSL_RC_AMBIGUOUS,
                                 "UUID prefix is ambiguous: %s",
                                 uuid);
                  rid = -6;
                break;
                case FSL_RC_STEP_DONE:
                  /* Unambiguous UUID */
                  rc = 0;
                  break;
                default:
                  assert(st->db->error.code);
                  /* fall through and uplift the db error below... */
              }
            }
            break;
          rc = fsl_stmt_step(q);
          switch(rc){
            case FSL_RC_STEP_ROW:
              rc = 0;
              fsl_cx_err_set(f, FSL_RC_AMBIGUOUS,
                             "UUID prefix is ambiguous: %s",
                             uuid);
              rid = -6;
              break;
            case FSL_RC_STEP_DONE:
              /* Unambiguous UUID */
              rc = 0;
              break;
            default:
              assert(db->error.code);
              break;
              /* fall through and uplift the db error below... */
          }
        }
        break;
          case FSL_RC_STEP_DONE:
            /* No entry found */
            rid = 0;
            rc = 0;
            break;
          default:
            assert(st->db->error.code);
            rid = -7;
            break;
        }
      case 0: /* No entry found */
        rid = 0;
        rc = 0;
        break;
      default:
        assert(db->error.code);
        rid = -7;
        break;
    }
      }
      if(rc && db->error.code && !f->error.code){
        fsl_cx_uplift_db_error(f, db);
      }
    if(rc && db->error.code && !f->error.code){
      fsl_cx_uplift_db_error(f, db);
    }
      if(qS) fsl_stmt_cached_yield(qS);
      else fsl_stmt_finalize(&q);
    fsl_stmt_reset(q);
    }
    return rid;
  }
}

fsl_id_t fsl_repo_filename_fnid( fsl_cx * f, char const * fn ){
  fsl_id_t rv = 0;
  int const rc = fsl__repo_filename_fnid2(f, fn, &rv, false);
32601
32602
32603
32604
32605
32606
32607
32608

32609
32610
32611
32612


32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628





















32629
32630

32631
32632

32633
32634
32635
32636
32637
32638
32639
32640
34410
34411
34412
34413
34414
34415
34416

34417




34418
34419
















34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440


34441


34442

34443
34444
34445
34446
34447
34448
34449







-
+
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
-
-
+
-







  }else if(db->error.code){
    fsl_cx_uplift_db_error(f, db);
  }
  return rc;
}

int fsl_delta_src_id( fsl_cx * const f, fsl_id_t deltaRid,
                      fsl_id_t * rv ){
                      fsl_id_t * const rv ){
  fsl_db * const dbR = fsl_cx_db_repo(f);
  if(!rv) return FSL_RC_MISUSE;
  else if(deltaRid<=0) return FSL_RC_RANGE;
  else if(!dbR) return FSL_RC_NOT_A_REPO;
  if(deltaRid<=0) return FSL_RC_RANGE;
  if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
  else {
    int rc;
    fsl_stmt * q = NULL;
    rc = fsl_db_prepare_cached(dbR, &q,
                               "SELECT srcid FROM delta "
                               "WHERE rid=? /*%s()*/",__func__);
    if(!rc){
      rc = fsl_stmt_bind_id(q, 1, deltaRid);
      if(!rc){
        if(FSL_RC_STEP_ROW==(rc=fsl_stmt_step(q))){
          rc = 0;
          *rv = fsl_stmt_g_id(q, 0);
        }else if(FSL_RC_STEP_DONE==rc){
          rc = 0;
          *rv = 0;
        }
  int rc = 0;
  fsl_stmt * const q = &f->cache.stmt.deltaSrcId;
  if(!q->stmt){
    rc = fsl_cx_prepare(f, q,
                        "SELECT srcid FROM delta "
                        "WHERE rid=? /*%s()*/",__func__);
    if(rc) return rc;
  }
  rc = fsl_stmt_bind_step(q, "R", deltaRid);
  switch(rc){
    case FSL_RC_STEP_ROW:
      rc = 0;
      *rv = fsl_stmt_g_id(q, 0);
      break;
    case 0:
      rc = 0;
      *rv = 0;
    default:
      fsl_cx_uplift_db_error(f, q->db);
      break;
  }
      }
      fsl_stmt_cached_yield(q);
  fsl_stmt_reset(q);
    }
    return rc;
  return rc;
  }
}



int fsl__repo_verify_before_commit( fsl_cx * const f, fsl_id_t rid ){
  if(0){
    /*
32868
32869
32870
32871
32872
32873
32874
32875
32876


32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931


32932
32933
32934
32935
32936
32937
32938
34677
34678
34679
34680
34681
34682
34683


34684
34685


34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700


34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716











34717
34718
34719
34720
34721
34722

34723

34724
34725
34726
34727
34728
34729
34730
34731
34732







-
-
+
+
-
-















-
-
















-
-
-
-
-
-
-
-
-
-
-






-

-
+
+








int fsl_repo_create(fsl_cx * f, fsl_repo_create_opt const * opt ){
  fsl_db * db = 0;
  fsl_cx F = fsl_cx_empty /* used if !f */;
  int rc = 0;
  char const * userName = 0;
  fsl_time_t const unixNow = (fsl_time_t)time(0);
  char fileExists;
  char inTrans = 0;
  bool fileExists;
  bool inTrans = 0;
  extern int fsl_cx_attach_role(fsl_cx * f, const char *zDbName, fsl_dbrole_e r)
    /* Internal routine from fsl_cx.c */;
  if(!opt || !opt->filename) return FSL_RC_MISUSE;
  fileExists = 0 == fsl_file_access(opt->filename,0);
  if(fileExists && !opt->allowOverwrite){
    return f
      ? fsl_cx_err_set(f, FSL_RC_ALREADY_EXISTS,
                       "File already exists and "
                       "allowOverwrite is false: %s",
                       opt->filename)
      : FSL_RC_ALREADY_EXISTS;
  }
  if(f){
    rc = fsl_ckout_close(f)
      /* Will fail if a transaction is active! */;
    switch(rc){
      case 0:
      case FSL_RC_NOT_FOUND:
        rc = 0;
        break;
      default:
        return rc;
    }
  }else{
    f = &F;
    rc = fsl_cx_init( &f, NULL );
    if(rc){
      fsl_cx_finalize(f);
      return rc;
    }
  }
  /* We probably should truncate/unlink the file here
     before continuing, to ensure a clean slate.
  */
  if(fileExists){
#if 0
    FILE * file = fsl_fopen(opt->filename, "w"/*truncates it*/);
    if(!file){
      rc = fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_IO),
                          "Cannot open '%s' for writing.",
                          opt->filename);
      goto end2;    
    }else{
      fsl_fclose(file);
    }
#else
    rc = fsl_file_unlink(opt->filename);
    if(rc){
      rc = fsl_cx_err_set(f, rc, "Cannot unlink existing repo file: %s",
                          opt->filename);
      goto end2;
    }
#endif
  }
  rc = fsl_cx_attach_role(f, opt->filename, FSL_DBROLE_REPO);
  rc = fsl__cx_attach_role(f, opt->filename, FSL_DBROLE_REPO, true);
  MARKER(("attach role rc=%s\n", fsl_rc_cstr(rc)));
  if(rc){
    goto end2;
  }
  db = fsl_cx_db(f);
  if(!f->repo.user){
    f->repo.user = fsl_user_name_guess()
      /* Ignore OOM error here - we'll use 'root'
32959
32960
32961
32962
32963
32964
32965
32966

32967
32968
32969
32970

32971
32972
32973
32974
32975


32976
32977
32978
32979
32980
32981
32982
32983
32984
32985

32986
32987

32988
32989
32990
32991
32992
32993
32994
34753
34754
34755
34756
34757
34758
34759

34760
34761
34762
34763

34764
34765
34766
34767


34768
34769

34770
34771

34772
34773
34774
34775
34776

34777
34778

34779
34780
34781
34782
34783
34784
34785
34786







-
+



-
+



-
-
+
+
-


-





-
+

-
+








      in fossil this is optional, so we will presumably eventually
      have to make it so here as well. Not yet sure where this routine
      is used in fossil (i.e. whether the option is actually
      exercised).
    */
    rc = fsl_db_exec_multi(db,
                           "INSERT INTO repo.config (name,value,mtime) "
                           "INSERT OR IGNORE INTO %q.config (name,value,mtime) "
                           "VALUES ('server-code',"
                           "lower(hex(randomblob(20))),"
                           "%"PRIi64");"
                           "INSERT INTO repo.config (name,value,mtime) "
                           "INSERT OR IGNORE INTO %q.config (name,value,mtime) "
                           "VALUES ('project-code',"
                           "lower(hex(randomblob(20))),"
                           "%"PRIi64");",
                           (int64_t)unixNow,
                           (int64_t)unixNow
                           db->name, (int64_t)unixNow,
                           db->name, (int64_t)unixNow);
                           );
    if(rc) goto end1;
  }

  
  /* Set some config vars ... */
  {
    fsl_stmt st = fsl_stmt_empty;
    rc = fsl_db_prepare(db, &st,
                        "INSERT INTO repo.config (name,value,mtime) "
                        "INSERT INTO %q.config (name,value,mtime) "
                        "VALUES (?,?,%"PRIi64")",
                        (int64_t)unixNow);
                        db->name, (int64_t)unixNow);
    if(!rc){
      fsl_stmt_bind_int64(&st, 3, unixNow);
#define DBSET_STR(KEY,VAL) \
      fsl_stmt_bind_text(&st, 1, KEY, -1, 0);    \
      fsl_stmt_bind_text(&st, 2, VAL, -1, 0); \
      fsl_stmt_step(&st); \
      fsl_stmt_reset(&st)
33019
33020
33021
33022
33023
33024
33025
33026

33027
33028
33029
33030
33031
33032
33033
34811
34812
34813
34814
34815
34816
34817

34818
34819
34820
34821
34822
34823
34824
34825







-
+







    rc = fsl_cx_uplift_db_error(f, db);
  }
  if(inTrans){
    if(!rc) rc = fsl_db_transaction_end(db, 0);
    else fsl_db_transaction_end(db, 1);
    inTrans = 0;
  }
  fsl_cx_close_dbs(f);
  fsl_close_scm_dbs(f);
  db = 0;
  if(rc) goto end2;

  /**
      In order for injection of the first commit to go through
      cleanly (==without any ugly kludging of f->dbMain), we
      need to now open the new db so that it gets connected
33076
33077
33078
33079
33080
33081
33082
33083

33084
33085
33086
33087

33088
33089
33090
33091



33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103

33104
33105
33106
33107
33108
33109
33110
33111
33112
33113


33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128

33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
34868
34869
34870
34871
34872
34873
34874

34875
34876
34877
34878

34879
34880
34881


34882
34883
34884
34885
34886
34887
34888
34889
34890
34891
34892
34893
34894
34895

34896
34897
34898
34899
34900
34901
34902
34903
34904


34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919


34920









34921
34922
34923
34924
34925
34926
34927







-
+



-
+


-
-
+
+
+











-
+








-
-
+
+













-
-
+
-
-
-
-
-
-
-
-
-







      goto detach;
    }
    inTrans2 = 1;
    /*
       Copy all settings from the supplied template repository.
    */
    rc = fsl_db_exec(db,
                     "INSERT OR REPLACE INTO repo.config"
                     "INSERT OR REPLACE INTO %q.config"
                     " SELECT name,value,mtime FROM settingSrc.config"
                     "  WHERE (name IN %s OR name IN %s)"
                     "    AND name NOT GLOB 'project-*';",
                     inopConfig, inopDb);
                     db->name, inopConfig, inopDb);
    if(rc) goto detach;
    rc = fsl_db_exec(db,
                     "REPLACE INTO repo.reportfmt "
                     "SELECT * FROM settingSrc.reportfmt;");
                     "REPLACE INTO %q.reportfmt "
                     "SELECT * FROM settingSrc.reportfmt;",
                     db->name);
    if(rc) goto detach;

    /*
       Copy the user permissions, contact information, last modified
       time, and photo for all the "system" users from the supplied
       template repository into the one being setup.  The other
       columns are not copied because they contain security
       information or other data specific to the other repository.
       The list of columns copied by this SQL statement may need to be
       revised in the future.
    */
    rc = fsl_db_exec(db, "UPDATE repo.user SET"
    rc = fsl_db_exec(db, "UPDATE %q.user SET"
      "  cap = (SELECT u2.cap FROM settingSrc.user u2"
      "         WHERE u2.login = user.login),"
      "  info = (SELECT u2.info FROM settingSrc.user u2"
      "          WHERE u2.login = user.login),"
      "  mtime = (SELECT u2.mtime FROM settingSrc.user u2"
      "           WHERE u2.login = user.login),"
      "  photo = (SELECT u2.photo FROM settingSrc.user u2"
      "           WHERE u2.login = user.login)"
      " WHERE user.login IN ('anonymous','nobody','developer','reader');"
    );
      " WHERE user.login IN ('anonymous','nobody','developer','reader');",
      db->name);

    detach:
    fsl_free(inopConfig);
    fsl_free(inopDb);
    if(inTrans2){
      if(!rc) rc = fsl_db_transaction_end(db,0);
      else fsl_db_transaction_end(db,1);
    }
    fsl_db_detach(db, "settingSrc");
    if(rc) goto end2;
  }

  if(opt->commitMessage && *opt->commitMessage){
    /*
      Set up initial commit. Because of the historically empty P-card
    /* Set up initial commit. */
      on the first commit, we can't create that one using the fsl_deck
      API unless we elide the P-card (not as fossil does) and insert
      an empty R-card (as fossil does). We need one of P- or R-card to
      unambiguously distinguish this MANIFEST from a CONTROL artifact.

      Reminder to self: fsl_deck has been adjusted to deal with the
      initial-checkin(-like) case in the mean time. But this code
      works, so no need to go changing it...
    */
    fsl_deck d = fsl_deck_empty;
    fsl_cx_err_reset(f);
    fsl_deck_init(f, &d, FSL_SATYPE_CHECKIN);
    rc = fsl_deck_C_set(&d, opt->commitMessage, -1);
    if(!rc) rc = fsl_deck_D_set(&d, fsl_db_julian_now(db));
    if(!rc) rc = fsl_deck_R_set(&d, FSL_MD5_INITIAL_HASH);
    if(!rc && opt->commitMessageMimetype && *opt->commitMessageMimetype){
33161
33162
33163
33164
33165
33166
33167
33168


33169
33170
33171
33172
33173
33174
33175
34944
34945
34946
34947
34948
34949
34950

34951
34952
34953
34954
34955
34956
34957
34958
34959







-
+
+







  if(f == &F){
    fsl_cx_finalize(f);
    if(rc) fsl_file_unlink(opt->filename);
  }
  return rc;
}

static int fsl_repo_dir_names_rid( fsl_cx * f, fsl_id_t rid, fsl_list * tgt,
static int fsl_repo_dir_names_rid( fsl_cx * const f, fsl_id_t rid,
                                   fsl_list * const tgt,
                                   bool addSlash){
  fsl_db * dbR = fsl_needs_repo(f);
  fsl_deck D = fsl_deck_empty;
  fsl_deck * d = &D;
  int rc = 0;
  fsl_stmt st = fsl_stmt_empty;
  fsl_buffer tname = fsl_buffer_empty;
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199

33200
33201
33202
33203

33204
33205
33206
33207
33208
33209
33210
34972
34973
34974
34975
34976
34977
34978

34979
34980
34981

34982
34983
34984
34985

34986
34987
34988
34989
34990
34991
34992
34993







-



-
+



-
+







  }
  rc = fsl_buffer_appendf(&tname,
                          "tmp_filelist_for_rid_%d",
                          (int)rid);
  if(rc) goto end;
  rc = fsl_deck_F_rewind(d);
  while( !rc && !(rc=fsl_deck_F_next(d, &fc)) && fc ){
    //if(!fc->name) continue;
    assert(fc->name && *fc->name);
    if(!st.stmt){
      rc = fsl_db_exec(dbR, "CREATE TEMP TABLE IF NOT EXISTS "
                       "%b(n TEXT UNIQUE ON CONFLICT IGNORE)",
                       "\"%b\"(n TEXT UNIQUE ON CONFLICT IGNORE)",
                       &tname);
      if(!rc){
        rc = fsl_db_prepare(dbR, &st,
                            "INSERT INTO %b(n) "
                            "INSERT INTO \"%b\"(n) "
                            "VALUES(fsl_dirpart(?,%d))",
                            &tname, addSlash ? 1 : 0);
      }
      if(rc) goto end;
      assert(st.stmt);
    }
    rc = fsl_stmt_bind_text(&st, 1, fc->name, -1, 0);
33218
33219
33220
33221
33222
33223
33224
33225

33226
33227
33228
33229
33230
33231
33232
35001
35002
35003
35004
35005
35006
35007

35008
35009
35010
35011
35012
35013
35014
35015







-
+







    fsl_stmt_reset(&st);
    fc = 0;
  }

  if(!rc && (count>0)){
    fsl_stmt_finalize(&st);
    rc = fsl_db_prepare(dbR, &st,
                        "SELECT n FROM %b WHERE n "
                        "SELECT n FROM \"%b\" WHERE n "
                        "IS NOT NULL ORDER BY n %s",
                        &tname,
                        fsl_cx_filename_collation(f));
    while( !rc && (FSL_RC_STEP_ROW==(rc=fsl_stmt_step(&st))) ){
      fsl_size_t nLen = 0;
      char const * name = fsl_stmt_g_text(&st, 0, &nLen);
      rc = 0;
33251
33252
33253
33254
33255
33256
33257
33258

33259
33260
33261
33262
33263
33264

33265
33266

33267
33268


33269
33270
33271
33272
33273
33274
33275
35034
35035
35036
35037
35038
35039
35040

35041
35042
35043
35044
35045
35046

35047
35048

35049


35050
35051
35052
35053
35054
35055
35056
35057
35058







-
+





-
+

-
+
-
-
+
+







  end:
  if(rc && !f->error.code && dbR->error.code){
    fsl_cx_uplift_db_error(f, dbR);
  }
  fsl_stmt_finalize(&st);
  fsl_deck_clean(d);
  if(tname.used){
    fsl_db_exec(dbR, "DROP TABLE IF EXISTS %b", &tname);
    fsl_db_exec(dbR, "DROP TABLE IF EXISTS \"%b\"", &tname);
  }
  fsl_buffer_clear(&tname);
  return rc;
}

int fsl_repo_dir_names( fsl_cx * f, fsl_id_t rid, fsl_list * tgt,
int fsl_repo_dir_names( fsl_cx * const f, fsl_id_t rid, fsl_list * const tgt,
                        bool addSlash ){
  fsl_db * db = (f && tgt) ? fsl_needs_repo(f) : NULL;
  fsl_db * const db = fsl_needs_repo(f);
  if(!f || !tgt) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  if(!db) return FSL_RC_NOT_A_REPO;
  else if(!tgt) return FSL_RC_MISUSE;
  else {
    int rc;
    if(rid>=0){
      if(!rid){
        /* Dir list for current checkout version */
        if(f->ckout.rid>0){
          rid = f->ckout.rid;
33315
33316
33317
33318
33319
33320
33321
33322

33323
33324
33325
33326
33327
33328
33329
35098
35099
35100
35101
35102
35103
35104

35105
35106
35107
35108
35109
35110
35111
35112







-
+







/* UNTESTED */
char fsl_repo_is_readonly(fsl_cx const * f){
  if(!f || !f->dbMain) return 0;
  else{
    int const roleId = f->ckout.db.dbh ? FSL_DBROLE_MAIN : FSL_DBROLE_REPO
      /* If CKOUT is attached, it is the main DB and REPO is ATTACHed. */
      ;
    char const * zRole = fsl_db_role_label(roleId);
    char const * zRole = fsl_db_role_name(roleId);
    assert(f->dbMain);
    return sqlite3_db_readonly(f->dbMain->dbh, zRole) ? 1 : 0;
  }
}

int fsl__repo_record_filename(fsl_cx * const f){
  fsl_db * dbR = fsl_needs_repo(f);
33348
33349
33350
33351
33352
33353
33354
33355

33356
33357




33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368

33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383

33384
33385
33386
33387
33388
33389
33390
33391
33392

33393
33394
33395
33396
33397
33398
33399
35131
35132
35133
35134
35135
35136
35137

35138
35139

35140
35141
35142
35143
35144
35145
35146
35147
35148
35149
35150
35151
35152
35153

35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165
35166
35167
35168

35169
35170
35171
35172
35173
35174
35175
35176
35177

35178
35179
35180
35181
35182
35183
35184
35185







-
+

-
+
+
+
+










-
+














-
+








-
+







  dbConf = fsl_cx_db_config(f);
  if(dbConf){
    int const dbRole = (f->dbMain==&f->config.db)
      ? FSL_DBROLE_MAIN : FSL_DBROLE_CONFIG;
    rc = fsl_db_exec(dbConf,
                     "INSERT OR IGNORE INTO %s.global_config(name,value) "
                     "VALUES('repo:%q',1)",
                     fsl_db_role_label(dbRole),
                     fsl_db_role_name(dbRole),
                     fsl_buffer_cstr(full));
    if(rc) goto end;
    if(rc){
      fsl_cx_uplift_db_error(f, dbConf);
      goto end;
    }
  }

  dbC = fsl_cx_db_ckout(f);
  if(dbC && (zCDir=f->ckout.dir)){
    /* If we have a checkout, update its repo's list of checkouts... */
    /* Assumption: if we have an opened checkout, dbR is ATTACHed with
       the role REPO. */
    int ro;
    assert(dbR);
    ro = sqlite3_db_readonly(dbR->dbh,
                             fsl_db_role_label(FSL_DBROLE_REPO));
                             fsl_db_role_name(FSL_DBROLE_REPO));
    assert(ro>=0);
    if(!ro){
      fsl_buffer localRoot = fsl_buffer_empty;
      rc = fsl_file_canonical_name(zCDir, &localRoot, 1);
      if(0==rc){
        if(dbConf){
          /*
            If global config is open, write the checkout db's name to it.
          */
          int const dbRole = (f->dbMain==&f->config.db)
            ? FSL_DBROLE_MAIN : FSL_DBROLE_CONFIG;
          rc = fsl_db_exec(dbConf,
                           "REPLACE INTO INTO %s.global_config(name,value) "
                           "VALUES('ckout:%q',1)",
                           fsl_db_role_label(dbRole),
                           fsl_db_role_name(dbRole),
                           fsl_buffer_cstr(&localRoot));
        }
        if(0==rc){
          /* We know that repo is ATTACHed to ckout here. */
          assert(dbR == dbC);
          rc = fsl_db_exec(dbR,
                           "REPLACE INTO %s.config(name, value, mtime) "
                           "VALUES('ckout:%q', 1, now())",
                           fsl_db_role_label(FSL_DBROLE_REPO),
                           fsl_db_role_name(FSL_DBROLE_REPO),
                           fsl_buffer_cstr(&localRoot));
        }
      }
      fsl_buffer_clear(&localRoot);
    }
  }

33433
33434
33435
33436
33437
33438
33439
33440

33441
33442
33443
33444
33445
33446
33447
33448
33449


33450
33451
33452
33453
33454
33455
33456
35219
35220
35221
35222
35223
35224
35225

35226
35227
35228
35229
35230
35231
35232
35233


35234
35235
35236
35237
35238
35239
35240
35241
35242







-
+







-
-
+
+







    if(db->error.code){
      fsl_cx_uplift_db_error(f, db);
    }
    return rv;
  }
}

int fsl_repo_extract( fsl_cx * f, fsl_repo_extract_opt const * opt_ ){
int fsl_repo_extract( fsl_cx * const f, fsl_repo_extract_opt const * const opt_ ){
  if(!f || !opt_->callback) return FSL_RC_MISUSE;
  else if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
  else if(opt_->checkinRid<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE, "RID must be positive.");
  }else{
    int rc;
    fsl_deck mf = fsl_deck_empty;
    fsl_buffer * content = opt_->extractContent
      ? &f->fileContent
    fsl_buffer * const content = opt_->extractContent
      ? &f->cache.fileContent
      : NULL;
    fsl_id_t fid;
    fsl_repo_extract_state xst = fsl_repo_extract_state_empty;
    fsl_card_F const * fc = NULL;
    fsl_repo_extract_opt const opt = *opt_
      /* Copy in case the caller modifies it via their callback. If we
         find an interesting use for such modification then we can
33489
33490
33491
33492
33493
33494
33495

33496
33497
33498
33499
33500
33501
33502
35275
35276
35277
35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289







+







      }else if(!fid){
        rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "Could not resolve RID for UUID: %s",
                            fc->uuid);
      }else if(opt.extractContent){
        fsl_buffer_reuse(content);
        rc = fsl_content_get(f, fid, content);
        //assert(FSL_RC_RANGE!=rc);
      }
      if(!rc){
        /** Call the callback. */
        xst.fCard = fc;
        assert(fid>0);
        xst.content = content;
        xst.fileRid = fid;
33556
33557
33558
33559
33560
33561
33562
33563
33564


33565
33566
33567
33568
33569
33570
33571
35343
35344
35345
35346
35347
35348
35349


35350
35351
35352
35353
35354
35355
35356
35357
35358







-
-
+
+







                                        rid, uuid );
    assert(cursorKludge.mem == in->mem);
    return rc;
  }
}


int fsl_repo_blob_lookup( fsl_cx * f, fsl_buffer const * src, fsl_id_t * ridOut,
                          fsl_uuid_str * hashOut ){
int fsl_repo_blob_lookup( fsl_cx * const f, fsl_buffer const * const src,
                          fsl_id_t * const ridOut, fsl_uuid_str * hashOut ){
  int rc;
  fsl_buffer hash_ = fsl_buffer_empty;
  fsl_buffer * hash;
  fsl_id_t rid = 0;
  if(!fsl_cx_db_repo(f)) return FSL_RC_NOT_A_REPO;
  hash = hashOut ? &hash_ : fsl__cx_scratchpad(f);
  /* First check the auxiliary hash to see if there is already an artifact
33680
33681
33682
33683
33684
33685
33686
33687

33688
33689
33690
33691
33692
33693
33694
35467
35468
35469
35470
35471
35472
35473

35474
35475
35476
35477
35478
35479
35480
35481







-
+







  }
  end:
  fsl__cx_scratchpad_yield(f, sql);
  fsl_stmt_finalize(&q);
  return rc;
}

int fsl_repo_manifest_write(fsl_cx *f,
int fsl_repo_manifest_write(fsl_cx * const f,
                            fsl_id_t manifestRid,
                            fsl_buffer * const pManifest,
                            fsl_buffer * const pHash,
                            fsl_buffer * const pTags) {
  fsl_db * const db = fsl_needs_repo(f);
  if(!db) return FSL_RC_NOT_A_REPO;
  if(manifestRid<=0){
33820
33821
33822
33823
33824
33825
33826
33827

33828
33829
33830
33831
33832
33833
33834
35607
35608
35609
35610
35611
35612
35613

35614
35615
35616
35617
35618
35619
35620
35621







-
+







  /**
     Update the repository schema for Fossil version 2.0.  (2017-02-28)
     (1) Change the CHECK constraint on BLOB.UUID so that the length
     is greater than or equal to 40, not exactly equal to 40.
  */
  zBlobSchema =
    fsl_db_g_text(frs->db, NULL, "SELECT sql FROM %!Q.sqlite_schema"
                  " WHERE name='blob'", fsl_db_role_label(FSL_DBROLE_REPO));
                  " WHERE name='blob'", fsl_db_role_name(FSL_DBROLE_REPO));
  if(!zBlobSchema){
    /* ^^^^ reminder: fossil(1) simply ignores this case, silently
       doing nothing instead. */
    rc = fsl_cx_uplift_db_error(frs->f, frs->db);
    if(!rc){
      rc = fsl_cx_err_set(frs->f, FSL_RC_DB,
                          "Unknown error fetching blob table schema.");
33843
33844
33845
33846
33847
33848
33849
33850

33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862

33863
33864
33865
33866
33867
33868
33869
35630
35631
35632
35633
35634
35635
35636

35637
35638
35639
35640
35641
35642
35643
35644
35645
35646
35647
35648

35649
35650
35651
35652
35653
35654
35655
35656







-
+











-
+







      int rc2 = 0;
      zBlobSchema[i] = '>';
      sqlite3_db_config(frs->db->dbh, SQLITE_DBCONFIG_DEFENSIVE, 0, &rc2);
      rc = fsl_cx_exec_multi(frs->f,
           "PRAGMA writable_schema=ON;"
           "UPDATE %!Q.sqlite_schema SET sql=%Q WHERE name LIKE 'blob';"
           "PRAGMA writable_schema=OFF;",
           fsl_db_role_label(FSL_DBROLE_REPO), zBlobSchema
           fsl_db_role_name(FSL_DBROLE_REPO), zBlobSchema
      );
      sqlite3_db_config(frs->db->dbh, SQLITE_DBCONFIG_DEFENSIVE, 1, &rc2);
      break;
    }
  }
  if(rc) goto end;
  rc = fsl_cx_exec(frs->f,
    "CREATE VIEW IF NOT EXISTS "
    "  %!Q.artifact(rid,rcvid,size,atype,srcid,hash,content) AS "
    "    SELECT blob.rid,rcvid,size,1,srcid,uuid,content"
    "      FROM blob LEFT JOIN delta ON (blob.rid=delta.rid);",
    fsl_db_role_label(FSL_DBROLE_REPO)
    fsl_db_role_name(FSL_DBROLE_REPO)
  );
  
  end:
  fsl_free(zBlobSchema);
  return rc;
}

34024
34025
34026
34027
34028
34029
34030
34031

34032
34033
34034
34035
34036
34037
34038
34039
34040

34041
34042
34043
34044

34045
34046
34047
34048
34049
34050
34051
35811
35812
35813
35814
35815
35816
35817

35818







35819

35820

35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831







-
+
-
-
-
-
-
-
-

-
+
-



+







      fsl_stmt_bind_id(&frs->qChild, 1, cid);
      if( FSL_RC_STEP_ROW==fsl_stmt_step(&frs->qChild) &&
          (sz = fsl_stmt_g_int64(&frs->qChild, 1))>=0 ){
        fsl_buffer next = fsl_buffer_empty;
        fsl_buffer delta = fsl_buffer_empty;
        void const * blob = 0;
        fsl_size_t deltaBlobSize = 0;
        rc = INTCHECK fsl_stmt_get_blob(&frs->qChild, 0, &blob, &deltaBlobSize)
        rc = INTCHECK fsl_stmt_get_blob(&frs->qChild, 0, &blob, &deltaBlobSize);
          /* Library-level TODO: a heuristic/convention in fsl_buffer
             APIs which says that if buf.mem is not NULL and buf.capacity
             is 0 then the memory is owned elsewhere and must be copied
             if/when it would be modified by the buffer API. That would allow
             us to emulate some of the buffer-copy optimization which fossil does,
             e.g. in this very spot.
           */;
        if(rc) goto outro;
        rc = fsl_buffer_append(&delta, blob, (fsl_int_t)deltaBlobSize);
        fsl_buffer_external(&delta, blob, (fsl_int_t)deltaBlobSize);
        fsl_stmt_reset(&frs->qChild);
        rc = INTCHECK fsl_buffer_uncompress(&delta, &delta);
        if(rc) goto outro;
        rc = INTCHECK fsl_buffer_delta_apply(content, &delta, &next);
        fsl_stmt_reset(&frs->qChild);
        fsl_buffer_clear(&delta);
        if(rc){
          if(FSL_RC_OOM!=rc){
            rc = fsl_cx_err_set(frs->f, rc,
                                "Error applying delta #%" FSL_ID_T_PFMT
                                " to parent #%" FSL_ID_T_PFMT, cid, rid);
          }
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149

34150
34151
34152
34153
34154
34155

34156
34157
34158


34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173

34174
34175
34176

34177
34178
34179
34180
34181


34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
35913
35914
35915
35916
35917
35918
35919



35920
35921
35922
35923
35924
35925

35926
35927
35928
35929
35930
35931

35932
35933
35934
35935
35936
35937
35938
35939
35940
35941
35942
35943
35944

35945

35946
35947
35948
35949

35950
35951
35952

35953
35954
35955
35956


35957
35958
35959
35960
35961
35962

35963

35964
35965
35966
35967
35968
35969
35970







-
-
-






-
+





-
+



+
+







-

-




-
+


-
+



-
-
+
+




-

-







  }
  fsl__cx_scratchpad_yield(frs->f, b);
  return rc;
}



#define FSL__REBUILD_SKIP_TICKETS 1 /* remove this once crosslinking does
                                       something useful with tickets. */

static int fsl__rebuild(fsl_cx * const f, fsl_rebuild_opt const * const opt){
  fsl_stmt s = fsl_stmt_empty;
  fsl_stmt q = fsl_stmt_empty;
  fsl_db * const db = fsl_cx_db_repo(f);
  int rc;
  FslRebuildState frs = FslRebuildState_empty;
  fsl_buffer sql = fsl_buffer_empty;
  fsl_buffer * const sql = fsl__cx_scratchpad(f);
  assert(db);
  frs.f = frs.step.f = f;
  frs.db = db;
  frs.opt = frs.step.opt = opt;
  rc = fsl__rebuild_update_schema(&frs);
  if(!rc) rc = fsl_buffer_reserve(&sql, 1024 * 4);
  if(!rc) rc = fsl_buffer_reserve(sql, 1024 * 4);
  if(rc) goto end;

  fsl__cx_clear_mf_seen(f, false);
  /* DROP all tables which are not part of our One True Vision of the
     repo db... */
  rc = fsl_cx_prepare(f, &q,
     "SELECT name FROM %!Q.sqlite_schema /*scan*/"
     " WHERE type='table'"
     " AND name NOT IN ('admin_log', 'blob','delta','rcvfrom','user','alias',"
                       "'config','shun','private','reportfmt',"
                       "'concealed','accesslog','modreq',"
                       "'purgeevent','purgeitem','unversioned',"
#if FSL__REBUILD_SKIP_TICKETS
                      "'ticket','ticketchng',"
#endif
                       "'subscriber','pending_alert','chat'"
                      ")"
     " AND name NOT GLOB 'sqlite_*'"
     " AND name NOT GLOB 'fx_*'",
     fsl_db_role_label(FSL_DBROLE_REPO)
     fsl_db_role_name(FSL_DBROLE_REPO)
  );
  while( 0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){
    rc = fsl_buffer_appendf(&sql, "DROP TABLE IF EXISTS %!Q;\n",
    rc = fsl_buffer_appendf(sql, "DROP TABLE IF EXISTS %!Q;\n",
                            fsl_stmt_g_text(&q, 0, NULL));
  }
  fsl_stmt_finalize(&q);
  if(0==rc && fsl_buffer_size(&sql)){
    rc = fsl_cx_exec_multi(f, "%b", &sql);
  if(0==rc && fsl_buffer_size(sql)){
    rc = fsl_cx_exec_multi(f, "%b", sql);
  }
  if(rc) goto end;

  rc = fsl_cx_exec_multi(f, "%s", fsl_schema_repo2());
#if !FSL__REBUILD_SKIP_TICKETS
  if(0==rc) rc = fsl__cx_ticket_create_table(f);
#endif
  if(0==rc) rc = fsl__shunned_remove(f);
  if(0==rc){
    rc = fsl_cx_exec_multi(f,
      "INSERT INTO unclustered"
      " SELECT rid FROM blob EXCEPT SELECT rid FROM private;"
      "DELETE FROM unclustered"
      " WHERE rid IN (SELECT rid FROM shun JOIN blob USING(uuid));"
34211
34212
34213
34214
34215
34216
34217

34218
34219
34220
34221
34222
34223
34224
35986
35987
35988
35989
35990
35991
35992
35993
35994
35995
35996
35997
35998
35999
36000







+







  }

  //totalSize += incrSize*2;
  rc = fsl_cx_prepare(f, &s,
     "SELECT rid, size FROM blob /*scan*/"
     " WHERE NOT EXISTS(SELECT 1 FROM shun WHERE uuid=blob.uuid)"
     "   AND NOT EXISTS(SELECT 1 FROM delta WHERE rid=blob.rid)"
     "%s", opt->randomize ? " ORDER BY RANDOM()" : ""
  );
  if(rc) goto end;
  rc = fsl__crosslink_begin(f)
    /* Maintenace reminder: if this call succeeds, BE SURE that
       we do not skip past the fsl__crosslink_end() call via
       (goto end). Doing so would get the transaction stack out
       of sync. */;
34237
34238
34239
34240
34241
34242
34243

34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255























34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274

34275
34276
34277
34278
34279
34280
34281
34282

34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
36013
36014
36015
36016
36017
36018
36019
36020
36021
36022
36023
36024
36025
36026
36027
36028
36029
36030
36031
36032
36033
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043
36044
36045
36046
36047
36048
36049
36050
36051
36052
36053
36054
36055
36056
36057
36058
36059
36060
36061
36062
36063
36064
36065
36066
36067
36068
36069
36070
36071
36072
36073

36074
36075
36076
36077
36078
36079
36080
36081
36082
36083
36084
36085
36086
36087
36088
36089

36090
36091
36092
36093
36094
36095
36096







+












+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


















-
+








+






-







    }
  }
  fsl_stmt_finalize(&s);
  if(rc) goto crosslink_end;
  rc = fsl_cx_prepare(f, &s,
     "SELECT rid, size FROM blob"
     " WHERE NOT EXISTS(SELECT 1 FROM shun WHERE uuid=blob.uuid)"
     "%s", opt->randomize ? " ORDER BY RANDOM()" : ""
  );
  while( 0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&s) ){
    fsl_id_t const rid = fsl_stmt_g_id(&s, 0);
    int64_t const size = fsl_stmt_g_int64(&s, 1);
    if( size>=0 ){
      if( !fsl_id_bag_contains(&frs.idsDone, rid) ){
        fsl_buffer content = fsl_buffer_empty;
        rc = fsl_content_get(f, rid, &content);
        if(0==rc){
          rc = fsl__rebuild_step(&frs, rid, size, &content);
          assert(!content.mem);
        }
        /*
          2021-12-17: hmmm... while debugging the problem reported here:

          https://fossil-scm.org/forum/forumpost/f4cc31863179f843

          It was discovered that fossil will simply skip any content
          it cannot read in this step, even if it's skipped over
          because of a broken blob-to-delta mapping (whereas fossil's
          test-integrity command will catch that case). If such a case
          happens to us, fsl_content_get() fails with FSL_RC_PHANTOM.
          That seems to me to be the right thing to do, as such a case
          is indicative of db corruption. However, if we skip over
          these then we cannot rebuild a repo which has such (invalid)
          state.

          Feature or bug?

          For now let's keep it strict and fail if we can't fetch the
          content. We can reevaluate that decision later if needed. We
          can add a fsl_rebuild_opt::ignorePhantomFailure (better name
          pending!) flag which tells us how the user would prefer to
          deal with this.
        */
        fsl_buffer_clear(&content);
      }
    }else{
      rc = fsl_cx_exec_multi(f, "INSERT OR IGNORE INTO phantom "
                             "VALUES(%" FSL_ID_T_PFMT ")", rid);
      if(0==rc){
        frs.step.blobSize = -1;
        frs.step.artifactType = FSL_SATYPE_INVALID;
        rc = fsl__rebuild_step_done(&frs, rid);
      }
    }
  }
  fsl_stmt_finalize(&s);
  crosslink_end:
  rc = fsl__crosslink_end(f, rc);
  if(rc) goto end;
  rc = fsl__rebuild_tag_trunk(&frs);
  if(rc) goto end;
  //if( opt->clustering ) rc = fsl__create_cluster(f);
  //if( opt->createClusters ) rc = fsl__create_cluster(f);
  rc = fsl_cx_exec_multi(f,
     "REPLACE INTO config(name,value,mtime) VALUES('content-schema',%Q,now());"
      "REPLACE INTO config(name,value,mtime) VALUES('aux-schema',%Q,now());"
      "REPLACE INTO config(name,value,mtime) VALUES('rebuilt',%Q,now());",
      FSL_CONTENT_SCHEMA, FSL_AUX_SCHEMA,
      "libfossil " FSL_LIB_VERSION_HASH " " FSL_LIB_VERSION_TIMESTAMP
  );
  end:
  fsl__cx_scratchpad_yield(f, sql);
  if(0==rc && frs.opt->callback){
    frs.step.stepNumber = 0;
    frs.step.rid = 0;
    frs.step.blobSize = 0;
    rc = frs.opt->callback(&frs.step);
  }
  fsl_buffer_clear(&sql);
  fsl_stmt_finalize(&s);
  fsl_stmt_finalize(&frs.qDeltas);
  fsl_stmt_finalize(&frs.qSize);
  fsl_stmt_finalize(&frs.qChild);
  fsl_id_bag_clear(&frs.idsDone);
  return rc;
}
34305
34306
34307
34308
34309
34310
34311
34312





































































































34313
34314
34315


34316
34317
34318
34319
34320
34321
34322
36105
36106
36107
36108
36109
36110
36111

36112
36113
36114
36115
36116
36117
36118
36119
36120
36121
36122
36123
36124
36125
36126
36127
36128
36129
36130
36131
36132
36133
36134
36135
36136
36137
36138
36139
36140
36141
36142
36143
36144
36145
36146
36147
36148
36149
36150
36151
36152
36153
36154
36155
36156
36157
36158
36159
36160
36161
36162
36163
36164
36165
36166
36167
36168
36169
36170
36171
36172
36173
36174
36175
36176
36177
36178
36179
36180
36181
36182
36183
36184
36185
36186
36187
36188
36189
36190
36191
36192
36193
36194
36195
36196
36197
36198
36199
36200
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213


36214
36215
36216
36217
36218
36219
36220
36221
36222







-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
+
+







    int const rc2 = fsl_cx_transaction_end(f, opt->dryRun || rc!=0);
    if(0==rc && 0!=rc2) rc = rc2;
  }
  fsl_cx_interrupt(f, 0, NULL);
  return rc;
}

#undef FSL__REBUILD_SKIP_TICKETS

int fsl_cidiff(fsl_cx * const f, fsl_cidiff_opt const * const opt){
  fsl_deck d1 = fsl_deck_empty;
  fsl_deck d2 = fsl_deck_empty;
  fsl_card_F const * fc1;
  fsl_card_F const * fc2;
  int rc;
  fsl_cidiff_state cst = fsl_cidiff_state_empty;
  if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
  rc = fsl_deck_load_rid(f, &d1, opt->v1, FSL_SATYPE_CHECKIN);
  if(rc) goto end;
  rc = fsl_deck_load_rid(f, &d2, opt->v2, FSL_SATYPE_CHECKIN);
  if(rc) goto end;
  rc = fsl_deck_F_rewind(&d1);
  if(0==rc) rc = fsl_deck_F_rewind(&d2);
  if(rc) goto end;
  fsl_deck_F_next(&d1, &fc1);
  fsl_deck_F_next(&d2, &fc2);
  cst.f = f;
  cst.opt = opt;
  cst.d1 = &d1;
  cst.d2 = &d2;
  rc = opt->callback(&cst);
  cst.stepType = FSL_RC_STEP_ROW;
  while(0==rc && (fc1 || fc2)){
    int nameCmp;
    cst.changes = FSL_CIDIFF_NONE;
    if(!fc1) nameCmp = 1;
    else if(!fc2) nameCmp = -1;
    else{
      nameCmp = fsl_strcmp(fc1->name, fc2->name);
      if(fc2->priorName){
        if(0==nameCmp){
          cst.changes |= FSL_CIDIFF_FILE_RENAMED;
        }else if(0==fsl_strcmp(fc1->name, fc2->priorName)){
          /**
             Treat these as being the same file for this purpose.

             We ostensibly know that fc1 was renamed to fc2->name here
             BUT there's a corner case we can't sensibly determine
             here: file A renamed to B and file C renamed to A. If
             both of those F-cards just happen to align at this point
             in this loop, we're mis-informing the user. Reliably
             catching that type of complex situation requires
             significant hoop-jumping, as can be witness in
             fsl_ckout_merge() (which still misses some convoluted
             cases).
          */
          nameCmp = 0;
          cst.changes |= FSL_CIDIFF_FILE_RENAMED;
        }
      }
      if(fc1->perm!=fc2->perm){
        cst.changes |= FSL_CIDIFF_FILE_PERMS;
      }
    }
    if(nameCmp<0){
      nameCmp = -1/*see below*/;
      assert(fc1);
      cst.changes |= FSL_CIDIFF_FILE_REMOVED;
      cst.fc1 = fc1; cst.fc2 = NULL;
    }else if(nameCmp>0){
      nameCmp = 1/*see below*/;
      cst.changes |= FSL_CIDIFF_FILE_ADDED;
      cst.fc1 = NULL; cst.fc2 = fc2;
    }else{
      cst.fc1 = fc1; cst.fc2 = fc2;
    }
    if(fc1 && fc2 && 0!=fsl_strcmp(fc1->uuid, fc2->uuid)){
      cst.changes |= FSL_CIDIFF_FILE_MODIFIED;
    }
    rc = opt->callback(&cst);
    switch(rc ? 2 : nameCmp){
      case  2: break;
      case -1: rc = fsl_deck_F_next(&d1, &fc1); break;
      case  1: rc = fsl_deck_F_next(&d2, &fc2); break;
      case  0:
        rc = fsl_deck_F_next(&d1, &fc1);
        if(0==rc) rc = fsl_deck_F_next(&d2, &fc2);
        break;
      default:
        fsl__fatal(FSL_RC_MISUSE,"Internal API misuse.");
    }
  }/*while(f-cards)*/
  if(0==rc){
    cst.fc1 = cst.fc2 = NULL;
    cst.stepType = FSL_RC_STEP_DONE;
    rc = opt->callback(&cst);
  }
  end:
  fsl_deck_finalize(&d1);
  fsl_deck_finalize(&d2);
  return rc;
}


bool fsl_repo_forbids_delta_manifests(fsl_cx * const f){
  return fsl_config_get_bool(f, FSL_CONFDB_REPO, false,
                             "forbid-delta-manifests");
}

#undef MARKER
/* end of file repo.c */
/* start of file schema.c */
/* end of file ./src/repo.c */
/* start of file ./src/schema.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 Stephan Beal (https://wanderinghorse.net).


  
34364
34365
34366
34367
34368
34369
34370
34371
34372


34373
34374
34375
34376
34377
34378
34379
36264
36265
36266
36267
36268
36269
36270


36271
36272
36273
36274
36275
36276
36277
36278
36279







-
-
+
+







  return fsl_schema_ticket_cstr;
}

char const * fsl_schema_forum(){
  extern char const * fsl_schema_forum_cstr;
  return fsl_schema_forum_cstr;
}
/* end of file schema.c */
/* start of file search.c */
/* end of file ./src/schema.c */
/* start of file ./src/search.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
34465
34466
34467
34468
34469
34470
34471
34472
34473


34474
34475
34476
34477
34478
34479
34480
36365
36366
36367
36368
36369
36370
36371


36372
36373
36374
36375
36376
36377
36378
36379
36380







-
-
+
+







  /* All forum posts are always indexed */
  end:
  return rc;
#endif
}

#undef MARKER
/* end of file search.c */
/* start of file sha1.c */
/* end of file ./src/search.c */
/* start of file ./src/sha1.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
#include <assert.h>
#include <string.h> /* strlen() */
#include <stddef.h> /* NULL on linux */

#include <sys/types.h>
36369
36370
36371
36372
36373
36374
36375
36376
36377


36378
36379
36380
36381
36382
36383
36384
38269
38270
38271
38272
38273
38274
38275


38276
38277
38278
38279
38280
38281
38282
38283
38284







-
-
+
+







    fsl_sha1_init(&ctx);
    fsl_sha1_update(&ctx, zIn,
                    (len<0) ? fsl_strlen(zIn) : (fsl_size_t)len);
    fsl_sha1_final_hex(&ctx, zHex);
    return zHex;
  }
}
/* end of file sha1.c */
/* start of file sha3.c */
/* end of file ./src/sha1.c */
/* start of file ./src/sha3.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
** Copyright (c) 2017 D. Richard Hipp
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the Simplified BSD License (also
37004
37005
37006
37007
37008
37009
37010


























37011
37012
37013
37014
37015


37016
37017
37018
37019
37020
37021
37022
38904
38905
38906
38907
38908
38909
38910
38911
38912
38913
38914
38915
38916
38917
38918
38919
38920
38921
38922
38923
38924
38925
38926
38927
38928
38929
38930
38931
38932
38933
38934
38935
38936
38937
38938
38939


38940
38941
38942
38943
38944
38945
38946
38947
38948







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+



-
-
+
+







    fsl_sha3_end(&ctx);
    rc = fsl_buffer_append(pCksum, ctx.hex, fsl_strlen(ctx.hex));
    return rc;
#endif
  }
}

#undef A00
#undef A01
#undef A02
#undef A03
#undef A04
#undef A10
#undef A11
#undef A12
#undef A13
#undef A14
#undef A20
#undef A21
#undef A22
#undef A23
#undef A24
#undef A30
#undef A31
#undef A32
#undef A33
#undef A34
#undef A40
#undef A41
#undef A42
#undef A43
#undef A44
#undef ROL64

#undef SHA3_BYTEORDER
#undef MARKER
/* end of file sha3.c */
/* start of file strftime.c */
/* end of file ./src/sha3.c */
/* start of file ./src/strftime.c */
/*******************************************************************************
 *  The Elm Mail System  -  $Revision: 1.3 $   $State: Exp $
 *
 * Public-domain relatively quick-and-dirty implemenation of
 * ANSI library routine for System V Unix systems.
 *
 * Arnold Robbins
37619
37620
37621
37622
37623
37624
37625
37626
37627


37628
37629
37630
37631
37632
37633
37634
39545
39546
39547
39548
39549
39550
39551


39552
39553
39554
39555
39556
39557
39558
39559
39560







-
-
+
+







*/
fsl_size_t fsl_strftime_unix(char * dest, fsl_size_t destLen, char const * format,
                             fsl_time_t epochTime, bool convertToLocal){
  time_t orig = (time_t)epochTime;
  struct tm * tim = convertToLocal ? localtime(&orig) : gmtime(&orig);
  return fsl_strftime( dest, destLen, format, tim );
}
/* end of file strftime.c */
/* start of file tag.c */
/* end of file ./src/strftime.c */
/* start of file ./src/tag.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
38258
38259
38260
38261
38262
38263
38264
38265
38266


38267
38268
38269
38270
38271
38272
38273
40184
40185
40186
40187
40188
40189
40190


40191
40192
40193
40194
40195
40196
40197
40198
40199







-
-
+
+







  fsl_deck_finalize(&parent);
  fsl_deck_finalize(&deck);
  return rc;
}
                       

#undef MARKER
/* end of file tag.c */
/* start of file ticket.c */
/* end of file ./src/tag.c */
/* start of file ./src/ticket.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
38287
38288
38289
38290
38291
38292
38293
38294

38295
38296
38297
38298
38299
38300
38301
38302

38303
38304
38305
38306
38307
38308
38309
38310
38311
38312
38313
38314
38315

38316
38317
38318
38319
38320

38321
38322
38323

38324
38325



38326

38327
38328




38329
38330
38331


38332
38333
38334
38335
38336
38337
38338
38339
38340
38341
38342
38343
38344
38345
38346
38347
38348
38349

38350
38351




38352
38353
38354


38355
38356
38357

38358
38359
38360
38361
38362
38363
38364
40213
40214
40215
40216
40217
40218
40219

40220
40221
40222
40223
40224
40225
40226
40227

40228
40229
40230
40231
40232
40233
40234
40235
40236
40237
40238



40239


40240
40241

40242
40243


40244
40245
40246
40247
40248
40249

40250
40251
40252
40253
40254
40255
40256
40257
40258
40259
40260
40261
40262
40263
40264
40265
40266
40267
40268
40269
40270
40271
40272
40273
40274
40275
40276
40277
40278

40279
40280
40281
40282
40283
40284
40285
40286
40287
40288
40289
40290
40291
40292

40293
40294
40295
40296
40297
40298
40299
40300







-
+







-
+










-
-
-
+
-
-


-
+

-
-
+


+
+
+
-
+


+
+
+
+



+
+

















-
+


+
+
+
+



+
+


-
+







  int rc;
  if(!db) return FSL_RC_NOT_A_REPO;
  rc = fsl_cx_exec_multi(f,
                         "DROP TABLE IF EXISTS ticket;"
                         "DROP TABLE IF EXISTS ticketchng;"
                         );
  if(!rc){
    fsl_buffer * const buf = &f->fileContent;
    fsl_buffer * const buf = &f->cache.fileContent;
    fsl_buffer_reuse(buf);
    rc = fsl_cx_schema_ticket(f, buf);
    if(!rc) rc = fsl_cx_exec_multi(f, "%b", buf);
  }
  return rc;
}

static int fsl_tkt_field_id(fsl_list const * jli, const char *zFieldName){
static int fsl__tkt_field_id(fsl_list const * jli, const char *zFieldName){
  int i;
  fsl_card_J const * jc;
  for(i=0; i<(int)jli->used; ++i){
    jc = (fsl_card_J const *)jli->list[i];
    if( !fsl_strcmp(zFieldName, jc->field) ) return i;
  }
  return -1;
}

int fsl__cx_ticket_load_fields(fsl_cx * const f, bool forceReload){
  fsl_stmt q = fsl_stmt_empty;
  int i, rc = 0;
  fsl_list * li = &f->ticket.customFields;
  fsl_list * const li = &f->ticket.customFields;
  fsl_card_J * jc;
  fsl_db * db;
  if(li->used){
    if(!forceReload) return 0;
    fsl__card_J_list_free(li, 0);
    fsl__card_J_list_free(li, false);
    /* Fall through and reload ... */
  }
  if( !(db = fsl_needs_repo(f)) ){
  }else if( !fsl_needs_repo(f) ){
    return FSL_RC_NOT_A_REPO;
  }
  fsl_card_J * jc;
  fsl_stmt q = fsl_stmt_empty;
  int i;
  rc = fsl_db_prepare(db, &q, "PRAGMA table_info(ticket)");
  int rc = fsl_cx_prepare(f, &q, "PRAGMA table_info(ticket)");
  if(!rc) while( FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){
    char const * zFieldName = fsl_stmt_g_text(&q, 1, NULL);
    if(!zFieldName){
      rc = FSL_RC_OOM;
      break;
    }
    f->ticket.hasTicket = 1;
    if( 0==memcmp(zFieldName,"tkt_", 4)){
      if( 0==fsl_strcmp(zFieldName,"tkt_ctime")) f->ticket.hasCTime = 1;
      /* These are core field names, part of every fossil ticket
         table. */
      continue;
    }
    jc = fsl_card_J_malloc(0, zFieldName, NULL);
    if(!jc){
      rc = FSL_RC_OOM;
      break;
    }
    jc->flags = FSL_CARD_J_TICKET;
    rc = fsl_list_append(li, jc);
    if(rc){
      fsl_card_J_free(jc);
      break;
    }
  }
  fsl_stmt_finalize(&q);
  if(rc) goto end;

  rc = fsl_db_prepare(db, &q, "PRAGMA table_info(ticketchng)");
  rc = fsl_cx_prepare(f, &q, "PRAGMA table_info(ticketchng)");
  if(!rc) while( FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){
    char const * zFieldName = fsl_stmt_g_text(&q, 1, NULL);
    if(!zFieldName){
      rc = FSL_RC_OOM;
      break;
    }
    f->ticket.hasChng = 1;
    if( 0==memcmp(zFieldName,"tkt_", 4)){
      if( 0==fsl_strcmp(zFieldName,"tkt_rid")) f->ticket.hasChngRid = 1;
      /* These are core field names, part of every fossil ticketchng
         table. */
      continue;
    }
    if( (i=fsl_tkt_field_id(li, zFieldName)) >= 0){
    if( (i=fsl__tkt_field_id(li, zFieldName)) >= 0){
      jc = (fsl_card_J*)li->list[i];
      jc->flags |= FSL_CARD_J_CHNG;
      continue;
    }
    jc = fsl_card_J_malloc(0, zFieldName, NULL);
    if(!jc){
      rc = FSL_RC_OOM;
38374
38375
38376
38377
38378
38379
38380


















































































































































































































































































































































































































































































































































































































































































































































































































































38381
38382


38383
38384
38385
38386
38387
38388
38389
40310
40311
40312
40313
40314
40315
40316
40317
40318
40319
40320
40321
40322
40323
40324
40325
40326
40327
40328
40329
40330
40331
40332
40333
40334
40335
40336
40337
40338
40339
40340
40341
40342
40343
40344
40345
40346
40347
40348
40349
40350
40351
40352
40353
40354
40355
40356
40357
40358
40359
40360
40361
40362
40363
40364
40365
40366
40367
40368
40369
40370
40371
40372
40373
40374
40375
40376
40377
40378
40379
40380
40381
40382
40383
40384
40385
40386
40387
40388
40389
40390
40391
40392
40393
40394
40395
40396
40397
40398
40399
40400
40401
40402
40403
40404
40405
40406
40407
40408
40409
40410
40411
40412
40413
40414
40415
40416
40417
40418
40419
40420
40421
40422
40423
40424
40425
40426
40427
40428
40429
40430
40431
40432
40433
40434
40435
40436
40437
40438
40439
40440
40441
40442
40443
40444
40445
40446
40447
40448
40449
40450
40451
40452
40453
40454
40455
40456
40457
40458
40459
40460
40461
40462
40463
40464
40465
40466
40467
40468
40469
40470
40471
40472
40473
40474
40475
40476
40477
40478
40479
40480
40481
40482
40483
40484
40485
40486
40487
40488
40489
40490
40491
40492
40493
40494
40495
40496
40497
40498
40499
40500
40501
40502
40503
40504
40505
40506
40507
40508
40509
40510
40511
40512
40513
40514
40515
40516
40517
40518
40519
40520
40521
40522
40523
40524
40525
40526
40527
40528
40529
40530
40531
40532
40533
40534
40535
40536
40537
40538
40539
40540
40541
40542
40543
40544
40545
40546
40547
40548
40549
40550
40551
40552
40553
40554
40555
40556
40557
40558
40559
40560
40561
40562
40563
40564
40565
40566
40567
40568
40569
40570
40571
40572
40573
40574
40575
40576
40577
40578
40579
40580
40581
40582
40583
40584
40585
40586
40587
40588
40589
40590
40591
40592
40593
40594
40595
40596
40597
40598
40599
40600
40601
40602
40603
40604
40605
40606
40607
40608
40609
40610
40611
40612
40613
40614
40615
40616
40617
40618
40619
40620
40621
40622
40623
40624
40625
40626
40627
40628
40629
40630
40631
40632
40633
40634
40635
40636
40637
40638
40639
40640
40641
40642
40643
40644
40645
40646
40647
40648
40649
40650
40651
40652
40653
40654
40655
40656
40657
40658
40659
40660
40661
40662
40663
40664
40665
40666
40667
40668
40669
40670
40671
40672
40673
40674
40675
40676
40677
40678
40679
40680
40681
40682
40683
40684
40685
40686
40687
40688
40689
40690
40691
40692
40693
40694
40695
40696
40697
40698
40699
40700
40701
40702
40703
40704
40705
40706
40707
40708
40709
40710
40711
40712
40713
40714
40715
40716
40717
40718
40719
40720
40721
40722
40723
40724
40725
40726
40727
40728
40729
40730
40731
40732
40733
40734
40735
40736
40737
40738
40739
40740
40741
40742
40743
40744
40745
40746
40747
40748
40749
40750
40751
40752
40753
40754
40755
40756
40757
40758
40759
40760
40761
40762
40763
40764
40765
40766
40767
40768
40769
40770
40771
40772
40773
40774
40775
40776
40777
40778
40779
40780
40781
40782
40783
40784
40785
40786
40787
40788
40789
40790
40791
40792
40793
40794
40795
40796
40797
40798
40799
40800
40801
40802
40803
40804
40805
40806
40807
40808
40809
40810
40811
40812
40813
40814
40815
40816
40817
40818
40819
40820
40821
40822
40823
40824
40825
40826
40827
40828
40829
40830
40831
40832
40833
40834
40835
40836
40837
40838
40839
40840
40841
40842
40843
40844
40845
40846
40847
40848
40849
40850
40851
40852
40853
40854
40855
40856
40857
40858
40859
40860
40861
40862
40863
40864
40865
40866
40867
40868
40869
40870
40871
40872
40873
40874
40875
40876
40877
40878
40879
40880
40881
40882
40883
40884
40885
40886
40887
40888
40889
40890
40891
40892
40893
40894
40895
40896
40897
40898
40899
40900
40901
40902
40903
40904
40905
40906
40907
40908
40909
40910
40911
40912
40913
40914
40915
40916
40917
40918
40919
40920
40921
40922
40923
40924
40925
40926
40927
40928
40929
40930
40931
40932
40933
40934
40935
40936
40937
40938
40939
40940
40941
40942
40943
40944
40945
40946
40947
40948
40949
40950
40951
40952
40953
40954
40955
40956
40957
40958
40959
40960
40961
40962
40963
40964
40965
40966
40967
40968
40969
40970
40971
40972
40973
40974
40975
40976
40977
40978
40979
40980
40981
40982
40983
40984
40985
40986
40987
40988
40989
40990
40991
40992
40993
40994
40995
40996
40997
40998
40999
41000
41001
41002
41003
41004
41005
41006
41007
41008
41009
41010
41011
41012
41013
41014
41015
41016
41017
41018
41019
41020
41021
41022
41023
41024
41025
41026
41027
41028
41029
41030
41031
41032
41033
41034
41035
41036
41037
41038
41039
41040
41041
41042
41043
41044
41045
41046
41047
41048
41049
41050
41051
41052
41053
41054
41055
41056
41057
41058
41059
41060
41061
41062
41063
41064
41065
41066
41067
41068
41069
41070
41071
41072
41073
41074
41075
41076
41077
41078
41079
41080
41081
41082
41083
41084
41085
41086
41087
41088
41089
41090
41091
41092
41093
41094
41095
41096
41097
41098
41099
41100
41101
41102
41103
41104
41105
41106
41107
41108
41109
41110
41111
41112
41113
41114
41115
41116
41117
41118
41119
41120
41121
41122
41123
41124
41125
41126
41127
41128
41129
41130
41131
41132
41133
41134


41135
41136
41137
41138
41139
41140
41141
41142
41143







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+







  fsl_stmt_finalize(&q);
  end:
  if(!rc){
    fsl_list_sort(li, fsl__qsort_cmp_J_cards);
  }
  return rc;
}

static int fsl__ticket_insert(fsl_deck * const d, fsl_id_t tktId,
                              fsl_id_t * const tgtId){
  /* Derived from fossil(1) tkt.c:ticket_insert() */;
  fsl_cx * const f = d->f;
  fsl_id_t const rid = d->rid;
  int rc = 0;
  fsl_buffer * const sql1 = fsl__cx_scratchpad(f);
  fsl_buffer * const sql2 = fsl__cx_scratchpad(f);
  fsl_buffer * const sql3 = fsl__cx_scratchpad(f);
  fsl_db * const db = fsl_cx_db_repo(f);
  fsl_list const * const cf = &f->ticket.customFields;
  fsl_size_t i;
  //char const * zMimetype = NULL;
  fsl_stmt q = fsl_stmt_empty;
  char aUsed[cf->used];
  assert(rid>0 && f!=NULL && db);
  if(0==tktId){
    rc = fsl_cx_exec_multi(f, "INSERT INTO ticket(tkt_uuid, tkt_mtime) "
                           "VALUES(%Q, 0)", d->K);
    if(rc) goto end;
    tktId = fsl_db_last_insert_id(db);
  }
  rc = fsl_buffer_append(sql1, "UPDATE OR REPLACE ticket SET tkt_mtime=?1", -1);
  if(0==rc && f->ticket.hasCTime){
    rc = fsl_buffer_append(sql1, ", tkt_ctime=coalesce(tkt_ctime,?1)", -1);
  }
  if(rc) goto end;
  memset(aUsed, 0, cf->used);
  for(i = 0; 0==rc && i < d->J.used; ++i){
    fsl_card_J const * const dJC = (fsl_card_J*)d->J.list[i];
    int const j = fsl__tkt_field_id(cf, dJC->field);
    if(j<0){
      /* Ticket has a field which this repo does not have. Skip it. */
      continue;
    }
    aUsed[j] = FSL_CARD_J_TICKET;
    fsl_card_J const * const rJC = (fsl_card_J*)cf->list[j];
    if(rJC->flags & FSL_CARD_J_TICKET){
      if(dJC->append){
        rc = fsl_buffer_appendf(sql1, ", %!Q=coalesce(%!Q,'') || %Q",
                                dJC->field, dJC->field, dJC->value);
      }else{
        rc = fsl_buffer_appendf(sql1, ", %!Q=%Q",
                                dJC->field, dJC->value);
      }
      if(rc) break;
    }
    if(rJC->flags & FSL_CARD_J_CHNG){
      rc = fsl_buffer_appendf(sql2, ",%!Q", dJC->field);
      if(0==rc) rc = fsl_buffer_appendf(sql3, ",%Q", dJC->value);
      if(rc) break;
    }
#if 0
    if(0==fsl_strcmp(dJC->field, "mimetype")){
      zMimetype = dJC->value;
    }
#endif
  }
  if(rc) goto end;
  /* MISSING: a block from fossil(1) tkt.c which extracts backlinks:

  if( rid>0 ){
    for(i=0; i<p->nField; i++){
      const char *zName = p->aField[i].zName;
      const char *zBaseName = zName[0]=='+' ? zName+1 : zName;
      j = fieldId(zBaseName);
      if( j<0 ) continue;
      backlink_extract(p->aField[i].zValue, zMimetype, rid, BKLNK_TICKET,
                       p->rDate, i==0);
    }
  }

  That's not critical for core ticket functionality.
  */
  rc = fsl_buffer_appendf(sql1, " WHERE tkt_id=%" FSL_ID_T_PFMT, tktId);
  if(rc) goto end;
  rc = fsl_cx_prepare(f, &q, "%b", sql1);
  if(rc) goto end;
  rc = fsl_stmt_bind_step(&q, "f", d->D);
  fsl_stmt_finalize(&q);
  if(rc) goto end;
  fsl_buffer_reuse(sql1);
  if(f->ticket.hasChngRid || sql2->used){
    bool fromTkt = false;
    if(f->ticket.hasChngRid){
      rc = fsl_buffer_append(sql2, ",tkt_rid", -1);
      if(0==rc) rc = fsl_buffer_appendf(sql3, ",%" FSL_ID_T_PFMT, d->rid);
      if(rc) goto end;
    }
    for(i = 0; 0==rc &&  i < cf->used; ++i){
      fsl_card_J const * const rJC = (fsl_card_J*)cf->list[i];
      if(0==aUsed[i] && (rJC->flags & FSL_CARD_J_BOTH)==FSL_CARD_J_BOTH){
        fromTkt = true;
        rc = fsl_buffer_appendf(sql2, ",%!Q", rJC->field);
        if(0==rc) rc = fsl_buffer_appendf(sql3, ",%!Q", rJC->field);
      }
    }
    if(rc) goto end;
    if(fromTkt){
      rc = fsl_cx_prepare(f, &q, "INSERT INTO ticketchng(tkt_id,tkt_mtime%b)"
                          "SELECT %"FSL_ID_T_PFMT",?1%b "
                          "FROM ticket WHERE tkt_id=%"FSL_ID_T_PFMT,
                          sql2, tktId, sql3, tktId);
    }else{
      rc = fsl_cx_prepare(f, &q, "INSERT INTO ticketchng(tkt_id,tkt_mtime%b)"
                          "VALUES(%"FSL_ID_T_PFMT",?1%b)",
                          sql2, tktId, sql3);
    }
    if(0==rc) rc = fsl_stmt_bind_step(&q, "f", d->D);
  }
  end:
  fsl_stmt_finalize(&q);
  fsl__cx_scratchpad_yield(f, sql1);
  fsl__cx_scratchpad_yield(f, sql2);
  fsl__cx_scratchpad_yield(f, sql3);
  *tgtId = tktId;
  return rc;
}

static int fsl__ticket_timeline_entry(fsl_deck * const d, bool isNew, fsl_id_t tagId){
  /* Derived from fossil(1) manifest.c:mainfest_ticket_event() */;
  int rc;
  fsl_buffer * const comment = fsl__cx_scratchpad(d->f);
  fsl_buffer * const brief = fsl__cx_scratchpad(d->f);
  char * zTitle = 0;
  char * zNewStatus = 0;
  fsl_db * const db = fsl_cx_db_repo(d->f);
  fsl_cx * const f = d->f;
  if(!f->ticket.titleColumn){
    assert(!f->ticket.statusColumn);
    rc = fsl_db_get_text(db, &f->ticket.titleColumn, NULL,
             "SELECT coalesce("
             "(SELECT value FROM config WHERE name='ticket-title-expr'),"
             "'title')");
    if(0==rc){
      rc = fsl_db_get_text(db, &f->ticket.statusColumn, NULL,
               "SELECT coalesce("
               "(SELECT value FROM config WHERE name='ticket-status-column'),"
               "'status')");
    }
    if(rc) return fsl_cx_uplift_db_error( f, db );
  }
  rc = fsl_db_get_text(db, &zTitle, NULL,
                       "SELECT coalesce(%!Q,'unknown') "
                       "FROM ticket WHERE tkt_uuid=%Q",
                       f->ticket.titleColumn, d->K);
  if(rc){
    fsl_cx_uplift_db_error(d->f, db);
    goto end;
  }
  if(isNew){
    rc = fsl_buffer_appendf(comment, "New ticket [%!S|%S] <i>%h</i>.",
                            d->K, d->K, zTitle);
    if(0==rc){
      rc = fsl_buffer_appendf(brief, "New ticket [%!S|%S].",
                              d->K, d->K);
    }
    if(rc) goto end;
  }else{
    // Update an existing ticket...
    char * zNewStatus = 0;
    for(fsl_size_t i = 0; i < d->J.used; ++i){
      fsl_card_J const * const jc = (fsl_card_J*)d->J.list[i];
      if(0==fsl_strcmp(jc->field, f->ticket.statusColumn)){
        zNewStatus = jc->value;
        break;
      }
    }
    if(zNewStatus){
      rc = fsl_buffer_appendf(comment, "%h ticket [%!S|%S]: <i>%h</i>",
                              zNewStatus, d->K, d->K, zTitle);
      if(!rc && d->J.used>1){
        rc = fsl_buffer_appendf(comment, " plus %d other change%s",
                                (int)d->J.used-1, d->J.used==2 ? "" : "s");
      }
      if(0==rc) rc = fsl_buffer_appendf(brief, "%h ticket [%!S|%S].",
                                        zNewStatus, d->K, d->K);
      if(rc) goto end;
    }else{
      rc = fsl_db_get_text(db, &zNewStatus, NULL,
                           "SELECT coalesce(%!Q,'unknown') "
                           "FROM ticket WHERE tkt_uuid=%Q",
                           f->ticket.statusColumn, d->K);
      if(rc){
        rc = fsl_cx_uplift_db_error2(f, db, rc);
        goto end;
      }
      rc = fsl_buffer_appendf(comment, "Ticket [%!S|%S] <i>%h</i> "
                              "status still %h with %d other change%s",
                              d->K, d->K, zTitle, zNewStatus, (int)d->J.used,
                              1==d->J.used ? "" : "s");
      fsl_free(zNewStatus);
      if(rc) goto end;
      rc = fsl_buffer_appendf(brief, "Ticket [%!S|%S]: %d change%s",
                              d->K, d->K, (int)d->J.used,
                              1==d->J.used ? "" : "s");
      if(rc) goto end;
    }
  }
  assert(0==rc);
  // MISSING: manifest_create_event_triggers()
  rc = fsl_cx_exec(d->f,
                   "REPLACE INTO event"
                   "(type, tagid, mtime, objid, user, comment, brief) "
                   "VALUES('t', %"FSL_ID_T_PFMT", %"FSL_JULIAN_T_PFMT", "
                   "%"FSL_ID_T_PFMT",%Q,%B,%B)",
                   tagId, d->D, d->rid, d->U, comment, brief);
  end:
  fsl_free(zTitle);
  fsl_free(zNewStatus);
  fsl__cx_scratchpad_yield(d->f, comment);
  fsl__cx_scratchpad_yield(d->f, brief);
  return rc;
}

int fsl__ticket_rebuild(fsl_cx * const f, char const * zTktKCard){
  int rc;
  fsl_id_t tktId;
  fsl_id_t tagId;
  fsl_db * const db = fsl_needs_repo(f);
  fsl_stmt q = fsl_stmt_empty;
  if(!db) return FSL_RC_NOT_A_REPO;
  assert(!f->cache.isCrosslinking);
  rc = fsl__cx_ticket_load_fields(f, false);
  if(rc) goto end;
  else if(!f->ticket.hasTicket) return 0;
  char * const zTag = fsl_mprintf("tkt-%s", zTktKCard);
  if(!zTag){
    rc = FSL_RC_OOM;
    goto end;
  }
  tagId = fsl_tag_id(f, zTag, true);
  fsl_free(zTag);
  if(tagId<0){
    rc = f->error.code;
    assert(0!=rc);
    goto end;
  }
  tktId = fsl_db_g_id(db, 0, "SELECT tkt_id FROM ticket "
                      "WHERE tkt_uuid=%Q", zTktKCard);
  if(tktId>0){
    if(f->ticket.hasChng){
      rc = fsl_cx_exec(f, "DELETE FROM ticketchng "
                       "WHERE tkt_id=%" FSL_ID_T_PFMT,
                       tktId);
    }
    if(!rc) rc = fsl_cx_exec(f, "DELETE FROM ticket "
                             "WHERE tkt_id=%" FSL_ID_T_PFMT,
                             tktId);
    if(rc) goto end;
  }
  tktId = 0;
  rc = fsl_cx_prepare(f, &q, "SELECT rid FROM tagxref "
                      "WHERE tagid=%" FSL_ID_T_PFMT
                      " ORDER BY mtime", tagId);
  int counter = 0;
  /* Potential TODO (fossil does not do this):
     DELETE FROM EVENT WHERE tagid=${tagId} */
  while(0==rc && FSL_RC_STEP_ROW==fsl_stmt_step(&q)){
    fsl_deck deck = fsl_deck_empty;
    fsl_id_t const rid = fsl_stmt_g_id(&q, 0);
    rc = fsl_deck_load_rid(f, &deck, rid, FSL_SATYPE_TICKET);
    if(rc) goto outro;
    assert(deck.rid==rid);
    rc = fsl__ticket_insert(&deck, tktId, &tktId);
    if(0==rc){
      rc = fsl__ticket_timeline_entry(&deck, 0==counter++, tagId);
      if(0==rc) rc = fsl__call_xlink_listeners(&deck);
    }
    outro:
    fsl_deck_finalize(&deck);
  }
  end:
  fsl_stmt_finalize(&q);
  return rc;
}
/* end of file ./src/ticket.c */
/* start of file ./src/udf.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/*************************************************************************
  This file houses fsl_cx-related sqlite3 User Defined Functions (UDFs).
*/
#if !defined(FSL_ENABLE_SQLITE_REGEXP)
#  define FSL_ENABLE_SQLITE_REGEXP 0
#endif
#if FSL_ENABLE_SQLITE_REGEXP
#endif
#include <assert.h>

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)


/**
   SQL function for debugging.
  
   The print() function writes its arguments to fsl_output()
   if the bound fsl_cx->cxConfig.sqlPrint flag is true.
*/
static void fsl_db_sql_print(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  assert(f);
  if( f->cxConfig.sqlPrint ){
    int i;
    for(i=0; i<argc; i++){
      char c = i==argc-1 ? '\n' : ' ';
      fsl_outputf(f, "%s%c", sqlite3_value_text(argv[i]), c);
    }
  }
}

/**
   SQL function to return the number of seconds since 1970.  This is
   the same as strftime('%s','now') but is more compact.
*/
static void fsl_db_now_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  sqlite3_result_int64(context, (sqlite3_int64)time(0));
}

/**
   SQL function to convert a Julian Day to a Unix timestamp.
*/
static void fsl_db_j2u_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  double const jd = (double)sqlite3_value_double(argv[0]);
  sqlite3_result_int64(context, (sqlite3_int64)fsl_julian_to_unix(jd));
}

/**
   SQL function FSL_CKOUT_DIR([bool includeTrailingSlash=1]) returns
   the top-level checkout directory, optionally (by default) with a
   trailing slash. Returns NULL if the fsl_cx instance bound to
   sqlite3_user_data() has no checkout.
*/
static void fsl_db_cx_chkout_dir_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  int const includeSlash = argc
    ? sqlite3_value_int(argv[0])
    : 1;
  if(f && f->ckout.dir && f->ckout.dirLen){
    sqlite3_result_text(context, f->ckout.dir,
                        (int)f->ckout.dirLen
                        - (includeSlash ? 0 : 1),
                        SQLITE_TRANSIENT);
  }else{
    sqlite3_result_null(context);
  }
}


/**
    SQL Function to return the check-in time for a file.
    Requires (vid,fid) RID arguments, as described for
    fsl_mtime_of_manifest_file().
 */
static void fsl_db_checkin_mtime_udf(
                                     sqlite3_context *context,
                                     int argc,
                                     sqlite3_value **argv
){
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  fsl_time_t mtime = 0;
  int rc;
  fsl_id_t vid, fid;
  assert(f);
  vid = (fsl_id_t)sqlite3_value_int(argv[0]);
  fid = (fsl_id_t)sqlite3_value_int(argv[1]);
  rc = fsl_mtime_of_manifest_file(f, vid, fid, &mtime);
  if( rc==0 ){
    sqlite3_result_int64(context, mtime);
  }else{
    sqlite3_result_error(context, "fsl_mtime_of_manifest_file() failed", -1); 
  }
}


/**
   SQL UDF binding for fsl_content_get().

   FSL_CONTENT(RID INTEGER | SYMBOLIC_NAME) returns the
   undeltified/uncompressed content of the [blob] record identified by
   the given RID or symbolic name.
*/
static void fsl_db_content_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * const f = (fsl_cx*)sqlite3_user_data(context);
  fsl_id_t rid = 0;
  char const * arg;
  int rc;
  fsl_buffer b = fsl_buffer_empty;
  assert(f);
  if(1 != argc){
    sqlite3_result_error(context, "Expecting one argument", -1);
    return;
  }
  if(SQLITE_INTEGER==sqlite3_value_type(argv[0])){
    rid = (fsl_id_t)sqlite3_value_int64(argv[0]);
    arg = NULL;
  }else{
    arg = (const char*)sqlite3_value_text(argv[0]);
    if(!arg){
      sqlite3_result_error(context, "Invalid argument", -1);
      return;
    }
    rc = fsl_sym_to_rid(f, arg, FSL_SATYPE_ANY, &rid);
    if(rc) goto cx_err;
    else if(!rid){
      sqlite3_result_error(context, "No blob found", -1);
      return;
    }
  }
  rc = fsl_content_get(f, rid, &b);
  if(rc) goto cx_err;
  /* Curiously, i'm seeing no difference in allocation counts here whether
     we copy the blob here or pass off ownership... */
  sqlite3_result_blob(context, b.mem, (int)b.used, fsl_free);
  b = fsl_buffer_empty;
  return;
  cx_err:
  fsl_buffer_clear(&b);
  assert(f->error.msg.used);
  if(FSL_RC_OOM==rc){
    sqlite3_result_error_nomem(context);
  }else{
    assert(f->error.msg.used);
    sqlite3_result_error(context, (char const *)f->error.msg.mem,
                         (int)f->error.msg.used);
  }
}

/**
   SQL UDF FSL_SYM2RID(SYMBOLIC_NAME) resolves the name to a [blob].[rid]
   value or triggers an error if it cannot be resolved.
 */
static void fsl_db_sym2rid_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * const f = (fsl_cx*)sqlite3_user_data(context);
  char const * arg;
  assert(f);
  if(1 != argc){
    sqlite3_result_error(context, "Expecting one argument", -1);
    return;
  }
  arg = (const char*)sqlite3_value_text(argv[0]);
  if(!arg){
    sqlite3_result_error(context, "Expecting a STRING argument", -1);
  }else{
    fsl_id_t rid = 0;
    int const rc = fsl_sym_to_rid(f, arg, FSL_SATYPE_ANY, &rid);
    if(rc){
      if(FSL_RC_OOM==rc){
        sqlite3_result_error_nomem(context);
      }else{
        assert(f->error.msg.used);
        sqlite3_result_error(context, (char const *)f->error.msg.mem,
                             (int)f->error.msg.used);
      }
      fsl_cx_err_reset(f)
        /* This is arguable but keeps this error from poluting
           down-stream code (seen it happen in unit tests).  The irony
           is, it's very possible/likely that the error will propagate
           back up into f->error at some point.
        */;
    }else{
      assert(rid>0);
      sqlite3_result_int64(context, rid);
    }
  }
}

static void fsl_db_dirpart_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  char const * arg;
  int rc;
  fsl_buffer b = fsl_buffer_empty;
  int fSlash = 0;
  if(argc<1 || argc>2){
    sqlite3_result_error(context,
                         "Expecting (string) or (string,bool) arguments",
                         -1);
    return;
  }
  arg = (const char*)sqlite3_value_text(argv[0]);
  if(!arg){
    sqlite3_result_error(context, "Invalid argument", -1);
    return;
  }
  if(argc>1){
    fSlash = sqlite3_value_int(argv[1]);
  }
  rc = fsl_file_dirpart(arg, -1, &b, fSlash ? 1 : 0);
  if(!rc){
    if(b.used && *b.mem){
#if 0
      sqlite3_result_text(context, (char const *)b.mem,
                          (int)b.used, SQLITE_TRANSIENT);
#else
      sqlite3_result_text(context, (char const *)b.mem,
                          (int)b.used, fsl_free);
      b = fsl_buffer_empty /* we passed ^^^^^ on ownership of b.mem */;
#endif
    }else{
      sqlite3_result_null(context);
    }
  }else{
    if(FSL_RC_OOM==rc){
      sqlite3_result_error_nomem(context);
    }else{
      sqlite3_result_error(context, "fsl_dirpart() failed!", -1);
    }
  }
  fsl_buffer_clear(&b);
}


/*
   Implement the user() SQL function.  user() takes no arguments and
   returns the user ID of the current user.
*/
static void fsl_db_user_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  assert(f);
  if(f->repo.user){
    sqlite3_result_text(context, f->repo.user, -1, SQLITE_STATIC);
  }else{
    sqlite3_result_null(context);
  }
}

/**
   SQL function:

   fsl_is_enqueued(vfile.id)
   fsl_if_enqueued(vfile.id, X, Y)

   On the commit command, when filenames are specified (in order to do
   a partial commit) the vfile.id values for the named files are
   loaded into the fsl_cx state.  This function looks at that state to
   see if a file is named in that list.

   In the first form (1 argument) return TRUE if either no files are
   named (meaning that all changes are to be committed) or if id is
   found in the list.

   In the second form (3 arguments) return argument X if true and Y if
   false unless Y is NULL, in which case always return X.
*/
static void fsl_db_selected_for_checkin_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  int rc = 0;
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  fsl_id_bag * bag = &f->ckin.selectedIds;
  assert(argc==1 || argc==3);
  if( bag->entryCount ){
    fsl_id_t const iId = (fsl_id_t)sqlite3_value_int64(argv[0]);
    rc = iId ? (fsl_id_bag_contains(bag, iId) ? 1 : 0) : 0;
  }else{
    rc = 1;
  }
  if(1==argc){
    sqlite3_result_int(context, rc);
  }else{
    assert(3 == argc);
    assert( rc==0 || rc==1 );
    if( sqlite3_value_type(argv[2-rc])==SQLITE_NULL ) rc = 1-rc;
    sqlite3_result_value(context, argv[2-rc]);
  }
}

/**
   fsl_match_vfile_or_dir(p1,p2)

   A helper for resolving expressions like:

   WHERE pathname='X' C OR
      (pathname>'X/' C AND pathname<'X0' C)

   i.e. is 'X' a match for the LHS or is it a directory prefix of
   LHS?

   C = empty or COLLATE NOCASE, depending on the case-sensitivity
   setting of the fsl_cx instance associated with
   sqlite3_user_data(context). p1 is typically vfile.pathname or
   vfile.origname, and p2 is the string being compared against that.

   Resolves to NULL if either argument is NULL, 0 if the comparison
   shown above is false, 1 if the comparison is an exact match, or 2
   if p2 is a directory prefix part of p1.
*/
static void fsl_db_match_vfile_or_dir(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * f = (fsl_cx*)sqlite3_user_data(context);
  char const * p1;
  char const * p2;
  fsl_buffer * b = 0;
  int rc = 0;
  assert(f);
  if(2 != argc){
    sqlite3_result_error(context, "Expecting two arguments", -1);
    return;
  }
  p1 = (const char*)sqlite3_value_text(argv[0]);
  p2 = (const char*)sqlite3_value_text(argv[1]);
  if(!p1 || !p2){
    sqlite3_result_null(context);
    return;
  }
  int (*cmp)(char const *, char const *) =
    f->cache.caseInsensitive ? fsl_stricmp : fsl_strcmp;
  if(0==cmp(p1, p2)){
    sqlite3_result_int(context, 1);
    return;
  }
  b = fsl__cx_scratchpad(f);
  rc = fsl_buffer_appendf(b, "%s/", p2);
  if(rc) goto oom;
  else if(cmp(p1, fsl_buffer_cstr(b))>0){
    b->mem[b->used-1] = '0';
    if(cmp(p1, fsl_buffer_cstr(b))<0)
    rc = 2;
  }
  assert(0==rc || 2==rc);
  sqlite3_result_int(context, rc);
  end:
  fsl__cx_scratchpad_yield(f, b);
  return;
  oom:
  sqlite3_result_error_nomem(context);
  goto end;
}

/**
   F(glob-list-name, filename)

   Returns 1 if the 2nd argument matches any glob in the fossil glob
   list named by the first argument. The first argument must be a name
   resolvable via fsl_glob_name_to_category() or an error is
   triggered. The second value is intended to be a string, but NULL is
   accepted (but never matches anything).

   If no match is found, 0 is returned. An empty glob list never matches
   anything.
*/
static void fsl_db_cx_glob_udf(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fsl_cx * const f = (fsl_cx*)sqlite3_user_data(context);
  fsl_list * li = NULL;
  fsl_glob_category_e globType;
  char const * p1;
  char const * p2;
  p2 = (const char*)sqlite3_value_text(argv[1])/*value to check*/;
  if(NULL==p2 || 0==p2[0]){
    sqlite3_result_int(context, 0);
    return;
  }
  p1 = (const char*)sqlite3_value_text(argv[0])/*glob set name*/;
  globType  = fsl_glob_name_to_category(p1);
  if(FSL_GLOBS_INVALID==globType){
    char buf[100] = {0};
    buf[sizeof(buf)-1] = 0;
    fsl_snprintf(buf, (fsl_size_t)sizeof(buf)-1,
                 "Unknown glob pattern name: %#.*s",
                 50, p1 ? p1 : "NULL");
    sqlite3_result_error(context, buf, -1);
    return;
  }
  fsl_cx_glob_list(f, globType, &li, false);
  assert(li);
  sqlite3_result_int(context, fsl_glob_list_matches(li, p2) ? 1 : 0);
}


/**
   Plug in fsl_cx-specific db functionality into the given db handle.
   This must only be passed the MAIN db handle for the context.
*/
int fsl__cx_init_db(fsl_cx * const f, fsl_db * const db){
  int rc;
  assert(!f->dbMain);
  if(f->cxConfig.traceSql){
    fsl_db_sqltrace_enable(db, stdout);
  }
  f->dbMain = db;
  db->role = FSL_DBROLE_MAIN;
  /* This all comes from db.c:db_open()... */
  /* FIXME: check result codes here. */
  sqlite3 * const dbh = db->dbh;
  sqlite3_busy_timeout(dbh, 5000 /* historical value */);
  sqlite3_wal_autocheckpoint(dbh, 1);  /* Set to checkpoint frequently */
  rc = fsl_cx_exec_multi(f,
                         "PRAGMA foreign_keys=OFF;"
                         // ^^^ vmerge table relies on this for its magical
                         // vmerge.id values.
                         //"PRAGMA main.temp_store=FILE;"
                         //"PRAGMA main.journal_mode=TRUNCATE;"
                         // ^^^ note that WAL is not possible on a TEMP db
                         // and OFF leads to undefined behaviour if
                         // ROLLBACK is used!
                         );
  if(rc) goto end;
  sqlite3_create_function(dbh, "now", 0, SQLITE_ANY, 0,
                          fsl_db_now_udf, 0, 0);
  sqlite3_create_function(dbh, "fsl_ci_mtime", 2,
                          SQLITE_ANY | SQLITE_DETERMINISTIC, f,
                          fsl_db_checkin_mtime_udf, 0, 0);
  sqlite3_create_function(dbh, "fsl_user", 0,
                          SQLITE_ANY | SQLITE_DETERMINISTIC, f,
                          fsl_db_user_udf, 0, 0);
  sqlite3_create_function(dbh, "fsl_print", -1,
                          SQLITE_UTF8
                          /* not strictly SQLITE_DETERMINISTIC
                             because it produces output */,
                          f, fsl_db_sql_print,0,0);
  sqlite3_create_function(dbh, "fsl_content", 1,
                          SQLITE_ANY | SQLITE_DETERMINISTIC, f,
                          fsl_db_content_udf, 0, 0);
  sqlite3_create_function(dbh, "fsl_sym2rid", 1,
                          SQLITE_ANY | SQLITE_DETERMINISTIC, f,
                          fsl_db_sym2rid_udf, 0, 0);
  sqlite3_create_function(dbh, "fsl_dirpart", 1,
                          SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL,
                          fsl_db_dirpart_udf, 0, 0);
  sqlite3_create_function(dbh, "fsl_dirpart", 2,
                          SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL,
                          fsl_db_dirpart_udf, 0, 0);
  sqlite3_create_function(dbh, "fsl_j2u", 1,
                          SQLITE_ANY | SQLITE_DETERMINISTIC, NULL,
                          fsl_db_j2u_udf, 0, 0);
  /*
    fsl_i[sf]_selected() both require access to the f's list of
    files being considered for commit.
  */
  sqlite3_create_function(dbh, "fsl_is_enqueued", 1, SQLITE_UTF8, f,
                          fsl_db_selected_for_checkin_udf,0,0 );
  sqlite3_create_function(dbh, "fsl_if_enqueued", 3, SQLITE_UTF8, f,
                          fsl_db_selected_for_checkin_udf,0,0 );

  sqlite3_create_function(dbh, "fsl_ckout_dir", -1,
                          SQLITE_UTF8 | SQLITE_DETERMINISTIC,
                          f, fsl_db_cx_chkout_dir_udf,0,0 );
  sqlite3_create_function(dbh, "fsl_match_vfile_or_dir", 2,
                          SQLITE_UTF8 | SQLITE_DETERMINISTIC,
                          f, fsl_db_match_vfile_or_dir,0,0 );
  sqlite3_create_function(dbh, "fsl_glob", 2,
                          SQLITE_UTF8 | SQLITE_DETERMINISTIC,
                          /* noting that ^^^^^ it's only deterministic
                             for a given statement execution IF no SQL
                             triggers an effect which forces the globs to
                             reload. That "shouldn't ever happen." */
                          f, fsl_db_cx_glob_udf, 0, 0 );

#if 0
  /* functions registered in v1 by db.c:db_open(). */
  /* porting cgi() requires access to the HTTP/CGI
     layer. i.e. this belongs downstream. */
  sqlite3_create_function(dbh, "cgi", 1, SQLITE_ANY, 0, db_sql_cgi, 0, 0);
  sqlite3_create_function(dbh, "cgi", 2, SQLITE_ANY, 0, db_sql_cgi, 0, 0);
  re_add_sql_func(db) /* Requires the regex bits. */;
#endif
  end:
  return rc;
}


#undef MARKER
/* end of file ticket.c */
/* start of file utf8.c */
/* end of file ./src/udf.c */
/* start of file ./src/utf8.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
** Copyright (c) 2017 D. Richard Hipp
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the Simplified BSD License (also
38642
38643
38644
38645
38646
38647
38648
38649

38650

38651
38652
38653
38654
38655
38656
38657
41396
41397
41398
41399
41400
41401
41402

41403

41404
41405
41406
41407
41408
41409
41410
41411







-
+
-
+







        p[-1] = '/';
      }
    }
  }
  return zPath;
#elif defined(__APPLE__) && !defined(WITHOUT_ICONV)
  return fsl_strdup(zUtf8)
    /* Why? Why not just act like Unix? */
    /* Why? Why not just act like Unix?
    ;
       Much later: so that fsl_filename_free() can DTRT. */;
#else
  return (void *)zUtf8;  /* No-op on unix */
#endif
}


char *fsl_getenv(const char *zName){
38692
38693
38694
38695
38696
38697
38698
38699
38700


38701
38702
38703
38704
38705
38706
38707
41446
41447
41448
41449
41450
41451
41452


41453
41454
41455
41456
41457
41458
41459
41460
41461







-
-
+
+







        default:
          break;
      }
    }
    return rc;
  }
}
/* end of file utf8.c */
/* start of file vfile.c */
/* end of file ./src/utf8.c */
/* start of file ./src/vfile.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
38890
38891
38892
38893
38894
38895
38896
38897
38898
38899
38900
38901
38902
38903

38904
38905
38906
38907
38908
38909
38910

38911
38912
38913
38914
38915
38916
38917
38918
38919
38920
38921
38922
38923
38924
38925
38926
38927
38928
38929
38930
38931

38932
38933
38934
38935
38936
38937
38938
41644
41645
41646
41647
41648
41649
41650

41651
41652
41653
41654
41655

41656
41657
41658
41659
41660
41661
41662

41663
41664
41665
41666
41667
41668
41669
41670
41671
41672
41673
41674
41675
41676
41677
41678
41679
41680
41681
41682
41683

41684
41685
41686
41687
41688
41689
41690
41691







-





-
+






-
+




















-
+







}


int fsl_vfile_changes_scan(fsl_cx * const f, fsl_id_t vid, unsigned cksigFlags){
  fsl_stmt * stUpdate = NULL;
  fsl_stmt q = fsl_stmt_empty;
  int rc = 0;
  fsl_db * const db = fsl_needs_ckout(f);
  fsl_fstat fst = fsl_fstat_empty;
  fsl_size_t rootLen;
  fsl_buffer * fileCksum = fsl__cx_scratchpad(f);
  bool const useMtime = (cksigFlags & FSL_VFILE_CKSIG_HASH)==0
    && fsl_config_get_bool(f, FSL_CONFDB_REPO, true, "mtime-changes");
  if(!db) return FSL_RC_NOT_A_CKOUT;
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  assert(f->ckout.dir);
  if(vid<=0) vid = f->ckout.rid;
  assert(vid>=0);
  rootLen = fsl_strlen(f->ckout.dir);
  assert(rootLen);

  rc = fsl_db_transaction_begin(db);
  rc = fsl_cx_transaction_begin(f);
  if(rc) return rc;
  if(f->ckout.rid != vid){
    rc = fsl_vfile_load(f, vid,
                        (FSL_VFILE_CKSIG_KEEP_OTHERS & cksigFlags)
                        ? false : true, NULL);
  }
  if(rc) goto end;

#if 0
  MARKER(("changed/deleted vfile contents post load-from-rid:\n"));
  fsl_db_each( fsl_cx_db_ckout(f), fsl_stmt_each_f_dump, NULL,
               "SELECT vf.id, substr(b.uuid,0,8) hash, chnged, "
               "deleted, vf.pathname "
               "FROM vfile vf LEFT JOIN blob b "
               "ON b.rid=vf.rid "
               "WHERE vf.vid=%"FSL_ID_T_PFMT" "
               "AND (chnged<>0 OR pathname<>origname OR deleted<>0)"
               "ORDER BY vf.id", vid);
#endif

  rc = fsl_db_prepare(db, &q, "SELECT "
  rc = fsl_cx_prepare(f, &q, "SELECT "
                      /*0*/"id,"
                      /*1*/"%Q || pathname,"
                      /*2*/"vfile.mrid,"
                      /*3*/"deleted,"
                      /*4*/"chnged,"
                      /*5*/"uuid,"
                      /*6*/"size,"
39085
39086
39087
39088
39089
39090
39091
39092

39093
39094
39095
39096
39097
39098
39099
39100
39101
39102
39103
39104
39105


39106
39107
39108
39109
39110
39111
39112
39113
39114
39115
39116
39117
39118
39119
39120
39121
39122
39123



39124
39125
39126
39127
39128
39129
39130
39131

39132
39133

39134
39135
39136
39137
39138
39139
39140
39141
39142
39143
41838
41839
41840
41841
41842
41843
41844

41845
41846
41847
41848
41849
41850


41851





41852
41853

41854
41855
41856
41857
41858
41859
41860
41861
41862
41863
41864
41865
41866
41867
41868
41869
41870
41871
41872
41873
41874
41875
41876


41877
41878

41879
41880

41881



41882
41883
41884
41885
41886
41887
41888







-
+





-
-

-
-
-
-
-
+
+
-

















+
+
+



-
-


-
+

-
+
-
-
-







      }else if( origPerm==FSL_FILE_PERM_LINK ){
        changed = FSL_VFILE_CHANGE_NOT_SYMLINK;
      }
    }
#endif
    if( currentMtime!=oldMtime || changed!=oldChanged ){
      if(!stUpdate){
        rc = fsl_db_prepare_cached(db, &stUpdate,
        rc = fsl_cx_prepare_cached(f, &stUpdate,
                                   "UPDATE vfile SET "
                                   "mtime=?1, chnged=?2 "
                                   "WHERE id=?3 "
                                   "/*%s()*/",__func__);
        if(rc) goto end;
      }else{
        fsl_stmt_reset(stUpdate);
      }
      fsl_stmt_bind_int64(stUpdate, 1, currentMtime);
      fsl_stmt_bind_int32(stUpdate, 2, changed);
      fsl_stmt_bind_id(stUpdate, 3, id);
      rc = fsl_stmt_step(stUpdate);
      if(FSL_RC_STEP_DONE!=rc) goto end;
      rc = fsl_stmt_bind_step(stUpdate, "IiR", currentMtime, changed, id);
      if(rc) goto end;
      rc = 0;
      /* MARKER(("UPDATED vfile.(mtime,chnged) for: %s\n", zName)); */
    }
  }/*while(step)*/

#if 0
  MARKER(("changed/deleted vfile contents post vfile scan:\n"));
  fsl_db_each( fsl_cx_db_ckout(f), fsl_stmt_each_f_dump, NULL,
               "SELECT vf.id, substr(b.uuid,0,8) hash, chnged, "
               "deleted, vf.pathname "
               "FROM vfile vf LEFT JOIN blob b "
               "ON b.rid=vf.rid "
               "WHERE vf.vid=%"FSL_ID_T_PFMT" "
               "AND (chnged<>0 OR pathname<>origname OR deleted<>0)"
               "ORDER BY vf.id", vid);
#endif
  end:
  fsl__cx_scratchpad_yield(f, fileCksum);
  if(!rc){
    rc = fsl__ckout_clear_merge_state(f, false);
  }
  if(!rc && (cksigFlags & FSL_VFILE_CKSIG_WRITE_CKOUT_VERSION)
     && (f->ckout.rid != vid)){
    rc = fsl__ckout_version_write(f, vid, 0);
  }else if(rc){
    rc = fsl_cx_uplift_db_error2(f, db, rc);
  }
  if(rc) {
    fsl_db_transaction_rollback(db);
    fsl_cx_transaction_end(f, true);
  }else{
    rc = fsl_db_transaction_commit(db);
    rc = fsl_cx_transaction_end(f, false);
    if(rc){
      rc = fsl_cx_uplift_db_error2(f, db, rc);
    }
  }
  fsl_stmt_cached_yield(stUpdate);
  fsl_stmt_finalize(&q);
  return rc;
}

int fsl__vfile_to_ckout(fsl_cx * const f, fsl_id_t vfileId,
39277
39278
39279
39280
39281
39282
39283
39284
39285


39286
39287
39288
39289
39290
39291
39292
42022
42023
42024
42025
42026
42027
42028


42029
42030
42031
42032
42033
42034
42035
42036
42037







-
-
+
+







  end:
  fsl_buffer_clear(&content);
  fsl_stmt_finalize(&q);
  return rc;
}

#undef MARKER
/* end of file vfile.c */
/* start of file vpath.c */
/* end of file ./src/vfile.c */
/* start of file ./src/vpath.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
39483
39484
39485
39486
39487
39488
39489
39490
39491



39492
39493
39494
39495
39496
39497
39498
42228
42229
42230
42231
42232
42233
42234


42235
42236
42237
42238
42239
42240
42241
42242
42243
42244







-
-
+
+
+







  fsl_stmt_finalize(&s);
  fsl_vpath_clear(path);
  return rc;
}

/**
   Creates, if needed, the [ancestor] table, else clears its
   contents. Returns 
 */
   contents. Returns 0 on success, non-0 on db error (in which case
   f's error state is updated).
*/
static int fsl__init_ancestor(fsl_cx * const f){
  fsl_db * const db = fsl_cx_db_repo(f);
  int rc;
  if(db){
    rc = fsl_db_exec_multi(db,
                           "CREATE TEMP TABLE IF NOT EXISTS ancestor("
                           "  rid INT UNIQUE,"
39721
39722
39723
39724
39725
39726
39727
39728
39729


39730
39731
39732
39733
39734
39735
39736
42467
42468
42469
42470
42471
42472
42473


42474
42475
42476
42477
42478
42479
42480
42481
42482







-
-
+
+







  dberr:
  assert(rc);
  rc = fsl_cx_uplift_db_error2(f, db, rc);
  goto end;
}

#undef MARKER
/* end of file vpath.c */
/* start of file wiki.c */
/* end of file ./src/vpath.c */
/* start of file ./src/wiki.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
39748
39749
39750
39751
39752
39753
39754
39755

39756
39757
39758
39759
39760
39761
39762
39763
39764
39765
39766
39767
39768
39769
39770
39771
39772

39773
39774
39775
39776
39777
39778
39779
39780


39781
39782
39783
39784
39785

39786
39787
39788
39789
39790
39791

39792
39793
39794
39795
39796
39797
39798
39799
39800
39801
39802
39803
39804
39805

39806
39807
39808


39809
39810
39811
39812
39813
39814


39815
39816
39817
39818
39819
39820
39821
39822
39823
39824
39825

39826
39827
39828
39829




39830
39831
39832
39833
39834

39835
39836
39837
39838
39839
39840
39841
39842
39843
39844
39845
39846
39847













39848
39849
39850

39851
39852
39853
39854
39855
39856
39857
42494
42495
42496
42497
42498
42499
42500

42501
42502
42503
42504
42505
42506
42507
42508
42509
42510
42511
42512
42513
42514
42515
42516
42517

42518
42519
42520
42521
42522
42523
42524
42525
42526
42527
42528
42529
42530
42531
42532

42533
42534
42535
42536
42537
42538

42539
42540
42541
42542
42543
42544
42545
42546
42547
42548
42549
42550
42551
42552

42553



42554
42555
42556
42557
42558
42559


42560
42561
42562
42563
42564
42565
42566
42567
42568
42569
42570
42571

42572
42573
42574


42575
42576
42577
42578
42579
42580



42581













42582
42583
42584
42585
42586
42587
42588
42589
42590
42591
42592
42593
42594

42595
42596
42597
42598
42599
42600
42601
42602
42603
42604







-
+
















-
+








+
+




-
+





-
+













-
+
-
-
-
+
+




-
-
+
+










-
+


-
-
+
+
+
+


-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-


+







#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)


int fsl_wiki_names_get( fsl_cx * f, fsl_list * tgt ){
int fsl_wiki_names_get( fsl_cx * const f, fsl_list * const tgt ){
  fsl_db * db = fsl_needs_repo(f);
  if(!f || !tgt) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  else {
    int rc = fsl_db_select_slist( db, tgt,
                                  "SELECT substr(tagname,6) AS name "
                                  "FROM tag "
                                  "WHERE tagname GLOB 'wiki-*' "
                                  "ORDER BY lower(name)");
    if(rc && db->error.code && !f->error.code){
      fsl_cx_uplift_db_error(f, db);
    }
    return rc;
  }
}

int fsl_wiki_latest_rid( fsl_cx * f, char const * pageName, fsl_id_t * rid ){
int fsl_wiki_latest_rid( fsl_cx * const f, char const * pageName, fsl_id_t * const rid ){
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  if(!f || !pageName) return FSL_RC_MISUSE;
  else if(!*pageName) return FSL_RC_RANGE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  else return fsl_db_get_id(db, rid,
                            "SELECT x.rid FROM tag t, tagxref x "
                            "WHERE x.tagid=t.tagid "
                            "AND t.tagname='wiki-%q' "
                            "AND TYPEOF(x.value+0)='integer' "
                            // ^^^^ only 'wiki-%' tags which are wiki pages
                            "ORDER BY mtime DESC LIMIT 1",
                            pageName);
}

bool fsl_wiki_page_exists(fsl_cx * f, char const * pageName){
bool fsl_wiki_page_exists(fsl_cx * const f, char const * pageName){
  fsl_id_t rid = 0;
  return (0==fsl_wiki_latest_rid(f, pageName, &rid))
    && (rid>0);
}

int fsl_wiki_load_latest( fsl_cx * f, char const * pageName, fsl_deck * d ){
int fsl_wiki_load_latest( fsl_cx * const f, char const * pageName, fsl_deck * d ){
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  if(!f || !pageName || !d) return FSL_RC_MISUSE;
  else if(!*pageName) return FSL_RC_RANGE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  else{
    fsl_id_t rid = 0;
    int rc = fsl_wiki_latest_rid(f, pageName, &rid);
    if(rc) return rc;
    else if(0==rid) return FSL_RC_NOT_FOUND;
    return fsl_deck_load_rid( f, d, rid, FSL_SATYPE_WIKI);
  }
}

int fsl_wiki_foreach_page( fsl_cx * f, fsl_deck_visitor_f cb, void * state ){
int fsl_wiki_foreach_page( fsl_cx * const f, fsl_deck_visitor_f cb, void * state ){
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  if(!f || !cb) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  if(!cb) return FSL_RC_MISUSE;
  else if(!fsl_needs_repo(f)) return FSL_RC_NOT_A_REPO;
  else{
    fsl_stmt st = fsl_stmt_empty;
    fsl_stmt names = fsl_stmt_empty;
    int rc;
    char doBreak = 0;
    rc = fsl_db_prepare(db, &names,
    bool doBreak = false;
    rc = fsl_cx_prepare(f, &names,
                        "SELECT substr(tagname,6) AS name "
                        "FROM tag "
                        "WHERE tagname GLOB 'wiki-*' "
                        "ORDER BY lower(name)");
    if(rc) return rc;
    while( !doBreak && !rc
           && (FSL_RC_STEP_ROW==fsl_stmt_step(&names))){
      fsl_size_t nameLen = 0;
      char const * pageName = fsl_stmt_g_text(&names, 0, &nameLen);
      if(!st.stmt){
        rc = fsl_db_prepare(db, &st,
        rc = fsl_cx_prepare(f, &st,
                            "SELECT x.rid AS mrid FROM tag t, tagxref x "
                            "WHERE x.tagid=t.tagid "
                            "AND t.tagname='wiki-'||? "
                            "ORDER BY mtime DESC LIMIT 1");
                            "AND t.tagname='wiki-'||?1 "
                            "AND TYPEOF(x.value+0)='integer' "
                            // ^^^^ only 'wiki-%' tags which are wiki pages
                            "ORDER BY x.mtime DESC LIMIT 1");
        if(rc) goto end;
      }
      rc = fsl_stmt_bind_text(&st, 1, pageName, (fsl_int_t)nameLen, 0);
      if(rc) break;
      rc = fsl_stmt_step(&st);
      rc = fsl_stmt_bind_step(&st, "s", pageName);
      assert(FSL_RC_STEP_ROW==rc);
      if(FSL_RC_STEP_ROW==rc){
        fsl_deck d = fsl_deck_empty;
        fsl_id_t rid = fsl_stmt_g_id(&st, 0);
        rc = fsl_deck_load_rid( f, &d, rid, FSL_SATYPE_WIKI);
        if(!rc){
          rc = cb(f, &d, state);
          if(FSL_RC_BREAK==rc){
            rc = 0;
            doBreak = 1;
          }
        }
        fsl_deck_finalize(&d);
      if(rc!=FSL_RC_STEP_ROW) continue;
      fsl_deck d = fsl_deck_empty;
      fsl_id_t const rid = fsl_stmt_g_id(&st, 0);
      rc = fsl_deck_load_rid( f, &d, rid, FSL_SATYPE_WIKI);
      if(!rc){
        assert(d.rid==rid);
        rc = cb(f, &d, state);
        if(FSL_RC_BREAK==rc){
          rc = 0;
          doBreak = true;
        }
      }
      fsl_deck_finalize(&d);
      }
      fsl_stmt_reset(&st);
    }

    end:
    fsl_stmt_finalize(&st);
    fsl_stmt_finalize(&names);
    return rc;
  }
}

39919
39920
39921
39922
39923
39924
39925
39926
39927


39928
39929
39930
39931
39932
39933
39934
42666
42667
42668
42669
42670
42671
42672


42673
42674
42675
42676
42677
42678
42679
42680
42681







-
-
+
+







    end:
    fsl_deck_finalize(&d);
    return rc;
  }
}

#undef MARKER
/* end of file wiki.c */
/* start of file zip.c */
/* end of file ./src/wiki.c */
/* start of file ./src/zip.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
** Copyright (c) 2017 D. Richard Hipp
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the Simplified BSD License (also
40392
40393
40394
40395
40396
40397
40398
40399

40400
40401
40402
40403
40404
40405
40406
43139
43140
43141
43142
43143
43144
43145

43146
43147
43148
43149
43150
43151
43152
43153







-
+







      }
    }
  }
  return rc;
}


int fsl_repo_zip_sym_to_filename( fsl_cx * f, char const * sym,
int fsl_repo_zip_sym_to_filename( fsl_cx * const f, char const * sym,
                                  char const *  rootDir,
                                  char const * fileName,
                                  fsl_card_F_visitor_f progress,
                                  void * progressState ){
  int rc;
  fsl_deck mf = fsl_deck_empty;
  ZipState zs = ZipState_empty;
40441
40442
40443
40444
40445
40446
40447
40448

40449
40450
40451
40452
40453
40454
40455
43188
43189
43190
43191
43192
43193
43194

43195
43196
43197
43198
43199
43200
43201
43202







-
+







  }

  /**
     Always write the manifest files to the zip, regardless of
     the repo-level settings. This decision is up for debate. */
  if(rc) goto end;
  else {
    fsl_buffer * const bManifest = &f->fileContent;
    fsl_buffer * const bManifest = &f->cache.fileContent;
    fsl_buffer * const bHash = fsl__cx_scratchpad(f);
    fsl_buffer * const bTags = fsl__cx_scratchpad(f);
    fsl_buffer_reuse(bManifest);
    rc = fsl_repo_manifest_write(f, mf.rid, bManifest, bHash, bTags);
    if(rc) goto mf_end;
    rc = fsl_zip_file_add(&zs.z, "manifest", bManifest,
                          FSL_FILE_PERM_REGULAR);
40478
40479
40480
40481
40482
40483
40484
40485
40486


40487
40488
40489
40490
40491


















































































































































































40492
40493
40494
40495




40496


















































































































































































































































































































































































































































































































































40497
40498
40499


40500
40501
40502
40503
40504
40505
40506
40507
40508
40509
43225
43226
43227
43228
43229
43230
43231


43232
43233





43234
43235
43236
43237
43238
43239
43240
43241
43242
43243
43244
43245
43246
43247
43248
43249
43250
43251
43252
43253
43254
43255
43256
43257
43258
43259
43260
43261
43262
43263
43264
43265
43266
43267
43268
43269
43270
43271
43272
43273
43274
43275
43276
43277
43278
43279
43280
43281
43282
43283
43284
43285
43286
43287
43288
43289
43290
43291
43292
43293
43294
43295
43296
43297
43298
43299
43300
43301
43302
43303
43304
43305
43306
43307
43308
43309
43310
43311
43312
43313
43314
43315
43316
43317
43318
43319
43320
43321
43322
43323
43324
43325
43326
43327
43328
43329
43330
43331
43332
43333
43334
43335
43336
43337
43338
43339
43340
43341
43342
43343
43344
43345
43346
43347
43348
43349
43350
43351
43352
43353
43354
43355
43356
43357
43358
43359
43360
43361
43362
43363
43364
43365
43366
43367
43368
43369
43370
43371
43372
43373
43374
43375
43376
43377
43378
43379
43380
43381
43382
43383
43384
43385
43386
43387
43388
43389
43390
43391
43392
43393
43394
43395
43396
43397
43398
43399
43400
43401
43402
43403
43404
43405
43406
43407
43408
43409
43410
43411




43412
43413
43414
43415

43416
43417
43418
43419
43420
43421
43422
43423
43424
43425
43426
43427
43428
43429
43430
43431
43432
43433
43434
43435
43436
43437
43438
43439
43440
43441
43442
43443
43444
43445
43446
43447
43448
43449
43450
43451
43452
43453
43454
43455
43456
43457
43458
43459
43460
43461
43462
43463
43464
43465
43466
43467
43468
43469
43470
43471
43472
43473
43474
43475
43476
43477
43478
43479
43480
43481
43482
43483
43484
43485
43486
43487
43488
43489
43490
43491
43492
43493
43494
43495
43496
43497
43498
43499
43500
43501
43502
43503
43504
43505
43506
43507
43508
43509
43510
43511
43512
43513
43514
43515
43516
43517
43518
43519
43520
43521
43522
43523
43524
43525
43526
43527
43528
43529
43530
43531
43532
43533
43534
43535
43536
43537
43538
43539
43540
43541
43542
43543
43544
43545
43546
43547
43548
43549
43550
43551
43552
43553
43554
43555
43556
43557
43558
43559
43560
43561
43562
43563
43564
43565
43566
43567
43568
43569
43570
43571
43572
43573
43574
43575
43576
43577
43578
43579
43580
43581
43582
43583
43584
43585
43586
43587
43588
43589
43590
43591
43592
43593
43594
43595
43596
43597
43598
43599
43600
43601
43602
43603
43604
43605
43606
43607
43608
43609
43610
43611
43612
43613
43614
43615
43616
43617
43618
43619
43620
43621
43622
43623
43624
43625
43626
43627
43628
43629
43630
43631
43632
43633
43634
43635
43636
43637
43638
43639
43640
43641
43642
43643
43644
43645
43646
43647
43648
43649
43650
43651
43652
43653
43654
43655
43656
43657
43658
43659
43660
43661
43662
43663
43664
43665
43666
43667
43668
43669
43670
43671
43672
43673
43674
43675
43676
43677
43678
43679
43680
43681
43682
43683
43684
43685
43686
43687
43688
43689
43690
43691
43692
43693
43694
43695
43696
43697
43698
43699
43700
43701
43702
43703
43704
43705
43706
43707
43708
43709
43710
43711
43712
43713
43714
43715
43716
43717
43718
43719
43720
43721
43722
43723
43724
43725
43726
43727
43728
43729
43730
43731
43732
43733
43734
43735
43736
43737
43738
43739
43740
43741
43742
43743
43744
43745
43746
43747
43748
43749
43750
43751
43752
43753
43754
43755
43756
43757
43758
43759
43760
43761
43762
43763
43764
43765
43766
43767
43768
43769
43770
43771
43772
43773
43774
43775
43776
43777
43778
43779
43780
43781
43782
43783
43784
43785
43786
43787
43788
43789
43790
43791
43792
43793
43794
43795
43796
43797
43798
43799
43800
43801
43802
43803
43804
43805
43806
43807
43808
43809
43810
43811
43812
43813
43814
43815
43816
43817
43818
43819
43820
43821
43822
43823
43824
43825
43826
43827
43828
43829
43830
43831
43832
43833
43834
43835
43836
43837
43838
43839
43840
43841
43842
43843
43844
43845
43846
43847
43848
43849
43850
43851
43852
43853
43854
43855
43856
43857
43858
43859
43860
43861
43862
43863
43864
43865
43866
43867
43868
43869
43870
43871
43872
43873
43874
43875
43876
43877
43878
43879
43880
43881
43882
43883
43884
43885
43886
43887
43888
43889
43890
43891
43892
43893
43894
43895
43896
43897
43898
43899
43900
43901
43902
43903
43904
43905
43906
43907
43908
43909
43910
43911
43912
43913
43914
43915
43916
43917
43918
43919
43920
43921
43922
43923
43924
43925
43926
43927
43928
43929
43930
43931
43932
43933
43934
43935
43936
43937
43938
43939
43940
43941
43942
43943
43944
43945
43946


43947
43948



43949
43950
43951
43952
43953
43954
43955







-
-
+
+
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
+
+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
+
+
-
-
-







  fsl_deck_clean(&mf);
  return rc;
}



#undef MARKER
/* end of file zip.c */
/* start of file schema_config_cstr.c */
/* end of file ./src/zip.c */
/* start of file ./src/difftk_cstr.c */
/* Binary form of file ../sql/config.sql */
/** @page page_schema_config_cstr Schema: config.sql
@code
-- This file contains the schema for the database that is kept in the
-- ~/.fossil file and that stores information about the users setup.
/** @page page_difftk_cstr difftk.tcl

Binary form of file ./src/difftk.tcl.

*/
/* auto-generated code - edit at your own risk! (Good luck with that!) */
static char const fsl_difftk_cstr_a[] = {
35, 32, 84, 104, 105, 115, 32, 115, 99, 114, 105, 112, 116, 32, 119, 97, 115, 32, 116, 97, 
107, 101, 110, 32, 118, 101, 114, 98, 97, 116, 105, 109, 32, 102, 114, 111, 109, 32, 116, 104, 
101, 32, 70, 111, 115, 115, 105, 108, 32, 83, 67, 77, 32, 112, 114, 111, 106, 101, 99, 116, 
46, 32, 32, 73, 116, 32, 105, 115, 10, 35, 32, 110, 111, 116, 32, 115, 116, 97, 110, 100, 
97, 108, 111, 110, 101, 58, 32, 105, 116, 32, 105, 115, 32, 105, 110, 116, 101, 110, 100, 101, 
100, 32, 116, 111, 32, 98, 101, 32, 101, 109, 98, 101, 100, 100, 101, 100, 32, 105, 110, 32, 
111, 117, 116, 112, 117, 116, 32, 103, 101, 110, 101, 114, 97, 116, 101, 100, 32, 98, 121, 10, 
35, 32, 102, 45, 118, 100, 105, 102, 102, 32, 40, 111, 114, 32, 115, 105, 109, 105, 108, 97, 
114, 41, 46, 10, 115, 101, 116, 32, 112, 114, 111, 103, 32, 123, 10, 112, 97, 99, 107, 97, 
103, 101, 32, 114, 101, 113, 117, 105, 114, 101, 32, 84, 107, 10, 10, 97, 114, 114, 97, 121, 
32, 115, 101, 116, 32, 67, 70, 71, 32, 123, 10, 32, 32, 84, 73, 84, 76, 69, 32, 32, 
32, 32, 32, 32, 123, 70, 111, 115, 115, 105, 108, 32, 68, 105, 102, 102, 125, 10, 32, 32, 
76, 78, 95, 67, 79, 76, 95, 66, 71, 32, 32, 35, 100, 100, 100, 100, 100, 100, 10, 32, 
32, 76, 78, 95, 67, 79, 76, 95, 70, 71, 32, 32, 35, 52, 52, 52, 52, 52, 52, 10, 
32, 32, 84, 88, 84, 95, 67, 79, 76, 95, 66, 71, 32, 35, 102, 102, 102, 102, 102, 102, 
10, 32, 32, 84, 88, 84, 95, 67, 79, 76, 95, 70, 71, 32, 35, 48, 48, 48, 48, 48, 
48, 10, 32, 32, 77, 75, 82, 95, 67, 79, 76, 95, 66, 71, 32, 35, 52, 52, 52, 52, 
52, 52, 10, 32, 32, 77, 75, 82, 95, 67, 79, 76, 95, 70, 71, 32, 35, 100, 100, 100, 
100, 100, 100, 10, 32, 32, 67, 72, 78, 71, 95, 66, 71, 32, 32, 32, 32, 35, 100, 48, 
100, 48, 102, 102, 10, 32, 32, 65, 68, 68, 95, 66, 71, 32, 32, 32, 32, 32, 35, 99, 
48, 102, 102, 99, 48, 10, 32, 32, 82, 77, 95, 66, 71, 32, 32, 32, 32, 32, 32, 35, 
102, 102, 99, 48, 99, 48, 10, 32, 32, 72, 82, 95, 70, 71, 32, 32, 32, 32, 32, 32, 
35, 52, 52, 52, 52, 52, 52, 10, 32, 32, 72, 82, 95, 80, 65, 68, 95, 84, 79, 80, 
32, 52, 10, 32, 32, 72, 82, 95, 80, 65, 68, 95, 66, 84, 77, 32, 56, 10, 32, 32, 
70, 78, 95, 66, 71, 32, 32, 32, 32, 32, 32, 35, 52, 52, 52, 52, 52, 52, 10, 32, 
32, 70, 78, 95, 70, 71, 32, 32, 32, 32, 32, 32, 35, 102, 102, 102, 102, 102, 102, 10, 
32, 32, 70, 78, 95, 80, 65, 68, 32, 32, 32, 32, 32, 53, 10, 32, 32, 69, 82, 82, 
95, 70, 71, 32, 32, 32, 32, 32, 35, 101, 101, 48, 48, 48, 48, 10, 32, 32, 80, 65, 
68, 88, 32, 32, 32, 32, 32, 32, 32, 53, 10, 32, 32, 87, 73, 68, 84, 72, 32, 32, 
32, 32, 32, 32, 56, 48, 10, 32, 32, 72, 69, 73, 71, 72, 84, 32, 32, 32, 32, 32, 
52, 53, 10, 32, 32, 76, 66, 95, 72, 69, 73, 71, 72, 84, 32, 32, 50, 53, 10, 125, 
10, 10, 105, 102, 32, 123, 33, 91, 110, 97, 109, 101, 115, 112, 97, 99, 101, 32, 101, 120, 
105, 115, 116, 115, 32, 116, 116, 107, 93, 125, 32, 123, 10, 32, 32, 105, 110, 116, 101, 114, 
112, 32, 97, 108, 105, 97, 115, 32, 123, 125, 32, 58, 58, 116, 116, 107, 58, 58, 115, 99, 
114, 111, 108, 108, 98, 97, 114, 32, 123, 125, 32, 58, 58, 115, 99, 114, 111, 108, 108, 98, 
97, 114, 10, 32, 32, 105, 110, 116, 101, 114, 112, 32, 97, 108, 105, 97, 115, 32, 123, 125, 
32, 58, 58, 116, 116, 107, 58, 58, 109, 101, 110, 117, 98, 117, 116, 116, 111, 110, 32, 123, 
125, 32, 58, 58, 109, 101, 110, 117, 98, 117, 116, 116, 111, 110, 10, 125, 10, 10, 112, 114, 
111, 99, 32, 100, 101, 104, 116, 109, 108, 32, 123, 120, 125, 32, 123, 10, 32, 32, 115, 101, 
116, 32, 120, 32, 91, 114, 101, 103, 115, 117, 98, 32, 45, 97, 108, 108, 32, 123, 60, 91, 
94, 62, 93, 42, 62, 125, 32, 36, 120, 32, 123, 125, 93, 10, 32, 32, 114, 101, 116, 117, 
114, 110, 32, 91, 115, 116, 114, 105, 110, 103, 32, 109, 97, 112, 32, 123, 38, 97, 109, 112, 
59, 32, 38, 32, 38, 108, 116, 59, 32, 60, 32, 38, 103, 116, 59, 32, 62, 32, 38, 35, 
51, 57, 59, 32, 39, 32, 38, 113, 117, 111, 116, 59, 32, 92, 34, 125, 32, 36, 120, 93, 
10, 125, 10, 10, 112, 114, 111, 99, 32, 99, 111, 108, 115, 32, 123, 125, 32, 123, 10, 32, 
32, 114, 101, 116, 117, 114, 110, 32, 91, 108, 105, 115, 116, 32, 46, 108, 110, 65, 32, 46, 
116, 120, 116, 65, 32, 46, 109, 107, 114, 32, 46, 108, 110, 66, 32, 46, 116, 120, 116, 66, 
93, 10, 125, 10, 10, 112, 114, 111, 99, 32, 99, 111, 108, 84, 121, 112, 101, 32, 123, 99, 
125, 32, 123, 10, 32, 32, 114, 101, 103, 101, 120, 112, 32, 123, 91, 97, 45, 122, 93, 43, 
125, 32, 36, 99, 32, 116, 121, 112, 101, 10, 32, 32, 114, 101, 116, 117, 114, 110, 32, 36, 
116, 121, 112, 101, 10, 125, 10, 10, 112, 114, 111, 99, 32, 103, 101, 116, 76, 105, 110, 101, 
32, 123, 100, 105, 102, 102, 116, 120, 116, 32, 78, 32, 105, 105, 118, 97, 114, 125, 32, 123, 
10, 32, 32, 117, 112, 118, 97, 114, 32, 36, 105, 105, 118, 97, 114, 32, 105, 105, 10, 32, 
32, 105, 102, 32, 123, 36, 105, 105, 62, 61, 36, 78, 125, 32, 123, 114, 101, 116, 117, 114, 
110, 32, 45, 49, 125, 10, 32, 32, 115, 101, 116, 32, 120, 32, 91, 108, 105, 110, 100, 101, 
120, 32, 36, 100, 105, 102, 102, 116, 120, 116, 32, 36, 105, 105, 93, 10, 32, 32, 105, 110, 
99, 114, 32, 105, 105, 10, 32, 32, 114, 101, 116, 117, 114, 110, 32, 36, 120, 10, 125, 10, 
10, 112, 114, 111, 99, 32, 114, 101, 97, 100, 68, 105, 102, 102, 115, 32, 123, 102, 111, 115, 
115, 105, 108, 99, 109, 100, 125, 32, 123, 10, 32, 32, 103, 108, 111, 98, 97, 108, 32, 100, 
105, 102, 102, 116, 120, 116, 10, 32, 32, 105, 102, 32, 123, 33, 91, 105, 110, 102, 111, 32, 
101, 120, 105, 115, 116, 115, 32, 100, 105, 102, 102, 116, 120, 116, 93, 125, 32, 123, 10, 32, 
32, 32, 32, 115, 101, 116, 32, 105, 110, 32, 91, 111, 112, 101, 110, 32, 36, 102, 111, 115, 
115, 105, 108, 99, 109, 100, 32, 114, 93, 10, 32, 32, 32, 32, 102, 99, 111, 110, 102, 105, 
103, 117, 114, 101, 32, 36, 105, 110, 32, 45, 101, 110, 99, 111, 100, 105, 110, 103, 32, 117, 
116, 102, 45, 56, 10, 32, 32, 32, 32, 115, 101, 116, 32, 100, 105, 102, 102, 116, 120, 116, 
32, 91, 115, 112, 108, 105, 116, 32, 91, 114, 101, 97, 100, 32, 36, 105, 110, 93, 32, 92, 
110, 93, 10, 32, 32, 32, 32, 99, 108, 111, 115, 101, 32, 36, 105, 110, 10, 32, 32, 125, 
10, 32, 32, 115, 101, 116, 32, 78, 32, 91, 108, 108, 101, 110, 103, 116, 104, 32, 36, 100, 
105, 102, 102, 116, 120, 116, 93, 10, 32, 32, 115, 101, 116, 32, 105, 105, 32, 48, 10, 32, 
32, 115, 101, 116, 32, 110, 68, 105, 102, 102, 115, 32, 48, 10, 32, 32, 115, 101, 116, 32, 
110, 49, 32, 48, 10, 32, 32, 115, 101, 116, 32, 110, 50, 32, 48, 32, 32, 10, 32, 32, 
97, 114, 114, 97, 121, 32, 115, 101, 116, 32, 119, 105, 100, 116, 104, 115, 32, 123, 116, 120, 
116, 32, 51, 32, 108, 110, 32, 51, 32, 109, 107, 114, 32, 49, 125, 10, 32, 32, 119, 104, 
105, 108, 101, 32, 123, 91, 115, 101, 116, 32, 108, 105, 110, 101, 32, 91, 103, 101, 116, 76, 
105, 110, 101, 32, 36, 100, 105, 102, 102, 116, 120, 116, 32, 36, 78, 32, 105, 105, 93, 93, 
32, 33, 61, 32, 45, 49, 125, 32, 123, 10, 32, 32, 32, 32, 115, 119, 105, 116, 99, 104, 
32, 45, 45, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 101, 32, 48, 93, 
32, 123, 10, 32, 32, 32, 32, 32, 32, 70, 73, 76, 69, 32, 123, 10, 32, 32, 32, 32, 
32, 32, 32, 32, 105, 110, 99, 114, 32, 110, 68, 105, 102, 102, 115, 10, 32, 32, 32, 32, 
32, 32, 32, 32, 102, 111, 114, 101, 97, 99, 104, 32, 119, 120, 32, 91, 108, 105, 115, 116, 
32, 91, 115, 116, 114, 105, 110, 103, 32, 108, 101, 110, 103, 116, 104, 32, 36, 110, 49, 93, 
32, 91, 115, 116, 114, 105, 110, 103, 32, 108, 101, 110, 103, 116, 104, 32, 36, 110, 50, 93, 
93, 32, 123, 10, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 105, 102, 32, 123, 36, 119, 
120, 62, 36, 119, 105, 100, 116, 104, 115, 40, 108, 110, 41, 125, 32, 123, 115, 101, 116, 32, 
119, 105, 100, 116, 104, 115, 40, 108, 110, 41, 32, 36, 119, 120, 125, 10, 32, 32, 32, 32, 
32, 32, 32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, 
110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 102, 110, 32, 92, 110, 32, 45, 
10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 
116, 32, 101, 110, 100, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 101, 32, 
49, 93, 92, 110, 32, 102, 110, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 
32, 46, 109, 107, 114, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 
102, 110, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 66, 
32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 110, 32, 102, 110, 32, 92, 110, 
32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 115, 
101, 114, 116, 32, 101, 110, 100, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 
101, 32, 50, 93, 92, 110, 32, 102, 110, 32, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 
32, 32, 32, 46, 119, 102, 105, 108, 101, 115, 46, 108, 98, 32, 105, 110, 115, 101, 114, 116, 
32, 101, 110, 100, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 105, 110, 101, 32, 50, 
93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 110, 49, 32, 48, 10, 32, 
32, 32, 32, 32, 32, 32, 32, 115, 101, 116, 32, 110, 50, 32, 48, 10, 32, 32, 32, 32, 
32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 83, 75, 73, 80, 32, 123, 10, 32, 32, 32, 
32, 32, 32, 32, 32, 115, 101, 116, 32, 110, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 
108, 105, 110, 101, 32, 49, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 
32, 110, 49, 32, 36, 110, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, 
110, 50, 32, 36, 110, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, 
110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 46, 46, 46, 92, 110, 32, 104, 114, 108, 110, 
10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 
116, 32, 101, 110, 100, 32, 91, 115, 116, 114, 105, 110, 103, 32, 114, 101, 112, 101, 97, 116, 
32, 46, 32, 51, 48, 93, 92, 110, 32, 104, 114, 116, 120, 116, 10, 32, 32, 32, 32, 32, 
32, 32, 32, 46, 109, 107, 114, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 92, 
110, 32, 104, 114, 108, 110, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 66, 32, 
105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 46, 46, 46, 92, 110, 32, 104, 114, 108, 
110, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 116, 120, 116, 66, 32, 105, 110, 115, 101, 
114, 116, 32, 101, 110, 100, 32, 91, 115, 116, 114, 105, 110, 103, 32, 114, 101, 112, 101, 97, 
116, 32, 46, 32, 51, 48, 93, 92, 110, 32, 104, 114, 116, 120, 116, 10, 32, 32, 32, 32, 
32, 32, 125, 10, 32, 32, 32, 32, 32, 32, 67, 79, 77, 32, 123, 10, 32, 32, 32, 32, 
32, 32, 32, 32, 115, 101, 116, 32, 120, 32, 91, 108, 105, 110, 100, 101, 120, 32, 36, 108, 
105, 110, 101, 32, 49, 93, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, 
110, 49, 10, 32, 32, 32, 32, 32, 32, 32, 32, 105, 110, 99, 114, 32, 110, 50, 10, 32, 
32, 32, 32, 32, 32, 32, 32, 46, 108, 110, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 
110, 100, 32, 36, 110, 49, 92, 110, 32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 
116, 120, 116, 65, 32, 105, 110, 115, 101, 114, 116, 32, 101, 110, 100, 32, 36, 120, 92, 110, 
32, 45, 10, 32, 32, 32, 32, 32, 32, 32, 32, 46, 109, 107, 114, 32, 105, 110, 115, 101,