fnc

Check-in Differences
Login

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

Difference From 689182448e To 0.3

2021-10-17 07:16
Bump version number: 0.4 (check-in: 20578f6ca1 user: mark tags: trunk)
2021-10-17 07:15
Add CHANGES for 0.3 (check-in: e231a952cf user: mark tags: trunk, 0.3)
2021-10-16 17:32
Update documentation with new blame command. (check-in: 96b3dbc641 user: mark tags: trunk)
2021-09-04 04:59
Bump version number: 0.3 (check-in: eb1807634c user: mark tags: trunk)
2021-09-04 04:57
Add changes for 0.2. (check-in: 689182448e user: mark tags: trunk, 0.2)
2021-09-03 16:23
Fix subtle bug in diff involving renamed files. (check-in: bbc35e7e69 user: mark tags: trunk)

Added .editorconfig.















1
2
3
4
5
6
7
8
9
10
11
12
13
14
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# EditorConfig (https://editorconfig.com) Configuration for fnc
#
# Following https://fossil-scm.org/fossil/doc/trunk/www/style.wiki

# Defaults for all files
[*]
end_of_line = lf
insert_final_newline = true
indent_style = tab
indent_size = 8

[{Makefile,Makefile.*,*.make,*.make.in}]
indent_style = tab
indent_size = 4

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







**fnc 0.3** 2021-10-17

- add in-app help with H|?|F1 key binding
- improvements to the build system
- decompose build_commits() to make reusable commit_builder() method
- dynamically size header so metadata is not truncated in timeline view
- fix highlight of coloured search results in tmux with A_REVERSE attribute
- correct install path of man pages with 'make install'
- implement 'fnc tree' command to navigate repository tree
- deduplicate code with utility functions fnc_home() and strtonumcheck()
- implement 'fnc path' convenience form of 'fnc timeline path'
- improve error reporting and cleaner code with rc wrapper
- make -R repo option available to 'fnc timeline' 
- make -R repo option compatible with 'fnc timeline path' invocation
- implement 'fnc blame' command with the new libfossil annotate API
- enable accessing the blame interface from the tree view
- fix handling of artifacts with no comment string
- substantial UX and performance improvements by making 'fnc blame' threaded
- fix bug in 'fnc blame --limit|-n' calls when lines were not annotated
- enable handling of master branches not named 'trunk' in 'fnc blame'
- enable accessing the tree interface from the timeline with new 't' key binding
- add '-C|--no-colour' and 'c' key binding to 'fnc blame'
- enhance and standardise parsing of path arguments for all commands

**fnc 0.2** 2021-09-04

- fix iconv lib linking in macOS builds
- use pkg-config for detecting ncurses libs
- prune dead auto.def code
- bypass pkg-config in configure script on macOS systems
- major overhaul to use amalgamation build
29
30
31
32
33
34
35

36
37
38
39
40
53
54
55
56
57
58
59
60
61
62
63
64
65







+





- make display of technote and ticket commits more consistent with fossil(1) ui
- fix bug where diff algorithm choked on binary files
- add coloured output to diff view
- replace BSD-specific getprogname() calls with libf API
- enhance diff view to display more informative control artifact commits
- add Linux support so we now build and run on OpenBSD, macOS, and Linux
- wrap commit comments to the current view width
- implement cmd_diff() to provide the 'fnc diff' interface
- tailor help/usage output to the specified command
- fix invalid memory read in diff routine
- add support for repository fingerprint version 1
- fix line wrap bug that truncated lines in fullscreen mode

Added README.md.
































































































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
95
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
# README

# fnc 0.2a

## A read-only 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 x86 systems (additional platforms
noted inline):

1. OpenBSD 6.8- and 6.9-release
2. macOS 10.15.7 (Catalina) and 11.5.2 (Big Sur)
3. Linux Mint 20.2 (32- and 64-bit ARM)
4. Ubuntu 18.04 running Linux kernel 5.11 (32-bit ARM)
5. Debian GNU/Linux 8, 9, and 10
6. CentOS 6.5

Alpha development notwithstanding, the `timeline` and `diff` commands are
relatively stable; however, several known bugs exist—and there is no commitment
to refrain from breaking changes.

# Build

1. clone the repository
  - `fossil clone https://fnc.bsdbox.org`
2. move into the repository checkout
  - `cd fnc`
3. run the configure script
  - `./configure`
4. build fnc
  - `make`
5. install the `fnc` binary (requires privileges)
  - `doas make install`
6. move into an open Fossil checkout, and run it:
  - `cd ~/museum/repo && fossil open ../repo.fossil && fnc`

This will install the `fnc` executable and man page into `/usr/local/bin` and
`/usr/local/share/man/man1`, respectively. To change the install path, use the
`--prefix` option to `configure`; for example, replacing step 3 with
`./configure --prefix=$HOME` will install the executable and man page into
`~/bin` and `~/man/man1`, respectively. Alternatively, cryptographically signed
binaries for some of the abovementioned platforms are available to [download][3].

# Doc

See `fnc --help` and the [fnc(1)][4] manual page. The following
video briefly demonstrates some of the key bindings in use. [![fnc demo][5]][6]

# Why

`fnc` is heavily inspired by [`tog`][7], which I missed when I left [Got][8]
(Git) behind and started using Fossil. The objective is to provide an
alternative to `fossil ui` without leaving the terminal.

# Problems & Patches

Please submit bug reports via [email][9], the [forum][10], or by creating a new
[ticket][11]. As a rule, all reports should include a bug reproduction recipe;
that is, either (1) the series of steps beginning with `fossil init` to create a
new repository through to the `fnc` command that triggers the unexpected
behaviour; or, if possible, (2) a shell script that contains all necessary
ingredients to reproduce the problem.

Patches are thoughtfully considered and can be sent to the [mailing list][12].
While `fossil patch create` patches are preferred, `diff -u` and `fossil diff` 
patches are also welcomed. Please ensure code complies with OpenBSD's KNF
[style(9)][13], and any patch containing user-visible code addition,
modification, or deletion (i.e., code that impacts user interfaces) should
concomitantly include updating documentation affected by the change.

# Screenshots

![diff split screen](https://fnc.bsdbox.org/uv/resources/img/fnc-diff-splitscreen.png "fnc diff split screen")
![diff renamed file](https://fnc.bsdbox.org/uv/resources/img/fnc-diff-full-file_renamed.png "fnc diff file renamed")
![diff added file](https://fnc.bsdbox.org/uv/resources/img/fnc-diff-split-file_added.png "fnc diff file added")
![diff removed file](https://fnc.bsdbox.org/uv/resources/img/fnc-diff-split-file-removed.png "fnc diff file removed")
![timeline help](https://fnc.bsdbox.org/uv/resources/img/fnc-timeline-help.png "fnc timeline help")

[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
[7]: https://gameoftrees.org/tog.1.html
[8]: https://gameoftrees.org
[9]: mailto:fnc@bsdbox.org
[10]: https://fnc.bsdbox.org/forum
[11]: https://fnc.bsdbox.org/ticket
[12]: https://itac.bsdbox.org/listinfo/fnc
[13]: https://man.openbsd.org/style.9

Changes to auto.def.

1
2
3

4
5
6
7


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
1
2

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

18
19
20
21
22
23
24


-
+




+
+








-







# vim:se syn=tcl:
#
use cc cc-shared cc-lib
use cc cc-shared cc-lib wh-common

options {
    no-debug=0 => "Disable debug build options."
    loud=0 => "Enables 'loud' build mode."
    no-compile-commands=0 =>
      "Disable compile_commands.json support even if detected (possibly incorrectly)."
}


# autosetup interceps 'debug' and 'enable-debug' flags :/
#    prefix:=[get-env HOME /usr/local] -> "Installation prefix."

#cc-check-c11

use wh-common
wh-require-bash
cc-check-sizeof "void *"

if {![cc-check-includes zlib.h] ||
    ![cc-check-function-in-lib compress z]} {
    user-error "Missing functional zlib"
}
65
66
67
68
69
70
71
72

73
74
75
76
77
78
79
66
67
68
69
70
71
72

73
74
75
76
77
78
79
80







-
+







    # ^^^^ causes warning (-Werror breakage) with glibc >=2.20
    define _DEFAULT_SOURCE 1
    define _POSIX_C_SOURCE 200112L
}

# Find some tools
cc-check-tools ar strip
wh-bin-install
wh-bin-define install

set extra_objs {}

if {[find-an-executable cygpath] ne "" || $::tcl_platform(os)=="Windows NT"} {
  set cFlags {}
} else {
  set cFlags {-fPIC}
87
88
89
90
91
92
93
94

95
96
97
98
99
100
101

102
103
104
105
106

107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
88
89
90
91
92
93
94

95







96

97



98



99
100
101







102

103
104
105
106
107
108



109
110
111
112
113
114
115
116
117







-
+
-
-
-
-
-
-
-
+
-

-
-
-
+
-
-
-



-
-
-
-
-
-
-

-
+





-
-
-









    msg-result "Non-debug build."
    set cFlags "$cFlags -O2"
} else {
    msg-result "Debug build enabled. Use --no-debug to build in non-debug mode."
    set cFlags "$cFlags -g -DDEBUG -O0"
}

puts "Checking for compile_commands.json support..."
wh-check-compile-commands no-compile-commands
if {[cctest -lang c -cflags {/dev/null -MJ} -source {}]} {
    msg-result "Compiler supports compile_commands.json."
    define MAKE_COMPILATION_DB yes
} else {
    msg-result "Compiler does not support compile_commands.json."
    define MAKE_COMPILATION_DB no
}


define CFLAGS $cFlags

if {[opt-bool loud]} {
    define BUILD_QUIETLY 0
if {[wh-opt-bool-01 -v loud BUILD_QUIETLY]} {
    puts "Using 'loud' build mode."
} else {
    define BUILD_QUIETLY 1
    puts "Enabling quiet build mode. Use --loud to enable loud mode."
}

# Creates mkefile(-like) file $name from $name.in but explicitly makes
# the output read-only, to avoid inadvertent editing (who, me?).
proc makeFromDotIn {name} {
    catch { exec chmod u+w $name }
    make-template $name.in $name
    catch { exec chmod u-w $name }
}
# Each generated Makefile requires an input file with a .in extension:
set makefiles {
wh-make-from-dot-in {
    config.make
    Makefile
    src/Makefile
    fnc/Makefile
}
foreach {f} $makefiles {
    makeFromDotIn $f
}

if {0} {
    # Achtung: ordering of the -bare/-str options here is important
    # because of the mixed use of strings and integers for #defines...
    make-config-header include/fossil-scm/autoconfig.h \
        -none {DOXYGEN_*} \
        -bare {HAVE_*  FSL_ENABLE_* _DEFAULT_SOURCE _XOPEN_SOURCE} \
        -str {FSL_* PACKAGE_*}
}

Changes to autosetup/wh-common.tcl.

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
95
96
97
98
99


100
101
102
103
104
105
106
107
108
109
110
111
112

113
114
115
116
117
118
119
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
95
96
97
98
99
100
101

102



103
104
105

106
107
108
109





110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166


167
168
169
170
171
172
173
174
175
176
177
178
179
180

181
182
183
184
185
186
187
188





-
+

-
+


+
-
+
-
-
+
+
-

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















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

-
-
+
+
+
+
+
+
+





+


+
+
+
+










-
+







-
+
-
-
-
+
+
+
-


+

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

+




















-
-
+
+












-
+







########################################################################
# Routines for Steve Bennett's autosetup which are common to trees
# managed under the umbrella of wanderinghorse.net.
#
# In the interest of assisting to keep multiple copies of this file
# up to date:
# up to date:s
#
# 1) the "canonical" version is the one in libfossil:
# The "canonical" version is the one in libfossil:
#
#  https://fossil.wanderinghorse.net/r/libfossil/finfo?name=autosetup/wh-common.tcl
########################################################################
#

# 2) Please, dear maintainer, try to keep the following string updated:
#
array set whcache {} ; # used for caching various results.

# Last(?) update: 2021-09-01
########################################################################
# wh-lshift shifts $count elements from the list named $listVar and
# returns them.
#
# Modified slightly from: https://wiki.tcl-lang.org/page/lshift
#
# On an empty list, returns "".
proc wh-lshift {listVar {count 1}} {
    upvar 1 $listVar l
    if {![info exists l]} {
        # make the error message show the real variable name
        error "can't read \"$listVar\": no such variable"
    }
    if {![llength $l]} {
        # error Empty
        return ""
    }
    set r [lrange $l 0 [incr count -1]]
    set l [lreplace $l [set l 0] $count]
    return $r
}

########################################################################
# A proxy for cc-check-function-in-lib which "undoes" any changes that
# routine makes to the LIBS define. Returns the result of
# cc-check-function-in-lib.
proc wh-check-function-in-lib {function libs {otherlibs {}}} {
    set _LIBS [get-define LIBS]
    set found [cc-check-function-in-lib $function $libs $otherlibs]
    define LIBS $_LIBS
    return $found
}

########################################################################
# Look for binary named $binName and `define`s $defName to that full
# path, or an empty string if not found. Returns the value it defines.
# This caches the result for a given $binName value, but if called multiple
# times with a different defName, the 2nd and subsequent defName will not
# get `define`d (patches to fix that are welcomed).
proc wh-bin-define {binName defName} {
    set check [get-define $defName 0]
# This caches the result for a given $binName/$defName combination, so
# calls after the first for a given combination will always return the
# same result.
#
# If defName is empty then "BIN_X" is used, where X is the upper-case
# form of $binName with any '-' characters removed.
proc wh-bin-define {binName {defName {}}} {
    global whcache
    set cacheName "$binName:$defName"
    set check {}
    if {[info exists whcache($cacheName)]} {
        set check $whcache($cacheName)
    }
    msg-checking "Looking for $binName ... "
    if {0 ne $check} {
        msg-result "(cached) $check"
    if {"" ne $check} {
        set lbl $check
        if {" _ 0 _ " eq $check} {
            set lbl "not found"
            set check ""
        }
        msg-result "(cached) $lbl"
        return $check
    }
    set check [find-executable-path $binName]
    if {"" eq $check} {
        msg-result "not found"
        set whcache($cacheName) " _ 0 _ "
    } else {
        msg-result $check
        set whcache($cacheName) $check
    }
    if {"" eq $defName} {
        set defName "BIN_[string toupper [string map {- {}} $binName]]"
    }
    define $defName $check
    return $check
}

########################################################################
# Looks for `bash` binary and dies if not found. On success, defines
# BIN_BASH to the full path to bash and returns that value. We
# _require_ bash because it's the SHELL value used in our makefiles.
proc wh-require-bash {} {
    set bash [wh-bin-define bash BIN_BASH]
    set bash [wh-bin-define bash]
    if {"" eq $bash} {
        user-error "Our Makefiles require the bash shell."
    }
    return $bash
}

########################################################################
# Looks for `pkg-config` binary and returns a full path to it if
# Internal impl for wh-opt-bool-01 and wh-opt-bool-01-invert.
# found, else an empty string. Also defines BIN_PKGCONFIG to the
# (cached) result value.
proc wh-bin-pkgconfig {} {
#
# args = {optName defName invert {descr {}}}
proc wh-opt-bool-01-impl {args} {
    return [wh-bin-define pkg-config BIN_PKGCONFIG]
}


########################################################################
# Looks for `install` binary and returns a full path to it if found,
# else an empty string. Also defines BIN_INSTALL to the (cached)
# result value.
proc wh-bin-install {} {
    return [wh-bin-define install BIN_INSTALL]
# Args: [-v] optName defName {descr {}}
#
# Checks [opt-bool $optName] and does [define $defName X] where X is 0
# for false and 1 for true. descr is an optional [msg-checking]
# argument which defaults to $defName. Returns X.
#
# If args[0] is -v then the boolean semantics are inverted: if
# the option is set, it gets define'd to 0, else 1. Returns the
# define'd value.
proc wh-opt-bool-01 {args} {
    set invert 0
    if {[lindex $args 0] eq "-v"} {
		set invert 1
		set args [lrange $args 1 end]
	}
    set optName [wh-lshift args]
    set defName [wh-lshift args]
    set descr [wh-lshift args]
    if {"" eq $descr} {
        set descr $defName
    }
    set rc 0
    msg-checking "$descr ... "
    if {[opt-bool $optName]} {
        if {0 eq $invert} {
            set rc 1
        } else {
            set rc 0
        }
    } elseif {0 ne $invert} {
        set rc 1
    }
    msg-result $rc
    define $defName $rc
    return $rc
}


########################################################################
# Curses!
#
# Jumps through numerous hoops to try to find ncurses libraries and
# appropriate compilation/linker flags. Returns 0 on failure, 1 on
# success, and defines (either way) LIB_CURSES to the various linker
# flags and CFLAGS_CURSES to the various CFLAGS (both empty strings if
# no lib is found).
#
# This impl prefers to use pkg-config to find ncurses and libpanel
# because various platforms either combine, or not, the wide-char
# versions of those libs into the same library (or not). If no
# pkg-config is available, OR the platform looks like Mac, then we
# simply make an educated guess and hope it works. On Mac pkg-config
# is not sufficient because the core system and either brew or
# macports can contain mismatched versions of ncurses and iconv, so on
# that platform we simply guess from the core system level, ignoring
# brew/macports options.
proc wh-check-ncurses {} {
    puts "Looking for \[n]curses..."
    set pcBin [wh-bin-pkgconfig]
    set pcBin [wh-bin-define pkg-config]
    msg-checking "Looking for \[n]curses... "
    set LIB_CURSES ""
    set CFLAGS_CURSES ""
    set rc 0
    if {"" ne $pcBin && $::tcl_platform(os)!="Darwin"} {
        # Some macOS pkg-config configurations alter library search paths, which make
        # the compiler unable to find lib iconv, so don't use pkg-config on macOS.
        set np ""
        foreach p {ncursesw ncurses} {
            if {[catch {exec $pcBin --exists $p}]} {
                continue
            }
            set np $p
            puts "Using pkg-config curses package \[$p]"
            msg-result "Using pkg-config curses package \[$p]"
            break
        }
        if {"" ne $np} {
            set ppanel ""
            if {"ncursesw" eq $np} {
                if {![catch {exec $pcBin --exists panelw}]} {
                    set ppanel panelw
233
234
235
236
237
238
239
































































302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
        }
    }
    define HAVE_LIBLTDL $HAVE_LIBLTDL
    define HAVE_LIBDL $HAVE_LIBDL
    define LDFLAGS_MODULE_LOADER $LDFLAGS_MODULE_LOADER
    return $rc
}


########################################################################
# Opens the given file, reads all of its content, and returns it.
proc wh-file-content {fname} {
    set fp [open $fname r]
    set rc [read $fp]
    close $fp
    return $rc
}

########################################################################
# Returns the contents of the given file as an array, with the EOL
# stripped from each input line.
proc wh-file-content-list {fname} {
    set fp [open $fname r]
    set rc {}
    while { [gets $fp line] >= 0 } {
        lappend rc $line
    }
    return $rc
}

########################################################################
# Checks the compiler for compile_commands.json support. If passed an
# argument it is assumed to be the name of an autosetup boolean config
# option to explicitly DISABLE the compile_commands.json support.
#
# Returns 1 if supported, else 0. Defines MAKE_COMPILATION_DB to "yes"
# if supported, "no" if not.
proc wh-check-compile-commands {{configOpt {}}} {
    msg-checking "compile_commands.json support... "
    if {"" ne $configOpt && [opt-bool $configOpt]} {
        msg-result "explicitly disabled"
        define MAKE_COMPILATION_DB no
        return 0
    } else {
        if {[cctest -lang c -cflags {/dev/null -MJ} -source {}]} {
            # This test reportedly incorrectly succeeds on one of
            # Martin G.'s older systems.
            msg-result "compiler supports compile_commands.json"
            define MAKE_COMPILATION_DB yes
            return 1
        } else {
            msg-result "compiler does not support compile_commands.json"
            define MAKE_COMPILATION_DB no
            return 0
        }
    }
}

########################################################################
# Uses [make-template] to creates makefile(-like) file $filename from
# $filename.in but explicitly makes the output read-only, to avoid
# inadvertent editing (who, me?).
#
# The argument may be a list of filenames.
proc wh-make-from-dot-in {filename} {
    foreach f $filename {
        catch { exec chmod u+w $f }
        make-template $f.in $f
        catch { exec chmod u-w $f }
    }
}

Changes to fnc/Makefile.in.

1
2
3
4
5
6
7
8
9

10
11
12
13
14
15
16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17









+







all:
include ../subdir-inc.make
LIB_CURSES := @LIB_CURSES@
ifeq (,$(LIB_CURSES))
$(error Expecting LIB_CURSES to be set by the configure process.)
endif
CFLAGS_CURSES := @CFLAGS_CURSES@
LIBF_DIR := $(TOP_DIR)/src
CPPFLAGS += -I$(LIBF_DIR) $(CFLAGS_CURSES)
DISTCLEAN_FILES += Makefile

########################################################################
# To build fnc, we need the curses and pthread libraries.
# -lz is for libfossil
# -liconv is for libfossil on macOS
# -lutil is... ???
# -lm is for sqlite3

Changes to fnc/fnc.1.

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
97
98
99
100
101
102
103
104
105
106
107

108
109


110
111
112








113
114
115

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131

132
133
134
135
136
137
138
139
140



141
142
143
144
145
146
147
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118


119
120
121


122
123
124
125
126
127
128
129
130


131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146

147
148
149
150
151
152
153



154
155
156
157
158
159
160
161
162
163







-
+



+




-
-
+
+

+
+
+
+

-
-
+
+
+




















+
+




















+
+




















+
-
-
+
+

-
-
+
+
+
+
+
+
+
+

-
-
+















-
+






-
-
-
+
+
+







.Op Fl h | -help
.Op Fl v | -version
.Nm
.Cm timeline
.Op Fl z
.Op Fl T Ar tag
.Op Fl b Ar branch
.Op Fl c Ar hash
.Op Fl c Ar commit
.Op Fl n Ar number
.Op Fl t Ar type
.Op Fl u Ar user
.Op Ar path
.Nm
.Cm diff
.Op Fl ciw
.Op Fl x Ar number
.Ar artifact1
.Ar artifact2
.Ar commit1
.Ar commit2
.Nm
.Cm tree
.Op Fl c Ar commit
.Op Ar path
.Nm
.Cm blame
.Op Fl c Ar hash
.Ar file
.Op Fl c Ar commit Op Fl r
.Op Fl n Ar number
.Ar path
.Sh DESCRIPTION
.Nm
is an interactive read-only browser for
.Xr fossil 1
repositories,
and supports multiple views to display repository data:
.Bl -tag -width Ds
.It Timeline view
Display commits from the repository's history in chronologically
descending order.
.Br
If no
.Ar command
or
.Ar arg
are specified,
.Nm
will default to displaying this view.
.It Diff view
Display changes introduced in the specified commit.
.It Tree view
Display tree reflecting the repository state as at the specified commit.
.It Blame view
Display historical attribution of each line in the specified file.
.El
.Pp
.Nm
provides both global and command-specific options and in-app key
bindings.  Global options are specified absent a command name, and
are as follows:
.Bl -tag -width 6v
.It Fl h , -help
Display program help and usage information then exit.
.It Fl v , -version
Display program version then exit.
.El
.Pp
Note that any global options preceding a command name will be
interpreted as the command-specific variant if such an option exists.
.Pp
Global key bindings are as follows:
.Bl -tag -width Ds
.It Cm H, ?, F1
Open in-app help.
.It Cm Tab
Switch focus between open views.
.It Cm f
Toggle the active view between fullscreen and splitscreen mode.  Note
that
.Nm
will open nested views in splitscreen mode if the terminal window is
equal to or greater than 120 columns wide.
.It Cm Q
Immediatey quit
.Nm .
.It Cm q
Quit the active view.
.El
.Pp
Commands available to
.Nm
are as follows:
.Bl -tag -width 4v
.It Cm timeline Oo Fl T | -tag Ar tag Oc Oo Fl b | -branch Ar branch Oc \
Oo Fl c | -commit Ar commit Oc Oo Fl h | -help Oc \
Oo Fl c | -commit Ar hash Oc Oo Fl h | -help Oc Oo Fl n | -limit Ar n Oc \
Oo Fl t | -type Ar type Oc Oo Fl u | -username Ar user Oc Oo Fl z | -utc Oc
Oo Fl n | -limit Ar n Oc  Oo Fl t | -type Ar type Oc \
Oo Fl u | -username Ar user Oc Oo Fl z | -utc Oc  Op Ar path
.Pp
Display commit history of a repository.  This command must be executed
from within or below the repository root; that is,
Display commit history of a repository.  If
.Ar path
is specified, only commits that modified the file(s) at this path will populate
the timeline.  The
.Ar path
may be absolute, relative to the current working directory, or relative to the
repository root.  This command must be executed from within or below the top
level directory of the repository; that is,
.Nm
assumes a local
checkout is open in or above the current working directory.
assumes a local checkout is open in or above the current working directory.
.Pp
If no command is explicitly specified, this command will be executed by
default.
.Pp
Options for
.Cm fnc timeline
are as follows:
.Bl -tag -width Ds
.It Fl T , -tag Ar tag
Only display commits with T cards containing
.Ar tag .
By default,
.Nm
will indiscriminately display all commits irrespective of which T cards
are attached to the commit manifest.
.It Fl b , branch Ar branch
.It Fl b , -branch Ar branch
Display commits that are members of the specified
.Ar branch .
The expected argument is the symbolic name of a branch. By default,
.Nm
will display all commits irrespective of the branch on which they
reside.
.It Fl c , commit Ar hash
Open the timeline from the commit identified by
.Ar hash .
.It Fl c , -commit Ar commit
Open the timeline from the check-in identified by
.Ar commit .
The expected argument is either the name of a branch, which will resolve
to the latest commit on the given branch, or (a unique abbreviated
prefix of) a valid commit UUID SHA1 or SHA3 hash. When this option is
not supplied,
.Nm
will open the timeline to the latest leaf on the trunk of the repository
tree.  Note that this option also accepts
203
204
205
206
207
208
209



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226

227
228
229
230



231
232

233
234

235
236
237
238
239
240
241

242
243
244
245
246
247
248
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244

245
246



247
248
249
250

251
252

253
254
255
256
257
258
259

260
261
262
263
264
265
266
267







+
+
+
















-
+

-
-
-
+
+
+

-
+

-
+






-
+







.It Cm gg, Home
Move selection cursor to the first commit on the timeline (i.e., newest commit
in the repository).
.It Cm Enter, Space
Open a
.Cm diff
view displaying the changeset of the currently selected commit.
.It Cm t
Display the tree of the repository corresponding to the currently selected
commit.
.It Cm /
Prompt to enter a search term to begin searching for commits matching
the pattern provided.  The search term is an extended regular expression,
which is cross-referenced against a commit's comment, the username of
its author, branch, and UUID SHA1 or SHA3 hash.  See
.Xr re_format 7
for regular expression syntax.
.It Cm n
Find the next commit that matches the current search term.  The search
will continue until either a match is found or the earliest commit on
the timeline is consumed.
.It Cm N
Find the previous commit that matches the current search term.  The
search will continue until either a match is found or the latest commit
on the timeline is consumed.
.El
.It Cm diff Oo Fl c | -no-colour Oc Oo Fl h | -help Oc Oo Fl i | -invert \
.It Cm diff Oo Fl C | -no-colour Oc Oo Fl h | -help Oc Oo Fl i | -invert \
Oc Oo Fl w | -whitespace Oc Oo Fl x | -context Ar n Oc \
Ar artifact1 Ar artifact2
Display the differences between two repository artifacts.  Both
.Ar artifact1
Ar commit1 Ar commit2
Display the differences between two commits.  Both
.Ar commit1
and
.Ar artifact2
.Ar commit2
must be of the same type, which is expected to be either (a unique
abbreviated prefix of) a file or commit artifact UUID SHA1 or SHA3 hash,
abbreviated prefix of) a commit artifact UUID SHA1 or SHA3 hash,
a symbolic branch name, or an ISO 8601 formatted date.
.Pp
Options for
.Cm fnc diff
are as follows:
.Bl -tag -width Ds
.It Fl c , -no-colour
.It Fl C , -no-colour
Disable coloured diff output, which is enabled by default on supported
terminals. If this option is not used, colour can be toggled with the
.Sy c
diff view key binding as documented below.
.It Fl h , -help
Display diff command help and usage information then exit.
.It Fl i , -invert
272
273
274
275
276
277
278
279

280
281
282
283
284
285
286
291
292
293
294
295
296
297

298
299
300
301
302
303
304
305







-
+







will display the entire content of newly added or deleted files.
.It Cm w
Toggle display of whitespace-only changes in diff output.
.It Cm Arrow-down, j
Scroll down one line of diff output.
.It Cm Arrow-up, k
Scroll up one line of diff output.
.It Cm Ctrl+f, Page-down
.It Cm Ctrl+f, Page-down, Space
Scroll down one page of diff output.
.It Cm Ctrl+b, Page-up
Scroll up one page of diff output.
.It Cm G, End
Scroll to the end of the view (i.e., last line of diff output).
.It Cm gg, Home
Scroll to the top of the view (i.e., first line of diff output).
302
303
304
305
306
307
308

309
310
311























312























313
314

315
316














317
318


























319










320
321
322
323
324





325
326
327





328
329
330



































































331
332
333
334
335
336
337
338
339
321
322
323
324
325
326
327
328



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376

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


394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440



441
442
443
444
445
446
447

448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523







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

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

-
+


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

+
+
+
+
+
+
+
+
+
+





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


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









regular expression, which is documented in
.Xr re_format 7 .
.It Cm n
Find the next line that matches the current search term.
.It Cm N
Find the previous line that matches the current search term.
.El
.It Cm tree Oo Fl C | -no-colour Oc Oo Fl c | -commit Ar commit Oc \
.It Cm blame Oo Fl c | -commit Ar hash Oc Ar file
Show commit attribution history for each line of the specified
.Ar file .
Oo Fl h | -help Oc Op Ar path
Display hierarchical tree of a repository.  If a
.Ar path
is specified, display tree nodes of this path.  The
.Ar path
may be absolute, relative to the current working directory, or relative to the
repository root.  With no options passed, the tree will reflect the state of the
latest commit on trunk.  This command must be executed from within or below the
top level directory of the repository; that is,
.Nm
assumes a local checkout is open in or above the current working directory.
.Pp
Tree nodes are lexicographically ordered and may be postfixed with an identifier
corresponding to the mode of the file object on disk as returned by
.Xr lstat 2 :
.Bl -column YXZ description
.It / Ta directory
.It * Ta executable
.It @ Ta symbolic link
.El
.Pp
Nodes representing symbolic links are also annotated with the path of the
source file.
.Pp
Options for
.Cm fnc tree
are as follows:
.Bl -tag -width Ds
.It Fl C , -no-colour
Disable coloured output, which is enabled by default on supported terminals.
If this option is not used, colour can be toggled with the
.Sy c
tree view key binding as documented below.
.It Fl c , -commit Ar commit
The displayed tree will reflect the state of the repository as at the check-in
identified by
.Ar commit .
The expected argument is either the name of a branch, which will resolve
to the latest commit on the given branch, or (a unique abbreviated
prefix of) a valid commit UUID SHA1 or SHA3 hash.  Note that this option also
accepts
.Lk https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki \
"Fossil's Special Tags".
.It Fl h , -help
Display tree command help and usage information then exit.
.El
.Pp
Key bindings for
.Cm fnc blame
.Cm fnc tree
are as follows:
.Bl -tag -width Ds
.It Cm Enter, Arrow-right, l
Enter the currently selected directory, or open a
.Cm blame
view of the currently selected file.
.It Cm Backspace, Arrow-left, h
Move up a level to the parent directory.  This is a no-op when in the root tree.
.It Cm Arrow-down, j
Move selection cursor one node down the tree.
.It Cm Arrow-up, k
Move selection cursor one node up the tree.
.It Cm Page-down, Ctrl+f
Move selection cursor one page down the tree.
.It Cm Page-up, Ctrl+b
Move selection cursor one page up the tree.
.It Cm NYI
Not yet implemented.
.It Cm Home, gg
Move selection cursor to the first node in the tree.
.It Cm End, G
Move selection cursor to the last node in the tree.
.It Cm c
Toggle coloured output.
.Nm
will default to displaying the tree in colour.
.It Cm t
Open
.Cm timeline
view for the currently selected tree node.  This will display the timeline of
all commits that involve the versioned file(s) corresponding to the selected
node.
.It Cm i
Show SHA hash UUID for all file nodes displayed in the tree.
.It Cm /
Prompt to enter a search term to begin searching the tree for nodes matching the
entered pattern.  The search term is an extended regular expression, as
documented in
.Xr re_format 7 ,
and is matched against the path of each tree node.
.It Cm n
Find the next tree node that matches the current search pattern.
.It Cm N
Find the previous tree node that matches the current search pattern.
.El
.It Cm blame Oo Fl C | -no-colour Oc \
Oo Fl c | -commit Ar commit Oo Fl r | -reverse Oc Oc Oo Fl h | -help Oc \
Oo Fl n | -limit Ar n Oc Ar path
Show commit attribution history for each line of the file at the specified
.Ar path ,
which may be absolute, relative to the current working directory, or relative to
the repository root.  This command must be executed from within or below the top
level directory of the repository; that is,
.Nm
assumes a local checkout is open in or above the current working directory.
.Pp
Options for
.Cm fnc blame
are as follows:
.Bl -tag -width Ds
.It Fl C , -no-colour
Disable coloured output, which is enabled by default on supported terminals.
If this option is not used, colour can be toggled with the
.Sy c
blame view key binding as documented below.
.It Fl c , -commit Ar hash
Open the timeline from the commit identified by
.Ar hash .
.It Fl c , -commit Ar commit
Start blame of file at the specified
.Ar path
from the check-in identified by
.Ar commit .
The expected argument is either the name of a branch, which will resolve
to the latest commit on the given branch, or (a unique abbreviated
prefix of) a valid commit UUID SHA1 or SHA3 hash.
prefix of) a valid commit UUID SHA1 or SHA3 hash. When this option is
not supplied,
.Nm
will blame the version of the file from the current checkout.  This option also
accepts
.Lk https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki \
"Fossil's Special Tags".
.It Fl h , -help
Display blame command help and usage information then exit.
.It Fl n , -limit Ar n
Limit depth of blame history to
.Ar n
commits.
By default,
.Nm
will traverse the entire historical record of the file, which can be expensive
for large files that span many commits. Use this option for more targeted
annotation.
.It Fl r , -reverse
Reverse annotate the file starting from a historical commit and move forward in
time. That is, rather than show the most recent change to each line, show the
first time each line was modified by a subsequent commit after the specified
.Ar commit .
(Requires \fB\-c\fP|\fB\-\-commit\fP.)
.El
.Pp
Key bindings for
.Cm fnc blame
are as follows:
.Bl -tag -width Ds
.It Cm Arrow-down, j
Move selection cursor down one line.
.It Cm Arrow-up, k
Move selection cursor up one line.
.It Cm Page-down, Ctrl+f
Move selection cursor down one page.
.It Cm Page-up, Ctrl+b
Move selection cursor up one page.
.It Cm Home, gg
Move selection cursor to the first line in the file.
.It Cm End, G
Move selection cursor to the last line in the file.
.It Cm Enter
Display the
.Cm diff
of the commit corresponding to the currently selected line.
.It Cm b
Blame the version of the file corresponding to the commit in the currently
selected line.
.It Cm p
Blame the version of the file corresponding to the parent of the commit in
the currently selected line.
.It Cm B, Backspace
Reload the previous blamed version of the file.
.It Cm c
Toggle coloured output.
.Nm
will default to displaying the blamed file in colour.
.It Cm /
Prompt to enter a search term to begin searching the file for tokens matching
the entered pattern.  The search term is an extended regular expression, as
documented in
.Xr re_format 7 .
.It Cm n
Find the next token that matches the current search pattern.
.It Cm N
Find the previous token that matches the current search pattern.
.El
.El
.Sh EXIT STATUS
.Ex -std fnc
.Sh SEE ALSO
.Xr fossil 1 ,
.Xr re_format 7
.Sh AUTHOR
.An Mark Jamsek Aq Mt mark@jamsek.com

Changes to fnc/fnc.c.

34
35
36
37
38
39
40

41
42
43
44
45
46
47
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48







+







/* Needed for strsep() on glibc >= 2.19. */
#  endif
#endif


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

#ifdef _WIN32
#include <windows.h>
#define ssleep(x) Sleep(x)
#else
#define ssleep(x) usleep((x) * 1000)
#endif
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
97
98
99
100
101
102
103
104
105



















106
107
108

109
110
111
112

113
114
115
116
117
118
119
120


121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

153
154
155
156
157
158


159
160

161

162
163


164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180

181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199




200
201
202
203
204
205
206

207
208
209
210
211
212
213
214


215
216
217
218
219
220
221
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
97
98
99
100
101


102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170




171
172
173
174
175
176
177
178
179
180
181
182
183
184

185
186
187
188
189


190
191
192
193
194

195
196
197
198
199
200
201
202
203
204

205
206
207
208
209
210
211
212
213
214

215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232


233
234
235
236
237
238
239
240
241
242

243
244
245
246
247
248
249


250
251
252
253
254
255
256
257
258







-
+










+
+
+



+




-
+
+
+
+
+
+
+
+


-
-
+
+
+
+














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



+




+








+
+













-
-
-
-














-
+




-
-
+
+


+
-
+


+
+





-










-
+

















-
-
+
+
+
+






-
+






-
-
+
+







#include <regex.h>
#include <signal.h>
#include <wchar.h>
#include <langinfo.h>

#include "libfossil.h"

#define FNC_VERSION	0.2a
#define FNC_VERSION	0.3a

/* Utility macros. */
#define MIN(a, b)	(((a) < (b)) ? (a) : (b))
#define MAX(a, b)	(((a) > (b)) ? (a) : (b))
#if !defined(CTRL)
#define CTRL(key)	((key) & 037)	/* CTRL+<key> input. */
#endif
#define nitems(a)	(sizeof((a)) / sizeof((a)[0]))
#define STRINGIFYOUT(s)	#s
#define STRINGIFY(s)	STRINGIFYOUT(s)
#define CONCATOUT(a, b)	a ## b
#define CONCAT(a, b)	CONCATOUT(a, b)
#define FILE_POSITION	__FILE__ ":" STRINGIFY(__LINE__)

/* Application macros. */
#define PRINT_VERSION	STRINGIFY(FNC_VERSION)
#define DIFF_DEF_CTXT	5		/* Default diff context lines. */
#define DIFF_MAX_CTXT	64		/* Max diff context lines. */
#define SPIN_INTERVAL	200		/* Status line progress indicator. */
#define SPINNER		"\\|/-\0"
#define NULL_DEVICE	"/dev/null"
#define NULL_DEVICELEN (sizeof(NULL_DEVICE)-1)
#define NULL_DEVICELEN	(sizeof(NULL_DEVICE) - 1)
#define KEY_ESCAPE	27
#if DEBUG
#define RC(r, fmt, ...)	fcli_err_set(r, "%s::%s " fmt,			\
			    __func__, FILE_POSITION, __VA_ARGS__)
#else
#define RC(r, fmt, ...) fcli_err_set(r, fmt, __VA_ARGS__)
#endif /* DEBUG */

/* Portability macros. */
#ifdef __OpenBSD__
#define strtol(s, p, b)	strtonum(s, INT_MIN, INT_MAX, (const char **)p)
#ifndef __OpenBSD__
#ifndef HAVE_STRTONUM
#  define strtonum(s, min, max, o) strtol(s, (char **)o, 10)
# endif /* HAVE_STRTONUM */
#endif

#if !defined(__dead)
#define __dead
#endif

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

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

#if defined __linux__
# ifndef strlcat
#  define strlcat(_d, _s, _sz) fnc_strlcat(_d, _s, _sz)
# endif /* strlcat */
# ifndef strlcpy
#  define strlcpy(_d, _s, _sz) fnc_strlcpy(_d, _s, _sz)
# endif /* strlcpy */
#endif /* __linux__ */

__dead static void	usage(void);
static void		usage_timeline(void);
static void		usage_diff(void);
static void		usage_tree(void);
static void		usage_blame(void);
static int		fcli_flag_type_arg_cb(fcli_cliflag const *);
static int		cmd_timeline(fcli_command const *);
static int		cmd_diff(fcli_command const *);
static int		cmd_tree(fcli_command const *);
static int		cmd_blame(fcli_command const *);

/*
 * Singleton initialising global configuration and state for app startup.
 */
static struct fnc_setup {
	/* Global options. */
	const char	*cmdarg;	/* Retain argv[1] for use/err report. */
	const char	*sym;		/* Open view from this symbolic name. */
	const char	*path;		/* Optional path for timeline & tree. */
	int		 err;		/* Indicate fnc error state. */
	bool		 hflag;		/* Flag if --help is requested. */
	bool		 vflag;		/* Flag if --version is requested. */

	/* Timeline options. */
	struct artifact_types {
		const char	**values;
		short		  nitems;
	} *filter_types;		/* Only load commits of <type>. */
	union {
		const char	 *zlimit;
		int limit;
	} nrecords;			/* Number of commits to load. */
	union {
		const char	 *sym;
		fsl_id_t	  rid;
	} start_commit;			/* Open timeline from this commit. */
	const char	*filter_tag;	/* Only load commits with <tag>. */
	const char	*filter_branch;	/* Only load commits from <branch>. */
	const char	*filter_user;	/* Only load commits from <user>. */
	const char	*filter_type;	/* Placeholder for repeatable types. */
	bool		 utc;		/* Display UTC sans user local time. */

	/* Diff options. */
	const char	*context;	/* Number of context lines. */
	bool		 ws;		/* Ignore whitespace-only changes. */
	bool		 nocolour;	/* Disable colour in diff output. */
	bool		 quiet;		/* Disable verbose diff output. */
	bool		 invert;	/* Toggle inverted diff output. */

	/* Blame options. */
	const char	*path;		/* Show blame of REQUIRED <path> arg. */
	bool		 reverse;	/* Reverse annotation; requires sym. */

	/* Command line flags and help. */
	fcli_help_info	  fnc_help;			/* Global help. */
	fcli_cliflag	  cliflags_global[3];		/* Global options. */
	fcli_command	  cmd_args[4];			/* App commands. */
	void		(*fnc_usage_cb[3])(void);	/* Command usage. */
	fcli_command	  cmd_args[5];			/* App commands. */
	void		(*fnc_usage_cb[4])(void);	/* Command usage. */
	fcli_cliflag	  cliflags_timeline[10];	/* Timeline options. */
	fcli_cliflag	  cliflags_diff[7];		/* Diff options. */
	fcli_cliflag	  cliflags_tree[4];		/* Tree options. */
	fcli_cliflag	  cliflags_blame[2];		/* Blame options. */
	fcli_cliflag	  cliflags_blame[6];		/* Blame options. */
} fnc_init = {
	NULL,		/* cmdarg copy of argv[1] to aid usage/error report. */
	NULL,		/* sym(bolic name) of commit to open defaults to tip. */
	NULL,		/* path for tree to open or timeline to find commits. */
	0,		/* err fnc error state. */
	false,		/* hflag if --help is requested. */
	false,		/* vflag if --version is requested. */
	NULL,		/* filter_types defaults to indiscriminate. */
	{0},		/* nrecords defaults to all commits. */
	{0},		/* start_commit defaults to latest leaf. */
	NULL,		/* filter_tag defaults to indiscriminate. */
	NULL,		/* filter_branch defaults to indiscriminate. */
	NULL,		/* filter_user defaults to indiscriminate. */
	NULL,		/* filter_type temporary placeholder. */
	false,		/* utc defaults to off (i.e., show user local time). */
	NULL,		/* context defaults to five context lines. */
	false,		/* ws defaults to acknowledge whitespace. */
	false,		/* nocolour defaults to off (i.e., use diff colours). */
	false,		/* quiet defaults to off (i.e., verbose diff is on). */
	false,		/* invert diff defaults to off. */
	NULL,		/* path blame command required argument. */
	false,		/* reverse annotation defaults to off. */

	{ /* fnc_help global app help details. */
	    "A read-only ncurses browser for Fossil repositories in the "
	    "terminal.", NULL, usage
	},

	{ /* cliflags_global global app options. */
	    FCLI_FLAG_BOOL("h", "help", &fnc_init.hflag,
	    "Display program help and usage then exit."),
	    FCLI_FLAG_BOOL("v", "version", &fnc_init.vflag,
	    "Display program version number and exit."),
	    fcli_cliflag_empty_m
	},

	{ /* cmd_args available app commands. */
	    {"timeline", "Show chronologically descending commit history of "
	    "the repository.", cmd_timeline, fnc_init.cliflags_timeline},
	    {"diff", "Show differences between versioned files in the "
	    "repository.", cmd_diff, fnc_init.cliflags_diff},
	    {"diff", "Show changes to versioned files introduced with a given "
	    "commit.", cmd_diff, fnc_init.cliflags_diff},
	    {"tree", "Show repository tree corresponding to a given commit",
	    cmd_tree, fnc_init.cliflags_tree},
	    {"blame", "Show commit attribution history for each line of a "
	    "file.", cmd_blame, fnc_init.cliflags_blame},
	    {NULL,NULL,NULL, NULL}	/* Sentinel. */
	},

	/* fnc_usage_cb individual command usage details. */
	{&usage_timeline, &usage_diff, &usage_blame},
	{&usage_timeline, &usage_diff, &usage_tree, &usage_blame},

	{ /* cliflags_timeline timeline command related options. */
	    FCLI_FLAG("T", "tag", "<tag>", &fnc_init.filter_tag,
            "Only display commits with T cards containing <tag>."),
	    FCLI_FLAG("b", "branch", "<branch>", &fnc_init.filter_branch,
            "Only display commits that reside on the given <branch>."),
	    FCLI_FLAG("c", "commit", "<sym>", &fnc_init.start_commit.sym,
            "Open the timeline from commit <sym>. Common valid symbols are:\n"
	    FCLI_FLAG("c", "commit", "<commit>", &fnc_init.sym,
            "Open the timeline from <commit>. Common symbols are:\n"
            "\tSHA{1,3} hash\n"
            "\tSHA{1,3} unique prefix\n"
            "\tbranch\n"
            "\ttag:TAG\n"
            "\troot:BRANCH\n"
            "\tISO8601 date\n"
            "\tISO8601 timestamp\n"
240
241
242
243
244
245
246
247

248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268























269
















270
271








272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288

289

290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306

307
308
309
310




311
312
313
314
315
316
317
277
278
279
280
281
282
283

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373

374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390

391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406







-
+





















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

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


+
+
+
+
+
+
+
+

















+
-
+
















-
+




+
+
+
+







            "Only display commits authored by <username>."),
	    FCLI_FLAG_BOOL("z", "utc", &fnc_init.utc,
            "Use UTC (instead of local) time."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_timeline. */

	{ /* cliflags_diff diff command related options. */
	    FCLI_FLAG_BOOL("c", "no-colour", &fnc_init.nocolour,
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
            "Disable coloured diff output, which is enabled by default on\n    "
            "supported terminals. Colour can also be toggled with the 'c' "
            "\n    key binding in diff view when this option is not used."),
	    FCLI_FLAG_BOOL("h", "help", NULL,
            "Display diff command help and usage."),
	    FCLI_FLAG_BOOL("i", "invert", &fnc_init.invert,
            "Invert difference between artifacts. Inversion can also be "
            "toggled\n    with the 'i' key binding in diff view."),
	    FCLI_FLAG_BOOL("q", "quiet", &fnc_init.quiet,
            "Disable verbose diff output; that is, do not output complete"
            " content\n    of newly added or deleted files. Verbosity can also"
            " be toggled with\n    the 'v' key binding in diff view."),
	    FCLI_FLAG_BOOL("w", "whitespace", &fnc_init.ws,
            "Ignore whitespace-only changes when displaying diff. This option "
            "can\n    also be toggled with the 'w' key binding in diff view."),
	    FCLI_FLAG("x", "context", "<n>", &fnc_init.context,
            "Show <n> context lines when displaying diff; <n> is capped at 64."
            "\n    Negative values are a no-op."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_diff. */

	{ /* cliflags_tree tree command related options. */
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
            "Disable coloured output, which is enabled by default on supported"
            "\n    terminals. Colour can also be toggled with the 'c' key "
            "binding when\n    this option is not used."),
	    FCLI_FLAG("c", "commit", "<commit>", &fnc_init.sym,
            "Display tree that reflects repository state as at <commit>.\n"
            "    Common symbols are:"
            "\n\tSHA{1,3} hash\n"
            "\tSHA{1,3} unique prefix\n"
            "\tbranch\n"
            "\ttag:TAG\n"
            "\troot:BRANCH\n"
            "\tISO8601 date\n"
            "\tISO8601 timestamp\n"
            "\t{tip,current,prev,next}\n    "
            "For a complete list of symbols see Fossil's Check-in Names:\n    "
            "https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki"),
	    FCLI_FLAG_BOOL("h", "help", NULL,
            "Display tree command help and usage."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_tree. */

	{ /* cliflags_blame blame command related options. */
	    FCLI_FLAG_BOOL("C", "no-colour", &fnc_init.nocolour,
            "Disable coloured output, which is enabled by default on supported"
            "\n    terminals. Colour can also be toggled with the 'c' key "
            "binding when\n    this option is not used."),
	    FCLI_FLAG("c", "commit", "<commit>", &fnc_init.sym,
            "Start blame of specified file from <commit>. Common symbols are:\n"
            "\tSHA{1,3} hash\n"
            "\tSHA{1,3} unique prefix\n"
            "\tbranch\n"
            "\ttag:TAG\n"
            "\troot:BRANCH\n"
            "\tISO8601 date\n"
            "\tISO8601 timestamp\n"
            "\t{tip,current,prev,next}\n    "
            "For a complete list of symbols see Fossil's Check-in Names:\n    "
            "https://fossil-scm.org/home/doc/trunk/www/checkin_names.wiki"),
	    FCLI_FLAG_BOOL("h", "help", NULL,
            "Display blame command help and usage."),
            FCLI_FLAG("n", "limit", "<n>", &fnc_init.nrecords.zlimit,
	    "Limit depth of blame history to <n> commits. Useful for large "
	    "files\n    with extensive history."),
            FCLI_FLAG_BOOL("r", "reverse", &fnc_init.reverse,
	    "Reverse annotate the file starting from a historical commit. "
	    "Rather\n    than show the most recent change of each line, show "
	    "the first time\n    each line was modified after the specified "
	    "commit. Requires -c|--commit."),
	    fcli_cliflag_empty_m
	}, /* End cliflags_blame. */
};

enum fsl_list_object {
	FNC_ARTIFACT_OBJ,
	FNC_COLOUR_OBJ
};

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

enum fnc_view_id {
	FNC_VIEW_TIMELINE,
	FNC_VIEW_DIFF,
	FNC_VIEW_TREE,
	FNC_VIEW_BLAME,
	FNC_VIEW_BLAME
};

enum fnc_search_mvmnt {
	SEARCH_DONE,
	SEARCH_FORWARD,
	SEARCH_REVERSE
};

enum fnc_search_state {
	SEARCH_WAITING,
	SEARCH_CONTINUE,
	SEARCH_COMPLETE,
	SEARCH_NO_MATCH,
	SEARCH_FOR_END
};

enum diff_colours {
enum fnc_colours {
	FNC_DIFF_META = 1,
	FNC_DIFF_MINUS,
	FNC_DIFF_PLUS,
	FNC_DIFF_CHNK,
	FNC_TREE_LINK,
	FNC_TREE_DIR,
	FNC_TREE_EXEC,
	FNC_COMMIT
};

struct fnc_colour {
	regex_t	regex;
	uint8_t	scheme;
};

346
347
348
349
350
351
352


























































353
354
355
356
357
358
359
360
361
362

363
364
365
366





367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382

383
384
385
386
387
388
389
390
391
392
393


394
395
396
397
398
399
400
401
402
403
404




















































































405
406
407
408
409
410
411
412
413
414
415
416
417

418

419
420
421
422
423
424
425
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658

659
660
661
662
663
664
665
666







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










+




+
+
+
+
+
















+











+
+











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













+
-
+







	int				 idx;
};

struct commit_queue {
	struct commit_tailhead	head;
	int			ncommits;
};

/*
 * The following two structs are used to construct the tree of the entire
 * repository; that is, from the root through to all subdirectories and files.
 */
struct fnc_repository_tree {
	struct fnc_repo_tree_node	*head;     /* Head of repository tree */
	struct fnc_repo_tree_node	*tail;     /* Final node in the tree. */
	struct fnc_repo_tree_node	*rootail;  /* Final root level node. */
};

struct fnc_repo_tree_node {
	struct fnc_repo_tree_node	*next;	     /* Next node in tree. */
	struct fnc_repo_tree_node	*prev;	     /* Prev node in tree. */
	struct fnc_repo_tree_node	*parent_dir; /* Dir containing node. */
	struct fnc_repo_tree_node	*sibling;    /* Next node in same dir */
	struct fnc_repo_tree_node	*children;   /* List of node children */
	struct fnc_repo_tree_node	*lastchild;  /* Last child in list. */
	char				*basename;   /* Final path component. */
	char				*path;	     /* Full pathname of node */
	fsl_uuid_str			 uuid;	     /* File artifact hash. */
	mode_t				 mode;	     /* File mode. */
	double				 mtime;	     /* Mod time of file. */
	uint_fast16_t			 pathlen;    /* Length of path. */
	uint_fast16_t			 nparents;   /* Path components sans- */
						     /* -basename. */
};

/*
 * The following two structs represent a given subtree within the repository;
 * for example, the top level tree and all its elements, or the elements of
 * the src/ directory (but not any members of src/ subdirectories).
 */
struct fnc_tree_object {
	struct fnc_tree_entry	*entries;  /* Array of tree entries. */
	int			 nentries; /* Number of tree entries. */
};

struct fnc_tree_entry {
	char			*basename; /* Final component of path. */
	char			*path;	   /* Full pathname of tree entry. */
	fsl_uuid_str		 uuid;	   /* File artifact hash. */
	mode_t			 mode;	   /* File mode. */
	double			 mtime;	   /* Modification time of file. */
	int			 idx;	   /* Index of this tree entry. */
};

/*
 * Each fnc_tree_object that is _not_ the repository root will have a (list of)
 * fnc_parent_tree(s) to be tracked.
 */
struct fnc_parent_tree {
	TAILQ_ENTRY(fnc_parent_tree)	 entry;
	struct fnc_tree_object		*tree;
	struct fnc_tree_entry		*first_entry_onscreen;
	struct fnc_tree_entry		*selected_entry;
	int				 selected_idx;
};

pthread_mutex_t fnc_mutex = PTHREAD_MUTEX_INITIALIZER;

struct fnc_tl_thread_cx {
	struct commit_queue	 *commits;
	struct commit_entry	**first_commit_onscreen;
	struct commit_entry	**selected_commit;
	fsl_db			 *db;
	fsl_stmt		 *q;
	regex_t			 *regex;
	char			 *path;	     /* Match commits involving path. */
	enum fnc_search_state	 *search_status;
	enum fnc_search_mvmnt	 *searching;
	int			  spin_idx;
	int			  ncommits_needed;
	/*
	 * XXX Is there a more elegant solution to retrieving return codes from
	 * thread functions while pinging between, but before we join, threads?
	 */
	int			  rc;
	bool			  endjmp;
	bool			  timeline_end;
	sig_atomic_t		 *quit;
	pthread_cond_t		  commit_consumer;
	pthread_cond_t		  commit_producer;
};

struct fnc_tl_view_state {
	struct fnc_tl_thread_cx	 thread_cx;
	struct commit_queue	 commits;
	struct commit_entry	*first_commit_onscreen;
	struct commit_entry	*last_commit_onscreen;
	struct commit_entry	*selected_commit;
	struct commit_entry	*matched_commit;
	struct commit_entry	*search_commit;
	const char		*curr_ckout_uuid;
	char			*path;	     /* Match commits involving path. */
	int			 selected_idx;
	sig_atomic_t		 quit;
	pthread_t		 thread_id;
};

struct fnc_diff_view_state {
	struct fnc_view			*timeline_view;
	struct fnc_commit_artifact	*selected_commit;
	fsl_buffer			 buf;
	fsl_list			 colours;
	FILE				*f;
	fsl_uuid_str			 id1;
	fsl_uuid_str			 id2;
	int				 first_line_onscreen;
	int				 last_line_onscreen;
	int				 diff_flags;
	int				 context;
	int				 sbs;
	int				 matched_line;
	int				 current_line;
	size_t				 ncols;
	size_t				 nlines;
	off_t				*line_offsets;
	bool				 eof;
	bool				 colour;
	bool				 showmeta;
};

TAILQ_HEAD(fnc_parent_trees, fnc_parent_tree);
struct fnc_tree_view_state {			  /* Parent trees of the- */
	struct fnc_parent_trees		 parents; /* -current subtree. */
	struct fnc_repository_tree	*repo;    /* The repository tree. */
	struct fnc_tree_object		*root;    /* Top level repo tree. */
	struct fnc_tree_object		*tree;    /* Currently displayed tree */
	struct fnc_tree_entry		*first_entry_onscreen;
	struct fnc_tree_entry		*last_entry_onscreen;
	struct fnc_tree_entry		*selected_entry;
	struct fnc_tree_entry		*matched_entry;
	fsl_list			 colours;
	char				*tree_label;  /* Headline string. */
	fsl_uuid_str			 commit_id;
	fsl_id_t			 rid;
	int				 ndisplayed;
	int				 selected_idx;
	bool				 colour;
	bool				 show_id;
};

struct fnc_blame_line {
	fsl_uuid_str	id;
	bool		annotated;
};

struct fnc_blame_cb_cx {
	struct fnc_view		*view;
	struct fnc_blame_line	*lines;
	fsl_uuid_str		 commit_id;
	fsl_uuid_str		 root_commit;
	int			 nlines;
	bool			*quit;
};

typedef int (*fnc_cancel_cb)(void *);

struct fnc_blame_thread_cx {
	struct fnc_blame_cb_cx	*cb_cx;
	fsl_annotate_opt	 blame_opt;
	fnc_cancel_cb		 cancel_cb;
	const char		*path;
	void			*cancel_cx;
	bool			*complete;
};

struct fnc_blame {
	struct fnc_blame_thread_cx	 thread_cx;
	struct fnc_blame_cb_cx		 cb_cx;
	FILE				*f;	/* Non-annotated copy of file */
	struct fnc_blame_line		*lines;
	off_t				*line_offsets;
	off_t				 filesz;
	fsl_id_t			 origin; /* Tip rid for reverse blame */
	int				 nlines;
	int				 ndepth;    /* Limit depth traversal. */
	pthread_t			 thread_id;
};

CONCAT(STAILQ, _HEAD)(fnc_commit_id_queue, fnc_commit_qid);
struct fnc_commit_qid {
	CONCAT(STAILQ, _ENTRY)(fnc_commit_qid) entry;
	fsl_uuid_str	 id;
};

struct fnc_blame_view_state {
	struct fnc_blame		 blame;
	struct fnc_commit_id_queue	 blamed_commits;
	struct fnc_commit_qid		*blamed_commit;
	struct fnc_commit_artifact	*selected_commit;
	fsl_list			 colours;
	fsl_uuid_str			 commit_id;
	char				*path;
	int				 first_line_onscreen;
	int				 last_line_onscreen;
	int				 selected_line;
	int				 matched_line;
	int				 spin_idx;
	bool				 done;
	bool				 blame_complete;
	bool				 eof;
	bool				 colour;
};

TAILQ_HEAD(view_tailhead, fnc_view);
struct fnc_view {
	TAILQ_ENTRY(fnc_view)	 entries;
	WINDOW			*window;
	PANEL			*panel;
	struct fnc_view		*parent;
	struct fnc_view		*child;
	union {
		struct fnc_diff_view_state	diff;
		struct fnc_tl_view_state	timeline;
		struct fnc_tree_view_state	tree;
		/* struct fnc_blame_view_state	blame; */
		struct fnc_blame_view_state	blame;
	} state;
	enum fnc_view_id	 vid;
	enum fnc_search_state	 search_status;
	enum fnc_search_mvmnt	 searching;
	int			 nlines;
	int			 ncols;
	int			 start_ln;
443
444
445
446
447
448
449
450


451
452
453
454
455


456
457
458
459
460
461
462
463
464





465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483

484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502


503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520




































































521
522
523
524
525
526
527
528
529
530
531
532
533


534












535
536
537
538
539
540
541

542
543
544
545
546
547
548
684
685
686
687
688
689
690

691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731

732

733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748


749
750
751
752
753


754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877







-
+
+





+
+









+
+
+
+
+


















-
+
-
















-
-
+
+



-
-













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













+
+

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







+







static volatile sig_atomic_t rec_sigwinch;
static volatile sig_atomic_t rec_sigpipe;
static volatile sig_atomic_t rec_sigcont;

static void		 fnc_show_version(void);
static int		 init_curses(void);
static struct fnc_view	*view_open(int, int, int, int, enum fnc_view_id);
static int		 open_timeline_view(struct fnc_view *);
static int		 open_timeline_view(struct fnc_view *, fsl_id_t,
			    const char *);
static int		 view_loop(struct fnc_view *);
static int		 show_timeline_view(struct fnc_view *);
static void		*tl_producer_thread(void *);
static int		 block_main_thread_signals(void);
static int		 build_commits(struct fnc_tl_thread_cx *);
static int		 commit_builder(struct fnc_commit_artifact **, fsl_id_t,
			    fsl_stmt *);
static int		 signal_tl_thread(struct fnc_view *, int);
static int		 draw_commits(struct fnc_view *);
static void		 parse_emailaddr_username(char **);
static int		 formatln(wchar_t **, int *, const char *, int, int);
static int		 multibyte_to_wchar(const char *, wchar_t **, size_t *);
static int		 write_commit_line(struct fnc_view *,
			    struct fnc_commit_artifact *, int);
static int		 view_input(struct fnc_view **, int *,
			    struct fnc_view *, struct view_tailhead *);
static void		 help(struct fnc_view *);
static void		 padpopup(struct fnc_view *, const char **,
			    const char *);
static void		 centerprint(WINDOW *, int, int, int, const char *,
			    chtype);
static int		 tl_input_handler(struct fnc_view **, struct fnc_view *,
			    int);
static int		 timeline_scroll_down(struct fnc_view *, int);
static void		 timeline_scroll_up(struct fnc_tl_view_state *, int);
static void		 select_commit(struct fnc_tl_view_state *);
static int		 view_is_parent(struct fnc_view *);
static int		 make_splitscreen(struct fnc_view *);
static int		 make_fullscreen(struct fnc_view *);
static int		 view_split_start_col(int);
static int		 view_search_start(struct fnc_view *);
static int		 tl_search_init(struct fnc_view *);
static int		 tl_search_next(struct fnc_view *);
static bool		 find_commit_match(struct fnc_commit_artifact *,
			    regex_t *);
static int		 init_diff_commit(struct fnc_view **, int,
			    struct fnc_commit_artifact *, struct fnc_view *);
static int		 open_diff_view(struct fnc_view *,
			    struct fnc_commit_artifact *, int, bool, bool, bool,
			    struct fnc_view *);
			    struct fnc_view *, bool);
static int		 set_diff_colours(fsl_list *);
static void		 show_diff_status(struct fnc_view *);
static int		 create_diff(struct fnc_diff_view_state *);
static int		 create_changeset(struct fnc_commit_artifact *);
static int		 write_commit_meta(struct fnc_diff_view_state *);
static int		 wrapline(char *, fsl_size_t ncols_avail,
			    struct fnc_diff_view_state *, off_t *);
static int		 add_line_offset(off_t **, size_t *, off_t);
static int		 diff_commit(fsl_buffer *, struct fnc_commit_artifact *,
			    int, int, int);
static int		 diff_checkout(fsl_buffer *, fsl_id_t, int, int, int);
static int		 write_diff_meta(fsl_buffer *, const char *,
			    fsl_uuid_str, const char *, fsl_uuid_str, int,
			    enum fsl_ckout_change_e);
static int		 diff_file(fsl_buffer *, fsl_buffer *, const char *,
			    fsl_uuid_str, const char *, enum fsl_ckout_change_e,
			    int, int, bool);
static int		 diff_non_checkin(fsl_buffer *, struct
			    fnc_commit_artifact *, int, int, int);
static int		 diff_non_checkin(fsl_buffer *,
			    struct fnc_commit_artifact *, int, int, int);
static int		 diff_file_artifact(fsl_buffer *, fsl_id_t,
			    const fsl_card_F *, fsl_id_t, const fsl_card_F *,
			    fsl_ckout_change_e, int, int, int);
static int		 fsl_ckout_file_content(fsl_cx *, char const *,
			    fsl_buffer *);
static int		 show_diff(struct fnc_view *);
static int		 write_diff(struct fnc_view *, char *);
static int		 match_line(const void *, const void *);
static int		 write_matched_line(int *, const char *, int, int,
			    WINDOW *, regmatch_t *);
static void		 draw_vborder(struct fnc_view *);
static int		 diff_input_handler(struct fnc_view **,
			    struct fnc_view *, int);
static int		 set_selected_commit(struct fnc_diff_view_state *,
			    struct commit_entry *);
static int		 diff_search_init(struct fnc_view *);
static int		 diff_search_next(struct fnc_view *);
static int		 view_close(struct fnc_view *);
static int		 map_repo_path(char **);
static bool		 path_is_child(const char *, const char *, size_t);
static int		 path_skip_common_ancestor(char **, const char *,
			    size_t, const char *, size_t);
static bool		 fnc_path_is_root_dir(const char *);
/* static bool		 fnc_path_is_cwd(const char *); */
static int		 browse_commit_tree(struct fnc_view **, int,
			    struct commit_entry *, const char *);
static int		 open_tree_view(struct fnc_view *, const char *,
			    fsl_id_t);
static int		 walk_tree_path(struct fnc_tree_view_state *,
			    struct fnc_repository_tree *,
			    struct fnc_tree_object **, const char *);
static int		 create_repository_tree(struct fnc_repository_tree **,
			    fsl_uuid_str *, fsl_id_t);
static int		 tree_builder(struct fnc_repository_tree *,
			    struct fnc_tree_object **, const char *);
/* static void		 delete_tree_node(struct fnc_tree_entry **, */
/*			    struct fnc_tree_entry *); */
static int		 link_tree_node(struct fnc_repository_tree *,
			    const char *, const char *, fsl_time_t);
static int		 show_tree_view(struct fnc_view *);
static int		 tree_input_handler(struct fnc_view **,
			    struct fnc_view *, int);
static int		 blame_tree_entry(struct fnc_view **, int,
			    struct fnc_tree_entry *, struct fnc_parent_trees *,
			    fsl_uuid_str);
static int		 tree_search_init(struct fnc_view *);
static int		 tree_search_next(struct fnc_view *);
static int		 tree_entry_path(char **, struct fnc_parent_trees *,
			    struct fnc_tree_entry *);
static int		 draw_tree(struct fnc_view *, const char *);
static int		 timeline_tree_entry(struct fnc_view **, int,
			    struct fnc_tree_view_state *);
static void		 tree_scroll_up(struct fnc_tree_view_state *, int);
static void		 tree_scroll_down(struct fnc_tree_view_state *, int);
static int		 visit_subtree(struct fnc_tree_view_state *,
			    struct fnc_tree_object *);
static int		 tree_entry_get_symlink_target(char **,
			    struct fnc_tree_entry *);
static int		 match_tree_entry(struct fnc_tree_entry *, regex_t *);
static void		 fnc_object_tree_close(struct fnc_tree_object *);
static void		 fnc_close_repository_tree(struct fnc_repository_tree *);
static int		 open_blame_view(struct fnc_view *, char *,
			    fsl_uuid_str, fsl_id_t, int);
static int		 run_blame(struct fnc_view *);
static int		 fnc_dump_buffer_to_file(off_t *, int *, off_t **,
			    FILE *, fsl_buffer *);
static int		 show_blame_view(struct fnc_view *);
static void		*blame_thread(void *);
static int		 blame_cb(void *, fsl_annotate_opt const * const,
			    fsl_annotate_step const * const);
static int		 draw_blame(struct fnc_view *);
static int		 blame_input_handler(struct fnc_view **,
			    struct fnc_view *, int);
static int		 blame_search_init(struct fnc_view *);
static int		 blame_search_next(struct fnc_view *);
static fsl_uuid_cstr	 get_selected_commit_id(struct fnc_blame_line *,
			    int, int, int);
static int		 fnc_commit_qid_alloc(struct fnc_commit_qid **,
			    fsl_uuid_cstr);
static int		 close_blame_view(struct fnc_view *);
static int		 stop_blame(struct fnc_blame *);
static int		 cancel_blame(void *);
static void		 fnc_commit_qid_free(struct fnc_commit_qid *);
static void		 view_set_child(struct fnc_view *, struct fnc_view *);
static int		 view_close_child(struct fnc_view *);
static int		 close_tree_view(struct fnc_view *);
static int		 close_timeline_view(struct fnc_view *);
static int		 close_diff_view(struct fnc_view *);
static int		 view_resize(struct fnc_view *);
static int		 screen_is_split(struct fnc_view *);
static bool		 screen_is_shared(struct fnc_view *);
static void		 fnc_resizeterm(void);
static int		 join_tl_thread(struct fnc_tl_view_state *);
static void		 fnc_free_commits(struct commit_queue *);
static void		 fnc_commit_artifact_close(struct fnc_commit_artifact*);
static int		 fsl_list_object_free(void *, void *);
static void		 sigwinch_handler(int);
static void		 sigpipe_handler(int);
static void		 sigcont_handler(int);
static int		 strtonumcheck(int *, const char *, const int,
			    const int);
static char		*fnc_strsep (char **, const char *);
#ifdef __linux__
static size_t		 fnc_strlcat(char *, const char *, size_t);
static size_t		 fnc_strlcpy(char *, const char *, size_t);
#endif
static int		 set_colours(fsl_list *, enum fnc_view_id vid);
static int		 match_colour(const void *, const void *);
static bool		 fnc_home(struct fnc_view *);
static struct fnc_colour	*get_colour(fsl_list *, int);
static struct fnc_tree_entry	*get_tree_entry(struct fnc_tree_object *,
				    int);
static struct fnc_tree_entry	*find_tree_entry(struct fnc_tree_object *,
				    const char *, size_t);

int
main(int argc, const char **argv)
{
	fcli_command	*cmd = NULL;
	fsl_cx		*f = NULL;
	fsl_error	 e = fsl_error_empty;	/* DEBUG */
	char		*path = NULL;
	int		 rc = 0;

	fnc_init.filter_types =
	    (struct artifact_types *)fsl_malloc(sizeof(struct artifact_types));
	fnc_init.filter_types->values = fsl_malloc(sizeof(char *));
	fnc_init.filter_types->nitems = 0;

558
559
560
561
562
563
564

565
566
567
568
569
570
571
572
573
574
575
576
577


























578
579
580
581

582
583
584
585
586
587

588
589
590
591
592
593
594
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901






902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930

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







+







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



-
+






+







		goto end;

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

	rc = fcli_fingerprint_check(true);
	if (rc)
		goto end;

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

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

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

	if (cmd != NULL)
		rc = cmd->f(cmd);
end:
	fsl_free(path);
	endwin();
	putchar('\n');
	if (rc) {
		if (rc == FCLI_RC_HELP)
			rc = 0;
		else {
			fsl_error_set(&e, rc, NULL);
602
603
604
605
606
607
608

609
610
611
612
613
614
615

616
617

618
619
620
621

622
623

624
625
626
627
628
629
630
631

632
633
634


635
636
637

638
639

640
641
642
643





644

645
646
647

648
649
650
651
652
653






































654












































































































































655

656



































































657
658
659
660
661
662
663
664
665
666
667
668
669

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












688
689

690
691
692
693
694
695
696
953
954
955
956
957
958
959
960
961
962
963
964
965
966

967


968




969


970








971



972
973

974

975
976

977


978
979
980
981
982
983
984

985
986


987
988





989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167

1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240


1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257









1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270

1271
1272
1273
1274
1275
1276
1277
1278







+






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

-
+

-
+
-
-


+
+
+
+
+
-
+

-
-
+

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

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

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




-
-







+









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

-
+








static int
cmd_timeline(fcli_command const *argv)
{
	struct fnc_view	*v;
	fsl_cx		*f = fcli_cx();
	fsl_id_t	 rid = -1;
	char		*path = NULL;
	int		 rc = 0;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	if (fnc_init.nrecords.zlimit) {
	if (fnc_init.nrecords.zlimit)
		const char	*ptr, *s;
		s = fnc_init.nrecords.zlimit;
		if ((rc = strtonumcheck(&fnc_init.nrecords.limit,
		ptr = NULL;
		errno = 0;

		fnc_init.nrecords.limit = strtol(s, (char **)&ptr, 10);
		    fnc_init.nrecords.zlimit, INT_MIN, INT_MAX)))
		if (errno == ERANGE)
			return fsl_cx_err_set(f, FSL_RC_RANGE,
			return rc;
			    "<n> out of range: -n|--limit=%s [%s]", s, ptr);
		else if (errno != 0 || errno == EINVAL)
			return fsl_cx_err_set(f, FSL_RC_MISUSE,
			    "<n> not a number: -n|--limit=%s [%s]", s, ptr);
		else if (ptr && *ptr != '\0')
			return fsl_cx_err_set(f, FSL_RC_MISUSE,
			    "invalid char in <n>: -n|--limit=%s [%s]", s, ptr);
	}


	if (fnc_init.start_commit.sym != NULL) {
		rc = fsl_sym_to_rid(f, fnc_init.start_commit.sym,
	if (fnc_init.sym != NULL) {
		rc = fsl_sym_to_rid(f, fnc_init.sym, FSL_SATYPE_CHECKIN, &rid);
		    FSL_SATYPE_CHECKIN, &rid);
		if (rc || rid < 0)
			return fcli_err_set(FSL_RC_TYPE,
			return RC(FSL_RC_TYPE,
			    "artifact [%s] not resolvable to a commit",
			    fnc_init.start_commit.sym);
			    fnc_init.sym);
		else
			fnc_init.start_commit.rid = rid;
	}

	if (fnc_init.path)
		path = fsl_strdup(fnc_init.path);
	else
		rc = map_repo_path(&path);
	if (!rc)
	rc = init_curses();
		rc = init_curses();
	if (rc)
		return fsl_cx_err_set(f, fsl_errno_to_rc(rc, FSL_RC_ERROR),
		    "can not initialise ncurses");
		goto end;
	v = view_open(0, 0, 0, 0, FNC_VIEW_TIMELINE);
	if (v == NULL)
		return fsl_cx_err_set(f, FSL_RC_ERROR, "view_open() failed");
	rc = open_timeline_view(v);
	if (rc)
		return rc;
	if (v == NULL) {
		RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}
	rc = open_timeline_view(v, rid, path);
	if (!rc)
		rc = view_loop(v);
end:
	fsl_free(path);
	return rc;
}

/*
 * Look for an in-repository path in **argv. If found, canonicalise it as an
 * absolute path relative to the repository root (e.g., /ckoutdir/found/path),
 * and assign to a dynamically allocated string in *requested_path, which the
 * caller must dispose of with fsl_free or free(3).
 */
static int
map_repo_path(char **requested_path)
{
	fsl_cx		*const f = fcli_cx();
	fsl_buffer	 buf = fsl_buffer_empty;
	char		*canonpath = NULL, *ckoutdir = NULL, *path = NULL;
	const char	*ckoutdir0 = NULL;
	fsl_size_t	 len;
	int		 rc = 0;
	bool		 root;

	*requested_path = NULL;

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

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

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

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

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

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

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

		*requested_path = path;
	}
	return view_loop(v);
	return rc;
}

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

	if (fsl_strncmp(parent, child, parentlen) != 0)
		return false;
	if (child[parentlen - 1 /* Trailing slash */] != '/')
		return false;

	return true;
}

/*
 * As a special case, due to fsl_ckout_filename_check() resolving the current
 * checkout directory to ".", this function returns true for ".". For this
 * reason, when path is intended to be the current working directory for any
 * directory other than the repository root, callers must ensure path is either
 * absolute or relative to the respository root--not ".".
 */
static bool
fnc_path_is_root_dir(const char *path)
{
	while (*path == '/' || *path == '.')
		++path;
	return (*path == '\0');
}

static int
path_skip_common_ancestor(char **child, const char *parent_abspath,
    size_t parentlen, const char *abspath, size_t len)
{
	size_t	bufsz;
	int	rc = 0;

	*child = NULL;

	if (parentlen >= len)
		return RC(FSL_RC_RANGE, "invalid path [%s]", abspath);
	if (fsl_strncmp(parent_abspath, abspath, parentlen) != 0)
		return RC(FSL_RC_TYPE, "invalid path [%s]", abspath);
	if (!fnc_path_is_root_dir(parent_abspath) &&
	    abspath[parentlen - 1 /* Trailing slash */] != '/')
		return RC(FSL_RC_TYPE, "invalid path [%s]", abspath);
	while (abspath[parentlen] == '/')
		++abspath;
	bufsz = len - parentlen + 1;
	*child = fsl_malloc(bufsz);
	if (*child == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	if (strlcpy(*child, abspath + parentlen, bufsz) >= bufsz) {
		rc = RC(FSL_RC_RANGE, "%s", "strlcpy");
		fsl_free(*child);
		*child = NULL;
	}
	return rc;
}

#if 0
static bool
fnc_path_is_cwd(const char *path)
{
	return (path[0] == '.' && path[1] == '\0');
}
#endif

static int
init_curses(void)
{
	int rc = 0;

	initscr();
	cbreak();
	noecho();
	nonl();
	intrflush(stdscr, FALSE);
	keypad(stdscr, TRUE);
	curs_set(0);
	set_escdelay(0);  /* ESC should return immediately. */
#ifndef __linux__
	typeahead(-1);	/* Don't disrupt screen update operations. */
#endif

	if (!fnc_init.nocolour && has_colors()) {
		start_color();
		use_default_colors();
	}

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

	return rc;
	return 0;
}

static struct fnc_view *
view_open(int nlines, int ncols, int start_ln, int start_col,
    enum fnc_view_id vid)
{
	struct fnc_view *view = calloc(1, sizeof(*view));
717
718
719
720
721
722
723
724

725
726
727
728
729
730
731
732
733

















734
735
736
737
738
739
740

741
742

743
744
745






























746
747
748


749
750
751
752
753


754
755
756
757
758
759
760
1299
1300
1301
1302
1303
1304
1305

1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338

1339
1340

1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375


1376
1377
1378
1379
1380


1381
1382
1383
1384
1385
1386
1387
1388
1389







-
+









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






-
+

-
+



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

-
-
+
+



-
-
+
+







	}

	keypad(view->window, TRUE);
	return view;
}

static int
open_timeline_view(struct fnc_view *view)
open_timeline_view(struct fnc_view *view, fsl_id_t rid, const char *path)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	fsl_cx				*f = fcli_cx();
	fsl_db				*db = fsl_cx_db_repo(f);
	fsl_buffer			 sql = fsl_buffer_empty;
	char				*startdate = NULL;
	fsl_id_t			 idtag = 0;
	int				 idx, rc = 0;

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

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

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

	if (fnc_init.start_commit.rid)
	if (rid != -1)
		startdate = fsl_mprintf("(SELECT mtime FROM event "
		    "WHERE objid=%d)", fnc_init.start_commit.rid);
		    "WHERE objid=%d)", rid);
	else
		fsl_ckout_version_info(f, NULL, &s->curr_ckout_uuid);

	/*
	 * In 'fnc timeline -R repo.fossil path' case, check that path is a
	 * valid repository path in the repository tree as at either the
	 * latest check-in or the specified commit.
	 */
	if (s->curr_ckout_uuid == NULL && path[1]) {
		fsl_deck d = fsl_deck_empty;
		bool ispath = false;
		rc = fsl_deck_load_sym(f, &d, fnc_init.sym ? fnc_init.sym :
		    "tip", FSL_SATYPE_CHECKIN);
		fsl_deck_F_rewind(&d);
		if (fsl_deck_F_search(&d, path + 1 /* Slash */) == NULL) {
			const fsl_card_F *cf;
			fsl_deck_F_next(&d, &cf);
			do {
				fsl_deck_F_next(&d, &cf);
				if (cf && !fsl_strncmp(path + 1 /* Slash */,
				    cf->name, fsl_strlen(path) - 1)) {
					ispath = true;
					break;
				}
			} while (cf);
		} else
			ispath = true;
		fsl_deck_finalize(&d);
		if (!ispath)
			return RC(FSL_RC_NOT_FOUND, "'%s' invalid path in [%s]",
			    path + 1, fnc_init.sym ? fnc_init.sym : "tip");
	}

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

	fsl_buffer_appendf(&sql, "SELECT "
            /* 0 */"uuid, "
	    /* 1 */"datetime(event.mtime%s), "
	    /* 2 */"coalesce(euser, user), "
787
788
789
790
791
792
793
794
795

796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816


817
818
819
820
821
822
823
824
825
826
827
828
829
830
























831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846

847
848
849
850
851
852
853
854
855
856
857

858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875

876
877

878

879
880
881
882
883
884
885
1416
1417
1418
1419
1420
1421
1422


1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442


1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527


1528
1529
1530
1531

1532
1533
1534
1535
1536
1537
1538
1539







-
-
+



















-
-
+
+














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
















+











+
















-
-
+


+
-
+







                    fnc_init.filter_branch);
		if (idtag > 0)
			fsl_buffer_appendf(&sql,
                             " AND EXISTS(SELECT 1 FROM tagxref"
                             " WHERE tagid=%"FSL_ID_T_PFMT
                             " AND tagtype > 0 AND rid=blob.rid)", idtag);
		else {
			rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
			    "Invalid branch name [%s]",
			rc = RC(FSL_RC_NOT_FOUND, "Invalid branch name [%s]",
			    fnc_init.filter_branch);
			goto end;
		}
	}

	if (fnc_init.filter_tag) {
		idtag = fsl_db_g_id(db, 0,
                    "SELECT tagid FROM tag WHERE tagname GLOB 'sym-%q'",
                    fnc_init.filter_tag);
                if (idtag == 0)
			idtag = fsl_db_g_id(db, 0,
			    "SELECT tagid FROM tag WHERE tagname='%q'",
			    fnc_init.filter_tag);
		if (idtag > 0)
			fsl_buffer_appendf(&sql,
                             " AND EXISTS(SELECT 1 FROM tagxref"
                             " WHERE tagid=%"FSL_ID_T_PFMT
                             " AND tagtype > 0 AND rid=blob.rid)", idtag);
		else {
			rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
			    "Invalid tag [%s]", fnc_init.filter_tag);
			rc = RC(FSL_RC_NOT_FOUND, "Invalid tag [%s]",
			    fnc_init.filter_tag);
			goto end;
		}
	}

	if (fnc_init.filter_user)
		if ((rc = fsl_buffer_appendf(&sql,
                    " AND coalesce(euser, user) GLOB lower('*%q*')",
                    fnc_init.filter_user)))
		goto end;

	if (startdate) {
		fsl_buffer_appendf(&sql, " AND event.mtime <= %s", startdate);
		fsl_free(startdate);
	}

	/*
	 * If path is not root ("/"), a versioned path in the repository has
	 * been requested, only retrieve commits involving path.
	 */
	if (path[1]) {
		fsl_buffer_appendf(&sql,
		    " AND EXISTS(SELECT 1 FROM mlink"
		    " WHERE mlink.mid = event.objid"
		    " AND mlink.fnid IN ");
		if (fsl_cx_is_case_sensitive(f)) {
			fsl_buffer_appendf(&sql,
			    "(SELECT fnid FROM filename"
			    " WHERE name = %Q OR name GLOB '%q/*')",
			    path + 1, path + 1);  /* Skip prepended slash. */
		} else {
			fsl_buffer_appendf(&sql,
			    "(SELECT fnid FROM filename"
			    " WHERE name = %Q COLLATE nocase"
			    " OR lower(name) GLOB lower('%q/*'))",
			    path + 1, path + 1);  /* Skip prepended slash. */
		}
		fsl_buffer_append(&sql, ")", 1);
	}

	fsl_buffer_appendf(&sql, " ORDER BY event.mtime DESC");

	if (fnc_init.nrecords.limit > 0)
		fsl_buffer_appendf(&sql, " LIMIT %d", fnc_init.nrecords.limit);

	view->show = show_timeline_view;
	view->input = tl_input_handler;
	view->close = close_timeline_view;
	view->search_init = tl_search_init;
	view->search_next = tl_search_next;

	if ((rc = fsl_db_prepare_cached(db, &s->thread_cx.q, "%b", &sql)))
		goto end;
	fsl_stmt_step(s->thread_cx.q);

	s->thread_cx.rc = 0;
	s->thread_cx.db = db;
	s->thread_cx.spin_idx = 0;
	s->thread_cx.ncommits_needed = view->nlines - 1;
	s->thread_cx.commits = &s->commits;
	s->thread_cx.timeline_end = false;
	s->thread_cx.quit = &s->quit;
	s->thread_cx.first_commit_onscreen = &s->first_commit_onscreen;
	s->thread_cx.selected_commit = &s->selected_commit;
	s->thread_cx.searching = &view->searching;
	s->thread_cx.search_status = &view->search_status;
	s->thread_cx.regex = &view->regex;
	s->thread_cx.path = s->path;

end:
	fsl_buffer_clear(&sql);
	if (rc) {
		close_timeline_view(view);
		if (db->error.code)
			rc = fsl_cx_uplift_db_error(f, db);
	}
	return rc;
}

static int
view_loop(struct fnc_view *view)
{
	struct view_tailhead	 views;
	struct fnc_view		*new_view;
	fsl_cx			*f = fcli_cx();
	int			 done = 0, rc = 0;
	int			 done = 0, err = 0, rc = 0;

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

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

	view->active = true;
	rc = view->show(view);
	if (rc)
981
982
983
984
985
986
987
988
989
990



991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005


1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037


1038

1039
1040
1041
1042
1043
1044
1045



1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056



1057
1058
1059
1060
1061
1062
1063
1064
1065
1066




1067
1068
1069
1070
1071
1072
1073



1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090


1091
1092
1093
1094
1095


1096
1097
1098


1099
1100
1101
1102
1103


1104
1105
1106
1107


1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122


1123
1124

1125

1126
1127
1128



1129
1130
1131
1132
1133
1134
1135

1136


1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214

1215
1216
1217
1218
1219
1220




1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233




1234
1235
1236
1237
1238
1239
1240



















































































































1241
1242
1243
1244
1245

1246
1247
1248
1249
1250


1251
1252
1253
1254
1255
1256



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



1274
1275
1276
1277
1278
1279
1280
1281

1282
1283
1284
1285
1286
1287
1288
1289
1290

1291
1292
1293
1294
1295
1296

1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310

1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325


1326
1327
1328
1329



1330
1331
1332












1333
1334
1335
1336
1337
















1338
1339
1340
1341
1342
1343
1344
1635
1636
1637
1638
1639
1640
1641



1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658

1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674

1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690

1691
1692
1693
1694
1695
1696
1697
1698
1699


1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710



1711
1712
1713
1714
1715
1716
1717
1718
1719
1720



1721
1722
1723
1724
1725
1726
1727
1728



1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740

1741
1742


1743


1744
1745
1746
1747
1748


1749
1750
1751


1752
1753
1754
1755
1756


1757
1758
1759
1760


1761
1762
1763
1764
1765
1766
1767
1768
1769


1770

1771
1772


1773
1774
1775
1776
1777

1778

1779

1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790

1791
1792
1793
1794
1795


1796





































































1797
1798

1799
1800
1801

1802


1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817


1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947

1948

1949
1950


1951
1952
1953
1954
1955



1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972



1973
1974
1975
1976
1977
1978
1979
1980
1981
1982

1983
1984
1985
1986
1987
1988
1989
1990
1991

1992
1993
1994
1995
1996
1997

1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011

2012
2013
2014
2015


2016
2017
2018
2019
2020
2021
2022
2023
2024

2025
2026
2027



2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045





2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068







-
-
-
+
+
+














-
+
+














-
















-
+
+

+





-
-
+
+
+








-
-
-
+
+
+







-
-
-
+
+
+
+




-
-
-
+
+
+









-


-
-

-
-
+
+



-
-
+
+

-
-
+
+



-
-
+
+


-
-
+
+







-
-

-


-
-
+
+


+
-
+
-

-
+
+
+







+
-
+
+



-
-

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


-
+


-

-
-
+
+
+
+











-
-
+
+
+
+







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




-
+
-


-
-
+
+



-
-
-
+
+
+














-
-
-
+
+
+







-
+








-
+





-
+













-
+



-
-









-
+
+

-
-
-
+
+
+



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







end:
	while (!TAILQ_EMPTY(&views)) {
		view = TAILQ_FIRST(&views);
		TAILQ_REMOVE(&views, view, entries);
		view_close(view);
	}

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

	return rc;
}

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

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

	return draw_commits(view);
}

static void *
tl_producer_thread(void *state)
{
	struct fnc_tl_thread_cx	*cx = state;
	fsl_cx			*f = fcli_cx();
	int			 rc;
	bool			 done = false;

	rc = block_main_thread_signals();
	if (rc)
		return (void *)(intptr_t)rc;

	while (!done && !rc && !rec_sigpipe) {
		switch (rc = build_commits(cx)) {
		case FSL_RC_STEP_DONE:
			done = true;
			/* FALL THROUGH */
		case FSL_RC_STEP_ROW:
			rc = 0;
			/* FALL THROUGH */
		default:
			if (rc)
			if (rc) {
				cx->rc = rc;
				return (void *)(intptr_t)rc;
			}
			else if (cx->ncommits_needed > 0)
				cx->ncommits_needed--;
			break;
		}

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

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

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

		if (pthread_mutex_unlock(&fnc_mutex))
			rc = fsl_cx_err_set(f, FSL_RC_ERROR,
			    "mutex unlock fail");
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
	}

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

static int
block_main_thread_signals(void)
{
	fsl_cx		*f = NULL;
	sigset_t	 set;

	f = fcli_cx();

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

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

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

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

	return 0;
}

static int
build_commits(struct fnc_tl_thread_cx *cx)
{
	fsl_buffer	 buf = fsl_buffer_empty;
	fsl_id_t	 rid = 0;
	int		 rc = 0;
	fsl_cx		*f = fcli_cx();

	/*
	 * Step through the result set returned from our SQL query,
	 * parsing columns required to build commits for the timeline.
	 * Step through the given SQL query, passing each row to the commit
	 * builder to build commits for the timeline.
	 */
	do {
		struct fnc_commit_artifact	*commit = NULL;
		struct commit_entry	*dup_entry;
		struct commit_entry		*dup_entry, *entry;
		const char		*comment, *prefix, *type, *uuid;

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

		if ((rc = fsl_stmt_get_id(cx->q, 3, &rid)))
			break;

		type = fsl_stmt_g_text(cx->q, 4, NULL);
		/* Should we only build check-in commits for the timeline? */
		/* if (*type != 'c') */
		/*	continue; */

		comment = fsl_stmt_g_text(cx->q, 6, NULL);
		prefix = NULL;

		switch (*type) {
		case 'c':
			type = "checkin";
			break;
		case 'w':
			type = "wiki";
			if (comment)
				switch (*comment) {
				case '+':
					prefix = "Added: ";
					++comment;
					break;
				case '-':
					prefix = "Deleted: ";
					++comment;
					break;
				case ':':
					prefix = "Edited: ";
					++comment;
					break;
				default:
					break;
				}
			break;
		case 'g':
			  type = "tag";
			  break;
		case 'e':
			  type = "technote";
			  break;
		case 't':
			  type = "ticket";
			  break;
		case 'f':
			  type = "forum";
			  break;
		};

		commit = calloc(1, sizeof(*commit));
		if (commit == NULL)
			return fsl_cx_err_set(f, FSL_RC_OOM, "calloc fail");

		fsl_buffer_append(&buf, prefix, -1);
		fsl_buffer_append(&buf, comment, -1);
		commit->comment = fsl_strdup(fsl_buffer_str(&buf));
		fsl_buffer_clear(&buf);

		/* Is there are more efficient way to get the parent? */
		commit->puuid = fsl_db_g_text(cx->db, NULL,
		    "SELECT uuid FROM plink, blob WHERE plink.cid=%d "
		    "AND blob.rid=plink.pid AND plink.isprim", rid);
		commit->uuid = fsl_strdup(uuid);
		commit->timestamp = fsl_strdup(fsl_stmt_g_text(cx->q, 1, NULL));
		commit->user = fsl_strdup(fsl_stmt_g_text(cx->q, 2, NULL));
		commit->branch = fsl_strdup(fsl_stmt_g_text(cx->q, 5, NULL));
		commit->type = fsl_strdup(type);
		commit->rid = rid;

		entry = fsl_malloc(sizeof(*entry));
		if (entry == NULL)
			return fsl_cx_err_set(f, FSL_RC_OOM, "malloc fail");
			return RC(FSL_RC_ERROR, "%s", "fsl_malloc");

		entry->commit = commit;
		fsl_stmt_cached_yield(cx->q);

		if (pthread_mutex_lock(&fnc_mutex))
			return fsl_cx_err_set(f, FSL_RC_ERROR, "mutex lock");
		rc = pthread_mutex_lock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");

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

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

		if (pthread_mutex_unlock(&fnc_mutex))
			return fsl_cx_err_set(f, FSL_RC_ERROR, "mutex unlock");
		rc = pthread_mutex_unlock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");

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

	return rc;
}

/*
 * Given prepared SQL statement q _XOR_ record ID rid, allocate and build the
 * corresponding commit artifact from the result set. The commit must
 * eventually be disposed of with fnc_commit_artifact_close().
 */
static int
commit_builder(struct fnc_commit_artifact **ptr, fsl_id_t rid, fsl_stmt *q)
{
	fsl_cx				*f = fcli_cx();
	fsl_db				*db = fsl_needs_repo(f);
	struct fnc_commit_artifact	*commit = NULL;
	fsl_buffer			 buf = fsl_buffer_empty;
	const char			*comment, *prefix, *type;
	int				 rc = 0;

	if (rid) {
		rc = fsl_db_prepare_cached(db, &q, "SELECT "
		    /* 0 */"uuid, "
		    /* 1 */"datetime(event.mtime%s), "
		    /* 2 */"coalesce(euser, user), "
		    /* 3 */"rid AS rid, "
		    /* 4 */"event.type AS eventtype, "
		    /* 5 */"(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, "
		    /*6*/"coalesce(ecomment, comment) AS comment "
		    "FROM event JOIN blob WHERE blob.rid=%d AND event.objid=%d",
		    fnc_init.utc ? "" : ", 'localtime'", rid, rid);
		if (rc)
			return RC(FSL_RC_DB, "%s", "fsl_db_prepare_cached");
		fsl_stmt_step(q);
	}

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

	switch (*type) {
	case 'c':
		type = "checkin";
		break;
	case 'w':
		type = "wiki";
		if (comment) {
			switch (*comment) {
			case '+':
				prefix = "Added: ";
				++comment;
				break;
			case '-':
				prefix = "Deleted: ";
				++comment;
				break;
			case ':':
				prefix = "Edited: ";
				++comment;
				break;
			default:
				break;
			}
			if (prefix)
				rc = fsl_buffer_append(&buf, prefix, -1);
		}
		break;
	case 'g':
		type = "tag";
		break;
	case 'e':
		type = "technote";
		break;
	case 't':
		type = "ticket";
		break;
	case 'f':
		type = "forum";
		break;
	};
	if (!rc && comment)
		rc = fsl_buffer_append(&buf, comment, -1);
	if (rc) {
		rc = RC(rc, "%s", "fsl_buffer_append");
		goto end;
	}

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


	if (!rid && (rc = fsl_stmt_get_id(q, 3, &rid))) {
		rc = RC(rc, "%s", "fsl_stmt_get_id");
		goto end;
	}
	/* Is there a more efficient way to get the parent? */
	commit->puuid = fsl_db_g_text(db, NULL,
	    "SELECT uuid FROM plink, blob WHERE plink.cid=%d "
	    "AND blob.rid=plink.pid AND plink.isprim", rid);
	commit->uuid = fsl_strdup(fsl_stmt_g_text(q, 0, NULL));
	commit->rid = rid;
	commit->type = fsl_strdup(type);
	commit->timestamp = fsl_strdup(fsl_stmt_g_text(q, 1, NULL));
	commit->user = fsl_strdup(fsl_stmt_g_text(q, 2, NULL));
	commit->branch = fsl_strdup(fsl_stmt_g_text(q, 5, NULL));
	commit->comment = fsl_strdup(comment ? fsl_buffer_str(&buf) : "");
	fsl_buffer_clear(&buf);

	*ptr = commit;
end:
	fsl_stmt_cached_yield(q);
	return rc;
}

static int
signal_tl_thread(struct fnc_view *view, int wait)
{
	struct fnc_tl_thread_cx	*ta = &view->state.timeline.thread_cx;
	struct fnc_tl_thread_cx	*cx = &view->state.timeline.thread_cx;
	fsl_cx			*f = fcli_cx();
	int			 rc = 0;

	while (ta->ncommits_needed > 0) {
		if (ta->timeline_end)
	while (cx->ncommits_needed > 0) {
		if (cx->timeline_end)
			break;

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

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

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

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

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

	return rc;
	return cx->rc;
}

static int
draw_commits(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct fnc_tl_thread_cx		*tcx = &s->thread_cx;
	struct commit_entry		*entry = s->selected_commit;
	fsl_cx				*f = fcli_cx();
	const char			*search_str = NULL;
	char				*headln = NULL, *idxstr = NULL;
	char				*branch = NULL, *type = NULL;
	char				*uuid = NULL;
	wchar_t				*wcstr;
	int				 ncommits = 0, rc = 0, wstrlen = 0;
	int				 max_usrlen = -1;
	int				 ncols_needed, max_usrlen = -1;

	if (s->selected_commit && !(view->searching != SEARCH_DONE &&
	    view->search_status == SEARCH_WAITING)) {
		uuid = fsl_strdup(s->selected_commit->commit->uuid);
		branch = fsl_strdup(s->selected_commit->commit->branch);
		type = fsl_strdup(s->selected_commit->commit->type);
	}

	if (s->thread_cx.ncommits_needed > 0) {
		if ((idxstr = fsl_mprintf(" [%d/%d] %s",
		    entry ? entry->idx + 1 : 0, s->commits.ncommits,
		    (view->searching && !view->search_status) ?
		    "searching..." : "loading...")) == NULL) {
			rc = fsl_cx_err_set(f, FSL_RC_RANGE, "mprintf idx");
			rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
			goto end;
		}
	} else {
		const char	*search_str = NULL;

		if (view->searching) {
			if (view->search_status == SEARCH_COMPLETE)
				search_str = "no more matches";
			else if (view->search_status == SEARCH_NO_MATCH)
				search_str = "no matches found";
			else if (view->search_status == SEARCH_WAITING)
				search_str = "searching...";
		}

		if ((idxstr = fsl_mprintf(" [%d/%d] %s",
		if ((idxstr = fsl_mprintf("%s [%d/%d] %s",
		    !fsl_strcmp(uuid, s->curr_ckout_uuid) ? " [current]" : "",
		    entry ? entry->idx + 1 : 0, s->commits.ncommits,
		    search_str ? search_str :
		    (branch ? branch : ""))) == NULL) {
			rc = fsl_cx_err_set(f, FSL_RC_RANGE, "mprintf idx");
		    search_str ? search_str : (branch ? branch : "")))
		    == NULL) {
			rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
			goto end;
		}
	}
	/*
	 * Compute cols needed to fit all components of the headline to truncate
	 * the hash component if needed. wiki, tag, and ticket artifacts don't
	 * have a branch component, checkins and some technotes do, so add a col
	 * for the space separator. Same applies if search_str is being shown.
	 */
	ncols_needed = fsl_strlen(type) + fsl_strlen(idxstr) + FSL_STRLEN_K256
	    + (!search_str && (!fsl_strcmp(type, "wiki") ||
	    !fsl_strcmp(type, "tag")  || !fsl_strcmp(type, "ticket") ||
	    (!branch && !fsl_strcmp(type, "technote"))) ? 0 : 1);
	/* If a path has been requested, display it in the headline. */
	if (s->path[1]) {
	if ((headln = fsl_mprintf("%s%c%s%s%s", type ? type : "", type ?
	    ' ' : SPINNER[tcx->spin_idx], uuid ? uuid :
	    "........................................", !fsl_strcmp(uuid,
	    s->curr_ckout_uuid) ? " [current]" : "", idxstr)) == NULL) {
		rc = fsl_cx_err_set(f, FSL_RC_RANGE, "mprintf headln");
		if ((headln = fsl_mprintf("%s%c%.*s %s%s", type ? type : "",
		    type ? ' ' : SPINNER[tcx->spin_idx], view->ncols <
		    ncols_needed ? view->ncols - (ncols_needed -
		    FSL_STRLEN_K256) : FSL_STRLEN_K256, uuid ? uuid :
		    "........................................",
		    s->path, idxstr)) == NULL) {
			rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
			headln = NULL;
			goto end;
		}
	} else if ((headln = fsl_mprintf("%s%c%.*s%s", type ? type : "", type ?
	    ' ' : SPINNER[tcx->spin_idx], view->ncols < ncols_needed ?
	    view->ncols - (ncols_needed - FSL_STRLEN_K256) : FSL_STRLEN_K256,
	    uuid ? uuid : "........................................", idxstr))
	    == NULL) {
		rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		headln = NULL;
		goto end;
	}
	if (SPINNER[++tcx->spin_idx] == '\0')
		tcx->spin_idx = 0;
	rc = formatln(&wcstr, &wstrlen, headln, view->ncols, 0);
	if (rc)
1365
1366
1367
1368
1369
1370
1371
1372
1373


1374
1375
1376
1377
1378
1379
1380
2089
2090
2091
2092
2093
2094
2095


2096
2097
2098
2099
2100
2101
2102
2103
2104







-
-
+
+







		wchar_t		*usr_wcstr;
		char		*user;
		int		 usrlen;
		if (ncommits >= view->nlines - 1)
			break;
		user = fsl_strdup(entry->commit->user);
		if (user == NULL) {
			rc = fsl_errno_to_rc(errno, FSL_RC_OOM);
			return rc;
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		if (strpbrk(user, "<@>") != NULL)
			parse_emailaddr_username(&user);
		rc = formatln(&usr_wcstr, &usrlen, user, view->ncols, 0);
		if (max_usrlen < usrlen)
			max_usrlen = usrlen;
		fsl_free(usr_wcstr);
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
2149
2150
2151
2152
2153
2154
2155

2156
2157
2158
2159
2160
2161
2162







-







	*username = usr;
}

static int
formatln(wchar_t **ptr, int *wstrlen, const char *mbstr, int column_limit,
    int start_column)
{
	fsl_cx		*f = fcli_cx();
	wchar_t		*wline = NULL;
	size_t		 i, wlen;
	int		 rc = 0, cols = 0;

	*ptr = NULL;
	*wstrlen = 0;

1463
1464
1465
1466
1467
1468
1469
1470

1471
1472
1473
1474
1475
1476
1477
1478
1479
1480

1481
1482
1483
1484
1485
1486
1487
2186
2187
2188
2189
2190
2191
2192

2193
2194
2195
2196
2197
2198
2199
2200
2201
2202

2203
2204
2205
2206
2207
2208
2209
2210







-
+









-
+







			if (cols + width > column_limit)
				break;
			cols += width;
			i++;
		} else if (width == -1) {
			if (wline[i] == L'\t') {
				width = TABSIZE -
				((cols + column_limit) % TABSIZE);
				    ((cols + column_limit) % TABSIZE);
			} else {
				width = 1;
				wline[i] = L'.';
			}
			if (cols + width > column_limit)
				break;
			cols += width;
			i++;
		} else {
			rc = fsl_cx_err_set(f, FSL_RC_RANGE, "wcwidth");
			rc = RC(FSL_RC_RANGE, "%s", "wcwidth");
			goto end;
		}
	}
	wline[i] = L'\0';
	if (wstrlen)
		*wstrlen = cols;
end:
1499
1500
1501
1502
1503
1504
1505
1506

1507
1508
1509


1510
1511

1512
1513
1514
1515
1516
1517
1518

1519
1520
1521
1522
1523

1524
1525
1526
1527
1528
1529
1530
2222
2223
2224
2225
2226
2227
2228

2229
2230


2231
2232


2233
2234
2235
2236
2237
2238
2239

2240
2241
2242
2243
2244

2245
2246
2247
2248
2249
2250
2251
2252







-
+

-
-
+
+
-
-
+






-
+




-
+








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


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

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

end:
	if (rc) {
		fsl_free(*dst);
		*dst = NULL;
		*dstlen = 0;
	}
1539
1540
1541
1542
1543
1544
1545
1546

1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
2261
2262
2263
2264
2265
2266
2267

2268
2269
2270
2271
2272
2273

2274
2275
2276
2277
2278
2279
2280







-
+





-







 *   DATE UUID USERNAME  COMMIT-COMMENT
 *
 * Assuming an 8-character username, this scheme provides 80 characters for the
 * comment, which should be sufficient considering it's suggested good practice
 * to limit commit comment summary lines to a maximum 50 characters, and most
 * plaintext-based conventions suggest not exceeding 72-80 characters.
 *
 * When < 120 columns, the (abbreviated 9-character) UUID will be elided.
 * When < 110 columns, the (abbreviated 9-character) UUID will be elided.
 */
static int
write_commit_line(struct fnc_view *view, struct fnc_commit_artifact *commit,
    int max_usrlen)
{
	fsl_cx		*f = fcli_cx();
	wchar_t		*usr_wcstr = NULL, *wcomment = NULL;
	char		*comment0 = NULL, *comment = NULL, *date = NULL;
	char		*eol = NULL, *pad = NULL, *user = NULL;
	size_t		 i = 0;
	int		 col_pos, ncols_avail, usrlen, commentlen, rc = 0;

	/* Trim time component from timestamp for the date field. */
1584
1585
1586
1587
1588
1589
1590
1591

1592
1593
1594
1595
1596
1597
1598

1599
1600
1601

1602
1603
1604
1605
1606
1607
1608
2305
2306
2307
2308
2309
2310
2311

2312
2313
2314
2315
2316
2317
2318

2319
2320
2321

2322
2323
2324
2325
2326
2327
2328
2329







-
+






-
+


-
+







	if (strpbrk(user, "<@>") != NULL)
		parse_emailaddr_username(&user);
	rc = formatln(&usr_wcstr, &usrlen, user, view->ncols - col_pos,
	    col_pos);
	if (rc)
		goto end;
	waddwstr(view->window, usr_wcstr);
	pad = fsl_mprintf("%*s",  max_usrlen - usrlen + 2, " ");
	pad = fsl_mprintf("%*c",  max_usrlen - usrlen + 2, ' ');
	waddstr(view->window, pad);
	col_pos += (max_usrlen + 2);
	if (col_pos > view->ncols)
		goto end;

	/* Only show comment up to the first newline character. */
	comment0 = strdup(commit->comment);
	comment0 = fsl_strdup(commit->comment);
	comment = comment0;
	if (comment == NULL)
		return fsl_cx_err_set(f, FSL_RC_OOM, "strdup");
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	while (*comment == '\n')
		++comment;
	eol = strchr(comment, '\n');
	if (eol)
		*eol = '\0';
	ncols_avail = view->ncols - col_pos;
	rc = formatln(&wcomment, &commentlen, comment, ncols_avail, col_pos);
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643

1644

1645
1646

1647
1648


1649
1650
1651
1652
1653
1654

1655

1656
1657

1658

1659
1660
1661
1662
1663
1664
1665
2346
2347
2348
2349
2350
2351
2352

2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364

2365
2366
2367
2368


2369
2370
2371
2372
2373
2374
2375
2376
2377

2378
2379
2380
2381

2382
2383
2384
2385
2386
2387
2388
2389







-











+
-
+


+
-
-
+
+






+
-
+


+
-
+







}

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

	*new = NULL;

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

	if (view->searching && view->search_status == SEARCH_WAITING) {
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			return fsl_cx_err_set(f, rc, "mutex unlock");
			    "%s", "pthread_mutex_unlock");
		sched_yield();
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			return fsl_cx_err_set(f, rc, "mutex lock");
		view->search_next(view);
			    "%s", "pthread_mutex_lock");
		rc = view->search_next(view);
		return rc;
	}

	nodelay(stdscr, FALSE);
	/* Allow thread to make progress while waiting for input. */
	if ((rc = pthread_mutex_unlock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		return fsl_cx_err_set(f, rc, "mutex unlock");
		    "%s", "pthread_mutex_unlock");
	ch = wgetch(view->window);
	if ((rc = pthread_mutex_lock(&fnc_mutex)))
		return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		return fsl_cx_err_set(f, rc, "mutex lock");
		    "%s", "pthread_mutex_lock");

	if (rec_sigwinch || rec_sigcont) {
		fnc_resizeterm();
		rec_sigwinch = 0;
		rec_sigcont = 0;
		TAILQ_FOREACH(v, views, entries) {
			if ((rc = view_resize(v)))
1683
1684
1685
1686
1687
1688
1689





1690
1691
1692
1693
1694
1695
1696
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425







+
+
+
+
+







			view->child->active = true;
			view->focus_child = true;
		} else if (view->parent) {
			view->active = false;
			view->parent->active = true;
			view->parent->focus_child = false;
		}
		break;
	case KEY_F(1):
	case 'H':
	case '?':
		help(view);
		break;
	case 'q':
		rc = view->input(new, view, ch);
		view->egress = true;
		break;
	case 'f':
		if (view_is_parent(view)) {
1725
1726
1727
1728
1729
1730
1731
1732

1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749

























































































































































































































































































1750
1751
1752
1753
1754
1755

1756
1757
1758
1759
1760
1761
1762
2454
2455
2456
2457
2458
2459
2460

2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764

2765
2766
2767
2768
2769
2770
2771
2772







-
+

















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





-
+







		break;
	case 'N':
	case 'n':
		if (view->started_search && view->search_next) {
			view->searching = (ch == 'n' ?
			    SEARCH_FORWARD : SEARCH_REVERSE);
			view->search_status = SEARCH_WAITING;
			view->search_next(view);
			rc = view->search_next(view);
		} else
			rc = view->input(new, view, ch);
		break;
	case KEY_RESIZE:
		break;
	case ERR:
		break;
	case 'Q':
		*done = 1;
		break;
	default:
		rc = view->input(new, view, ch);
		break;
	}

	return rc;
}

static void
help(struct fnc_view *view)
{
	static const char	*progname = NULL;
	static const char	*help[] = {
	    "",
	    "Global",
	    "  H,?,F1           Open in-app help",
	    "  f                Toggle fullscreen",
	    "  Tab              Switch focus between open views",
	    "  Q                Quit the program",
	    "  q                Quit the active view",
	    "",
	    "Timeline",
	    "  k,<Up>,<,,       Move selection cursor up one commit",
	    "  j,<Down>,>,.     Move selection cursor down one commit",
	    "  C-b,PgUp         Scroll up one page",
	    "  C-f,PgDn         Scroll down one page",
	    "  gg,Home          Jump to first line in the current view",
	    "  G,End            Jump to last line in the current view",
	    "  Enter,Space      Open a diff view of the selected commit",
	    "  /                Open prompt to enter timeline search",
	    "  n                Find next commit matching the current search "
	    "term",
	    "  N                Find previous commit matching the current "
	    "search term",
	    "",
	    "Diff",
	    "  k,<Up>           Scroll up one line of diff output",
	    "  j,<Down>         Scroll down one line of diff output",
	    "  C-b,PgUp         Scroll up one page of diff output",
	    "  C-f,PgDn         Scroll down one page of diff output",
	    "  gg,Home          Scroll to the top of the diff view",
	    "  G,End            Scroll to the end of the diff view",
	    "  c                Toggle coloured diff output",
	    "  i                Toggle inversion of diff output",
	    "  v                Toggle verbosity of diff output",
	    "  w                Toggle ignore whitespace-only changes in diff",
	    "  -,_              Decrease the number of context lines",
	    "  +,=              Increase the number of context lines",
	    "  C-k,K,<,,        Display diff of next commit in the timeline",
	    "  C-j,J,>,.        Display diff of previous commit in the "
	    "timeline",
	    "  /                Open prompt to enter diff search",
	    "  n                Find next line matching the current search "
	    "term",
	    "  N                Find previous line matching the current search"
	    " term",
	    "",
	    "Tree",
	    "  k,<Up>           Move selection cursor up one entry",
	    "  j,<Down>         Move selection cursor down one entry",
	    "  C-b,PgUp         Scroll up one page",
	    "  C-f,PgDn         Scroll down one page",
	    "  gg,Home          Jump to first entry in the tree",
	    "  G,End            Jump to last entry in the tree",
	    "  l,Enter,<Right>  Move into the selected directory",
	    "  h,<BS>,<Left>    Return to the parent directory",
	    "  c                Toggle coloured tree output",
	    "  i                Toggle display of file artifact SHA hashes",
	    "  t                Display timeline of all commits modifying the "
	    "selected entry",
	    "  /                Open prompt to enter tree search",
	    "  n                Find next tree entry matching the current "
	    "search term",
	    "  N                Find previous tree entry matching the current "
	    "search term",
	    "",
	    "  See fnc(1) for complete list of options and key bindings.",
	    0};
	 static const char	*help0[] =
	 {
	    "",
	    "Global",
	    "  ❬H❭❬?❭❬F1❭      Open in-app help",
	    "  ❬f❭             Toggle fullscreen",
	    "  ❬TAB❭           Switch focus between open views",
	    "  ❬Q❭             Quit the program",
	    "  ❬q❭             Quit the active view",
	    "",
	    "Timeline",
	    "  ❬↑❭❬k❭❬<❭❬,❭    Move selection cursor up one commit",
	    "  ❬↓❭❬j❭❬>❭❬.❭    Move selection cursor down one commit",
	    "  ❬C-b❭❬PgUp❭     Scroll up one page",
	    "  ❬C-f❭❬PgDn❭     Scroll down one page",
	    "  ❬gg❭❬Home❭      Jump to first line in the current view",
	    "  ❬G❭❬End❭        Jump to last line in the current view",
	    "  ❬Enter❭❬Space❭  Open diff view of the selected commit",
	    "  ❬/❭             Open prompt to enter timeline search",
	    "  ❬n❭             Find next commit matching the current search "
	    "term",
	    "  ❬N❭             Find previous commit matching the current search"
	    " term",
	    "",
	    "Diff",
	    "  ❬↑❭❬k❭          Scroll up one line of diff output",
	    "  ❬↓❭❬j❭          Scroll down one line of diff output",
	    "  ❬C-b❭❬PgUp❭     Scroll up one page of diff output",
	    "  ❬C-f❭❬PgDn❭     Scroll down one page of diff output",
	    "  ❬gg❭❬Home❭      Scroll to the top of the diff view",
	    "  ❬G❭❬End❭        Scroll to the end of the diff view",
	    "  ❬c❭             Toggle coloured diff output",
	    "  ❬i❭             Toggle inversion of diff output",
	    "  ❬v❭             Toggle verbosity of diff output",
	    "  ❬w❭             Toggle ignore whitespace-only changes in diff",
	    "  ❬-❭❬_❭          Decrease the number of context lines",
	    "  ❬+❭❬=❭          Increase the number of context lines",
	    "  ❬C-k❭❬K❭❬<❭❬,❭  Display diff of next commit in the timeline",
	    "  ❬C-j❭❬J❭❬>❭❬.❭  Display diff of previous commit in the "
	    "timeline",
	    "  ❬/❭             Open prompt to enter diff search",
	    "  ❬n❭             Find next line matching the current search term",
	    "  ❬N❭             Find previous line matching the current search "
	    "term",
	    "",
	    "Tree",
	    "  ❬↑❭❬k❭          Move selection cursor up one entry",
	    "  ❬↓❭❬j❭          Move selection cursor down one entry",
	    "  ❬C-b❭❬PgUp❭     Scroll up one page",
	    "  ❬C-f❭❬PgDn❭     Scroll down one page",
	    "  ❬gg❭❬Home❭      Jump to first entry in the tree",
	    "  ❬G❭❬End❭        Jump to last entry in the tree",
	    "  ❬→❭❬l❭❬Enter❭   Move into the selected directory",
	    "  ❬←❭❬h❭❬⌫❭       Return to the parent directory",
	    "  ❬c❭             Toggle coloured tree output",
	    "  ❬i❭             Toggle display of file artifact SHA hashes",
	    "  ❬t❭             Display timeline of all commits modifying the "
	    "selected entry",
	    "  ❬/❭             Open prompt to enter tree search",
	    "  ❬n❭             Find next tree entry matching the current search"
	    " term",
	    "  ❬N❭             Find previous tree entry matching the current "
	    "search term",
	    "",
	    "  See fnc(1) for complete list of options and key bindings.",
	    0
	 };
	const char		*codeset = nl_langinfo(CODESET);

	progname = fsl_mprintf("%s %s Help\n", fcli_progname(), PRINT_VERSION);
	padpopup(view, !strcmp(codeset, "UTF-8") ? help0 : help, progname);
}

/*
 * Create popup pad in which to write the supplied txt string and optional
 * title. The pad is contained within a window that is offset four columns in
 * and two lines down from the parent window.
 */
static void
padpopup(struct fnc_view *view, const char **txt, const char *title)
{
	WINDOW	*help, *content;
	int	 ch, cury, end, idx, len, py, px, wy, wx, x0, y0;

	x0 = 4;		/* Number of columns to border help window. */
	y0 = 2;		/* Number of lines to border help window. */
	cury = 0;
	wx = getmaxx(view->window) - ((x0 + 1) * 2); /* Width of help window. */
	wy = getmaxy(view->window) - ((y0 + 1) * 2); /* Height of help window */
	ch = ERR;

	/*
	 * Compute longest line and total number of lines in text to be
	 * displayed to determine pad dimensions.
	 */
	px = 0;  /* Width of help pad (i.e., longest line in txt). */
	for (idx = 0; txt[idx] != 0; ++idx) {
		len = fsl_strlen(txt[idx]);
		if (px < len)
			px = len;
	}
	py = idx;  /* Height of help pad (i.e., number of lines in txt). */
	if (title)
		px = MAX(fsl_strlen(title), (fsl_size_t)px);

	if ((help = newwin(wy, wx, y0, x0)) == 0)
		return;
	if ((content = newpad(py + 1, px + 1)) == 0) {
		delwin(help);
		return;
	}

	doupdate();
	keypad(content, TRUE);

	/* Write text content to pad. */
	if (title)
		centerprint(content, 0, 0, px, title, 0);
	for (idx = 0; idx < py; ++idx) {
		waddstr(content, txt[idx]);
		if ((idx + 1) < py)
			waddch(content, '\n');
	}

	end = (getcury(content) - (wy - 3));  /* No. lines past end of pad. */
	do {
		switch (ch) {
			case KEY_UP:
			case 'k':
				if (cury > 0)
					--cury;
				break;
			case KEY_DOWN:
			case 'j':
				if (cury < end)
					++cury;
				break;
			case KEY_PPAGE:
			case CTRL('b'):
				if (cury > 0) {
					cury -= wy / 2;
					if (cury < 0)
						cury = 0;
				}
				break;
			case KEY_NPAGE:
			case CTRL('f'):
			case ' ':
				if (cury < end) {
					cury += wy / 2;
					if (cury > end)
						cury = end;
				}
				break;
			case 'g':
				if (!fnc_home(view))
					break;
				/* FALL THROUGH */
			case KEY_HOME:
				cury = 0;
				break;
			case KEY_END:
			case 'G':
				cury = end;
				break;
			case ERR:
			default:
				break;
		}
		werase(help);
		box(help, 0, 0);
		wnoutrefresh(help);
		pnoutrefresh(content, cury, 0, y0 + 1, x0 + 1, wy, wx);
		doupdate();
	} while ((ch = wgetch(content)) != 'q' && ch != KEY_ESCAPE
	    && ch != ERR);

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

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

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

	if (win == NULL)
		win = stdscr;

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

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

static int
tl_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct fnc_view			*diff_view = NULL;
	struct fnc_view			*diff_view = NULL, *tree_view = NULL;
	int				 rc = 0, start_col = 0;

	switch (ch) {
	case KEY_DOWN:
	case 'j':
	case '.':
	case '>':
1807
1808
1809
1810
1811
1812
1813
1814

1815
1816
1817
1818
1819
1820

1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
2817
2818
2819
2820
2821
2822
2823

2824






2825
2826
2827

2828
2829
2830
2831
2832
2833
2834







-
+
-
-
-
-
-
-
+


-







			break;
		if (TAILQ_FIRST(&s->commits.head) == s->first_commit_onscreen)
			s->selected_idx = 0;
		else
			timeline_scroll_up(s, view->nlines - 1);
		select_commit(s);
		break;
	case 'g': {
	case 'g':
		bool home = true;
		halfdelay(10);	/* Block for 1 second, then return ERR. */
		if (wgetch(view->window) != 'g')
			home = false;
		cbreak();	/* Return to blocking mode on user input. */
		if (!home)
		if (!fnc_home(view))
			break;
		/* FALL THROUGH */
	}
	case KEY_HOME:
		if (s->first_commit_onscreen == NULL)
			break;
		s->selected_idx = 0;
		timeline_scroll_up(s, s->commits.ncommits);
		select_commit(s);
		break;
1862
1863
1864
1865
1866
1867
1868




















1869
1870
1871
1872
1873
1874
1875
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899







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







				return rc;
			view->child = diff_view;
			diff_view->parent = view;
			view->focus_child = true;
		} else
			*new_view = diff_view;
		break;
	case 't':
		if (s->selected_commit == NULL)
			break;
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		rc = browse_commit_tree(&tree_view, start_col,
		    s->selected_commit, s->path);
		if (rc)
			break;
		view->active = false;
		tree_view->active = true;
		if (view_is_parent(view)) {
			rc = view_close_child(view);
			if (rc)
				return rc;
			view_set_child(view, tree_view);
			view->focus_child = true;
		} else
			*new_view = tree_view;
		break;
	case 'q':
		s->quit = 1;
		break;
	default:
		break;
	}

1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968

1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990

1991
1992
1993
1994
1995
1996
1997
1998
2972
2973
2974
2975
2976
2977
2978

2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990

2991

2992
2993
2994
2995
2996
2997
2998

2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010

3011

3012
3013
3014
3015
3016
3017
3018







-












-
+
-







-












-
+
-







		++ncommits;
	}
}

static int
make_splitscreen(struct fnc_view *view)
{
	fsl_cx	*f = fcli_cx();
	int	 rc = 0;

	view->start_ln = 0;
	view->start_col = view_split_start_col(0);
	view->nlines = LINES;
	view->ncols = COLS - view->start_col;
	view->lines = LINES;
	view->cols = COLS;
	if ((rc = view_resize(view)))
		return rc;

	if (mvwin(view->window, view->start_ln, view->start_col) == ERR)
		return fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_ERROR),
		return RC(FSL_RC_ERROR, "%s", "mvwin");
		    "curses mvwin -> %s", __func__);

	return rc;
}

static int
make_fullscreen(struct fnc_view *view)
{
	fsl_cx	*f = fcli_cx();
	int	 rc = 0;

	view->start_col = 0;
	view->start_ln = 0;
	view->nlines = LINES;
	view->ncols = COLS;
	view->lines = LINES;
	view->cols = COLS;
	if ((rc = view_resize(view)))
		return rc;

	if (mvwin(view->window, view->start_ln, view->start_col) == ERR)
		return fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_ERROR),
		return RC(FSL_RC_ERROR, "%s", "mvwin");
		    "curses mvwin -> %s", __func__);

	return rc;
}

/*
 * Only open a new view in a splitscreen if the console is >= 120 columns wide.
 * Otherwise, open in the current view. If splitting the screen, make the new
2025
2026
2027
2028
2029
2030
2031
2032

2033
2034
2035
2036
2037
2038
2039
3045
3046
3047
3048
3049
3050
3051

3052
3053
3054
3055
3056
3057
3058
3059







-
+








	if (view->search_status == SEARCH_FOR_END) {
		view->search_init(view);
		view->started_search = true;
		view->searching = SEARCH_FORWARD;
		view->search_status = SEARCH_WAITING;
		view->state.timeline.thread_cx.endjmp = true;
		view->search_next(view);
		rc = view->search_next(view);

		return rc;
	}

	mvwaddstr(view->window, view->start_ln + view->nlines - 1, 0, "/");
	wclrtoeol(view->window);

2049
2050
2051
2052
2053
2054
2055
2056

2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091


2092
2093
2094


2095
2096
2097
2098
2099
2100
2101
3069
3070
3071
3072
3073
3074
3075

3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096

3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109

3110
3111
3112
3113

3114
3115
3116
3117
3118
3119
3120
3121
3122







-
+




















-













-
+
+


-
+
+







		if ((rc = view->search_init(view))) {
			regfree(&view->regex);
			return rc;
		}
		view->started_search = true;
		view->searching = SEARCH_FORWARD;
		view->search_status = SEARCH_WAITING;
		view->search_next(view);
		rc = view->search_next(view);
	}

	return rc;
}

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

	s->matched_commit = NULL;
	s->search_commit = NULL;
	return 0;
}

static int
tl_search_next(struct fnc_view *view)
{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	struct commit_entry		*entry;
	fsl_cx				*f = fcli_cx();
	int				 rc = 0;

	if (!s->thread_cx.ncommits_needed && view->started_search)
		halfdelay(1);

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

	if (s->search_commit) {
		int	ch;
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return fsl_cx_err_set(f, rc, "mutex unlock fail");
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		ch = wgetch(view->window);
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return fsl_cx_err_set(f, rc, "mutex lock fail");
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
		if (ch == KEY_BACKSPACE) {
			view->search_status = SEARCH_CONTINUE;
			return rc;
		}
		if (view->searching == SEARCH_FORWARD)
			entry = TAILQ_NEXT(s->search_commit, entries);
		else
2214
2215
2216
2217
2218
2219
2220


2221
2222
2223
2224
2225
2226
2227
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250







+
+







{
	struct fnc_tl_view_state	*s = &view->state.timeline;
	int				 rc = 0;

	rc = join_tl_thread(s);
	fnc_free_commits(&s->commits);
	regfree(&view->regex);
	fsl_free(s->path);
	s->path = NULL;

	return rc;
}

/* static void */
/* sspinner(void) */
/* { */
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249

2250

2251
2252


2253
2254
2255
2256


2257
2258


2259
2260
2261
2262
2263

2264

2265
2266

2267

2268
2269
2270
2271
2272
2273
2274
3259
3260
3261
3262
3263
3264
3265

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
3301







-






+
-
+

-
+
+


-
-
+
+

-
+
+





+
-
+


+
-
+







/* 	} */
/* } */

static int
join_tl_thread(struct fnc_tl_view_state *s)
{
	void	*err;
	fsl_cx	*f = fcli_cx();
	int	 rc = 0;

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

		if ((rc = pthread_cond_signal(&s->thread_cx.commit_consumer)))
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			return fsl_cx_err_set(f, rc, "pthread_cond_signal");
			    "%s", "pthread_cond_signal");
		if ((rc = pthread_mutex_unlock(&fnc_mutex)))
			return fsl_cx_err_set(f, rc, "mutex unlock fail");
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		if ((rc = pthread_join(s->thread_id, &err)) ||
		    err == PTHREAD_CANCELED)
			return fsl_cx_err_set(f, rc ? rc : (intptr_t)err,
			    "pthread_join");
			return RC(fsl_errno_to_rc(rc, FSL_RC_MISUSE),
			    "%s", "pthread_join");
		if ((rc = pthread_mutex_lock(&fnc_mutex)))
			return fsl_cx_err_set(f, rc, "mutex lock fail");
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");

		s->thread_id = 0;
	}

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

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

	return rc;
}

static void
fnc_free_commits(struct commit_queue *commits)
{
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319





2320
2321
2322
2323
2324
2325
2326
2327
2328
2329

2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346

2347
2348
2349


2350
2351
2352
2353
2354
2355
2356
2357
2358
2359

2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376


2377
2378
2379


2380
2381
2382
2383
2384
2385
2386
2387
2388





2389

2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465

2466
2467
2468
2469
2470

2471
2472
2473
2474
2475

2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488

2489
2490
2491
2492
2493
2494





















2495
2496
2497
2498
2499
2500
2501
2502
2503

2504
2505
2506
2507
2508
2509
2510
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
3366
3367
3368

3369
3370
3371
3372

3373
3374


3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385

3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402

3403
3404
3405


3406
3407
3408
3409
3410
3411
3412
3413
3414
3415

3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429









































3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447

3448
3449
3450
3451
3452
3453
3454
3455

3456
3457
3458
3459
3460

3461

3462
3463
3464

3465

3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476

3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508





3509
3510
3511
3512
3513
3514
3515
3516







-
-
-
-
+
+
+
+
+









-
+











-




-
+

-
-
+
+









-
+
















-
+
+

-
-
+
+








-
+
+
+
+
+

+







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


















-








-
+




-
+
-



-
+
-











-
+






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




-
-
-
-
-
+







fsl_list_object_free(void *elem, void *state)
{
	struct fsl_list_state *st = state;

	switch (st->obj) {
	case FNC_ARTIFACT_OBJ: {
		struct fsl_file_artifact *ffa = elem;
		if (ffa->fc)
			fsl_free(ffa->fc);
		if (ffa)
			fsl_free(ffa);
		fsl_free(ffa->fc->name);
		fsl_free(ffa->fc->uuid);
		fsl_free(ffa->fc->priorName);
		fsl_free(ffa->fc);
		fsl_free(ffa);
		break;
	}
	case FNC_COLOUR_OBJ: {
		struct fnc_colour *c = elem;
		regfree(&c->regex);
		fsl_free(c);
		break;
	}
	default:
		return fcli_err_set(FSL_RC_MISSING_INFO,
		return RC(FSL_RC_MISSING_INFO,
		    "fsl_list_state.obj missing or invalid: %d", st->obj);
	}

	return 0;
}

static int
init_diff_commit(struct fnc_view **new_view, int start_col,
    struct fnc_commit_artifact *commit, struct fnc_view *timeline_view)
{
	struct fnc_view			*diff_view;
	fsl_cx				*f = fcli_cx();
	int				 rc = 0;

	diff_view = view_open(0, 0, 0, start_col, FNC_VIEW_DIFF);
	if (diff_view == NULL)
		return fsl_cx_err_set(f, FSL_RC_OOM, "new_view");
		return RC(FSL_RC_ERROR, "%s", "view_open");

	rc = open_diff_view(diff_view, commit, 5, fnc_init.ws,
	    fnc_init.invert, !fnc_init.quiet, timeline_view);
	rc = open_diff_view(diff_view, commit, DIFF_DEF_CTXT, fnc_init.ws,
	    fnc_init.invert, !fnc_init.quiet, timeline_view, true);
	if (!rc)
		*new_view = diff_view;

	return rc;
}

static int
open_diff_view(struct fnc_view *view, struct fnc_commit_artifact *commit,
    int context, bool ignore_ws, bool invert, bool verbosity,
    struct fnc_view *timeline_view)
    struct fnc_view *timeline_view, bool showmeta)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	int				 rc = 0;

	s->selected_commit = commit;
	s->first_line_onscreen = 1;
	s->last_line_onscreen = view->nlines;
	s->current_line = 1;
	s->f = NULL;
	s->context = context;
	s->sbs = 0;
	verbosity ? s->diff_flags |= FSL_DIFF_VERBOSE : 0;
	ignore_ws ? s->diff_flags |= FSL_DIFF_IGNORE_ALLWS : 0;
	invert ? s->diff_flags |= FSL_DIFF_INVERT : 0;
	s->timeline_view = timeline_view;
	s->colours = fsl_list_empty;
	s->colour = !fnc_init.nocolour;
	s->colour = !fnc_init.nocolour && has_colors();
	s->showmeta = showmeta;

	if (s->colour && has_colors())
		set_diff_colours(&s->colours);
	if (s->colour)
		set_colours(&s->colours, FNC_VIEW_DIFF);
	if (timeline_view && screen_is_split(view))
		show_timeline_view(timeline_view); /* draw vborder */
	show_diff_status(view);

	s->line_offsets = NULL;
	s->nlines = 0;
	s->ncols = view->ncols;
	rc = create_diff(s);
	if (rc)
	if (rc) {
		if (s->colour) {
			struct fsl_list_state st = { FNC_COLOUR_OBJ };
			fsl_list_clear(&s->colours, fsl_list_object_free, &st);
		}
		return rc;
	}

	view->show = show_diff;
	view->input = diff_input_handler;
	view->close = close_diff_view;
	view->search_init = diff_search_init;
	view->search_next = diff_search_next;

	return rc;
}

static int
set_diff_colours(fsl_list *s)
{
	struct fnc_colour	*colour;
	fsl_cx			*f = fcli_cx();
	fsl_size_t		 idx;
	const char		*regexp[4] = {
				    "^((checkin|wiki|ticket|technote) [0-9a-f]|"
				    "hash [+-] |\\[[+~>-]] |[+-]{3} )",
				    "^-", "^\\+", "^@@"
				 };
	int			 pairs[4][2] = {
				    {FNC_DIFF_META, COLOR_GREEN},
				    {FNC_DIFF_MINUS, COLOR_MAGENTA},
				    {FNC_DIFF_PLUS, COLOR_CYAN},
				    {FNC_DIFF_CHNK, COLOR_YELLOW}
				 };
	int			 rc = 0;

	for (idx = 0; idx < nitems(regexp); ++idx) {
		colour = fsl_malloc(sizeof(*colour));
		if (colour == NULL)
			return fsl_cx_err_set(f, FSL_RC_OOM, "malloc");
		rc = regcomp(&colour->regex, regexp[idx],
		    REG_EXTENDED | REG_NEWLINE | REG_NOSUB);
		if (rc) {
			static char regerr[512];
			regerror(rc, &colour->regex, regerr, sizeof(regerr));
			free(colour);
			return fsl_cx_err_set(f, fsl_errno_to_rc(rc,
			    FSL_RC_ERROR), "regcomp: %s [%s]", regerr,
			    regexp[idx]);
		}
		colour->scheme = pairs[idx][0];
		init_pair(colour->scheme, pairs[idx][1], -1);
		fsl_list_append(s, colour);
	}

	return rc;
}

static void
show_diff_status(struct fnc_view *view)
{
	mvwaddstr(view->window, 0, 0, "generating diff...");
#ifdef __linux__
	wnoutrefresh(view->window);
#else
	update_panels();
#endif
	doupdate();
}

static int
create_diff(struct fnc_diff_view_state *s)
{
	fsl_cx	*f = fcli_cx();
	FILE	*fout = NULL;
	char	*line, *st0 = NULL, *st = NULL;
	off_t	 lnoff = 0;
	int	 n, rc = 0;

	free(s->line_offsets);
	s->line_offsets = fsl_malloc(sizeof(off_t));
	if (s->line_offsets == NULL)
		return fsl_cx_err_set(f, FSL_RC_OOM, "fsl_malloc");
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	s->nlines = 0;

	fout = tmpfile();
	if (fout == NULL) {
		rc = fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_IO),
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "tmpfile");
		    "tmpfile");
		goto end;
	}
	if (s->f && fclose(s->f) == EOF) {
		rc = fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_IO),
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fclose");
		    "fclose");
		goto end;
	}
	s->f = fout;

	/*
	 * We'll diff artifacts of type "ci" (i.e., "checkin") separately, as
	 * it's a different process to diff the others (wiki, technote, etc.).
	 */
	if (!fsl_strcmp(s->selected_commit->type, "checkin")) {
		rc = create_changeset(s->selected_commit);
		if (rc) {
			rc = fsl_cx_err_set(f, FSL_RC_DB, "create_changeset");
			rc = RC(FSL_RC_DB, "%s", "create_changeset");
			goto end;
		}
	} else
		diff_non_checkin(&s->buf, s->selected_commit, s->diff_flags,
		    s->context, s->sbs);

	/*
	 * Delay assigning diff headline labels (i.e., diff id1 id2) till now
	 * because wiki parent commits are obtained in diff_non_checkin().
	 */
	if (s->selected_commit->puuid) {
		s->id1 = fsl_strdup(s->selected_commit->puuid);
		if (s->id1 == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	} else
		s->id1 = NULL;	/* Initial commit, tag, technote, etc. */
	if (s->selected_commit->uuid) {
		s->id2 = fsl_strdup(s->selected_commit->uuid);
		if (s->id2 == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	} else
		s->id2 = NULL;	/* Local work tree. */

	rc = add_line_offset(&s->line_offsets, &s->nlines, 0);
	if (rc)
		goto end;

	/*
	 * If we don't have a timeline view, we arrived here via cmd_diff()
	 * (i.e., 'fnc diff' on the CLI), so don't display commit metadata.
	 */
	if (s->timeline_view)
	if (s->showmeta)
		write_commit_meta(s);

	/*
	 * Diff local changes on disk in the current checkout differently to
	 * checked-in versions: the former compares on disk file content with
	 * file artifacts; the latter compares file artifact blobs only.
	 */
2520
2521
2522
2523
2524
2525
2526
2527

2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544

2545
2546
2547
2548
2549
2550
2551
3526
3527
3528
3529
3530
3531
3532

3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549

3550
3551
3552
3553
3554
3555
3556
3557







-
+
















-
+







	 * Parse the diff buffer line-by-line to record byte offsets of each
	 * line for scrolling and searching in diff view.
	 */
	st0 = fsl_strdup(fsl_buffer_str(&s->buf));
	st = st0;
	lnoff = (s->line_offsets)[s->nlines - 1];
	while ((line = fnc_strsep(&st, "\n")) != NULL) {
		n = fsl_fprintf(s->f, "%s\n", line);
		n = fprintf(s->f, "%s\n", line);
		lnoff += n;
		rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff);
		if (rc)
			goto end;
	}

	fputc('\n', s->f);
	++lnoff;
	rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff);
	if (rc)
		goto end;

end:
	free(st0);
	fsl_buffer_clear(&s->buf);
	if (s->f && fflush(s->f) != 0 && rc == 0)
		rc = fsl_cx_err_set(f, FSL_RC_IO, "fflush");
		rc = RC(FSL_RC_IO, "%s", "fflush");
	return rc;
}

static int
create_changeset(struct fnc_commit_artifact *commit)
{
	fsl_cx		*f = fcli_cx();
2561
2562
2563
2564
2565
2566
2567
2568

2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583

2584
2585
2586
2587
2588
2589
2590
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







-
+















+







	    "(SELECT name FROM filename WHERE filename.fnid=mlink.pfnid) "
	    "FROM mlink JOIN filename ON filename.fnid=mlink.fnid "
	    "WHERE mlink.mid=%d AND NOT mlink.isaux "
	    "AND (mlink.fid > 0 "
	    "OR mlink.fnid NOT IN (SELECT pfnid FROM mlink WHERE mid=%d)) "
	    "ORDER BY name", commit->rid, commit->rid);
	if (rc)
		return fsl_cx_err_set(f, FSL_RC_DB, "fsl_db_prepare_cached");
		return RC(FSL_RC_DB, "%s", "fsl_db_prepare_cached");

	while ((rc = fsl_stmt_step(st)) == FSL_RC_STEP_ROW) {
		struct fsl_file_artifact *fdiff = NULL;
		const char *path, *oldpath, *olduuid, *uuid;
		/* TODO: Parse file mode to display in commit changeset. */
		/* int perm; */

		path = fsl_stmt_g_text(st, 0, NULL);	/* Current filename. */
		//perm = fsl_stmt_g_int32(st, 1);	/* File permissions. */
		olduuid = fsl_stmt_g_text(st, 2, NULL);	/* UUID before change */
		uuid = fsl_stmt_g_text(st, 3, NULL);	/* UUID after change. */
		oldpath = fsl_stmt_g_text(st, 4, NULL);	/* Old name, if chngd */

		fdiff = fsl_malloc(sizeof(struct fsl_file_artifact));
		fdiff->fc = fsl_malloc(sizeof(fsl_card_F));
		*fdiff->fc = fsl_card_F_empty;
		fdiff->fc->name = fsl_strdup(path);
		if (!uuid) {
			fdiff->fc->uuid = fsl_strdup(olduuid);
			fdiff->change = FSL_CKOUT_CHANGE_REMOVED;
		} else if (!olduuid) {
			fdiff->fc->uuid = fsl_strdup(uuid);
			fdiff->change = FSL_CKOUT_CHANGE_ADDED;
2612
2613
2614
2615
2616
2617
2618
2619

2620
2621
2622
2623
2624
2625
2626

2627
2628
2629
2630
2631
2632

2633
2634
2635
2636
2637
2638
2639

2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654

2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665

2666
2667
2668
2669
2670
2671
2672
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







-
+






-
+





-
+






-
+














-
+










-
+







write_commit_meta(struct fnc_diff_view_state *s)
{
	char		*line = NULL, *st0 = NULL, *st = NULL;
	fsl_size_t	 linelen, idx = 0;
	off_t		 lnoff = 0;
	int		 n, rc = 0;

	if ((n = fsl_fprintf(s->f,"%s %s\n", s->selected_commit->type,
	if ((n = fprintf(s->f,"%s %s\n", s->selected_commit->type,
	    s->selected_commit->uuid)) < 0)
		goto end;
	lnoff += n;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	if ((n = fsl_fprintf(s->f,"user: %s\n", s->selected_commit->user)) < 0)
	if ((n = fprintf(s->f,"user: %s\n", s->selected_commit->user)) < 0)
		goto end;
	lnoff += n;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	if ((n = fsl_fprintf(s->f,"tags: %s\n", s->selected_commit->branch ?
	if ((n = fprintf(s->f,"tags: %s\n", s->selected_commit->branch ?
	    s->selected_commit->branch : "/dev/null")) < 0)
		goto end;
	lnoff += n;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	if ((n = fsl_fprintf(s->f,"date: %s\n",
	if ((n = fprintf(s->f,"date: %s\n",
	    s->selected_commit->timestamp)) < 0)
		goto end;
	lnoff += n;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	fputc('\n', s->f);
	++lnoff;
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
		goto end;

	st0 = fsl_strdup(s->selected_commit->comment);
	st = st0;
	if (st == NULL) {
		fcli_err_set(FSL_RC_OOM, "fsl_strdup");
		RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		goto end;
	}
	while ((line = fnc_strsep(&st, "\n")) != NULL) {
		linelen = fsl_strlen(line);
		if (linelen >= s->ncols) {
			rc = wrapline(line, s->ncols, s, &lnoff);
			if (rc)
				goto end;
		}
		else {
			if ((n = fsl_fprintf(s->f, "%s\n", line)) < 0)
			if ((n = fprintf(s->f, "%s\n", line)) < 0)
				goto end;
			lnoff += n;
			if ((rc = add_line_offset(&s->line_offsets, &s->nlines,
			    lnoff)))
				goto end;

		}
2697
2698
2699
2700
2701
2702
2703
2704

2705
2706
2707
2708
2709
2710
2711
3704
3705
3706
3707
3708
3709
3710

3711
3712
3713
3714
3715
3716
3717
3718







-
+







		case FSL_CKOUT_CHANGE_REMOVED:
			changeline = "[-] ";
			break;
		default:
			changeline = "[!] ";
			break;
		}
		if ((n = fsl_fprintf(s->f, "%s%s\n", changeline,
		if ((n = fprintf(s->f, "%s%s\n", changeline,
		    file_change->fc->name)) < 0)
			goto end;
		lnoff += n;
		if ((rc = add_line_offset(&s->line_offsets, &s->nlines, lnoff)))
			goto end;
	}

2743
2744
2745
2746
2747
2748
2749
2750

2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771

2772
2773
2774
2775
2776
2777
2778
3750
3751
3752
3753
3754
3755
3756

3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772

3773
3774
3775
3776

3777
3778
3779
3780
3781
3782
3783
3784







-
+















-




-
+







			++(*lnoff);
			rc = add_line_offset(&s->line_offsets, &s->nlines,
			    *lnoff);
			if (rc)
				return rc;
			cursor = 0;
		}
		if ((n  = fsl_fprintf(s->f, "%s ", word)) < 0)
		if ((n  = fprintf(s->f, "%s ", word)) < 0)
			return rc;
		*lnoff += n;
		cursor += n;
	}
	fputc('\n', s->f);
	++(*lnoff);
	if ((rc = add_line_offset(&s->line_offsets, &s->nlines, *lnoff)))
		return rc;

	return 0;
}

static int
add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
{
	fsl_cx	*f = fcli_cx();
	off_t	*p;

	p = fsl_realloc(*line_offsets, (*nlines + 1) * sizeof(off_t));
	if (p == NULL)
		return fsl_cx_err_set(f, FSL_RC_OOM, "fsl_realloc");
		return RC(FSL_RC_ERROR, "%s", "fsl_realloc");
	*line_offsets = p;
	(*line_offsets)[*nlines] = off;
	(*nlines)++;

	return 0;
}

2857
2858
2859
2860
2861
2862
2863
2864






2865
2866
2867
2868
2869
2870
2871
3863
3864
3865
3866
3867
3868
3869

3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882







-
+
+
+
+
+
+







		} else {
			change = FSL_CKOUT_CHANGE_MOD;
			rc = diff_file_artifact(buf, id1, fc1, commit->rid, fc2,
			    change, diff_flags, context, sbs);
			fsl_deck_F_next(&d1, &fc1);
			fsl_deck_F_next(&d2, &fc2);
		}
		if (rc == FSL_RC_RANGE || rc == FSL_RC_TYPE) {
		if (rc == FSL_RC_RANGE) {
			fsl_buffer_append(buf,
			    "\nDiff has too many changes\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc == FSL_RC_DIFF_BINARY) {
			fsl_buffer_append(buf,
			    "\nBinary files cannot be diffed\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc)
			goto end;
	}
2899
2900
2901
2902
2903
2904
2905
2906

2907
2908
2909
2910
2911
2912
2913
3910
3911
3912
3913
3914
3915
3916

3917
3918
3919
3920
3921
3922
3923
3924







-
+







	abspath = bminus = sql = fsl_buffer_empty;
	fsl_ckout_version_info(f, &cid, NULL);
	/* cid = fsl_config_get_id(f, FSL_CONFDB_CKOUT, 0, "checkout"); */
	/* XXX Already done in cmd_diff(): Load vfile table with local state. */
	/* rc = fsl_vfile_changes_scan(f, cid, */
	/*     FSL_VFILE_CKSIG_ENOTFILE & FSL_VFILE_CKSIG_KEEP_OTHERS); */
	/* if (rc) */
	/*	return fcli_err_set(rc, "fsl_vfile_changes_scan"); */
	/*	return RC(rc, "%s", "fsl_vfile_changes_scan"); */

	/*
	 * If a previous version is supplied, load its vfile state to query
	 * changes. Otherwise query the current checkout state for changes.
	 */
	if (vid != cid) {
		/* Keep vfile ckout state; but unload vid when finished. */
2996
2997
2998
2999
3000
3001
3002
3003

3004
3005
3006
3007
3008
3009
3010

3011
3012
3013
3014
3015
3016
3017
4007
4008
4009
4010
4011
4012
4013

4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029







-
+







+







			if (rc)
				goto yield;
			do {
				fsl_deck_F_next(&d, &cf);
				if (cf && !fsl_strcmp(cf->name, path)) {
					xminus = fsl_strdup(cf->uuid);
					if (xminus == NULL) {
						fcli_err_set(FSL_RC_OOM,
						RC(FSL_RC_ERROR, "%s",
						    "fsl_strdup");
						goto yield;
					}
					fid = fsl_uuid_to_rid(f, xminus);
					break;
				}
			} while (cf);
			fsl_deck_finalize(&d);
		}
		if (!xminus)
			xminus = fsl_strdup(NULL_DEVICE);

		if (!symlink != !fsl_is_symlink(fsl_buffer_cstr(&abspath))) {
			rc = write_diff_meta(buf, path, xminus, path,
			    NULL_DEVICE, diff_flags, change);
3029
3030
3031
3032
3033
3034
3035
3036






3037
3038
3039
3040
3041
3042
3043
4041
4042
4043
4044
4045
4046
4047

4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060







-
+
+
+
+
+
+







			rc = diff_file(buf, &bminus, path, xminus,
			    fsl_buffer_cstr(&abspath), change, diff_flags,
			    context, sbs);
		fsl_buffer_reuse(&bminus);
		fsl_buffer_reuse(&abspath);
		fsl_free(xminus);
		xminus = NULL;
		if (rc == FSL_RC_RANGE || rc == FSL_RC_TYPE) {
		if (rc == FSL_RC_RANGE) {
			fsl_buffer_append(buf,
			    "\nDiff has too many changes\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc == FSL_RC_DIFF_BINARY) {
			fsl_buffer_append(buf,
			    "\nBinary files cannot be diffed\n", -1);
			rc = 0;
			fsl_cx_err_reset(f);
		} else if (rc)
			goto yield;
	}
3147
3148
3149
3150
3151
3152
3153
3154

3155
3156
3157
3158
3159
3160
3161
4164
4165
4166
4167
4168
4169
4170

4171
4172
4173
4174
4175
4176
4177
4178







-
+







	 * as being entirely removed. With this check, fnc now contrasts the
	 * behaviour of fossil(1), which produces the abovementioned unexpected
	 * output described in (1) and (2).
	 */
	if (fsl_file_size(abspath) < 0)
		zplus = NULL_DEVICE;
	else if (change != FSL_CKOUT_CHANGE_REMOVED) {
		rc = fsl_ckout_file_content(f, abspath, &bplus);
		rc = fsl_ckout_file_content(f, false, abspath, &bplus);
		if (rc)
			goto end;
		/*
		 * To replicate fossil(1)'s behaviour—where a fossil rm'd file
		 * will either show as an unchanged or edited rather than a
		 * removed file with 'fossil diff -v' output—remove the above
		 * 'if (change != FSL_CKOUT_CHANGE_REMOVED)' from the else
3186
3187
3188
3189
3190
3191
3192
3193
3194

3195
3196
3197
3198
3199
3200
3201
4203
4204
4205
4206
4207
4208
4209


4210
4211
4212
4213
4214
4215
4216
4217







-
-
+







			/* FALL THROUGH */
		case FSL_HPOLICY_SHA3_ONLY:
			rc = fsl_sha3sum_buffer(&bplus, &xplus);
			break;
		}
		break;
	default:
		fcli_err_set(FSL_RC_SIZE_MISMATCH,
		    "invalid artifact uuid [%s], xminus");
		RC(FSL_RC_SIZE_MISMATCH, "invalid artifact uuid [%s]", xminus);
		goto end;
	}
	if (rc)
		goto end;

	rc = write_diff_meta(buf, zminus, xminus, zplus, fsl_buffer_str(&xplus),
	    diff_flags, change);
3234
3235
3236
3237
3238
3239
3240
3241

3242
3243
3244
3245
3246
3247
3248
4250
4251
4252
4253
4254
4255
4256

4257
4258
4259
4260
4261
4262
4263
4264







-
+







	fsl_id_t	 prid = 0;
	fsl_size_t	 idx;
	int		 rc = 0;

	fsl_deck *d = NULL;
	d = fsl_deck_malloc();
	if (d == NULL)
		return fsl_cx_err_set(f, FSL_RC_OOM, "fsl_deck_malloc");
		return RC(FSL_RC_ERROR, "%s", "fsl_deck_malloc");

	fsl_deck_init(f, d, FSL_SATYPE_ANY);
	if ((rc = fsl_deck_load_rid(f, d, commit->rid, FSL_SATYPE_ANY)))
		goto end;

	/*
	 * Present ticket commits as a series of field: value tuples as per
3374
3375
3376
3377
3378
3379
3380
3381

3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392

3393
3394
3395


3396
3397
3398
3399
3400




3401
3402
3403





3404
3405

3406
3407
3408

3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419








3420
3421
3422
3423
3424
3425
3426
3427

3428
3429
3430
3431
3432

3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456

3457
3458
3459
3460
3461
3462
3463
3464
3465

3466
3467
3468
3469
3470
3471
3472
4390
4391
4392
4393
4394
4395
4396

4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407

4408
4409


4410
4411
4412




4413
4414
4415
4416
4417


4418
4419
4420
4421
4422


4423



4424











4425
4426
4427
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
4457

4458

4459
4460
4461
4462
4463
4464


4465
4466
4467
4468
4469
4470
4471
4472







-
+










-
+

-
-
+
+

-
-
-
-
+
+
+
+

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

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







-















-
+
-






-
-
+







	rc = write_diff_meta(buf, zminus, xminus, zplus, xplus, diff_flags,
	    change);
	verbose = (diff_flags & FSL_DIFF_VERBOSE) != 0 ? true : false;
	if (verbose || (a && b))
		rc = fsl_diff_text_to_buffer(&fbuf1, &fbuf2, buf, context, sbs,
		    diff_flags);
	if (rc)
		fcli_err_set(rc, "Error %s: fsl_diff_text_to_buffer\n"
		RC(rc, "%s: fsl_diff_text_to_buffer\n"
		    " -> %s [%s]\n -> %s [%s]", fsl_rc_cstr(rc),
		    a ? a->name : NULL_DEVICE, a ? a->uuid : NULL_DEVICE,
		    b ? b->name : NULL_DEVICE, b ? b->uuid : NULL_DEVICE);
end:
	fsl_buffer_clear(&fbuf1);
	fsl_buffer_clear(&fbuf2);
	return rc;
}

static int
fsl_ckout_file_content(fsl_cx *f, char const *path, fsl_buffer *dest)
show_diff(struct fnc_view *view)
{
	fsl_buffer	fname = fsl_buffer_empty;
	int		rc;
	struct fnc_diff_view_state	*s = &view->state.diff;
	char				*headln, *id2, *id1 = NULL;

	if (!f || !path || !*path || !dest)
		return FSL_RC_MISUSE;
	else if (!fsl_needs_ckout(f))
		return FSL_RC_NOT_A_CKOUT;
	/* Some diffs (e.g., technote, tag) have no parent hash to display. */
	id1 = fsl_strdup(s->id1 ? s->id1 : "/dev/null");
	if (id1 == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");

	fname.used = 0;
	rc = fsl_file_canonical_name2(fsl_cx_ckout_dir_name(f, NULL), path,
	/*
	 * If diffing the work tree, we have no hash to display for it.
	 * XXX Display "work tree" or "checkout" or "/dev/null" for clarity?
	 */
	id2 = fsl_strdup(s->id2 ? s->id2 : "");
	    &fname, true);
	if (!rc) {
	if (id2 == NULL) {
		assert(fname.used);
		if (fname.mem[fname.used - 1] == '/') {
			rc = fsl_cx_err_set(f, FSL_RC_MISUSE,
		fsl_free(id1);
			    "Filename may not have a trailing slash.");
		} else {
			dest->used = 0;
			rc = fsl_buffer_fill_from_filename(dest,
			    fsl_buffer_cstr(&fname));
		}
	}
	fsl_buffer_clear(&fname);

	return rc;
}
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	}

	if ((headln = fsl_mprintf("diff %.40s %.40s", id1, id2)) == NULL) {
		fsl_free(id1);
		fsl_free(id2);
		return RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
	}

static int
show_diff(struct fnc_view *view)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	fsl_cx				*f = fcli_cx();
	char				*headln;

	fsl_free(id1);
	if ((headln = fsl_mprintf("diff %.40s %.40s",
	    s->selected_commit->puuid ? s->selected_commit->puuid : "/dev/null",
	    s->selected_commit->uuid)) == NULL)
		return fsl_cx_err_set(f, FSL_RC_RANGE, "mprintf");

	fsl_free(id2);
	return write_diff(view, headln);
}

static int
write_diff(struct fnc_view *view, char *headln)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	fsl_cx				*f = fcli_cx();
	regmatch_t			*regmatch = &view->regmatch;
	struct fnc_colour		*c = NULL;
	wchar_t				*wcstr;
	char				*line;
	size_t				 linesz = 0;
	ssize_t				 linelen;
	off_t				 line_offset;
	int				 wstrlen;
	int				 max_lines = view->nlines;
	int				 nlines = s->nlines;
	int				 rc = 0, nprintln = 0;
	int				 match = -1;

	line_offset = s->line_offsets[s->first_line_onscreen - 1];
	if (fseeko(s->f, line_offset, SEEK_SET))
		return fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_ERROR),
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "fseeko");
		    "fseeko");

	werase(view->window);

	if (headln) {
		if ((line = fsl_mprintf("[%d/%d] %s", (s->first_line_onscreen -
		    1 + s->current_line), nlines, headln)) == NULL)
			return fsl_cx_err_set(f, fsl_errno_to_rc(errno,
			    FSL_RC_ERROR), "mprintf");
			return RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0);
		fsl_free(line);
		fsl_free(headln);
		if (rc)
			return rc;

		if (screen_is_shared(view))
3490
3491
3492
3493
3494
3495
3496
3497
3498


3499
3500
3501
3502
3503
3504
3505
4490
4491
4492
4493
4494
4495
4496


4497
4498
4499
4500
4501
4502
4503
4504
4505







-
-
+
+







		linelen = getline(&line, &linesz, s->f);
		if (linelen == -1) {
			if (feof(s->f)) {
				s->eof = true;
				break;
			}
			fsl_free(line);
			fsl_cx_err_set(f, fsl_errno_to_rc(ferror(s->f),
			    FSL_RC_IO), "getline");
			RC(ferror(s->f) ? fsl_errno_to_rc(errno, FSL_RC_IO) :
			    FSL_RC_IO, "%s", "getline");
			return rc;
		}

		if (s->colour && (match = fsl_list_index_of(&s->colours, line,
		    match_line)) != -1)
			c = s->colours.list[match];
		if (c)
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
4586
4587
4588
4589
4590
4591
4592

4593
4594
4595
4596
4597
4598
4599
4600
4601
4602

4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620

4621
4622
4623
4624
4625
4626
4627
4628
4629

4630
4631

4632
4633
4634
4635
4636
4637
4638
4639







-










-
+

















-
+








-
+

-
+







	return view->start_col > 0;
}

static int
write_matched_line(int *col_pos, const char *line, int ncols_avail,
    int start_column, WINDOW *window, regmatch_t *regmatch)
{
	fsl_cx		*f = fcli_cx();
	wchar_t		*wcstr;
	char		*s;
	int		 wstrlen;
	int		 rc = 0;

	*col_pos = 0;

	/* Copy the line up to the matching substring & write it to screen. */
	s = fsl_strndup(line, regmatch->rm_so);
	if (s == NULL)
		return fsl_cx_err_set(f, FSL_RC_OOM, "fsl_strndup");
		return RC(FSL_RC_ERROR, "%s", "fsl_strndup");

	rc = formatln(&wcstr, &wstrlen, s, ncols_avail, start_column);
	if (rc) {
		free(s);
		return rc;
	}
	waddwstr(window, wcstr);
	free(wcstr);
	free(s);
	ncols_avail -= wstrlen;
	*col_pos += wstrlen;

	/* If not EOL, copy matching string & write to screen with highlight. */
	if (ncols_avail > 0) {
		s = fsl_strndup(line + regmatch->rm_so,
		    regmatch->rm_eo - regmatch->rm_so);
		if (s == NULL) {
			rc = fsl_cx_err_set(f, FSL_RC_OOM, "strndup");
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strndup");
			free(s);
			return rc;
		}
		rc = formatln(&wcstr, &wstrlen, s, ncols_avail, start_column);
		if (rc) {
			free(s);
			return rc;
		}
		wattr_on(window, A_STANDOUT, NULL);
		wattr_on(window, A_REVERSE, NULL);
		waddwstr(window, wcstr);
		wattr_off(window, A_STANDOUT, NULL);
		wattr_off(window, A_REVERSE, NULL);
		free(wcstr);
		free(s);
		ncols_avail -= wstrlen;
		*col_pos += wstrlen;
	}

	/* Write the rest of the line if not yet at EOL. */
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
4674
4675
4676
4677
4678
4679
4680

4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706


4707
4708
4709
4710
4711
4712
4713
4714
4715







-














+










+
-
-
+
+








static int
diff_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	struct fnc_tl_view_state	*tlstate;
	struct commit_entry		*previous_selection;
	fsl_cx				*f = fcli_cx();
	char				*line = NULL;
	ssize_t				 linelen;
	size_t				 linesz = 0;
	int				 i, rc = 0;
	bool				 tl_down = false;

	switch (ch) {
	case KEY_DOWN:
	case 'j':
		if (!s->eof)
			++s->first_line_onscreen;
		break;
	case KEY_NPAGE:
	case CTRL('f'):
	case ' ':
		if (s->eof)
			break;
		i = 0;
		while (!s->eof && i++ < view->nlines - 1) {
			linelen = getline(&line, &linesz, s->f);
			++s->first_line_onscreen;
			if (linelen == -1) {
				if (feof(s->f))
					s->eof = true;
				else
					RC(ferror(s->f) ?
					rc = fsl_cx_err_set(f, fsl_errno_to_rc
					    (errno, FSL_RC_IO), "ftell");
					    fsl_errno_to_rc(errno, FSL_RC_IO) :
					    FSL_RC_IO, "%s", "getline");
				break;
			}
		}
		free(line);
		break;
	case KEY_END:
	case 'G':
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
4727
4728
4729
4730
4731
4732
4733

4734






4735
4736
4737

4738
4739
4740
4741
4742
4743
4744
4745

4746
4747
4748
4749
4750
4751
4752
4753







-
+
-
-
-
-
-
-
+


-








-
+







	case CTRL('b'):
		if (s->first_line_onscreen == 1)
			break;
		i = 0;
		while (i++ < view->nlines - 1 && s->first_line_onscreen > 1)
			--s->first_line_onscreen;
		break;
	case 'g': {
	case 'g':
		bool home = true;
		halfdelay(10);	/* Only block for 1 second, then return ERR. */
		if (wgetch(view->window) != 'g')
			home = false;
		cbreak();	/* Return to blocking mode on user input. */
		if (!home)
		if (!fnc_home(view))
			break;
		/* FALL THROUGH */
	}
	case KEY_HOME:
		s->first_line_onscreen = 1;
		break;
	case 'c':
	case 'i':
	case 'v':
	case 'w':
		if (ch == 'c')
			s->colour = s->colour == false;
			s->colour = !s->colour;
		if (ch == 'i')
			s->diff_flags ^= FSL_DIFF_INVERT;
		if (ch == 'v')
			s->diff_flags ^= FSL_DIFF_VERBOSE;
		if (ch == 'w')
			s->diff_flags ^= FSL_DIFF_IGNORE_ALLWS;
		wclear(view->window);
3820
3821
3822
3823
3824
3825
3826






3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844

4845
4846
4847
4848
4849
4850
4851







+
+
+
+
+
+


















-








	return rc;
}

static int
set_selected_commit(struct fnc_diff_view_state *s, struct commit_entry *entry)
{
	fsl_free(s->id2);
	s->id2 = fsl_strdup(entry->commit->uuid);
	if (s->id2 == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
	fsl_free(s->id1);
	s->id1 = entry->commit->puuid ? fsl_strdup(entry->commit->puuid) : NULL;
	s->selected_commit = entry->commit;

	return 0;
}

static int
diff_search_init(struct fnc_view *view)
{
	struct fnc_diff_view_state *s = &view->state.diff;

	s->matched_line = 0;
	return 0;
}

static int
diff_search_next(struct fnc_view *view)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	fsl_cx				*f = fcli_cx();
	char				*line = NULL;
	ssize_t				 linelen;
	size_t				 linesz = 0;
	int				 start_ln;

	if (view->searching == SEARCH_DONE) {
		view->search_status = SEARCH_CONTINUE;
3879
3880
3881
3882
3883
3884
3885
3886
3887


3888
3889
3890
3891
3892
3893
3894
4878
4879
4880
4881
4882
4883
4884


4885
4886
4887
4888
4889
4890
4891
4892
4893







-
-
+
+







			else
				start_ln = s->nlines;
		}

		offset = s->line_offsets[start_ln - 1];
		if (fseeko(s->f, offset, SEEK_SET) != 0) {
			free(line);
			return fsl_cx_err_set(f, fsl_errno_to_rc(errno,
			    FSL_RC_IO), "fseeko");
			return RC(fsl_errno_to_rc(errno, FSL_RC_IO),
			    "%s", "fseeko");
		}
		linelen = getline(&line, &linesz, s->f);
		if (linelen != -1 && regexec(&view->regex, line, 1,
		    &view->regmatch, 0) == 0) {
			view->search_status = SEARCH_CONTINUE;
			s->matched_line = start_ln;
			break;
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922






3923
3924
3925
3926
3927
3928
3929
4908
4909
4910
4911
4912
4913
4914

4915
4916
4917



4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930







-



-
-
-
+
+
+
+
+
+







}

static int
close_diff_view(struct fnc_view *view)
{
	struct fnc_diff_view_state	*s = &view->state.diff;
	struct fsl_list_state		st = { FNC_COLOUR_OBJ };
	fsl_cx				*f = fcli_cx();
	int				 rc = 0;

	if (s->f && fclose(s->f) == EOF)
		rc = fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_IO),
		    "fclose");
	free(s->line_offsets);
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fclose");
	fsl_free(s->id1);
	s->id1 = NULL;
	fsl_free(s->id2);
	s->id2 = NULL;
	fsl_free(s->line_offsets);
	fsl_list_clear(&s->colours, fsl_list_object_free, &st);
	s->line_offsets = NULL;
	s->nlines = 0;
	return rc;
}

static void
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962

3963
3964
3965
3966

3967
3968
3969
3970
3971
3972
3973
4942
4943
4944
4945
4946
4947
4948

4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961

4962

4963


4964
4965
4966
4967
4968
4969
4970
4971







-













-
+
-

-
-
+







	}
	resize_term(lines, cols);
}

static int
view_resize(struct fnc_view *view)
{
	fsl_cx	*f = fcli_cx();
	int	 nlines, ncols;

	if (view->lines > LINES)
		nlines = view->nlines - (view->lines - LINES);
	else
		nlines = view->nlines + (LINES - view->lines);

	if (view->cols > COLS)
		ncols = view->ncols - (view->cols - COLS);
	else
		ncols = view->ncols + (COLS - view->cols);

	if (wresize(view->window, nlines, ncols) == ERR)
		return fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_ERROR),
		return RC(FSL_RC_ERROR, "%s", "wresize");
		    "curses wresize -> %s", __func__);
	if (replace_panel(view->panel, view->window) == ERR)
		return fsl_cx_err_set(f, fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "curses replace_panel -> %s", __func__);
		return RC(FSL_RC_ERROR, "%s", "replace_panel");
	wclear(view->window);

	view->nlines = nlines;
	view->ncols = ncols;
	view->lines = LINES;
	view->cols = COLS;

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
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253










































5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089



5090
5091
5092
5093
5094
5095
5096
5097
5098
5099

5100
5101

5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118

5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129

5130

5131

5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151

5152
5153
5154
5155
5156
5157
5158
5159

5160
5161
5162
5163
5164
5165

5166
5167
5168
5169

5170
5171
5172
5173

5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186


5187
5188




5189
5190
5191
5192
5193
5194
5195
5196
5197
5198

5199
5200
5201
5202
5203

5204


5205
5206








5207



5208
5209
5210



5211
5212
5213
5214
5215
5216

5217
5218
5219

5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
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
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
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
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
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
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
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
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
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
6591
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
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
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
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776







+












-
-
-
+
+
+







-
+

-
+
+
+
+
+
+
+
+
+
+







-
+










-
+
-

-
+



















-
+







-
+





-
+



-
+



-
+












-
-
+
+
-
-
-
-
+
+






+
+
-
+
+
+


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

-
-
-
+
+

-
-
-
+
+
+
+
+

-
+


-
+



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




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







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


















+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
		}

	/* Otherwise, output help/usage for all commands. */
	fcli_command_help(fnc_init.cmd_args, false);
	fsl_fprintf(f, "[usage]\n\n");
	usage_timeline();
	usage_diff();
	usage_tree();
	usage_blame();
	fsl_fprintf(f, "  note: %s "
	    "with no args defaults to the timeline command.\n\n",
	    fcli_progname());

	exit(fcli_end_of_main(fnc_init.err));
}

static void
usage_timeline(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " %s timeline [-T tag] [-b branch] [-c sym]"
	    " [-h|--help] [-n n] [-t type] [-u user] [-z|--utc]\n"
	    "  e.g.: %s timeline --type ci -u jimmy\n\n",
	    " %s timeline [-T tag] [-b branch] [-c commit]"
	    " [-h|--help] [-n n] [-t type] [-u user] [-z|--utc] [path]\n"
	    "  e.g.: %s timeline --type ci -u jimmy src/frobnitz.c\n\n",
	    fcli_progname(), fcli_progname());
}

static void
usage_diff(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " %s diff [-c|--no-colour] [-h|--help] [-i|--invert]"
	    " %s diff [-C|--no-colour] [-h|--help] [-i|--invert]"
	    " [-q|--quiet] [-w|--whitespace] [-x|--context n] "
	    "[sym ...]\n  e.g.: %s diff --context 3 d34db33f c0ff33\n\n",
	    "[commit ...]\n  e.g.: %s diff --context 3 d34db33f c0ff33\n\n",
	    fcli_progname(), fcli_progname());
}

static void
usage_tree(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " %s tree [-C|--no-colour] [-h|--help] [-c commit] [path]\n"
	    "  e.g.: %s tree -c d34dc0d3\n\n" ,
	    fcli_progname(), fcli_progname());
}

static void
usage_blame(void)
{
	fsl_fprintf(fnc_init.err ? stderr : stdout,
	    " %s blame [-h|--help] [-c hash] artifact\n"
	    " %s blame [-c commit [-r]] [-h|--help] [-n n] path\n"
	    "  e.g.: %s blame -c d34db33f src/foo.c\n\n" ,
	    fcli_progname(), fcli_progname());
}

static int
cmd_diff(fcli_command const *argv)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_view			*view;
	struct fnc_commit_artifact	*commit = NULL;
	const char			*artifact1, *artifact2, *s;
	const char			*artifact1, *artifact2;
	char				*ptr;
	fsl_id_t			 prid = -1, rid = -1;
	int				 context, rc = 0;
	int				 context = DIFF_DEF_CTXT, rc = 0;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		return rc;

	/*
	 * If only one artifact is supplied, use the local changes in the
	 * current checkout to diff against it. If no artifacts are supplied,
	 * diff any local changes on disk against the current checkout.
	 */
	if (fcli.argc == 2) {
		artifact1 = fcli_next_arg(true);
		artifact2 = fcli_next_arg(true);
	} else if (fcli.argc < 2) {
		artifact1 = "current";
		rid = 0;
		if (fcli_next_arg(false))
			artifact1 = fcli_next_arg(true);
		if ((rc = fsl_ckout_changes_scan(f)))
			return fcli_err_set(rc, "fsl_ckout_changes_scan");
			return RC(rc, "%s", "fsl_ckout_changes_scan");
		if (!fsl_strcmp(artifact1, "current") &&
		    !fsl_ckout_has_changes(f)) {
			fsl_fprintf(stdout, "No local changes.\n");
			return rc;
		}
	} else { /* fcli_* APIs should prevent getting here but just in case. */
		usage_diff();
		return fcli_err_set(FSL_RC_MISUSE, "\ninvalid args");
		return RC(FSL_RC_MISUSE, "invalid args: %s", fcli.argv);
	}

	/* Find the corresponding rids for the versions we have; checkout = 0 */
	rc = fsl_sym_to_rid(f, artifact1, FSL_SATYPE_ANY, &prid);
	if (rc || prid < 0)
		return fcli_err_set(rc, "invalid artifact [%s]", artifact1);
		return RC(rc, "invalid artifact [%s]", artifact1);
	if (rid != 0)
		rc = fsl_sym_to_rid(f, artifact2, FSL_SATYPE_ANY, &rid);
	if (rc || rid < 0)
		return fcli_err_set(rc, "invalid artifact [%s]", artifact2);
		return RC(rc, "invalid artifact [%s]", artifact2);

	commit = calloc(1, sizeof(*commit));
	if (commit == NULL)
		return fcli_err_set(FSL_RC_OOM, "calloc fail");
		return RC(FSL_RC_ERROR, "%s", "calloc fail");
	if (rid == 0)
		fsl_ckout_version_info(f, NULL, (fsl_uuid_cstr *)commit->uuid);
	else
		commit->uuid = fsl_rid_to_uuid(f, rid);
	commit->puuid = fsl_rid_to_uuid(f, prid);
	commit->prid = prid;
	commit->rid = rid;

	/*
	 * If either of the supplied versions are not checkin artifacts,
	 * let the user know which operands aren't valid.
	 */
	if ((fsl_rid_is_a_checkin(f, rid) || rid == 0) &&
	    fsl_rid_is_a_checkin(f, prid))
	if ((!fsl_rid_is_a_checkin(f, rid) && rid != 0) ||
	    !fsl_rid_is_a_checkin(f, prid))
		commit->type = fsl_strdup("checkin");
	else
		return fcli_err_set(FSL_RC_TYPE,
		    "artifact(s) [%s] not resolvable to a checkin",
		return RC(FSL_RC_TYPE,
		    "artifact(s) [%s] not resolvable to checkin(s)",
		    (!fsl_rid_is_a_checkin(f, rid) && rid != 0) &&
		    !fsl_rid_is_a_checkin(f, prid) ?
		    fsl_mprintf("%s / %s", artifact1, artifact2) :
		    (!fsl_rid_is_a_checkin(f, rid) && rid != 0) ?
		    artifact2 : artifact1);

	commit->type = fsl_strdup("checkin");

	init_curses();
	rc = init_curses();
	if (rc)
		goto end;

	if (fnc_init.context) {
		s = fnc_init.context;
		if ((rc = strtonumcheck(&context, fnc_init.context, INT_MIN,
		context = strtol(s, &ptr, 10);
		if (errno == ERANGE)
		    INT_MAX)))
			goto end;
			return fsl_cx_err_set(f, FSL_RC_RANGE,
			    "out of range: -x|--context=%s [%s]", s, ptr);
		else if (errno != 0 || errno == EINVAL)
			return fsl_cx_err_set(f, FSL_RC_MISUSE,
			    "not a number: -x|--context=%s [%s]", s, ptr);
		else if (ptr && *ptr != '\0')
			return fsl_cx_err_set(f, FSL_RC_MISUSE,
			    "invalid char: -x|--context=%s [%s]", s, ptr);
		context = MIN(DIFF_MAX_CTXT, context);
	} else
		context = 5;

	}

	view = view_open(0, 0, 0, 0, FNC_VIEW_DIFF);
	if (view == NULL)
		return fcli_err_set(FSL_RC_OOM, "view_open fail");

	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_diff_view(view, commit, context, fnc_init.ws,
	    fnc_init.invert, !fnc_init.quiet, NULL);
	    fnc_init.invert, !fnc_init.quiet, NULL, false);
	if (!rc)
		rc = view_loop(view);

end:
	fnc_commit_artifact_close(commit);
	return rc;
}

static int
browse_commit_tree(struct fnc_view **new_view, int start_col,
    struct commit_entry *entry, const char *path)
{
	struct fnc_view	*tree_view;
	int		 rc = 0;

	tree_view = view_open(0, 0, 0, start_col, FNC_VIEW_TREE);
	if (tree_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	rc = open_tree_view(tree_view, path, entry->commit->rid);
	if (rc)
		return rc;

	*new_view = tree_view;

	return rc;
}

static int
cmd_tree(fcli_command const *argv)
{
	fsl_cx		*f = fcli_cx();
	struct fnc_view	*view;
	char		*path = NULL;
	fsl_id_t	 rid;
	int		 rc = 0;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		goto end;

	rc = map_repo_path(&path);
	if (rc)
		goto end;
	if (fnc_init.sym)
		rc = fsl_sym_to_rid(f, fnc_init.sym, FSL_SATYPE_CHECKIN, &rid);
	else
		fsl_ckout_version_info(f, &rid, NULL);

	if (rc) {
		switch (rc) {
		case FSL_RC_AMBIGUOUS:
			RC(rc, "prefix too ambiguous [%s]",
			    fnc_init.sym);
			goto end;
		case FSL_RC_NOT_A_REPO:
			RC(rc, "%s tree needs a local checkout",
			    fcli_progname());
			goto end;
		case FSL_RC_NOT_FOUND:
			RC(rc, "invalid symbolic checkin name [%s]",
			    fnc_init.sym);
			goto end;
		case FSL_RC_MISUSE:
			/* FALL THROUGH */
		default:
			goto end;
		}
	}

	if (!fsl_rid_is_a_checkin(f, rid)) {
		RC(FSL_RC_TYPE, "%s tree can only open a check-in",
		    fcli_progname());
		goto end;
	}

	rc = init_curses();
	if (rc)
		goto end;

	view = view_open(0, 0, 0, 0, FNC_VIEW_TREE);
	if (view == NULL) {
		RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_tree_view(view, path, rid);
	if (!rc)
		rc = view_loop(view);
end:
	fsl_free(path);
	return rc;
}

static int
open_tree_view(struct fnc_view *view, const char *path, fsl_id_t rid)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_tree_view_state	*s = &view->state.tree;
	int				 rc = 0;

	TAILQ_INIT(&s->parents);
	s->show_id = false;
	s->colour = !fnc_init.nocolour && has_colors();
	s->rid = rid;
	s->commit_id = fsl_rid_to_uuid(f, rid);
	if (s->commit_id == NULL)
		return RC(FSL_RC_AMBIGUOUS, "%s", "fsl_rid_to_uuid");

	/*
	 * Construct tree of entire repository from which all (sub)tress will
	 * be derived. This object will be released when this view closes.
	 */
	rc = create_repository_tree(&s->repo, &s->commit_id, s->rid);
	if (rc)
		goto end;

	/*
	 * Open the initial root level of the repository tree now. Subtrees
	 * opened during traversal are built and destroyed on demand.
	 */
	rc = tree_builder(s->repo, &s->root, "/");
	if (rc)
		goto end;
	s->tree = s->root;
	/*
	 * If user has supplied a path arg (i.e., fnc tree path/in/repo), or
	 * has selected a commit from an 'fnc timeline path/in/repo' command,
	 * walk the path and open corresponding (sub)tree objects now.
	 */
	if (!fnc_path_is_root_dir(path)) {
		rc = walk_tree_path(s, s->repo, &s->root, path);
		if (rc)
			goto end;
	}


	if ((s->tree_label = fsl_mprintf("checkin %s", s->commit_id)) == NULL) {
		rc = RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		goto end;
	}

	s->first_entry_onscreen = &s->tree->entries[0];
	s->selected_entry = &s->tree->entries[0];

	if (s->colour)
		set_colours(&s->colours, FNC_VIEW_TREE);

	view->show = show_tree_view;
	view->input = tree_input_handler;
	view->close = close_tree_view;
	view->search_init = tree_search_init;
	view->search_next = tree_search_next;
end:
	if (rc)
		close_tree_view(view);
	return rc;
}

/*
 * Decompose the supplied path into its constituent components, then build,
 * open and visit each subtree segment on the way to the requested entry.
 */
static int
walk_tree_path(struct fnc_tree_view_state *s, struct fnc_repository_tree *repo,
    struct fnc_tree_object **root, const char *path)
{
	struct fnc_tree_object	*tree = NULL;
	const char		*p;
	char			*slash, *subpath = NULL;
	int			 rc = 0;

	/* Find each slash and open preceding directory segment as a tree. */
	p = path;
	while (*p) {
		struct fnc_tree_entry	*te;
		char			*te_name;

		while (p[0] == '/')
			p++;

		slash = strchr(p, '/');
		if (slash == NULL)
			te_name = fsl_strdup(p);
		else
			te_name = fsl_strndup(p, slash - p);
		if (te_name == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			break;
		}

		te = find_tree_entry(s->tree, te_name, fsl_strlen(te_name));
		if (te == NULL) {
			rc = RC(FSL_RC_NOT_FOUND, "find_tree_entry(%s)",
			    te_name);
			fsl_free(te_name);
			break;
		}
		fsl_free(te_name);

		s->first_entry_onscreen = s->selected_entry = te;
		if (!S_ISDIR(s->selected_entry->mode))
			break;	/* If a file, jump to this entry. */

		slash = strchr(p, '/');
		if (slash)
			subpath = fsl_strndup(path, slash - path);
		else
			subpath = fsl_strdup(path);
		if (subpath == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			break;
		}

		rc = tree_builder(repo, &tree, subpath + 1 /* Leading slash */);
		if (rc)
			break;
		rc = visit_subtree(s, tree);
		if (rc) {
			fnc_object_tree_close(tree);
			break;
		}

		if (slash == NULL)
			break;
		fsl_free(subpath);
		subpath = NULL;
		p = slash;
	}

	fsl_free(subpath);
	return rc;
}

/*
 * This routine constructs the repository tree, repo, which is a DLL; from this
 * tree, all displayed (sub)trees are derived. File paths are extracted from F
 * cards of the checkin identified by id referenced in the repo database by rid.
 */
static int
create_repository_tree(struct fnc_repository_tree **repo, fsl_uuid_str *id,
    fsl_id_t rid)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_repository_tree	*ptr;
	fsl_deck			 d = fsl_deck_empty;
	const fsl_card_F		*cf = NULL;
	int				 rc = 0;

	ptr = fsl_malloc(sizeof(struct fnc_repository_tree));
	if (ptr == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
	memset(ptr, 0, sizeof(struct fnc_repository_tree));

	rc = fsl_deck_load_rid(fcli_cx(), &d, rid, FSL_SATYPE_CHECKIN);
	if (rc)
		return RC(rc, "fsl_deck_load_rid(%d) [%s]", rid, id);
	rc = fsl_deck_F_rewind(&d);
	if (!rc)
		rc = fsl_deck_F_next(&d, &cf);
	if (rc)
		goto end;;

	while (cf) {
		char		*filename = NULL, *uuid = NULL;
		fsl_time_t	 mtime;

		filename = fsl_strdup(cf->name);
		if (filename == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		uuid = fsl_strdup(cf->uuid);
		if (uuid == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
		rc = fsl_mtime_of_F_card(f, rid, cf, &mtime);
		rc = link_tree_node(ptr, filename, uuid, mtime);
		fsl_free(filename);
		fsl_free(uuid);
		if (!rc)
			rc = fsl_deck_F_next(&d, &cf);
		if (rc)
			goto end;
	}
end:
	fsl_deck_finalize(&d);

	*repo = ptr;
	return rc;
}

/*
 * This routine constructs the (sub)trees that are displayed. The directory dir
 * and its contents form a subtree, which is an array of tree entries copied
 * from DLL nodes in repo and stored in tree. This routine is called for each
 * directory that is displayed as a tree.
 */
static int
tree_builder(struct fnc_repository_tree *repo, struct fnc_tree_object **tree,
    const char *dir)
{
	struct fnc_tree_entry		*te = NULL;
	struct fnc_repo_tree_node	*tn = NULL;
	int				 i = 0;

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

	/* Count how many elements will comprise the tree to be allocated. */
	for(tn = repo->head; tn; tn = tn->next) {
		if ((!tn->parent_dir && fsl_strcmp(dir, "/")) ||
		    (tn->parent_dir && fsl_strcmp(dir, tn->parent_dir->path)))
			continue;
		++i;
	}
	(*tree)->entries = calloc(i, sizeof(struct fnc_tree_entry));
	if ((*tree)->entries == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");
	/* Construct the tree to be displayed. */
	for(tn = repo->head, i = 0; tn; tn = tn->next) {
		if ((!tn->parent_dir && fsl_strcmp(dir, "/")) ||
		    (tn->parent_dir && fsl_strcmp(dir, tn->parent_dir->path)))
			continue;
		te = &(*tree)->entries[i];
		te->mode = tn->mode;
		te->mtime = tn->mtime;
		te->basename = fsl_strdup(tn->basename);
		if (te->basename == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		te->path = fsl_strdup(tn->path);
		if (te->path == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		te->uuid = fsl_strdup(tn->uuid);
		if (te->uuid == NULL && !S_ISDIR(te->mode))
			return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		te->idx = i++;
	}
	(*tree)->nentries = i;

	return 0;
}

#if 0
static void
delete_tree_node(struct fnc_tree_entry **head, struct fnc_tree_entry *del)
{
	struct fnc_tree_entry *temp = *head, *prev;

	if (temp == del) {
		*head = temp->next;
		fsl_free(temp);
		return;
	}

	while (temp != NULL && temp != del) {
		prev = temp;
		temp = temp->next;
	}

	if (temp == NULL)
		return;

	prev->next = temp->next;

	fsl_free(temp);
}
#endif

/*
 * This routine inserts nodes into the doubly-linked repository tree. Each
 * path component of path (i.e., tokens delimited by '/') becomes a node in
 * tree. The final path component of each segment is the node's .basename, and
 * its full repository relative path its .path. All files in a given directory
 * will comprise the directory node's .children list, and each file node's
 * .sibling list; said directory will be each file node's .parent_dir. The
 * elements of each requested tree will be identified by the node's .parent_dir;
 * that is, each node with the same parent_dir will be an entry in the same tree
 *   tree    The repository tree into which nodes are inserted
 *   path    The repository relative pathname of the versioned file
 *   uuid    The SHA hash of the file
 *   mtime   Modification time of the file
 * Returns 0 on success, non-zero on error.
 */
static int
link_tree_node(struct fnc_repository_tree *tree, const char *path,
    const char *uuid, fsl_time_t mtime)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_repo_tree_node	*parent_dir;
	fsl_buffer			 buf = fsl_buffer_empty;
	struct stat			 s;
	int				 i, rc = 0;

	parent_dir = tree->tail;
	while (parent_dir != 0 &&
	    (strncmp(parent_dir->path, path, parent_dir->pathlen) != 0 ||
            path[parent_dir->pathlen] != '/'))
		parent_dir = parent_dir->parent_dir;

	i = parent_dir ? parent_dir->pathlen + 1 : 0;

	while (path[i]) {
		struct fnc_repo_tree_node	*tn;
		int				 nodesz, slash = i;

		/* Find slash to demarcate each path component. */
		while (path[i] && path[i] != '/')
			i++;
		nodesz = sizeof(*tn) + i + 1;

		/*
		 * If not at end of path string, node is a directory so don't
		 * allocate space for the hash.
		 */
		if (uuid != 0 && path[i] == '\0')
			nodesz += FSL_STRLEN_K256 + 1; /* NUL */
		tn = fsl_malloc(nodesz);
		if (tn == NULL)
			return RC(FSL_RC_ERROR, "%s", "fsl_malloc");
		memset(tn, 0, sizeof(*tn));

		tn->path = (char *)&tn[1];
		memcpy(tn->path, path, i);
		tn->path[i] = '\0';
		tn->pathlen = i;

		if (uuid != 0 && path[i] == '\0') {
			tn->uuid = tn->path + i + 1;
			memcpy(tn->uuid, uuid, fsl_strlen(uuid) + 1);
		}

		tn->basename = tn->path + slash;

		/* Insert node into DLL or make it the head if first. */
		if (tree->tail) {
			tree->tail->next = tn;
			tn->prev = tree->tail;
		} else
			tree->head = tn;

		tree->tail = tn;
		tn->parent_dir = parent_dir;
		if (parent_dir) {
			if (parent_dir->children)
				parent_dir->lastchild->sibling = tn;
			else
				parent_dir->children = tn;
			tn->nparents = parent_dir->nparents + 1;
			parent_dir->lastchild = tn;
		} else {
			if (tree->rootail)
				tree->rootail->sibling = tn;
			tree->rootail = tn;
		}

		tn->mtime = mtime;
		while (path[i] == '/')	/* Consume slashes. */
			++i;
		parent_dir = tn;

		/* Stat path for tree display features. */
		rc = fsl_file_canonical_name2(f->ckout.dir, tn->path, &buf,
		    false);
		if (rc)
			goto end;
		if (lstat(fsl_buffer_cstr(&buf), &s) == -1) {
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS),
			    "lstat(%s)", fsl_buffer_cstr(&buf));
			goto end;
		}
		tn->mode = s.st_mode;
		fsl_buffer_reuse(&buf);
	}

	while (parent_dir && parent_dir->parent_dir) {
		if (parent_dir->parent_dir->mtime < parent_dir->mtime)
			parent_dir->parent_dir->mtime = parent_dir->mtime;
		parent_dir = parent_dir->parent_dir;
	}
end:
	fsl_buffer_clear(&buf);
	return rc;
}

static int
show_tree_view(struct fnc_view *view)
{
	struct fnc_tree_view_state	*s = &view->state.tree;
	char				*treepath;
	int				 rc = 0;

	rc = tree_entry_path(&treepath, &s->parents, NULL);
	if (rc)
		return rc;

	rc = draw_tree(view, treepath);
	fsl_free(treepath);
	draw_vborder(view);

	return rc;
}

/*
 * Construct absolute repository path of the currently selected tree entry to
 * display in the tree view header, or pass to open_timeline_view() to construct
 * a timeline of all commits modifying path.
 */
static int
tree_entry_path(char **path, struct fnc_parent_trees *parents,
    struct fnc_tree_entry *te)
{
	struct fnc_parent_tree	*pt;
	size_t			 len = 2;  /* Leading slash and NUL. */
	int			 rc = 0;

	TAILQ_FOREACH(pt, parents, entry)
		len += strlen(pt->selected_entry->basename) + 1 /* slash */;
	if (te)
		len += strlen(te->basename);

	*path = calloc(1, len);
	if (path == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");

	(*path)[0] = '/';  /* Make it absolute from the repository root. */
	pt = TAILQ_LAST(parents, fnc_parent_trees);
	while (pt) {
		const char *name = pt->selected_entry->basename;
		if (strlcat(*path, name, len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, %s, %d)",
			    *path, name, len);
			goto end;
		}
		if (strlcat(*path, "/", len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, \"/\", %d)",
			    *path, len);
			goto end;
		}
		pt = TAILQ_PREV(pt, fnc_parent_trees, entry);
	}
	if (te) {
		if (strlcat(*path, te->basename, len) >= len) {
			rc = RC(FSL_RC_RANGE, "strlcat(%s, %s, %d)",
			    *path, te->basename, len);
			goto end;
		}
	}
end:
	if (rc) {
		fsl_free(*path);
		*path = NULL;
	}
	return rc;
}

/*
 * Draw the currently visited tree. Headline view with the checkin's SHA hash,
 * and write subheader comprised of the tree path. Lexicographically order nodes
 * (cf. ls(1)) and postfix with identifier corresponding to the file mode as
 * returned by lstat(2) such that the tree takes the following form:
 *
 *  checkin COMMIT-HASH
 *  /absolute/repository/tree/path/
 *
 *   ..
 *   dir/
 *   executable*
 *   regularfile
 *   symlink@ -> /path/to/source/file
 *
 * If the 'i' key binding is entered, prefix each versioned file with its
 * SHA{1,3} hash. Directories, however, have no such hash UUID to display.
 */
static int
draw_tree(struct fnc_view *view, const char *treepath)
{
	struct fnc_tree_view_state	*s = &view->state.tree;
	struct fnc_tree_entry		*te;
	struct fnc_colour		*c = NULL;
	wchar_t				*wcstr;
	int				 match = -1, rc = 0;
	int				 wstrlen, n, idx, nentries;
	int				 limit = view->nlines;
	uint_fast8_t			 hashlen = FSL_UUID_STRLEN_MIN;

	s->ndisplayed = 0;
	werase(view->window);
	if (limit == 0)
		return rc;

	/* Write (highlighted) headline (if view is active in splitscreen). */
	rc = formatln(&wcstr, &wstrlen, s->tree_label, view->ncols, 0);
	if (rc)
		return rc;
	if (screen_is_shared(view))
		wstandout(view->window);
	if (s->colour)
		c = get_colour(&s->colours, FNC_COMMIT);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddwstr(view->window, wcstr);
	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
	if (screen_is_shared(view))
		wstandend(view->window);
	fsl_free(wcstr);
	wcstr = NULL;
	if (wstrlen < view->ncols - 1)
		waddch(view->window, '\n');
	if (--limit <= 0)
		return rc;

	/* Write this (sub)tree's absolute repository path subheader. */
	rc = formatln(&wcstr, &wstrlen, treepath, view->ncols, 0);
	if (rc)
		return rc;
	waddwstr(view->window, wcstr);
	fsl_free(wcstr);
	wcstr = NULL;
	if (wstrlen < view->ncols - 1)
		waddch(view->window, '\n');
	if (--limit <= 0)
		return rc;
	waddch(view->window, '\n');
	if (--limit <= 0)
		return rc;

	/* Write parent dir entry (i.e., "..") if top of the tree is in view. */
	if (s->first_entry_onscreen == NULL) {
		te = &s->tree->entries[0];
		if (s->selected_idx == 0) {
			if (view->active)
				wattr_on(view->window, A_REVERSE, NULL);
			s->selected_entry = NULL;
		}
		waddstr(view->window, "  ..\n");
		if (s->selected_idx == 0 && view->active)
			wattr_off(view->window, A_REVERSE, NULL);
		++s->ndisplayed;
		if (--limit <= 0)
			return rc;
		n = 1;
	} else {
		n = 0;
		te = s->first_entry_onscreen;
	}

	nentries = s->tree->nentries;
	for (idx = 0; idx < nentries; ++idx)	/* Find max hash length. */
		if (hashlen < fsl_strlen(s->tree->entries[idx].uuid))
			hashlen = fsl_strlen(s->tree->entries[idx].uuid);
	/* Iterate and write tree nodes postfixed with path type identifier. */
	for (idx = te->idx; idx < nentries; ++idx) {
		char		*line = NULL, *idstr = NULL, *targetlnk = NULL;
		const char	*modestr = "";
		mode_t		 mode;

		if (idx < 0 || idx >= s->tree->nentries)
			return 0;
		te = &s->tree->entries[idx];
		mode = te->mode;

		if (s->show_id) {
			idstr = fsl_strdup(te->uuid);
			/* Directories don't have UUIDs; pad with "..." dots. */
			if (idstr == NULL && !S_ISDIR(mode))
				return RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			/* If needed, pad SHA1 hash to align w/ SHA3 hashes. */
			if (idstr == NULL || fsl_strlen(idstr) < hashlen) {
				char buf[hashlen], pad = '.';
				idstr = fsl_mprintf("%s%s", idstr ? idstr : "",
				    (char *)memset(buf, pad,
				    hashlen - fsl_strlen(idstr)));
				if (idstr == NULL)
					return RC(FSL_RC_RANGE,
					    "%s", "fsl_mprintf");
				idstr[hashlen] = '\0';
				/* idstr = fsl_mprintf("%*c", hashlen, ' '); */
			}
		}
		if (S_ISLNK(mode)) {
			fsl_size_t	ch;

			rc = tree_entry_get_symlink_target(&targetlnk, te);
			if (rc) {
				fsl_free(idstr);
				return rc;
			}
			for (ch = 0; ch < fsl_strlen(targetlnk); ++ch) {
				if (!isprint((unsigned char)targetlnk[ch]))
					targetlnk[ch] = '?';
			}
			modestr = "@";
		}
		else if (S_ISDIR(mode))
			modestr = "/";
		else if (mode & S_IXUSR)
			modestr = "*";
		if ((line = fsl_mprintf("%s  %s%s%s%s", idstr ? idstr : "",
		    te->basename, modestr, targetlnk ? " -> ": "",
		    targetlnk ? targetlnk : "")) == NULL) {
			fsl_free(idstr);
			fsl_free(targetlnk);
			return RC(FSL_RC_RANGE, "%s", "fsl_mprintf");
		}
		fsl_free(idstr);
		fsl_free(targetlnk);
		rc = formatln(&wcstr, &wstrlen, line, view->ncols, 0);
		if (rc) {
			fsl_free(line);
			break;
		}
		if (n == s->selected_idx) {
			if (view->active)
				wattr_on(view->window, A_REVERSE, NULL);
			s->selected_entry = te;
		}
		if (s->colour && (match = fsl_list_index_of(&s->colours, line,
		    match_line)) != -1)
			c = s->colours.list[match];
		else
			c = NULL;
		if (c)
			wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
		waddwstr(view->window, wcstr);
		if (c)
			wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
		if (wstrlen < view->ncols - 1)
			waddch(view->window, '\n');
		if (n == s->selected_idx && view->active)
			wattr_off(view->window, A_REVERSE, NULL);
		fsl_free(line);
		fsl_free(wcstr);
		wcstr = NULL;
		++n;
		++s->ndisplayed;
		s->last_entry_onscreen = te;
		if (--limit <= 0)
			break;
	}

	return rc;
}

static int
tree_entry_get_symlink_target(char **targetlnk, struct fnc_tree_entry *te)
{
	struct stat	 s;
	fsl_buffer	 fb = fsl_buffer_empty;
	char		*buf = NULL;
	ssize_t		 nbytes, bufsz;
	int		 rc = 0;

	*targetlnk = NULL;

	fsl_file_canonical_name2(fcli_cx()->ckout.dir, te->path, &fb, false);
	if (lstat(fsl_buffer_cstr(&fb), &s) == -1) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ACCESS), "lstat(%s)",
		    fsl_buffer_cstr(&fb));
		goto end;
	}

	bufsz = s.st_size ? (s.st_size + 1 /* NUL */) : PATH_MAX;
	buf = fsl_malloc(bufsz);
	if (buf == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_malloc");
		goto end;
	}

	nbytes = readlink(fsl_buffer_cstr(&fb), buf, bufsz);
	if (nbytes == -1) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "readlink(%s)",
		    fsl_buffer_cstr(&fb));
		goto end;
	}
	buf[nbytes] = '\0';	/* readlink() does _not_ NUL terminate */
end:
	fsl_buffer_clear(&fb);
	if (rc)
		fsl_free(buf);
	*targetlnk = buf;
	return rc;
	/*
	 * XXX Not sure if we should rely on fossil(1) populating symlinks
	 * with the path of the target source file to obtain the target link.
	 */
	/* fsl_cx		*f = fcli_cx(); */
	/* fsl_buffer	 blob = fsl_buffer_empty; */
	/* fsl_id_t	 rid; */

	/* if (!((te->mode & (S_IFDIR | S_IFLNK)) == S_IFLNK)) */
	/* 	return RC(FSL_RC_TYPE, "file not symlink [%s]", te->path); */
	/* rc = fsl_sym_to_rid(f, te->uuid, FSL_SATYPE_ANY, &rid); */
	/* if (!rc) */
	/* 	rc = fsl_content_blob(f, rid, &blob); */
	/* if (rc) */
	/* 	return rc; */

	/* *targetlnk = fsl_strdup(fsl_buffer_str(&blob)); */
	/* fsl_buffer_clear(&blob); */
}

static int
tree_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_view			*timeline_view/*, *branch_view */;
	struct fnc_tree_view_state	*s = &view->state.tree;
	struct fnc_tree_entry		*te;
	int				 n, start_col = 0, rc = 0;

	switch (ch) {
	case 'c':
		s->colour = !s->colour;
		break;
	case 'i':
		s->show_id = !s->show_id;
		break;
	case 't':
		if (!s->selected_entry)
			break;
		if (view_is_parent(view))
			start_col = view_split_start_col(view->start_col);
		rc = timeline_tree_entry(&timeline_view, start_col, s);
		view->active = false;
		timeline_view->active = true;
		if (view_is_parent(view)) {
			rc = view_close_child(view);
			if (rc)
				return rc;
			view_set_child(view, timeline_view);
			view->focus_child = true;
		} else
			*new_view = timeline_view;
		break;
	case 'g':
		if (!fnc_home(view))
			break;
		/* FALL THROUGH */
	case KEY_HOME:
		s->selected_idx = 0;
		if (s->tree == s->root)
			s->first_entry_onscreen = &s->tree->entries[0];
		else
			s->first_entry_onscreen = NULL;
		break;
	case KEY_END:
	case 'G':
		s->selected_idx = 0;
		te = &s->tree->entries[s->tree->nentries - 1];
		for (n = 0; n < view->nlines - 3; ++n) {
			if (te == NULL) {
				if(s->tree != s->root) {
					s->first_entry_onscreen = NULL;
					++n;
				}
				break;
			}
			s->first_entry_onscreen = te;
			te = get_tree_entry(s->tree, te->idx - 1);
		}
		if (n > 0)
			s->selected_idx = n - 1;
		break;
	case KEY_UP:
	case 'k':
		if (s->selected_idx > 0) {
			--s->selected_idx;
			break;
		}
		tree_scroll_up(s, 1);
		break;
	case KEY_PPAGE:
	case CTRL('b'):
		if (s->tree == s->root) {
			if (&s->tree->entries[0] == s->first_entry_onscreen)
				s->selected_idx = 0;
		} else {
			if (s->first_entry_onscreen == NULL)
				s->selected_idx = 0;
		}
		tree_scroll_up(s, MAX(0, view->nlines - 3));
		break;
	case KEY_DOWN:
	case 'j':
		if (s->selected_idx < s->ndisplayed - 1) {
			++s->selected_idx;
			break;
		}
		if (get_tree_entry(s->tree, s->last_entry_onscreen->idx + 1)
		    == NULL)
			break;	/* Reached last entry. */
		tree_scroll_down(s, 1);
		break;
	case KEY_NPAGE:
	case CTRL('f'):
		if (get_tree_entry(s->tree, s->last_entry_onscreen->idx + 1)
		    == NULL) {
			/*
			 * When the last entry on screen is the last node in the
			 * tree move cursor to it instead of scrolling the view.
			 */
			if (s->selected_idx < s->ndisplayed - 1)
				s->selected_idx = s->ndisplayed - 1;
			break;
		}
		tree_scroll_down(s, view->nlines - 3);
		break;
	case KEY_BACKSPACE:
	case KEY_ENTER:
	case KEY_LEFT:
	case KEY_RIGHT:
	case '\r':
	case 'h':
	case 'l':
		/*
		 * h/backspace/arrow-left: return to parent dir irrespective
		 * of selected entry type (unless already at root).
		 * l/arrow-right: move into selected dir entry.
		 */
		if (ch != KEY_RIGHT && ch != 'l' && (s->selected_entry == NULL
		    || ch == 'h' || ch == KEY_BACKSPACE || ch == KEY_LEFT)) {
			struct fnc_parent_tree	*parent;
			/* h/backspace/left-arrow pressed or ".." selected. */
			if (s->tree == s->root)
				break;
			parent = TAILQ_FIRST(&s->parents);
			TAILQ_REMOVE(&s->parents, parent,
			    entry);
			fnc_object_tree_close(s->tree);
			s->tree = parent->tree;
			s->first_entry_onscreen = parent->first_entry_onscreen;
			s->selected_entry = parent->selected_entry;
			s->selected_idx = parent->selected_idx;
			fsl_free(parent);
		} else if (s->selected_entry != NULL &&
		    S_ISDIR(s->selected_entry->mode)) {
			struct fnc_tree_object	*subtree = NULL;
			rc = tree_builder(s->repo, &subtree,
			    s->selected_entry->path);
			if (rc)
				break;
			rc = visit_subtree(s, subtree);
			if (rc) {
				fnc_object_tree_close(subtree);
				break;
			}
		} else if (S_ISREG(s->selected_entry->mode)) {
			struct fnc_view *blame_view;
			int start_col = view_is_parent(view) ?
			    view_split_start_col(view->start_col) : 0;

			rc = blame_tree_entry(&blame_view, start_col,
			    s->selected_entry, &s->parents, s->commit_id);
			if (rc)
				break;
			view->active = false;
			blame_view->active = true;
			if (view_is_parent(view)) {
				rc = view_close_child(view);
				if (rc)
					return rc;
				view_set_child(view, blame_view);
				view->focus_child = true;
			} else
				*new_view = blame_view;
		}
		break;
	case KEY_RESIZE:
		if (view->nlines >= 4 && s->selected_idx >= view->nlines - 3)
			s->selected_idx = view->nlines - 4;
		break;
	default:
		break;
	}

	return rc;
}

static int
timeline_tree_entry(struct fnc_view **new_view, int start_col,
    struct fnc_tree_view_state *s)
{
	struct fnc_view	*timeline_view;
	char		*path;
	int		 rc = 0;

	*new_view = NULL;

	timeline_view = view_open(0, 0, 0, start_col, FNC_VIEW_TIMELINE);
	if (timeline_view == NULL)
		return RC(FSL_RC_ERROR, "%s", "view_open");

	/* Construct repository relative path for timeline query. */
	rc = tree_entry_path(&path, &s->parents, s->selected_entry);
	if (rc)
		return rc;

	rc = open_timeline_view(timeline_view, s->rid, path);
	if (rc)
		view_close(timeline_view);
	else
		*new_view = timeline_view;

	fsl_free(path);
	return rc;
}

static void
tree_scroll_up(struct fnc_tree_view_state *s, int maxscroll)
{
	struct fnc_tree_entry	*te;
	int			 isroot, i = 0;

	isroot = s->tree == s->root;

	if (s->first_entry_onscreen == NULL)
		return;

	te = get_tree_entry(s->tree, s->first_entry_onscreen->idx - 1);
	while (i++ < maxscroll) {
		if (te == NULL) {
			if (!isroot)
				s->first_entry_onscreen = NULL;
			break;
		}
		s->first_entry_onscreen = te;
		te = get_tree_entry(s->tree, te->idx - 1);
	}
}

static void
tree_scroll_down(struct fnc_tree_view_state *s, int maxscroll)
{
	struct fnc_tree_entry	*next, *last;
	int			 n = 0;

	if (s->first_entry_onscreen)
		next = get_tree_entry(s->tree,
		    s->first_entry_onscreen->idx + 1);
	else
		next = &s->tree->entries[0];

	last = s->last_entry_onscreen;
	while (next && last && n++ < maxscroll) {
		last = get_tree_entry(s->tree, last->idx + 1);
		if (last) {
			s->first_entry_onscreen = next;
			next = get_tree_entry(s->tree, next->idx + 1);
		}
	}
}

static int
visit_subtree(struct fnc_tree_view_state *s, struct fnc_tree_object *subtree)
{
	struct fnc_parent_tree	*parent;

	parent = calloc(1, sizeof(*parent));
	if (parent == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");

	parent->tree = s->tree;
	parent->first_entry_onscreen = s->first_entry_onscreen;
	parent->selected_entry = s->selected_entry;
	parent->selected_idx = s->selected_idx;
	TAILQ_INSERT_HEAD(&s->parents, parent, entry);
	s->tree = subtree;
	s->selected_idx = 0;
	s->first_entry_onscreen = NULL;

	return 0;
}

static int
blame_tree_entry(struct fnc_view **new_view, int start_col,
    struct fnc_tree_entry *te, struct fnc_parent_trees *parents,
    fsl_uuid_str commit_id)
{
	struct fnc_view	*blame_view;
	char		*path;
	int		 rc = 0;

	*new_view = NULL;

	rc = tree_entry_path(&path, parents, te);
	if (rc)
		return rc;

	blame_view = view_open(0, 0, 0, start_col, FNC_VIEW_BLAME);
	if (blame_view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "view_open");
		goto end;
	}

	rc = open_blame_view(blame_view, path, commit_id, 0, 0);
	if (rc)
		view_close(blame_view);
	else
		*new_view = blame_view;
end:
	fsl_free(path);
	return rc;
}

static int
tree_search_init(struct fnc_view *view)
{
	struct fnc_tree_view_state *s = &view->state.tree;

	s->matched_entry = NULL;
	return 0;
}

static int
tree_search_next(struct fnc_view *view)
{
	struct fnc_tree_view_state	*s = &view->state.tree;
	struct fnc_tree_entry		*te = NULL;
	int				 rc = 0;

	if (view->searching == SEARCH_DONE) {
		view->search_status = SEARCH_CONTINUE;
		return rc;
	}

	if (s->matched_entry) {
		if (view->searching == SEARCH_FORWARD) {
			if (s->selected_entry)
				te = &s->tree->entries[s->selected_entry->idx
				    + 1];
			else
				te = &s->tree->entries[0];
		} else {
			if (s->selected_entry == NULL)
				te = &s->tree->entries[s->tree->nentries - 1];
			else
				te = &s->tree->entries[s->selected_entry->idx
				    - 1];
		}
	} else {
		if (view->searching == SEARCH_FORWARD)
			te = &s->tree->entries[0];
		else
			te = &s->tree->entries[s->tree->nentries - 1];
	}

	while (1) {
		if (te == NULL) {
			if (s->matched_entry == NULL) {
				view->search_status = SEARCH_CONTINUE;
				return rc;
			}
			if (view->searching == SEARCH_FORWARD)
				te = &s->tree->entries[0];
			else
				te = &s->tree->entries[s->tree->nentries - 1];
		}

		if (match_tree_entry(te, &view->regex)) {
			view->search_status = SEARCH_CONTINUE;
			s->matched_entry = te;
			break;
		}

		if (view->searching == SEARCH_FORWARD)
			te = &s->tree->entries[te->idx + 1];
		else
			te = &s->tree->entries[te->idx - 1];
	}

	if (s->matched_entry) {
		s->first_entry_onscreen = s->matched_entry;
		s->selected_idx = 0;
	}

	return rc;
}

static int
match_tree_entry(struct fnc_tree_entry *te, regex_t *regex)
{
	regmatch_t regmatch;

	return regexec(regex, te->basename, 1, &regmatch, 0) == 0;
}

struct fnc_tree_entry *
get_tree_entry(struct fnc_tree_object *tree, int i)
{
	if (i < 0 || i >= tree->nentries)
		return NULL;

	return &tree->entries[i];
}

/* Find entry in tree with basename name. */
static struct fnc_tree_entry *
find_tree_entry(struct fnc_tree_object *tree, const char *name, size_t len)
{
	int	idx;

	/* Entries are sorted in strcmp() order. */
	for (idx = 0; idx < tree->nentries; ++idx) {
		struct fnc_tree_entry *te = &tree->entries[idx];
		int cmp = strncmp(te->basename, name, len);
		if (cmp < 0)
			continue;
		if (cmp > 0)
			break;
		if (te->basename[len] == '\0')
			return te;
	}
	return NULL;
}

static int
close_tree_view(struct fnc_view *view)
{
	struct fnc_tree_view_state	*s = &view->state.tree;
	struct fsl_list_state		 st = { FNC_COLOUR_OBJ };

	fsl_list_clear(&s->colours, fsl_list_object_free, &st);

	fsl_free(s->tree_label);
	s->tree_label = NULL;
	fsl_free(s->commit_id);
	s->commit_id = NULL;

	while (!TAILQ_EMPTY(&s->parents)) {
		struct fnc_parent_tree *parent;
		parent = TAILQ_FIRST(&s->parents);
		TAILQ_REMOVE(&s->parents, parent, entry);
		if (parent->tree != s->root)
			fnc_object_tree_close(parent->tree);
		fsl_free(parent);

	}

	if (s->tree != NULL && s->tree != s->root)
		fnc_object_tree_close(s->tree);
	if (s->root)
		fnc_object_tree_close(s->root);
	if (s->repo)
		fnc_close_repository_tree(s->repo);

	return 0;
}

static void
fnc_object_tree_close(struct fnc_tree_object *tree)
{
	int	idx;

	for (idx = 0; idx < tree->nentries; ++idx) {
		fsl_free(tree->entries[idx].basename);
		fsl_free(tree->entries[idx].path);
		fsl_free(tree->entries[idx].uuid);
	}

	fsl_free(tree->entries);
	fsl_free(tree);
}

static void
fnc_close_repository_tree(struct fnc_repository_tree *repo)
{
	struct fnc_repo_tree_node *next, *tn;

	tn = repo->head;
	while (tn) {
		next = tn->next;
		fsl_free(tn);
		tn = next;
	}
	fsl_free(repo);
}

static int
view_close_child(struct fnc_view *view)
{
	int	rc = 0;

	if (view->child == NULL)
		return rc;

	rc = view_close(view->child);
	view->child = NULL;

	return rc;
}

static void
view_set_child(struct fnc_view *view, struct fnc_view *child)
{
	view->child = child;
	child->parent = view;
}

static int
set_colours(fsl_list *s, enum fnc_view_id vid)
{
	struct fnc_colour	 *colour;
	const char		**regexp = NULL;
	const char		 *regexp_blame[] = {"^"};
	const char		 *regexp_tree[] = {"@$", "/$", "\\*$", "^$"};
	const char		 *regexp_diff[] = {
				    "^((checkin|wiki|ticket|technote) "
				    "[0-9a-f]|hash [+-] |\\[[+~>-]] |"
				    "[+-]{3} )",
				    "^-", "^\\+", "^@@"
				  };
	int			  pairs_diff[][2] = {
				    {FNC_DIFF_META, COLOR_GREEN},
				    {FNC_DIFF_MINUS, COLOR_MAGENTA},
				    {FNC_DIFF_PLUS, COLOR_CYAN},
				    {FNC_DIFF_CHNK, COLOR_YELLOW}
				  };
	int			  pairs_tree[][2] = {
				    {FNC_TREE_LINK, COLOR_MAGENTA},
				    {FNC_TREE_DIR, COLOR_CYAN},
				    {FNC_TREE_EXEC, COLOR_GREEN},
				    {FNC_COMMIT, COLOR_MAGENTA}
				  };
	int			  pairs_blame[][2] = {{FNC_COMMIT, COLOR_CYAN}};
	int			(*pairs)[2], rc = 0;
	fsl_size_t		  idx, n;

	switch (vid) {
	case FNC_VIEW_DIFF:
		n = nitems(regexp_diff);
		regexp = regexp_diff;
		pairs = pairs_diff;
		break;
	case FNC_VIEW_TREE:
		n = nitems(regexp_tree);
		regexp = regexp_tree;
		pairs = pairs_tree;
		break;
	case FNC_VIEW_BLAME:
		n = nitems(regexp_blame);
		regexp = regexp_blame;
		pairs = pairs_blame;
		break;
	default:
		return RC(FSL_RC_TYPE, "%s", "invalid fnc_view_id");
	}

	for (idx = 0; idx < n; ++idx) {
		colour = fsl_malloc(sizeof(*colour));
		if (colour == NULL)
			return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
			    "%s", "fsl_malloc");

		rc = regcomp(&colour->regex, regexp[idx],
		    REG_EXTENDED | REG_NEWLINE | REG_NOSUB);
		if (rc) {
			static char regerr[512];
			regerror(rc, &colour->regex, regerr, sizeof(regerr));
			fsl_free(colour);
			return RC(FSL_RC_ERROR, "regcomp(%s) -> %s",
			    regexp[idx], regerr);
		}

		colour->scheme = pairs[idx][0];
		init_pair(colour->scheme, pairs[idx][1], -1);
		fsl_list_append(s, colour);
	}

	return rc;
}

struct fnc_colour *
get_colour(fsl_list *colours, int scheme)
{
	struct fnc_colour	cs;
	int			match = -1;

	cs.scheme = scheme;
	match = fsl_list_index_of(colours, &cs, match_colour);

	if (match != -1)
		return colours->list[match];

	return NULL;
}

static int
match_colour(const void *target, const void *key)
{
	struct fnc_colour *c = (struct fnc_colour *)key;
	struct fnc_colour *t = (struct fnc_colour *)target;

	return (c->scheme == t->scheme) ? 0 : 1;
}

/*
 * Emulate vim(1) gg: User has 1 sec to follow first 'g' keypress with another.
 */
static bool
fnc_home(struct fnc_view *view)
{
	bool	home = true;

	halfdelay(10);	/* Block for 1 second, then return ERR. */
	if (wgetch(view->window) != 'g')
		home = false;
	cbreak();	/* Return to blocking mode on user input. */

	return home;
}

static int
cmd_blame(fcli_command const *argv)
{
	fsl_cx		*f = fcli_cx();
	struct fnc_view	*view;
	char		*path = NULL;
	fsl_uuid_str	 commit_id = NULL;
	fsl_id_t	 tip = 0, rid = 0;
	int		 ndepth = 0, rc = 0;
	/* Not yet implemened. */
	f_out("%s blame is not yet implemented.\n", fcli_progname());
	return FSL_RC_NYI;

	rc = fcli_process_flags(argv->flags);
	if (rc || (rc = fcli_has_unused_flags(false)))
		goto end;
	if (!fcli_next_arg(false)) {
		rc = RC(FSL_RC_MISSING_INFO,
		    "%s blame requires versioned file path", fcli_progname());
		goto end;
	}

	if (fnc_init.nrecords.zlimit)
		if ((rc = strtonumcheck(&ndepth, fnc_init.nrecords.zlimit,
		    INT_MIN, INT_MAX)))
			goto end;

	if (fnc_init.sym || fnc_init.reverse) {
		if (fnc_init.reverse) {
			if (!fnc_init.sym) {
				rc = RC(FSL_RC_MISSING_INFO,
				    "%s blame --reverse requires --commit",
				    fcli_progname());
				goto end;
			}
			rc = fsl_sym_to_rid(f, "tip", FSL_SATYPE_CHECKIN, &tip);
			if (rc)
				goto end;
		}
		rc = fsl_sym_to_rid(f, fnc_init.sym, FSL_SATYPE_CHECKIN, &rid);
		if (rc)
			goto end;
	} else if (!fnc_init.sym)
		fsl_ckout_version_info(f, &rid, NULL);

	rc = map_repo_path(&path);
	if (rc) {
		if (rc != FSL_RC_NOT_FOUND || !fnc_init.sym)
			goto end;
		/* Path may be valid in repository tree of specified commit. */
		rc = 0;
		fcli_err_reset();
	}

	commit_id = fsl_rid_to_uuid(f, rid);
	if (rc || (path[0] == '/' && path[1] == '\0')) {
		rc = rc ? rc : RC(FSL_RC_MISSING_INFO,
		    "%s blame requires versioned file path", fcli_progname());
		goto end;
	}

	init_curses();

	view = view_open(0, 0, 0, 0, FNC_VIEW_BLAME);
	if (view == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", view_open);
		goto end;
	}

	rc = open_blame_view(view, path, commit_id, tip, ndepth);
	if (rc)
		goto end;
	rc = view_loop(view);
end:
	fsl_free(path);
	fsl_free(commit_id);
	return rc;
}

static int
open_blame_view(struct fnc_view *view, char *path, fsl_uuid_str commit_id,
    fsl_id_t tip, int ndepth)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	int				 rc = 0;

	CONCAT(STAILQ, _INIT)(&s->blamed_commits);

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

	rc = fnc_commit_qid_alloc(&s->blamed_commit, commit_id);
	if (rc) {
		fsl_free(s->path);
		return rc;
	}

	CONCAT(STAILQ, _INSERT_HEAD)(&s->blamed_commits, s->blamed_commit,
	    entry);
	memset(&s->blame, 0, sizeof(s->blame));
	s->first_line_onscreen = 1;
	s->last_line_onscreen = view->nlines;
	s->selected_line = 1;
	s->blame_complete = false;
	s->commit_id = commit_id;
	s->blame.origin = tip;
	s->blame.ndepth = ndepth;
	s->spin_idx = 0;
	s->colour = !fnc_init.nocolour && has_colors();

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

	view->show = show_blame_view;
	view->input = blame_input_handler;
	view->close = close_blame_view;
	view->search_init = blame_search_init;
	view->search_next = blame_search_next;

	return run_blame(view);
}

static int
run_blame(struct fnc_view *view)
{
	fsl_cx				*f = fcli_cx();
	struct fnc_blame_view_state	*s = &view->state.blame;
	struct fnc_blame		*blame = &s->blame;
	fsl_deck			 d = fsl_deck_empty;
	fsl_buffer			 buf = fsl_buffer_empty;
	fsl_annotate_opt		*opt = NULL;
	const fsl_card_F		*cf;
	char				*filepath = NULL;
	char				*master = NULL, *root = NULL;
	int				 rc = 0;

	/*
	 * Trim prefixed '/' if path has been processed by map_repo_path(),
	 * which only occurs when the -c option has not been passed.
	 * XXX This slash trimming is cumbersome; we should not prefix a slash
	 * in map_repo_path() as we only want the slash for displaying an
	 * absolute-repository-relative path, so we should prefix it only then.
	 */
	filepath = s->path[0] != '/' ? s->path : s->path + 1;

	rc = fsl_deck_load_sym(f, &d, s->blamed_commit->id, FSL_SATYPE_CHECKIN);
	if (rc)
		goto end;

	cf = fsl_deck_F_search(&d, filepath);
	if (cf == NULL) {
		rc = RC(FSL_RC_NOT_FOUND, "'%s' not found in tree [%s]",
		    filepath, s->blamed_commit->id);
		goto end;
	}
	rc = fsl_card_F_content(f, cf, &buf);
	if (rc)
		goto end;

	/*
	 * We load f with the actual file content to map line offsets so we
	 * accurately find tokens when running a search.
	 */
	blame->f = tmpfile();
	if (blame->f == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "tmpfile");
		goto end;
	}

	opt = &blame->thread_cx.blame_opt;
	opt->filename = fsl_strdup(filepath);
	fcli_fax((char *)opt->filename);
	rc = fsl_sym_to_rid(f, s->blamed_commit->id, FSL_SATYPE_CHECKIN,
	    &opt->versionRid);
	opt->originRid = blame->origin;    /* tip when -r is passed */
	opt->limit = blame->ndepth;
	opt->out = blame_cb;
	opt->outState = &blame->cb_cx;

	rc = fnc_dump_buffer_to_file(&blame->filesz, &blame->nlines,
	    &blame->line_offsets, blame->f, &buf);
	if (rc)
		goto end;
	if (blame->nlines == 0) {
		s->blame_complete = true;
		goto end;
	}

	/* Don't include EOF \n in blame line count. */
	if (blame->line_offsets[blame->nlines - 1] == blame->filesz)
		--blame->nlines;

	blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
	if (blame->lines == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");
		goto end;
	}

	master = fsl_config_get_text(f, FSL_CONFDB_REPO, "main-branch", NULL);
	if (master == NULL) {
		master = fsl_strdup("trunk");
		if (master == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
			goto end;
		}
	}
	root = fsl_mprintf("root:%s", master);
	rc = fsl_sym_to_uuid(f, root, FSL_SATYPE_CHECKIN,
	    &blame->cb_cx.root_commit, NULL);
	if (rc) {
		rc = RC(rc, "%s", "fsl_sym_to_uuid");
		goto end;
	}

	blame->cb_cx.view = view;
	blame->cb_cx.lines = blame->lines;
	blame->cb_cx.nlines = blame->nlines;
	blame->cb_cx.commit_id = fsl_strdup(s->blamed_commit->id);
	if (blame->cb_cx.commit_id == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		goto end;
	}
	blame->cb_cx.quit = &s->done;

	blame->thread_cx.path = s->path;
	blame->thread_cx.cb_cx = &blame->cb_cx;
	blame->thread_cx.complete = &s->blame_complete;
	blame->thread_cx.cancel_cb = cancel_blame;
	blame->thread_cx.cancel_cx = &s->done;
	s->blame_complete = false;

	if (s->first_line_onscreen + view->nlines - 1 > blame->nlines) {
		s->first_line_onscreen = 1;
		s->last_line_onscreen = view->nlines;
		s->selected_line = 1;
	}

end:
	fsl_free(master);
	fsl_free(root);
	fsl_deck_finalize(&d);
	fsl_buffer_clear(&buf);
	if (rc)
		stop_blame(blame);
	return rc;
}

/*
 * Write file content in buf to out file. Record the number of lines in the file
 * in nlines, and total bytes written in filesz. Assign byte offsets of each
 * line to the dynamically allocated *line_offsets, which must eventually be
 * disposed of by the caller. Flush and rewind out file when done.
 */
static int
fnc_dump_buffer_to_file(off_t *filesz, int *nlines, off_t **line_offsets,
    FILE *out, fsl_buffer *buf)
{
	off_t		 off = 0, total_len = 0;
	size_t		 len, n, i = 0, nalloc = 0;
	int		 rc = 0;
	const int	 alloc_chunksz = MIN(512, BUFSIZ);

	if (line_offsets)
		*line_offsets = NULL;
	if (filesz)
		*filesz = 0;
	if (nlines)
		*nlines = 0;

	len = buf->used;
	if (len == 0)
		return RC(FSL_RC_SIZE_MISMATCH, "%s",
		    "fnc_dump_buffer_to_file");
	if (nlines) {
		if (line_offsets && *line_offsets == NULL) {
			*nlines = 1;
			nalloc = alloc_chunksz;
			*line_offsets = calloc(nalloc, sizeof(**line_offsets));
			if (*line_offsets == NULL)
				return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
				    "%s", "calloc");

			/* Consume the first line. */
			while (i < len) {
				if (buf->mem[i] == '\n')
					break;
				++i;
			}
		}
		/* Scan '\n' offsets. */
		while (i < len) {
			if (buf->mem[i] != '\n') {
				++i;
				continue;
			}
			++(*nlines);
			if (line_offsets && nalloc < (size_t)*nlines) {
				size_t n, oldsz, newsz;
				off_t *new = NULL;

				n = *nlines + alloc_chunksz;
				oldsz = nalloc * sizeof(**line_offsets);
				newsz = n * sizeof(**line_offsets);
				if (newsz <= oldsz) {
					size_t b = oldsz - newsz;
					if (b < oldsz / 2 &&
					    b < (size_t)getpagesize()) {
						memset((char *)*line_offsets
						    + newsz, 0, b);
						goto allocated;
					}
				}
				new = fsl_realloc(*line_offsets, newsz);
				if (new == NULL) {
					fsl_free(*line_offsets);
					*line_offsets = NULL;
					return RC(FSL_RC_ERROR, "%s",
					    "fsl_realloc");
				}
				*line_offsets = new;
allocated:
				nalloc = n;
			}
			if (line_offsets) {
				off = total_len + i + 1;
				(*line_offsets)[*nlines - 1] = off;
			}
			++i;
		}
	}
	n = fwrite(buf->mem, 1, len, out);
	if (n != len)
		return RC(ferror(out) ? fsl_errno_to_rc(errno, FSL_RC_IO)
		    : FSL_RC_IO, "%s", "fwrite");
	total_len += len;

	if (fflush(out) != 0)
		return RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s", "fflush");
	rewind(out);

	if (filesz)
		*filesz = total_len;

	return rc;
}

static int
show_blame_view(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	int				 rc = 0;

	if (!s->blame.thread_id && !s->blame_complete) {
		rc = pthread_create(&s->blame.thread_id, NULL, blame_thread,
		    &s->blame.thread_cx);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_create");

		halfdelay(1);	/* Fast refresh while annotating.  */
	}

	if (s->blame_complete)
		cbreak();	/* Return to blocking mode. */

	rc = draw_blame(view);
	draw_vborder(view);

	return rc;
}

static void *
blame_thread(void *state)
{
	struct fnc_blame_thread_cx	*cx = state;
	int				 rc0, rc;

	rc = block_main_thread_signals();
	if (rc)
		return (void *)(intptr_t)rc;

	rc = fsl_annotate(fcli_cx(), &cx->blame_opt);
	if (rc && fsl_cx_err_get_e(fcli_cx())->code == FSL_RC_BREAK) {
		fcli_err_reset();
		rc = 0;
	}

	rc0 = pthread_mutex_lock(&fnc_mutex);
	if (rc0)
		return (void *)(intptr_t)RC(fsl_errno_to_rc(rc0, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_lock");

	*cx->complete = true;

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

	return (void *)(intptr_t)rc;
}

static int
blame_cb(void *state, fsl_annotate_opt const * const opt,
    fsl_annotate_step const * const step)
{
	struct fnc_blame_cb_cx	*cx = state;
	struct fnc_blame_line	*line;
	int			 rc = 0;

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

	if (*cx->quit) {
		rc = fcli_err_set(FSL_RC_BREAK, "user quit");
		goto end;
	}

	line = &cx->lines[step->lineNumber - 1];
	if (line->annotated)
		goto end;

	if (step->mtime) {
		line->id = fsl_strdup(step->versionHash);
		if (line->id == NULL) {
			rc = RC(FSL_RC_ERROR, "%s", fsl_strdup);
			goto end;
		}
		line->annotated = true;
	} else
		line->id = NULL;

	/* -r can return lines with no version, so use root check-in. */
	if (opt->originRid && !line->id) {
		line->id = fsl_strdup(cx->root_commit);
		line->annotated = true;
	}

	++cx->nlines;
end:
	rc = pthread_mutex_unlock(&fnc_mutex);
	if (rc)
		rc = RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
		    "%s", "pthread_mutex_unlock");
	return rc;
}

static int
draw_blame(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	struct fnc_blame		*blame = &s->blame;
	struct fnc_blame_line		*blame_line;
	regmatch_t			*regmatch = &view->regmatch;
	struct fnc_colour		*c = NULL;
	wchar_t				*wcstr;
	char				*line = NULL;
	fsl_uuid_str			 prev_id = NULL, id_str = NULL;
	ssize_t				 linelen;
	size_t				 linesz = 0;
	int				 width, lineno = 0, nprinted = 0;
	int				 rc = 0;
	const int			 idfield = 11;  /* Prefix + space. */

	id_str = fsl_strdup(s->blamed_commit->id);
	if (id_str == NULL)
		return RC(FSL_RC_ERROR, "%s", "fsl_strdup");

	rewind(blame->f);
	werase(view->window);

	if ((line = fsl_mprintf("checkin %s", id_str)) == NULL) {
		rc = RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "fsl_mprintf");
		fsl_free(id_str);
		return rc;
	}

	rc = formatln(&wcstr, &width, line, view->ncols, 0);
	fsl_free(line);
	line = NULL;
	if (rc)
		return rc;
	if (screen_is_shared(view))
		wstandout(view->window);
	if (s->colour)
		c = get_colour(&s->colours, FNC_COMMIT);
	if (c)
		wattr_on(view->window, COLOR_PAIR(c->scheme), NULL);
	waddwstr(view->window, wcstr);
	if (c)
		wattr_off(view->window, COLOR_PAIR(c->scheme), NULL);
	if (screen_is_shared(view))
		wstandend(view->window);
	fsl_free(wcstr);
	wcstr = NULL;
	if (width < view->ncols - 1)
		waddch(view->window, '\n');

	if ((line = fsl_mprintf("[%d/%d] %s%s%s %c",
	    s->first_line_onscreen - 1 + s->selected_line, blame->nlines,
	    s->blame_complete ? "" : "annotating... ",
	    fnc_init.sym ? "/" : "", s->path,
	    s->blame_complete ? ' ' : SPINNER[s->spin_idx])) == NULL) {
		fsl_free(id_str);
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR),
		    "%s", "fsl_mprintf");
	}
	if (SPINNER[++s->spin_idx] == '\0')
		s->spin_idx = 0;
	fsl_free(id_str);
	rc = formatln(&wcstr, &width, line, view->ncols, 0);
	fsl_free(line);
	line = NULL;
	if (rc)
		return rc;
	waddwstr(view->window, wcstr);
	fsl_free(wcstr);
	wcstr = NULL;
	if (width < view->ncols - 1)
		waddch(view->window, '\n');

	s->eof = false;
	while (nprinted < view->nlines - 2) {
		linelen = getline(&line, &linesz, blame->f);
		if (linelen == -1) {
			if (feof(blame->f)) {
				s->eof = true;
				break;
			}
			fsl_free(line);
			return RC(ferror(blame->f) ? fsl_errno_to_rc(errno,
			    FSL_RC_IO) : FSL_RC_IO, "%s", "getline");
		}
		if (++lineno < s->first_line_onscreen)
			continue;

		if (view->active && nprinted == s->selected_line - 1)
			wattr_on(view->window, A_REVERSE, NULL);

		if (blame->nlines > 0) {
			blame_line = &blame->lines[lineno - 1];
			if (blame_line->annotated && prev_id &&
			    fsl_uuidcmp(prev_id, blame_line->id) == 0 &&
			    !(view->active &&
			    nprinted == s->selected_line - 1)) {
				waddstr(view->window, "          ");
			} else if (blame_line->annotated) {
				char *id_str;
				id_str = fsl_strndup(blame_line->id,
				    idfield - 1);
				if (id_str == NULL) {
					fsl_free(line);
					return RC(FSL_RC_ERROR, "%s",
					    "fsl_strdup");
				}
				if (s->colour)
					c = get_colour(&s->colours, FNC_COMMIT);
				if (c)
					wattr_on(view->window,
					    COLOR_PAIR(c->scheme), NULL);
				wprintw(view->window, "%.*s", idfield - 1,
				    id_str);
				if (c)
					wattr_off(view->window,
					    COLOR_PAIR(c->scheme), NULL);
				fsl_free(id_str);
				prev_id = blame_line->id;
			} else {
				waddstr(view->window, "..........");
				prev_id = NULL;
			}
		} else {
			waddstr(view->window, "..........");
			prev_id = NULL;
		}

		if (view->active && nprinted == s->selected_line - 1)
			wattr_off(view->window, A_REVERSE, NULL);
		waddstr(view->window, " ");

		if (view->ncols <= idfield) {
			width = idfield;
			wcstr = wcsdup(L"");
			if (wcstr == NULL) {
				rc = RC(fsl_errno_to_rc(errno, FSL_RC_RANGE),
				    "%s", "wcsdup");
				fsl_free(line);
				return rc;
			}
		} else if (s->first_line_onscreen + nprinted == s->matched_line
		    && regmatch->rm_so >= 0 &&
		    regmatch->rm_so < regmatch->rm_eo) {
			rc = write_matched_line(&width, line,
			    view->ncols - idfield, idfield,
			    view->window, regmatch);
			if (rc) {
				fsl_free(line);
				return rc;
			}
			width += idfield;
		} else {
			rc = formatln(&wcstr, &width, line,
			    view->ncols - idfield, idfield);
			waddwstr(view->window, wcstr);
			fsl_free(wcstr);
			wcstr = NULL;
			width += idfield;
		}

		if (width <= view->ncols - 1)
			waddch(view->window, '\n');
		if (++nprinted == 1)
			s->first_line_onscreen = lineno;
	}
	fsl_free(line);
	s->last_line_onscreen = lineno;

	draw_vborder(view);

	return rc;
}

static int
blame_input_handler(struct fnc_view **new_view, struct fnc_view *view, int ch)
{
	struct fnc_view			*diff_view;
	struct fnc_blame_view_state	*s = &view->state.blame;
	int				 start_col = 0, rc = 0;

	switch (ch) {
	case 'q':
		s->done = true;
		if (s->selected_commit)
			fnc_commit_artifact_close(s->selected_commit);
		break;
	case 'c':
		s->colour = !s->colour;
		break;
	case 'g':
		if (!fnc_home(view))
			break;
	case KEY_HOME:
		s->selected_line = 1;
		s->first_line_onscreen = 1;
		break;
	case KEY_END:
	case 'G':
		if (s->blame.nlines < view->nlines - 2) {
			s->selected_line = s->blame.nlines;
			s->first_line_onscreen = 1;
		} else {
			s->selected_line = view->nlines - 2;
			s->first_line_onscreen = s->blame.nlines -
			    (view->nlines - 3);
		}
		break;
	case KEY_UP:
	case 'k':
		if (s->selected_line > 1)
			--s->selected_line;
		else if (s->selected_line == 1 && s->first_line_onscreen > 1)
			--s->first_line_onscreen;
		break;
	case KEY_PPAGE:
	case CTRL('b'):
		if (s->first_line_onscreen == 1) {
			s->selected_line = 1;
			break;
		}
		if (s->first_line_onscreen > view->nlines - 2)
			s->first_line_onscreen -= (view->nlines - 2);
		else
			s->first_line_onscreen = 1;
		break;
	case KEY_DOWN:
	case 'j':
		if (s->selected_line < view->nlines - 2 &&
		    s->first_line_onscreen +
		    s->selected_line <= s->blame.nlines)
			++s->selected_line;
		else if (s->last_line_onscreen < s->blame.nlines)
			++s->first_line_onscreen;
		break;
	case 'b':
	case 'p': {
		fsl_uuid_cstr id = NULL;
		id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
		    s->first_line_onscreen, s->selected_line);
		if (id == NULL)
			break;
		if (ch == 'p') {
			fsl_cx		*f = fcli_cx();
			fsl_db		*db = fsl_needs_repo(f);
			fsl_deck	 d = fsl_deck_empty;
			fsl_id_t	 rid = fsl_uuid_to_rid(f, id);
			fsl_uuid_str	 pid = fsl_db_g_text(db, NULL,
			    "SELECT uuid FROM plink, blob WHERE plink.cid=%d "
			    "AND blob.rid=plink.pid AND plink.isprim", rid);
			if (pid == NULL)
				break;
			/* Check file exists in parent check-in. */
			rc = fsl_deck_load_sym(f, &d, pid, FSL_SATYPE_CHECKIN);
			if (rc) {
				rc = RC(rc, "%s", "fsl_deck_load_sym");
				goto cleanup;
			}
			rc = fsl_deck_F_rewind(&d);
			if (rc) {
				rc = RC(rc, "%s", "fsl_deck_F_rewind");
				goto cleanup;
			}
			if (fsl_deck_F_search(&d, s->path +
			    (fnc_init.sym ? 0 : 1)) == NULL)
				goto cleanup; /* File not in selected version */
			rc = fnc_commit_qid_alloc(&s->blamed_commit, pid);
cleanup:
			fsl_deck_finalize(&d);
			fsl_free(pid);
			if (rc)
				return rc;
		} else {
			if (!fsl_uuidcmp(id, s->blamed_commit->id))
				break;
			rc = fnc_commit_qid_alloc(&s->blamed_commit, id);
		}
		if (rc)
			break;
		s->done = true;
		rc = stop_blame(&s->blame);
		s->done = false;
		if (rc)
			break;
		CONCAT(STAILQ, _INSERT_HEAD)(&s->blamed_commits,
		    s->blamed_commit, entry);
		rc = run_blame(view);
		if (rc)
			break;
		break;
	}
	case KEY_BACKSPACE:
	case 'B': {
		struct fnc_commit_qid *first;
		first = CONCAT(STAILQ, _FIRST)(&s->blamed_commits);
		if (!fsl_uuidcmp(first->id, s->commit_id))
			break;
		s->done = true;
		rc = stop_blame(&s->blame);
		s->done = false;
		if (rc)
			break;
		CONCAT(STAILQ, _REMOVE_HEAD)(&s->blamed_commits, entry);
		fnc_commit_qid_free(s->blamed_commit);
		s->blamed_commit = CONCAT(STAILQ, _FIRST)(&s->blamed_commits);
		rc = run_blame(view);
		if (rc)
			break;
		break;
	}
	case KEY_ENTER:
	case '\r': {
		fsl_cx				*f = fcli_cx();
		struct fnc_commit_artifact	*commit = NULL;
		fsl_uuid_cstr			 id = NULL;
		char				 sym[FSL_UUID_STRLEN_MIN];
		fsl_id_t			 rid;

		id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
		    s->first_line_onscreen, s->selected_line);
		if (id == NULL)
			break;
		if (s->selected_commit)
			fnc_commit_artifact_close(s->selected_commit);
		memcpy(sym, id, FSL_UUID_STRLEN_MIN);
		sym[FSL_UUID_STRLEN_MIN - 1] = '\0';
		rc = fsl_sym_to_rid(f, sym, FSL_SATYPE_CHECKIN, &rid);
		if (rc)
			break;
		rc = commit_builder(&commit, rid, NULL);
		if (rc) {
			fnc_commit_artifact_close(commit);
			break;
		}
		if (view_is_parent(view))
		    start_col = view_split_start_col(view->start_col);
		diff_view = view_open(0, 0, 0, start_col, FNC_VIEW_DIFF);
		if (diff_view == NULL) {
			fnc_commit_artifact_close(commit);
			rc = RC(FSL_RC_ERROR, "%s", "view_open");
			break;
		}
		rc = open_diff_view(diff_view, commit, DIFF_DEF_CTXT,
		    fnc_init.ws, fnc_init.invert, !fnc_init.quiet, NULL, true);
		s->selected_commit = commit;
		if (rc) {
			fnc_commit_artifact_close(commit);
			view_close(diff_view);
			break;
		}
		view->active = false;
		diff_view->active = true;
		if (view_is_parent(view)) {
			rc = view_close_child(view);
			if (rc)
				break;
			view_set_child(view, diff_view);
			view->focus_child = true;
		} else
			*new_view = diff_view;
		if (rc)
			break;
		break;
	}
	case KEY_NPAGE:
	case CTRL('f'):
	case ' ':
		if (s->last_line_onscreen >= s->blame.nlines && s->selected_line
		    >= MIN(s->blame.nlines, view->nlines - 2))
			break;
		if (s->last_line_onscreen >= s->blame.nlines &&
		    s->selected_line < view->nlines - 2) {
			s->selected_line = MIN(s->blame.nlines,
			    view->nlines - 2);
			break;
		}
		if (s->last_line_onscreen + view->nlines - 2 <= s->blame.nlines)
			s->first_line_onscreen += view->nlines - 2;
		else
			s->first_line_onscreen =
			    s->blame.nlines - (view->nlines - 3);
		break;
	case KEY_RESIZE:
		if (s->selected_line > view->nlines - 2) {
			s->selected_line = MIN(s->blame.nlines,
			    view->nlines - 2);
		}
		break;
	default:
		break;
	}
	return rc;
}

static int
blame_search_init(struct fnc_view *view)
{
	struct fnc_blame_view_state *s = &view->state.blame;

	s->matched_line = 0;
	return 0;
}

static int
blame_search_next(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	char				*line = NULL;
	ssize_t				 linelen;
	size_t				 linesz = 0;
	int				 lineno;

	if (view->searching == SEARCH_DONE) {
		view->search_status = SEARCH_CONTINUE;
		return 0;
	}

	if (s->matched_line) {
		if (view->searching == SEARCH_FORWARD)
			lineno = s->matched_line + 1;
		else
			lineno = s->matched_line - 1;
	} else {
		if (view->searching == SEARCH_FORWARD)
			lineno = 1;
		else
			lineno = s->blame.nlines;
	}

	while (1) {
		off_t offset;

		if (lineno <= 0 || lineno > s->blame.nlines) {
			if (s->matched_line == 0) {
				view->search_status = SEARCH_CONTINUE;
				break;
			}

			if (view->searching == SEARCH_FORWARD)
				lineno = 1;
			else
				lineno = s->blame.nlines;
		}

		offset = s->blame.line_offsets[lineno - 1];
		if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
			fsl_free(line);
			return RC(fsl_errno_to_rc(errno, FSL_RC_IO),
			    "%s", "fseeko");
		}
		linelen = getline(&line, &linesz, s->blame.f);
		if (linelen != -1 && regexec(&view->regex, line, 1,
		    &view->regmatch, 0) == 0) {
			view->search_status = SEARCH_CONTINUE;
			s->matched_line = lineno;
			break;
		}
		if (view->searching == SEARCH_FORWARD)
			++lineno;
		else
			--lineno;
	}
	fsl_free(line);

	if (s->matched_line) {
		s->first_line_onscreen = s->matched_line;
		s->selected_line = 1;
	}

	return 0;
}

static fsl_uuid_cstr
get_selected_commit_id(struct fnc_blame_line *lines, int nlines,
    int first_line_onscreen, int selected_line)
{
	struct fnc_blame_line *line;

	if (nlines <= 0)
		return NULL;

	line = &lines[first_line_onscreen - 1 + selected_line - 1];

	return line->id;
}

static int
fnc_commit_qid_alloc(struct fnc_commit_qid **qid, fsl_uuid_cstr id)
{
	int rc = 0;

	*qid = calloc(1, sizeof(**qid));
	if (*qid == NULL)
		return RC(fsl_errno_to_rc(errno, FSL_RC_ERROR), "%s", "calloc");

	(*qid)->id = fsl_strdup(id);
	if ((*qid)->id == NULL) {
		rc = RC(FSL_RC_ERROR, "%s", "fsl_strdup");
		fnc_commit_qid_free(*qid);
		*qid = NULL;
	}

	return rc;
}

static int
close_blame_view(struct fnc_view *view)
{
	struct fnc_blame_view_state	*s = &view->state.blame;
	struct fsl_list_state		 st = { FNC_COLOUR_OBJ };
	int				 rc = 0;

	rc = stop_blame(&s->blame);

	while (!CONCAT(STAILQ, _EMPTY)(&s->blamed_commits)) {
		struct fnc_commit_qid *blamed_commit;
		blamed_commit = CONCAT(STAILQ, _FIRST)(&s->blamed_commits);
		CONCAT(STAILQ, _REMOVE_HEAD)(&s->blamed_commits, entry);
		fnc_commit_qid_free(blamed_commit);
	}

	fsl_free(s->path);
	fsl_list_clear(&s->colours, fsl_list_object_free, &st);

	return rc;
}

static int
stop_blame(struct fnc_blame *blame)
{
	int idx, rc = 0;

	if (blame->thread_id) {
		int retval;
		rc = pthread_mutex_unlock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_unlock");
		rc = pthread_join(blame->thread_id, (void **)&retval);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_join");
		rc = pthread_mutex_lock(&fnc_mutex);
		if (rc)
			return RC(fsl_errno_to_rc(rc, FSL_RC_ACCESS),
			    "%s", "pthread_mutex_lock");
		if (!rc && fsl_cx_err_get_e(fcli_cx())->code == FSL_RC_BREAK) {
			rc = 0;
			fcli_err_reset();
		}
		blame->thread_id = 0;
	}
	if (blame->f) {
		if (fclose(blame->f) == EOF && rc == 0)
			rc = RC(fsl_errno_to_rc(errno, FSL_RC_IO), "%s",
			    fclose);
		blame->f = NULL;
	}
	if (blame->lines) {
		for (idx = 0; idx < blame->nlines; ++idx)
			fsl_free(blame->lines[idx].id);
		fsl_free(blame->lines);
		blame->lines = NULL;
	}

	fsl_free(blame->cb_cx.root_commit);
	blame->cb_cx.root_commit = NULL;
	fsl_free(blame->cb_cx.commit_id);
	blame->cb_cx.commit_id = NULL;
	fsl_free(blame->line_offsets);

	return rc;
}

static int
cancel_blame(void *state)
{
	int	*done = state;
	int	 rc = 0;

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

	if (*done)
		rc = fcli_err_set(FSL_RC_BREAK, "user quit");

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

	return rc;
}

static void
fnc_commit_qid_free(struct fnc_commit_qid *qid)
{
	fsl_free(qid->id);
	fsl_free(qid);
}

static void
fnc_show_version(void)
{
	printf("%s %s\n", fcli_progname(), PRINT_VERSION);
}

static int
strtonumcheck(int *ret, const char *nstr, const int min, const int max)
{
	const char	*ptr;
	int		 n;

	ptr = NULL;
	errno = 0;

	n = strtonum(nstr, min, max, &ptr);
	if (errno == ERANGE)
		return RC(FSL_RC_RANGE, "<n> out of range: -n|--limit=%s [%s]",
		    nstr, ptr);
	else if (errno != 0 || errno == EINVAL)
		return RC(FSL_RC_MISUSE, "<n> not a number: -n|--limit=%s [%s]",
		    nstr, ptr);
	else if (ptr && *ptr != '\0')
		return RC(FSL_RC_MISUSE,
		    "invalid char in <n>: -n|--limit=%s [%s]", nstr, ptr);

	*ret = n;
	return 0;
}

static char *
fnc_strsep(char **ptr, const char *sep)
{
	char	*s, *token;

	if ((s = *ptr) == NULL)
		return NULL;

	if (*(token = s + strcspn(s, sep)) != '\0') {
		*token++ = '\0';
		*ptr = token;
	} else
		*ptr = NULL;

	return s;
}

#ifdef __linux__
static size_t
fnc_strlcat(char *restrict dst, const char *restrict src, size_t dstsz)
{
	size_t	offset;
	int	dstlen, srclen, idx = 0;

	offset = dstlen = fsl_strlen(dst);
	srclen = fsl_strlen(src);

	while ((*(dst + offset++) = *(src + idx++)) != '\0')
		if (offset == dstsz - 1)
			break;

	*(dst + offset) = '\0';

	return dstlen + srclen;
}

static size_t
fnc_strlcpy(char *restrict dst, const char *restrict src, size_t dstsz)
{
	size_t offset = 0;

	if (dstsz < 1)
		goto end;

	while ((*(dst + offset) = *(src + offset)) != '\0')
		if (++offset == dstsz) {
			--offset;
			break;
		}

end:
	*(dst + offset) = '\0';
	while (*(src + offset) != '\0')
		++offset;	/* Return src length. */

	return offset;
}
#endif

Changes to shakenmake.make.

351
352
353
354
355
356
357

358
359
360
361
362
363
364
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365







+







%.o: %.cpp
	@$(call ShakeNMake.CALL.SETX,"C++ [$@]"); \
	$(COMPILE.cc) $(COMPILE.cc.OPTIONS) $(OUTPUT_OPTION) $<
endif # Tromey's Way

########################################################################
# create emacs tags...
ifneq (1,$(ShakeNMake.ETAGS.DISABLE))
bin_etags := $(call ShakeNMake.CALL.FIND_FILE,etags)
ifeq (.,$(TOP_SRCDIR_REL))
ifneq (,$(bin_etags))
TAGTHESE := $(shell find . -name '*.[ch]' -print)
ifneq (,$(TAGTHESE))
    $(TAGTHESE):
    TAGFILE := TAGS
373
374
375
376
377
378
379


380
381
382
383
384
385
386
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389







+
+







    CLEAN_FILES += $(TAGFILE)
    all: $(TAGFILE)
endif
endif
# ^^^ bin_etags
endif
# ^^^ TOP_SRCDIR_REL==.
endif
# ^^^ $(ShakeNMake.TAGS.DISABLE)

#%.o:
#	@$$(call ShakeNMake.CALL.SETX,"CC [$@] ..."); \
#	$(COMPILE.c) $(COMPILE.c.OPTIONS) -o $@

########################################################################
# Installation rules...
512
513
514
515
516
517
518
519

520
521
522
515
516
517
518
519
520
521

522
523
524
525







-
+



#$(call ShakeNMake.CALL.define-install-set,package_dlls,$(prefix)/lib/$(package.name),$(ShakeNMake.INSTALL.flags.dlls))
#$(call ShakeNMake.CALL.define-install-set,headers,$(prefix)/include,$(ShakeNMake.INSTALL.flags.nonbins))
#$(call ShakeNMake.CALL.define-install-set,package_headers,$(prefix)/include/$(package.name),$(ShakeNMake.INSTALL.flags.nonbins))
#$(call ShakeNMake.CALL.define-install-set,package_data,$(prefix)/share/$(package.name),$(ShakeNMake.INSTALL.flags.nonbins))
#$(call ShakeNMake.CALL.define-install-set,docs,$(prefix)/share/doc/$(package.name),$(ShakeNMake.INSTALL.flags.nonbins))
# Set up man page entries...
$(foreach NUM,1 2 3 4 5 6 7 8 9,$(call \
	ShakeNMake.CALL.define-install-set,man$(NUM),$(prefix)/man/man$(NUM),$(ShakeNMake.INSTALL.flags.nonbins)))
	ShakeNMake.CALL.define-install-set,man$(NUM),$(prefix)/share/man/man$(NUM),$(ShakeNMake.INSTALL.flags.nonbins)))
endif
# /install
########################################################################

Added signify/fnc-02-release.pub.



1
2
+
+
untrusted comment: fnc 0.2 public key
RWQbpVGH9jal6DtP0CjKTyQETetZS7nMoD76X9NVVji8MZ15XHX0IAHQ

Added signify/fnc-03-release.pub.



1
2
+
+
untrusted comment: fnc 0.3 public key
RWSXIKpSr2F8z3tjmWW3pcJvNH07ArhQ8jkiA/b7weZbyS+Q7R2DG28g

Changes to src/Makefile.in.

1
2
3

4
5
6
7
8
9
10
11
1
2

3

4
5
6
7
8
9
10


-
+
-







all:
include ../subdir-inc.make
#$(error $(TOP_SRCDIR))
DISTCLEAN_FILES += Makefile
#EXTRA_LIBS := -lz

THE_OBJ := libfossil.o
ifneq (,$(wildcard sqlite3.c))
  HAVE_OWN_SQLITE := 1
  CPPFLAGS += -DSQLITE_CORE
  THE_OBJ += sqlite3.o
else

Changes to src/libfossil-config.h.

79
80
81
82
83
84
85
86
87
88



89
90
91
92
93
94
95
79
80
81
82
83
84
85



86
87
88
89
90
91
92
93
94
95







-
-
-
+
+
+







#if !defined(HAVE_STDINT_H)
#  define HAVE_STDINT_H 1
#endif
#endif
/* _WIN32 */


#define FSL_LIB_VERSION_HASH "5d405b727bd79bf2abb5349407432178394a962a"
#define FSL_LIB_VERSION_TIMESTAMP "2021-08-23 15:36:42.964 UTC"
#define FSL_LIB_CONFIG_TIME "2021-08-23 15:38 GMT"
#define FSL_LIB_VERSION_HASH "acbd39275f0d573a74d996caea7918afafff2ff7"
#define FSL_LIB_VERSION_TIMESTAMP "2021-10-08 03:15:51.855 UTC"
#define FSL_LIB_CONFIG_TIME "2021-10-08 04:07 GMT"
#if defined(_MSC_VER)
#define FSL_PLATFORM_OS "windows"
#define FSL_PLATFORM_IS_WINDOWS 1
#define FSL_PLATFORM_IS_UNIX 0
#define FSL_PLATFORM_PLATFORM "windows"
#define FSL_PLATFORM_PATH_SEPARATOR ";"
#define FSL_CHECKOUTDB_NAME "./_FOSSIL_"

Changes to src/libfossil.c.

370
371
372
373
374
375
376


377
378
379
380
381
382
383
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385







+
+







    STR(CONFLICT);
    STR(CONSISTENCY);
    STR(DB);
    STR(DELTA_INVALID_OPERATOR);
    STR(DELTA_INVALID_SEPARATOR);
    STR(DELTA_INVALID_SIZE);
    STR(DELTA_INVALID_TERMINATOR);
    STR(DIFF_BINARY);
    STR(DIFF_WS_ONLY);
    STR(end);
    STR(ERROR);
    STR(IO);
    STR(MISSING_INFO);
    STR(MISUSE);
    STR(NOOP);
    STR(NOT_A_CKOUT);
645
646
647
648
649
650
651
652

653
654
655
656
657
658
659
647
648
649
650
651
652
653

654
655
656
657
658
659
660
661







-
+







  time_t const tt = (time_t)u;
  fsl_strftime( buf, BufSize, "%Y-%m-%dT%H:%M:%S", gmtime(&tt) );
  return fsl_strdup(buf);
}
#endif


char fsl_iso8601_to_julian( char const * zDate, double * out ){
bool fsl_iso8601_to_julian( char const * zDate, double * out ){
  /* Adapted from this article:

     https://quasar.as.utexas.edu/BillInfo/JulianDatesG.html
  */
  char const * p = zDate;
  int y = 0, m = 0, d = 0;
  int h = 0, mi = 0, s = 0, f = 0;
701
702
703
704
705
706
707
708

709
710
711
712
713
714
715
703
704
705
706
707
708
709

710
711
712
713
714
715
716
717







-
+







#undef DIG
}

fsl_time_t fsl_julian_to_unix( double JD ){
  return (fsl_time_t) ((JD - 2440587.5) * 86400);
}

char fsl_julian_to_iso8601( double J, char * out, bool addMs ){
bool fsl_julian_to_iso8601( double J, char * out, bool addMs ){
  /* Adapted from this article:

     https://quasar.as.utexas.edu/BillInfo/JulianDatesG.html
  */
  typedef int64_t TI;
  int Y, M, D, H, MI, S, F;
  TI ms;
1102
1103
1104
1105
1106
1107
1108












































































































































































































































































































































































































































































1109
1110
1111
1112
1113
1114
1115
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577







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







}

#undef MARKER
#if defined(_WIN32) || defined(WIN32)
#undef isatty
#endif
/* end of file fsl.c */
/* start of file 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
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/
/************************************************************************
  This file implements the annoate/blame/praise-related APIs.
*/
#include <assert.h>
#include <string.h>/*memset()*/

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

const fsl_annotate_opt fsl_annotate_opt_empty = fsl_annotate_opt_empty_m;

/*
** The status of an annotation operation is recorded by an instance
** of the following structure.
*/
typedef struct Annotator Annotator;
struct Annotator {
  fsl_diff_cx c;       /* The diff-engine context */
  fsl_buffer headVersion;/*starting version of the content*/
  struct AnnLine {  /* Lines of the original files... */
    const char *z;       /* The text of the line. Points into
                            this->headVersion. */
    short int n;         /* Number of bytes (omitting trailing \n) */
    short int iVers;     /* Level at which tag was set */
  } *aOrig;
  unsigned int nOrig;/* Number of elements in aOrig[] */
  unsigned int nVers;/* Number of versions analyzed */
  bool bMoreToDo;    /* True if the limit was reached */
  fsl_id_t origId;       /* RID for the zOrigin version */
  fsl_id_t showId;       /* RID for the version being analyzed */
  struct AnnVers {
    char *zFUuid;   /* File being analyzed */
    char *zMUuid;   /* Check-in containing the file */
    char *zUser;    /* Name of user who did the check-in */
    double mtime;   /* [event].[mtime] db entry */
  } *aVers;         /* For each check-in analyzed */
  unsigned int naVers; /* # of entries allocated in this->aVers */
};

static const Annotator Annotator_empty = {
fsl_diff_cx_empty_m,
fsl_buffer_empty_m/*headVersion*/,
NULL/*aOrig*/,
0U/*nOrig*/, 0U/*nVers*/,
false/*bMoreToDo*/,
0/*origId*/,
0/*showId*/,
NULL/*aVers*/,
0U/*naVerse*/
};

static void fsl__annotator_clean(Annotator * const a){
  unsigned i;
  fsl__diff_cx_clean(&a->c);
  for(i = 0; i < a->nVers; ++i){
    fsl_free(a->aVers[i].zFUuid);
    fsl_free(a->aVers[i].zMUuid);
    fsl_free(a->aVers[i].zUser);
  }
  fsl_free(a->aVers);
  fsl_free(a->aOrig);
  fsl_buffer_clear(&a->headVersion);
}

static uint64_t fsl__annotate_opt_difflags(fsl_annotate_opt const * const opt){
  uint64_t diffFlags = FSL_DIFF2_STRIP_EOLCR;
  if(opt->spacePolicy>0) diffFlags |= FSL_DIFF2_IGNORE_ALLWS;
  else if(opt->spacePolicy<0) diffFlags |= FSL_DIFF2_IGNORE_EOLWS;
  return diffFlags;
}

/**
   Initializes the annocation process by populating `a` from
   a->toAnnote, which must have been previously populated.  `a` must
   have already been cleanly initialized via copying from
   Annotator_empty and a->headVersion populated.  Returns 0 on success,
   else:

   - FSL_RC_RANGE if pInput is empty.
   - FSL_RC_OOM on OOM.

   Regardless of success or failure, `a` must eventually be passed
   to fsl__annotator_clean() to free up any resources.
*/
static int fsl__annotation_start(Annotator * const a,
                                 fsl_annotate_opt const * const opt){
  int rc;
  uint64_t const diffFlags = fsl__annotate_opt_difflags(opt);
  if(opt->spacePolicy>0){
    a->c.cmpLine = fsl_dline_cmp_ignore_ws;
  }else{
    assert(fsl_dline_cmp == a->c.cmpLine);
  }
  rc = fsl_break_into_dlines(fsl_buffer_cstr(&a->headVersion),
                             (fsl_int_t)a->headVersion.used,
                             (uint32_t*)&a->c.nTo, &a->c.aTo, diffFlags);
  if(rc) goto end;
  if(!a->c.nTo){
    rc = FSL_RC_RANGE;
    goto end;
  }
  a->aOrig = fsl_malloc( (fsl_size_t)(sizeof(a->aOrig[0]) * a->c.nTo) );
  if(!a->aOrig){
    rc = FSL_RC_OOM;
    goto end;
  }
  for(int i = 0; i < a->c.nTo; ++i){
    a->aOrig[i].z = a->c.aTo[i].z;
    a->aOrig[i].n = a->c.aTo[i].n;
    a->aOrig[i].iVers = -1;
  }
  a->nOrig = (unsigned)a->c.nTo;
  end:
  return rc;
}

/**
   The input pParent is the next most recent ancestor of the file
   being annotated.  Do another step of the annotation. On success
   return 0 and, if additional annotation is required, assign *doMore
   (if not NULL) to true.
*/
static int fsl__annotation_step(
  Annotator * const a,
  fsl_buffer const *pParent,
  int iVers,
  fsl_annotate_opt const * const opt
){
  int i, j, rc;
  int lnTo;
  uint64_t const diffFlags = fsl__annotate_opt_difflags(opt);

  /* Prepare the parent file to be diffed */
  rc = fsl_break_into_dlines(fsl_buffer_cstr(pParent),
                             (fsl_int_t)pParent->used,
                             (uint32_t*)&a->c.nFrom, &a->c.aFrom,
                             diffFlags);
  if(rc) goto end;
  else if( a->c.aFrom==0 ){
    return 0;
  }
  //MARKER(("Line #1: %.*s\n", (int)a->c.aFrom[0].n, a->c.aFrom[0].z));
  /* Compute the differences going from pParent to the file being
  ** annotated. */
  rc = fsl__diff_all(&a->c);
  if(rc) goto end;

  /* Where new lines are inserted on this difference, record the
  ** iVers as the source of the new line.
  */
  for(i=lnTo=0; i<a->c.nEdit; i+=3){
    int const nCopy = a->c.aEdit[i];
    int const nIns = a->c.aEdit[i+2];
    lnTo += nCopy;
    for(j=0; j<nIns; ++j, ++lnTo){
      if( a->aOrig[lnTo].iVers<0 ){
        a->aOrig[lnTo].iVers = iVers;
      }
    }
  }

  /* Clear out the diff results except for c.aTo, as that's pointed to
     by a->aOrig.*/
  fsl_free(a->c.aEdit);
  a->c.aEdit = 0;
  a->c.nEdit = 0;
  a->c.nEditAlloc = 0;

  /* Clear out the from file */
  fsl_free(a->c.aFrom);
  a->c.aFrom = 0;
  a->c.nFrom = 0;
  end:
  return rc;
}

/* MISSING(?) fossil(1) converts the diff inputs into utf8 with no
   BOM. Whether we really want to do that here or rely on the caller
   to is up for debate. If we do it here, we have to make the inputs
   non-const, which seems "wrong" for a library API. */
#define blob_to_utf8_no_bom(A,B) (void)0

static int fsl__annotate_file(fsl_cx * const f,
                              Annotator * const a,
                              fsl_annotate_opt const * const opt){
  int rc = FSL_RC_NYI;
  fsl_buffer step = fsl_buffer_empty /*previous revision*/;
  fsl_id_t cid = 0, fnid = 0; // , rid = 0;
  fsl_stmt q = fsl_stmt_empty;
  bool openedTransaction = false;
  fsl_db * const db = fsl_needs_repo(f);

  if(!db) return FSL_RC_NOT_A_REPO;
  rc = fsl_cx_transaction_begin(f);
  if(rc) goto dberr;
  openedTransaction = true;

  fnid = fsl_db_g_id(db, 0,
                     "SELECT fnid FROM filename WHERE name=%Q %s",
                     opt->filename, fsl_cx_filename_collation(f));
  if(0==fnid){
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                        "File not found in repository: %s",
                        opt->filename);
    goto end;
  }
  if(opt->versionRid>0){
    cid = opt->versionRid;
  }else{
    fsl_ckout_version_info(f, &cid, NULL);
    if(cid<=0){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_A_CKOUT,
                          "Cannot determine version RID to "
                          "annotate from.");
      goto end;
    }
  }
  if(opt->originRid>0){
    rc = fsl_vpath_shortest_store_in_ancestor(f, cid, opt->originRid, NULL);
  }else{
    rc = fsl_compute_direct_ancestors(f, cid);
  }
  if(rc) goto end;
  
  rc = fsl_db_prepare(db, &q,
    "SELECT DISTINCT"
    "   (SELECT uuid FROM blob WHERE rid=mlink.fid),"
    "   (SELECT uuid FROM blob WHERE rid=mlink.mid),"
    "   coalesce(event.euser,event.user),"
    "   mlink.fid, event.mtime"
    "  FROM mlink, event, ancestor"
    " WHERE mlink.fnid=%" FSL_ID_T_PFMT
    "   AND ancestor.rid=mlink.mid"
    "   AND event.objid=mlink.mid"
    "   AND mlink.mid!=mlink.pid"
    " ORDER BY ancestor.generation;",
    fnid
  );
  if(rc) goto dberr;
  
  while(FSL_RC_STEP_ROW==fsl_stmt_step(&q)){
    if(a->nVers>=3){
      /*Process at least 3 rows before imposing any limit.
        Note that we do not impose a time-based limit here like
        fossil does, but may want to add that at some point.*/
      if(opt->limit>0 && a->nVers>=opt->limit){
        a->bMoreToDo = true;
        break;
      }
    }
    char * zTmp = 0;
    char const * zCol = 0;
    fsl_size_t nCol = 0;
    fsl_id_t const rid = fsl_stmt_g_id(&q, 3);
    double const mtime = fsl_stmt_g_double(&q, 4);
    if(0==a->nVers){
      rc = fsl_content_get(f, rid, &a->headVersion);
      if(rc) goto end;
      blob_to_utf8_no_bom(&a->headVersion,0);
      rc = fsl__annotation_start(a, opt);
      if(rc) goto end;
      a->bMoreToDo = opt->originRid>0;
      a->origId = opt->originRid;
      a->showId = cid;
      assert(0==a->nVers);
      assert(NULL==a->aVers);
    }
    if(a->naVers==a->nVers){
      unsigned int const n = a->naVers ? a->naVers*3/2 : 10;
      void * const x = fsl_realloc(a->aVers, n*sizeof(a->aVers[0]));
      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); \
    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;
    if( a->nVers>0 ){
      rc = fsl_content_get(f, rid, &step);
      if(!rc){
        rc = fsl__annotation_step(a, &step, a->nVers-1, opt);
      }
      fsl_buffer_reuse(&step);
      if(rc) goto end;
    }
    ++a->nVers;
  }

  assert(0==rc);
  if(0==a->nVers){
    if(opt->versionRid>0){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "File [%s] does not exist "
                          "in checkin RID %" FSL_ID_T_PFMT,
                          opt->filename, opt->versionRid);
    }else{
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "No history found for file: %s",
                          opt->filename);
    }
  }
  
  end:
  fsl_buffer_clear(&step);
  fsl_stmt_finalize(&q);
  if(openedTransaction) fsl_cx_transaction_end(f, rc!=0);
  return rc;
  dberr:
  assert(openedTransaction);
  assert(rc!=0);
  fsl_stmt_finalize(&q);
  fsl_buffer_clear(&step);
  rc = fsl_cx_uplift_db_error2(f, db, rc);
  if(openedTransaction) fsl_cx_transaction_end(f, rc!=0);
  return rc;
}

int fsl_annotate_step_f_fossilesque(void * state,
                                    fsl_annotate_opt const * const opt,
                                    fsl_annotate_step const * const step){
  static const int szHash = 10;
  fsl_outputer const * fout = (fsl_outputer*)state;
  int rc = 0;
  char ymd[24];
  if(step->mtime>0){
    fsl_julian_to_iso8601(step->mtime, &ymd[0], false);
    ymd[10] = 0;
  }
  switch(step->stepType){
    case FSL_ANNOTATE_STEP_VERSION:
      rc = fsl_appendf(fout->out, fout->state,
                       "version %3d: %s %.*s file %.*s\n",
                       step->stepNumber+1, ymd, szHash,
                       step->versionHash, szHash, step->fileHash);
      break;
    case FSL_ANNOTATE_STEP_FULL:
      if(opt->praise){
        rc = fsl_appendf(fout->out, fout->state,
                         "%.*s %s %13.13s: %.*s\n",
                         szHash,
                         opt->fileVersions ? step->fileHash : step->versionHash,
                         ymd, step->username,
                         (int)step->lineLength, step->line);
      }else{
        rc = fsl_appendf(fout->out, fout->state,
                         "%.*s %s %5d: %.*s\n",
                         szHash, opt->fileVersions ? step->fileHash : step->versionHash,
                         ymd, step->lineNumber,
                         (int)step->lineLength, step->line);
      }
      break;
    case FSL_ANNOTATE_STEP_LIMITED:
      if(opt->praise){
        rc = fsl_appendf(fout->out, fout->state,
                         "%*s %.*s\n", szHash+26, "",
                         (int)step->lineLength, step->line);
      }else{
        rc = fsl_appendf(fout->out, fout->state,
                         "%*s %5" PRIu32 ": %.*s\n",
                         szHash+11, "", step->lineNumber,
                         (int)step->lineLength, step->line);
      }
      break;
  }
  return rc;
}


int fsl_annotate( fsl_cx * const f, fsl_annotate_opt const * const opt ){
  int rc;
  Annotator ann = Annotator_empty;
  unsigned int i;
  fsl_buffer * const scratch = fsl_cx_scratchpad(f);
  fsl_annotate_step aStep;
  assert(opt->out);

  rc = fsl__annotate_file(f, &ann, opt);
  if(rc) goto end;
  memset(&aStep,0,sizeof(fsl_annotate_step));

  if(opt->dumpVersions){
    struct AnnVers *av;
    for(av = ann.aVers, i = 0;
        0==rc && i < ann.nVers; ++i, ++av){
      aStep.fileHash = av->zFUuid;
      aStep.versionHash = av->zMUuid;
      aStep.mtime = av->mtime;
      aStep.stepNumber = i;
      aStep.stepType = FSL_ANNOTATE_STEP_VERSION;
      rc = opt->out(opt->outState, opt, &aStep);
    }
    if(rc) goto end;
  }

  for(i = 0; 0==rc && i<ann.nOrig; ++i){
    short iVers = ann.aOrig[i].iVers;
    char const * z = ann.aOrig[i].z;
    int const n = ann.aOrig[i].n;
    if(iVers<0 && !ann.bMoreToDo){
      iVers = ann.nVers-1;
    }
    fsl_buffer_reuse(scratch);
    rc = fsl_buffer_append(scratch, z, n);
    if(rc) break;
    aStep.stepNumber = iVers;
    ++aStep.lineNumber;
    aStep.line = fsl_buffer_cstr(scratch);
    aStep.lineLength = (uint32_t)scratch->used;

    if(iVers>=0){
      struct AnnVers * const av = &ann.aVers[iVers];
      aStep.fileHash = av->zFUuid;
      aStep.versionHash = av->zMUuid;
      aStep.mtime = av->mtime;
      aStep.username = av->zUser;
      aStep.stepType = FSL_ANNOTATE_STEP_FULL;
    }else{
      aStep.fileHash = aStep.versionHash =
        aStep.username = NULL;
      aStep.stepType = FSL_ANNOTATE_STEP_LIMITED;
      aStep.mtime = 0.0;
    }
    rc = opt->out(opt->outState, opt, &aStep);
  }
  
  end:
  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 */
/* -*- 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.

1140
1141
1142
1143
1144
1145
1146





1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627








1628
1629
1630
1631
1632
1633
1634







+
+
+
+
+














-
-
-
-
-
-
-
-







  but without any warranty; without even the implied warranty of
  merchantability or fitness for a particular purpose.
**********************************************************************/

#include <string.h> /* strlen() */
#include <ctype.h>
#include <assert.h>

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

/* FIXME: determine this type at compile time via configuration
   options. OTOH, it compiles everywhere as-is so far.
 */
typedef long double LONGDOUBLE_TYPE;

/*
  If FSLPRINTF_OMIT_FLOATING_POINT is defined to a true value, then
  floating point conversions are disabled.
*/
#ifndef FSLPRINTF_OMIT_FLOATING_POINT
#  define FSLPRINTF_OMIT_FLOATING_POINT 0
#endif

/*
  If FSLPRINTF_OMIT_SIZE is defined to a true value, then
  the %n specifier is disabled.
*/
#ifndef FSLPRINTF_OMIT_SIZE
#  define FSLPRINTF_OMIT_SIZE 0
#endif

/*
  If FSLPRINTF_OMIT_SQL is defined to a true value, then
  the %q, %Q, and %B specifiers are disabled.
*/
#ifndef FSLPRINTF_OMIT_SQL
#  define FSLPRINTF_OMIT_SQL 0
#endif
1216
1217
1218
1219
1220
1221
1222
1223

1224
1225
1226
1227
1228
1229
1230
1675
1676
1677
1678
1679
1680
1681

1682
1683
1684
1685
1686
1687
1688
1689







-
+







  Conversion types fall into various categories as defined by the
  following enumeration.
*/
enum PrintfCategory {etRADIX = 1, /* Integer types.  %d, %x, %o, and so forth */
                     etFLOAT = 2, /* Floating point.  %f */
                     etEXP = 3, /* Exponentional notation. %e and %E */
                     etGENERIC = 4, /* Floating or exponential, depending on exponent. %g */
                     etSIZE = 5, /* Return number of characters processed so far. %n */
                     /* 5 can be reused. Formerly etSIZE (%n) */
                     etSTRING = 6, /* Strings. %s */
                     etDYNSTRING = 7, /* Dynamically allocated strings. %z */
                     etPERCENT = 8, /* Percent symbol. %% */
                     etCHARX = 9, /* Characters. %c */
                     /* The rest are extensions, not normally found in printf() */
                     etCHARLIT = 10, /* Literal characters.  %' */
#if !FSLPRINTF_OMIT_SQL
1382
1383
1384
1385
1386
1387
1388
1389

1390
1391
1392
1393
1394
1395
1396
1841
1842
1843
1844
1845
1846
1847

1848
1849
1850
1851
1852
1853
1854
1855







-
+







{'j'/*106*/, 0, 0, etJSONSTR, 0, 0 },
#else
{'j'/*106*/, 0, 0, 0, 0, 0 },
#endif
{'k'/*107*/, 0, 0, 0, 0, 0 },
{'l'/*108*/, 0, 0, 0, 0, 0 },
{'m'/*109*/, 0, 0, 0, 0, 0 },
{'n'/*110*/, 0, 0, etSIZE, 0, 0 },
{'n'/*110*/, 0, 0, 0, 0, 0 },
{'o'/*111*/, 8, 0, etRADIX,      0,  2 },
{'p'/*112*/, 16, 0, etPOINTER, 0, 1 },
#if FSLPRINTF_OMIT_SQL
{'q'/*113*/, 0, 0, 0, 0, 0 },
#else
{'q'/*113*/, 0, FLAG_STRING, etSQLESCAPE,  0, 0 },
#endif
1517
1518
1519
1520
1521
1522
1523
1524

1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536


1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548

1549
1550

1551
1552
1553

1554
1555

1556
1557
1558
1559

1560
1561

1562
1563
1564
1565
1566

1567
1568
1569


1570
1571
1572
1573

1574
1575

1576
1577
1578

1579
1580
1581
1582

1583
1584
1585

1586
1587
1588
1589
1590
1591
1592
1593
1976
1977
1978
1979
1980
1981
1982

1983
1984
1985
1986
1987
1988
1989
1990
1991
1992



1993
1994


1995
1996
1997
1998
1999
2000
2001
2002
2003

2004


2005



2006
2007

2008
2009
2010
2011

2012


2013


2014
2015

2016
2017


2018
2019
2020
2021
2022

2023
2024

2025
2026
2027

2028
2029
2030
2031

2032
2033
2034

2035

2036
2037
2038
2039
2040
2041
2042







-
+









-
-
-
+
+
-
-









-
+
-
-
+
-
-
-
+

-
+



-
+
-
-
+
-
-


-
+

-
-
+
+



-
+

-
+


-
+



-
+


-
+
-








   SIGNIFICANT LIMITATIONS:

   - Has no way of iterating over the format string, so handling
   precisions and such here can't work too well. (Nevermind:
   precision/justification is handled in fsl_appendfv().)
*/
typedef fsl_int_t (*fsl_appendf_spec_handler)( fsl_appendf_f pf,
typedef int (*fsl_appendf_spec_handler)( fsl_output_f pf,
                                               void * pfArg,
                                               unsigned int pfLen,
                                               void * vargp );


/**
   fsl_appendf_spec_handler for etSTRING types. It assumes that varg
   is a NUL-terminated (char [const] *)
*/
static fsl_int_t spech_string( fsl_appendf_f pf,
                               void * pfArg,
                               unsigned int pfLen,
static int spech_string( fsl_output_f pf, void * pfArg,
                         unsigned int pfLen, void * varg ){
                               void * varg )
{
  char const * ch = (char const *) varg;
  return ch ? pf( pfArg, ch, pfLen ) : 0;
}

/**
   fsl_appendf_spec_handler for etDYNSTRING types.  It assumes that
   varg is a non-const (char *). It behaves identically to
   spec_string() and then calls fsl_free() on that (char *).
*/
static fsl_int_t spech_dynstring( fsl_appendf_f pf,
static int spech_dynstring( fsl_output_f pf, void * pfArg,
                                  void * pfArg,
                                  unsigned int pfLen,
                            unsigned int pfLen, void * varg ){
                                  void * varg )
{
  fsl_int_t ret = spech_string( pf, pfArg, pfLen, varg );
  int const rc = spech_string( pf, pfArg, pfLen, varg );
  fsl_free( varg );
  return ret;
  return rc;
}

#if !FSLPRINTF_OMIT_HTML
static fsl_int_t spech_string_to_html( fsl_appendf_f pf,
static int spech_string_to_html( fsl_output_f pf, void * pfArg,
                                       void * pfArg,
                                       unsigned int pfLen,
                                 unsigned int pfLen, void * varg ){
                                       void * varg )
{
  char const * ch = (char const *) varg;
  unsigned int i;
  fsl_int_t ret = 0;
  int rc = 0;
  if( ! ch ) return 0;
  ret = 0;
  for( i = 0; (i<pfLen) && *ch; ++ch, ++i )
  rc = 0;
  for( i = 0; 0==rc && (i<pfLen) && *ch; ++ch, ++i )
  {
    switch( *ch )
    {
      case '<': ret += pf( pfArg, "&lt;", 4 );
      case '<': rc = pf( pfArg, "&lt;", 4 );
        break;
      case '&': ret += pf( pfArg, "&amp;", 5 );
      case '&': rc = pf( pfArg, "&amp;", 5 );
        break;
      default:
        ret += pf( pfArg, ch, 1 );
        rc = pf( pfArg, ch, 1 );
        break;
    };
  }
  return ret;
  return rc;
}

static int httpurl_needs_escape( int c )
static int httpurl_needs_escape( int c ){
{
  /*
    Definition of "safe" and "unsafe" chars
    was taken from:

    https://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4029/
  */
  return ( (c >= 32 && c <=47)
1603
1604
1605
1606
1607
1608
1609
1610

1611
1612

1613
1614
1615
1616

1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627

1628
1629

1630
1631

1632
1633
1634

1635
1636
1637
1638
1639
1640

1641
1642
1643
1644

1645
1646
1647
1648
1649
1650
1651
1652
1653

1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671

1672
1673

1674
1675
1676
1677

1678
1679
1680
1681
1682
1683
1684

1685
1686

1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697

1698
1699
1700
1701

1702
1703
1704
1705
1706
1707

1708
1709
1710
1711
1712

1713
1714
1715
1716

1717
1718
1719
1720
1721
1722

1723
1724
1725

1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741

1742
1743

1744
1745

1746
1747
1748
1749
1750
1751
1752
1753

1754
1755
1756
1757
1758
1759
1760
1761
1762
1763

1764
1765
1766
1767
1768
1769
1770
1771
1772

1773
1774

1775
1776
1777

1778
1779

1780
1781
1782
1783
1784
1785

1786
1787

1788
1789
1790
1791
1792
1793

1794
1795

1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
2052
2053
2054
2055
2056
2057
2058

2059


2060


2061

2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072

2073


2074


2075
2076


2077
2078
2079
2080
2081
2082

2083
2084
2085
2086

2087
2088
2089
2090
2091
2092
2093
2094
2095

2096

2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112

2113


2114


2115

2116
2117
2118
2119
2120
2121
2122

2123


2124

2125
2126
2127
2128
2129
2130
2131
2132
2133

2134
2135
2136


2137

2138
2139
2140
2141

2142
2143
2144
2145


2146

2147
2148

2149
2150
2151
2152
2153
2154

2155
2156
2157

2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173

2174


2175


2176

2177
2178
2179
2180
2181
2182

2183
2184
2185
2186
2187
2188
2189
2190
2191
2192

2193
2194
2195
2196
2197
2198
2199
2200
2201

2202
2203

2204
2205
2206

2207


2208


2209
2210
2211

2212


2213


2214
2215
2216

2217


2218


2219
2220
2221
2222
2223











2224
2225
2226
2227
2228
2229
2230







-
+
-
-
+
-
-

-
+










-
+
-
-
+
-
-
+

-
-
+





-
+



-
+








-
+
-
















-
+
-
-
+
-
-

-
+






-
+
-
-
+
-









-
+


-
-
+
-




-
+



-
-
+
-


-
+





-
+


-
+















-
+
-
-
+
-
-
+
-






-
+









-
+








-
+

-
+


-
+
-
-
+
-
-



-
+
-
-
+
-
-



-
+
-
-
+
-
-





-
-
-
-
-
-
-
-
-
-
-








   It expects varg to be a string value, which it will preceed to
   encode using an URL encoding algothrim (certain characters are
   converted to %XX, where XX is their hex value) and passes the
   encoded string to pf(). It returns the total length of the output
   string.
*/
static fsl_int_t spech_urlencode( fsl_appendf_f pf,
static int spech_urlencode( fsl_output_f pf, void * pfArg,
                                  void * pfArg,
                                  unsigned int pfLen,
                            unsigned int pfLen, void * varg ){
                                  void * varg )
{
  char const * str = (char const *) varg;
  fsl_int_t ret = 0;
  int rc = 0;
  char ch = 0;
  char const * hex = "0123456789ABCDEF";
#define xbufsz 10
  char xbuf[xbufsz];
  int slen = 0;
  if( ! str ) return 0;
  memset( xbuf, 0, xbufsz );
  ch = *str;
#define xbufsz 10
  slen = 0;
  for( ; ch; ch = *(++str) )
  for( ; 0==rc && ch; ch = *(++str) ){
  {
    if( ! httpurl_needs_escape( ch ) )
    if( ! httpurl_needs_escape( ch ) ){
    {
      ret += pf( pfArg, str, 1 );
      rc = pf( pfArg, str, 1 );
      continue;
    }
    else {
    }else{
      xbuf[0] = '%';
      xbuf[1] = hex[((ch>>4)&0xf)];
      xbuf[2] = hex[(ch&0xf)];
      xbuf[3] = 0;
      slen = 3;
      ret += pf( pfArg, xbuf, slen );
      rc = pf( pfArg, xbuf, slen );
    }
  }
#undef xbufsz
  return ret;
  return rc;
}

/* 
   hexchar_to_int():

   For 'a'-'f', 'A'-'F' and '0'-'9', returns the appropriate decimal
   number.  For any other character it returns -1.
*/
static int hexchar_to_int( int ch )
static int hexchar_to_int( int ch ){
{
  if( (ch>='0' && ch<='9') ) return ch-'0';
  else if( (ch>='a' && ch<='f') ) return ch-'a'+10;
  else if( (ch>='A' && ch<='F') ) return ch-'A'+10;
  else return -1;
}

/**
   The handler for the etURLDECODE specifier.

   It expects varg to be a ([const] char *), possibly encoded
   with URL encoding. It decodes the string using a URL decode
   algorithm and passes the decoded string to
   pf(). It returns the total length of the output string.
   If the input string contains malformed %XX codes then this
   function will return prematurely.
*/
static fsl_int_t spech_urldecode( fsl_appendf_f pf,
static int spech_urldecode( fsl_output_f pf, void * pfArg,
                                  void * pfArg,
                                  unsigned int pfLen,
                            unsigned int pfLen, void * varg ){
                                  void * varg )
{
  char const * str = (char const *) varg;
  fsl_int_t ret = 0;
  int rc = 0;
  char ch = 0;
  char ch2 = 0;
  char xbuf[4];
  int decoded;
  if( ! str ) return 0;
  ch = *str;
  while( ch )
  while( 0==rc && ch ){
  {
    if( ch == '%' )
    if( ch == '%' ){
    {
      ch = *(++str);
      ch2 = *(++str);
      if( isxdigit((int)ch) &&
          isxdigit((int)ch2) )
      {
        decoded = (hexchar_to_int( ch ) * 16)
          + hexchar_to_int( ch2 );
        xbuf[0] = (char)decoded;
        xbuf[1] = 0;
        ret += pf( pfArg, xbuf, 1 );
        rc = pf( pfArg, xbuf, 1 );
        ch = *(++str);
        continue;
      }
      else
      }else{
      {
        xbuf[0] = '%';
        xbuf[1] = ch;
        xbuf[2] = ch2;
        xbuf[3] = 0;
        ret += pf( pfArg, xbuf, 3 );
        rc = pf( pfArg, xbuf, 3 );
        ch = *(++str);
        continue;
      }
    }
    else if( ch == '+' )
    }else if( ch == '+' ){
    {
      xbuf[0] = ' ';
      xbuf[1] = 0;
      ret += pf( pfArg, xbuf, 1 );
      rc = pf( pfArg, xbuf, 1 );
      ch = *(++str);
      continue;
    }
    xbuf[0] = ch;
    xbuf[1] = 0;
    ret += pf( pfArg, xbuf, 1 );
    rc = pf( pfArg, xbuf, 1 );
    ch = *(++str);
  }
  return ret;
  return rc;
}

#endif /* !FSLPRINTF_OMIT_HTML */


#if !FSLPRINTF_OMIT_SQL
/**
   Quotes the (char *) varg as an SQL string 'should'
   be quoted. The exact type of the conversion
   is specified by xtype, which must be one of
   etSQLESCAPE, etSQLESCAPE2, or etSQLESCAPE3.

   Search this file for those constants to find
   the associated documentation.
*/
static fsl_int_t spech_sqlstring_main( int xtype,
static int spech_sqlstring_main( int xtype, fsl_output_f pf,
                                       fsl_appendf_f pf,
                                       void * pfArg,
                                 void * pfArg, unsigned int pfLen,
                                       unsigned int pfLen,
                                       void * varg )
                                 void * varg ){
{
  unsigned int i, n;
  int j, ch, isnull;
  int needQuote;
  char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
  char const * escarg = (char const *) varg;
  char * bufpt = NULL;
  fsl_int_t ret;
  int rc;
  isnull = escarg==0;
  if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  for(i=n=0; (i<pfLen) && ((ch=escarg[i])!=0); ++i){
    if( ch==q ) ++n;
  }
  needQuote = !isnull && xtype==etSQLESCAPE2;
  n += i + 1 + needQuote*2;
  /* FIXME: use a static buffer here instead of malloc()! Shame on you! */
  bufpt = (char *)fsl_malloc( n );
  if( ! bufpt ) return -1;
  if( ! bufpt ) return FSL_RC_OOM;
  j = 0;
  if( needQuote ) bufpt[j++] = q;
  for(i=0; (ch=escarg[i])!=0; i++){
    bufpt[j++] = ch;
    if( ch==q ) bufpt[j++] = ch;
  }
  if( needQuote ) bufpt[j++] = q;
  bufpt[j] = 0;
  ret = pf( pfArg, bufpt, j );
  rc = pf( pfArg, bufpt, j );
  fsl_free( bufpt );
  return ret;
  return rc;
}

static fsl_int_t spech_sqlstring1( fsl_appendf_f pf,
static int spech_sqlstring1( fsl_output_f pf, void * pfArg,
                                   void * pfArg,
                                   unsigned int pfLen,
                             unsigned int pfLen, void * varg ){
                                   void * varg )
{
  return spech_sqlstring_main( etSQLESCAPE, pf, pfArg, pfLen, varg );
}

static fsl_int_t spech_sqlstring2( fsl_appendf_f pf,
static int spech_sqlstring2( fsl_output_f pf, void * pfArg,
                                   void * pfArg,
                                   unsigned int pfLen,
                             unsigned int pfLen, void * varg ){
                                   void * varg )
{
  return spech_sqlstring_main( etSQLESCAPE2, pf, pfArg, pfLen, varg );
}

static fsl_int_t spech_sqlstring3( fsl_appendf_f pf,
static int spech_sqlstring3( fsl_output_f pf, void * pfArg,
                                   void * pfArg,
                                   unsigned int pfLen,
                             unsigned int pfLen, void * varg ){
                                   void * varg )
{
  return spech_sqlstring_main( etSQLESCAPE3, pf, pfArg, pfLen, varg );
}

#endif /* !FSLPRINTF_OMIT_SQL */

#if 0
static fsl_int_t spech_blob2( fsl_appendf_f pf,
                              void * pfArg,
                              unsigned int pfLen,
                              void * varg )
{
  fsl_buffer * b = (fsl_buffer *)varg;
  return spech_sqlstring_main( etSQLESCAPE3, pf, pfArg, pfLen, varg );
}
#endif

#if FSLPRINTF_ENABLE_JSON
/* TODO? Move these UTF8 bits into the public API? */
/*
** This lookup table is used to help decode the first byte of
** a multi-byte UTF8 character.
**
** Taken from sqlite3:
1913
1914
1915
1916
1917
1918
1919
1920
1921


1922
1923
1924
1925

1926
1927
1928
1929
1930
1931
1932
1933


1934
1935
1936
1937
1938
1939
1940
1941

1942

1943
1944
1945
1946
1947
1948
1949
2323
2324
2325
2326
2327
2328
2329


2330
2331

2332


2333
2334
2335
2336
2337
2338
2339


2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350

2351
2352
2353
2354
2355
2356
2357
2358







-
-
+
+
-

-
-
+






-
-
+
+








+
-
+







  bool escapeSmallUtf8;
};

/**
   fsl_appendf_spec_handler for etJSONSTR. It assumes that varg is a
   SpechJson struct instance.
*/
static fsl_int_t spech_json( fsl_appendf_f pf, void * pfArg,
                             unsigned int pfLen, void * varg )
static int spech_json( fsl_output_f pf, void * pfArg,
                       unsigned int pfLen, void * varg ){
{
  struct SpechJson const * state = (struct SpechJson *)varg;
  fsl_int_t pfRcTmp = 0;
  fsl_int_t pfRc = 0;
  int pfRc = 0;
  const unsigned char *z = (const unsigned char *)state->z;
  const unsigned char *zEnd = z + pfLen;
  const unsigned char * zNext = 0;
  unsigned int c;
  unsigned char c1;

#define out(X,N) pfRcTmp=pf(pfArg, (char const *)(X), N); \
  if(pfRcTmp<0) return pfRcTmp; pfRc+=pfRcTmp
#define out(X,N) pfRc=pf(pfArg, (char const *)(X), N); \
  if(0!=pfRc) return pfRc
#define outc c1 = (unsigned char)c; out(&c1,1)
  if(!z){
    out("null",4);
    return pfRc;
  }    
  if(state->addQuotes){
    out("\"", 1);
  }
  for( ; 0==pfRc && (z < zEnd)
  for( ; (z < zEnd) && (c=fsl_utf8_read_char(z, zEnd, &zNext));
         && (c=fsl_utf8_read_char(z, zEnd, &zNext));
       z = zNext ){
    if( c=='\\' || c=='"' ){
      out("\\", 1);
      outc;
    }else if( c<' ' ){
      out("\\",1);
      if( c=='\n' ){
2006
2007
2008
2009
2010
2011
2012
















































2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023



2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041






2042
2043
2044
2045
2046
2047
2048

2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059





2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072

2073
2074
2075
2076
2077
2078
2079
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477



2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492






2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504

2505
2506
2507
2508
2509
2510
2511





2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523


2524
2525
2526

2527
2528
2529
2530
2531
2532
2533
2534







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








-
-
-
+
+
+












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






-
+






-
-
-
-
-
+
+
+
+
+







-
-



-
+







   is an alias for strlen().
*/
static int StrNLen32(const char *z, int N){
  int n = 0;
  while( (N-- != 0) && *(z++)!=0 ){ n++; }
  return n;
}

#if 0
/**
   Given the first byte of an assumed-to-be well-formed UTF8
   character, returns the length of that character. Returns 0 if the
   character appears to be an invalid UTF8 character, else returns its
   length, in bytes (1-4). Note that a NUL byte is a valid length-1
   character.
*/
static int utf8__char_length( unsigned char const * const c ){
  switch(0xF0 & *c) {
    case 0xF0: return (c[1]&0x80 && c[2]&0x80 && c[3]&0x80) ? 4 : 0;
    case 0xE0: return (c[1]&0x80 && c[2]&0x80) ? 3 : 0;
    case 0xC0: return (c[1]&0x80) ? 2 : 0;
    case 0x80: return 0;
    default: return 1;
      /* See also: https://stackoverflow.com/questions/4884656/utf-8-encoding-size */
  }
}
#endif

/**
   Internal helper for %#W.Ps format.
*/
static void appendf__utf8_altform(char const * z, int * pLength,
                                  int * pPrecision, int * pWidth){
  /* Treat %#W.Ps as a width/precision limit of W resp. P UTF8
     characters instead of bytes. */
  int pC = 0/*precision, chars*/, pB = 0/*precision, bytes*/,
    wC = 0/*width, chars*/, wB = 0/*width, bytes*/;
  char const * const zEnd = z + *pLength;
  int lc;
  while( z < zEnd ){
    switch(0xF0 & *z) {
      case 0xF0: lc = (z[1]&0x80 && z[2]&0x80 && z[3]&0x80) ? 4 : 0; break;
      case 0xE0: lc = (z[1]&0x80 && z[2]&0x80) ? 3 : 0; break;
      case 0xC0: lc = (z[1]&0x80) ? 2 : 0; break;
      case 0x80: lc = 0; break;
      default: lc = 1; break;
    }
    if(!lc) break;
    else if(wC<*pWidth && (*pPrecision<=0 || pC<*pPrecision)){ ++wC; wB+=lc;}
    if(pC<*pPrecision){ ++pC; pB+=lc;}
    z+=lc;
  }
  if(*pPrecision>0) *pLength = pB;
  if(*pWidth>0) *pWidth = *pWidth - wC + wB;
}

/*
  The root printf program.  All variations call this core.  It
  implements most of the common printf behaviours plus (optionally)
  some extended ones.

  INPUTS:

  pfAppend : The is a fsl_appendf_f function which is responsible
  for accumulating the output. If pfAppend returns a negative integer
  then processing stops immediately.
  pfAppend : The is a fsl_output_f function which is responsible for
  accumulating the output. If pfAppend returns non-0 then processing
  stops immediately.

  pfAppendArg : is ignored by this function but passed as the first
  argument to pfAppend. pfAppend will presumably use it as a data
  store for accumulating its string.

  fmt : This is the format string, as in the usual printf().

  ap : This is a pointer to a list of arguments.  Same as in
  vprintf() and friends.

  OUTPUTS:

  The return value is the total number value from all calls to
  pfAppend.

  Note that the order in which automatic variables are declared below
  seems to make a big difference in determining how fast this beast
  will run.
  The return value is 0 on success, non-0 on error. Historically it
  returned the total number bytes reported appended by pfAppend, but
  those semantics (A) are only very, very rarely useful and (B) they
  make sensibly reporting errors via the generic callback interface
  next to impossible. e.g. the callback may encounter I/O or allocation
  errors.

  Much of this code dates back to the early 1980's, supposedly.

  Known change history (most historic info has been lost):

  10 Feb 2008 by Stephan Beal: refactored to remove the 'useExtended'
  flag (which is now always on). Added the fsl_appendf_f typedef to
  flag (which is now always on). Added the fsl_output_f typedef to
  make this function generic enough to drop into other source trees
  without much work.

  31 Oct 2008 by Stephan Beal: refactored the et_info lookup to be
  constant-time instead of linear.
*/
fsl_int_t fsl_appendfv(fsl_appendf_f pfAppend, /* Accumulate results here */
                       void * pfAppendArg,     /* Passed as first arg to pfAppend. */
                       const char *fmt,        /* Format string */
                       va_list ap              /* arguments */
                       ){
int fsl_appendfv(fsl_output_f pfAppend, /* Accumulate results here */
                 void * pfAppendArg,     /* Passed as first arg to pfAppend. */
                 const char *fmt,        /* Format string */
                 va_list ap              /* arguments */
                 ){
  /**
     HISTORIC NOTE (author and year unknown):

     Note that the order in which automatic variables are declared below
     seems to make a big difference in determining how fast this beast
     will run.
  */

  fsl_int_t outCount = 0;          /* accumulated output count */
  int pfrc = 0;              /* result from calling pfAppend */
  int c;                     /* Next character in the format string */
  char *bufpt = 0;           /* Pointer to the conversion buffer */
  int precision;             /* Precision of the current field */
  int precision = 0;         /* Precision of the current field */
  int length;                /* Length of the field */
  int idx;                   /* A general purpose loop counter */
  int width;                 /* Width of the current field */
  etByte flag_leftjustify;   /* True if "-" flag is present */
  etByte flag_plussign;      /* True if "+" flag is present */
  etByte flag_blanksign;     /* True if " " flag is present */
  etByte flag_alternateform; /* True if "#" flag is present */
2120
2121
2122
2123
2124
2125
2126
2127
2128


2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140

2141
2142
2143
2144
2145
2146
2147
2575
2576
2577
2578
2579
2580
2581


2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603







-
-
+
+












+







  }
#  define FSLPRINTF_CHARARRAY_FREE(V) if(V!=V##2) fsl_free(V)
#endif

  /* FSLPRINTF_RETURN, FSLPRINTF_CHECKERR, and FSLPRINTF_SPACES
     are internal helpers.
  */
#define FSLPRINTF_RETURN if( zExtra ) fsl_free(zExtra); return outCount
#define FSLPRINTF_CHECKERR if( pfrc<0 ) { FSLPRINTF_RETURN; } else outCount += pfrc
#define FSLPRINTF_RETURN if( zExtra ) fsl_free(zExtra); return pfrc
#define FSLPRINTF_CHECKERR if( 0!=pfrc ) { FSLPRINTF_RETURN; } (void)0
#define FSLPRINTF_SPACES(N)                     \
  {                                             \
    FSLPRINTF_CHARARRAY(zSpaces,N);             \
    memset( zSpaces,' ',N);                     \
    pfrc = pfAppend(pfAppendArg, zSpaces, N);   \
    FSLPRINTF_CHARARRAY_FREE(zSpaces);          \
    FSLPRINTF_CHECKERR;                \
  } (void)0

  length = 0;
  bufpt = 0;
  for(; (c=(*fmt))!=0; ++fmt){
    assert(0==pfrc);
    if( c!='%' ){
      int amt;
      bufpt = (char *)fmt;
      amt = 1;
      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
      pfrc = pfAppend( pfAppendArg, bufpt, amt);
      FSLPRINTF_CHECKERR;
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2651
2652
2653
2654
2655
2656
2657

2658
2659
2660
2661
2662
2663
2664







-







      c = *++fmt;
      if( c=='*' ){
        precision = va_arg(ap,int);
        c = *++fmt;
        if( precision<0 ){
          precision = precision >= -2147483647 ? -precision : -1;
        }

      }else{
        unsigned px = 0;
        while( c>='0' && c<='9' ){
          px = px*10 + c - '0';
          c = *++fmt;
        }
        precision = px & 0x7fffffff;
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2690
2691
2692
2693
2694
2695
2696

2697
2698
2699
2700
2701
2702
2703







-







    if( infop ) xtype = infop->type;
#undef FMTINFO
#undef FMTNDX
    zExtra = 0;
    if( (!infop) || (!infop->type) ){
      FSLPRINTF_RETURN;
    }


    /* Limit the precision to prevent overflowing buf[] during conversion */
    if( precision>FSLPRINTF_BUF_SIZE-40 && (infop->flags & FLAG_STRING)==0 ){
      precision = FSLPRINTF_BUF_SIZE-40;
    }

    /*
2307
2308
2309
2310
2311
2312
2313
2314

2315
2316

2317
2318
2319
2320
2321
2322
2323
2324
2761
2762
2763
2764
2765
2766
2767

2768


2769

2770
2771
2772
2773
2774
2775
2776







-
+
-
-
+
-







            x = 0;
          }
          buf[FSLPRINTF_BUF_SIZE-3] = zOrd[x*2];
          buf[FSLPRINTF_BUF_SIZE-2] = zOrd[x*2+1];
          bufpt -= 2;
        }
        {
          const char *cset;
          int const base = infop->base;
          int base;
          cset = &aDigits[infop->charset];
          const char *cset = &aDigits[infop->charset];
          base = infop->base;
          do{                                           /* Convert to ascii */
            *(--bufpt) = cset[longvalue%base];
            longvalue = longvalue/base;
          }while( longvalue>0 );
        }
        length = &buf[FSLPRINTF_BUF_SIZE-1]-bufpt;
        while( precision>length ){
2401
2402
2403
2404
2405
2406
2407
2408

2409
2410
2411
2412
2413
2414
2415
2853
2854
2855
2856
2857
2858
2859

2860
2861
2862
2863
2864
2865
2866
2867







-
+







            }else if( prefix=='+' ){
              static char Inf[5] = {'+','I','n','f','\0'};
              bufpt = Inf;
            }else{
              static char Inf[4] = {'I','n','f','\0'};
              bufpt = Inf;
            }
            length = strlen(bufpt);
            length = (int)strlen(bufpt);
            break;
          }
        }
        bufpt = buf;
        /*
          If the field type is etGENERIC, then convert to either etEXP
          or etFLOAT, as appropriate.
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2959
2960
2961
2962
2963
2964
2965






2966
2967
2968
2969
2970
2971
2972







-
-
-
-
-
-







          }
          i = prefix!=0;
          while( nPad-- ) bufpt[i++] = '0';
          length = width;
        }
#endif /* !FSLPRINTF_OMIT_FLOATING_POINT */
        break;
#if !FSLPRINTF_OMIT_SIZE
      case etSIZE:
        *(va_arg(ap,int*)) = outCount;
        length = width = 0;
        break;
#endif
      case etPERCENT:
        buf[0] = '%';
        bufpt = buf;
        length = 1;
        break;
      case etCHARLIT:
      case etCHARX:
2560
2561
2562
2563
2564
2565
2566
2567
2568











2569
2570
2571
2572
2573
2574

2575
2576
2577
2578
2579
2580
2581













2582
2583
2584
2585
2586
2587
2588
3006
3007
3008
3009
3010
3011
3012


3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028

3029

3030





3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050







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





-
+
-

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







             has the '!' flag_altform2, which indicates that it
             should be for a URL, and thus longer than the default.
             We are only roughly approximating that behaviour here. */;
        /* Fall through */
      }
      case etSTRING: {
        bufpt = va_arg(ap,char*);
        length = bufpt ? strlen(bufpt) : 0;
        if( precision>=0 && precision<length ) length = precision;
        length = bufpt
          ? StrNLen32(bufpt,
                      (precision>0 && flag_alternateform)
                      ? precision*4/*max bytes per char*/
                      : (precision ? 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.
           block). This means, though, that %-#z does not work. */
        */
        bufpt = va_arg(ap,char*);
        length = bufpt ? strlen(bufpt) : 0;
        pfrc = spech_dynstring( pfAppend, pfAppendArg,
                                (precision>=0 && precision<length)
                                ? precision : length,
                                bufpt );
        length = bufpt
          ? StrNLen32(bufpt,
                      (precision>0 && flag_alternateform)
                      ? precision*4/*max bytes per char*/
                      : (precision ? 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,
                                length, bufpt );
        bufpt = NULL;
        FSLPRINTF_CHECKERR;
        length = 0;
        break;
      }
      case etBLOB: {
        /* int const limit = flag_alternateform ? va_arg(ap, int) : -1; */
2611
2612
2613
2614
2615
2616
2617
2618



2619
2620
2621
2622
2623
2624
2625
3073
3074
3075
3076
3077
3078
3079

3080
3081
3082
3083
3084
3085
3086
3087
3088
3089







-
+
+
+







        if( precision>=0 && precision<length ) length = precision;
        break;
      }
#if FSLPRINTF_ENABLE_JSON
      case etJSONSTR: {
        struct SpechJson state;
        bufpt = va_arg(ap,char *);
        length = bufpt ? (int)fsl_strlen(bufpt) : 0;
        length = bufpt
          ? (precision>=0 ? precision : (int)fsl_strlen(bufpt))
          : 0;
        state.z = bufpt;
        state.addQuotes = flag_altform2 ? true : false;
        state.escapeSmallUtf8 = flag_alternateform ? true : false;
        pfrc = spech_json( pfAppend, pfAppendArg, (unsigned)length, &state );
        bufpt = NULL;
        FSLPRINTF_CHECKERR;
        length = 0;
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738



2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758

2759
2760

2761
2762
2763
2764

2765
2766
2767
2768
2769
2770
2771
2772






2773
2774
2775
2776
2777
2778
2779
2780
3193
3194
3195
3196
3197
3198
3199



3200
3201
3202
3203
3204
3205
3206
3207
3208
3209













3210
3211

3212
3213
3214
3215

3216








3217
3218
3219
3220
3221
3222

3223
3224
3225
3226
3227
3228
3229







-
-
-
+
+
+







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

-
+



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







#undef FSLPRINTF_RETURN
#undef FSLPRINTF_OMIT_FLOATING_POINT
#undef FSLPRINTF_OMIT_SIZE
#undef FSLPRINTF_OMIT_SQL
#undef FSLPRINTF_BUF_SIZE
#undef FSLPRINTF_OMIT_HTML

fsl_int_t fsl_appendf(fsl_appendf_f pfAppend, void * pfAppendArg,
                      const char *fmt, ... ){
  fsl_int_t ret;
int fsl_appendf(fsl_output_f pfAppend, void * pfAppendArg,
                const char *fmt, ... ){
  int ret;
  va_list vargs;
  va_start( vargs, fmt );
  ret = fsl_appendfv( pfAppend, pfAppendArg, fmt, vargs );
  va_end(vargs);
  return ret;
}


/*
   fsl_appendf_f() impl which requires that state be-a writable
   (FILE*).
*/
fsl_int_t fsl_appendf_f_FILE( void * state,
                              char const * s, fsl_int_t n ){
  if( !state ) return -1;
  else return (1==fwrite( s, (size_t)n, 1, (FILE *)state ))
    ? n : -2;
}

fsl_int_t fsl_fprintfv( FILE * fp, char const * fmt, va_list args ){
int fsl_fprintfv( FILE * fp, char const * fmt, va_list args ){
  return (fp && fmt)
    ? fsl_appendfv( fsl_appendf_f_FILE, fp, fmt, args )
    ? fsl_appendfv( fsl_output_f_FILE, fp, fmt, args )
    :  -1;
}

fsl_int_t fsl_fprintf( FILE * fp, char const * fmt, ... ){
int fsl_fprintf( FILE * fp, char const * fmt, ... ){
  if(!fp || !fmt) return -1;
  else {
    fsl_int_t ret;
    va_list vargs;
    va_start( vargs, fmt );
    ret = fsl_appendfv( fsl_appendf_f_FILE, fp, fmt, vargs );
    va_end(vargs);
    return ret;
  int ret;
  va_list vargs;
  va_start( vargs, fmt );
  ret = fsl_appendfv( fsl_output_f_FILE, fp, fmt, vargs );
  va_end(vargs);
  return ret;
  }
}

char * fsl_mprintfv( char const * fmt, va_list vargs ){
  if( !fmt ) return 0;
  else if(!*fmt) return fsl_strndup("",0);
  else{
    fsl_buffer buf = fsl_buffer_empty;
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815




2816
2817
2818
2819
2820
2821
2822

2823
2824
2825

2826
2827
2828
2829


2830
2831
2832


2833
2834
2835
2836
2837
2838
2839

2840
2841
2842
2843
2844
2845
2846
2847
2848


2849
2850
2851
2852
2853
2854


2855
2856
2857
2858
2859
2860
2861
3255
3256
3257
3258
3259
3260
3261



3262
3263
3264
3265
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
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312







-
-
-
+
+
+
+






-
+


-
+


-
-
+
+

-
-
+
+






-
+



-



-
-
+
+






+
+







  /** Current output position in this->dest. */
  fsl_size_t pos;
  /** Length of this->dest. */
  fsl_size_t len;
};
typedef struct fsl_snp_state fsl_snp_state;

static fsl_int_t fsl_appendf_f_snprintf( void * arg,
                                         char const * data,
                                         fsl_int_t n ){
static int fsl_output_f_snprintf( void * arg,
                                  void const * data_,
                                  fsl_size_t n ){
  char const * data = (char const *)data_;
  fsl_snp_state * st = (fsl_snp_state*) arg;
  assert(n>=0);
  if(n==0 || (st->pos >= st->len)) return 0;
  else if((n + st->pos) > st->len){
    n = st->len - st->pos;
  }
  memcpy(st->dest + st->pos, data, (fsl_size_t)n);
  memcpy(st->dest + st->pos, data, n);
  st->pos += n;
  assert(st->pos <= st->len);
  return n;
  return 0;
}

fsl_int_t fsl_snprintfv( char * dest, fsl_size_t n,
                         char const * fmt, va_list args){
int fsl_snprintfv( char * dest, fsl_size_t n,
                   char const * fmt, va_list args){
  fsl_snp_state st = {NULL,0,0};
  fsl_int_t rc;
  if(!dest || !fmt) return -1;
  int rc = 0;
  if(!dest || !fmt) return FSL_RC_MISUSE;
  else if(!n || !*fmt){
    if(dest) *dest = 0;
    return 0;
  }
  st.len = n;
  st.dest = dest;
  rc = fsl_appendfv( fsl_appendf_f_snprintf, &st, fmt, args );
  rc = fsl_appendfv( fsl_output_f_snprintf, &st, fmt, args );
  if(st.pos < st.len){
    dest[st.pos] = 0;
  }
  assert( rc <= (fsl_int_t)n );
  return rc;
}

fsl_int_t fsl_snprintf( char * dest, fsl_size_t n, char const * fmt, ... ){
  fsl_int_t rc;
int fsl_snprintf( char * dest, fsl_size_t n, char const * fmt, ... ){
  int rc = 0;
  va_list vargs;
  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 */
/* -*- 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

3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371


3372
3373
3374
3375
3376
3377

3378
3379
3380


3381
3382
3383

3384
3385
3386
3387
3388
3389
3390
3765
3766
3767
3768
3769
3770
3771



















































3772
3773






3774



3775
3776
3777


3778
3779
3780
3781
3782
3783
3784
3785







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

-
-
+







      b->used += len;
      b->mem[b->used] = 0;
    }
    return rc;
  }
}

/*
   Internal helper for implementing fsl_buffer_appendf()
*/
typedef struct BufferAppender {
  fsl_buffer * b;
  /*
     Result code of the appending process.
  */
  int rc;
} BufferAppender;

/*
   fsl_appendf_f() impl which requires arg to be a (fsl_buffer*).
   It appends the data to arg. Returns the number of bytes written
   on success, a negative value on error. Always NUL-terminates the
   buffer on success.
*/
static fsl_int_t fsl_appendf_f_buffer( void * arg,
                                       char const * data, fsl_int_t n ){
  BufferAppender * ba = (BufferAppender*)arg;
  fsl_buffer * sb = ba->b;
  if( !sb || (n<0) ) return -1;
  else if( ! n ) return 0;
  else{
    fsl_int_t rc;
    fsl_size_t npos = sb->used + n;
    if( npos >= sb->capacity ){
      const size_t asz = npos ? ((4 * npos / 3) + 1) : 16;
      if( asz < npos ) {
        ba->rc = FSL_RC_RANGE;
        return -1; /* overflow */
      }
      else{
        rc = fsl_buffer_reserve( sb, asz );
        if(rc) {
          ba->rc = FSL_RC_OOM;
          return -1;
        }
      }
    }
    rc = 0;
    for( ; rc < n; ++rc, ++sb->used ){
      sb->mem[sb->used] = data[rc];
    }
    sb->mem[sb->used] = 0;
    return rc;
  }
}

int fsl_buffer_appendfv( fsl_buffer * b,
                         char const * fmt, va_list args){
int fsl_buffer_appendfv( fsl_buffer * const b, char const * fmt,
                         va_list args){
  if(!b || !fmt) return FSL_RC_MISUSE;
  else{
    BufferAppender ba;
    ba.b = b;
    ba.rc = 0;
    fsl_appendfv( fsl_appendf_f_buffer, &ba, fmt, args );
  return fsl_appendfv( fsl_output_f_buffer, b, fmt, args );
    return ba.rc;
  }
}
}



int fsl_buffer_appendf( fsl_buffer * b,
int fsl_buffer_appendf( fsl_buffer * const b,
                        char const * fmt, ... ){
  if(!b || !fmt) return FSL_RC_MISUSE;
  else{
    int rc;
    va_list args;
    va_start(args,fmt);
    rc = fsl_buffer_appendfv( b, fmt, args );
3987
3988
3989
3990
3991
3992
3993
























3994
3995
3996
3997
3998
3999
4000
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419







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







  for(fsl_id_t e = fsl_id_bag_first(bag);
      !rc && e; e = fsl_id_bag_next(bag, e)){
    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,
                                  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];
    switch( c ){
      case '\r':  c = 'r';
      case '[':
      case ']':
      case '$':
      case '"':
      case '\\':
        if((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
/* end of file buffer.c */
/* start of file cache.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
5815
5816
5817
5818
5819
5820
5821
5822

5823
5824
5825
5826
5827
5828
5829
6234
6235
6236
6237
6238
6239
6240

6241
6242
6243
6244
6245
6246
6247
6248







-
+







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

int fsl_ckout_manage( fsl_cx * f, fsl_ckout_manage_opt * opt_ ){
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_
8123
8124
8125
8126
8127
8128
8129















































































8130
8131
8132
8133
8134
8135
8136
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634







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







    rc = fsl_filename_to_vfile_ids(f, vid, dest,
                                   fsl_buffer_cstr(canon),
                                   changedOnly);
  }
  fsl_cx_scratchpad_yield(f, canon);
  return rc;
}

int fsl_ckout_file_content(fsl_cx * const f, bool relativeToCwd, char const * zName,
                           fsl_buffer * const dest ){
  int rc;
  fsl_buffer * fname;
  if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
  fname = fsl_cx_scratchpad(f);
  rc = fsl_file_canonical_name2( relativeToCwd
                                 ? NULL
                                 : fsl_cx_ckout_dir_name(f, NULL),
                                 zName, fname, 1 );
  if(!rc){
    assert(fname->used);
    if('/'==fname->mem[fname->used-1]){
      rc = fsl_cx_err_set(f, FSL_RC_MISUSE,"Filename may not have a trailing slash.");
      /* If we don't do this, we might end up reading a directory entry in raw form.
         Well, we still might. */
    }else{
      fsl_fstat fstat = fsl_fstat_empty;
      const char * zCanon = fsl_buffer_cstr(fname);
      rc = fsl_stat(zCanon, &fstat, true);
      if(rc){
        rc = fsl_cx_err_set(f, rc, "Cannot stat file; %b", fname);
      }else if(FSL_FSTAT_TYPE_FILE!=fstat.type){
        rc = fsl_cx_err_set(f, FSL_RC_TYPE,
                            "Not a regular file file; %b", fname);
      }else{
        dest->used =0;
        rc = fsl_buffer_fill_from_filename(dest, fsl_buffer_cstr(fname));
        if(rc){
          rc = fsl_cx_err_set(f, rc, "%s error reading file; %b",
                              fsl_rc_cstr(rc), fname);
        }
      }
    }
  }
  fsl_cx_scratchpad_yield(f, fname);
  return rc;
}

int fsl_card_F_ckout_mtime(fsl_cx * const f,
                           fsl_id_t vid,
                           fsl_card_F const * fc,
                           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){
    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",
                                    fc->name);
  }
  else if(!fid){
    return fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Could not resolve filename: %s",
                          fc->name);
  }
  if(localMtime){
    rc = fsl_cx_stat(f, 0, fc->name, &fst);
    if(rc){
      return fsl_cx_err_set(f, rc, "Could not stat() file: %s",
                            fc->name);
    }
    *localMtime = fst.mtime;
  }
  if(repoMtime){
    rc = fsl_mtime_of_manifest_file(f, vid, fid, repoMtime);
  }
  return rc;
}


#undef MARKER
/* end of file checkout.c */
/* start of file cli.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
8165
8166
8167
8168
8169
8170
8171
8172
8173



8174
8175
8176
8177
8178
8179
8180
8663
8664
8665
8666
8667
8668
8669


8670
8671
8672
8673
8674
8675
8676
8677
8678
8679







-
-
+
+
+







    "."/*checkoutDir*/,      \
    0/*verbose*/,            \
    false/*dryRun*/ \
  }, \
  {/*transient*/      \
    NULL/*repoDb*/,      \
    NULL/*userArg*/, \
    0/*helpRequested*/                   \
  },                                                            \
    0/*helpRequested*/, \
    false/*versionRequested*/\
  },                    \
  {/*config*/      \
    -1/*traceSql*/,      \
    fsl_outputer_empty_m      \
  },                          \
  fsl_error_empty_m/*err*/  \
}

8352
8353
8354
8355
8356
8357
8358


8359
8360
8361
8362

8363
8364

8365
8366

8367
8368

8369
8370
8371
8372

8373
8374

8375
8376
8377
8378
8379
8380
8381
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862

8863
8864

8865
8866

8867
8868

8869
8870
8871
8872

8873
8874

8875
8876
8877
8878
8879
8880
8881
8882







+
+



-
+

-
+

-
+

-
+



-
+

-
+







  return FCLI_RC_FLAG_AGAIN;
}

static const fcli_cliflag FCliFlagsGlobal[] = {
  FCLI_FLAG_BOOL_X("?","help",NULL,
                   fcli_flag_f_help,
                   "Show app help. Also triggered if the first non-flag is \"help\"."),
  FCLI_FLAG_BOOL(0,"lib-version", &fcli.transient.versionRequested,
                 "Show app version number."),
  FCLI_FLAG("R","repo","REPO-FILE",&fcli.transient.repoDbArg,
            "Selects a specific repository database, ignoring the one "
            "used by the current directory's checkout (if any)."),
  FCLI_FLAG_BOOL("D","dry-run",&fcli.clientFlags.dryRun,
  FCLI_FLAG_BOOL(NULL,"dry-run",&fcli.clientFlags.dryRun,
                 "Enable dry-run mode (not supported by all apps)."),
  FCLI_FLAG("U","user","username",&fcli.transient.userArg,
  FCLI_FLAG(NULL,"user","username",&fcli.transient.userArg,
            "Sets the name of the fossil user name for this session."),
  FCLI_FLAG_BOOL_X("C", "no-checkout",NULL,fcli_flag_f_nocheckoutDir,
  FCLI_FLAG_BOOL_X(NULL, "no-checkout",NULL,fcli_flag_f_nocheckoutDir,
                   "Disable automatic attempt to open checkout."),
  FCLI_FLAG(0,"checkout-dir","DIRECTORY", &fcli.clientFlags.checkoutDir,
  FCLI_FLAG(NULL,"checkout-dir","DIRECTORY", &fcli.clientFlags.checkoutDir,
            "Open the given directory as a checkout, instead of the current dir."),
  FCLI_FLAG_BOOL_X("V","verbose",NULL,fcli_flag_f_verbose,
              "Increases the verbosity level by 1. May be used multiple times."),
  FCLI_FLAG_BOOL(0,"trace-sql",&TempFlags.traceSql,
  FCLI_FLAG_BOOL(NULL,"trace-sql",&TempFlags.traceSql,
                 "Enable SQL tracing."),
  FCLI_FLAG_BOOL(0,"timer",&TempFlags.doTimer,
  FCLI_FLAG_BOOL(NULL,"timer",&TempFlags.doTimer,
                 "At the end of successful app execution, output how long it took "
                 "from the call to fcli_setup() until the end of main()."),
  fcli_cliflag_empty_m
};

void fcli_cliflag_help(fcli_cliflag const *defs){
  fcli_cliflag const * f;
8829
8830
8831
8832
8833
8834
8835
8836

8837
8838
8839
8840
8841
8842
8843
9330
9331
9332
9333
9334
9335
9336

9337
9338
9339
9340
9341
9342
9343
9344







-
+







  init.config.sqlPrint = 1;
  if(fcli.config.outputer.out){
    init.output = fcli.config.outputer;
    fcli.config.outputer = fsl_outputer_empty
      /* To avoid any confusion about ownership */;
  }else{
    init.output = fsl_outputer_FILE;
    init.output.state.state = stdout;
    init.output.state = stdout;
  }
  if(fcli.config.traceSql>0 || TempFlags.traceSql){
    init.config.traceSql = fcli.config.traceSql;
  }
    
  rc = fsl_cx_init( &f, &init );
  fcli.f = f;
8888
8889
8890
8891
8892
8893
8894






8895
8896
8897
8898
8899
8900
8901
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408







+
+
+
+
+
+







  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;
  }else{
    rc = fcli_process_flags(flags);
    if(rc) assert(fcli__error->msg.used);
    if(!rc){
      rc = fcli_setup_common2();
    }
  }
8912
8913
8914
8915
8916
8917
8918
8919

8920
8921
8922
8923
8924



8925
8926
8927
8928
8929
8930
8931
9419
9420
9421
9422
9423
9424
9425

9426
9427
9428



9429
9430
9431
9432
9433
9434
9435
9436
9437
9438







-
+


-
-
-
+
+
+







    //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;
    }else{
      if( fcli_flag2("C", "no-checkout", NULL) ){
      if( fcli_flag2(NULL, "no-checkout", NULL) ){
        fcli.clientFlags.checkoutDir = NULL;
      }
      fcli_flag2("U","user", &fcli.transient.userArg);
      fcli.config.traceSql =  fcli_flag2("S","trace-sql", NULL);
      fcli.clientFlags.dryRun = fcli_flag2("D","dry-run", NULL);
      fcli_flag2(NULL,"user", &fcli.transient.userArg);
      fcli.config.traceSql =  fcli_flag2(NULL,"trace-sql", NULL);
      fcli.clientFlags.dryRun = fcli_flag2(NULL,"dry-run", NULL);
      fcli_flag2("R", "repo", &fcli.transient.repoDbArg);
      rc = fcli_setup_common2();
    }
  }
  return rc;
}

9325
9326
9327
9328
9329
9330
9331





















9332
9333
9334
9335
9336
9337
9338
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866







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







      case (int)'\\':
        return zEnd+1;
      default: break;
    }
  }
  return zEnd;
}

void fcli_diff_colors(fsl_diff_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";
          zEdit = "\x1b[36m";
          zDel = "\x1b[31m";
          zReset = "\x1b[0m";
          break;
    case FCLI_DIFF_COLORS_NONE:
    default: break;
  }
  tgt->ansiColor.insertion = zIns;
  tgt->ansiColor.edit = zEdit;
  tgt->ansiColor.deletion = zDel;
  tgt->ansiColor.reset = zReset;
}

#undef FCLI_V3
#undef fcli_empty_m
#undef fcli__error
#undef MARKER
/* end of file cli.c */
/* start of file content.c */
9480
9481
9482
9483
9484
9485
9486
9487
9488



9489
9490
9491
9492
9493
9494
9495
10008
10009
10010
10011
10012
10013
10014


10015
10016
10017
10018
10019
10020
10021
10022
10023
10024







-
-
+
+
+







    if(!rc) rc = fsl_stmt_step(s1);
    fsl_stmt_cached_yield(s1);
  }
  return rc==FSL_RC_STEP_ROW ? true : false;
}


int fsl_content_get( fsl_cx * f, fsl_id_t rid, fsl_buffer * tgt ){
  fsl_db * db = fsl_cx_db_repo(f);
int fsl_content_get( fsl_cx * const f, fsl_id_t rid,
                     fsl_buffer * const tgt ){
  fsl_db * const db = fsl_cx_db_repo(f);
  if(!tgt) return FSL_RC_MISUSE;
  else if(rid<=0){
    return fsl_cx_err_set(f, FSL_RC_RANGE,
                          "RID %"FSL_ID_T_PFMT" is out of range.",
                          rid);
  }
  else if(!db){
9646
9647
9648
9649
9650
9651
9652
9653


9654
9655
9656
9657
9658
9659
9660
10175
10176
10177
10178
10179
10180
10181

10182
10183
10184
10185
10186
10187
10188
10189
10190







-
+
+







                             : &f->cache.arty.missing,
                             rid);
    }
    return rc;
  }
}

int fsl_content_get_sym( fsl_cx * f, char const * sym, fsl_buffer * tgt ){
int fsl_content_get_sym( fsl_cx * const f, char const * sym,
                         fsl_buffer * const tgt ){
  int rc;
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  fsl_id_t rid = 0;
  if(!f || !sym || !tgt) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  rc = fsl_sym_to_rid(f, sym, FSL_SATYPE_ANY, &rid);
  return rc ? rc : fsl_content_get(f, rid, tgt);
11724
11725
11726
11727
11728
11729
11730





11731
11732
11733
11734
11735
11736
11737
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272







+
+
+
+
+







  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
11755
11756
11757
11758
11759
11760
11761


11762
11763
11764
11765

11766
11767
11768
11769
11770
11771
11772
11773
11774
11775


11776
11777
11778
11779
11780
11781
11782
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311


12312
12313
12314
12315
12316
12317
12318
12319
12320







+
+




+








-
-
+
+







         /sizeof(fsl_cx_empty.scratchpads.buf[0])))
const int StaticAssert_scratchpadsCounts[
     (FSL_CX_NSCRATCH==
      ((int)(sizeof(fsl_cx_empty.scratchpads.used)
             /sizeof(fsl_cx_empty.scratchpads.used[0]))))
     ? 1 : -1
];

#if FSL_ENABLE_SQLITE_REGEXP
/**
   Used for setup and teardown of sqlite3_auto_extension().
*/
static volatile long sg_autoregctr = 0;
#endif

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 *f);
  if(!tgt) return FSL_RC_MISUSE;
  else if(!param){
    if(!paramDefaults.output.state.state){
      paramDefaults.output.state.state = stdout;
    if(!paramDefaults.output.state){
      paramDefaults.output.state = stdout;
    }
    param = &paramDefaults;
  }
  if(*tgt){
    void const * allocStamp = (*tgt)->allocStamp;
    fsl_cx_reset(*tgt, 1) /* just to be safe */;
    f = *tgt;
11814
11815
11816
11817
11818
11819
11820

11821

11822
11823
11824
11825
11826
11827
11828







11829
11830
11831
11832
11833
11834
11835
12352
12353
12354
12355
12356
12357
12358
12359

12360







12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374







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







     also ignoring any OOM error at this point. */
  fsl_buffer_reserve(&f->error.msg, InitialScratchCapacity);

#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  sqlite3_initialize(); /*the SQLITE_MUTEX_STATIC_MASTER will not cause autoinit of sqlite for some reason*/
  sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
#endif
#if FSL_ENABLE_SQLITE_REGEXP
    if ( 1 == ++sg_autoregctr )
  if ( 1 == ++sg_autoregctr ){
    {
      /*register our statically linked extensions to be auto-init'ed at the appropriate time*/
      sqlite3_auto_extension((void(*)(void))(sqlite3_regexp_init));     /*sqlite regexp extension*/
      atexit(sqlite3_reset_auto_extension)
        /* Clean up pseudo-leak valgrind complains about:
           https://www.sqlite.org/c3ref/auto_extension.html */;
    }
    /*register our statically linked extensions to be auto-init'ed at the appropriate time*/
    sqlite3_auto_extension((void(*)(void))(sqlite3_regexp_init));     /*sqlite regexp extension*/
    atexit(sqlite3_reset_auto_extension)
      /* 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){
    /* Attempt to ensure that the TEMP tables/indexes use FILE storage. */
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957

11958

11959
11960
11961
11962
11963

11964
11965
11966
11967
11968
11969
11970
12450
12451
12452
12453
12454
12455
12456













12457
12458
12459
12460
12461
12462
12463
12464
12465




12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480

12481

12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493







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









-
-
-
-














+
-
+
-




+







}

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

  if(f->xlinkers.list){
#if 0
    /* Potential TODO: add client-specified finalizer for xlink
       callback state, using a fsl_state to replace the current
       (void*) for x->state. Seems like overkill for the time being.
     */
    fsl_size_t i;
    for( i = 0; i < f->xlinkers.used; ++i ){
      fsl_xlinker * x = f->xlinkers.list + i;
      if(x->state.finalize.f){
        x->state.finalize.f(x->state.finalize.state, x->state.state);
      }
    }
#endif    
    fsl_free(f->xlinkers.list);
    f->xlinkers = fsl_xlinker_list_empty;
  }

  if(f->clientState.finalize.f){
    f->clientState.finalize.f( f->clientState.finalize.state,
                               f->clientState.state );
  }
  f->clientState = fsl_state_empty;
  if(f->output.state.finalize.f){
    f->output.state.finalize.f( f->output.state.finalize.state,
                                f->output.state.state );
  }
  f->output = fsl_outputer_empty;
  fsl_cx_reset(f, 1);
  fsl_db_close(&f->dbMem);
  *f = fsl_cx_empty;
  if(&fsl_cx_empty == allocStamp){
    fsl_free(f);
  }else{
    f->allocStamp = allocStamp;
  }

  /* clean up the auto extension; not strictly necessary, but pleases debug malloc's */
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
#endif
#if FSL_ENABLE_SQLITE_REGEXP
  if ( 0 == --sg_autoregctr )
  if ( 0 == --sg_autoregctr ){
  {
    /*register our statically linked extensions to be auto-init'ed at the appropriate time*/
    sqlite3_cancel_auto_extension((void(*)(void))(sqlite3_regexp_init));     /*sqlite regexp extension*/
  }
  assert(sg_autoregctr>=0);
#endif
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
#endif
}

void fsl_cx_err_reset(fsl_cx * f){
  if(f){
12024
12025
12026
12027
12028
12029
12030
12031

12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045

12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057

12058
12059
12060
12061
12062
12063
12064
12065
12066

12067
12068
12069
12070
12071
12072
12073

12074
12075
12076
12077
12078
12079
12080

12081
12082
12083
12084
12085
12086
12087
12088
12089

12090
12091
12092
12093
12094
12095
12096
12097
12098

12099
12100
12101
12102
12103
12104
12105

12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122

12123
12124
12125
12126
12127
12128
12129
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
12572
12573
12574
12575
12576
12577
12578
12579

12580
12581
12582
12583
12584
12585
12586
12587
12588

12589
12590
12591
12592
12593
12594
12595

12596
12597
12598
12599
12600
12601
12602

12603
12604
12605
12606
12607
12608
12609
12610
12611

12612
12613
12614
12615
12616
12617
12618
12619
12620

12621
12622
12623
12624
12625
12626
12627

12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644

12645
12646
12647
12648
12649
12650
12651
12652







-
+













-
+











-
+








-
+






-
+






-
+








-
+








-
+






-
+
















-
+







  if(rc) {
    *rc = fsl_cx_empty;
    rc->allocStamp = &fsl_cx_empty;
  }
  return rc;
}

int fsl_cx_err_report( fsl_cx * f, char addNewline ){
int fsl_cx_err_report( fsl_cx * const f, bool addNewline ){
  if(!f) return FSL_RC_MISUSE;
  else if(f->error.code){
    char const * msg = f->error.msg.used
      ? (char const *)f->error.msg.mem
      : fsl_rc_cstr(f->error.code)
      ;
    return fsl_outputf(f, "Error #%d: %s%s",
                       f->error.code, msg,
                       addNewline ? "\n" : "");
  }
  else return 0;
}

int fsl_cx_uplift_db_error( fsl_cx * f, fsl_db * db ){
int fsl_cx_uplift_db_error( fsl_cx * const f, fsl_db * db ){
  assert(f);
  if(!f) return FSL_RC_MISUSE;
  if(!db){
    db = f->dbMain;
    assert(db && "misuse: no DB handle to uplift error from!");
    if(!db) return FSL_RC_MISUSE;
  }
  fsl_error_move( &db->error, &f->error );
  return f->error.code;
}

int fsl_cx_uplift_db_error2(fsl_cx *f, fsl_db * db, int rc){
int fsl_cx_uplift_db_error2(fsl_cx * const f, fsl_db * db, int rc){
  if(!db) db = f->dbMain;
  assert(db);
  if(rc && FSL_RC_OOM!=rc && !f->error.code && db->error.code){
    rc = fsl_cx_uplift_db_error(f, db);
  }
  return rc;
}

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

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

fsl_db * fsl_needs_repo(fsl_cx * f){
fsl_db * fsl_needs_repo(fsl_cx * const f){
  fsl_db * const db = fsl_cx_db_repo(f);
  if(!db){
    fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                   "Fossil context has no opened repository db.");
  }
  return db;
}

fsl_db * fsl_needs_ckout(fsl_cx * f){
fsl_db * fsl_needs_ckout(fsl_cx * const f){
  fsl_db * const db = fsl_cx_db_ckout(f);
  if(!db){
    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 * f ){
fsl_db * fsl_cx_db_ckout( fsl_cx * const f ){
  if(!f) return NULL;
  else if(f->ckout.db.dbh) return &f->ckout.db;
  else if(f->dbMain && (FSL_DBROLE_CKOUT & f->dbMain->role)) return f->dbMain;
  else return NULL;
}

fsl_db * fsl_cx_db( fsl_cx * f ){
fsl_db * fsl_cx_db( fsl_cx * const f ){
  return f ? f->dbMain : NULL;
}
/** @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 * 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;
12989
12990
12991
12992
12993
12994
12995
12996


12997
12998
12999
13000
13001
13002
13003
13512
13513
13514
13515
13516
13517
13518

13519
13520
13521
13522
13523
13524
13525
13526
13527







-
+
+







  if(!rc){
    int const mode = vid ? -1 : 0;
    rc = fsl_ckout_manifest_write(f, mode, mode, mode, 0);
  }
  return rc;
}

void fsl_ckout_version_info(fsl_cx *f, fsl_id_t * rid, fsl_uuid_cstr * uuid ){
void fsl_ckout_version_info(fsl_cx * const f, fsl_id_t * const rid,
                            fsl_uuid_cstr * const uuid ){
  if(uuid) *uuid = f->ckout.uuid;
  if(rid) *rid = f->ckout.rid>=0 ? f->ckout.rid : 0;
}

int fsl_ckout_db_search( char const * dirName, bool checkParentDirs,
                         fsl_buffer * pOut ){
  int rc;
13230
13231
13232
13233
13234
13235
13236

13237
13238
13239

13240
13241
13242
13243
13244
13245
13246
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763

13764
13765
13766
13767
13768
13769
13770
13771







+


-
+







}

int fsl_cx_flags_get( fsl_cx * f ){
  return f->flags;
}

int fsl_cx_flag_set( fsl_cx * f, int flags, bool enable ){
  int const oldFlags = f->flags;
  if(enable) f->flags |= flags;
  else f->flags &= ~flags;
  return f->flags;
  return oldFlags;
}


fsl_xlinker * fsl_xlinker_by_name( fsl_cx * f, char const * name ){

  fsl_xlinker * rv = NULL;
  fsl_size_t i;
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323



13324
13325
13326
13327
13328
13329
13330
13839
13840
13841
13842
13843
13844
13845



13846
13847
13848
13849
13850
13851
13852
13853
13854
13855







-
-
-
+
+
+







      rc = fsl_buffer_append(pOut, fsl_schema_ticket(), -1);
    }
    return rc;
  }
}


int fsl_cx_stat2( fsl_cx * f, bool relativeToCwd,
                  char const * zName, fsl_fstat * tgt,
                  fsl_buffer * nameOut, bool fullPath){
int fsl_cx_stat2( fsl_cx * const f, bool relativeToCwd,
                  char const * zName, fsl_fstat * const tgt,
                  fsl_buffer * const nameOut, bool fullPath){
  int rc;
  fsl_buffer * b = 0;
  fsl_buffer * bufRel = 0;
  fsl_size_t n;
  assert(f);
  if(!zName || !*zName) return FSL_RC_MISUSE;
  else if(!fsl_needs_ckout(f)) return FSL_RC_NOT_A_CKOUT;
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378



13379
13380
13381
13382
13383
13384
13385
13894
13895
13896
13897
13898
13899
13900



13901
13902
13903
13904
13905
13906
13907
13908
13909
13910







-
-
-
+
+
+







  }
  end:
  fsl_cx_scratchpad_yield(f, b);
  fsl_cx_scratchpad_yield(f, bufRel);
  return rc;
}

int fsl_cx_stat(fsl_cx * f, bool relativeToCwd, char const * zName,
                fsl_fstat * tgt){
  return fsl_cx_stat2(f, relativeToCwd, zName, tgt, NULL, 0);
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);
}


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

13519
13520
13521
13522
13523
13524
13525
13526

13527
13528
13529
13530
13531
13532
13533



13534
13535
13536
13537



13538
13539
13540
13541
13542
13543
13544
14044
14045
14046
14047
14048
14049
14050

14051
14052
14053
14054
14055
14056


14057
14058
14059
14060
14061


14062
14063
14064
14065
14066
14067
14068
14069
14070
14071







-
+





-
-
+
+
+


-
-
+
+
+







  return old;
}

fsl_hashpolicy_e fsl_cx_hash_policy_get(fsl_cx const*f){
  return f->cxConfig.hashPolicy;
}

int fsl_cx_transaction_level(fsl_cx * f){
int fsl_cx_transaction_level(fsl_cx * const f){
  return f->dbMain
    ? fsl_db_transaction_level(f->dbMain)
    : 0;
}

int fsl_cx_transaction_begin(fsl_cx * f){
  return fsl_db_transaction_begin(f->dbMain);
int fsl_cx_transaction_begin(fsl_cx * const f){
  int const rc = fsl_db_transaction_begin(f->dbMain);
  return rc ? fsl_cx_uplift_db_error2(f, f->dbMain, rc) : 0;
}

int fsl_cx_transaction_end(fsl_cx * f, bool doRollback){
  return fsl_db_transaction_end(f->dbMain, doRollback);
int fsl_cx_transaction_end(fsl_cx * const f, bool doRollback){
  int const rc = fsl_db_transaction_end(f->dbMain, doRollback);
  return rc ? fsl_cx_uplift_db_error2(f, f->dbMain, rc) : 0;
}

void fsl_cx_confirmer(fsl_cx * f,
                      fsl_confirmer const * newConfirmer,
                      fsl_confirmer * prevConfirmer){
  if(prevConfirmer) *prevConfirmer = f->confirmer;
  f->confirmer = newConfirmer ? *newConfirmer : fsl_confirmer_empty;
13791
13792
13793
13794
13795
13796
13797
13798
13799


13800
13801
13802
13803
13804
13805
13806
14318
14319
14320
14321
14322
14323
14324


14325
14326
14327
14328
14329
14330
14331
14332
14333







-
-
+
+








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){
  fsl_db * const db = fsl_needs_ckout(f);
  if(!db) return FSL_RC_NOT_A_CKOUT;
  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);
  rc = fsl_config_get_buffer(f, FSL_CONFDB_CKOUT, "fingerprint", buf);
  if(FSL_RC_NOT_FOUND==rc){
13834
13835
13836
13837
13838
13839
13840





13841
13842
13843
13844
13845
13846
13847
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379







+
+
+
+
+







  return rc;
  mismatch:
  rc = fsl_cx_err_set(f, FSL_RC_REPO_MISMATCH,
                      "Mismatch found between repo/checkout "
                      "fingerprints.");
  goto end;
}

bool fsl_cx_has_ckout(fsl_cx const * const f ){
  return f->ckout.dir ? true : false;
}


#if 0
struct tm * fsl_cx_localtime( fsl_cx const * f, const time_t * clock ){
  if(!clock) return NULL;
  else if(!f) return localtime(clock);
  else return (f->flags & FSL_CX_F_LOCALTIME_GMT)
         ? gmtime(clock)
14055
14056
14057
14058
14059
14060
14061


14062
14063
14064
14065
14066
14067
14068
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602







+
+







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

14546
14547
14548
14549
14550
14551
14552
14553

14554
14555
14556
14557
14558
14559
14560
14561
14562

14563
14564
14565
14566
14567
14568
14569
15080
15081
15082
15083
15084
15085
15086

15087
15088
15089
15090
15091
15092
15093
15094
15095

15096
15097
15098
15099
15100
15101
15102
15103







-
+








-
+







  }
  return rc;
}

/**
   The elipsis counterpart of fsl_stmt_bind_fmtv().
*/
int fsl_stmt_bind_fmt( fsl_stmt * st, char const * fmt, ... ){
int fsl_stmt_bind_fmt( fsl_stmt * const st, char const * fmt, ... ){
  int rc;
  va_list args;
  va_start(args,fmt);
  rc = fsl_stmt_bind_fmtv(st, fmt, args);
  va_end(args);
  return rc;
}

int fsl_stmt_bind_stepv( fsl_stmt * st, char const * fmt,
int fsl_stmt_bind_stepv( fsl_stmt * const st, char const * fmt,
                         va_list args ){
  int rc;
  fsl_stmt_reset(st);
  rc = fsl_stmt_bind_fmtv(st, fmt, args);
  if(!rc){
    rc = fsl_stmt_step(st);
    switch(rc){
15660
15661
15662
15663
15664
15665
15666
15667

15668
15669
15670
15671
15672
15673
15674
16194
16195
16196
16197
16198
16199
16200

16201
16202
16203
16204
16205
16206
16207
16208







-
+







    }
    db_multi_exec(db.doRollback ? "ROLLBACK" : "COMMIT");
    db.doRollback = 0;
  }
#endif  
}

int fsl_db_get_int32v( fsl_db * db, int32_t * rv,
int fsl_db_get_int32v( fsl_db * const db, int32_t * rv,
                       char const * sql, va_list args){
  /* Potential fixme: the fsl_db_get_XXX() funcs are 95%
     code duplicates. We "could" replace these with a macro
     or supermacro, though the latter would be problematic
     in the context of an amalgamation build.
  */
  if(!db || !db->dbh || !rv || !sql || !*sql) return FSL_RC_MISUSE;
15690
15691
15692
15693
15694
15695
15696
15697
15698


15699
15700
15701
15702
15703
15704
15705
15706
16224
16225
16226
16227
16228
16229
16230


16231
16232

16233
16234
16235
16236
16237
16238
16239







-
-
+
+
-







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

int fsl_db_get_int32( fsl_db * db, int32_t * rv,
                      char const * sql,
int fsl_db_get_int32( fsl_db * const db, int32_t * rv,
                      char const * sql, ... ){
                      ... ){
  int rc;
  va_list args;
  va_start(args,sql);
  rc = fsl_db_get_int32v(db, rv, sql, args);
  va_end(args);
  return rc;
}
16003
16004
16005
16006
16007
16008
16009
16010
16011


16012
16013
16014
16015
16016
16017
16018
16019
16536
16537
16538
16539
16540
16541
16542


16543
16544

16545
16546
16547
16548
16549
16550
16551







-
-
+
+
-







  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 * db, int32_t dflt,
                            char const * sql,
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;
}
16263
16264
16265
16266
16267
16268
16269
16270

16271
16272
16273
16274

16275
16276
16277
16278
16279
16280
16281
16795
16796
16797
16798
16799
16800
16801

16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814







-
+




+







      err->msg.used = 0;
    }
  }
  fsl_db_close(db);
  return rc;
}

int fsl_stmt_each_f_dump( fsl_stmt * stmt, void * state ){
int fsl_stmt_each_f_dump( fsl_stmt * const stmt, void * state ){
  int i;
  fsl_cx * f = (stmt && stmt->db) ? stmt->db->f : NULL;
  char const * sep = "\t";
  if(!f) return FSL_RC_MISUSE;
  if(state){/*unused arg*/}
  if(1==stmt->rowCount){
    for( i = 0; i < stmt->colCount; ++i ){
      fsl_outputf(f, "%s%s", fsl_stmt_col_name(stmt, i),
            (i==stmt->colCount-1) ? "" : sep);
    }
    fsl_output(f, "\n", 1);
  }
16873
16874
16875
16876
16877
16878
16879

16880
16881
16882
16883
16884
16885
16886
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420







+







        case 'G': case 'H': case 'I':
        case 'N': case 'P':
          return -1;
        default:
          return 0;
      };
    default:
      MARKER(("invalid fsl_satype_e value: %d, card=%c\n", t, card));
      assert(!"Invalid fsl_satype_e.");
      return 0;
  };
}

bool fsl_deck_has_required_cards( fsl_deck const * d ){
  if(!d) return 0;
17299
17300
17301
17302
17303
17304
17305
17306
17307


17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318

17319
17320
17321
17322
17323
17324
17325
17833
17834
17835
17836
17837
17838
17839


17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851

17852
17853
17854
17855
17856
17857
17858
17859







-
-
+
+










-
+







  }
}

static void fsl_deck_F_sort(fsl_deck * mf){
  fsl_card_F_list_sort(&mf->F);
}

int fsl_card_F_compare( fsl_card_F const * lhs,
                        fsl_card_F const * rhs){
int fsl_card_F_compare_name( fsl_card_F const * const lhs,
                             fsl_card_F const * const rhs){
  return (lhs == rhs) ? 0 : fsl_card_F_cmp( lhs, rhs );
}

int fsl_deck_R_set( fsl_deck * mf, fsl_uuid_cstr md5){
  return mf
    ? fsl_deck_sethex_impl(mf, md5, 'R', md5 ? FSL_STRLEN_MD5 : 0, &mf->R)
    : FSL_RC_MISUSE;
}

int fsl_deck_R_calc2(fsl_deck *mf, char ** tgt){
  fsl_cx * f = mf->f;
  fsl_cx * const f = mf->f;
  char const * theHash = 0;
  char hex[FSL_STRLEN_MD5+1];
  if(!f) return FSL_RC_MISUSE;
  else if(!fsl_needs_repo(f)){
    return FSL_RC_NOT_A_REPO;
  }else if(!fsl_deck_check_type(mf,'R')) {
    assert(mf->f->error.code);
17396
17397
17398
17399
17400
17401
17402
17403

17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415

17416
17417
17418
17419
17420
17421
17422
17930
17931
17932
17933
17934
17935
17936

17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948

17949
17950
17951
17952
17953
17954
17955
17956







-
+











-
+







    if(rc) return rc;
    fsl_deck_F_rewind(mf);
    theHash = hex;
  }
  assert(theHash);
  if(*tgt){
    memcpy(*tgt, theHash, FSL_STRLEN_MD5);
    (*tgt)[FSL_STRLEN_MD5+1] = 0;
    (*tgt)[FSL_STRLEN_MD5] = 0;
    return 0;
  }else{
    char * x = fsl_strdup(theHash);
    if(x) *tgt = x;
    return x ? 0 : FSL_RC_OOM;
  }
}

int fsl_deck_R_calc(fsl_deck * mf){
  char R[FSL_STRLEN_MD5+1] = {0};
  char * r = R;
  int rc = fsl_deck_R_calc2(mf, &r);
  const int rc = fsl_deck_R_calc2(mf, &r);
  return rc ? rc : fsl_deck_R_set(mf, r);
}

int fsl_deck_T_add2( fsl_deck * mf, fsl_card_T * t){
  if(!t) return FSL_RC_MISUSE;
  else if(!fsl_deck_check_type(mf, 'T')){
    return mf->f->error.code;
17655
17656
17657
17658
17659
17660
17661
17662

17663
17664
17665
17666
17667
17668
17669
18189
18190
18191
18192
18193
18194
18195

18196
18197
18198
18199
18200
18201
18202
18203







-
+







    }
    return (FSL_RC_BREAK==rc) ? 0 : rc;
  }
}

  
/**
    Output state for fsl_appendf_f_mf() and friends. Used for managing
    Output state for fsl_output_f_mf() and friends. Used for managing
    the output of a fsl_deck.
 */
struct fsl_deck_out_state {
  /**
      The set of cards being output. We use this to delegate certain
      output bits.
   */
17692
17693
17694
17695
17696
17697
17698
17699

17700
17701
17702
17703
17704
17705
17706
18226
18227
18228
18229
18230
18231
18232

18233
18234
18235
18236
18237
18238
18239
18240







-
+







      Counter for list-visiting routines. Must be re-set before each
      visit loop if the visitor makes use of this (most do not).
   */
  fsl_int_t counter;

  /**
      Incrementally-calculated MD5 sum of all output sent via
      fsl_appendf_f_mf().
      fsl_output_f_mf().
   */
  fsl_md5_cx md5;

  /* Holds error state for propagating back to the client. */
  fsl_error error;

  /**
17719
17720
17721
17722
17723
17724
17725
17726

17727
17728
17729
17730
17731
17732

17733
17734
17735


17736
17737
17738
17739
17740
17741

17742
17743
17744
17745
17746
17747
17748

17749
17750
17751
17752
17753
17754
17755
17756
17757

17758
17759
17760
17761
17762
17763
17764
18253
18254
18255
18256
18257
18258
18259

18260
18261
18262
18263
18264
18265

18266



18267
18268
18269
18270
18271
18272
18273

18274


18275
18276
18277
18278

18279
18280
18281
18282
18283
18284
18285
18286
18287

18288
18289
18290
18291
18292
18293
18294
18295







-
+





-
+
-
-
-
+
+





-
+
-
-




-
+








-
+







0/*counter*/,
fsl_md5_cx_empty_m/*md5*/,
fsl_error_empty_m/*error*/,
NULL/*scratch*/
};

/**
    fsl_appendf_f() impl which forwards its data to arg->out(). arg
    fsl_output_f() impl which forwards its data to arg->out(). arg
    must be a (fsl_deck_out_state *). Updates arg->rc to the result of
    calling arg->out(fp->fState, data, n). If arg->out() succeeds then
    arg->md5 is updated to reflect the given data. i.e. this is where
    the Z-card gets calculated incrementally during output of a deck.
*/
static fsl_int_t fsl_appendf_f_mf( void * arg,
static int fsl_output_f_mf( void * arg, void const * data,
                                   char const * data,
                                   fsl_int_t n ){
  fsl_deck_out_state * os = (fsl_deck_out_state *)arg;
                            fsl_size_t n ){
  fsl_deck_out_state * const os = (fsl_deck_out_state *)arg;
  if((n>0)
     && !(os->rc = os->out(os->outState, data, (fsl_size_t)n))
     && (os->md5.isInit)){
    fsl_md5_update( &os->md5, data, (fsl_size_t)n );
  }
  return (0==os->rc)
  return os->rc;
    ? n
    : -1;
}

/**
    Internal helper for fsl_deck_output(). Appends formatted output to
    os->out() via fsl_appendf_f_mf(). Returns os->rc (0 on success).
    os->out() via fsl_output_f_mf(). Returns os->rc (0 on success).
 */
static int fsl_deck_append( fsl_deck_out_state * os,
                            char const * fmt, ... ){
  fsl_int_t rc;
  va_list args;
  assert(os);
  assert(fmt && *fmt);
  va_start(args,fmt);
  rc = fsl_appendfv( fsl_appendf_f_mf, os, fmt, args);
  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,
17983
17984
17985
17986
17987
17988
17989
17990

17991
17992
17993
17994
17995
17996
17997
18514
18515
18516
18517
18518
18519
18520

18521
18522
18523
18524
18525
18526
18527
18528







-
+







    if(*zPerm) rc = fsl_deck_append( os, "%s", zPerm);
    if(!rc && hasOldName){
      assert(*zPerm);
      rc = fsl_deck_fossilize(os, (unsigned char const *)f->priorName, -1);
      if(!rc) rc = fsl_deck_append( os, " %b", os->scratch);
    }
  }
  if(!rc) fsl_appendf_f_mf(os, "\n", 1);
  if(!rc) fsl_output_f_mf(os, "\n", 1);
  return os->rc;
}

static int fsl_deck_out_list_obj( fsl_deck_out_state * os,
                                  char letter,
                                  fsl_list const * li,
                                  fsl_list_visitor_f visitor){
18100
18101
18102
18103
18104
18105
18106
18107
18108


18109
18110
18111

18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123

18124
18125
18126
18127
18128
18129
18130
18631
18632
18633
18634
18635
18636
18637


18638
18639
18640
18641

18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653

18654
18655
18656
18657
18658
18659
18660
18661







-
-
+
+


-
+











-
+







  fsl_deck_out_state * 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_appendf_f_mf(os, "P ", 2);
  else fsl_appendf_f_mf(os, " ", 1);
  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_appendf_f_mf(os, uuid, (fsl_size_t)uLen);
    fsl_output_f_mf(os, uuid, (fsl_size_t)uLen);
  }
  return os->rc;
}


static int fsl_deck_out_P( fsl_deck_out_state * 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_appendf_f_mf(os, "\n", 1);
    if(!os->rc) fsl_output_f_mf(os, "\n", 1);
  }
#if 1
  /* Arguable: empty P-cards are harmless but cosmetically unsightly. */
  else if(FSL_SATYPE_CHECKIN==os->d->type){
    /*
      Evil ugly hack, primarily for round-trip compatibility with
      manifest #1, which has an empty P card.
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301



18302
18303
18304

18305
18306
18307
18308
18309
18310
18311
18823
18824
18825
18826
18827
18828
18829



18830
18831
18832
18833
18834

18835
18836
18837
18838
18839
18840
18841
18842







-
-
-
+
+
+


-
+







                           t->uuid ? t->uuid : "*");
  if(os->rc) return os->rc;
  if(/*(t->type != FSL_TAGTYPE_CANCEL) &&*/t->value && *t->value){
    /* CANCEL tags historically don't store a value but
       the spec doesn't disallow it and they are harmless
       for (aren't used by) fossil(1). */
    fsl_deck_fossilize(os, (unsigned char const *)t->value, -1);
    if(!os->rc) fsl_appendf_f_mf(os, " ", 1);
    if(!os->rc) fsl_appendf_f_mf(os, (char const*)os->scratch->mem,
                                 (fsl_int_t)os->scratch->used);
    if(!os->rc) fsl_output_f_mf(os, " ", 1);
    if(!os->rc) fsl_output_f_mf(os, (char const*)os->scratch->mem,
                                (fsl_int_t)os->scratch->used);
  }
  if(!os->rc){
    fsl_appendf_f_mf(os, "\n", 1);
    fsl_output_f_mf(os, "\n", 1);
  }
  return os->rc;
}


char fsl_tag_prefix_char( fsl_tagtype_e t ){
  switch(t){
22966
22967
22968
22969
22970
22971
22972





22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514

23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534






23535
23536
23537
23538
23539
23540
23541







+
+
+
+
+






-




















-
-
-
-
-
-







  This file houses Fossil's diff-generation routines (as opposed to
  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 TO_BE_STATIC /* Porting crutch for unused static funcs */

#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 */

/**
    Maximum length of a line in a text file, in bytes.  (2**13 = 8192 bytes)
 */
#define LENGTH_MASK_SZ  13
#define LENGTH_MASK     ((1<<LENGTH_MASK_SZ)-1)


/*
  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")
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
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
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
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23601
23602
23603
23604
23605
23606
23607
23608





















23609
23610
23611
23612





















































































































































23613
23614
23615
23616
23617
23618
23619








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




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







  DO(FSL_DIFF_INVERT);
  DO(FSL_DIFF_NOTTOOBIG);
  DO(FSL_DIFF_STRIP_EOLCR);
#undef DO
  return rc;
}

/*
   Information about each line of a file being diffed.
  
   The lower LENGTH_MASK_SZ bits of the hash (DLine.h) are the length
   of the line.  If any line is longer than LENGTH_MASK characters,
   the file is considered binary.
*/
typedef struct DLine DLine;
struct DLine {
  const char *z;        /* The text of the line */
  unsigned int h;       /* Hash of the line */
  unsigned short indent;  /* Indent of the line. Only !=0 with -w/-Z option */
  unsigned short n;     /* number of bytes */
  unsigned int iNext;   /* 1+(Index of next line with same the same hash) */

  /* an array of DLine elements serves two purposes.  The fields
     above are one per line of input text.  But each entry is also
     a bucket in a hash table, as follows: */
  unsigned int iHash;   /* 1+(first entry in the hash chain) */
};

/*
   Length of a dline
*/
#define LENGTH(X)   ((X)->n)

/*
   Return an array of DLine objects containing a pointer to the
   start of each line and a hash of that line.  The lower
   bits of the hash store the length of each line.
  
   Trailing whitespace is removed from each line.  2010-08-20:  Not any
   more.  If trailing whitespace is ignored, the "patch" command gets
   confused by the diff output.  Ticket [a9f7b23c2e376af5b0e5b]
  
   If the file is binary or contains a line that is too long, or is
   empty, it sets *pOut to NULL, *pnLine to 0. It returns 0 if no
   lines are found, FSL_RC_TYPE if the input is binary, and
   FSL_RC_RANGE if a some number (e.g. the number of columns) is out
   of range.
  
   Profiling shows that in most cases this routine consumes the bulk
   of the CPU time on a diff.
  
   TODO: enhance the error reporting: add a (fsl_error*) arg.
*/
static int break_into_lines(const char *z, int n, int *pnLine,
                            DLine **pOut, int diffFlags){
  int nLine, i, j, k, s, x;
  unsigned int h, h2;
  DLine *a = NULL;
  /* Count the number of lines.  Allocate space to hold
     the returned array.
  */
  for(i=j=0, nLine=1; i<n; i++, j++){
    int c = z[i];
    if( c==0 ){
      /* printf("BINARY DATA AT BYTE %d\n", i); */
      /* goto gotNone; */
      *pOut = NULL;
      return FSL_RC_TYPE;
    }
    if( c=='\n' && z[i+1]!=0 ){
      nLine++;
      if( j>LENGTH_MASK ){
        /* printf("TOO LONG AT COLUMN %d\n", j); */
        /* goto gotNone; */
        *pOut = NULL;
        return FSL_RC_RANGE;
      }
      j = 0;
    }
  }
  if( j>LENGTH_MASK ){
    /* printf("TOO LONG AGAIN AT COLUMN %d\n", j); */
    /* goto gotNone; */
    *pOut = NULL;
    return FSL_RC_RANGE;
  }
  a = fsl_malloc( nLine*sizeof(a[0]) );
  if(!a) return FSL_RC_OOM;
  memset(a, 0, nLine*sizeof(a[0]) );
  if( n==0 ){
    /* gotNone: */
    *pnLine = 0;
    *pOut = a;
    return 0;
  }

  /* Fill in the array */
  for(i=0; i<nLine; i++){
    for(j=0; z[j] && z[j]!='\n'; j++){}
    a[i].z = z;
    k = j;
    if( diffFlags & DIFF_STRIP_EOLCR ){
      if( k>0 && z[k-1]=='\r' ){ k--; }
    }
    a[i].n = k;
    s = 0;
    if(diffFlags & DIFF_IGNORE_EOLWS){
      while( k>0 && fsl_isspace(z[k-1]) ){ k--; }
    }
    if( (diffFlags & DIFF_IGNORE_ALLWS)==DIFF_IGNORE_ALLWS ){
      while( s<k && fsl_isspace(z[s]) ){ s++; }
    }
    a[i].indent = s;
    for(h=0, x=s; x<k; x++){
      h = h ^ (h<<2) ^ z[x];
    }
    a[i].h = h = (h<<LENGTH_MASK_SZ) | (k-s);
    h2 = h % nLine;
    a[i].iNext = a[h2].iHash;
    a[h2].iHash = i+1;
    z += j+1;
  }

  /* Return results */
  *pnLine = nLine;
  *pOut = a;
  return 0;
}


/*
   Return true if two DLine elements are identical.
*/
static int same_dline(DLine const *pA, DLine const *pB){
  return pA->h==pB->h && memcmp(pA->z+pA->indent,pB->z+pB->indent,
                                pA->h & LENGTH_MASK)==0;
}


/*
** Return true if two DLine elements are identical, ignoring
** all whitespace. The indent field of pA/pB already points
** to the first non-space character in the string.
*/
static int same_dline_ignore_allws(const DLine *pA, const DLine *pB){
  int a = pA->indent, b = pB->indent;
  if( pA->h==pB->h ){
    while( a<pA->n || b<pB->n ){
      if( a<pA->n && b<pB->n && pA->z[a++] != pB->z[b++] ) return 0;
      while( a<pA->n && fsl_isspace(pA->z[a])) ++a;
      while( b<pB->n && fsl_isspace(pB->z[b])) ++b;
    }
    return pA->n-a == pB->n-b;
  }
  return 0;
}

/*
   A context for running a raw diff.
  
   The aEdit[] array describes the raw diff.  Each triple of integers in
   aEdit[] means:
  
     (1) COPY:   Number of lines aFrom and aTo have in common
     (2) DELETE: Number of lines found only in aFrom
     (3) INSERT: Number of lines found only in aTo
  
   The triples repeat until all lines of both aFrom and aTo are accounted
   for.
*/
typedef struct DContext DContext;
struct DContext {
  int *aEdit;        /* Array of copy/delete/insert triples */
  int nEdit;         /* Number of integers (3x num of triples) in aEdit[] */
  int nEditAlloc;    /* Space allocated for aEdit[] */
  DLine *aFrom;      /* File on left side of the diff */
  int nFrom;         /* Number of lines in aFrom[] */
  DLine *aTo;        /* File on right side of the diff */
  int nTo;           /* Number of lines in aTo[] */
  int (*same_fn)(const DLine *, const DLine *); /* Function to be used for comparing */
};

/**
    Holds output state for diff generation.
 */
struct DiffOutState {
  /** Output callback. */
  fsl_output_f out;
  /** State for this->out(). */
23271
23272
23273
23274
23275
23276
23277
23278

23279
23280

23281
23282
23283
23284
23285
23286

23287
23288
23289
23290
23291



23292
23293

23294
23295
23296
23297
23298
23299

23300
23301
23302
23303
23304
23305
23306
23307
23308

23309
23310

23311
23312
23313
23314
23315
23316
23317
23630
23631
23632
23633
23634
23635
23636

23637
23638

23639
23640
23641
23642

23643

23644
23645
23646



23647
23648
23649


23650
23651
23652
23653
23654
23655

23656
23657
23658
23659
23660
23661
23662
23663
23664

23665
23666

23667
23668
23669
23670
23671
23672
23673
23674







-
+

-
+



-

-
+


-
-
-
+
+
+
-
-
+





-
+








-
+

-
+







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 * o, void const * src, fsl_int_t n ){
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)
    ? o->out(o->oState, src, n<0 ? fsl_strlen((char const *)src) : (fsl_size_t)n)
    : 0;
}


/**
    fsl_appendf_f() impl for use with diff_outf(). state must be a
    fsl_output_f() impl for use with diff_outf(). state must be a
    (DiffOutState*).
 */
static fsl_int_t fsl_appendf_f_diff_out( void * state, char const * s,
                                         fsl_int_t n ){
  DiffOutState * os = (DiffOutState *)state;
static int fsl_output_f_diff_out( void * state, void const * src,
                                  fsl_size_t n ){
  DiffOutState * const os = (DiffOutState *)state;
  diff_out(os, s, n);
  return os->rc ? -1 : n;
  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_appendf_f_diff_out, o, fmt, va);
  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 *pOut,         /* Where to write the line of output */
  DiffOutState *const pOut, /* Where to write the line of output */
  char cPrefix,       /* One of " ", "+",  or "-" */
  DLine *pLine,       /* The line to be output */
  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 
23387
23388
23389
23390
23391
23392
23393
23394
23395

23396
23397
23398
23399

23400
23401
23402
23403
23404



23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419


23420
23421
23422
23423

23424
23425
23426
23427
23428
23429
23430
23744
23745
23746
23747
23748
23749
23750


23751
23752
23753
23754

23755
23756
23757



23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773


23774
23775
23776
23777
23778

23779
23780
23781
23782
23783
23784
23785
23786







-
-
+



-
+


-
-
-
+
+
+













-
-
+
+



-
+







  return rc;
}


/*
   Minimum of two values
*/
#define minInt(a,b) (((a)<(b)) ? (a) : (b))

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
    exhaustive search. This version of the LCS is only used for
    shorter input strings since runtime is O(N*N) where N is the
    input string length.
 */
static void optimalLCS(
  DContext *p,               /* Two files being compared */
*/
static void fsl__diff_optimal_lcs(
  fsl_diff_cx * const p,     /* Two files being compared */
  int iS1, int iE1,          /* Range of lines in p->aFrom[] */
  int iS2, int iE2,          /* Range of lines in p->aTo[] */
  int *piSX, int *piEX,      /* Write p->aFrom[] common segment here */
  int *piSY, int *piEY       /* Write p->aTo[] common segment here */
){
  int mxLength = 0;          /* Length of longest common subsequence */
  int i, j;                  /* Loop counters */
  int k;                     /* Length of a candidate subsequence */
  int iSXb = iS1;            /* Best match so far */
  int iSYb = iS2;            /* Best match so far */

  for(i=iS1; i<iE1-mxLength; i++){
    for(j=iS2; j<iE2-mxLength; j++){
      if( !p->same_fn(&p->aFrom[i], &p->aTo[j]) ) continue;
      if( mxLength && !p->same_fn(&p->aFrom[i+mxLength], &p->aTo[j+mxLength]) ){
      if( p->cmpLine(&p->aFrom[i], &p->aTo[j]) ) continue;
      if( mxLength && p->cmpLine(&p->aFrom[i+mxLength], &p->aTo[j+mxLength]) ){
        continue;
      }
      k = 1;
      while( i+k<iE1 && j+k<iE2 && p->same_fn(&p->aFrom[i+k],&p->aTo[j+k]) ){
      while( i+k<iE1 && j+k<iE2 && p->cmpLine(&p->aFrom[i+k],&p->aTo[j+k])==0 ){
        k++;
      }
      if( k>mxLength ){
        iSXb = i;
        iSYb = j;
        mxLength = k;
      }
23448
23449
23450
23451
23452
23453
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
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489

23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506

23507
23508
23509
23510
23511
23512
23513
23514

23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534








23535



23536
23537
23538


23539
23540
23541
23542
23543
23544
23545
23546












23547

23548
23549
23550

23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565

23566
23567
23568
23569
23570
23571
23572
23804
23805
23806
23807
23808
23809
23810




23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821

23822
23823
23824
23825

23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844

23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861

23862
23863
23864
23865
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
23946
23947
23948
23949
23950







-
-
-
-
+
+
+
+







-
+



-
+


















-
+
















-
+







-
+




















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

-
-
+
+








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


-
+














-
+







   
    Ideally, the common sequence should be the longest possible common
    sequence.  However, an exact computation of LCS is O(N*N) which is
    way too slow for larger files.  So this routine uses an O(N)
    heuristic approximation based on hashing that usually works about
    as well.  But if the O(N) algorithm doesn't get a good solution
    and N is not too large, we fall back to an exact solution by
    calling optimalLCS().
 */
static void longestCommonSequence(
  DContext *p,               /* Two files being compared */
    calling fsl__diff_optimal_lcs().
*/
static void fsl__diff_lcs(
  fsl_diff_cx * const p,     /* Two files being compared */
  int iS1, int iE1,          /* Range of lines in p->aFrom[] */
  int iS2, int iE2,          /* Range of lines in p->aTo[] */
  int *piSX, int *piEX,      /* Write p->aFrom[] common segment here */
  int *piSY, int *piEY       /* Write p->aTo[] common segment here */
){
  int i, j, k;               /* Loop counters */
  int n;                     /* Loop limit */
  DLine *pA, *pB;            /* Pointers to lines */
  fsl_dline *pA, *pB;            /* Pointers to lines */
  int iSX, iSY, iEX, iEY;    /* Current match */
  int skew = 0;              /* How lopsided is the match */
  int dist = 0;              /* Distance of match from center */
  int mid;                   /* Center of the span */
  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 */

  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;
  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->same_fn(&p->aFrom[i], &p->aTo[j-1]))
      && (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->same_fn(pA,pB); k++, pA--, pB--){}
    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->same_fn(pA,pB); k++, pA++, pB++){}
    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(
#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
  if( iSXb==iEXb && (int64_t)(iE1-iS1)*(iE2-iS2)<400 ){
     iSXb==iEXb && (sqlite3_int64)(iE1-iS1)*(iE2-iS2)<400
#endif
     ){
    /* If no common sequence is found using the hashing heuristic and
       the input is not too big, use the expensive exact solution */
    optimalLCS(p, iS1, iE1, iS2, iE2, piSX, piEX, piSY, piEY);
    ** 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;
  }
}


void fsl__dump_triples(fsl_diff_cx const * const p,
                       char const * zFile, int ln ){
  // Compare this with (fossil xdiff --raw) on the same inputs
  fprintf(stderr,"%s:%d: Compare this with (fossil xdiff --raw) on the same inputs:\n",
          zFile, ln);
  for(int i = 0; p->aEdit[i] || p->aEdit[i+1] || p->aEdit[i+2]; i+=3){
    printf(" copy %6d  delete %6d  insert %6d\n",
           p->aEdit[i], p->aEdit[i+1], p->aEdit[i+2]);
  }
}

/**
/** @internal
    Expand the size of p->aEdit array to hold at least nEdit elements.
 */
static int expandEdit(DContext *p, int nEdit){
static int fsl__diff_expand_edit(fsl_diff_cx * const p, int nEdit){
  void * re = fsl_realloc(p->aEdit, nEdit*sizeof(int));
  if(!re) return FSL_RC_OOM;
  else{
    p->aEdit = (int*)re;
    p->nEditAlloc = nEdit;
    return 0;
  }
}

/**
    Append a new COPY/DELETE/INSERT triple.
   
    Returns 0 on success, FSL_RC_OOM on OOM.
 */
static int appendTriple(DContext *p, int nCopy, int nDel, int nIns){
static int appendTriple(fsl_diff_cx *p, int nCopy, int nDel, int nIns){
  /* printf("APPEND %d/%d/%d\n", nCopy, nDel, nIns); */
  if( p->nEdit>=3 ){
    if( p->aEdit[p->nEdit-1]==0 ){
      if( p->aEdit[p->nEdit-2]==0 ){
        p->aEdit[p->nEdit-3] += nCopy;
        p->aEdit[p->nEdit-2] += nDel;
        p->aEdit[p->nEdit-1] += nIns;
23580
23581
23582
23583
23584
23585
23586
23587

23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610

23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626

23627
23628
23629
23630
23631
23632

23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649

23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669

23670
23671
23672
23673
23674

23675
23676
23677
23678
23679
23680
23681

23682
23683

23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694








23695
23696
23697
23698
23699
23700
23701
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







-
+








-













-
+















-
+
-




-
+













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





-
+




-
+







+

-
+



-

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







    }
    if( nCopy==0 && nDel==0 ){
      p->aEdit[p->nEdit-1] += nIns;
      return 0;
    }
  }
  if( p->nEdit+3>p->nEditAlloc ){
    int const rc = expandEdit(p, p->nEdit*2 + 15);
    int const rc = fsl__diff_expand_edit(p, p->nEdit*2 + 15);
    if(rc) return rc;
    else if( p->aEdit==0 ) return 0;
  }
  p->aEdit[p->nEdit++] = nCopy;
  p->aEdit[p->nEdit++] = nDel;
  p->aEdit[p->nEdit++] = nIns;
  return 0;
}


/**
    Do a single step in the difference.  Compute a sequence of
    copy/delete/insert steps that will convert lines iS1 through iE1-1
    of the input into lines iS2 through iE2-1 of the output and write
    that sequence into the difference context.
   
    The algorithm is to find a block of common text near the middle of
    the two segments being diffed.  Then recursively compute
    differences on the blocks before and after that common segment.
    Special cases apply if either input segment is empty or if the two
    segments have no text in common.
 */
static int diff_step(DContext *p, int iS1, int iE1, int iS2, int iE2){
static int diff_step(fsl_diff_cx *p, int iS1, int iE1, int iS2, int iE2){
  int iSX, iEX, iSY, iEY;
  int rc = 0;
  if( iE1<=iS1 ){
    /* The first segment is empty */
    if( iE2>iS2 ){
      rc = appendTriple(p, 0, 0, iE2-iS2);
    }
    return rc;
  }
  if( iE2<=iS2 ){
    /* The second segment is empty */
    return appendTriple(p, 0, iE1-iS1, 0);
  }

  /* Find the longest matching segment between the two sequences */
  longestCommonSequence(p, iS1, iE1, iS2, iE2, &iSX, &iEX, &iSY, &iEY);
  fsl__diff_lcs(p, iS1, iE1, iS2, iE2, &iSX, &iEX, &iSY, &iEY);

  if( iEX>iSX ){
    /* A common segment has been found.
       Recursively diff either side of the matching segment */
    rc = diff_step(p, iS1, iSX, iS2, iSY);
    if( !rc){
    if(!rc){
      if(iEX>iSX){
        rc = appendTriple(p, iEX - iSX, 0, 0);
      }
      if(!rc) rc = diff_step(p, iEX, iE1, iEY, iE2);
    }
  }else{
    /* The two segments have nothing in common.  Delete the first then
       insert the second. */
    rc = appendTriple(p, 0, iE1-iS1, iE2-iS2);
  }
  return rc;
}

/**
    Compute the differences between two files already loaded into
    the DContext structure.
   
int fsl__diff_all(fsl_diff_cx * const p){
    A divide and conquer technique is used.  We look for a large
    block of common text that is in the middle of both files.  Then
    compute the difference on those parts of the file before and
    after the common block.  This technique is fast, but it does
    not necessarily generate the minimum difference set.  On the
    other hand, we do not need a minimum difference set, only one
    that makes sense to human readers, which this algorithm does.
   
    Any common text at the beginning and end of the two files is
    removed before starting the divide-and-conquer algorithm.
   
    Returns 0 on succes, FSL_RC_OOM on an allocation error.
 */
static int diff_all(DContext *p){
  int mnE, iS, iE1, iE2;
  int rc = 0;
  /* Carve off the common header and footer */
  iE1 = p->nFrom;
  iE2 = p->nTo;
  while( iE1>0 && iE2>0 && p->same_fn(&p->aFrom[iE1-1], &p->aTo[iE2-1]) ){
  while( iE1>0 && iE2>0 && p->cmpLine(&p->aFrom[iE1-1], &p->aTo[iE2-1])==0 ){
    iE1--;
    iE2--;
  }
  mnE = iE1<iE2 ? iE1 : iE2;
  for(iS=0; iS<mnE && p->same_fn(&p->aFrom[iS],&p->aTo[iS]); iS++){}
  for(iS=0; iS<mnE && p->cmpLine(&p->aFrom[iS],&p->aTo[iS])==0; iS++){}

  /* do the difference */
  if( iS>0 ){
    rc = appendTriple(p, iS, 0, 0);
    if(rc) return rc;
  }
  rc = diff_step(p, iS, iE1, iS, iE2);
  //fsl__dump_triples(p, __FILE__, __LINE__);
  if(rc) return rc;
  if( iE1<p->nFrom ){
  else if( iE1<p->nFrom ){
    rc = appendTriple(p, p->nFrom - iE1, 0, 0);
    if(rc) return rc;
  }

  /* Terminate the COPY/DELETE/INSERT triples with three zeros */
  rc = expandEdit(p, p->nEdit+3);
  if(rc) return rc;
  else if( p->aEdit ){
    p->aEdit[p->nEdit++] = 0;
    p->aEdit[p->nEdit++] = 0;
    p->aEdit[p->nEdit++] = 0;
  rc = fsl__diff_expand_edit(p, p->nEdit+3);
  if(0==rc){
    if(p->aEdit ){
      p->aEdit[p->nEdit++] = 0;
      p->aEdit[p->nEdit++] = 0;
      p->aEdit[p->nEdit++] = 0;
      //fsl__dump_triples(p, __FILE__, __LINE__);
    }
  }
  return rc;
}


/*
   Attempt to shift insertion or deletion blocks so that they begin and
23724
23725
23726
23727
23728
23729
23730
23731

23732
23733
23734
23735
23736

23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749



23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762



23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775



23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788



23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799

23800
23801
23802
23803
23804
23805
23806
23807
23808

23809
23810
23811
23812
23813
23814


23815
23816
23817
23818
23819
23820
23821
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
24131
24132
24133
24134



24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147



24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170

24171
24172
24173
24174
24175


24176
24177
24178
24179
24180
24181
24182
24183
24184







-
+





+










-
-
-
+
+
+










-
-
-
+
+
+










-
-
-
+
+
+










-
-
-
+
+
+











+








-
+




-
-
+
+







       +   return x*20;               +   return x*20;
       +}                             +}
                                      +
        int func3(int x){              int func3(int x){
           return x/5;                    return x/5;
        }                              }
*/
static void diff_optimize(DContext *p){
void fsl__diff_optimize(fsl_diff_cx * const p){
  int r;       /* Index of current triple */
  int lnFrom;  /* Line number in p->aFrom */
  int lnTo;    /* Line number in p->aTo */
  int cpy, del, ins;

  //fsl__dump_triples(p, __FILE__, __LINE__);
  lnFrom = lnTo = 0;
  for(r=0; r<p->nEdit; r += 3){
    cpy = p->aEdit[r];
    del = p->aEdit[r+1];
    ins = p->aEdit[r+2];
    lnFrom += cpy;
    lnTo += cpy;

    /* Shift insertions toward the beginning of the file */
    while( cpy>0 && del==0 && ins>0 ){
      DLine *pTop = &p->aFrom[lnFrom-1];  /* Line before start of insert */
      DLine *pBtm = &p->aTo[lnTo+ins-1];  /* Last line inserted */
      if( p->same_fn(pTop, pBtm)==0 ) break;
      fsl_dline *pTop = &p->aFrom[lnFrom-1];  /* Line before start of insert */
      fsl_dline *pBtm = &p->aTo[lnTo+ins-1];  /* Last line inserted */
      if( p->cmpLine(pTop, pBtm) ) break;
      if( LENGTH(pTop+1)+LENGTH(pBtm)<=LENGTH(pTop)+LENGTH(pBtm-1) ) break;
      lnFrom--;
      lnTo--;
      p->aEdit[r]--;
      p->aEdit[r+3]++;
      cpy--;
    }

    /* Shift insertions toward the end of the file */
    while( r+3<p->nEdit && p->aEdit[r+3]>0 && del==0 && ins>0 ){
      DLine *pTop = &p->aTo[lnTo];       /* First line inserted */
      DLine *pBtm = &p->aTo[lnTo+ins];   /* First line past end of insert */
      if( p->same_fn(pTop, pBtm)==0 ) break;
      fsl_dline *pTop = &p->aTo[lnTo];       /* First line inserted */
      fsl_dline *pBtm = &p->aTo[lnTo+ins];   /* First line past end of insert */
      if( p->cmpLine(pTop, pBtm) ) break;
      if( LENGTH(pTop)+LENGTH(pBtm-1)<=LENGTH(pTop+1)+LENGTH(pBtm) ) break;
      lnFrom++;
      lnTo++;
      p->aEdit[r]++;
      p->aEdit[r+3]--;
      cpy++;
    }

    /* Shift deletions toward the beginning of the file */
    while( cpy>0 && del>0 && ins==0 ){
      DLine *pTop = &p->aFrom[lnFrom-1];     /* Line before start of delete */
      DLine *pBtm = &p->aFrom[lnFrom+del-1]; /* Last line deleted */
      if( p->same_fn(pTop, pBtm)==0 ) break;
      fsl_dline *pTop = &p->aFrom[lnFrom-1];     /* Line before start of delete */
      fsl_dline *pBtm = &p->aFrom[lnFrom+del-1]; /* Last line deleted */
      if( p->cmpLine(pTop, pBtm) ) break;
      if( LENGTH(pTop+1)+LENGTH(pBtm)<=LENGTH(pTop)+LENGTH(pBtm-1) ) break;
      lnFrom--;
      lnTo--;
      p->aEdit[r]--;
      p->aEdit[r+3]++;
      cpy--;
    }

    /* Shift deletions toward the end of the file */
    while( r+3<p->nEdit && p->aEdit[r+3]>0 && del>0 && ins==0 ){
      DLine *pTop = &p->aFrom[lnFrom];     /* First line deleted */
      DLine *pBtm = &p->aFrom[lnFrom+del]; /* First line past end of delete */
      if( p->same_fn(pTop, pBtm)==0 ) break;
      fsl_dline *pTop = &p->aFrom[lnFrom];     /* First line deleted */
      fsl_dline *pBtm = &p->aFrom[lnFrom+del]; /* First line past end of delete */
      if( p->cmpLine(pTop, pBtm) ) break;
      if( LENGTH(pTop)+LENGTH(pBtm-1)<=LENGTH(pTop)+LENGTH(pBtm) ) break;
      lnFrom++;
      lnTo++;
      p->aEdit[r]++;
      p->aEdit[r+3]--;
      cpy++;
    }

    lnFrom += del;
    lnTo += ins;
  }
  //fsl__dump_triples(p, __FILE__, __LINE__);
}


/*
   Given a raw diff p[] in which the p->aEdit[] array has been filled
   in, compute a context diff into pOut.
*/
static int contextDiff(
  DContext *p,      /* The difference */
  fsl_diff_cx *p,      /* The difference */
  DiffOutState *pOut,       /* Output a context diff to here */
  ReCompiled *pRe,  /* Only show changes that match this regex */
  u64 diffFlags     /* Flags controlling the diff format */
){
  DLine *A;     /* Left side of the diff */
  DLine *B;     /* Right side of the diff */
  fsl_dline *A;     /* Left side of the diff */
  fsl_dline *B;     /* Right side of the diff */
  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 */
23896
23897
23898
23899
23900
23901
23902
23903

23904
23905
23906
23907
23908
23909
23910
24259
24260
24261
24262
24263
24264
24265

24266
24267
24268
24269
24270
24271
24272
24273







-
+







      nb += R[r+i*3];
    }

    /* Show the header for this block, or if we are doing a modified
       context diff that contains line numbers, show the separator from
       the previous block.
    */
    nChunk++;
    ++nChunk;
    if( showLn ){
      if( !showDivider ){
        /* Do not show a top divider */
        showDivider = 1;
      }else if( html ){
        rc = diff_outf(pOut, "<span class=\"fsl-diff-hr\">%.80c</span>\n", '.');
      }else{
24045
24046
24047
24048
24049
24050
24051
24052

24053
24054
24055
24056
24057
24058
24059
24408
24409
24410
24411
24412
24413
24414

24415
24416
24417
24418
24419
24420
24421
24422







-
+







   width characters.  Translate tabs into spaces.  Add newlines if col
   is SBS_TXTB.  Translate HTML characters if escHtml is true.  Pad the
   rendering to width bytes if col is SBS_TXTA and escHtml is false.
  
   This comment contains multibyte unicode characters (�, �, �) in order
   to test the ability of the diff code to handle such characters.
*/
static int sbsWriteText(SbsLine *p, DLine *pLine, int col){
static int sbsWriteText(SbsLine *p, fsl_dline *pLine, int col){
  fsl_buffer *pCol = p->apCols[col];
  int rc = 0;
  int n = pLine->n;
  int i;   /* Number of input characters consumed */
  int k;   /* Cursor position */
  int needEndSpan = 0;
  const char *zIn = pLine->z;
24291
24292
24293
24294
24295
24296
24297
24298

24299
24300

24301
24302
24303
24304
24305
24306
24307
24654
24655
24656
24657
24658
24659
24660

24661
24662

24663
24664
24665
24666
24667
24668
24669
24670







-
+

-
+








/*
   Write out lines that have been edited.  Adjust the highlight to cover
   only those parts of the line that actually changed.
*/
static int sbsWriteLineChange(
  SbsLine *p,          /* The SBS output line */
  DLine *pLeft,        /* Left line of the change */
  fsl_dline *pLeft,        /* Left line of the change */
  int lnLeft,          /* Line number for the left line */
  DLine *pRight,       /* Right line of the change */
  fsl_dline *pRight,       /* Right line of the change */
  int lnRight          /* Line number of the right line */
){
  int rc = 0;
  int nLeft;           /* Length of left line in bytes */
  int nRight;          /* Length of right line in bytes */
  int nShort;          /* Shortest of left and right */
  int nPrefix;         /* Length of common prefix */
24464
24465
24466
24467
24468
24469
24470
24471

24472
24473
24474
24475
24476
24477
24478
24827
24828
24829
24830
24831
24832
24833

24834
24835
24836
24837
24838
24839
24840
24841







-
+







   The current algorithm is as follows:
  
   (1) Remove leading and trailing whitespace.
   (2) Truncate both strings to at most 250 characters
   (3) Find the length of the longest common subsequence
   (4) Longer common subsequences yield lower scores.
*/
static int match_dline(DLine *pA, DLine *pB){
static int match_dline(fsl_dline *pA, fsl_dline *pB){
  const char *zA;            /* Left string */
  const char *zB;            /* right string */
  int nA;                    /* Bytes in zA[] */
  int nB;                    /* Bytes in zB[] */
  int avg;                   /* Average length of A and B */
  int i, j, k;               /* Loop counters */
  int best = 0;              /* Longest match found so far */
24544
24545
24546
24547
24548
24549
24550
24551
24552


24553
24554
24555
24556
24557
24558
24559
24907
24908
24909
24910
24911
24912
24913


24914
24915
24916
24917
24918
24919
24920
24921
24922







-
-
+
+







   Algorithm:  Wagner's minimum edit-distance algorithm, modified by
   adding a cost to each match based on how well the two rows match
   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 unsigned char *sbsAlignment(
   DLine *aLeft, int nLeft,       /* Text on the left */
   DLine *aRight, int nRight      /* Text on the right */
   fsl_dline *aLeft, int nLeft,       /* Text on the left */
   fsl_dline *aRight, int nRight      /* Text on the right */
){
  int i, j, k;                 /* Loop counters */
  int *a;                      /* One row of the Wagner matrix */
  int *pToFree;                /* Space that needs to be freed */
  unsigned char *aM;           /* Wagner result matrix */
  int nMatch, iMatch;          /* Number of matching lines and match score */
  int mnLen;                   /* MIN(nLeft, nRight) */
24683
24684
24685
24686
24687
24688
24689
24690

24691
24692
24693
24694
24695
24696


24697
24698
24699
24700
24701
24702
24703
25046
25047
25048
25049
25050
25051
25052

25053
25054
25055
25056
25057


25058
25059
25060
25061
25062
25063
25064
25065
25066







-
+




-
-
+
+







}

/*
   Given a diff context in which the aEdit[] array has been filled
   in, compute a side-by-side diff into pOut.
*/
static int sbsDiff(
  DContext *p,       /* The computed diff */
  fsl_diff_cx *p,       /* The computed diff */
  DiffOutState *pOut,        /* Write the results here */
  ReCompiled *pRe,   /* Only show changes that match this regex */
  u64 diffFlags      /* Flags controlling the diff */
){
  DLine *A;     /* Left side of the diff */
  DLine *B;     /* Right side of the diff */
  fsl_dline *A;     /* Left side of the diff */
  fsl_dline *B;     /* Right side of the diff */
  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 */
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
25334
25335
25336
25337
25338
25339
25340

25341
25342
25343
25344
25345
25346
25347







-







  for( i = 0; i < (int)(sizeof(aCols)/sizeof(aCols[0])); ++i ){
    fsl_buffer_clear(&aCols[i]);
  }
  fsl_buffer_clear(&unesc);
  return rc;
}


/** @internal

    Performs a text diff on two buffers, either streaming the
    output to the 3rd argument or returning the results as an
    array of copy/delete/insert triples via the final argument.

    ONE of the 3rd or final arguments must be set and the other
25011
25012
25013
25014
25015
25016
25017
25018

25019
25020
25021
25022
25023
25024
25025




25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040

25041
25042

25043
25044
25045


25046
25047
25048


25049
25050
25051
25052
25053
25054
25055
25056
25057


25058
25059
25060
25061
25062
25063
25064
25065
25066
25067

25068
25069

25070
25071

25072

25073
25074
25075
25076
25077
25078
25079
25373
25374
25375
25376
25377
25378
25379

25380
25381
25382
25383
25384
25385


25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401

25402

25403
25404

25405
25406


25407
25408
25409


25410
25411
25412
25413





25414

25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425

25426
25427
25428
25429
25430

25431
25432
25433
25434
25435
25436
25437
25438
25439
25440







-
+





-
-
+
+
+
+












-

-
+

-
+

-
-
+
+

-
-
+
+


-
-
-
-
-

-
+
+









-
+


+

-
+

+







  /* ReCompiled *pRe, */ /* Only output changes where this Regexp matches */
  short contextLines,
  short sbsWidth,
  int diffFlags_,    /* FSL_DIFF_* flags */
  int ** outRaw
){
  int rc;
  DContext c;
  fsl_diff_cx c = fsl_diff_cx_empty;
  uint64_t diffFlags = fsl_diff_flags_convert(diffFlags_)
    | DIFF_CONTEXT_EX /* to shoehorn newer 0-handling semantics into
                         older (ported-in) code. */;
  if(!pA || !pB || (out && outRaw) || (!out && !outRaw)) return FSL_RC_MISUSE;
  else if(contextLines<0) contextLines = 5;
  else if(contextLines & ~LENGTH_MASK) contextLines = (int)LENGTH_MASK;
  diffFlags |= (LENGTH_MASK & contextLines);
  else if(contextLines & ~FSL_LINE_LENGTH_MASK){
    contextLines = (int)FSL_LINE_LENGTH_MASK;
  }
  diffFlags |= (FSL_LINE_LENGTH_MASK & contextLines);
  /* Encode SBS width... */
  if(sbsWidth<0
     || ((DIFF_SIDEBYSIDE & diffFlags) && !sbsWidth) ) sbsWidth = 80;
  if(sbsWidth) diffFlags |= DIFF_SIDEBYSIDE;
  diffFlags |= ((int)(sbsWidth & 0xFF))<<16;
  if( diffFlags & DIFF_INVERT ){
    fsl_buffer const *pTemp = pA;
    pA = pB;
    pB = pTemp;
  }

  /* Prepare the input files */
  memset(&c, 0, sizeof(c));
  if( (diffFlags & DIFF_IGNORE_ALLWS)==DIFF_IGNORE_ALLWS ){
    c.same_fn = same_dline_ignore_allws;
    c.cmpLine = fsl_dline_cmp_ignore_ws;
  }else{
    c.same_fn = same_dline;
    c.cmpLine = fsl_dline_cmp;
  }
  rc = break_into_lines(fsl_buffer_cstr(pA), fsl_buffer_size(pA),
                        &c.nFrom, &c.aFrom, diffFlags);
  rc = fsl_break_into_dlines(fsl_buffer_cstr(pA), (fsl_int_t)fsl_buffer_size(pA),
                             (uint32_t*)&c.nFrom, &c.aFrom, diffFlags);
  if(rc) goto end;
  rc = break_into_lines(fsl_buffer_cstr(pB), fsl_buffer_size(pB),
                        &c.nTo, &c.aTo, diffFlags);
  rc = fsl_break_into_dlines(fsl_buffer_cstr(pB), (fsl_int_t)fsl_buffer_size(pB),
                             (uint32_t*)&c.nTo, &c.aTo, diffFlags);
  if(rc) goto end;

  if( c.aFrom==0 || c.aTo==0 ){
    /* Empty diff */
    goto end;
  }

  /* Compute the difference */
  rc = diff_all(&c);
  rc = fsl__diff_all(&c);
  //fsl__dump_triples(&c, __FILE__, __LINE__);
  if(rc) goto end;
  if( (diffFlags & DIFF_NOTTOOBIG)!=0 ){
    int i, m, n;
    int *a = c.aEdit;
    int mx = c.nEdit;
    for(i=m=n=0; i<mx; i+=3){ m += a[i]; n += a[i+1]+a[i+2]; }
    if( !n || n>10000 ){
      rc = FSL_RC_RANGE;
      /* diff_errmsg(pOut, DIFF_TOO_MANY_CHANGES, diffFlags); */
      goto end;;
      goto end;
    }
  }
  //fsl__dump_triples(&c, __FILE__, __LINE__);
  if( (diffFlags & DIFF_NOOPT)==0 ){
    diff_optimize(&c);
    fsl__diff_optimize(&c);
  }
  //fsl__dump_triples(&c, __FILE__, __LINE__);

  if( out ){
    /* Compute a context or side-by-side diff */
    /* MISSING: regex support */
    DiffOutState dos = DiffOutState_empty;
    dos.out = out;
    dos.oState = outState;
25119
25120
25121
25122
25123
25124
25125
25126
25127

25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25480
25481
25482
25483
25484
25485
25486


25487

25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502

25503
25504
25505
25506
25507
25508
25509







-
-
+
-















-







                            int diffFlags ){
  return (pA && pB && pOut)
    ? fsl_diff_text_impl(pA, pB, fsl_output_f_buffer, pOut,
                         contextLines, sbsWidth, diffFlags, NULL )
    : FSL_RC_MISUSE;
}

#undef TO_BE_STATIC
#undef LENGTH_MASK
#undef MARKER
#undef LENGTH_MASK_SZ
#undef LENGTH
#undef DIFF_CONTEXT_MASK
#undef DIFF_WIDTH_MASK
#undef DIFF_IGNORE_EOLWS
#undef DIFF_IGNORE_ALLWS
#undef DIFF_SIDEBYSIDE
#undef DIFF_VERBOSE
#undef DIFF_BRIEF
#undef DIFF_HTML
#undef DIFF_LINENO
#undef DIFF_NOOPT
#undef DIFF_INVERT
#undef DIFF_CONTEXT_EX
#undef DIFF_NOTTOOBIG
#undef DIFF_STRIP_EOLCR
#undef minInt
#undef SBS_LNA
#undef SBS_TXTA
#undef SBS_MKR
#undef SBS_LNB
#undef SBS_TXTB
#undef ANN_FILE_VERS
#undef ANN_FILE_ANCEST
25169
25170
25171
25172
25173
25174
25175






















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































25176
25177
25178
25179
25180
25181
25182
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
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
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
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
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
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
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
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
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
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
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
26868
26869
26870
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
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
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
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
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







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







#undef ANSI_RESET_COLOR
#undef ANSI_RESET_ALL
#undef ANSI_RESET
#undef ANSI_DIFF_ADD
#undef ANSI_DIFF_MOD
#undef ANSI_DIFF_RM
/* end of file diff.c */
/* start of file 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_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);
  fsl_free(cx->aEdit);
  cx->aFrom = cx->aTo = NULL;
  cx->aEdit = NULL;
  *cx = fsl_diff_cx_empty;
}

/**
   Counts the number of lines in the first n bytes of the given 
   string. If n<0 then fsl_strlen() is used to count it. 

   It includes the last line in the count even if it lacks the \n
   terminator. If an empty string is passed in, the number of lines
   is zero.

   For the purposes of this function, a string is considered empty if
   it contains no characters OR contains only NUL characters.

   If the input appears to be plain text it returns true and, if nOut
   is not NULL, writes the number of lines there. If the input appears
   to be binary, returns false and does not modify nOut.
*/
FSL_EXPORT bool fsl_count_lines(const char *z, fsl_int_t n, uint32_t * nOut );

bool fsl_count_lines(const char *z, fsl_int_t n, uint32_t * nOut ){
  uint32_t nLine;
  const char *zNL, *z2;
  if(n<0) n = (fsl_int_t)fsl_strlen(z);
  for(nLine=0, z2=z; (zNL = strchr(z2,'\n'))!=0; z2=zNL+1, nLine++){}
  if( z2[0]!='\0' ){
    nLine++;
    do{ z2++; }while( z2[0]!='\0' );
  }
  if( n!=(fsl_int_t)(z2-z) ) return false;
  if( nOut ) *nOut = nLine;
  return true;
}

int fsl_break_into_dlines(const char *z, fsl_int_t n,
                          uint32_t *pnLine,
                          fsl_dline **pOut, uint64_t diffFlags){
  uint32_t nLine, i, k, nn, s, x;
  uint64_t h, h2;
  fsl_dline *a = 0;
  const char *zNL;

  if(!z || !n){
    *pnLine = 0;
    *pOut = NULL;
    return 0;
  }
  if( !fsl_count_lines(z, n, &nLine) ){
    return FSL_RC_DIFF_BINARY;
  }
  assert( nLine>0 || z[0]=='\0' );
  if(nLine>0){
    a = fsl_malloc( sizeof(a[0])*nLine );
    if(!a) return FSL_RC_OOM;
    memset(a, 0, sizeof(a[0])*nLine);
  }else{
    *pnLine = 0;
    *pOut = a;
    return 0;
  }
  assert( a );
  i = 0;
  do{
    zNL = strchr(z,'\n');
    if( zNL==0 ) zNL = z+n;
    nn = (uint32_t)(zNL - z);
    if( nn>FSL_LINE_LENGTH_MASK ){
      fsl_free(a);
      *pOut = 0;
      *pnLine = 0;
      return FSL_RC_DIFF_BINARY;
    }
    a[i].z = z;
    k = nn;
    if( diffFlags & FSL_DIFF2_STRIP_EOLCR ){
      if( k>0 && z[k-1]=='\r' ){ k--; }
    }
    a[i].n = k;
    s = 0;
    if( diffFlags & FSL_DIFF2_IGNORE_EOLWS ){
      while( k>0 && fsl_isspace(z[k-1]) ){ k--; }
    }
    if( (diffFlags & FSL_DIFF2_IGNORE_ALLWS)
        ==FSL_DIFF2_IGNORE_ALLWS ){
      uint32_t numws = 0;
      while( s<k && fsl_isspace(z[s]) ){ ++s; }
      for(h=0, x=s; x<k; ++x){
        char c = z[x];
        if( fsl_isspace(c) ){
          ++numws;
        }else{
          h = (h^c)*9000000000000000041LL;
        }
      }
      k -= numws;
    }else{
      uint32_t k2 = k & ~0x7;
      uint64_t m;
      for(h=0, x=s; x<k2; x += 8){
        memcpy(&m, z+x, 8);
        h = (h^m)*9000000000000000041LL;
      }
      m = 0;
      memcpy(&m, z+x, k-k2);
      h ^= m;
    }
    a[i].indent = s;
    a[i].h = h = ((h%281474976710597LL)<<FSL_LINE_LENGTH_MASK_SZ) | (k-s);
    h2 = h % nLine;
    a[i].iNext = a[h2].iHash;
    a[h2].iHash = i+1;
    z += nn+1; n -= nn+1;
    i++;
  }while( zNL[0]!='\0' && zNL[1]!='\0' );
  assert( i==nLine );

  *pnLine = nLine;
  *pOut = a;
  return 0;
}

int fsl_dline_cmp(const fsl_dline * const pA,
                  const fsl_dline * const pB){
  if( pA->h!=pB->h ) return 1;
  return memcmp(pA->z,pB->z, pA->h&FSL_LINE_LENGTH_MASK);
}

int fsl_dline_cmp_ignore_ws(const fsl_dline * const pA,
                            const fsl_dline * const pB){
  unsigned short a = pA->indent, b = pB->indent;
  if( pA->h==pB->h ){
    while( a<pA->n || b<pB->n ){
      if( a<pA->n && b<pB->n && pA->z[a++] != pB->z[b++] ) return 1;
      while( a<pA->n && fsl_isspace(pA->z[a])) ++a;
      while( b<pB->n && fsl_isspace(pB->z[b])) ++b;
    }
    return pA->n-a != pB->n-b;
  }
  return 1;
}

/*
** The two text segments zLeft and zRight are known to be different on
** both ends, but they might have  a common segment in the middle.  If
** they do not have a common segment, return 0.  If they do have a large
** common segment, return non-0 and before doing so set:
**
**   aLCS[0] = start of the common segment in zLeft
**   aLCS[1] = end of the common segment in zLeft
**   aLCS[2] = start of the common segment in zLeft
**   aLCS[3] = end of the common segment in zLeft
**
** This computation is for display purposes only and does not have to be
** optimal or exact.
*/
static int textLCS2(
  const char *zLeft,  uint32_t nA, /* String on the left */
  const char *zRight, uint32_t nB, /* String on the right */
  uint32_t *aLCS                   /* Identify bounds of LCS here */
){
  const unsigned char *zA = (const unsigned char*)zLeft;    /* left string */
  const unsigned char *zB = (const unsigned char*)zRight;   /* right string */
  uint32_t i, j, k;               /* Loop counters */
  uint32_t lenBest = 0;           /* Match length to beat */

  for(i=0; i<nA-lenBest; i++){
    unsigned char cA = zA[i];
    if( (cA&0xc0)==0x80 ) continue;
    for(j=0; j<nB-lenBest; j++ ){
      if( zB[j]==cA ){
        for(k=1; j+k<nB && i+k<nA && zB[j+k]==zA[i+k]; k++){}
        while( (zB[j+k]&0xc0)==0x80 ){ k--; }
        if( k>lenBest ){
          lenBest = k;
          aLCS[0] = i;
          aLCS[1] = i+k;
          aLCS[2] = j;
          aLCS[3] = j+k;
        }
      }
    }
  }
  return lenBest>0;
}

/*
** Find the smallest spans that are different between two text strings
** that are known to be different on both ends. Returns the number
** of entries in p->a which get populated.
*/
static unsigned short textLineChanges(
  const char *zLeft,  uint32_t nA, /* String on the left */
  const char *zRight, uint32_t nB, /* String on the right */
  fsl_dline_change * const p             /* Write results here */
){
  p->n = 1;
  p->a[0].iStart1 = 0;
  p->a[0].iLen1 = nA;
  p->a[0].iStart2 = 0;
  p->a[0].iLen2 = nB;
  p->a[0].isMin = 0;
  while( p->n<fsl_dline_change_max_spans-1 ){
    int mxi = -1;
    int mxLen = -1;
    int x, i;
    uint32_t aLCS[4];
    struct fsl_dline_change_span *a, *b;
    for(i=0; i<p->n; i++){
      if( p->a[i].isMin ) continue;
      x = p->a[i].iLen1;
      if( p->a[i].iLen2<x ) x = p->a[i].iLen2;
      if( x>mxLen ){
        mxLen = x;
        mxi = i;
      }
    }
    if( mxLen<6 ) break;
    x = textLCS2(zLeft + p->a[mxi].iStart1, p->a[mxi].iLen1,
                 zRight + p->a[mxi].iStart2, p->a[mxi].iLen2, aLCS);
    if( x==0 ){
      p->a[mxi].isMin = 1;
      continue;
    }
    a = p->a+mxi;
    b = a+1;
    if( mxi<p->n-1 ){
      memmove(b+1, b, sizeof(*b)*(p->n-mxi-1));
    }
    p->n++;
    b->iStart1 = a->iStart1 + aLCS[1];
    b->iLen1 = a->iLen1 - aLCS[1];
    a->iLen1 = aLCS[0];
    b->iStart2 = a->iStart2 + aLCS[3];
    b->iLen2 = a->iLen2 - aLCS[3];
    a->iLen2 = aLCS[2];
    b->isMin = 0;
  }
  return p->n;
}

/*
** Return true if the string starts with n spaces
*/
static int allSpaces(const char *z, int n){
  int i;
  for(i=0; i<n && fsl_isspace(z[i]); ++i){}
  return i==n;
}

/*
** Try to improve the human-readability of the fsl_dline_change p.
**
** (1)  If the first change span shows a change of indentation, try to
**      move that indentation change to the left margin.
**
** (2)  Try to shift changes so that they begin or end with a space.
*/
static void improveReadability(
  const char *zA,  /* Left line of the change */
  const char *zB,  /* Right line of the change */
  fsl_dline_change * const p /* The fsl_dline_change to be adjusted */
){
  int j, n, len;
  if( p->n<1 ) return;

  /* (1) Attempt to move indentation changes to the left margin */
  if( p->a[0].iLen1==0
   && (len = p->a[0].iLen2)>0
   && (j = p->a[0].iStart2)>0
   && zB[0]==zB[j]
   && allSpaces(zB, j)
  ){
    for(n=1; n<len && n<j && zB[j]==zB[j+n]; n++){}
    if( n<len ){
      memmove(&p->a[1], &p->a[0], sizeof(p->a[0])*p->n);
      p->n++;
      p->a[0] = p->a[1];
      p->a[1].iStart2 += n;
      p->a[1].iLen2 -= n;
      p->a[0].iLen2 = n;
    }
    p->a[0].iStart1 = 0;
    p->a[0].iStart2 = 0;
  }else
  if( p->a[0].iLen2==0
   && (len = p->a[0].iLen1)>0
   && (j = p->a[0].iStart1)>0
   && zA[0]==zA[j]
   && allSpaces(zA, j)
  ){
    for(n=1; n<len && n<j && zA[j]==zA[j+n]; n++){}
    if( n<len ){
      memmove(&p->a[1], &p->a[0], sizeof(p->a[0])*p->n);
      p->n++;
      p->a[0] = p->a[1];
      p->a[1].iStart1 += n;
      p->a[1].iLen1 -= n;
      p->a[0].iLen1 = n;
    }
    p->a[0].iStart1 = 0;
    p->a[0].iStart2 = 0;
  }

  /* (2) Try to shift changes so that they begin or end with a
  ** space.  (TBD) */
}

void fsl_dline_change_spans(const fsl_dline *pLeft, const fsl_dline *pRight,
                            fsl_dline_change * const p){
  /* fossil(1) counterpart ==> diff.c oneLineChange() */
  int nLeft;           /* Length of left line in bytes */
  int nRight;          /* Length of right line in bytes */
  int nShort;          /* Shortest of left and right */
  int nPrefix;         /* Length of common prefix */
  int nSuffix;         /* Length of common suffix */
  int nCommon;         /* Total byte length of suffix and prefix */
  const char *zLeft;   /* Text of the left line */
  const char *zRight;  /* Text of the right line */
  int nLeftDiff;       /* nLeft - nPrefix - nSuffix */
  int nRightDiff;      /* nRight - nPrefix - nSuffix */

  nLeft = pLeft->n;
  zLeft = pLeft->z;
  nRight = pRight->n;
  zRight = pRight->z;
  nShort = nLeft<nRight ? nLeft : nRight;

  nPrefix = 0;
  while( nPrefix<nShort && zLeft[nPrefix]==zRight[nPrefix] ){
    nPrefix++;
  }
  if( nPrefix<nShort ){
    while( nPrefix>0 && (zLeft[nPrefix]&0xc0)==0x80 ) nPrefix--;
  }
  nSuffix = 0;
  if( nPrefix<nShort ){
    while( nSuffix<nShort
           && zLeft[nLeft-nSuffix-1]==zRight[nRight-nSuffix-1] ){
      nSuffix++;
    }
    if( nSuffix<nShort ){
      while( nSuffix>0 && (zLeft[nLeft-nSuffix]&0xc0)==0x80 ) nSuffix--;
    }
    if( nSuffix==nLeft || nSuffix==nRight ) nPrefix = 0;
  }
  nCommon = nPrefix + nSuffix;

  /* If the prefix and suffix overlap, that means that we are dealing with
  ** a pure insertion or deletion of text that can have multiple alignments.
  ** Try to find an alignment to begins and ends on whitespace, or on
  ** punctuation, rather than in the middle of a name or number.
  */
  if( nCommon > nShort ){
    int iBest = -1;
    int iBestVal = -1;
    int i;
    int nLong = nLeft<nRight ? nRight : nLeft;
    int nGap = nLong - nShort;
    for(i=nShort-nSuffix; i<=nPrefix; i++){
       int iVal = 0;
       char c = zLeft[i];
       if( fsl_isspace(c) ){
         iVal += 5;
       }else if( !fsl_isalnum(c) ){
         iVal += 2;
       }
       c = zLeft[i+nGap-1];
       if( fsl_isspace(c) ){
         iVal += 5;
       }else if( !fsl_isalnum(c) ){
         iVal += 2;
       }
       if( iVal>iBestVal ){
         iBestVal = iVal;
         iBest = i;
       }
    }
    nPrefix = iBest;
    nSuffix = nShort - nPrefix;
    nCommon = nPrefix + nSuffix;
  }

  /* A single chunk of text inserted */
  if( nCommon==nLeft ){
    p->n = 1;
    p->a[0].iStart1 = nPrefix;
    p->a[0].iLen1 = 0;
    p->a[0].iStart2 = nPrefix;
    p->a[0].iLen2 = nRight - nCommon;
    improveReadability(zLeft, zRight, p);
    return;
  }

  /* A single chunk of text deleted */
  if( nCommon==nRight ){
    p->n = 1;
    p->a[0].iStart1 = nPrefix;
    p->a[0].iLen1 = nLeft - nCommon;
    p->a[0].iStart2 = nPrefix;
    p->a[0].iLen2 = 0;
    improveReadability(zLeft, zRight, p);
    return;
  }

  /* At this point we know that there is a chunk of text that has
  ** changed between the left and the right.  Check to see if there
  ** is a large unchanged section in the middle of that changed block.
  */
  nLeftDiff = nLeft - nCommon;
  nRightDiff = nRight - nCommon;
  if( nLeftDiff >= 4
   && nRightDiff >= 4
   && textLineChanges(&zLeft[nPrefix], nLeftDiff,
                      &zRight[nPrefix], nRightDiff, p)>1
  ){
    int i;
    for(i=0; i<p->n; i++){
      p->a[i].iStart1 += nPrefix;
      p->a[i].iStart2 += nPrefix;
    }
    improveReadability(zLeft, zRight, p);
    return;
  }

  /* If all else fails, show a single big change between left and right */
  p->n = 1;
  p->a[0].iStart1 = nPrefix;
  p->a[0].iLen1 = nLeft - nCommon;
  p->a[0].iStart2 = nPrefix;
  p->a[0].iLen2 = nRight - nCommon;
  improveReadability(zLeft, zRight, p);
}



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

/*
** 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;
}

static unsigned short diff_opt_context_lines(fsl_diff_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;
}

/*
** Minimum of two values
*/
static int diffMin(int a, int b){ return a<b ? a : b; }

/****************************************************************************/
/*
** Return the number between 0 and 100 that is smaller the closer pA and
** pB match.  Return 0 for a perfect match.  Return 100 if pA and pB are
** completely different.
**
** The current algorithm is as follows:
**
** (1) Remove leading and trailing whitespace.
** (2) Truncate both strings to at most 250 characters
** (3) If the two strings have a common prefix, measure that prefix
** (4) Find the length of the longest common subsequence that is
**     at least 150% longer than the common prefix.
** (5) Longer common subsequences yield lower scores.
*/
static int match_dline2(const fsl_dline *pA, const fsl_dline *pB){
  const char *zA;            /* Left string */
  const char *zB;            /* right string */
  int nA;                    /* Bytes in zA[] */
  int nB;                    /* Bytes in zB[] */
  int nMin;
  int nPrefix;
  int avg;                   /* Average length of A and B */
  int i, j, k;               /* Loop counters */
  int best = 0;              /* Longest match found so far */
  int score;                 /* Final score.  0..100 */
  unsigned char c;           /* Character being examined */
  unsigned char aFirst[256]; /* aFirst[X] = index in zB[] of first char X */
  unsigned char aNext[252];  /* aNext[i] = index in zB[] of next zB[i] char */

  zA = pA->z;
  zB = pB->z;
  nA = pA->n;
  nB = pB->n;
  while( nA>0 && (unsigned char)zA[0]<=' ' ){ nA--; zA++; }
  while( nA>0 && (unsigned char)zA[nA-1]<=' ' ){ nA--; }
  while( nB>0 && (unsigned char)zB[0]<=' ' ){ nB--; zB++; }
  while( nB>0 && (unsigned char)zB[nB-1]<=' ' ){ nB--; }
  if( nA>250 ) nA = 250;
  if( nB>250 ) nB = 250;
  avg = (nA+nB)/2;
  if( avg==0 ) return 0;
  nMin = nA;
  if( nB<nMin ) nMin = nB;
  if( nMin==0 ) return 68;
  for(nPrefix=0; nPrefix<nMin && zA[nPrefix]==zB[nPrefix]; nPrefix++){}
  best = 0;
  if( nPrefix>5 && nPrefix>nMin/2 ){
    best = nPrefix*3/2;
    if( best>=avg - 2 ) best = avg - 2;
  }
  if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
  memset(aFirst, 0xff, sizeof(aFirst));
  zA--; zB--;   /* Make both zA[] and zB[] 1-indexed */
  for(i=nB; i>0; i--){
    c = (unsigned char)zB[i];
    aNext[i] = aFirst[c];
    aFirst[c] = i;
  }
  for(i=1; i<=nA-best; i++){
    c = (unsigned char)zA[i];
    for(j=aFirst[c]; j<nB-best && memcmp(&zA[i],&zB[j],best)==0; j = aNext[j]){
      int limit = diffMin(nA-i, nB-j);
      for(k=best; k<=limit && zA[k+i]==zB[k+j]; k++){}
      if( k>best ) best = k;
    }
  }
  score = (best>=avg) ? 0 : (avg - best)*100/avg;

#if 0
  fprintf(stderr, "A: [%.*s]\nB: [%.*s]\nbest=%d avg=%d score=%d\n",
  nA, zA+1, nB, zB+1, best, avg, score);
#endif

  /* Return the result */
  return score;
}

/*
** There is a change block in which nLeft lines of text on the left are
** converted into nRight lines of text on the right.  This routine computes
** how the lines on the left line up with the lines on the right.
**
** The return value is a buffer of unsigned characters, obtained from
** fossil_malloc().  (The caller needs to free the return value using
** fossil_free().)  Entries in the returned array have values as follows:
**
**    1.  Delete the next line of pLeft.
**    2.  Insert the next line of pRight.
**    3.  The next line of pLeft changes into the next line of pRight.
**    4.  Delete one line from pLeft and add one line to pRight.
**
** The length of the returned array will be at most nLeft+nRight bytes.
** If the first bytes is 4,  that means we could not compute reasonable
** alignment between the two blocks.
**
** Algorithm:  Wagner's minimum edit-distance algorithm, modified by
** adding a cost to each match based on how well the two rows match
** 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 */
  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 */
  int nMatch, iMatch;          /* Number of matching lines and match score */
  int aBuf[100];               /* Stack space for a[] if nRight not to big */
  int rc = 0;

  if( nLeft==0 ){
    aM = fsl_malloc( nRight + 2 );
    if(!aM) return FSL_RC_OOM;
    memset(aM, 2, nRight);
    *pNResult = nRight;
    *pResult = aM;
    return 0;
  }
  if( nRight==0 ){
    aM = fsl_malloc( nLeft + 2 );
    if(!aM) return FSL_RC_OOM;
    memset(aM, 1, nLeft);
    *pNResult = nLeft;
    *pResult = aM;
    return 0;
  }

  /* For large alignments, use a divide and conquer algorithm that is
  ** O(NlogN).  The result is not as precise, but this whole thing is an
  ** approximation anyhow, and the faster response time is an acceptable
  ** trade-off for reduced precision.
  */
  if( nLeft*nRight>DIFF_ALIGN_MX
      && (pOpt->diffFlags & FSL_DIFF2_SLOW_SBS)==0 ){
    const fsl_dline *aSmall;   /* The smaller of aLeft and aRight */
    const fsl_dline *aBig;     /* The larger of aLeft and aRight */
    int nSmall, nBig;      /* Size of aSmall and aBig.  nSmall<=nBig */
    int iDivSmall, iDivBig;  /* Divider point for aSmall and aBig */
    int iDivLeft, iDivRight; /* Divider point for aLeft and aRight */
    unsigned char *a1 = 0, *a2 = 0;  /* Results of the alignments on two halves */
    unsigned int n1, n2;     /* Number of entries in a1 and a2 */
    int score, bestScore;    /* Score and best score seen so far */
    if( nLeft>nRight ){
      aSmall = aRight;
      nSmall = nRight;
      aBig = aLeft;
      nBig = nLeft;
    }else{
      aSmall = aLeft;
      nSmall = nLeft;
      aBig = aRight;
      nBig = nRight;
    }
    iDivBig = nBig/2;
    iDivSmall = nSmall/2;
    bestScore = 10000;
    for(i=0; i<nSmall; i++){
      score = match_dline2(aBig+iDivBig, aSmall+i) + abs(i-nSmall/2)*2;
      if( score<bestScore ){
        bestScore = score;
        iDivSmall = i;
      }
    }
    if( aSmall==aRight ){
      iDivRight = iDivSmall;
      iDivLeft = iDivBig;
    }else{
      iDivRight = iDivBig;
      iDivLeft = iDivSmall;
    }
    rc = diffBlockAlignment(aLeft,iDivLeft,aRight, iDivRight,
                            pOpt, &a1, &n1);
    if(!rc){
      rc = diffBlockAlignment(aLeft+iDivLeft, nLeft-iDivLeft,
                              aRight+iDivRight, nRight-iDivRight,
                              pOpt, &a2, &n2);
    }
    if(rc) goto bail;
    void * a1Re = fsl_realloc(a1, n1+n2 );
    if(!a1Re) goto bail;
    a1 = (unsigned char *)a1Re;
    memcpy(a1+n1,a2,n2);
    fsl_free(a2);
    a2 = 0;
    *pNResult = n1+n2;
    *pResult = a1;
    return 0;
    bail:
    assert(0!=rc);
    fsl_free( a1 );
    fsl_free( a2 );
    goto end;
  }

  /* If we reach this point, we will be doing an O(N*N) Wagner minimum
  ** edit distance to compute the alignment.
  */
  if( nRight < (int)(sizeof(aBuf)/sizeof(aBuf[0]))-1 ){
    pToFree = 0;
    a = aBuf;
  }else{
    a = pToFree = fsl_malloc( sizeof(a[0])*(nRight+1) );
    if(!a){
      rc = FSL_RC_OOM;
      goto end;
    }
  }
  aM = fsl_malloc( (nLeft+1)*(nRight+1) );
  if(!aM){
    rc = FSL_RC_OOM;
    goto end;
  }

  /* Compute the best alignment */
  for(i=0; i<=nRight; i++){
    aM[i] = 2;
    a[i] = i*50;
  }
  aM[0] = 0;
  for(j=1; j<=nLeft; j++){
    int p = a[0];
    a[0] = p+50;
    aM[j*(nRight+1)] = 1;
    for(i=1; i<=nRight; i++){
      int m = a[i-1]+50;
      int d = 2;
      if( m>a[i]+50 ){
        m = a[i]+50;
        d = 1;
      }
      if( m>p ){
        int const score =
          match_dline2(&aLeft[j-1], &aRight[i-1]);
        if( (score<=90 || (i<j+1 && i>j-1)) && m>p+score ){
          m = p+score;
          d = 3 | score*4;
        }
      }
      p = a[i];
      a[i] = m;
      aM[j*(nRight+1)+i] = d;
    }
  }

  /* Compute the lowest-cost path back through the matrix */
  i = nRight;
  j = nLeft;
  k = (nRight+1)*(nLeft+1)-1;
  nMatch = iMatch = 0;
  while( i+j>0 ){
    unsigned char c = aM[k];
    if( c>=3 ){
      assert( i>0 && j>0 );
      i--;
      j--;
      nMatch++;
      iMatch += (c>>2);
      aM[k] = 3;
    }else if( c==2 ){
      assert( i>0 );
      i--;
    }else{
      assert( j>0 );
      j--;
    }
    k--;
    aM[k] = aM[j*(nRight+1)+i];
  }
  k++;
  i = (nRight+1)*(nLeft+1) - k;
  memmove(aM, &aM[k], i);
  *pNResult = i;
  *pResult = aM;

  end:
  fsl_free(pToFree);
  return rc;
}


/*
** Format a diff using a fsl_diff_builder object
*/
static int fdb__format(
  fsl_diff_cx * const cx,
  fsl_diff_builder * 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;
  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
  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;
  if(pBuilder->start){
    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. */
    /* 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;
      int xa = a, xb = b;
      for(i=0; hideBlock && i<nr; i++){
        int c1, c2;
        xa += R[r+i*3];
        xb += R[r+i*3];
        c1 = re_dline_match(pOpt->pRe, &A[xa], R[r+i*3+1]);
        c2 = re_dline_match(pOpt->pRe, &B[xb], R[r+i*3+2]);
        hideBlock = c1==c2;
        xa += R[r+i*3+1];
        xb += R[r+i*3+2];
      }
      if( hideBlock ){
        a = xa;
        b = xb;
        continue;
      }
    }
#endif

    /* Figure out how many lines of A and B are to be displayed
    ** for this change block.
    */
    if( R[r]>(int)contextLines ){
      na = nb = contextLines;
      skip = R[r] - contextLines;
    }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]>(int)contextLines ){
      na += contextLines;
      nb += contextLines;
    }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];
    }

    //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
#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);
      RC;
    }

    /* Show the initial common area */
    a += skip;
    b += skip;
    m = R[r] - skip;
    if( r ) skip -= contextLines;

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

           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
        ** go ahead and show the skip band as it is not worth eliding */
        //MARKER(("skip %d < contextLines %d\n", skip, contextLines));
        /* from fossil(1) from formatDiff() */
        for(j=0; 0==rc && j<(unsigned)skip; j++){
          //MARKER(("(A) COMMON\n"));
          rc = pBuilder->common(pBuilder, &A[a+j-skip]);
        }
      }else{
        rc = pBuilder->skip(pBuilder, skip);
      }
      RC;
    }
    for(j=0; 0==rc && j<m; j++){
      //MARKER(("(B) COMMON\n"));
      rc = pBuilder->common(pBuilder, &A[a+j]);
    }
    RC;
    a += m;
    b += m;
    //MARKER(("Show the differences... a=%d, b=%d, m=%d\n", a, b, m));

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

      /* 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;
      }

      /* 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 */
            rc = pBuilder->deletion(pBuilder, &A[a]);
            if(rc) goto bail;
            ma--;
            a++;
            break;
          }
          case 2: {
            /* Insert one line on the right */
            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 ){
              rc = pBuilder->common(pBuilder, &A[a]);
            }else{
              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 */
            rc = pBuilder->replacement(pBuilder, &A[a], &B[b]);
            if(rc) goto bail;
            ma--;
            a++;
            mb--;
            b++;
            break;
          }
        }
      }
      assert( nAlign==j );
      fsl_free(alignment);
      if( i<nr-1 ){
        m = R[r+i*3+3];
        for(j=0; 0==rc && j<m; j++){
          //MARKER(("D common\n"));
          rc = pBuilder->common(pBuilder, &A[a+j]);
        }
        RC;
        b += m;
        a += m;
      }
      continue;
      bail:
      assert(rc);
      fsl_free(alignment);
      goto end;
    }

    /* Show the final common area */
    assert( nr==i );
    m = R[r+nr*3];
    if( m>contextLines ) m = contextLines;
    for(j=0; 0==rc && j<m && j<contextLines; j++){
      //MARKER(("E common\n"));
      rc = pBuilder->common(pBuilder, &A[a+j]);
    }
    RC;
  }
  if( R[r]>(int)contextLines ){
    rc = pBuilder->skip(pBuilder, R[r] - contextLines);
  }
  end:
#undef RC
  if(0==rc){
    if(pBuilder->finish) pBuilder->finish(pBuilder);
    if(pBuilder->twoPass && 1==passNumber){
      goto pass_again;
    }
  }
  return rc;
}

/* MISSING(?) fossil(1) converts the diff inputs into utf8 with no
   BOM. Whether we really want to do that here or rely on the caller
   to is up for debate. If we do it here, we have to make the inputs
   non-const, which seems "wrong" for a library API. */
#define blob_to_utf8_no_bom(A,B) (void)0

/**
   Performs a diff of version 1 (pA) and version 2 (pB). ONE of
   pBuilder or outRaw must be non-NULL. If pBuilder is not NULL, all
   output for the diff is emitted via pBuilder. If outRaw is not NULL
   then on success *outRaw is set to the array of diff triples,
   transfering ownership to the caller, who must eventually fsl_free()
   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_,
                               int ** outRaw){
  int rc = 0;
  fsl_diff_cx c = fsl_diff_cx_empty;
  bool ignoreWs = false;
  int ansiOptCount = 0;
  fsl_diff_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 ){
    char const * z;
    fsl_buffer const *pTemp = pA;
    pA = pB;
    pB = pTemp;
    z = opt.hashRHS; opt.hashRHS = opt.hashLHS; opt.hashLHS = z;
    z = opt.nameRHS; opt.nameRHS = opt.nameLHS; opt.nameLHS = z;
  }
#define AOPT(OPT) \
  if(opt.ansiColor.OPT) ansiOptCount += (*opt.ansiColor.OPT) ? 1 : 0; \
  else opt.ansiColor.OPT = ""
  AOPT(insertion);
  AOPT(edit);
  AOPT(deletion);
#undef AOPT
  if(0==ansiOptCount){
    opt.ansiColor.reset = "";
  }else if(!opt.ansiColor.reset || !*opt.ansiColor.reset){
    opt.ansiColor.reset = "\x1b[0m";
  }
  ignoreWs = (opt.diffFlags & FSL_DIFF2_IGNORE_ALLWS)!=0;
  if(FSL_DIFF2_IGNORE_ALLWS==(opt.diffFlags & FSL_DIFF2_IGNORE_ALLWS)){
    c.cmpLine = fsl_dline_cmp_ignore_ws;
  }else{
    c.cmpLine = fsl_dline_cmp;
  }
 
  rc = fsl_break_into_dlines(fsl_buffer_cstr(pA), (fsl_int_t)pA->used,
                             (uint32_t*)&c.nFrom, &c.aFrom, opt.diffFlags);
  if(rc) goto end;
  rc = fsl_break_into_dlines(fsl_buffer_cstr(pB), (fsl_int_t)pB->used,
                             (uint32_t*)&c.nTo, &c.aTo, opt.diffFlags);
  if(rc) goto end;

  /* Compute the difference */
  rc = fsl__diff_all(&c);
  if(rc) goto end;
  if( ignoreWs && c.nEdit==6 && c.aEdit[1]==0 && c.aEdit[2]==0 ){
    rc = FSL_RC_DIFF_WS_ONLY;
    goto end;
  }
  if( (opt.diffFlags & FSL_DIFF2_NOTTOOBIG)!=0 ){
    int i, m, n;
    int const * const a = c.aEdit;
    int const mx = c.nEdit;
    for(i=m=n=0; i<mx; i+=3){ m += a[i]; n += a[i+1]+a[i+2]; }
    if( !n || n>10000 ){
      rc = FSL_RC_RANGE;
      /* diff_errmsg(pOut, DIFF_TOO_MANY_CHANGES, diffFlags); */
      goto end;
    }
  }
  //fsl__dump_triples(&c, __FILE__, __LINE__);
  if( (opt.diffFlags & FSL_DIFF2_NOOPT)==0 ){
    fsl__diff_optimize(&c);
  }
  //fsl__dump_triples(&c, __FILE__, __LINE__);

  /**
     Reference:

     https://fossil-scm.org/home/file?ci=cae7036bb7f07c1b&name=src/diff.c&ln=2749-2804

     Noting that:

     - That function's return value is this one's *outRaw

     - 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;
    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){
  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,
                    int **outRaw ){
  return fsl_diff2_text_impl(pv1, pv2, NULL, opt, 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);
  if(rc){
    *rc = fsl_diff_builder_empty;
    if(extra){
      rc->pimpl = ((unsigned char *)rc)+sizeof(fsl_diff_builder);
    }
  }
  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__outf(fsl_diff_builder * 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;
}


static int fdb__debug_start(fsl_diff_builder * const b){
  int rc = fdb__outf(b, "DEBUG builder starting up.\n");
  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,
                                  uint32_t lnnoLHS, uint32_t linesLHS,
                                  uint32_t lnnoRHS, uint32_t linesRHS ){
#if 1
  return fdb__outf(b, "@@ -%" PRIu32 ",%" PRIu32
                   " +%" 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;
  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_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_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_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);
  if(!rc){
    rc = fdb__outf(p, "            %8u %.*s\n",
                   p->lnRHS, (int)lineRhs->n, lineRhs->z);
  }
  return rc;
}
                 
static int fdb__debug_edit(fsl_diff_builder * const b,
                           fsl_dline const * pX,
                           fsl_dline const * pY){
  int rc = 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);
  RC;
  fsl_dline_change_spans(pX, pY, &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 ){
          rc = fdb__out(b, " ", 1);
          RC;
        }
        x++;
      }
      for(j=0; j<len; j++, x++){
        if( (pX->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);
  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 ){
          rc = fdb__out(b, " ", 1);
          RC;
        }
        x++;
      }
      for(j=0; j<len; j++, x++){
        if( (pY->z[x]&0xc0)!=0x80 ){
          rc = fdb__out(b, &c, 1);
          RC;
        }
      }
    }
  }
  if( x ){
    rc = fdb__out(b, "\n", 1);
  }
  end:
#undef RC
  return rc;
}

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){
  fsl_free(b);
}

static fsl_diff_builder * fsl__diff_builder_debug(void){
  fsl_diff_builder * rc = fsl__diff_builder_alloc(0);
  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);
    assert(0==rc->implFlags);
    assert(0==rc->lnLHS);
    assert(0==rc->lnRHS);
    assert(NULL==rc->opt);
  }
  return rc;
}

/******************** json1 diff builder ********************/
/* Description taken verbatim from fossil(1): */
/*
** This formatter generates a JSON array that describes the difference.
**
** The Json array consists of integer opcodes with each opcode followed
** by zero or more arguments:
**
**   Syntax        Mnemonic    Description
**   -----------   --------    --------------------------
**   0             END         This is the end of the diff
**   1  INTEGER    SKIP        Skip N lines from both files
**   2  STRING     COMMON      The line show by STRING is in both files
**   3  STRING     INSERT      The line STRING is in only the right file
**   4  STRING     DELETE      The STRING line is in only the left file
**   5  SUBARRAY   EDIT        One line is different on left and right.
**
** 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,
                     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){
  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){
  return fdb__outf(b, "1,%" PRIu32 ",\n", n);
}
static int fdb__json1_common(fsl_diff_builder * 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){
  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){
  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,
                              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){
  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);
  for(i=x=0; i<(int)chng.n; i++){
    rc = fdb__outj(b, pX->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;
    x += chng.a[i].iLen1;
    rc = fdb__out(b, ",", 1); RC;
    rc = fdb__outj(b, pY->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__out(b, "],\n",3); RC;
  end:
  return rc;
#undef RC
}

static int fdb__json1_finish(fsl_diff_builder * 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);
  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;
    assert(!rc->pimpl);
    assert(0==rc->implFlags);
    assert(0==rc->lnLHS);
    assert(0==rc->lnRHS);
    assert(NULL==rc->opt);
  }
  return rc;
}

static int fdb__utxt_start(fsl_diff_builder * const b){
  int rc = 0;
  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,
                                 uint32_t lnnoLHS, uint32_t linesLHS,
                                 uint32_t lnnoRHS, uint32_t linesRHS ){
  if(FSL_DIFF2_LINE_NUMBERS & b->opt->diffFlags){
    return fdb__outf(b, "%.40c\n", '~');
  }else{
    return fdb__outf(b, "@@ -%" PRIu32 ",%" PRIu32
                     " +%" PRIu32 ",%" PRIu32 " @@\n",
                     lnnoLHS, linesLHS, lnnoRHS, linesRHS);
  }
}


static int fdb__utxt_skip(fsl_diff_builder * const b, uint32_t n){
  //MARKER(("SKIP\n"));
  b->lnLHS += n;
  b->lnRHS += n;
  return 0;
}

/** Outputs line numbers to b->opt->out. */
static int fdb__utxt_lineno(fsl_diff_builder * const b, uint32_t lnL, uint32_t lnR){
  int rc = 0;
  if(FSL_DIFF2_LINE_NUMBERS & b->opt->diffFlags){
    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(0==rc){
      rc = lnR
      ? fdb__outf(b, "%s%6" PRIu32 "%s ",
                  (lnL ? "" : b->opt->ansiColor.insertion),
                  lnR,
                  (lnL ? "" : b->opt->ansiColor.reset))
      : fdb__out(b, "       ", 7);
    }
  }
  return rc;
}

static int fdb__utxt_common(fsl_diff_builder * const b, fsl_dline const * pLine){
  //MARKER(("COMMON\n"));
  ++b->lnLHS;
  ++b->lnRHS;
  const int 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){
  //MARKER(("INSERT\n"));
  ++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){
  //MARKER(("DELETE\n"));
  ++b->lnLHS;
  const int 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,
                                 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,
                           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 void fdb__utxt_finalize(fsl_diff_builder * const b){
  fsl_free(b);
}

static fsl_diff_builder * fsl__diff_builder_utxt(void){
  fsl_diff_builder * rc = fsl__diff_builder_alloc(0);
  if(!rc) return NULL;
  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->finalize = fdb__utxt_finalize;
  return rc;
}

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) \
    rc = fdb__out(b, "{", 1)
#define BR_CLOSE if(FSL_DIFF2_TCL_BRACES & b->opt->diffFlags) \
    rc = fdb__out(b, "}", 1)

#define DTCL_BUFFER(B) &((DiBuTcl*)(B)->pimpl)->str
static int fdb__outtcl(fsl_diff_builder * 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);
  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){
  int rc = 0;
  fsl_buffer_reuse(DTCL_BUFFER(b));
  BR_OPEN;
  if(0==rc) 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){
  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){
  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){
  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){
  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,
                                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){
  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);
  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;
    x = chng.a[i].iStart1;
    rc = fdb__outtcl(b, pX->z + x, chng.a[i].iLen1, ' '); RC;
    x += chng.a[i].iLen1;
    rc = fdb__outtcl(b, pY->z + chng.a[i].iStart2,
                     chng.a[i].iLen2, 0); RC;
  }
  assert(0==rc);
  if( x < pX->n ){
    rc = fdb__out(b, " ", 1); RC;
    rc = fdb__outtcl(b, pX->z + x, pX->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){
  int rc = 0;
  BR_CLOSE;
  if(0==rc && FSL_DIFF2_TCL_BRACES & b->opt->diffFlags){
    rc = fdb__out(b, "\n", 1);
  }
  return rc;
}
#undef BR_OPEN
#undef BR_CLOSE

static void fdb__tcl_finalize(fsl_diff_builder * const b){
  fsl_buffer_clear( &((DiBuTcl*)b->pimpl)->str );
  *b = fsl_diff_builder_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));
  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->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){
  assert(2==b->passNumber);
  return fdb__outf(b, " %c ", ch);
}

static int fdb__splittxt_lineno(fsl_diff_builder * const b,
                                SplitTxt const * const sst,
                                bool isLeft, uint32_t n){
  assert(2==b->passNumber);
  int const col = isLeft ? STC_NUM1 : STC_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){
  int rc = 0;
  if(1==b->passNumber){
    SPLITSTATE(sst);
    *sst = SplitTxt_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;
    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){
  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);
  return fdb__outf(b, "%.*c %.*c   %.*c %.*c\n",
                 sst->maxWidths[STC_NUM1], '~',
                 maxWidth1, '~',
                 sst->maxWidths[STC_NUM2], '~',
                 maxWidth2, '~');
}

static int fdb__splittxt_color(fsl_diff_builder * 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,
                              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);
    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,
                                fsl_dline const * const pLine){
  int rc = 0;
  SPLITSTATE(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);
    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,
                                   fsl_dline const * const pLine){
  int rc = 0;
  SPLITSTATE(sst);
  ++b->lnRHS;
  if(1==b->passNumber){
    fdb__splittext_update_maxlen(sst, STC_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,
                                  fsl_dline const * const pLine){
  int rc = 0;
  SPLITSTATE(sst);
  ++b->lnLHS;
  if(1==b->passNumber){
    fdb__splittext_update_maxlen(sst, STC_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,
                                     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);
  ++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);
    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){
  int rc = 0;
  if(1==b->passNumber){
    SPLITSTATE(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];
    ln = b->lnRHS;
    for(; ln>=10; ln/=10) ++sst->maxWidths[STC_NUM2];
  }
  return rc;
}

static void fdb__splittxt_finalize(fsl_diff_builder * const b){
  *b = fsl_diff_builder_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));
  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;
  }
  return rc;
}

int fsl_diff_builder_factory( fsl_diff_builder_e type,
                              fsl_diff_builder **pOut ){
  int rc = FSL_RC_TYPE;
  fsl_diff_builder * (*factory)(void) = NULL;
  switch(type){
    case FSL_DIFF_BUILDER_DEBUG:
      factory = fsl__diff_builder_debug;
      break;
    case FSL_DIFF_BUILDER_JSON1:
      factory = fsl__diff_builder_json1;
      break;
    case FSL_DIFF_BUILDER_UNIFIED_TEXT:
      factory = fsl__diff_builder_utxt;
      break;
    case FSL_DIFF_BUILDER_TCL:
      factory = fsl__diff_builder_tcl;
      break;
    case FSL_DIFF_BUILDER_SPLIT_TEXT:
      factory = fsl__diff_builder_splittxt;
      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 */
/* -*- 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
25496
25497
25498
25499
25500
25501
25502
25503
25504
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
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
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
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
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
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
28020
28021
28022
28023
28024
28025
28026




























































































































































































































































































































































































































































































































































































































































































































































































28027
28028
28029
28030
28031
28032
28033







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







    return rc;
  }
}


#undef MARKER
/* end of file event.c */
/* start of file ext_regexp.c */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
** 2012-11-13
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** The code in this file implements a compact but reasonably
** efficient regular-expression matcher for posix extended regular
** expressions against UTF8 text.
**
** This file is an SQLite extension.  It registers a single function
** named "regexp(A,B)" where A is the regular expression and B is the
** string to be matched.  By registering this function, SQLite will also
** then implement the "B regexp A" operator.  Note that with the function
** the regular expression comes first, but with the operator it comes
** second.
**
**  The following regular expression syntax is supported:
**
**     X*      zero or more occurrences of X
**     X+      one or more occurrences of X
**     X?      zero or one occurrences of X
**     X{p,q}  between p and q occurrences of X
**     (X)     match X
**     X|Y     X or Y
**     ^X      X occurring at the beginning of the string
**     X$      X occurring at the end of the string
**     .       Match any single character
**     \c      Character c where c is one of \{}()[]|*+?.
**     \c      C-language escapes for c in afnrtv.  ex: \t or \n
**     \uXXXX  Where XXXX is exactly 4 hex digits, unicode value XXXX
**     \xXX    Where XX is exactly 2 hex digits, unicode value XX
**     [abc]   Any single character from the set abc
**     [^abc]  Any single character not in the set abc
**     [a-z]   Any single character in the range a-z
**     [^a-z]  Any single character not in the range a-z
**     \b      Word boundary
**     \w      Word character.  [A-Za-z0-9_]
**     \W      Non-word character
**     \d      Digit
**     \D      Non-digit
**     \s      Whitespace character
**     \S      Non-whitespace character
**
** A nondeterministic finite automaton (NFA) is used for matching, so the
** performance is bounded by O(N*M) where N is the size of the regular
** expression and M is the size of the input string.  The matcher never
** exhibits exponential behavior.  Note that the X{p,q} operator expands
** to p copies of X following by q-p copies of X? and that the size of the
** regular expression in the O(N*M) performance bound is computed after
** this expansion.
*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#ifndef SQLITE_CORE
#include "sqlite3ext.h"
/*declares extern the vtable of all the sqlite3 functions (for loadable modules only)*/
SQLITE_EXTENSION_INIT3
#else
#include "sqlite3.h"
#endif
#include <string.h>
#include <stdlib.h>


/* The end-of-input character */
#define RE_EOF            0    /* End of input */

/* The NFA is implemented as sequence of opcodes taken from the following
** set.  Each opcode has a single integer argument.
*/
#define RE_OP_MATCH       1    /* Match the one character in the argument */
#define RE_OP_ANY         2    /* Match any one character.  (Implements ".") */
#define RE_OP_ANYSTAR     3    /* Special optimized version of .* */
#define RE_OP_FORK        4    /* Continue to both next and opcode at iArg */
#define RE_OP_GOTO        5    /* Jump to opcode at iArg */
#define RE_OP_ACCEPT      6    /* Halt and indicate a successful match */
#define RE_OP_CC_INC      7    /* Beginning of a [...] character class */
#define RE_OP_CC_EXC      8    /* Beginning of a [^...] character class */
#define RE_OP_CC_VALUE    9    /* Single value in a character class */
#define RE_OP_CC_RANGE   10    /* Range of values in a character class */
#define RE_OP_WORD       11    /* Perl word character [A-Za-z0-9_] */
#define RE_OP_NOTWORD    12    /* Not a perl word character */
#define RE_OP_DIGIT      13    /* digit:  [0-9] */
#define RE_OP_NOTDIGIT   14    /* Not a digit */
#define RE_OP_SPACE      15    /* space:  [ \t\n\r\v\f] */
#define RE_OP_NOTSPACE   16    /* Not a digit */
#define RE_OP_BOUNDARY   17    /* Boundary between word and non-word */

/* Each opcode is a "state" in the NFA */
typedef unsigned short sqlite3_ReStateNumber;

/* Because this is an NFA and not a DFA, multiple states can be active at
** once.  An instance of the following object records all active states in
** the NFA.  The implementation is optimized for the common case where the
** number of actives states is small.
*/
typedef struct sqlite3_ReStateSet {
  unsigned nState;            /* Number of current states */
  sqlite3_ReStateNumber *aState;      /* Current states */
} sqlite3_ReStateSet;

/* An input string read one character at a time.
*/
typedef struct sqlite3_ReInput sqlite3_ReInput;
struct sqlite3_ReInput {
  const unsigned char *z;  /* All text */
  int i;                   /* Next byte to read */
  int mx;                  /* EOF when i>=mx */
};

/* A compiled NFA (or an NFA that is in the process of being compiled) is
** an instance of the following object.
*/
/*typedef struct sqlite3_ReCompiled sqlite3_ReCompiled;*/
struct sqlite3_ReCompiled {
  sqlite3_ReInput sIn;        /* Regular expression text */
  const char *zErr;           /* Error message to return */
  char *aOp;                  /* Operators for the virtual machine */
  int *aArg;                  /* Arguments to each operator */
  unsigned (*xNextChar)(sqlite3_ReInput*);  /* Next character function */
  unsigned char zInit[12];    /* Initial text to match */
  int nInit;                  /* Number of characters in zInit */
  unsigned nState;            /* Number of entries in aOp[] and aArg[] */
  unsigned nAlloc;            /* Slots allocated for aOp[] and aArg[] */
};

/* Add a state to the given state set if it is not already there */
static void sqlite3re_add_state(sqlite3_ReStateSet *pSet, int newState){
  unsigned i;
  for(i=0; i<pSet->nState; i++) if( pSet->aState[i]==newState ) return;
  pSet->aState[pSet->nState++] = newState;
}

/* Extract the next unicode character from *pzIn and return it.  Advance
** *pzIn to the first byte past the end of the character returned.  To
** be clear:  this routine converts utf8 to unicode.  This routine is 
** optimized for the common case where the next character is a single byte.
*/
static unsigned sqlite3re_next_char(sqlite3_ReInput *p){
  unsigned c;
  if( p->i>=p->mx ) return 0;
  c = p->z[p->i++];
  if( c>=0x80 ){
    if( (c&0xe0)==0xc0 && p->i<p->mx && (p->z[p->i]&0xc0)==0x80 ){
      c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f);
      if( c<0x80 ) c = 0xfffd;
    }else if( (c&0xf0)==0xe0 && p->i+1<p->mx && (p->z[p->i]&0xc0)==0x80
           && (p->z[p->i+1]&0xc0)==0x80 ){
      c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f);
      p->i += 2;
      if( c<=0x3ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd;
    }else if( (c&0xf8)==0xf0 && p->i+3<p->mx && (p->z[p->i]&0xc0)==0x80
           && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){
      c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6)
                       | (p->z[p->i+2]&0x3f);
      p->i += 3;
      if( c<=0xffff || c>0x10ffff ) c = 0xfffd;
    }else{
      c = 0xfffd;
    }
  }
  return c;
}
static unsigned sqlite3re_next_char_nocase(sqlite3_ReInput *p){
  unsigned c = sqlite3re_next_char(p);
  if( c>='A' && c<='Z' ) c += 'a' - 'A';
  return c;
}

/* Return true if c is a perl "word" character:  [A-Za-z0-9_] */
static int sqlite3re_word_char(int c){
  return (c>='0' && c<='9') || (c>='a' && c<='z')
      || (c>='A' && c<='Z') || c=='_';
}

/* Return true if c is a "digit" character:  [0-9] */
static int sqlite3re_digit_char(int c){
  return (c>='0' && c<='9');
}

/* Return true if c is a perl "space" character:  [ \t\r\n\v\f] */
static int sqlite3re_space_char(int c){
  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
}

/* Run a compiled regular expression on the zero-terminated input
** string zIn[].  Return true on a match and false if there is no match.
*/
int sqlite3re_match(sqlite3_ReCompiled *pRe, const unsigned char *zIn, int nIn){
  sqlite3_ReStateSet aStateSet[2], *pThis, *pNext;
  sqlite3_ReStateNumber aSpace[100];
  sqlite3_ReStateNumber *pToFree;
  unsigned int i = 0;
  unsigned int iSwap = 0;
  int c = RE_EOF+1;
  int cPrev = 0;
  int rc = 0;
  sqlite3_ReInput in;

  in.z = zIn;
  in.i = 0;
  in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn);

  /* Look for the initial prefix match, if there is one. */
  if( pRe->nInit ){
    unsigned char x = pRe->zInit[0];
    while( in.i+pRe->nInit<=in.mx 
     && (zIn[in.i]!=x ||
         strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0)
    ){
      in.i++;
    }
    if( in.i+pRe->nInit>in.mx ) return 0;
  }

  if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){
    pToFree = 0;
    aStateSet[0].aState = aSpace;
  }else{
    pToFree = sqlite3_malloc( sizeof(sqlite3_ReStateNumber)*2*pRe->nState );
    if( pToFree==0 ) return -1;
    aStateSet[0].aState = pToFree;
  }
  aStateSet[1].aState = &aStateSet[0].aState[pRe->nState];
  pNext = &aStateSet[1];
  pNext->nState = 0;
  sqlite3re_add_state(pNext, 0);
  while( c!=RE_EOF && pNext->nState>0 ){
    cPrev = c;
    c = pRe->xNextChar(&in);
    pThis = pNext;
    pNext = &aStateSet[iSwap];
    iSwap = 1 - iSwap;
    pNext->nState = 0;
    for(i=0; i<pThis->nState; i++){
      int x = pThis->aState[i];
      switch( pRe->aOp[x] ){
        case RE_OP_MATCH: {
          if( pRe->aArg[x]==c ) sqlite3re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_ANY: {
          sqlite3re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_WORD: {
          if( sqlite3re_word_char(c) ) sqlite3re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_NOTWORD: {
          if( !sqlite3re_word_char(c) ) sqlite3re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_DIGIT: {
          if( sqlite3re_digit_char(c) ) sqlite3re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_NOTDIGIT: {
          if( !sqlite3re_digit_char(c) ) sqlite3re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_SPACE: {
          if( sqlite3re_space_char(c) ) sqlite3re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_NOTSPACE: {
          if( !sqlite3re_space_char(c) ) sqlite3re_add_state(pNext, x+1);
          break;
        }
        case RE_OP_BOUNDARY: {
          if( sqlite3re_word_char(c)!=sqlite3re_word_char(cPrev) ) sqlite3re_add_state(pThis, x+1);
          break;
        }
        case RE_OP_ANYSTAR: {
          sqlite3re_add_state(pNext, x);
          sqlite3re_add_state(pThis, x+1);
          break;
        }
        case RE_OP_FORK: {
          sqlite3re_add_state(pThis, x+pRe->aArg[x]);
          sqlite3re_add_state(pThis, x+1);
          break;
        }
        case RE_OP_GOTO: {
          sqlite3re_add_state(pThis, x+pRe->aArg[x]);
          break;
        }
        case RE_OP_ACCEPT: {
          rc = 1;
          goto re_match_end;
        }
        case RE_OP_CC_INC:
        case RE_OP_CC_EXC: {
          int j = 1;
          int n = pRe->aArg[x];
          int hit = 0;
          for(j=1; j>0 && j<n; j++){
            if( pRe->aOp[x+j]==RE_OP_CC_VALUE ){
              if( pRe->aArg[x+j]==c ){
                hit = 1;
                j = -1;
              }
            }else{
              if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){
                hit = 1;
                j = -1;
              }else{
                j++;
              }
            }
          }
          if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit;
          if( hit ) sqlite3re_add_state(pNext, x+n);
          break;            
        }
      }
    }
  }
  for(i=0; i<pNext->nState; i++){
    if( pRe->aOp[pNext->aState[i]]==RE_OP_ACCEPT ){ rc = 1; break; }
  }
re_match_end:
  sqlite3_free(pToFree);
  return rc;
}

/* Resize the opcode and argument arrays for an RE under construction.
*/
static int sqlite3re_resize(sqlite3_ReCompiled *p, int N){
  char *aOp;
  int *aArg;
  aOp = sqlite3_realloc(p->aOp, N*sizeof(p->aOp[0]));
  if( aOp==0 ) return 1;
  p->aOp = aOp;
  aArg = sqlite3_realloc(p->aArg, N*sizeof(p->aArg[0]));
  if( aArg==0 ) return 1;
  p->aArg = aArg;
  p->nAlloc = N;
  return 0;
}

/* Insert a new opcode and argument into an RE under construction.  The
** insertion point is just prior to existing opcode iBefore.
*/
static int sqlite3re_insert(sqlite3_ReCompiled *p, int iBefore, int op, int arg){
  int i;
  if( p->nAlloc<=p->nState && sqlite3re_resize(p, p->nAlloc*2) ) return 0;
  for(i=p->nState; i>iBefore; i--){
    p->aOp[i] = p->aOp[i-1];
    p->aArg[i] = p->aArg[i-1];
  }
  p->nState++;
  p->aOp[iBefore] = op;
  p->aArg[iBefore] = arg;
  return iBefore;
}

/* Append a new opcode and argument to the end of the RE under construction.
*/
static int sqlite3re_append(sqlite3_ReCompiled *p, int op, int arg){
  return sqlite3re_insert(p, p->nState, op, arg);
}

/* Make a copy of N opcodes starting at iStart onto the end of the RE
** under construction.
*/
static void sqlite3re_copy(sqlite3_ReCompiled *p, int iStart, int N){
  if( p->nState+N>=p->nAlloc && sqlite3re_resize(p, p->nAlloc*2+N) ) return;
  memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0]));
  memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0]));
  p->nState += N;
}

/* Return true if c is a hexadecimal digit character:  [0-9a-fA-F]
** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c).  If
** c is not a hex digit *pV is unchanged.
*/
static int sqlite3re_hex(int c, int *pV){
  if( c>='0' && c<='9' ){
    c -= '0';
  }else if( c>='a' && c<='f' ){
    c -= 'a' - 10;
  }else if( c>='A' && c<='F' ){
    c -= 'A' - 10;
  }else{
    return 0;
  }
  *pV = (*pV)*16 + (c & 0xff);
  return 1;
}

/* A backslash character has been seen, read the next character and
** return its interpretation.
*/
static unsigned sqlite3re_esc_char(sqlite3_ReCompiled *p){
  static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]";
  static const char zTrans[] = "\a\f\n\r\t\v";
  int i, v = 0;
  char c;
  if( p->sIn.i>=p->sIn.mx ) return 0;
  c = p->sIn.z[p->sIn.i];
  if( c=='u' && p->sIn.i+4<p->sIn.mx ){
    const unsigned char *zIn = p->sIn.z + p->sIn.i;
    if( sqlite3re_hex(zIn[1],&v)
     && sqlite3re_hex(zIn[2],&v)
     && sqlite3re_hex(zIn[3],&v)
     && sqlite3re_hex(zIn[4],&v)
    ){
      p->sIn.i += 5;
      return v;
    }
  }
  if( c=='x' && p->sIn.i+2<p->sIn.mx ){
    const unsigned char *zIn = p->sIn.z + p->sIn.i;
    if( sqlite3re_hex(zIn[1],&v)
     && sqlite3re_hex(zIn[2],&v)
    ){
      p->sIn.i += 3;
      return v;
    }
  }
  for(i=0; zEsc[i] && zEsc[i]!=c; i++){}
  if( zEsc[i] ){
    if( i<6 ) c = zTrans[i];
    p->sIn.i++;
  }else{
    p->zErr = "unknown \\ escape";
  }
  return c;
}

/* Forward declaration */
static const char* sqlite3re_subcompile_string(sqlite3_ReCompiled*);

/* Peek at the next byte of input */
static unsigned char sqlite3rePeek(sqlite3_ReCompiled *p){
  return p->sIn.i<p->sIn.mx ? p->sIn.z[p->sIn.i] : 0;
}

/* Compile RE text into a sequence of opcodes.  Continue up to the
** first unmatched ")" character, then return.  If an error is found,
** return a pointer to the error message string.
*/
static const char* sqlite3re_subcompile_re(sqlite3_ReCompiled *p){
  const char *zErr;
  int iStart, iEnd, iGoto;
  iStart = p->nState;
  zErr = sqlite3re_subcompile_string(p);
  if( zErr ) return zErr;
  while( sqlite3rePeek(p)=='|' ){
    iEnd = p->nState;
    sqlite3re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart);
    iGoto = sqlite3re_append(p, RE_OP_GOTO, 0);
    p->sIn.i++;
    zErr = sqlite3re_subcompile_string(p);
    if( zErr ) return zErr;
    p->aArg[iGoto] = p->nState - iGoto;
  }
  return 0;
}

/* Compile an element of regular expression text (anything that can be
** an operand to the "|" operator).  Return NULL on success or a pointer
** to the error message if there is a problem.
*/
static const char* sqlite3re_subcompile_string(sqlite3_ReCompiled *p){
  int iPrev = -1;
  int iStart;
  unsigned c;
  const char *zErr;
  while( (c = p->xNextChar(&p->sIn))!=0 ){
    iStart = p->nState;
    switch( c ){
      case '|':
      case '$': 
      case ')': {
        p->sIn.i--;
        return 0;
      }
      case '(': {
        zErr = sqlite3re_subcompile_re(p);
        if( zErr ) return zErr;
        if( sqlite3rePeek(p)!=')' ) return "unmatched '('";
        p->sIn.i++;
        break;
      }
      case '.': {
        if( sqlite3rePeek(p)=='*' ){
          sqlite3re_append(p, RE_OP_ANYSTAR, 0);
          p->sIn.i++;
        }else{ 
          sqlite3re_append(p, RE_OP_ANY, 0);
        }
        break;
      }
      case '*': {
        if( iPrev<0 ) return "'*' without operand";
        sqlite3re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1);
        sqlite3re_append(p, RE_OP_FORK, iPrev - p->nState + 1);
        break;
      }
      case '+': {
        if( iPrev<0 ) return "'+' without operand";
        sqlite3re_append(p, RE_OP_FORK, iPrev - p->nState);
        break;
      }
      case '?': {
        if( iPrev<0 ) return "'?' without operand";
        sqlite3re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1);
        break;
      }
      case '{': {
        int m = 0, n = 0;
        int sz, j;
        if( iPrev<0 ) return "'{m,n}' without operand";
        while( (c=sqlite3rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; }
        n = m;
        if( c==',' ){
          p->sIn.i++;
          n = 0;
          while( (c=sqlite3rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; }
        }
        if( c!='}' ) return "unmatched '{'";
        if( n>0 && n<m ) return "n less than m in '{m,n}'";
        p->sIn.i++;
        sz = p->nState - iPrev;
        if( m==0 ){
          if( n==0 ) return "both m and n are zero in '{m,n}'";
          sqlite3re_insert(p, iPrev, RE_OP_FORK, sz+1);
          n--;
        }else{
          for(j=1; j<m; j++) sqlite3re_copy(p, iPrev, sz);
        }
        for(j=m; j<n; j++){
          sqlite3re_append(p, RE_OP_FORK, sz+1);
          sqlite3re_copy(p, iPrev, sz);
        }
        if( n==0 && m>0 ){
          sqlite3re_append(p, RE_OP_FORK, -sz);
        }
        break;
      }
      case '[': {
        int iFirst = p->nState;
        if( sqlite3rePeek(p)=='^' ){
          sqlite3re_append(p, RE_OP_CC_EXC, 0);
          p->sIn.i++;
        }else{
          sqlite3re_append(p, RE_OP_CC_INC, 0);
        }
        while( (c = p->xNextChar(&p->sIn))!=0 ){
          if( c=='[' && sqlite3rePeek(p)==':' ){
            return "POSIX character classes not supported";
          }
          if( c=='\\' ) c = sqlite3re_esc_char(p);
          if( sqlite3rePeek(p)=='-' ){
            sqlite3re_append(p, RE_OP_CC_RANGE, c);
            p->sIn.i++;
            c = p->xNextChar(&p->sIn);
            if( c=='\\' ) c = sqlite3re_esc_char(p);
            sqlite3re_append(p, RE_OP_CC_RANGE, c);
          }else{
            sqlite3re_append(p, RE_OP_CC_VALUE, c);
          }
          if( sqlite3rePeek(p)==']' ){ p->sIn.i++; break; }
        }
        if( c==0 ) return "unclosed '['";
        p->aArg[iFirst] = p->nState - iFirst;
        break;
      }
      case '\\': {
        int specialOp = 0;
        switch( sqlite3rePeek(p) ){
          case 'b': specialOp = RE_OP_BOUNDARY;   break;
          case 'd': specialOp = RE_OP_DIGIT;      break;
          case 'D': specialOp = RE_OP_NOTDIGIT;   break;
          case 's': specialOp = RE_OP_SPACE;      break;
          case 'S': specialOp = RE_OP_NOTSPACE;   break;
          case 'w': specialOp = RE_OP_WORD;       break;
          case 'W': specialOp = RE_OP_NOTWORD;    break;
        }
        if( specialOp ){
          p->sIn.i++;
          sqlite3re_append(p, specialOp, 0);
        }else{
          c = sqlite3re_esc_char(p);
          sqlite3re_append(p, RE_OP_MATCH, c);
        }
        break;
      }
      default: {
        sqlite3re_append(p, RE_OP_MATCH, c);
        break;
      }
    }
    iPrev = iStart;
  }
  return 0;
}

/* Free and reclaim all the memory used by a previously compiled
** regular expression.  Applications should invoke this routine once
** for every call to re_compile() to avoid memory leaks.
*/
void sqlite3re_free(sqlite3_ReCompiled *pRe){
  if( pRe ){
    sqlite3_free(pRe->aOp);
    sqlite3_free(pRe->aArg);
    sqlite3_free(pRe);
  }
}

/*
** Compile a textual regular expression in zIn[] into a compiled regular
** expression suitable for us by re_match() and return a pointer to the
** compiled regular expression in *ppRe.  Return NULL on success or an
** error message if something goes wrong.
*/
const char* sqlite3re_compile(sqlite3_ReCompiled **ppRe, const char *zIn, int noCase){
  sqlite3_ReCompiled *pRe;
  const char *zErr;
  int i, j;

  *ppRe = 0;
  pRe = sqlite3_malloc( sizeof(*pRe) );
  if( pRe==0 ){
    return "out of memory";
  }
  memset(pRe, 0, sizeof(*pRe));
  pRe->xNextChar = noCase ? sqlite3re_next_char_nocase : sqlite3re_next_char;
  if( sqlite3re_resize(pRe, 30) ){
    sqlite3re_free(pRe);
    return "out of memory";
  }
  if( zIn[0]=='^' ){
    zIn++;
  }else{
    sqlite3re_append(pRe, RE_OP_ANYSTAR, 0);
  }
  pRe->sIn.z = (unsigned char*)zIn;
  pRe->sIn.i = 0;
  pRe->sIn.mx = (int)strlen(zIn);
  zErr = sqlite3re_subcompile_re(pRe);
  if( zErr ){
    sqlite3re_free(pRe);
    return zErr;
  }
  if( sqlite3rePeek(pRe)=='$' && pRe->sIn.i+1>=pRe->sIn.mx ){
    sqlite3re_append(pRe, RE_OP_MATCH, RE_EOF);
    sqlite3re_append(pRe, RE_OP_ACCEPT, 0);
    *ppRe = pRe;
  }else if( pRe->sIn.i>=pRe->sIn.mx ){
    sqlite3re_append(pRe, RE_OP_ACCEPT, 0);
    *ppRe = pRe;
  }else{
    sqlite3re_free(pRe);
    return "unrecognized character";
  }

  /* The following is a performance optimization.  If the regex begins with
  ** ".*" (if the input regex lacks an initial "^") and afterwards there are
  ** one or more matching characters, enter those matching characters into
  ** zInit[].  The re_match() routine can then search ahead in the input 
  ** string looking for the initial match without having to run the whole
  ** regex engine over the string.  Do not worry able trying to match
  ** unicode characters beyond plane 0 - those are very rare and this is
  ** just an optimization. */
  if( pRe->aOp[0]==RE_OP_ANYSTAR ){
    for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){
      unsigned x = pRe->aArg[i];
      if( x<=127 ){
        pRe->zInit[j++] = x;
      }else if( x<=0xfff ){
        pRe->zInit[j++] = 0xc0 | (x>>6);
        pRe->zInit[j++] = 0x80 | (x&0x3f);
      }else if( x<=0xffff ){
        pRe->zInit[j++] = 0xd0 | (x>>12);
        pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f);
        pRe->zInit[j++] = 0x80 | (x&0x3f);
      }else{
        break;
      }
    }
    if( j>0 && pRe->zInit[j-1]==0 ) j--;
    pRe->nInit = j;
  }
  return pRe->zErr;
}

/*
** Implementation of the regexp() SQL function.  This function implements
** the build-in REGEXP operator.  The first argument to the function is the
** pattern and the second argument is the string.  So, the SQL statements:
**
**       A REGEXP B
**
** is implemented as regexp(B,A).
*/
static void re_sql_func(
  sqlite3_context *context, 
  int argc, 
  sqlite3_value **argv
){
  sqlite3_ReCompiled *pRe;  /* Compiled regular expression */
  const char *zPattern;     /* The regular expression */
  const unsigned char *zStr;/* String being searched */
  const char *zErr;         /* Compile error message */
  int setAux = 0;           /* True to invoke sqlite3_set_auxdata() */

  pRe = sqlite3_get_auxdata(context, 0);
  if( pRe==0 ){
    zPattern = (const char*)sqlite3_value_text(argv[0]);
    if( zPattern==0 ) return;
    zErr = sqlite3re_compile(&pRe, zPattern, 0);
    if( zErr ){
      sqlite3re_free(pRe);
      sqlite3_result_error(context, zErr, -1);
      return;
    }
    if( pRe==0 ){
      sqlite3_result_error_nomem(context);
      return;
    }
    setAux = 1;
  }
  zStr = (const unsigned char*)sqlite3_value_text(argv[1]);
  if( zStr!=0 ){
    sqlite3_result_int(context, sqlite3re_match(pRe, zStr, -1));
  }
  if( setAux ){
    sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))sqlite3re_free);
  }
}

/*
** Invoke this routine to register the regexp() function with the
** SQLite database connection.
*/
int sqlite3_regexp_init(
  sqlite3 *db, 
  char **pzErrMsg, 
  const struct sqlite3_api_routines *pApi
){
  int rc = SQLITE_OK;
#ifndef SQLITE_CORE
	SQLITE_EXTENSION_INIT2(pApi)	/*sets up the 'vtable' to the host exe sqlite3 impl*/
#else
#endif
  rc = sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8, 0,
                                 re_sql_func, 0, 0);
  return rc;
}
/* end of file ext_regexp.c */
/* start of file 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
26877
26878
26879
26880
26881
26882
26883


26884
26885
26886
26887
26888
26889

26890
26891

26892
26893
26894
26895
26896
26897
26898
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662







+
+






+


+







    case ENOMEM:
      return FSL_RC_OOM;
    case EROFS:
    case EACCES:
    case EBUSY:
    case EPERM:
    case EDQUOT:
    case EAGAIN:
    case ETXTBSY:
      return FSL_RC_ACCESS;
    case EISDIR:
    case ENOTDIR:
      return FSL_RC_TYPE;
    case ENAMETOOLONG:
    case ELOOP:
    case ERANGE:
      return FSL_RC_RANGE;
    case ENOENT:
    case ESRCH:
      return FSL_RC_NOT_FOUND;
    case EEXIST:
    case ENOTEMPTY:
      return FSL_RC_ALREADY_EXISTS;
    case EIO:
      return FSL_RC_IO;
    default:
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
29538
29539
29540
29541
29542
29543
29544



29545
29546
29547


29548
29549
29550
29551
29552
29553



29554


29555


29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569

29570
29571
29572

29573

29574
29575
29576
29577
29578

29579
29580
29581
29582
29583
29584
29585
29586







-
-
-
+
+
+
-
-

+




-
-
-
+
-
-
+
-
-














-



-
+
-





-
+







    printf pfexp;                                                   \
  } while(0)

/**
    fsl_appendf_f() impl which sends its output to fsl_output(). state
    must be a (fsl_cx*).
 */
static fsl_int_t fsl_appendf_f_fsl_output( void * state, char const * s,
                                           fsl_int_t n ){
  return fsl_output( (fsl_cx *)state, s, (fsl_size_t)n )
static int fsl_output_f_fsl_output( void * state, void const * s,
                                    fsl_size_t n ){
  return fsl_output( (fsl_cx *)state, s, n );
    ? -1
    : n;
}


int fsl_outputfv( fsl_cx * f, char const * fmt, va_list args ){
  if(!f || !fmt) return FSL_RC_MISUSE;
  else if(!*fmt) return FSL_RC_RANGE;
  else{
    long const prc = fsl_appendfv( fsl_appendf_f_fsl_output,
                                   f, fmt, args );
  return fsl_appendfv( fsl_output_f_fsl_output, f, fmt, args );
    return (prc>=0) ? 0 : FSL_RC_IO;
  }
}
}

    
int fsl_outputf( fsl_cx * f, char const * fmt, ... ){
  if(!f || !fmt) return FSL_RC_MISUSE;
  else if(!*fmt) return FSL_RC_RANGE;
  else{
    int rc;
    va_list args;
    va_start(args,fmt);
    rc = fsl_outputfv( f, fmt, args );
    va_end(args);
    return rc;
  }
}


int fsl_output( fsl_cx * cx, void const * src, fsl_size_t n ){
  if(!cx || !src) return FSL_RC_MISUSE;
  else if(!n || !cx->output.out) return 0;
  else return cx->output.out( cx->output.state.state,
  else return cx->output.out( cx->output.state, src, n );
                              src, n );
}

int fsl_flush( fsl_cx * f ){
  return f
    ? (f->output.flush
       ? f->output.flush(f->output.state.state)
       ? f->output.flush(f->output.state)
       : 0)
    : FSL_RC_MISUSE;
}


int fsl_flush_f_FILE(void * _FILE){
  return _FILE
28429
28430
28431
28432
28433
28434
28435




















































































































































28436
28437
28438
28439
28440
28441
28442
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346







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









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 */
/* -*- 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
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

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

#include <string.h> /* memcmp() */


/* definitions for various UTF-8 sequence lengths, encoded as start value
 * and size of each valid range belonging to some lead byte*/
#define US2A  0x80, 0x01 /* for lead byte 0xC0 */
#define US2B  0x80, 0x40 /* for lead bytes 0xC2-0xDF */
#define US3A  0xA0, 0x20 /* for lead byte 0xE0 */
#define US3B  0x80, 0x40 /* for lead bytes 0xE1-0xEF */
#define US4A  0x90, 0x30 /* for lead byte 0xF0 */
#define US4B  0x80, 0x40 /* for lead bytes 0xF1-0xF3 */
#define US4C  0x80, 0x10 /* for lead byte 0xF4 */
#define US0A  0x00, 0x00 /* for any other lead byte */

/* a table used for quick lookup of the definition that goes with a
 * particular lead byte */
static const unsigned char lb_tab[] = {
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A,
  US2A, US0A, US2B, US2B, US2B, US2B, US2B, US2B,
  US2B, US2B, US2B, US2B, US2B, US2B, US2B, US2B,
  US2B, US2B, US2B, US2B, US2B, US2B, US2B, US2B,
  US2B, US2B, US2B, US2B, US2B, US2B, US2B, US2B,
  US3A, US3B, US3B, US3B, US3B, US3B, US3B, US3B,
  US3B, US3B, US3B, US3B, US3B, US3B, US3B, US3B,
  US4A, US4B, US4B, US4B, US4C, US0A, US0A, US0A,
  US0A, US0A, US0A, US0A, US0A, US0A, US0A, US0A
};

#undef US2A
#undef US2B
#undef US3A
#undef US3B
#undef US4A
#undef US4B
#undef US4C
#undef US0A

int fsl_looks_like_utf8(fsl_buffer const * const b, int stopFlags){
  fsl_size_t n;
  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 */
  c = *z;
  if( c==0 ){
    flags |= FSL_LOOKSLIKE_NUL;  /* NUL character in a file -> binary */
  }else if( c=='\r' ){
    flags |= FSL_LOOKSLIKE_CR;
    if( n<=1 || z[1]!='\n' ){
      flags |= FSL_LOOKSLIKE_LONE_CR;  /* Not enough chars or next char not LF */
    }
  }
  j = (c!='\n');
  if( !j ) flags |= (FSL_LOOKSLIKE_LF | FSL_LOOKSLIKE_LONE_LF);  /* Found LF as first char */
  while( !(flags&stopFlags) && --n>0 ){
    int c2 = c;
    c = *++z; ++j;
    if( c==0 ){
      flags |= FSL_LOOKSLIKE_NUL;  /* NUL character in a file -> binary */
    }else if( c=='\n' ){
      flags |= FSL_LOOKSLIKE_LF;
      if( c2=='\r' ){
        flags |= (FSL_LOOKSLIKE_CR | FSL_LOOKSLIKE_CRLF);  /* Found LF preceded by CR */
      }else{
        flags |= FSL_LOOKSLIKE_LONE_LF;
      }
      if( j>FSL_LINE_LENGTH_MASK ){
        flags |= FSL_LOOKSLIKE_LONG;  /* Very long line -> binary */
      }
      j = 0;
    }else if( c=='\r' ){
      flags |= FSL_LOOKSLIKE_CR;
      if( n<=1 || z[1]!='\n' ){
        flags |= FSL_LOOKSLIKE_LONE_CR;  /* Not enough chars or next char not LF */
      }
    }
  }
  if( n ){
    flags |= FSL_LOOKSLIKE_SHORT;  /* The whole blob was not examined */
  }
  if( j>FSL_LINE_LENGTH_MASK ){
    flags |= FSL_LOOKSLIKE_LONG;  /* Very long line -> binary */
  }
  return flags;
}

unsigned char const *fsl_utf8_bom(unsigned int *pnByte){
  static const unsigned char bom[] = {
    0xef, 0xbb, 0xbf, 0x00, 0x00, 0x00
  };
  if( pnByte ) *pnByte = 3;
  return bom;
}

bool fsl_starts_with_bom_utf8(fsl_buffer const * const b,
                              unsigned int *pBomSize){
  unsigned int bomSize;
  const char * const z = fsl_buffer_cstr(b);
  const unsigned char * const bom = fsl_utf8_bom(&bomSize);
  if( pBomSize ) *pBomSize = bomSize;
  return fsl_buffer_size(b)<bomSize
    ? false
    : memcmp(z, bom, bomSize)==0;
}

bool fsl_invalid_utf8(fsl_buffer const * const b){
  fsl_size_t n;
  const unsigned char *z = (unsigned char *) fsl_buffer_cstr2(b, &n);
  unsigned char c; /* lead byte to be handled. */
  if( n==0 ) return false;  /* Empty file -> OK */
  c = *z;
  while( --n>0 ){
    if( c>=0x80 ){
      const unsigned char *def; /* pointer to range table*/
      c <<= 1; /* multiply by 2 and get rid of highest bit */
      def = &lb_tab[c]; /* search fb's valid range in table */
      if( (unsigned int)(*++z-def[0])>=def[1] ){
        return false/*FSL_LOOKSLIKE_INVALID*/;
      }
      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 */
/* -*- 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:
*/
/*
28634
28635
28636
28637
28638
28639
28640
28641

28642
28643
28644
28645
28646
28647
28648
30538
30539
30540
30541
30542
30543
30544

30545
30546
30547
30548
30549
30550
30551
30552







-
+







    memcpy(ctx->in, buf, len);
}

/*
 * Final wrapup - pad to 64-byte boundary with the bit pattern 
 * 1 0* (64-bit count of bits processed, MSB-first)
 */
void fsl_md5_final(fsl_md5_cx * ctx, unsigned char digest[16]){
void fsl_md5_final(fsl_md5_cx * ctx, unsigned char * digest){
    unsigned count;
    unsigned char *p;

    /* Compute number of bytes mod 64 */
    count = (ctx->bits[0] >> 3) & 0x3F;

    /* Set the first char of padding to 0x80.  This is safe since there is
29879
29880
29881
29882
29883
29884
29885
29886
29887


29888
29889
29890
29891
29892
29893
29894
31783
31784
31785
31786
31787
31788
31789


31790
31791
31792
31793
31794
31795
31796
31797
31798







-
-
+
+







  }
  return ans;
  oom:
  fsl_cx_err_set(f, FSL_RC_OOM, NULL);
  return -1;
}

int fsl_sym_to_rid( fsl_cx * f, char const * sym, fsl_satype_e type,
                    fsl_id_t * rv ){
int fsl_sym_to_rid( fsl_cx * const f, char const * sym,
                    fsl_satype_e type, fsl_id_t * rv ){
  fsl_id_t rid = 0;
  fsl_id_t vid;
  fsl_size_t symLen;
  /* fsl_int_t i; */
  fsl_db * dbR = fsl_cx_db_repo(f);
  fsl_db * dbC = fsl_cx_db_ckout(f);
  bool startOfBranch = 0;
31385
31386
31387
31388
31389
31390
31391















































































31392
31393
31394
31395
31396
31397
31398
33289
33290
33291
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







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







  }
  end:
  fsl_cx_scratchpad_yield(f, sql);
  fsl_stmt_finalize(&q);
  return rc;
}

int fsl_repo_manifest_write(fsl_cx *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){
    manifestRid = f->ckout.rid;
    if(manifestRid<=0){
      return fsl_cx_err_set(f, 0==f->ckout.rid
                            ? FSL_RC_RANGE
                            : FSL_RC_NOT_A_CKOUT,
                            "%s(): no checkin version was specified "
                            "and %s.", __func__,
                            0==f->ckout.rid
                            ? "checkout has no version"
                            : "no checkout is opened");
    }
  }
  int rc = 0;
  char * str = 0;
  fsl_uuid_str ridHash = 0;
  fsl_buffer * bHash = 0;
  assert(manifestRid>0);
  
  if(pManifest){
    fsl_buffer_reuse(pManifest);
    rc = fsl_content_get(f, manifestRid, pManifest);
    if(rc) goto end;
  }
  if(pHash){
    if(f->ckout.rid!=manifestRid){
      bHash = fsl_cx_scratchpad(f);
      rc = fsl_rid_to_uuid2(f, manifestRid, bHash);
      if(rc) goto end;
      ridHash = (char *)bHash->mem;
    }else{
      ridHash = f->ckout.uuid;
    }
    assert(ridHash);
    rc = fsl_buffer_append(pHash, ridHash, -1);
    if(!rc) rc = fsl_buffer_append(pHash, "\n", 1);
    if(rc) goto end;
  }
  if(pTags){
    fsl_stmt q = fsl_stmt_empty;
    fsl_db * const db = fsl_cx_db_repo(f);
    assert(db && "We can't have a checkout w/o a repo.");
    str = fsl_db_g_text(db, NULL, "SELECT VALUE FROM tagxref "
                        "WHERE rid=%" FSL_ID_T_PFMT
                        " AND tagid=%d /*%s()*/",
                        f->ckout.rid, FSL_TAGID_BRANCH, __func__);
    rc = fsl_buffer_appendf(pTags, "branch %z\n", str);
    str = 0;
    if(rc) goto end;
    rc = fsl_db_prepare(db, &q,
                        "SELECT substr(tagname, 5)"
                        "  FROM tagxref, tag"
                        " WHERE tagxref.rid=%" FSL_ID_T_PFMT
                        "   AND tagxref.tagtype>0"
                        "   AND tag.tagid=tagxref.tagid"
                        "   AND tag.tagname GLOB 'sym-*'"
                        " /*%s()*/",
                        f->ckout.rid, __func__);
    if(rc) goto end;
    while( FSL_RC_STEP_ROW==fsl_stmt_step(&q) ){
      const char *zName = fsl_stmt_g_text(&q, 0, NULL);
      rc = fsl_buffer_appendf(pTags, "tag %s\n", zName);
      if(rc) break;
    }
    fsl_stmt_finalize(&q);
  }
  end:
  if(bHash){
    fsl_cx_scratchpad_yield(f, bHash);
  }
  return rc;
}

/**
   NOT YET IMPLEMENTED. (We have the infrastructure, just need to glue
   it together.)

   Re-crosslinks all artifacts of the given type (or all artifacts if
   the 2nd argument is FSL_SATYPE_ANY). This is an expensive
35095
35096
35097
35098
35099
35100
35101
35102

35103
35104
35105
35106
35107
35108
35109
37078
37079
37080
37081
37082
37083
37084

37085
37086
37087
37088
37089
37090
37091
37092







-
+







    /*
      Legacy: i don't want this behaviour in the lib right now
      (possibly never). And don't want to port it yet, either :/.
     */
    if( tagid==FSL_TAGID_COMMENT ){
      char *zCopy = fsl_strdup(zValue);
      wiki_extract_links(zCopy, rid, 0, mtime, 1, WIKI_INLINE);
      free(zCopy);
      fsl_free(zCopy);
    }
#endif
  }

  if( FSL_TAGID_DATE == tagid ){
    rc = fsl_db_exec(db, "UPDATE event "
                     "SET mtime=julianday(%Q),"
35779
35780
35781
35782
35783
35784
35785































35786
35787
35788
35789
35790
35791
35792
37762
37763
37764
37765
37766
37767
37768
37769
37770
37771
37772
37773
37774
37775
37776
37777
37778
37779
37780
37781
37782
37783
37784
37785
37786
37787
37788
37789
37790
37791
37792
37793
37794
37795
37796
37797
37798
37799
37800
37801
37802
37803
37804
37805
37806







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







  fsl_free(uName);
#else
  char *zValue = (char *)getenv(zName);
#endif
  if( zValue ) zValue = fsl_filename_to_utf8(zValue);
  return zValue;
}

fsl_size_t fsl_strlen_utf8( char const * str, fsl_int_t len ){
  if( !str || !len ) return 0;
  else if(len<0){
    len = (fsl_int_t)fsl_strlen(str);
  }
  {
    char unsigned const * x = (char unsigned const *)str;
    char unsigned const * end = x + len;
    fsl_size_t rc = 0;
    /* Derived from:
       http://www.daemonology.net/blog/2008-06-05-faster-utf8-strlen.html
    */
    for( ; x < end; ++x, ++rc ){
      switch(0xF0 & *x) {
        case 0xF0: /* length 4 */
          x += 3;
          break;
        case 0xE0: /* length 3 */
          x+= 2;
          break;
        case 0xC0: /* length 2 */
          x += 1;
          break;
        default:
          break;
      }
    }
    return rc;
  }
}
/* end of file utf8.c */
/* start of file 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

35843
35844
35845
35846
35847
35848
35849
35850

35851
35852
35853
35854
35855
35856
35857
37857
37858
37859
37860
37861
37862
37863

37864
37865
37866
37867
37868
37869
37870
37871







-
+







    rc = 0;
    goto end;
  }
  if(rc) goto end;

  if(0==vid){
    /* This is either misuse or an empty/initial repo with no
       checkins.  Let's assume the latter, since that's what triggered
       checkins. Let's assume the latter, since that's what triggered
       the addition of this check. */
    goto end;
  }

  rc = fsl_deck_load_rid(f, &d, vid, FSL_SATYPE_CHECKIN);
  if(rc) goto end;
  assert(d.rid==vid);
35948
35949
35950
35951
35952
35953
35954
35955
35956


35957
35958
35959
35960
35961
35962
35963
35964
35965
35966
35967
35968
35969
35970
35971
35972
35973
35974
35975
35976
35977
35978
35979
35980
35981
37962
37963
37964
37965
37966
37967
37968


37969
37970
37971
37972
37973
37974
37975
37976
37977
37978
37979
37980
37981
37982
37983
37984
37985
37986
37987

37988
37989
37990
37991
37992
37993
37994







-
-
+
+

















-







   file's hash in order to be sure whether it was really
   modified. hashLen must be the length of the previous (db-side) hash
   of the file. This routine will hash that file using the same hash
   type. The new hash is appended to pTgt.

   Returns 0 on success.
*/
static int fsl_vfile_recheck_file_hash( fsl_cx * f, const char * zName,
                                        fsl_size_t hashLen, fsl_buffer * pTgt ){
static int fsl_vfile_recheck_file_hash( fsl_cx * const f, const char * const zName,
                                        fsl_size_t hashLen, fsl_buffer * const pTgt ){
  bool errReported = false;
  int rc = 0;
  if((fsl_size_t)FSL_STRLEN_SHA1==hashLen){
    rc = fsl_sha1sum_filename(zName, pTgt);
  }else if((fsl_size_t)FSL_STRLEN_K256==hashLen){
    rc = fsl_sha3sum_filename(zName, pTgt);
  }else{
    assert(!"This \"cannot happen\".");
    rc = fsl_cx_err_set(f, FSL_RC_CHECKSUM_MISMATCH,
                        "Cannot determine which hash to use for file: %s",
                        zName);
    errReported = true;
  }
  if(rc && !errReported && FSL_RC_OOM != rc){
    rc = fsl_cx_err_set(f, rc, "Error %s while hashing file: %s",
                        fsl_rc_cstr(rc), zName);
  }
  //if(!rc) assert(fsl_is_uuid_len(pTgt->used));
  return rc;
}


int fsl_vfile_changes_scan(fsl_cx * f, fsl_id_t vid, unsigned cksigFlags){
  fsl_stmt * stUpdate = NULL;
  fsl_stmt q = fsl_stmt_empty;
35993
35994
35995
35996
35997
35998
35999
36000
36001


36002
36003
36004
36005
36006
36007
36008
36009
38006
38007
38008
38009
38010
38011
38012


38013
38014

38015
38016
38017
38018
38019
38020
38021







-
-
+
+
-







  rootLen = fsl_strlen(f->ckout.dir);
  assert(rootLen);

  rc = fsl_db_transaction_begin(db);
  if(rc) return rc;
  if(f->ckout.rid != vid){
    rc = fsl_vfile_load(f, vid,
                                 (FSL_VFILE_CKSIG_KEEP_OTHERS & cksigFlags)
                                 ? false : true,
                        (FSL_VFILE_CKSIG_KEEP_OTHERS & cksigFlags)
                        ? false : true, NULL);
                                 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, "
36476
36477
36478
36479
36480
36481
36482
36483

36484
36485
36486
36487
36488
36489
36490
38488
38489
38490
38491
38492
38493
38494

38495
38496
38497
38498
38499
38500
38501
38502







-
+







  rc->u.pPeer = path->pCurrent;
  path->pCurrent = rc;
  rc->pAll = path->pAll;
  path->pAll = rc;
  return rc;
}

int fsl_vpath_shortest( fsl_cx * f, fsl_vpath * path,
int fsl_vpath_shortest( fsl_cx * const f, fsl_vpath * const path,
                        fsl_id_t iFrom, fsl_id_t iTo,
                        bool directOnly, bool oneWayOnly ){
  fsl_stmt s = fsl_stmt_empty;
  fsl_db * db = fsl_needs_repo(f);
  int rc = 0;
  fsl_vpath_node * pPrev;
  fsl_vpath_node * p;
36567
36568
36569
36570
36571
36572
36573








































































36574
36575
36576
36577
36578
36579
36580
38579
38580
38581
38582
38583
38584
38585
38586
38587
38588
38589
38590
38591
38592
38593
38594
38595
38596
38597
38598
38599
38600
38601
38602
38603
38604
38605
38606
38607
38608
38609
38610
38611
38612
38613
38614
38615
38616
38617
38618
38619
38620
38621
38622
38623
38624
38625
38626
38627
38628
38629
38630
38631
38632
38633
38634
38635
38636
38637
38638
38639
38640
38641
38642
38643
38644
38645
38646
38647
38648
38649
38650
38651
38652
38653
38654
38655
38656
38657
38658
38659
38660
38661
38662
38663
38664







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







    }
  }
  end:
  fsl_stmt_finalize(&s);
  fsl_vpath_clear(path);
  return rc;
}

/**
   Creates, if needed, the [ancestor] table, else clears its
   contents. Returns 
 */
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,"
                           "  generation INTEGER PRIMARY KEY"
                           ");"
                           "DELETE FROM TEMP.ancestor;");
  }else{
    rc = fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                        "Cannot compute ancestors without an "
                        "opened repository.");
  }
  return rc ? fsl_cx_uplift_db_error2(f, db, rc) : 0;
}

int fsl_compute_direct_ancestors(fsl_cx * const f, fsl_id_t rid){
  int rc = fsl__init_ancestor(f);
  fsl_db * const db = rc ? NULL : fsl_needs_repo(f);
  if(rc) return rc;
  assert(db);
  return fsl_db_exec_multi(db,
      "WITH RECURSIVE g(x,i) AS ("
      "  VALUES(%" FSL_ID_T_PFMT ",1)"
      "  UNION ALL"
      "  SELECT plink.pid, g.i+1 FROM plink, g"
      "   WHERE plink.cid=g.x AND plink.isprim)"
      "INSERT INTO ancestor(rid,generation) SELECT x,i FROM g;",
      rid
  );
}

int fsl_vpath_shortest_store_in_ancestor(fsl_cx * const f,
                                         fsl_id_t iFrom,
                                         fsl_id_t iTo,
                                         uint32_t *pSteps){
  int rc;
  fsl_vpath path = fsl_vpath_empty;
  fsl_stmt ins = fsl_stmt_empty;
  fsl_db * const db = fsl_needs_repo(f);
  fsl_vpath_node * node;
  int32_t gen = 0;
  if(!db) return FSL_RC_NOT_A_REPO;
  rc = fsl_vpath_shortest(f, &path, iFrom, iTo, true, false);
  if(rc) goto end;
  rc = fsl__init_ancestor(f);
  if(rc) goto end;
  rc = fsl_db_prepare(db, &ins,
                      "INSERT INTO TEMP.ancestor(rid, generation) "
                      "VALUES(?,?)");
  if(rc) goto dberr;
  for(node = fsl_vpath_first(&path);
      node; node = fsl_vpath_next(node)){
    rc = fsl_stmt_bind_step(&ins, "Ri", node->rid, ++gen);
    if(rc) goto dberr;
  }
  end:
  if(0==rc && pSteps) *pSteps = (uint32_t)gen;
  fsl_stmt_finalize(&ins);
  fsl_vpath_clear(&path);
  return rc;
  dberr:
  assert(rc!=0);
  return fsl_cx_uplift_db_error2(f, db, rc);
}

/*
** A record of a file rename operation.
*/
typedef struct NameChange NameChange;
struct NameChange {
  fsl_id_t origName;        /* Original name of file */
36734
36735
36736
36737
36738
36739
36740
36741
36742
36743
36744
36745
36746
36747
36748
38818
38819
38820
38821
38822
38823
38824

38825
38826
38827
38828
38829
38830
38831







-







  fsl_vpath_clear(&path);
  return rc;
  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 */
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
37450
37451
37452
37453
37454
37455
37456



























37457
37458
37459



37460
37461
37462
37463
37464
37465
37466
39533
39534
39535
39536
39537
39538
39539
39540
39541
39542
39543
39544
39545
39546
39547
39548
39549
39550
39551
39552
39553
39554
39555
39556
39557
39558
39559
39560
39561
39562
39563
39564
39565
39566



39567
39568
39569
39570
39571
39572
39573
39574
39575
39576







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







      }else{
        rc = fsl_cx_err_set(f, FSL_RC_RANGE, "Cowardly refusing to create "
                            "empty ZIP file for repo version [%.*s].",
                            12, mf.uuid);
      }
      if(rc) goto end;
    }
  }

  /**
     Always write he manifest files to the zip, regardless of
     the repo-level settings. */
  if(rc) goto end;
  else {
    fsl_buffer * const bManifest = &f->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);
    if(rc) goto mf_end;
    rc = fsl_zip_file_add(&zs.z, "manifest.uuid", bHash,
                          FSL_FILE_PERM_REGULAR);
    if(rc) goto mf_end;
    rc = fsl_zip_file_add(&zs.z, "manifest.tags", bTags,
                          FSL_FILE_PERM_REGULAR);
    mf_end:
    fsl_buffer_reuse(bManifest);
    fsl_cx_scratchpad_yield(f, bHash);
    fsl_cx_scratchpad_yield(f, bTags);
  }
  if(rc) goto end;
    rc = fsl_zip_end( &zs.z );
    if(!rc) rc = fsl_buffer_to_filename( fsl_zip_body(&zs.z), fileName );
  }
  rc = fsl_zip_end( &zs.z );
  if(!rc) rc = fsl_buffer_to_filename( fsl_zip_body(&zs.z), fileName );
  
  end:
  if(rc && !f->error.code){
    fsl_cx_err_set(f, rc, "Error #%d (%s) during ZIP.",
                   rc, fsl_rc_cstr(rc));
  }
  fsl_buffer_clear(&zs.cbuf);
  fsl_zip_finalize(&zs.z);

Changes to src/libfossil.h.

551
552
553
554
555
556
557
558

559
560
561
562
563
564
565
566
551
552
553
554
555
556
557

558

559
560
561
562
563
564
565







-
+
-







   semantics similar to fsl_input_f(): at call-time n is the number
   of bytes to output, and on returning n is the number of bytes
   actually written. This would allow, e.g. the fsl_zip_writer APIs
   to be able to stream a ZIP file (they have to know the real size
   of the output, and this interface doesn't support that
   operation).
*/
typedef int (*fsl_output_f)( void * state,
typedef int (*fsl_output_f)( void * state, void const * src, fsl_size_t n );
                             void const * src, fsl_size_t n );


/**
   Generic interface for flushing arbitrary output streams.  Must
   return 0 on success, non-0 on error, but the result code
   "should" (to avoid downstream confusion) be one of the fsl_rc_e
   values. When in doubt, return FSL_RC_IO on error. The
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
575
576
577
578
579
580
581







582
583
584
585
586
587
588







-
-
-
-
-
-
-







   return non-0 on error (assumed to be a value from the fsl_rc_e
   enum). When called, *n is the max length to read. On return, *n
   is the actual amount read. The state parameter is the
   implementation-specified input file/buffer/whatever channel.
*/
typedef int (*fsl_input_f)( void * state, void * dest, fsl_size_t * n );

/**
   fsl_output_f() implementation which requires state to be a
   writeable (FILE*) handle. Is a no-op (returning 0) if
   !n. Returns FSL_RC_MISUSE if !state or !src.
*/
FSL_EXPORT int fsl_output_f_FILE( void * state, void const * src, fsl_size_t n );

/**
   fsl_output_f() implementation which requires state to be a
   (fsl_cx*) to which this routine simply redirects the output via
   fsl_output().  Is a no-op (returning 0) if !n. Returns
   FSL_RC_MISUSE if !state or !src.
*/
FSL_EXPORT int fsl_output_f_fsl_cx(void * state, void const * src, fsl_size_t n );
607
608
609
610
611
612
613
614



615
616
617
618
619

620
621

622
623
624

625
626
627
628
629
630
631
632
633

634
635

636
637
638
639
640
641
642
643
644
645
646
647
648
649
650

651
652

653
654
655
656
657
658
659
660
661
599
600
601
602
603
604
605

606
607
608
609
610
611
612

613
614

615
616
617

618
619
620
621
622
623
624
625
626

627
628

629





630
631
632
633
634
635
636
637
638

639


640


641
642
643
644
645
646
647







-
+
+
+




-
+

-
+


-
+








-
+

-
+
-
-
-
-
-









-
+
-
-
+
-
-







*/
struct fsl_outputer {
  /**
     Output channel.
  */
  fsl_output_f out;
  /**
     flush() implementation.
     flush() implementation. This may be NULL for most uses of this
     class. Cases which specifically require it must document that
     requirement so.
  */
  fsl_flush_f flush;
  /**
     State to be used when calling this->out(), namely:
     this->out( this->state.state, ... ).
     this->out( this->state, ... ) and this->flush(this->state).
  */
  fsl_state state;
  void * state;
};
/** Empty-initialized fsl_outputer instance. */
#define fsl_outputer_empty_m {NULL,NULL,fsl_state_empty_m}
#define fsl_outputer_empty_m {NULL,NULL,NULL}
/**
   Empty-initialized fsl_outputer instance, intended for
   copy-initializing.
*/
FSL_EXPORT const fsl_outputer fsl_outputer_empty;

/**
   A fsl_outputer instance which is initialized to output to a
   (FILE*). To use it, this value then set the copy's state.state
   (FILE*). To use it, this value then set the copy's state
   member to an opened-for-write (FILE*) handle. By default it will
   use stdout. Its finalizer (if called!) will fclose(3)
   use stdout.
   self.state.state if self.state.state is not one of (stdout,
   stderr). To disable the closing behaviour (and not close the
   file), set self.state.finalize.f to NULL (but then be sure that
   the file handle outlives this object and to fclose(3) it when
   finished with it).
*/
FSL_EXPORT const fsl_outputer fsl_outputer_FILE;

/**
   fsl_outputer initializer which uses fsl_flush_f_FILE(),
   fsl_output_f_FILE(), and fsl_finalizer_f_FILE().
*/
#define fsl_outputer_FILE_m {                   \
    fsl_output_f_FILE,                          \
      fsl_flush_f_FILE,                         \
    fsl_flush_f_FILE,                         \
      {/*state*/                                \
        NULL,                                   \
    NULL \
        {NULL,fsl_finalizer_f_FILE}             \
      }                                         \
  }
/**
   Generic stateful alloc/free/realloc() interface.

   Implementations must behave as follows:

   - If 0==n then semantically behave like free(3) and return
1021
1022
1023
1024
1025
1026
1027
1028

1029
1030
1031
1032
1033
1034

1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047

1048
1049
1050
1051
1052
1053
1054
1007
1008
1009
1010
1011
1012
1013

1014
1015
1016
1017
1018
1019

1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032

1033
1034
1035
1036
1037
1038
1039
1040







-
+





-
+












-
+







   to avoid a memory allocation (which would presumably fail).

   @see fsl_error_get()
   @see fsl_error_clear()
   @see fsl_error_move()
*/
FSL_EXPORT int fsl_error_set( fsl_error * err, int code, char const * fmt,
                   ... );
                              ... );

/**
   va_list counterpart to fsl_error_set().
*/
FSL_EXPORT int fsl_error_setv( fsl_error * err, int code, char const * fmt,
                    va_list args );
                               va_list args );

/**
   Fetches the error state from err. If !err it returns
   FSL_RC_MISUSE without side-effects, else it returns err's current
   error code.

   If str is not NULL then *str will be assigned to the raw
   (NUL-terminated) error string (which might be empty or even
   NULL). The memory for the string is owned by err and may be
   invalidated by any calls which take err as a non-const parameter
   OR which might modify it indirectly through a container object,
   so the client is required to copy it if it is needed for later
   on.
   reference.

   If len is not NULL then *len will be assigned to the length of
   the returned string (in bytes).

   @see fsl_error_set()
   @see fsl_error_clear()
   @see fsl_error_move()
1282
1283
1284
1285
1286
1287
1288
1289

1290
1291



1292
1293
1294
1295
1296

1297
1298
1299
1300


1301
1302
1303
1304
1305
1306
1307
1268
1269
1270
1271
1272
1273
1274

1275


1276
1277
1278
1279
1280
1281
1282

1283
1284
1285


1286
1287
1288
1289
1290
1291
1292
1293
1294







-
+
-
-
+
+
+




-
+


-
-
+
+







   @see fsl_buffer_appendf()
   @see fsl_buffer_reserve()
*/
FSL_EXPORT int fsl_buffer_append( fsl_buffer * b,
                                  void const * src, fsl_int_t n );

/**
   Uses fsl_appendf() to append formatted output to the given
   Uses fsl_appendf() to append formatted output to the given buffer.
   buffer.  Returns 0 on success, FSL_RC_MISUSE if !f or !dest, and
   FSL_RC_OOM if an allocation fails while expanding dest.
   Returns 0 on success and FSL_RC_OOM if an allocation fails while
   expanding dest. Results are undefined if either of the first two
   arguments are NULL.

   @see fsl_buffer_append()
   @see fsl_buffer_reserve()
*/
FSL_EXPORT int fsl_buffer_appendf( fsl_buffer * dest,
FSL_EXPORT int fsl_buffer_appendf( fsl_buffer * const dest,
                                   char const * fmt, ... );

/** va_list counterpart to fsl_buffer_appendfv(). */
FSL_EXPORT int fsl_buffer_appendfv( fsl_buffer * dest,
/** va_list counterpart to fsl_buffer_appendf(). */
FSL_EXPORT int fsl_buffer_appendfv( fsl_buffer * const dest,
                                    char const * fmt, va_list args );

/**
   Compresses the first pIn->used bytes of pIn to pOut. It is ok for
   pIn and pOut to be the same blob.

   pOut must either be the same as pIn or else a properly
1678
1679
1680
1681
1682
1683
1684
1685

1686
1687

1688
1689
1690


1691
1692
1693

1694
1695
1696
1697
1698

1699
1700
1701
1702
1703
1704
1705
1665
1666
1667
1668
1669
1670
1671

1672


1673
1674


1675
1676

1677

1678
1679
1680
1681
1682

1683
1684
1685
1686
1687
1688
1689
1690







-
+
-
-
+

-
-
+
+
-

-
+




-
+







/**
   va_list counterpart to fsl_mprintf().
*/
FSL_EXPORT char * fsl_mprintfv(char const * fmt, va_list vargs );

/**
   An sprintf(3) clone which uses fsl_appendf() for the formatting.
   Outputs at most n bytes to dest and returns the number of bytes
   Outputs at most n bytes to dest. Returns 0 on success, non-0
   output. Returns a negative value if !dest or !fmt. Returns 0
   without side-effects if !n or !*fmt.
   on error. Returns 0 without side-effects if !n or !*fmt.

   If the destination buffer is long enough (this function returns
   a non-negative value less than n), this function NUL-terminates it.
   If the destination buffer is long enough, this function
   NUL-terminates it.
   If it returns n then there was no space for the terminator.
*/
FSL_EXPORT fsl_int_t fsl_snprintf( char * dest, fsl_size_t n, char const * fmt, ... );
FSL_EXPORT int fsl_snprintf( char * dest, fsl_size_t n, char const * fmt, ... );

/**
   va_list counterpart to fsl_snprintf()
*/
FSL_EXPORT fsl_int_t fsl_snprintfv( char * dest, fsl_size_t n, char const * fmt, va_list args );
FSL_EXPORT int fsl_snprintfv( char * dest, fsl_size_t n, char const * fmt, va_list args );

/**
   Equivalent to fsl_strndup(src,-1).
*/
FSL_EXPORT char * fsl_strdup( char const * src );

/**
1715
1716
1717
1718
1719
1720
1721












1722
1723
1724
1725
1726
1727
1728
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725







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








/**
   Equivalent to strlen(3) but returns 0 if src is NULL.
   Note that it counts bytes, not UTF characters.
*/
FSL_EXPORT fsl_size_t fsl_strlen( char const * src );

/**
   Returns the number of UTF8 characters which begin within the first
   n bytes of str (noting that it's possible that a multi-byte
   character starts 1-3 bytes away from the end and overlaps past the
   end of (str+len)). If len is negative then fsl_strlen() is used to
   calculate it.

   Results are undefined if str is not UTF8 input or if str contains a
   BOM marker.
*/
FSL_EXPORT fsl_size_t fsl_strlen_utf8( char const * str, fsl_int_t n );

/**
   Like strcmp(3) except that it accepts NULL pointers.  NULL sorts
   before all non-NULL string pointers.  Also, this routine
   performs a binary comparison that does not consider locale.
*/
FSL_EXPORT int fsl_strcmp( char const * lhs, char const * rhs );

1784
1785
1786
1787
1788
1789
1790
1791

1792
1793
1794
1795
1796
1797
1798
1781
1782
1783
1784
1785
1786
1787

1788
1789
1790
1791
1792
1793
1794
1795







-
+







   else it returns true.
*/
FSL_EXPORT bool fsl_str_bool( char const * s );

/**
   Flags for use with fsl_db_open() and friends.
*/
enum fsl_open_flags {
enum fsl_open_flags_e {
/**
   The "no flags" value.
*/
FSL_OPEN_F_NONE = 0,
/**
   Flag for fsl_db_open() specifying that the db should be opened
   in read-only mode.
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843




1844
1845
1846
1847
1848
1849
1850
1830
1831
1832
1833
1834
1835
1836




1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847







-
-
-
-
+
+
+
+








   - expects name to be UTF8-encoded.

   - If name=="-", it returns one of stdin or stdout, depending on
   the mode string: stdout is returned if 'w' or '+' appear,
   otherwise stdin.

   If it returns NULL, the errno "should" contain a description of
   the problem unless the problem was argument validation. Pass it
   to fsl_errno_to_rc() to convert that into an API-conventional
   error code.
   If it returns NULL, the global errno "should" contain a description
   of the problem unless the problem was argument validation. Pass it
   to fsl_errno_to_rc() to convert that into an API-conventional error
   code.

   If at all possible, use fsl_close() (as opposed to fclose()) to
   close these handles, as it has logic to skip closing the
   standard streams.

   Potential TODOs:

1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914

1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935





1936
1937
1938

1939
1940
1941
1942
1943
1944

1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957








1958
1959



1960

1961
1962


1963
1964

1965
1966
1967
1968
1969
1970
1971
1859
1860
1861
1862
1863
1864
1865


































1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876

1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893





1894
1895
1896
1897
1898



1899






1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921


1922
1923
1924
1925
1926


1927
1928
1929

1930
1931
1932
1933
1934
1935
1936
1937







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











-
+
















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













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

+
-
-
+
+

-
+







/**
   Passes f to fclose(3) unless f is NULL or one of the C-standard
   (stdin, stdout, stderr) handles, in which cases it does nothing
   at all.
*/
FSL_EXPORT void fsl_fclose(FILE * f);

/**
   @typedef fsl_int_t (*fsl_appendf_f)( void * state, char const * data, fsl_int_t n )

   The fsl_appendf_f typedef is used to provide fsl_appendfv() with
   a flexible output routine, so that it can be easily send its
   output to arbitrary targets.

   The policies which implementations need to follow are:

   - state is an implementation-specific pointer (may be 0) which
   is passed to fsl_appendf(). fsl_appendfv() doesn't know what
   this argument is but passes it to its fsl_appendf_f argument.
   Typically this pointer will be an object or resource handle to
   which string data is pushed.

   - The 'data' parameter is the data to append. The API does not
   currently guaranty that data containing embeded NULs will survive
   the ride through fsl_appendf() and its delegates.

   - n is the number of bytes to read from data. The fact that n is
   of a signed type is historical. It can be treated as an unsigned
   type for purposes of fsl_appendf().

   - Returns, on success, the number of bytes appended (may be 0).

   - Returns, on error, an implementation-specified negative
   number.  Returning a negative error code will cause
   fsl_appendfv() to stop processing and return. Note that 0 is a
   success value (some printf format specifiers do not add anything
   to the output).
*/
typedef fsl_int_t (*fsl_appendf_f)( void * state, char const * data,
                                    fsl_int_t n );

/**
   This function works similarly to classical printf
   implementations, but instead of outputing somewhere specific, it
   uses a callback function to push its output somewhere. This
   allows it to be used for arbitrary external representations. It
   can be used, for example, to output to an external string, a UI
   widget, or file handle (it can also emulate printf by outputing
   to stdout this way).

   INPUTS:

   pfAppend: The is a fsl_appendf_f function which is responsible
   pfAppend: The is a fsl_output_f function which is responsible
   for accumulating the output. If pfAppend returns a negative
   value then processing stops immediately.

   pfAppendArg: is ignored by this function but passed as the first
   argument to pfAppend. pfAppend will presumably use it as a data
   store for accumulating its string.

   fmt: This is the format string, as in the usual printf(3), except
   that it supports more options (detailed below).

   ap: This is a pointer to a list of arguments.  Same as in
   vprintf() and friends.


   OUTPUTS:

   The return value is the total number of characters sent to the
   function "func", or a negative number on a pre-output error. If
   this function returns an integer greater than 1 it is in general
   impossible to know if all of the elements were output. As such
   failure can only happen if the callback function returns an
   ACHTUNG: this interface changed significantly in 2021-09:

   - The output function was changed from a type specific to this
   interface to fsl_output_f().

   error or if one of the formatting options needs to allocate
   memory and cannot. Both of those cases are very rare in a
   printf-like context, so this is not considered to be a
   - The return semantics where changed from printf()-like to
   significant problem. (The same is true for any classical printf
   implementations.) Clients may use their own state objects which
   can propagate errors from their own internals back to the
   caller, but generically speaking it is difficult to trace errors
   back through this routine. Then again, in practice that has
   never proven to be a problem.
   0 on success, non-0 on error.

   Most printf-style specifiers work as they do in standard printf()
   implementations. There might be some very minor differences, but
   the more common format specifiers work as most developers expect
   them to. In addition...

   Current (documented) printf extensions:

   (If you are NOT reading this via doxygen-processed sources: the
   percent signs below are doubled for the sake of doxygen, and
   each pair refers to only a single percent sign in the format
   string.)

   %%s works like conventional printf %%s except that any precision
   value can be modified via the '#' flag to counts in UTF8 characters
   instead of bytes! That is, if an "%%#.10s" argument has a byte
   length of 20, a precision of 10, and contains only 8 UTF8, its
   precision will allow it to output all 8 characters, even though
   they total 20 bytes. The '#' flag works this way for both width and
   precision.

   %%z works like %%s, but takes a non-const (char *) and deletes
   the string (using fsl_free()) after appending it to the output.
   %%z works exactly like %%s, but takes a non-const (char *) and
   deletes the string (using fsl_free()) after appending it to the
   output.

   %%h (HTML) works like %%s but (A) does not support the '#' flag and
   %%h (HTML) works like %%s but converts certain characters (namely
   '<' and '&') to their HTML escaped equivalents.
   (B) converts certain characters (namely '<' and '&') to their HTML
   escaped equivalents.

   %%t (URL encode) works like %%s but converts certain characters
   %%t (URL encode) works like %%h but converts certain characters
   into a representation suitable for use in an HTTP URL. (e.g. ' ' 
   gets converted to %%20)

   %%T (URL decode) does the opposite of %%t - it decodes
   URL-encoded strings and outputs their decoded form. ACHTUNG:
   fossil(1) interprets this the same as %%t except that it leaves
   '/' characters unescaped (did that change at some point? This
1989
1990
1991
1992
1993
1994
1995
1996

1997
1998
1999
2000

2001
2002
2003
2004
2005
2006
2007
2008
2009

2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044


2045
2046
2047
2048


2049
2050
2051
2052
2053
2054
2055
2056
2057




2058
2059
2060
2061
2062
2063
2064
2065

2066
2067
2068
2069


2070
2071
2072
2073
2074
2075
2076

2077
2078
2079
2080
2081

2082
2083
2084
2085
2086
2087
2088
1955
1956
1957
1958
1959
1960
1961

1962
1963
1964
1965

1966
1967
1968
1969
1970
1971
1972
1973
1974

1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993














1994


1995
1996

1997


1998
1999
2000
2001
2002
2003
2004




2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015

2016
2017
2018


2019
2020
2021
2022
2023
2024
2025
2026

2027
2028
2029
2030
2031

2032
2033
2034
2035
2036
2037
2038
2039







-
+



-
+








-
+


















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

-
-
+
+
-

-
-
+
+





-
-
-
-
+
+
+
+







-
+


-
-
+
+






-
+




-
+







   %%S works like %%.16s. It is intended for fossil hashes. The '!'
   modifier removes the length limit, resulting in the whole hash
   (making this formatting option equivalent to %%s).  (Sidebar: in
   fossil(1) this length is runtime configurable but that requires
   storing that option in global state, which is not an option for
   this implementation.)

   %%/: works like %%s but normalizes path-like strings by
   %%/: works mostly like %%s but normalizes path-like strings by
   replacing backslashes with the One True Slash.

   %%b: works like %%s but takes its input from a (fsl_buffer
   const*) argument.
   const*) argument. It does not support the '#' flag.

   %%B: works like %%Q but takes its input from a (fsl_buffer
   const*) argument.

   %%F: works like %%s but runs the output through
   fsl_bytes_fossilize().  This requires dynamic memory allocation, so
   is less efficient than re-using a client-provided buffer with
   fsl_bytes_fossilize() if the client needs to fossilize more than
   one element.
   one element. Does not support the '#' flag.

   %%j: works like %%s but JSON-encodes the string. It does not
   include the outer quotation marks by default, but using the '!'
   flag, i.e. %%!j, causes those to be added. The length and precision
   flags are NOT supported for this format. Results are undefined if
   given input which is not legal UTF8. By default non-ASCII
   characters with values less than 0xffff are emitted as as literal
   characters (no escaping), but the '#' modifier flag will cause it
   to emit such characters in the \\u#### form. It always encodes
   characters above 0xFFFF as UTF16 surrogate pairs (as JSON
   requires). Invalid UTF8 characters may get converted to '?' or may
   produce invalid JSON output. As a special case, if the value is NULL
   pointer, it resolves to "null" without quotes (regardless of the '!'
   modifier).

   Some of these extensions may be disabled by setting certain macros
   when compiling appendf.c (see that file for details).

   FIXME? fsl_appendf_f() is an artifact of older code from which
   this implementation derives. The first parameter should arguably
   be replaced with fsl_output_f(), which does the same thing _but_
   has different return semantics (more reliable, because the
   current semantics report partial success as success in some
   cases). Doing this would require us to change the return
   semantics of this function, but that wouldn't necessarily be a
   bad thing (we don't rely on sprintf()-like return semantics all
   that much, if at all). Or we just add a proxy which forwards to
   a fsl_output_f(). (Oh, hey, that's what fsl_outputf() does.) But
   that doesn't catch certain types of errors (namely allocation
   failures) which can happen as side-effects of some formatting
   operations.

   Potential TODO: add fsl_bytes_fossilize_out() which works like
   fsl_bytes_fossilize() but sends its output to an fsl_output_f()
   and fsl_appendf_f(), so that this routine doesn't need to alloc
   fsl_bytes_fossilize() but sends its output to an fsl_output_f(), so
   that this routine doesn't need to alloc for that case.
   for that case.
*/
FSL_EXPORT fsl_int_t fsl_appendfv(fsl_appendf_f pfAppend, void * pfAppendArg,
                                  const char *fmt, va_list ap );
FSL_EXPORT int fsl_appendfv(fsl_output_f pfAppend, void * pfAppendArg,
                            const char *fmt, va_list ap );

/**
   Identical to fsl_appendfv() but takes an ellipses list (...)
   instead of a va_list.
*/
FSL_EXPORT fsl_int_t fsl_appendf(fsl_appendf_f pfAppend,
                      void * pfAppendArg,
                      const char *fmt,
                      ... )
FSL_EXPORT int fsl_appendf(fsl_output_f pfAppend,
                           void * pfAppendArg,
                           const char *fmt,
                           ... )
#if 0
/* Would be nice, but complains about our custom format options: */
  __attribute__ ((__format__ (__printf__, 3, 4)))
#endif
  ;

/**
   A fsl_appendf_f() impl which requires that state be an opened,
   A fsl_output_f() impl which requires that state be an opened,
   writable (FILE*) handle.
*/
FSL_EXPORT fsl_int_t fsl_appendf_f_FILE( void * state, char const * s,
                                         fsl_int_t n );
FSL_EXPORT int fsl_output_f_FILE( void * state, void const * s,
                                  fsl_size_t n );


/**
   Emulates fprintf() using fsl_appendf(). Returns the result of
   passing the data through fsl_appendf() to the given file handle.
*/
FSL_EXPORT fsl_int_t fsl_fprintf( FILE * fp, char const * fmt, ... );
FSL_EXPORT int fsl_fprintf( FILE * fp, char const * fmt, ... );

/**
   The va_list counterpart of fsl_fprintf().
*/
FSL_EXPORT fsl_int_t fsl_fprintfv( FILE * fp, char const * fmt, va_list args );
FSL_EXPORT int fsl_fprintfv( FILE * fp, char const * fmt, va_list args );


/**
   Possibly reallocates self->list, changing its size. This function
   ensures that self->list has at least n entries. If n is 0 then
   the list is deallocated (but the self object is not), BUT THIS
   DOES NOT DO ANY TYPE-SPECIFIC CLEANUP of the items. If n is less
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2576
2577
2578
2579
2580
2581
2582

2583
2584
2585
2586
2587
2588
2589







-







/**
   Deallocates the given memory, which must have been allocated
   from fsl_unicode_to_utf8(), fsl_utf8_to_unicode(), or any
   function which explicitly documents this function as being the
   proper finalizer for its returned memory.
*/
FSL_EXPORT void fsl_unicode_free(void *);


/**
   Translate UTF-8 to Unicode for use in system calls. Returns a
   pointer to the translated text. The returned value must
   eventually be passed to fsl_unicode_free() to deallocate any
   memory used to store the returned pointer when done.

3386
3387
3388
3389
3390
3391
3392
3393

3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414


3415
3416

3417
3418
3419
3420
3421
3422
3423
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
3366

3367
3368
3369
3370
3371
3372
3373
3374







-
+


-


















+
+

-
+







*/
FSL_EXPORT int fsl_htmlize_to_buffer(fsl_buffer *p, const char *zIn, fsl_int_t n);

/**
   Equivalent to fsl_htmlize_to_buffer() but returns the result as a
   new string which must eventually be fsl_free()d by the caller.

   Returns NULL for invalidate arguments or allocation error.
   Returns NULL for invalid arguments or allocation error.
*/
FSL_EXPORT char *fsl_htmlize_str(const char *zIn, fsl_int_t n);


/**
   If c is a character Fossil likes to HTML-escape, assigns *xlate
   to its transformed form, else set it to NULL. Returns 1 for
   untransformed characters and the strlen of *xlate for others.
   Bytes returned via xlate are static and immutable.

   Results are undefined if xlate is NULL.
*/
FSL_EXPORT fsl_size_t fsl_htmlize_xlate(int c, char const ** xlate);

/**
   Flags for use with text-diff generation APIs,
   e.g. fsl_diff_text().

   Maintenance reminder: these values are holy and must not be
   changed without also changing the corresponding code in
   diff.c.

   @deprecated in favor of fsl_diff2_flag_e and fsl_diff_v2()
*/
enum fsl_diff_flag_t {
enum fsl_diff_flag_e {
/** Ignore end-of-line whitespace */
FSL_DIFF_IGNORE_EOLWS = 0x01,
/** Ignore end-of-line whitespace */
FSL_DIFF_IGNORE_ALLWS = 0x03,
/** Generate a side-by-side diff */
FSL_DIFF_SIDEBYSIDE =   0x04,
/** Missing shown as empty files */
3441
3442
3443
3444
3445
3446
3447
3448

3449
3450
3451
3452
3453
3454
3455
3456
3392
3393
3394
3395
3396
3397
3398

3399

3400
3401
3402
3403
3404
3405
3406







-
+
-







   sequences to some output.  The colors are currently hard-coded
   and non-configurable. This has no effect for HTML output, and
   that flag trumps this one. It also currently only affects
   unified diffs, not side-by-side.

   Maintenance reminder: this one currently has no counterpart in
   fossil(1), is not tracked in the same way, and need not map to an
   internal flag value. That's a good thing, because we'll be out
   internal flag value.
   of flags once Jan's done tinkering in fossil(1) ;).
*/
FSL_DIFF_ANSI_COLOR =     0x2000
};

/**
   Generates a textual diff from two text inputs and writes
   it to the given output function.
3490
3491
3492
3493
3494
3495
3496



3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511



3512
3513
3514
3515






































































































































































































































































































































































































































































































































































































































































































































































































3516
3517
3518
3519
3520
3521
3522
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
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
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
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
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
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
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
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
4244
4245
4246
4247
4248
4249
4250
4251
4252







+
+
+















+
+
+




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








   - Add a predicate function for outputing only matching
   differences, analog to fossil(1)'s regex support (but more
   flexible).

   - Expose the raw diff-generation bits via the internal API
   to facilitate/enable the creation of custom diff formats.

   @see fsl_diff_v2()
   @deprecated Prefer fsl_diff_v2() for new code.
*/
FSL_EXPORT int fsl_diff_text(fsl_buffer const *pA, fsl_buffer const *pB,
                             fsl_output_f out, void * outState,
                             short contextLines, short sbsWidth,
                             int diffFlags );

/**
   Functionally equivalent to:

   @code:
   fsl_diff_text(pA, pB, fsl_output_f_buffer, pOut,
   contextLines, sbsWidth, diffFlags);
   @endcode

   Except that it returns FSL_RC_MISUSE if !pOut.

   @see fsl_diff_v2()
   @deprecated Prefer fsl_diff_v2() for new code.
*/
FSL_EXPORT int fsl_diff_text_to_buffer(fsl_buffer const *pA, fsl_buffer const *pB,
                                       fsl_buffer *pOut, short contextLines,
                                       short sbsWidth, int diffFlags );

/**
   Flags for use with the 2021-era text-diff generation APIs
   (fsl_diff_builder and friends). This set of flags may still change
   considerably.

   Maintenance reminder: some of these values are holy and must not be
   changed without also changing the corresponding code in diff2.c.
*/
enum fsl_diff2_flag_e {
/** Ignore end-of-line whitespace. Applies to
    all diff builders. */
FSL_DIFF2_IGNORE_EOLWS = 0x01,
/** Ignore end-of-line whitespace. Applies to
    all diff builders.  */
FSL_DIFF2_IGNORE_ALLWS = 0x03,
/** Suppress optimizations (debug). Applies to
    all diff builders. */
FSL_DIFF2_NOOPT =        0x0100,
/** Invert the diff. Applies to all diff builders. */
FSL_DIFF2_INVERT =       0x0200,
/** Use context line count even if it's zero. Applies to all diff
    builders. Normally a value of 0 is treated as the built-in
    default. */
FSL_DIFF2_CONTEXT_ZERO =  0x0400,
/**
   Only calculate diff if it's not "too big." Applies to all diff
   builders and will cause the public APIs which hit this to return
   FSL_RC_RANGE.
*/
FSL_DIFF2_NOTTOOBIG =    0x0800,
/**
   Strip trailing CR before diffing. Applies to all diff builders.
*/
FSL_DIFF2_STRIP_EOLCR =    0x1000,
/**
   More precise but slower side-by-side diff algorithm, for diffs
   which use that.
*/
FSL_DIFF2_SLOW_SBS =       0x2000,
/**
   Tells diff builders which support it to include line numbers in
   their output.
*/
FSL_DIFF2_LINE_NUMBERS = 0x10000,
/**
   Tells diff builders which optionally support an "index" line
   to NOT include it in their output.
*/
FSL_DIFF2_NOINDEX = 0x20000,

/**
   Tells the TCL diff builder that the complete output and each line
   should be wrapped in {...}.
*/
FSL_DIFF2_TCL_BRACES = 0x40000,

/**
   Reserved for client-defined diff builder use.
*/
FSL_DIFF2_CLIENT1 = 0x01000000,
/**
   Reserved for client-defined diff builder use.
*/
FSL_DIFF2_CLIENT2 = 0x02000000,
/**
   Reserved for client-defined diff builder use.
*/
FSL_DIFF2_CLIENT3 = 0x04000000,
/**
   Reserved for client-defined diff builder use.
*/
FSL_DIFF2_CLIENT4 = 0x08000000
};

/**
   An instance of this class is used to convey certain state to
   fsl_diff_builder objects. Some of this state is configuration
   provided by the client and some is volatile, used for communicating
   common state to diff builder instances during the diff rendering
   process.

   Certain fsl_diff_builder implementations may require that some
   ostensibly optional fields be filled out. Documenting that is TODO,
   as the builders get developed.
*/
struct fsl_diff_opt {
  /**
     Flags from the fsl_diff2_flag_e enum.
  */
  uint32_t diffFlags;
  /**
     Number of lines of diff context (number of lines common to the
     LHS and RHS of the diff). Library-wide default is 5.
  */
  unsigned short contextLines;
  /**
     Maximum column width for side-by-side, a.k.a. split, diffs.

     FSL_DIFF_BUILDER_SPLIT_TEXT truncates its content columns (as
     opposed to line numbers and its modification marker) to, at most,
     this width. By default it uses as much width as is necessary to
     render whole lines. It treats this limit as UTF8 characters, not
     bytes.

     This is a hint, not a rule. A given diff builder is free to
     ignore it or to ignore values which are arbitrarily deemed "too
     small" or "too large."
  */
  unsigned short columnWidth;
  /**
     The filename of the object represented by the LHS of the
     diff. This is intentended for, e.g., generating header-style
     output. This may be NULL.
  */
  const char * nameLHS;
  /**
     The hash of the object represented by the LHS of the diff. This
     is intentended for, e.g., generating header-style output. This
     may be NULL.
  */
  const char * hashLHS;
  /**
     The filename of the object represented by the LHS of the
     diff. This is intentended for, e.g., generating header-style
     output. If this is NULL but nameLHS is not then they are assumed
     to have the same name.
  */
  const char * nameRHS;
  /**
     The hash of the object represented by the RHS of the diff. This
     is intentended for, e.g., generating header-style output. This
     may be NULL.
  */
  const char * hashRHS;
  /**
     Output destination. Any given builder might, depending on how it
     actually constructs the diff, buffer output and delay calling
     this until its finish() method is called.
  */
  fsl_output_f out;
  /**
     State for this->out(). Ownership is unspecified by this
     interface: it is for use by this->out() but what is supposed to
     happen to it after this object is done with it depends on
     higher-level code.
  */
  void * outState;

  /**
     EXPERIMENTAL AND SUBJECT TO CHANGE.

     Optional ANSI color control sequences to be injected into
     text-mode diff output by diff builders which support them. All
     members of this struct must either be NULL, an empty string, or a
     valid ANSI escape sequence. The reset option must be the escape
     sequence to reset either just the color or to reset all ANSI
     control attributes, depending on how the other members are
     set. If any member other than reset is set, all must be set.

     The diff driver will treat any members of this which are NULL as
     empty strings to simplify diff builder color integration. The
     exception is the reset member - see its docs for details.
  */
  struct fsl_diff_opt_ansi {
    /**
       Color escape sequence for inserted lines.
    */
    char const * insertion;
    /**
       Color escape sequence for edited or replaced lines. This option
       might be ignored, depending on how the renderer works. Some
       will render edits as a deletion/insertion pair.
    */
    char const * edit;
    /**
       Color escape sequence for inserted lines.
    */
    char const * deletion;
    /**
       Escape sequence to reset colors. If reset is empty or NULL and
       any others are not then reset is automatically treated as if it
       were the ANSI code to reset all color attributes.
    */
    char const * reset;
  } ansiColor;
};

/** Convenience typedef. */
typedef struct fsl_diff_opt fsl_diff_opt;

/** Initialized-with-defaults fsl_diff_opt structure, intended for
    const-copy initialization. */
#define fsl_diff_opt_empty_m {\
  0/*diffFlags*/, 5/*contextLines*/, 0/*columnWidth*/,\
  NULL/*nameLHS*/,NULL/*hashLHS*/,                       \
  NULL/*nameRHS*/, NULL/*hashRHS*/,                      \
  NULL/*out*/, NULL/*outState*/,                          \
  {/*ansiColor*/ ""/*insertion*/,""/*edit*/,""/*deletion*/,\
    ""/*reset*/}                                                \
}

/** Initialized-with-defaults fsl_diff_opt structure, intended for
    non-const copy initialization. */
extern const fsl_diff_opt fsl_diff_opt_empty;

/**
   Information about each line of a file being diffed.

   This type is only in the public API for use by the fsl_diff_builder
   interface, specifically for use with fsl_dline_change_spans(). It
   is not otherwise intended for public use. None of its members are
   considered even remotely public except for this->z and this->n.
*/
struct fsl_dline {
  /** 
      The text of the line. Owned by higher-level code.  Not
      necessarily NUL-terminated: this->n holds its length.
  */
  const char *z;
  /** Number of bytes of z which belong to this line. */
  unsigned short n;
  // All members after this point are strictly for internal use only.
  /** Indent of the line. Only !=0 with certain options. */
  unsigned short indent;
  /** Hash of the line. Lower X bits are the length. */
  uint64_t h;
  /** 1+(Index of next line with same the same hash) */
  unsigned int iNext;
  /**
     An array of fsl_dline elements serves two purposes.  The fields
     above are one per line of input text.  But each entry is also
     a bucket in a hash table, as follows:
  */
  unsigned int iHash;   /* 1+(first entry in the hash chain) */
};

/**
   Convenience typedef.
*/
typedef struct fsl_dline fsl_dline;
/** Initialized-with-defaults fsl_dline structure, intended for
    const-copy initialization. */
#define fsl_dline_empty_m {NULL,0U,0U,0U,0U,0U}
/** Initialized-with-defaults fsl_dline structure, intended for
    non-const copy initialization. */
extern const fsl_dline fsl_dline_empty;

/**
   Maximum number of change spans for fsl_dline_change.
*/
#define fsl_dline_change_max_spans 8

/**
   This "mostly-internal" type describes zero or more (up to
   fsl_dline_change_max_spans) areas of difference between two lines
   of text. This type is only in the public API for use with concrete
   fsl_diff_builder implementations.
*/
struct fsl_dline_change {
  /** Number of change spans (number of used elements in this->a). */
  unsigned char n;
  /** Array of change spans, in left-to-right order */
  struct fsl_dline_change_span {
    /* Reminder: int instead of uint b/c some ported-in algos use
       negatives. */
    /** Byte offset to start of a change on the left */
    int iStart1;
    /** Length of the left change in bytes */
    int iLen1;
    /** Byte offset to start of a change on the right */
    int iStart2;
    /** Length of the change on the right in bytes */
    int iLen2;
    /** True if this change is known to have no useful subdivs */
    int isMin;
  } a[fsl_dline_change_max_spans];
};

/**
   Convenience typedef.
*/
typedef struct fsl_dline_change fsl_dline_change;

/** Initialized-with-defaults fsl_dline_change structure, intended for
    const-copy initialization. */
#define fsl_dline_change_empty_m { \
  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,0}, {0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0} \
  } \
}

/** Initialized-with-defaults fsl_dline_change structure, intended for
    non-const copy initialization. */
extern const fsl_dline_change fsl_dline_change_empty;

/**
   Given two lines of a diff, this routine computes a set of changes
   between those lines for display purposes and writes a description
   of those changes into the 3rd argument. After returning, p->n
   contains the number of elements in p->a which were populated by
   this routine.

   This function is only in the public API for use with
   fsl_diff_builder objects. It is not a requirement for such objects
   but can be used to provide more detailed diff changes than marking
   whole lines as simply changed or not.
*/
FSL_EXPORT void fsl_dline_change_spans(const fsl_dline *pLeft,
                                       const fsl_dline *pRight,
                                       fsl_dline_change * const p);

/**
   Compares two fsl_dline instances using memcmp() semantics,
   returning 0 if they are equivalent.

   @see fsl_dline_cmp_ignore_ws()
*/
FSL_EXPORT int fsl_dline_cmp(const fsl_dline * const pA,
                             const fsl_dline * const pB);

/**
   Counterpart of fsl_dline_cmp() but ignores all whitespace
   when comparing for equivalence.
*/
FSL_EXPORT int fsl_dline_cmp_ignore_ws(const fsl_dline * const pA,
                                       const fsl_dline * const pB);

/**
   Breaks the first n bytes of z into an array of fsl_dline records,
   each of which refers back to z (so it must remain valid for their
   lifetime). If n is negative, fsl_strlen() is used to calculate
   z's length.

   The final argument may be any flags from the fsl_diff2_flag_e
   enum, but only the following flags are honored:

   - FSL_DIFF2_STRIP_EOLCR
   - FSL_DIFF2_IGNORE_EOLWS
   - FSL_DIFF2_IGNORE_ALLWS

   On success, returns 0, assigns *pnLine to the number of lines, and
   sets *pOut to the array of fsl_dline objects, transfering ownership
   to the caller, who must eventually pass it to fsl_free() to free
   it.

   If z is NULL or n is 0, the input is assumed to be empty, 0 is returned,
   (*pOut) will be set to NULL, and (*pnLine) will be set to 0.

   On error, neither (*pnLine) nor (*pOut) are modified and returns one
   of:

   - FSL_RC_DIFF_BINARY if the input appears to be non-text.
   - FSL_RC_OOM on allocation error.
*/
FSL_EXPORT int fsl_break_into_dlines(const char *z, fsl_int_t n,
                                     uint32_t *pnLine,
                                     fsl_dline **pOut, uint64_t diff2Flags);

/** Convenience typedef. */
typedef struct fsl_diff_builder fsl_diff_builder;

/**
   This class is the basis of libfossil's port of the diff engine
   added to fossil(1) in 2021-09.

   A diff builder is an object responsible for formatting low-level
   diff info another form, typically for human readability but also
   for machine readability (patches). The library generates a
   low-level diff then feeds that through an algorithm which
   determines which methods of this class to call, delegating all
   rendering of the diff to an instance of this class.

   The internal APIs which drive each instance of this class guaranty
   that if any method of this class returns non-0 (an error code) then
   no futher methods will be called except for finalize().

   Potential TODO: add a two-phase option to this interface. If
   builder->passes is greater than 0, builder->currentPass gets set to
   the current pass number (1 or 2) then it gets passed the diff once
   for each pass the builder needs, updating the currentPass flag
   between runs. The first phase is simply for it to analyze what
   needs to be done and the second is to do it. That would allow,
   e.g. the split-mode impl to avoid buffering all of the output
   because the first pass would allow it to calculate the width it
   needs for outputing the text columns. It would also allow for it to
   dynamically resize the line number columns more easily.
*/
struct fsl_diff_builder {
  /**
     Config info, owned by higher-level routines. Every diff builder
     requires one of these. Builders are prohibited from modifying
     these but the diff driver will.

     Note that the diff driver may make a bitwise copy of this object
     and use _that_ one for the actual diff generation. That is,
     methods of this class must never assume that this member's
     pointer refers to a specific object. (This leeway is necessary in
     order to implement diff inversion (swapping the LHS/RHS of a
     diff).)
  */
  fsl_diff_opt * opt;
  /**
     If not NULL, this is called once per diff to give the builder a
     chance to perform any bootstrapping initialization or header
     output. At the point this is called, this->cfg is assumed to have
     been filled out properly. Diff builder implementations which
     require dynamic resource allocation may perform it here or in
     their factory routine(s).

     This method should also reset any dynamic state of a builder so
     that it may be reused for subsequent diffs. This enables the API
     to use a single builder for a collection of logically grouped
     files without having to destroy and reallocate the builder.

     Must return 0 on success, non-0 on error. If it returns non-0,
     the only other method of the instance which may be legally called
     is finalize().

     The diff driver sets this->lnLHS and this->lnRHS to 0 before
     calling this.
  */
  int (*start)(fsl_diff_builder* const);

  /**
     If this is not NULL, it is called one time at the start of each
     chunk of diff for a given file and is passed the line number of
     each half of the diff and the number of lines in that chunk for
     that half (including insertions and deletions). This is primarily
     intended for generating conventional unified diff chunk headers
     in the form:

     @code
     @@ -A,B +C,D @@
     @endcode

     The inclusion of this method in an object might preclude certain
     other diff formatting changes which might otherwise apply.
     Notably, if the span between two diff chunks is smaller than the
     context lines count, the diff builder driver prefers to merge
     those two chunks together. That "readability optimization" is
     skipped when this method is set because this method may otherwise
     report that lines are being skipped which then subsequently get
     output by the driver.

     Must return 0 on success, non-0 on error.
  */
  int (*chunkHeader)(fsl_diff_builder* const,
                     uint32_t A, uint32_t B,
                     uint32_t C, uint32_t D);

  /**
     Tells the builder that n lines of common output are to be
     skipped. How it represents this is up to the impl. Must return 0
     on success, non-0 on error.

     Typical common implementation details:

     - Increment both this->lnLHS and this->lnRHS by n.
  */
  int (*skip)(fsl_diff_builder* const, uint32_t n);
  /**
     Tells the builder that the given line represents one line of
     common output. Must return 0 on success, non-0 on error.

     Typical common implementation details:

     - Increment both this->lnLHS and this->lnRHS by 1.
  */
  int (*common)(fsl_diff_builder* const, fsl_dline const * line);
  /**
     Tells the builder that the given line represents an "insert" into
     the RHS. Must return 0 on success, non-0 on error.

     Typical common implementation details:

     - Increment this->lnRHS by 1.
  */
  int (*insertion)(fsl_diff_builder* const, fsl_dline const * line);
  /**
     Tells the builder that the given line represents a "deletion" - a
     line removed from the LHS. Must return 0 on success, non-0 on
     error.

     Typical common implementation details:

     - Increment this->lnLHS by 1.
  */
  int (*deletion)(fsl_diff_builder* const, fsl_dline const * line);
  /**
     Tells the builder that the given line represents a replacement
     from the LHS to the RHS. Must return 0 on success, non-0 on
     error. This differs from an "edit" in that the line being
     replaced seems to have on relationship to the replacement. Even
     so, builders are free to represent replacements and edits
     identically, and are free to represent either or both as a pair
     of deletion/insertion operations.

     Typical common implementation details:

     - Increment both this->lnLHS and this->lnRHS by 1.
  */
  int (*replacement)(fsl_diff_builder* const, fsl_dline const * lineLhs,
                     fsl_dline const * lineRhs);
  /**
     Tells the builder that the given line represents an "edit" from
     the LHS to the RHS. Must return 0 on success, non-0 on
     error. Builders are free, syntax permitting, to usse the
     fsl_dline_change_spans() API to elaborate on edits for display
     purposes, to treat it identically to this->replacement(), or to
     treat this as a single pair of calls to this->deletion() and
     this->insertion(). In the latter case they simply need to pass
     lineLhs to this->deletion() and lineRhs to this->insertion().

     Typical common implementation details:

     - Increment both this->lnLHS and this->lnRHS by 1.
  */
  int (*edit)(fsl_diff_builder* const, fsl_dline const * lineLhs,
              fsl_dline const * lineRhs);
  /**
     Must "finish" the diff process. Depending on the diff impl, this
     might flush any pending output or may be a no-op. This is only
     called if the rest of the diff was generated without producing an
     error result.

     This member may be NULL.

     Implementations are free to collect all of their output in an
     internal representation and delay flushing it until this routine
     is called.

     Must return 0 on success, non-0 on error (e.g. output flushing
     fails).
  */
  int (*finish)(fsl_diff_builder* const);
  /**
     Must free any state owned by this builder, including the builder
     object. It must not generate any output.

     Must return 0 on success, non-0 on error (e.g. output flushing
     fails), but must clean up its own state and the builder object in
     either case.
  */
  void (*finalize)(fsl_diff_builder* const);

  /**
     If true, this builder gets passed through the diff generation
     process twice. See this->passNumber for details.
  */
  bool twoPass;

  /**
     Gets set to the "pass number" immediately before this->start() is
     called, starting with pass number 1. This value is only relevant
     for two-pass builders, which can use this to control their mode
     of operation, e.g. data collection in pass 1 and actual work in
     pass 2. Note that all of the diff-building API methods are call
     for both passes, including start() and finish().  Only finalize()
     is not affected by this.
  */
  unsigned short passNumber;
  /**
     Impl-specific diff-generation state. If it is owned by this
     instance then this->finalize() must clean it up.
  */
  void * pimpl;
  /**
     Impl-specific int for tracking basic output state, e.g.  of
     opening/closing tags. This must not be modified by clients.
  */
  unsigned int implFlags;
  /**
     A place to store the number of files seen by this builder so far,
     for builders which need to distinguish that somehow (e.g. adding
     a separator before each file after the first). Implementations
     which use this should increment it in their start() method.
  */
  uint32_t fileCount;
  /**
     Number of lines seen of the LHS content. It is up to the concrete
     builder impl to update this if it's needed. The core diff driver
     sets this to 0 before calling this->start().
  */
  uint32_t lnLHS;
  /**
     Number of lines seen of the RHS content. It is up to the concrete
     builder impl to update this if it's needed. The core diff driver
     sets this to 0 before calling this->start().
  */
  uint32_t lnRHS;
};

/** Initialized-with-defaults fsl_diff_builder structure, intended for
    const-copy initialization. */
#define fsl_diff_builder_empty_m { \
  NULL/*cfg*/,                                                        \
  NULL/*start()*/,NULL/*chunkHeader()*/,NULL/*skip()*/, NULL/*common()*/, \
  NULL/*insertion()*/,NULL/*deletion()*/, NULL/*replacement()*/, \
  NULL/*edit()*/, NULL/*finish()*/, NULL/*finalize()*/,        \
  false/*twoPass*/,0U/*passNumber*/, \
  NULL/*pimpl*/, 0U/*implFlags*/,0U/*fileCount*/,         \
  0/*lnLHS*/,0/*lnRHS*/ \
}

/** Initialized-with-defaults fsl_diff_builder structure, intended for
    non-const copy initialization. */
extern const fsl_diff_builder fsl_diff_builder_empty;

/**
   Type IDs for use with fsl_diff_builder_factory().
*/
enum fsl_diff_builder_e {
/**
   A "dummy" diff builder intended only for testing the
   fsl_diff_builder interface and related APIs. It does not produce
   output which is generically useful.
*/
FSL_DIFF_BUILDER_DEBUG = 1,
/**
   Generates diffs in a compact low(ist)-level form originally
   designed for use by diff renderers implemented in JavaScript.

   This diff builder outputs a JSON object with the following
   properties:

   - hashLHS, hashRHS: the hashes of the LHS/RHS content.

   - nameLHS, nameRHS: the filenames of the LHS/RHS. By convention, if
     the RHS is NULL but the LHS is not, both sides have the same
     name.

   - diff: raw diff content, an array with the structure described
     below.

   Note that it is legal for the names and hashes to be "falsy" (null,
   not set, or empty strings).

   The JSON array consists of integer opcodes with each opcode
   followed by zero or more arguments:

   @code
   Syntax        Mnemonic    Description

   -----------   --------    --------------------------
   0             END         This is the end of the diff.
   1  INTEGER    SKIP        Skip N lines from both files.
   2  STRING     COMMON      The line STRING is in both files.
   3  STRING     INSERT      The line STRING is in only the right file.
   4  STRING     DELETE      The line STRING is in only the left file.
   5  SUBARRAY   EDIT        One line is different on left and right.
   @endcode

   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.
*/
FSL_DIFF_BUILDER_JSON1,

/**
   A diff builder which produces output compatible with the patch(1)
   command. Its output is functionally identical to fossil(1)'s
   default diff output except that by default includes an Index line
   at the top of each file (use the FSL_DIFF2_NOINDEX flag in its
   fsl_diff_opt::diffFlags to disable that).

   Supported flags:

   - FSL_DIFF2_LINE_NUMBERS (makes it incompatible with patch(1))
   - FSL_DIFF2_NOINDEX
*/
FSL_DIFF_BUILDER_UNIFIED_TEXT,

/**
   A diff builder which outputs a description of the diff in a
   TCL-readable form. It requires external TCL code in order to
   function.

   TODO: a flag which includes the tcl/tk script as part of the
   output. We first need to compile fossil's diff.tcl into the
   library.
*/
FSL_DIFF_BUILDER_TCL,
/**
   A pain-text side-by-side (a.k.a. split) diff view. This diff always
   behaves as if the FSL_DIFF2_LINE_NUMBERS flag were set because its
   output is fairly useless without line numbers. It optionally
   supports ANSI coloring.
*/
FSL_DIFF_BUILDER_SPLIT_TEXT
};
typedef enum fsl_diff_builder_e fsl_diff_builder_e;

/**
   A factory for creating fsl_diff_builder instances of types which
   are built in to the library. This does not preclude the creation of
   client-side diff builders (e.g. ones which write to ncurses widgets
   or similar special-case output).

   On success, returns 0 and assigns *pOut to a new builder instance
   which must eventually be freed by calling its pOut->finalize()
   method. On error, returns non-0 and *pOut is not modified. Error
   codes include FSL_RC_OOM (alloc failed) and FSL_RC_TYPE (unknown
   type ID), FSL_RC_TYPE (type is not (or not yet) implemented).
*/
FSL_EXPORT int fsl_diff_builder_factory( fsl_diff_builder_e type,
                                         fsl_diff_builder **pOut );

/**
   This counterpart of fsl_diff_text() defines its output format in
   terms of a fsl_diff_builder instance which the caller must provide.
   The caller is responsible for pointing pBuilder->cfg to a
   configuration object suitable for the desired diff. In particular,
   pBuilder->cfg->out and (if necessary) pBuilder->cfg->outState must
   be set to non-NULL values.

   This function generates a low-level diff of two versions of content,
   contained in the given buffers, and passes that diff through the
   given diff builder to format it.

   Returns 0 on success. On error, it is not generally knowable whether
   or not any diff output was generated.

   The builder may produce any error codes it wishes, in which case
   they are propagated back to the caller. Common error codes include:

   - FSL_RC_OOM if an allocation fails.

   - FSL_RC_RANGE if the diff is "too big" and
   pBuilder->config->diffFlags contains the FSL_DIFF2_NOTTOOBIG flag.

   - FSL_RC_DIFF_BINARY if the to-diff content appears to be binary,
   noting that "appears to be" is heuristric-driven and subject to
   false positives. Specifically, files with extremely long lines will
   be recognized as binary (and are, in any case, generally less than
   useful for most graphical diff purposes).

   @see fsl_diff_builder_factory()
   @see fsl_diff_text()
   @see fsl_diff_raw_v2()
*/
FSL_EXPORT int fsl_diff_v2(fsl_buffer const * pv1,
                           fsl_buffer const * pv2,
                           fsl_diff_builder * const pBuilder);

/**
   Performs a diff, as for fsl_diff_v2(), but returns the results in
   the form of an array of COPY, DELETE, INSERT triples terminated by
   3 entries with the value 0.

   Each triple in the list specifies how many *lines* of each half of
   the diff (the first 2 arguments to this function) to COPY as-is
   (common code), DELETE (exists in the LHS but not in the RHS), and
   INSERT (exists in the RHS but not in the LHS). By breaking the
   input into lines and following these values, a line-level text-mode
   diff of the two blobs can be generated.

   See fsl_diff_v2() for the details, all of which apply except for
   the output:

   - cfg->out is ignored.

   - On success, *outRaw is assigned to the output array and ownership
     of it is transfered to the caller, who must eventually pass it to
     fsl_free() to free it.

*/
FSL_EXPORT int fsl_diff_v2_raw(fsl_buffer const * pv1,
                               fsl_buffer const * pv2,
                               fsl_diff_opt const * const cfg,
                               int **outRaw );


/**
   If zDate is an ISO8601-format string, optionally with a .NNN
   fractional suffix, then this function returns true and sets
   *pOut (if pOut is not NULL) to the corresponding Julian
   value. If zDate is not an ISO8601-format string then this
   returns false (0) and pOut is not modified.
3533
3534
3535
3536
3537
3538
3539
3540

3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557

3558
3559
3560
3561
3562
3563


3564
3565
3566
3567
3568
3569
3570
4263
4264
4265
4266
4267
4268
4269

4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286

4287
4288
4289
4290
4291


4292
4293
4294
4295
4296
4297
4298
4299
4300







-
+
















-
+




-
-
+
+







   millisecond or two or _might_ not). Thus this routine should not
   be used when 100% round-trip fidelity is required, but is close
   enough for routines which do not require 100% millisecond-level
   fidelity in time conversions.

   @see fsl_julian_to_iso8601()
*/
FSL_EXPORT char fsl_iso8601_to_julian( char const * zDate, double * pOut );
FSL_EXPORT bool fsl_iso8601_to_julian( char const * zDate, double * pOut );

/** 
    Converts the Julian Day J to an ISO8601 time string. If addMs is
    true then the string includes the '.NNN' fractional part, else
    it will not. This function writes (on success) either 20 or 24
    bytes (including the terminating NUL byte) to pOut, depending on
    the value of addMs, and it is up to the caller to ensure that
    pOut is at least that long.

    Returns true (non-0) on success and the only error conditions
    [it can catch] are if pOut is NULL, J is less than 0, or
    evaluates to a time value which does not fit in ISO8601
    (e.g. only years 0-9999 are supported).

    @see fsl_iso8601_to_julian()
*/
FSL_EXPORT char fsl_julian_to_iso8601( double J, char * pOut, bool addMs );
FSL_EXPORT bool fsl_julian_to_iso8601( double J, char * pOut, bool addMs );

/**
   Returns the Julian Day time J value converted to a Unix Epoch
   timestamp. It assumes 86400 seconds per day and does not account
   for any sort leap seconds, leap years, leap frogs, or any other
   kind of leap, up to and including a leap of faith.
   for leap seconds, leap years, leap frogs, or any other kind of
   leap, up to and including leaps of faith.
*/
FSL_EXPORT fsl_time_t fsl_julian_to_unix( double J );

/**
   Performs a chdir() to the directory named by zChDir.

   Returns 0 on success. On error it tries to convert the
4466
4467
4468
4469
4470
4471
4472









4473
4474
4475
4476
4477
4478
4479
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218







+
+
+
+
+
+
+
+
+







   Returns 0 on success, FSL_RC_OOM on OOM, FSL_RC_TYPE if any input
   appears to be binary. 

   @see fsl_buffer_contains_merge_marker()
*/
FSL_EXPORT int fsl_buffer_merge3(fsl_buffer *pPivot, fsl_buffer *pV1, fsl_buffer *pV2,
                                 fsl_buffer *pOut, unsigned int *conflictCount);

/**
   Appends the first n bytes of string z to buffer b in the form of
   TCL-format string literal. If n<0 then fsl_strlen() is used to
   determine the length. Returns 0 on success, FSL_RC_OOM on error.
 */
FSL_EXPORT int fsl_buffer_append_tcl_literal(fsl_buffer * const b,
                                             char const * z, fsl_int_t n);


/**
   Event IDs for use with fsl_confirm_callback_f implementations.

   The idea here is to send, via callback, events from the library to
   the client when a potentially interactive response is necessary.
   We define a bare minimum of information needed for the client to
4845
4846
4847
4848
4849
4850
4851




































































































































4852
4853
4854
4855
4856
4857
4858
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729







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







/**
   Appends each ID from the given bag to the given buffer using the given
   separator string. Returns FSL_RC_OOM on allocation error.
*/
FSL_EXPORT int fsl_id_bag_to_buffer(fsl_id_bag const * bag, fsl_buffer * b,
                                    char const * separator);

/**
   Flags for use with the fsl_looks family of functions.
*/
enum fsl_lookslike_e {
/* Nothing special was found. */
FSL_LOOKSLIKE_NONE    = 0x00000000,
/* One or more NUL chars were found. */
FSL_LOOKSLIKE_NUL     = 0x00000001,
/* One or more CR chars were found. */
FSL_LOOKSLIKE_CR      = 0x00000002,
/* An unpaired CR char was found. */
FSL_LOOKSLIKE_LONE_CR = 0x00000004,
/* One or more LF chars were found. */
FSL_LOOKSLIKE_LF      = 0x00000008,
/* An unpaired LF char was found. */
FSL_LOOKSLIKE_LONE_LF = 0x00000010,
/* One or more CR/LF pairs were found. */
FSL_LOOKSLIKE_CRLF    = 0x00000020,
/* An over length line was found. */
FSL_LOOKSLIKE_LONG    = 0x00000040,
/* An odd number of bytes was found. */
FSL_LOOKSLIKE_ODD     = 0x00000080,
/* Unable to perform full check. */
FSL_LOOKSLIKE_SHORT   = 0x00000100,
/* Invalid sequence was found. */
FSL_LOOKSLIKE_INVALID = 0x00000200,
/* Might be binary. */
FSL_LOOKSLIKE_BINARY  = FSL_LOOKSLIKE_NUL | FSL_LOOKSLIKE_LONG | FSL_LOOKSLIKE_SHORT,
 /* Line separators. */
FSL_LOOKSLIKE_EOL     = (FSL_LOOKSLIKE_LONE_CR | FSL_LOOKSLIKE_LONE_LF | FSL_LOOKSLIKE_CRLF)
};

/**
   Returns true if b appears to contain "binary" (non-UTF8/16) content,
   else returns true.
*/
FSL_EXPORT bool fsl_looks_like_binary(fsl_buffer const * const b);

/**
   If b appears to contain any non-UTF8 content, returns a truthy
   value: one or more values from the fsl_lookslike_e enum indicating
   which sort of data was seen which triggered its conclusion:

   - FSL_LOOKSLIKE_BINARY means the content appears to be binary
     because it contains embedded NUL bytes or an "extremely long"
     line. This function may diagnose UTF-16 as binary.

   - !FSL_LOOKSLIKE_BINARY means the content is non-binary but may
     not necessarily be valid UTF-8.

   - 0 means the contents appear to be valid UTF-8.

   It b's content is empty, returns 0.

   The 2nd argument can be a mask of any values from fsl_lookslike_e
   and will cause this routine to stop inspecting the input once it
   encounters any content described by those flags.

   The contents are examined until the end is reached or a condition
   described by the 2nd parameter's flags is encountered.

   WARNINGS:

   - This function does not validate that the blob content is properly
     formed UTF-8.  It assumes that all code points are the same size.
     It does not validate any code points.  It makes no attempt to
     detect if any [invalid] switches between UTF-8 and other
     encodings occur.

    - The only code points that this function cares about are the NUL
      character, carriage-return, and line-feed.
*/
FSL_EXPORT int fsl_looks_like_utf8(fsl_buffer const * const b, int stopFlags);

/**
   Returns true if b's contents appear to contain anything other than valid
   UTF8.

   It uses the approach described at:

   http://en.wikipedia.org/wiki/UTF-8#Invalid_byte_sequences

   except for the "overlong form" of \\u0000 which is not considered
   invalid here: Some languages, like Java and Tcl, use it. This function
   also considers valid the derivatives CESU-8 & WTF-8.
*/
FSL_EXPORT bool fsl_invalid_utf8(fsl_buffer const * const b);

/**
   Returns a static pointer to bytes of a UTF8 BOM. If the argument is
   not NULL, it is set to the strlen of those bytes (always 3).
*/
FSL_EXPORT unsigned char const *fsl_utf8_bom(unsigned int *pnByte);

/**
   Returns true if b starts with a UTF8 BOM. If the 2nd argument is
   not NULL, *pBomSize is set to the number of bytes in the BOM
   (always 3), regardless of whether or not the function returns true
   or false.
*/
FSL_EXPORT bool fsl_starts_with_bom_utf8(fsl_buffer const * const b, unsigned int *pBomSize);

#if 0
/**
   The UTF16 counterpart of fsl_looks_like_utf8(), with the addition that the
   2nd argument, if true, specifies that the 2nd argument is true then
   the contents of the buffer are byte-swapped for checking purposes.

   This is not validate that the blob is valid UTF16. It assumes that all
   code points are the same size and does not validate any of them, nor does
   it attempt to detect (invalid) switches between big-endian and little-endian.
 */
FSL_EXPORT int fsl_looks_like_utf16(fsl_buffer const * const pContent,
                                    bool reverse, int stopFlags);

/**
   Returns true if b'c contents begin with a UTF-16 BOM. If pBomSize is not NULL
   then it is set to the byte length of the UTF-16 BOM (2 bytes). If isReversed
   is not NULL, it gets assigned to true if the input appears to be in little-endian
   format and false if it appears to be in big-endian format.
*/
FSL_EXPORT bool fsl_starts_with_bom_utf16(fsl_buffer const * const b, unsigned int *pBomSize,
                                          bool * isReversed);
/**
   Returns true if b's content _might_ be valid UTF-16. If the 2nd argument is not NULL,
   it gets set to true if the input appears to be little-endian and false if it appears
   to be big-endian.
*/
FSL_EXPORT bool fsl_might_be_utf16(fsl_buffer const * const b, bool * isReversed);
#endif
/* ^^^^ UTF-16 interfaces */

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_UTIL_H_INCLUDED */
/* end of file ../include/fossil-scm/fossil-util.h */
/* start of file ../include/fossil-scm/fossil-core.h */
4958
4959
4960
4961
4962
4963
4964
4965






4966
4967
4968
4969
4970
4971
4972
5829
5830
5831
5832
5833
5834
5835

5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848







-
+
+
+
+
+
+







/**
   Analog to fossil's "main", which is basically an alias for the
   first db opened. This API opens an in-memory db to act as the main
   db and attaches the repo/checkout/config databases separately so
   that it has complete control over their names and internal
   relationships.
*/
FSL_DBROLE_MAIN = 0x08
FSL_DBROLE_MAIN = 0x08,
/**
   Refers to the "temp" database. This is only used by a very few APIs
   and is outright invalid for most.
*/
FSL_DBROLE_TEMP = 0x10
};
typedef enum fsl_dbrole_e fsl_dbrole_e;

/**
   Bitmask values specifying "configuration sets."  The values in
   this enum come directly from fossil(1), but they are not part of
   the db structure, so may be changed over time.
5310
5311
5312
5313
5314
5315
5316











5317
5318
5319
5320
5321
5322
5323
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







+
+
+
+
+
+
+
+
+
+
+








/**
   Indicates that the requested operation is missing certain required
   information.
*/
FSL_RC_MISSING_INFO,

/**
   Special case of FSL_RC_TYPE triggered in some diff APIs, indicating
   that the API cannot diff what appears to be binary data.
*/
FSL_RC_DIFF_BINARY,
/**
   Triggered by some diff APIs to indicate that only whitespace
   changes we found and the diff was requested to ignore whitespace.
 */
FSL_RC_DIFF_WS_ONLY,

/**
   Must be the final entry in the enum. Used for creating client-side
   result codes which are guaranteed to live outside of this one's
   range.
*/
FSL_RC_end
};
5405
5406
5407
5408
5409
5410
5411
5412

5413
5414
5415
5416
5417

5418
5419
5420
5421
5422
5423
5424
6292
6293
6294
6295
6296
6297
6298

6299
6300
6301
6302
6303

6304
6305
6306
6307
6308
6309
6310
6311







-
+




-
+








*/
struct fsl_cx_config {
  /**
     If true, all SQL which goes through the fossil engine
     will be traced to the fsl_output()-configured channel.
  */
  int traceSql;
  bool traceSql;
  /**
     If true, the fsl_print() SQL function will output its output to the
     fsl_output()-configured channel, else it is a no-op.
  */
  int sqlPrint;
  bool sqlPrint;

  /**
     Specifies the default hash policy.
  */
  fsl_hashpolicy_e hashPolicy;
};

5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568




5569
5570
5571
5572
5573
5574
5575
6445
6446
6447
6448
6449
6450
6451




6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462







-
-
-
-
+
+
+
+







   state to destruct.
*/
FSL_EXPORT void fsl_cx_finalize( fsl_cx * f );


/**
   Sets or unsets one or more option flags on the given fossil
   context.  flags is the flag or a bitmask of flags to set (from
   the fsl_cx_flags_e enum).  If enable is true the flag(s) is (are)
   set, else it (they) is (are) unset. Returns the new set of
   flags.
   context.  flags is the flag or a bitmask of flags to set (from the
   fsl_cx_flags_e enum).  If enable is true the flag(s) is (are) set,
   else it (they) is (are) unset. Returns the _previous_ set of flags
   (that is, the state they were in before this call was made).
*/
FSL_EXPORT int fsl_cx_flag_set( fsl_cx * f, int flags, bool enable );

/**
   Returns f's flags.
*/
FSL_EXPORT int fsl_cx_flags_get( fsl_cx * f );
5642
5643
5644
5645
5646
5647
5648
5649

5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662

5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674

5675
5676
5677
5678
5679
5680
5681
6529
6530
6531
6532
6533
6534
6535

6536
6537
6538
6539
6540
6541
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







-
+












-
+











-
+







   FSL_RC_MISUSE if !f, 0 if f has no error state our output of the
   state succeeds. If addNewline is true then it adds a trailing
   newline to the output, else it does not.

   This is intended for testing and debugging only, and not as an
   error reporting mechanism for a full-fledged application.
*/
FSL_EXPORT int fsl_cx_err_report( fsl_cx * f, char addNewline );
FSL_EXPORT int fsl_cx_err_report( fsl_cx * const f, bool addNewline );

/**
   Unconditionally Moves db->error's state into f. If db is NULL then
   f's primary db connection is used. Returns FSL_RC_MISUSE if !f or
   (!db && f-is-not-opened). On success it returns f's new error code.

   The main purpose of this function is to propagate db-level
   errors up to higher-level code which deals directly with the f
   object but not the underlying db(s).

   @see fsl_cx_uplift_db_error2()
*/
FSL_EXPORT int fsl_cx_uplift_db_error( fsl_cx * f, fsl_db * db );
FSL_EXPORT int fsl_cx_uplift_db_error( fsl_cx * const f, fsl_db * db );

/**
   If rc is not 0 and f has no error state but db does, this calls
   fsl_cx_uplift_db_error() and returns its result, else returns
   rc. If db is NULL, f's main db connection is used. It is intended
   to be called immediately after calling a db operation which might
   have failed, and passed that operation's result.

   Results are undefined if db is NULL and f has no main db
   connection.
*/
FSL_EXPORT int fsl_cx_uplift_db_error2(fsl_cx *f, fsl_db * db, int rc);
FSL_EXPORT int fsl_cx_uplift_db_error2(fsl_cx * const f, fsl_db * db, int rc);

/**
   Outputs the first n bytes of src to f's configured output
   channel. Returns 0 on success, FSL_RC_MISUSE if (!f || !src),
   0 (without side effects) if !n, else it returns the result of
   the underlying output call. This is a harmless no-op if f is
   configured with no output channel.
6113
6114
6115
6116
6117
6118
6119


6120
6121
6122
6123
6124
6125
6126
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015







+
+







                                              fsl_size_t * len);

/**
   Similar to fsl_cx_db_file_ckout() and friends except that it
   applies to db file implied by the specified role (2nd
   parameter). If no such role is opened, or the role is invalid,
   NULL is returned.

   Note that the role of FSL_DBROLE_TEMP is invalid here.
*/
FSL_EXPORT char const * fsl_cx_db_file_for_role(fsl_cx const * f,
                                                fsl_dbrole_e r,
                                                fsl_size_t * len);

/**
   Similar to fsl_cx_db_file_ckout() and friends except that it
6141
6142
6143
6144
6145
6146
6147


6148
6149
6150
6151
6152
6153
6154
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045







+
+







   libfossil uses "ckout", "repo", and "cfg", respective. So long as
   queries use table names which unambiguously refer to a given
   database, the DB name is normally not needed. It is needed when
   creating new non-TEMP db tables and views. By default such
   tables/views would go into the "main" DB, which is actually a
   transient DB in this API, so it's important to use the correct DB
   name when creating such constructs.

   Note that the role of FSL_DBROLE_TEMP is invalid here.
*/
FSL_EXPORT char const * fsl_cx_db_name_for_role(fsl_cx const * f,
                                                fsl_dbrole_e r,
                                                fsl_size_t * len);

/**
   If f has an opened checkout db (from fsl_ckout_open_dir()) then
6192
6193
6194
6195
6196
6197
6198
6199

6200
6201
6202
6203
6204
6205
6206
6207
6208

6209
6210
6211
6212
6213
6214
6215
6216
6217

6218
6219
6220
6221
6222
6223
6224
6225
6226
6227

6228
6229

6230
6231
6232



6233
6234
6235
6236

6237
6238









6239
6240
6241
6242
6243
6244
6245
7083
7084
7085
7086
7087
7088
7089

7090
7091
7092
7093
7094
7095
7096
7097
7098

7099
7100
7101
7102
7103
7104
7105
7106
7107

7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120

7121
7122
7123

7124
7125
7126
7127
7128
7129
7130
7131
7132

7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148







-
+








-
+








-
+










+

-
+


-
+
+
+




+

-
+
+
+
+
+
+
+
+
+







   names. Even so, it uses separate fsl_db instances to track each one
   so that we "could," if needed, switch back to a multi-db-instance
   approach if needed.

   @see fsl_cx_db_repo()
   @see fsl_cx_db_ckout()
*/
FSL_EXPORT fsl_db * fsl_cx_db( fsl_cx * f );
FSL_EXPORT fsl_db * fsl_cx_db( fsl_cx * const f );

/**
   If f is not NULL and has had its repo opened via
   fsl_repo_open(), fsl_ckout_open_dir(), or similar, this
   returns a pointer to that database, else it returns NULL.

   @see fsl_cx_db()
*/
FSL_EXPORT fsl_db * fsl_cx_db_repo( fsl_cx * f );
FSL_EXPORT fsl_db * fsl_cx_db_repo( fsl_cx * const f );

/**
   If f is not NULL and has had a checkout opened via
   fsl_ckout_open_dir() or similar, this returns a pointer to that
   database, else it returns NULL.

   @see fsl_cx_db()
*/
FSL_EXPORT fsl_db * fsl_cx_db_ckout( fsl_cx * f );
FSL_EXPORT fsl_db * fsl_cx_db_ckout( fsl_cx * const f );

/**
   A helper which fetches f's repository db. If f has no repo db
   then it sets f's error state to FSL_RC_NOT_A_REPO with a message
   describing the requirement, then returns NULL.  Returns NULL if
   !f.

   @see fsl_cx_db()
   @see fsl_cx_db_repo()
   @see fsl_needs_ckout()
   @see fsl_cx_has_ckout()
*/
FSL_EXPORT fsl_db * fsl_needs_repo(fsl_cx * f);
FSL_EXPORT fsl_db * fsl_needs_repo(fsl_cx * const f);

/**
   The checkout-db counterpart of fsl_needs_repo().
   The checkout-db counterpart of fsl_needs_repo(). If no checkout is
   opened, f's error state is updated with a FSL_RC_NOT_A_CKOUT code
   and description of the problem.

   @see fsl_cx_db()
   @see fsl_needs_repo()
   @see fsl_cx_db_ckout()
   @see fsl_cx_has_ckout()
*/
FSL_EXPORT fsl_db * fsl_needs_ckout(fsl_cx * f);
FSL_EXPORT fsl_db * fsl_needs_ckout(fsl_cx * const f);

/**
   Returns true if the given context has a checkout opened, else
   false.

   @see fsl_needs_ckout()
*/
FSL_EXPORT bool fsl_cx_has_ckout(fsl_cx const * const f );

/**
   Opens the given database file as f's configuration database. If f
   already has a config database opened, it is closed before opening
   the new one. The database is created and populated with an
   initial schema if needed.

6271
6272
6273
6274
6275
6276
6277
6278

6279
6280
6281
6282
6283
6284
6285
7174
7175
7176
7177
7178
7179
7180

7181
7182
7183
7184
7185
7186
7187
7188







-
+







/**
   If f has an opened/attached configuration db then its handle is
   returned, else 0 is returned.

   @see fsl_config_open()
   @see fsl_config_close()
*/
FSL_EXPORT fsl_db * fsl_cx_db_config( fsl_cx * f );
FSL_EXPORT fsl_db * fsl_cx_db_config( fsl_cx * const f );

/**
   Convenience form of fsl_db_prepare() which uses f's main db.
   Returns 0 on success, FSL_RC_MISUSE if !f or !sql, FSL_RC_RANGE
   if !*sql.
*/
FSL_EXPORT int fsl_cx_prepare( fsl_cx *f, fsl_stmt * tgt, char const * sql, ... );
6329
6330
6331
6332
6333
6334
6335
6336
6337


6338
6339
6340
6341
6342
6343
6344
7232
7233
7234
7235
7236
7237
7238


7239
7240
7241
7242
7243
7244
7245
7246
7247







-
-
+
+







   See fsl_stat() for more details regarding the tgt parameter.

   TODO: fossil-specific symlink support. Currently it does not
   distinguish between symlinks and non-links.

   @see fsl_cx_stat2()
*/
FSL_EXPORT int fsl_cx_stat( fsl_cx * f, bool relativeToCwd,
                            char const * zName, fsl_fstat * tgt );
FSL_EXPORT int fsl_cx_stat( fsl_cx * const f, bool relativeToCwd,
                            char const * zName, fsl_fstat * const tgt );

/**
   This works identically to fsl_cx_stat(), but provides more
   information about the file being stat'd.

   If nameOut is not NULL then the resolved/normalized path to to
   that file is appended to nameOut. If fullPath is true then an
6353
6354
6355
6356
6357
6358
6359
6360
6361





6362
6363
6364
6365
6366
6367
6368
7256
7257
7258
7259
7260
7261
7262


7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274







-
-
+
+
+
+
+







   nameOut.

   This function DOES NOT resolve symlinks, stat()nig the link instead
   of what it points to.

   @see fsl_cx_stat()
*/
FSL_EXPORT int fsl_cx_stat2( fsl_cx * f, bool relativeToCwd, char const * zName,
                             fsl_fstat * tgt, fsl_buffer * nameOut, bool fullPath);
FSL_EXPORT int fsl_cx_stat2( fsl_cx * const f, bool relativeToCwd,
                             char const * zName,
                             fsl_fstat * const tgt,
                             fsl_buffer * const nameOut,
                             bool fullPath);


/**
   Sets the case-sensitivity flag for f to the given value. This
   flag alters how some filename-search/comparison operations
   operate. This option is only intended to have an effect on
   plaforms with case-insensitive filesystems.
6629
6630
6631
6632
6633
6634
6635
6636

6637
6638
6639
6640
6641

6642
6643
6644
6645
6646

6647
6648
6649
6650
6651
6652
6653
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







-
+




-
+




-
+








/**
   Returns the same as passing fsl_cx_db() to
   fsl_db_transaction_level(), or 0 if f has no db opened.

   @see fsl_cx_db()
*/
FSL_EXPORT int fsl_cx_transaction_level(fsl_cx * f);
FSL_EXPORT int fsl_cx_transaction_level(fsl_cx * const f);
/**
   Returns the same as passing fsl_cx_db() to
   fsl_db_transaction_begin().
*/
FSL_EXPORT int fsl_cx_transaction_begin(fsl_cx * f);
FSL_EXPORT int fsl_cx_transaction_begin(fsl_cx * const f);
/**
   Returns the same as passing fsl_cx_db() to
   fsl_db_transaction_end().
*/
FSL_EXPORT int fsl_cx_transaction_end(fsl_cx * f, bool doRollback);
FSL_EXPORT int fsl_cx_transaction_end(fsl_cx * const f, bool doRollback);

/**
   Installs or (if f is NULL) uninstalls a confirmation callback for
   use by operations on f which require user confirmation. The exact
   implications of *not* installing a confirmer depend on the
   operation in question: see fsl_cx_confirm().

7882
7883
7884
7885
7886
7887
7888
7889
7890


7891
7892
7893
7894
7895
7896


7897
7898
7899
7900
7901
7902
7903
7904



7905
7906
7907
7908
7909
7910
7911
8788
8789
8790
8791
8792
8793
8794


8795
8796
8797
8798
8799
8800


8801
8802
8803
8804
8805
8806
8807
8808


8809
8810
8811
8812
8813
8814
8815
8816
8817
8818







-
-
+
+




-
-
+
+






-
-
+
+
+








   Returns 0 on success. On error db's error state is updated and
   *rv is not modified.

   Returns FSL_RC_MISUSE without side effects if !db, !rv, !sql,
   or !*sql.
*/
FSL_EXPORT int fsl_db_get_int32( fsl_db * db, int32_t * rv,
                      char const * sql, ... );
FSL_EXPORT int fsl_db_get_int32( fsl_db * const db, int32_t * rv,
                                 char const * sql, ... );

/**
   va_list counterpart of fsl_db_get_int32().
*/
FSL_EXPORT int fsl_db_get_int32v( fsl_db * db, int32_t * rv,
                       char const * sql, va_list args);
FSL_EXPORT int fsl_db_get_int32v( fsl_db * const db, int32_t * rv,
                                  char const * sql, va_list args);

/**
   Convenience form of fsl_db_get_int32() which returns the value
   directly but provides no way of checking for errors. On error,
   or if no result is found, defaultValue is returned.
*/
FSL_EXPORT int32_t fsl_db_g_int32( fsl_db * db, int32_t defaultValue,
                            char const * sql, ... );
FSL_EXPORT int32_t fsl_db_g_int32( fsl_db * const db,
                                   int32_t defaultValue,
                                   char const * sql, ... );

/**
   The int64 counterpart of fsl_db_get_int32(). See that function
   for the semantics.
*/
FSL_EXPORT int fsl_db_get_int64( fsl_db * db, int64_t * rv,
                      char const * sql, ... );
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
9354
9355
9356
9357
9358
9359
9360

9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375

9376
9377
9378
9379
9380
9381
9382
9383
9384







-
+





+
+
+






-
+
+







/**
   A fsl_stmt_each_f() impl, intended primarily for debugging, which
   simply outputs row data in tabular form via fsl_output(). The
   state argument is ignored. This only works if stmt was prepared
   by a fsl_db instance which has an associated fsl_cx instance. On
   the first row, the column names are output.
*/
FSL_EXPORT int fsl_stmt_each_f_dump( fsl_stmt * stmt, void * state );
FSL_EXPORT int fsl_stmt_each_f_dump( fsl_stmt * const stmt, void * state );

/**
   Returns true if the table name specified by the final argument
   exists in the fossil database specified by the 2nd argument on the
   db connection specified by the first argument, else returns false.

   Trivia: this is one of the few libfossil APIs which makes use of
   FSL_DBROLE_TEMP.

   Potential TODO: this is a bit of a wonky interface. Consider
   changing it to eliminate the role argument, which is only really
   needed if we have duplicate table names across attached dbs or if
   we internally mess up and write a table to the wrong db.
*/
FSL_EXPORT bool fsl_db_table_exists(fsl_db * db, fsl_dbrole_e whichDb, const char *zTable);
FSL_EXPORT bool fsl_db_table_exists(fsl_db * db, fsl_dbrole_e whichDb,
                                    const char *zTable);

/**
   The elipsis counterpart of fsl_stmt_bind_fmtv().
*/
FSL_EXPORT int fsl_stmt_bind_fmt( fsl_stmt * st, char const * fmt, ... );

/**
8503
8504
8505
8506
8507
8508
8509
8510

8511
8512
8513
8514
8515
8516
8517
9414
9415
9416
9417
9418
9419
9420

9421
9422
9423
9424
9425
9426
9427
9428







-
+







    ACHTUNG: the "sSbB" bindings assume, because of how this API is
    normally used, that the memory pointed to by the given argument
    will outlive the pending step of the given statement, so that
    memory is NOT copied by the binding. Thus results are undefined if
    such an argument's memory is invalidated before the statement is
    done with it.
*/
FSL_EXPORT int fsl_stmt_bind_fmtv( fsl_stmt * st, char const * fmt,
FSL_EXPORT int fsl_stmt_bind_fmtv( fsl_stmt * const st, char const * fmt,
                                   va_list args );

/**
   Works like fsl_stmt_bind_fmt() but:

   1) It calls fsl_stmt_reset() before binding the arguments.

8529
8530
8531
8532
8533
8534
8535
8536

8537
8538
8539
8540
8541
8542
8543
9440
9441
9442
9443
9444
9445
9446

9447
9448
9449
9450
9451
9452
9453
9454







-
+








   Design note: the return value for FSL_RC_STEP_ROW, as opposed to
   returning 0, is necessary for proper statement use if the client
   wants to fetch any result data from the statement afterwards (which
   is illegal if FSL_RC_STEP_ROW was not the result). This is also why
   it cannot reset the statement if that result is returned.
*/
FSL_EXPORT int fsl_stmt_bind_stepv( fsl_stmt * st, char const * fmt,
FSL_EXPORT int fsl_stmt_bind_stepv( fsl_stmt * const st, char const * fmt,
                                    va_list args );

/**
   The elipsis counterpart of fsl_stmt_bind_stepv().
*/
FSL_EXPORT int fsl_stmt_bind_step( fsl_stmt * st, char const * fmt, ... );

8688
8689
8690
8691
8692
8693
8694
8695

8696
8697
8698
8699
8700
8701
8702
9599
9600
9601
9602
9603
9604
9605

9606
9607
9608
9609
9610
9611
9612
9613







-
+







*/
FSL_EXPORT void fsl_md5_update(fsl_md5_cx *cx, void const * buf, fsl_size_t len);

/**
   Finishes up the calculation of the md5 for the given context and
   writes a 16-byte digest value to the 2nd parameter.  Use
   fsl_md5_digest_to_base16() to convert the digest output value to
   hexidecimal form.
   hexadecimal form.

   @see fsl_md5_init()
   @see fsl_md5_update()
   @see fsl_md5_digest_to_base16()
*/
FSL_EXPORT void fsl_md5_final(fsl_md5_cx * cx, unsigned char * digest);

10011
10012
10013
10014
10015
10016
10017
10018

10019
10020
10021
10022





10023
10024
10025
10026


10027
10028
10029
10030
10031
10032
10033
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







-
+




+
+
+
+
+


-
-
+
+







   the typical use case require potentially lazy-loading
   d->B.baseline and updating d->F.
*/
FSL_EXPORT fsl_card_F const * fsl_deck_F_search(fsl_deck *d, const char *zName);

/**
   Given two F-card instances, this function compares their names
   (case-insensitively). Returns a negative value if lhs is
   (case-sensitively). Returns a negative value if lhs is
   lexically less than rhs, a positive value if lhs is lexically
   greater than rhs, and 0 if they are lexically equivalent (or are
   the same pointer).


   Though fossil repositories may be case-insensitive, the F-cards use
   a stable casing unless a file is removed and re-added with a
   different case, so this comparison is case-sensitive..

   Results are undefined if either argument is NULL.
*/
FSL_EXPORT int fsl_card_F_compare( fsl_card_F const * lhs,
                                   fsl_card_F const * rhs);
FSL_EXPORT int fsl_card_F_compare_name( fsl_card_F const * const lhs,
                                        fsl_card_F const * const rhs);

/**
   If fc->uuid refers to a blob in f's repository database then that
   content is placed into dest (as per fsl_content_get()) and 0 is
   returned. Returns FSL_RC_NOT_FOUND if fc->uuid is not
   found. Returns FSL_RC_MISUSE if any argument is NULL.  If
   fc->uuid is NULL (indicating that it refers to a file deleted in
10909
10910
10911
10912
10913
10914
10915
10916


10917
10918
10919
10920
10921
10922


10923
10924
10925
10926
10927
10928
10929
11825
11826
11827
11828
11829
11830
11831

11832
11833
11834
11835
11836
11837
11838

11839
11840
11841
11842
11843
11844
11845
11846
11847







-
+
+





-
+
+








   - FSL_RC_OOM if an allocation fails.


   @see fsl_content_blob()
   @see fsl_content_size()
*/
FSL_EXPORT int fsl_content_get( fsl_cx * f, fsl_id_t blobRid, fsl_buffer * tgt );
FSL_EXPORT int fsl_content_get( fsl_cx * const f, fsl_id_t blobRid,
                                fsl_buffer * const tgt );

/**
   Uses fsl_sym_to_rid() to convert sym to a record ID, then
   passes that to fsl_content_get(). Returns 0 on success.
*/
FSL_EXPORT int fsl_content_get_sym( fsl_cx * f, char const * sym, fsl_buffer * tgt );
FSL_EXPORT int fsl_content_get_sym( fsl_cx * const f, char const * sym,
                                    fsl_buffer * const tgt );

/**
   Returns true if the given rid is marked as PRIVATE in f's current
   repository. Returns false (0) on error or if the content is not
   marked as private.
*/
FSL_EXPORT bool fsl_content_is_private(fsl_cx * f, fsl_id_t rid);
11397
11398
11399
11400
11401
11402
11403







11404
11405
11406
11407
11408
11409
11410
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335







+
+
+
+
+
+
+







   If progressVisitor is not NULL then it is called once just
   before each file is processed, passed the F-card for the file
   about to be zipped and the progressState parameter. If it
   returns non-0, ZIPping is cancelled and that error code is
   returned. This is intended primarily for providing feedback on
   the update process, but could also be used to cancel the
   operation between files.

   As of 2021-09-05 this routine automatically adds the files
   (manifest, manifest.uuid, manifest.tags) to the zip file,
   regardless of repository-level settings regarding those
   pseudo-files (see fsl_ckout_manifest_write()). As there are no
   F-cards associated with those non-files, the progressVisitor is not
   called for those.

   BUG: this function does not honor symlink content in a
   fossil-compatible fashion. If it encounters a symlink entry
   during ZIP generation, it will fail and f's error state will be
   updated with an explanation of this shortcoming.

   @see fsl_zip_writer
11764
11765
11766
11767
11768
11769
11770
11771

11772
11773
11774
11775
11776
11777

11778
11779
11780
11781
11782
11783
11784
12689
12690
12691
12692
12693
12694
12695

12696
12697
12698
12699
12700
12701

12702
12703
12704
12705
12706
12707
12708
12709







-
+





-
+







/**
   Ensures that the given list has capacity for at least n entries. If
   the capacity is currently equal to or less than n, this is a no-op
   unless n is 0, in which case li->list is freed and the list is
   zeroed out. Else li->list is expanded to hold at least n
   elements. Returns 0 on success, FSL_RC_OOM on allocation error.
 */
int fsl_card_F_list_reserve( fsl_card_F_list * li, uint32_t n );
FSL_EXPORT int fsl_card_F_list_reserve( fsl_card_F_list * li, uint32_t n );

/**
   Frees all memory owned by li and the F-cards it contains. Does not
   free the li pointer.
*/
void fsl_card_F_list_finalize( fsl_card_F_list * li );
FSL_EXPORT void fsl_card_F_list_finalize( fsl_card_F_list * li );

/**
   Holds options for use with fsl_branch_create().
*/
struct fsl_branch_opt {
  /**
     The checkin RID from which the branch should originate.
11982
11983
11984
11985
11986
11987
11988
11989
11990


11991
11992
11993
11994
11995
11996
11997
12907
12908
12909
12910
12911
12912
12913


12914
12915
12916
12917
12918
12919
12920
12921
12922







-
-
+
+








   If type is not FSL_SATYPE_ANY then it will only match artifacts
   of the specified type. In order to resolve arbitrary UUIDs, e.g.
   those of arbitrary blob content, type needs to be
   FSL_SATYPE_ANY.

*/
FSL_EXPORT int fsl_sym_to_rid( fsl_cx * f, char const * sym, fsl_satype_e type,
                               fsl_id_t * rv );
FSL_EXPORT int fsl_sym_to_rid( fsl_cx * const f, char const * sym,
                               fsl_satype_e type, fsl_id_t * rv );

/**
   Similar to fsl_sym_to_rid() but on success it returns a UUID string
   by assigning it to *rv (if rv is not NULL). If rid is not NULL then
   on success the db record ID corresponding to the returned UUID is
   assigned to *rid. The caller must eventually free the returned
   string memory by passing it to fsl_free(). Returns 0 if it finds a
12317
12318
12319
12320
12321
12322
12323


















































































































































































































































































12324
12325
12326
12327
12328
12329
12330
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
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
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
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529







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







   those which are injected into the db via lower-level means (e.g. a
   direct blob import or from a remote sync).

   Results are undefined if f has no opened repository.
*/
FSL_EXPORT bool fsl_repo_forbids_delta_manifests(fsl_cx * f);

/**
   This is a variant of fsl_ckout_manifest_write() which writes data
   regarding the given manifest RID to the given blobs. If manifestRid
   is 0 or less then the current checkout is assumed and
   FSL_RC_NOT_A_CKOUT is returned if no checkout is opened (or
   FSL_RC_RANGE if an empty checkout is opened - a freshly-created
   repository with no checkins).

   For each buffer argument which is not NULL, the corresponding
   checkin-related data are appended to it. All such blobs will end
   in a terminating newline character.

   Returns 0 on success, any of numerious non-0 fsl_rc_e codes on
   error.
*/
FSL_EXPORT int fsl_repo_manifest_write(fsl_cx *f,
                                       fsl_id_t manifestRid,
                                       fsl_buffer * const manifest,
                                       fsl_buffer * const manifestUuid,
                                       fsl_buffer * const manifestTags );


/**
   "Stage" flag for use with fsl_annotate_step and
   fsl_annotate_step_f().
*/
enum fsl_annotate_step_e {
/**
   Indicates that the current fsl_annotate_step_f() call is
   part of the "version dump" stage of the annotation.
*/
FSL_ANNOTATE_STEP_VERSION,
/**
   Indicates that the current fsl_annotate_step_f() call has
   complete version information for the line it is reporting
   about.
*/
FSL_ANNOTATE_STEP_FULL,
/**
   Indicates that the current fsl_annotate_step_f() call has
   only partial version information for the line it is reporting
   about, as a result of a limited-run annotation.
*/
FSL_ANNOTATE_STEP_LIMITED
};
typedef enum fsl_annotate_step_e fsl_annotate_step_e;

/**
   Callback state for use by fsl_annotate_step_f().

   ACHTUNG: this state gets repopulated for each call to the
   fsl_annote_step_f() callback and any pointers it holds must be
   treated as if they are invalidated as soon as the callback returns
   (whether or not that is the case is undefined, though).

   Not all state is set on each call involving this object. See the
   stepType member for details.
*/
struct fsl_annotate_step {
  /**
     Tells the caller the "type" of annotation step this call
     represents. The type of step will determine which fields
     of this object are populated when it is passed to a
     fsl_annotate_step_f() callback:

     Always set:

     stepType, stepNumber (but interpretation varies - see that
     member's docs for details).

     FSL_ANNOTATE_STEP_VERSION: fileHash, versionHash, mtime

     FSL_ANNOTATE_STEP_LIMITED: stepNumber (always 0 for the limited
     case), lineNumber, line, lineNength.

     FSL_ANNOTATE_STEP_FULL: as for FSL_ANNOTATE_STEP_LIMITED plus:
     fileHash, versionHash, mtime, username.
  */
  fsl_annotate_step_e stepType;
  /**
     Step number in this annotation run. When this->stepType is
     FSL_ANNOTATE_STEP_VERSION, this value is the relative number of
     the version, starting at 0 and incremented by 1 on each call. In
     the other modes it is 0-based relative version from which the
     current line is from, or negative if that information is
     incomplete due to a limited annotation run. e.g. a value of 3
     indicates that this line is from 3 version away from the starting
     version.
  */
  int stepNumber;
  /**
     Line number for the current file.
  */
  uint32_t lineNumber;
  /**
     NUL-terminated current line of the input file, minus any
     newline and/or carriage return.
  */
  char const * line;
  /**
     The number of bytes in this->line.
  */
  uint32_t lineLength;
  /**
     The hash of the file version from which this->line was
     pulled.
  */
  fsl_uuid_cstr fileHash;
  /**
     The hash of the checkin version from which this->line was
     pulled.
  */
  fsl_uuid_cstr versionHash;

  /**
     The mtime field from the [event] table (timeline) entry
     associated with this version. This is a Julian Date and, because
     it is updated by annotations which modify timestamps in the
     [event] table, it reflects any "edited" time (if any).

     @see fsl_julian_to_iso8601()
  */
  double mtime;
  /**
     The user name this change was attributed to, noting that merges
     are attributed to the one who did the merge.
  */
  char const * username;
};

/** Convenience typedef. */
typedef struct fsl_annotate_step fsl_annotate_step;
/** Forward decl and convenience typedef. */
typedef struct fsl_annotate_opt fsl_annotate_opt;

/**
   Callback for use with fsl_annotate(). Implementations receive
   state about each step of an annotation process. They must return 0
   on success. On error, their non-0 result code is propagated back
   to the fsl_annotate() caller.
*/
typedef int (*fsl_annotate_step_f)(void * state,
                                   fsl_annotate_opt const * const opt,
                                   fsl_annotate_step const * const step);

/**
   A fsl_annotate_step_f() impl. which requires that its first argument
   be a fsl_outputer. It formats each step of the annotation
   in a manner similar to fossil(1) and forwards the result to
   state->out(state->state, ...), returning that function's result code.
*/
int fsl_annotate_step_f_fossilesque(void * state,
                                    fsl_annotate_opt const * const opt,
                                    fsl_annotate_step const * const step);

/**
   Configuration for use with fsl_annotate().

   This structure holds options for the "annotate" operation and its
   close cousin, "blame" a.k.a. "praise." Annotation takes a given
   file version and builds a line-by-line history, showing when each
   line was last modified. The "blame" a.k.a. "praise" option includes
   *who* modified that line.
*/
struct fsl_annotate_opt {
  /**
     The repository-root-relative NUL-terminated filename to annotate.
  */
  char const * filename;
  /**
     The checkin from which the file's version should be selected. A
     value of 0 or less means the current checkout, if in a checkout,
     and is otherwise an error.
  */
  fsl_id_t versionRid;
  /**
     The origin checkin version. A value of 0 or less means the "root of the
     tree."

     TODO: figure out and explain the difference between versionRid
     and originRid.
  */
  fsl_id_t originRid;
  /**
     The maximum number of versions to search through.

     Note that fossil(1) offers the ability to limit the calculation
     based on processing time, e.g. to 1500ms. We may or may not add
     that in this library.
  */
  uint32_t limit;
  /**
     - 0 = do not ignore any spaces.
     - <0 = ignore trailing end-of-line spaces.
     - >1 = ignore all spaces
  */
  int16_t spacePolicy;
  /**
     If true, include the name of the user for which each change is
     attributed (noting that merges show whoever merged the change,
     which may differ from the original committer, and amended user
     names will be used over those in the initial commit). If false,
     show only version information.

     This option is alternately known as "blame".

     For reasons lost to history, blame/praise mode does not include
     line numbers. That may change in the future.
  */
  bool praise;
  /**
     Output file blob versions, instead of checkin versions.
  */
  bool fileVersions;

  /**
     If true, annotation output will start with a list of all
     versions analyzed by the annotation process.
  */
  bool dumpVersions;
  /**
     The output channel for the resulting annotation.
  */
  fsl_annotate_step_f out;
  /**
     State for passing as the first argument to this->out().
  */
  void * outState;
};

/** Initialized-with-defaults fsl_annotate_opt structure, intended for
    const-copy initialization. */
#define fsl_annotate_opt_empty_m {\
  NULL/*filename*/, \
  0/*versionRid*/,0/*originRid*/,    \
  0U/*limit*/, 0/*spacePolicy*/, \
  false/*praise*/, false/*fileVersions*/,     \
  false/*dumpVersions*/,                  \
  NULL/*out*/, NULL/*outState*/               \
}

/** Initialized-with-defaults fsl_annotate_opt structure, intended for
    non-const copy initialization. */
extern const fsl_annotate_opt fsl_annotate_opt_empty;

/**
   UNDER CONSTRUCTION. Not yet known to be fully functional or
   bug-free.

   Runs an "annotation" of an SCM-controled file and sends the results
   to opt->out().

   Returns 0 on success. On error, returns one of:

   - FSL_RC_OOM on OOM

   - FSL_RC_NOT_A_CKOUT if opt->versionRid<=0 and f has no opened checkout.

   - FSL_RC_NOT_FOUND if the given filename cannot be found in the
     repository OR a given version ID does not resolve to a blob. (Sorry
     about this ambiguity!)

   - FSL_RC_PHANTOM if a phantom blob is encountered while trying to
     annotate.

   opt->out() may return arbitrary non-0 result codes, in which case
   the returned code is propagated to the caller of this function.

   Results are undefined if either argument is invalid or opt->out is
   NULL.
*/
FSL_EXPORT int fsl_annotate( fsl_cx * const f,
                             fsl_annotate_opt const * const opt );

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_REPO_H_INCLUDED */
/* end of file ../include/fossil-scm/fossil-repo.h */
/* start of file ../include/fossil-scm/fossil-checkout.h */
12372
12373
12374
12375
12376
12377
12378
12379
12380


12381
12382
12383
12384
12385
12386
12387
13571
13572
13573
13574
13575
13576
13577


13578
13579
13580
13581
13582
13583
13584
13585
13586







-
-
+
+







   later.

   Corner case: a new repo with no checkins has an RID of 0 and a UUID
   of NULL. That does not happen with fossil-generated repositories,
   as those always "seed" the database with an initial commit artifact
   containing no files.
*/
FSL_EXPORT void fsl_ckout_version_info(fsl_cx *f, fsl_id_t * rid,
                                       fsl_uuid_cstr * uuid );
FSL_EXPORT void fsl_ckout_version_info(fsl_cx * const f, fsl_id_t * const rid,
                                       fsl_uuid_cstr * const uuid );

/**
   Given a fsl_cx with an opened checkout, and a filename, this
   function canonicalizes zOrigName to a form suitable for use as
   an in-repo filename, _appending_ the results to pOut. If pOut is
   NULL, it performs its normal checking but does not write a
   result, other than to return 0 for success.
12573
12574
12575
12576
12577
12578
12579
12580
12581


12582
12583
12584
12585
12586
12587
12588
13772
13773
13774
13775
13776
13777
13778


13779
13780
13781
13782
13783
13784
13785
13786
13787







-
-
+
+








   Files queued for addition this way can be unqueued before they are
   committed using fsl_ckout_unmanage().

   @see fsl_ckout_unmanage()
   @see fsl_reserved_fn_check()
*/
FSL_EXPORT int fsl_ckout_manage( fsl_cx * f,
                                   fsl_ckout_manage_opt * opt );
FSL_EXPORT int fsl_ckout_manage( fsl_cx * const f,
                                 fsl_ckout_manage_opt * const opt );


/**
   Callback type for use with fsl_ckout_unmanage(). It is called
   by the removal process, immediately after a file is "removed"
   from SCM management (a.k.a. when the file becomes "unmanaged").

14193
14194
14195
14196
14197
14198
14199


14200
14201
14202
14203
14204
14205
14206
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407







+
+







   was/were written before the error was triggered.

   Each file implied by the various manifest settings which is NOT
   written by this routine and is also not part of the current
   checkout (i.e. not listed in the vfile table) will be removed from
   disk, but a failure while attempting to do so will be silently
   ignored.

   @see fsl_repo_manifest_write()
*/
FSL_EXPORT int fsl_ckout_manifest_write(fsl_cx *f,
                                        int manifest,
                                        int manifestUuid,
                                        int manifestTags,
                                        int *wroteWhat );

14535
14536
14537
14538
14539
14540
14541
14542
14543
14544




14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563





















































14564
14565
14566
14567
14568
14569
14570
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







-
-
-
+
+
+
+



















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







   @see fsl_vfile_unload()
*/
FSL_EXPORT int fsl_vfile_unload_except(fsl_cx * f, fsl_id_t vid);


/**
   Performs a "fingerprint check" between f's current checkout and
   repository databases. Returns 0 if either there is no mismatch or
   it is impossible to determine because the checkout is missing a
   fingerprint (which is legal for "older" checkout databases).
   repository databases. Returns 0 if either there is no checkout, no
   mismatch, or it is impossible to determine because the checkout is
   missing a fingerprint (which is legal for "older" checkout
   databases).

   If a mismatch is found, FSL_RC_REPO_MISMATCH is returned. Returns
   some other non-0 code on a lower-level error (db access, OOM,
   etc.).

   A mismatch can happen when the repository to which a checkout
   belongs is replaced, either with a completely different repository
   or a copy/clone of that same repository. Each repository copy may
   have differing blob.rid values, and those are what the checkout
   database uses to refer to repository-side data. If those RIDs
   change, then the checkout is left pointing to data other than what
   it should be.

   TODO: currently the library offers no automated recovery mechanism
   from a mismatch, the only remedy being to close the checkout
   database, destroy it, and re-create it. fossil(1) is able, in some cases,
   to automatically recover from this situation.
*/
FSL_EXPORT int fsl_ckout_fingerprint_check(fsl_cx * f);

/**
   Looks for the given file in f's current checkout. If relativeToCwd
   then the name is resolved from the current directory, otherwise it is
   assumed to be relative to the checkout root or an absolute path
   with the checkout dir as a prefix of that path.

   On success, 0 is returned and dest's gets populated with the
   content of the file.

   On error, non-0 is returned and, depending on the error type, dest
   might be partially populated. f's error state will be updated to
   describe the error.

   Results are undefined if any pointer argument is NULL.

   This function currently resolves symlinks on its way to the
   content, but that behaviour may change in the future to reflect f's
   symlink preferences.
*/
FSL_EXPORT int fsl_ckout_file_content(fsl_cx * const f, bool relativeToCwd,
                                      char const * zName,
                                      fsl_buffer * const dest);


/**
   Fetches the timestamp of the given F-card's name against the
   filesystem and/or the most recent checkin in which it was modified
   (as reported by fsl_mtime_of_manifest()). vid is the checkin
   version to look at. If it's 0, the current checkout will be used.

   On success, returns 0 and:

   - If repoMtime is not NULL then (*repoMtime) is assigned to the
   result of fsl_mtime_of_manifest_file() for the given file.

   - If localMtime is not NULL then (*localMtime) is assigned to
   the checkout-local timestamp of the file.

   Returns non-0 on error. Some of the potential results include:

   - FSL_RC_NOT_A_CKOUT.

   - FSL_RC_NOT_FOUND if the filename cannot be resolved in the
     requested version or cannot be stat()'d.

   - FSL_RC_OOM.
*/
FSL_EXPORT int fsl_card_F_ckout_mtime(fsl_cx * const f, fsl_id_t vid,
                                      fsl_card_F const * const fc,
                                      fsl_time_t * repoMtime,
                                      fsl_time_t * localMtime);


#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_CHECKOUT_H_INCLUDED */
/* end of file ../include/fossil-scm/fossil-checkout.h */
15099
15100
15101
15102
15103
15104
15105
15106
15107


15108
15109
15110
15111
15112
15113
15114
16354
16355
16356
16357
16358
16359
16360


16361
16362
16363
16364
16365
16366
16367
16368
16369







-
-
+
+







/**
   Frees all nodes in path (which must not be NULL) and resets all
   state in path. Does not free path.
*/
FSL_EXPORT void fsl_vpath_clear(fsl_vpath *path);

/**
   Find the mid-point of the path.  If the path contains fewer than
   2 steps, returns 0. The returned node is owned by path may be
   Find the mid-point of the path.  If the path contains fewer than 2
   steps, returns 0. The returned node is owned by path and may be
   invalidated by any APIs which manipulate path.
*/
FSL_EXPORT fsl_vpath_node * fsl_vpath_midpoint(fsl_vpath * path);


/**
   Computes the shortest path from checkin versions iFrom to iTo
15136
15137
15138
15139
15140
15141
15142
15143

15144
15145
15146

















































15147
15148
15149
15150
15151
15152
15153
16391
16392
16393
16394
16395
16396
16397

16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
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







-
+



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







   }
   fsl_vpath_clear(&path);
   @endcode

   On error, f's error state may be updated with a description of the
   problem.
*/
FSL_EXPORT int fsl_vpath_shortest( fsl_cx * f, fsl_vpath * path,
FSL_EXPORT int fsl_vpath_shortest( fsl_cx * const f, fsl_vpath * const path,
                                   fsl_id_t iFrom, fsl_id_t iTo,
                                   bool directOnly, bool oneWayOnly );

/**
   This variant of fsl_vpath_shortest() stores the shortest direct
   path from version iFrom to version iTo in the ANCESTOR temporary
   table using f's current repo db handle. That table gets created, if
   needed, else cleared by this call.

   The ANCESTOR temp table has the following interface:

   @code
   rid INT UNIQUE
   generation INTEGER PRIMARY KEY
   @endcode

   Where [rid] is a checkin version RID and [generation] is the
   1-based number of steps from iFrom, including iFrom (so iFrom's own
   generation is 1).

   On error returns 0 and, if pSteps is not NULL, assigns *pSteps to
   the number of entries added to the ancestor table. On error, pSteps
   is never modifed, any number of various non-0 codes may be
   returned, and f's error state will, if possible (not an OOM), be
   updated to describe the problem.

   This function's name is far too long and descriptive. We might want
   to consider something shorter.

   Maintenance reminder: this impl swaps the 2nd and 3rd parameters
   compared to fossil(1)'s version!
*/
FSL_EXPORT int fsl_vpath_shortest_store_in_ancestor(fsl_cx * const f,
                                                    fsl_id_t iFrom,
                                                    fsl_id_t iTo,
                                                    uint32_t *pSteps);

/**
   Computes a list of direct (non-merge) ancestors of the given
   checkin RID and stores it in the TEMP table [ancestor], which it
   creates if needed or clears if it currently exists.

   The [ancestor] schema is described in
   fsl_vpath_shortest_store_in_ancestor(). The [generation] value of
   the record corresponding to rid is 1, increasing by 1 for each
   generation back in the history.

   Returns 0 on success, FSL_RC_NOT_A_REPO if f has no repo db opened,
   and any number of lower-level result codes if something goes wrong.
*/
FSL_EXPORT int fsl_compute_direct_ancestors(fsl_cx * const f, fsl_id_t rid);

/**
   Reconstructs path from path->pStart to path->pEnd, reversing its
   order by fiddling with the u->pTo fields.

   Unfortunately does not reverse after the initial creation/reversal
   :/.
*/
17140
17141
17142
17143
17144
17145
17146



















































































17147
17148
17149
17150
17151
17152
17153
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
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







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







   expected to be in many repositories which are accessed via this
   library. Practice has, however, revealed some.

   @see fsl_ckout_fingerprint_check()
*/
FSL_EXPORT int fsl_repo_fingerprint_search(fsl_cx *f, fsl_id_t rcvid, char ** zOut);

/**
   A context for running a raw diff.
  
   The aEdit[] array describes the raw diff.  Each triple of integers in
   aEdit[] means:
  
     (1) COPY:   Number of lines aFrom and aTo have in common
     (2) DELETE: Number of lines found only in aFrom
     (3) INSERT: Number of lines found only in aTo
  
   The triples repeat until all lines of both aFrom and aTo are accounted
   for.
*/
struct fsl_diff_cx {
  /*TODO unsigned*/ int *aEdit;        /* Array of copy/delete/insert triples */
  /*TODO unsigned*/ int nEdit;         /* Number of integers (3x num of triples) in aEdit[] */
  /*TODO unsigned*/ int nEditAlloc;    /* Space allocated for aEdit[] */
  fsl_dline *aFrom;      /* File on left side of the diff */
  /*TODO unsigned*/ int nFrom;         /* Number of lines in aFrom[] */
  fsl_dline *aTo;        /* File on right side of the diff */
  /*TODO unsigned*/ int nTo;           /* Number of lines in aTo[] */
  int (*cmpLine)(const fsl_dline * const, const fsl_dline *const); /* Function to be used for comparing */
};
/**
   Convenience typeef.
*/
typedef struct fsl_diff_cx fsl_diff_cx;
/** Initialized-with-defaults fsl_diff_cx structure, intended for
    const-copy initialization. */
#define fsl_diff_cx_empty_m {\
  NULL,0,0,NULL,0,NULL,0,fsl_dline_cmp \
}
/** Initialized-with-defaults fsl_diff_cx structure, intended for
    non-const copy initialization. */
extern const fsl_diff_cx fsl_diff_cx_empty;



/** @internal

    Compute the differences between two files already loaded into
    the fsl_diff_cx structure.
   
    A divide and conquer technique is used.  We look for a large
    block of common text that is in the middle of both files.  Then
    compute the difference on those parts of the file before and
    after the common block.  This technique is fast, but it does
    not necessarily generate the minimum difference set.  On the
    other hand, we do not need a minimum difference set, only one
    that makes sense to human readers, which this algorithm does.
   
    Any common text at the beginning and end of the two files is
    removed before starting the divide-and-conquer algorithm.
   
    Returns 0 on succes, FSL_RC_OOM on an allocation error.
*/
int fsl__diff_all(fsl_diff_cx * const p);

/** @internal
 */
void fsl__diff_optimize(fsl_diff_cx * const p);

/** @internal
 */
void fsl__diff_cx_clean(fsl_diff_cx * const cx);

/** @internal

    Undocumented. For internal debugging only.
 */
void fsl__dump_triples(fsl_diff_cx const * const p,
                       char const * zFile, int ln );

/** @internal

    Maximum length of a line in a text file, in bytes.  (2**13 = 8192 bytes)
*/
#define FSL_LINE_LENGTH_MASK_SZ  15
/** @internal

 */
#define FSL_LINE_LENGTH_MASK     ((1<<FSL_LINE_LENGTH_MASK_SZ)-1)

#if defined(__cplusplus)
} /*extern "C"*/
#endif
#endif
/* ORG_FOSSIL_SCM_FSL_INTERNAL_H_INCLUDED */
/* end of file ../include/fossil-scm/fossil-internal.h */
/* start of file ../include/fossil-scm/fossil-auth.h */
17276
17277
17278
17279
17280
17281
17282
17283


17284
17285




17286
17287
17288
17289
17290
17291
17292
18663
18664
18665
18666
18667
18668
18669

18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684







-
+
+


+
+
+
+







  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 declares public APIs for working with fossil-managed content.
  This file declares public APIs for working with fossil-managed forum
  content.
*/


#if defined(__cplusplus)
extern "C" {
#endif

/**
   If the given fossil context has a db opened, this function
   installs, if needed, the forum-related schema and returns 0 on
   success (or if no installation was needed). If f has no repository
   opened, FSL_RC_NOT_A_REPO is returned. Some other FSL_RC_xxx value
   is returned if there is a db-level error during installation.
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060



18061
18062
18063
18064
18065
18066
18067
19443
19444
19445
19446
19447
19448
19449



19450
19451
19452
19453
19454
19455
19456
19457
19458
19459







-
-
-
+
+
+







  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 provides a basis for basic libfossil-using apps. It is intended
  to be used as the basis for test/demo apps, and not necessarily full-featured
  applications.
  This file provides a basis for basic libfossil-using apps. It
  attempts to provide basic services required by a wide variety of
  fossil-using apps, with the intent of simplifying their creation.
*/

/* Force assert() to always work... */
#if defined(NDEBUG)
#undef NDEBUG
#define DEBUG 1
#endif
18295
18296
18297
18298
18299
18300
18301
18302

18303
18304
18305
18306
18307
18308
18309
19687
19688
19689
19690
19691
19692
19693

19694
19695
19696
19697
19698
19699
19700
19701







-
+







  */
  const char * helpText;
};
#define fcli_cliflag_empty_m {\
    0/*flagShort*/,0/*flagLong*/,\
    FCLI_FLAG_TYPE_INVALID/*flagType*/,\
    NULL/*flagValue*/,\
      NULL/*flagValueLabel*/,NULL/*callback*/,NULL/*helpText*/}
    NULL/*flagValueLabel*/,NULL/*callback*/,NULL/*helpText*/}
/** Non-const-copyable counterpart of fcli_cliflag_empty_m. */
FSL_EXPORT const fcli_cliflag fcli_cliflag_empty;

/** @def FCLI_FLAG_xxx

   The various FCLI_FLAG_xxx macros are convenience-form initializers
   for fcli_cliflag instances for use in initializing a fcli_cliflag
18523
18524
18525
18526
18527
18528
18529





18530
18531
18532
18533
18534
18535
18536
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933







+
+
+
+
+







    */
    const char * userArg;
    /**
       Incremented if fcli_setup() detects -? or --help in the
       argument list, or if the first non-flag argument is "help".
    */
    short helpRequested;
    /**
       True if the --lib-version CLI flag was used. This causes
       fcli setup to exit as if --help had been invoked.
    */
    bool versionRequested;
  } transient;
  /**
     Holds bits which can/should be configured by clients BEFORE
     calling fcli_setup().
  */
  struct {
    /**
19076
19077
19078
19079
19080
19081
19082
























19083
19084
19085
19086
19087
19088
19089
19090
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511







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








   Returns the "tail" part of the argv[0] string which was passed to
   fcli_setup() or fcli_setup2(), or NULL if neither of those have yet
   been called. The "tail" part is the part immediately after the
   final '/' or '\\' character.
*/
FSL_EXPORT char const * fcli_progname();

/**
   Color theme IDs for use with fcli_diff_colors.
 */
enum fcli_diff_colors_e{
/**
   Tells fcli_diff_colors() to NULL out the ANSI color state of its
   target object.
*/
FCLI_DIFF_COLORS_NONE = 0,
/**
   Basic red (deletion) and green (insertion) diff colors.
*/
FCLI_DIFF_COLORS_RG,
FCLI_DIFF_COLORS_DEFAULT = FCLI_DIFF_COLORS_RG
};
typedef enum fcli_diff_colors_e fcli_diff_colors_e;

/**
   Populates the given fsl_diff_opt::ansiColors state with values
   dependend on the second argument.
*/
FSL_EXPORT void fcli_diff_colors(fsl_diff_opt * const tgt,
                                 fcli_diff_colors_e theme);

#if defined(__cplusplus)
} /*extern "C"*/
#endif


#endif
/* _ORG_FOSSIL_SCM_FCLI_H_INCLUDED_ */
/* end of file ../include/fossil-scm/fossil-cli.h */

Changes to src/sqlite3.c.

more than 10,000 changes

Changes to src/sqlite3.h.

39
40
41
42
43
44
45
46
























47
48
49
50
51
52
53
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







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







*/
#ifdef __cplusplus
extern "C" {
#endif


/*
** Provide the ability to override linkage features of the interface.
** Facilitate override of interface linkage and calling conventions.
** Be aware that these macros may not be used within this particular
** translation of the amalgamation and its associated header file.
**
** The SQLITE_EXTERN and SQLITE_API macros are used to instruct the
** compiler that the target identifier should have external linkage.
**
** The SQLITE_CDECL macro is used to set the calling convention for
** public functions that accept a variable number of arguments.
**
** The SQLITE_APICALL macro is used to set the calling convention for
** public functions that accept a fixed number of arguments.
**
** The SQLITE_STDCALL macro is no longer used and is now deprecated.
**
** The SQLITE_CALLBACK macro is used to set the calling convention for
** function pointers.
**
** The SQLITE_SYSAPI macro is used to set the calling convention for
** functions provided by the operating system.
**
** Currently, the SQLITE_CDECL, SQLITE_APICALL, SQLITE_CALLBACK, and
** SQLITE_SYSAPI macros are used only when building for environments
** that require non-default calling conventions.
*/
#ifndef SQLITE_EXTERN
# define SQLITE_EXTERN extern
#endif
#ifndef SQLITE_API
# define SQLITE_API
#endif
119
120
121
122
123
124
125
126
127
128



129
130
131
132
133
134
135
142
143
144
145
146
147
148



149
150
151
152
153
154
155
156
157
158







-
-
-
+
+
+







** been edited in any way since it was last checked in, then the last
** four hexadecimal digits of the hash may be modified.
**
** See also: [sqlite3_libversion()],
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()].
*/
#define SQLITE_VERSION        "3.35.0"
#define SQLITE_VERSION_NUMBER 3035000
#define SQLITE_SOURCE_ID      "2021-02-19 14:32:58 c844a331e78949850fde8ed95058cb34f863566944bc9e92e3ae042768f130e1"
#define SQLITE_VERSION        "3.37.0"
#define SQLITE_VERSION_NUMBER 3037000
#define SQLITE_SOURCE_ID      "2021-10-04 11:10:15 8b24c177061c38361588f419eda9b7943b72a0c6b2855b6f39272451b8a1b813"

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

519
520
521
522
523
524
525
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549







+







#define SQLITE_BUSY_TIMEOUT            (SQLITE_BUSY   |  (3<<8))
#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
#define SQLITE_CANTOPEN_DIRTYWAL       (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
#define SQLITE_CANTOPEN_SYMLINK        (SQLITE_CANTOPEN | (6<<8))
#define SQLITE_CANTOPEN_EXISTS         (SQLITE_CANTOPEN | (7<<8))
#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
#define SQLITE_CORRUPT_SEQUENCE        (SQLITE_CORRUPT | (2<<8))
#define SQLITE_CORRUPT_INDEX           (SQLITE_CORRUPT | (3<<8))
#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
#define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
533
534
535
536
537
538
539

540
541
542
543
544
545
546
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571







+







#define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
#define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
#define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
#define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
#define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
#define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
#define SQLITE_CONSTRAINT_PINNED       (SQLITE_CONSTRAINT |(11<<8))
#define SQLITE_CONSTRAINT_DATATYPE     (SQLITE_CONSTRAINT |(12<<8))
#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
#define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
#define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
#define SQLITE_OK_SYMLINK              (SQLITE_OK | (2<<8))

1124
1125
1126
1127
1128
1129
1130

















1131
1132
1133
1134
1135
1136
1137
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179







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







**
** <li>[[SQLITE_FCNTL_CKPT_DONE]]
** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint
** in wal mode after the client has finished copying pages from the wal
** file to the database file, but before the *-shm file is updated to
** record the fact that the pages have been checkpointed.
** </ul>
**
** <li>[[SQLITE_FCNTL_EXTERNAL_READER]]
** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect
** whether or not there is a database client in another process with a wal-mode
** transaction open on the database or not. It is only available on unix.The
** (void*) argument passed with this file-control should be a pointer to a
** value of type (int). The integer value is set to 1 if the database is a wal
** mode database and there exists at least one client in another process that
** currently has an SQL transaction open on the database. It is set to 0 if
** the database is not a wal-mode db, or if there is no such connection in any
** other process. This opcode cannot be used to detect transactions opened
** by clients within the current process, only within other processes.
** </ul>
**
** <li>[[SQLITE_FCNTL_CKSM_FILE]]
** Used by the cksmvfs VFS module only.
** </ul>
*/
#define SQLITE_FCNTL_LOCKSTATE               1
#define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
#define SQLITE_FCNTL_SET_LOCKPROXYFILE       3
#define SQLITE_FCNTL_LAST_ERRNO              4
#define SQLITE_FCNTL_SIZE_HINT               5
#define SQLITE_FCNTL_CHUNK_SIZE              6
1163
1164
1165
1166
1167
1168
1169


1170
1171
1172
1173
1174
1175
1176
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220







+
+







#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE  33
#define SQLITE_FCNTL_LOCK_TIMEOUT           34
#define SQLITE_FCNTL_DATA_VERSION           35
#define SQLITE_FCNTL_SIZE_LIMIT             36
#define SQLITE_FCNTL_CKPT_DONE              37
#define SQLITE_FCNTL_RESERVE_BYTES          38
#define SQLITE_FCNTL_CKPT_START             39
#define SQLITE_FCNTL_EXTERNAL_READER        40
#define SQLITE_FCNTL_CKSM_FILE              41

/* deprecated names */
#define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
#define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE
#define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO


2128
2129
2130
2131
2132
2133
2134
2135







2136
2137
2138
2139
2140
2141
2142
2172
2173
2174
2175
2176
2177
2178

2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192







-
+
+
+
+
+
+
+







** <dd> ^This option is used to enable or disable [CREATE VIEW | views].
** There should be two additional arguments.
** The first argument is an integer which is 0 to disable views,
** positive to enable views or negative to leave the setting unchanged.
** The second parameter is a pointer to an integer into which
** is written 0 or 1 to indicate whether views are disabled or enabled
** following this call.  The second parameter may be a NULL pointer, in
** which case the view setting is not reported back. </dd>
** which case the view setting is not reported back.
**
** <p>Originally this option disabled all views.  ^(However, since
** SQLite version 3.35.0, TEMP views are still allowed even if
** this option is off.  So, in other words, this option now only disables
** views in the main database schema or in the schemas of ATTACH-ed
** databases.)^ </dd>
**
** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
** <dd> ^This option is used to enable or disable the
** [fts3_tokenizer()] function which is part of the
** [FTS3] full-text search engine extension.
** There should be two additional arguments.
2435
2436
2437
2438
2439
2440
2441
2442

2443
2444




2445

2446
2447
2448
2449
2450
2451
2452
2453
2485
2486
2487
2488
2489
2490
2491

2492
2493
2494
2495
2496
2497
2498

2499

2500
2501
2502
2503
2504
2505
2506







-
+


+
+
+
+
-
+
-







*/
SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);

/*
** CAPI3REF: Count The Number Of Rows Modified
** METHOD: sqlite3
**
** ^This function returns the number of rows modified, inserted or
** ^These functions return the number of rows modified, inserted or
** deleted by the most recently completed INSERT, UPDATE or DELETE
** statement on the database connection specified by the only parameter.
** The two functions are identical except for the type of the return value
** and that if the number of rows modified by the most recent INSERT, UPDATE
** or DELETE is greater than the maximum value supported by type "int", then
** the return value of sqlite3_changes() is undefined. ^Executing any other
** ^Executing any other type of SQL statement does not modify the value
** type of SQL statement does not modify the value returned by these functions.
** returned by this function.
**
** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
** [foreign key actions] or [REPLACE] constraint resolution are not counted.
**
** Changes to a view that are intercepted by
** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
2488
2489
2490
2491
2492
2493
2494

2495
2496
2497
2498
2499
2500

2501
2502




2503
2504


2505
2506
2507
2508
2509
2510
2511
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553

2554
2555
2556
2557
2558
2559
2560


2561
2562
2563
2564
2565
2566
2567
2568
2569







+





-
+


+
+
+
+
-
-
+
+







** <li> the [sqlite3_total_changes()] interface
** <li> the [count_changes pragma]
** <li> the [changes() SQL function]
** <li> the [data_version pragma]
** </ul>
*/
SQLITE_API int sqlite3_changes(sqlite3*);
SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3*);

/*
** CAPI3REF: Total Number Of Rows Modified
** METHOD: sqlite3
**
** ^This function returns the total number of rows inserted, modified or
** ^These functions return the total number of rows inserted, modified or
** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
** since the database connection was opened, including those executed as
** part of trigger programs. The two functions are identical except for the
** type of the return value and that if the number of rows modified by the
** connection exceeds the maximum value supported by type "int", then
** the return value of sqlite3_total_changes() is undefined. ^Executing
** part of trigger programs. ^Executing any other type of SQL statement
** does not affect the value returned by sqlite3_total_changes().
** any other type of SQL statement does not affect the value returned by
** sqlite3_total_changes().
**
** ^Changes made as part of [foreign key actions] are included in the
** count, but those made as part of REPLACE constraint resolution are
** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
** are not counted.
**
** The [sqlite3_total_changes(D)] interface only reports the number
2525
2526
2527
2528
2529
2530
2531

2532
2533
2534
2535
2536
2537
2538
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597







+







** <li> the [count_changes pragma]
** <li> the [changes() SQL function]
** <li> the [data_version pragma]
** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]
** </ul>
*/
SQLITE_API int sqlite3_total_changes(sqlite3*);
SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3*);

/*
** CAPI3REF: Interrupt A Long-Running Query
** METHOD: sqlite3
**
** ^This function causes any pending database operation to abort and
** return at its earliest opportunity. This routine is typically
3356
3357
3358
3359
3360
3361
3362






3363
3364
3365
3366
3367
3368
3369
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434







+
+
+
+
+
+







** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>
** <dd>The database is opened [shared cache] disabled, overriding
** the default shared cache setting provided by
** [sqlite3_enable_shared_cache()].)^
**
** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
** <dd>The database filename is not allowed to be a symbolic link</dd>
**
** [[OPEN_EXCLUSIVE]] ^(<dt>[SQLITE_OPEN_EXCLUSIVE]</dt>
** <dd>This flag causes the open to fail if the database file already
** exists.  The open will only be success if this flag is used in combination
** with the SQLITE_OPEN_CREATE and SQLITE_OPEN_READWRITE flags and if
** the file does not previously exist.</dd>
** </dl>)^
**
** If the 3rd parameter to sqlite3_open_v2() is not one of the
** required combinations shown above optionally combined with other
** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
** then the behavior is undefined.
**
4129
4130
4131
4132
4133
4134
4135
4136

4137



4138
4139
4140

4141

4142
4143
4144
4145
4146
4147
4148
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







-
+

+
+
+



+

+







** bound parameter expansions.  ^The [SQLITE_OMIT_TRACE] compile-time
** option causes sqlite3_expanded_sql() to always return NULL.
**
** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)
** are managed by SQLite and are automatically freed when the prepared
** statement is finalized.
** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
** is obtained from [sqlite3_malloc()] and must be free by the application
** is obtained from [sqlite3_malloc()] and must be freed by the application
** by passing it to [sqlite3_free()].
**
** ^The sqlite3_normalized_sql() interface is only available if
** the [SQLITE_ENABLE_NORMALIZE] compile-time option is defined.
*/
SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
#ifdef SQLITE_ENABLE_NORMALIZE
SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
#endif

/*
** CAPI3REF: Determine If An SQL Statement Writes The Database
** METHOD: sqlite3_stmt
**
** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
** and only if the [prepared statement] X makes no direct changes to
4169
4170
4171
4172
4173
4174
4175









4176
4177
4178
4179
4180
4181
4182
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261







+
+
+
+
+
+
+
+
+







** sqlite3_stmt_readonly() to return true since, while those statements
** change the configuration of a database connection, they do not make
** changes to the content of the database files on disk.
** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
** sqlite3_stmt_readonly() returns false for those commands.
**
** ^This routine returns false if there is any possibility that the
** statement might change the database file.  ^A false return does
** not guarantee that the statement will change the database file.
** ^For example, an UPDATE statement might have a WHERE clause that
** makes it a no-op, but the sqlite3_stmt_readonly() result would still
** be false.  ^Similarly, a CREATE TABLE IF NOT EXISTS statement is a
** read-only no-op if the table already exists, but
** sqlite3_stmt_readonly() still returns false for such a statement.
*/
SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);

/*
** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement
** METHOD: sqlite3_stmt
**
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350







4351
4352
4353
4354






4355
4356



4357
4358
4359
4360
4361
4362
4363
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







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







** that parameter must be the byte offset
** where the NUL terminator would occur assuming the string were NUL
** terminated.  If any NUL characters occurs at byte offsets less than
** the value of the fourth parameter then the resulting string value will
** contain embedded NULs.  The result of expressions involving strings
** with embedded NULs is undefined.
**
** ^The fifth argument to the BLOB and string binding interfaces
** is a destructor used to dispose of the BLOB or
** string after SQLite has finished with it.  ^The destructor is called
** to dispose of the BLOB or string even if the call to the bind API fails,
** except the destructor is not called if the third parameter is a NULL
** pointer or the fourth parameter is negative.
** ^The fifth argument to the BLOB and string binding interfaces controls
** or indicates the lifetime of the object referenced by the third parameter.
** These three options exist:
** ^ (1) A destructor to dispose of the BLOB or string after SQLite has finished
** with it may be passed. ^It is called to dispose of the BLOB or string even
** if the call to the bind API fails, except the destructor is not called if
** the third parameter is a NULL pointer or the fourth parameter is negative.
** ^If the fifth argument is
** the special value [SQLITE_STATIC], then SQLite assumes that the
** information is in static, unmanaged space and does not need to be freed.
** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
** ^ (2) The special constant, [SQLITE_STATIC], may be passsed to indicate that
** the application remains responsible for disposing of the object. ^In this
** case, the object and the provided pointer to it must remain valid until
** either the prepared statement is finalized or the same SQL parameter is
** bound to something else, whichever occurs sooner.
** ^ (3) The constant, [SQLITE_TRANSIENT], may be passed to indicate that the
** SQLite makes its own private copy of the data immediately, before
** the sqlite3_bind_*() routine returns.
** object is to be copied prior to the return from sqlite3_bind_*(). ^The
** object and pointer to it must remain valid until then. ^SQLite will then
** manage the lifetime of its private copy.
**
** ^The sixth argument to sqlite3_bind_text64() must be one of
** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
** to specify the encoding of the text in the third parameter.  If
** the sixth argument to sqlite3_bind_text64() is not one of the
** allowed values shown above, or if the text encoding is different
** from the encoding specified by the sixth parameter, then the behavior
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5174
5175
5176
5177
5178
5179
5180

5181
5182
5183
5184
5185
5186
5187
5188
5189

5190
5191
5192
5193
5194
5195
5196







-









-







** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
**
** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY]
** flag, which if present prevents the function from being invoked from
** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,
** index expressions, or the WHERE clause of partial indexes.
**
** <span style="background-color:#ffff90;">
** For best security, the [SQLITE_DIRECTONLY] flag is recommended for
** all application-defined SQL functions that do not need to be
** used inside of triggers, view, CHECK constraints, or other elements of
** the database schema.  This flags is especially recommended for SQL
** functions that have side effects or reveal internal application state.
** Without this flag, an attacker might be able to modify the schema of
** a database file to include invocations of the function with parameters
** chosen by the attacker, which the application will then execute when
** the database file is opened and read.
** </span>
**
** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
** function can gain access to this pointer using [sqlite3_user_data()].)^
**
** ^The sixth, seventh and eighth parameters passed to the three
** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are
** pointers to C-language functions that implement the SQL function or
7769
7770
7771
7772
7773
7774
7775

7776

7777
7778
7779
7780
7781
7782
7783
7850
7851
7852
7853
7854
7855
7856
7857

7858
7859
7860
7861
7862
7863
7864
7865







+
-
+







#define SQLITE_TESTCTRL_IMPOSTER                25
#define SQLITE_TESTCTRL_PARSER_COVERAGE         26
#define SQLITE_TESTCTRL_RESULT_INTREAL          27
#define SQLITE_TESTCTRL_PRNG_SEED               28
#define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     29
#define SQLITE_TESTCTRL_SEEK_COUNT              30
#define SQLITE_TESTCTRL_TRACEFLAGS              31
#define SQLITE_TESTCTRL_TUNE                    32
#define SQLITE_TESTCTRL_LAST                    31  /* Largest TESTCTRL */
#define SQLITE_TESTCTRL_LAST                    32  /* Largest TESTCTRL */

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



8978
8979
8980
8981
8982
8983
8984
9051
9052
9053
9054
9055
9056
9057


9058
9059
9060
9061
9062
9063
9064
9065
9066
9067







-
-
+
+
+







** to report an error, though the commit will have still occurred. If the
** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
** that does not correspond to any valid SQLite error code, the results
** are undefined.
**
** A single database handle may have at most a single write-ahead log callback
** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
** previously registered write-ahead log callback. ^Note that the
** [sqlite3_wal_autocheckpoint()] interface and the
** previously registered write-ahead log callback. ^The return value is
** a copy of the third parameter from the previous call, if any, or 0.
** ^Note that the [sqlite3_wal_autocheckpoint()] interface and the
** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
** overwrite any prior [sqlite3_wal_hook()] settings.
*/
SQLITE_API void *sqlite3_wal_hook(
  sqlite3*,
  int(*)(void *,sqlite3*,const char*,int),
  void*
9521
9522
9523
9524
9525
9526
9527









9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547

9548
9549
9550
9551
9552
9553
9554
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647







+
+
+
+
+
+
+
+
+




















+







**
** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
** callback was invoked as a result of a direct insert, update, or delete
** operation; or 1 for inserts, updates, or deletes invoked by top-level
** triggers; or 2 for changes resulting from triggers called by top-level
** triggers; and so forth.
**
** When the [sqlite3_blob_write()] API is used to update a blob column,
** the pre-update hook is invoked with SQLITE_DELETE. This is because the
** in this case the new values are not available. In this case, when a
** callback made with op==SQLITE_DELETE is actuall a write using the
** sqlite3_blob_write() API, the [sqlite3_preupdate_blobwrite()] returns
** the index of the column being written. In other cases, where the
** pre-update hook is being invoked for some other reason, including a
** regular DELETE, sqlite3_preupdate_blobwrite() returns -1.
**
** See also:  [sqlite3_update_hook()]
*/
#if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
SQLITE_API void *sqlite3_preupdate_hook(
  sqlite3 *db,
  void(*xPreUpdate)(
    void *pCtx,                   /* Copy of third arg to preupdate_hook() */
    sqlite3 *db,                  /* Database handle */
    int op,                       /* SQLITE_UPDATE, DELETE or INSERT */
    char const *zDb,              /* Database name */
    char const *zName,            /* Table name */
    sqlite3_int64 iKey1,          /* Rowid of row about to be deleted/updated */
    sqlite3_int64 iKey2           /* New rowid value (for a rowid UPDATE) */
  ),
  void*
);
SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
SQLITE_API int sqlite3_preupdate_blobwrite(sqlite3 *);
#endif

/*
** CAPI3REF: Low-level system error code
** METHOD: sqlite3
**
** ^Attempt to return the underlying operating system error code or error
9779
9780
9781
9782
9783
9784
9785
9786
9787


9788
9789
9790
9791
9792
9793
9794
9872
9873
9874
9875
9876
9877
9878


9879
9880
9881
9882
9883
9884
9885
9886
9887







-
-
+
+







** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
** of the database exists.
**
** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
** allocation error occurs.
**
** This interface is only available if SQLite is compiled with the
** [SQLITE_ENABLE_DESERIALIZE] option.
** This interface is omitted if SQLite is compiled with the
** [SQLITE_OMIT_DESERIALIZE] option.
*/
SQLITE_API unsigned char *sqlite3_serialize(
  sqlite3 *db,           /* The database connection */
  const char *zSchema,   /* Which DB to serialize. ex: "main", "temp", ... */
  sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
  unsigned int mFlags    /* Zero or more SQLITE_SERIALIZE_* flags */
);
9826
9827
9828
9829
9830
9831
9832




9833
9834
9835
9836
9837
9838
9839


9840
9841
9842
9843
9844
9845
9846
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







+
+
+
+





-
-
+
+







** connection closes.  If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
** SQLite will try to increase the buffer size using sqlite3_realloc64()
** if writes on the database cause it to grow larger than M bytes.
**
** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
** database is currently in a read transaction or is involved in a backup
** operation.
**
** It is not possible to deserialized into the TEMP database.  If the
** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the
** function returns SQLITE_ERROR.
**
** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
** [sqlite3_free()] is invoked on argument P prior to returning.
**
** This interface is only available if SQLite is compiled with the
** [SQLITE_ENABLE_DESERIALIZE] option.
** This interface is omitted if SQLite is compiled with the
** [SQLITE_OMIT_DESERIALIZE] option.
*/
SQLITE_API int sqlite3_deserialize(
  sqlite3 *db,            /* The database connection */
  const char *zSchema,    /* Which DB to reopen with the deserialization */
  unsigned char *pData,   /* The serialized database content */
  sqlite3_int64 szDb,     /* Number bytes in the deserialization */
  sqlite3_int64 szBuf,    /* Total size of buffer pData[] */
10081
10082
10083
10084
10085
10086
10087
































10088
10089
10090
10091
10092
10093
10094
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







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







**
** Session objects must be deleted before the database handle to which they
** are attached is closed. Refer to the documentation for
** [sqlite3session_create()] for details.
*/
SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);

/*
** CAPIREF: Conigure a Session Object
** METHOD: sqlite3_session
**
** This method is used to configure a session object after it has been
** created. At present the only valid value for the second parameter is
** [SQLITE_SESSION_OBJCONFIG_SIZE].
**
** Arguments for sqlite3session_object_config()
**
** The following values may passed as the the 4th parameter to
** sqlite3session_object_config().
**
** <dt>SQLITE_SESSION_OBJCONFIG_SIZE <dd>
**   This option is used to set, clear or query the flag that enables
**   the [sqlite3session_changeset_size()] API. Because it imposes some
**   computational overhead, this API is disabled by default. Argument
**   pArg must point to a value of type (int). If the value is initially
**   0, then the sqlite3session_changeset_size() API is disabled. If it
**   is greater than 0, then the same API is enabled. Or, if the initial
**   value is less than zero, no change is made. In all cases the (int)
**   variable is set to 1 if the sqlite3session_changeset_size() API is
**   enabled following the current call, or 0 otherwise.
**
**   It is an error (SQLITE_MISUSE) to attempt to modify this setting after
**   the first table has been attached to the session object.
*/
SQLITE_API int sqlite3session_object_config(sqlite3_session*, int op, void *pArg);

/*
*/
#define SQLITE_SESSION_OBJCONFIG_SIZE 1

/*
** CAPI3REF: Enable Or Disable A Session Object
** METHOD: sqlite3_session
**
** Enable or disable the recording of changes by a session object. When
** enabled, a session object records changes made to the database. When
10325
10326
10327
10328
10329
10330
10331
















10332
10333
10334
10335
10336
10337
10338
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483







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







*/
SQLITE_API int sqlite3session_changeset(
  sqlite3_session *pSession,      /* Session object */
  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
  void **ppChangeset              /* OUT: Buffer containing changeset */
);

/*
** CAPI3REF: Return An Upper-limit For The Size Of The Changeset
** METHOD: sqlite3_session
**
** By default, this function always returns 0. For it to return
** a useful result, the sqlite3_session object must have been configured
** to enable this API using sqlite3session_object_config() with the
** SQLITE_SESSION_OBJCONFIG_SIZE verb.
**
** When enabled, this function returns an upper limit, in bytes, for the size
** of the changeset that might be produced if sqlite3session_changeset() were
** called. The final changeset size might be equal to or smaller than the
** size in bytes returned by this function.
*/
SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession);

/*
** CAPI3REF: Load The Difference Between Tables Into A Session
** METHOD: sqlite3_session
**
** If it is not already attached to the session object passed as the first
** argument, this function attaches table zTbl in the same manner as the
** [sqlite3session_attach()] function. If zTbl does not exist, or if it
10552
10553
10554
10555
10556
10557
10558



10559
10560
10561
10562
10563









10564
10565


10566
10567
10568

10569
10570
10571
10572
10573
10574
10575
10576
10577
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706





10707
10708
10709
10710
10711
10712
10713
10714
10715


10716
10717
10718
10719

10720


10721
10722
10723
10724
10725
10726
10727







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


-
+
-
-







**
** The pIter argument passed to this function may either be an iterator
** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
** created by [sqlite3changeset_start()]. In the latter case, the most recent
** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
** is not the case, this function returns [SQLITE_MISUSE].
**
** Arguments pOp, pnCol and pzTab may not be NULL. Upon return, three
** outputs are set through these pointers:
**
** If argument pzTab is not NULL, then *pzTab is set to point to a
** nul-terminated utf-8 encoded string containing the name of the table
** affected by the current change. The buffer remains valid until either
** sqlite3changeset_next() is called on the iterator or until the
** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
** *pOp is set to one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
** depending on the type of change that the iterator currently points to;
**
** *pnCol is set to the number of columns in the table affected by the change; and
**
** *pzTab is set to point to a nul-terminated utf-8 encoded string containing
** the name of the table affected by the current change. The buffer remains
** valid until either sqlite3changeset_next() is called on the iterator
** or until the conflict-handler function returns.
** set to the number of columns in the table affected by the change. If
** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
**
** If pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
** is an indirect change, or false (0) otherwise. See the documentation for
** [sqlite3session_indirect()] for a description of direct and indirect
** changes. Finally, if pOp is not NULL, then *pOp is set to one of
** changes.
** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
** type of change that the iterator currently points to.
**
** If no error occurs, SQLITE_OK is returned. If an error does occur, an
** SQLite error code is returned. The values of the output variables may not
** be trusted in this case.
*/
SQLITE_API int sqlite3changeset_op(
  sqlite3_changeset_iter *pIter,  /* Iterator object */